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
934/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
935/// `:contratos :wit` census-label [`WitShape`] closed-set typed enum from
936/// an *owned* input onto the owned-[`String`] axis — routes byte-for-byte
937/// through the substrate-primitive [`WitShape::as_str`] `pub const fn`
938/// accessor so every consumer that binds a [`WitShape`] through the
939/// standard-library `.into()` / [`From<Self> for String`] (equivalently
940/// [`Into<String>`]) axis reaches the same four-arm `"http"` / `"pubsub"`
941/// / `"store"` / `"capability"` census-label byte-string the paired
942/// owned-input [`From<WitShape> for &'static str`] (56998ec), the
943/// borrowed-input [`From<&WitShape> for &'static str`] (3187bd0), the
944/// sibling [`std::fmt::Display`], [`AsRef<str>`], and [`WitShape::as_str`]
945/// surfaces already return.
946///
947/// Extends the trait-idiomatic *owned-[`String`]* forward-projection
948/// family (opened on [`crate::supervisor::RestartStrategy`] — 7baa18a —
949/// the first-mover on the M2 OTP-shape sibling-restart-strategy axis,
950/// extended onto [`crate::supervisor::RestartPolicy`] — 7851725 — the
951/// second-of-two-in-M2 per-child restart-decision axis, then onto
952/// [`crate::CaixaKind`] — 231a18c — the structurally most fundamental
953/// closed-set fieldless typed enum on the caixa surface, then onto
954/// [`crate::CaixaDialeto`] — 88942cd — the dialect-classification axis,
955/// then onto [`crate::dep::DepList`] — 32b0ee8 — the two-list dep-graph
956/// axis, then onto [`PlacementStrategy`] — 1154c2f — the first M3
957/// mesh-primitive-defining slot enum on the caixa surface) onto the
958/// seventh peer: the M3 mesh-primitive `:contratos :wit` census-label
959/// axis [`WitShape`] carries. Second M3-mesh-primitive-defining closed-set
960/// typed enum to converge onto this owned-[`String`] forward-projection
961/// campaign — the caixa-mesh renderer's per-edge programs.yaml fan-out
962/// keys off this axis end-to-end, so every future consumer that promotes
963/// classification output onto an owned-heap-string carrier (the future M4
964/// admission-webhook rejection body's accepted-`:contratos :wit`
965/// enumeration, a future `HashMap::<String, WitShape>::from_iter(…)`
966/// owned-key per-shape lookup) now reaches the substrate-primitive
967/// accessor through one uniform trait dispatch.
968///
969/// Rust's standard library does not carry a blanket
970/// `impl<T: AsRef<str>> From<T> for String` (nor an
971/// `impl<T: fmt::Display> From<T> for String`), so every closed-set typed
972/// enum that carries the paired [`AsRef<str>`] / [`std::fmt::Display`] /
973/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`]
974/// quadruple but not the owned-[`String`] axis forces every owned-string
975/// call site through a `.to_string()` / `.as_str().to_owned()` /
976/// `String::from(shape.as_str())` detour whose type bounds have no
977/// compile-time link to the substrate primitive.
978///
979/// Same as the peer [`crate::supervisor::RestartStrategy`] /
980/// [`crate::supervisor::RestartPolicy`] / [`crate::CaixaDialeto`] /
981/// [`crate::dep::DepList`] / [`PlacementStrategy`] owned-[`String`] axis
982/// pairs (whose forward emit and reverse parse share one vocabulary by
983/// construction), [`WitShape`]'s [`WitShape::as_str`] emit and
984/// [`WitShape::from_wire`] parse resolve through the same four inline
985/// census-label byte-strings by construction (there is no wire/diagnostic
986/// axis split on this enum), so the owned-[`String`] forward projection
987/// this impl exposes composes directly with the paired trait-idiomatic
988/// reverse [`TryFrom<&str>`] axis on the owned-[`String`]'s
989/// [`String::as_str`] borrow — no intermediate wire-vocab hop like the
990/// peer [`crate::CaixaKind`] axis pair requires.
991///
992/// The remaining eight closed-set typed enums on the caixa substrate
993/// surface (`RateLimitUnit`, `PathShapeViolation`, `InvariantKind`,
994/// `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`)
995/// are the future targets of this campaign — each carries the same paired
996/// [`AsRef<str>`] / [`std::fmt::Display`] / [`From<Self> for &'static
997/// str`] / [`From<&Self> for &'static str`] quadruple that this
998/// owned-[`String`] axis extends onto.
999///
1000/// Pinned load-bearing by
1001/// [`tests::wit_shape_from_into_owned_string_routes_through_as_str_accessor`]
1002/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
1003/// [`WitShape::ALL`] emit-set plus a blanket `.into::<String>()` shape
1004/// witness) and
1005/// [`tests::wit_shape_from_into_owned_string_and_static_str_agree_on_every_arm`]
1006/// (cross-axis partition against the sibling owned-`&'static str` axis
1007/// and the [`ToString::to_string`] surface, a
1008/// `.iter().copied().map(String::from)` pipe witness over
1009/// [`WitShape::ALL`], plus a direct `Self → String → Self` round-trip via
1010/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`] borrow
1011/// — composes directly without the wire-vocab intermediate hop the peer
1012/// [`crate::CaixaKind`] axis pair requires).
1013impl From<WitShape> for String {
1014    fn from(shape: WitShape) -> String {
1015        shape.as_str().to_owned()
1016    }
1017}
1018
1019/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1020/// projection on the M3 mesh-primitive `:contratos :wit` census-label
1021/// [`WitShape`] closed-set typed enum — the fourth (and closing) corner
1022/// of the `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1023/// projection family on this second M3-mesh-primitive-defining slot
1024/// enum. Routes byte-for-byte through the substrate-primitive
1025/// [`WitShape::as_str`] `pub const fn` accessor (via
1026/// [`str::to_owned`]) so every consumer that holds a borrowed
1027/// [`&WitShape`] and needs an owned [`String`] — a future
1028/// `serde_json::Value::String(String::from(&shape))` structured-payload
1029/// composer over a borrowed field, a future `Iterator::map` over
1030/// `&[WitShape]` that projects to owned keys through
1031/// `.iter().map(String::from)` (whose iterator yields `&WitShape`, not
1032/// `WitShape`, so the owned-input [`From<WitShape> for String`] axis
1033/// alone forces every call site through an explicit `.copied()` /
1034/// spurious [`Copy`] deref restatement rather than the direct
1035/// trait-idiomatic projection), a future
1036/// `HashMap::<String, WitShape>::from_iter` that keys off a borrowed-
1037/// iteration axis where dereferencing the shape would force an
1038/// unnecessary [`Copy`] at every step, the future M4
1039/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
1040/// body composer that names the accepted-`:contratos :wit` census-label
1041/// enumeration through an iterated
1042/// `WitShape::ALL.iter().map(String::from).collect()` pipe rather than
1043/// a per-arm cascade, the future caixa-mesh renderer
1044/// `contratos.wit`-column diagnostic composer whose borrowed-iteration
1045/// axis over declared shapes projects to owned keys by construction —
1046/// reaches the same four-arm `"http"` / `"pubsub"` / `"store"` /
1047/// `"capability"` census-label byte-string the paired
1048/// [`std::fmt::Display`], [`AsRef<str>`], [`WitShape::as_str`], and the
1049/// three other trait-idiomatic forward-projection impls
1050/// ([`From<WitShape> for &'static str`],
1051/// [`From<&WitShape> for &'static str`],
1052/// [`From<WitShape> for String`]) already return.
1053///
1054/// Seventh peer on the substrate-wide trait-idiomatic *borrowed-input,
1055/// owned-`String` output* forward-projection family opened on
1056/// [`crate::supervisor::RestartStrategy`] (579385f), closed on the M2
1057/// OTP-shape sibling axis pair by
1058/// [`crate::supervisor::RestartPolicy`] (8465740), extended onto the
1059/// two-list dep-graph peer by [`crate::dep::DepList`] (e0cb617), onto
1060/// the top-level [`crate::CaixaKind`] peer by (e76436d), onto the
1061/// dialect-classification peer by [`crate::CaixaDialeto`] (d3c0d1d),
1062/// and onto the first M3 mesh-slot peer by [`PlacementStrategy`]
1063/// (d3dc000) — extends the `{Self, &Self} × {&'static str, String}`
1064/// 2×2 projection corner off the first M3 slot enum onto the second M3
1065/// slot enum, keeping the M3 mesh-primitive triple's completion sweep
1066/// in lockstep with the M2 OTP-shape sibling pair's earlier closure.
1067/// Second M3-mesh-primitive-defining closed-set typed enum to reach the
1068/// 2×2-completion corner — the [`PlacementStrategy`] first-mover
1069/// (d3dc000) closed the `:placement :estrategia` distribution-strategy
1070/// axis, and [`WitShape`]'s `:contratos :wit` census-label axis (the
1071/// caixa-mesh renderer's per-edge programs.yaml fan-out key) closes the
1072/// next M3 slot ahead of the sibling [`RateLimitUnit`] `:politicas
1073/// :rate-limit` canonical-suffix axis whose 2×2-completion corner
1074/// remains a future target of this campaign.
1075///
1076/// Rust's standard library does not carry a blanket
1077/// `impl<T: AsRef<str>> From<&T> for String` (nor an
1078/// `impl<T: fmt::Display> From<&T> for String`), so every closed-set
1079/// typed enum that carries the paired [`AsRef<str>`] /
1080/// [`std::fmt::Display`] / [`From<Self> for &'static str`] /
1081/// [`From<&Self> for &'static str`] / [`From<Self> for String`]
1082/// quintuple but not the borrowed-input owned-[`String`] axis forces
1083/// every borrowed-input owned-string call site through a
1084/// `shape.as_str().to_owned()` / `String::from(*shape)` (with a
1085/// spurious [`Copy`]) / `shape.to_string()` (through
1086/// [`std::fmt::Display`]) detour whose type bounds have no compile-time
1087/// link to the substrate primitive.
1088///
1089/// Same three-path convergence discipline as the paired owned-input
1090/// impl (this borrowed-input axis, the paired owned-input
1091/// [`From<WitShape> for String`], and [`WitShape::as_str`] all route
1092/// through the same four-arm inline census-label byte-strings), so a
1093/// future variant rename or per-arm serde-attribute drift reaches every
1094/// one of the paired forward-projection paths through exactly one
1095/// caixa-core edit.
1096///
1097/// Same as the peer [`crate::supervisor::RestartStrategy`] /
1098/// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`] /
1099/// [`crate::CaixaDialeto`] / [`PlacementStrategy`] borrowed-input
1100/// owned-[`String`] axis pairs (whose forward emit and reverse parse
1101/// share one vocabulary by construction) and unlike the peer
1102/// [`crate::CaixaKind`] pair (whose forward emit lands on the lowercase
1103/// Portuguese diagnostic vocabulary while the reverse parse lands on
1104/// the `PascalCase` wire vocabulary, forcing the round-trip through an
1105/// intermediate [`crate::CaixaKind::wire_name`] hop), [`WitShape`]'s
1106/// [`WitShape::as_str`] emit and [`WitShape::from_wire`] parse resolve
1107/// through the same four inline census-label byte-strings by
1108/// construction (there is no wire/diagnostic axis split on this M3 slot
1109/// enum — both halves of the round-trip route through the same four
1110/// `pub const &str` values), so the borrowed-input owned-[`String`]
1111/// projection this impl exposes composes directly with the paired
1112/// trait-idiomatic reverse [`TryFrom<&str>`] axis on the
1113/// owned-[`String`]'s [`String::as_str`] borrow — no intermediate
1114/// wire-vocab hop required.
1115///
1116/// The remaining seven closed-set typed enums on the caixa substrate
1117/// surface (`RateLimitUnit`, `PathShapeViolation`, `InvariantKind`,
1118/// `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`)
1119/// are the future targets of this 2×2-completion campaign — each
1120/// carries the same paired quintuple that this borrowed-input
1121/// owned-[`String`] axis extends onto.
1122///
1123/// Pinned load-bearing by
1124/// [`tests::wit_shape_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1125/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
1126/// emit-set through the borrowed-input surface) and
1127/// [`tests::wit_shape_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1128/// (cross-axis partition pin against the paired owned-input owned-
1129/// [`String`] [`From<WitShape> for String`] impl, the paired
1130/// borrowed-input owned-[`&'static str`]
1131/// [`From<&WitShape> for &'static str`] impl, the paired owned-input
1132/// owned-[`&'static str`] [`From<WitShape> for &'static str`] impl, and
1133/// the sibling [`ToString::to_string`] surface routed through
1134/// [`std::fmt::Display`], plus a `.iter().map(String::from)` pipe
1135/// witness over [`WitShape::ALL`] (whose iterator yields `&WitShape` by
1136/// construction, so the borrowed-input owned-[`String`] axis is what
1137/// routes the pipe through the substrate-primitive
1138/// [`WitShape::as_str`] accessor without a spurious [`Copy`] deref),
1139/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
1140/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
1141/// `&Self → String → Self` round-trip on the trait-idiomatic
1142/// borrowed-input owned-[`String`] forward + reverse axis pair — no
1143/// intermediate wire-vocab hop like the peer [`crate::CaixaKind`] axis
1144/// pair requires).
1145impl From<&WitShape> for String {
1146    fn from(shape: &WitShape) -> String {
1147        shape.as_str().to_owned()
1148    }
1149}
1150
1151/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
1152/// `:contratos :wit` census-label [`WitShape`] closed-set typed enum
1153/// from an *owned* input onto the [`std::borrow::Cow<'static, str>`]
1154/// axis — routes byte-for-byte through the substrate-primitive
1155/// [`WitShape::as_str`] `pub const fn` accessor (via
1156/// [`std::borrow::Cow::Borrowed`]) so every consumer that binds a
1157/// [`WitShape`] through the standard-library `.into()` /
1158/// [`From<Self> for std::borrow::Cow<'static, str>`] (equivalently
1159/// [`Into<std::borrow::Cow<'static, str>>`]) axis reaches the same
1160/// four-arm `"http"` / `"pubsub"` / `"store"` / `"capability"`
1161/// census-label byte-string the paired
1162/// [`From<WitShape> for &'static str`],
1163/// [`From<&WitShape> for &'static str`],
1164/// [`From<WitShape> for String`], and
1165/// [`From<&WitShape> for String`] 2×2 trait-idiomatic
1166/// forward-projection corners, the sibling [`std::fmt::Display`],
1167/// [`AsRef<str>`], and [`WitShape::as_str`] surfaces already return,
1168/// rather than an open-coded per-call-site
1169/// `std::borrow::Cow::Borrowed(shape.as_str())` /
1170/// `std::borrow::Cow::Owned(shape.to_string())` composition whose
1171/// type bounds have no compile-time link back to the substrate
1172/// primitive.
1173///
1174/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1175/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1176/// [`WitShape::as_str`] accessor's return carries the `&'static str`
1177/// lifetime by construction (each `match` arm resolves to an inline
1178/// `"http"` / `"pubsub"` / `"store"` / `"capability"` census-label
1179/// byte-string literal with static lifetime), so the zero-alloc
1180/// borrowed arm is the type-correct projection with no runtime
1181/// allocation. The paired [`std::borrow::Cow::Owned`] arm stays
1182/// reachable at the call site through the existing
1183/// [`From<WitShape> for String`] axis composed with
1184/// [`std::borrow::Cow::from`] on the resulting owned [`String`] —
1185/// a caller who chose to mutate the projection lands on the owned
1186/// arm by their own composition, not by the substrate-primitive
1187/// projection silently allocating on their behalf.
1188///
1189/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
1190/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
1191/// From<T> for Cow<'static, str>`), so the paired sibling
1192/// [`From<WitShape> for &'static str`],
1193/// [`From<WitShape> for String`], [`AsRef<str>`], and
1194/// [`std::fmt::Display`] surfaces do not implicitly extend to a
1195/// [`Cow<'static, str>`]-bound call site — every such site is forced
1196/// through a `Cow::Borrowed(shape.as_str())` /
1197/// `Cow::Owned(shape.to_string())` open-code whose type bounds have
1198/// no compile-time link back to the substrate primitive until this
1199/// lift.
1200///
1201/// First-mover on the *M3 mesh-shape tier* of the substrate-wide
1202/// trait-idiomatic [`std::borrow::Cow<'static, str>`] forward-
1203/// projection campaign — the [`crate::CaixaKind`] first-mover (99c1735 owned-
1204/// input + d45c409 borrowed-input) opened the axis on the
1205/// structurally most fundamental closed-set fieldless typed enum;
1206/// the paired M2 OTP-shape [`crate::supervisor::RestartStrategy`]
1207/// (7dd28b3 owned-input + 9b3e4b3 borrowed-input) and
1208/// [`crate::supervisor::RestartPolicy`] (0612398 owned-input +
1209/// ee577fd borrowed-input) extended it onto the two M2 OTP-shape
1210/// sibling peers, closing the whole M2 OTP-shape tier. [`WitShape`]
1211/// is the *first* M3-mesh-primitive-defining closed-set fieldless
1212/// typed enum to converge onto this campaign — the caixa-mesh
1213/// renderer's per-edge programs.yaml fan-out and the
1214/// [`WitContract`] shape-dispatch surface both key off this axis
1215/// end-to-end, so every future consumer that binds through a
1216/// [`Cow<'static, str>`] boundary and holds a [`WitShape`] by value
1217/// reaches the substrate-primitive accessor through one uniform
1218/// trait dispatch. The remaining ten peers (`RestartStrategy` and
1219/// `RestartPolicy` closed on the M2 tier;
1220/// [`PlacementStrategy`], [`RateLimitUnit`],
1221/// [`crate::dep::DepList`], [`crate::CaixaDialeto`],
1222/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1223/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1224/// `Semantic`, `FerriteRuntime`) are the remaining future targets
1225/// of this campaign.
1226///
1227/// Pinned load-bearing by
1228/// [`tests::wit_shape_from_into_static_cow_str_routes_through_as_str_accessor`]
1229/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1230/// against [`WitShape::as_str`] across the four-arm
1231/// [`WitShape::ALL`]) and
1232/// [`tests::wit_shape_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1233/// (cross-axis partition pin against the paired
1234/// [`From<WitShape> for &'static str`],
1235/// [`From<WitShape> for String`], and
1236/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
1237/// `.iter().copied().map(Cow::from)` pipe witness over
1238/// [`WitShape::ALL`] that materializes the four-arm accept-set
1239/// through the [`Cow<'static, str>`] axis alone and pins the
1240/// zero-alloc discipline on every element).
1241impl From<WitShape> for std::borrow::Cow<'static, str> {
1242    fn from(shape: WitShape) -> std::borrow::Cow<'static, str> {
1243        std::borrow::Cow::Borrowed(shape.as_str())
1244    }
1245}
1246
1247/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
1248/// output* forward projection on the M3-mesh-primitive-defining
1249/// `:contratos :wit` census-label [`WitShape`] closed-set typed enum —
1250/// the borrowed-input companion to the paired owned-input
1251/// [`From<WitShape> for std::borrow::Cow<'static, str>`] impl
1252/// immediately above (8634dec). Routes byte-for-byte through the same
1253/// substrate-primitive [`WitShape::as_str`] `pub const fn` accessor
1254/// (via [`std::borrow::Cow::Borrowed`]) so every consumer that holds
1255/// a `&WitShape` and needs a [`std::borrow::Cow<'static, str>`] — a
1256/// `WitShape::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
1257/// per-arm accept-set materializer whose iterator over
1258/// `&'static [WitShape]` yields `&WitShape` (not `WitShape`, so the
1259/// paired owned-input [`From<WitShape> for std::borrow::Cow<'static, str>`]
1260/// axis alone forces every call site through an explicit `.copied()` /
1261/// dereference / [`Copy`]-bound restatement rather than the direct
1262/// trait-idiomatic projection), a future generic
1263/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
1264/// on a per-`:contratos :wit` diagnostic column that walks the
1265/// `iter().map(Into::into)` shape verbatim, the future M4
1266/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
1267/// body that composes the accepted-`:contratos :wit` census-label
1268/// enumeration from an iterated
1269/// `WitShape::ALL.iter().map(|s| s.into())` pipe rather than a per-arm
1270/// `match s { … }` cascade — reaches the same four-arm inline
1271/// `"http"` / `"pubsub"` / `"store"` / `"capability"` census-label
1272/// byte-string the paired [`std::fmt::Display`], [`AsRef<str>`],
1273/// [`WitShape::as_str`], the four
1274/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1275/// forward-projection corners, and the paired owned-input
1276/// [`From<WitShape> for std::borrow::Cow<'static, str>`] impl already
1277/// return.
1278///
1279/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1280/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1281/// [`WitShape::as_str`] accessor's return carries the `&'static str`
1282/// lifetime by construction (each `match` arm resolves to an inline
1283/// `"http"` / `"pubsub"` / `"store"` / `"capability"` census-label
1284/// byte-string literal with static lifetime), so the zero-alloc
1285/// borrowed arm is the type-correct projection with no runtime
1286/// allocation on the borrowed-input surface just as on the paired
1287/// owned-input surface.
1288///
1289/// Closes the `{Self, &Self}` input-shape corner on the M3-mesh-shape
1290/// `:contratos :wit` census-label [`std::borrow::Cow<'static, str>`]
1291/// axis opened one commit prior (8634dec) on the paired owned-input
1292/// [`From<WitShape> for std::borrow::Cow<'static, str>`] impl —
1293/// first-of-`{PlacementStrategy, RateLimitUnit}`-plus-`WitShape` on
1294/// the M3-mesh-primitive-defining closed-set fieldless typed enum
1295/// tier of the campaign, exactly as d45c409 closed it on the
1296/// top-level [`crate::CaixaKind`] one commit after the owning half
1297/// (99c1735) landed and as 9b3e4b3 / ee577fd closed it on the M2
1298/// OTP-shape [`crate::supervisor::RestartStrategy`] /
1299/// [`crate::supervisor::RestartPolicy`] sibling peers one commit
1300/// after their owning halves (7dd28b3 / 0612398) landed. Rust's
1301/// standard library does not carry a blanket
1302/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
1303/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
1304/// closed-set fieldless typed enum peer on the substrate that carries
1305/// the paired owned-input [`Cow<'static, str>`] axis but not the
1306/// borrowed-input axis forces every borrowed-input
1307/// [`Cow<'static, str>`]-parameterized call site through a spurious
1308/// [`Copy`] deref (`std::borrow::Cow::from(*shape)`) or a
1309/// `std::borrow::Cow::Borrowed(shape.as_str())` open-code whose type
1310/// bounds have no compile-time link to the substrate primitive.
1311///
1312/// The remaining M3-mesh-primitive-defining peers
1313/// ([`PlacementStrategy`], [`RateLimitUnit`]) and the outside-M3
1314/// substrate-wide peers ([`crate::dep::DepList`],
1315/// [`crate::CaixaDialeto`], [`crate::render::PathShapeViolation`],
1316/// and the outside-`caixa-core` peers `InvariantKind`, `ArchVerdict`,
1317/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
1318/// remaining future targets of the campaign.
1319///
1320/// Pinned load-bearing by
1321/// [`tests::wit_shape_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
1322/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1323/// against [`WitShape::as_str`] across the four-arm
1324/// [`WitShape::ALL`] through the borrowed-input surface) and
1325/// [`tests::wit_shape_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1326/// (cross-axis partition pin against the paired owned-input
1327/// [`From<WitShape> for std::borrow::Cow<'static, str>`], the paired
1328/// borrowed-input owned-`&'static str`
1329/// [`From<&WitShape> for &'static str`], and the paired
1330/// borrowed-input owned-`String` [`From<&WitShape> for String`]
1331/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
1332/// over [`WitShape::ALL`] — whose iterator yields `&WitShape` by
1333/// construction, so the borrowed-input [`Cow<'static, str>`] axis is
1334/// what routes the pipe through the substrate-primitive
1335/// [`WitShape::as_str`] accessor with the zero-alloc
1336/// [`Cow::Borrowed`] arm by construction and without a spurious
1337/// [`Copy`] deref).
1338impl From<&WitShape> for std::borrow::Cow<'static, str> {
1339    fn from(shape: &WitShape) -> std::borrow::Cow<'static, str> {
1340        std::borrow::Cow::Borrowed(shape.as_str())
1341    }
1342}
1343
1344impl WitContract {
1345    /// Substrate-canonical per-`:contratos` caller-Servico scalar
1346    /// accessor every consumer that reads the edge's source endpoint
1347    /// keys off — returns the author-declared `:contratos :de`
1348    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1349    /// own [`String`] storage.
1350    ///
1351    /// The `:contratos :de` slot names the caller-side member Servico
1352    /// on a typed inter-Servico edge (validated by
1353    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
1354    /// Aplicacao declares — a stray `:de` that doesn't name a member is
1355    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
1356    /// caller-attachment miss at cluster-apply time). Peer of the
1357    /// sibling [`WitContract::destination`] accessor on the same
1358    /// per-`:contratos` entry — the pair `( source(), destination() )`
1359    /// jointly names the typed edge every renderer that fans on the
1360    /// caller-callee identity keys off (the
1361    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
1362    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
1363    /// map, the per-edge dedup key, the per-edge membership-lookup
1364    /// diagnostic).
1365    ///
1366    /// Prior to this lift the `.de` byte-string was accessed inline at
1367    /// four caixa-core sites (the two validate-side membership lookups
1368    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
1369    /// tuple's caller-arm at
1370    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
1371    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
1372    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
1373    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
1374    /// — five open-coded `.de.as_str()` field-accesses that expressed
1375    /// no compile-time link back to the typed slot. A future extension
1376    /// of the `:contratos :de` axis to a richer author surface (a
1377    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
1378    /// canary flow, a per-cluster caller-alias table the operator pins
1379    /// through a future `:placement`-scoped slot, the M4
1380    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
1381    /// admission-webhook that promotes the scalar to a caller-set
1382    /// projection) would have had to be threaded through every
1383    /// open-coded copy in lockstep or one consumer would silently
1384    /// disagree with the peers on which caller Servico a given edge
1385    /// resolves to. Lifting the resolution rule to a typed method on
1386    /// the substrate primitive means every downstream caller-facing
1387    /// consumer reaches for one typed dispatch — the resolver's
1388    /// accept-set migrates as a unit on any future axis addition.
1389    ///
1390    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
1391    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
1392    /// axis — same "one typed dispatch on the substrate primitive,
1393    /// thin projections at each consumer" discipline extended onto the
1394    /// per-`:contratos` caller-Servico byte-string axis.
1395    ///
1396    /// Declared `pub const fn` — the body composes exclusively through
1397    /// the `pub const fn` [`String::as_str`] projection (const-stable
1398    /// since Rust 1.87, well within the workspace MSRV), so every
1399    /// downstream `const`-context consumer of the per-`:contratos`
1400    /// caller-Servico byte-string reaches through the same substrate-
1401    /// primitive dispatch at const-eval time as at runtime. Peer of
1402    /// the sibling `pub const fn` [`Self::destination`] /
1403    /// [`Self::world_ref`] scalar accessors on the same
1404    /// per-`:contratos` byte-string trio (the family closure the
1405    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1406    /// locks load-bearing), and mirror on the method-surface of the
1407    /// sibling free-function [`wit_shape_matches`] +
1408    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
1409    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
1410    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
1411    /// dispatch family.
1412    #[must_use]
1413    pub const fn source(&self) -> &str {
1414        self.de.as_str()
1415    }
1416
1417    /// Substrate-canonical per-`:contratos` callee-Servico scalar
1418    /// accessor every consumer that reads the edge's destination
1419    /// endpoint keys off — returns the author-declared
1420    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
1421    /// from the typed slot's own [`String`] storage.
1422    ///
1423    /// The `:contratos :para` slot names the callee-side member Servico
1424    /// on a typed inter-Servico edge (validated by
1425    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
1426    /// Aplicacao declares — a stray `:para` that doesn't name a member
1427    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
1428    /// callee-attachment miss at cluster-apply time). Callee-side twin
1429    /// of the sibling [`WitContract::source`] accessor — the pair
1430    /// jointly names the typed edge every renderer that fans on the
1431    /// caller-callee identity keys off, and this accessor is also the
1432    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
1433    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
1434    /// composes with `destination()` at every emit site that projects a
1435    /// per-edge destination Servico's L4 listener port.
1436    ///
1437    /// Prior to this lift the `.para` byte-string was accessed inline
1438    /// at five sites — four caixa-core (the validate-side membership
1439    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
1440    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
1441    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
1442    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
1443    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
1444    /// — with no compile-time link back to the typed slot. A future
1445    /// extension of the `:contratos :para` axis to a richer author
1446    /// surface (a multi-callee weighted-fan-out overlay for canary /
1447    /// blue-green routing on typed edges, a per-cluster callee-alias
1448    /// table the operator pins through a future `:placement`-scoped
1449    /// slot, the M4 CR materializer's per-CR admission-webhook that
1450    /// promotes the scalar to a callee-set projection) would have had
1451    /// to be threaded through every open-coded copy in lockstep or one
1452    /// consumer would silently disagree on which callee Servico a given
1453    /// edge resolves to (a per-CNP `endpointSelector` that names a
1454    /// different destination than its L4 port resolver reads for, a
1455    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
1456    /// as distinct while the adjacency map collapses them, or vice
1457    /// versa). Lifting to a typed method on the substrate primitive
1458    /// means every downstream callee-facing consumer reaches for one
1459    /// typed dispatch.
1460    ///
1461    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
1462    /// (6db982c) accessor — both name the "destination-Servico
1463    /// byte-string" concept on their respective mesh-slot atoms (per-
1464    /// ingress apex vs. per-typed-edge callee), and both extend the
1465    /// substrate-primitive-owns-the-resolver discipline onto the
1466    /// per-slot destination-Servico scalar axis. Composes with
1467    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
1468    /// emit-side per-edge L4 port reader — the composition
1469    /// `spec.port_for_destination(c.destination())` pins the CNP per-
1470    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
1471    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
1472    /// `spec.port_for_destination(entrada.destination())`.
1473    ///
1474    /// Declared `pub const fn` — sibling in `const`-eval posture to the
1475    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
1476    /// per-`:contratos` byte-string scalar accessors, all three
1477    /// projecting through the `pub const fn` [`String::as_str`]
1478    /// (const-stable since Rust 1.87). See [`Self::source`] for the
1479    /// family-closure rationale.
1480    #[must_use]
1481    pub const fn destination(&self) -> &str {
1482        self.para.as_str()
1483    }
1484
1485    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
1486    /// accessor every consumer that reads the edge's WIT world
1487    /// discriminator keys off — returns the author-declared
1488    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
1489    /// the typed slot's own [`String`] storage.
1490    ///
1491    /// The `:contratos :wit` slot names the WIT world the typed edge
1492    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
1493    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
1494    /// be a well-shaped WIT world reference via
1495    /// [`crate::render::is_wit_world_ref`] and by
1496    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
1497    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
1498    /// [`WitContract::source`] / [`WitContract::destination`] accessors
1499    /// on the same per-`:contratos` entry — the triple
1500    /// `( source(), destination(), world_ref() )` jointly names the
1501    /// typed edge every renderer that fans on the caller-callee-shape
1502    /// identity keys off (the per-edge dedup key at
1503    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
1504    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
1505    /// [`caixa_mesh::cilium_network_policies`], the
1506    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
1507    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
1508    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
1509    ///
1510    /// Prior to this lift the `.wit` byte-string was accessed inline at
1511    /// five sites — three caixa-core (the `WitContract::is_*` shape-
1512    /// dispatch predicates' `&self.wit` arg, the validate-side empty
1513    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
1514    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
1515    /// printer's `{}` format-slot at `c.wit`) — five open-coded
1516    /// `.wit` field-accesses that expressed no compile-time link back to
1517    /// the typed slot. A future extension of the `:contratos :wit` axis
1518    /// to a richer author surface (an M4 promotion from `String` to a
1519    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
1520    /// lisp per this struct's own `:wit` field docstring, a per-cluster
1521    /// WIT-alias table the operator pins through a future
1522    /// `:placement`-scoped slot, a canonicalization pass that lowercases
1523    /// `wasi:*` prefixes) would have had to be threaded through every
1524    /// open-coded copy in lockstep or one consumer would silently
1525    /// disagree with the peers on which WIT shape a given edge resolves
1526    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
1527    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
1528    /// empty-check that missed a whitespace-only string a peer accessor
1529    /// stripped, or vice versa). Lifting to a typed method on the
1530    /// substrate primitive means every downstream WIT-shape-facing
1531    /// consumer reaches for one typed dispatch — the resolver's
1532    /// accept-set migrates as a unit on any future axis addition.
1533    ///
1534    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
1535    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
1536    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
1537    /// 6db982c), per-`:membros` [`Membro::nome`] /
1538    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
1539    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
1540    /// on the substrate primitive, thin projections at each consumer"
1541    /// discipline extended onto the last unlifted per-`:contratos`
1542    /// scalar (the WIT-world-reference arm).
1543    ///
1544    /// [fag]: caixa-feira/src/cmd/app.rs
1545    ///
1546    /// Declared `pub const fn` — sibling in `const`-eval posture to the
1547    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
1548    /// per-`:contratos` byte-string scalar accessors on the trio, and
1549    /// the load-bearing enabler for the paired `pub const fn`
1550    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1551    /// [`Self::is_capability`] WIT-shape-predicate family (each
1552    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
1553    /// the `const`-eval posture by construction once this accessor
1554    /// carries it). See [`Self::source`] for the family-closure
1555    /// rationale and the paired
1556    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1557    /// for the load-bearing witness.
1558    #[must_use]
1559    pub const fn world_ref(&self) -> &str {
1560        self.wit.as_str()
1561    }
1562
1563    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
1564    /// payload-target scalar accessor every consumer that reads the
1565    /// edge's L7 HTTP request path payload keys off — returns the
1566    /// author-declared `:contratos :endpoint` byte-string verbatim as
1567    /// an `Option<&str>`, borrowed from the typed slot's own
1568    /// `Option<String>` storage; `None` when the slot is absent (the
1569    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
1570    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
1571    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
1572    /// [`WitTarget::Capability`] edge carries none of the three).
1573    ///
1574    /// The `:contratos :endpoint` slot carries the HTTP request path
1575    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
1576    /// — same shape required of `:entrada :paths`, gated by the shared
1577    /// [`crate::render::is_gateway_api_http_path`] predicate) that
1578    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
1579    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
1580    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
1581    /// downstream consumer that reads the payload keys off this scalar
1582    /// (the [`WitContract::target`] Http-arm payload extraction that
1583    /// materializes [`WitTarget::Http { endpoint }`] under the paired
1584    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
1585    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1586    /// key's endpoint arm that pins the payload as part of the six-tuple
1587    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
1588    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
1589    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1590    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
1591    /// emission path that lands the payload verbatim as a Cilium L7
1592    /// `path:` rule).
1593    ///
1594    /// Prior to this lift the `.endpoint` field was accessed inline at
1595    /// two production sites in `caixa-core/src/aplicacao.rs` — the
1596    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
1597    /// self.endpoint.as_deref();` binding at the top of the method, and
1598    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1599    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
1600    /// field-accesses that expressed no compile-time link back to the
1601    /// typed slot. A future extension of the `:contratos :endpoint`
1602    /// axis to a richer author surface (an M4 promotion from
1603    /// `Option<String>` to a typed HTTP path-template enum once the
1604    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
1605    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
1606    /// alias table the operator pins through a future `:placement`-
1607    /// scoped slot, a canonicalization pass that percent-encodes non-
1608    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
1609    /// materializer applies per-tenant) would have had to be threaded
1610    /// through both open-coded copies in lockstep or the two consumers
1611    /// would silently disagree on which HTTP path a given edge resolves
1612    /// to — the [`WitContract::target`] payload-extraction reading
1613    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
1614    /// the operator-resolved `"/tenant-a/lookup"` would silently split
1615    /// the [`WitTarget::Http`]-arm rendered payload from the actual
1616    /// dedup-key uniqueness axis, a two-consumer split at the validator
1617    /// far from the source `caixa.lisp` with no field naming the
1618    /// payload-drift root cause. Lifting the resolution rule to a typed
1619    /// method on the substrate primitive means every downstream
1620    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
1621    /// L7-payload surface reaches for exactly one typed dispatch — the
1622    /// resolver's accept-set migrates as a unit on any future axis
1623    /// addition.
1624    ///
1625    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
1626    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
1627    /// accessors on the M3 mesh-slot family — same "one typed dispatch
1628    /// on the substrate primitive, thin projections at each consumer"
1629    /// discipline extended onto the per-`:contratos` HTTP-shaped
1630    /// payload-carrier `Option<String>` optional-scalar axis. First
1631    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
1632    /// atom — opens the "optional per-slot payload-carrier scalar"
1633    /// projection pattern the sibling per-`:contratos` `:subject` /
1634    /// `:slot` future lifts fold on, matching the closed
1635    /// per-`:contratos` scalar-value accessor family
1636    /// ([`WitContract::source`] / [`WitContract::destination`] /
1637    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
1638    /// scalar `String` axes. Named `endpoint()` to match the storage
1639    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
1640    /// author-facing label const; the accessor's identity name maps
1641    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1642    /// docstring already carries.
1643    #[must_use]
1644    pub const fn endpoint(&self) -> Option<&str> {
1645        match &self.endpoint {
1646            Some(s) => Some(s.as_str()),
1647            None => None,
1648        }
1649    }
1650
1651    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
1652    /// payload-target scalar accessor every consumer that reads the
1653    /// edge's NATS / Kafka publish subject payload keys off — returns
1654    /// the author-declared `:contratos :subject` byte-string verbatim
1655    /// as an `Option<&str>`, borrowed from the typed slot's own
1656    /// `Option<String>` storage; `None` when the slot is absent (the
1657    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
1658    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
1659    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
1660    /// [`WitTarget::Capability`] edge carries none of the three).
1661    ///
1662    /// The `:contratos :subject` slot carries the NATS / Kafka publish
1663    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
1664    /// per-edge target selector — `orders.paid`, `events.>`, whatever
1665    /// subject namespace the author names on the pub-sub edge) that
1666    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
1667    /// arm's `subject: &'a str` payload when the edge's `:wit` world
1668    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
1669    /// downstream consumer that reads the payload keys off this scalar
1670    /// (the [`WitContract::target`] PubSub-arm payload extraction that
1671    /// materializes [`WitTarget::PubSub { subject }`] under the paired
1672    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
1673    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1674    /// key's subject arm that pins the payload as part of the six-tuple
1675    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
1676    /// future M4 per-edge WIT registry resolver's pub-sub-arm
1677    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
1678    /// materializer's per-edge NATS admission webhook, the future
1679    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
1680    /// as a NATS subject the operator pins per-CR).
1681    ///
1682    /// Prior to this lift the `.subject` field was accessed inline at
1683    /// two production sites in `caixa-core/src/aplicacao.rs` — the
1684    /// [`WitContract::target`] payload-shape dispatch's `let subject =
1685    /// self.subject.as_deref();` binding at the top of the method, and
1686    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1687    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
1688    /// field-accesses that expressed no compile-time link back to the
1689    /// typed slot. A future extension of the `:contratos :subject` axis
1690    /// to a richer author surface (an M4 promotion from `Option<String>`
1691    /// to a typed NATS-subject-template enum once the WIT registry
1692    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
1693    /// struct's own `:wit` field docstring, a per-cluster subject-alias
1694    /// table the operator pins through a future `:placement`-scoped
1695    /// slot, a canonicalization pass that lowercases / dedupes wildcard
1696    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
1697    /// applies per-tenant) would have had to be threaded through both
1698    /// open-coded copies in lockstep or the two consumers would silently
1699    /// disagree on which NATS subject a given edge resolves to — the
1700    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
1701    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
1702    /// resolved `"tenant-a.orders.paid"` would silently split the
1703    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
1704    /// key uniqueness axis, a two-consumer split at the validator far
1705    /// from the source `caixa.lisp` with no field naming the payload-
1706    /// drift root cause. Lifting the resolution rule to a typed method
1707    /// on the substrate primitive means every downstream pub-sub-payload-
1708    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
1709    /// surface reaches for exactly one typed dispatch — the resolver's
1710    /// accept-set migrates as a unit on any future axis addition.
1711    ///
1712    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
1713    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
1714    /// carrier axis — second `Option<&str>`-return accessor on the
1715    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
1716    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
1717    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
1718    /// key/value-store arm as the last unlifted per-`:contratos`
1719    /// `Option<String>` axis. Named `subject()` to match the storage
1720    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
1721    /// author-facing label const; the accessor's identity name maps
1722    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1723    /// docstring already carries.
1724    #[must_use]
1725    pub const fn subject(&self) -> Option<&str> {
1726        match &self.subject {
1727            Some(s) => Some(s.as_str()),
1728            None => None,
1729        }
1730    }
1731
1732    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
1733    /// shaped payload-target scalar accessor every consumer that reads
1734    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
1735    /// off — returns the author-declared `:contratos :slot` byte-string
1736    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
1737    /// own `Option<String>` storage; `None` when the slot is absent
1738    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
1739    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
1740    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
1741    /// [`WitTarget::Capability`] edge carries none of the three).
1742    ///
1743    /// The `:contratos :slot` slot carries the key/value store
1744    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
1745    /// arm's per-edge target selector — `carts/{cart_id}`,
1746    /// `sessions/{tenant}/{sid}`, whatever key-template the author
1747    /// names on the store edge) that [`WitContract::target`] projects
1748    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
1749    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
1750    /// accept-set. Every downstream consumer that reads the payload
1751    /// keys off this scalar (the [`WitContract::target`] Store-arm
1752    /// payload extraction that materializes [`WitTarget::Store { slot }`]
1753    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
1754    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1755    /// key's store arm that pins the payload as part of the six-tuple
1756    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
1757    /// the future M4 per-edge WIT registry resolver's store-arm
1758    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
1759    /// materializer's per-edge key/value admission webhook, the future
1760    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
1761    /// as a key-template the operator pins per-CR).
1762    ///
1763    /// Prior to this lift the `.slot` field was accessed inline at two
1764    /// production sites in `caixa-core/src/aplicacao.rs` — the
1765    /// [`WitContract::target`] payload-shape dispatch's `let slot =
1766    /// self.slot.as_deref();` binding at the top of the method, and
1767    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1768    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
1769    /// field-accesses that expressed no compile-time link back to the
1770    /// typed slot. A future extension of the `:contratos :slot` axis
1771    /// to a richer author surface (an M4 promotion from `Option<String>`
1772    /// to a typed key-template enum once the WIT registry stabilizes
1773    /// key-template parameter shapes in tatara-lisp per this struct's
1774    /// own `:wit` field docstring, a per-cluster slot-alias table the
1775    /// operator pins through a future `:placement`-scoped slot, a
1776    /// canonicalization pass that lowercases the bucket prefix, a
1777    /// per-CR fully-qualified rewrite the M4 CR materializer applies
1778    /// per-tenant) would have had to be threaded through both
1779    /// open-coded copies in lockstep or the two consumers would
1780    /// silently disagree on which key-template a given edge resolves
1781    /// to — the [`WitContract::target`] payload-extraction reading
1782    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
1783    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
1784    /// would silently split the [`WitTarget::Store`]-arm rendered
1785    /// payload from the actual dedup-key uniqueness axis, a
1786    /// two-consumer split at the validator far from the source
1787    /// `caixa.lisp` with no field naming the payload-drift root cause.
1788    /// Lifting the resolution rule to a typed method on the substrate
1789    /// primitive means every downstream store-payload-facing consumer
1790    /// of the Aplicacao's per-`:contratos` payload surface reaches for
1791    /// exactly one typed dispatch — the resolver's accept-set migrates
1792    /// as a unit on any future axis addition.
1793    ///
1794    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
1795    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
1796    /// accessors on the M3 mesh-slot payload-carrier axis — third and
1797    /// final `Option<&str>`-return accessor on the per-`:contratos`
1798    /// mesh-slot atom, closes the last unlifted per-`:contratos`
1799    /// `Option<String>` axis and completes the "optional per-slot
1800    /// payload-carrier scalar" projection pattern the peer HTTP /
1801    /// pub-sub arms established across the three payload-shape
1802    /// dispatch arms. Named `slot()` to match the storage field's
1803    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
1804    /// author-facing label const; the accessor's identity name maps
1805    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1806    /// docstring already carries.
1807    #[must_use]
1808    pub const fn slot(&self) -> Option<&str> {
1809        match &self.slot {
1810            Some(s) => Some(s.as_str()),
1811            None => None,
1812        }
1813    }
1814
1815    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
1816    /// caller-callee-pair accessor every consumer that constructs an
1817    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
1818    /// caller-callee pair keys off — returns the author-declared
1819    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
1820    /// owned `(String, String)` tuple, projected through the lifted
1821    /// [`WitContract::source`] / [`WitContract::destination`] scalar
1822    /// accessors so any future rebrand on the caller-arm / callee-arm
1823    /// projection axis (an M4 per-cluster caller-alias table the
1824    /// operator pins through a future `:placement`-scoped slot, a
1825    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
1826    /// a per-`:membros` alias overlay from the future `:membros
1827    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1828    /// acknowledges) reaches every diagnostic-construction site by
1829    /// construction.
1830    ///
1831    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
1832    /// owned form" primitive every per-`:contratos` diagnostic variant on
1833    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
1834    /// nine variants [`AplicacaoError::EmptyWit`],
1835    /// [`AplicacaoError::ContratoEndpointEmpty`],
1836    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
1837    /// [`AplicacaoError::ContratoEndpointInvalid`],
1838    /// [`AplicacaoError::ContratoSubjectEmpty`],
1839    /// [`AplicacaoError::ContratoSubjectInvalid`],
1840    /// [`AplicacaoError::ContratoSlotEmpty`],
1841    /// [`AplicacaoError::ContratoSlotInvalid`], and
1842    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
1843    /// para: String` field pair the constructor site reads verbatim off
1844    /// the [`WitContract`] the diagnostic points at, so a diagnostic
1845    /// whose `de:` and `para:` labels silently drift off the source
1846    /// caller/callee — a per-cluster caller-alias rewrite that landed on
1847    /// one variant's inline `de: c.de.clone()` field access but not on
1848    /// its sibling variant's, an accidental swap of the `de:` and `para:`
1849    /// arms in a copy-paste of the constructor block — would emit a
1850    /// build-time error whose "which caixa is at fault" question the
1851    /// operator answers wrongly, far from the source `caixa.lisp`.
1852    ///
1853    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
1854    /// pair was inlined at seven [`WitContract::target`] error-
1855    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
1856    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
1857    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
1858    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
1859    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
1860    /// the [`AplicacaoError::ContratoSlotEmpty`] /
1861    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
1862    /// two [`AplicacaoSpec::validate`] error-construction sites (the
1863    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
1864    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
1865    /// insert-first-seen closure) — nine open-coded `.de.clone() +
1866    /// .para.clone()` pairs that expressed no compile-time contract that
1867    /// the caller-arm and callee-arm arms of the same diagnostic
1868    /// construction reach for the same [`WitContract`] instance or that
1869    /// the `de:` and `para:` label pair binds to the fields the author
1870    /// declared. Any future rebrand on the axis — an M4 per-cluster
1871    /// caller/callee-alias rewrite the operator pins through a future
1872    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
1873    /// per-CR fully-qualified namespace prefix the M4
1874    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
1875    /// per-tenant, a canonicalization pass that lowercases the caller +
1876    /// callee identifiers post-parse — would have had to be threaded
1877    /// through every open-coded copy in lockstep or one variant's
1878    /// diagnostic would silently name a different caller/callee pair
1879    /// than its peer, silently degrading the "which caixa is at fault"
1880    /// self-locating signal every operator-facing typed diagnostic
1881    /// exists to carry. Lifting the pair to a typed method on the
1882    /// substrate primitive means every downstream diagnostic-construction
1883    /// site reaches for exactly one typed dispatch — the resolver's
1884    /// projection migrates as a unit on any future axis addition.
1885    ///
1886    /// Peer of the sibling per-`:contratos` scalar accessor family
1887    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
1888    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
1889    /// scalar-value axes — first composite-projection accessor on the
1890    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
1891    /// form `.clone()` field-accesses that pair the sibling
1892    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
1893    /// one typed dispatch. Named `edge_pair()` to reflect the identity
1894    /// name of the projected tuple (the typed-edge caller-callee pair,
1895    /// distinct from the sibling triple-projection
1896    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
1897    /// closure in [`WitContract::target`] + the paired
1898    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
1899    /// site's `(de, para, wit)` triple onto one typed dispatch).
1900    #[must_use]
1901    pub fn edge_pair(&self) -> (String, String) {
1902        (self.source().to_string(), self.destination().to_string())
1903    }
1904
1905    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
1906    /// :wit)` triple every per-edge diagnostic constructor that names
1907    /// all three axes threads verbatim into its `de:` / `para:` /
1908    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
1909    /// / missing-target / invalid-wit / capability-with-payload arms
1910    /// (eight sites all shape `let (de, para, wit) = edge();
1911    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
1912    /// accessor landed) and the sibling
1913    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
1914    /// constructor (which paired `edge_pair()` for the `(de, para)`
1915    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
1916    /// typed-dispatch + raw-field-access shape the sibling accessor
1917    /// family already flagged as a drift risk). Nine total call sites
1918    /// collapse onto this helper.
1919    ///
1920    /// Lifted with the same one-source-of-truth discipline
1921    /// [`WitContract::edge_pair`] carries on the paired
1922    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
1923    /// arms compose through the lifted [`WitContract::source`] /
1924    /// [`WitContract::destination`] / [`WitContract::world_ref`]
1925    /// scalar accessors byte-for-byte (pinned by the paired
1926    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
1927    /// composition-pin), so any future rebrand on the per-`:contratos`
1928    /// caller / callee / world-ref axis (an M4 per-cluster
1929    /// caller/callee-alias rewrite the operator pins through a future
1930    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
1931    /// per-CR fully-qualified namespace prefix the M4
1932    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
1933    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
1934    /// on `source()` / `destination()`, a per-CR canonicalization pass
1935    /// that lowercases the WIT world ref post-parse) migrates as a
1936    /// single caixa-core edit rather than a coordinated rewrite of
1937    /// nine open-coded triple-constructors.
1938    ///
1939    /// Peer of the sibling per-`:contratos` composite-projection
1940    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
1941    /// composite-value axes — closes the last unlifted owned-form
1942    /// composite-tuple axis on the per-`:contratos` diagnostic-
1943    /// construction surface. Named `edge_triple()` to reflect the
1944    /// identity name of the projected tuple (the typed-edge
1945    /// caller-callee-wit triple, sibling to the caller-callee-only
1946    /// pair `edge_pair()` returns).
1947    #[must_use]
1948    pub fn edge_triple(&self) -> (String, String, String) {
1949        (
1950            self.source().to_string(),
1951            self.destination().to_string(),
1952            self.world_ref().to_string(),
1953        )
1954    }
1955
1956    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
1957    /// dedups typed edges keys off — routes through the lifted
1958    /// [`WitContract::source`] / [`WitContract::destination`] /
1959    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
1960    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
1961    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
1962    /// type alias's six axes migrate as a unit on any future axis
1963    /// addition (adding a seventh field to [`WitContract`] is one
1964    /// [`ContratoIdentity`] alias edit + one accessor addition + one
1965    /// arm here, not a coordinated rewrite of every open-coded
1966    /// six-tuple builder that dedups on the identity axis).
1967    ///
1968    /// Sibling of [`WitContract::edge_pair`] /
1969    /// [`WitContract::edge_triple`] on the composite-projection axis:
1970    /// the pair projects the caller-callee axes, the triple extends it
1971    /// with the world-ref, this method extends it with the three
1972    /// payload-carrier axes. Every projection returns the same six
1973    /// scalar accessors' outputs; the three methods differ only in
1974    /// which arms they surface.
1975    ///
1976    /// Declared `pub const fn` — every callee is itself `pub const fn`
1977    /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
1978    /// project through `pub const fn` [`String::as_str`], const-stable
1979    /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
1980    /// [`Self::slot`] project through the same `String::as_str` under a
1981    /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
1982    /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1983    /// closed the const-eval surface on) and tuple construction from
1984    /// borrowed-reference / `Option`-of-borrowed-reference arms is
1985    /// itself trivially const. The `ContratoIdentity<'_>` alias
1986    /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1987    /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1988    /// no heap allocation, no non-const call folded through the tuple's
1989    /// construction. Sibling in `const`-eval posture to the peer
1990    /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1991    /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1992    /// composite-projection family the sibling
1993    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1994    /// already anchors — this extends the same `const`-eval-surface
1995    /// posture onto the peer six-arm composite-projection axis where
1996    /// the projection surfaces the full identity tuple rather than a
1997    /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1998    /// bearing by
1999    /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
2000    /// (a future accidental downgrade fires E0015 at the wrapper at
2001    /// caixa-core build time).
2002    #[must_use]
2003    pub const fn identity(&self) -> ContratoIdentity<'_> {
2004        (
2005            self.source(),
2006            self.destination(),
2007            self.world_ref(),
2008            self.endpoint(),
2009            self.subject(),
2010            self.slot(),
2011        )
2012    }
2013
2014    /// True when this contract targets an HTTP-shaped WIT world.
2015    ///
2016    /// Declared `pub const fn` — routes through the paired `pub const
2017    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
2018    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
2019    /// (d46420c). Sibling in `const`-eval posture to the peer
2020    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
2021    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
2022    /// 4-arm partition on the raw `:contratos :wit` axis now carries
2023    /// the same `const`-eval-surface posture as the free-function
2024    /// classifier family it composes through. Pinned load-bearing by
2025    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
2026    /// test (a future accidental downgrade to non-`const` fires E0015
2027    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
2028    /// build time).
2029    #[must_use]
2030    pub const fn is_http(&self) -> bool {
2031        wit_shape_is_http(self.world_ref())
2032    }
2033
2034    /// True when this contract targets a pub-sub-shaped WIT world.
2035    ///
2036    /// Declared `pub const fn` — sibling in `const`-eval posture to
2037    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
2038    /// [`Self::is_capability`] WIT-shape-predicate family. See
2039    /// [`Self::is_http`] for the family-closure rationale.
2040    #[must_use]
2041    pub const fn is_pubsub(&self) -> bool {
2042        wit_shape_is_pubsub(self.world_ref())
2043    }
2044
2045    /// True when this contract targets a key/value-shaped WIT world.
2046    ///
2047    /// Declared `pub const fn` — sibling in `const`-eval posture to
2048    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
2049    /// [`Self::is_capability`] WIT-shape-predicate family. See
2050    /// [`Self::is_http`] for the family-closure rationale.
2051    #[must_use]
2052    pub const fn is_store(&self) -> bool {
2053        wit_shape_is_store(self.world_ref())
2054    }
2055
2056    /// True when this contract targets *none* of the three known payload-
2057    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
2058    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
2059    /// open on the [`WitContract`] surface. Returns the exact-inverse
2060    /// disjunction of the peer trio — `true` when none of the three
2061    /// prefix-set predicates matches the raw `:contratos :wit` value; the
2062    /// author-declared WIT world is a pure typed capability edge with no
2063    /// payload selector (the shape [`WitContract::target`] projects onto
2064    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
2065    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
2066    ///
2067    /// The `:contratos :wit` shape-space is closed at four arms
2068    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
2069    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
2070    /// everything else on the payload-less capability arm), and every
2071    /// downstream consumer that must filter contratos by shape-class
2072    /// keys off the four sibling predicates (the [`WitContract::target`]
2073    /// dispatch's implicit `else` after the three payload-shape arm
2074    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
2075    /// every future substrate-side capability-shape-only emitter — the
2076    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
2077    /// future `feira app graph --capability` per-Aplicacao capability-
2078    /// column filter, the future per-cluster capability-scope reconciler
2079    /// that skips L4/L7 emission for payload-less edges since Cilium
2080    /// can't introspect WASI capability calls, the future
2081    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
2082    /// shape shape-count histogram). Every such consumer reaches for one
2083    /// typed dispatch on the substrate primitive so the "which arm
2084    /// carries the capability-only shape?" answer lives at one caixa-core
2085    /// edit rather than open-coded across per-consumer
2086    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
2087    /// negations, each of which would silently drop a future fourth
2088    /// payload-arm addition without a compile-time signal at the
2089    /// consumer site.
2090    ///
2091    /// Prior to this lift the "not one of the three known payload
2092    /// shapes" classification sat inline at [`WitContract::target`]'s
2093    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
2094    /// [`WitTarget::Capability`] admission arm after the three `if
2095    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
2096    /// { … }` guards) with no named accessor for downstream consumers
2097    /// to reach through. A future substrate-side capability-only
2098    /// filter or a future capability-scope reconciler would have had to
2099    /// re-inline the same triplet negation at every emit site with no
2100    /// compile-time link back to the sibling trio, and a future arm
2101    /// addition (a hypothetical fourth payload-shape prefix set — a
2102    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
2103    /// import carrier per the sibling [`wit_shape_matches`] docstring's
2104    /// trajectory bullet) would land the new predicate on the payload-
2105    /// carrying trio and silently misclassify the new shape as
2106    /// capability at every triplet-negation consumer site, propagating
2107    /// the drift far from the caixa-core prefix-set commit.
2108    ///
2109    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
2110    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
2111    /// trio into a 4-way partition witness on the raw `:contratos :wit`
2112    /// axis, mirroring the paired post-projection [`WitTarget`]
2113    /// `gen_platform::IsVariant`-derived 4-way predicate set
2114    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
2115    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
2116    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
2117    /// arm-set). The two typed axes — pre-projection on the raw
2118    /// `:contratos :wit` string, post-projection on the validated typed
2119    /// view — now carry a matched 4-arm predicate discipline: every
2120    /// arm on the closed [`WitTarget`] set has a peer pre-projection
2121    /// predicate on the [`WitContract`] surface, and any future
2122    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
2123    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
2124    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
2125    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
2126    /// pre-projection axis through a matching peer prefix-set + peer
2127    /// predicate lift by construction — the compile-time exhaustiveness
2128    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
2129    /// the post-projection accessor family stays in sync, and the sibling
2130    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
2131    /// partition-witness pin locks the pre-projection classification in
2132    /// load-bearing so a peer prefix-set addition that widened one arm's
2133    /// accept-set without shrinking the [`Self::is_capability`] accept-set
2134    /// surfaces as a test failure at caixa-core build time rather than a
2135    /// silent per-consumer split at renderer emit time.
2136    ///
2137    /// Composes byte-for-byte through the lifted peer trio
2138    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
2139    /// any future rebrand of any prefix-set const flows through this
2140    /// method by construction without a coordinated per-consumer rewrite
2141    /// (pinned by the sibling
2142    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
2143    /// composition-witness).
2144    ///
2145    /// Note: purely syntactic classification on the `:wit` prefix-set —
2146    /// unlike [`Self::target`], which additionally rejects value-shape-
2147    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
2148    /// package) via [`crate::render::is_wit_world_ref`] and payload-
2149    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
2150    /// structurally malformed returns `true` from `is_capability()` (the
2151    /// prefix set matches nothing), and the surrounding
2152    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
2153    /// is where the [`AplicacaoError::EmptyWit`] /
2154    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
2155    /// predicate is the classifier, not the validator.
2156    ///
2157    /// Declared `pub const fn` — closes the WIT-shape-predicate
2158    /// family's `const`-eval-surface pass at the fourth (payload-less)
2159    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
2160    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
2161    /// See [`Self::is_http`] for the family-closure rationale.
2162    #[must_use]
2163    pub const fn is_capability(&self) -> bool {
2164        wit_shape_is_capability(self.world_ref())
2165    }
2166
2167    /// True when this contract's caller equals its callee — a
2168    /// structurally degenerate typed edge that no `:contratos` entry can
2169    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
2170    /// Servico B" is an *inter*-Servico contract between two distinct
2171    /// graph nodes). A Servico contracting with itself resolves to an
2172    /// in-process call the wasm-engine never routes through the mesh at
2173    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
2174    /// per-edge policy can express the intended shape — the pub-sub
2175    /// path silently rendered a self-allow rule that is a no-op (intra-
2176    /// pod traffic bypasses the mesh entirely), and the synchronous
2177    /// paths surfaced as a misleading `ContratoCycle` whose path was
2178    /// `["cart", "cart"]` — framing a self-edge as a multi-node
2179    /// deadlock. Every downstream consumer that must reject the shape
2180    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
2181    /// gate at caixa-core/src/aplicacao.rs:5559, every future
2182    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
2183    /// axis, every future adjacency-graph builder that must skip self-
2184    /// edges rather than fold them into an incidental cycle) now keys
2185    /// off exactly one typed dispatch on the substrate primitive, so
2186    /// any future rebrand on the axis (an M4-typed-caller enum whose
2187    /// identity comparison rule the accessor could route through, an
2188    /// operator-side per-cluster caller/callee-alias table the
2189    /// materializer resolves per-CR before the equality probe, a
2190    /// promotion of the pointwise `==` to a set-membership check once
2191    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
2192    /// so a per-replica self-edge is rejected under the same predicate)
2193    /// migrates as a single caixa-core edit rather than a coordinated
2194    /// rewrite of every downstream self-edge consumer. Composes
2195    /// byte-for-byte through the lifted [`Self::source`] /
2196    /// [`Self::destination`] scalar accessors — the accessor pair every
2197    /// per-`:contratos` scalar-value axis already routes through — so
2198    /// any future rebrand of the underlying `:de` / `:para` storage
2199    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
2200    /// a per-Aplicacao interning arena the M4 CR materializer authors,
2201    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
2202    /// same one body without a coordinated per-consumer rewrite.
2203    ///
2204    /// Sibling in shape to the peer per-`:contratos` shape-predicate
2205    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
2206    /// on the `:wit` world-ref axis — extended onto the per-edge
2207    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
2208    /// partition the WIT-shape-space; `is_self_loop` partitions the
2209    /// caller-callee identity-space. Named `is_self_loop()` to reflect
2210    /// the graph-theoretic identity of the shape (a loop from a graph
2211    /// node to itself, distinct from the sibling multi-node
2212    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
2213    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
2214    /// variant already carrying the term.
2215    ///
2216    /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
2217    /// shape-predicate on the substrate's `const`-eval surface. The peer
2218    /// per-`:contratos` shape-predicate family [`Self::is_http`] /
2219    /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
2220    /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
2221    /// posture on the WIT-world-ref classifier axis; this lift extends it
2222    /// onto the peer caller-callee identity-space predicate. The body
2223    /// projects the `:de` / `:para` `String` storage through the sibling
2224    /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
2225    /// accessors, then compares the resulting `&str` byte-slices under a
2226    /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
2227    /// const-stable since Rust 1.39), primitive-`usize` `!=` on
2228    /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
2229    /// — every operation `const`-eval-callable on stable Rust, no
2230    /// iterator methods, no `PartialEq for str` trait dispatch (which
2231    /// remains non-`const` on stable). Mirrors the peer `pub const fn`
2232    /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
2233    /// loop verbatim on the paired-slice-equality shape. Every downstream
2234    /// substrate-side `const`-context consumer of the per-`:contratos`
2235    /// self-edge partition (a future `const _: () = assert!(…)` module-
2236    /// scope invariant pin over a per-fixture typed [`WitContract`] once
2237    /// the type's carriers admit `const`-context construction, a future
2238    /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
2239    /// composer that fans on the identity-space partition at compile
2240    /// time) reaches through the same typed dispatch on the substrate
2241    /// primitive at const-eval time as at runtime. Pinned by
2242    /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
2243    /// witnesses the `const`-eval posture via a `const fn` wrapper so any
2244    /// future accidental downgrade to non-`const` trips at caixa-core
2245    /// build time with E0015 (`cannot call non-const method`), strictly
2246    /// stronger than a runtime `assert!`.
2247    #[must_use]
2248    pub const fn is_self_loop(&self) -> bool {
2249        // Compose through the paired `pub const fn` [`Self::source`] /
2250        // [`Self::destination`] scalar accessors so any future rebrand of
2251        // the underlying `:de` / `:para` storage (a lift from `String` to
2252        // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
2253        // arena the M4 CR materializer authors, a `smol_str::SmolStr`
2254        // inline-buffer swap) flows through the same one body without a
2255        // coordinated per-consumer rewrite. Peer of the sibling
2256        // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
2257        // [`Self::is_capability`] shape-predicate family — each of which
2258        // composes through the paired [`Self::world_ref`] scalar accessor
2259        // onto the peer `pub const fn` [`wit_shape_is_http`] /
2260        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
2261        // [`wit_shape_is_capability`] free-function classifier — the same
2262        // "typed dispatch composes with typed dispatch, not raw field
2263        // access" discipline extended onto the caller-callee identity-
2264        // space partition. Pinned by
2265        // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
2266        // above.
2267        let a = self.source().as_bytes();
2268        let b = self.destination().as_bytes();
2269        if a.len() != b.len() {
2270            return false;
2271        }
2272        // Manual byte-level equality loop — mirrors the peer
2273        // [`wit_shape_matches`] combinator's manual `starts_with` loop
2274        // verbatim on the paired-slice-equality shape. `PartialEq for
2275        // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
2276        // trait dispatch it routes through is not `const`), so a naive
2277        // `self.source() == self.destination()` body would trip on
2278        // `const`-eval-callability; the byte-slice loop dispatches
2279        // through primitive-`u8` `!=`, primitive-`usize` comparison, and
2280        // const-stable slice indexing (since Rust 1.79) — every
2281        // operation `const`-eval-callable on stable.
2282        let mut i = 0;
2283        while i < a.len() {
2284            if a[i] != b[i] {
2285                return false;
2286            }
2287            i += 1;
2288        }
2289        true
2290    }
2291
2292    /// Reject a `:contratos` entry whose `:de` or `:para` names a
2293    /// caixa the `:membros` graph does not contain — the substrate-
2294    /// primitive per-edge graph-membership gate every consumer of the
2295    /// typed inter-Servico edge's endpoint-resolution axis reaches
2296    /// through one dispatch.
2297    ///
2298    /// A `:contratos` entry is a typed directed edge between two
2299    /// declared members (MESH-COMPOSITION §III.1 — "the typed edges
2300    /// address graph nodes, so a reference to a node the graph does
2301    /// not contain is a build error"). Both endpoints must resolve
2302    /// against the same [`AplicacaoSpec::membro_names`] oracle: the
2303    /// paired [`AplicacaoError::ContratoMemberMissing`] diagnostic
2304    /// framing does not distinguish `:de` from `:para` (both arms
2305    /// carry the offending `caixa` name verbatim without a
2306    /// slot-discriminator field, unlike the sibling per-arm shape
2307    /// gate [`validate_contrato_caixa`] whose paired
2308    /// [`AplicacaoError::ContratoCaixaEmpty`] / `ContratoCaixaInvalid`
2309    /// variants each carry a `slot: &'static str` tag). So the two
2310    /// arms are byte-identical modulo the accessor projection they
2311    /// key off, and folding them into one per-edge dispatch preserves
2312    /// every existing diagnostic-fired output byte-for-byte while
2313    /// closing the last inline duplication the substrate-primitive
2314    /// per-edge gate family carried inside
2315    /// [`AplicacaoSpec::validate_contratos`].
2316    ///
2317    /// Routes through the paired [`Self::source`] / [`Self::destination`]
2318    /// scalar accessors so every future rebrand of the underlying
2319    /// `:de` / `:para` storage (a lift from `String` to a typed
2320    /// `ServicoName(String)` newtype, a per-Aplicacao interning arena
2321    /// the M4 CR materializer authors, a per-cluster caller-alias
2322    /// table the operator pins through a future `:placement`-scoped
2323    /// slot, an M4 promotion from `String` to a typed edge-endpoint
2324    /// enum) flows through the same body without a coordinated
2325    /// per-consumer rewrite. Peer of the sibling per-edge substrate
2326    /// primitives already lifted on the same `impl WitContract`
2327    /// surface ([`Self::is_self_loop`] on the identity-space arm,
2328    /// [`Self::target`] on the payload-shape ↔ target-consistency
2329    /// arm, [`Self::identity`] on the dedup-key arm) — this run
2330    /// extends the shape to the last per-edge axis
2331    /// [`AplicacaoSpec::validate_contratos`] carried as an inline
2332    /// twin-arm cascade.
2333    ///
2334    /// Every future consumer that wants to re-check *one* edge's
2335    /// graph-membership reaches through one call: the M4
2336    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
2337    /// admission-webhook re-checking `:contratos` after a
2338    /// per-`(:de, :para)` edge patch without re-walking the whole
2339    /// `:contratos` list, the per-`:contratos`-edge `:politicas`
2340    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
2341    /// resolves an effective per-edge [`MeshPolicy`] and must
2342    /// re-check the edge's endpoints against the same membership
2343    /// oracle before it can key a per-edge override off the endpoint
2344    /// tuple. Pre-lift each such consumer was structurally forced to
2345    /// either re-inline the twin `if !names.contains(...)` cascade
2346    /// (the duplication the PRIME DIRECTIVE names as a bug) or call
2347    /// [`AplicacaoSpec::validate_contratos`] and pay a whole-list
2348    /// walk to re-check one edge. Post-lift each reaches the axis
2349    /// through one dispatch on the substrate primitive.
2350    ///
2351    /// `:de` runs before `:para` per the canonical edge-direction
2352    /// order the sibling per-arm shape gate
2353    /// [`validate_contrato_caixa`] arm ordering, the self-loop
2354    /// diagnostic string, and every peer arm ordering in
2355    /// [`AplicacaoSpec::validate_contratos`] already use — a
2356    /// well-shaped-but-phantom `:de` fires before a well-shaped-but-
2357    /// phantom `:para`, preserving byte-equal ordering with the
2358    /// pre-lift inline cascade.
2359    fn require_endpoints_in(
2360        &self,
2361        names: &std::collections::HashSet<&str>,
2362    ) -> Result<(), AplicacaoError> {
2363        if !names.contains(self.source()) {
2364            return Err(AplicacaoError::contrato_member_missing(self.source()));
2365        }
2366        if !names.contains(self.destination()) {
2367            return Err(AplicacaoError::contrato_member_missing(self.destination()));
2368        }
2369        Ok(())
2370    }
2371
2372    /// Typed view of the contract's payload target. Enforces that the
2373    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
2374    /// fields agree, and that each carried value is itself
2375    /// value-shape valid:
2376    ///
2377    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
2378    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
2379    ///     `PathPrefix` invariant — same shape required of `:entrada
2380    ///     :paths`)
2381    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
2382    ///     non-empty (NATS / Kafka publish without a subject is a
2383    ///     no-op subscribe, never the author's intent)
2384    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
2385    ///     non-empty (an empty slot template addresses the bucket
2386    ///     root, defeating the per-key isolation the slot exists for)
2387    ///   - Anything else ⇒ none of the three; the contract is a pure
2388    ///     typed capability edge with no payload selector.
2389    ///
2390    /// Translates the Apollo Federation discipline ("conflicts are
2391    /// errors at compile time, not warnings at runtime";
2392    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
2393    /// a contract whose WIT shape disagrees with its target field, or
2394    /// whose target field carries a value-shape-invalid string, is a
2395    /// build error — not a silent renderer drop. The returned
2396    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
2397    /// non-empty (and absolute, for `Http`); every downstream consumer
2398    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
2399    /// the M4 per-edge policy resolver) can rely on that without
2400    /// re-checking.
2401    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
2402        // Route the HTTP-shaped payload-target extraction through the
2403        // lifted [`WitContract::endpoint`] accessor rather than the raw
2404        // `self.endpoint.as_deref()` field access — the two production
2405        // consumers of the per-`:contratos :endpoint` HTTP-shaped
2406        // payload-carrier scalar (this method's Http-arm payload
2407        // extraction, the [`AplicacaoSpec::validate`] duplicate-
2408        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
2409        // off exactly one typed dispatch on the substrate primitive, so
2410        // any future rebrand on the axis (an M4 per-cluster endpoint-
2411        // alias rewrite, a per-CR fully-qualified path prefix the M4
2412        // materializer applies per-tenant, an M4 promotion from
2413        // `Option<String>` to a typed HTTP path-template enum) migrates
2414        // as a single caixa-core edit rather than a coordinated rewrite
2415        // of the two call sites — peer of the sibling M3 per-`:placement`
2416        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
2417        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
2418        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
2419        let endpoint = self.endpoint();
2420        let subject = self.subject();
2421        // Route the store-arm payload-carrier scalar through the
2422        // lifted [`WitContract::slot`] accessor rather than the raw
2423        // `self.slot.as_deref()` field access — the two production
2424        // consumers of the per-`:contratos :slot` key/value-store-
2425        // shaped payload-carrier scalar (this method's Store-arm
2426        // payload extraction, the [`AplicacaoSpec::validate`]
2427        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
2428        // arm) now key off exactly one typed dispatch on the substrate
2429        // primitive. Closes the last unlifted per-`:contratos`
2430        // `Option<String>` axis, completing the payload-carrier
2431        // accessor family peer of the sibling per-`:contratos`
2432        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
2433        // (90de675) lifts across the HTTP / pub-sub arms.
2434        let slot = self.slot();
2435        // Route the local `(de, para, wit)` triple-projection closure
2436        // through the lifted [`WitContract::edge_triple`] typed accessor
2437        // rather than re-inlining `(self.de.clone(), self.para.clone(),
2438        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
2439        // triple-carrying diagnostic constructors below (wrong-target /
2440        // missing-target on all three payload arms + capability-with-
2441        // payload + invalid-wit) now key off exactly one typed dispatch
2442        // on the substrate-primitive composite projection, sibling to
2443        // the peer [`WitContract::edge_pair`]-routed
2444        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
2445        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
2446        // diagnostic constructors on the same per-`:contratos`
2447        // diagnostic-construction surface.
2448        let edge = || self.edge_triple();
2449
2450        // The `:wit` value drives every downstream dispatch — the
2451        // is_http/is_pubsub/is_store prefix matchers below, the
2452        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
2453        // exclusion. Until this gate landed `target()` accepted any
2454        // non-empty string and silently demoted unrecognized shapes to
2455        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
2456        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
2457        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
2458        // package, the paste-from-binary footgun a multi-line blob
2459        // accidentally landing in the slot, the un-percent-encoded
2460        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
2461        // routing, got L4-only" footgun. Empty is still pre-checked at
2462        // the [`AplicacaoSpec::validate`] call site via the narrower
2463        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
2464        // validate layer); the value-shape gate here picks up the
2465        // structurally-invalid non-empty cases the empty check misses,
2466        // and remains correct under direct `target()` calls outside
2467        // validate (the predicate's defensive empty arm returns a
2468        // parser-shaped reason rather than silently falling through to
2469        // the Capability arm). Same trajectory as c4213a4 (WitContract
2470        // endpoint/subject/slot value-shape gates lifted into
2471        // `target()`) on the peer payload axes.
2472        //
2473        // Routed through the lifted [`WitContract::world_ref`] accessor
2474        // rather than the raw `&self.wit` field access — the two
2475        // production consumers of the per-`:contratos :wit` world-ref
2476        // byte-string on the value-shape axis (this method's invalid-
2477        // wit gate, the [`AplicacaoSpec::validate`] duplicate-
2478        // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
2479        // [`WitContract::identity`]) now key off exactly one typed
2480        // dispatch on the substrate primitive, so any future rebrand on
2481        // the axis (an M4 promotion from `String` to a typed WIT
2482        // world-ref enum once the WIT registry stabilizes in
2483        // tatara-lisp, a per-CR canonicalization pass that lowercases
2484        // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
2485        // inline-buffer swap on the storage arm) migrates as a single
2486        // caixa-core edit rather than a coordinated rewrite of the two
2487        // call sites — sibling of the peer [`WitContract::endpoint`] /
2488        // [`WitContract::subject`] / [`WitContract::slot`] accessor-
2489        // routed payload-carrier extractions above on the same
2490        // [`WitContract::target`] body, completing the per-`:contratos`
2491        // scalar-accessor-routing pass at the last unlifted raw-field-
2492        // access site inside `impl WitContract`. Same "typed dispatch
2493        // composes with typed dispatch, not with raw field access"
2494        // discipline the sibling [`WitContract::edge_pair`] /
2495        // [`WitContract::edge_triple`] / [`WitContract::identity`]
2496        // composite-projection accessors and the
2497        // [`WitContract::is_self_loop`] identity-space predicate
2498        // already route through. Pinned by
2499        // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
2500        if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
2501            return Err(AplicacaoError::contrato_wit_invalid(
2502                self.edge_pair(),
2503                self.world_ref(),
2504                reason,
2505            ));
2506        }
2507
2508        if self.is_http() {
2509            if subject.is_some() || slot.is_some() {
2510                return Err(AplicacaoError::contrato_wrong_target(
2511                    edge(),
2512                    WitTarget::HTTP_FIELD_NAME,
2513                ));
2514            }
2515            let ep = endpoint.ok_or_else(|| {
2516                AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
2517            })?;
2518            if ep.is_empty() {
2519                return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
2520            }
2521            if !ep.starts_with('/') {
2522                return Err(AplicacaoError::contrato_endpoint_not_absolute(
2523                    self.edge_pair(),
2524                    ep,
2525                ));
2526            }
2527            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
2528            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
2529            // API v1 HTTPPathMatch.value admission grammar with the
2530            // sibling `:entrada :paths` axis. Until this gate landed
2531            // `target()` only refused the empty string + the missing-
2532            // leading-`/` form; a structurally invalid endpoint
2533            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
2534            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
2535            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
2536            // path-traversal segment, the >1024-byte slug) silently
2537            // passed validate and the failure surfaced at apply time
2538            // as a Cilium policy rejection / silent traffic drop, far
2539            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
2540            // grammar `:entrada :paths` already gates (55410e4), now
2541            // shared with `:contratos :endpoint` through the lifted
2542            // `crate::render::is_gateway_api_http_path` predicate.
2543            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
2544                return Err(AplicacaoError::contrato_endpoint_invalid(
2545                    self.edge_pair(),
2546                    ep,
2547                    reason,
2548                ));
2549            }
2550            return Ok(WitTarget::Http { endpoint: ep });
2551        }
2552        if self.is_pubsub() {
2553            if endpoint.is_some() || slot.is_some() {
2554                return Err(AplicacaoError::contrato_wrong_target(
2555                    edge(),
2556                    WitTarget::PUBSUB_FIELD_NAME,
2557                ));
2558            }
2559            let s = subject.ok_or_else(|| {
2560                AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
2561            })?;
2562            if s.is_empty() {
2563                return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
2564            }
2565            // The `:subject` lands at runtime as the NATS subject the
2566            // producer publishes to and the consumer subscribes from.
2567            // Until this gate landed `target()` only refused the
2568            // empty string; a structurally invalid subject
2569            // (`"foo..bar"` — empty token between separators,
2570            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
2571            // server's subject parser rejects, `"foo bar"` —
2572            // un-percent-encoded whitespace, `"foo.café"` —
2573            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
2574            // empty leading/trailing tokens, the >256-byte
2575            // paste-from-binary slug) silently passed validate and
2576            // the failure surfaced at runtime as a NATS server-side
2577            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
2578            // a silent message drop, far from the source caixa.lisp.
2579            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
2580            // trajectory `:contratos :endpoint` (4f0390b) and
2581            // `:contratos :wit` (6226bf4) already gate, now shared
2582            // with `:contratos :subject` through the lifted
2583            // `crate::render::is_nats_subject` predicate.
2584            if let Err(reason) = crate::render::is_nats_subject(s) {
2585                return Err(AplicacaoError::contrato_subject_invalid(
2586                    self.edge_pair(),
2587                    s,
2588                    reason,
2589                ));
2590            }
2591            return Ok(WitTarget::PubSub { subject: s });
2592        }
2593        if self.is_store() {
2594            if endpoint.is_some() || subject.is_some() {
2595                return Err(AplicacaoError::contrato_wrong_target(
2596                    edge(),
2597                    WitTarget::STORE_FIELD_NAME,
2598                ));
2599            }
2600            let sl = slot.ok_or_else(|| {
2601                AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
2602            })?;
2603            if sl.is_empty() {
2604                return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
2605            }
2606            // Value-shape gate on the third (and last) typed payload
2607            // axis the `WitContract::target` dispatch carries — the
2608            // peer of [`crate::render::is_gateway_api_http_path`] for
2609            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
2610            // for `:subject` (63e18a0). Until this gate landed
2611            // `target()` only refused the empty string; a structurally
2612            // invalid slot (`"check out/$order"` — un-percent-encoded
2613            // whitespace whose runtime behavior varies unpredictably
2614            // across kv backends, `"checkout/\x01order"` — control
2615            // character that Redis admits but corrupts on next read
2616            // and DynamoDB rejects outright, `"chéckout/$order"` —
2617            // un-percent-encoded non-ASCII byte each backend re-encodes
2618            // differently, `"checkout\n/$order"` — embedded newline,
2619            // the 513-byte paste-from-binary slug) silently passed
2620            // validate and surfaced at runtime as a per-backend kv
2621            // write rejection (DynamoDB / etcd) or as a silent
2622            // next-read corruption (Redis-via-RESP3), far from the
2623            // source caixa.lisp with no field naming which `:contratos`
2624            // edge carried the typo. The lifted predicate makes the
2625            // kv-backend intersection-floor a substrate-level
2626            // invariant at validate time, not a runtime "this passed
2627            // validate but the kv backend rejected on first write"
2628            // surprise — closes the typed payload-axis value-shape
2629            // trajectory across all three legs of the four
2630            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
2631            // that caixa-mesh + the future kv emitters land in.
2632            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
2633                return Err(AplicacaoError::contrato_slot_invalid(
2634                    self.edge_pair(),
2635                    sl,
2636                    reason,
2637                ));
2638            }
2639            return Ok(WitTarget::Store { slot: sl });
2640        }
2641
2642        // Unrecognized WIT world — must not carry any payload target.
2643        if endpoint.is_some() || subject.is_some() || slot.is_some() {
2644            return Err(AplicacaoError::contrato_wrong_target(
2645                edge(),
2646                WitTarget::CAPABILITY_EXPECTED,
2647            ));
2648        }
2649        Ok(WitTarget::Capability)
2650    }
2651
2652    /// Substrate-canonical post-validation projection of the typed
2653    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
2654    /// downstream of an [`AplicacaoSpec`] that has already crossed the
2655    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
2656    /// [`typed_view`]-shaped entry point that composes `validate` into
2657    /// the projection) reaches through when it needs the typed
2658    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
2659    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
2660    /// coherence for every `:contratos` entry. The peer accessor to the
2661    /// [`Self::target`] `Result`-returning validator on the same
2662    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
2663    /// pre-validation validator that computes the projection *and* raises
2664    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
2665    /// (`:wit`, payload) mismatch; this method is the post-validation
2666    /// projection every downstream consumer reaches through once the
2667    /// pre-validation gate has succeeded.
2668    ///
2669    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
2670    ///
2671    /// Prior to this lift the "call `.target()` then `.expect(…)` with
2672    /// the same message" pattern sat inline at two production sites with
2673    /// no compile-time link between them: the
2674    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
2675    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
2676    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
2677    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
2678    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
2679    /// (`c.target().expect("validated by typed_view").graph_label()`),
2680    /// each open-coding the same `.target().expect("validated by
2681    /// typed_view")` pair with the message spelled twice. A future
2682    /// vocabulary shift on the panic-message axis (a tightening from
2683    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
2684    /// validate"` as the substrate's validator entry-point vocabulary
2685    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
2686    /// panic to a `debug_assert` under a `--release` build profile) would
2687    /// have had to be threaded through both open-coded call sites in
2688    /// lockstep or one consumer would silently disagree with the peer on
2689    /// which invariant the panic message names. Same "same shape written
2690    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
2691    /// discipline the sibling [`Self::edge_pair`] /
2692    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
2693    /// lifts already establish on the paired composite-projection axis;
2694    /// this lift extends it onto the post-validation typed-view axis.
2695    ///
2696    /// Every future downstream consumer of the projected typed view
2697    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
2698    /// CR materializer's per-edge admission webhook, the future
2699    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
2700    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
2701    /// resolver, the future `feira app graph --l7` / `--pubsub` /
2702    /// `--kv` per-shape column emitters) reaches through this one typed
2703    /// dispatch on the substrate primitive rather than an open-coded
2704    /// per-consumer `.target().expect(…)` pair with the message
2705    /// re-inlined. The invariant the accessor's panic path pins — "this
2706    /// call is only reachable after [`AplicacaoSpec::validate`] has
2707    /// succeeded on the containing spec" — is the substrate's answer to
2708    /// give exactly once, at the primitive, not once per consumer.
2709    ///
2710    /// # Panics
2711    ///
2712    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
2713    /// would return an `Err` — i.e. if this contract's
2714    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
2715    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
2716    /// this accessor only from a code path that has already reached the
2717    /// containing [`AplicacaoSpec`] through a validating entry-point
2718    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
2719    /// [`typed_view`] compose, the future M4 CR admission webhook's
2720    /// per-CR validate). Use [`Self::target`] instead on any pre-
2721    /// validation code path.
2722    ///
2723    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
2724    #[must_use]
2725    pub fn target_projected(&self) -> WitTarget<'_> {
2726        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
2727    }
2728
2729    /// Canonical panic message the [`Self::target_projected`]
2730    /// post-validation projection accessor threads through when the
2731    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
2732    /// has succeeded" precondition. Lifted as a `pub const` on the
2733    /// [`WitContract`] surface so the byte-string lives in one place
2734    /// across the substrate — the [`Self::target_projected`] method
2735    /// body, the two prior production call sites' comments now naming
2736    /// the const, and every future consumer that must format-match the
2737    /// panic-message shape (a future test suite that asserts the panic-
2738    /// message byte-string across a fuzzed invalid-contract corpus,
2739    /// a future custom-panic hook in `caixa-operator` that surfaces the
2740    /// message with per-`:contratos` telemetry, the future admission
2741    /// webhook's per-CR validate-error report) reaches through the same
2742    /// canonical `&'static str`. A future rebrand on the panic-message
2743    /// axis (a tightening from `"validated by typed_view"` to `"validated
2744    /// by AplicacaoSpec::validate"` as the substrate's validator
2745    /// entry-point vocabulary sharpens once caixa-core grows a
2746    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
2747    /// [`typed_view`]) lands at one caixa-core edit rather than a
2748    /// coordinated per-consumer sweep — same "one canonical declaration
2749    /// per axis, next to the accessor that reads it" discipline the peer
2750    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
2751    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
2752    /// const family already establishes on the paired per-consumer-axis
2753    /// diagnostic-scalar surface.
2754    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
2755}
2756
2757/// Borrowed identity key for the typed-graph duplicate-`:contratos`
2758/// gate (see [`AplicacaoSpec::validate`]): every field that
2759/// distinguishes one contract from another, in declaration order
2760/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
2761/// with equal [`ContratoIdentity`]s are the same typed edge declared
2762/// twice — the graph-edge analogue of duplicate `:membros` /
2763/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
2764/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
2765/// clippy's `type_complexity` lint (and so a future axis added to
2766/// `WitContract` is one alias edit, not a coordinated rewrite of
2767/// every set instantiation).
2768pub type ContratoIdentity<'a> = (
2769    &'a str,
2770    &'a str,
2771    &'a str,
2772    Option<&'a str>,
2773    Option<&'a str>,
2774    Option<&'a str>,
2775);
2776
2777/// Typed view of a [`WitContract`]'s payload target. Each variant
2778/// carries the field its WIT shape requires; constructing a `Http`
2779/// view without an endpoint is impossible by the type system.
2780///
2781/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
2782/// instead of probing `Option<String>` fields one by one — the
2783/// "which payload field is set?" question is answered once, at
2784/// validation time.
2785#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
2786pub enum WitTarget<'a> {
2787    /// HTTP-shaped WIT world. Carries the configured request path.
2788    Http { endpoint: &'a str },
2789    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
2790    ///
2791    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
2792    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
2793    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
2794    /// method name byte-identical to the sibling
2795    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
2796    /// arm-discriminator that routes through
2797    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
2798    /// through `matches!` on the variant), so the two arm-discriminator
2799    /// axes — target-side variant-arm and shape-side ref-prefix — reach
2800    /// every downstream consumer through the same `is_pubsub()` name.
2801    #[is_variant(name = "pubsub")]
2802    PubSub { subject: &'a str },
2803    /// Key-value-shaped WIT world. Carries the slot template.
2804    Store { slot: &'a str },
2805    /// A typed capability edge with no payload selector — the WIT
2806    /// world stands on its own (rare; reserved for plain capability
2807    /// imports or M4-and-later WIT worlds we haven't shaped yet).
2808    Capability,
2809}
2810
2811impl<'a> WitTarget<'a> {
2812    /// Canonical author-facing `:contratos` payload field name for the
2813    /// HTTP-shaped arm — the `expected: &'static str` scalar the
2814    /// [`AplicacaoError::ContratoMissingTarget`] /
2815    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
2816    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
2817    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
2818    /// the `feira app graph` verb prints. Peer of
2819    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
2820    /// on the payload-field-name axis; declared as a peer const next
2821    /// to the [`WitTarget::Http`] variant so a future rename on the
2822    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
2823    /// :endpoint …)))` field lands in exactly one place, not scattered
2824    /// across the [`WitContract::target`] gate's six `expected:`
2825    /// literals, the label template, and every downstream consumer
2826    /// that prints a per-arm prefix. Same trajectory as the peer
2827    /// [`WitTarget::label`] lift (174e96a): a single source of truth
2828    /// for the arm's shape, next to the variant declaration.
2829    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
2830    /// Canonical author-facing `:contratos` payload field name for the
2831    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
2832    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
2833    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
2834    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
2835    /// Canonical author-facing `:contratos` payload field name for the
2836    /// key/value-store-shaped arm. Peer of
2837    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
2838    /// on the payload-field-name axis; see
2839    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
2840    pub const STORE_FIELD_NAME: &'static str = "slot";
2841
2842    /// Canonical stable human-readable label the payload-less
2843    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
2844    /// the byte-string every consumer that formats a payload-less
2845    /// typed capability edge as text lands on (the
2846    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
2847    /// naming which identical edge was declared twice, the future
2848    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
2849    /// policy resolver's audit view, the operator's mesh-graph audit).
2850    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
2851    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
2852    /// author-facing label-scalar consts — the same
2853    /// "one canonical declaration per arm, next to the variant, so a
2854    /// future rename lands in one place" discipline extended to the
2855    /// payload-less arm. Until this lift landed the byte-string sat
2856    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
2857    /// match arm, once in the pin test asserting the label's
2858    /// [`WitTarget::Capability`] output — with no compile-time link
2859    /// between the two: a rebrand on either side (an operator-facing
2860    /// vocabulary shift, a per-consumer disambiguation like
2861    /// `"(capability — no payload; typed edge only)"`) would silently
2862    /// desynchronize until a downstream consumer surfaced the drift at
2863    /// runtime.
2864    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
2865
2866    /// Canonical `expected:` scalar the
2867    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
2868    /// through for the payload-less [`WitTarget::Capability`] arm — the
2869    /// byte-string authors read as "this WIT world's shape is not one
2870    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
2871    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
2872    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2873    /// [`Self::STORE_FIELD_NAME`] consts on the
2874    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
2875    /// same "which payload field name goes in the diagnostic" dispatch
2876    /// the three payload-arm consts cover, extended to the payload-less
2877    /// arm. Until this lift landed the byte-string sat twice — once
2878    /// inline in the [`Self::target`] Capability-arm rejection at the
2879    /// production dispatch, once in the pin test asserting the
2880    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
2881    /// no compile-time link between the two: a rebrand on either side
2882    /// (an author-facing vocabulary shift to `"capability"` /
2883    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
2884    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
2885    /// [`WitTarget::Capability`] into per-shape peers) would silently
2886    /// desynchronize until a downstream consumer surfaced the drift at
2887    /// runtime. Same "one canonical declaration per arm, next to the
2888    /// variant, so a future rename lands in one place" discipline the
2889    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
2890    /// established for the payload-less arm's human-readable label
2891    /// axis; this lift extends it onto the peer diagnostic-scalar axis
2892    /// so both halves of the "how does the Capability arm surface at
2893    /// its two consumer axes (human-readable label, wrong-target
2894    /// diagnostic)" pipeline route through peer consts declared next
2895    /// to the variant.
2896    ///
2897    /// Pairwise-distinctness against the three payload-arm scalars
2898    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2899    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
2900    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
2901    /// test — the 4-way closure of the 3-way
2902    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
2903    /// the `ContratoWrongTarget::expected` axis, matching the peer
2904    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
2905    /// scalar-value distinctness discipline the sibling M3 typed-enum
2906    /// discriminator axis already carries.
2907    pub const CAPABILITY_EXPECTED: &'static str = "none";
2908
2909    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
2910    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
2911    /// as under [`Self::graph_label`] — the sibling
2912    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
2913    /// payload-column axis (the graph verb spells payload-less as
2914    /// `(capability-only)`, distinct from the duplicate-`:contratos`
2915    /// diagnostic's `(capability — no payload)` on the human-readable
2916    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
2917    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
2918    /// family — extends the "one canonical declaration per arm, next to
2919    /// the variant, so a future rename lands in one place" discipline
2920    /// onto the third payload-less-arm consumer axis (`feira app graph`
2921    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
2922    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
2923    /// axis).
2924    ///
2925    /// Until this lift landed the byte-string sat inline in
2926    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
2927    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
2928    /// `"(capability-only)".to_string()` literal, with no compile-time link
2929    /// back to the [`WitTarget::Capability`] variant declaration nor to
2930    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
2931    /// peer consts already carrying the "one canonical declaration per
2932    /// payload-less-arm consumer axis" discipline. A rebrand on either
2933    /// side (the graph verb's operator-facing vocabulary tightening from
2934    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
2935    /// the WIT registry vocabulary sharpens, an M4 split of
2936    /// [`Self::Capability`] into per-shape peers) would silently
2937    /// desynchronize the graph-verb byte-string from the paired
2938    /// per-arm-adjacent const and land two spellings of the same axis in
2939    /// two spots.
2940    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
2941
2942    /// The `(author-facing field name, payload)` pair this typed target
2943    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
2944    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
2945    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
2946    /// [`Self::Store`], `None` for the payload-less
2947    /// [`Self::Capability`] arm.
2948    ///
2949    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
2950    /// (formats `":{field} {payload:?}"` on `Some`, falls to
2951    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
2952    /// (returns the first component) route through, so a future
2953    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
2954    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
2955    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
2956    /// exactly one new match-arm here (a compile-time exhaustiveness
2957    /// error otherwise), not a coordinated three-way rewrite of the
2958    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
2959    /// + every downstream consumer that reaches for the pair.
2960    ///
2961    /// Until this lift landed the three payload arms sat in
2962    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
2963    /// invocations (one per variant, each hand-quoting the paired
2964    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2965    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
2966    /// "same shape, written N times" duplication THEORY.md §I.3.5
2967    /// ("Generation first, composition second, hand-authoring last;
2968    /// the duplication budget is zero") promotes to a build-time
2969    /// concern, with each per-arm site paired to its own const with no
2970    /// compile-time link between the format template and the arm's
2971    /// payload extraction.
2972    #[must_use]
2973    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
2974        match *self {
2975            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
2976            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
2977            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
2978            WitTarget::Capability => None,
2979        }
2980    }
2981
2982    /// The canonical author-facing `:contratos` payload field name
2983    /// this typed target arm carries (`Http` → `Some("endpoint")`,
2984    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
2985    /// `None` for the payload-less `Capability` arm.
2986    ///
2987    /// Routes through [`Self::payload_pair`] — the single 4-arm
2988    /// dispatch [`Self::label`] also reads — so a future variant
2989    /// addition is one match-arm edit at [`Self::payload_pair`], not a
2990    /// per-consumer rewrite. Same "exhaustive-match at one canonical
2991    /// dispatch, thin projections at each consumer" trajectory the
2992    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
2993    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
2994    #[must_use]
2995    pub const fn field_name(&self) -> Option<&'static str> {
2996        match self.payload_pair() {
2997            Some((f, _)) => Some(f),
2998            None => None,
2999        }
3000    }
3001
3002    /// The underlying scalar the payload-carrying arm carries — the
3003    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
3004    /// subject ([`Self::PubSub`] `:subject`), or slot template
3005    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
3006    /// `&'a str` storage — or `None` on the payload-less
3007    /// [`Self::Capability`] arm.
3008    ///
3009    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
3010    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
3011    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
3012    /// the paired sub-selector axis. Both per-half accessors read from
3013    /// one authoritative match, so a future [`WitTarget`] variant
3014    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
3015    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
3016    /// on [`Self::payload_pair`] and both per-half projections + every
3017    /// downstream consumer picks the new arm up by construction — no
3018    /// coordinated N-way rewrite across the paired accessor dispatches,
3019    /// the [`Self::label`] / [`Self::graph_label`] format templates,
3020    /// and every future WIT-registry-shaped consumer.
3021    ///
3022    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
3023    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
3024    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
3025    /// both per-half projections as thin readers, every downstream
3026    /// consumer through the same match" discipline extended onto the
3027    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
3028    /// gap between the two paired-dispatch surfaces: the peer
3029    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
3030    /// the first-component projection until this lift; the second-
3031    /// component sibling now sits alongside so both halves reach every
3032    /// future consumer through the same substrate-primitive dispatch.
3033    ///
3034    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
3035    #[must_use]
3036    pub const fn payload(&self) -> Option<&'a str> {
3037        match self.payload_pair() {
3038            Some((_, p)) => Some(p),
3039            None => None,
3040        }
3041    }
3042
3043    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
3044    /// consumer that fans on the L7-HTTP-shaped payload keys off —
3045    /// returns the [`Self::Http`]-arm's author-declared request path
3046    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
3047    /// projected target is [`Self::Http { endpoint }`], `None` on the
3048    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
3049    /// [`Self::Capability`], each of which carries no HTTP endpoint by
3050    /// definition).
3051    ///
3052    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
3053    /// `path:` rule payload every substrate-side L7-introspecting
3054    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
3055    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
3056    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
3057    /// on the L7 introspection branch; every peer WIT shape stays
3058    /// L4-only because Cilium can't introspect NATS / key-value / plain
3059    /// capability edges), and every future L7-introspecting consumer
3060    /// of the projected target's HTTP endpoint (the future M4
3061    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
3062    /// materializer's per-edge L7 admission-webhook overlay, the
3063    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
3064    /// path bucket-key resolver, the future per-`:contratos`-edge
3065    /// mTLS-required overlay's HTTP-shape scope filter, the future
3066    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
3067    /// through the same typed dispatch.
3068    ///
3069    /// Prior to this lift the sole production consumer of the projected-
3070    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
3071    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
3072    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
3073    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
3074    /// }`) — reached the payload through a raw per-arm `if let` pattern-
3075    /// match that expressed no compile-time link back to the substrate
3076    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
3077    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
3078    /// scalar accessor on the peer per-`:contratos` raw-field axis but
3079    /// with no post-projection peer on the typed-view surface. A future
3080    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
3081    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
3082    /// gRPC-shaped worlds per this enum's own docstring at
3083    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
3084    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
3085    /// would have had to be threaded through the caixa-mesh L7 emit
3086    /// branch's raw `if let` in lockstep — either coalescing the two
3087    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
3088    /// emit path per-arm — with no substrate-primitive dispatch making
3089    /// the "which arms count as L7-HTTP-shaped for path-emission
3090    /// purposes" question the substrate's answer to give. Lifting the
3091    /// resolution to a typed method on the substrate primitive means
3092    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
3093    /// projected-target HTTP endpoint reaches for exactly one typed
3094    /// dispatch — the resolver's accept-set migrates as a unit on any
3095    /// future arm-family widening, and the caixa-mesh L7 emit branch
3096    /// reads through the same substrate primitive.
3097    ///
3098    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
3099    /// (7020470) `Option<&str>` scalar accessor on the raw
3100    /// `:contratos :endpoint` field-access axis — same "one typed
3101    /// dispatch on the substrate primitive, thin projections at each
3102    /// consumer" discipline extended onto the peer post-projection typed-
3103    /// view surface (the [`WitContract::endpoint`] pre-projection
3104    /// accessor returns `Some` for any author-declared `:endpoint`
3105    /// value regardless of the paired `:wit` world's HTTP-shape
3106    /// classification — the raw slot before validation crosses it —
3107    /// while this post-projection [`Self::http_endpoint`] accessor
3108    /// returns `Some` iff the target has been projected onto the
3109    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
3110    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
3111    /// coherence; the two accessors close the pre-projection /
3112    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
3113    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
3114    /// the three payload-carrying arms) — extends the per-arm
3115    /// projection family onto the [`Self::Http`] specialization axis
3116    /// that the pan-arm accessor's shape blends into a single arm-
3117    /// agnostic view; paired with [`Self::pubsub_subject`] /
3118    /// [`Self::store_slot`] on the sibling per-arm axes so every
3119    /// per-payload-arm shape carries a named post-projection accessor
3120    /// on the same shape as `http_endpoint`, closing the per-arm-shape
3121    /// accept-set the substrate primitive owns.
3122    #[must_use]
3123    pub const fn http_endpoint(&self) -> Option<&'a str> {
3124        match *self {
3125            WitTarget::Http { endpoint } => Some(endpoint),
3126            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
3127        }
3128    }
3129
3130    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
3131    /// consumer that fans on the pub-sub-shaped payload keys off —
3132    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
3133    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
3134    /// the projected target is [`Self::PubSub { subject }`], `None` on
3135    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
3136    /// [`Self::Capability`], each of which carries no NATS-shaped
3137    /// subject by definition).
3138    ///
3139    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
3140    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
3141    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
3142    /// CR materializer's `spec.subjects[]` projection, the future
3143    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
3144    /// bucket-key resolver, the future `feira app graph --pubsub`
3145    /// per-Aplicacao subject column, any future substrate-lifted
3146    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
3147    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
3148    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
3149    /// future pub-sub-shape consumer reaches for the same typed
3150    /// dispatch this accessor exposes so the "which arm carries the
3151    /// subject scalar?" answer lives at one caixa-core edit rather
3152    /// than open-coded across per-consumer `if let WitTarget::PubSub
3153    /// { subject } = c.target()…` pattern-matches.
3154    ///
3155    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
3156    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
3157    /// the pre-projection [`WitContract::subject`] scalar accessor on
3158    /// the raw `:contratos :subject` field-access axis — same "one
3159    /// typed dispatch on the substrate primitive, thin projections at
3160    /// each consumer" discipline extended onto the per-arm pub-sub
3161    /// post-projection axis. The pre-projection accessor returns
3162    /// `Some` for any author-declared `:subject` value regardless of
3163    /// the paired `:wit` world's pub-sub-shape classification (the raw
3164    /// slot before validation crosses it); this post-projection
3165    /// accessor returns `Some` iff the target has been projected onto
3166    /// the [`Self::PubSub`] arm, i.e. only after the
3167    /// [`WitContract::target`] gate has admitted the
3168    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
3169    /// the pre-/post-projection pair on the pub-sub-subject axis to
3170    /// match the pair the [`WitContract::endpoint`] +
3171    /// [`Self::http_endpoint`] surfaces already close on the peer
3172    /// HTTP-endpoint axis.
3173    ///
3174    /// Sibling of the unified pan-arm [`Self::payload`]
3175    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
3176    /// extends the per-arm projection family onto the [`Self::PubSub`]
3177    /// specialization axis that the pan-arm accessor's shape blends
3178    /// into a single arm-agnostic view; the pair
3179    /// (`pubsub_subject`, `store_slot`) closes the trio
3180    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
3181    /// payload arm now carries its own per-arm-shape post-projection
3182    /// accessor.
3183    #[must_use]
3184    pub const fn pubsub_subject(&self) -> Option<&'a str> {
3185        match *self {
3186            WitTarget::PubSub { subject } => Some(subject),
3187            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
3188        }
3189    }
3190
3191    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
3192    /// every consumer that fans on the store-shaped payload keys off —
3193    /// returns the [`Self::Store`]-arm's author-declared slot template
3194    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
3195    /// projected target is [`Self::Store { slot }`], `None` on the
3196    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
3197    /// [`Self::Capability`], each of which carries no
3198    /// key/value-store slot by definition).
3199    ///
3200    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
3201    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
3202    /// every future substrate-side store-introspecting per-`(:de,
3203    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
3204    /// namespace / prefix reconciler's per-slot projection, the future
3205    /// per-store-backend routing overlay's slot-shape gate, the future
3206    /// `feira app graph --store` per-Aplicacao slot column, any future
3207    /// substrate-lifted store-shape emitter that reads a projected
3208    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
3209    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
3210    /// Every future store-shape consumer reaches for the same typed
3211    /// dispatch this accessor exposes so the "which arm carries the
3212    /// slot scalar?" answer lives at one caixa-core edit rather than
3213    /// open-coded across per-consumer
3214    /// `if let WitTarget::Store { slot } = c.target()…`
3215    /// pattern-matches.
3216    ///
3217    /// Peer of the sibling [`Self::http_endpoint`] +
3218    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
3219    /// axes and of the pre-projection [`WitContract::slot`] scalar
3220    /// accessor on the raw `:contratos :slot` field-access axis — same
3221    /// "one typed dispatch on the substrate primitive, thin projections
3222    /// at each consumer" discipline extended onto the per-arm store
3223    /// post-projection axis. Closes the pre-/post-projection pair on
3224    /// the store-slot axis to match the pairs the
3225    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
3226    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
3227    /// already close on the peer HTTP-endpoint and pub-sub-subject
3228    /// axes; the substrate-side pre-/post-projection accessor family
3229    /// now spans all three payload arms as a matched trio, so any
3230    /// future arm-shape widening (a `Rest`/`Grpc` split of
3231    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
3232    /// lands one accessor without threading through the sibling
3233    /// pre-projection or the peer per-arm post-projection surfaces a
3234    /// compile-time exhaustiveness error at the substrate primitive,
3235    /// not a silent per-consumer split at renderer emit time.
3236    ///
3237    /// Sibling of the unified pan-arm [`Self::payload`]
3238    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
3239    /// closes the per-arm projection family onto the [`Self::Store`]
3240    /// specialization axis that the pan-arm accessor's shape blends
3241    /// into a single arm-agnostic view. The trio
3242    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
3243    /// pan-arm accept-set on every payload-carrying arm: exactly one
3244    /// per-arm accessor returns `Some(payload)` and the two peers
3245    /// return `None`, and every payload-less [`Self::Capability`]
3246    /// input returns `None` on all three — the partition the sibling
3247    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
3248    /// pin locks in load-bearing.
3249    #[must_use]
3250    pub const fn store_slot(&self) -> Option<&'a str> {
3251        match *self {
3252            WitTarget::Store { slot } => Some(slot),
3253            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
3254        }
3255    }
3256
3257    /// Render this typed target as a stable human-readable label
3258    /// (`:endpoint "/charge"`, `:subject "events.x"`,
3259    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
3260    /// the WIT world is a pure capability edge).
3261    ///
3262    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
3263    /// gate so the diagnostic names *which* identical edge was
3264    /// declared twice (not just which `(de, para, wit)` triple).
3265    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
3266    /// on the payload-carrying arms (`Some((field, payload)) →
3267    /// format!(":{field} {payload:?}")`) and through the lifted
3268    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
3269    /// [`Self::Capability`] arm — so a future variant addition (the
3270    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
3271    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
3272    /// `Queue`-shaped peer) becomes a single new match-arm on
3273    /// [`Self::payload_pair`] rather than a rewrite of this template
3274    /// (and every downstream consumer that reaches for the label
3275    /// shape: the per-edge policy resolver in M4, the `feira app
3276    /// graph` view, the operator's mesh-graph audit). Until this
3277    /// lift landed the three payload arms carried three near-identical
3278    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
3279    /// [`Self::Capability`] arm carried the payload-less byte-string
3280    /// twice (once inline here, once in the pin test) — closing the
3281    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
3282    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
3283    /// / 4a1e490) peer-const lifts already established for the
3284    /// payload-carrying arms.
3285    #[must_use]
3286    pub fn label(&self) -> String {
3287        match self.payload_pair() {
3288            Some((field, payload)) => format!(":{field} {payload:?}"),
3289            None => Self::CAPABILITY_LABEL.to_string(),
3290        }
3291    }
3292
3293    /// Render this typed target as the `feira app graph` per-`:contratos`
3294    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
3295    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
3296    /// payload-less arm).
3297    ///
3298    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
3299    /// on the payload-carrying arms (`Some((field, payload)) →
3300    /// format!("{field}={payload}")`) and through the lifted
3301    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
3302    /// [`Self::Capability`] arm — so a future variant addition
3303    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
3304    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
3305    /// `Queue`-shaped peer) becomes one match-arm edit at
3306    /// [`Self::payload_pair`], propagating through this graph-verb
3307    /// projection at zero call-site cost, sibling to the peer
3308    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
3309    /// same 4-arm dispatch.
3310    ///
3311    /// Until this lift landed the [`caixa-feira`]
3312    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
3313    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
3314    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
3315    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
3316    /// `format!("{}={endpoint}", ...)` template and hard-coding
3317    /// `"(capability-only)"` as a fifth payload-less scalar with no link
3318    /// back to the paired [`WitTarget::Capability`] variant declaration.
3319    /// A future variant addition would have had to be threaded through
3320    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
3321    /// verb's inline match in lockstep or the two projections would
3322    /// silently disagree on the arm-set the graph verb prints — the
3323    /// duplicate-`:contratos` diagnostic reading one shape while the
3324    /// graph verb's payload column silently dropped the new arm to
3325    /// `(capability-only)`. Lifting the graph-verb projection onto the
3326    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
3327    /// the axis: both projections migrate as a unit.
3328    ///
3329    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
3330    /// quoting) shape is graph-verb-canonical — distinct from the
3331    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
3332    /// duplicate-`:contratos` diagnostic seeds (see
3333    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
3334    /// on the payload-less axis for the paired distinction).
3335    #[must_use]
3336    pub fn graph_label(&self) -> String {
3337        match self.payload_pair() {
3338            Some((field, payload)) => format!("{field}={payload}"),
3339            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
3340        }
3341    }
3342}
3343
3344/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
3345/// pretty-printed byte-string every consumer that formats a typed
3346/// payload target as user-facing text lands on (the
3347/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
3348/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
3349/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
3350/// graph` per-`:contratos`-edge payload column that reaches the graph
3351/// verb through `format!("{target}")`, the future M4 per-edge policy
3352/// resolver's per-edge audit-log line, the operator's mesh-graph
3353/// per-edge inspection view) reaches for the same lifted
3354/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
3355/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
3356/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
3357/// routes through — extending the three-path-convergence
3358/// (`Debug` for structural inspection, `Display` for user-facing text,
3359/// per-arm typed accessor for the canonical byte-string) discipline the
3360/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
3361/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
3362/// onto the fourth (and only remaining) typed-shape-discriminator axis
3363/// on the caixa surface.
3364///
3365/// Pre-lift the two paths were structurally independent — every consumer
3366/// reaching for a payload byte-string past the [`WitTarget::label`]
3367/// helper had to pick between three paths ([`WitTarget::label`],
3368/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
3369/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
3370/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
3371/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
3372/// that reached for `format!("{target}")` — the canonical shape every
3373/// user-facing pretty-print site on the sibling typed-enum axes already
3374/// uses — would silently land on the `Debug` derive's structural output
3375/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
3376/// than the `label()` helper's stable byte-string (`:endpoint
3377/// "/charge"` — the author-facing `:contratos` keyword form) the
3378/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
3379/// already threads through. The two spellings would diverge silently in
3380/// every downstream diagnostic / graph / audit line reached through
3381/// `format!` rather than through the `label()` helper. Routing
3382/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
3383/// path: every `format!("{v}")` call reaches the same
3384/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
3385/// and the duplicate-`:contratos` gate already route through, so a
3386/// future variant addition (the M4-and-later per-edge WIT registry may
3387/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
3388/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
3389/// consumer at exactly one place — the [`WitTarget::payload_pair`]
3390/// match — rather than fanning out through hand-rolled per-arm
3391/// [`std::fmt::Display`] arms.
3392///
3393/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
3394/// is the typed view returned by [`WitContract::target`], not a
3395/// closed-set discriminator enum with a gen-platform Discriminant
3396/// registration, so the `Debug` derive's structural output (which every
3397/// `{v:?}` consumer still reaches) stays distinct from the `Display`
3398/// helper's stable pretty-printed byte-string. `Debug` reveals variant
3399/// shape for structural inspection; `Display` (via `label`) reveals the
3400/// stable author-facing payload projection.
3401///
3402/// Pin tests
3403/// [`tests::wit_target_display_routes_through_label_helper`] and
3404/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
3405/// assert the two paths agree byte-for-byte on every variant, so a
3406/// future variant addition or `label()` reimplementation that hand-rolls
3407/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
3408/// build error visible at caixa-core test time, not a silent
3409/// per-consumer dispatch miss at diagnostic / audit / graph time.
3410impl std::fmt::Display for WitTarget<'_> {
3411    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3412        f.write_str(&self.label())
3413    }
3414}
3415
3416// ── one Aplicacao member ─────────────────────────────────────────────
3417
3418/// A Servico participating in the Aplicacao. Same shape as
3419/// `crate::supervisor::ChildSpec` but without a restart policy —
3420/// supervision is per-Servico (each member has its own
3421/// `:supervisor`), the Aplicacao orchestrates *placement*.
3422#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3423#[serde(rename_all = "camelCase")]
3424pub struct Membro {
3425    /// Member caixa's `:nome`. Resolves through the same dep
3426    /// resolution path as `crate::dep::Dep`.
3427    pub caixa: String,
3428
3429    /// Semver constraint.
3430    pub versao: String,
3431}
3432
3433impl Membro {
3434    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
3435    /// accessor every consumer that reads the member's Servico identity
3436    /// keys off — returns the author-declared `:membros :caixa`
3437    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
3438    /// own [`String`] storage.
3439    ///
3440    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
3441    /// participating in the Aplicacao — validated by
3442    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
3443    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
3444    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
3445    /// [`validate_no_self_membership`]) — and every downstream consumer
3446    /// that fans on the member's identity keys off this scalar (the
3447    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
3448    /// lookup, the per-`:membros` duplicate gate's dedup key, the
3449    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
3450    /// identity, the self-membership gate, the
3451    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
3452    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
3453    /// CR materializer's per-member resolver).
3454    ///
3455    /// Prior to this lift the `.caixa` byte-string was read inline at
3456    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
3457    /// set collector at
3458    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
3459    /// [`validate_membros`] validation-side member-caixa gate at
3460    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
3461    /// per-member duplicate-gate dedup key at
3462    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
3463    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
3464    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
3465    /// [`validate_no_self_membership`] self-loop gate at
3466    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
3467    /// expressed no compile-time link back to the typed slot. Every
3468    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
3469    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
3470    /// `name:` axis, so a future extension of the `:membros :caixa`
3471    /// axis to a richer author surface — a per-cluster alias table the
3472    /// operator pins through a future `:placement`-scoped slot, a
3473    /// namespace-qualified rewrite the M4 CR materializer applies
3474    /// per-CR, a per-member overlay from the future `:membros
3475    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
3476    /// acknowledges — would have had to be threaded through every
3477    /// open-coded copy in lockstep or one consumer would silently
3478    /// disagree with the peers on which caixa a given member resolves
3479    /// to. A member-set lookup that treated the name as `"cart"` while
3480    /// the peer adjacency map treated it as `"tenant-a/cart"` would
3481    /// silently split the `:contratos` membership-lookup diagnostic from
3482    /// the cycle-detector's node identity — a two-consumer split at the
3483    /// validator far from the source `caixa.lisp` with no field naming
3484    /// the identity-drift root cause. Lifting the resolution rule to a
3485    /// typed method on the substrate primitive means every downstream
3486    /// consumer of the Aplicacao's per-`:membros` identity surface
3487    /// reaches for exactly one typed dispatch — the resolver's
3488    /// accept-set migrates as a unit on any future axis addition.
3489    ///
3490    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
3491    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
3492    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
3493    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
3494    /// destination-Servico scalar accessors — same "one typed dispatch
3495    /// on the substrate primitive, thin projections at each consumer"
3496    /// discipline extended onto the per-`:membros` member-caixa `:nome`
3497    /// byte-string axis. Named `nome()` to match the tatara-lisp
3498    /// author-surface term the field's docstring already reaches for
3499    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
3500    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
3501    /// already carries — the accessor's name maps directly onto the
3502    /// canonical caixa-identity vocabulary rather than shadowing the
3503    /// field's storage-side `caixa` label.
3504    #[must_use]
3505    pub const fn nome(&self) -> &str {
3506        self.caixa.as_str()
3507    }
3508
3509    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
3510    /// requirement scalar accessor every consumer that reads the
3511    /// member's version pin keys off — returns the author-declared
3512    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
3513    /// from the typed slot's own [`String`] storage.
3514    ///
3515    /// The `:membros :versao` slot carries the Cargo-shaped semver
3516    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
3517    /// pins which release of the member-caixa the Aplicacao composes
3518    /// against — the same requirement grammar the peer `:deps :versao`
3519    /// / `:children :versao` axes carry, resolved through the shared
3520    /// [`crate::render::require_valid_versao_requirement`] cascade and
3521    /// the shared [`crate::version::parse_requirement`] parser. Every
3522    /// downstream consumer that fans on the member's version pin keys
3523    /// off this scalar (the [`validate_membros`] per-member requirement
3524    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
3525    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
3526    /// m.nome(), m.versao_requirement())` line, every future per-cluster
3527    /// version-lock overlay the operator pins through a future
3528    /// `:placement`-scoped slot, the future
3529    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
3530    /// version resolver, the future `feira app deploy` pipeline's
3531    /// per-member lacre BLAKE3-closure lookup).
3532    ///
3533    /// Prior to this lift the `.versao` byte-string was accessed inline
3534    /// at two `&str`-shaped sites — the [`validate_membros`]
3535    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
3536    /// …)` and the `feira app graph` per-member printer's `println!(
3537    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
3538    /// prior to this lift) — two open-coded field-accesses that expressed
3539    /// no compile-time link back to the typed slot. A future extension of
3540    /// the `:membros :versao` axis to a richer author surface (a
3541    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
3542    /// flow, a lacre-projected concrete-version rewrite the operator
3543    /// materializes at CR-admission time, a future `:membros :versao-lock`
3544    /// per-cluster override slot) would have had to be threaded through
3545    /// every open-coded copy in lockstep or one consumer would silently
3546    /// disagree with the peers on which release constraint a given
3547    /// member resolves to. Lifting the resolution rule to a typed method
3548    /// on the substrate primitive means every downstream requirement-
3549    /// facing consumer reaches for exactly one typed dispatch — the
3550    /// resolver's accept-set migrates as a unit on any future axis
3551    /// addition.
3552    ///
3553    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
3554    /// member-caixa `:nome` scalar accessor — the pair
3555    /// `(nome(), versao_requirement())` jointly projects the
3556    /// `(caixa, versao)` field pair every renderer that fans on
3557    /// per-member identity + version pin keys off, closing the last
3558    /// unlifted per-`:membros` scalar axis so every downstream
3559    /// per-`:membros` reader now routes through a typed dispatch on the
3560    /// substrate primitive. Named `versao_requirement()` rather than
3561    /// `versao()` because the field's storage-side `.versao` label is
3562    /// already the author-surface term (`:versao`); the accessor's name
3563    /// carries the semantic role — the semver *requirement* string the
3564    /// shared [`crate::version::parse_requirement`] entry-point consumes
3565    /// — so a raw field access and a typed dispatch read differently at
3566    /// every consumer site.
3567    ///
3568    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
3569    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
3570    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
3571    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
3572    /// destination-Servico scalar accessors — same "one typed dispatch
3573    /// on the substrate primitive, thin projections at each consumer"
3574    /// discipline extended onto the per-`:membros` member-`:versao`
3575    /// semver-requirement byte-string axis.
3576    #[must_use]
3577    pub const fn versao_requirement(&self) -> &str {
3578        self.versao.as_str()
3579    }
3580}
3581
3582// ── mesh-level policies ──────────────────────────────────────────────
3583
3584/// Mesh policies that apply to every `:contratos` edge unless
3585/// overridden per-edge in M4. V0 is a single global policy block.
3586#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3587#[serde(rename_all = "camelCase")]
3588pub struct MeshPolicy {
3589    /// Per-call timeout. Authored as a duration string (`"30s"`).
3590    #[serde(
3591        default,
3592        skip_serializing_if = "Option::is_none",
3593        with = "supervisor::duration_codec"
3594    )]
3595    pub timeout: Option<Duration>,
3596
3597    /// Number of retries on transient failure. None = no retries.
3598    #[serde(default, skip_serializing_if = "Option::is_none")]
3599    pub retries: Option<u32>,
3600
3601    /// Circuit breaker config. Trips after N failures within W
3602    /// duration; closes after a cooldown.
3603    #[serde(default, skip_serializing_if = "Option::is_none")]
3604    pub circuit_breaker: Option<CircuitBreaker>,
3605
3606    /// Whether mTLS is required for every contrato. Default: true
3607    /// (sandboxing-by-default; explicit opt-out only).
3608    #[serde(default, skip_serializing_if = "Option::is_none")]
3609    pub mtls_required: Option<bool>,
3610
3611    /// Token-bucket rate limit. Authored as `"100/s"` or
3612    /// `"5000/m"`; stored as `(rate, window)`.
3613    #[serde(
3614        default,
3615        skip_serializing_if = "Option::is_none",
3616        with = "rate_limit_codec"
3617    )]
3618    pub rate_limit: Option<RateLimit>,
3619}
3620
3621/// Route the derived-style [`Default`] impl on [`MeshPolicy`] through
3622/// the substrate-canonical [`MeshPolicy::empty`] `pub const fn`
3623/// constructor rather than the derive-generated per-field
3624/// `<Option<_> as Default>::default` cascade — one source of truth for
3625/// the "canonical unset per-`:politicas` slot" shape across the two
3626/// paths every downstream consumer already reaches through (the
3627/// derived-until-now [`Default::default`] the `..Default::default()`
3628/// struct-update-syntax on every one-axis-under-test fixture in this
3629/// crate's test module rests on, and the `pub const fn`
3630/// [`MeshPolicy::empty`] constructor every `const`-context consumer
3631/// reaches through).
3632///
3633/// Prior to this fold the two paths were byte-equal by *coincidence*
3634/// under the pinning test
3635/// [`tests::mesh_policy_empty_byte_equals_default`] rather than
3636/// byte-equal by *construction* — the derive-generated
3637/// [`Default::default`] resolved each `Option<_>` field through its
3638/// own `<Option<_> as Default>::default` (which returns `None`) and
3639/// the lifted `pub const fn` [`MeshPolicy::empty`] named the same five
3640/// `None` arms verbatim in its struct-literal. Two hand-authored (or
3641/// derive-authored) sources of the same "canonical unset baseline"
3642/// shape on the same primitive is exactly the substrate-canonical-
3643/// source-of-truth duplication the [`crate::LimitsSpec::empty`]
3644/// (9739971) / [`MeshPolicy::empty`] (6df969b) /
3645/// [`crate::BehaviorSpec::empty`] (f9b18e3) lifts closed on the
3646/// forward `const`-context path — extending the same discipline onto
3647/// the paired [`Default`] impl means every consumer of the derived-
3648/// until-now [`Default::default`] surface (every `..Default::default()`
3649/// struct-update-syntax fixture in this crate's test module — the
3650/// five per-axis-only pins at [`tests::mesh_policy_with_only_timeout_is_not_empty`],
3651/// [`tests::mesh_policy_with_only_retries_is_not_empty`],
3652/// [`tests::mesh_policy_with_only_circuit_breaker_is_not_empty`],
3653/// [`tests::mesh_policy_with_only_mtls_required_is_not_empty`],
3654/// [`tests::mesh_policy_with_only_rate_limit_is_not_empty`] — and the
3655/// entry pin at [`tests::mesh_policy_default_is_empty`], the future
3656/// M4 per-edge `:politicas` overlay CR materializer's admission-time
3657/// default-overlay-emit gate, every future `..Default::default()`
3658/// struct-update-syntax fixture-builder arm) also routes through the
3659/// substrate primitive's single source of truth.
3660///
3661/// A future extension of the `:politicas` axis set (a per-edge
3662/// `:politicas` overlay the M4 roadmap grows once per-`:contratos`-
3663/// edge overrides land, a sixth `:politicas` sub-slot the roadmap
3664/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3665/// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
3666/// reaches this impl's return value through exactly one edit on
3667/// [`MeshPolicy::empty`] — the derived path could silently disagree
3668/// with the constructor's shape on any new field whose
3669/// `Default::default` is not `None` (a future non-`Option<_>` field
3670/// with a non-`Default::default`-equivalent baseline, a `Vec<_>` field
3671/// defaulting to an empty vector, an enum arm-carrying field with a
3672/// non-`Default::default` canonical unset arm), while this delegated
3673/// impl reaches the constructor directly and picks up every future
3674/// extension by construction.
3675///
3676/// Direct peer of [`crate::LimitsSpec`]'s
3677/// [`Default`]-through-[`crate::LimitsSpec::empty`] fold (abd52c2) on
3678/// the M2 `:limits` typed slot — same "one source of truth for the
3679/// canonical unset baseline" discipline extended onto the M3
3680/// `:politicas` typed slot. The sibling [`crate::BehaviorSpec`] impl
3681/// on the M2 `:behavior` slot is the third and last established
3682/// candidate for the same delegation fold once the per-slot peer pin
3683/// on this axis lands in a future run. Pinned load-bearing by
3684/// [`tests::mesh_policy_default_routes_through_empty_ctor`]
3685/// (byte-parity pin against [`MeshPolicy::empty`] under `PartialEq`,
3686/// sharpening the pre-existing
3687/// [`tests::mesh_policy_empty_byte_equals_default`] pin from a "two
3688/// paths byte-equal by coincidence" invariant into a "two paths
3689/// byte-equal by construction — one delegates to the other" invariant)
3690/// and by [`tests::mesh_policy_empty_validates_ok`] (the canonical
3691/// unset baseline must pass [`MeshPolicy::validate`] — every per-axis
3692/// value-shape gate is `if let Some(_)` guarded and every cross-axis
3693/// arm on [`MeshPolicy::first_cross_axis_violation`] is a
3694/// `let (Some(_), Some(_))` pattern, so an all-`None` input
3695/// structurally short-circuits every arm; the pin makes the invariant
3696/// load-bearing so a future extension that adds a non-`Option`-guarded
3697/// gate to [`MeshPolicy::validate`] trips at caixa-core test time
3698/// rather than at a downstream consumer that composed
3699/// [`MeshPolicy::default`]/[`MeshPolicy::empty`] with
3700/// [`MeshPolicy::validate`] as its "no-op axis short-circuit").
3701impl Default for MeshPolicy {
3702    #[inline]
3703    fn default() -> Self {
3704        Self::empty()
3705    }
3706}
3707
3708impl MeshPolicy {
3709    /// Substrate-canonical `const`-context peer of the derived
3710    /// [`Default::default`] on [`MeshPolicy`] — returns the fully-empty
3711    /// per-`:politicas` slot (every one of the five `Option<_>`-carrying
3712    /// per-axis fields set to `None`), materializable at `const`-eval
3713    /// time.
3714    ///
3715    /// Named `empty()` (not `default()` / `new()`) to match the sibling
3716    /// `is_empty()` predicate on the same primitive: the pair
3717    /// (`empty()` / `is_empty()`) forms the round-trip discipline
3718    /// `MeshPolicy::empty().is_empty() == true` the pin
3719    /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
3720    /// locks load-bearing, and every `const`-context consumer that
3721    /// wants a canonical unset baseline reads through this constructor
3722    /// rather than the derived (non-`const`) [`Default::default`] or
3723    /// the five-field struct-literal `MeshPolicy { timeout: None,
3724    /// retries: None, circuit_breaker: None, mtls_required: None,
3725    /// rate_limit: None }` open-coded per-site.
3726    ///
3727    /// Direct peer of [`crate::LimitsSpec::empty`] (9739971) on the
3728    /// M2 `:limits` typed slot — same "`const`-context peer of the
3729    /// derived non-`const` [`Default::default`]" discipline extended
3730    /// onto the M3 `:politicas` typed slot. The two lifted `pub const
3731    /// fn` constructors together now cover the two per-slot
3732    /// [`Default`]-carrying M2/M3 typed slots that also carry an
3733    /// `is_empty()` emptiness predicate: every `const`-context consumer
3734    /// of a canonical unset per-slot baseline reads through the same
3735    /// paired-`(empty(), is_empty())` shape on either slot without a
3736    /// runtime dispatch on the derived [`Default::default`].
3737    ///
3738    /// Prior to this lift the "canonical unset [`MeshPolicy`]" shape
3739    /// was reached through one of two paths — the derived
3740    /// [`Default::default`] (`fn`, not `const fn` — a downstream
3741    /// `const _: MeshPolicy = MeshPolicy::default();` cannot compile
3742    /// because [`Default::default`] is not `const`-stable on stable
3743    /// Rust; the tracking issue on `const Default` still blocks the
3744    /// promotion) or an open-coded struct-literal with five `None`
3745    /// arms threaded verbatim at every call site (the five
3746    /// `MeshPolicy { timeout: Some(_), ..Default::default() }` /
3747    /// `MeshPolicy { retries: Some(_), ..Default::default() }` /
3748    /// sibling per-axis-only fixtures in this crate's own test module
3749    /// each rest on `..Default::default()` for the four peer arms; a
3750    /// future axis addition silently drifts the fixture's intent from
3751    /// "one axis under test, the other four unset" to "one axis under
3752    /// test, N axes unset, one field forgotten"). A future extension
3753    /// of the axis (a per-edge `:politicas` overlay the M4 roadmap
3754    /// grows once per-`:contratos`-edge overrides land, a sixth
3755    /// `:politicas` sub-slot the roadmap
3756    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3757    /// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
3758    /// reaches this constructor at one edit (one added struct field
3759    /// on the type + one added `<axis>: None` line here) rather than
3760    /// a coordinated rewrite of every open-coded struct-literal at
3761    /// every downstream consumer.
3762    ///
3763    /// `pub const fn` — matches the sibling
3764    /// [`MeshPolicy::is_empty`] `pub const fn` shape verbatim, so
3765    /// every downstream consumer that folds a canonical unset
3766    /// baseline into a `const` position (a `const EMPTY: MeshPolicy =
3767    /// MeshPolicy::empty();` module-scope binding a future per-edge
3768    /// `:politicas` overlay reads through as its "no override
3769    /// declared" arm, a compile-time per-fixture-builder default the
3770    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3771    /// admission-time default-overlay-emit gate consults, a
3772    /// compile-time lookup table the LSP hover renderer materializes
3773    /// per typed-slot fixture) reads through one `const` dispatch
3774    /// rather than being forced onto the runtime code path. Pinned
3775    /// load-bearing at the substrate-primitive level by
3776    /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
3777    /// (round-trip pin against [`Self::is_empty`]),
3778    /// [`tests::mesh_policy_empty_byte_equals_default`] (byte-parity
3779    /// pin against the derived [`Default::default`]), and
3780    /// [`tests::mesh_policy_empty_ctor_is_const_fn`] (const-eval-surface
3781    /// pin via `const` binding — any future accidental downgrade to
3782    /// `pub fn` fires E0015 at the binding at caixa-core build time,
3783    /// strictly stronger than a runtime `assert!`).
3784    #[must_use]
3785    pub const fn empty() -> Self {
3786        Self {
3787            timeout: None,
3788            retries: None,
3789            circuit_breaker: None,
3790            mtls_required: None,
3791            rate_limit: None,
3792        }
3793    }
3794
3795    /// True when no `:politicas` axis carries a value — every field is
3796    /// `None`. The same emptiness contract every other M2/M3 typed
3797    /// surface carries ([`crate::LimitsSpec::is_empty`],
3798    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
3799    /// typed slot onto a cluster artifact key off this predicate to
3800    /// decide "emit the slot" vs "skip the slot entirely", so an
3801    /// authored-but-unset `:politicas (())` round-trips to a rendered
3802    /// artifact that's structurally identical to one that omits the
3803    /// slot. Lifted as a typed predicate (rather than per-renderer
3804    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
3805    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
3806    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
3807    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
3808    /// not a coordinated rewrite of every consumer that's reaching
3809    /// for the emptiness semantic.
3810    #[must_use]
3811    pub const fn is_empty(&self) -> bool {
3812        self.timeout().is_none()
3813            && self.retries().is_none()
3814            && self.circuit_breaker().is_none()
3815            && self.mtls_required().is_none()
3816            && self.rate_limit().is_none()
3817    }
3818
3819    /// Substrate-canonical cross-axis coherence predicate on the
3820    /// `:politicas` slot: does the `:circuit-breaker :window` rolling
3821    /// failure-observation interval span at least one full
3822    /// `:timeout`-bounded call?
3823    ///
3824    /// The first *cross-axis* invariant on the `:politicas` surface —
3825    /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
3826    /// zero-floor + canonical-form + cap brackets) validates one axis
3827    /// in isolation, so a `MeshPolicy` whose axes are each individually
3828    /// well-formed could still name a structurally inert pair. The
3829    /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
3830    /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
3831    /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
3832    /// both above the zero floor) and is nonetheless a breaker that
3833    /// cannot trip on the failure mode it exists to catch: a call
3834    /// dispatched at t=0 is declared failed at t=30s, by which point
3835    /// the 10s window open at dispatch has rolled twice over, so no
3836    /// window can ever hold even one timeout-derived failure however
3837    /// high the call volume. Envoy's `outlier_detection.interval`
3838    /// carries the identical relation against the per-route request
3839    /// timeout; Hystrix ships the canonical ratio in its defaults
3840    /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
3841    /// `execution.isolation.thread.timeoutInMilliseconds`).
3842    ///
3843    /// Vacuously `true` when either axis is absent — a `:politicas`
3844    /// that names only one of the pair declares no relation for the
3845    /// substrate to hold it to (`:timeout` alone is a per-call deadline
3846    /// with no breaker; `:circuit-breaker` alone is a breaker whose
3847    /// failures arrive from the transport's own error signal rather
3848    /// than from a substrate-imposed deadline, so no dispatch-to-report
3849    /// lag is knowable at author time). This is the same
3850    /// "unset means the cluster default applies, not zero" partition
3851    /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
3852    /// arm already carry.
3853    ///
3854    /// Lifted as a typed predicate on the substrate primitive rather
3855    /// than open-coded at the validate gate so every downstream
3856    /// consumer of the pair reaches the invariant through one dispatch:
3857    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
3858    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3859    /// (MESH-COMPOSITION §III.2 #3) that must emit
3860    /// `outlier_detection.interval` and the per-route `timeout` as one
3861    /// coherent Envoy block, the future M4
3862    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3863    /// webhook, and the future per-`:contratos`-edge `:politicas`
3864    /// override that same roadmap acknowledges — which resolves an
3865    /// *effective* pair per edge (edge-level `:timeout` against the
3866    /// Aplicacao-level `:window`, or vice versa) and so must re-check
3867    /// the relation on a pair neither axis's declaration site can see
3868    /// whole. Naming the invariant once means that resolver folds this
3869    /// predicate over its resolved pair instead of re-deriving the
3870    /// comparison, exactly as the sibling cross-slot
3871    /// [`PlacementStrategy::is_shard_keyed`] predicate names the
3872    /// `:placement`/`:shard-key` relation for its own consumers.
3873    #[must_use]
3874    pub const fn breaker_window_observes_timeout(&self) -> bool {
3875        match (self.timeout(), self.circuit_breaker()) {
3876            (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
3877            _ => true,
3878        }
3879    }
3880
3881    /// Substrate-canonical cross-axis coherence predicate on the
3882    /// `:politicas` slot: can the token-bucket rate declared by
3883    /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
3884    /// :window` to reach `:max-failures`?
3885    ///
3886    /// The second cross-axis invariant on the `:politicas` surface —
3887    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
3888    /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
3889    /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
3890    /// pair is validated in isolation by the per-axis brackets in
3891    /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
3892    /// max-failures zero-floor + cap, both windows zero-floor +
3893    /// integer-millisecond + cap, rate-limit window canonical-form),
3894    /// so a `MeshPolicy` whose axes are each individually well-formed
3895    /// can still name a structurally inert pair. The pair
3896    /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
3897    /// "10s") }` passes every per-axis bracket and is nonetheless a
3898    /// breaker that cannot trip on the failure mode it exists to
3899    /// catch: the token bucket admits `rate × (cb.window / rl.window)`
3900    /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
3901    /// no window can accumulate five failures however catastrophically
3902    /// the upstream is failing. Envoy's
3903    /// `outlier_detection.consecutive_5xx` paired against
3904    /// `local_rate_limit.token_bucket.max_tokens` /
3905    /// `fill_interval` carries the identical relation; every
3906    /// production playbook that pairs the two axes (Envoy, Istio, AWS
3907    /// App Mesh, Kong) recommends sizing the rate at or above the
3908    /// breaker's minimum-request-volume threshold for exactly this
3909    /// reason.
3910    ///
3911    /// The typed test is the integer inequality
3912    /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
3913    /// (rearranged from `rate × cb.window / rl.window >= max_failures`
3914    /// so no floating-point division mediates the comparison and so
3915    /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
3916    /// exactly). Both multiplicands are `saturating_mul`'d into
3917    /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
3918    /// have not yet passed [`AplicacaoSpec::validate_politicas`]
3919    /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
3920    /// panic the predicate; a saturated pair collapses to the
3921    /// "vacuously coherent" branch the peer per-axis brackets reject
3922    /// via their own zero-floor / cap arms first.
3923    ///
3924    /// Vacuously `true` when either axis is absent — a `:politicas`
3925    /// that names only one of the pair declares no relation for the
3926    /// substrate to hold it to (`:rate-limit` alone is a per-edge
3927    /// token-bucket declaration with no failure counter to starve;
3928    /// `:circuit-breaker` alone is a rolling-window failure counter
3929    /// whose call rate is unconstrained by the substrate, so no
3930    /// bucket-derived upper bound on calls-per-window is knowable at
3931    /// author time). Same "unset means the cluster default applies,
3932    /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
3933    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
3934    /// carry.
3935    ///
3936    /// Lifted as a typed predicate on the substrate primitive rather
3937    /// than open-coded at the validate gate so every downstream
3938    /// consumer of the pair reaches the invariant through one
3939    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
3940    /// below, the future `CiliumClusterwideEnvoyConfig`
3941    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
3942    /// must emit `local_rate_limit.token_bucket.{max_tokens,
3943    /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
3944    /// / `outlier_detection.interval` as one coherent Envoy block,
3945    /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3946    /// materializer's admission webhook, and the future
3947    /// per-`:contratos`-edge `:politicas` override the same roadmap
3948    /// acknowledges — which resolves an *effective* pair per edge
3949    /// (edge-level `:rate-limit` against the Aplicacao-level
3950    /// `:circuit-breaker`, or vice versa) and so must re-check the
3951    /// relation on a pair neither axis's declaration site can see
3952    /// whole. Naming the invariant once means that resolver folds
3953    /// this predicate over its resolved pair instead of re-deriving
3954    /// the comparison, exactly as the sibling cross-axis
3955    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
3956    /// names the `(:timeout, :window)` relation for its own consumers.
3957    #[must_use]
3958    pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
3959        match (self.rate_limit(), self.circuit_breaker()) {
3960            (Some(rl), Some(cb)) => {
3961                let calls_per_cb_window =
3962                    (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
3963                let trip_threshold_per_cb_window =
3964                    (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
3965                calls_per_cb_window >= trip_threshold_per_cb_window
3966            }
3967            _ => true,
3968        }
3969    }
3970
3971    /// Substrate-canonical cross-axis coherence predicate on the
3972    /// `:politicas` slot: can one client's declared `:retries` all
3973    /// complete before `:circuit-breaker :max-failures` trips the
3974    /// breaker mid-retry?
3975    ///
3976    /// The third cross-axis invariant on the `:politicas` surface —
3977    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
3978    /// the `(:timeout, :circuit-breaker :window)` pair and
3979    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
3980    /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
3981    /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
3982    /// the pair is validated in isolation by the per-axis brackets in
3983    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3984    /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
3985    /// are each individually well-formed can still name a
3986    /// structurally-inert retry policy. The pair
3987    /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
3988    /// passes every per-axis bracket and is nonetheless a retry
3989    /// policy the substrate cannot honor: one client's initial attempt
3990    /// plus three retries is four attempts, but the breaker trips on
3991    /// the third failure — the fourth attempt (the last declared
3992    /// retry) is blocked by the open breaker, so the substrate
3993    /// declared four attempts and structurally allows three.
3994    ///
3995    /// The typed test is the integer inequality
3996    /// `cb.max_failures() > retries` — the retries count is the
3997    /// *number of retry attempts beyond the initial* (Envoy's
3998    /// `retry_policy.num_retries` semantics), so a client makes at
3999    /// most `retries + 1` attempts per client call, each of which may
4000    /// fail. For the breaker to *admit* the retry policy through
4001    /// completion, its trip threshold must not be reached by one
4002    /// client's failures alone: `retries + 1 <= max_failures`,
4003    /// equivalently `retries < max_failures`, equivalently
4004    /// `max_failures > retries`. The boundary case
4005    /// `max_failures == retries + 1` accepts (the R+1th failure — the
4006    /// last retry — trips the breaker exactly as it completes; retries
4007    /// are fully executed). The strict-below case
4008    /// `max_failures <= retries` rejects (the breaker trips before
4009    /// retries exhaust, silently truncating the declared retry policy
4010    /// mid-run — the same declared-but-structurally-inert footgun the
4011    /// sibling per-axis cap arms close on the single-axis surfaces).
4012    ///
4013    /// Vacuously `true` when either axis is absent — a `:politicas`
4014    /// that names only one of the pair declares no relation for the
4015    /// substrate to hold it to (`:retries` alone is a client-retry
4016    /// policy with no failure counter to trip; `:circuit-breaker`
4017    /// alone is a failure counter whose per-client attempt count is
4018    /// unconstrained by the substrate, so no per-client saturation
4019    /// bound on failures-per-client-call is knowable at author time).
4020    /// Same "unset means the cluster default applies, not zero"
4021    /// partition [`MeshPolicy::is_empty`] and the sibling
4022    /// [`MeshPolicy::breaker_window_observes_timeout`] /
4023    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
4024    /// carry.
4025    ///
4026    /// Lifted as a typed predicate on the substrate primitive rather
4027    /// than open-coded at the validate gate so every downstream
4028    /// consumer of the pair reaches the invariant through one
4029    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
4030    /// below, the future `CiliumClusterwideEnvoyConfig`
4031    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
4032    /// must emit `retry_policy.num_retries` alongside
4033    /// `outlier_detection.consecutive_5xx` as one coherent Envoy
4034    /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4035    /// materializer's admission webhook, and the future
4036    /// per-`:contratos`-edge `:politicas` override the same roadmap
4037    /// acknowledges — which resolves an *effective* pair per edge
4038    /// (edge-level `:retries` against the Aplicacao-level
4039    /// `:circuit-breaker`, or vice versa) and so must re-check the
4040    /// relation on a pair neither axis's declaration site can see
4041    /// whole. Naming the invariant once means that resolver folds
4042    /// this predicate over its resolved pair instead of re-deriving
4043    /// the comparison, exactly as the sibling cross-axis
4044    /// [`MeshPolicy::breaker_window_observes_timeout`] and
4045    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
4046    /// name the `(:timeout, :window)` and `(:rate-limit,
4047    /// :circuit-breaker)` relations for their own consumers.
4048    #[must_use]
4049    pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
4050        match (self.retries(), self.circuit_breaker()) {
4051            (Some(retries), Some(cb)) => cb.max_failures() > retries,
4052            _ => true,
4053        }
4054    }
4055
4056    /// Substrate-canonical cross-axis coherence predicate on the
4057    /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
4058    /// admit one client's full `:retries + 1` attempt burst inside a
4059    /// single refill window?
4060    ///
4061    /// The fourth cross-axis invariant on the `:politicas` surface,
4062    /// completing the triangle of pairs the three sibling gates carve
4063    /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
4064    /// on the `(:timeout, :circuit-breaker :window)` pair,
4065    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
4066    /// `(:rate-limit, :circuit-breaker)` pair, and
4067    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
4068    /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
4069    /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
4070    /// among the three scalar `:politicas` axes (`:retries`,
4071    /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
4072    /// coherence surface every production overlay (Envoy, Istio,
4073    /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
4074    /// the pair is validated in isolation by the per-axis brackets in
4075    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
4076    /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
4077    /// whose axes are each individually well-formed can still name a
4078    /// structurally-truncated retry policy the rate limiter refuses to
4079    /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
4080    /// per-axis bracket and is nonetheless a retry policy the substrate
4081    /// cannot honor: one client's initial attempt plus five retries is
4082    /// six attempts, but the token bucket admits at most three tokens
4083    /// per one-second refill window, so the fourth attempt onward is
4084    /// blocked by the rate limiter itself — the substrate declared six
4085    /// attempts and structurally allows three. Envoy's
4086    /// `local_rate_limit.token_bucket.max_tokens` paired against
4087    /// `retry_policy.num_retries` carries the identical relation; every
4088    /// production playbook that pairs the two axes recommends sizing
4089    /// the bucket capacity above any single client's retry budget so
4090    /// the retry policy is not silently truncated by the same rate
4091    /// limiter it feeds through.
4092    ///
4093    /// The typed test is the integer inequality
4094    /// `rl.rate() >= retries + 1` — the retries count is the *number of
4095    /// retry attempts beyond the initial* (Envoy's
4096    /// `retry_policy.num_retries` semantics), so a client makes at most
4097    /// `retries + 1` attempts per client call, each of which consumes
4098    /// one token from the local rate-limit bucket. For the bucket to
4099    /// *admit* the retry burst without dropping tokens, its capacity
4100    /// must not be reached by one client's attempts alone:
4101    /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
4102    /// boundary case `rate == retries + 1` accepts (the bucket admits
4103    /// exactly one client's full retry sequence per refill window —
4104    /// retries fully executed). The strict-below case `rate <= retries`
4105    /// rejects (the bucket exhausts before retries complete, silently
4106    /// truncating the declared retry policy mid-run — the same
4107    /// declared-but-structurally-inert footgun the sibling per-axis cap
4108    /// arms close on the single-axis surfaces). The equivalent
4109    /// coherent-direction form `rl.rate() > retries` sidesteps the
4110    /// `retries + 1` addition entirely (both `rate` and `retries` are
4111    /// `u32`; the `>` comparison is total on the type with no overflow
4112    /// against past-the-guard struct-literal `retries` values a caller
4113    /// might pass before `validate` runs), matching the peer
4114    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
4115    /// `>`-comparison discipline on the sibling
4116    /// `(:retries, :max-failures)` pair.
4117    ///
4118    /// Vacuously `true` when either axis is absent — a `:politicas`
4119    /// that names only one of the pair declares no relation for the
4120    /// substrate to hold it to (`:retries` alone is a client-retry
4121    /// policy with no rate limiter to saturate; `:rate-limit` alone is
4122    /// a token-bucket declaration whose per-client attempt count is
4123    /// unconstrained by the substrate, so no per-client saturation
4124    /// bound on tokens-per-client-call is knowable at author time).
4125    /// Same "unset means the cluster default applies, not zero"
4126    /// partition [`MeshPolicy::is_empty`] and the three sibling
4127    /// cross-axis predicates
4128    /// ([`MeshPolicy::breaker_window_observes_timeout`],
4129    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
4130    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
4131    ///
4132    /// Lifted as a typed predicate on the substrate primitive rather
4133    /// than open-coded at the validate gate so every downstream
4134    /// consumer of the pair reaches the invariant through one dispatch:
4135    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
4136    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4137    /// (MESH-COMPOSITION §III.2 #3) that must emit
4138    /// `local_rate_limit.token_bucket.max_tokens` alongside
4139    /// `retry_policy.num_retries` as one coherent Envoy block, the
4140    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4141    /// admission webhook, and the future per-`:contratos`-edge
4142    /// `:politicas` override the same roadmap acknowledges — which
4143    /// resolves an *effective* pair per edge (edge-level `:retries`
4144    /// against the Aplicacao-level `:rate-limit`, or vice versa) and
4145    /// so must re-check the relation on a pair neither axis's
4146    /// declaration site can see whole. Naming the invariant once means
4147    /// that resolver folds this predicate over its resolved pair
4148    /// instead of re-deriving the comparison, exactly as the three
4149    /// sibling cross-axis predicates name the
4150    /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
4151    /// `(:retries, :max-failures)` relations for their own consumers,
4152    /// closing the fourth and last cross-axis relation on the scalar
4153    /// `:politicas` axis-triple.
4154    #[must_use]
4155    pub const fn rate_limit_admits_retry_burst(&self) -> bool {
4156        match (self.retries(), self.rate_limit()) {
4157            (Some(retries), Some(rl)) => rl.rate() > retries,
4158            _ => true,
4159        }
4160    }
4161
4162    /// Substrate-canonical fold over the four cross-axis coherence
4163    /// predicates on the `:politicas` slot — returns the *first*
4164    /// cross-axis violation (as its [`AplicacaoError`] variant) in the
4165    /// canonical "more-foundational-cross-axis first" ordering
4166    /// [`MeshPolicy::breaker_window_observes_timeout`] on
4167    /// `(:timeout, :circuit-breaker :window)` →
4168    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
4169    /// `(:rate-limit, :circuit-breaker)` →
4170    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
4171    /// `(:retries, :circuit-breaker :max-failures)` →
4172    /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
4173    /// :rate-limit)`. Returns `None` when every cross-axis relation
4174    /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
4175    /// coherent shape both land here).
4176    ///
4177    /// The ordering discipline this method encodes was open-coded four
4178    /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
4179    /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
4180    /// "cross-axis gate fires only when :<axis> is present"); let <b>
4181    /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
4182    /// axis-fetch step depended on the predicate having just returned
4183    /// `false` (structurally guaranteed both paired axes are `Some`,
4184    /// but the compiler cannot see through the predicate body, so
4185    /// every arm re-called the accessor with `.expect(…)` to reach
4186    /// the axis it just tested). Two unsound consequences: (1) the
4187    /// validate gate carried eight `.expect(…)` panic call sites the
4188    /// predicate contract already forbids on every well-typed input
4189    /// but the type system does not enforce; (2) the
4190    /// "which-cross-axis-fires-first-when-two-apply" contract lived
4191    /// twice — once in each predicate's own doc comments and once at
4192    /// the validate call site's four-arm cascade. Lifting the four-arm
4193    /// cascade onto this substrate primitive collapses both
4194    /// duplications: the predicate contract and the axis-fetch step
4195    /// live in the same body (no `.expect(…)` — the pattern match at
4196    /// each arm rebinds the paired axes so their `Some` presence is a
4197    /// compile-time property of the local scope), and the ordering
4198    /// discipline lives once at the top of the primitive rather than
4199    /// scattered across four sibling doc-comment blocks that must
4200    /// stay in lockstep.
4201    ///
4202    /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
4203    /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
4204    /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
4205    /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
4206    /// §III.2 #3 acknowledges — the last of which resolves an
4207    /// *effective* per-edge pair and must emit *the same* diagnostic
4208    /// on the same paired-axis input as `feira build`) reaches through
4209    /// one call rather than re-inlining the four pattern-matches +
4210    /// accessor-fetches + variant-constructions + ordering-cascade.
4211    ///
4212    /// Returns owned copies of every axis carried into the diagnostic:
4213    /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
4214    /// occurs on the happy path when no violation fires.
4215    #[must_use]
4216    pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
4217        // Ordering discipline this fold encodes matches the four
4218        // per-arm predicate doc comments' pairwise-ordering contract:
4219        // window-below-timeout wins over every arm that names `:rate-
4220        // limit` or `:retries` (its diagnostic is more self-locating —
4221        // the pair is a per-call-deadline invariant every synchronous
4222        // edge carries whether or not `:rate-limit`/`:retries` is
4223        // declared); the starve arm wins over the two retry arms (its
4224        // diagnostic reasons across the token-bucket-vs-breaker
4225        // relation, an axis the retry arms do not touch); the
4226        // retries-saturate arm wins over the retries-burst arm (its
4227        // diagnostic reasons across the per-client-vs-breaker
4228        // relation, which carries whether or not `:rate-limit` is
4229        // declared). Each arm rebinds the paired axes through the
4230        // pattern match, so the `.expect(…)` panics the four-block
4231        // cascade at `validate_politicas` carried collapse to no-op
4232        // pattern rebindings the compiler statically proves exhaust.
4233        if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
4234            && !self.breaker_window_observes_timeout()
4235        {
4236            return Some(AplicacaoError::policy_breaker_window_below_timeout(&cb, t));
4237        }
4238        if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
4239            && !self.breaker_can_trip_under_rate_limit()
4240        {
4241            return Some(AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(
4242                &rl, &cb,
4243            ));
4244        }
4245        if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
4246            && !self.retries_fit_under_breaker_trip_threshold()
4247        {
4248            return Some(
4249                AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb),
4250            );
4251        }
4252        if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
4253            && !self.rate_limit_admits_retry_burst()
4254        {
4255            return Some(AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(
4256                retries, &rl,
4257            ));
4258        }
4259        None
4260    }
4261
4262    /// Substrate-canonical compound entry gate over the whole
4263    /// `:politicas` typed slot — folds every per-axis bracket
4264    /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
4265    /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
4266    /// window-canonical-form) *and* the compound cross-axis fold
4267    /// [`MeshPolicy::first_cross_axis_violation`] into one call every
4268    /// consumer of a validated [`MeshPolicy`] reaches through.
4269    ///
4270    /// Returns the first violation as its [`AplicacaoError`] variant,
4271    /// or `Ok(())` when every per-axis value lies in its accept-set and
4272    /// every cross-axis relation holds. Per-axis brackets run strictly
4273    /// before the cross-axis fold — the sibling
4274    /// [`AplicacaoSpec::validate_politicas`] gate carried the same
4275    /// ordering discipline for the same reason: a per-axis
4276    /// structurally-invalid value (a `Duration::ZERO` `:window`, an
4277    /// above-cap `:rate-limit` rate) surfaces its own self-locating
4278    /// diagnostic first, ahead of any cross-axis arm that would send
4279    /// the author to reconcile two values one of which is not a
4280    /// meaningful window at all. Within the per-axis phase, arms fire
4281    /// in the same slot-order the peer per-axis brackets carry
4282    /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
4283    /// each internally ordered zero-floor before canonical-form before
4284    /// cap by [`crate::render::require_positive_bounded_u32`] /
4285    /// [`crate::render::require_positive_canonical_bounded_duration`]);
4286    /// within the cross-axis phase, arms fire in the canonical
4287    /// more-foundational-cross-axis-first ordering
4288    /// [`MeshPolicy::first_cross_axis_violation`] encodes.
4289    ///
4290    /// Lifted as a typed method on the substrate primitive so every
4291    /// downstream consumer of a validated [`MeshPolicy`] reaches the
4292    /// invariant through one dispatch: the
4293    /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
4294    /// body collapses to `self.politicas().validate()`), the future
4295    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4296    /// admission webhook, the future per-`:contratos`-edge `:politicas`
4297    /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
4298    /// which resolves an *effective* per-edge [`MeshPolicy`] and must
4299    /// emit *the same* diagnostic on the same input as `feira build`.
4300    /// Naming the compound gate once on the substrate primitive means
4301    /// every downstream consumer inherits both the per-axis brackets
4302    /// *and* the cross-axis fold through one call, rather than
4303    /// re-inlining the four-per-axis + one-cross-axis cascade in
4304    /// lockstep with `validate_politicas`.
4305    ///
4306    /// Peer of the per-kind compound entry gates lifted at
4307    /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
4308    /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
4309    /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
4310    /// layout axis, and the sibling compound cross-axis fold
4311    /// [`MeshPolicy::first_cross_axis_violation`] on the same
4312    /// `:politicas` axis — extended here onto the per-slot per-axis +
4313    /// cross-axis compound entry gate that folds both surfaces.
4314    pub fn validate(&self) -> Result<(), AplicacaoError> {
4315        if let Some(t) = self.timeout() {
4316            crate::render::require_positive_canonical_bounded_duration(
4317                t,
4318                POLICY_TIMEOUT_MAX,
4319                || AplicacaoError::PolicyTimeoutZero,
4320                AplicacaoError::policy_timeout_not_canonical,
4321                AplicacaoError::policy_timeout_exceeds_cap,
4322            )?;
4323        }
4324        if let Some(r) = self.retries() {
4325            crate::render::require_positive_bounded_u32(
4326                r,
4327                POLICY_RETRIES_MAX,
4328                || AplicacaoError::PolicyRetriesZero,
4329                AplicacaoError::policy_retries_exceeds_cap,
4330            )?;
4331        }
4332        if let Some(cb) = self.circuit_breaker() {
4333            crate::render::require_positive_bounded_u32(
4334                cb.max_failures(),
4335                POLICY_BREAKER_MAX_FAILURES_MAX,
4336                || AplicacaoError::PolicyBreakerZeroFailures,
4337                AplicacaoError::policy_breaker_max_failures_exceeds_cap,
4338            )?;
4339            crate::render::require_positive_canonical_bounded_duration(
4340                cb.window(),
4341                POLICY_BREAKER_WINDOW_MAX,
4342                || AplicacaoError::PolicyBreakerZeroWindow,
4343                AplicacaoError::policy_breaker_window_not_canonical,
4344                AplicacaoError::policy_breaker_window_exceeds_cap,
4345            )?;
4346        }
4347        if let Some(rl) = self.rate_limit() {
4348            crate::render::require_positive_bounded_u32(
4349                rl.rate(),
4350                POLICY_RATE_LIMIT_MAX,
4351                || AplicacaoError::PolicyRateLimitZero,
4352                AplicacaoError::policy_rate_limit_exceeds_cap,
4353            )?;
4354            if rl.canonical_unit().is_none() {
4355                return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
4356                    rl.window(),
4357                ));
4358            }
4359        }
4360        if let Some(err) = self.first_cross_axis_violation() {
4361            return Err(err);
4362        }
4363        Ok(())
4364    }
4365
4366    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
4367    /// per-call-deadline scalar accessor every consumer of the
4368    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
4369    /// returns the author-declared `:politicas :timeout` typed
4370    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
4371    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
4372    /// is `Copy`, so the accessor returns by value; no borrow of
4373    /// `&self` past the call). `None` when the slot is absent (the
4374    /// "cluster default applies — typically the gateway class's
4375    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
4376    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
4377    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
4378    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
4379    /// round-trips to a rendered `HTTPRoute` structurally identical to
4380    /// one that omits the slot).
4381    ///
4382    /// The `:politicas :timeout` slot carries the "no infinite blocking"
4383    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
4384    /// the typed slot's `Option<Duration>` accept-set (zero-floor
4385    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
4386    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
4387    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
4388    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
4389    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
4390    /// Every downstream consumer that reads the per-call cap keys off
4391    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
4392    /// renderers key off to decide "emit :politicas overlay" vs "skip
4393    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
4394    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
4395    /// fans the deadline into every rule via
4396    /// [`crate::render::single_field_overlay`], the future M4 per-
4397    /// Aplicacao Gateway API reconciler materialization pass, the
4398    /// future per-`:contratos`-edge timeout-override overlay the
4399    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
4400    ///
4401    /// Prior to this lift the `.timeout` field was accessed inline at
4402    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
4403    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
4404    /// …)` call — two open-coded field-accesses that expressed no
4405    /// compile-time link back to the typed slot. A future extension of
4406    /// the `:politicas :timeout` axis to a richer author surface — a
4407    /// per-`:contratos`-edge timeout override the operator pins through
4408    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
4409    /// roadmap acknowledges, a per-cluster timeout-default overlay the
4410    /// M4 CR materializer resolves per-CR, a split of the single
4411    /// per-call `Duration` into a richer `{request, backendRequest}`
4412    /// pair once the Gateway API's per-rule `timeouts` block grows the
4413    /// upstream-facing backendRequest arm alongside the client-facing
4414    /// request arm — would have had to be threaded through both open-
4415    /// coded copies in lockstep or the emptiness predicate and the
4416    /// caixa-mesh emit path would silently disagree on which per-call
4417    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
4418    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
4419    /// == false` while the renderer's overlay-emit path silently read
4420    /// a drifted other value, or vice versa: an author's `:timeout
4421    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
4422    /// the emptiness predicate still classified the policy as non-
4423    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
4424    /// | grep -A2 timeouts` audit would land on a route whose author's
4425    /// typed slot value silently vanished at the renderer layer).
4426    /// Lifting the resolution to a typed method on the substrate
4427    /// primitive means every downstream consumer of the Aplicacao's
4428    /// per-`:politicas` deadline surface reaches for exactly one typed
4429    /// dispatch — the resolver's accept-set migrates as a unit on any
4430    /// future axis addition.
4431    ///
4432    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
4433    /// family (sibling of the peer per-`:politicas`
4434    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
4435    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
4436    /// `Option<bool>` accessor — same "one typed dispatch on the
4437    /// substrate primitive, thin projections at each consumer"
4438    /// discipline extended onto the peer per-`:politicas` typed-
4439    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
4440    /// numeric-Copy-T scalar" projection pattern the sibling
4441    /// `Option<u32>` / `Option<bool>` lifts opened, since every
4442    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
4443    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
4444    /// than a scalar). Named `timeout()` to match the storage field's
4445    /// name; the accessor's identity maps onto the canonical MESH-
4446    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
4447    #[must_use]
4448    pub const fn timeout(&self) -> Option<Duration> {
4449        self.timeout
4450    }
4451
4452    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
4453    /// retry-budget scalar accessor every consumer of the Aplicacao's
4454    /// Gateway API v1.x per-rule retry-cap keys off — returns the
4455    /// author-declared `:politicas :retries` typed `u32` verbatim as an
4456    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
4457    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
4458    /// value; no borrow of `&self` past the call). `None` when the slot
4459    /// is absent (the "cluster default applies — typically 'no retries
4460    /// beyond a single dispatch attempt'" arm the caixa-mesh
4461    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
4462    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
4463    /// this predicate too, so an authored-but-unset `:politicas
4464    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
4465    /// identical to one that omits the slot).
4466    ///
4467    /// The `:politicas :retries` slot carries the "transient failure
4468    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
4469    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
4470    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
4471    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
4472    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
4473    /// count scalar the caixa-mesh `retry_overlay` builder writes.
4474    /// Every downstream consumer that reads the retry cap keys off this
4475    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
4476    /// renderers key off to decide "emit :politicas overlay" vs "skip
4477    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
4478    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
4479    /// the value into every rule via [`crate::render::single_field_overlay`],
4480    /// the future M4 per-Aplicacao Gateway API reconciler
4481    /// materialization pass, the future per-`:contratos`-edge retry-
4482    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
4483    /// acknowledges).
4484    ///
4485    /// Prior to this lift the `.retries` field was accessed inline at
4486    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
4487    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
4488    /// …)` call — two open-coded field-accesses that expressed no
4489    /// compile-time link back to the typed slot. A future extension of
4490    /// the `:politicas :retries` axis to a richer author surface — a
4491    /// per-`:contratos`-edge retry override the operator pins through a
4492    /// future `:contratos :retries` slot, a per-cluster retry-default
4493    /// overlay the M4 CR materializer resolves per-CR, a promotion of
4494    /// the plain `u32` attempt-count to a richer `{attempts, codes,
4495    /// backoff}` sub-block once the Gateway API grows the peer
4496    /// `retry.codes` / `retry.backoff` axes — would have had to be
4497    /// threaded through both open-coded copies in lockstep or the
4498    /// emptiness predicate and the caixa-mesh emit path would silently
4499    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
4500    /// (a `:politicas` block whose only axis is a `Some :retries` would
4501    /// satisfy `is_empty() == false` while the renderer's overlay-emit
4502    /// path silently read a drifted other value, or vice versa: an
4503    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
4504    /// block while the emptiness predicate still classified the policy
4505    /// as non-empty). Lifting the resolution to a typed method on the
4506    /// substrate primitive means every downstream consumer of the
4507    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
4508    /// one typed dispatch — the resolver's accept-set migrates as a
4509    /// unit on any future axis addition.
4510    ///
4511    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
4512    /// family (sibling of the peer per-`:politicas`
4513    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
4514    /// same "one typed dispatch on the substrate primitive, thin
4515    /// projections at each consumer" discipline extended onto the
4516    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
4517    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
4518    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
4519    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
4520    /// fold on). Named `retries()` to match the storage field's name;
4521    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
4522    /// §III.2 vocabulary the slot's docstring already carries.
4523    #[must_use]
4524    pub const fn retries(&self) -> Option<u32> {
4525        self.retries
4526    }
4527
4528    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
4529    /// enforcement-toggle scalar accessor every consumer of the
4530    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
4531    /// — returns the author-declared `:politicas :mtls-required` typed
4532    /// bool verbatim as an `Option<bool>`, copied out of the typed
4533    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
4534    /// the accessor returns by value; no borrow of `&self` past the
4535    /// call). `None` when the slot is absent (the "cluster default
4536    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
4537    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
4538    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
4539    /// this predicate too, so an authored-but-unset `:politicas
4540    /// (:mtls-required ())` round-trips to a rendered
4541    /// `CiliumNetworkPolicy` structurally identical to one that omits
4542    /// the slot).
4543    ///
4544    /// The `:politicas :mtls-required` slot carries the "explicit opt-
4545    /// out only, sandboxing-by-default" mTLS-enforcement toggle
4546    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
4547    /// `{None, Some(true), Some(false)}` accept-set maps onto the
4548    /// Cilium `authentication.mode` bijection through
4549    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
4550    /// handshake enforced), `Some(false) → "disabled"` (handshake
4551    /// skipped — the debug-edge opt-out), `None` → omit the block
4552    /// (cluster default applies). Every downstream consumer that
4553    /// reads the toggle keys off this scalar (the
4554    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4555    /// off to decide "emit :politicas overlay" vs "skip entirely", the
4556    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
4557    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
4558    /// ingress rule via [`crate::render::single_field_overlay`], the
4559    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
4560    /// materialization pass, the future per-`:contratos`-edge mTLS
4561    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4562    ///
4563    /// Prior to this lift the `.mtls_required` field was accessed
4564    /// inline at two sites — [`MeshPolicy::is_empty`]'s
4565    /// `self.mtls_required.is_none()` arm and caixa-mesh's
4566    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
4567    /// two open-coded field-accesses that expressed no compile-time
4568    /// link back to the typed slot. A future extension of the
4569    /// `:politicas :mtls-required` axis to a richer author surface —
4570    /// a per-`:contratos`-edge mTLS override the operator pins through
4571    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
4572    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
4573    /// M4 CR materializer resolves per-CR, a three-valued
4574    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
4575    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
4576    /// would have had to be threaded through both open-coded copies in
4577    /// lockstep or the emptiness predicate and the caixa-mesh emit
4578    /// path would silently disagree on which toggle a given
4579    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
4580    /// axis is a `Some`
4581    /// `:mtls-required` would satisfy `is_empty() == false` while the
4582    /// renderer's overlay-emit path silently read a drifted other
4583    /// value, or vice versa). Lifting the resolution to a typed method
4584    /// on the substrate primitive means every downstream consumer of
4585    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
4586    /// for exactly one typed dispatch — the resolver's accept-set
4587    /// migrates as a unit on any future axis addition.
4588    ///
4589    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
4590    /// family (peer of the sibling per-`:placement`
4591    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
4592    /// same "one typed dispatch on the substrate primitive, thin
4593    /// projections at each consumer" discipline extended onto the
4594    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
4595    /// the "optional per-slot Copy-T scalar" projection pattern the
4596    /// sibling per-`:politicas` `:retries` (Option<u32>) /
4597    /// `:timeout` (Option<Duration>) future lifts fold on). Named
4598    /// `mtls_required()` to match the storage field's name; the
4599    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4600    /// §III.2 vocabulary the slot's docstring already carries.
4601    #[must_use]
4602    pub const fn mtls_required(&self) -> Option<bool> {
4603        self.mtls_required
4604    }
4605
4606    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
4607    /// `local_rate_limit`-mesh token-bucket-declaration scalar
4608    /// accessor every consumer of the Aplicacao's per-`:politicas`
4609    /// per-`(rate, window)` rate-limit surface keys off — returns the
4610    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
4611    /// verbatim as an `Option<RateLimit>`, copied out of the typed
4612    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
4613    /// `Copy`, so the accessor returns by value; no borrow of `&self`
4614    /// past the call). `None` when the slot is absent (the "cluster
4615    /// default applies — typically 'no per-Aplicacao rate declaration,
4616    /// gateway-class per-listener default applies'" arm the future
4617    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
4618    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
4619    /// `rate_limit().is_none()` arm reads this predicate too, so an
4620    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
4621    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
4622    /// identical to one that omits the slot).
4623    ///
4624    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
4625    /// token-bucket rate declaration" contract (MESH-COMPOSITION
4626    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
4627    /// (rate lower-bounded by 1 through
4628    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
4629    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
4630    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
4631    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
4632    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
4633    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
4634    /// `:politicas` overlay emits. Every downstream consumer that
4635    /// reads the rate declaration keys off this scalar (the
4636    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4637    /// off to decide "emit :politicas overlay" vs "skip entirely", the
4638    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
4639    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
4640    /// `rl.window` against [`is_canonical_rate_limit_window`], the
4641    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
4642    /// the future per-`:contratos`-edge rate-limit override the
4643    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4644    ///
4645    /// Prior to this lift the `.rate_limit` field was accessed inline
4646    /// at two sites — [`MeshPolicy::is_empty`]'s
4647    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
4648    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
4649    /// field-accesses that expressed no compile-time link back to the
4650    /// typed slot. A future extension of the `:politicas :rate-limit`
4651    /// axis to a richer author surface — a per-`:contratos`-edge
4652    /// rate-limit override the operator pins through a future
4653    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
4654    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
4655    /// the M4 CR materializer resolves per-CR, a promotion of the
4656    /// plain `(rate, window)` scalar pair to a richer
4657    /// `{rate, window, burst, key}` sub-block once Envoy's
4658    /// `local_rate_limit` grows the peer `burst_size` /
4659    /// `descriptor_key` axes — would have had to be threaded through
4660    /// both open-coded copies in lockstep or the emptiness predicate
4661    /// and the validate gate would silently disagree on which rate
4662    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
4663    /// block whose only axis is a `Some :rate-limit` would satisfy
4664    /// `is_empty() == false` while the validate path silently read a
4665    /// drifted other value, or vice versa: an author's
4666    /// `:rate-limit "100/s"` would omit the value-shape gate while the
4667    /// emptiness predicate still classified the policy as non-empty).
4668    /// Lifting the resolution to a typed method on the substrate
4669    /// primitive means every downstream consumer of the Aplicacao's
4670    /// per-`:politicas` rate-limit surface reaches for exactly one
4671    /// typed dispatch — the resolver's accept-set migrates as a unit
4672    /// on any future axis addition.
4673    ///
4674    /// First `Option<Copy-composite-T>`-return accessor on the M3
4675    /// mesh-slot family — closes the last un-lifted per-`:politicas`
4676    /// scalar-value axis. Peer of the sibling per-`:politicas`
4677    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
4678    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
4679    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
4680    /// "one typed dispatch on the substrate primitive, thin
4681    /// projections at each consumer" discipline extended onto the
4682    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
4683    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
4684    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
4685    /// sub-accessors rather than a top-level accessor because
4686    /// consumers reach for the axes not the aggregate). Named
4687    /// `rate_limit()` to match the storage field's name; the
4688    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4689    /// §III.2 vocabulary the slot's docstring already carries.
4690    #[must_use]
4691    pub const fn rate_limit(&self) -> Option<RateLimit> {
4692        self.rate_limit
4693    }
4694
4695    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
4696    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
4697    /// declaration scalar accessor every consumer of the Aplicacao's
4698    /// per-`:politicas` breaker declaration keys off — returns the
4699    /// author-declared `:politicas :circuit-breaker` typed
4700    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
4701    /// copied out of the typed slot's own `Option<CircuitBreaker>`
4702    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
4703    /// by value; no borrow of `&self` past the call). `None` when the
4704    /// slot is absent (the "cluster default applies — typically 'no
4705    /// per-Aplicacao breaker declaration, gateway-class per-listener
4706    /// default applies'" arm the future caixa-mesh
4707    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
4708    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
4709    /// arm reads this predicate too, so an authored-but-unset
4710    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
4711    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
4712    /// that omits the slot).
4713    ///
4714    /// The `:politicas :circuit-breaker` slot carries the
4715    /// "per-Aplicacao consecutive-transient-failure trip declaration"
4716    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
4717    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
4718    /// zero-floor rejected through
4719    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
4720    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
4721    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
4722    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
4723    /// canonical-form pinned through
4724    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
4725    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
4726    /// bijection the future `CiliumClusterwideEnvoyConfig`
4727    /// per-`:politicas` overlay emits. Every downstream consumer that
4728    /// reads the breaker declaration keys off this scalar (the
4729    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4730    /// off to decide "emit :politicas overlay" vs "skip entirely", the
4731    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
4732    /// that brackets `cb.max_failures()` against
4733    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
4734    /// [`POLICY_BREAKER_WINDOW_MAX`] via
4735    /// [`crate::render::require_positive_canonical_bounded_duration`],
4736    /// the future M4 per-Aplicacao Envoy reconciler materialization
4737    /// pass, the future per-`:contratos`-edge breaker override the
4738    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4739    ///
4740    /// Prior to this lift the `.circuit_breaker` field was accessed
4741    /// inline at two sites — [`MeshPolicy::is_empty`]'s
4742    /// `self.circuit_breaker.is_none()` arm and the
4743    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
4744    /// bind — two open-coded field-accesses that expressed no
4745    /// compile-time link back to the typed slot. A future extension of
4746    /// the `:politicas :circuit-breaker` axis to a richer author
4747    /// surface — a per-`:contratos`-edge breaker override the operator
4748    /// pins through a future `:contratos :circuit-breaker` slot the
4749    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
4750    /// breaker-default overlay the M4 CR materializer resolves per-CR,
4751    /// a promotion of the plain `(max_failures, window)` scalar pair to
4752    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
4753    /// sub-block once Envoy's `outlier_detection` grows the peer
4754    /// ejection-percentage / ejection-time axes — would have had to be
4755    /// threaded through both open-coded copies in lockstep or the
4756    /// emptiness predicate and the validate gate would silently
4757    /// disagree on which breaker declaration a given [`MeshPolicy`]
4758    /// resolves to (a `:politicas` block whose only axis is a
4759    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
4760    /// the validate path silently read a drifted other value, or vice
4761    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
4762    /// "60s"))` would omit the value-shape gate while the emptiness
4763    /// predicate still classified the policy as non-empty). Lifting
4764    /// the resolution to a typed method on the substrate primitive
4765    /// means every downstream consumer of the Aplicacao's
4766    /// per-`:politicas` breaker surface reaches for exactly one typed
4767    /// dispatch — the resolver's accept-set migrates as a unit on any
4768    /// future axis addition.
4769    ///
4770    /// Second `Option<Copy-composite-T>`-return accessor on the M3
4771    /// mesh-slot family (sibling of the peer per-`:politicas`
4772    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
4773    /// on the same composite-Copy shape, and of the sibling per-
4774    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
4775    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
4776    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
4777    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
4778    /// same "one typed dispatch on the substrate primitive, thin
4779    /// projections at each consumer" discipline extended onto the last
4780    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
4781    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
4782    /// match the storage field's name; the accessor's identity maps
4783    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4784    /// docstring already carries. Closes the last unlifted
4785    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
4786    /// reader now routes through a typed dispatch on the substrate
4787    /// primitive.
4788    #[must_use]
4789    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
4790        self.circuit_breaker
4791    }
4792}
4793
4794#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
4795#[serde(rename_all = "camelCase")]
4796pub struct CircuitBreaker {
4797    pub max_failures: u32,
4798    #[serde(with = "supervisor::duration_codec_required")]
4799    pub window: Duration,
4800}
4801
4802impl CircuitBreaker {
4803    /// Substrate-canonical per-`:politicas :circuit-breaker`
4804    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
4805    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4806    /// breaker trip-count keys off — returns the author-declared
4807    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
4808    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
4809    /// so the accessor returns by value; no borrow of `&self` past the
4810    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
4811    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
4812    /// axis; a `CircuitBreaker` past pattern-match is definitionally
4813    /// present, and its `:max-failures` field carries the trip count as a
4814    /// required-axis scalar).
4815    ///
4816    /// The `:politicas :circuit-breaker :max-failures` axis carries the
4817    /// "consecutive-transient-failure trip threshold" contract
4818    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
4819    /// (zero-floor rejected through
4820    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
4821    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
4822    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
4823    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
4824    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
4825    /// Every downstream consumer that reads the trip threshold keys off
4826    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4827    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
4828    /// canonical `require_positive_bounded_u32` helper, the future M4
4829    /// per-Aplicacao Envoy config reconciler materialization pass, the
4830    /// future per-`:contratos`-edge breaker-override overlay the
4831    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4832    ///
4833    /// Prior to this lift the `.max_failures` field was accessed inline
4834    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
4835    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
4836    /// open-coded field-access that expressed no compile-time link back
4837    /// to the typed sub-struct axis. A future extension of the
4838    /// `:max-failures` axis to a richer author surface — a
4839    /// per-`:contratos`-edge breaker override the operator pins through a
4840    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
4841    /// #3 roadmap acknowledges, a per-cluster max-failures-default
4842    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
4843    /// plain `u32` trip count to a richer
4844    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
4845    /// tuple once Envoy's `outlier_detection` block's peer axes come into
4846    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
4847    /// count arms — would have had to be threaded through every open-
4848    /// coded copy in lockstep or the validate gate and the future M4
4849    /// emit path would silently disagree on which trip threshold a given
4850    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
4851    /// would satisfy validate while the emit path silently read a drifted
4852    /// other value, or vice versa: a validated typed slot would land at
4853    /// the emit boundary as a no-op breaker whose trip threshold is
4854    /// structurally never reached). Lifting the resolution to a typed
4855    /// method on the substrate primitive means every downstream consumer
4856    /// of the Aplicacao's per-`:politicas :circuit-breaker`
4857    /// trip-threshold surface reaches for exactly one typed dispatch —
4858    /// the resolver's accept-set migrates as a unit on any future axis
4859    /// addition.
4860    ///
4861    /// First sub-struct scalar accessor on the M3 mesh-slot family
4862    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
4863    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
4864    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
4865    /// closes the last unlifted per-`:politicas` scalar-value axis after
4866    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
4867    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
4868    /// Same "one typed dispatch on the substrate primitive, thin
4869    /// projections at each consumer" discipline the peer
4870    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
4871    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
4872    /// [`Membro::versao_requirement`] (a40b0e3),
4873    /// [`Entrada::destination`] (6db982c) accessors carry on their
4874    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
4875    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
4876    /// match the storage field's name; the accessor's identity maps onto
4877    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4878    /// docstring already carries.
4879    #[must_use]
4880    pub const fn max_failures(&self) -> u32 {
4881        self.max_failures
4882    }
4883
4884    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
4885    /// Envoy-outlier-detection rolling-observation-interval scalar
4886    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4887    /// breaker rolling-window duration keys off — returns the
4888    /// author-declared `:politicas :circuit-breaker :window` typed
4889    /// `Duration` verbatim, copied out of the typed slot's own
4890    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
4891    /// by value; no borrow of `&self` past the call). Non-optional (the
4892    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
4893    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
4894    /// `CircuitBreaker` past pattern-match is definitionally present,
4895    /// and its `:window` field carries the rolling-observation interval
4896    /// as a required-axis scalar).
4897    ///
4898    /// The `:politicas :circuit-breaker :window` axis carries the
4899    /// "consecutive-transient-failure rolling-observation interval"
4900    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
4901    /// `Duration` accept-set (zero-floor rejected through
4902    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
4903    /// residue rejected through
4904    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
4905    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
4906    /// Envoy `outlier_detection.interval` per-cluster
4907    /// ejection-observation-interval scalar (equivalently the future
4908    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4909    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4910    /// consumer that reads the rolling-observation interval keys off
4911    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4912    /// integer-millisecond canonical-form + cap bracket at
4913    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
4914    /// [`crate::render::require_positive_canonical_bounded_duration`]
4915    /// helper, the future M4 per-Aplicacao Envoy config reconciler
4916    /// materialization pass, the future per-`:contratos`-edge
4917    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4918    /// acknowledges).
4919    ///
4920    /// Prior to this lift the `.window` field was accessed inline at
4921    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
4922    /// `require_positive_canonical_bounded_duration(cb.window, …)`
4923    /// call — one open-coded field-access that expressed no compile-
4924    /// time link back to the typed sub-struct axis. A future extension
4925    /// of the `:window` axis to a richer author surface — a
4926    /// per-`:contratos`-edge window override the operator pins through
4927    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
4928    /// #3 roadmap acknowledges, a per-cluster window-default overlay
4929    /// the M4 CR materializer resolves per-CR, a promotion of the plain
4930    /// `Duration` observation interval to a richer
4931    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
4932    /// once Envoy's `outlier_detection` block's peer axes come into
4933    /// scope, a per-Envoy-cluster minimum-request-volume gate before
4934    /// the window arms — would have had to be threaded through every
4935    /// open-coded copy in lockstep or the validate gate and the future
4936    /// M4 emit path would silently disagree on which observation
4937    /// interval a given [`CircuitBreaker`] resolves to (an author's
4938    /// `:window "60s"` would satisfy validate while the emit path
4939    /// silently read a drifted other value, or vice versa: a validated
4940    /// typed slot would land at the emit boundary as a breaker whose
4941    /// observation window is structurally so wide that no realistic
4942    /// failure-rate shape can trip it). Lifting the resolution to a
4943    /// typed method on the substrate primitive means every downstream
4944    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
4945    /// observation-window surface reaches for exactly one typed
4946    /// dispatch — the resolver's accept-set migrates as a unit on any
4947    /// future axis addition.
4948    ///
4949    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
4950    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
4951    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
4952    /// required-axis, extended onto the per-sub-struct required-`Duration`
4953    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
4954    /// axis. Same "one typed dispatch on the substrate primitive, thin
4955    /// projections at each consumer" discipline the peer
4956    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
4957    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
4958    /// [`Membro::versao_requirement`] (a40b0e3),
4959    /// [`Entrada::destination`] (6db982c) accessors carry on their
4960    /// respective per-mesh-slot-atom scalar-value axes, extended onto
4961    /// the per-sub-struct required-`Duration` axis. Named `window()` to
4962    /// match the storage field's name; the accessor's identity maps onto
4963    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4964    /// docstring already carries.
4965    #[must_use]
4966    pub const fn window(&self) -> Duration {
4967        self.window
4968    }
4969}
4970
4971#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4972pub struct RateLimit {
4973    /// Requests per window.
4974    pub rate: u32,
4975    /// Window duration.
4976    pub window: Duration,
4977}
4978
4979impl RateLimit {
4980    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
4981    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
4982    /// every consumer of the Aplicacao's per-`:contratos`-edge
4983    /// rate-limit-bucket capacity keys off — returns the author-declared
4984    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
4985    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
4986    /// returns by value; no borrow of `&self` past the call). Non-optional
4987    /// (the surrounding `Option<RateLimit>` is the "slot present?"
4988    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
4989    /// `RateLimit` past pattern-match is definitionally present, and its
4990    /// `:rate` field carries the token-bucket capacity as a required-axis
4991    /// scalar).
4992    ///
4993    /// The `:politicas :rate-limit` `:rate` axis carries the
4994    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
4995    /// the typed slot's `u32` accept-set (zero-floor rejected through
4996    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
4997    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
4998    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
4999    /// token-bucket-capacity scalar (equivalently the future
5000    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5001    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
5002    /// consumer that reads the token-bucket capacity keys off this
5003    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
5004    /// cap bracket that gates on the canonical
5005    /// [`crate::render::require_positive_bounded_u32`] helper, the
5006    /// [`rate_limit_codec::render`] `Duration → unit` projection that
5007    /// emits the `<n>/<s|m|h>` author surface, the future M4
5008    /// per-Aplicacao Envoy config reconciler materialization pass, the
5009    /// future per-`:contratos`-edge rate-limit-override overlay the
5010    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
5011    ///
5012    /// Prior to this lift the `.rate` field was accessed inline at three
5013    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
5014    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
5015    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
5016    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
5017    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
5018    /// field-accesses that expressed no compile-time link back to the
5019    /// typed sub-struct axis. A future extension of the `:rate` axis
5020    /// to a richer author surface — a per-`:contratos`-edge rate
5021    /// override the operator pins through a future `:contratos :rate`
5022    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
5023    /// per-cluster rate-default overlay the M4 CR materializer resolves
5024    /// per-CR, a promotion of the plain `u32` token capacity to a
5025    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
5026    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
5027    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
5028    /// before the token arms — would have had to be threaded through
5029    /// every open-coded copy in lockstep or the validate gate, the
5030    /// codec's render path, and the future M4 emit path would silently
5031    /// disagree on which token capacity a given [`RateLimit`] resolves
5032    /// to (an author's `:rate-limit "100/s"` would satisfy validate
5033    /// while the render / emit paths silently read a drifted other
5034    /// value, or vice versa: a validated typed slot would land at the
5035    /// emit boundary as a no-op limiter whose token capacity is
5036    /// structurally so high that no realistic per-edge traffic shape
5037    /// can drain it). Lifting the resolution to a typed method on the
5038    /// substrate primitive means every downstream consumer of the
5039    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
5040    /// reaches for exactly one typed dispatch — the resolver's
5041    /// accept-set migrates as a unit on any future axis addition.
5042    ///
5043    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
5044    /// in shape to the peer per-`CircuitBreaker`
5045    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
5046    /// on the peer per-sub-struct required-axis, extended onto the
5047    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
5048    /// required-axis scalar" projection pattern the sibling
5049    /// [`RateLimit::window`] future lift folds on. Same "one typed
5050    /// dispatch on the substrate primitive, thin projections at each
5051    /// consumer" discipline the peer [`WitContract::source`] /
5052    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
5053    /// (0804823), [`Membro::nome`] (4a32abf),
5054    /// [`Membro::versao_requirement`] (a40b0e3),
5055    /// [`Entrada::destination`] (6db982c),
5056    /// [`CircuitBreaker::max_failures`] (3a74062),
5057    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
5058    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
5059    /// to match the storage field's name; the accessor's identity maps
5060    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
5061    /// docstring already carries.
5062    #[must_use]
5063    pub const fn rate(&self) -> u32 {
5064        self.rate
5065    }
5066
5067    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
5068    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
5069    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
5070    /// rate-limit-bucket refill period keys off — returns the
5071    /// author-declared `:politicas :rate-limit` typed `Duration`
5072    /// verbatim, copied out of the typed slot's own `Duration` storage
5073    /// (`Duration` is `Copy`, so the accessor returns by value; no
5074    /// borrow of `&self` past the call). Non-optional (the surrounding
5075    /// `Option<RateLimit>` is the "slot present?" projection at the
5076    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
5077    /// pattern-match is definitionally present, and its `:window`
5078    /// field carries the token-bucket refill period as a required-axis
5079    /// scalar).
5080    ///
5081    /// The `:politicas :rate-limit` `:window` axis carries the
5082    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
5083    /// — the typed slot's `Duration` accept-set (constrained to the
5084    /// three canonical windows `{1s, 60s, 3600s}` the
5085    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
5086    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
5087    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
5088    /// per-cluster token-bucket-refill-period scalar (equivalently the
5089    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5090    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
5091    /// consumer that reads the token-bucket refill period keys off
5092    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
5093    /// canonical-window gate that keys off
5094    /// [`is_canonical_rate_limit_window`], the
5095    /// [`rate_limit_codec::render`] `Duration → unit` projection that
5096    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
5097    /// [`rate_limit_window_unit`] and non-canonical fallback via
5098    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
5099    /// reconciler materialization pass, the future per-`:contratos`-
5100    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
5101    /// roadmap acknowledges).
5102    ///
5103    /// Prior to this lift the `.window` field was accessed inline at
5104    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
5105    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
5106    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
5107    /// error-payload construction on refusal, and the two
5108    /// [`rate_limit_codec::render`] arms
5109    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
5110    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
5111    /// open-coded field-accesses that expressed no compile-time link
5112    /// back to the typed sub-struct axis. A future extension of the
5113    /// `:window` axis to a richer author surface — a per-`:contratos`-
5114    /// edge window override the operator pins through a future
5115    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
5116    /// acknowledges, a per-cluster window-default overlay the M4 CR
5117    /// materializer resolves per-CR, a promotion of the plain
5118    /// `Duration` refill period to a richer
5119    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
5120    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
5121    /// axis comes into scope, an addition of a `"d"` day suffix once
5122    /// Envoy's `rate_limit_action` grows daily-bucket support — would
5123    /// have had to be threaded through every open-coded copy in
5124    /// lockstep or the validate gate, the codec's render path, and
5125    /// the future M4 emit path would silently disagree on which
5126    /// refill period a given [`RateLimit`] resolves to (an author's
5127    /// `:rate-limit "100/s"` would satisfy validate while the render
5128    /// / emit paths silently read a drifted other value, or vice
5129    /// versa: a validated typed slot would land at the emit boundary
5130    /// as a limiter whose refill period is structurally so long that
5131    /// no realistic per-edge traffic shape stays inside the token
5132    /// budget). Lifting the resolution to a typed method on the
5133    /// substrate primitive means every downstream consumer of the
5134    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
5135    /// reaches for exactly one typed dispatch — the resolver's
5136    /// accept-set migrates as a unit on any future axis addition.
5137    ///
5138    /// Second sub-struct scalar accessor on the `RateLimit` axis —
5139    /// sibling in shape to the just-landed [`RateLimit::rate`]
5140    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
5141    /// required-axis, extended onto the per-sub-struct
5142    /// required-`Duration` axis; closes the last unlifted
5143    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
5144    /// per-sub-struct accessor coverage is now complete across both
5145    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
5146    /// the substrate primitive, thin projections at each consumer"
5147    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
5148    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
5149    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
5150    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
5151    /// [`Membro::nome`] (4a32abf),
5152    /// [`Membro::versao_requirement`] (a40b0e3),
5153    /// [`Entrada::destination`] (6db982c) accessors carry on their
5154    /// respective per-mesh-slot-atom scalar-value axes. Named
5155    /// `window()` to match the storage field's name; the accessor's
5156    /// identity maps onto the canonical MESH-COMPOSITION §III.2
5157    /// vocabulary the slot's docstring already carries.
5158    #[must_use]
5159    pub const fn window(&self) -> Duration {
5160        self.window
5161    }
5162
5163    /// Recognize this rate-limit's `:window` as a canonical
5164    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
5165    /// exactly matches one of the three closed-set arm-Durations
5166    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
5167    /// non-canonical magnitude the codec's round-trip would break on
5168    /// (sub-second residue, or a second-magnitude outside the set
5169    /// [`RateLimitUnit::ALL`] enumerates).
5170    ///
5171    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
5172    /// returns `Some` here — the validate gate's
5173    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
5174    /// rejects every window this accessor returns `None` on. Downstream
5175    /// consumers past validate (the codec's [`rate_limit_codec::render`]
5176    /// path, the future M4 per-Aplicacao Envoy config reconciler's
5177    /// materialization pass, the future per-`:contratos`-edge rate-limit-
5178    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
5179    /// acknowledges) that read the typed unit off a validated slot can
5180    /// pattern-match on the returned `Some` without re-checking
5181    /// canonicality at the consumer layer — the typed enum surface is
5182    /// the load-bearing carrier of the canonicality invariant.
5183    ///
5184    /// Preferred over the free [`is_canonical_rate_limit_window`]
5185    /// module-private helper at any call site that has the typed
5186    /// [`RateLimit`] in hand (the codec's `render` arm at
5187    /// [`rate_limit_codec::render`], the validate gate's canonical-form
5188    /// arm in [`AplicacaoSpec::validate_politicas`], any future
5189    /// per-`:contratos` edge-override overlay resolver): those consumers
5190    /// reach for the typed enum without going through the
5191    /// `.window()` scalar-projection layer, and get the enum value
5192    /// directly (which the codec's render arm can then format via
5193    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
5194    /// "typed sub-struct scalar accessor, one dispatch on the substrate
5195    /// primitive" discipline the sibling [`RateLimit::rate`] and
5196    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
5197    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
5198    /// projection axis (the third scalar accessor on the [`RateLimit`]
5199    /// axis, first typed-enum-return projection).
5200    ///
5201    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
5202    /// the canonical [`RateLimitUnit`] arm now carries the same
5203    /// `const`-eval-surface posture the sibling `pub const fn`
5204    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
5205    /// this typed sub-struct already carry, composing through the
5206    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
5207    /// reverse-resolver in `const` context. Any downstream substrate-
5208    /// side `const`-context consumer of the typed unit (a module-scope
5209    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
5210    /// invariant pin on a typed fixture, a future M4 admission-webhook
5211    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
5212    /// resolver over a typed [`RateLimit`], any future `const fn`
5213    /// per-`:contratos`-edge rate-limit-override overlay resolver over
5214    /// the substrate primitive) now reaches the same typed dispatch on
5215    /// the substrate primitive at const-eval time as at runtime.
5216    ///
5217    /// Pinned load-bearing at the substrate-primitive level by
5218    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
5219    /// eval-surface pin via `const fn` wrapper).
5220    #[must_use]
5221    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
5222        RateLimitUnit::from_window(self.window)
5223    }
5224}
5225
5226/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
5227/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
5228/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
5229///
5230/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
5231/// the `:politicas :rate-limit` unit surface reads from
5232/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
5233/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
5234/// [`is_canonical_rate_limit_window`] predicate the
5235/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
5236/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
5237/// projection) now lives inside this typed enum's `match self` arms — a
5238/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
5239/// `rate_limit_action` grows daily-bucket support) is one new variant
5240/// plus the exhaustiveness arms on the four methods, so every consumer
5241/// picks it up by compile-time construction rather than a runtime
5242/// table-scan miss.
5243///
5244/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
5245/// scanned via `find_map` at every projection call — an untyped runtime
5246/// walk that carried no compile-time link between the parse arm's
5247/// accepted suffixes, the render arm's emitted suffixes, and the
5248/// validate gate's accepted windows. A future rate-limit-unit addition
5249/// that landed one row without threading through the other consumers
5250/// (or a copy-paste flip that collapsed two rows onto one suffix) would
5251/// silently split the accepted-set across the three consumers — the
5252/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
5253/// for a 24h window that parse can't round-trip, the validate gate
5254/// misses one canonical window. Lifting the pairs onto a typed
5255/// closed-set enum with exhaustive `match` arms makes any such
5256/// half-landed extension a caixa-core build error (the compiler enforces
5257/// arm coverage on every method), not a silent per-consumer drift
5258/// surfacing at apply time. Same "closed-set typed-enum discriminator"
5259/// discipline the sibling [`PlacementStrategy`] (cc8f749),
5260/// [`crate::supervisor::RestartStrategy`],
5261/// [`crate::supervisor::RestartPolicy`],
5262/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
5263/// closed-set typed enums carry on their respective closed-set axes —
5264/// extended onto the seventh closed-set typed-enum discriminator axis
5265/// on the caixa typed surface (the `:politicas :rate-limit :window`
5266/// canonical-unit axis).
5267#[derive(
5268    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5269)]
5270pub enum RateLimitUnit {
5271    /// 1-second window — canonical author-surface suffix `"s"`
5272    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
5273    /// with a 1s magnitude.
5274    Second,
5275    /// 1-minute window — canonical author-surface suffix `"m"`
5276    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
5277    /// with a 60s magnitude.
5278    Minute,
5279    /// 1-hour window — canonical author-surface suffix `"h"`
5280    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
5281    /// with a 3600s magnitude.
5282    Hour,
5283}
5284
5285impl RateLimitUnit {
5286    /// Exhaustive iteration surface for every consumer that reads the
5287    /// full canonical-unit set (the byte-parity witness against the
5288    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
5289    /// webhook's accepted-suffix listing in its rejection body, any
5290    /// future round-trip fuzz harness). A future variant addition to
5291    /// [`RateLimitUnit`] extends this slice as a single edit and every
5292    /// consumer picks up the new entry by construction — the compiler-
5293    /// checked exhaustiveness on the sibling method `match` arms is the
5294    /// build-time guarantee that no arm forgets to grow.
5295    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
5296
5297    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
5298    /// string every `<n>/<unit>` rate-limit shape carries after its
5299    /// `/` separator. The single source of truth the codec's parse and
5300    /// render arms both dispatch on: the parse arm matches an incoming
5301    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
5302    /// output; the render arm emits the entry's `as_suffix` verbatim
5303    /// after the rate magnitude.
5304    #[must_use]
5305    pub const fn as_suffix(self) -> &'static str {
5306        match self {
5307            Self::Second => "s",
5308            Self::Minute => "m",
5309            Self::Hour => "h",
5310        }
5311    }
5312
5313    /// Canonical `Duration` for this unit — the token-bucket refill
5314    /// period the [`RateLimit::window`] axis carries when the surrounding
5315    /// slot's `:rate-limit` author surface named this unit.
5316    #[must_use]
5317    pub const fn window(self) -> Duration {
5318        Duration::from_secs(match self {
5319            Self::Second => 1,
5320            Self::Minute => 60,
5321            Self::Hour => 3_600,
5322        })
5323    }
5324
5325    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
5326    /// `None` when `suffix` is outside the closed-set arm-string set
5327    /// [`Self::as_suffix`] emits. The single `str → Self` projection
5328    /// [`rate_limit_codec::parse`] consumes.
5329    #[must_use]
5330    pub fn from_suffix(suffix: &str) -> Option<Self> {
5331        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
5332    }
5333
5334    /// Recognize a canonical rate-limit `Duration` as one of the three
5335    /// arms, or `None` when `window` carries sub-second residue or a
5336    /// second-magnitude outside the closed-set arm-window set
5337    /// [`Self::window`] emits. The single `Duration → Self` projection
5338    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
5339    /// both consume.
5340    ///
5341    /// `pub const fn` — the reverse `Duration → Self` projection now
5342    /// carries the same `const`-eval-surface posture the sibling
5343    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
5344    /// projection accessors on this closed-set typed enum already
5345    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
5346    /// typed-`RateLimit`-projection sibling composes through in `const`
5347    /// context. Routes byte-for-byte through the peer `pub const fn`
5348    /// [`Self::window`] canonical-`Duration` projection so any future
5349    /// arm-magnitude edit on the sibling accessor reaches this reverse
5350    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
5351    /// per-arm probes each dispatch through one `pub const fn` on the
5352    /// substrate primitive rather than a hand-authored per-arm second-
5353    /// magnitude literal that would silently drift on any future
5354    /// [`Self::window`] arm-magnitude edit.
5355    ///
5356    /// Prior to the `const` lift the body dispatched through
5357    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
5358    /// iterator-driven linear scan whose iterator methods
5359    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
5360    /// `PartialEq` dispatch each carry non-`const` bounds on stable
5361    /// Rust 1.94, so any downstream substrate-side `const`-context
5362    /// consumer of the reverse resolver (a module-scope
5363    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
5364    /// invariant pin on a typed fixture, a future M4
5365    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
5366    /// webhook `const fn` per-`:politicas` canonical-window floor over a
5367    /// typed [`RateLimit`] scalar, any future `const fn`
5368    /// per-`:contratos`-edge rate-limit-override overlay resolver over
5369    /// the substrate primitive that wants to fan on the canonical unit
5370    /// at compile time) surfaced as a downstream E0015 far from the
5371    /// resolver's own declaration. The `pub const fn` posture closes
5372    /// the drift structurally at caixa-core build time.
5373    ///
5374    /// Pinned load-bearing at the substrate-primitive level by
5375    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
5376    /// eval-surface pin via `const fn` wrapper) and
5377    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
5378    /// (composition-witness pin against the peer `Self::window` scalar
5379    /// dispatch).
5380    #[must_use]
5381    pub const fn from_window(window: Duration) -> Option<Self> {
5382        if window.subsec_nanos() != 0 {
5383            return None;
5384        }
5385        // Route through the peer `pub const fn` [`Self::window`]
5386        // canonical-`Duration` projection so any future arm-magnitude
5387        // edit on the sibling accessor reaches this reverse resolver by
5388        // construction — the per-arm `secs` comparison keys off
5389        // `Duration::as_secs` (`pub const fn`), not a hand-authored
5390        // per-arm second-magnitude literal that would silently drift.
5391        let secs = window.as_secs();
5392        if secs == Self::Second.window().as_secs() {
5393            Some(Self::Second)
5394        } else if secs == Self::Minute.window().as_secs() {
5395            Some(Self::Minute)
5396        } else if secs == Self::Hour.window().as_secs() {
5397            Some(Self::Hour)
5398        } else {
5399            None
5400        }
5401    }
5402
5403    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
5404    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
5405    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
5406    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
5407    /// consumes.
5408    ///
5409    /// The peer `Duration → &'static str` axis folded onto the substrate
5410    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
5411    /// production consumers ([`rate_limit_codec::render`] and
5412    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
5413    /// migrated (61421a6): the free helper's `Duration → &str` projection
5414    /// is now the two-step composition
5415    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
5416    /// reads through the typed accessor. This lift closes the peer
5417    /// `&str → Duration` axis by folding the vestigial module-private
5418    /// `rate_limit_window_from_unit` delegate onto this associated method
5419    /// — the codec's parse arm and every future wire-side consumer of the
5420    /// `&str → Duration` projection (a future admission-webhook that
5421    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
5422    /// before it's promoted to a validated typed slot, a future
5423    /// `feira lint` shape-probe that reads the author-surface bytes
5424    /// verbatim) now reach for exactly one typed dispatch on the
5425    /// substrate primitive.
5426    ///
5427    /// Same "closed-set typed-enum discriminator with canonical
5428    /// projections per axis" discipline the sibling [`Self::as_suffix`]
5429    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
5430    /// methods carry — this associated method closes the fifth (and last
5431    /// unlifted) projection axis on the arm-table, so the closed-set enum
5432    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
5433    /// consumer of the `:politicas :rate-limit :window` axis reaches
5434    /// through. A future rate-limit-unit addition (a `"d"` day suffix
5435    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
5436    /// `"ms"` sub-second window once high-throughput per-edge policies
5437    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
5438    /// variant plus one arm per method — the compiler enforces
5439    /// exhaustiveness on every consumer's `match self` arms and picks
5440    /// the new unit up by construction across all five projections.
5441    #[must_use]
5442    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
5443        Self::from_suffix(suffix).map(Self::window)
5444    }
5445}
5446
5447/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
5448/// every consumer that formats a canonical rate-limit unit as user-
5449/// facing text (future M4 admission-webhook rejection bodies naming
5450/// the accepted-suffix set, future `feira app graph` per-`:politicas`
5451/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
5452/// codec's parse arm accepts and the render arm emits. Same
5453/// as_str-through-Display convergence discipline the sibling
5454/// [`PlacementStrategy`], [`crate::CaixaKind`],
5455/// [`crate::supervisor::RestartStrategy`], and
5456/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
5457impl std::fmt::Display for RateLimitUnit {
5458    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5459        f.write_str(self.as_suffix())
5460    }
5461}
5462
5463/// Substrate-canonical [`AsRef<str>`] projection on the M3
5464/// `:politicas :rate-limit` closed-set typed unit-suffix enum —
5465/// routes through the same [`RateLimitUnit::as_suffix`] `pub const fn`
5466/// scalar accessor the paired [`std::fmt::Display`] impl already
5467/// delegates through, so any future consumer that binds a
5468/// [`RateLimitUnit`] through the standard-library `impl AsRef<str>`
5469/// bound (a [`std::process::Command::arg`] shell-out that composes the
5470/// canonical suffix into an Envoy sidecar config-CLI's per-`:politicas`
5471/// `--rate-limit-unit <s|m|h>` arg on the future
5472/// `CiliumClusterwideEnvoyConfig` overlay MESH-COMPOSITION §III.2 #3
5473/// names, a `tracing::field::Value::Str`-arm structured-log recorder
5474/// on the future `app-operator`'s per-`:politicas :rate-limit`
5475/// reconcile step, a [`std::collections::HashMap`] lookup keyed on
5476/// the canonical suffix through `map.get::<str>(unit.as_ref())` on a
5477/// future per-unit token-bucket-refill dispatch table the future M4
5478/// admission-webhook rejection body composes) reaches the paired
5479/// `"s"` / `"m"` / `"h"` byte-string through one substrate-primitive
5480/// dispatch rather than an open-coded `.as_suffix()` re-inlining at
5481/// every wire-up.
5482///
5483/// Deliberately routes through the canonical suffix axis, not the
5484/// second-magnitude [`RateLimitUnit::window`] axis — `AsRef<str>` and
5485/// [`fmt::Display`] land on the same author-surface-canonical byte-
5486/// string the codec's parse and render arms both dispatch on, while
5487/// the token-bucket-refill period stays reachable only through the
5488/// explicit [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`]
5489/// paths.
5490///
5491/// Same "route the trait impl through the substrate-primitive
5492/// accessor" discipline the sibling [`crate::CaixaVersion`]
5493/// [`AsRef<str>`] impl (16d5c7e), the paired M2
5494/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
5495/// (63eb1a4), the paired M2 [`crate::supervisor::RestartPolicy`]
5496/// [`AsRef<str>`] impl (419ea81), the M3
5497/// [`PlacementStrategy`] [`AsRef<str>`] impl (d86edd2), and the
5498/// top-level [`crate::CaixaKind`] [`AsRef<str>`] impl (cd2091f) carry
5499/// — closes the substrate primitive's [`AsRef<str>`] projection axis
5500/// onto the last remaining closed-set typed enum with a
5501/// [`fmt::Display`] surface, so every closed-set typed enum / newtype
5502/// on the caixa surface (top-level `:kind`, both M2
5503/// `:supervisor`-slot per-child and sibling-restart typed enums, the
5504/// M3 `:placement :estrategia` typed enum, the M3
5505/// `:politicas :rate-limit` unit-suffix typed enum, and the `:versao`
5506/// typed newtype) now carries the paired [`AsRef<str>`] +
5507/// [`fmt::Display`] + `as_*` triple through one lifted-const family.
5508///
5509/// Pinned load-bearing by
5510/// [`tests::rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`]
5511/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5512/// three-arm closed set) and
5513/// [`tests::rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`]
5514/// (three-path convergence: `AsRef<str>` + `Display` + `as_suffix`
5515/// all resolve to the same byte-string per arm) — any future silent
5516/// detour that routes the impl through a divergent projection (a
5517/// per-arm inline `match self { … }` re-inlining that opens a compile-
5518/// time link to the un-lifted arm-literal, a swap onto the
5519/// second-magnitude [`RateLimitUnit::window`] axis that would collide
5520/// the canonical-suffix / token-bucket-refill two-axis split) trips at
5521/// caixa-core test time under `assert_eq!` rather than at a downstream
5522/// `impl AsRef<str>`-bound consumer's silent split.
5523impl AsRef<str> for RateLimitUnit {
5524    fn as_ref(&self) -> &str {
5525        self.as_suffix()
5526    }
5527}
5528
5529/// Trait-idiomatic reverse projection on the M3-mesh-primitive-defining
5530/// [`RateLimitUnit`] closed-set typed enum — routes byte-for-byte through
5531/// the paired substrate-primitive [`RateLimitUnit::from_suffix`]
5532/// `Option<Self>` accessor so every future consumer that binds a
5533/// canonical `:politicas :rate-limit` unit-suffix byte-string through the
5534/// standard-library `.try_into()` / [`TryFrom`] axis (a future
5535/// `feira app policy --rate-limit-unit <s|m|h>` CLI arg-parse that
5536/// composes into `let unit: RateLimitUnit = s.try_into()?`, a future
5537/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook that folds a
5538/// `spec.politicas.rateLimit.unit: String` field through
5539/// `RateLimitUnit::try_from(&s)?`, a generic `<T: TryFrom<&str>>`-bound
5540/// loader over any of the substrate's closed-set typed enums) reaches
5541/// the same three-arm accept-set the sibling
5542/// [`RateLimitUnit::from_suffix`] resolver parses through and the sibling
5543/// [`RateLimitUnit::as_suffix`] emits, rather than an open-coded per-arm
5544/// `match s { "s" => …, "m" => …, "h" => …, _ => … }` cascade whose
5545/// arm-set has no compile-time link back to the substrate primitive.
5546///
5547/// Complements the pre-existing forward-projection triple
5548/// ([`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`])
5549/// with the paired trait-idiomatic reverse-projection axis: Rust-side
5550/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
5551/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so
5552/// a caller who can project *out to* a `&str` can also project *in
5553/// from* one. The [`TryFrom<&str>`] axis is deliberately chosen over
5554/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
5555/// lint the sibling method-named [`RateLimitUnit::from_suffix`] would
5556/// trigger under a `FromStr` impl (the same design tradeoff the peer
5557/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
5558/// [`PlacementStrategy`] (6fd00cd), [`crate::supervisor::RestartStrategy`]
5559/// (5b828ed), [`crate::supervisor::RestartPolicy`] (6fdd0d9), and
5560/// [`WitShape`] (5472902) blocks note) — this impl closes the trait-
5561/// idiomatic reverse axis without disturbing the method-named
5562/// `from_suffix` shape the peer closed-set typed enums already carry.
5563///
5564/// `type Error = ()` matches the sibling [`RateLimitUnit::from_suffix`]'s
5565/// `Option<Self>` return-shape's deliberate deferral of error typing:
5566/// the caller picks the diagnostic form appropriate for its use site (a
5567/// future `feira app policy --rate-limit-unit` arg-parse composes its
5568/// own per-verb "unknown rate-limit unit: <arg> — accepted: {…}"
5569/// message enumerating [`RateLimitUnit::ALL`], a future M4 admission-
5570/// webhook rejection body wraps the `Err(())` outcome with the accepted-
5571/// set enumeration for operator diagnostics, a `Result::map_err` at the
5572/// call site lifts the unit-error to a per-verb error type). Same shape
5573/// the peer sibling reverse-projection axes carry.
5574///
5575/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
5576/// set the [`RateLimitUnit::from_suffix`] resolver dispatches through,
5577/// so any future arm addition (a `"d"` day suffix once Envoy's
5578/// `rate_limit_action` grows daily-bucket support, a `"ms"` sub-second
5579/// window once high-throughput per-edge policies come into scope per
5580/// MESH-COMPOSITION §III.2 #3 — both trajectory items the sibling
5581/// [`RateLimitUnit::window_from_suffix`] doc block already names) grows
5582/// the trait-idiomatic axis by construction — one caixa-core edit on
5583/// [`RateLimitUnit::from_suffix`] extends both the method-named reverse
5584/// projection every existing consumer keys off and the trait-idiomatic
5585/// reverse projection this impl exposes, without a coordinated rewrite
5586/// across every future `TryFrom<&str>`-bound consumer's arm-set.
5587///
5588/// Extends the substrate-wide closed-set-enum trait-idiomatic reverse-
5589/// projection family ([`crate::CaixaKind`] via 3c83606,
5590/// [`crate::CaixaDialeto`] via bf33136, [`PlacementStrategy`] via
5591/// 6fd00cd, [`crate::supervisor::RestartStrategy`] via 5b828ed,
5592/// [`crate::supervisor::RestartPolicy`] via 6fdd0d9, [`WitShape`] via
5593/// 5472902) onto the third M3-mesh-primitive-defining slot enum on the
5594/// caixa surface — the `:politicas :rate-limit` unit-suffix closed set
5595/// the caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
5596/// `local_rate_limit.token_bucket.fill_interval` overlay emission, and
5597/// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-
5598/// webhook's per-`:politicas` accept-set validation.
5599///
5600/// Pinned load-bearing by
5601/// [`tests::rate_limit_unit_try_from_str_routes_through_from_suffix_accessor`]
5602/// (byte-parity pin against [`RateLimitUnit::from_suffix`] across the
5603/// three-arm accept-set) and
5604/// [`tests::rate_limit_unit_try_from_str_rejects_unknown_byte_strings`]
5605/// (rejection witness against silent accept-set widening).
5606impl TryFrom<&str> for RateLimitUnit {
5607    type Error = ();
5608
5609    fn try_from(s: &str) -> Result<Self, Self::Error> {
5610        Self::from_suffix(s).ok_or(())
5611    }
5612}
5613
5614/// Standard-library trait-idiomatic forward projection on the
5615/// [`RateLimitUnit`] closed-set typed enum. Routes byte-for-byte through
5616/// the paired substrate-primitive [`RateLimitUnit::as_suffix`]
5617/// `pub const fn` accessor so `<&'static str>::from(unit)` /
5618/// `unit.into::<&'static str>()` reaches the same three-arm `"s"` /
5619/// `"m"` / `"h"` canonical-suffix emit-set the sibling method-named
5620/// accessor dispatches through and the sibling
5621/// [`std::fmt::Display for RateLimitUnit`] / [`AsRef<str> for RateLimitUnit`]
5622/// impls also route through.
5623///
5624/// Extends the substrate-wide closed-set-enum trait-idiomatic
5625/// forward-projection family
5626/// ([`crate::supervisor::RestartStrategy`] via 523157d,
5627/// [`crate::supervisor::RestartPolicy`] via 9fb37d0,
5628/// [`crate::CaixaKind`] via edb827b,
5629/// [`crate::CaixaDialeto`] via c189a6f,
5630/// [`PlacementStrategy`] via afa3562,
5631/// [`WitShape`] via 56998ec) onto the third
5632/// M3-mesh-primitive-defining slot enum on the caixa surface — the
5633/// `:politicas :rate-limit` canonical-unit-suffix closed set the
5634/// caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
5635/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
5636/// Pairs with the sibling [`TryFrom<&str> for RateLimitUnit`] impl
5637/// (bf78400) to close the two-way `Self ↔ &'static str` round-trip on
5638/// the trait-idiomatic axis pair, mirroring the pre-existing
5639/// method-named [`RateLimitUnit::as_suffix`] +
5640/// [`RateLimitUnit::from_suffix`] pair on the substrate-primitive axis
5641/// pair.
5642///
5643/// Return type is `&'static str` by construction — every
5644/// [`RateLimitUnit::as_suffix`] arm resolves to an inline
5645/// `"s"` / `"m"` / `"h"` `&'static str` literal, so the trait's
5646/// return-type promise is upheld structurally without a
5647/// [`String::leak`] cast or a per-arm inline literal outside the paired
5648/// [`RateLimitUnit::as_suffix`] dispatch.
5649///
5650/// Deliberately routes through the canonical-suffix axis, not the
5651/// second-magnitude [`RateLimitUnit::window`] axis — every closed-set
5652/// forward-projection path on the caixa surface lands on the same
5653/// author-surface-canonical byte-string the codec's parse and render
5654/// arms both dispatch on, while the token-bucket-refill period stays
5655/// reachable only through the explicit [`RateLimitUnit::window`] /
5656/// [`RateLimitUnit::from_window`] paths.
5657///
5658/// The paired [`RateLimitUnit::as_suffix`] accessor's three-arm emit-set
5659/// is the single source of truth — every future arm addition (a `"d"`
5660/// day suffix once Envoy's `rate_limit_action` grows daily-bucket
5661/// support, a `"ms"` sub-second window once high-throughput per-edge
5662/// policies come into scope per MESH-COMPOSITION §III.2 #3 — both
5663/// trajectory items the sibling [`RateLimitUnit::window_from_suffix`]
5664/// doc block already names) grows the trait-idiomatic forward axis by
5665/// construction: one caixa-core edit on [`RateLimitUnit::as_suffix`]
5666/// extends every one of the sibling forward-projection paths
5667/// ([`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`]
5668/// itself, and this [`From<Self> for &'static str`]) without a
5669/// coordinated rewrite across every future `Into<&'static str>`-bound
5670/// consumer's arm-set.
5671///
5672/// Pinned load-bearing by
5673/// [`tests::rate_limit_unit_from_into_static_str_routes_through_as_suffix_accessor`]
5674/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5675/// three-arm emit-set, plus a `const`-context materialization witness
5676/// for the `&'static str` lifetime promise routed through the paired
5677/// [`RateLimitUnit::as_suffix`] `pub const fn` accessor, plus a paired
5678/// `.into()` shape assertion covering the blanket-derived
5679/// `Into<&'static str>` shape) and
5680/// [`tests::rate_limit_unit_from_into_static_str_and_as_suffix_partition_the_emit_set`]
5681/// (partition pin asserting `<&'static str as
5682/// From<RateLimitUnit>>::from` and [`RateLimitUnit::as_suffix`] agree on
5683/// every arm, plus a two-way direct round-trip witness through the
5684/// paired trait-idiomatic [`TryFrom<&str>`] axis that closes the
5685/// two-way `Self ↔ &'static str` round-trip on the trait-idiomatic axis
5686/// pair — the emit-side [`RateLimitUnit::as_suffix`] and the parse-side
5687/// [`RateLimitUnit::from_suffix`] dispatch on the same three inline
5688/// canonical-suffix byte-strings by construction, so round-tripping
5689/// composes the two trait impls directly).
5690impl From<RateLimitUnit> for &'static str {
5691    fn from(unit: RateLimitUnit) -> &'static str {
5692        unit.as_suffix()
5693    }
5694}
5695
5696/// Trait-idiomatic *forward* projection on [`RateLimitUnit`] from a
5697/// *borrowed* input onto the `&'static str` axis — the borrowed-input
5698/// companion to the paired owned-input [`From<RateLimitUnit> for &'static
5699/// str`] impl immediately above. Routes byte-for-byte through the same
5700/// substrate-primitive [`RateLimitUnit::as_suffix`] `pub const fn`
5701/// accessor so every consumer that binds a `&RateLimitUnit` through the
5702/// standard-library `.into()` / [`From<&Self> for &'static str`] axis (a
5703/// `RateLimitUnit::ALL.iter().map(<&'static str>::from).collect::<Vec<_>>()`
5704/// per-arm accept-set materializer — whose iterator over
5705/// `&'static [RateLimitUnit]` yields `&RateLimitUnit`, not
5706/// `RateLimitUnit`, so the owned-input [`From<RateLimitUnit>`] axis alone
5707/// forces every call site through an explicit `.copied()` / dereference /
5708/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
5709/// projection; a future generic `<T: Copy + for<'a> Into<&'static str>>`-
5710/// bound diagnostic column over the substrate-wide closed-set typed-enum
5711/// family that walks the `iter().map(Into::into)` shape verbatim; the
5712/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
5713/// rejection body that composes the accepted-`:politicas :rate-limit`
5714/// canonical-suffix enumeration from an iterated
5715/// `RateLimitUnit::ALL.iter().map(|u| u.into())` pipe rather than a per-
5716/// arm `match u { … }` cascade; a future
5717/// `HashMap::<&'static str, RateLimitUnit>::from_iter(
5718///   RateLimitUnit::ALL.iter().map(|u| (u.into(), *u)))`-style per-unit
5719/// reverse-lookup table the sibling [`TryFrom<&str>`] impl cannot compose
5720/// without this borrowed-input axis in place) reaches the same three-arm
5721/// `"s"` / `"m"` / `"h"` canonical-suffix emit-set the paired owned-input
5722/// [`From<RateLimitUnit> for &'static str`], the sibling
5723/// [`std::fmt::Display`], [`AsRef<str>`], and [`RateLimitUnit::as_suffix`]
5724/// surfaces already return.
5725///
5726/// Eighth peer on the substrate-wide trait-idiomatic *borrowed-input*
5727/// forward-projection family opened on [`crate::dep::DepList`] (64aa742)
5728/// and extended onto [`crate::CaixaKind`] (5ab993a),
5729/// [`crate::CaixaDialeto`] (807b0b5), the paired M2 OTP-shape
5730/// [`crate::supervisor::RestartStrategy`] (e941836) and
5731/// [`crate::supervisor::RestartPolicy`] (842c7f3), and the M3
5732/// mesh-primitive slot enums [`PlacementStrategy`] (4d941d8) and
5733/// [`WitShape`] (3187bd0). Rust's `From` trait does not auto-derive the
5734/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
5735/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not exist
5736/// in `core`), so every closed-set typed enum that carries the owned-
5737/// input axis but not the borrowed-input axis forces every borrowed-input
5738/// call site through a `.copied()` / `<&'static str>::from(*unit)` /
5739/// `unit.as_suffix()` detour whose type bounds have no compile-time link
5740/// to the substrate primitive. [`RateLimitUnit`] is the *third* (and
5741/// last) M3-mesh-primitive-defining closed-set typed enum to converge
5742/// onto the substrate-wide borrowed-input campaign — the
5743/// [`PlacementStrategy`] first-mover (4d941d8) opened the M3-slot arm on
5744/// the `:placement :estrategia` axis, the [`WitShape`] follow-on
5745/// (3187bd0) closed the `:contratos :wit` census-label axis, and this
5746/// lift closes the `:politicas :rate-limit` canonical-suffix axis the
5747/// caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
5748/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
5749///
5750/// Same three-path convergence discipline as the paired owned-input impl
5751/// (this borrowed-input axis, the paired owned-input
5752/// [`From<RateLimitUnit> for &'static str`], and
5753/// [`RateLimitUnit::as_suffix`] all route through the same three-arm
5754/// inline canonical-suffix byte-strings), so a future variant rename or
5755/// per-arm serde-attribute drift reaches every one of the six sibling
5756/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
5757/// [`Self::as_suffix`], [`From<Self> for &'static str`], this
5758/// [`From<&Self> for &'static str`], and the un-`rename`d
5759/// [`serde::Serialize`] derive that also emits [`Self::as_suffix`]'s
5760/// bytes) through exactly one caixa-core edit.
5761///
5762/// Deliberately routes through the canonical-suffix axis, not the
5763/// second-magnitude [`RateLimitUnit::window`] axis — the borrowed-input
5764/// `From` lands on the same author-surface-canonical byte-string the
5765/// codec's parse and render arms both dispatch on, while the token-
5766/// bucket-refill period stays reachable only through the explicit
5767/// [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`] paths, so
5768/// the canonical-suffix / token-bucket-refill two-axis split the sibling
5769/// [`AsRef<str>`] impl already carries reaches the borrowed-input axis
5770/// by construction.
5771///
5772/// The [`RateLimitUnit::as_suffix`] emit and
5773/// [`RateLimitUnit::from_suffix`] parse share the same three inline
5774/// canonical-suffix byte-strings by construction — so the borrowed-input
5775/// forward axis and the reverse [`TryFrom<&str>`] axis compose directly
5776/// without the intermediate wire-vocab hop the peer [`crate::CaixaKind`]
5777/// axis pair requires. The round-trip witness pin below locks this
5778/// direct composition on the M3 slot enum's trait-idiomatic axis pair.
5779///
5780/// Pinned load-bearing by
5781/// [`tests::rate_limit_unit_from_borrowed_into_static_str_routes_through_as_suffix_accessor`]
5782/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5783/// three-arm emit-set via a borrowed input, plus a `const`-context
5784/// materialization witness for the `&'static str` lifetime promise, plus
5785/// a blanket `.into()` shape) and
5786/// [`tests::rate_limit_unit_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
5787/// (cross-axis partition pin against the paired owned-input
5788/// [`From<RateLimitUnit> for &'static str`] impl, plus a
5789/// `.iter().map(Into::into)` pipe witness over [`RateLimitUnit::ALL`],
5790/// plus a direct round-trip witness through [`TryFrom<&str>`] that closes
5791/// the two-way `&Self → &'static str → Self` round-trip on the M3 slot
5792/// enum's trait-idiomatic axis pair without the wire-vocab intermediate
5793/// the peer [`crate::CaixaKind`] axis pair requires).
5794impl From<&RateLimitUnit> for &'static str {
5795    fn from(unit: &RateLimitUnit) -> &'static str {
5796        unit.as_suffix()
5797    }
5798}
5799
5800/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
5801/// `:politicas :rate-limit` canonical-suffix [`RateLimitUnit`] closed-set
5802/// typed enum from an *owned* input onto the owned-[`String`] axis —
5803/// routes byte-for-byte through the substrate-primitive
5804/// [`RateLimitUnit::as_suffix`] `pub const fn` accessor so every consumer
5805/// that binds a [`RateLimitUnit`] through the standard-library `.into()` /
5806/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis reaches
5807/// the same three-arm `"s"` / `"m"` / `"h"` canonical-suffix byte-string
5808/// the paired owned-input [`From<RateLimitUnit> for &'static str`]
5809/// (7fdfbf4), the borrowed-input [`From<&RateLimitUnit> for &'static str`]
5810/// (f4b9e6b), the sibling [`std::fmt::Display`], [`AsRef<str>`], and
5811/// [`RateLimitUnit::as_suffix`] surfaces already return.
5812///
5813/// Extends the trait-idiomatic *owned-[`String`]* forward-projection
5814/// family (opened on [`crate::supervisor::RestartStrategy`] — 7baa18a —
5815/// the first-mover on the M2 OTP-shape sibling-restart-strategy axis,
5816/// extended onto [`crate::supervisor::RestartPolicy`] — 7851725 — the
5817/// second-of-two-in-M2 per-child restart-decision axis, then onto
5818/// [`crate::CaixaKind`] — 231a18c — the structurally most fundamental
5819/// closed-set fieldless typed enum on the caixa surface, then onto
5820/// [`crate::CaixaDialeto`] — 88942cd — the dialect-classification axis,
5821/// then onto [`crate::dep::DepList`] — 32b0ee8 — the two-list dep-graph
5822/// axis, then onto [`PlacementStrategy`] — 1154c2f — the first M3
5823/// mesh-primitive-defining slot enum, then onto [`WitShape`] — 79a8723 —
5824/// the second M3 mesh-primitive-defining slot enum on the caixa surface)
5825/// onto the eighth peer: the M3 mesh-primitive `:politicas :rate-limit`
5826/// canonical-suffix axis [`RateLimitUnit`] carries. Third (and last)
5827/// M3-mesh-primitive-defining closed-set typed enum to converge onto this
5828/// owned-[`String`] forward-projection campaign — the caixa-mesh renderer
5829/// keys off this axis end-to-end for per-Aplicacao Envoy
5830/// `local_rate_limit.token_bucket.fill_interval` overlay emission, so
5831/// every future consumer that promotes canonical-suffix output onto an
5832/// owned-heap-string carrier (the future M4 admission-webhook rejection
5833/// body's accepted-`:politicas :rate-limit` enumeration, a future
5834/// `HashMap::<String, RateLimitUnit>::from_iter(…)` owned-key per-unit
5835/// lookup, a future `serde_json::Value::String(unit.into())` structured-
5836/// payload composer) now reaches the substrate-primitive accessor
5837/// through one uniform trait dispatch.
5838///
5839/// Rust's standard library does not carry a blanket
5840/// `impl<T: AsRef<str>> From<T> for String` (nor an
5841/// `impl<T: fmt::Display> From<T> for String`), so every closed-set typed
5842/// enum that carries the paired [`AsRef<str>`] / [`std::fmt::Display`] /
5843/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`]
5844/// quadruple but not the owned-[`String`] axis forces every owned-string
5845/// call site through a `.to_string()` / `.as_suffix().to_owned()` /
5846/// `String::from(unit.as_suffix())` detour whose type bounds have no
5847/// compile-time link to the substrate primitive.
5848///
5849/// Same as the peer [`crate::supervisor::RestartStrategy`] /
5850/// [`crate::supervisor::RestartPolicy`] / [`crate::CaixaDialeto`] /
5851/// [`crate::dep::DepList`] / [`PlacementStrategy`] / [`WitShape`]
5852/// owned-[`String`] axis pairs (whose forward emit and reverse parse
5853/// share one vocabulary by construction), [`RateLimitUnit`]'s
5854/// [`RateLimitUnit::as_suffix`] emit and [`RateLimitUnit::from_suffix`]
5855/// parse resolve through the same three inline canonical-suffix
5856/// byte-strings by construction (there is no wire/diagnostic axis split
5857/// on this enum — both halves route through the same three `match`-arm-
5858/// inline `&'static str` values `"s"` / `"m"` / `"h"`), so the
5859/// owned-[`String`] forward projection this impl exposes composes directly
5860/// with the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on the
5861/// owned-[`String`]'s [`String::as_str`] borrow — no intermediate
5862/// wire-vocab hop like the peer [`crate::CaixaKind`] axis pair requires.
5863///
5864/// Deliberately routes through the canonical-suffix axis, not the
5865/// second-magnitude [`RateLimitUnit::window`] axis — the owned-[`String`]
5866/// `From` lands on the same author-surface-canonical byte-string the
5867/// codec's parse and render arms both dispatch on, while the token-
5868/// bucket-refill period stays reachable only through the explicit
5869/// [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`] paths, so
5870/// the canonical-suffix / token-bucket-refill two-axis split the sibling
5871/// owned-input and borrowed-input `&'static str` axes already carry
5872/// reaches the owned-[`String`] axis by construction.
5873///
5874/// The remaining seven closed-set typed enums on the caixa substrate
5875/// surface (`PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
5876/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the future
5877/// targets of this campaign — each carries the same paired [`AsRef<str>`]
5878/// / [`std::fmt::Display`] / [`From<Self> for &'static str`] /
5879/// [`From<&Self> for &'static str`] quadruple that this owned-[`String`]
5880/// axis extends onto.
5881///
5882/// Pinned load-bearing by
5883/// [`tests::rate_limit_unit_from_into_owned_string_routes_through_as_suffix_accessor`]
5884/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5885/// three-arm [`RateLimitUnit::ALL`] emit-set plus a blanket
5886/// `.into::<String>()` shape witness) and
5887/// [`tests::rate_limit_unit_from_into_owned_string_and_static_str_agree_on_every_arm`]
5888/// (cross-axis partition against the sibling owned-`&'static str` axis
5889/// and the [`ToString::to_string`] surface, a
5890/// `.iter().copied().map(String::from)` pipe witness over
5891/// [`RateLimitUnit::ALL`], plus a direct `Self → String → Self`
5892/// round-trip via [`TryFrom<&str>`] on the owned-[`String`]'s
5893/// [`String::as_str`] borrow — composes directly without the wire-vocab
5894/// intermediate hop the peer [`crate::CaixaKind`] axis pair requires).
5895impl From<RateLimitUnit> for String {
5896    fn from(unit: RateLimitUnit) -> String {
5897        unit.as_suffix().to_owned()
5898    }
5899}
5900
5901/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
5902/// projection on the M3 mesh-primitive `:politicas :rate-limit`
5903/// canonical-suffix [`RateLimitUnit`] closed-set typed enum — the fourth
5904/// (and closing) corner of the `{Self, &Self} × {&'static str, String}`
5905/// 2×2 trait-idiomatic projection family on this third (and last)
5906/// M3-mesh-primitive-defining slot enum. Routes byte-for-byte through the
5907/// substrate-primitive [`RateLimitUnit::as_suffix`] `pub const fn`
5908/// accessor (via [`str::to_owned`]) so every consumer that holds a
5909/// borrowed [`&RateLimitUnit`] and needs an owned [`String`] — a future
5910/// `serde_json::Value::String(String::from(&unit))` structured-payload
5911/// composer over a borrowed field, a future `Iterator::map` over
5912/// `&[RateLimitUnit]` that projects to owned keys through
5913/// `.iter().map(String::from)` (whose iterator yields `&RateLimitUnit`,
5914/// not `RateLimitUnit`, so the owned-input [`From<RateLimitUnit> for
5915/// String`] axis alone forces every call site through an explicit
5916/// `.copied()` / spurious [`Copy`] deref restatement rather than the
5917/// direct trait-idiomatic projection), a future
5918/// `HashMap::<String, RateLimitUnit>::from_iter` that keys off a borrowed-
5919/// iteration axis where dereferencing the unit would force an unnecessary
5920/// [`Copy`] at every step, the future M4
5921/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection body
5922/// composer that names the accepted-`:politicas :rate-limit`
5923/// canonical-suffix enumeration through an iterated
5924/// `RateLimitUnit::ALL.iter().map(String::from).collect()` pipe rather
5925/// than a per-arm cascade, the future caixa-mesh renderer per-Aplicacao
5926/// Envoy `local_rate_limit.token_bucket.fill_interval` overlay composer
5927/// whose borrowed-iteration axis over declared units projects to owned
5928/// keys by construction — reaches the same three-arm `"s"` / `"m"` /
5929/// `"h"` canonical-suffix byte-string the paired
5930/// [`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`],
5931/// and the three other trait-idiomatic forward-projection impls
5932/// ([`From<RateLimitUnit> for &'static str`],
5933/// [`From<&RateLimitUnit> for &'static str`],
5934/// [`From<RateLimitUnit> for String`]) already return.
5935///
5936/// Eighth peer on the substrate-wide trait-idiomatic *borrowed-input,
5937/// owned-`String` output* forward-projection family opened on
5938/// [`crate::supervisor::RestartStrategy`] (579385f), closed on the M2
5939/// OTP-shape sibling axis pair by [`crate::supervisor::RestartPolicy`]
5940/// (8465740), extended onto the two-list dep-graph peer by
5941/// [`crate::dep::DepList`] (e0cb617), onto the top-level
5942/// [`crate::CaixaKind`] peer by (e76436d), onto the
5943/// dialect-classification peer by [`crate::CaixaDialeto`] (d3c0d1d),
5944/// onto the first M3 mesh-slot peer by [`PlacementStrategy`] (d3dc000),
5945/// and onto the second M3 mesh-slot peer by [`WitShape`] (d638fd3) —
5946/// closes the `{Self, &Self} × {&'static str, String}` 2×2 projection
5947/// corner across the whole M3 mesh-primitive triple, keeping the M3
5948/// slot-enum sweep in lockstep with the M2 OTP-shape sibling pair's
5949/// earlier closure. Third (and last) M3-mesh-primitive-defining
5950/// closed-set typed enum to reach the 2×2-completion corner — the
5951/// [`PlacementStrategy`] first-mover (d3dc000) closed the `:placement
5952/// :estrategia` distribution-strategy axis, [`WitShape`] (d638fd3)
5953/// closed the `:contratos :wit` census-label axis, and this lift closes
5954/// the `:politicas :rate-limit` canonical-suffix axis the caixa-mesh
5955/// renderer keys off end-to-end for per-Aplicacao Envoy
5956/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
5957///
5958/// Rust's standard library does not carry a blanket
5959/// `impl<T: AsRef<str>> From<&T> for String` (nor an
5960/// `impl<T: fmt::Display> From<&T> for String`), so every closed-set
5961/// typed enum that carries the paired [`AsRef<str>`] /
5962/// [`std::fmt::Display`] / [`From<Self> for &'static str`] /
5963/// [`From<&Self> for &'static str`] / [`From<Self> for String`]
5964/// quintuple but not the borrowed-input owned-[`String`] axis forces
5965/// every borrowed-input owned-string call site through a
5966/// `unit.as_suffix().to_owned()` / `String::from(*unit)` (with a
5967/// spurious [`Copy`]) / `unit.to_string()` (through
5968/// [`std::fmt::Display`]) detour whose type bounds have no compile-time
5969/// link to the substrate primitive.
5970///
5971/// Same three-path convergence discipline as the paired owned-input
5972/// impl (this borrowed-input axis, the paired owned-input
5973/// [`From<RateLimitUnit> for String`], and [`RateLimitUnit::as_suffix`]
5974/// all route through the same three-arm inline canonical-suffix
5975/// byte-strings), so a future variant rename or per-arm serde-attribute
5976/// drift reaches every one of the paired forward-projection paths
5977/// through exactly one caixa-core edit.
5978///
5979/// Same as the peer [`crate::supervisor::RestartStrategy`] /
5980/// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`] /
5981/// [`crate::CaixaDialeto`] / [`PlacementStrategy`] / [`WitShape`]
5982/// borrowed-input owned-[`String`] axis pairs (whose forward emit and
5983/// reverse parse share one vocabulary by construction) and unlike the
5984/// peer [`crate::CaixaKind`] pair (whose forward emit lands on the
5985/// lowercase Portuguese diagnostic vocabulary while the reverse parse
5986/// lands on the `PascalCase` wire vocabulary, forcing the round-trip
5987/// through an intermediate [`crate::CaixaKind::wire_name`] hop),
5988/// [`RateLimitUnit`]'s [`RateLimitUnit::as_suffix`] emit and
5989/// [`RateLimitUnit::from_suffix`] parse resolve through the same three
5990/// inline canonical-suffix byte-strings by construction (there is no
5991/// wire/diagnostic axis split on this M3 slot enum — both halves of the
5992/// round-trip route through the same three `match`-arm-inline `&'static
5993/// str` values `"s"` / `"m"` / `"h"`), so the borrowed-input
5994/// owned-[`String`] projection this impl exposes composes directly with
5995/// the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on the
5996/// owned-[`String`]'s [`String::as_str`] borrow — no intermediate
5997/// wire-vocab hop required.
5998///
5999/// Deliberately routes through the canonical-suffix axis, not the
6000/// second-magnitude [`RateLimitUnit::window`] axis — the borrowed-input
6001/// owned-[`String`] `From` lands on the same author-surface-canonical
6002/// byte-string the codec's parse and render arms both dispatch on, while
6003/// the token-bucket-refill period stays reachable only through the
6004/// explicit [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`]
6005/// paths, so the canonical-suffix / token-bucket-refill two-axis split
6006/// the sibling axes already carry reaches the borrowed-input owned-
6007/// [`String`] axis by construction.
6008///
6009/// The remaining six closed-set typed enums on the caixa substrate
6010/// surface (`PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
6011/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
6012/// future targets of this 2×2-completion campaign — each carries the
6013/// same paired quintuple that this borrowed-input owned-[`String`] axis
6014/// extends onto.
6015///
6016/// Pinned load-bearing by
6017/// [`tests::rate_limit_unit_from_into_borrowed_owned_string_routes_through_as_suffix_accessor`]
6018/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
6019/// three-arm emit-set through the borrowed-input surface) and
6020/// [`tests::rate_limit_unit_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
6021/// (cross-axis partition pin against the paired owned-input owned-
6022/// [`String`] [`From<RateLimitUnit> for String`] impl, the paired
6023/// borrowed-input owned-[`&'static str`]
6024/// [`From<&RateLimitUnit> for &'static str`] impl, the paired owned-
6025/// input owned-[`&'static str`] [`From<RateLimitUnit> for &'static
6026/// str`] impl, and the sibling [`ToString::to_string`] surface routed
6027/// through [`std::fmt::Display`], plus a `.iter().map(String::from)`
6028/// pipe witness over [`RateLimitUnit::ALL`] (whose iterator yields
6029/// `&RateLimitUnit` by construction, so the borrowed-input owned-
6030/// [`String`] axis is what routes the pipe through the substrate-
6031/// primitive [`RateLimitUnit::as_suffix`] accessor without a spurious
6032/// [`Copy`] deref), plus a direct round-trip witness through
6033/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
6034/// borrow that closes the two-way `&Self → String → Self` round-trip
6035/// on the trait-idiomatic borrowed-input owned-[`String`] forward +
6036/// reverse axis pair — no intermediate wire-vocab hop like the peer
6037/// [`crate::CaixaKind`] axis pair requires).
6038impl From<&RateLimitUnit> for String {
6039    fn from(unit: &RateLimitUnit) -> String {
6040        unit.as_suffix().to_owned()
6041    }
6042}
6043
6044/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
6045/// `:politicas :rate-limit` canonical-suffix [`RateLimitUnit`]
6046/// closed-set typed enum from an *owned* input onto the
6047/// [`std::borrow::Cow<'static, str>`] axis — routes byte-for-byte
6048/// through the substrate-primitive [`RateLimitUnit::as_suffix`]
6049/// `pub const fn` accessor (via [`std::borrow::Cow::Borrowed`]) so
6050/// every consumer that binds a [`RateLimitUnit`] through the
6051/// standard-library `.into()` / [`From<Self> for
6052/// std::borrow::Cow<'static, str>`] (equivalently
6053/// [`Into<std::borrow::Cow<'static, str>>`]) axis reaches the same
6054/// three-arm inline `"s"` / `"m"` / `"h"` canonical-suffix byte-
6055/// string the paired [`From<RateLimitUnit> for &'static str`],
6056/// [`From<&RateLimitUnit> for &'static str`],
6057/// [`From<RateLimitUnit> for String`], and
6058/// [`From<&RateLimitUnit> for String`] 2×2 trait-idiomatic
6059/// forward-projection corners, the sibling [`std::fmt::Display`],
6060/// [`AsRef<str>`], and [`RateLimitUnit::as_suffix`] surfaces already
6061/// return, rather than an open-coded per-call-site
6062/// `std::borrow::Cow::Borrowed(unit.as_suffix())` /
6063/// `std::borrow::Cow::Owned(unit.to_string())` composition whose
6064/// type bounds have no compile-time link back to the substrate
6065/// primitive.
6066///
6067/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
6068/// [`std::borrow::Cow::Owned`] — the substrate-primitive
6069/// [`RateLimitUnit::as_suffix`] accessor's return carries the
6070/// `&'static str` lifetime by construction (each `match` arm
6071/// resolves to one of the three inline `"s"` / `"m"` / `"h"` byte-
6072/// strings with static lifetime), so the zero-alloc borrowed arm
6073/// is the type-correct projection with no runtime allocation. The
6074/// paired [`std::borrow::Cow::Owned`] arm stays reachable at the
6075/// call site through the existing [`From<RateLimitUnit> for
6076/// String`] axis composed with [`std::borrow::Cow::from`] on the
6077/// resulting owned [`String`] — a caller who chose to mutate the
6078/// projection lands on the owned arm by their own composition, not
6079/// by the substrate-primitive projection silently allocating on
6080/// their behalf.
6081///
6082/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
6083/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
6084/// From<T> for Cow<'static, str>`), so the paired sibling
6085/// [`From<RateLimitUnit> for &'static str`],
6086/// [`From<RateLimitUnit> for String`], [`AsRef<str>`], and
6087/// [`std::fmt::Display`] surfaces do not implicitly extend to a
6088/// [`Cow<'static, str>`]-bound call site — every such site is
6089/// forced through a `Cow::Borrowed(unit.as_suffix())` /
6090/// `Cow::Owned(unit.to_string())` open-code whose type bounds have
6091/// no compile-time link back to the substrate primitive until this
6092/// lift.
6093///
6094/// Third — and last — M3-mesh-primitive-defining peer on the
6095/// substrate-wide trait-idiomatic [`std::borrow::Cow<'static, str>`]
6096/// forward-projection campaign, closing the M3-mesh-shape tier of
6097/// the axis onto its final closed-set fieldless typed enum. The
6098/// [`WitShape`] `:contratos :wit` census-label first-mover (8634dec
6099/// owned-input + 25690ef borrowed-input) opened the tier on the
6100/// first M3-mesh-primitive peer; the paired [`PlacementStrategy`]
6101/// `:placement :estrategia` distribution-strategy peer (eee504d
6102/// owned-input + afdf0f4 borrowed-input) extended it onto the
6103/// second peer. The [`CaixaKind`](crate::CaixaKind) top-level
6104/// first-mover (99c1735 owned-input + d45c409 borrowed-input) opened
6105/// the axis on the structurally most fundamental closed-set
6106/// fieldless typed enum; the paired M2 OTP-shape
6107/// [`crate::supervisor::RestartStrategy`] (7dd28b3 + 9b3e4b3) and
6108/// [`crate::supervisor::RestartPolicy`] (0612398 + ee577fd) closed
6109/// the M2 OTP-shape tier. The outside-M3 substrate-wide peers
6110/// ([`crate::dep::DepList`], [`crate::CaixaDialeto`],
6111/// [`crate::render::PathShapeViolation`], and the outside-
6112/// `caixa-core` peers `InvariantKind`, `ArchVerdict`, `Severity`,
6113/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the remaining
6114/// future targets of this campaign; closing the owned-input corner
6115/// on [`RateLimitUnit`] leaves only the paired borrowed-input
6116/// [`From<&RateLimitUnit> for std::borrow::Cow<'static, str>`]
6117/// `{Self, &Self}`-closer as the last un-lifted axis on the
6118/// M3-mesh-primitive triple.
6119///
6120/// Same three-path convergence discipline as the paired sibling
6121/// [`From<RateLimitUnit> for &'static str`] /
6122/// [`From<RateLimitUnit> for String`] / [`std::fmt::Display`] /
6123/// [`AsRef<str>`] surfaces (this [`Cow<'static, str>`] axis, the
6124/// paired sibling surfaces, and [`RateLimitUnit::as_suffix`] all
6125/// route through the same three inline `"s"` / `"m"` / `"h"` byte-
6126/// strings by construction), so a future variant addition, rename,
6127/// or per-arm suffix drift reaches every forward-projection path
6128/// through exactly one caixa-core edit at the
6129/// [`RateLimitUnit::as_suffix`] `match` head.
6130///
6131/// Pinned load-bearing by
6132/// [`tests::rate_limit_unit_from_into_static_cow_str_routes_through_as_suffix_accessor`]
6133/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
6134/// against [`RateLimitUnit::as_suffix`] across the three-arm
6135/// [`RateLimitUnit::ALL`]) and
6136/// [`tests::rate_limit_unit_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
6137/// (cross-axis partition pin against the paired
6138/// [`From<RateLimitUnit> for &'static str`],
6139/// [`From<RateLimitUnit> for String`], and
6140/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
6141/// `.iter().copied().map(Cow::from)` pipe witness over
6142/// [`RateLimitUnit::ALL`] that materializes the three-arm
6143/// accept-set through the [`Cow<'static, str>`] axis alone and pins
6144/// the zero-alloc discipline on every element).
6145impl From<RateLimitUnit> for std::borrow::Cow<'static, str> {
6146    fn from(unit: RateLimitUnit) -> std::borrow::Cow<'static, str> {
6147        std::borrow::Cow::Borrowed(unit.as_suffix())
6148    }
6149}
6150
6151/// Upper-bound ceiling on the `:politicas :timeout` axis — every
6152/// validated [`MeshPolicy::timeout`] past
6153/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
6154/// (inclusive on both ends, integer-millisecond magnitudes by the
6155/// canonical-form gate immediately preceding).
6156///
6157/// The typed field is `Option<Duration>` (the zero-floor arm
6158/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
6159/// `Duration::ZERO`, and the canonical-form arm
6160/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
6161/// sub-millisecond residue), so a programmatic struct literal
6162/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
6163/// 24h) and the equivalent author-surface form
6164/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
6165/// integer-hour magnitude) both round-trip cleanly through serde — a
6166/// structurally unbounded `Duration` ceiling. A `:timeout` value far
6167/// above the documented production-playbook band (Envoy default `15s`,
6168/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
6169/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
6170/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
6171/// at `~3600s`) silently degenerates the mesh-policy contract: the
6172/// per-call deadline is structurally so long that no realistic
6173/// synchronous-`:contratos` traversal can reach it, so the typed slot
6174/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
6175/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
6176/// blocking" degenerates to a nominal-only contract on the
6177/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
6178/// the sibling `:politicas :retries` axis and the
6179/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
6180/// `:politicas :circuit-breaker :max-failures` axis — all three close
6181/// the "structurally unbounded ceiling on a typed `:politicas` axis"
6182/// footgun the prior zero-floor-and-canonical-form-only checks left
6183/// open.
6184///
6185/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
6186/// shared duration codec emits (`"<n>h"` for any integer-hour
6187/// magnitude) — every value in the canonical authoring form's
6188/// `<integer><unit>` grammar at or below this cap renders to a clean
6189/// canonical string. The cap sits an order of magnitude above every
6190/// documented production-playbook recommendation band (Envoy default
6191/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
6192/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
6193/// configured maximum (`proxy_read_timeout` typical max `3600s`),
6194/// below the clearly-pathological "effectively no timeout" floor
6195/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
6196/// want for a long-running synchronous workflow, but a hard wall above
6197/// which the mesh-level deadline is structurally a non-deadline.
6198/// Lifted as a typed `pub const` so the bound has exactly one source
6199/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6200/// materializer's admission webhook and the caixa-mesh-side
6201/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6202/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
6203/// other typed upper bound in this crate carries
6204/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
6205/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
6206/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
6207/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
6208pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
6209
6210/// Upper-bound ceiling on the `:politicas :retries` axis — every
6211/// validated [`MeshPolicy::retries`] past
6212/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
6213///
6214/// The typed slot is `Option<u32>` (`None` = no retries on transient
6215/// failure; `Some(0)` already rejected by the
6216/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
6217/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
6218/// .. }`) and the equivalent author-surface form
6219/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
6220/// serde / the codec — a structurally unbounded `u32` ceiling. The
6221/// runtime substrate that consumes the value (Envoy's
6222/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
6223/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
6224/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
6225/// admission cap is 10) translates a four-billion-retry policy into a
6226/// thundering-herd amplification vector on transient failure — the
6227/// caller's one request fans out to `retries` server-side calls per
6228/// edge per traversal, multiplying load by `(retries+1)^depth` across
6229/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
6230/// invariant "no infinite blocking" pairs with a no-runaway-amplification
6231/// invariant on the retry axis; both belong at the typed-slot layer.
6232///
6233/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
6234/// upstream mesh-policy schema that documents one) and sits above the
6235/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
6236/// every documented production playbook): a value the author can
6237/// plausibly want, but a hard wall above which the policy is
6238/// structurally a footgun. Lifted as a typed `pub const` so the bound
6239/// has exactly one source of truth — a future axis reaching for the
6240/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6241/// materializer's admission webhook, the caixa-mesh-side
6242/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
6243/// one place. Same shape every other typed upper bound in this crate
6244/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
6245/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
6246/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
6247/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
6248pub const POLICY_RETRIES_MAX: u32 = 10;
6249
6250/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
6251/// axis — every validated [`CircuitBreaker::max_failures`] past
6252/// [`AplicacaoSpec::validate_politicas`] lies in
6253/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
6254///
6255/// The typed field is `u32` (the zero-floor arm
6256/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
6257/// `0` — a breaker that trips on the first call), so a programmatic
6258/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
6259/// and the equivalent author-surface form
6260/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
6261/// cleanly through serde — a structurally unbounded `u32` ceiling. A
6262/// `max_failures` value far above the documented production-playbook
6263/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
6264/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
6265/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
6266/// typical 5–50) silently disables the breaker's protection role:
6267/// the threshold is structurally so high that no realistic
6268/// failures-per-`:window` traffic shape can reach it, so the breaker
6269/// never trips and the typed slot becomes a no-op carried on every
6270/// emitted Envoy / Cilium L7 overlay. Pairs with the
6271/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
6272/// axis — both close the "structurally unbounded `u32` ceiling on a
6273/// typed policy axis" footgun the prior zero-floor-only checks left
6274/// open.
6275///
6276/// The `1000` ceiling sits an order of magnitude above every
6277/// documented upstream production-playbook recommendation band (the
6278/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
6279/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
6280/// the clearly-pathological "effectively no protection"
6281/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
6282/// plausibly want at hyperscale, but a hard wall above which the
6283/// policy is structurally a no-op. Lifted as a typed `pub const` so
6284/// the bound has exactly one source of truth — the future M4
6285/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
6286/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
6287/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
6288/// one place. Same shape every other typed upper bound in this crate
6289/// carries ([`POLICY_RETRIES_MAX`],
6290/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
6291/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
6292/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
6293pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
6294
6295/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
6296/// every validated [`CircuitBreaker::window`] past
6297/// [`AplicacaoSpec::validate_politicas`] lies in
6298/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
6299/// integer-millisecond magnitudes by the canonical-form gate
6300/// immediately preceding).
6301///
6302/// The typed field is `Duration` (the zero-floor arm
6303/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
6304/// `Duration::ZERO`, and the canonical-form arm
6305/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
6306/// sub-millisecond residue), so a programmatic struct literal
6307/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
6308/// and the equivalent author-surface form
6309/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
6310/// integer-hour magnitude) both round-trip cleanly through serde — a
6311/// structurally unbounded `Duration` ceiling. A `:window` value far
6312/// above the documented production-playbook band (Hystrix
6313/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
6314/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
6315/// Istio `outlierDetection.interval` default `10s`, Envoy
6316/// `outlier_detection.interval` default `10s`, AWS App Mesh
6317/// circuit-breaker time-window typical `30s..=300s`) degenerates the
6318/// breaker's role: a rolling-window failure counter whose window is
6319/// hours long is operationally a lifetime counter, the breaker's
6320/// "recent failures" memory is structurally so long that transient
6321/// failures are never forgotten, and the typed slot becomes a no-op
6322/// trigger that trips once and stays tripped for the lifetime of the
6323/// component carried on every emitted Envoy / Cilium L7 overlay.
6324///
6325/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
6326/// shared duration codec emits (`"<n>h"` for any integer-hour
6327/// magnitude) — every value in the canonical authoring form's
6328/// `<integer><unit>` grammar at or below this cap renders to a clean
6329/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
6330/// cap on the first typed-`Duration` `:politicas` axis: the two
6331/// duration-typed `:politicas` axes now share a single uniform top
6332/// edge so the next typed-slot wiring (the future caixa-mesh
6333/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
6334/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
6335/// admission webhook) reaches for either field knowing the value is
6336/// in `1ms..=1h` without re-validating at the renderer layer. The cap
6337/// sits two orders of magnitude above every documented upstream
6338/// production-playbook recommendation band (Hystrix / resilience4j /
6339/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
6340/// and below the clearly-pathological "rolling window degenerates to
6341/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
6342/// author can plausibly want for a very-low-traffic long-tail
6343/// failure-detection window, but a hard wall above which the breaker's
6344/// rolling-window contract is structurally a lifetime-counter contract.
6345/// Lifted as a typed `pub const` so the bound has exactly one source
6346/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6347/// materializer's admission webhook and the caixa-mesh-side
6348/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6349/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
6350/// other typed upper bound in this crate carries
6351/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6352/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
6353/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
6354/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
6355/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
6356pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
6357
6358/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
6359/// every validated [`RateLimit::rate`] past
6360/// [`AplicacaoSpec::validate_politicas`] lies in
6361/// `1..=POLICY_RATE_LIMIT_MAX`.
6362///
6363/// The typed field is `u32` (the zero-floor arm
6364/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
6365/// zero-rate limit denies every request, the canonical "I forgot
6366/// that 0 means deny-everything" footgun), so a programmatic struct
6367/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
6368/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
6369/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
6370/// round-trip cleanly through serde — a structurally unbounded `u32`
6371/// ceiling. The runtime substrate consuming the value (Envoy's
6372/// `local_rate_limit.token_bucket.max_tokens`, the future
6373/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6374/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
6375/// rate-limit into a no-op rate-limiter: the bucket capacity is
6376/// structurally so high no realistic per-edge traffic shape can
6377/// drain it, the limiter never trips, and the typed slot becomes a
6378/// "rate-limit declared, no enforcement" footgun — the canonical
6379/// declared-but-inert shape every other `:politicas` cap arm
6380/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
6381/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
6382///
6383/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
6384/// above every documented upstream production-playbook recommendation
6385/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
6386/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
6387/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
6388/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
6389/// `limit_req_zone` typical `1..=1_000` RPS) and below the
6390/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
6391/// `u32::MAX`): a value the author can plausibly want at hyperscale
6392/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
6393/// /h-window arm), but a hard wall above which the policy is
6394/// structurally a no-op carried verbatim on every emitted Envoy /
6395/// Cilium L7 overlay. The cap brackets all three canonical windows
6396/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
6397/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
6398/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
6399/// per-endpoint API band). Lifted as a typed `pub const` so the bound
6400/// has exactly one source of truth — the future M4
6401/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
6402/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
6403/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
6404/// one place. Same shape every other typed upper bound in this crate
6405/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6406/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6407/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
6408/// [`crate::LIMITS_WALL_CLOCK_MAX`],
6409/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
6410/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
6411pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
6412
6413// `:entrada :host` total-length and per-label cap axes route through
6414// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
6415// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
6416// pair of aplicacao-private aliases the previous `validate_entrada_host`
6417// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
6418// = 63`) were structurally the same K8s Gateway API v1 Hostname
6419// admission-schema bounds — the total-length cap on the OpenAPI
6420// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
6421// same regex — that the peer axes at the caixa-core::render level pin,
6422// so hoisting both readers onto the shared lifted constants closes the
6423// third-occurrence duplication threshold structurally: the M4
6424// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
6425// label validator, the future per-`Certificate` SAN emitter, and every
6426// other per-Gateway-API-Hostname landing site reach the same one place
6427// as the `:entrada :host` gate does — no per-axis alias drift surface
6428// between them, by construction.
6429
6430/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
6431/// extractor expression — the upper bound `validate_placement_shard_key`
6432/// enforces on every well-shaped shard-key past validate. The realistic
6433/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
6434/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
6435/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
6436/// `:placement :affinity` / `:placement :clusters` identifier-shaped
6437/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
6438/// in `:shard-key`" footgun at validate time rather than at the future
6439/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
6440const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
6441
6442/// Reject `:membros :caixa` values the K8s apiserver would refuse at
6443/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
6444/// that maps the shared parser-shaped reason into the
6445/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
6446/// is self-locating (the offending `caixa:` is named verbatim) and
6447/// the author can grep their caixa.lisp for `:caixa "<name>"` and
6448/// fix it in one edit. Same diagnostic shape as
6449/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
6450/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
6451fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
6452    // Empty is already gated by `MembroCaixaEmpty` at the call site;
6453    // re-checking here keeps the predicate usable from any future
6454    // call site (the M4 CR materializer) without an empty-check
6455    // footgun. The shared
6456    // [`crate::render::require_valid_dns_1123_label`] helper brackets
6457    // the empty-first + shape cascade every peer name axis
6458    // (`:placement :clusters`, `:placement :affinity`, `:contratos
6459    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
6460    // `:upgrade-from :module`) routes through, so drift between the
6461    // eight axes' accepted DNS-1123-label sets is structurally
6462    // impossible.
6463    crate::render::require_valid_dns_1123_label(
6464        caixa,
6465        || AplicacaoError::MembroCaixaEmpty,
6466        |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
6467    )
6468}
6469
6470/// Reject `:placement :clusters` entries the K8s apiserver would refuse
6471/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
6472/// that maps the shared parser-shaped reason into the
6473/// [`AplicacaoError::PlacementClusterInvalid`] variant.
6474///
6475/// Cluster names land in DNS-1123-label territory across every consumer:
6476/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
6477/// the `lareira-fleet-programs` aggregator applies to scope programs to
6478/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
6479/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
6480/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
6481/// cluster identity the M4 CR materializer round-trips. Each apiserver-
6482/// side schema enforces the DNS-1123 label rule on admission; a
6483/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
6484/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
6485/// mistaken-identity slug) silently passes the prior empty-/duplicate-
6486/// only gate and the failure surfaces as a no-match at filter time —
6487/// the workload doesn't land in the named cluster, with no diagnostic
6488/// naming the offending `:clusters` entry. Lifting the gate to caixa-
6489/// build time mirrors the `:membros :caixa` value-shape trajectory
6490/// (3f9d7a0) on the peer name axis.
6491///
6492/// The diagnostic carries the offending `cluster:` verbatim plus a
6493/// parser-shaped `reason:` naming the specific violation, so the
6494/// author can grep their caixa.lisp for `:clusters` and fix it in
6495/// one edit. Same diagnostic shape as
6496/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
6497fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
6498    // Empty is already gated by `PlacementClusterEmpty` at the call
6499    // site; re-checking here keeps the predicate usable from any
6500    // future call site (the M4 CR materializer's per-cluster validator)
6501    // without an empty-check footgun. Routes through the shared
6502    // [`crate::render::require_valid_dns_1123_label`] gate the peer
6503    // name axes each land on.
6504    crate::render::require_valid_dns_1123_label(
6505        cluster,
6506        || AplicacaoError::PlacementClusterEmpty,
6507        |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
6508    )
6509}
6510
6511/// Reject `:placement :affinity` hints whose shape can never legitimately
6512/// land in any downstream selector or label-keyed routing axis. Thin
6513/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
6514/// shared parser-shaped reason into the
6515/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
6516/// diagnostic is self-locating (the offending `:affinity` is named
6517/// verbatim) and the author can grep their caixa.lisp for
6518/// `:affinity "<hint>"` and fix it in one edit.
6519///
6520/// The `:affinity` slot carries a placement-engine hint — canonical
6521/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
6522/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
6523/// compression overlay and the future M4 placement-engine's per-hint
6524/// routing axis. Each downstream consumer (caixa-mesh's
6525/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
6526/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6527/// `spec.placement.affinity` admission rule, the future M4 per-hint
6528/// node-affinity / pod-affinity rule generator keying off the same
6529/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
6530/// selector) requires the value to be a DNS-1123 label — K8s label
6531/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
6532/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
6533/// admission rule the apiserver enforces.
6534///
6535/// Until this gate landed an `:affinity "DataLocality"` (the canonical
6536/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
6537/// Python-module-name leak), `:affinity "data.locality"` (the
6538/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
6539/// `:affinity "data-locality-"` (boundary-hyphen violation),
6540/// `:affinity "data locality"` (paste-from-doc whitespace),
6541/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
6542/// 64-byte over-cap slug silently passed the empty-only check and the
6543/// failure surfaced as a no-match at the M3 Adaptive compression
6544/// overlay's filter time (`placement.affinity` carried a malformed
6545/// value, no node matched, the workload landed on the default
6546/// heuristic) — the canonical "declared-but-inert" footgun mirroring
6547/// the empty-:affinity / empty-shard-key / zero-:politicas /
6548/// empty-:contratos-target gates already close on every other
6549/// declare-but-no-opinion axis. Lifting the rejection to a build-time
6550/// gate closes the fifth typed slot on the Aplicacao surface to land
6551/// on the canonical DNS-1123 label floor (after the four Servico-name
6552/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
6553/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
6554/// b0e8748).
6555///
6556/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
6557/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
6558/// validated values are guaranteed-accepted by the apiserver without
6559/// re-validation at any downstream renderer or admission layer.
6560fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
6561    // Empty is gated separately at the call site for a self-locating
6562    // diagnostic; re-checking here keeps the predicate usable from any
6563    // future call site (the M4 CR materializer's per-affinity
6564    // validator) without an empty-check footgun. Routes through the
6565    // shared [`crate::render::require_valid_dns_1123_label`] gate the
6566    // peer name axes each land on.
6567    crate::render::require_valid_dns_1123_label(
6568        affinity,
6569        || AplicacaoError::PlacementAffinityEmpty,
6570        |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
6571    )
6572}
6573
6574/// Reject `:placement :shard-key` extractor expressions whose shape can
6575/// never legitimately drive the future M4 Akka-style cluster-sharding
6576/// reconciler's hash-extractor pass. Maps the per-byte / length checks
6577/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
6578/// diagnostic is self-locating (the offending `:shard-key` value is
6579/// named verbatim alongside the parser-shaped reason) and the author can
6580/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
6581/// edit.
6582///
6583/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
6584/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
6585/// expression naming the message property to hash on. The realistic
6586/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
6587/// property name; `$tenantId` — Akka entity-id placeholder;
6588/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
6589/// `${tenant}` — interpolation-style template) all sit in the printable
6590/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
6591/// multi-line blob landing in `:shard-key`, an embedded space from a
6592/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
6593/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
6594/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
6595/// check and the failure surfaces at the future M4 reconciler's hash
6596/// pass as a runtime extractor-evaluation error far from the source
6597/// `caixa.lisp`, with no field naming which member's `:shard-key`
6598/// carried the offending value.
6599///
6600/// The contract — the printable ASCII single-token intersection-floor
6601/// every Akka-style entity-id extractor implementation admits:
6602///
6603///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
6604///     peer DNS-1123-label-shaped `:placement :affinity` /
6605///     `:placement :clusters` identifier axes; realistic shard-keys sit
6606///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
6607///     blob footguns at validate time;
6608///   - every byte in the printable ASCII range `0x21..=0x7E` —
6609///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
6610///     `"$tenantId\n"` from paste-from-aligned-doc /
6611///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
6612///     `\x7F` — the canonical "embedded null from a copy-paste-binary
6613///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
6614///     un-Punycode-encoded IDN that round-trips inconsistently across
6615///     NFC/NFD normalization).
6616///
6617/// The accepted set is broader than the DNS-1123 label floor the peer
6618/// `:placement :clusters` / `:placement :affinity` axes use because the
6619/// `:shard-key` value is not a K8s `metadata.name` / label-selector
6620/// landing site; it's an extractor expression the future Akka-style
6621/// reconciler reads as a property reference. The realistic forms
6622/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
6623/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
6624/// but every Akka-style entity-id extractor parses. The
6625/// printable-ASCII-token floor accepts every shape any such extractor
6626/// would accept while rejecting the cross-implementation footguns
6627/// (whitespace breaks token boundaries; non-ASCII round-trips
6628/// inconsistently across YAML emitters and NFC/NFD normalization;
6629/// control characters silently corrupt the next read).
6630///
6631/// Until this gate landed `validate_placement` only refused the
6632/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
6633/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
6634/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
6635/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
6636/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
6637/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
6638/// control character from paste-from-binary, the 64-byte over-cap
6639/// paste-from-doc multi-line slug) silently passed validate. The future
6640/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
6641/// would then surface the malformed value either as a runtime
6642/// extractor-evaluation error (whitespace breaks the extractor's token
6643/// boundary, no match) or as a silently-different shard assignment
6644/// across YAML emitters (non-ASCII normalizes differently between the
6645/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
6646/// parser, the same entity ID maps to two distinct shards on a
6647/// re-render). Lifting the shape gate to caixa-build time makes the
6648/// extractor-floor invariant a structural property of every validated
6649/// `Placement`: every `Sharded` placement past `validate_placement` has
6650/// a `:shard-key` the future M4 reconciler can hash without
6651/// re-validating at the runtime layer.
6652///
6653/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
6654/// [`AplicacaoError::ContratoSubjectInvalid`] /
6655/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
6656/// on the peer `:contratos` payload axes — each lifts the
6657/// runtime-side parser's intersection-floor to a caixa-build-time gate,
6658/// closing the canonical "this passed validate but the runtime parser
6659/// rejected it" surprise.
6660fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
6661    // Empty is gated separately at the call site via the more
6662    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
6663    // re-checking here keeps the predicate usable from any future call
6664    // site (the M4 CR materializer's per-shard-key validator) without
6665    // an empty-check footgun.
6666    if key.is_empty() {
6667        return Err(AplicacaoError::ShardedKeyEmpty);
6668    }
6669    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
6670        return Err(AplicacaoError::shard_key_invalid(
6671            key,
6672            format!(
6673                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
6674                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
6675                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
6676                 well under 32 bytes, this length suggests a paste-from-doc \
6677                 multi-line blob landed in `:shard-key` instead of a single-token \
6678                 extractor expression)",
6679                key.len()
6680            ),
6681        ));
6682    }
6683    for &b in key.as_bytes() {
6684        if (0x21..=0x7E).contains(&b) {
6685            continue;
6686        }
6687        let reason = if b == b' ' {
6688            "contains a space (Akka-style entity-id extractor expressions are \
6689             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
6690             whitespace breaks the extractor's token boundary at the runtime layer, \
6691             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
6692             a multi-token blob in one `:shard-key` slot)"
6693                .to_string()
6694        } else if b == b'\t' {
6695            "contains a tab character (paste-from-aligned-doc footgun; the \
6696             Akka-style entity-id extractor reads `:shard-key` as a single-token \
6697             reference, embedded whitespace breaks the token boundary at the \
6698             runtime hash-extractor pass)"
6699                .to_string()
6700        } else if b == b'\n' || b == b'\r' {
6701            format!(
6702                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
6703                 paste-from-multiline-doc footgun; the Akka-style entity-id \
6704                 extractor reads `:shard-key` as a single-token reference, embedded \
6705                 newlines either truncate the value at the YAML emitter layer or \
6706                 break the token boundary at the runtime hash-extractor pass)"
6707            )
6708        } else if b < 0x20 || b == 0x7F {
6709            format!(
6710                "contains control character 0x{b:02x} (the canonical \
6711                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
6712                 control characters silently corrupt round-trip serialization \
6713                 across YAML emitters and break the runtime hash-extractor's \
6714                 single-token parser)"
6715            )
6716        } else {
6717            format!(
6718                "contains non-ASCII byte 0x{b:02x} (the canonical \
6719                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
6720                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
6721                 across YAML emitter implementations — the same entity ID can \
6722                 silently map to two distinct shards on a re-render. Use a \
6723                 printable-ASCII extractor expression like `tenantId`, \
6724                 `$tenantId`, or `metadata.tenantId`)"
6725            )
6726        };
6727        return Err(AplicacaoError::shard_key_invalid(key, reason));
6728    }
6729    Ok(())
6730}
6731
6732/// Reject `:contratos :de` / `:contratos :para` values whose shape
6733/// can never legitimately match a validated `:membros :caixa`. Thin
6734/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
6735/// shared parser-shaped reason into the
6736/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
6737/// diagnostic is self-locating (which slot — `:de` or `:para` — and
6738/// the offending value verbatim) and the author can grep their
6739/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
6740/// one edit.
6741///
6742/// Until this gate landed an empty or DNS-1123-malformed `:de` /
6743/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
6744/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
6745/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
6746/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
6747/// un-Punycode-encoded IDN) silently passed the per-axis check and
6748/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
6749/// membership lookup — diagnostic-framed as "this caixa is not in
6750/// `:membros`" when the root cause is "this `:de` value is not a
6751/// well-shaped Servico-name identifier and could never legitimately
6752/// match any validated member". Because every `:membros :caixa` is
6753/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
6754/// `names` HashSet structurally never contains an empty / malformed
6755/// string, so the membership lookup arm misframes every empty /
6756/// malformed input. Lifting the shape arm ahead of the lookup
6757/// preserves the legitimate `ContratoMemberMissing` arm (a
6758/// well-shaped `:de` that simply isn't in `:membros` — a phantom
6759/// reference) while routing every structurally-impossible-to-match
6760/// input through the narrower self-locating shape diagnostic.
6761///
6762/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
6763/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
6764/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
6765/// to land on the canonical [`crate::render::is_dns_1123_label`]
6766/// floor. The `slot: &'static str` field carries the kebab-case
6767/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
6768/// per-callback-slot diagnostic shape and the
6769/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
6770/// (85f102c) cross-list-tag pattern.
6771fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
6772    // Routes through the shared
6773    // [`crate::render::require_valid_dns_1123_label`] gate the peer
6774    // name axes each land on. The `slot: &'static str` field flows
6775    // through both error variants so the diagnostic names which
6776    // per-edge axis (`:de` vs `:para`) the offending value came from.
6777    crate::render::require_valid_dns_1123_label(
6778        caixa,
6779        || AplicacaoError::contrato_caixa_empty(slot),
6780        |reason| AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
6781    )
6782}
6783
6784/// Reject `:entrada :para` values whose shape can never legitimately
6785/// match a validated `:membros :caixa`. Thin wrapper around
6786/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
6787/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
6788/// variant, so the diagnostic is self-locating (the offending
6789/// `:entrada :para` value is named verbatim) and the author can grep
6790/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
6791///
6792/// Until this gate landed an empty or DNS-1123-malformed `:entrada
6793/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
6794/// ADR typo, `:para "my_cart"` the Python-module-name leak,
6795/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
6796/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
6797/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
6798/// silently passed the per-axis check and surfaced as
6799/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
6800/// — diagnostic-framed as "this caixa is not in `:membros`" when the
6801/// root cause is "this `:entrada :para` value is not a well-shaped
6802/// Servico-name identifier and could never legitimately match any
6803/// validated member". Because every `:membros :caixa` is shape-
6804/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
6805/// `HashSet` structurally never contains an empty / malformed string,
6806/// so the membership lookup arm misframes every empty / malformed
6807/// input. Lifting the shape arm ahead of the lookup preserves the
6808/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
6809/// simply isn't in `:membros` — a phantom reference) while routing
6810/// every structurally-impossible-to-match input through the narrower
6811/// self-locating shape diagnostic.
6812///
6813/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
6814/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
6815/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
6816/// fourth and last Aplicacao-level Servico-name reference axis to
6817/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
6818/// No `slot: &'static str` field because there is only one axis
6819/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
6820/// the simpler shape mirrors [`validate_membro_caixa`] and
6821/// [`validate_placement_cluster`].
6822fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
6823    // Empty is gated separately at the call site for a self-locating
6824    // diagnostic; re-checking here keeps the predicate usable from any
6825    // future call site (the M4 CR materializer's per-`:entrada`
6826    // validator) without an empty-check footgun. Routes through the
6827    // shared [`crate::render::require_valid_dns_1123_label`] gate the
6828    // peer name axes each land on.
6829    crate::render::require_valid_dns_1123_label(
6830        para,
6831        || AplicacaoError::EntradaParaEmpty,
6832        |reason| AplicacaoError::entrada_para_invalid(para, reason),
6833    )
6834}
6835
6836/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
6837/// would refuse at admission time. The contract — exactly the regex
6838/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
6839/// and `HTTPRoute.spec.hostnames[]`,
6840/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
6841/// (max length 253; per-label max length 63):
6842///
6843///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
6844///     uppercase, no underscore, no Unicode/IDN — IDN must be
6845///     pre-encoded as Punycode `xn--…` by the author);
6846///   - exactly one optional leading wildcard label (`*.`); a wildcard
6847///     in any non-leading label position is rejected;
6848///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
6849///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
6850///   - total length 1..=253 bytes;
6851///   - no IPv4 literal (Gateway API forbids IP literals);
6852///   - no scheme (`https://`, `http://`), no port (`:8080`), no
6853///     whitespace, no path (`/`).
6854///
6855/// Lifted as a typed gate (rather than an inline cascade in
6856/// `validate()`) so the contract lives in one place — every future
6857/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6858/// materializer's host validator, the future per-`:entrada` SAN
6859/// emission for cert-manager Certificates, the multi-`:entrada`
6860/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
6861/// for the same predicate, not its own. Same compounding shape as
6862/// `is_canonical_rate_limit_window` (808017c) and
6863/// [`WitTarget::label`] (previously the free `contrato_target_label`
6864/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
6865/// per-variant label match is compiler-checked-exhaustive).
6866///
6867/// The diagnostic carries the offending `host:` verbatim plus a
6868/// parser-shaped `reason:` naming the specific violation, so the
6869/// author can grep their caixa.lisp for `:host "<host>"` and fix it
6870/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
6871/// (9888b13).
6872fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
6873    // Empty is already gated by `EmptyEntradaHost` at the call site;
6874    // re-checking here keeps the predicate usable from any future
6875    // call site (M4 CR materializer) without an empty-check footgun.
6876    if host.is_empty() {
6877        return Err(AplicacaoError::EmptyEntradaHost);
6878    }
6879    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
6880        return Err(AplicacaoError::entrada_host_invalid(
6881            host,
6882            format!(
6883                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
6884                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
6885                host.len(),
6886                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
6887            ),
6888        ));
6889    }
6890    if host.contains("://") {
6891        return Err(AplicacaoError::entrada_host_invalid(
6892            host,
6893            "must not carry a scheme (drop the `https://` or `http://` prefix; \
6894             Gateway API takes the bare hostname)",
6895        ));
6896    }
6897    if host.contains('/') {
6898        return Err(AplicacaoError::entrada_host_invalid(
6899            host,
6900            "must not carry a path (drop the `/…` suffix; Gateway API path \
6901             matching is in `:entrada :paths`)",
6902        ));
6903    }
6904    // After the `://` scheme-prefix and `/` path arms have ruled out the
6905    // two `:`-bearing shapes the Gateway API actively rejects with
6906    // location-shaped diagnostics, any remaining `:` in the host body is
6907    // either the canonical "I put the port in the `:host` slot"
6908    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
6909    // slot lives one axis away on the same `:entrada` block) or an
6910    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
6911    // Hostname forbids identically to the IPv4-literal arm below. Both
6912    // shapes silently fell through the `://` and `/` arms before this
6913    // lift and surfaced as a deep `label "<rest>:<port>" contains
6914    // invalid character ':'` diagnostic from the per-byte loop near the
6915    // bottom of this predicate, which named the offending byte but not
6916    // the canonical authoring fix — for the port case the author has to
6917    // know the `:entrada` block carries a separate `:port u16` slot
6918    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
6919    // move the value over; for the IPv6 case the author has to know
6920    // Gateway API v1 forbids IP literals across the board. The contract
6921    // doc-comment above already promises "no port (`:8080`)" verbatim
6922    // in the rejected-shape enumeration but the predicate's
6923    // implementation refused the `:` only as a side-effect of the
6924    // per-label `[a-z0-9-]` character-class loop; this arm brings the
6925    // implementation in line with the documented contract by surfacing
6926    // the canonical fix at the top-level shape gate, peer with how the
6927    // `://` arm names the scheme prefix and the `/` arm names the
6928    // `:entrada :paths` axis. Same compounding trajectory the recent
6929    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
6930    // — the typed slot's rejected set matches the apiserver's rejected
6931    // set, structurally, with a self-locating diagnostic at the
6932    // offending axis instead of a deep parser-shape leak.
6933    if host.contains(':') {
6934        return Err(AplicacaoError::entrada_host_invalid(
6935            host,
6936            "must not contain `:` (the port belongs in the `:entrada :port` \
6937             slot — a separate `u16` axis on the same `:entrada` block, \
6938             defaulting to 8080 — not in the host body; drop the `:<port>` \
6939             suffix and author the bare hostname. If you intended an IPv6 \
6940             literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
6941             Hostname forbids IP literals identically to the IPv4-literal \
6942             arm — use a DNS name)",
6943        ));
6944    }
6945    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
6946    // predicate — the same single source of truth every peer
6947    // ASCII-whitespace scan in caixa-core flows through: the four
6948    // typed-magnitude codec sites (`limits::parse_byte_size` backing
6949    // `:limits :memory`, `limits::parse_duration` backing `:limits
6950    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
6951    // `aplicacao::rate_limit_codec::parse` backing `:politicas
6952    // :rate-limit`) and the shared duration codec
6953    // (`supervisor::duration_codec::parse`) backing `:supervisor
6954    // :restart-window` / `:politicas :timeout` / `:politicas
6955    // :circuit-breaker :window`. This landing closes the last string-typed
6956    // slot in caixa-core still calling `.bytes().any(|b|
6957    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
6958    // across every typed slot now shares one predicate, so a future
6959    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
6960    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
6961    // deliberately excluded from the peer non-ASCII predicate) can
6962    // extend at this shared site in one edit rather than seven
6963    // independent scans diverging over time. Naming the offending byte
6964    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
6965    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
6966    // the offending byte verbatim" discipline every peer codec site
6967    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
6968    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
6969    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
6970        return Err(AplicacaoError::entrada_host_invalid(
6971            host,
6972            format!(
6973                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
6974                 Hostname is a single-token DNS name — leading, trailing, \
6975                 or embedded whitespace breaks the K8s apiserver's Hostname \
6976                 regex at admission time; the paste-from-aligned-doc / \
6977                 paste-from-shell-history / paste-from-CSV footgun silently \
6978                 lands a multi-token blob in `:entrada :host`. Strip every \
6979                 whitespace byte and author the bare hostname — space \
6980                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
6981                 refuse identically)"
6982            ),
6983        ));
6984    }
6985    // Peer of the ASCII-whitespace scan above: route the non-ASCII
6986    // subset of Unicode `White_Space` through the shared
6987    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
6988    // single source of truth every peer non-ASCII-whitespace scan in
6989    // caixa-core flows through: `limits::parse_byte_size` (`:limits
6990    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
6991    // `limits::parse_millicores` (`:limits :cpu`),
6992    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
6993    // and `supervisor::duration_codec::parse` (`:supervisor
6994    // :restart-window` / `:politicas :timeout` / `:politicas
6995    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
6996    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
6997    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
6998    // paste-from-web-doc), or an EM-SPACE-split host
6999    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
7000    // survived this predicate's ASCII byte-scan (none of the UTF-8
7001    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
7002    // `u8::is_ascii_whitespace`), then landed on the per-label
7003    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
7004    // predicate with the generic `label "…" must start and end with an
7005    // alphanumeric` diagnostic — a "far from source at build-time"
7006    // leak that names the label-shape violation but not the
7007    // paste-from-typography origin the author actually needs to fix.
7008    // Peer with the four codec sites the 1b75b38 landing pinned: the
7009    // typed slot's diagnostic axis names the offending codepoint
7010    // (`U+XXXX`) verbatim rather than laundering the value through a
7011    // downstream label-shape arm, so the author can grep their
7012    // caixa.lisp for the invisible codepoint at the surfaced position
7013    // rather than eyeball a multi-byte host for embedded NBSP / LINE
7014    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
7015    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
7016    // drift between any two typed-slot sites' non-ASCII-whitespace
7017    // rejection set becomes a single-edit fix at the shared predicate
7018    // rather than N independent inline scans diverging over time, and
7019    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
7020    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
7021    // `char::is_whitespace`" class the peer non-ASCII predicate's
7022    // doc-comment names as the follow-up trajectory) extends at the
7023    // shared predicate in one edit rather than seven.
7024    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
7025        return Err(AplicacaoError::entrada_host_invalid(
7026            host,
7027            format!(
7028                "contains non-ASCII Unicode whitespace character {ch:?} \
7029                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
7030                 single-token DNS name limited to `[a-z0-9-]` labels; \
7031                 the paste-from-typography footgun silently lands an \
7032                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
7033                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
7034                 `U+3000`, and every other member of the Unicode \
7035                 `White_Space` property outside the ASCII byte range) \
7036                 in `:entrada :host`, which the K8s apiserver's \
7037                 Hostname regex refuses at admission time far from the \
7038                 caixa.lisp source line. Strip every non-ASCII \
7039                 whitespace character and author the bare hostname \
7040                 with only ASCII bytes (write \"checkout.quero.cloud\" \
7041                 verbatim)",
7042                codepoint = ch as u32,
7043            ),
7044        ));
7045    }
7046
7047    // Strip the optional single leading wildcard label *before* the
7048    // trailing-dot check so the bare `"*."` form surfaces the more
7049    // self-locating "wildcard without domain" diagnostic instead of
7050    // the generic "trailing dot" one.
7051    let (had_wildcard, rest) = match host.strip_prefix("*.") {
7052        Some(r) => (true, r),
7053        None => (false, host),
7054    };
7055    if had_wildcard && rest.is_empty() {
7056        return Err(AplicacaoError::entrada_host_invalid(
7057            host,
7058            "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
7059        ));
7060    }
7061    if rest.contains('*') {
7062        return Err(AplicacaoError::entrada_host_invalid(
7063            host,
7064            "wildcard `*` is allowed only as the first label (`*.example.com`); \
7065             no inner or trailing `*` labels",
7066        ));
7067    }
7068    if rest.ends_with('.') {
7069        return Err(AplicacaoError::entrada_host_invalid(
7070            host,
7071            "must not have a trailing `.` (Gateway API hostnames are not \
7072             fully-qualified with a root dot; the apiserver regex rejects \
7073             trailing dots)",
7074        ));
7075    }
7076
7077    // Reject pure IPv4 literals: four dot-separated labels, every
7078    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
7079    // literals as Hostnames.
7080    let labels: Vec<&str> = rest.split('.').collect();
7081    if labels.len() == 4
7082        && labels
7083            .iter()
7084            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
7085    {
7086        return Err(AplicacaoError::entrada_host_invalid(
7087            host,
7088            "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
7089             literals; use a DNS name)",
7090        ));
7091    }
7092
7093    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
7094    // hyphen, with non-hyphen at both boundaries.
7095    for label in &labels {
7096        if label.is_empty() {
7097            return Err(AplicacaoError::entrada_host_invalid(
7098                host,
7099                "has an empty label (consecutive `..` or a leading `.`)",
7100            ));
7101        }
7102        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
7103            return Err(AplicacaoError::entrada_host_invalid(
7104                host,
7105                format!(
7106                    "label {label:?} exceeds DNS-1123 label max length of \
7107                     {cap} bytes (got {} bytes)",
7108                    label.len(),
7109                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
7110                ),
7111            ));
7112        }
7113        let bytes = label.as_bytes();
7114        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
7115            return Err(AplicacaoError::entrada_host_invalid(
7116                host,
7117                format!(
7118                    "label {label:?} must start and end with an alphanumeric \
7119                     (no leading or trailing `-`)"
7120                ),
7121            ));
7122        }
7123        for &b in bytes {
7124            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
7125            if !valid {
7126                let msg = if b.is_ascii_uppercase() {
7127                    format!(
7128                        "label {label:?} contains uppercase character {ch:?} \
7129                         (Gateway API hostnames are lowercase-only; use {lower:?})",
7130                        ch = b as char,
7131                        lower = label.to_ascii_lowercase()
7132                    )
7133                } else if b == b'_' {
7134                    format!(
7135                        "label {label:?} contains `_` (Gateway API hostnames \
7136                         allow only `[a-z0-9-]`; use `-` instead)"
7137                    )
7138                } else {
7139                    format!(
7140                        "label {label:?} contains invalid character {ch:?} \
7141                         (Gateway API hostnames allow only `[a-z0-9-]`)",
7142                        ch = b as char
7143                    )
7144                };
7145                return Err(AplicacaoError::entrada_host_invalid(host, msg));
7146            }
7147        }
7148    }
7149    Ok(())
7150}
7151
7152/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
7153/// would refuse at admission time. Thin wrapper around
7154/// [`crate::render::is_gateway_api_http_path`] that maps the shared
7155/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
7156/// variant, preserving the more self-locating
7157/// [`AplicacaoError::EntradaPathEmpty`] /
7158/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
7159/// path fails those narrower invariants first.
7160///
7161/// The contract is the canonical HTTP-path grammar — `1..=
7162/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
7163/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
7164/// whitespace/control/non-ASCII bytes — shared with the
7165/// `:contratos :endpoint` axis through the lifted predicate so drift
7166/// between either landing site and the K8s apiserver-side
7167/// HTTPPathMatch.value OpenAPI schema is a build error visible at
7168/// the predicate, not a per-renderer "this passed validate but failed
7169/// admission" surprise. The diagnostic carries the offending `path:`
7170/// verbatim plus a parser-shaped `reason:` naming the specific
7171/// violation, so the author can grep their caixa.lisp for `:paths`
7172/// and fix it in one edit. Same diagnostic shape as
7173/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
7174/// axis.
7175fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
7176    // Empty and missing-leading-`/` are already gated at the call
7177    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
7178    // checking here keeps the per-axis narrower diagnostics in force
7179    // when the predicate is reached directly (and `is_gateway_api_http_path`
7180    // itself defends against `bytes[0]`-style indexing on empty
7181    // input).
7182    if path.is_empty() {
7183        return Err(AplicacaoError::EntradaPathEmpty);
7184    }
7185    if !path.starts_with('/') {
7186        return Err(AplicacaoError::entrada_path_not_absolute(path));
7187    }
7188    crate::render::is_gateway_api_http_path(path)
7189        .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
7190}
7191
7192mod rate_limit_codec {
7193    // `Duration` is no longer named here — the codec routes through
7194    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
7195    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
7196    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
7197    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
7198    // closed-set enum's arm-table rather than through vestigial free-helper
7199    // delegates.
7200    use super::{RateLimit, RateLimitUnit};
7201    use serde::{Deserializer, Serializer};
7202
7203    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
7204        // Route through the canonical [`crate::render::serialize_option_via_str`]
7205        // — the substrate-side single-owner primitive for the forward
7206        // arm of the typed-magnitude codec family. See its docstring
7207        // for the full sibling roster.
7208        crate::render::serialize_option_via_str(v, s, render)
7209    }
7210
7211    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
7212        // Route through the canonical [`crate::render::deserialize_option_via_str`]
7213        // — the substrate-side single-owner primitive for the reverse
7214        // arm of the typed-magnitude codec family. See its docstring
7215        // for the full sibling roster.
7216        crate::render::deserialize_option_via_str(d, parse)
7217    }
7218
7219    fn parse(s: &str) -> Result<RateLimit, String> {
7220        // Paired whitespace-rejection arm — same canonical-form
7221        // render-determinism discipline as the peer
7222        // `limits::parse_byte_size` / `limits::parse_duration` /
7223        // `limits::parse_millicores` /
7224        // `supervisor::duration_codec::parse` sites: the ASCII
7225        // byte-scan closes the WhatWG-conformant whitespace bytes
7226        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
7227        // `char::is_whitespace` scan closes the strictly-complementary
7228        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
7229        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
7230        // codepoints) that `str::trim` at parse entry silently strips.
7231        // Either drift class would round-trip through `render` to a
7232        // *different* canonical form on next emit — breaking the
7233        // THEORY.md Part V render-determinism contract on
7234        // `:politicas :rate-limit`.
7235        //
7236        // Routed through the lifted [`crate::render::reject_whitespace`]
7237        // primitive — the substrate-side single-owner paired-arm gate
7238        // every typed-magnitude codec in caixa-core shares.
7239        crate::render::reject_whitespace::<String, _, _>(
7240            s,
7241            |b| {
7242                format!(
7243                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
7244                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
7245                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
7246                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
7247                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
7248                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
7249                 on first serialize — breaking the THEORY.md Part V render-determinism \
7250                 contract every typed slot carries. Strip every whitespace byte (write \
7251                 `\"100/s\"` verbatim)"
7252                )
7253            },
7254            |ch| {
7255                format!(
7256                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
7257                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
7258                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
7259                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
7260                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
7261                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
7262                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
7263                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
7264                 silently strips it at parse entry, and the value round-trips through \
7265                 `render` to a *different* canonical form (`\"100/s\"`) on first \
7266                 serialize — breaking the THEORY.md Part V render-determinism contract \
7267                 every typed slot carries. Strip every non-ASCII whitespace character \
7268                 (write `\"100/s\"` verbatim with only ASCII bytes)",
7269                    cp = ch as u32
7270                )
7271            },
7272        )?;
7273        let s = s.trim();
7274        let (rate_str, unit) = s
7275            .split_once('/')
7276            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
7277        let rate_trim = rate_str.trim();
7278        // The canonical authoring form for `:politicas :rate-limit` is
7279        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
7280        // non-negative integer with no decimal point and no leading
7281        // sign, so the parser's accepted set must match for
7282        // serialize/deserialize to round-trip without canonical-form
7283        // drift. Until this gate landed the parser accepted any
7284        // `u32::from_str`-shaped magnitude — and current Rust
7285        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
7286        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
7287        // serde silently round-tripped to `"100/s"` on the next emit
7288        // (a *different* canonical string) — breaking the THEORY.md
7289        // Part V render-determinism contract on the fifth typed-codec
7290        // surface in caixa-core (peer with the four duration codecs the
7291        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
7292        // already covered: `supervisor::duration_codec` backing three
7293        // typed-duration slots, `limits::parse_duration` backing
7294        // `:limits :wall-clock`, `limits::parse_byte_size` backing
7295        // `:limits :memory`). The fractional / decimal-shaped sibling
7296        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
7297        // existing rejection arm, but the diagnostic is value-laundered
7298        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
7299        // doesn't name the canonical-form remediation or the round-trip
7300        // drift the next emit would produce); this gate lifts the
7301        // fractional arm onto the same canonical-form diagnostic the
7302        // peer codecs carry.
7303        //
7304        // Strict canonical form: every byte of the magnitude is an
7305        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
7306        // inputs the gate distinguishes "non-canonical-but-numeric"
7307        // (parses as f64 or i64 — surfaced with a self-locating
7308        // diagnostic naming the canonical authoring form and the
7309        // round-trip drift the rejected shape would produce on first
7310        // serialize) from "garbage" (parses as neither — surfaced with
7311        // the existing narrower `"not a u32"` wording so its
7312        // diagnostic shape remains stable for the parser-shape footgun
7313        // case).
7314        //
7315        // Routed through the lifted
7316        // [`crate::render::is_digit_only_magnitude`] predicate — the
7317        // same source of truth the four peer typed-magnitude codec
7318        // sites share.
7319        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
7320        if !digit_only {
7321            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
7322            if numeric {
7323                return Err(format!(
7324                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
7325                     canonical authoring form for `:politicas :rate-limit` is \
7326                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
7327                     with no decimal point and no leading `+` / `-` sign. A fractional / \
7328                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
7329                     through `render` to a *different* canonical form (`\"1/s\"`, \
7330                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
7331                     THEORY.md Part V render-determinism contract every typed slot \
7332                     carries. Pick an integer rate that fits the desired window \
7333                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
7334                ));
7335            }
7336            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
7337        }
7338        // Leading-zero arm — peer with the prior `"+100/s"` arm above
7339        // (4eeae98's predecessor) on the same canonical-form
7340        // render-determinism axis. The digit-only gate accepts
7341        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
7342        // them losslessly (= 100, 0, 7), but `render` emits the
7343        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
7344        // a *different* canonical string on the next emit, breaking
7345        // the THEORY.md Part V render-determinism contract the same
7346        // way `"+100/s"` did before the leading-`+` arm landed. The
7347        // single-byte magnitude `"0"` itself round-trips losslessly
7348        // through `render` (`render(0)` emits `"0/s"`) — the
7349        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
7350        // what refuses rate-zero authoring, so `"0/s"` stays in the
7351        // accepted set at this codec layer and the diagnostic
7352        // partitioning between canonical-form drift (this arm) and
7353        // semantic-zero (the downstream gate) remains stable.
7354        // Peer with the future leading-zero arms on the three peer
7355        // typed-magnitude codecs the trajectory acknowledges:
7356        // `supervisor::duration_codec`, `limits::parse_duration`,
7357        // `limits::parse_byte_size` — each carries the same
7358        // canonical-form-drift class today; this gate lands the
7359        // discipline on the fourth typed-magnitude codec in
7360        // caixa-core first because the peer `"+100/s"` arm above is
7361        // the closest predecessor on the trajectory.
7362        //
7363        // Routed through the lifted
7364        // [`crate::render::is_leading_zero_padded_magnitude`]
7365        // predicate — the same source of truth the four peer
7366        // typed-magnitude codec sites share.
7367        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
7368            return Err(format!(
7369                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
7370                 canonical authoring form for `:politicas :rate-limit` is \
7371                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
7372                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
7373                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
7374                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
7375                 first serialize — breaking the THEORY.md Part V render-determinism \
7376                 contract every typed slot carries. Strip the leading zeros (write \
7377                 `\"100/s\"` instead of `\"0100/s\"`)"
7378            ));
7379        }
7380        // The digit-only gate guarantees every byte is `[0-9]`, and
7381        // the leading-zero arm above guarantees the magnitude is
7382        // either the single byte `"0"` or starts with `[1-9]`, so
7383        // the only way `u32::from_str` can fail here is overflow
7384        // (the magnitude exceeds `u32::MAX`). Surface that with an
7385        // overflow-shaped wording so the diagnostic names the
7386        // offending magnitude verbatim rather than collapsing onto
7387        // the non-canonical arm. Same shape
7388        // `supervisor::duration_codec` (1c55a2a) carries on the peer
7389        // duration-codec axis.
7390        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
7391            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
7392        })?;
7393        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
7394        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
7395        // arm reads the `&str → Duration` projection through the
7396        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
7397        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
7398        // with [`super::RateLimitUnit::window`]) rather than the vestigial
7399        // module-private `rate_limit_window_from_unit` free helper the
7400        // predecessor 61421a6 left as the last unlifted delegate on this
7401        // axis. One typed dispatch on the substrate primitive instead of
7402        // one runtime call through the free-helper delegate; the sole
7403        // production consumer of the `&str → Duration` axis (this parse
7404        // arm) now reaches for exactly one typed method on the closed-set
7405        // enum, sibling to the codec's render arm's
7406        // [`super::RateLimit::canonical_unit`] dispatch on the paired
7407        // `Duration → RateLimitUnit` axis and to the validate gate's
7408        // [`super::RateLimit::canonical_unit`] shape-probe on the
7409        // canonical-window axis. A future rate-limit-unit addition (a
7410        // `"d"` day suffix once Envoy's `rate_limit_action` grows
7411        // daily-bucket support, a `"ms"` sub-second window once
7412        // high-throughput per-edge policies come into scope per
7413        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
7414        // on the closed-set enum, and the compiler enforces exhaustiveness
7415        // on every consumer's `match self` arms — this parse arm's
7416        // accepted-suffix set, the render arm's emitted-suffix set, the
7417        // validate gate's canonical-window set, and every future
7418        // per-`:contratos`-edge rate-limit-override overlay all pick it up
7419        // by construction.
7420        let unit = unit.trim();
7421        let window = RateLimitUnit::window_from_suffix(unit)
7422            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
7423        Ok(RateLimit { rate, window })
7424    }
7425
7426    fn render(rl: RateLimit) -> String {
7427        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
7428        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
7429        // this render arm reads the `Duration → RateLimitUnit` projection
7430        // through the substrate primitive [`super::RateLimit::canonical_unit`]
7431        // (returns `None` on every non-canonical window — the sub-second /
7432        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
7433        // formats the returned typed enum through its
7434        // [`std::fmt::Display`] impl (which routes through
7435        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
7436        // the substrate primitive instead of one runtime `find_map`
7437        // walk through the free-helper delegate chain
7438        // [`super::rate_limit_window_unit`] (the vestigial free helper's
7439        // sole production consumer was this arm; every other consumer of
7440        // the `Duration → unit` axis — the validate gate below and the
7441        // future M4 per-Aplicacao Envoy config reconciler — now reads
7442        // the same typed method).
7443        //
7444        // A future rate-limit-unit addition (a `"d"` day suffix once
7445        // Envoy's `rate_limit_action` grows daily-bucket support) is
7446        // one variant + one arm per method on the closed-set enum, and
7447        // the compiler enforces exhaustiveness on every consumer's
7448        // `match self` arms — the codec's `parse` accepted-suffix set,
7449        // this render arm's emitted-suffix set, the validate gate's
7450        // canonical-window set, and every future per-`:contratos`-edge
7451        // rate-limit-override overlay all pick it up by construction.
7452        if let Some(unit) = rl.canonical_unit() {
7453            format!("{}/{unit}", rl.rate())
7454        } else {
7455            // Defensive fallback for non-canonical windows. Note:
7456            // [`AplicacaoSpec::validate_politicas`] rejects any
7457            // non-canonical `:rate-limit :window` via
7458            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
7459            // a validated `RateLimit` never reaches this branch. The
7460            // emitted `<n>/<k>s` form is *not* round-trippable through
7461            // [`parse`] (which accepts only the closed-set
7462            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
7463            // explicit count) — the validate gate is what makes the
7464            // round-trip a structural property; this branch exists only
7465            // so a programmatic non-validated serialize doesn't panic.
7466            format!("{}/{}s", rl.rate(), rl.window().as_secs())
7467        }
7468    }
7469}
7470
7471// ── placement strategy ───────────────────────────────────────────────
7472
7473/// How the Aplicacao distributes across clusters. Three options:
7474///
7475/// - `SingleNode` — one cluster runs the app at a time; takeover on
7476///   death (Erlang/OTP distributed-app semantics).
7477/// - `Replicated` — every named cluster runs an instance (active-active).
7478/// - `Sharded` — entities distribute by hash key across clusters
7479///   (Akka cluster sharding).
7480#[derive(
7481    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
7482)]
7483pub enum PlacementStrategy {
7484    SingleNode,
7485    Replicated,
7486    Sharded,
7487}
7488
7489/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
7490/// distribution-strategy default for the `:placement :estrategia` axis —
7491/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
7492/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
7493/// so every substrate-side consumer that resolves "what
7494/// [`PlacementStrategy`] variant does an author-omitted `:placement
7495/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
7496/// primitive [`PlacementStrategy`].
7497///
7498/// The `:placement :estrategia` default axis has three production
7499/// consumers on the substrate side today: the [`Default for
7500/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
7501/// impl's struct-literal `estrategia` field, and the serde-side
7502/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
7503/// author-omitted `:placement :estrategia` scalar through the [`Default
7504/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
7505/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
7506/// impl and implicit `PlacementStrategy::default()` routes at the sibling
7507/// consumers, with no compile-time link back to the paired
7508/// [`crate::manifest::Caixa::aplicacao_view`] fold's
7509/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
7510/// production consumer that resolves an author-omitted `:placement` slot
7511/// (entirely omitted, not just the `:estrategia` scalar within a declared
7512/// `:placement` block) through [`Placement::default`] which then routes
7513/// through this same discriminator. A future coherent rebrand of the
7514/// `:placement :estrategia` default (a widening to `Sharded` once the
7515/// substrate discovers hash-keyed distribution as the more common
7516/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
7517/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
7518/// names, a per-cluster overlay the operator pins through a future
7519/// `:placement-overrides` slot) would have had to migrate a lifted
7520/// discriminator on one path and open-coded discriminators on the peers
7521/// in lockstep or the four consumers would silently drift out of
7522/// pairing. Lifting the resolution rule to a typed `pub const` on the
7523/// substrate primitive means the M3-mesh-canonical `:placement
7524/// :estrategia` default migrates as one unit on any future axis change.
7525///
7526/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
7527/// §II.2's active-active-across-every-named-cluster arm — the closest
7528/// canonical M3 production reference the substrate carries, matching the
7529/// caixa-mesh default axis every M3 renderer already keys off (a
7530/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
7531/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
7532/// under the substrate's fleet-programs aggregator without an explicit
7533/// `:placement :estrategia` override). The two alternatives the closed
7534/// [`PlacementStrategy::ALL`] accept-set carries
7535/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
7536/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
7537/// Akka-style hash-keyed distribution across clusters,
7538/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
7539/// postures an author declares explicitly, never a posture an omitted
7540/// slot should silently assume.
7541///
7542/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
7543/// exactly one source of truth on the `:placement :estrategia` axis, on
7544/// the same substrate-primitive lift discipline the sibling M2
7545/// per-supervisor default set carries
7546/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
7547/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
7548/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
7549/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
7550/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
7551/// ([`crate::render::DEFAULT_NAMESPACE`],
7552/// [`crate::render::DEFAULT_LIBRARY_NAME`],
7553/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
7554/// the M3 mesh-primitive-defining slot family to converge onto the
7555/// substrate-primitive-lift discipline the M2 supervisor-slot family
7556/// already carries end-to-end.
7557pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
7558
7559impl Default for PlacementStrategy {
7560    fn default() -> Self {
7561        // Route the [`Default for PlacementStrategy`] impl through the
7562        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
7563        // `pub const` rather than a raw `Self::Replicated` arm — one
7564        // source of truth for the M3-mesh-canonical active-active-
7565        // across-every-named-cluster `:placement :estrategia` default
7566        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
7567        // lift discipline the sibling M2 per-supervisor default set
7568        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
7569        // paired halves) carries end-to-end. Pinned by
7570        // `placement_strategy_default_routes_through_lifted_default`.
7571        PLACEMENT_ESTRATEGIA_DEFAULT
7572    }
7573}
7574
7575impl PlacementStrategy {
7576    /// Exhaustive iteration surface for every consumer that reads the
7577    /// full closed-set (the future M4 admission-webhook's accepted-
7578    /// strategy listing in its rejection body, a future `feira app
7579    /// placement --list` CLI-side surfacing of the accepted arm-set,
7580    /// any future round-trip fuzz harness). A future variant addition
7581    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
7582    /// names as a trajectory item) extends this slice as a single edit
7583    /// and every consumer picks up the new entry by construction — the
7584    /// compiler-checked exhaustiveness on the sibling method `match`
7585    /// arms is the build-time guarantee that no arm forgets to grow.
7586    /// Same shape as the sibling closed-set typed enums'
7587    /// [`RateLimitUnit::ALL`] (6bce03d) and
7588    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7589    /// surfaces — the third closed-set typed enum on the caixa surface
7590    /// to converge onto the same discipline.
7591    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
7592
7593    /// Canonical camelCase-schema discriminator scalar this variant
7594    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
7595    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
7596    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7597    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
7598    /// every substrate consumer that dispatches on the strategy (the
7599    /// `lareira-fleet-programs` aggregator, the future `app-operator`
7600    /// reconciler, the M3 Adaptive compression pass) reads the same
7601    /// byte-string the `Serialize` derive emits — the pin test in
7602    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
7603    /// asserts the two paths agree.
7604    #[must_use]
7605    pub const fn as_str(self) -> &'static str {
7606        match self {
7607            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
7608            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
7609            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
7610        }
7611    }
7612
7613    /// Substrate-canonical reverse projection on the `:placement
7614    /// :estrategia` closed-set axis — parses the camelCase-schema
7615    /// discriminator scalar back to the typed variant, or `None` when
7616    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
7617    /// emits. Dispatches on the same lifted
7618    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
7619    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7620    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
7621    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
7622    /// the round-trip migrate through one caixa-core edit on any future
7623    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
7624    /// §II.5 hint names as a trajectory item lands one variant + one
7625    /// arm per method and the compiler enforces exhaustiveness on every
7626    /// consumer's `match self` arms).
7627    ///
7628    /// Prior to this lift the substrate carried only the forward
7629    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
7630    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
7631    /// derive that emits the same byte-string under
7632    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
7633    /// consumer that wanted to parse a wire-form strategy scalar had to
7634    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
7635    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
7636    /// compile-time link back to the typed variant's canonical lifted
7637    /// constant. A future variant rename or a per-arm serde-attribute
7638    /// drift would silently split the wire byte-string one non-serde
7639    /// consumer parsed from the one the emitter wrote, with the
7640    /// failure surfacing at parse time far from the rebrand commit.
7641    ///
7642    /// Same closed-set-reverse-projection discipline the sibling
7643    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
7644    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
7645    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
7646    /// defining `:placement :estrategia` closed-set axis, the third
7647    /// substrate-side closed-set typed enum to converge on the two-way
7648    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
7649    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
7650    /// and side-step the [`std::str::FromStr`]-collision clippy
7651    /// (`clippy::should_implement_trait`) the plain `from_str` name
7652    /// carries; a future explicit [`std::str::FromStr`] impl can layer
7653    /// on top by delegating to this canonical arm-dispatch method.
7654    ///
7655    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
7656    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
7657    /// picks the diagnostic form appropriate for its use site — a
7658    /// future `feira app placement --set` CLI-side arg-parse that wants
7659    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
7660    /// Sharded)"` diagnostic builds one on top by iterating
7661    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
7662    /// path folds `None` onto its per-CR structured refusal body.
7663    #[must_use]
7664    pub fn from_wire(s: &str) -> Option<Self> {
7665        match s {
7666            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
7667            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
7668            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
7669            _ => None,
7670        }
7671    }
7672
7673    /// Substrate-canonical per-arm predicate naming the cross-slot
7674    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
7675    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
7676    /// consumes the paired [`Placement::shard_key`] axis (and therefore
7677    /// requires — and is the only strategy that permits — a non-empty
7678    /// `:shard-key` on the paired slot). Today the accept-set is the
7679    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
7680    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
7681    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
7682    /// distributed-app takeover — §II.1) and `Replicated` (active-active
7683    /// across every named cluster) have no hash-keyed routing axis to
7684    /// consume the slot and refuse a declared-but-inert `:shard-key`
7685    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
7686    ///
7687    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
7688    /// satisfies `placement.shard_key().is_some() ==
7689    /// placement.estrategia().requires_shard_key()` by construction — the
7690    /// cross-slot partition the pin
7691    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
7692    /// locks load-bearing, so every downstream consumer that reaches for
7693    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
7694    /// CR materializer's per-CR shard-key resolver, the future
7695    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
7696    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
7697    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
7698    /// shard-key requirement probe, a future author-facing tatara-lisp
7699    /// linter that flags `(:placement (:estrategia Replicated :shard-key
7700    /// "tenantId"))` shapes before `feira lint` reaches
7701    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
7702    /// the substrate primitive — the predicate names *the cross-slot
7703    /// invariant*, not the arm identity.
7704    ///
7705    /// Prior to this lift the "does this strategy consume `:shard-key`"
7706    /// classification lived under the `gen_platform::IsVariant`-derived
7707    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
7708    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
7709    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
7710    /// } else { None }` cascade, the
7711    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
7712    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
7713    /// "tenantId".to_string())` cascade, and the
7714    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
7715    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
7716    /// cascade). Each site conflated two semantically distinct questions:
7717    /// "is the variant `Sharded`?" (arm-identity, what
7718    /// [`Self::is_sharded`] answers) and "does the variant consume
7719    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
7720    /// The two questions land on the same three-way answer under today's
7721    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
7722    /// future arm addition that consumed `:shard-key` under a different
7723    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
7724    /// §II.5 roadmap-hint names that hash-partitions across the cluster
7725    /// pool by client-IP hash rather than an author-declared extractor
7726    /// expression, a hypothetical `WeightedShard` variant that carries a
7727    /// shard-key + per-cluster weight table under a promoted M5
7728    /// adaptive-placement engine) or an addition that did *not* consume
7729    /// `:shard-key` on a semantically Sharded-shaped arm would silently
7730    /// split the two questions. Any consumer that read
7731    /// `.is_sharded().then(…)` for the shard-key requirement gate would
7732    /// silently misclassify the new arm as non-consuming — a fixture
7733    /// builder would omit `:shard-key` where the new arm required one and
7734    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
7735    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
7736    /// commit, a future M4 CR materializer would fall through the
7737    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
7738    /// silently emit an empty extractor at the Akka reconciler layer.
7739    ///
7740    /// Lifting the classification as a substrate-primitive method on the
7741    /// closed-set typed enum names the cross-slot invariant on the
7742    /// primitive that owns the partition: every future arm addition
7743    /// declares its `:shard-key` consumption in one place (this predicate's
7744    /// `match self` arm-set), and every downstream consumer that reaches
7745    /// for the paired shape reads through one typed dispatch. Same
7746    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
7747    /// per-arm predicate on the pre-projection WIT-shape axis and the
7748    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
7749    /// paired predicate on the post-projection typed-view axis — a
7750    /// per-arm semantic-classification predicate paired with the
7751    /// arm-identity predicate the derive already emits, closing the drift
7752    /// footgun on the cross-slot invariant axis.
7753    ///
7754    /// Method-named `requires_shard_key` (not `has_shard_key`, not
7755    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
7756    /// invariant reads as "this strategy *requires* the paired
7757    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
7758    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
7759    /// merely omit it. The `has_*` framing would read as an accessor
7760    /// (returning the presence of an already-carried value) rather than a
7761    /// requirement (naming the invariant the paired slot must satisfy).
7762    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
7763    /// shape as the sibling [`WitContract::is_capability`] /
7764    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
7765    /// arm-family, so every consumer reaches for `.requires_shard_key()`
7766    /// as a drop-in replacement for the `.is_sharded()` conflated read
7767    /// without a return-shape migration.
7768    #[must_use]
7769    pub const fn requires_shard_key(self) -> bool {
7770        match self {
7771            Self::Sharded => true,
7772            Self::SingleNode | Self::Replicated => false,
7773        }
7774    }
7775}
7776
7777// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
7778// cross-slot-invariant per-arm predicate: the module-scope const-eval
7779// assertions below trip at caixa-core build time (not test time) if a
7780// future edit rewires the predicate's arm-set away from the singleton
7781// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
7782// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
7783// runtime pin covers the same truth-table with a more descriptive
7784// diagnostic on failure; these const-eval items add a build-time failure
7785// surface strictly stronger than the runtime pin (a downstream renderer's
7786// `const`-context reader that composed against a rebound predicate would
7787// still surface here before the test suite even ran) and side-step the
7788// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
7789// would otherwise accumulate on the caixa-core module baseline.
7790const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
7791const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
7792const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
7793
7794/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
7795/// the pretty-printed byte-string every consumer that formats the strategy
7796/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
7797/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
7798/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
7799/// per-Aplicacao strategy line, the future M4 CR materializer's per-
7800/// admission-webhook rejection body) reaches for the same lifted
7801/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
7802/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7803/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
7804/// `Serialize` derive already emits under
7805/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
7806/// [`PlacementStrategy::as_str`] helper already returns.
7807///
7808/// Until this lift landed the sibling OTP-shape typed enums —
7809/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
7810/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
7811/// so [`std::fmt::Display`] routes through the same discriminant string
7812/// the wire format emits) — carried a stable [`std::fmt::Display`]
7813/// surface but [`PlacementStrategy`] did not; every consumer reaching
7814/// for a strategy byte-string past the wire format had to pick between
7815/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
7816/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
7817/// derive), any two of which a future variant rename or
7818/// `#[serde(rename_all = "kebab-case")]` attribute would silently
7819/// desynchronize — with the failure surfacing as a downstream renderer /
7820/// operator's per-strategy dispatch reading one spelling while the wire
7821/// format emitted another, far from the source rebrand commit and with
7822/// no field naming the drift. Routing `Display` through
7823/// [`PlacementStrategy::as_str`] makes the three paths
7824/// (`Debug` for structural inspection, `Display` for user-facing text,
7825/// `Serialize` for the wire format) converge on the same lifted
7826/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
7827/// the diagnostic byte-string, and the pretty-printed byte-string move
7828/// as a single unit through one canonical declaration each, by
7829/// construction. Same trajectory as [`PlacementStrategy::as_str`]
7830/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
7831/// closes the third path.
7832///
7833/// Pin tests
7834/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
7835/// and
7836/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
7837/// assert the three paths agree byte-for-byte on every variant, so a
7838/// future variant rename or per-arm serde attribute drift is a build
7839/// error visible at caixa-core test time, not a silent per-consumer
7840/// dispatch miss at apply / reconcile time.
7841impl std::fmt::Display for PlacementStrategy {
7842    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7843        f.write_str(self.as_str())
7844    }
7845}
7846
7847/// Substrate-canonical [`AsRef<str>`] projection on the M3
7848/// per-Aplicacao distribution-strategy [`PlacementStrategy`] closed-set
7849/// typed enum — routes through the same [`PlacementStrategy::as_str`]
7850/// `pub const fn` scalar accessor the paired [`std::fmt::Display`] impl
7851/// and the un-`rename`d [`serde::Serialize`] derive already key off, so
7852/// any future consumer that binds a [`PlacementStrategy`] through the
7853/// standard-library `impl AsRef<str>` bound (a future `feira app
7854/// placement --set <arm>` verb that composes the emitted
7855/// `PascalCase`/camelCase wire scalar into a
7856/// [`std::process::Command::arg`] shell-out of the future
7857/// `lareira-fleet-programs` aggregator's per-Aplicacao gate, a
7858/// per-Aplicacao structured-log recorder on the future `app-operator`'s
7859/// hierarchical reconciliation surface that accepts `impl AsRef<str>`
7860/// at the `tracing::field::Value` `Str`-arm, a
7861/// [`std::collections::HashMap`] lookup keyed on the strategy wire byte
7862/// through `map.get::<str>(strategy.as_ref())` on a future
7863/// per-strategy dispatch table the M5 adaptive-placement engine
7864/// composes) reaches the paired
7865/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
7866/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7867/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted-const
7868/// through one substrate-primitive dispatch rather than an open-coded
7869/// `.as_str()` projection at every wire-up.
7870///
7871/// Peer of the sibling [`std::fmt::Display`] impl on the same
7872/// primitive — both delegate to the shared
7873/// [`PlacementStrategy::as_str`] `pub const fn` accessor, so
7874/// [`format!("{v}")`], `v.as_str()`, and `<PlacementStrategy as
7875/// AsRef<str>>::as_ref(&v)` resolve to the same byte-string per
7876/// instance by construction. A future variant rename or `#[serde(rename_all
7877/// = "kebab-case")]` attribute-drift on the enum reaches every one of
7878/// the three paths (plus the wire-format `Serialize` derive that
7879/// already routes through the same lifted const) through exactly one
7880/// caixa-core edit.
7881///
7882/// Same "route the trait impl through the substrate-primitive
7883/// accessor" discipline the sibling [`crate::CaixaVersion`]
7884/// [`AsRef<str>`] impl (16d5c7e), the paired M2
7885/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
7886/// (63eb1a4), and the paired M2 [`crate::supervisor::RestartPolicy`]
7887/// [`AsRef<str>`] impl (419ea81) carry — closes the M2/M3
7888/// closed-set-typed-enum family's standard-library [`AsRef<str>`]
7889/// projection axis onto the last remaining M3 mesh-primitive-defining
7890/// slot, so every OTP/mesh-shape closed-set typed enum on the caixa
7891/// surface now carries the paired [`AsRef<str>`] + [`fmt::Display`] +
7892/// `as_str` triple through one lifted `M3_PLACEMENT_ESTRATEGIA_*` /
7893/// `SUPERVISOR_*` const. Rust-side newtype/typed-enum convention pairs
7894/// [`AsRef<str>`] and [`fmt::Display`] on the same primitive so a
7895/// caller who has one has both; before this lift,
7896/// [`PlacementStrategy`] carried [`fmt::Display`] but not the paired
7897/// [`AsRef<str>`] impl the convention names.
7898///
7899/// Pinned load-bearing by
7900/// [`tests::placement_strategy_as_ref_str_routes_through_as_str_accessor`]
7901/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
7902/// three-arm closed set) and
7903/// [`tests::placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`]
7904/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
7905/// resolve to the same lifted `M3_PLACEMENT_ESTRATEGIA_*` const per
7906/// arm) — any future silent detour that routes the impl through a
7907/// divergent projection (a per-arm inline `match self { … }`
7908/// re-inlining that opens a compile-time link to the un-lifted
7909/// arm-literal, a swap onto the kebab-case
7910/// [`gen_platform::Discriminant`] catalog identity that would collide
7911/// the wire axis with the dispatcher-catalog axis) trips at
7912/// caixa-core test time under `assert_eq!` rather than at a downstream
7913/// `impl AsRef<str>`-bound consumer's silent split.
7914impl AsRef<str> for PlacementStrategy {
7915    fn as_ref(&self) -> &str {
7916        self.as_str()
7917    }
7918}
7919
7920/// Trait-idiomatic reverse projection on the M3-mesh-primitive-defining
7921/// [`PlacementStrategy`] closed-set typed enum — routes byte-for-byte
7922/// through the paired substrate-primitive [`PlacementStrategy::from_wire`]
7923/// `Option<Self>` accessor so every future consumer that binds a
7924/// camelCase-schema `:placement :estrategia` wire byte-string through the
7925/// standard-library `.try_into()` / [`TryFrom`] axis (a future `feira app
7926/// placement --set <SingleNode|Replicated|Sharded>` CLI arg-parse that
7927/// composes into `let estrategia: PlacementStrategy = s.try_into()?`, a
7928/// future `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook that
7929/// folds a `spec.placement.estrategia: String` field through
7930/// `PlacementStrategy::try_from(&s)?`, a generic `<T: TryFrom<&str>>`-
7931/// bound loader over any of the substrate's closed-set typed enums)
7932/// reaches the same three-arm accept-set the sibling
7933/// [`PlacementStrategy::from_wire`] resolver parses through and the
7934/// sibling [`PlacementStrategy::as_str`] emits, rather than an open-coded
7935/// per-arm `match s { "SingleNode" => …, "Replicated" => …, "Sharded" =>
7936/// …, _ => … }` cascade whose arm-set has no compile-time link back to
7937/// the substrate primitive.
7938///
7939/// Complements the pre-existing forward-projection triple
7940/// ([`std::fmt::Display`], [`AsRef<str>`], [`PlacementStrategy::as_str`])
7941/// with the paired trait-idiomatic reverse-projection axis: Rust-side
7942/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
7943/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
7944/// caller who can project *out to* a `&str` can also project *in from*
7945/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
7946/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
7947/// lint the sibling method-named [`PlacementStrategy::from_wire`] would
7948/// trigger under a `FromStr` impl (the same design tradeoff the peer
7949/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
7950/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks note)
7951/// — this impl closes the trait-idiomatic reverse axis without
7952/// disturbing the method-named `from_wire` shape every sibling closed-set
7953/// typed enum on the substrate already carries.
7954///
7955/// `type Error = ()` matches the sibling [`PlacementStrategy::from_wire`]'s
7956/// `Option<Self>` return-shape's deliberate deferral of error typing:
7957/// the caller picks the diagnostic form appropriate for its use site (a
7958/// future `feira app placement --set` arg-parse composes its own per-verb
7959/// "unknown strategy: <arg> — accepted: {…}" message enumerating
7960/// [`PlacementStrategy::ALL`], a future M4 admission-webhook rejection
7961/// body wraps the `Err(())` outcome with the accepted-set enumeration for
7962/// operator diagnostics, a `Result::map_err` at the call site lifts the
7963/// unit-error to a per-verb error type).
7964///
7965/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
7966/// set the [`PlacementStrategy::from_wire`] resolver dispatches through,
7967/// so any future arm addition (an `Anycast` mesh-anycast arm the
7968/// MESH-COMPOSITION §II.5 hint names as a trajectory item) grows the
7969/// trait-idiomatic axis by construction — one caixa-core edit on
7970/// [`PlacementStrategy::from_wire`] extends both the method-named reverse
7971/// projection every existing consumer keys off and the trait-idiomatic
7972/// reverse projection this impl exposes, without a coordinated rewrite
7973/// across every future `TryFrom<&str>`-bound consumer's arm-set.
7974///
7975/// Extends the substrate-wide closed-set-enum reverse-projection family
7976/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
7977/// bf33136) onto the first M3-mesh-primitive-defining slot enum on the
7978/// caixa surface — the `:placement :estrategia` closed set the
7979/// caixa-mesh renderer keys off end-to-end.
7980///
7981/// Pinned load-bearing by
7982/// [`tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7983/// (byte-parity pin against [`PlacementStrategy::from_wire`] across the
7984/// three-arm accept-set) and
7985/// [`tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7986/// (rejection witness against silent accept-set widening).
7987impl TryFrom<&str> for PlacementStrategy {
7988    type Error = ();
7989
7990    fn try_from(s: &str) -> Result<Self, Self::Error> {
7991        Self::from_wire(s).ok_or(())
7992    }
7993}
7994
7995/// Trait-idiomatic forward projection on the M3-mesh-primitive-defining
7996/// [`PlacementStrategy`] closed-set typed enum — routes byte-for-byte
7997/// through the paired substrate-primitive [`PlacementStrategy::as_str`]
7998/// `pub const fn` accessor via `strategy.as_str()`. Return type is
7999/// `&'static str` by construction — every [`PlacementStrategy::as_str`]
8000/// arm resolves to a paired lifted
8001/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
8002/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
8003/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] `pub const &str`
8004/// with static lifetime, so the trait's return-type promise is upheld
8005/// structurally without a `String::leak()` cast or a per-arm inline
8006/// literal.
8007///
8008/// Complements the pre-existing forward-projection triple
8009/// ([`std::fmt::Display`], [`AsRef<str>`], [`PlacementStrategy::as_str`])
8010/// with the trait-idiomatic forward-projection axis: Rust-side
8011/// newtype/typed-enum convention pairs [`TryFrom<&str>`] with the mirror-
8012/// image [`From<Self> for &'static str`] on the same primitive so a
8013/// caller who can project *in from* a `&str` via the trait axis can also
8014/// project *out to* one under a `'static`-lifetime bound. The
8015/// [`AsRef<str>`] impl already carries the same emit-set on the borrowed
8016/// return path; this impl closes the trait-idiomatic axis pair with the
8017/// stricter `&'static str` lifetime the sibling [`AsRef<str>`] cannot
8018/// promise (its return borrows from `&self`, not from the
8019/// [`PlacementStrategy::as_str`] `pub const fn`'s static-string result).
8020///
8021/// Same "route the trait impl through the substrate-primitive accessor"
8022/// discipline the sibling [`crate::supervisor::RestartStrategy`]
8023/// `From<Self> for &'static str` impl (523157d — first-mover on this
8024/// forward-projection family), [`crate::supervisor::RestartPolicy`]
8025/// `From<Self> for &'static str` impl (9fb37d0 — second peer, closing
8026/// the M2 OTP-shape sibling pair), [`crate::CaixaKind`]
8027/// `From<Self> for &'static str` impl (edb827b — third peer, opening
8028/// the campaign onto the top-level caixa surface), and
8029/// [`crate::CaixaDialeto`] `From<Self> for &'static str` impl (c189a6f
8030/// — fourth peer, extending onto the dialect-classification axis)
8031/// carry — extends the substrate primitive's trait-idiomatic forward-
8032/// projection axis onto the fifth closed-set fieldless typed enum on
8033/// the caixa surface: the M3-mesh-primitive-defining `:placement
8034/// :estrategia` closed-set axis the caixa-mesh renderer keys off end-
8035/// to-end, previously carrying the paired [`std::fmt::Display`] /
8036/// [`AsRef<str>`] / [`PlacementStrategy::as_str`] / [`TryFrom<&str>`] /
8037/// [`PlacementStrategy::from_wire`] forward+reverse projections but not
8038/// yet the trait-idiomatic forward projection with the `&'static str`
8039/// lifetime bound.
8040///
8041/// Same shape as the sibling [`crate::CaixaDialeto`] axis pair:
8042/// [`PlacementStrategy::as_str`] output and
8043/// [`PlacementStrategy::from_wire`] input share the same camelCase-
8044/// schema `PascalCase` vocabulary by construction (the same three
8045/// lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants
8046/// dispatch on both halves) — the trait-idiomatic axis pair
8047/// ([`From<Self> for &'static str`] + [`TryFrom<&str> for Self`])
8048/// therefore round-trips directly, without an intermediate wire-vocab
8049/// hop the peer [`crate::CaixaKind`] axis pair requires. This lift
8050/// extends the "direct round-trip" precedent
8051/// [`crate::CaixaDialeto`] (c189a6f) established onto the first M3-
8052/// mesh-primitive-defining slot enum.
8053///
8054/// The paired [`PlacementStrategy::as_str`] accessor's three-arm emit-
8055/// set is the single source of truth — every future arm addition (an
8056/// `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint names as
8057/// a trajectory item, a hypothetical `WeightedShard` variant that
8058/// carries a shard-key + per-cluster weight table under a promoted M5
8059/// adaptive-placement engine) grows the trait-idiomatic forward axis
8060/// by construction: one caixa-core edit on
8061/// [`PlacementStrategy::as_str`] extends every one of the sibling
8062/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
8063/// [`PlacementStrategy::as_str`] itself, and this [`From<Self> for
8064/// &'static str`]) without a coordinated rewrite across every future
8065/// `Into<&'static str>`-bound consumer's arm-set. This lift closes the
8066/// fifth peer on the trait-idiomatic forward-projection campaign the
8067/// recently-landed peer commits opened; the remaining nine closed-set
8068/// typed enums on the caixa substrate surface (`WitShape`,
8069/// `RateLimitUnit`, `PathShapeViolation`, `InvariantKind`,
8070/// `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
8071/// `FerriteRuntime`) are the future targets of this campaign.
8072///
8073/// Pinned load-bearing by
8074/// [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
8075/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
8076/// three-arm emit-set, plus a `const`-context materialization witness
8077/// for the `&'static str` lifetime promise routed through the paired
8078/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] lifted constants, plus
8079/// a paired `.into()` shape assertion covering the blanket-derived
8080/// `Into<&'static str>` shape) and
8081/// [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
8082/// (partition pin asserting `<&'static str as
8083/// From<PlacementStrategy>>::from` and [`PlacementStrategy::as_str`]
8084/// agree on every arm, plus a two-way direct round-trip witness through
8085/// the paired trait-idiomatic [`TryFrom<&str>`] axis that closes the
8086/// two-way `Self ↔ &'static str` round-trip on the trait-idiomatic
8087/// axis pair without the wire-vocab intermediate the peer
8088/// [`crate::CaixaKind`] axis pair requires — the emit-side
8089/// [`PlacementStrategy::as_str`] and the parse-side
8090/// [`PlacementStrategy::from_wire`] dispatch on the same three lifted
8091/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants by
8092/// construction, so round-tripping composes the two trait impls
8093/// directly).
8094impl From<PlacementStrategy> for &'static str {
8095    fn from(strategy: PlacementStrategy) -> &'static str {
8096        strategy.as_str()
8097    }
8098}
8099
8100/// Trait-idiomatic *forward* projection on [`PlacementStrategy`] from a
8101/// *borrowed* input onto the `&'static str` axis — the borrowed-input
8102/// companion to the paired owned-input [`From<PlacementStrategy> for
8103/// &'static str`] impl immediately above. Routes byte-for-byte through
8104/// the same substrate-primitive [`PlacementStrategy::as_str`] `pub const
8105/// fn` accessor so every consumer that binds a `&PlacementStrategy`
8106/// through the standard-library `.into()` / [`From<&Self> for &'static
8107/// str`] axis (a `PlacementStrategy::ALL.iter().map(<&'static
8108/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
8109/// whose iterator over `&'static [PlacementStrategy]` yields
8110/// `&PlacementStrategy`, not `PlacementStrategy`, so the owned-input
8111/// [`From<PlacementStrategy>`] axis alone forces every call site through
8112/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
8113/// rather than the direct trait-idiomatic projection; a future generic
8114/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column over
8115/// the substrate-wide closed-set typed-enum family that walks the
8116/// `iter().map(Into::into)` shape verbatim; the future M4
8117/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
8118/// body that composes the accepted-`:placement :estrategia` enumeration
8119/// from an iterated `PlacementStrategy::ALL.iter().map(|s| s.into())`
8120/// pipe rather than a per-arm `match s { … }` cascade; a future
8121/// `HashMap::<&'static str, PlacementStrategy>::from_iter(
8122///     PlacementStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8123/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`] impl
8124/// cannot compose without this borrowed-input axis in place) reaches
8125/// the same three-arm lifted
8126/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
8127/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
8128/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the paired
8129/// owned-input [`From<PlacementStrategy> for &'static str`], the sibling
8130/// [`std::fmt::Display`], [`AsRef<str>`], and [`PlacementStrategy::as_str`]
8131/// surfaces already return.
8132///
8133/// Sixth peer on the substrate-wide trait-idiomatic *borrowed-input*
8134/// forward-projection family opened on [`crate::dep::DepList`]
8135/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
8136/// [`crate::CaixaDialeto`] (807b0b5), the paired M2 OTP-shape
8137/// [`crate::supervisor::RestartStrategy`] (e941836), and
8138/// [`crate::supervisor::RestartPolicy`] (842c7f3). Rust's `From` trait
8139/// does not auto-derive the `From<&Self>` sibling from a `From<Self>`
8140/// impl (the blanket `impl<T, U> From<&T> for U where T: Copy, U:
8141/// From<T>` does not exist in `core`), so every closed-set typed enum
8142/// that carries the owned-input axis but not the borrowed-input axis
8143/// forces every borrowed-input call site through a `.copied()` /
8144/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
8145/// type bounds have no compile-time link to the substrate primitive.
8146/// [`PlacementStrategy`] is the first M3-mesh-primitive-defining
8147/// closed-set typed enum to converge onto this borrowed-input campaign
8148/// — first-mover on the M3 mesh-slot family the caixa-mesh renderer
8149/// keys off end-to-end, ahead of the sibling
8150/// [`crate::aplicacao::WitShape`] `:contratos :wit` census-label axis
8151/// (56998ec) and [`crate::aplicacao::RateLimitUnit`]
8152/// `:politicas :rate-limit` canonical-suffix axis (7fdfbf4) whose owned-
8153/// input forward-projection axes landed earlier in the substrate-wide
8154/// campaign but await the paired borrowed-input closure.
8155///
8156/// Same three-path convergence discipline as the paired owned-input
8157/// impl (this borrowed-input axis, the paired owned-input
8158/// [`From<PlacementStrategy> for &'static str`], and
8159/// [`PlacementStrategy::as_str`] all route through the same lifted
8160/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] const), so a future
8161/// variant rename or per-arm serde-attribute drift reaches every one
8162/// of the six sibling forward-projection paths
8163/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
8164/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
8165/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
8166/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
8167/// edit.
8168///
8169/// The [`PlacementStrategy::as_str`] emit and
8170/// [`PlacementStrategy::from_wire`] parse share the same `PascalCase`
8171/// vocabulary by construction — the same three lifted
8172/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants dispatch on
8173/// both halves — so the borrowed-input forward axis and the reverse
8174/// axis compose directly without the intermediate wire-vocab hop the
8175/// peer [`crate::CaixaKind`] axis pair requires. The round-trip
8176/// witness pin below locks this direct composition on the M3 slot
8177/// enum's trait-idiomatic axis pair.
8178///
8179/// Pinned load-bearing by
8180/// [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
8181/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
8182/// three-arm emit-set via a borrowed input, plus a `const`-context
8183/// materialization witness for the `&'static str` lifetime promise,
8184/// plus a blanket `.into()` shape) and
8185/// [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8186/// (cross-axis partition pin against the paired owned-input
8187/// [`From<PlacementStrategy> for &'static str`] impl, plus a
8188/// `.iter().map(Into::into)` pipe witness over
8189/// [`PlacementStrategy::ALL`], plus a direct round-trip witness through
8190/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
8191/// Self` round-trip on the M3 slot enum's trait-idiomatic axis pair
8192/// without the wire-vocab intermediate the peer [`crate::CaixaKind`]
8193/// axis pair requires).
8194impl From<&PlacementStrategy> for &'static str {
8195    fn from(strategy: &PlacementStrategy) -> &'static str {
8196        strategy.as_str()
8197    }
8198}
8199
8200/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
8201/// `:placement :estrategia` distribution-strategy [`PlacementStrategy`]
8202/// closed-set typed enum from an *owned* input onto the owned-[`String`]
8203/// axis — routes byte-for-byte through the substrate-primitive
8204/// [`PlacementStrategy::as_str`] `pub const fn` accessor so every consumer
8205/// that binds a [`PlacementStrategy`] through the standard-library
8206/// `.into()` / [`From<Self> for String`] (equivalently [`Into<String>`])
8207/// axis reaches the same three-arm lifted
8208/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
8209/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
8210/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-string the
8211/// paired owned-input [`From<PlacementStrategy> for &'static str`] (afa3562),
8212/// the borrowed-input [`From<&PlacementStrategy> for &'static str`]
8213/// (4d941d8), the sibling [`std::fmt::Display`], [`AsRef<str>`], and
8214/// [`PlacementStrategy::as_str`] surfaces already return.
8215///
8216/// Extends the trait-idiomatic *owned-[`String`]* forward-projection
8217/// family (opened on [`crate::supervisor::RestartStrategy`] — 7baa18a —
8218/// the first-mover on the M2 OTP-shape sibling-restart-strategy axis,
8219/// extended onto [`crate::supervisor::RestartPolicy`] — 7851725 — the
8220/// second-of-two-in-M2 per-child restart-decision axis, then onto
8221/// [`crate::CaixaKind`] — 231a18c — the structurally most fundamental
8222/// closed-set fieldless typed enum on the caixa surface, then onto
8223/// [`crate::CaixaDialeto`] — 88942cd — the dialect-classification axis,
8224/// then onto [`crate::dep::DepList`] — 32b0ee8 — the two-list dep-graph
8225/// axis) onto the sixth peer: the M3 mesh-primitive
8226/// `:placement :estrategia` distribution-strategy axis
8227/// [`PlacementStrategy`] carries. First M3-mesh-primitive-defining
8228/// closed-set typed enum to converge onto this owned-[`String`]
8229/// forward-projection campaign — first-mover on the M3 mesh-slot family
8230/// the caixa-mesh renderer keys off end-to-end, ahead of the sibling
8231/// [`WitShape`] `:contratos :wit` census-label axis and
8232/// [`RateLimitUnit`] `:politicas :rate-limit` canonical-suffix axis whose
8233/// owned-[`String`] axis closures remain future targets of this campaign.
8234///
8235/// Rust's standard library does not carry a blanket
8236/// `impl<T: AsRef<str>> From<T> for String` (nor an
8237/// `impl<T: fmt::Display> From<T> for String`), so every closed-set typed
8238/// enum that carries the paired [`AsRef<str>`] / [`std::fmt::Display`] /
8239/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`]
8240/// quadruple but not the owned-[`String`] axis forces every owned-string
8241/// call site through a `.to_string()` / `.as_str().to_owned()` /
8242/// `String::from(strategy.as_str())` detour whose type bounds have no
8243/// compile-time link to the substrate primitive.
8244///
8245/// Same as the peer [`crate::supervisor::RestartStrategy`] /
8246/// [`crate::supervisor::RestartPolicy`] / [`crate::CaixaDialeto`] /
8247/// [`crate::dep::DepList`] owned-[`String`] axis pairs (whose forward
8248/// emit and reverse parse share one vocabulary by construction),
8249/// [`PlacementStrategy`]'s [`PlacementStrategy::as_str`] emit and
8250/// [`PlacementStrategy::from_wire`] parse resolve through the same
8251/// three lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] consts by
8252/// construction (there is no wire/diagnostic axis split on this enum —
8253/// both halves of the round-trip route through the same three
8254/// `pub const &str` values), so the owned-[`String`] forward projection
8255/// this impl exposes composes directly with the paired trait-idiomatic
8256/// reverse [`TryFrom<&str>`] axis on the owned-[`String`]'s
8257/// [`String::as_str`] borrow — no intermediate wire-vocab hop like the
8258/// peer [`crate::CaixaKind`] axis pair requires.
8259///
8260/// The remaining nine closed-set typed enums on the caixa substrate
8261/// surface (`WitShape`, `RateLimitUnit`, `PathShapeViolation`,
8262/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
8263/// `FerriteRuntime`) are the future targets of this campaign — each
8264/// carries the same paired [`AsRef<str>`] / [`std::fmt::Display`] /
8265/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`]
8266/// quadruple that this owned-[`String`] axis extends onto.
8267///
8268/// Pinned load-bearing by
8269/// [`tests::placement_strategy_from_into_owned_string_routes_through_as_str_accessor`]
8270/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
8271/// three-arm [`PlacementStrategy::ALL`] emit-set plus a blanket
8272/// `.into::<String>()` shape witness) and
8273/// [`tests::placement_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
8274/// (cross-axis partition against the sibling owned-`&'static str` axis
8275/// and the [`ToString::to_string`] surface, a
8276/// `.iter().copied().map(String::from)` pipe witness over
8277/// [`PlacementStrategy::ALL`], plus a direct `Self → String → Self`
8278/// round-trip via [`TryFrom<&str>`] on the owned-[`String`]'s
8279/// [`String::as_str`] borrow — composes directly without the wire-vocab
8280/// intermediate hop the peer [`crate::CaixaKind`] axis pair requires).
8281impl From<PlacementStrategy> for String {
8282    fn from(strategy: PlacementStrategy) -> String {
8283        strategy.as_str().to_owned()
8284    }
8285}
8286
8287/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
8288/// projection on the M3 mesh-primitive `:placement :estrategia`
8289/// distribution-strategy [`PlacementStrategy`] closed-set typed enum —
8290/// the fourth (and closing) corner of the
8291/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
8292/// projection family on this first M3-mesh-primitive-defining slot enum.
8293/// Routes byte-for-byte through the substrate-primitive
8294/// [`PlacementStrategy::as_str`] `pub const fn` accessor (via
8295/// [`str::to_owned`]) so every consumer that holds a borrowed
8296/// [`&PlacementStrategy`] and needs an owned [`String`] — a future
8297/// `serde_json::Value::String(String::from(&strategy))` structured-
8298/// payload composer over a borrowed field, a future `Iterator::map` over
8299/// `&[PlacementStrategy]` that projects to owned keys through
8300/// `.iter().map(String::from)` (whose iterator yields
8301/// `&PlacementStrategy`, not `PlacementStrategy`, so the owned-input
8302/// [`From<PlacementStrategy> for String`] axis alone forces every call
8303/// site through an explicit `.copied()` / spurious [`Copy`] deref
8304/// restatement rather than the direct trait-idiomatic projection), a
8305/// future `HashMap::<String, PlacementStrategy>::from_iter` that keys off
8306/// a borrowed-iteration axis where dereferencing the strategy would
8307/// force an unnecessary [`Copy`] at every step, the future M4
8308/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
8309/// body composer that names the accepted-`:placement :estrategia`
8310/// enumeration through an iterated
8311/// `PlacementStrategy::ALL.iter().map(String::from).collect()` pipe
8312/// rather than a per-arm cascade, the future caixa-mesh renderer
8313/// `placement.estrategia`-column diagnostic composer whose borrowed-
8314/// iteration axis over declared strategies projects to owned keys by
8315/// construction — reaches the same three-arm lifted
8316/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
8317/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
8318/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings the
8319/// paired [`std::fmt::Display`], [`AsRef<str>`],
8320/// [`PlacementStrategy::as_str`], and the three other trait-idiomatic
8321/// forward-projection impls
8322/// ([`From<PlacementStrategy> for &'static str`],
8323/// [`From<&PlacementStrategy> for &'static str`],
8324/// [`From<PlacementStrategy> for String`]) already return.
8325///
8326/// Sixth peer on the substrate-wide trait-idiomatic *borrowed-input,
8327/// owned-`String` output* forward-projection family opened on
8328/// [`crate::supervisor::RestartStrategy`] (579385f), closed on the M2
8329/// OTP-shape sibling axis pair by
8330/// [`crate::supervisor::RestartPolicy`] (8465740), extended onto the
8331/// two-list dep-graph peer by [`crate::dep::DepList`] (e0cb617), onto
8332/// the top-level [`crate::CaixaKind`] peer by (e76436d), and onto the
8333/// dialect-classification peer by [`crate::CaixaDialeto`] (d3c0d1d) —
8334/// extends the `{Self, &Self} × {&'static str, String}` 2×2 projection
8335/// corner off the caixa-surface enum axes onto the M3 mesh-slot family
8336/// the caixa-mesh renderer keys off end-to-end. First
8337/// M3-mesh-primitive-defining closed-set typed enum to reach the
8338/// 2×2-completion corner — first-mover on the M3 slot-enum triple,
8339/// ahead of the sibling [`WitShape`] `:contratos :wit` census-label axis
8340/// and [`RateLimitUnit`] `:politicas :rate-limit` canonical-suffix axis
8341/// whose 2×2-completion corners remain future targets of this campaign.
8342/// Rust's standard library does not carry a blanket
8343/// `impl<T: AsRef<str>> From<&T> for String` (nor an
8344/// `impl<T: fmt::Display> From<&T> for String`), so every closed-set
8345/// typed enum that carries the paired `AsRef<str>` / `Display` /
8346/// `From<Self> for &'static str` / `From<&Self> for &'static str` /
8347/// `From<Self> for String` quintuple but not the borrowed-input
8348/// owned-[`String`] axis forces every borrowed-input owned-string call
8349/// site through a `strategy.as_str().to_owned()` /
8350/// `String::from(*strategy)` (with a spurious [`Copy`]) /
8351/// `strategy.to_string()` (through [`std::fmt::Display`]) detour whose
8352/// type bounds have no compile-time link to the substrate primitive.
8353///
8354/// Same three-path convergence discipline as the paired owned-input
8355/// impl (this borrowed-input axis, the paired owned-input
8356/// [`From<PlacementStrategy> for String`], and
8357/// [`PlacementStrategy::as_str`] all route through the same lifted
8358/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] const), so a future
8359/// variant rename or per-arm serde-attribute drift reaches every one
8360/// of the paired forward-projection paths through exactly one
8361/// caixa-core edit.
8362///
8363/// Same as the peer [`crate::supervisor::RestartStrategy`] /
8364/// [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`] /
8365/// [`crate::CaixaDialeto`] borrowed-input owned-[`String`] axis pairs
8366/// (whose forward emit and reverse parse share one vocabulary by
8367/// construction — `PascalCase` on the M2 OTP-shape peers and on the
8368/// [`CaixaDialeto`] peer, the lifted
8369/// [`crate::render::DEP_AUTHOR_KEY_DEPS`] /
8370/// [`crate::render::DEP_AUTHOR_KEY_DEPS_DEV`] consts on the two-list
8371/// dep-graph peer) and unlike the peer [`crate::CaixaKind`] pair
8372/// (whose forward emit lands on the lowercase Portuguese diagnostic
8373/// vocabulary while the reverse parse lands on the `PascalCase` wire
8374/// vocabulary, forcing the round-trip through an intermediate
8375/// [`crate::CaixaKind::wire_name`] hop), [`PlacementStrategy`]'s
8376/// [`PlacementStrategy::as_str`] emit and
8377/// [`PlacementStrategy::from_wire`] parse resolve through the same
8378/// three lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] consts by
8379/// construction (there is no wire/diagnostic axis split on this M3
8380/// slot enum — both halves of the round-trip route through the same
8381/// three `pub const &str` values), so the borrowed-input
8382/// owned-[`String`] projection this impl exposes composes directly
8383/// with the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
8384/// the owned-[`String`]'s [`String::as_str`] borrow — no intermediate
8385/// wire-vocab hop required.
8386///
8387/// The remaining eight closed-set typed enums on the caixa substrate
8388/// surface (`WitShape`, `RateLimitUnit`, `PathShapeViolation`,
8389/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
8390/// `FerriteRuntime`) are the future targets of this 2×2-completion
8391/// campaign — each carries the same paired quintuple that this
8392/// borrowed-input owned-[`String`] axis extends onto.
8393///
8394/// Pinned load-bearing by
8395/// [`tests::placement_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
8396/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
8397/// three-arm emit-set through the borrowed-input surface) and
8398/// [`tests::placement_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
8399/// (cross-axis partition pin against the paired owned-input owned-
8400/// [`String`] [`From<PlacementStrategy> for String`] impl, the paired
8401/// borrowed-input owned-[`&'static str`]
8402/// [`From<&PlacementStrategy> for &'static str`] impl, the paired
8403/// owned-input owned-[`&'static str`]
8404/// [`From<PlacementStrategy> for &'static str`] impl, and the sibling
8405/// [`ToString::to_string`] surface routed through
8406/// [`std::fmt::Display`], plus a `.iter().map(String::from)` pipe
8407/// witness over [`PlacementStrategy::ALL`] (whose iterator yields
8408/// `&PlacementStrategy` by construction, so the borrowed-input
8409/// owned-[`String`] axis is what routes the pipe through the
8410/// substrate-primitive [`PlacementStrategy::as_str`] accessor without
8411/// a spurious [`Copy`] deref), plus a direct round-trip witness through
8412/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
8413/// borrow that closes the two-way `&Self → String → Self` round-trip
8414/// on the trait-idiomatic borrowed-input owned-[`String`] forward +
8415/// reverse axis pair — no intermediate wire-vocab hop like the peer
8416/// [`crate::CaixaKind`] axis pair requires).
8417impl From<&PlacementStrategy> for String {
8418    fn from(strategy: &PlacementStrategy) -> String {
8419        strategy.as_str().to_owned()
8420    }
8421}
8422
8423/// Trait-idiomatic *forward* projection on the M3 mesh-primitive
8424/// `:placement :estrategia` distribution-strategy [`PlacementStrategy`]
8425/// closed-set typed enum from an *owned* input onto the
8426/// [`std::borrow::Cow<'static, str>`] axis — routes byte-for-byte
8427/// through the substrate-primitive [`PlacementStrategy::as_str`]
8428/// `pub const fn` accessor (via [`std::borrow::Cow::Borrowed`]) so
8429/// every consumer that binds a [`PlacementStrategy`] through the
8430/// standard-library `.into()` / [`From<Self> for
8431/// std::borrow::Cow<'static, str>`] (equivalently
8432/// [`Into<std::borrow::Cow<'static, str>>`]) axis reaches the same
8433/// three-arm lifted
8434/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
8435/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
8436/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-string the
8437/// paired [`From<PlacementStrategy> for &'static str`],
8438/// [`From<&PlacementStrategy> for &'static str`],
8439/// [`From<PlacementStrategy> for String`], and
8440/// [`From<&PlacementStrategy> for String`] 2×2 trait-idiomatic
8441/// forward-projection corners, the sibling [`std::fmt::Display`],
8442/// [`AsRef<str>`], and [`PlacementStrategy::as_str`] surfaces already
8443/// return, rather than an open-coded per-call-site
8444/// `std::borrow::Cow::Borrowed(strategy.as_str())` /
8445/// `std::borrow::Cow::Owned(strategy.to_string())` composition whose
8446/// type bounds have no compile-time link back to the substrate
8447/// primitive.
8448///
8449/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
8450/// [`std::borrow::Cow::Owned`] — the substrate-primitive
8451/// [`PlacementStrategy::as_str`] accessor's return carries the
8452/// `&'static str` lifetime by construction (each `match` arm resolves
8453/// to one of the three lifted
8454/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] `pub const &str`
8455/// byte-strings with static lifetime), so the zero-alloc borrowed arm
8456/// is the type-correct projection with no runtime allocation. The
8457/// paired [`std::borrow::Cow::Owned`] arm stays reachable at the call
8458/// site through the existing [`From<PlacementStrategy> for String`]
8459/// axis composed with [`std::borrow::Cow::from`] on the resulting
8460/// owned [`String`] — a caller who chose to mutate the projection
8461/// lands on the owned arm by their own composition, not by the
8462/// substrate-primitive projection silently allocating on their
8463/// behalf.
8464///
8465/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
8466/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
8467/// From<T> for Cow<'static, str>`), so the paired sibling
8468/// [`From<PlacementStrategy> for &'static str`],
8469/// [`From<PlacementStrategy> for String`], [`AsRef<str>`], and
8470/// [`std::fmt::Display`] surfaces do not implicitly extend to a
8471/// [`Cow<'static, str>`]-bound call site — every such site is forced
8472/// through a `Cow::Borrowed(strategy.as_str())` /
8473/// `Cow::Owned(strategy.to_string())` open-code whose type bounds
8474/// have no compile-time link back to the substrate primitive until
8475/// this lift.
8476///
8477/// Second M3-mesh-primitive-defining peer on the substrate-wide
8478/// trait-idiomatic [`std::borrow::Cow<'static, str>`] forward-
8479/// projection campaign — extends the axis off the M3 mesh-shape tier
8480/// opened one commit prior by the paired [`WitShape`] `:contratos
8481/// :wit` census-label first-mover (8634dec owned-input + 25690ef
8482/// borrowed-input) onto the second M3-mesh-primitive-defining slot
8483/// enum. The [`CaixaKind`](crate::CaixaKind) top-level first-mover
8484/// (99c1735 owned-input + d45c409 borrowed-input) opened the axis
8485/// on the structurally most fundamental closed-set fieldless typed
8486/// enum; the paired M2 OTP-shape
8487/// [`crate::supervisor::RestartStrategy`] (7dd28b3 + 9b3e4b3) and
8488/// [`crate::supervisor::RestartPolicy`] (0612398 + ee577fd) closed
8489/// the M2 OTP-shape tier. The remaining M3-mesh-primitive-defining
8490/// peer ([`RateLimitUnit`]) and the outside-M3 substrate-wide peers
8491/// ([`crate::dep::DepList`], [`crate::CaixaDialeto`],
8492/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
8493/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
8494/// `Semantic`, `FerriteRuntime`) are the remaining future targets of
8495/// this campaign.
8496///
8497/// Same three-path convergence discipline as the paired sibling
8498/// [`From<PlacementStrategy> for &'static str`] /
8499/// [`From<PlacementStrategy> for String`] / [`std::fmt::Display`] /
8500/// [`AsRef<str>`] surfaces (this [`Cow<'static, str>`] axis, the
8501/// paired sibling surfaces, and [`PlacementStrategy::as_str`] all
8502/// route through the same lifted
8503/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] const), so a future
8504/// variant rename or per-arm serde-attribute drift reaches every
8505/// forward-projection path through exactly one caixa-core edit.
8506///
8507/// Pinned load-bearing by
8508/// [`tests::placement_strategy_from_into_static_cow_str_routes_through_as_str_accessor`]
8509/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
8510/// against [`PlacementStrategy::as_str`] across the three-arm
8511/// [`PlacementStrategy::ALL`]) and
8512/// [`tests::placement_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
8513/// (cross-axis partition pin against the paired
8514/// [`From<PlacementStrategy> for &'static str`],
8515/// [`From<PlacementStrategy> for String`], and
8516/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
8517/// `.iter().copied().map(Cow::from)` pipe witness over
8518/// [`PlacementStrategy::ALL`] that materializes the three-arm
8519/// accept-set through the [`Cow<'static, str>`] axis alone and pins
8520/// the zero-alloc discipline on every element).
8521impl From<PlacementStrategy> for std::borrow::Cow<'static, str> {
8522    fn from(strategy: PlacementStrategy) -> std::borrow::Cow<'static, str> {
8523        std::borrow::Cow::Borrowed(strategy.as_str())
8524    }
8525}
8526
8527/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
8528/// output* forward projection on the M3-mesh-primitive-defining
8529/// `:placement :estrategia` distribution-strategy [`PlacementStrategy`]
8530/// closed-set typed enum — the borrowed-input companion to the paired
8531/// owned-input [`From<PlacementStrategy> for std::borrow::Cow<'static,
8532/// str>`] impl immediately above (eee504d). Routes byte-for-byte
8533/// through the same substrate-primitive [`PlacementStrategy::as_str`]
8534/// `pub const fn` accessor (via [`std::borrow::Cow::Borrowed`]) so
8535/// every consumer that holds a `&PlacementStrategy` and needs a
8536/// [`std::borrow::Cow<'static, str>`] — a
8537/// `PlacementStrategy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
8538/// per-arm accept-set materializer whose iterator over
8539/// `&'static [PlacementStrategy]` yields `&PlacementStrategy` (not
8540/// `PlacementStrategy`, so the paired owned-input
8541/// [`From<PlacementStrategy> for std::borrow::Cow<'static, str>`] axis
8542/// alone forces every call site through an explicit `.copied()` /
8543/// dereference / [`Copy`]-bound restatement rather than the direct
8544/// trait-idiomatic projection), a future generic
8545/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
8546/// on a per-`:placement :estrategia` diagnostic column that walks the
8547/// `iter().map(Into::into)` shape verbatim, the future M4
8548/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
8549/// body that composes the accepted-`:placement :estrategia`
8550/// enumeration from an iterated
8551/// `PlacementStrategy::ALL.iter().map(|s| s.into())` pipe rather than
8552/// a per-arm `match s { … }` cascade — reaches the same three-arm
8553/// lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
8554/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
8555/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-string the
8556/// paired [`std::fmt::Display`], [`AsRef<str>`],
8557/// [`PlacementStrategy::as_str`], the four
8558/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
8559/// forward-projection corners, and the paired owned-input
8560/// [`From<PlacementStrategy> for std::borrow::Cow<'static, str>`] impl
8561/// already return.
8562///
8563/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
8564/// [`std::borrow::Cow::Owned`] — the substrate-primitive
8565/// [`PlacementStrategy::as_str`] accessor's return carries the
8566/// `&'static str` lifetime by construction (each `match` arm resolves
8567/// to one of the three lifted
8568/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] `pub const &str`
8569/// byte-strings with static lifetime), so the zero-alloc borrowed arm
8570/// is the type-correct projection with no runtime allocation on the
8571/// borrowed-input surface just as on the paired owned-input surface.
8572///
8573/// Closes the `{Self, &Self}` input-shape corner on the M3-mesh-shape
8574/// `:placement :estrategia` distribution-strategy
8575/// [`std::borrow::Cow<'static, str>`] axis opened one commit prior
8576/// (eee504d) on the paired owned-input [`From<PlacementStrategy> for
8577/// std::borrow::Cow<'static, str>`] impl — second M3-mesh-primitive-
8578/// defining peer on the axis, one commit after the sibling
8579/// [`WitShape`] `:contratos :wit` census-label first-mover (8634dec
8580/// owned-input + 25690ef borrowed-input) closed the first
8581/// M3-mesh-primitive-defining slot enum, exactly as d45c409 closed
8582/// the axis on the top-level [`crate::CaixaKind`] one commit after
8583/// the owning half (99c1735) landed and as 9b3e4b3 / ee577fd closed
8584/// it on the M2 OTP-shape [`crate::supervisor::RestartStrategy`] /
8585/// [`crate::supervisor::RestartPolicy`] sibling peers one commit
8586/// after their owning halves (7dd28b3 / 0612398) landed. Rust's
8587/// standard library does not carry a blanket
8588/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
8589/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
8590/// closed-set fieldless typed enum peer on the substrate that carries
8591/// the paired owned-input [`Cow<'static, str>`] axis but not the
8592/// borrowed-input axis forces every borrowed-input
8593/// [`Cow<'static, str>`]-parameterized call site through a spurious
8594/// [`Copy`] deref (`std::borrow::Cow::from(*strategy)`) or a
8595/// `std::borrow::Cow::Borrowed(strategy.as_str())` open-code whose
8596/// type bounds have no compile-time link to the substrate primitive.
8597///
8598/// The remaining M3-mesh-primitive-defining peer ([`RateLimitUnit`])
8599/// and the outside-M3 substrate-wide peers ([`crate::dep::DepList`],
8600/// [`crate::CaixaDialeto`], [`crate::render::PathShapeViolation`],
8601/// and the outside-`caixa-core` peers `InvariantKind`, `ArchVerdict`,
8602/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
8603/// remaining future targets of the campaign; closing this
8604/// borrowed-input corner on [`PlacementStrategy`] leaves
8605/// [`RateLimitUnit`] as the last un-lifted M3-mesh-primitive-defining
8606/// slot enum on the [`Cow<'static, str>`] axis.
8607///
8608/// Pinned load-bearing by
8609/// [`tests::placement_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
8610/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
8611/// against [`PlacementStrategy::as_str`] across the three-arm
8612/// [`PlacementStrategy::ALL`] through the borrowed-input surface) and
8613/// [`tests::placement_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
8614/// (cross-axis partition pin against the paired owned-input
8615/// [`From<PlacementStrategy> for std::borrow::Cow<'static, str>`], the
8616/// paired borrowed-input owned-`&'static str`
8617/// [`From<&PlacementStrategy> for &'static str`], and the paired
8618/// borrowed-input owned-`String` [`From<&PlacementStrategy> for
8619/// String`] impls, plus a `.iter().map(std::borrow::Cow::from)` pipe
8620/// witness over [`PlacementStrategy::ALL`] — whose iterator yields
8621/// `&PlacementStrategy` by construction, so the borrowed-input
8622/// [`Cow<'static, str>`] axis is what routes the pipe through the
8623/// substrate-primitive [`PlacementStrategy::as_str`] accessor with the
8624/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
8625/// spurious [`Copy`] deref).
8626impl From<&PlacementStrategy> for std::borrow::Cow<'static, str> {
8627    fn from(strategy: &PlacementStrategy) -> std::borrow::Cow<'static, str> {
8628        std::borrow::Cow::Borrowed(strategy.as_str())
8629    }
8630}
8631
8632/// Where the Aplicacao runs.
8633#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
8634#[serde(rename_all = "camelCase")]
8635pub struct Placement {
8636    /// Distribution strategy.
8637    #[serde(default)]
8638    pub estrategia: PlacementStrategy,
8639
8640    /// Named clusters that host this Aplicacao. Required for
8641    /// `Replicated` and `SingleNode`; for `Sharded` declares the
8642    /// shard pool.
8643    #[serde(default)]
8644    pub clusters: Vec<String>,
8645
8646    /// Optional hint to the placement engine: `"data-locality"`,
8647    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
8648    #[serde(default, skip_serializing_if = "Option::is_none")]
8649    pub affinity: Option<String>,
8650
8651    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
8652    #[serde(default, skip_serializing_if = "Option::is_none")]
8653    pub shard_key: Option<String>,
8654}
8655
8656impl Placement {
8657    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
8658    /// `:shard-key` extractor-expression scalar accessor every consumer
8659    /// of the Aplicacao's hash-keyed distribution routing keys off —
8660    /// returns the author-declared `:placement :shard-key` byte-string
8661    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
8662    /// own `Option<String>` storage; `None` when the slot is absent
8663    /// (the canonical shape under `:estrategia Replicated` /
8664    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
8665    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
8666    /// partition — `validate` refuses any `Placement` past this call
8667    /// that lands `Some` on a non-`Sharded` strategy or `None` on
8668    /// `Sharded`).
8669    ///
8670    /// The `:placement :shard-key` slot carries the Akka-style
8671    /// cluster-sharding entity-id extractor expression
8672    /// (MESH-COMPOSITION §II.4) — validated by
8673    /// [`validate_placement_shard_key`] to be a non-empty printable-
8674    /// ASCII single-token reference (`tenantId`, `$tenantId`,
8675    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
8676    /// future M4 Akka-style cluster-sharding reconciler hashes without
8677    /// re-validating at the runtime layer), and every downstream
8678    /// consumer that reads the key keys off this scalar (the
8679    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
8680    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
8681    /// declared-but-inert refusal diagnostic, the caixa-mesh
8682    /// per-Aplicacao `placement.shardKey` emit path the substrate
8683    /// operator's per-entity hash-routing reader consumes, the future
8684    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8685    /// per-shard-key resolver).
8686    ///
8687    /// Prior to this lift the `.shard_key` field was accessed inline at
8688    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
8689    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
8690    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
8691    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
8692    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
8693    /// — two open-coded field-accesses that expressed no compile-time
8694    /// link back to the typed slot. A future extension of the
8695    /// `:placement :shard-key` axis to a richer author surface — a
8696    /// per-cluster override the operator pins through a future
8697    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
8698    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
8699    /// alias table the M4 CR materializer resolves per-CR, a
8700    /// per-Aplicacao dynamic `:shard-key` derivation the future
8701    /// adaptive placement engine computes from `:affinity` weights —
8702    /// would have had to be threaded through both open-coded copies in
8703    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
8704    /// arm refusal would silently disagree on which extractor
8705    /// expression a given Placement resolves to. Lifting the resolution
8706    /// rule to a typed method on the substrate primitive means every
8707    /// downstream consumer of the Aplicacao's per-`:placement`
8708    /// hash-key surface reaches for exactly one typed dispatch — the
8709    /// resolver's accept-set migrates as a unit on any future axis
8710    /// addition.
8711    ///
8712    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
8713    /// [`WitContract::destination`] / [`WitContract::world_ref`]
8714    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
8715    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
8716    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
8717    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
8718    /// typed dispatch on the substrate primitive, thin projections at
8719    /// each consumer" discipline extended onto the per-`:placement`
8720    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
8721    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
8722    /// — opens the "optional per-slot scalar" projection pattern the
8723    /// sibling per-`:placement` `:affinity`, per-`:politicas`
8724    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
8725    /// match the storage field's name; the accessor's identity name
8726    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
8727    /// slot's docstring already carries.
8728    #[must_use]
8729    pub const fn shard_key(&self) -> Option<&str> {
8730        match &self.shard_key {
8731            Some(s) => Some(s.as_str()),
8732            None => None,
8733        }
8734    }
8735
8736    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
8737    /// compression-hint scalar accessor every weighting-consumer of the
8738    /// Aplicacao's per-hint routing surface keys off — returns the
8739    /// author-declared `:placement :affinity` byte-string verbatim as
8740    /// an `Option<&str>`, borrowed from the typed slot's own
8741    /// `Option<String>` storage; `None` when the slot is absent (the
8742    /// canonical shape of an Aplicacao that leaves the compression
8743    /// weighting up to the placement engine's cluster-default arm — no
8744    /// author-authored `data-locality` / `low-latency` / etc. hint
8745    /// biases the routing).
8746    ///
8747    /// The `:placement :affinity` slot carries the M3 Adaptive-
8748    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
8749    /// by [`validate_placement_affinity`] to be a DNS-1123 label
8750    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
8751    /// K8s-conformant label-selector shape every apiserver-side pod-
8752    /// affinity / node-affinity materializer already gates on
8753    /// admission), and every downstream consumer that reads the hint
8754    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
8755    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
8756    /// `placement.affinity` overlay emit path the substrate operator's
8757    /// per-hint weighting-consumer reads, the future M4
8758    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
8759    /// pod-affinity / node-affinity selector resolver).
8760    ///
8761    /// Prior to this lift the `.affinity` field was accessed inline at
8762    /// the sole caixa-core site — the
8763    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
8764    /// `if let Some(a) = &self.placement.affinity { …
8765    /// validate_placement_affinity(a)? … }` cascade — one open-coded
8766    /// field-access that expressed no compile-time link back to the
8767    /// typed slot. A future extension of the `:placement :affinity`
8768    /// axis to a richer author surface — a per-cluster override the
8769    /// operator pins through a future `:placement :affinity-overrides`
8770    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
8771    /// tenant hint alias table the M4 CR materializer resolves per-CR,
8772    /// a per-Aplicacao dynamic `:affinity` derivation the future
8773    /// adaptive placement engine computes from `:clusters` topology —
8774    /// would have had to be threaded through the open-coded copy in
8775    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
8776    /// materializer reader that landed on the axis, or the per-hint
8777    /// value-shape gate and its downstream weighting consumers would
8778    /// silently disagree on which hint a given Placement resolves to.
8779    /// Lifting the resolution rule to a typed method on the substrate
8780    /// primitive means every downstream consumer of the Aplicacao's
8781    /// per-`:placement` compression-hint surface reaches for exactly
8782    /// one typed dispatch — the resolver's accept-set migrates as a
8783    /// unit on any future axis addition.
8784    ///
8785    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
8786    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
8787    /// optional-scalar axis — same "one typed dispatch on the substrate
8788    /// primitive, thin projections at each consumer" discipline extended
8789    /// onto the per-`:placement` M3-Adaptive-compression-hint
8790    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
8791    /// return accessor on the M3 mesh-slot family; closes the last
8792    /// un-lifted per-`:placement` `Option<String>` axis. Named
8793    /// `affinity()` to match the storage field's name; the accessor's
8794    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
8795    /// vocabulary the slot's docstring already carries.
8796    #[must_use]
8797    pub const fn affinity(&self) -> Option<&str> {
8798        match &self.affinity {
8799            Some(s) => Some(s.as_str()),
8800            None => None,
8801        }
8802    }
8803
8804    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
8805    /// strategy scalar accessor every consumer that dispatches on the
8806    /// Aplicacao's per-cluster distribution shape keys off — returns the
8807    /// author-declared `:placement :estrategia` variant verbatim as a
8808    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
8809    /// `PlacementStrategy` storage.
8810    ///
8811    /// The `:placement :estrategia` slot carries the closed-set
8812    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
8813    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
8814    /// `Replicated` — active-active across every named cluster; `Sharded`
8815    /// — Akka-style hash-keyed entity distribution across the cluster pool
8816    /// per §II.4) that every downstream consumer of the Aplicacao's
8817    /// per-cluster fan-out shape keys off. Validated by
8818    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
8819    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
8820    /// matches!(estrategia, Sharded)` — the cross-slot partition the
8821    /// [`Placement::shard_key`] accessor's docstring pins), and every
8822    /// downstream consumer that reads the strategy keys off this scalar
8823    /// (the [`AplicacaoSpec::validate_placement`]
8824    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
8825    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
8826    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
8827    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
8828    /// declared-but-inert refusal's
8829    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
8830    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
8831    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
8832    /// emit path the substrate operator's per-strategy fan-out reader
8833    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
8834    /// materializer's per-strategy admission-webhook resolver).
8835    ///
8836    /// Prior to this lift the `.estrategia` field was accessed inline at
8837    /// four sites — the [`AplicacaoSpec::validate_placement`]
8838    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
8839    /// `estrategia: self.placement.estrategia`, the same method's
8840    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
8841    /// partition dispatch, the non-`Sharded`-arm
8842    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
8843    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
8844    /// per-Aplicacao strategy print line at
8845    /// `println!("… {} …", spec.placement.estrategia, …)`
8846    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
8847    /// expressed no compile-time link back to the typed slot. A future
8848    /// extension of the `:placement :estrategia` axis to a richer author
8849    /// surface (a per-cluster override the operator pins through a future
8850    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
8851    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
8852    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
8853    /// derivation the future adaptive placement engine computes from
8854    /// `:affinity` + `:clusters` topology) would have had to be threaded
8855    /// through every open-coded copy in lockstep — one consumer reading
8856    /// the raw variant while a peer read the operator-resolved variant
8857    /// would silently split the `PlacementWithoutClusters` /
8858    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
8859    /// partition-dispatch input, a two-consumer split at the validator
8860    /// far from the source `caixa.lisp` with no field naming the
8861    /// strategy-drift root cause. Lifting the resolution rule to a typed
8862    /// method on the substrate primitive means every downstream consumer
8863    /// of the Aplicacao's per-`:placement` distribution-strategy surface
8864    /// reaches for exactly one typed dispatch — the resolver's accept-set
8865    /// migrates as a unit on any future axis addition.
8866    ///
8867    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
8868    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
8869    /// same "one typed dispatch on the substrate primitive, thin
8870    /// projections at each consumer" discipline extended onto the
8871    /// per-`:placement` distribution-strategy `Copy`-composite-enum
8872    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
8873    /// family; first `Copy`-return accessor on the M3 mesh-slot
8874    /// `Placement` type — companion to the sibling per-`:placement`
8875    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
8876    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
8877    /// optional-scalar axes, closing the last unlifted per-`:placement`
8878    /// scalar-value axis (the closed-set `PlacementStrategy`
8879    /// distribution-strategy discriminator) so every downstream
8880    /// per-`:placement` reader now routes through a typed dispatch on
8881    /// the substrate primitive. Named `estrategia()` to match the storage
8882    /// field's name; the accessor's identity name maps onto the
8883    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
8884    /// already carries. Declared `pub const fn` (matching the peer M3
8885    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
8886    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
8887    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
8888    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
8889    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
8890    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
8891    /// [`RateLimit`] — every one a `pub const fn`) so every future
8892    /// substrate-side `const`-context consumer of the resolved
8893    /// distribution-strategy variant (a `const _: () = assert!(…)`
8894    /// module-scope invariant pin on a per-fixture typed [`Placement`],
8895    /// a future M4 admission-webhook `const fn` resolver over a typed
8896    /// [`Placement`], any `const fn` composer that fans on the strategy
8897    /// at compile time) reaches through the same typed dispatch on the
8898    /// substrate primitive at const-eval time as at runtime. Pinned by
8899    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
8900    /// const-eval posture at module scope via `const _:() = …` items so
8901    /// any future accidental downgrade to non-`const` trips at caixa-core
8902    /// build time.
8903    #[must_use]
8904    pub const fn estrategia(&self) -> PlacementStrategy {
8905        self.estrategia
8906    }
8907
8908    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
8909    /// per-cluster distribution-target slice accessor every consumer that
8910    /// walks the Aplicacao's declared cluster-pool keys off — returns the
8911    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
8912    /// `&[String]` slice-view, borrowed from the typed slot's own
8913    /// `Vec<String>` storage (a zero-copy slice-view over the same
8914    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
8915    /// through). Non-optional: the empty slice is the load-bearing
8916    /// pre-validation sentinel every downstream consumer of the paired
8917    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
8918    /// off — every strategy in the closed
8919    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
8920    /// requires a non-empty list (`SingleNode` / `Replicated` use the
8921    /// list as hosting / takeover candidates per Erlang/OTP distributed-
8922    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
8923    /// shard pool per Akka cluster-sharding convention, §II.4), so the
8924    /// `.is_empty()` probe is the shared pre-condition every
8925    /// [`AplicacaoSpec::validate_placement`] arm heads on.
8926    ///
8927    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
8928    /// 1123-label per-cluster distribution-target list — the same
8929    /// set-not-multiset shape the sibling `:membros :caixa` /
8930    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
8931    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
8932    /// pins the shape). Every downstream consumer that fans on the list
8933    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
8934    /// pre-flight `.is_empty()` probe that trips
8935    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
8936    /// per-cluster value-shape + duplicate-detection fan-out loop, the
8937    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
8938    /// that materializes the list verbatim onto every
8939    /// programs.yaml entry the substrate operator's per-cluster
8940    /// `placement.clusters | contains .Values.cluster` filter reads,
8941    /// the `feira app graph` per-Aplicacao cluster print line, the
8942    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8943    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
8944    /// placement engine's cluster-topology reader).
8945    ///
8946    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
8947    /// inline at three production sites — the
8948    /// [`AplicacaoSpec::validate_placement`] pre-flight
8949    /// `self.placement.clusters.is_empty()` refusal probe, the same
8950    /// method's per-cluster validate loop's
8951    /// `for c in &self.placement.clusters` traversal head, and the
8952    /// `feira app graph` per-Aplicacao print line's
8953    /// `spec.placement.clusters` `{:?}` formatter argument
8954    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
8955    /// that expressed no compile-time link back to the typed slot. A
8956    /// future extension of the `:placement :clusters` axis to a richer
8957    /// author surface (a per-tenant cluster-pool overlay the operator
8958    /// pins through a future `:placement :clusters-overrides` slot the
8959    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
8960    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
8961    /// the future M5 adaptive-placement engine computes from
8962    /// `:affinity` weights + live cluster-topology probes, a promotion
8963    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
8964    /// partition once the substrate operator's cluster-membership
8965    /// reconciler comes into typed scope) would have had to be threaded
8966    /// through all three open-coded copies in lockstep or one consumer
8967    /// would silently disagree with the peers on which cluster-pool a
8968    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
8969    /// reading the raw slot while the peer per-cluster validate loop
8970    /// read an operator-resolved slot would silently split the paired
8971    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
8972    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
8973    /// input from the pre-flight input, a three-consumer split at the
8974    /// validator and formatter far from the source `caixa.lisp` with
8975    /// no field naming the cluster-pool-drift root cause. Lifting the
8976    /// resolution rule to a typed method on the substrate primitive
8977    /// means every downstream consumer of the Aplicacao's
8978    /// per-`:placement` cluster-pool surface reaches for exactly one
8979    /// typed dispatch — the resolver's accept-set migrates as a unit
8980    /// on any future axis addition.
8981    ///
8982    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
8983    /// slot — sibling to the seed M2
8984    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
8985    /// slice-return accessor on the peer per-`:supervisor` static-
8986    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
8987    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
8988    /// primitive, thin projections at each consumer" discipline. The
8989    /// three peer `Vec`-carry axes still unlifted at the time of this
8990    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
8991    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
8992    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
8993    /// [`crate::UpgradeFromEntry::instructions`]
8994    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
8995    /// — inherit this accessor's discipline as future compounding runs
8996    /// migrate their consumers onto the shared slice-return shape.
8997    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
8998    /// type, sibling to the two `Option<&str>`-return
8999    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
9000    /// (74ec2d3) accessors and the `Copy`-return
9001    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
9002    /// unlifted per-`:placement` field axis (the `Vec<String>`
9003    /// distribution-target-list carrier) so every downstream
9004    /// per-`:placement` reader now routes through a typed dispatch on
9005    /// the substrate primitive. Named `clusters()` to match the storage
9006    /// field's name verbatim and the tatara-lisp author-surface term
9007    /// (`:clusters`) the field's own docstring already carries; the
9008    /// accessor's identity maps onto the canonical MESH-COMPOSITION
9009    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
9010    /// for. Returns `&[String]` (not `&Vec<String>`) because every
9011    /// downstream consumer of the cluster list treats it as a read-only
9012    /// sequence — the slice-view is the narrowest borrow that supports
9013    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
9014    /// `.len()`) without leaking the backing `Vec`'s
9015    /// grow/push/reserve surface that no consumer of the typed view
9016    /// reaches for (the storage-side `Vec` remains reachable through
9017    /// the `pub clusters` field for the mutation-carrying serde
9018    /// round-trip and per-test fixture-mutation paths).
9019    #[must_use]
9020    pub const fn clusters(&self) -> &[String] {
9021        self.clusters.as_slice()
9022    }
9023}
9024
9025impl Default for Placement {
9026    fn default() -> Self {
9027        Self {
9028            // Route the struct-literal `estrategia` default arm through
9029            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
9030            // typed `pub const` rather than the transitively-derived
9031            // [`PlacementStrategy::default`] route — one source of truth
9032            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
9033            // active-active-across-every-named-cluster arm
9034            // (MESH-COMPOSITION §II.2) that both this struct-literal
9035            // altitude and the sibling [`Default for PlacementStrategy`]
9036            // impl already key off through the same substrate primitive.
9037            // Pinned by
9038            // `placement_default_estrategia_routes_through_lifted_default`.
9039            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
9040            clusters: Vec::new(),
9041            affinity: None,
9042            shard_key: None,
9043        }
9044    }
9045}
9046
9047// ── external entry point ─────────────────────────────────────────────
9048
9049/// External entry point — what an outside caller sees. Renders to a
9050/// Gateway / Ingress + a route to the named member Servico.
9051#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
9052#[serde(rename_all = "camelCase")]
9053pub struct Entrada {
9054    /// Public hostname (e.g. `"checkout.quero.cloud"`).
9055    pub host: String,
9056
9057    /// Member Servico the gateway routes to. Must be in `:membros`.
9058    pub para: String,
9059
9060    /// Optional path filter — if set, only matching paths route to
9061    /// this Aplicacao (the rest fall through to other route rules).
9062    #[serde(default)]
9063    pub paths: Vec<String>,
9064
9065    /// Default port on the destination Servico (the trigger.service.port).
9066    #[serde(default = "default_port")]
9067    pub port: u16,
9068}
9069
9070impl Entrada {
9071    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
9072    /// every HTTPRoute-aware renderer keys off — returns the author-
9073    /// declared `:entrada :paths` list verbatim when non-empty, and the
9074    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
9075    /// all fallback otherwise (so an Aplicacao author who declares an
9076    /// external `:entrada` block but no per-path rule surface still
9077    /// gets a route whose sole `HTTPPathMatch` matches every incoming
9078    /// request under the paired
9079    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
9080    ///
9081    /// Prior to this lift the "if `:entrada :paths` is empty use the
9082    /// substrate catch-all; else return each declared path verbatim"
9083    /// cascade lived inline at
9084    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
9085    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
9086    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
9087    /// substrate ships today, with no typed method on the substrate
9088    /// primitive that named the rule. A future path-resolution axis
9089    /// addition — a per-cluster `:entrada :default-path` override the
9090    /// operator pins through a future `:placement`-scoped slot, an
9091    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
9092    /// admission-webhook floor that materializes the catch-all before
9093    /// the CR lands, a future per-`:entrada :paths` overlay from a
9094    /// per-cluster policy the future `feira app deploy` pipeline
9095    /// consumes — would have to be threaded through every renderer's
9096    /// inline copy of the cascade in lockstep or one consumer would
9097    /// silently disagree with the peers on which path list a given
9098    /// `:entrada` block resolves to. Lifting the rule to a typed
9099    /// method on the substrate primitive means every downstream
9100    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
9101    /// per-cluster overlay resolver, every future per-Aplicacao
9102    /// snapshot renderer) reaches for exactly one typed dispatch —
9103    /// the resolver's accept-set moves as a unit on any future axis
9104    /// addition.
9105    ///
9106    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
9107    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
9108    /// per-`:entrada` scalar-value axes — extends the "one typed
9109    /// dispatch on the substrate primitive, thin projections at each
9110    /// consumer" discipline onto the per-`:entrada` path-list
9111    /// resolution axis every HTTPRoute-aware renderer consumes. Same
9112    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
9113    /// sibling `:politicas` primitive — one typed method on the
9114    /// substrate primitive that names the cascade every renderer
9115    /// otherwise re-inlines.
9116    #[must_use]
9117    pub fn resolved_paths(&self) -> Vec<&str> {
9118        // Route the internal cascade-head + per-entry projection reads
9119        // through the lifted [`Self::paths`] slice accessor rather than
9120        // the raw `self.paths` field access — the substrate-primitive
9121        // per-`:entrada` path-list resolver's two internal reads now
9122        // key off the canonical raw-slot surface every downstream
9123        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
9124        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
9125        // entrada summary line's `{:?}` Debug print) routes through, so
9126        // any future rebrand on the typed slot's raw-slot reader lands
9127        // at exactly one place. Same two-consumer coherence discipline
9128        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
9129        // the peer M3 mesh-slot `Vec<String>`-carry axis.
9130        if self.paths().is_empty() {
9131            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
9132        } else {
9133            self.paths().iter().map(String::as_str).collect()
9134        }
9135    }
9136
9137    /// Substrate-canonical per-`:entrada` DNS-hostname singular
9138    /// accessor every Gateway-API `Listener.hostname` reader keys off
9139    /// — returns the author-declared `:entrada :host` byte-string
9140    /// verbatim as a `&str`, borrowed from the typed slot's own
9141    /// [`String`] storage.
9142    ///
9143    /// Named the "singular" half of the DNS-hostname resolver pair on
9144    /// the substrate primitive: the parent-Gateway per-listener
9145    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
9146    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
9147    /// hostname per listener), and this accessor is the typed dispatch
9148    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
9149    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
9150    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
9151    /// per-Aplicacao ingress-hostname surface projects onto.
9152    ///
9153    /// Prior to this lift the `entrada.host.clone()` byte-string was
9154    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
9155    /// per-listener singular `hostname:` axis
9156    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
9157    /// per-HTTPRoute plural `spec.hostnames[]` axis
9158    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
9159    /// consumers read the same `entrada.host` field but the two-site
9160    /// duplication expressed no compile-time contract that the singular
9161    /// Gateway-listener filter and the plural `HTTPRoute` filter list
9162    /// stay in lockstep on future extensions of the `:entrada` slot to
9163    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
9164    /// overlay, a per-cluster SNI fan-out the operator pins through a
9165    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
9166    /// Aplicacao` CR materializer's per-listener virtual-host filter
9167    /// admission-webhook overlay). Any such extension would have to be
9168    /// threaded through every renderer's inline copy of the resolution
9169    /// in lockstep or the Gateway listener's `hostname:` filter would
9170    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
9171    /// — a Gateway-API-conformance divergence whose apply-time symptom
9172    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
9173    /// `NoMatchingParent` — the API server rejects the route because
9174    /// its `hostnames[]` filter doesn't intersect the parent listener's
9175    /// `hostname` filter) is far from the source `caixa.lisp` and never
9176    /// surfaces in the emitted YAML. Lifting the singular and plural
9177    /// resolvers to typed methods on the substrate primitive means
9178    /// every consumer of the Aplicacao's ingress-hostname surface
9179    /// reaches for exactly one typed dispatch, and the pair-invariant
9180    /// `hostnames() == vec![hostname()]` pinned by the sibling
9181    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
9182    /// keeps the two axes in lockstep by construction.
9183    ///
9184    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
9185    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
9186    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
9187    /// the substrate primitive, thin projections at each consumer"
9188    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
9189    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
9190    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
9191    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
9192    /// `:entrada` scalar-value + list-value axes.
9193    #[must_use]
9194    pub const fn hostname(&self) -> &str {
9195        self.host.as_str()
9196    }
9197
9198    /// Substrate-canonical per-`:entrada` DNS-hostname plural
9199    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
9200    /// keys off — returns the singleton `[hostname()]` list under
9201    /// today's single-hostname-per-Aplicacao author surface, and the
9202    /// authoritative multi-hostname list under a future
9203    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
9204    ///
9205    /// Plural half of the DNS-hostname resolver pair — see the
9206    /// companion [`Entrada::hostname`] docstring for the two-consumer
9207    /// lift + pair-invariant discipline (`hostnames() ==
9208    /// vec![hostname()]`, pinned load-bearing by the sibling
9209    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
9210    /// test).
9211    ///
9212    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
9213    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
9214    /// per-rule path-list axis — same `Vec<&str>` shape, same
9215    /// substrate-primitive-owns-the-resolver discipline extended to
9216    /// the per-HTTPRoute virtual-host filter-list axis.
9217    #[must_use]
9218    pub fn hostnames(&self) -> Vec<&str> {
9219        vec![self.hostname()]
9220    }
9221
9222    /// Substrate-canonical per-`:entrada` destination-Servico scalar
9223    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
9224    /// the author-declared `:entrada :para` byte-string verbatim as a
9225    /// `&str`, borrowed from the typed slot's own [`String`] storage.
9226    ///
9227    /// The `:entrada :para` slot names the single member Servico the
9228    /// external Gateway routes to (validated by
9229    /// [`AplicacaoSpec::validate`] to be a
9230    /// [`Membro::caixa`] the Aplicacao declares — a stray
9231    /// `:para` that doesn't name a member is
9232    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
9233    /// backend-attachment miss at cluster-apply time). Under today's
9234    /// single-destination author surface `:entrada :para` is the ingress
9235    /// apex Servico's canonical identity; under a hypothetical
9236    /// future multi-backend author surface (a `:entrada
9237    /// :split :backends` weighted-fan-out overlay for canary /
9238    /// blue-green traffic-split rollouts, per-path override for
9239    /// path-based per-Servico routing beyond the single-apex model,
9240    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
9241    /// per-CR admission-webhook that promotes the scalar to a
9242    /// weighted list) this accessor is the substrate primitive's typed
9243    /// dispatch every downstream `HTTPRoute`-aware consumer routes
9244    /// through, so the resolution shape migrates as a unit on one
9245    /// caixa-core edit rather than a coordinated rewrite across every
9246    /// renderer's inline field-access.
9247    ///
9248    /// Prior to this lift the `entrada.para` byte-string was accessed
9249    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
9250    /// `metadata.name` composer's per-destination discriminator arg
9251    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
9252    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
9253    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
9254    /// (`entrada.para.clone()`,
9255    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
9256    /// consumers read the same `entrada.para` field but the two-site
9257    /// duplication expressed no compile-time contract that the HTTPRoute
9258    /// name-discriminator and the per-rule backend name stay in
9259    /// lockstep on future extensions of the `:entrada` slot to a
9260    /// multi-destination author surface. Any such extension would have
9261    /// to be threaded through every renderer's inline copy of the
9262    /// destination projection in lockstep or the HTTPRoute
9263    /// `metadata.name` would silently reference a different destination
9264    /// than its own `backendRefs[]` — an operator-side
9265    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
9266    /// grep-by-name lookup would land on a route whose `backendRefs[]`
9267    /// silently point at a peer Servico, dropping every external
9268    /// `:entrada` flow at the gateway with the destination-drift root
9269    /// cause invisible in the emitted YAML.
9270    ///
9271    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
9272    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
9273    /// the per-listener singular / per-HTTPRoute plural filter axes and
9274    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
9275    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
9276    /// typed dispatch on the substrate primitive, thin projections at
9277    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
9278    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
9279    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
9280    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
9281    /// sibling per-`:entrada` scalar-value + list-value axes — this
9282    /// accessor closes the last unlifted per-`:entrada` scalar axis
9283    /// (the destination-Servico byte-string) so every downstream
9284    /// per-`:entrada` reader now routes through a typed dispatch on
9285    /// the substrate primitive.
9286    #[must_use]
9287    pub const fn destination(&self) -> &str {
9288        self.para.as_str()
9289    }
9290
9291    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
9292    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
9293    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
9294    /// reader keys off — returns the author-declared `:entrada :port`
9295    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
9296    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
9297    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
9298    /// [`AplicacaoError::EntradaPortZero`], not a silent
9299    /// admission-webhook rejection at cluster-apply time).
9300    ///
9301    /// The `:entrada :port` slot carries the destination Servico's
9302    /// canonical in-cluster L4 listener port (`trigger.service.port` on
9303    /// the `pleme-computeunit` library chart), and every downstream
9304    /// consumer that reads the port keys off this scalar (the
9305    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
9306    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
9307    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
9308    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
9309    /// CR materializer's per-Aplicacao gateway port resolver).
9310    ///
9311    /// Prior to this lift the `.port` field was accessed inline at two
9312    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
9313    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
9314    /// the [`AplicacaoSpec::port_for_destination`] resolver's
9315    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
9316    /// open-coded field-accesses that expressed no compile-time link
9317    /// back to the typed slot. A future extension of the `:entrada :port`
9318    /// axis to a richer author surface — a per-cluster override the
9319    /// operator pins through a future `:placement :default-port` slot the
9320    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
9321    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
9322    /// heterogeneous listener ports, an M4
9323    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
9324    /// admission-webhook floor that promotes the scalar to a
9325    /// per-destination map — would have had to be threaded through both
9326    /// open-coded copies in lockstep or the structural-floor validator
9327    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
9328    /// silently disagree on which port a given [`Entrada`] resolves to.
9329    /// Lifting the resolution rule to a typed method on the substrate
9330    /// primitive means every downstream consumer of the Aplicacao's
9331    /// per-`:entrada` L4-port surface reaches for exactly one typed
9332    /// dispatch — the resolver's accept-set migrates as a unit on any
9333    /// future axis addition.
9334    ///
9335    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
9336    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
9337    /// accessors on the per-`:entrada` scalar-value axis — same "one
9338    /// typed dispatch on the substrate primitive, thin projections at
9339    /// each consumer" discipline extended onto the per-`:entrada`
9340    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
9341    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
9342    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
9343    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
9344    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
9345    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
9346    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
9347    /// storage field's name; the accessor's identity name maps onto the
9348    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
9349    /// already carries. Declared `pub const fn` (matching the peer M3
9350    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
9351    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
9352    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
9353    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
9354    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
9355    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
9356    /// [`RateLimit`], and the sibling per-`:placement`
9357    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
9358    /// enum scalar axis — every one a `pub const fn`) so every future
9359    /// substrate-side `const`-context consumer of the resolved
9360    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
9361    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
9362    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
9363    /// admission-webhook `const fn` per-CR gateway-port floor over a
9364    /// typed [`Entrada`], any `const fn` composer that fans on the port
9365    /// at compile time) reaches through the same typed dispatch on the
9366    /// substrate primitive at const-eval time as at runtime. Pinned by
9367    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
9368    /// const-eval posture at module scope via `const _:() = …` items so
9369    /// any future accidental downgrade to non-`const` trips at caixa-core
9370    /// build time.
9371    #[must_use]
9372    pub const fn port(&self) -> u16 {
9373        self.port
9374    }
9375
9376    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
9377    /// slice accessor every HTTPRoute-aware renderer keys off when it
9378    /// wants the raw author-declared path-list (not the fallback-
9379    /// applied projection [`Self::resolved_paths`] returns) — returns
9380    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
9381    /// borrowed from the typed slot's own [`Vec<String>`] storage.
9382    ///
9383    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
9384    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
9385    /// (1449891) closes the fallback-applying arm every per-Aplicacao
9386    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
9387    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
9388    /// catch-all; non-empty slot → per-entry verbatim projection); this
9389    /// accessor closes the raw-slot arm every consumer that must see the
9390    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
9391    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
9392    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
9393    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
9394    /// external-gateway summary line's `{:?}` Debug print — which must
9395    /// name the author's declaration, not the substrate's fallback, so
9396    /// an author reading their graph output can grep their caixa.lisp
9397    /// for the exact list they authored) routes through.
9398    ///
9399    /// Prior to this lift the `.paths` field was accessed inline at four
9400    /// production sites: the two internal reads in [`Self::resolved_paths`]
9401    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
9402    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
9403    /// value-shape gate's `for p in &e.paths` traversal head, and the
9404    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
9405    /// Debug print — four open-coded field-accesses that expressed no
9406    /// compile-time link back to the typed slot. A future extension of
9407    /// the `:entrada :paths` axis to a richer author surface — a
9408    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
9409    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
9410    /// spec supports through `matches[].method`), a per-path per-header
9411    /// filter overlay (`matches[].headers[]`), a per-cluster override
9412    /// the operator pins through a future `:placement :path-overlay`
9413    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
9414    /// per-CR admission-webhook that normalized the list at admission
9415    /// time — would have had to be threaded through every open-coded
9416    /// copy in lockstep or the validator's per-entry gate would silently
9417    /// disagree with the renderer's per-entry emit on which list a given
9418    /// `:entrada` block resolves to. Lifting the resolution to a typed
9419    /// method on the substrate primitive means every downstream consumer
9420    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
9421    /// exactly one typed dispatch — the resolver's accept-set migrates
9422    /// as a unit on any future axis addition.
9423    ///
9424    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
9425    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
9426    /// carry axis — same "one typed dispatch on the substrate primitive,
9427    /// thin projections at each consumer" discipline extended onto the
9428    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
9429    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
9430    /// carrier) so every downstream per-`:entrada` reader now routes
9431    /// through a typed dispatch on the substrate primitive. Returns
9432    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
9433    /// treats the list as a read-only sequence — the slice-view is the
9434    /// narrowest borrow that supports every present + roadmapped consumer
9435    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
9436    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
9437    /// view reaches for (the storage-side `Vec` remains reachable through
9438    /// the `pub paths` field for the mutation-carrying serde round-trip
9439    /// and per-test fixture-mutation paths).
9440    #[must_use]
9441    pub const fn paths(&self) -> &[String] {
9442        self.paths.as_slice()
9443    }
9444}
9445
9446/// Canonical default L4 port every typed Servico exposes on its
9447/// in-cluster K8s Service (the `trigger.service.port` axis the
9448/// `pleme-computeunit` library chart emits, the `:entrada :port` author
9449/// surface defaults to when the author omits the slot, and the
9450/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
9451/// `:entrada` block matches the per-`:contratos` destination Servico).
9452/// The single source of truth all three typed-port consumers reach for:
9453///
9454///   - [`Entrada::port`]'s serde default (via the
9455///     [`default_port`] helper this constant feeds); the author surface
9456///     `(:entrada (:host … :para …))` without an explicit `:port` slot
9457///     reads back as a typed [`Entrada`] carrying this exact value;
9458///   - the
9459///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
9460///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
9461///     fallback, fired when the typed `:entrada` block doesn't name
9462///     the per-`:contratos` destination Servico — the typed
9463///     `:contratos` graph carries no per-destination port axis (the
9464///     destination port is the destination Servico's
9465///     `lareira-<nome>` chart's `trigger.service.port`, which the
9466///     Aplicacao-level renderer has no visibility into without a
9467///     resolver round-trip), so the renderer falls back to the
9468///     substrate's canonical Servico-port assumption — by
9469///     construction the same value the destination's own
9470///     `pleme-computeunit` chart emits, the same value the
9471///     destination's own typed `:entrada :port` slot defaults to;
9472///   - every future per-Servico renderer the absorption-roadmap
9473///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
9474///     CR materializer's per-edge port resolver, the future
9475///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
9476///     emitter's per-route bucket key, the future caixa-otel
9477///     collector-pipeline emitter's per-Servico scrape port).
9478///
9479/// Until this lift landed the value `8080` lived at two production-code
9480/// call-sites: the [`default_port`] helper at
9481/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
9482/// and the `.unwrap_or(8080)` literal at
9483/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
9484/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
9485/// resolver). A future Servico-port rebrand — the substrate moving the
9486/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
9487/// gateway grows direct `:80` listeners, to `8443` once the substrate
9488/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
9489/// override the operator pins through a future
9490/// `:placement :default-port` slot — without a coordinated edit on
9491/// both sides would silently emit Servicos listening on one port and
9492/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
9493/// The CNP's apply-time symptom (the policy is admitted but every L4
9494/// flow on the destination Servico's actual port silently drops because
9495/// it doesn't match the whitelisted port) is far from the rebrand
9496/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
9497/// in hubble traces, not in `kubectl describe`. Lifting the literal to
9498/// a shared constant closes the drift footgun structurally — both
9499/// consumers read from the same `u16`, so any rebrand reaches both
9500/// sites by construction.
9501///
9502/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
9503/// per-renderer canonical-K8s-axis constant — the namespace string
9504/// and the canonical Servico port both lived as duplicated literals
9505/// across caixa-core / caixa-mesh / caixa-flux before their respective
9506/// lifts. Same "the typed constant lives in one place" discipline the
9507/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
9508/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
9509/// shared-string axes.
9510///
9511/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
9512pub const DEFAULT_SERVICO_PORT: u16 = 8080;
9513
9514/// Structural floor for the typed `:entrada :port` axis — every
9515/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
9516/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
9517///
9518/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
9519/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
9520/// interprets as "let the kernel pick a free port at bind time", not a
9521/// well-defined destination the substrate's per-`:entrada` Gateway API
9522/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
9523/// carrying `port: 0` degenerates to a nominal-only routing target: the
9524/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
9525/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
9526/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
9527/// at build time rather than at `kubectl apply` time), and the
9528/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
9529/// (caixa-mesh/src/lib.rs:2657 through
9530/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
9531/// [`Entrada::port`] typed value — silently emits a policy whose
9532/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
9533/// actual listener, dropping every L4 flow at the eBPF data plane far
9534/// from the source caixa.lisp with no field naming the port-zero-drift
9535/// root cause.
9536///
9537/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
9538/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
9539/// on the top edge (unlike the peer capped-`u32` `:politicas` /
9540/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
9541/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
9542/// well below `u32::MAX` and therefore need explicit typed caps).
9543///
9544/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
9545/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
9546/// scalar every `(:entrada (:host … :para …))` slot without an explicit
9547/// `:port` inherits through the serde default hook; this constant names
9548/// the accept-set floor every declared port must satisfy. The pair is
9549/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
9550/// substrate's default must satisfy its own accept-set floor by
9551/// construction) — a future rebrand that accidentally moved
9552/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
9553/// negative-cast typo, a per-cluster override the operator pins through
9554/// a future `:placement :default-port` slot that lands out-of-range)
9555/// would silently invalidate the serde-default emission at every
9556/// author-side `(:entrada (:host … :para …))` slot — the compile-time
9557/// invariant pin
9558/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
9559/// closes the drift footgun at caixa-core build time.
9560///
9561/// Lifted as a typed `pub const` (rather than an inline `0` literal at
9562/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
9563/// has exactly one source of truth — the future M4
9564/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
9565/// gateway resolver, the future per-Servico
9566/// `computeunit.trigger.service.port` renderer's per-CR port-value
9567/// validator, and every downstream test-fixture navigator asserting
9568/// the accept-set floor all read from one place. Same shape every
9569/// other typed bracket-floor / bracket-ceiling in this crate carries
9570/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
9571/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
9572/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
9573/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
9574/// [`POLICY_RATE_LIMIT_MAX`]).
9575pub const SERVICO_PORT_MIN: u16 = 1;
9576
9577const fn default_port() -> u16 {
9578    DEFAULT_SERVICO_PORT
9579}
9580
9581// ── the typed view ───────────────────────────────────────────────────
9582
9583/// Typed composition view of the flat Aplicacao slots on
9584/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
9585/// validation + downstream renderer consumption.
9586#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
9587#[serde(rename_all = "camelCase")]
9588pub struct AplicacaoSpec {
9589    pub membros: Vec<Membro>,
9590    pub contratos: Vec<WitContract>,
9591    pub politicas: MeshPolicy,
9592    pub placement: Placement,
9593    pub entrada: Option<Entrada>,
9594}
9595
9596impl AplicacaoSpec {
9597    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
9598    /// per-Aplicacao member-list slice-return accessor every
9599    /// per-Aplicacao member-list reader keys off — returns the author-
9600    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
9601    /// over the same backing buffer the raw `self.membros.as_slice()`
9602    /// field access borrows from.
9603    ///
9604    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
9605    /// member list — the load-bearing identity of the application graph
9606    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
9607    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
9608    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
9609    /// accessor) with a `:versao` semver-requirement string (through
9610    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
9611    /// and every downstream consumer that fans on the member-set keys
9612    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
9613    /// membership-lookup `HashSet<&str>` seed's collect input, the
9614    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
9615    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
9616    /// per-member DNS-1123 / semver-requirement / duplicate-detection
9617    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
9618    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
9619    /// programs.yaml per-`:membros` fan-out emitter's per-entry
9620    /// mapping-composition loop, the `feira app graph` per-Aplicacao
9621    /// member-count print line and per-member tree traversal,
9622    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
9623    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
9624    /// placement engine's per-member weight-topology reader).
9625    ///
9626    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
9627    /// inline at six production sites — the [`AplicacaoSpec::validate`]
9628    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
9629    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
9630    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
9631    /// probe, the same method's per-member `for m in &self.membros`
9632    /// validate-loop traversal head, the
9633    /// [`AplicacaoSpec::detect_sync_cycles`]'s
9634    /// `for m in &self.membros` adjacency-list seed, the
9635    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
9636    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
9637    /// paired with the peer `for m in &spec.membros` per-entry fan-out
9638    /// loop, and the `feira app graph` per-Aplicacao print line's
9639    /// `spec.membros.len()` count formatter argument paired with the
9640    /// peer `for m in &spec.membros` per-member tree traversal — six
9641    /// open-coded field-accesses that expressed no compile-time link
9642    /// back to the typed slot. A future extension of the `:membros`
9643    /// axis to a richer author surface (a per-cluster member-set
9644    /// overlay the operator pins through a future
9645    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
9646    /// roadmap acknowledges, a per-tenant member-alias table the M4
9647    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
9648    /// CR at admission time, a per-Aplicacao dynamic member-set
9649    /// derivation the future adaptive-placement engine computes from
9650    /// weighted membership topology, a promotion of the plain
9651    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
9652    /// Orleans-style virtual-actor dynamic-membership comes into typed
9653    /// scope) would have had to be threaded through all six open-coded
9654    /// copies in lockstep or one consumer would silently disagree with
9655    /// the peers on which member-set a given Aplicacao resolves to —
9656    /// the `HashSet<&str>` name-set seed reading the raw slot while
9657    /// the peer `.is_empty()` refusal probe read an operator-resolved
9658    /// slot would silently split the `:contratos` membership-lookup
9659    /// input from the pre-flight-refusal input, a six-consumer split
9660    /// at the validator + programs.yaml emitter + graph printer far
9661    /// from the source `caixa.lisp` with no field naming the member-
9662    /// set-drift root cause. Lifting the resolution rule to a typed
9663    /// method on the substrate primitive means every downstream
9664    /// consumer of the Aplicacao's per-`:membros` member-list surface
9665    /// reaches for exactly one typed dispatch — the resolver's accept-
9666    /// set migrates as a unit on any future axis addition.
9667    ///
9668    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
9669    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
9670    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
9671    /// static-child-list `Vec`-carry axis, and to the M3
9672    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
9673    /// on the peer per-`:placement` distribution-target-list `Vec`-
9674    /// carry axis. Same "one typed dispatch on the substrate primitive,
9675    /// thin projections at each consumer" discipline. The two peer
9676    /// `Vec`-carry axes still unlifted at the time of this lift —
9677    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
9678    /// WIT-typed edge list) and
9679    /// [`crate::UpgradeFromEntry::instructions`]
9680    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
9681    /// — inherit this accessor's discipline as future compounding runs
9682    /// migrate their consumers onto the shared slice-return shape.
9683    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
9684    /// `AplicacaoSpec` type itself, extending the discipline beyond
9685    /// the inner per-slot types ([`crate::Placement`],
9686    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
9687    /// view every renderer consumes. Named `membros()` to match the
9688    /// storage field's name verbatim and the tatara-lisp author-
9689    /// surface term (`:membros`) the field's own docstring already
9690    /// carries; the accessor's identity maps onto the canonical
9691    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
9692    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
9693    /// every downstream consumer of the member list treats it as a
9694    /// read-only sequence — the slice-view is the narrowest borrow
9695    /// that supports every present + roadmapped consumer
9696    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
9697    /// backing `Vec`'s grow/push/reserve surface that no consumer of
9698    /// the typed view reaches for (the storage-side `Vec` remains
9699    /// reachable through the `pub membros` field for the mutation-
9700    /// carrying serde round-trip and per-test fixture-mutation paths).
9701    #[must_use]
9702    pub const fn membros(&self) -> &[Membro] {
9703        self.membros.as_slice()
9704    }
9705
9706    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
9707    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
9708    /// accessor every per-Aplicacao contract-list reader keys off —
9709    /// returns the author-declared `:contratos` list verbatim as a
9710    /// `&[WitContract]` slice-view over the same backing buffer the raw
9711    /// `self.contratos.as_slice()` field access borrows from.
9712    ///
9713    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
9714    /// WIT-typed edge list — the load-bearing set of directed edges
9715    /// on the application graph whose nodes are the `:membros` entries
9716    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
9717    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
9718    /// six-tuple is the edge identity every downstream duplicate gate
9719    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
9720    /// Servico caller name + a `:para` destination-Servico callee name
9721    /// (through the lifted [`WitContract::source`] +
9722    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
9723    /// caller/callee-Servico axis) with a `:wit` world-reference
9724    /// (through the lifted [`WitContract::world_ref`] (0804823)
9725    /// accessor) and the target-shape-appropriate payload-carrier
9726    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
9727    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
9728    /// (ed22b66) accessor on the per-target-shape payload-carrier
9729    /// axis). Every downstream consumer that fans on the edge-set
9730    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
9731    /// name-set / self-edge / target-shape / dedup fan-out loop, the
9732    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
9733    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
9734    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
9735    /// grouping loop, the `feira app graph` per-Aplicacao contract-
9736    /// count print line and per-contract tree traversal, every future
9737    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
9738    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
9739    /// mesh-policy overlay resolver's per-contract typed-edge weight
9740    /// reader).
9741    ///
9742    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
9743    /// accessed inline at four production sites — the
9744    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
9745    /// per-edge validate-loop traversal head (which drives every
9746    /// per-edge name-set membership lookup, self-edge check,
9747    /// target-shape dispatch, and dedup `HashSet` insert), the
9748    /// [`AplicacaoSpec::detect_sync_cycles`]'s
9749    /// `for c in &self.contratos` adjacency-list seed head (which
9750    /// drives every per-edge sync-vs-pub-sub partition and per-edge
9751    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
9752    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
9753    /// `BTreeMap` grouping loop head (which drives every per-CNP
9754    /// fan-out emit), and the `feira app graph` per-Aplicacao print
9755    /// line's `spec.contratos.len()` count formatter argument paired
9756    /// with the peer `for c in &spec.contratos` per-contract tree
9757    /// traversal — four open-coded field-accesses that expressed no
9758    /// compile-time link back to the typed slot. A future extension
9759    /// of the `:contratos` axis to a richer author surface (a
9760    /// per-cluster contract overlay the operator pins through a
9761    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
9762    /// federation roadmap acknowledges, a per-tenant edge-policy
9763    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
9764    /// materializer resolves per-CR at admission time, a per-edge
9765    /// weight scalar the future adaptive-placement engine reads to
9766    /// bias sync-subgraph routing, a promotion of the plain
9767    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
9768    /// once virtual-actor-style dynamic-edge composition comes into
9769    /// typed scope) would have had to be threaded through all four
9770    /// open-coded copies in lockstep or one consumer would silently
9771    /// disagree with the peers on which edge-set a given Aplicacao
9772    /// resolves to — the validator's per-edge dedup `HashSet` seed
9773    /// reading the raw slot while the peer sync-cycle adjacency-list
9774    /// seed read an operator-resolved slot would silently split the
9775    /// build-time edge-set gate from the runtime deadlock-detection
9776    /// gate, a four-consumer split at the validator, the cycle
9777    /// detector, the CNP emitter, and the graph printer far from
9778    /// the source `caixa.lisp` with no field naming the edge-set-
9779    /// drift root cause. Lifting the resolution rule to a typed method on the
9780    /// substrate primitive means every downstream consumer of the
9781    /// Aplicacao's per-`:contratos` edge-list surface reaches for
9782    /// exactly one typed dispatch — the resolver's accept-set
9783    /// migrates as a unit on any future axis addition.
9784    ///
9785    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
9786    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
9787    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
9788    /// static-child-list `Vec`-carry axis, to the M3
9789    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
9790    /// on the peer per-`:placement` distribution-target-list `Vec`-
9791    /// carry axis, and to the immediately-adjacent sibling M3
9792    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
9793    /// the peer per-`:membros` node-list `Vec`-carry axis — the
9794    /// per-`:contratos` edge-list accessor is the natural pair of
9795    /// the per-`:membros` node-list accessor (graph edges over graph
9796    /// nodes; every graph-shaped consumer reads both). Same "one
9797    /// typed dispatch on the substrate primitive, thin projections
9798    /// at each consumer" discipline. The last remaining `Vec`-carry
9799    /// axis still unlifted at the time of this lift —
9800    /// [`crate::UpgradeFromEntry::instructions`]
9801    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
9802    /// list) — inherits this accessor's discipline as future
9803    /// compounding runs migrate its consumers onto the shared slice-
9804    /// return shape. Second `&[T]`-return accessor on the top-level
9805    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
9806    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
9807    /// `:contratos` are the two `Vec` fields on the outer typed
9808    /// composition view — `:politicas`, `:placement`, `:entrada` are
9809    /// scalar/option-shaped and already route through their per-slot
9810    /// accessor families). Named `contratos()` to match the storage
9811    /// field's name verbatim and the tatara-lisp author-surface term
9812    /// (`:contratos`) the field's own docstring already carries; the
9813    /// accessor's identity maps onto the canonical MESH-COMPOSITION
9814    /// §III.1 vocabulary the slot's docstring already reaches for.
9815    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
9816    /// every downstream consumer of the contract list treats it as a
9817    /// read-only sequence — the slice-view is the narrowest borrow
9818    /// that supports every present + roadmapped consumer
9819    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
9820    /// backing `Vec`'s grow/push/reserve surface that no consumer of
9821    /// the typed view reaches for (the storage-side `Vec` remains
9822    /// reachable through the `pub contratos` field for the mutation-
9823    /// carrying serde round-trip and per-test fixture-mutation paths).
9824    #[must_use]
9825    pub const fn contratos(&self) -> &[WitContract] {
9826        self.contratos.as_slice()
9827    }
9828
9829    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
9830    /// per-Aplicacao mesh-policy composite-reference accessor every
9831    /// per-Aplicacao policy-block reader keys off — returns the author-
9832    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
9833    /// reference over the same backing storage the raw `&self.politicas`
9834    /// field access borrows from.
9835    ///
9836    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
9837    /// mesh-policy composite — the load-bearing container of every
9838    /// mesh-level operational-policy axis every downstream mesh-artifact
9839    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
9840    /// mesh-policy overlay is the single typed surface a
9841    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
9842    /// from). Every per-`:politicas` axis threads through a lifted
9843    /// per-slot accessor on the [`MeshPolicy`] type: the
9844    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
9845    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
9846    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
9847    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
9848    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
9849    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
9850    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
9851    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
9852    /// accessor. Every downstream consumer that reaches for a policy
9853    /// axis first passes through this outer accessor onto the composite
9854    /// and then dispatches onto the per-axis accessor — the two-level
9855    /// dispatch means every per-`:politicas` reader now routes through
9856    /// a typed dispatch on the substrate primitive at both altitudes.
9857    ///
9858    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
9859    /// accessed inline at four production sites — the
9860    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
9861    /// &self.politicas;` traversal seed (which drives every per-axis
9862    /// zero-floor + upper-cap + canonical-form bracket dispatch through
9863    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
9864    /// `p.rate_limit()` on the axis-level lifted accessors), the
9865    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
9866    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
9867    /// chain (which drives every per-`(:de, :para)` CNP
9868    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
9869    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
9870    /// timeout + retry overlay emitter's paired
9871    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
9872    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
9873    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
9874    /// open-coded outer-field accesses that expressed no compile-time
9875    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
9876    /// future extension of the `:politicas` outer axis to a richer
9877    /// author surface (a per-cluster policy overlay the operator pins
9878    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
9879    /// §V federation roadmap acknowledges, a per-tenant policy-alias
9880    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
9881    /// resolves per-CR at admission time, a per-Aplicacao dynamic
9882    /// policy-composite derivation the future adaptive-placement engine
9883    /// computes from a per-cluster load-topology reader, a promotion of
9884    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
9885    /// partition once virtual-actor-style dynamic-mesh-policy
9886    /// composition comes into typed scope) would have had to be threaded
9887    /// through all four open-coded copies in lockstep or one consumer
9888    /// would silently disagree with the peers on which mesh-policy
9889    /// composite a given Aplicacao resolves to — the validator's
9890    /// per-axis bracket-dispatch seed reading the raw slot while the
9891    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
9892    /// would silently split the build-time policy-shape gate from the
9893    /// runtime CNP-emission gate, a four-consumer split at the
9894    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
9895    /// the source `caixa.lisp` with no field naming the policy-drift
9896    /// root cause. Lifting the resolution rule to a typed method on the
9897    /// substrate primitive means every downstream consumer of the
9898    /// Aplicacao's per-`:politicas` mesh-policy composite surface
9899    /// reaches for exactly one typed dispatch — the resolver's accept-
9900    /// set migrates as a unit on any future axis addition.
9901    ///
9902    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
9903    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
9904    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
9905    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
9906    /// close the two `Vec`-carry axes on the outer typed composition
9907    /// view; the outer `:politicas` composite-reference axis is the
9908    /// natural pair to the paired outer `Vec`-carry accessors on the
9909    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
9910    /// emitter reads all four axes as one unit (graph nodes + graph
9911    /// edges + mesh policy + placement pool). Peer to the same
9912    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
9913    /// slot: every M2 `SupervisorSpec`-scoped composite reader
9914    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
9915    /// `restart_window`, `children`) already routes through the M2
9916    /// `SupervisorSpec` accessor family — this lift extends the same
9917    /// "one typed dispatch on the substrate primitive at the outer
9918    /// composition altitude" discipline to the M3 mesh-slot
9919    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
9920    /// remaining peer outer-composite axes still unlifted at the time
9921    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
9922    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
9923    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
9924    /// inherit this accessor's discipline as future compounding runs
9925    /// migrate their consumers onto the shared reference-return shape.
9926    /// Named `politicas()` to match the storage field's name verbatim
9927    /// and the tatara-lisp author-surface term (`:politicas`) the
9928    /// field's own docstring already carries; the accessor's identity
9929    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
9930    /// slot's docstring already reaches for. Returns `&MeshPolicy`
9931    /// (not the owning composite by copy or clone) because every
9932    /// downstream consumer of the mesh-policy composite treats it as a
9933    /// read-only per-axis dispatch source — the reference-view is the
9934    /// narrowest borrow that supports every present + roadmapped
9935    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
9936    /// emptiness probe) without cloning the composite through every
9937    /// consumer's fast path.
9938    #[must_use]
9939    pub const fn politicas(&self) -> &MeshPolicy {
9940        &self.politicas
9941    }
9942
9943    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
9944    /// per-Aplicacao distribution-composite composite-reference accessor
9945    /// every per-Aplicacao placement-block reader keys off — returns the
9946    /// author-declared `:placement` composite verbatim as a `&Placement`
9947    /// reference over the same backing storage the raw `&self.placement`
9948    /// field access borrows from.
9949    ///
9950    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
9951    /// distribution composite — the load-bearing container of every
9952    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
9953    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
9954    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
9955    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
9956    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
9957    /// `:affinity` hint). Every per-`:placement` axis threads through a
9958    /// lifted per-slot accessor on the [`Placement`] type: the
9959    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
9960    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
9961    /// per-cluster distribution-target slice-return accessor, the
9962    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
9963    /// optional-scalar accessor, and the [`Placement::shard_key`]
9964    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
9965    /// downstream consumer that reaches for a placement axis first passes
9966    /// through this outer accessor onto the composite and then dispatches
9967    /// onto the per-axis accessor — the two-level dispatch means every
9968    /// per-`:placement` reader now routes through a typed dispatch on the
9969    /// substrate primitive at both altitudes.
9970    ///
9971    /// Prior to this lift the `.placement` `Placement` composite was
9972    /// accessed inline at three production sites — the
9973    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
9974    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
9975    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
9976    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
9977    /// cluster `.clusters()` validate-loop traversal head, the per-
9978    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
9979    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
9980    /// paired with the shape-gate cascade's `.shard_key()` /
9981    /// `.estrategia()` diagnostic-carry pair), the
9982    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
9983    /// per-entry placement-block emitter's outer
9984    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
9985    /// seed (which fans onto every per-cluster `programs[]` entry as a
9986    /// self-describing distribution overlay the aggregator filters by),
9987    /// and the `feira app graph` per-Aplicacao print line's paired
9988    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
9989    /// then-inner-accessor chains (which drive the human-readable
9990    /// distribution summary of the typed Aplicacao view) — three open-
9991    /// coded outer-field accesses that expressed no compile-time link
9992    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
9993    /// extension of the `:placement` outer axis to a richer author surface
9994    /// (a per-cluster placement overlay the operator pins through a
9995    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
9996    /// federation roadmap acknowledges, a per-tenant placement-alias
9997    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
9998    /// resolves per-CR at admission time, a per-Aplicacao dynamic
9999    /// placement-composite derivation the future M5 adaptive-placement
10000    /// engine computes from a per-cluster load-topology reader, a
10001    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
10002    /// partition once Orleans-style virtual-actor dynamic-placement comes
10003    /// into typed scope) would have had to be threaded through all three
10004    /// open-coded copies in lockstep or one consumer would silently
10005    /// disagree with the peers on which placement composite a given
10006    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
10007    /// seed reading the raw slot while the peer
10008    /// `programs_for_aplicacao` emitter read an operator-resolved slot
10009    /// would silently split the build-time distribution-shape gate from
10010    /// the runtime programs.yaml distribution-annotation gate, a three-
10011    /// consumer split at the validator, the programs.yaml emitter, and
10012    /// the `feira app graph` printer far from the source `caixa.lisp`
10013    /// with no field naming the placement-drift root cause. Lifting the
10014    /// resolution rule to a typed method on the substrate primitive
10015    /// means every downstream consumer of the Aplicacao's per-
10016    /// `:placement` distribution composite surface reaches for exactly
10017    /// one typed dispatch — the resolver's accept-set migrates as a unit
10018    /// on any future axis addition.
10019    ///
10020    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
10021    /// `AplicacaoSpec` type itself — sibling to the seed
10022    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
10023    /// composite-reference accessor on the peer per-`:politicas` outer-
10024    /// composite axis, and to the paired slice-return accessors
10025    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
10026    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
10027    /// the two `Vec`-carry axes on the outer typed composition view; the
10028    /// outer `:placement` composite-reference axis is the natural pair
10029    /// to the peer `:politicas` composite-reference axis on the two
10030    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
10031    /// how-to-run policy overlay, `:placement` carries the where-to-run
10032    /// distribution composite — every whole-Aplicacao mesh-artifact
10033    /// emitter reads both as one unit). Same "one typed dispatch on the
10034    /// substrate primitive, thin projections at each consumer"
10035    /// discipline the peer per-`:politicas` composite-reference axis
10036    /// already routes through. The one remaining outer-composite axis
10037    /// still unlifted at the time of this lift —
10038    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
10039    /// external-gateway composite) — inherits this accessor's discipline
10040    /// as the next compounding run migrates its consumers onto the shared
10041    /// reference-return shape, closing the outer-composite altitude on
10042    /// every M3 mesh-slot axis. Named `placement()` to match the storage
10043    /// field's name verbatim and the tatara-lisp author-surface term
10044    /// (`:placement`) the field's own docstring already carries; the
10045    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
10046    /// vocabulary the slot's docstring already reaches for. Returns
10047    /// `&Placement` (not the owning composite by copy or clone) because
10048    /// every downstream consumer of the placement composite treats it as
10049    /// a read-only per-axis dispatch source — the reference-view is the
10050    /// narrowest borrow that supports every present + roadmapped consumer
10051    /// (per-axis accessor dispatch, serde composite-serialization) without
10052    /// cloning the composite through every consumer's fast path.
10053    #[must_use]
10054    pub const fn placement(&self) -> &Placement {
10055        &self.placement
10056    }
10057
10058    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
10059    /// per-Aplicacao external-gateway composite optional-composite-
10060    /// reference accessor every per-Aplicacao gateway-block reader
10061    /// keys off — returns the author-declared `:entrada` composite
10062    /// verbatim as an `Option<&Entrada>` reference over the same
10063    /// backing storage the raw `self.entrada.as_ref()` field access
10064    /// borrows from, with `None` naming the internal-only mesh shape
10065    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
10066    /// gateway_routes emitter treats as "emit nothing" and the peer
10067    /// `feira app graph` printer treats as "internal-only mesh").
10068    ///
10069    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
10070    /// external-gateway composite — the load-bearing container of
10071    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
10072    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
10073    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
10074    /// hostname axis, §III.4 for the `:para` destination-Servico
10075    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
10076    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
10077    /// axis threads through a lifted per-slot accessor on the
10078    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
10079    /// Gateway-API `Listener.hostname` scalar accessor, the paired
10080    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
10081    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
10082    /// backendRefs destination-Servico scalar accessor, the
10083    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
10084    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
10085    /// scalar accessor. Every downstream consumer that reaches for
10086    /// an entrada axis first passes through this outer accessor onto
10087    /// the composite and then dispatches onto the per-axis accessor
10088    /// — the two-level dispatch means every per-`:entrada` reader
10089    /// now routes through a typed dispatch on the substrate primitive
10090    /// at both altitudes.
10091    ///
10092    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
10093    /// was accessed inline at four production sites — the
10094    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
10095    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
10096    /// (which drives every per-axis refusal on the composite: the
10097    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
10098    /// `EntradaMemberMissing` membership lookup against the
10099    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
10100    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
10101    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
10102    /// per-path shape gate on each entry of `e.paths`), the
10103    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
10104    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
10105    /// composite-projection seed (which drives the destination-
10106    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
10107    /// backendRefs port emitter fans on), the
10108    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
10109    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
10110    /// early-return seed (which drives the "no `:entrada` ⇒ no
10111    /// external artifacts" partition on the whole-Aplicacao Gateway-
10112    /// API emitter's fan-out), and the `feira app graph` per-
10113    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
10114    /// external-gateway summary emitter (which drives the human-
10115    /// readable `entrada: host → para (paths=…, port=…)` /
10116    /// `entrada: (internal-only mesh)` partition on the typed
10117    /// Aplicacao view) — four open-coded outer-field accesses that
10118    /// expressed no compile-time link back to the typed slot at the
10119    /// [`AplicacaoSpec`] altitude. A future extension of the
10120    /// `:entrada` outer axis to a richer author surface (a
10121    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
10122    /// at admission time so an Aplicacao can expose a public-web +
10123    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
10124    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
10125    /// operator can pin a per-cluster hostname override without
10126    /// re-authoring the `caixa.lisp`, a promotion of the plain
10127    /// `Option<Entrada>` to a richer `{single, multi}` partition once
10128    /// the multi-`:entrada` roadmap lands) would have had to be
10129    /// threaded through all four open-coded copies in lockstep or one
10130    /// consumer would silently disagree with the peers on which
10131    /// entrada composite a given Aplicacao resolves to — the
10132    /// validator's per-axis bracket-dispatch seed reading the raw
10133    /// slot while the peer `gateway_routes` emitter read an
10134    /// operator-resolved slot would silently split the build-time
10135    /// gateway-shape gate from the runtime Gateway + HTTPRoute
10136    /// emission gate, a four-consumer split at the validator, the
10137    /// `port_for_destination` L4-port resolver, the `gateway_routes`
10138    /// emitter, and the `feira app graph` printer far from the
10139    /// source `caixa.lisp` with no field naming the entrada-drift
10140    /// root cause. Lifting the resolution rule to a typed method on
10141    /// the substrate primitive means every downstream consumer of
10142    /// the Aplicacao's per-`:entrada` external-gateway composite
10143    /// surface reaches for exactly one typed dispatch — the
10144    /// resolver's accept-set migrates as a unit on any future axis
10145    /// addition.
10146    ///
10147    /// Third and final `&Composite`-return accessor on the top-level
10148    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
10149    /// unlifted outer-composite axis on the outer typed composition
10150    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
10151    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
10152    /// accessor on the per-`:politicas` outer-composite axis and to
10153    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
10154    /// distribution-composite composite-reference accessor on the
10155    /// per-`:placement` outer-composite axis; extends the outer-
10156    /// composite reference-return discipline the two peers already
10157    /// route through onto the last unlifted per-`AplicacaoSpec`
10158    /// outer-composite axis. The `:entrada` outer-composite axis is
10159    /// the natural pair to the two peer outer-composite axes on the
10160    /// three operationally-symmetric M3 mesh-slot outer composites
10161    /// (`:politicas` carries the how-to-run policy overlay,
10162    /// `:placement` carries the where-to-run distribution composite,
10163    /// `:entrada` carries the who-can-reach-it external-gateway
10164    /// composite — every whole-Aplicacao mesh-artifact emitter reads
10165    /// all three as one unit). Same "one typed dispatch on the
10166    /// substrate primitive, thin projections at each consumer"
10167    /// discipline the peer outer-composite axes already route through.
10168    /// Named `entrada()` to match the storage field's name verbatim
10169    /// and the tatara-lisp author-surface term (`:entrada`) the
10170    /// field's own docstring already carries; the accessor's
10171    /// identity maps onto the canonical MESH-COMPOSITION §III.4
10172    /// vocabulary the slot's docstring already reaches for. Returns
10173    /// `Option<&Entrada>` (not the owning composite by copy or
10174    /// clone) because every downstream consumer of the entrada
10175    /// composite treats it as a read-only per-axis dispatch source
10176    /// — the reference-view is the narrowest borrow that supports
10177    /// every present + roadmapped consumer (per-axis accessor
10178    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
10179    /// port-fallback projection, early-return partition on the
10180    /// `None` arm) without cloning the composite through every
10181    /// consumer's fast path. The `Option` half of the return-type
10182    /// preserves the load-bearing "author-omitted `:entrada` ⇒
10183    /// internal-only mesh" partition (not a default composite the
10184    /// downstream must reject on emptiness) — the accessor projects
10185    /// the raw `Option<Entrada>` slot's presence bit through the
10186    /// reference-return unchanged.
10187    #[must_use]
10188    pub const fn entrada(&self) -> Option<&Entrada> {
10189        self.entrada.as_ref()
10190    }
10191
10192    /// Validate the typed shape:
10193    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
10194    ///     and a non-empty `:versao`; no two entries share the same
10195    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
10196    ///     not a multiset)
10197    ///   - every `:contratos` :de + :para must be in `:membros`
10198    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
10199    ///     contract is an inter-Servico edge, so a Servico contracting
10200    ///     with itself is a build error under every WIT shape
10201    ///     (MESH-COMPOSITION §III.1)
10202    ///   - no two `:contratos` entries agree on
10203    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
10204    ///     edges are a set, not a multiset (peer of the `:membros` /
10205    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
10206    ///   - `:entrada :para` must be in `:membros`
10207    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
10208    ///     `:placement Replicated`/`SingleNode` must NOT declare
10209    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
10210    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
10211    ///     between strategy and shard-key is symmetric: every validated
10212    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
10213    ///     Sharded`
10214    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
10215    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
10216    ///     the shard pool (MESH-COMPOSITION §III.1)
10217    ///   - every `:clusters` entry is non-empty and unique
10218    ///   - `:placement :affinity`, when set, is non-empty
10219    ///   - the synchronous-`:contratos` subgraph is acyclic
10220    ///     (MESH-COMPOSITION §III.3)
10221    ///   - every declared `:politicas` value is operationally meaningful
10222    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
10223    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
10224    ///     omit the field instead to express "no policy on this axis")
10225    pub fn validate(&self) -> Result<(), AplicacaoError> {
10226        self.validate_membros()?;
10227
10228        // `:contratos` per-slot gate — folds both structural axes on the
10229        // slot into one substrate primitive: the per-entry cascade (shape
10230        // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
10231        // target + whole-edge dedup) and the cross-edge sync-cycle axis
10232        // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
10233        // — pub-sub edges excluded, "acyclic by construction"). Same
10234        // fold-per-axis-plus-cross-axis discipline the sibling
10235        // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
10236        // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
10237        // onto `:contratos` so every future consumer of the slot (the M4
10238        // admission webhook re-checking `:contratos` after a per-edge
10239        // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
10240        // acknowledges) reaches *both* structural axes through one call.
10241        self.validate_contratos()?;
10242
10243        self.validate_entrada()?;
10244
10245        self.validate_placement()?;
10246
10247        self.validate_politicas()?;
10248
10249        Ok(())
10250    }
10251
10252    /// The `:membros` graph-node name set — the membership oracle every
10253    /// per-Aplicacao name-reference axis resolves against.
10254    ///
10255    /// Three per-Aplicacao axes carry a Servico-name *reference* rather
10256    /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
10257    /// :para`, and `:entrada :para`. Each must resolve to a declared
10258    /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
10259    /// the external gateway both address graph nodes, so a reference to
10260    /// a node the graph does not contain is a build error). All three
10261    /// resolve against *this* set, so the set's construction is the one
10262    /// shared substrate primitive underneath the whole reference-
10263    /// resolution surface.
10264    ///
10265    /// Lifted out of [`AplicacaoSpec::validate`]'s inline
10266    /// `self.membros().iter().map(Membro::nome).collect()` builder so
10267    /// the two per-slot gates that consume it — the per-`:contratos`
10268    /// membership arms still inline at `validate` and the lifted
10269    /// [`AplicacaoSpec::validate_entrada`] below — reach the same
10270    /// oracle through one dispatch rather than each open-coding the
10271    /// projection. Every future consumer on the same axis (the M4
10272    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
10273    /// reference resolver, the per-`:contratos`-edge `:politicas`
10274    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
10275    /// resolves an edge's endpoints against the same membership set
10276    /// before it can key a per-edge policy off them) inherits the
10277    /// projection through the same call, so a future rebrand of the
10278    /// node-identity axis (a namespace-qualified member name the CR
10279    /// materializer applies per-CR, the `:membros :nome-suffix`
10280    /// overlay §III.2 acknowledges) lands at exactly one place rather
10281    /// than at every reference-resolution site in lockstep. Peer of
10282    /// the sibling per-slot substrate primitives
10283    /// [`MeshPolicy::validate`] (f03a154) and
10284    /// [`WitContract::identity`] on their own axes.
10285    fn membro_names(&self) -> std::collections::HashSet<&str> {
10286        self.membros().iter().map(Membro::nome).collect()
10287    }
10288
10289    /// Reject `:contratos` entries whose endpoints are malformed,
10290    /// reference a Servico outside the graph, self-loop, carry an
10291    /// empty `:wit` shape, duplicate a prior entry on the six-axis
10292    /// identity key, or close a synchronous-edge cycle in the
10293    /// resulting typed graph.
10294    ///
10295    /// The `:contratos` slot is the typed inter-Servico edge set
10296    /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
10297    /// edge whose `:de` / `:para` reference two distinct members and
10298    /// whose `:wit` picks the payload shape the paired L4/L7 renderer
10299    /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
10300    /// per-HTTP `HTTPRoute`) fans out on.
10301    ///
10302    /// Two structural axes on the slot are folded into this per-slot
10303    /// gate: the per-entry axis (six per-edge arms, listed below) and
10304    /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
10305    /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
10306    /// per-entry cascade). Same
10307    /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
10308    /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
10309    /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
10310    /// `:politicas` slot, extended here onto `:contratos`.
10311    ///
10312    /// Six per-entry axes are gated first, in the canonical
10313    /// edge-direction order the paired diagnostics already encode
10314    /// (per-arm value shape before graph-membership lookup; structural
10315    /// self-edge before payload-shape target dispatch; whole-edge dedup
10316    /// last):
10317    ///
10318    ///   - per-arm `:de` / `:para` value shape via
10319    ///     [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
10320    ///     `:de` before `:para`;
10321    ///   - per-edge graph-membership against the
10322    ///     [`AplicacaoSpec::membro_names`] oracle via
10323    ///     [`WitContract::require_endpoints_in`] (folds the twin
10324    ///     `:de` / `:para` arms onto one substrate-primitive
10325    ///     dispatch), `:de` before `:para`;
10326    ///   - structural self-edge via [`WitContract::is_self_loop`]
10327    ///     (caller-equals-callee under any WIT shape);
10328    ///   - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
10329    ///   - WIT shape ↔ target consistency via [`WitContract::target`]
10330    ///     (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
10331    ///     `Capability` — each carry their own required payload field);
10332    ///   - six-axis whole-edge dedup via [`WitContract::identity`]
10333    ///     ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
10334    ///     slot)` tuple).
10335    ///
10336    /// One cross-edge axis is gated last, after the per-entry cascade
10337    /// completes cleanly:
10338    ///
10339    ///   - synchronous-edge cycle detection via
10340    ///     [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
10341    ///     three-coloring over the sync-only subgraph, pub-sub edges
10342    ///     skipped per MESH-COMPOSITION §III.3 —
10343    ///     [`AplicacaoError::ContratoCycle`]). Runs *after* the
10344    ///     per-entry cascade so a per-entry defect surfaces through its
10345    ///     narrower shape/membership/dedup arm before the cross-edge
10346    ///     cycle diagnostic, matching the pre-fold `validate`-side
10347    ///     dispatch ordering (`validate_contratos()? →
10348    ///     detect_sync_cycles()?`).
10349    ///
10350    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
10351    /// seen_contracts = …; for c in self.contratos() { … }` block onto
10352    /// a named per-slot gate, closing the last unlifted per-slot gate
10353    /// on the M3 mesh-slot family. Every peer slot already carries the
10354    /// shape ([`AplicacaoSpec::validate_membros`],
10355    /// [`AplicacaoSpec::validate_entrada`],
10356    /// [`AplicacaoSpec::validate_placement`],
10357    /// [`AplicacaoSpec::validate_politicas`]).
10358    ///
10359    /// Self-contained on `&self` — it resolves its own membership
10360    /// oracle through [`AplicacaoSpec::membro_names`] rather than
10361    /// borrowing one threaded down from `validate`, and runs its own
10362    /// cross-edge cycle probe rather than deferring the axis to an
10363    /// outer dispatch — so a future consumer that re-validates *one*
10364    /// slot against a mutated spec (the M4 admission webhook
10365    /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
10366    /// without re-walking `:membros` / `:entrada` / `:placement` /
10367    /// `:politicas`, or the M4 per-edge policy resolver
10368    /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
10369    /// effective per-edge [`MeshPolicy`] and must re-check the edge's
10370    /// own identity closure *and* the sync-cycle invariant before it
10371    /// can key a per-edge override off the endpoint tuple) reaches
10372    /// *both* structural axes on the slot through one call, exactly as
10373    /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
10374    /// cross-axis surfaces on `:politicas` through
10375    /// [`MeshPolicy::validate`].
10376    fn validate_contratos(&self) -> Result<(), AplicacaoError> {
10377        let names = self.membro_names();
10378
10379        // Identity key for the typed-edge duplicate gate below: every
10380        // field that distinguishes one contract from another. Two
10381        // entries that agree on all six are *the same edge declared
10382        // twice*, the typed-graph analogue of duplicate `:membros` /
10383        // `:placement :clusters` / `:entrada :paths` entries (which
10384        // are already build errors at this layer). Rejecting it at the
10385        // validate gate closes a renderer-side footgun: caixa-mesh's
10386        // `cilium_network_policies` keys each emitted policy by
10387        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
10388        // (de, para) and identical payload would land as two K8s
10389        // objects with colliding `metadata.name`, rejected at apply
10390        // time far from the source caixa.lisp.
10391        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
10392            std::collections::HashSet::new();
10393        for c in self.contratos() {
10394            // Per-axis value-shape gate on every `:contratos` name
10395            // reference, before any graph-membership lookup. Empty +
10396            // DNS-1123-malformed `:de`/`:para` values silently fell
10397            // through to `ContratoMemberMissing` at the lookup arm
10398            // because every `:membros :caixa` is shape-validated
10399            // (3f9d7a0), so the `names` set structurally cannot contain
10400            // an empty / malformed string and the membership-lookup
10401            // diagnostic always misframed the root cause as
10402            // "this caixa is not in `:membros`". The shape gate runs
10403            // ahead of the lookup so structurally-impossible-to-match
10404            // inputs route through the narrower self-locating
10405            // diagnostic, preserving the legitimate "well-shaped
10406            // phantom reference" arm. `:de` runs before `:para` per
10407            // the canonical edge-direction order the existing
10408            // membership lookup, self-edge check, target dispatch,
10409            // and diagnostic strings already use.
10410            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
10411            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
10412            // Per-edge graph-membership gate on the twin `:de` / `:para`
10413            // arms — folded onto the substrate-primitive dispatch
10414            // [`WitContract::require_endpoints_in`] so every per-edge
10415            // consumer of the endpoint-resolution axis (this per-slot
10416            // gate at build time, the M4 admission webhook re-checking
10417            // one edge after a per-`(:de, :para)` patch, the per-edge
10418            // `:politicas` override MESH-COMPOSITION §III.2 #3
10419            // acknowledges) reaches the axis through one call rather
10420            // than re-inlining the twin `if !names.contains(...)`
10421            // cascade. `:de` fires before `:para` inside the primitive,
10422            // preserving byte-equal diagnostic ordering with the
10423            // pre-lift inline cascade.
10424            c.require_endpoints_in(&names)?;
10425            // A `:contratos` entry is an *inter*-Servico contract
10426            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
10427            // typed edge between two distinct graph nodes. An edge whose
10428            // `:de` equals its `:para` is a Servico contracting with
10429            // itself — a degenerate edge under every WIT shape. Firing
10430            // the gate before the `:wit`/`target()` shape checks means
10431            // the structural "this edge can't exist" error precedes the
10432            // narrower payload-shape diagnostics, and shape-agnostically
10433            // covers all four `WitTarget` arms (HTTP / Store / Capability
10434            // / PubSub) at one point. Peer of the duplicate-`:contratos`
10435            // / duplicate-`:membros` set gates: both reject a structurally
10436            // ill-formed graph at the typed surface, before the renderer
10437            // emits a K8s object that fails or no-ops far from the source
10438            // caixa.lisp.
10439            if c.is_self_loop() {
10440                return Err(AplicacaoError::contrato_self_loop(c));
10441            }
10442            if c.world_ref().is_empty() {
10443                return Err(AplicacaoError::empty_wit(c.edge_pair()));
10444            }
10445            // Shape ↔ target consistency — surfaces "HTTP wit without
10446            // :endpoint", "NATS wit with :endpoint set", etc. as named
10447            // build errors instead of silent renderer drops. Threaded
10448            // through the duplicate-edge diagnostic below (via
10449            // [`WitTarget::label`]) so the "which typed target arm did
10450            // the duplicate carry" question is answered by the typed
10451            // enum's variant discriminator, not by re-probing the raw
10452            // `Option<String>` payload fields.
10453            let target_view = c.target()?;
10454            // Contract identity: (de, para, wit, endpoint, subject, slot).
10455            // Two contracts that match on all six are the same typed edge
10456            // declared twice — author error, not a legitimate variant of
10457            // "same caller-callee pair, different payload" (e.g.
10458            // cart→catalog at /products vs /search), which keeps distinct
10459            // identity keys via the differing endpoint payloads.
10460            let key = c.identity();
10461            crate::render::insert_first_seen(&mut seen_contracts, key, || {
10462                AplicacaoError::contrato_duplicate(c, &target_view)
10463            })?;
10464        }
10465
10466        // Cross-edge cycle axis on the `:contratos` slot — folded into
10467        // the per-slot gate so the two structural axes on `:contratos`
10468        // (per-entry shape + membership + dedup above; cross-edge sync-
10469        // cycle detection here) reach every consumer through one call.
10470        // Same discipline the sibling per-slot compound gate
10471        // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
10472        // — one named per-slot gate that folds *both* per-axis and
10473        // cross-axis surfaces on the same slot onto one substrate
10474        // primitive — extended here onto `:contratos`, closing the last
10475        // per-slot-axis-family that lived split across `validate` (the
10476        // per-entry `validate_contratos` half here and the cross-edge
10477        // `detect_sync_cycles` call the sibling below at `validate`
10478        // dispatched separately).
10479        //
10480        // Runs after the per-entry cascade so a per-entry defect (empty
10481        // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
10482        // target inconsistency, whole-edge duplicate) surfaces first
10483        // through its narrower [`AplicacaoError`] arm before the cross-
10484        // edge cycle diagnostic. This matches the pre-lift ordering the
10485        // `validate`-side dispatch used verbatim (`self.validate_contratos()?
10486        // → self.detect_sync_cycles()?`) — the cycle detector was
10487        // already the second `:contratos`-axis gate in the dispatch,
10488        // just at the outer altitude; the fold moves it under the same
10489        // named per-slot gate without reshaping the diagnostic order.
10490        self.detect_sync_cycles()?;
10491
10492        Ok(())
10493    }
10494
10495    /// Reject `:entrada` values that are operationally meaningless,
10496    /// structurally malformed, or reference a Servico outside the
10497    /// graph.
10498    ///
10499    /// The `:entrada` slot is the Aplicacao's single external ingress
10500    /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
10501    /// Gateway API v1 `Listener`, `:paths` become the paired
10502    /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
10503    /// the member the route forwards to. Omitting the slot entirely is
10504    /// the internal-only-mesh partition — an Aplicacao with no external
10505    /// surface — so the `None` arm is a clean pass, not a refusal.
10506    ///
10507    /// Five axes are gated here, in the canonical order the paired
10508    /// diagnostics already encode (reference-resolution before value
10509    /// shape, per-axis emptiness before per-axis grammar):
10510    ///
10511    ///   - `:para` — DNS-1123 value shape, then membership against the
10512    ///     [`AplicacaoSpec::membro_names`] oracle;
10513    ///   - `:host` — emptiness, then the Gateway API hostname grammar;
10514    ///   - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
10515    ///   - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
10516    ///     path grammar, and set-not-multiset uniqueness.
10517    ///
10518    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
10519    /// Some(e) = self.entrada() { … }` block onto a named per-slot
10520    /// gate, the shape the three peer M3 mesh slots already carry
10521    /// ([`AplicacaoSpec::validate_membros`],
10522    /// [`AplicacaoSpec::validate_placement`],
10523    /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
10524    /// `&self` — it resolves its own membership oracle through
10525    /// [`AplicacaoSpec::membro_names`] rather than borrowing one
10526    /// threaded down from `validate` — so a future consumer that
10527    /// re-validates *one* slot against a mutated spec (the M4 admission
10528    /// webhook re-checking `:entrada` after a gateway-host patch
10529    /// without re-walking the whole `:contratos` graph) reaches the
10530    /// axis through one call, exactly as `detect_sync_cycles` is
10531    /// already self-contained for the M4 per-edge policy resolver.
10532    fn validate_entrada(&self) -> Result<(), AplicacaoError> {
10533        let names = self.membro_names();
10534        if let Some(e) = self.entrada() {
10535            // Route the per-`:entrada` composite-reference read
10536            // through the lifted [`AplicacaoSpec::entrada`] accessor
10537            // rather than the raw `&self.entrada` field access — the
10538            // shape-and-membership gate's traversal head is now the
10539            // canonical read-side surface every per-Aplicacao entrada
10540            // consumer routes through, closing the fourth of four
10541            // open-coded outer-field accesses on the per-`:entrada`
10542            // outer-composite axis.
10543            //
10544            // Shape gate on `:entrada :para` runs ahead of the
10545            // membership lookup. Every `:membros :caixa` past
10546            // `validate_membro_caixa` is a valid DNS-1123 label
10547            // (3f9d7a0), so the `names` set structurally cannot
10548            // contain an empty / malformed string and the membership-
10549            // lookup diagnostic always misframed the root cause as
10550            // "this caixa is not in `:membros`". The shape gate
10551            // routes structurally-impossible-to-match inputs through
10552            // the narrower self-locating diagnostic, preserving the
10553            // legitimate "well-shaped phantom reference" arm — the
10554            // same trajectory the peer `:membros :caixa` (3f9d7a0),
10555            // `:placement :clusters` (6c8c00b), and `:contratos :de`
10556            // / `:para` (8d5af6b) axes already follow. This closes
10557            // the fourth and last Aplicacao-level Servico-name
10558            // reference axis on the canonical DNS-1123 floor.
10559            // Route the per-`:entrada :para` byte-string reads through
10560            // the lifted [`Entrada::destination`] accessor rather than
10561            // the raw `e.para` field access — the three
10562            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
10563            // (shape-gate `validate_entrada_para` arg, membership
10564            // lookup, `EntradaMemberMissing` diagnostic carry) now key
10565            // off exactly one typed dispatch on the substrate
10566            // primitive, closing the last unlifted per-`:entrada :para`
10567            // raw-field-access axis on the M3 mesh-slot validator.
10568            // The `.destination().to_string()` at the diagnostic site
10569            // is byte-identical to `.para.clone()` — pinned by the
10570            // sibling `destination_returns_entrada_para_byte_equal` +
10571            // `destination_borrows_from_entrada_para_storage` accessor
10572            // tests — so a future rebrand of the underlying `:para`
10573            // storage (a lift from `String` to a typed
10574            // `ServicoName(String)` newtype, a per-Aplicacao interning
10575            // arena the M4 CR materializer authors, a
10576            // `smol_str::SmolStr` inline-buffer swap) flows through
10577            // the accessor's one body without a coordinated
10578            // per-consumer rewrite across the M3 mesh validator.
10579            validate_entrada_para(e.destination())?;
10580            if !names.contains(e.destination()) {
10581                return Err(AplicacaoError::entrada_member_missing(e));
10582            }
10583            // Route the per-`:entrada :host` byte-string reads through
10584            // the lifted [`Entrada::hostname`] accessor rather than
10585            // the raw `e.host` field access — the emptiness gate and
10586            // the shape-gate `validate_entrada_host` arg now key off
10587            // exactly one typed dispatch on the substrate primitive,
10588            // closing the last unlifted per-`:entrada :host` raw-
10589            // field-access axis on the M3 mesh-slot validator. Peer
10590            // of the sibling per-`:entrada :para` convergence above
10591            // and pinned by the existing
10592            // `hostname_returns_entrada_host_byte_equal` +
10593            // `hostnames_returns_singleton_of_hostname_accessor`
10594            // accessor tests, so any future
10595            // Gateway-API-shaped host renormalization (a wildcard-
10596            // label lift, a trailing-`.` FQDN substitution, an IDNA
10597            // Punycode round-trip the SNI fan-out overlay authors)
10598            // flows through the accessor's one body without a
10599            // coordinated per-consumer rewrite across the M3 mesh
10600            // validator.
10601            if e.hostname().is_empty() {
10602                return Err(AplicacaoError::EmptyEntradaHost);
10603            }
10604            // The `:host` lands verbatim as a K8s Gateway API v1
10605            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
10606            // both apiserver-validated against the same restrictive
10607            // pattern: lowercase RFC 1123 DNS subdomain, optional
10608            // single leading wildcard label (`*.`), max length 253,
10609            // per-label max length 63, no IP literals, no scheme,
10610            // no port. Until this gate landed `validate()` only
10611            // refused the empty string (`EmptyEntradaHost`); a
10612            // structurally invalid hostname (`"https://example.com"`,
10613            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
10614            // `"_underscored.example.com"`, `"FOO.example.com"`,
10615            // `"checkout.quero.cloud."`) silently passed validate
10616            // and the apiserver `field is invalid` error surfaced at
10617            // `kubectl apply` time, far from the source caixa.lisp.
10618            // Lifting the gate to caixa-build time mirrors the
10619            // `:entrada :paths` value-shape trajectory (eb3456d) and
10620            // closes the last unstructured `:entrada` axis.
10621            validate_entrada_host(e.hostname())?;
10622            // Structural-floor gate on `:entrada :port`: every
10623            // validated `Entrada::port` past this gate lies in
10624            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
10625            // type-inferred ceiling closes the top edge, so no companion
10626            // upper-cap arm is needed here — unlike the peer capped-
10627            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
10628            // `require_positive_bounded_u32` bracket covers both edges).
10629            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
10630            // accept-set-floor const rather than the prior inline
10631            // `if e.port == 0` byte-check so a future rebrand of the
10632            // accept-set floor (a hypothetical unprivileged-only
10633            // migration lifting the floor to `1024`, a per-cluster
10634            // scoping the operator pins through a future
10635            // `:placement :port-floor` slot as the M4 typed-slot
10636            // trajectory adds it, the future
10637            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
10638            // per-Aplicacao gateway resolver reaching for the same
10639            // floor) is a one-line edit on the canonical
10640            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
10641            // rewrite across the emit site + the pin test + every
10642            // future per-target renderer the substrate adds.
10643            if e.port() < SERVICO_PORT_MIN {
10644                return Err(AplicacaoError::EntradaPortZero);
10645            }
10646            // Each `:entrada :paths` entry becomes a K8s Gateway API
10647            // HTTPRoute `matches[].path.value`. The Gateway API rejects
10648            // values that don't start with `/` for `type: PathPrefix`,
10649            // and an empty value is meaningless. Surface those as build
10650            // errors (MESH-COMPOSITION §III.3) rather than apply-time
10651            // failures. Empty `:paths` itself is fine — caixa-mesh
10652            // falls back to a single `/` catch-all.
10653            let mut seen = std::collections::HashSet::new();
10654            // Route the per-entry value-shape gate's traversal head
10655            // through the lifted [`Entrada::paths`] slice accessor
10656            // rather than the raw `&e.paths` field access — the
10657            // per-Aplicacao `:entrada :paths` validate loop now keys
10658            // off the canonical raw-slot surface every downstream
10659            // per-`:entrada` path-list consumer (the sibling
10660            // [`Entrada::resolved_paths`] fallback-applying resolver
10661            // internal reads, `feira app graph`'s per-Aplicacao entrada
10662            // summary line's `{:?}` Debug print) routes through, so any
10663            // future rebrand on the typed slot's raw-slot reader lands
10664            // at exactly one place. Same convergence discipline as the
10665            // sibling [`Placement::clusters`] (a6e18d7) reader-site
10666            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
10667            // axis.
10668            for p in e.paths() {
10669                if p.is_empty() {
10670                    return Err(AplicacaoError::EntradaPathEmpty);
10671                }
10672                if !p.starts_with('/') {
10673                    return Err(AplicacaoError::entrada_path_not_absolute(p));
10674                }
10675                // Per-entry value-shape gate: the path lands verbatim
10676                // as a K8s Gateway API HTTPRoute `matches[].path.value`
10677                // (caixa-mesh/src/lib.rs:498), apiserver-validated
10678                // against `maxLength: 1024` + the Gateway API webhook's
10679                // path-grammar rules (no `//`, no `/./`, no `/../`, no
10680                // query/fragment separators, no whitespace, no control
10681                // characters, no non-ASCII bytes). Until this gate
10682                // landed `validate` only refused the empty string and
10683                // missing-leading-slash (eb3456d); a structurally
10684                // invalid path (`"/api?q=1"`, `"/api#frag"`,
10685                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
10686                // 1025-byte URL-shaped slug) silently passed validate
10687                // and the failure surfaced at `kubectl apply` time as
10688                // a Gateway API webhook rejection, far from the source
10689                // caixa.lisp, with no field naming the offending
10690                // `:paths` entry. Lifting the gate to caixa-build time
10691                // mirrors the `:entrada :host` value-shape trajectory
10692                // (c7d05ec) on the sibling axis — every author surface
10693                // that emits a Gateway API field now matches the
10694                // apiserver's accepted set at validate time.
10695                validate_entrada_path(p)?;
10696                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
10697                    AplicacaoError::entrada_path_duplicate(p)
10698                })?;
10699            }
10700        }
10701
10702        Ok(())
10703    }
10704
10705    /// Reject `:membros` values that are operationally meaningless. The
10706    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
10707    /// every entry names a Servico that participates in the Aplicacao,
10708    /// and the rendered programs.yaml fan-out emits one entry per
10709    /// `:membros`. Three authoring footguns are closed here:
10710    ///
10711    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
10712    ///     a `programs:` entry whose `name:` is the empty string, which
10713    ///     downstream `lareira-fleet-programs` rejects at template time
10714    ///     with a non-localized error;
10715    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
10716    ///     an empty semver constraint, so the failure surfaces far from
10717    ///     the source caixa.lisp;
10718    ///   - duplicate `:caixa` names — two entries with the same name
10719    ///     produce duplicate programs.yaml entries (one silently
10720    ///     overwrites the other in the cluster's HelmRelease values), and
10721    ///     contract membership lookups against `:contratos` collapse the
10722    ///     two onto one node, masking authoring mistakes.
10723    ///
10724    /// Same value-shape discipline as `:placement :clusters` (where empty
10725    /// + duplicate cluster names are rejected) and `:entrada :paths`
10726    /// (where empty + duplicate path entries are rejected). Lifting these
10727    /// invariants to the typed surface mirrors the MESH-COMPOSITION
10728    /// §III.3 promise that the `:membros` set — the load-bearing identity
10729    /// of the application graph — is well-formed by construction.
10730    fn validate_membros(&self) -> Result<(), AplicacaoError> {
10731        if self.membros().is_empty() {
10732            return Err(AplicacaoError::NoMembros);
10733        }
10734        let mut seen = std::collections::HashSet::new();
10735        for m in self.membros() {
10736            // Every emitted cluster artifact's `metadata.name` derives
10737            // from a `:membros :caixa` value verbatim — the rendered
10738            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
10739            // the [`crate::LABEL_PROGRAM`] label value on every CNP
10740            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
10741            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
10742            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
10743            // `metadata.name` when the member is the `:entrada :para`
10744            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
10745            // schema enforces the DNS-1123 label rule on admission;
10746            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
10747            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
10748            // mistaken-identity slug) silently passes the prior empty-/
10749            // duplicate-only gate and the failure surfaces at `kubectl
10750            // apply` time as a `metadata.name: Invalid value` rejection,
10751            // far from the source caixa.lisp, with no field naming the
10752            // offending `:membros` entry. Lifting the gate to caixa-build
10753            // time mirrors the `:entrada :host` value-shape trajectory
10754            // (c7d05ec) on the peer axis — every author surface that
10755            // emits a K8s name now matches the apiserver's accepted set
10756            // at validate time.
10757            validate_membro_caixa(m.nome())?;
10758            // The author surface for `:versao` is the same Cargo-shaped
10759            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
10760            // `"*"`) every `:deps` entry carries — and the lacre pipeline
10761            // resolves both axes through the same
10762            // [`crate::version::parse_requirement`] entry-point. The
10763            // shared [`crate::render::require_valid_versao_requirement`]
10764            // helper brackets the empty-first + parse cascade both peer
10765            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
10766            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
10767            // route through, so drift between the three axes' accepted
10768            // requirement sets is structurally impossible and the parse-
10769            // side no-op the empty-first arm closes (semver's empty
10770            // parse yields an implicit `*`) lives in exactly one
10771            // predicate.
10772            crate::render::require_valid_versao_requirement(
10773                m.versao_requirement(),
10774                || AplicacaoError::membro_versao_empty(m.nome()),
10775                |reason| {
10776                    AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
10777                },
10778            )?;
10779            crate::render::insert_first_seen(&mut seen, m.nome(), || {
10780                AplicacaoError::membro_duplicate(m.nome())
10781            })?;
10782        }
10783        Ok(())
10784    }
10785
10786    /// Reject `:placement` values that are operationally meaningless or
10787    /// internally contradictory. Each strategy variant has the same
10788    /// invariants on `:clusters` (non-empty list, non-empty unique
10789    /// entries) — the §III.1 author surface is uniform on this axis,
10790    /// even though the *meaning* of the list differs by strategy
10791    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
10792    /// shard pool).
10793    ///
10794    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
10795    /// are the same authoring footgun closed for `:politicas` zero
10796    /// values and `:entrada` empty paths: the field is *declared* but
10797    /// carries no meaning, so downstream renderers either skip it
10798    /// silently (cluster-fanout drops the empty entry, no diagnostic)
10799    /// or apply it literally and fail at admission time. Lifting both
10800    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
10801    /// violation is a build error" promise.
10802    ///
10803    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
10804    /// is required exactly when `:estrategia Sharded` (hash-keyed
10805    /// distribution, Akka cluster-sharding convention, §II.4) and
10806    /// refused on `:estrategia Replicated`/`SingleNode` (where no
10807    /// hash-keyed routing axis consumes it). The partition closes the
10808    /// "I think I configured sharding" footgun where an author writes
10809    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
10810    /// the typed slot's value silently vanishes at the renderer layer
10811    /// — every validated `Placement` past this call satisfies
10812    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
10813    fn validate_placement(&self) -> Result<(), AplicacaoError> {
10814        // Every strategy needs at least one named cluster: `Replicated`
10815        // and `SingleNode` use the list as hosting/takeover candidates
10816        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
10817        // §II.1), while `Sharded` uses it as the shard pool
10818        // (Akka cluster-sharding convention — §II.4). An empty list is
10819        // meaningless under any of the three.
10820        //
10821        // Route the paired pre-flight `.is_empty()` refusal probe and
10822        // the per-cluster validate loop's traversal head through the
10823        // lifted [`Placement::clusters`] slice-return accessor rather
10824        // than the raw `self.placement.clusters` field access — the
10825        // two production consumers of the per-`:placement` cluster-
10826        // pool `Vec`-carry now key off exactly one typed dispatch on
10827        // the substrate primitive, so any future rebrand on the axis
10828        // (a per-tenant cluster-pool overlay the operator pins through
10829        // a future `:placement :clusters-overrides` slot, a per-
10830        // Aplicacao dynamic cluster-pool derivation the future M5
10831        // adaptive-placement engine computes from `:affinity` weights)
10832        // migrates as a single caixa-core edit rather than a
10833        // coordinated rewrite of the paired arms — sibling of the
10834        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
10835        // arm migration on the per-`:supervisor` static-child-list
10836        // `Vec`-carry axis.
10837        //
10838        // Route the per-`:placement` outer-composite reference read
10839        // through the lifted [`AplicacaoSpec::placement`] outer accessor
10840        // rather than the raw `&self.placement` field access — the
10841        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
10842        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
10843        // axis-level lifted accessor family) now routes through the
10844        // substrate-primitive typed dispatch at the outer composition
10845        // altitude, the same shape the peer caixa-mesh
10846        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
10847        // and the sibling `feira app graph` per-Aplicacao print line
10848        // now key off after this accessor lift.
10849        let p = self.placement();
10850        if p.clusters().is_empty() {
10851            // Route the per-`:placement` empty-clusters diagnostic
10852            // through the substrate-primitive
10853            // [`AplicacaoError::placement_without_clusters`] ctor rather
10854            // than the pre-lift three-line open-coded
10855            // `AplicacaoError::PlacementWithoutClusters { estrategia:
10856            // p.estrategia() }` struct-literal — folds the sole in-crate
10857            // wire-up on this variant onto one dispatch matching the
10858            // sibling per-`:placement :clusters` dedup /
10859            // per-`:contratos` self-edge / per-`:upgrade-from :from`
10860            // duplicate substrate-primitive-projection ctors on the
10861            // same `AplicacaoError` / `UpgradeError` envelopes.
10862            return Err(AplicacaoError::placement_without_clusters(p));
10863        }
10864        let mut seen = std::collections::HashSet::new();
10865        for c in p.clusters() {
10866            // Per-entry value-shape gate: the cluster name lands in
10867            // every K8s context / `lareira-fleet-programs` aggregator
10868            // filter / future M4 CR materializer's per-cluster axis
10869            // a validated `:clusters` entry passes through, each
10870            // enforcing the DNS-1123 label rule on admission. Same
10871            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
10872            // on the peer name axis — both axes' validated values
10873            // are guaranteed-accepted by the apiserver without
10874            // re-validation at any downstream renderer or admission
10875            // layer.
10876            validate_placement_cluster(c)?;
10877            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
10878                // Route the per-`:placement :clusters` dedup diagnostic
10879                // through the substrate-primitive
10880                // [`AplicacaoError::placement_cluster_duplicate`] ctor
10881                // rather than the pre-lift three-line open-coded
10882                // `AplicacaoError::PlacementClusterDuplicate { cluster:
10883                // c.clone() }` struct-literal — folds the sole in-crate
10884                // wire-up on this variant onto one dispatch matching the
10885                // sibling per-`:membros :caixa` / per-`:entrada :paths` /
10886                // per-`:politicas <scalar>` single-slot ctor families on
10887                // the same [`AplicacaoError`] envelope.
10888                AplicacaoError::placement_cluster_duplicate(c)
10889            })?;
10890        }
10891        // Route the per-`:placement :affinity` per-hint value-shape
10892        // gate through the typed [`Placement::affinity`] accessor rather
10893        // than the raw `&self.placement.affinity` field access — the
10894        // sole open-coded field-access site on the per-`:placement`
10895        // M3-Adaptive-compression-hint axis the accessor lift now owns.
10896        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
10897        // the accessor's `Option<&str>` return type;
10898        // [`validate_placement_affinity`]'s `&str` parameter accepts
10899        // the narrower borrow without a re-allocation, so the routing
10900        // change is byte-for-byte in the pass arm and remains
10901        // byte-for-byte in every failure diagnostic
10902        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
10903        // String` field is populated inside
10904        // [`validate_placement_affinity`] via the peer `.to_string()`
10905        // path on the same borrowed slice). Peer of the sibling
10906        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
10907        // routing through [`Placement::shard_key`] at the caixa-core
10908        // site above — extends the "read `:placement` optional-scalars
10909        // through the typed accessor" discipline to the second
10910        // `Option<String>`-shape slot on the M3 mesh-slot family.
10911        //
10912        // Per-hint value-shape gate: the `:affinity` value lands
10913        // verbatim in the M3 Adaptive compression overlay
10914        // (caixa-mesh's `placement.affinity` emission) and every
10915        // future M4 placement-engine routing axis keying off the
10916        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
10917        // selector — each enforces the DNS-1123 label rule on
10918        // admission. Same typed-shape trajectory as `:placement
10919        // :clusters` (6c8c00b) on the sibling slot and the four
10920        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
10921        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
10922        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
10923        // on the Aplicacao surface to land on the canonical
10924        // [`crate::render::is_dns_1123_label`] floor.
10925        if let Some(a) = p.affinity() {
10926            validate_placement_affinity(a)?;
10927        }
10928        match p.estrategia() {
10929            // Route the `Sharded`-arm shape-gate cascade through the
10930            // typed [`Placement::shard_key`] accessor rather than the
10931            // raw `&self.placement.shard_key` field access — one of the
10932            // two open-coded field-access sites on the per-`:placement`
10933            // Akka-cluster-sharding-key axis the accessor lift now
10934            // owns. The `Some(k)`-bound `k` narrows from `&String` to
10935            // `&str` under the accessor's `Option<&str>` return type;
10936            // `str::is_empty` and [`validate_placement_shard_key`]'s
10937            // `&str` parameter both accept the narrower borrow without
10938            // a re-allocation.
10939            PlacementStrategy::Sharded => match p.shard_key() {
10940                None => return Err(AplicacaoError::ShardedWithoutKey),
10941                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
10942                // Per-axis value-shape gate on the Akka-cluster-sharding
10943                // `:shard-key` extractor expression. The shape gate runs
10944                // after the more self-locating `ShardedKeyEmpty` arm so
10945                // a `:shard-key ""` surfaces the narrower empty
10946                // diagnostic first; every non-empty `:shard-key` past
10947                // this call is guaranteed to be a printable-ASCII
10948                // single-token reference the future M4 Akka-style
10949                // cluster-sharding reconciler can hash without
10950                // re-validating at the runtime layer. Mirrors the
10951                // payload-axis shape gates on the peer `:contratos`
10952                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
10953                // 63e18a0 / c4213a4) — each lifts the runtime parser's
10954                // intersection-floor to a caixa-build-time gate.
10955                Some(k) => validate_placement_shard_key(k)?,
10956            },
10957            // `:shard-key` is the Akka-cluster-sharding axis
10958            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
10959            // across the cluster pool. `Replicated` (active-active across
10960            // every named cluster) and `SingleNode` (Erlang/OTP
10961            // distributed-app takeover/failover, §II.1) have no hash-keyed
10962            // routing axis to consume the slot; downstream renderers
10963            // (caixa-mesh's `placement.shardKey` overlay at
10964            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
10965            // sharding reconciler) ignore `:shard-key` outside the
10966            // `Sharded` arm by construction. Until this gate landed an
10967            // author who wrote `:placement (:estrategia Replicated
10968            // :shard-key "tenantId")` (an off-by-one strategy typo, a
10969            // copy-paste from a Sharded sibling caixa, the "I think I
10970            // configured sharding" footgun) silently passed validate and
10971            // the typed slot's value vanished at the renderer layer with
10972            // no diagnostic — the canonical "declared-but-inert" footgun
10973            // the empty-:affinity / empty-shard-key / zero-:politicas /
10974            // empty-:contratos-target gates already close on every other
10975            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
10976            // Lifting the rejection to a build-time gate closes the
10977            // Sharded ↔ non-Sharded partition over the typed
10978            // `:placement` slot: every validated `Placement` past this
10979            // call has `shard_key.is_some()` iff `estrategia ==
10980            // Sharded`, structurally — the future Akka reconciler can
10981            // reach for `placement.shard_key` knowing it's `Some` exactly
10982            // when the strategy consumes it, without re-deriving the
10983            // partition from inline strategy probes.
10984            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
10985                // Route the non-`Sharded`-arm declared-but-inert refusal
10986                // through the typed [`Placement::shard_key`] accessor —
10987                // the second of the two open-coded field-access sites the
10988                // accessor lift now owns. The `Some(k)`-bound `k` narrows
10989                // from `&String` to `&str`; the `AplicacaoError::
10990                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
10991                // materializes the owned `String` via `k.to_string()`
10992                // (peer to the sibling per-Membro `String`-carry sites
10993                // 4127bb6 routed through `m.nome().to_string()` /
10994                // `m.versao_requirement().to_string()`), so the whole
10995                // `Sharded` ↔ non-`Sharded` partition on the
10996                // `:shard-key` axis now flows through the same typed
10997                // dispatch as the sibling `Sharded`-arm shape gate.
10998                if let Some(k) = p.shard_key() {
10999                    return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
11000                }
11001            }
11002        }
11003        Ok(())
11004    }
11005
11006    /// Reject `:politicas` values that are operationally meaningless.
11007    /// Each axis is optional — omitting it expresses "no policy on this
11008    /// axis". Carrying a *zero* value for a declared axis is the bug
11009    /// this function rejects: zero is either
11010    ///
11011    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
11012    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
11013    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
11014    ///     "every Aplicacao declares :politicas :timeout (no infinite
11015    ///     blocking)", or
11016    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
11017    ///     first call; a 0-rate rate-limit denies every request).
11018    ///
11019    /// Lifting these "0 means the opposite of what you think" idioms to
11020    /// the typed Aplicacao surface as build errors mirrors the §III.3
11021    /// promise that contract drift, capability leaks, and cycles are all
11022    /// build errors — not runtime surprises.
11023    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
11024        // Route the whole per-axis + cross-axis `:politicas` cascade
11025        // through the substrate primitive [`MeshPolicy::validate`],
11026        // which folds all six per-axis brackets (`:timeout`,
11027        // `:retries`, `:circuit-breaker :max-failures`,
11028        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
11029        // window-canonical-form) plus the compound cross-axis fold
11030        // [`MeshPolicy::first_cross_axis_violation`] into one
11031        // `Result<(), AplicacaoError>` return. The whole per-axis-
11032        // brackets + cross-axis-fold cascade collapses to one call, and
11033        // every future [`MeshPolicy`] consumer (the future M4
11034        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
11035        // admission webhook, the per-`:contratos`-edge `:politicas`
11036        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
11037        // of which resolves an *effective* per-edge [`MeshPolicy`] and
11038        // must emit *the same* diagnostic on the same input as `feira
11039        // build`) reaches through the same substrate-primitive dispatch
11040        // rather than re-inlining the four-per-axis + one-cross-axis
11041        // cascade in lockstep with this validate gate. Same trajectory
11042        // the peer per-kind compound entry gates
11043        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
11044        // [`crate::render::require_supervisor_view`] (8d8a5c3),
11045        // [`crate::render::require_v0_servico_shape`] (per-Caixa
11046        // layout axis) and the sibling compound cross-axis fold
11047        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
11048        // extended here onto the per-slot compound entry gate that
11049        // folds both per-axis + cross-axis surfaces on the M3
11050        // mesh-slot family.
11051        self.politicas().validate()
11052    }
11053
11054    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
11055    /// A synchronous edge is any contract whose typed [`WitTarget`] is
11056    /// `Http`, `Store`, or `Capability` — the caller blocks on the
11057    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
11058    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
11059    /// block on its subscribers, so they can never close a sync loop.
11060    ///
11061    /// Iterative DFS with three-coloring; the reported cycle is the
11062    /// path of caixa names traversed from the back-edge target around
11063    /// to itself, in declaration order. Adjacency lists and DFS roots
11064    /// are visited in `BTreeMap` key order so the diagnostic is
11065    /// deterministic across runs.
11066    ///
11067    /// Now the cross-edge axis of the per-slot compound gate
11068    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
11069    /// the per-entry cascade rather than at the outer
11070    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
11071    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
11072    /// sync-cycle) reach every consumer through one call. Kept
11073    /// standalone (rather than inlined) so consumers that want only the
11074    /// cross-edge axis (the M4 per-edge policy resolver
11075    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
11076    /// mutates one `:contratos` entry and needs to re-probe *just* the
11077    /// cycle invariant against the post-patch adjacency without
11078    /// re-running the per-entry shape/membership/dedup cascade the
11079    /// per-entry-only [M4 admission] fast path already covered) still
11080    /// have a self-contained entry point on the cycle axis.
11081    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
11082        use std::collections::{BTreeMap, BTreeSet};
11083
11084        #[derive(Clone, Copy, PartialEq, Eq)]
11085        enum Mark {
11086            White,
11087            Gray,
11088            Black,
11089        }
11090
11091        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
11092        for m in self.membros() {
11093            adj.entry(m.nome()).or_default();
11094        }
11095        for c in self.contratos() {
11096            // target() was already called by validate(); re-running here
11097            // keeps detect_sync_cycles self-contained for callers that
11098            // reuse it (M4 per-edge policy resolver) without revalidating.
11099            //
11100            // The pub-sub-arm check routes through the lifted
11101            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
11102            // arm-discriminator predicate rather than a raw `matches!(…,
11103            // WitTarget::PubSub { .. })` on the variant so a future
11104            // rebrand on the axis (an M4 per-edge WIT registry split of
11105            // [`WitTarget::PubSub`] into shape-specific peers, a
11106            // per-consumer rename that the accept-set already carries)
11107            // reaches this call site through the derive rather than a
11108            // scattered per-arm `matches!` rewrite — same
11109            // `IsVariant`-derived-arm-discriminator discipline the
11110            // peer closed-set typed enums ([`crate::CaixaKind`] via
11111            // f5bba80, [`PlacementStrategy`] via 766ec63,
11112            // [`crate::supervisor::RestartStrategy`] +
11113            // [`crate::supervisor::RestartPolicy`],
11114            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
11115            // already route through on the substrate's other typed-enum
11116            // arm-discriminator axes.
11117            if c.target()?.is_pubsub() {
11118                continue;
11119            }
11120            adj.entry(c.source()).or_default().insert(c.destination());
11121        }
11122
11123        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
11124        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
11125
11126        // Stable DFS root order — BTreeMap iteration is sorted by key.
11127        let roots: Vec<&str> = adj.keys().copied().collect();
11128
11129        // Frame: (node, sorted-neighbours snapshot, next-edge index).
11130        for root in roots {
11131            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
11132                continue;
11133            }
11134            let root_neighbors: Vec<&str> = adj
11135                .get(root)
11136                .map(|s| s.iter().copied().collect())
11137                .unwrap_or_default();
11138            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
11139            color.insert(root, Mark::Gray);
11140
11141            loop {
11142                // Read+advance the top frame in one borrow scope so we
11143                // can later mutate the stack (push/pop) without holding
11144                // a borrow across.
11145                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
11146                    let node = top.0;
11147                    if top.2 >= top.1.len() {
11148                        (node, None)
11149                    } else {
11150                        let nxt = top.1[top.2];
11151                        top.2 += 1;
11152                        (node, Some(nxt))
11153                    }
11154                });
11155                let Some((node, nxt_opt)) = step else { break };
11156                let Some(nxt) = nxt_opt else {
11157                    color.insert(node, Mark::Black);
11158                    stack.pop();
11159                    continue;
11160                };
11161                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
11162                match nxt_color {
11163                    Mark::Gray => {
11164                        // Reconstruct the cycle from `node` back through
11165                        // the parent chain to `nxt`, then close.
11166                        let mut cycle = Vec::new();
11167                        let mut cur = node;
11168                        cycle.push(cur.to_string());
11169                        while cur != nxt {
11170                            match parent.get(cur).copied() {
11171                                Some(p) => {
11172                                    cur = p;
11173                                    cycle.push(cur.to_string());
11174                                }
11175                                None => break,
11176                            }
11177                        }
11178                        cycle.reverse();
11179                        cycle.push(nxt.to_string());
11180                        return Err(AplicacaoError::contrato_cycle(cycle));
11181                    }
11182                    Mark::White => {
11183                        parent.insert(nxt, node);
11184                        color.insert(nxt, Mark::Gray);
11185                        let nxt_neighbors: Vec<&str> = adj
11186                            .get(nxt)
11187                            .map(|s| s.iter().copied().collect())
11188                            .unwrap_or_default();
11189                        stack.push((nxt, nxt_neighbors, 0));
11190                    }
11191                    Mark::Black => {}
11192                }
11193            }
11194        }
11195        Ok(())
11196    }
11197
11198    /// Substrate-canonical destination-facing TCP port every emitted
11199    /// per-Aplicacao artifact must key `destination`-shaped port axes
11200    /// off. Returns the typed `:entrada :port` scalar when this
11201    /// Aplicacao's `:entrada` block names `destination` under its
11202    /// `:para` axis (the destination Servico *is* the ingress apex, so
11203    /// the substrate honors the author-declared listener port
11204    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
11205    /// fallback otherwise (every non-apex destination — the internal
11206    /// mesh Servicos `:contratos` reach across, the future per-edge
11207    /// policy resolver's per-destination probe targets, the
11208    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
11209    /// L4 port resolver — reads the same substrate-canonical port floor
11210    /// by construction).
11211    ///
11212    /// Prior to this lift the "if :entrada matches this destination use
11213    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
11214    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
11215    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
11216    /// prior to this lift), with no typed method on the substrate primitive
11217    /// that named the rule. A future per-destination port axis addition
11218    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
11219    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
11220    /// per-Servico listener ports land, a per-cluster override the operator
11221    /// pins through a future `:placement :default-port` slot — would have
11222    /// to be threaded through every renderer's inline cascade in lockstep
11223    /// or one consumer would silently disagree on which port a given
11224    /// destination Servico's ingress lands at. Lifting the rule to a
11225    /// typed method on the substrate primitive means the M4 CR
11226    /// materializer, the future per-edge policy resolver, and every
11227    /// downstream test-fixture navigator reach for exactly one typed
11228    /// dispatch — the resolver's accept-set moves as a unit on any
11229    /// future axis addition.
11230    ///
11231    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
11232    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
11233    /// the typed primitive, thin projections at each consumer"
11234    /// discipline lifts on the sibling `:contratos` payload / `:politicas
11235    /// :rate-limit` unit-suffix axes; extends the discipline onto the
11236    /// destination-facing port-resolution axis every per-Aplicacao
11237    /// L4-fallback renderer consumes.
11238    #[must_use]
11239    pub fn port_for_destination(&self, destination: &str) -> u16 {
11240        // Route the per-`:entrada` composite-reference read through
11241        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
11242        // the raw `self.entrada.as_ref()` field access — the
11243        // per-destination L4-port fallback resolver's composite-
11244        // projection seed is now the canonical read-side surface
11245        // every per-Aplicacao entrada consumer routes through, peer
11246        // of the sibling `validate` per-`:entrada` shape-and-
11247        // membership gate migration on the same outer-composite
11248        // axis.
11249        // Route the per-`:entrada` apex-destination membership probe
11250        // through the lifted [`Entrada::destination`] accessor rather
11251        // than the raw `e.para == destination` field access — the last
11252        // un-lifted `.para` production-code read site on the per-
11253        // `:entrada` `:para` axis, sibling to the four caixa-core
11254        // consumer sites the peer 15ddd8c converge already routed
11255        // through the accessor (the three
11256        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
11257        // membership gate sites: the `validate_entrada_para` DNS-1123
11258        // shape gate, the per-`:membros` membership lookup, and the
11259        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
11260        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
11261        // `entrada.para`-projection converge at
11262        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
11263        // route-name projection site). Prior to this converge the
11264        // `port_for_destination` resolver was the solitary consumer
11265        // bypassing the typed dispatch on the `.para` axis — the two
11266        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
11267        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
11268        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
11269        // reach through the same accessor family compose with this
11270        // resolver at the emit boundary via the apex-identity
11271        // invariant `spec.port_for_destination(entrada.destination())
11272        // == entrada.port` the sibling
11273        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
11274        // pin pins across four permutations. A future extension of the
11275        // `:entrada :para` axis to a richer author surface (a per-
11276        // cluster alias overlay the operator pins through a future
11277        // `:placement`-scoped slot, a namespace-qualified rewrite the
11278        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
11279        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
11280        // §III.2 acknowledges) that lands on the accessor would silently
11281        // disagree between this resolver and the two `caixa-mesh` emit
11282        // sites — an author-declared `:para "cart"` value the accessor
11283        // rewrote to `"cart-v2"` under a future canary arm would leave
11284        // the resolver's membership arm falling through to
11285        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
11286        // `.para`) while the peer emit-site consumers landed on the
11287        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
11288        // silently disagreed on which destination port a given typed
11289        // `:entrada` resolves to at cluster-apply time. Pinned by the
11290        // drift-detection test
11291        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
11292        // below.
11293        self.entrada()
11294            .filter(|e| e.destination() == destination)
11295            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
11296    }
11297}
11298
11299/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
11300/// entry may name the Aplicacao's own `:nome`.
11301///
11302/// An Aplicacao that lists itself as a member is a degenerate self-edge in
11303/// the typed graph — the application graph is a DAG rooted at the Aplicacao
11304/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
11305/// Servicos that compose the app; an Aplicacao is never its own constituent),
11306/// and the lacre pipeline's closure-resolution would otherwise be handed a
11307/// node that is its own parent: a one-node cycle it either rejects far from
11308/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
11309/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
11310/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
11311/// label + lacre closure root), a member whose `:caixa` equals the
11312/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
11313/// peer.
11314///
11315/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
11316/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
11317/// gate `validate_upgrade_from_against_versao` and the supervision-tree
11318/// self-parent gate `crate::supervisor::validate_no_self_supervision`
11319/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
11320/// not a tree/mesh edge" discipline, here on the second typed-graph axis
11321/// (the Aplicacao :membros set; the supervision-tree :children list was the
11322/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
11323/// every validated Supervisor's children are distinct from its `:nome`,
11324/// every validated Aplicacao's membros are distinct from its `:nome`. The
11325/// transitive consequence is that `:entrada :para` and `:contratos`
11326/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
11327/// name the Aplicacao itself, without re-deriving the partition.
11328pub fn validate_no_self_membership(
11329    membros: &[Membro],
11330    parent_nome: &str,
11331) -> Result<(), AplicacaoError> {
11332    for m in membros {
11333        if m.nome() == parent_nome {
11334            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
11335        }
11336    }
11337    Ok(())
11338}
11339
11340#[derive(Debug, Error, PartialEq, Eq)]
11341pub enum AplicacaoError {
11342    #[error("Aplicacao must declare at least one :membros entry")]
11343    NoMembros,
11344    #[error(
11345        ":membros entry has empty :caixa (every member must name a Servico; \
11346         omit the entry instead of carrying an empty name)"
11347    )]
11348    MembroCaixaEmpty,
11349    #[error(
11350        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
11351         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
11352         name / label value the member name lands in; use a lowercase \
11353         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
11354    )]
11355    MembroCaixaInvalid { caixa: String, reason: String },
11356    #[error(
11357        ":membros entry {caixa:?} has empty :versao (every member must pin a \
11358         semver constraint that resolves through the lacre pipeline)"
11359    )]
11360    MembroVersaoEmpty { caixa: String },
11361    #[error(
11362        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
11363         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
11364         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
11365         carries; the lacre pipeline resolves both through the same parser)"
11366    )]
11367    MembroVersaoInvalid {
11368        caixa: String,
11369        versao: String,
11370        reason: String,
11371    },
11372    #[error(
11373        ":membros entry {caixa:?} appears more than once (the graph node set \
11374         is a set, not a multiset; duplicate members produce duplicate \
11375         programs.yaml entries and ambiguous :contratos membership lookups)"
11376    )]
11377    MembroDuplicate { caixa: String },
11378    #[error(
11379        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
11380         never its own constituent Servico (the application graph is a DAG rooted \
11381         at the Aplicacao; :membros names the *other* caixas that compose the \
11382         app, not the app itself). Since every :nome is a globally-unique \
11383         substrate identity, a member naming the Aplicacao's own :nome is a \
11384         one-node lacre-closure recursion, not a coincidentally-named peer; \
11385         drop the self-referential :membros entry or rename it to the actual \
11386         constituent caixa."
11387    )]
11388    MembroIsSelfAplicacao { caixa: String },
11389    #[error(
11390        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
11391         caixa declared in :membros; omit the contract or fill the {slot} field with a \
11392         member name)"
11393    )]
11394    ContratoCaixaEmpty { slot: &'static str },
11395    #[error(
11396        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
11397         :contratos {slot} value names a member of :membros, which is itself a \
11398         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
11399         object the member name lands in — Service, Pod, identity-based Cilium \
11400         selector; use a lowercase alphanumeric + hyphen identifier like \
11401         `\"checkout\"` or `\"cart-v2\"`)"
11402    )]
11403    ContratoCaixaInvalid {
11404        slot: &'static str,
11405        caixa: String,
11406        reason: String,
11407    },
11408    #[error("contrato references caixa {caixa:?} not declared in :membros")]
11409    ContratoMemberMissing { caixa: String },
11410    #[error(
11411        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
11412         entry is an inter-Servico contract whose :de and :para must name distinct \
11413         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
11414         the contract, or point :para at the member it actually calls)"
11415    )]
11416    ContratoSelfLoop { caixa: String, wit: String },
11417    #[error("contrato {de:?} → {para:?} has empty :wit")]
11418    EmptyWit { de: String, para: String },
11419    #[error(
11420        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
11421         {reason} (the substrate dispatches `:wit` values on the canonical \
11422         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
11423         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
11424         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
11425         kebab-case identifier per segment)"
11426    )]
11427    ContratoWitInvalid {
11428        de: String,
11429        para: String,
11430        wit: String,
11431        reason: String,
11432    },
11433    #[error(
11434        ":entrada :para is empty (every :entrada must route to a caixa declared in \
11435         :membros; fill the :para field with a member name)"
11436    )]
11437    EntradaParaEmpty,
11438    #[error(
11439        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
11440         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
11441         label per the K8s apiserver's `metadata.name` rule on every object the \
11442         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
11443         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
11444         `\"checkout\"` or `\"cart-v2\"`)"
11445    )]
11446    EntradaParaInvalid { para: String, reason: String },
11447    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
11448    EntradaMemberMissing { para: String },
11449    #[error(":entrada must declare a non-empty :host")]
11450    EmptyEntradaHost,
11451    #[error(
11452        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
11453         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
11454         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
11455         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
11456    )]
11457    EntradaHostInvalid { host: String, reason: String },
11458    #[error(":entrada :port must be in 1..=65535, got 0")]
11459    EntradaPortZero,
11460    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
11461    EntradaPathEmpty,
11462    #[error(
11463        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
11464    )]
11465    EntradaPathNotAbsolute { path: String },
11466    #[error(
11467        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
11468         value: {reason} (the K8s apiserver enforces the same shape on \
11469         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
11470         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
11471         requires percent-encoding `%XX` for non-ASCII and whitespace)"
11472    )]
11473    EntradaPathInvalid { path: String, reason: String },
11474    #[error(":entrada :paths entry {path:?} appears more than once")]
11475    EntradaPathDuplicate { path: String },
11476    #[error(
11477        ":placement {estrategia} requires at least one :clusters entry \
11478         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
11479    )]
11480    PlacementWithoutClusters { estrategia: PlacementStrategy },
11481    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
11482    PlacementClusterEmpty,
11483    #[error(
11484        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
11485         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
11486         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
11487         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
11488         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
11489         identifier like `\"rio\"` or `\"mar-east\"`)"
11490    )]
11491    PlacementClusterInvalid { cluster: String, reason: String },
11492    #[error(":placement :clusters entry {cluster:?} appears more than once")]
11493    PlacementClusterDuplicate { cluster: String },
11494    #[error(
11495        ":placement :affinity must be non-empty when set (omit :affinity to express \
11496         `no placement hint`)"
11497    )]
11498    PlacementAffinityEmpty,
11499    #[error(
11500        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
11501         (placement hints land verbatim in the M3 Adaptive compression overlay's \
11502         `placement.affinity` field and in every future M4 placement-engine routing \
11503         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
11504         selector — both enforce the DNS-1123 label rule on admission; use a \
11505         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
11506         `\"low-latency\"`, or `\"anti-affinity\"`)"
11507    )]
11508    PlacementAffinityInvalid { affinity: String, reason: String },
11509    #[error(":placement Sharded requires :shard-key")]
11510    ShardedWithoutKey,
11511    #[error(
11512        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
11513         hashes every entity onto the same shard, defeating sharding entirely)"
11514    )]
11515    ShardedKeyEmpty,
11516    #[error(
11517        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
11518         entity-id extractor expression: {reason} (the future M4 Akka-style \
11519         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
11520         as a single-token property reference and hashes the extracted entity ID \
11521         to compute shard placement; use a printable-ASCII extractor expression \
11522         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
11523         `\"${{tenant}}\"`)"
11524    )]
11525    ShardKeyInvalid { shard_key: String, reason: String },
11526    #[error(
11527        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
11528         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
11529         convention); :estrategia Replicated runs every cluster active-active and \
11530         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
11531         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
11532         to :estrategia Sharded if hash-keyed routing is the intent"
11533    )]
11534    ShardKeyOnNonSharded {
11535        estrategia: PlacementStrategy,
11536        shard_key: String,
11537    },
11538    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
11539    ContratoMissingTarget {
11540        de: String,
11541        para: String,
11542        wit: String,
11543        expected: &'static str,
11544    },
11545    #[error(
11546        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
11547         expected `:{expected}` only"
11548    )]
11549    ContratoWrongTarget {
11550        de: String,
11551        para: String,
11552        wit: String,
11553        expected: &'static str,
11554    },
11555    #[error(
11556        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
11557         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
11558         that matches no traffic and silently drops every request)"
11559    )]
11560    ContratoEndpointEmpty { de: String, para: String },
11561    #[error(
11562        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
11563         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
11564         :entrada :paths)"
11565    )]
11566    ContratoEndpointNotAbsolute {
11567        de: String,
11568        para: String,
11569        endpoint: String,
11570    },
11571    #[error(
11572        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
11573         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
11574         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
11575         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
11576         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
11577         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
11578         and whitespace)"
11579    )]
11580    ContratoEndpointInvalid {
11581        de: String,
11582        para: String,
11583        endpoint: String,
11584        reason: String,
11585    },
11586    #[error(
11587        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
11588         subject is a no-op subscribe; omit :subject only if the WIT world is not \
11589         pub-sub-shaped)"
11590    )]
11591    ContratoSubjectEmpty { de: String, para: String },
11592    #[error(
11593        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
11594         NATS subject: {reason} (the NATS server's subject parser enforces the \
11595         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
11596         single-token and `>` multi-token wildcards — at publish/subscribe time; \
11597         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
11598         `\"orders.*.completed\"` — a malformed subject silently drops every \
11599         message at runtime far from the source caixa.lisp)"
11600    )]
11601    ContratoSubjectInvalid {
11602        de: String,
11603        para: String,
11604        subject: String,
11605        reason: String,
11606    },
11607    #[error(
11608        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
11609         addresses the bucket root, defeating the per-key isolation the slot exists \
11610         for; omit :slot only if the WIT world is not store-shaped)"
11611    )]
11612    ContratoSlotEmpty { de: String, para: String },
11613    #[error(
11614        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
11615         WASI keyvalue store slot template: {reason} (the substrate enforces \
11616         the printable-ASCII intersection-floor every kv backend admits — \
11617         use a single-token path / template expression like `\"checkout/$orderId\"`, \
11618         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
11619         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
11620         slot either gets rejected on write by strict backends or silently \
11621         corrupts the next read on permissive ones, far from the source caixa.lisp)"
11622    )]
11623    ContratoSlotInvalid {
11624        de: String,
11625        para: String,
11626        slot: String,
11627        reason: String,
11628    },
11629    #[error(
11630        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
11631         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
11632        cycle.join(" → ")
11633    )]
11634    ContratoCycle { cycle: Vec<String> },
11635    #[error(
11636        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
11637         than once (the typed graph edges are a set, not a multiset; duplicate \
11638         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
11639         values that K8s admission rejects far from the source caixa.lisp)"
11640    )]
11641    ContratoDuplicate {
11642        de: String,
11643        para: String,
11644        wit: String,
11645        target: String,
11646    },
11647    #[error(
11648        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
11649         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
11650         express `no per-call deadline on this axis`"
11651    )]
11652    PolicyTimeoutZero,
11653    #[error(
11654        ":politicas :retries must be > 0 when set; omit :retries to express \
11655         `no retries on transient failure`"
11656    )]
11657    PolicyRetriesZero,
11658    #[error(
11659        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
11660         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
11661         retry policy into a thundering-herd amplification vector on transient \
11662         failure (one caller request fans out to `(retries+1)^depth` server-side \
11663         calls across the synchronous-:contratos subgraph), exactly the failure \
11664         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
11665         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
11666         or omit :retries to disable retries entirely"
11667    )]
11668    PolicyRetriesExceedsCap { retries: u32 },
11669    #[error(
11670        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
11671         breaker trips on the first call); omit :circuit-breaker to disable it"
11672    )]
11673    PolicyBreakerZeroFailures,
11674    #[error(
11675        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
11676         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
11677         above this cap turns the typed breaker policy into a no-op: the trip \
11678         threshold is structurally so high that no realistic failures-per-:window \
11679         traffic shape can reach it, so the breaker never trips and every typed-slot \
11680         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
11681         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
11682         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
11683         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
11684         omit :circuit-breaker to disable the breaker entirely"
11685    )]
11686    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
11687    #[error(
11688        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
11689         tracks no failures); omit :circuit-breaker to disable it"
11690    )]
11691    PolicyBreakerZeroWindow,
11692    #[error(
11693        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
11694         request); omit :rate-limit to disable rate limiting"
11695    )]
11696    PolicyRateLimitZero,
11697    #[error(
11698        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
11699         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
11700         rate-limit policy into a no-op limiter: the token-bucket capacity is \
11701         structurally so high that no realistic per-edge traffic shape can drain it, \
11702         so the limiter never trips and every typed-slot consumer (the future \
11703         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
11704         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
11705         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
11706         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
11707         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
11708         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
11709         to disable rate limiting entirely"
11710    )]
11711    PolicyRateLimitExceedsCap { rate: u32 },
11712    #[error(
11713        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
11714         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
11715         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
11716         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
11717         three canonical windows)"
11718    )]
11719    PolicyRateLimitWindowNotCanonical { window: Duration },
11720    #[error(
11721        ":politicas :timeout must be an integer number of milliseconds — the canonical \
11722         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
11723         duration codec round-trips losslessly; got {timeout:?} which carries a \
11724         sub-millisecond residue that either truncates to a different `Duration` on \
11725         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
11726         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
11727         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
11728         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
11729    )]
11730    PolicyTimeoutNotCanonical { timeout: Duration },
11731    #[error(
11732        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
11733         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
11734         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
11735         overlays carry a deadline so long no realistic synchronous-:contratos \
11736         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
11737         CSE invariant degenerates to enforcement only at the per-Servico \
11738         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
11739         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
11740         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
11741         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
11742         maxes out at the same `3600s` ceiling) or omit :timeout to express \
11743         `no per-call deadline on this axis` (the synchronous-call deadline then \
11744         relies entirely on the per-Servico `:limits :wall-clock` axis)"
11745    )]
11746    PolicyTimeoutExceedsCap { timeout: Duration },
11747    #[error(
11748        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
11749         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
11750         the shared duration codec round-trips losslessly; got {window:?} which carries a \
11751         sub-millisecond residue that either truncates to a different `Duration` on \
11752         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
11753         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
11754    )]
11755    PolicyBreakerWindowNotCanonical { window: Duration },
11756    #[error(
11757        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
11758         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
11759         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
11760         is structurally so long that transient failures are never forgotten, the breaker \
11761         trips once and stays tripped for the lifetime of the component, and every typed-slot \
11762         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
11763         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
11764         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
11765         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
11766         the breaker entirely"
11767    )]
11768    PolicyBreakerWindowExceedsCap { window: Duration },
11769    #[error(
11770        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
11771         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
11772         a single timing-out call can be declared failed, so the dominant failure mode \
11773         the breaker exists to catch is structurally never counted: a call dispatched at \
11774         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
11775         open at dispatch has already rolled, and every typed-slot consumer (the future \
11776         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
11777         outlier_detection.interval paired against the per-route request timeout) emits a \
11778         breaker that cannot trip on timeouts however high the call volume. Pin :window \
11779         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
11780         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
11781         same shape), lower :timeout, or omit one of the two axes"
11782    )]
11783    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
11784    #[error(
11785        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
11786         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
11787         :window ({cb_window:?}) — the token-bucket dispatches at most \
11788         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
11789         structurally below the trip threshold, so the breaker cannot trip even under \
11790         100% failure and every typed-slot consumer (the future \
11791         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
11792         outlier_detection.consecutive_5xx paired against \
11793         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
11794         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
11795         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
11796    )]
11797    PolicyBreakerCannotTripUnderRateLimit {
11798        rate: u32,
11799        rl_window: Duration,
11800        max_failures: u32,
11801        cb_window: Duration,
11802    },
11803    #[error(
11804        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
11805         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
11806         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
11807         at or before the last retry, so the breaker opens with declared retries still \
11808         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
11809         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
11810         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
11811         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
11812         Envoy / resilience4j production playbooks recommend the breaker's trip \
11813         threshold be observably larger than any single client's retry budget so the \
11814         breaker distinguishes one persistently-failing client from sustained \
11815         multi-client failure), lower :retries, or omit one of the two axes"
11816    )]
11817    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
11818    #[error(
11819        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
11820         ({retries}) plus the initial attempt — one client's declared retry sequence is \
11821         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
11822         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
11823         retry policy is silently truncated by the same rate limiter it feeds through and \
11824         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
11825         overlay, Envoy's retry_policy.num_retries paired against \
11826         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
11827         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
11828         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
11829         bucket capacity be observably larger than any single client's retry budget so the \
11830         limiter distinguishes one client's declared retries from sustained multi-client \
11831         load), lower :retries, or omit one of the two axes"
11832    )]
11833    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
11834}
11835
11836// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
11837// ctor `entrada_host_invalid` is folded onto the sibling
11838// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
11839// `{ <field>: String, reason: String }` variants
11840// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
11841// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
11842// `ShardKeyInvalid`), so every variant on the uniform two-slot
11843// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
11844// reads through one substrate-primitive family rather than one macro
11845// closing six sites plus a hand-written seventh ctor closing the
11846// paired site alone. Prior separate-ctor rationale (17dd504) migrates
11847// verbatim to the macro's outer doc block.
11848
11849// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
11850// wit, expected }` wire-up sites at [`WitContract::target`] onto one
11851// substrate-primitive family per typed variant — the paired sibling on
11852// [`AplicacaoError`] of the four `LayoutError` constructor families
11853// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
11854// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
11855// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
11856// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
11857// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
11858// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
11859// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
11860// HTTP with subject/slot, PubSub with endpoint/slot, Store with
11861// endpoint/subject, Capability with any payload; three
11862// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
11863// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
11864// opened the identical six-line
11865// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
11866// WitTarget::<label> }` struct-literal against the local `edge()` closure
11867// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
11868// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
11869// on the same altitude the peer four `LayoutError` constructor families
11870// each closed on their sibling envelopes.
11871//
11872// The macro below generates one `#[must_use]` inherent constructor per
11873// variant of shape `fn <ctor>(edge: (String, String, String), expected:
11874// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
11875// dispatch per arm: `return
11876// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
11877// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
11878// the pre-lift struct-literal on the same edge fixture. The uniform four-
11879// field construction (`de, para, wit` triple-destructure onto same-named
11880// fields + `expected` verbatim) is spelled once — inside the macro —
11881// rather than at every wire-up site. `#[must_use]` fires a compile warning
11882// at any wire-up that mistakenly discards the constructed error.
11883//
11884// Every future consumer that wants to construct one of these two variants
11885// outside [`WitContract::target`] (a deferred
11886// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
11887// admission validator raising wrong-target / missing-target diagnostics
11888// on unrecognized shapes, a future `feira validate --contratos` per-caixa
11889// admission verb, a per-`WitContract` payload-axis pre-emitter probing
11890// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
11891// slots) reaches the variant through one call rather than re-inlining the
11892// six-line struct-literal block in lockstep with the seven in-crate
11893// wire-up sites.
11894macro_rules! contrato_target_ctors {
11895    ($($ctor:ident => $variant:ident),* $(,)?) => {
11896        impl AplicacaoError {
11897            $(
11898                #[doc = concat!(
11899                    "Construct an [`AplicacaoError::",
11900                    stringify!($variant),
11901                    "`] naming the offending edge `(de, para, wit)` triple ",
11902                    "under the given `expected` payload-field-name label. ",
11903                    "Folds the uniform `{ de, para, wit, expected }` four-",
11904                    "slot struct-literal onto one substrate primitive so ",
11905                    "every [`WitContract::target`] wire-up on this variant ",
11906                    "reads through one dispatch rather than the pre-lift ",
11907                    "six-line open-coded block. The `edge` triple threads ",
11908                    "verbatim from [`WitContract::edge_triple`] via the ",
11909                    "local `edge()` closure at the call site."
11910                )]
11911                #[must_use]
11912                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
11913                    let (de, para, wit) = edge;
11914                    Self::$variant { de, para, wit, expected }
11915                }
11916            )*
11917        }
11918    };
11919}
11920
11921contrato_target_ctors! {
11922    contrato_wrong_target => ContratoWrongTarget,
11923    contrato_missing_target => ContratoMissingTarget,
11924}
11925
11926// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
11927// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
11928// onto one substrate-primitive family per typed variant — the paired
11929// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
11930// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
11931// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
11932// `ContratoMissingTarget`) and of the two-slot
11933// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
11934// on the sibling per-`:entrada :host` envelope. Every one of the four
11935// wire-up sites — three under [`WitContract::target`] (the empty
11936// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
11937// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
11938// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
11939// value-shape gate fires ahead of) — opened the identical two-line
11940// `let (de, para) = <contract>.edge_pair(); return Err(
11941// AplicacaoError::<Variant> { de, para });` block against the local
11942// [`WitContract::edge_pair`] composite-projection accessor, the exact
11943// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
11944// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
11945// and [`AplicacaoError::entrada_host_invalid`] each closed on their
11946// sibling envelopes.
11947//
11948// The macro below generates one `#[must_use]` inherent constructor per
11949// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
11950// collapsing the four sites onto one dispatch per arm:
11951// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
11952// equal to the pre-lift struct-literal on the same edge pair. The
11953// uniform two-field construction (`de, para` pair-destructure onto
11954// same-named fields) is spelled once — inside the macro — rather than
11955// at every wire-up site. `#[must_use]` fires a compile warning at any
11956// wire-up that mistakenly discards the constructed error.
11957//
11958// Every future consumer that wants to construct one of these four
11959// variants outside the two in-crate wire-up sites (a deferred
11960// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
11961// admission validator raising empty-payload / empty-`:wit` diagnostics,
11962// a future `feira validate --contratos` per-caixa admission verb, an
11963// M4 typed WIT-registry-driven per-arm pre-emitter probing the
11964// [`WitContract`] payload slot against a canonical per-arm requirement
11965// table) reaches the variant through one call rather than re-inlining
11966// the two-line pair-destructure block in lockstep with the four
11967// in-crate wire-up sites.
11968macro_rules! contrato_empty_pair_ctors {
11969    ($($ctor:ident => $variant:ident),* $(,)?) => {
11970        impl AplicacaoError {
11971            $(
11972                #[doc = concat!(
11973                    "Construct an [`AplicacaoError::",
11974                    stringify!($variant),
11975                    "`] naming the offending edge `(de, para)` pair. ",
11976                    "Folds the uniform `{ de, para }` two-slot struct-",
11977                    "literal onto one substrate primitive so every ",
11978                    "wire-up on this variant reads through one dispatch ",
11979                    "rather than the pre-lift two-line open-coded ",
11980                    "`let (de, para) = <contract>.edge_pair(); return ",
11981                    "Err(<Variant> { de, para });` block. The `edge` ",
11982                    "pair threads verbatim from [`WitContract::edge_pair`] ",
11983                    "at the call site."
11984                )]
11985                #[must_use]
11986                pub fn $ctor(edge: (String, String)) -> Self {
11987                    let (de, para) = edge;
11988                    Self::$variant { de, para }
11989                }
11990            )*
11991        }
11992    };
11993}
11994
11995contrato_empty_pair_ctors! {
11996    empty_wit => EmptyWit,
11997    contrato_endpoint_empty => ContratoEndpointEmpty,
11998    contrato_subject_empty => ContratoSubjectEmpty,
11999    contrato_slot_empty => ContratoSlotEmpty,
12000}
12001
12002// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
12003// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
12004// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
12005// onto one substrate primitive on [`AplicacaoError`] — sibling on the
12006// `{ de: String, para: String, <field>: String }` three-slot envelope of
12007// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
12008// variants on the paired `{ de, para }` two-slot envelope carrying the
12009// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
12010// { de, para });` pair-destructure prelude), the peer four-slot
12011// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
12012// the paired `{ de, para, <field>: String, reason: String }` envelope
12013// carrying the parser-shaped `reason` trailer), and the peer four-slot
12014// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
12015// `{ de, para, wit, expected: &'static str }` envelope carrying the
12016// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
12017// variant is the sole occupant of the three-slot `{ de, para, <field>:
12018// String }` shape on [`AplicacaoError`] (no sibling
12019// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
12020// and `:slot` axes carry no "must start with /" invariant, since the
12021// NATS subject grammar and the WASI keyvalue slot template grammar don't
12022// share the Gateway-API-HTTPPathMatch leading-slash prelude the
12023// `:endpoint` axis does), so a full macro isn't warranted; a single
12024// `#[must_use]` inherent ctor matching the ambient
12025// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
12026// peer per-`:contratos` ctor families each carry closes the last
12027// open-coded three-slot struct-literal on the envelope, matching the
12028// same standalone-ctor discipline the sibling
12029// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
12030// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
12031// [`crate::SupervisorError::child_caixa_invalid`] /
12032// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
12033// `{ caixa: String, [versao: String,] reason: String }` two- and three-
12034// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
12035// one variant on the `{ host: String, reason: String }` two-slot
12036// envelope) apply on their sibling one-off variants.
12037//
12038// The one wire-up site on this variant — [`WitContract::target`]'s
12039// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
12040// six per-`:contratos` value-shape gates inside the same method body,
12041// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
12042// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
12043// `ContratoWitInvalid`) each already reach through one of the three
12044// peer macro-generated ctor families above — opened the same five-line
12045// `let (de, para) = self.edge_pair(); return
12046// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
12047// ep.to_string() });` struct-literal against the local
12048// [`WitContract::edge_pair`] composite-projection accessor and the
12049// caller-side `&str` endpoint — the exact "same block re-inlined at
12050// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
12051// altitude the six peer `AplicacaoError` constructor families each
12052// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
12053// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
12054// becomes a caixa-build error, not a Cilium L7 policy-side path-match
12055// silent traffic drop far from the source caixa.lisp) now routes through
12056// one substrate primitive on the envelope.
12057//
12058// The ctor below folds the site onto one dispatch:
12059// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
12060// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
12061// on the same `(edge_pair, endpoint)` pair. The uniform three-field
12062// construction (`de, para` pair-destructure onto same-named fields +
12063// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
12064// body — rather than at the wire-up site. `#[must_use]` fires a compile
12065// warning at any future wire-up that mistakenly discards the constructed
12066// error.
12067//
12068// Every future consumer that wants to construct this variant outside
12069// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
12070// CR materializer's per-`:contratos` admission validator raising the
12071// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
12072// `feira validate --contratos` per-caixa admission verb re-running the
12073// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
12074// probing each declared `:endpoint` against the same shared
12075// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
12076// resolver rejecting a leading-slash-missing `:endpoint` against a
12077// cluster-local Cilium snapshot the M4 CR materializer projects) now
12078// reaches this variant through one call rather than re-inlining the
12079// five-line pair-destructure + struct-literal block in lockstep with
12080// the sole in-crate wire-up site.
12081impl AplicacaoError {
12082    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
12083    /// naming the offending edge `(de, para)` pair and the per-payload
12084    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
12085    /// endpoint.to_string() }` three-slot struct-literal onto one
12086    /// substrate primitive so every wire-up on this variant reads
12087    /// through one dispatch rather than the pre-lift five-line
12088    /// pair-destructure + struct-literal block. The `edge` pair threads
12089    /// verbatim from [`WitContract::edge_pair`] at the call site,
12090    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
12091    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
12092    /// paired two-slot and four-slot per-`:contratos :endpoint`
12093    /// envelopes on the same [`AplicacaoError`] type.
12094    #[must_use]
12095    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
12096        let (de, para) = edge;
12097        Self::ContratoEndpointNotAbsolute {
12098            de,
12099            para,
12100            endpoint: endpoint.to_string(),
12101        }
12102    }
12103
12104    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
12105    /// offending self-edge's owning `caixa` and its `:wit` world
12106    /// reference, projecting both slots through the [`WitContract`]'s
12107    /// own [`WitContract::source`] and [`WitContract::world_ref`]
12108    /// scalar accessors on the substrate primitive.
12109    ///
12110    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
12111    /// contract.world_ref().to_string() }` two-slot struct-literal onto
12112    /// one substrate primitive so every wire-up on this variant reads
12113    /// through one dispatch rather than the pre-lift four-line
12114    /// twin-`.to_string()` struct-literal block. The `contract` borrow
12115    /// threads verbatim from the caller-side `for c in
12116    /// self.contratos()` iteration at the sole in-crate wire-up site
12117    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
12118    /// per-`:contratos` `WitContract`-projection ctor discipline the
12119    /// peer [`AplicacaoError::empty_wit`] /
12120    /// [`AplicacaoError::contrato_endpoint_empty`] /
12121    /// [`AplicacaoError::contrato_subject_empty`] /
12122    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
12123    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
12124    /// envelope.
12125    ///
12126    /// The `caixa` slot is projected through [`WitContract::source`]
12127    /// rather than [`WitContract::destination`] to preserve byte-equal
12128    /// diagnostic ordering with the pre-lift open-coded body — a
12129    /// [`WitContract::is_self_loop`]-gated call site has
12130    /// `source() == destination()` by that predicate's own contract, so
12131    /// the two accessors are exchange-symmetric at this call site, but
12132    /// naming `source` at the ctor definition matches the pre-lift
12133    /// site's field selection and pins the discipline for any future
12134    /// consumer that constructs the variant against a not-yet-gated
12135    /// candidate contract (e.g. an M4
12136    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12137    /// webhook re-checking a per-`(:de, :para)` patched contract, a
12138    /// future `feira validate --contratos` per-caixa verb re-running
12139    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
12140    /// overlay resolver rejecting a self-edge introduced by a
12141    /// cluster-local `:contratos` override the M4 CR materializer
12142    /// projects).
12143    ///
12144    /// Peer of the sibling `WitContract`-projection ctors on the
12145    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
12146    /// same "one typed dispatch on the substrate primitive, projecting
12147    /// through the paired [`WitContract`] accessors, thin projections
12148    /// at each consumer" discipline extended here onto the last unlifted
12149    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
12150    /// inside [`AplicacaoSpec::validate_contratos`].
12151    #[must_use]
12152    pub fn contrato_self_loop(contract: &WitContract) -> Self {
12153        Self::ContratoSelfLoop {
12154            caixa: contract.source().to_string(),
12155            wit: contract.world_ref().to_string(),
12156        }
12157    }
12158
12159    /// Construct an [`AplicacaoError::ContratoDuplicate`] naming the
12160    /// offending duplicate edge's `(:de, :para, :wit)` triple and the
12161    /// per-payload `:target` byte-string, projecting the first three slots
12162    /// through the paired [`WitContract::edge_triple`] typed-accessor and
12163    /// the trailing `target:` slot through [`WitTarget::label`] on the
12164    /// substrate primitive.
12165    ///
12166    /// Folds the uniform `let (de, para, wit) = contract.edge_triple();
12167    /// Self::ContratoDuplicate { de, para, wit, target: target.label() }`
12168    /// six-line pair-destructure + struct-literal onto one substrate
12169    /// primitive so every wire-up on this variant reads through one
12170    /// dispatch rather than the pre-lift open-coded block inside the
12171    /// [`AplicacaoSpec::validate_contratos`] whole-edge dedup closure
12172    /// passed to [`crate::render::insert_first_seen`]. Peer of the sibling
12173    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
12174    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
12175    /// per-`:contratos` self-edge two-slot envelope) and the sibling
12176    /// [`AplicacaoError::empty_wit`] (projecting through
12177    /// [`WitContract::edge_pair`] on the sibling per-`:contratos` empty-
12178    /// `:wit` two-slot envelope) `WitContract`-projection ctors on the
12179    /// same [`AplicacaoError`] type — extended here onto the last unlifted
12180    /// four-slot `{ de: String, para: String, wit: String, target: String }`
12181    /// per-`:contratos` whole-edge-dedup envelope inside
12182    /// [`AplicacaoSpec::validate_contratos`], closing the paired
12183    /// duplicate-gate diagnostic constructor site the peer
12184    /// [`WitContract::edge_triple`] (5dbcfaf) lift's doc-block flagged as
12185    /// the last unlifted composite-projection wire-up.
12186    ///
12187    /// The `contract` borrow threads verbatim from the caller-side `for c
12188    /// in self.contratos()` iteration at the sole in-crate wire-up site
12189    /// [`AplicacaoSpec::validate_contratos`], and `target` threads
12190    /// verbatim from the paired `let target_view = c.target()?` local
12191    /// materialized upstream of the [`crate::render::insert_first_seen`]
12192    /// dedup dispatch — both project onto their respective substrate-
12193    /// primitive accessors ([`WitContract::edge_triple`] +
12194    /// [`WitTarget::label`]) inside the ctor body, matching the sibling
12195    /// [`AplicacaoError::contrato_self_loop`] `WitContract`-projection
12196    /// posture verbatim on the paired self-edge envelope.
12197    ///
12198    /// Every future consumer that wants to construct this variant outside
12199    /// [`AplicacaoSpec::validate_contratos`] — a deferred
12200    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12201    /// webhook re-checking a per-`(:de, :para, :wit, :target)`-patched
12202    /// candidate against a per-tenant `:contratos` overlay before the
12203    /// whole-edge dedup gate re-fires, a future `feira validate
12204    /// --contratos` per-caixa admission verb re-running the dedup check on
12205    /// demand, an M4 per-cluster contrato-cap resolver rejecting a
12206    /// cross-tenant duplicate-edge collision introduced by a fleet-local
12207    /// overlay the M4 CR materializer projects — now reaches this variant
12208    /// through one call rather than re-inlining the six-line pair-
12209    /// destructure + struct-literal block in lockstep with the existing
12210    /// wire-up.
12211    #[must_use]
12212    pub fn contrato_duplicate(contract: &WitContract, target: &WitTarget<'_>) -> Self {
12213        let (de, para, wit) = contract.edge_triple();
12214        Self::ContratoDuplicate {
12215            de,
12216            para,
12217            wit,
12218            target: target.label(),
12219        }
12220    }
12221
12222    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
12223    /// offending `:membros :caixa` and its `:versao` requirement under
12224    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
12225    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
12226    /// reason.into() }` three-slot struct-literal onto one substrate
12227    /// primitive so every wire-up on this variant reads through one
12228    /// dispatch, matching the peer
12229    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
12230    /// shape verbatim on the sibling `SupervisorError { caixa: String,
12231    /// versao: String, reason: String }` envelope's per-`:children :versao`
12232    /// axis. `reason` accepts both `&str` literals and `format!(…)`
12233    /// outputs through the `impl Into<String>` bound so the sole
12234    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
12235    /// requirement-cascade closure (routing the shared
12236    /// [`crate::render::require_valid_versao_requirement`]-delivered
12237    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
12238    /// transformation on the caller-side `reason` axis. The
12239    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
12240    /// routing the sole wire-up already threads through remains verbatim
12241    /// — the ctor's two `&str` parameters accept the two accessors'
12242    /// returns as-is with no re-allocation at the call site.
12243    #[must_use]
12244    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
12245        Self::MembroVersaoInvalid {
12246            caixa: caixa.to_string(),
12247            versao: versao.to_string(),
12248            reason: reason.into(),
12249        }
12250    }
12251
12252    /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
12253    /// the offending `:placement :clusters` entry.
12254    ///
12255    /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
12256    /// cluster.to_string() }` one-field struct-literal onto one substrate
12257    /// primitive so every wire-up on this variant reads through one
12258    /// dispatch rather than the pre-lift three-line open-coded
12259    /// struct-literal block. The `cluster` slot threads verbatim from the
12260    /// caller-side `for c in p.clusters()` iteration at the sole in-crate
12261    /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
12262    /// per-entry dedup closure passed to
12263    /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
12264    /// bracket accepts the free function pointer as-is.
12265    ///
12266    /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
12267    /// per-`:politicas <scalar>` single-slot ctor families
12268    /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
12269    /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
12270    /// `{ path: String }` at the peer per-gateway envelope,
12271    /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
12272    /// at the peer per-`:politicas` cap-scalar envelope) on the same
12273    /// [`AplicacaoError`] type — extends the "one typed dispatch per
12274    /// substrate primitive on every single-slot per-M3-slot envelope"
12275    /// discipline onto the last unlifted `{ cluster: String }` one-slot
12276    /// per-`:placement :clusters` dedup-envelope inside
12277    /// [`AplicacaoSpec::validate_placement_shape`].
12278    ///
12279    /// Every future consumer that wants to construct this variant outside
12280    /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
12281    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12282    /// webhook re-checking a `:placement :clusters` overlay against a
12283    /// per-tenant cluster-topology snapshot, a future `feira validate
12284    /// --placement` per-caixa admission verb re-running the dedup check
12285    /// on demand, an M4 per-cluster placement resolver rejecting a
12286    /// duplicate cluster-name entry introduced by a fleet-local overlay
12287    /// the M4 CR materializer projects — now reaches this variant through
12288    /// one call rather than re-inlining the three-line struct-literal.
12289    #[must_use]
12290    pub fn placement_cluster_duplicate(cluster: &str) -> Self {
12291        Self::PlacementClusterDuplicate {
12292            cluster: cluster.to_string(),
12293        }
12294    }
12295
12296    /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
12297    /// the offending `:placement :estrategia` scalar the empty `:clusters`
12298    /// list was declared against, projecting through the paired
12299    /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
12300    /// primitive.
12301    ///
12302    /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
12303    /// placement.estrategia() }` one-field struct-literal onto one
12304    /// substrate primitive so every wire-up on this variant reads through
12305    /// one dispatch rather than the pre-lift three-line open-coded
12306    /// `AplicacaoError::PlacementWithoutClusters { estrategia:
12307    /// p.estrategia() }` block inside
12308    /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
12309    /// projection posture as the sibling
12310    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
12311    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
12312    /// per-`:contratos` self-edge envelope) and the peer
12313    /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
12314    /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
12315    /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
12316    /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
12317    /// per-`:placement` empty-clusters envelope inside
12318    /// [`AplicacaoSpec::validate_placement`].
12319    ///
12320    /// `#[must_use]` and `const fn` alike: the ctor threads the paired
12321    /// [`Placement::estrategia`] `Copy`-scalar return through one
12322    /// zero-runtime-work construction — no allocation, no owned-string
12323    /// materialization — so the pre-lift `Copy`-pass-through property the
12324    /// open-coded `p.estrategia()` field expression carried survives
12325    /// verbatim through the substrate primitive. The sibling
12326    /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
12327    /// carries the paired `.to_string()`-owned-String allocation on the
12328    /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
12329    /// preserves the zero-alloc posture at the substrate-primitive
12330    /// dispatch, matching the peer
12331    /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
12332    /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
12333    /// per-`:politicas` cap-scalar envelopes.
12334    ///
12335    /// Every future consumer that wants to construct this variant outside
12336    /// [`AplicacaoSpec::validate_placement`] — a deferred
12337    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12338    /// webhook re-checking a `:placement :clusters` overlay against a
12339    /// per-tenant cluster-topology snapshot when the overlay resolves to
12340    /// an empty list, a future `feira validate --placement` per-caixa
12341    /// admission verb re-running the empty-clusters check on demand, an
12342    /// M4 per-cluster placement resolver rejecting an empty cluster pool
12343    /// after a fleet-local overlay strips every declared cluster — now
12344    /// reaches this variant through one call rather than re-inlining the
12345    /// three-line struct-literal in lockstep with the one in-crate
12346    /// wire-up site.
12347    #[must_use]
12348    pub const fn placement_without_clusters(placement: &Placement) -> Self {
12349        Self::PlacementWithoutClusters {
12350            estrategia: placement.estrategia(),
12351        }
12352    }
12353
12354    /// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
12355    /// offending `:placement :estrategia` scalar and the declared-but-
12356    /// inert `:shard-key` value the non-`Sharded` arm refused, projecting
12357    /// the strategy through the paired [`Placement::estrategia`]
12358    /// `Copy`-scalar accessor on the substrate primitive.
12359    ///
12360    /// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
12361    /// placement.estrategia(), shard_key: shard_key.to_string() }`
12362    /// two-slot struct-literal onto one substrate primitive so every
12363    /// wire-up on this variant reads through one dispatch rather than
12364    /// the pre-lift four-line open-coded struct-literal block inside
12365    /// [`AplicacaoSpec::validate_placement`]'s
12366    /// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
12367    /// arm. Same substrate-primitive-projection posture as the sibling
12368    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
12369    /// projecting through [`Placement::estrategia`] on the peer
12370    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
12371    /// empty-clusters envelope) and the peer
12372    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
12373    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
12374    /// the paired per-`:contratos` self-edge envelope) ctors — extended
12375    /// here onto the last unlifted `{ estrategia: PlacementStrategy,
12376    /// shard_key: String }` two-slot per-`:placement :shard-key`
12377    /// declared-but-inert envelope on the sibling non-`Sharded`-arm
12378    /// partition.
12379    ///
12380    /// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
12381    /// `&str` from the sole in-crate wire-up site (narrowed from
12382    /// `Option<&str>` via [`Placement::shard_key`]) and any future
12383    /// `&String` deref from a downstream consumer that reaches for the
12384    /// slot through the paired accessor, materializing the owned
12385    /// [`String`] via one `.to_string()` at the substrate primitive so
12386    /// no per-arm `.to_string()` allocation lives at the caller. The
12387    /// `estrategia` slot threads through [`Placement::estrategia`]'s
12388    /// `Copy`-scalar return rather than accepting a bare
12389    /// [`PlacementStrategy`] argument, matching the peer
12390    /// [`AplicacaoError::placement_without_clusters`] discipline —
12391    /// carrying the [`Placement`] borrow through one accessor call at
12392    /// the substrate primitive is strictly stronger than accepting the
12393    /// scalar as a separate argument (a future caller that constructs
12394    /// the error against a candidate [`Placement`] whose
12395    /// [`Placement::estrategia`] value the caller re-derives from
12396    /// another source can silently disagree with the storage the
12397    /// [`Placement`] carries; the accessor-projected primitive cannot).
12398    ///
12399    /// Peer of the sibling per-`:placement` single-slot / two-slot ctor
12400    /// families on the same [`AplicacaoError`] type — same "one typed
12401    /// dispatch on the substrate primitive, projecting through the
12402    /// paired [`Placement`] accessors, thin projections at each
12403    /// consumer" discipline extended here onto the last unlifted
12404    /// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
12405    /// [`AplicacaoSpec::validate_placement`].
12406    ///
12407    /// Every future consumer that wants to construct this variant
12408    /// outside [`AplicacaoSpec::validate_placement`] — a deferred
12409    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12410    /// webhook re-checking a `:placement (:estrategia Replicated
12411    /// :shard-key …)` overlay against a per-tenant cluster-topology
12412    /// snapshot, a future `feira validate --placement` per-caixa
12413    /// admission verb re-running the non-`Sharded`-arm refusal on
12414    /// demand, an M4 per-cluster placement resolver rejecting a
12415    /// declared-but-inert `:shard-key` introduced by a fleet-local
12416    /// overlay the M4 CR materializer projects — now reaches this
12417    /// variant through one call rather than re-inlining the four-line
12418    /// struct-literal in lockstep with the one in-crate wire-up site.
12419    #[must_use]
12420    pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
12421        Self::ShardKeyOnNonSharded {
12422            estrategia: placement.estrategia(),
12423            shard_key: shard_key.to_string(),
12424        }
12425    }
12426
12427    /// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
12428    /// offending `:entrada :para` value the membership lookup against the
12429    /// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
12430    /// slot through the paired [`Entrada::destination`] byte-string
12431    /// accessor on the substrate primitive.
12432    ///
12433    /// Folds the uniform `Self::EntradaMemberMissing { para:
12434    /// entrada.destination().to_string() }` one-field struct-literal onto
12435    /// one substrate primitive so every wire-up on this variant reads
12436    /// through one dispatch rather than the pre-lift three-line
12437    /// open-coded `AplicacaoError::EntradaMemberMissing { para:
12438    /// e.destination().to_string() }` block inside
12439    /// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
12440    /// projection posture as the sibling
12441    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
12442    /// projecting through [`Placement::estrategia`] on the peer
12443    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
12444    /// empty-clusters envelope) and the sibling
12445    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
12446    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
12447    /// the paired per-`:contratos` self-edge envelope) ctors — extended
12448    /// here onto the last unlifted `{ para: String }` one-slot
12449    /// per-`:entrada :para` phantom-reference envelope on the sibling
12450    /// per-`:entrada` slot.
12451    ///
12452    /// The `entrada: &Entrada` parameter threads verbatim from the
12453    /// caller-side `if let Some(e) = self.entrada() { … }` traversal at
12454    /// the sole in-crate wire-up site
12455    /// [`AplicacaoSpec::validate_entrada`], matching the sibling
12456    /// per-`:entrada` byte-string reads that already route through
12457    /// [`Entrada::destination`] one accessor call earlier in the same
12458    /// gate (`validate_entrada_para(e.destination())?;` +
12459    /// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
12460    /// borrow through one accessor call at the substrate primitive is
12461    /// strictly stronger than accepting the bare `&str` as a separate
12462    /// argument — a future consumer that constructs the error against a
12463    /// candidate [`Entrada`] whose [`Entrada::destination`] value the
12464    /// caller re-derives from another source (a raw `e.para` field
12465    /// access that skipped the accessor, a stale snapshot of the
12466    /// pre-normalization storage) can silently disagree with the
12467    /// storage the [`Entrada`] carries; the accessor-projected primitive
12468    /// cannot. Matches the peer
12469    /// [`AplicacaoError::placement_without_clusters`] and
12470    /// [`AplicacaoError::shard_key_on_non_sharded`]
12471    /// [`Placement`]-borrow-projection discipline on the sibling
12472    /// per-`:placement` envelope, and matches the peer
12473    /// [`AplicacaoError::contrato_self_loop`] and
12474    /// [`AplicacaoError::contrato_endpoint_not_absolute`]
12475    /// [`WitContract`]-borrow-projection discipline on the sibling
12476    /// per-`:contratos` envelope.
12477    ///
12478    /// Every future consumer that wants to construct this variant
12479    /// outside [`AplicacaoSpec::validate_entrada`] — a deferred
12480    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12481    /// webhook re-checking a `:entrada :para` overlay against a
12482    /// per-tenant `:membros` snapshot after a fleet-local overlay
12483    /// renames a member, a future `feira validate --entrada` per-caixa
12484    /// admission verb re-running the phantom-reference lookup on
12485    /// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
12486    /// `:entrada :para` whose target Servico was stripped from the
12487    /// cluster-local `:membros` overlay, a future authoring-surface
12488    /// widening the field into a `(String, Vec<Suggestion>)` pair
12489    /// carrying a "did-you-mean-<nearest-member>" hint — now reaches
12490    /// this variant through one call rather than re-inlining the
12491    /// three-line struct-literal in lockstep with the one in-crate
12492    /// wire-up site.
12493    #[must_use]
12494    pub fn entrada_member_missing(entrada: &Entrada) -> Self {
12495        Self::EntradaMemberMissing {
12496            para: entrada.destination().to_string(),
12497        }
12498    }
12499
12500    /// Construct an [`AplicacaoError::ContratoCycle`] naming the
12501    /// synchronous-`:contratos` cycle path the DFS-with-three-coloring
12502    /// sync-only-subgraph gate at
12503    /// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
12504    /// gray-arm's back-edge target through the parent chain, folding the
12505    /// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
12506    /// onto one substrate primitive so every wire-up on this variant
12507    /// reads through one dispatch rather than the pre-lift open-coded
12508    /// `AplicacaoError::ContratoCycle { cycle }` block at the sole
12509    /// in-crate wire-up site inside
12510    /// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
12511    /// return. Same substrate-primitive-projection posture as the
12512    /// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
12513    /// projecting through [`Entrada::destination`] on the peer `{ para:
12514    /// String }` one-slot per-`:entrada :para` phantom-reference
12515    /// envelope) and [`AplicacaoError::placement_without_clusters`]
12516    /// (b0d24ba, projecting through [`Placement::estrategia`] on the
12517    /// sibling `{ estrategia: PlacementStrategy }` one-slot
12518    /// per-`:placement` empty-clusters envelope) ctors — extended here
12519    /// onto the last unlifted `{ cycle: Vec<String> }` one-slot
12520    /// per-`:contratos` cross-edge sync-cycle envelope on the same
12521    /// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
12522    /// struct-literal wire-up under
12523    /// [`AplicacaoSpec::detect_sync_cycles`].
12524    ///
12525    /// The `cycle: Vec<String>` parameter threads verbatim from the
12526    /// caller-side DFS traversal's reconstructed cycle path (built up by
12527    /// walking `parent` from the gray-back-edge's source node back to
12528    /// its target, reversing, then appending the target once more so the
12529    /// first and last elements coincide by construction and the
12530    /// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
12531    /// `cycle.join(" → ")` formatter reads as a closed loop), matching
12532    /// the pre-lift open-coded body's field selection exactly. Taking
12533    /// the owned [`Vec<String>`] rather than a borrowed slice + collect
12534    /// on the ctor side keeps the pre-lift wire-up byte-identical (the
12535    /// caller already owns the reconstructed [`Vec<String>`] at the
12536    /// gray-arm return, so no per-arm re-allocation lands on the ctor
12537    /// path).
12538    ///
12539    /// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
12540    /// families on the same [`AplicacaoError`] type — same "one typed
12541    /// dispatch on the substrate primitive, thin projections at each
12542    /// consumer" discipline extended here onto the last unlifted
12543    /// per-`:contratos` cross-edge cycle envelope inside
12544    /// [`AplicacaoSpec::detect_sync_cycles`].
12545    ///
12546    /// Every future consumer that wants to construct this variant
12547    /// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
12548    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12549    /// webhook re-checking a per-tenant `:contratos` overlay's
12550    /// sync-cycle invariant after a fleet-local overlay adds or removes
12551    /// a synchronous edge, a future `feira validate --contratos`
12552    /// per-caixa admission verb re-running the cross-edge cycle detector
12553    /// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
12554    /// #3 acknowledges (whose per-edge patch mutates one `:contratos`
12555    /// entry and needs to re-probe *just* the cycle invariant against
12556    /// the post-patch adjacency), a future authoring-surface widening
12557    /// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
12558    /// the per-hop WIT shape for a richer "break here" hint — now
12559    /// reaches this variant through one call rather than re-inlining the
12560    /// open-coded struct-literal in lockstep with the one in-crate
12561    /// wire-up site.
12562    #[must_use]
12563    pub fn contrato_cycle(cycle: Vec<String>) -> Self {
12564        Self::ContratoCycle { cycle }
12565    }
12566
12567    /// Construct an [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
12568    /// naming the offending `:politicas :circuit-breaker :window` and
12569    /// the paired `:politicas :timeout` scalars under the first-firing
12570    /// cross-axis-violation gate at
12571    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
12572    /// `window` slot through the [`CircuitBreaker::window`] scalar
12573    /// accessor on the substrate primitive.
12574    ///
12575    /// Folds the uniform `{ window: cb.window(), timeout: t }`
12576    /// two-slot `Copy`-`Duration` struct-literal onto one substrate
12577    /// primitive so every wire-up on this variant reads through one
12578    /// dispatch rather than the pre-lift four-line struct-literal
12579    /// block. The `cb` borrow threads verbatim from the caller-side
12580    /// `if let (Some(t), Some(cb)) = (self.timeout(),
12581    /// self.circuit_breaker())` pair-destructure at the sole in-crate
12582    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
12583    /// window-below-timeout arm; `timeout` threads verbatim from the
12584    /// paired [`MeshPolicy::timeout`] accessor return already
12585    /// destructured out of the same `if let` pair. `const fn`
12586    /// preserves the pre-lift `Copy`-pass-through's zero-runtime-work
12587    /// property verbatim (both fields are [`Duration`], the
12588    /// [`CircuitBreaker::window`] accessor is itself `const fn`, and
12589    /// no `.to_string()` / `.into()` allocation lands on the ctor
12590    /// path).
12591    ///
12592    /// The `window` slot is projected through [`CircuitBreaker::window`]
12593    /// (not spelled out as a bare `Duration` parameter) so a future
12594    /// widening of the `:circuit-breaker :window` axis — a
12595    /// per-`:contratos`-edge `:circuit-breaker :window` override the
12596    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a promotion of
12597    /// the plain [`Duration`] window to a richer per-status-class
12598    /// window tuple once Envoy's `outlier_detection.interval` peers
12599    /// come into scope — reaches the diagnostic through one accessor
12600    /// swap rather than every wire-up in lockstep, matching the peer
12601    /// substrate-primitive-projection posture of
12602    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
12603    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
12604    /// the sibling `{ caixa: String, wit: String }` two-slot
12605    /// per-`:contratos` self-edge envelope),
12606    /// [`AplicacaoError::entrada_member_missing`] (deeae5c, projecting
12607    /// through [`Entrada::destination`] on the sibling `{ para: String }`
12608    /// one-slot per-`:entrada :para` phantom-reference envelope), and
12609    /// [`AplicacaoError::shard_key_on_non_sharded`] (14bafca, projecting
12610    /// through [`Placement::estrategia`] on the sibling `{ estrategia:
12611    /// PlacementStrategy, shard_key: String }` two-slot per-`:placement`
12612    /// envelope) ctors carry on the sibling `:contratos` / `:entrada`
12613    /// / `:placement` envelopes.
12614    ///
12615    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
12616    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
12617    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
12618    /// [`MeshPolicy::validate`] gate — extended here onto the
12619    /// first-firing cross-axis compound variant, whose multi-slot
12620    /// `{ window: Duration, timeout: Duration }` shape does not fit
12621    /// that macro's one-`Copy`-scalar-per-variant arity. The three
12622    /// remaining cross-axis variants
12623    /// ([`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] on
12624    /// the four-slot `{ rate, rl_window, max_failures, cb_window }`
12625    /// envelope, [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
12626    /// on the two-slot `{ retries, max_failures }` envelope, and
12627    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
12628    /// two-slot `{ retries, rate }` envelope) each carry a distinct
12629    /// substrate-primitive-projection shape and are folded on their
12630    /// own axis by their own per-variant ctors as those wire-ups are
12631    /// lifted.
12632    ///
12633    /// Every future consumer that wants to construct this variant
12634    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
12635    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12636    /// webhook re-checking a per-tenant `:politicas` overlay's
12637    /// window-vs-timeout cross-axis invariant after a cluster-local
12638    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
12639    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
12640    /// future per-`:contratos`-edge `:politicas` override the M4 CR
12641    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
12642    /// projecting a per-tenant per-axis ceiling into the same
12643    /// diagnostic shape — now reaches this variant through one call
12644    /// rather than re-inlining the open-coded struct-literal in
12645    /// lockstep with the one in-crate wire-up site.
12646    #[must_use]
12647    pub const fn policy_breaker_window_below_timeout(
12648        cb: &CircuitBreaker,
12649        timeout: Duration,
12650    ) -> Self {
12651        Self::PolicyBreakerWindowBelowTimeout {
12652            window: cb.window(),
12653            timeout,
12654        }
12655    }
12656
12657    /// Construct an [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
12658    /// naming the `(:politicas :rate-limit, :politicas :circuit-breaker)`
12659    /// cross-axis pair whose token-bucket window structurally starves the
12660    /// breaker so `:max-failures` cannot be reached inside `:circuit-breaker
12661    /// :window`.
12662    ///
12663    /// Folds the uniform `{ rate: rl.rate(), rl_window: rl.window(),
12664    /// max_failures: cb.max_failures(), cb_window: cb.window() }`
12665    /// four-slot `Copy`-`(u32 | Duration)` struct-literal onto one substrate
12666    /// primitive so every wire-up on this variant reads through one dispatch
12667    /// rather than the pre-lift six-line struct-literal block. Both `rl` and
12668    /// `cb` borrows thread verbatim from the caller-side `if let (Some(rl),
12669    /// Some(cb)) = (self.rate_limit(), self.circuit_breaker())`
12670    /// pair-destructure at the sole in-crate wire-up site inside
12671    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-limit
12672    /// arm. `const fn` preserves the pre-lift `Copy`-pass-through's
12673    /// zero-runtime-work property verbatim (all four fields are `u32` /
12674    /// [`Duration`], every projected accessor is itself `const fn`, and no
12675    /// `.to_string()` / `.into()` allocation lands on the ctor path).
12676    ///
12677    /// Every slot is projected through its paired substrate-primitive
12678    /// accessor ([`RateLimit::rate`], [`RateLimit::window`],
12679    /// [`CircuitBreaker::max_failures`], [`CircuitBreaker::window`]) rather
12680    /// than spelled out as bare `u32` / [`Duration`] parameters so a future
12681    /// widening of either axis — a per-`:contratos`-edge `:rate-limit` or
12682    /// `:circuit-breaker` override the MESH-COMPOSITION §III.2 #3 roadmap
12683    /// acknowledges, a promotion of the plain scalar rate to a richer
12684    /// per-status-class token bucket once Envoy's per-descriptor
12685    /// `local_rate_limit` peers come into scope — reaches the diagnostic
12686    /// through one accessor swap rather than every wire-up in lockstep.
12687    /// Matches the peer substrate-primitive-projection posture of
12688    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
12689    /// projecting through [`CircuitBreaker::window`] on the sibling
12690    /// two-slot `{ window, timeout }` cross-axis
12691    /// `(:timeout, :circuit-breaker)` envelope) on the sibling
12692    /// first-firing cross-axis compound variant.
12693    ///
12694    /// Second cross-axis Policy* variant folded onto its own per-variant
12695    /// substrate primitive — extending the peer
12696    /// [`AplicacaoError::policy_breaker_window_below_timeout`] discipline
12697    /// onto the second-firing cross-axis compound variant, whose four-slot
12698    /// `{ rate, rl_window, max_failures, cb_window }` shape does not fit
12699    /// the sibling two-slot ctor's arity. The two remaining cross-axis
12700    /// variants ([`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
12701    /// on the two-slot `{ retries, max_failures }` envelope and
12702    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
12703    /// two-slot `{ retries, rate }` envelope) each carry a distinct
12704    /// substrate-primitive-projection shape and are folded on their own
12705    /// axis by their own per-variant ctors as those wire-ups are lifted.
12706    ///
12707    /// Every future consumer that wants to construct this variant outside
12708    /// [`MeshPolicy::first_cross_axis_violation`] — a deferred
12709    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12710    /// webhook re-checking a per-tenant `:politicas` overlay's
12711    /// starve-under-rate-limit cross-axis invariant after a cluster-local
12712    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
12713    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
12714    /// future per-`:contratos`-edge `:politicas` override the M4 CR
12715    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
12716    /// projecting a per-tenant per-axis ceiling into the same diagnostic
12717    /// shape — now reaches this variant through one call rather than
12718    /// re-inlining the open-coded struct-literal in lockstep with the one
12719    /// in-crate wire-up site.
12720    #[must_use]
12721    pub const fn policy_breaker_cannot_trip_under_rate_limit(
12722        rl: &RateLimit,
12723        cb: &CircuitBreaker,
12724    ) -> Self {
12725        Self::PolicyBreakerCannotTripUnderRateLimit {
12726            rate: rl.rate(),
12727            rl_window: rl.window(),
12728            max_failures: cb.max_failures(),
12729            cb_window: cb.window(),
12730        }
12731    }
12732
12733    /// Construct an
12734    /// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
12735    /// naming the offending `:politicas :retries` and the paired
12736    /// `:politicas :circuit-breaker :max-failures` scalars under the
12737    /// third-firing cross-axis-violation gate at
12738    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
12739    /// `max_failures` slot through the [`CircuitBreaker::max_failures`]
12740    /// scalar accessor on the substrate primitive.
12741    ///
12742    /// Folds the uniform `{ retries, max_failures: cb.max_failures() }`
12743    /// two-slot `Copy`-`u32` struct-literal onto one substrate
12744    /// primitive so every wire-up on this variant reads through one
12745    /// dispatch rather than the pre-lift four-line struct-literal
12746    /// block. The `cb` borrow threads verbatim from the caller-side
12747    /// `if let (Some(retries), Some(cb)) = (self.retries(),
12748    /// self.circuit_breaker())` pair-destructure at the sole in-crate
12749    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
12750    /// retries-saturate arm; `retries` threads verbatim from the paired
12751    /// [`MeshPolicy::retries`] accessor return already destructured out
12752    /// of the same `if let` pair. `const fn` preserves the pre-lift
12753    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
12754    /// fields are `u32`, the [`CircuitBreaker::max_failures`] accessor
12755    /// is itself `const fn`, and no `.to_string()` / `.into()`
12756    /// allocation lands on the ctor path).
12757    ///
12758    /// The `max_failures` slot is projected through
12759    /// [`CircuitBreaker::max_failures`] (not spelled out as a bare
12760    /// `u32` parameter) so a future widening of the
12761    /// `:circuit-breaker :max-failures` axis — a
12762    /// per-`:contratos`-edge `:circuit-breaker :max-failures` override
12763    /// the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-tenant
12764    /// `:max-failures` ceiling the M4 per-cluster `:politicas`-cap
12765    /// resolver projects, a promotion of the plain `u32` count to a
12766    /// richer per-status-class trip counter once Envoy's
12767    /// `outlier_detection.consecutive_5xx` peers come into scope —
12768    /// reaches the diagnostic through one accessor swap rather than
12769    /// every wire-up in lockstep, matching the peer
12770    /// substrate-primitive-projection posture of
12771    /// [`AplicacaoError::policy_breaker_window_below_timeout`]
12772    /// (9b30c07, projecting through [`CircuitBreaker::window`] on the
12773    /// sibling two-slot `{ window, timeout }` first cross-axis
12774    /// envelope) and
12775    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
12776    /// (6bb4e46, projecting through [`RateLimit::rate`] /
12777    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
12778    /// [`CircuitBreaker::window`] on the sibling four-slot second
12779    /// cross-axis envelope). `retries` remains a bare `u32` parameter,
12780    /// matching the sibling first-arm ctor's bare `timeout: Duration`
12781    /// parameter discipline: [`MeshPolicy::retries`] returns
12782    /// `Option<u32>` and the caller-side `if let` already destructures
12783    /// the inner `u32` out, so the ctor takes the destructured scalar
12784    /// verbatim rather than re-wrapping it into an accessor call.
12785    ///
12786    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
12787    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
12788    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
12789    /// [`MeshPolicy::validate`] gate — extended here onto the
12790    /// third-firing cross-axis compound variant, whose multi-slot
12791    /// `{ retries: u32, max_failures: u32 }` shape does not fit that
12792    /// macro's one-`Copy`-scalar-per-variant arity. The one remaining
12793    /// cross-axis variant
12794    /// ([`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
12795    /// two-slot `{ retries, rate }` envelope) carries a distinct
12796    /// substrate-primitive-projection shape (projecting through
12797    /// [`RateLimit::rate`] rather than
12798    /// [`CircuitBreaker::max_failures`]) and is folded on its own axis
12799    /// by its own per-variant ctor as that wire-up is lifted in a
12800    /// follow-up run.
12801    ///
12802    /// Every future consumer that wants to construct this variant
12803    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
12804    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12805    /// webhook re-checking a per-tenant `:politicas` overlay's
12806    /// retries-vs-max-failures cross-axis invariant after a
12807    /// cluster-local `:politicas` override the MESH-COMPOSITION §III.2
12808    /// #3 roadmap acknowledges resolves an *effective* per-edge
12809    /// [`MeshPolicy`], a future per-`:contratos`-edge `:politicas`
12810    /// override the M4 CR resolver projects, an M4 per-cluster
12811    /// `:politicas`-cap resolver projecting a per-tenant per-axis
12812    /// ceiling into the same diagnostic shape — now reaches this
12813    /// variant through one call rather than re-inlining the open-coded
12814    /// struct-literal in lockstep with the one in-crate wire-up site.
12815    #[must_use]
12816    pub const fn policy_breaker_trips_before_retries_exhausted(
12817        retries: u32,
12818        cb: &CircuitBreaker,
12819    ) -> Self {
12820        Self::PolicyBreakerTripsBeforeRetriesExhausted {
12821            retries,
12822            max_failures: cb.max_failures(),
12823        }
12824    }
12825
12826    /// Construct an
12827    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] naming
12828    /// the offending `:politicas :retries` and the paired `:politicas
12829    /// :rate-limit` `:rate` scalars under the fourth-firing (and last-
12830    /// remaining) cross-axis-violation gate at
12831    /// [`MeshPolicy::first_cross_axis_violation`], projecting the `rate`
12832    /// slot through the [`RateLimit::rate`] scalar accessor on the
12833    /// substrate primitive.
12834    ///
12835    /// Folds the uniform `{ retries, rate: rl.rate() }` two-slot
12836    /// `Copy`-`u32` struct-literal onto one substrate primitive so every
12837    /// wire-up on this variant reads through one dispatch rather than
12838    /// the pre-lift four-line struct-literal block. The `rl` borrow
12839    /// threads verbatim from the caller-side `if let (Some(retries),
12840    /// Some(rl)) = (self.retries(), self.rate_limit())` pair-destructure
12841    /// at the sole in-crate wire-up site inside
12842    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
12843    /// limit arm; `retries` threads verbatim from the paired
12844    /// [`MeshPolicy::retries`] accessor return already destructured out
12845    /// of the same `if let` pair. `const fn` preserves the pre-lift
12846    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
12847    /// fields are `u32`, the [`RateLimit::rate`] accessor is itself
12848    /// `const fn`, and no `.to_string()` / `.into()` allocation lands on
12849    /// the ctor path).
12850    ///
12851    /// The `rate` slot is projected through [`RateLimit::rate`] (not
12852    /// spelled out as a bare `u32` parameter) so a future widening of
12853    /// the `:rate-limit` `:rate` axis — a per-`:contratos`-edge
12854    /// `:rate-limit` `:rate` override the MESH-COMPOSITION §III.2 #3
12855    /// roadmap acknowledges, a per-tenant `:rate` ceiling the M4
12856    /// per-cluster `:politicas`-cap resolver projects, a promotion of
12857    /// the plain `u32` token capacity to a richer
12858    /// `{max_tokens, tokens_per_fill}` tuple once Envoy's
12859    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
12860    /// axis comes into scope — reaches the diagnostic through one
12861    /// accessor swap rather than every wire-up in lockstep, matching
12862    /// the peer substrate-primitive-projection posture of
12863    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
12864    /// projecting through [`CircuitBreaker::window`] on the sibling
12865    /// two-slot `{ window, timeout }` first cross-axis envelope),
12866    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
12867    /// (6bb4e46, projecting through [`RateLimit::rate`] /
12868    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
12869    /// [`CircuitBreaker::window`] on the sibling four-slot second
12870    /// cross-axis envelope), and
12871    /// [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
12872    /// (f54c539, projecting through [`CircuitBreaker::max_failures`] on
12873    /// the sibling two-slot `{ retries, max_failures }` third cross-axis
12874    /// envelope). `retries` remains a bare `u32` parameter, matching
12875    /// the sibling third-arm ctor's bare `retries: u32` parameter
12876    /// discipline: [`MeshPolicy::retries`] returns `Option<u32>` and the
12877    /// caller-side `if let` already destructures the inner `u32` out, so
12878    /// the ctor takes the destructured scalar verbatim rather than
12879    /// re-wrapping it into an accessor call.
12880    ///
12881    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
12882    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
12883    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
12884    /// [`MeshPolicy::validate`] gate — extended here onto the
12885    /// fourth-firing (and final) cross-axis compound variant, whose
12886    /// multi-slot `{ retries: u32, rate: u32 }` shape does not fit that
12887    /// macro's one-`Copy`-scalar-per-variant arity. After this lift all
12888    /// four cross-axis [`MeshPolicy::first_cross_axis_violation`] arms
12889    /// read through one substrate-primitive ctor dispatch each; the
12890    /// per-envelope compound cross-axis Policy* family closes on this
12891    /// variant.
12892    ///
12893    /// Every future consumer that wants to construct this variant
12894    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
12895    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
12896    /// webhook re-checking a per-tenant `:politicas` overlay's
12897    /// retries-vs-rate cross-axis invariant after a cluster-local
12898    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
12899    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
12900    /// future per-`:contratos`-edge `:politicas` override the M4 CR
12901    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
12902    /// projecting a per-tenant per-axis ceiling into the same diagnostic
12903    /// shape — now reaches this variant through one call rather than
12904    /// re-inlining the open-coded struct-literal in lockstep with the
12905    /// one in-crate wire-up site.
12906    #[must_use]
12907    pub const fn policy_rate_limit_cannot_admit_retry_burst(retries: u32, rl: &RateLimit) -> Self {
12908        Self::PolicyRateLimitCannotAdmitRetryBurst {
12909            retries,
12910            rate: rl.rate(),
12911        }
12912    }
12913
12914    /// Construct an [`AplicacaoError::ContratoCaixaInvalid`] naming the
12915    /// offending `:contratos <slot>` (`:de` / `:para`) and the value
12916    /// that broke the shared DNS-1123-label floor under the given
12917    /// `reason`. Folds the uniform `Self::ContratoCaixaInvalid { slot,
12918    /// caixa: caixa.to_string(), reason: reason.into() }` three-slot
12919    /// struct-literal onto one substrate primitive so every wire-up on
12920    /// this variant reads through one dispatch rather than the pre-lift
12921    /// six-line struct-literal block inside
12922    /// [`validate_contrato_caixa`]'s
12923    /// [`crate::render::require_valid_dns_1123_label`]
12924    /// `|reason| …` closure.
12925    ///
12926    /// Sibling of the per-axis [`aplicacao_field_reason_ctors!`]
12927    /// (981060b) macro-generated ctor family
12928    /// ([`AplicacaoError::membro_caixa_invalid`],
12929    /// [`AplicacaoError::entrada_para_invalid`],
12930    /// [`AplicacaoError::entrada_host_invalid`],
12931    /// [`AplicacaoError::entrada_path_invalid`],
12932    /// [`AplicacaoError::placement_cluster_invalid`],
12933    /// [`AplicacaoError::placement_affinity_invalid`],
12934    /// [`AplicacaoError::shard_key_invalid`]) — extends the "one typed
12935    /// dispatch per substrate primitive on every `{ <field>: String,
12936    /// reason: String }` per-axis parser-shaped envelope" discipline
12937    /// onto the sole unlifted three-slot `{ slot: &'static str, caixa:
12938    /// String, reason: String }` sibling whose extra `slot: &'static
12939    /// str` axis-tag distinguishes the two-arm `:de` / `:para` cascade
12940    /// on the per-`:contratos`-edge value axis and so does not fit the
12941    /// two-slot macro's arity.
12942    ///
12943    /// `slot` carries the kebab-case `:de` / `:para` tag verbatim
12944    /// (`&'static str` is `Copy`, no allocation), matching the caller-
12945    /// side [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
12946    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
12947    /// sole in-crate wire-up threads through. `reason: impl
12948    /// Into<String>` accepts both `&str` literals and the shared
12949    /// [`crate::render::require_valid_dns_1123_label`]-delivered
12950    /// owned-`String` return verbatim so the closure picks the ctor up
12951    /// without a per-arm wrapper transformation, matching the peer
12952    /// [`aplicacao_field_reason_ctors!`] family's `reason: impl
12953    /// Into<String>` bound. `#[must_use]` fires a compile warning at
12954    /// any wire-up that mistakenly discards the constructed error
12955    /// rather than routing it through `return Err(…)` / `.map_err(…)`
12956    /// / a closure return.
12957    ///
12958    /// Every future consumer that wants to construct this variant
12959    /// outside the current in-crate wire-up (the deferred
12960    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
12961    /// per-`:contratos`-edge admission validator projecting the same
12962    /// diagnostic through the caller-facing `slot: &'static str` tag,
12963    /// a future `feira validate --contratos` per-caixa admission verb,
12964    /// an M4 per-`:contratos`-edge pre-emitter running the same
12965    /// DNS-1123-label floor against a caller-supplied `:de` / `:para`
12966    /// pair before hitting the apiserver-side selector, an M4
12967    /// per-cluster contrato-cap resolver rejecting a cross-tenant
12968    /// selector projection into the same diagnostic shape) — now
12969    /// reaches this variant through one call rather than re-inlining
12970    /// the six-line struct-literal block in lockstep with the one
12971    /// in-crate wire-up site.
12972    #[must_use]
12973    pub fn contrato_caixa_invalid(
12974        slot: &'static str,
12975        caixa: &str,
12976        reason: impl Into<String>,
12977    ) -> Self {
12978        Self::ContratoCaixaInvalid {
12979            slot,
12980            caixa: caixa.to_string(),
12981            reason: reason.into(),
12982        }
12983    }
12984
12985    /// Construct an [`AplicacaoError::ContratoCaixaEmpty`] naming the
12986    /// offending `:contratos <slot>` (`:de` / `:para`) at which the
12987    /// caixa-reference value is the empty string. Folds the uniform
12988    /// `Self::ContratoCaixaEmpty { slot }` one-slot struct-literal onto
12989    /// one substrate primitive so the sole in-crate closure passed to
12990    /// [`crate::render::require_valid_dns_1123_label`] at
12991    /// [`validate_contrato_caixa`] on this variant reads through one
12992    /// dispatch rather than the pre-lift open-coded block. The `slot`
12993    /// label threads verbatim from the caller-side
12994    /// [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
12995    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
12996    /// wire-up feeds through [`validate_contrato_caixa`]'s
12997    /// `slot: &'static str` parameter.
12998    ///
12999    /// Sibling of the paired three-slot [`Self::contrato_caixa_invalid`]
13000    /// substrate primitive on the same
13001    /// [`crate::render::require_valid_dns_1123_label`] two-closure
13002    /// cascade — the empty-arm and invalid-arm now both reach the
13003    /// `AplicacaoError` envelope through one substrate primitive per
13004    /// typed variant, closing the pair. Same shape discipline as the
13005    /// peer [`crate::behavior::BehaviorError::empty_path`] one-slot
13006    /// `{ slot: &'static str }` sibling on the `BehaviorError`
13007    /// envelope's four-arm sandboxed-lisp-path cascade
13008    /// ([`crate::render::require_sandboxed_lisp_path`]) — extended here
13009    /// onto the sibling `AplicacaoError` envelope's two-arm
13010    /// DNS-1123-label cascade at the `:contratos <slot>` per-edge axis.
13011    ///
13012    /// `slot` stays `&'static str` (not `&str`) — every `:contratos
13013    /// <slot>` tag comes from the [`crate::render::CONTRATO_AUTHOR_KEY_*`]
13014    /// `const` roster carrying program-lifetime storage, matching the
13015    /// enum-field type and the [`validate_contrato_caixa`] wire-up's
13016    /// per-axis dispatch. A runtime-borrowed `&str` would silently
13017    /// downgrade the label lifetime and let a caller stash a
13018    /// non-`'static` borrow into the returned error. `#[must_use]` fires
13019    /// a compile warning at any wire-up that mistakenly discards the
13020    /// constructed error rather than routing it through `return Err(…)`
13021    /// / `.map_err(…)` / a closure return. `pub const fn` matches the
13022    /// peer per-envelope one-slot `Copy`-scalar ctor family discipline
13023    /// (`aplicacao_placement_scalar_ctors!`, `layout_nome_only_ctors!`,
13024    /// `dep_nome_only_ctors!`) so the ctor is usable in `const` position
13025    /// at every wire-up site.
13026    ///
13027    /// Every future consumer that wants to construct this variant
13028    /// outside the current in-crate wire-up (the deferred
13029    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
13030    /// per-`:contratos`-edge admission validator projecting the same
13031    /// diagnostic through the caller-facing `slot: &'static str` tag,
13032    /// a future `feira validate --contratos` per-caixa admission verb,
13033    /// an M4 per-`:contratos`-edge pre-emitter running the same
13034    /// DNS-1123-label floor's empty-arm against a caller-supplied
13035    /// `:de` / `:para` pair before hitting the apiserver-side selector,
13036    /// a per-`Caixa` overlay resolver rejecting an author-supplied
13037    /// `:contratos` overlay's empty `:de` / `:para` against a
13038    /// cluster-local snapshot) — now reaches this variant through one
13039    /// call rather than re-inlining the open-coded closure block in
13040    /// lockstep with the one in-crate wire-up site.
13041    #[must_use]
13042    pub const fn contrato_caixa_empty(slot: &'static str) -> Self {
13043        Self::ContratoCaixaEmpty { slot }
13044    }
13045}
13046
13047// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
13048// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
13049// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
13050// substrate-primitive family per typed variant — the paired
13051// `{ <field>: String, reason: String }` two-slot sibling on
13052// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
13053// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
13054// `ContratoMissingTarget`) and the peer two-slot
13055// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
13056// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
13057// on the sibling per-`:contratos` envelopes, plus the peer four-family
13058// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
13059// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
13060// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
13061// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
13062// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
13063// sibling layout-side envelope.
13064//
13065// Every one of the seven wire-up sites — six under the per-axis
13066// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
13067// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
13068// on `EntradaParaInvalid`, `validate_placement_cluster` on
13069// `PlacementClusterInvalid`, `validate_placement_affinity` on
13070// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
13071// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
13072// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
13073// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
13074// sites at [`validate_entrada_host`] (17dd504 already folded onto the
13075// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
13076// the macro-generated ctor of the same name), opened the identical
13077// four-line `AplicacaoError::<Variant>Invalid
13078// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
13079// the local `<field>: &str` argument — the exact "same block re-inlined
13080// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
13081// same altitude the peer three `AplicacaoError` constructor families
13082// and the four peer `LayoutError` constructor families each closed on
13083// their sibling envelopes.
13084//
13085// The macro below generates one `#[must_use]` inherent constructor per
13086// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
13087// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
13088// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
13089// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
13090// pre-lift struct-literal on the same `(<field>, reason)` pair. The
13091// uniform two-field construction (`<field>: <val>.to_string()`,
13092// `reason: reason.into()`) is spelled once — inside the macro — rather
13093// than at every wire-up site. The `reason: impl Into<String>` bound
13094// accepts both `&str` literals (with or without a trailing
13095// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
13096// wire-up site changes its per-arm diagnostic shape at the lift.
13097// `#[must_use]` fires a compile warning at any wire-up that mistakenly
13098// discards the constructed error rather than routing it through
13099// `return Err(…)` / `.map_err(…)` / a closure return.
13100//
13101// Every future consumer that wants to construct one of these seven
13102// variants outside the current in-crate wire-up sites (the deferred
13103// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
13104// admission validators, a future `feira validate --<axis>` per-caixa
13105// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
13106// on `:entrada :host`, an M4 typed placement-engine per-cluster /
13107// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
13108// per-path pre-emitter) reaches the variant through one call rather
13109// than re-inlining the four-line struct-literal block in lockstep with
13110// the current in-crate wire-up sites.
13111macro_rules! aplicacao_field_reason_ctors {
13112    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
13113        impl AplicacaoError {
13114            $(
13115                #[doc = concat!(
13116                    "Construct an [`AplicacaoError::",
13117                    stringify!($variant),
13118                    "`] naming the offending `",
13119                    stringify!($field),
13120                    "` under the given `reason`. Folds the uniform ",
13121                    "`{ ",
13122                    stringify!($field),
13123                    ": ",
13124                    stringify!($field),
13125                    ".to_string(), reason: reason.into() }` two-slot ",
13126                    "construction onto one substrate primitive so every ",
13127                    "wire-up on this variant reads through one dispatch ",
13128                    "rather than the pre-lift four-line struct-literal ",
13129                    "block. `reason` accepts both `&str` literals and ",
13130                    "`format!(…)` outputs through the `impl Into<String>` ",
13131                    "bound."
13132                )]
13133                #[must_use]
13134                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
13135                    Self::$variant {
13136                        $field: $field.to_string(),
13137                        reason: reason.into(),
13138                    }
13139                }
13140            )*
13141        }
13142    };
13143}
13144
13145aplicacao_field_reason_ctors! {
13146    membro_caixa_invalid => MembroCaixaInvalid { caixa },
13147    entrada_para_invalid => EntradaParaInvalid { para },
13148    entrada_host_invalid => EntradaHostInvalid { host },
13149    entrada_path_invalid => EntradaPathInvalid { path },
13150    placement_cluster_invalid => PlacementClusterInvalid { cluster },
13151    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
13152    shard_key_invalid => ShardKeyInvalid { shard_key },
13153}
13154
13155// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
13156// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
13157// [`WitContract::target`] onto one substrate-primitive family per typed
13158// variant — the paired `{ de: String, para: String, <field>: String,
13159// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
13160// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
13161// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
13162// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
13163// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
13164// `ContratoSlotEmpty`), and the peer two-slot
13165// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
13166// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
13167// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
13168// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
13169// sibling `AplicacaoError` envelopes, plus the peer four-family
13170// `LayoutError` ctor set on the sibling layout-side envelope.
13171//
13172// Every one of the four wire-up sites — four per-`:contratos` value-
13173// shape gates inside [`WitContract::target`] (the world-ref prefix
13174// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
13175// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
13176// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
13177// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
13178// failure on `:slot`) — opened the identical five-line
13179// `let (de, para) = self.edge_pair();
13180// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
13181// <field>: <val>.to_string(), reason });` block against the local
13182// [`WitContract::edge_pair`] composite-projection accessor and the
13183// per-arm `<val>: &str` argument — the exact "same block re-inlined at
13184// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
13185// altitude the peer three `AplicacaoError` constructor families and the
13186// four peer `LayoutError` constructor families each closed on their
13187// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
13188// macro closes the last unlifted `{ de, para, <field>: String, reason:
13189// String }` four-slot envelope inside `impl WitContract`, so every
13190// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
13191// reads through this one substrate primitive.
13192//
13193// The macro below generates one `#[must_use]` inherent constructor per
13194// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
13195// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
13196// sites onto one dispatch per arm:
13197// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
13198// byte-equal to the pre-lift struct-literal on the same
13199// `(edge_pair, <val>, reason)` triple. The uniform four-field
13200// construction (`de, para` pair-destructure onto same-named fields +
13201// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
13202// once — inside the macro — rather than at every wire-up site. The
13203// `reason: impl Into<String>` bound accepts both `&str` literals and
13204// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
13205// diagnostic shape at the lift, matching the peer
13206// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
13207// envelope. `#[must_use]` fires a compile warning at any wire-up that
13208// mistakenly discards the constructed error.
13209//
13210// Every future consumer that wants to construct one of these four
13211// variants outside [`WitContract::target`] (a deferred
13212// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
13213// admission validator raising per-payload value-shape diagnostics on
13214// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
13215// future `feira validate --contratos` per-caixa admission verb, an M4
13216// typed WIT-registry-driven per-arm pre-emitter probing each declared
13217// `:endpoint` / `:subject` / `:slot` payload against a canonical
13218// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
13219// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
13220// pre-emitter probing each `:endpoint` against the same shared
13221// HTTPPathMatch grammar) reaches the variant through one call rather
13222// than re-inlining the five-line pair-destructure + struct-literal
13223// block in lockstep with the four in-crate wire-up sites.
13224macro_rules! contrato_pair_value_reason_ctors {
13225    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
13226        impl AplicacaoError {
13227            $(
13228                #[doc = concat!(
13229                    "Construct an [`AplicacaoError::",
13230                    stringify!($variant),
13231                    "`] naming the offending edge `(de, para)` pair, the ",
13232                    "per-payload `",
13233                    stringify!($field),
13234                    "` value, and the parser-shaped `reason`. Folds the ",
13235                    "uniform `{ de, para, ",
13236                    stringify!($field),
13237                    ": ",
13238                    stringify!($field),
13239                    ".to_string(), reason: reason.into() }` four-slot ",
13240                    "construction onto one substrate primitive so every ",
13241                    "wire-up on this variant reads through one dispatch ",
13242                    "rather than the pre-lift five-line pair-destructure ",
13243                    "+ struct-literal block. The `edge` pair threads ",
13244                    "verbatim from [`WitContract::edge_pair`] at the ",
13245                    "call site; `reason` accepts both `&str` literals ",
13246                    "and `format!(…)` outputs through the `impl ",
13247                    "Into<String>` bound."
13248                )]
13249                #[must_use]
13250                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
13251                    let (de, para) = edge;
13252                    Self::$variant {
13253                        de,
13254                        para,
13255                        $field: $field.to_string(),
13256                        reason: reason.into(),
13257                    }
13258                }
13259            )*
13260        }
13261    };
13262}
13263
13264contrato_pair_value_reason_ctors! {
13265    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
13266    contrato_subject_invalid => ContratoSubjectInvalid { subject },
13267    contrato_slot_invalid => ContratoSlotInvalid { slot },
13268    contrato_wit_invalid => ContratoWitInvalid { wit },
13269}
13270
13271// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
13272// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
13273// caixa-only struct-variant wire-up sites at
13274// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
13275// `:contratos :para` arms of `ContratoMemberMissing`),
13276// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
13277// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
13278// and [`validate_no_self_membership`] (one site, the parent-`:nome`
13279// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
13280// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
13281// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
13282// three variants on `{ caixa: String }` at
13283// [`crate::SupervisorSpec::validate_children`] and
13284// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
13285// `SupervisorError` envelope, extending the same "one substrate primitive per
13286// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
13287// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
13288// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
13289// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
13290// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
13291// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
13292// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
13293// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
13294// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
13295// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
13296// variants on `{ nome, caminho }`), and
13297// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
13298// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
13299// peer three `AplicacaoError` sub-family folds already lifted here
13300// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
13301// [`aplicacao_field_reason_ctors!`] 981060b,
13302// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
13303// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
13304// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
13305// [`crate::LayoutError::missing_entry`] 1b09f9d,
13306// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
13307// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
13308//
13309// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
13310// at the per-`:contratos :de`/`:para` unknown-member arms, one on
13311// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
13312// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
13313// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
13314// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
13315// three-line struct-literal against a caller-side `&str` — the exact "same
13316// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
13317// bug, on the same altitude the peer `SupervisorError` /
13318// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
13319// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
13320// their sibling envelopes. The four variants share one `{ caixa: String }`
13321// shape, so the fold routes each wire-up site through one dispatch per typed
13322// variant.
13323//
13324// The macro below generates one `#[must_use]` inherent constructor per
13325// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
13326// wire-up site collapses onto one dispatch:
13327// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
13328// on the same `&str` fixture. The uniform one-field construction
13329// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
13330// than at every wire-up site. Every constructor is `#[must_use]` so a caller
13331// who mistakenly discards the constructed error trips a compile warning at
13332// the wire-up site.
13333//
13334// Every future consumer that wants to construct one of these four variants
13335// outside the current in-crate wire-up sites — a deferred
13336// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
13337// re-checking one added/renamed `:membros` entry against the sibling
13338// `:contratos` graph, a future `feira validate --membros` per-caixa admission
13339// verb re-checking each declared `:membros` entry's `:caixa` name against the
13340// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
13341// duplicate / self-referencing / unknown-membered `:contratos` entry against
13342// a cluster-local snapshot the M4 CR materializer projects — now reaches each
13343// variant through one call rather than re-inlining the three-line
13344// struct-literal in lockstep with the five in-crate wire-up sites.
13345macro_rules! aplicacao_caixa_only_ctors {
13346    ($($ctor:ident => $variant:ident),* $(,)?) => {
13347        impl AplicacaoError {
13348            $(
13349                #[doc = concat!(
13350                    "Construct an [`AplicacaoError::",
13351                    stringify!($variant),
13352                    "`] naming the offending `:membros :caixa` (or ",
13353                    "parent `:nome`, on the self-membership arm; or ",
13354                    "`:contratos :de`/`:para`, on the unknown-member ",
13355                    "arm). Folds the uniform `Self::",
13356                    stringify!($variant),
13357                    " { caixa: caixa.to_string() }` one-field ",
13358                    "struct-literal onto one substrate primitive so ",
13359                    "every wire-up on this variant reads through one ",
13360                    "dispatch rather than the pre-lift three-line ",
13361                    "open-coded struct-literal block."
13362                )]
13363                #[must_use]
13364                pub fn $ctor(caixa: &str) -> Self {
13365                    Self::$variant { caixa: caixa.to_string() }
13366                }
13367            )*
13368        }
13369    };
13370}
13371
13372aplicacao_caixa_only_ctors! {
13373    contrato_member_missing => ContratoMemberMissing,
13374    membro_versao_empty => MembroVersaoEmpty,
13375    membro_duplicate => MembroDuplicate,
13376    membro_is_self_aplicacao => MembroIsSelfAplicacao,
13377}
13378
13379// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
13380// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
13381// sites onto one substrate-primitive family per typed variant — the direct
13382// per-`:entrada :paths` value-shape sibling of the peer
13383// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
13384// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
13385// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
13386// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
13387// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
13388// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
13389// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
13390// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
13391// `:deps` envelope — every single-`String`-slot error family in caixa-core
13392// now reaches through one substrate primitive per typed variant.
13393//
13394// The three wire-up sites — one under [`validate_entrada_path`]'s
13395// leading-slash grammar arm (`EntradaPathNotAbsolute` against
13396// `path: &str`), one under the per-`:entrada :paths` loop's identical
13397// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
13398// and one under the per-`:entrada :paths` loop's dedup arm
13399// (`EntradaPathDuplicate` against the same `&String` via
13400// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
13401// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
13402// three-line struct-literal against a caller-side `&str` / `&String`, the
13403// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
13404// names as a bug. Every one of the compile-time guarantees in
13405// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
13406// start with `/` becomes a caixa-build error, not a Gateway API webhook
13407// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
13408// becomes a caixa-build error, not a silent last-writer-wins render) now
13409// routes through one dispatch per typed variant at every emit site.
13410//
13411// The macro below generates one `#[must_use]` inherent constructor per
13412// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
13413// every wire-up site onto one dispatch:
13414// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
13415// on the same `&str` fixture) or the `&String` sites through
13416// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
13417// construction (`path: path.to_string()`) is spelled once — inside the
13418// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
13419// a caller who mistakenly discards the constructed error trips a compile
13420// warning at the wire-up site.
13421//
13422// Every future consumer that wants to construct one of these two variants
13423// outside the current in-crate wire-up sites — a deferred
13424// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
13425// per-`:entrada :paths` re-check against a cluster-local Gateway API
13426// snapshot, a future `feira validate --entrada` per-caixa admission verb
13427// re-checking each declared `:paths` entry against the same axes, a
13428// per-tenant per-`Aplicacao` overlay resolver rejecting a
13429// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
13430// snapshot the M4 CR materializer projects — now reaches each variant
13431// through one call rather than re-inlining the three-line struct-literal in
13432// lockstep with the three in-crate wire-up sites.
13433macro_rules! aplicacao_path_only_ctors {
13434    ($($ctor:ident => $variant:ident),* $(,)?) => {
13435        impl AplicacaoError {
13436            $(
13437                #[doc = concat!(
13438                    "Construct an [`AplicacaoError::",
13439                    stringify!($variant),
13440                    "`] naming the offending `:entrada :paths` entry. ",
13441                    "Folds the uniform `Self::",
13442                    stringify!($variant),
13443                    " { path: path.to_string() }` one-field ",
13444                    "struct-literal onto one substrate primitive so ",
13445                    "every wire-up on this variant reads through one ",
13446                    "dispatch rather than the pre-lift three-line ",
13447                    "open-coded struct-literal block."
13448                )]
13449                #[must_use]
13450                pub fn $ctor(path: &str) -> Self {
13451                    Self::$variant { path: path.to_string() }
13452                }
13453            )*
13454        }
13455    };
13456}
13457
13458aplicacao_path_only_ctors! {
13459    entrada_path_not_absolute => EntradaPathNotAbsolute,
13460    entrada_path_duplicate => EntradaPathDuplicate,
13461}
13462
13463// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
13464// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
13465// substrate-primitive family per typed variant — the per-`:politicas` copy-
13466// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
13467// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
13468// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
13469// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
13470// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
13471// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
13472// the `String`-slot axis, and the peer per-`:politicas` cross-axis
13473// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
13474// carries at line 3064 on the same M3 mesh envelope.
13475//
13476// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
13477// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
13478// { <slot> }` one-line struct-literal closure against the caller-side
13479// `<slot>: <ty>` argument that the shared
13480// [`crate::render::require_positive_bounded_u32`] /
13481// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
13482// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
13483// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
13484// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
13485// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
13486// on line 3211) — the exact "same one-line struct-literal re-inlined at every
13487// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
13488// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
13489// been folded onto a substrate primitive.
13490//
13491// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
13492// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
13493// collapsing every wire-up onto either one direct dispatch
13494// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
13495// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
13496// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
13497// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
13498// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
13499// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
13500// constructor with matching arity and signature. The `const fn` qualifier
13501// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
13502// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
13503// per-variant `$field:ident` axis re-uses the enum's canonical field name so
13504// the generated ctor's parameter name matches every wire-up's local binding
13505// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
13506// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
13507// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
13508// warning at any wire-up that mistakenly discards the constructed error, on
13509// the same footing as every sibling `AplicacaoError` / `DepError` /
13510// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
13511// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
13512// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
13513// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
13514//
13515// Every future consumer that wants to construct one of these eight variants
13516// outside [`MeshPolicy::validate`] — a deferred
13517// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
13518// checking each `:politicas` axis against a cluster-local `:politicas` cap
13519// overlay, a future per-`:contratos`-edge `:politicas` override the
13520// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
13521// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
13522// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
13523// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
13524// a future `feira validate --politicas` per-caixa admission verb re-checking
13525// each declared per-axis value against the same bounds — now reaches each
13526// variant through one call rather than re-inlining the one-line struct-
13527// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
13528// which is exactly the invariant every prior ctor-macro lift already closed
13529// on its sibling envelope. Closes the last remaining per-`:politicas`
13530// per-axis `AplicacaoError` variant family that had not yet been folded onto
13531// a substrate primitive; the compound cross-axis variants
13532// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
13533// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
13534// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
13535macro_rules! aplicacao_policy_scalar_ctors {
13536    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
13537        impl AplicacaoError {
13538            $(
13539                #[doc = concat!(
13540                    "Construct an [`AplicacaoError::",
13541                    stringify!($variant),
13542                    "`] naming the offending per-`:politicas` `",
13543                    stringify!($field),
13544                    "` scalar. Folds the uniform `Self::",
13545                    stringify!($variant),
13546                    " { ",
13547                    stringify!($field),
13548                    " }` one-field `Copy`-pass-through struct-literal onto ",
13549                    "one substrate primitive so every per-axis wire-up on ",
13550                    "this variant reads through one dispatch — as a direct ",
13551                    "call (`AplicacaoError::",
13552                    stringify!($ctor),
13553                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
13554                    "the same `Copy`-`",
13555                    stringify!($ty),
13556                    "` fixture) or as a bare function pointer in the ",
13557                    "`impl FnOnce(",
13558                    stringify!($ty),
13559                    ") -> AplicacaoError` bracket-closure slot every ",
13560                    "`crate::render::require_positive_bounded_*` / ",
13561                    "`crate::render::require_positive_canonical_bounded_*` ",
13562                    "gate carries — rather than the pre-lift open-coded ",
13563                    "one-line closure over the same one-field struct-",
13564                    "literal. `const fn` preserves the `Copy`-pass-through's ",
13565                    "zero-runtime-work property verbatim."
13566                )]
13567                #[must_use]
13568                pub const fn $ctor($field: $ty) -> Self {
13569                    Self::$variant { $field }
13570                }
13571            )*
13572        }
13573    };
13574}
13575
13576aplicacao_policy_scalar_ctors! {
13577    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
13578    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
13579    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
13580    policy_breaker_max_failures_exceeds_cap =>
13581        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
13582    policy_breaker_window_not_canonical =>
13583        PolicyBreakerWindowNotCanonical { window: Duration },
13584    policy_breaker_window_exceeds_cap =>
13585        PolicyBreakerWindowExceedsCap { window: Duration },
13586    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
13587    policy_rate_limit_window_not_canonical =>
13588        PolicyRateLimitWindowNotCanonical { window: Duration },
13589}
13590
13591#[cfg(test)]
13592mod tests {
13593    use super::*;
13594
13595    fn membro(name: &str, ver: &str) -> Membro {
13596        Membro {
13597            caixa: name.into(),
13598            versao: ver.into(),
13599        }
13600    }
13601
13602    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
13603        WitContract {
13604            de: de.into(),
13605            para: para.into(),
13606            wit: "wasi:http/proxy".into(),
13607            endpoint: Some(ep.into()),
13608            subject: None,
13609            slot: None,
13610        }
13611    }
13612
13613    fn three_member_spec() -> AplicacaoSpec {
13614        AplicacaoSpec {
13615            membros: vec![
13616                membro("catalog", "^0.1"),
13617                membro("cart", "^0.1"),
13618                membro("payment", "^0.2"),
13619            ],
13620            contratos: vec![
13621                contract_http("cart", "catalog", "/products/:id"),
13622                contract_http("cart", "payment", "/charge"),
13623            ],
13624            politicas: MeshPolicy {
13625                timeout: Some(Duration::from_secs(30)),
13626                retries: Some(3),
13627                mtls_required: Some(true),
13628                ..Default::default()
13629            },
13630            placement: Placement {
13631                estrategia: PlacementStrategy::Replicated,
13632                clusters: vec!["rio".into(), "mar".into()],
13633                affinity: Some("data-locality".into()),
13634                shard_key: None,
13635            },
13636            entrada: Some(Entrada {
13637                host: "checkout.quero.cloud".into(),
13638                para: "cart".into(),
13639                paths: vec!["/api/cart".into(), "/api/products".into()],
13640                port: 8080,
13641            }),
13642        }
13643    }
13644
13645    #[test]
13646    fn happy_path_validates() {
13647        three_member_spec().validate().unwrap();
13648    }
13649
13650    #[test]
13651    fn rejects_empty_membros() {
13652        let mut s = three_member_spec();
13653        s.membros = vec![];
13654        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
13655    }
13656
13657    #[test]
13658    fn rejects_empty_membro_caixa() {
13659        // A `:caixa ""` entry has no name to render into programs.yaml
13660        // and no caixa.lisp to resolve at lacre time.
13661        let mut s = three_member_spec();
13662        s.membros[1].caixa = String::new();
13663        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
13664    }
13665
13666    #[test]
13667    fn rejects_empty_membro_versao() {
13668        // A `:versao ""` entry can't pin a semver constraint, so the
13669        // lacre pipeline fails far from the source.
13670        let mut s = three_member_spec();
13671        s.membros[2].versao = String::new();
13672        let err = s.validate().unwrap_err();
13673        assert!(
13674            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
13675            "got {err:?}"
13676        );
13677    }
13678
13679    #[test]
13680    fn rejects_duplicate_membro_caixa() {
13681        // Two `:membros` entries with the same `:caixa` collapse to one
13682        // node in the membership HashSet, which masks `:contratos`
13683        // membership errors and produces duplicate programs.yaml entries.
13684        let mut s = three_member_spec();
13685        s.membros.push(membro("cart", "^0.2"));
13686        let err = s.validate().unwrap_err();
13687        assert!(
13688            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
13689            "got {err:?}"
13690        );
13691    }
13692
13693    #[test]
13694    fn rejects_invalid_membro_versao_requirement() {
13695        // The fail-before-pass-after pin: a non-empty but malformed
13696        // semver requirement (`"^bad-version"`) silently passed
13697        // `validate()` on every pre-gate codebase because the prior
13698        // shape only refused the empty string. The parse failure
13699        // surfaced far downstream at lacre-resolve time with a
13700        // `semver::Error` that didn't name which `:membros` entry
13701        // carried the typo. The new gate moves the check to caixa-build
13702        // time at the source caixa.lisp.
13703        let mut s = three_member_spec();
13704        s.membros[2].versao = "^bad-version".into();
13705        let err = s.validate().unwrap_err();
13706        assert!(
13707            matches!(
13708                err,
13709                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
13710                    if caixa == "payment" && versao == "^bad-version"
13711            ),
13712            "got {err:?}"
13713        );
13714    }
13715
13716    #[test]
13717    fn rejects_membro_versao_with_double_caret_typo() {
13718        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
13719        // Cargo-shaped requirement on first glance but fails the parser
13720        // because semver doesn't accept stacked operators. Pin this
13721        // adjacent-shape footgun explicitly so a future relaxation that
13722        // accepts "looks-canonical-but-isn't" forms surfaces here.
13723        let mut s = three_member_spec();
13724        s.membros[0].versao = "^^0.1".into();
13725        let err = s.validate().unwrap_err();
13726        assert!(
13727            matches!(
13728                err,
13729                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
13730                    if caixa == "catalog" && versao == "^^0.1"
13731            ),
13732            "got {err:?}"
13733        );
13734    }
13735
13736    #[test]
13737    fn rejects_membro_versao_with_v_prefixed_tag() {
13738        // `"v0.1"` is the canonical "git-tag-shape leaking into the
13739        // semver requirement slot" typo — an author copies the
13740        // publish-side git-tag string verbatim into `:versao`, but
13741        // Cargo's semver parser rejects the leading `v` (only digits +
13742        // canonical operators are valid in the major-version
13743        // position). The gate's diagnostic names which member entry
13744        // carried the v-prefix so the fix is one edit, not a grep
13745        // through every member's `:versao`. (Note: bare `x`-glob
13746        // shorthands like `^0.1.x` are *accepted* by the semver crate
13747        // as an `*` wildcard on the patch axis — they're a Cargo-side
13748        // valid shape, not a typo, so the gate intentionally lets them
13749        // through.)
13750        let mut s = three_member_spec();
13751        s.membros[1].versao = "v0.1".into();
13752        let err = s.validate().unwrap_err();
13753        assert!(
13754            matches!(
13755                err,
13756                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
13757                    if caixa == "cart" && versao == "v0.1"
13758            ),
13759            "got {err:?}"
13760        );
13761    }
13762
13763    #[test]
13764    fn accepts_canonical_membro_versao_forms() {
13765        // The four Cargo-shaped requirement forms `:deps :versao`
13766        // already accepts via `crate::parse_requirement` must pass the
13767        // membros gate without re-validating at the resolver layer.
13768        // Pin every leg so a future tightening of the canonical set
13769        // surfaces here as a test failure.
13770        for form in [
13771            "^0.1",      // caret — minor-range pin (the most common shape)
13772            "~0.1.2",    // tilde — patch-range pin
13773            "0.1.0",     // exact — single-version pin
13774            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
13775            ">=0.1, <2", // multi-range — comma-separated comparators
13776        ] {
13777            let mut s = three_member_spec();
13778            for m in &mut s.membros {
13779                m.versao = form.into();
13780            }
13781            s.validate()
13782                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
13783        }
13784    }
13785
13786    #[test]
13787    fn membro_versao_empty_takes_precedence_over_invalid() {
13788        // Order pin: the existing `MembroVersaoEmpty` diagnostic
13789        // (which doesn't try to parse) fires before the new
13790        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
13791        // `:versao` keeps its narrower error message — `parse_requirement`
13792        // would also reject `""`, but the empty-string arm is the more
13793        // self-locating diagnostic for the author.
13794        let mut s = three_member_spec();
13795        s.membros[1].versao = String::new();
13796        let err = s.validate().unwrap_err();
13797        assert!(
13798            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
13799            "got {err:?}"
13800        );
13801    }
13802
13803    #[test]
13804    fn membro_versao_invalid_fires_before_duplicate_check() {
13805        // Order pin: a malformed requirement on a non-duplicate entry
13806        // surfaces *its own* diagnostic (which names the offending
13807        // `:versao` string), even when a later entry would otherwise
13808        // collapse onto an earlier name. The per-entry shape gate runs
13809        // inline before the duplicate-key insert, parallel to
13810        // `membros_validation_runs_before_contratos_membership_check`
13811        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
13812        let mut s = three_member_spec();
13813        s.membros[0].versao = "^bad".into();
13814        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
13815        let err = s.validate().unwrap_err();
13816        assert!(
13817            matches!(
13818                err,
13819                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
13820            ),
13821            "got {err:?}"
13822        );
13823    }
13824
13825    #[test]
13826    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
13827        // The diagnostic-shape pin: the error names the offending
13828        // `:versao` value verbatim so the author can grep their
13829        // caixa.lisp without re-running the build, and carries a
13830        // non-empty `reason` from `semver::VersionReq::parse` so the
13831        // parser's own wording flows through to the diagnostic.
13832        let mut s = three_member_spec();
13833        s.membros[2].versao = "not-a-req".into();
13834        let err = s.validate().unwrap_err();
13835        let AplicacaoError::MembroVersaoInvalid {
13836            caixa,
13837            versao,
13838            reason,
13839        } = err
13840        else {
13841            panic!("expected MembroVersaoInvalid, got other variant");
13842        };
13843        assert_eq!(caixa, "payment");
13844        assert_eq!(versao, "not-a-req");
13845        assert!(
13846            !reason.is_empty(),
13847            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
13848        );
13849    }
13850
13851    #[test]
13852    fn membro_versao_invalid_runs_before_contratos_check() {
13853        // A malformed `:versao` on any member must surface its own
13854        // diagnostic (which names *which* member to fix) before any
13855        // `:contratos` membership lookup raises `ContratoMemberMissing`.
13856        // The `:contratos` gate runs after `validate_membros`, so this
13857        // is structurally guaranteed — pin it explicitly so a future
13858        // refactor that reorders the gates surfaces here.
13859        let mut s = three_member_spec();
13860        s.membros[1].versao = "^^0.1".into();
13861        // Add a contrato whose `:para` doesn't exist — would normally
13862        // raise ContratoMemberMissing at the membership lookup, but
13863        // the membros gate must fire first.
13864        s.contratos
13865            .push(contract_http("cart", "phantom", "/never-reached"));
13866        let err = s.validate().unwrap_err();
13867        assert!(
13868            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
13869            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
13870        );
13871    }
13872
13873    #[test]
13874    fn membros_validation_runs_before_contratos_membership_check() {
13875        // If `:membros` carries a duplicate, the membership-collapse
13876        // would silently accept a `:contratos :para "phantom"` so long
13877        // as some entry hashes to "phantom". Pinning order: the
13878        // duplicate-membros error fires first, regardless of whether
13879        // contratos reference real members.
13880        let mut s = three_member_spec();
13881        s.membros = vec![
13882            membro("cart", "^0.1"),
13883            membro("cart", "^0.2"),
13884            membro("catalog", "^0.1"),
13885            membro("payment", "^0.1"),
13886        ];
13887        let err = s.validate().unwrap_err();
13888        assert!(
13889            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
13890            "got {err:?}"
13891        );
13892    }
13893
13894    #[test]
13895    fn distinct_membros_validate() {
13896        // Pin the happy-path: every `:membros` entry has a non-empty
13897        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
13898        // The fixture already satisfies this; this test makes the
13899        // invariant explicit so a future refactor of the fixture can't
13900        // silently break the guarantee.
13901        three_member_spec().validate().unwrap();
13902    }
13903
13904    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
13905
13906    #[test]
13907    fn rejects_membro_caixa_with_uppercase() {
13908        // The canonical "I copied the Servico's display name verbatim"
13909        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
13910        // but author tools often round-trip a TitleCase or CamelCase
13911        // identifier from an ADR or a sketch. Pin the diagnostic names
13912        // the offending name and suggests the lower-cased fix in one
13913        // edit, mirroring the `rejects_entrada_host_with_uppercase`
13914        // gate's shape (c7d05ec).
13915        let mut s = three_member_spec();
13916        s.membros[1].caixa = "Cart".into();
13917        let err = s.validate().unwrap_err();
13918        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
13919            panic!("expected MembroCaixaInvalid, got other variant");
13920        };
13921        assert_eq!(caixa, "Cart");
13922        assert!(
13923            reason.contains("uppercase"),
13924            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
13925        );
13926        assert!(
13927            reason.contains("\"cart\""),
13928            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
13929        );
13930    }
13931
13932    #[test]
13933    fn rejects_membro_caixa_with_underscore() {
13934        // The canonical "I'm thinking of a Python module / Postgres
13935        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
13936        // label schema. K8s rejects `metadata.name: my_cart` at admission
13937        // time with an opaque `field is invalid` (no source-citing
13938        // diagnostic). The gate moves it to caixa-build time.
13939        let mut s = three_member_spec();
13940        s.membros[0].caixa = "my_cart".into();
13941        let err = s.validate().unwrap_err();
13942        assert!(
13943            matches!(
13944                err,
13945                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
13946                    if caixa == "my_cart" && reason.contains('_')
13947            ),
13948            "got {err:?}"
13949        );
13950    }
13951
13952    #[test]
13953    fn rejects_membro_caixa_with_dot() {
13954        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
13955        // subdomain — even though K8s `metadata.name` itself accepts
13956        // dots (DNS-1123 subdomain rule), this string also lands as a
13957        // K8s Service name (DNS-1035 label — no dots) and as a label
13958        // value on identity-based Cilium selectors. The strictest floor
13959        // among the use sites wins. The "I want to namespace my member
13960        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
13961        let mut s = three_member_spec();
13962        s.membros[2].caixa = "team.cart".into();
13963        let err = s.validate().unwrap_err();
13964        assert!(
13965            matches!(
13966                err,
13967                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
13968                    if caixa == "team.cart" && reason.contains('.')
13969            ),
13970            "got {err:?}"
13971        );
13972    }
13973
13974    #[test]
13975    fn rejects_membro_caixa_with_leading_hyphen() {
13976        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
13977        // with an alphanumeric. The K8s apiserver rejects `-cart`
13978        // outright; the renderer would emit a `metadata.name: "-cart"`
13979        // that fails admission far from the source caixa.lisp.
13980        let mut s = three_member_spec();
13981        s.membros[0].caixa = "-cart".into();
13982        let err = s.validate().unwrap_err();
13983        assert!(
13984            matches!(
13985                err,
13986                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
13987                    if caixa == "-cart" && reason.contains("start and end")
13988            ),
13989            "got {err:?}"
13990        );
13991    }
13992
13993    #[test]
13994    fn rejects_membro_caixa_with_trailing_hyphen() {
13995        // The symmetric arm of the boundary rule. Pin separately so
13996        // both ends of the label are covered against a future relaxation
13997        // that only checks one boundary.
13998        let mut s = three_member_spec();
13999        s.membros[1].caixa = "cart-".into();
14000        let err = s.validate().unwrap_err();
14001        assert!(
14002            matches!(
14003                err,
14004                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
14005                    if caixa == "cart-"
14006            ),
14007            "got {err:?}"
14008        );
14009    }
14010
14011    #[test]
14012    fn rejects_membro_caixa_with_unicode() {
14013        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
14014        // (`xn--…`) by the author before it reaches K8s. The byte-by-
14015        // byte ASCII validity check rejects multi-byte UTF-8 sequences
14016        // by the first byte that fails the `[a-z0-9-]` predicate.
14017        let mut s = three_member_spec();
14018        s.membros[2].caixa = "café".into();
14019        let err = s.validate().unwrap_err();
14020        assert!(
14021            matches!(
14022                err,
14023                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
14024                    if caixa == "café"
14025            ),
14026            "got {err:?}"
14027        );
14028    }
14029
14030    #[test]
14031    fn rejects_membro_caixa_with_whitespace() {
14032        // Whitespace is the canonical "I pasted from a sketch / doc"
14033        // footgun. The apiserver rejects every `metadata.name` value
14034        // carrying whitespace; pin the gate fires at the right boundary.
14035        let mut s = three_member_spec();
14036        s.membros[0].caixa = "my cart".into();
14037        let err = s.validate().unwrap_err();
14038        assert!(
14039            matches!(
14040                err,
14041                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
14042                    if caixa == "my cart"
14043            ),
14044            "got {err:?}"
14045        );
14046    }
14047
14048    #[test]
14049    fn rejects_membro_caixa_too_long() {
14050        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
14051        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
14052        // exactly. The gate's reason names both the cap and the actual
14053        // length so the author can shorten in one edit.
14054        let mut s = three_member_spec();
14055        let too_long = "a".repeat(64);
14056        s.membros[1].caixa = too_long.clone();
14057        let err = s.validate().unwrap_err();
14058        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
14059            panic!("expected MembroCaixaInvalid");
14060        };
14061        assert_eq!(caixa, too_long);
14062        assert!(
14063            reason.contains("63") && reason.contains("64"),
14064            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
14065        );
14066    }
14067
14068    #[test]
14069    fn membro_caixa_max_length_validates() {
14070        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
14071        // so a future tightening (e.g. dropping to 62) surfaces here as
14072        // a regression, mirroring `entrada_host_max_length_validates`
14073        // (c7d05ec).
14074        let mut s = three_member_spec();
14075        s.membros[2].caixa = "a".repeat(63);
14076        s.entrada.as_mut().unwrap().para = "a".repeat(63);
14077        // remove contratos referencing the renamed member; they'd
14078        // raise ContratoMemberMissing otherwise
14079        s.contratos
14080            .retain(|c| c.de != "payment" && c.para != "payment");
14081        s.validate().unwrap();
14082    }
14083
14084    #[test]
14085    fn accepts_canonical_membro_caixa_forms() {
14086        // The DNS-1123 label shapes a caixa author is realistically
14087        // going to write: single-word lowercase, hyphen-joined, ending
14088        // in a digit-suffixed version (`cart-v2`), starting with a
14089        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
14090        // DNS-1035 which requires a letter at position 0), single-
14091        // character (`a` — boundary). Pin every leg so a future
14092        // tightening that bans (e.g.) digit-start identifiers surfaces
14093        // here.
14094        for form in [
14095            "checkout",
14096            "cart",
14097            "cart-v2",
14098            "a",
14099            "c0",
14100            "3rd-party-shim",
14101            "x-1-2-3-4",
14102        ] {
14103            let mut s = three_member_spec();
14104            // Renaming a member also requires updating downstream refs;
14105            // drop everything else and rebuild a minimal spec around
14106            // just the one renamed member.
14107            s.membros = vec![membro(form, "^0.1")];
14108            s.contratos = vec![];
14109            s.entrada = None;
14110            s.validate()
14111                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
14112        }
14113    }
14114
14115    #[test]
14116    fn membro_caixa_empty_takes_precedence_over_invalid() {
14117        // Order pin: the existing `MembroCaixaEmpty` diagnostic
14118        // (which doesn't try to parse) fires before the new
14119        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
14120        // `:caixa` keeps its narrower error message — the new gate
14121        // would also reject `""`, but the empty-string arm is the more
14122        // self-locating diagnostic for the author. Mirrors the
14123        // `entrada_host_empty_takes_precedence_over_invalid` pin
14124        // (c7d05ec).
14125        let mut s = three_member_spec();
14126        s.membros[1].caixa = String::new();
14127        let err = s.validate().unwrap_err();
14128        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
14129    }
14130
14131    #[test]
14132    fn membro_caixa_invalid_fires_before_versao_check() {
14133        // Order pin: an invalid-shape `:caixa` surfaces *its own*
14134        // diagnostic (which names the offending caixa name), even when
14135        // the same entry's `:versao` is also empty/invalid. The shape
14136        // gate runs first because the diagnostic is more self-locating —
14137        // an empty/invalid `:versao` on an invalid-shape caixa name is
14138        // a downstream-fix-after-the-caixa-rename concern.
14139        let mut s = three_member_spec();
14140        s.membros[1].caixa = "Cart".into();
14141        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
14142        let err = s.validate().unwrap_err();
14143        assert!(
14144            matches!(
14145                err,
14146                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
14147            ),
14148            "got {err:?}"
14149        );
14150    }
14151
14152    #[test]
14153    fn membro_caixa_invalid_fires_before_duplicate_check() {
14154        // Order pin: a malformed-shape `:caixa` on an earlier entry
14155        // surfaces *its own* diagnostic, even when a later entry would
14156        // otherwise collapse onto a duplicate name. The per-entry shape
14157        // gate runs inline before the duplicate-key insert, parallel
14158        // to `membro_versao_invalid_fires_before_duplicate_check`.
14159        let mut s = three_member_spec();
14160        s.membros[0].caixa = "Catalog".into();
14161        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
14162        let err = s.validate().unwrap_err();
14163        assert!(
14164            matches!(
14165                err,
14166                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
14167            ),
14168            "got {err:?}"
14169        );
14170    }
14171
14172    #[test]
14173    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
14174        // The diagnostic-shape pin: the error names the offending
14175        // `:caixa` value verbatim so the author can grep their
14176        // caixa.lisp without re-running the build, and carries a
14177        // non-empty `reason` naming the specific violation. Same
14178        // shape every typed-shape gate enshrines (c7d05ec's
14179        // `entrada_host_diagnostic_carries_offending_host`,
14180        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
14181        let mut s = three_member_spec();
14182        s.membros[2].caixa = "BAD_NAME".into();
14183        let err = s.validate().unwrap_err();
14184        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
14185            panic!("expected MembroCaixaInvalid");
14186        };
14187        assert_eq!(caixa, "BAD_NAME");
14188        assert!(
14189            !reason.is_empty(),
14190            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
14191        );
14192    }
14193
14194    #[test]
14195    fn rejects_contrato_with_unknown_de() {
14196        let mut s = three_member_spec();
14197        s.contratos.push(contract_http("phantom", "catalog", "/x"));
14198        let err = s.validate().unwrap_err();
14199        assert!(
14200            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
14201        );
14202    }
14203
14204    #[test]
14205    fn rejects_contrato_with_unknown_para() {
14206        let mut s = three_member_spec();
14207        s.contratos.push(contract_http("cart", "phantom", "/x"));
14208        let err = s.validate().unwrap_err();
14209        assert!(
14210            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
14211        );
14212    }
14213
14214    #[test]
14215    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
14216        // The read-path pin: the phantom-`:de` refusal arm's
14217        // `ContratoMemberMissing.caixa` carrier must be observed through
14218        // the lifted [`WitContract::source`] accessor, not the raw
14219        // `.de.clone()` field-access `String`-carry. Peer of the sibling
14220        // per-`:contratos` self-loop arm's `.source().to_string()` /
14221        // `.world_ref().to_string()` `String`-carry sites the earlier
14222        // convergence lifted onto the same accessor pair. A future
14223        // silent detour that reintroduced the raw `.de.clone()` at the
14224        // wrap envelope while the shape-gate and membership lookup
14225        // routed through the accessor would surface here as a byte-equal
14226        // miss between the fired diagnostic's `caixa:` field and the
14227        // offending edge's `.source()` — pinning the accessor as the
14228        // sole read path across the phantom-name refusal arm's arg +
14229        // wrap-envelope emit surface.
14230        let mut s = three_member_spec();
14231        let phantom = contract_http("phantom", "catalog", "/x");
14232        s.contratos.push(phantom.clone());
14233        let err = s.validate().unwrap_err();
14234        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
14235            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
14236        };
14237        assert_eq!(
14238            caixa,
14239            phantom.source(),
14240            "ContratoMemberMissing.caixa on the phantom-:de arm must \
14241             byte-equal WitContract::source — the wrap envelope must \
14242             route through the lifted accessor rather than the raw \
14243             .de.clone() field-access String-carry"
14244        );
14245    }
14246
14247    #[test]
14248    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
14249        // The symmetric read-path pin on the `:para` phantom-name
14250        // refusal arm — same shape as the sibling `:de` pin above but
14251        // on the callee-Servico axis. Pins the wrap envelope's
14252        // `caixa:` field is observed through the lifted
14253        // [`WitContract::destination`] accessor, not the raw
14254        // `.para.clone()` field-access `String`-carry.
14255        let mut s = three_member_spec();
14256        let phantom = contract_http("cart", "phantom", "/x");
14257        s.contratos.push(phantom.clone());
14258        let err = s.validate().unwrap_err();
14259        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
14260            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
14261        };
14262        assert_eq!(
14263            caixa,
14264            phantom.destination(),
14265            "ContratoMemberMissing.caixa on the phantom-:para arm must \
14266             byte-equal WitContract::destination — the wrap envelope \
14267             must route through the lifted accessor rather than the raw \
14268             .para.clone() field-access String-carry"
14269        );
14270    }
14271
14272    #[test]
14273    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
14274        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
14275        // refusal arm — the `validate_contrato_caixa` arg must be
14276        // observed through the lifted [`WitContract::source`] accessor,
14277        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
14278        // value routes through the shared
14279        // [`crate::render::require_valid_dns_1123_label`] floor with the
14280        // accessor-projected value; the fired
14281        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
14282        // the offending edge's `.source()`, pinning that the arg + the
14283        // downstream `caixa: caixa.to_string()` wrap route through the
14284        // same accessor's read path.
14285        let mut s = three_member_spec();
14286        let malformed = contract_http("BAD_NAME", "catalog", "/x");
14287        s.contratos.push(malformed.clone());
14288        let err = s.validate().unwrap_err();
14289        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
14290            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
14291        };
14292        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
14293        assert_eq!(
14294            caixa,
14295            malformed.source(),
14296            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
14297             byte-equal WitContract::source — the shape-gate arg + wrap \
14298             envelope must route through the lifted accessor rather \
14299             than the raw &c.de &String-borrow"
14300        );
14301    }
14302
14303    #[test]
14304    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
14305        // Symmetric arm to the sibling `:de` malformed-shape pin above,
14306        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
14307        // route through the lifted [`WitContract::destination`]
14308        // accessor. `:para` runs after the `:de` shape gate in the
14309        // canonical edge-direction order, so the `:de` value must be
14310        // well-shaped for the `:para` gate to fire — the `cart` :de is
14311        // canonical.
14312        let mut s = three_member_spec();
14313        let malformed = contract_http("cart", "BAD_NAME", "/x");
14314        s.contratos.push(malformed.clone());
14315        let err = s.validate().unwrap_err();
14316        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
14317            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
14318        };
14319        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
14320        assert_eq!(
14321            caixa,
14322            malformed.destination(),
14323            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
14324             byte-equal WitContract::destination — the shape-gate arg + \
14325             wrap envelope must route through the lifted accessor \
14326             rather than the raw &c.para &String-borrow"
14327        );
14328    }
14329
14330    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
14331
14332    #[test]
14333    fn rejects_contrato_de_empty() {
14334        // `:de ""` previously fell through to `ContratoMemberMissing`
14335        // (with `caixa: ""`) because the validated `:membros :caixa`
14336        // set never contains the empty string. The narrower
14337        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
14338        // the offending slot.
14339        let mut s = three_member_spec();
14340        s.contratos.push(contract_http("", "catalog", "/x"));
14341        let err = s.validate().unwrap_err();
14342        assert_eq!(
14343            err,
14344            AplicacaoError::ContratoCaixaEmpty {
14345                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
14346            },
14347            "got {err:?}"
14348        );
14349    }
14350
14351    #[test]
14352    fn rejects_contrato_para_empty() {
14353        // Symmetric arm to `:de ""` — `:para ""` previously fell
14354        // through to `ContratoMemberMissing { caixa: "" }`.
14355        let mut s = three_member_spec();
14356        s.contratos.push(contract_http("cart", "", "/x"));
14357        let err = s.validate().unwrap_err();
14358        assert_eq!(
14359            err,
14360            AplicacaoError::ContratoCaixaEmpty {
14361                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
14362            },
14363            "got {err:?}"
14364        );
14365    }
14366
14367    #[test]
14368    fn rejects_contrato_de_with_uppercase() {
14369        // The canonical "I copied the Servico's TitleCase display
14370        // name from an ADR" typo. Until this gate landed `:de "Cart"`
14371        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
14372        // as "this caixa isn't in `:membros`" when the root cause is
14373        // "this `:de` value's shape can never legitimately match a
14374        // validated member (DNS-1123 labels are lowercase)". The
14375        // narrower diagnostic names the offending slot, the value
14376        // verbatim, and the parser-shaped reason.
14377        let mut s = three_member_spec();
14378        s.contratos.push(contract_http("Cart", "catalog", "/x"));
14379        let err = s.validate().unwrap_err();
14380        let AplicacaoError::ContratoCaixaInvalid {
14381            slot,
14382            caixa,
14383            reason,
14384        } = err
14385        else {
14386            panic!("expected ContratoCaixaInvalid, got other variant");
14387        };
14388        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
14389        assert_eq!(caixa, "Cart");
14390        assert!(
14391            reason.contains("uppercase"),
14392            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
14393        );
14394    }
14395
14396    #[test]
14397    fn rejects_contrato_para_with_underscore() {
14398        // The canonical "I'm thinking of a Python module" leak —
14399        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
14400        // Pin the `:para` axis surfaces the same diagnostic shape as
14401        // the `:de` axis on the underscore violation.
14402        let mut s = three_member_spec();
14403        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
14404        let err = s.validate().unwrap_err();
14405        assert!(
14406            matches!(
14407                err,
14408                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
14409                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
14410            ),
14411            "got {err:?}"
14412        );
14413    }
14414
14415    #[test]
14416    fn rejects_contrato_de_with_dot() {
14417        // A `:contratos :de` value is a single DNS-1123 *label*, not
14418        // a subdomain — mirroring the `:membros :caixa` floor. The
14419        // strictest floor among the use sites wins.
14420        let mut s = three_member_spec();
14421        s.contratos
14422            .push(contract_http("team.cart", "catalog", "/x"));
14423        let err = s.validate().unwrap_err();
14424        assert!(
14425            matches!(
14426                err,
14427                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
14428                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
14429            ),
14430            "got {err:?}"
14431        );
14432    }
14433
14434    #[test]
14435    fn rejects_contrato_para_with_unicode() {
14436        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
14437        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
14438        // validity check rejects multi-byte UTF-8 by the first
14439        // non-`[a-z0-9-]` byte.
14440        let mut s = three_member_spec();
14441        s.contratos.push(contract_http("cart", "café", "/x"));
14442        let err = s.validate().unwrap_err();
14443        assert!(
14444            matches!(
14445                err,
14446                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
14447                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
14448            ),
14449            "got {err:?}"
14450        );
14451    }
14452
14453    #[test]
14454    fn rejects_contrato_de_with_leading_hyphen() {
14455        // DNS-1123 boundary rule: labels must start and end with an
14456        // alphanumeric. K8s rejects `-cart` outright; the narrower
14457        // shape diagnostic now names the violation at caixa-build
14458        // time rather than the misframed membership-lookup arm.
14459        let mut s = three_member_spec();
14460        s.contratos.push(contract_http("-cart", "catalog", "/x"));
14461        let err = s.validate().unwrap_err();
14462        assert!(
14463            matches!(
14464                err,
14465                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
14466                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
14467            ),
14468            "got {err:?}"
14469        );
14470    }
14471
14472    #[test]
14473    fn contrato_de_empty_takes_precedence_over_invalid() {
14474        // Order pin: the `ContratoCaixaEmpty` arm fires before the
14475        // `ContratoCaixaInvalid` parse-side arm — same empty-first
14476        // cascade `validate_membro_caixa` / `validate_placement_cluster`
14477        // / `validate_entrada_host` already establish on their peer
14478        // name axes. The empty string is a structurally distinct
14479        // authoring footgun (the author left the field blank, vs.
14480        // typed a malformed value), so it gets its own diagnostic.
14481        let mut s = three_member_spec();
14482        s.contratos.push(contract_http("", "catalog", "/x"));
14483        let err = s.validate().unwrap_err();
14484        assert_eq!(
14485            err,
14486            AplicacaoError::ContratoCaixaEmpty {
14487                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
14488            }
14489        );
14490    }
14491
14492    #[test]
14493    fn contrato_de_shape_fires_before_para_shape() {
14494        // Per-axis order pin: within one `:contratos` entry, the `:de`
14495        // shape gate fires before the `:para` shape gate — same
14496        // edge-direction order the existing `ContratoMemberMissing` /
14497        // `ContratoSelfLoop` / target-dispatch checks use, so the
14498        // diagnostic for a contract with both `:de` and `:para`
14499        // malformed is stable. Authors fixing the surfaced `:de`
14500        // first will see `:para`'s diagnostic on re-run.
14501        let mut s = three_member_spec();
14502        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
14503        let err = s.validate().unwrap_err();
14504        assert!(
14505            matches!(
14506                err,
14507                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
14508                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
14509            ),
14510            "got {err:?}"
14511        );
14512    }
14513
14514    #[test]
14515    fn contrato_shape_fires_before_membership_lookup() {
14516        // The load-bearing pin: an invalid-shape `:de` surfaces its
14517        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
14518        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
14519        // an invalid-shape `:de` could never legitimately match any
14520        // member — the prior `ContratoMemberMissing` diagnostic was
14521        // a structural impossibility framed as a graph-membership
14522        // failure. The shape gate now routes every such input through
14523        // the narrower self-locating diagnostic.
14524        let mut s = three_member_spec();
14525        s.contratos.push(contract_http("Cart", "catalog", "/x"));
14526        let err = s.validate().unwrap_err();
14527        assert!(
14528            matches!(
14529                err,
14530                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
14531            ),
14532            "got {err:?}"
14533        );
14534        // And the symmetric case: an invalid-shape `:para` surfaces
14535        // its own diagnostic too, even when `:de` is well-shaped.
14536        let mut s = three_member_spec();
14537        s.contratos.push(contract_http("cart", "Catalog", "/x"));
14538        let err = s.validate().unwrap_err();
14539        assert!(
14540            matches!(
14541                err,
14542                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
14543            ),
14544            "got {err:?}"
14545        );
14546    }
14547
14548    #[test]
14549    fn contrato_shape_fires_before_self_edge_check() {
14550        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
14551        // bugs: the shape violation (uppercase) and the self-edge
14552        // violation. The narrower per-axis shape diagnostic surfaces
14553        // first because fixing the shape may reveal that the author
14554        // also meant to point `:para` at a different member — the
14555        // self-edge framing is only useful once both endpoints have
14556        // valid shape.
14557        let mut s = three_member_spec();
14558        s.contratos.push(contract_http("Cart", "Cart", "/x"));
14559        let err = s.validate().unwrap_err();
14560        assert!(
14561            matches!(
14562                err,
14563                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
14564                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
14565            ),
14566            "got {err:?}"
14567        );
14568    }
14569
14570    #[test]
14571    fn contrato_well_shaped_phantom_still_raises_member_missing() {
14572        // Strict-improvement pin: a well-shaped `:de` that simply
14573        // isn't in `:membros` (a phantom reference — author meant
14574        // to add the member but didn't, or renamed and missed an
14575        // update) still surfaces `ContratoMemberMissing`, unchanged.
14576        // The shape gate only intercepts inputs that could never
14577        // legitimately match a validated member; legitimately-shaped
14578        // phantom references remain on the graph-membership axis.
14579        let mut s = three_member_spec();
14580        s.contratos
14581            .push(contract_http("phantom-shim", "catalog", "/x"));
14582        let err = s.validate().unwrap_err();
14583        assert!(
14584            matches!(
14585                err,
14586                AplicacaoError::ContratoMemberMissing { ref caixa }
14587                    if caixa == "phantom-shim"
14588            ),
14589            "got {err:?}"
14590        );
14591    }
14592
14593    #[test]
14594    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
14595        // The diagnostic-shape pin: the error names the offending
14596        // slot (`:de` or `:para`) verbatim and the offending value
14597        // verbatim plus a non-empty parser-shaped reason, so the
14598        // author can grep their caixa.lisp for `:de "<name>"` /
14599        // `:para "<name>"` and fix it in one edit. Same diagnostic
14600        // shape as `MembroCaixaInvalid` (3f9d7a0) and
14601        // `PlacementClusterInvalid` (6c8c00b).
14602        let mut s = three_member_spec();
14603        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
14604        let err = s.validate().unwrap_err();
14605        let AplicacaoError::ContratoCaixaInvalid {
14606            slot,
14607            caixa,
14608            reason,
14609        } = err
14610        else {
14611            panic!("expected ContratoCaixaInvalid, got {err:?}");
14612        };
14613        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
14614        assert_eq!(caixa, "BAD_NAME");
14615        assert!(
14616            !reason.is_empty(),
14617            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
14618        );
14619    }
14620
14621    #[test]
14622    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
14623        // Scalar-value pin: the two author-facing kebab-case labels the
14624        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
14625        // admits on the `:contratos` per-entry endpoint-shape axis,
14626        // one arm per typed sub-slot. Mirrors the peer scalar-value
14627        // pin the sibling top-level M2 / M3 / Supervisor
14628        // author-facing-label consts carry
14629        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
14630        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
14631        // slot itself), so every altitude of the typed-slot algebra
14632        // shares the same "one canonical byte-string per arm"
14633        // discipline. A future rebrand (`:de` → `:from` matching the
14634        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
14635        // sibling, `:para` → `:to` matching the same, or
14636        // `:de`/`:para` → `:source`/`:target` matching the WIT
14637        // world's `import`/`export` half-vocabulary) lands as an
14638        // edit to exactly one const, and every consumer that reaches
14639        // for the label picks it up at build time rather than at
14640        // runtime as a downstream `ContratoCaixaEmpty` /
14641        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
14642        // diagnostic mismatch far from the rename's commit.
14643        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
14644        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
14645    }
14646
14647    #[test]
14648    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
14649        // Production-through-const pin: the two per-axis labels the
14650        // per-`:contratos` entry endpoint-shape gate at
14651        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
14652        // argument to [`validate_contrato_caixa`] route through the
14653        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
14654        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
14655        // future rebrand that reaches the const but not the gate (or
14656        // vice versa) surfaces here at build time rather than at
14657        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
14658        // `slot: <stale-kebab-case>` diagnostic far from the rename's
14659        // commit. Mirror of the peer
14660        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
14661        // pin (882f498) on the sibling M3 top-level slot axis.
14662        let mut s = three_member_spec();
14663        s.contratos.push(contract_http("", "catalog", "/x"));
14664        assert_eq!(
14665            s.validate().unwrap_err(),
14666            AplicacaoError::ContratoCaixaEmpty {
14667                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
14668            }
14669        );
14670        let mut s = three_member_spec();
14671        s.contratos.push(contract_http("cart", "", "/x"));
14672        assert_eq!(
14673            s.validate().unwrap_err(),
14674            AplicacaoError::ContratoCaixaEmpty {
14675                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
14676            }
14677        );
14678    }
14679
14680    #[test]
14681    fn accepts_canonical_contrato_caixa_forms() {
14682        // The DNS-1123 label shapes a caixa author is realistically
14683        // going to write on a `:contratos :de` / `:para`. Pin every
14684        // leg so a future tightening that bans (e.g.) digit-start
14685        // identifiers surfaces here, mirroring
14686        // `accepts_canonical_membro_caixa_forms` on the peer name
14687        // axis.
14688        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
14689            let mut s = three_member_spec();
14690            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
14691            s.contratos = vec![contract_http("checkout", form, "/x")];
14692            s.entrada = None;
14693            s.validate().unwrap_or_else(|e| {
14694                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
14695            });
14696
14697            let mut s = three_member_spec();
14698            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
14699            s.contratos = vec![contract_http(form, "catalog", "/x")];
14700            s.entrada = None;
14701            s.validate().unwrap_or_else(|e| {
14702                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
14703            });
14704        }
14705    }
14706
14707    #[test]
14708    fn rejects_empty_wit() {
14709        let mut s = three_member_spec();
14710        s.contratos.push(WitContract {
14711            de: "cart".into(),
14712            para: "catalog".into(),
14713            wit: String::new(),
14714            endpoint: None,
14715            subject: None,
14716            slot: None,
14717        });
14718        let err = s.validate().unwrap_err();
14719        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
14720    }
14721
14722    #[test]
14723    fn rejects_entrada_to_unknown_member() {
14724        let mut s = three_member_spec();
14725        s.entrada.as_mut().unwrap().para = "phantom".into();
14726        assert!(matches!(
14727            s.validate().unwrap_err(),
14728            AplicacaoError::EntradaMemberMissing { .. }
14729        ));
14730    }
14731
14732    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
14733
14734    #[test]
14735    fn rejects_entrada_para_empty() {
14736        // `:para ""` previously fell through to
14737        // `EntradaMemberMissing { para: "" }` because the validated
14738        // `:membros :caixa` set never contains the empty string. The
14739        // narrower `EntradaParaEmpty` diagnostic now names the
14740        // offending slot directly — same empty-first cascade
14741        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
14742        // `ContratoCaixaEmpty` establish on the peer name axes.
14743        let mut s = three_member_spec();
14744        s.entrada.as_mut().unwrap().para = String::new();
14745        let err = s.validate().unwrap_err();
14746        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
14747    }
14748
14749    #[test]
14750    fn rejects_entrada_para_with_uppercase() {
14751        // The canonical "I copied the Servico's TitleCase display
14752        // name from an ADR" typo. Until this gate landed `:para "Cart"`
14753        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
14754        // as "this caixa isn't in `:membros`" when the root cause is
14755        // "this `:para` value's shape can never legitimately match a
14756        // validated member (DNS-1123 labels are lowercase)". The
14757        // narrower diagnostic names the value verbatim plus the
14758        // parser-shaped reason.
14759        let mut s = three_member_spec();
14760        s.entrada.as_mut().unwrap().para = "Cart".into();
14761        let err = s.validate().unwrap_err();
14762        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
14763            panic!("expected EntradaParaInvalid, got other variant");
14764        };
14765        assert_eq!(para, "Cart");
14766        assert!(
14767            reason.contains("uppercase"),
14768            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
14769        );
14770    }
14771
14772    #[test]
14773    fn rejects_entrada_para_with_underscore() {
14774        // The canonical "I'm thinking of a Python module" leak —
14775        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
14776        let mut s = three_member_spec();
14777        s.entrada.as_mut().unwrap().para = "my_cart".into();
14778        let err = s.validate().unwrap_err();
14779        assert!(
14780            matches!(
14781                err,
14782                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
14783                    if para == "my_cart" && reason.contains('_')
14784            ),
14785            "got {err:?}"
14786        );
14787    }
14788
14789    #[test]
14790    fn rejects_entrada_para_with_dot() {
14791        // An `:entrada :para` value is a single DNS-1123 *label*, not
14792        // a subdomain — mirroring the `:membros :caixa` floor. The
14793        // strictest floor among the use sites wins.
14794        let mut s = three_member_spec();
14795        s.entrada.as_mut().unwrap().para = "team.cart".into();
14796        let err = s.validate().unwrap_err();
14797        assert!(
14798            matches!(
14799                err,
14800                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
14801                    if para == "team.cart" && reason.contains('.')
14802            ),
14803            "got {err:?}"
14804        );
14805    }
14806
14807    #[test]
14808    fn rejects_entrada_para_with_unicode() {
14809        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
14810        // (`xn--…`) before it reaches K8s.
14811        let mut s = three_member_spec();
14812        s.entrada.as_mut().unwrap().para = "café".into();
14813        let err = s.validate().unwrap_err();
14814        assert!(
14815            matches!(
14816                err,
14817                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
14818            ),
14819            "got {err:?}"
14820        );
14821    }
14822
14823    #[test]
14824    fn rejects_entrada_para_with_leading_hyphen() {
14825        // DNS-1123 boundary rule: labels must start and end with an
14826        // alphanumeric. K8s rejects `-cart` outright.
14827        let mut s = three_member_spec();
14828        s.entrada.as_mut().unwrap().para = "-cart".into();
14829        let err = s.validate().unwrap_err();
14830        assert!(
14831            matches!(
14832                err,
14833                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
14834                    if para == "-cart" && reason.contains("start and end")
14835            ),
14836            "got {err:?}"
14837        );
14838    }
14839
14840    #[test]
14841    fn rejects_entrada_para_with_trailing_hyphen() {
14842        // Symmetric boundary arm.
14843        let mut s = three_member_spec();
14844        s.entrada.as_mut().unwrap().para = "cart-".into();
14845        let err = s.validate().unwrap_err();
14846        assert!(
14847            matches!(
14848                err,
14849                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
14850                    if para == "cart-" && reason.contains("start and end")
14851            ),
14852            "got {err:?}"
14853        );
14854    }
14855
14856    #[test]
14857    fn rejects_entrada_para_too_long() {
14858        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
14859        // bytes per label. K8s rejects longer names at admission on
14860        // every `metadata.name` axis.
14861        let mut s = three_member_spec();
14862        s.entrada.as_mut().unwrap().para = "a".repeat(64);
14863        let err = s.validate().unwrap_err();
14864        assert!(
14865            matches!(
14866                err,
14867                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
14868                    if para.len() == 64 && reason.contains("max length")
14869            ),
14870            "got {err:?}"
14871        );
14872    }
14873
14874    #[test]
14875    fn entrada_para_empty_takes_precedence_over_invalid() {
14876        // Order pin: the `EntradaParaEmpty` arm fires before the
14877        // `EntradaParaInvalid` parse-side arm — same empty-first
14878        // cascade `validate_membro_caixa` / `validate_placement_cluster`
14879        // / `validate_contrato_caixa` already establish.
14880        let mut s = three_member_spec();
14881        s.entrada.as_mut().unwrap().para = String::new();
14882        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
14883    }
14884
14885    #[test]
14886    fn entrada_para_shape_fires_before_membership_lookup() {
14887        // The load-bearing pin: an invalid-shape `:para` surfaces its
14888        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
14889        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
14890        // an invalid-shape `:para` could never legitimately match any
14891        // member — the prior `EntradaMemberMissing` diagnostic framed
14892        // a structural impossibility as a graph-membership failure.
14893        let mut s = three_member_spec();
14894        s.entrada.as_mut().unwrap().para = "Cart".into();
14895        let err = s.validate().unwrap_err();
14896        assert!(
14897            matches!(
14898                err,
14899                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
14900            ),
14901            "got {err:?}"
14902        );
14903    }
14904
14905    #[test]
14906    fn entrada_para_shape_fires_before_host_gate() {
14907        // Per-`:entrada` order pin: the `:para` shape gate fires
14908        // before the `:host` gate, mirroring the existing
14909        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
14910        // ordering where the member-lookup arm preceded the host gate.
14911        // The shape gate slots ahead of that, so a malformed `:para`
14912        // surfaces its own diagnostic even when `:host` is also wrong.
14913        let mut s = three_member_spec();
14914        let e = s.entrada.as_mut().unwrap();
14915        e.para = "Cart".into();
14916        e.host = "BAD HOST".into();
14917        let err = s.validate().unwrap_err();
14918        assert!(
14919            matches!(
14920                err,
14921                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
14922            ),
14923            "got {err:?}"
14924        );
14925    }
14926
14927    #[test]
14928    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
14929        // Strict-improvement pin: a well-shaped `:para` that simply
14930        // isn't in `:membros` (a phantom reference — author meant to
14931        // add the member but didn't, or renamed and missed an
14932        // update) still surfaces `EntradaMemberMissing`, unchanged.
14933        // The shape gate only intercepts inputs that could never
14934        // legitimately match a validated member.
14935        let mut s = three_member_spec();
14936        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
14937        let err = s.validate().unwrap_err();
14938        assert!(
14939            matches!(
14940                err,
14941                AplicacaoError::EntradaMemberMissing { ref para }
14942                    if para == "phantom-shim"
14943            ),
14944            "got {err:?}"
14945        );
14946    }
14947
14948    #[test]
14949    fn entrada_para_invalid_diagnostic_carries_offending_para() {
14950        // The diagnostic-shape pin: the error names the offending
14951        // `:para` value verbatim plus a non-empty parser-shaped
14952        // reason, so the author can grep their caixa.lisp for
14953        // `:para "<name>"` and fix it in one edit. Same diagnostic
14954        // shape as `MembroCaixaInvalid` (3f9d7a0),
14955        // `PlacementClusterInvalid` (6c8c00b), and
14956        // `ContratoCaixaInvalid` (8d5af6b).
14957        let mut s = three_member_spec();
14958        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
14959        let err = s.validate().unwrap_err();
14960        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
14961            panic!("expected EntradaParaInvalid, got {err:?}");
14962        };
14963        assert_eq!(para, "BAD_NAME");
14964        assert!(
14965            !reason.is_empty(),
14966            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
14967        );
14968    }
14969
14970    #[test]
14971    fn accepts_canonical_entrada_para_forms() {
14972        // Positive-control sweep covering the DNS-1123 label shapes a
14973        // caixa author is realistically going to write on `:entrada
14974        // :para`. Pin every leg so a future tightening that bans
14975        // (e.g.) digit-start identifiers surfaces here, mirroring
14976        // `accepts_canonical_membro_caixa_forms` and
14977        // `accepts_canonical_contrato_caixa_forms` on the peer name
14978        // axes.
14979        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
14980            let mut s = three_member_spec();
14981            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
14982            s.contratos = vec![contract_http(form, "catalog", "/x")];
14983            s.entrada = Some(Entrada {
14984                host: "checkout.quero.cloud".into(),
14985                para: form.into(),
14986                paths: vec!["/api".into()],
14987                port: 8080,
14988            });
14989            s.validate().unwrap_or_else(|e| {
14990                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
14991            });
14992        }
14993    }
14994
14995    #[test]
14996    fn rejects_replicated_without_clusters() {
14997        let mut s = three_member_spec();
14998        s.placement.clusters = vec![];
14999        assert!(matches!(
15000            s.validate().unwrap_err(),
15001            AplicacaoError::PlacementWithoutClusters { .. }
15002        ));
15003    }
15004
15005    #[test]
15006    fn rejects_sharded_without_key() {
15007        let mut s = three_member_spec();
15008        s.placement.estrategia = PlacementStrategy::Sharded;
15009        s.placement.shard_key = None;
15010        s.placement.clusters = vec!["rio".into()];
15011        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
15012    }
15013
15014    #[test]
15015    fn sharded_with_key_validates() {
15016        let mut s = three_member_spec();
15017        s.placement.estrategia = PlacementStrategy::Sharded;
15018        s.placement.shard_key = Some("$tenantId".into());
15019        s.validate().unwrap();
15020    }
15021
15022    #[test]
15023    fn round_trip_via_json_preserves_shape() {
15024        let s = three_member_spec();
15025        let json = serde_json::to_string(&s.membros).unwrap();
15026        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
15027        assert_eq!(back, s.membros);
15028
15029        let json = serde_json::to_string(&s.contratos).unwrap();
15030        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
15031        assert_eq!(back, s.contratos);
15032
15033        let json = serde_json::to_string(&s.placement).unwrap();
15034        let back: Placement = serde_json::from_str(&json).unwrap();
15035        assert_eq!(back, s.placement);
15036
15037        let json = serde_json::to_string(&s.entrada).unwrap();
15038        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
15039        assert_eq!(back, s.entrada);
15040    }
15041
15042    #[test]
15043    fn rate_limit_round_trip_seconds() {
15044        let policy = MeshPolicy {
15045            rate_limit: Some(RateLimit {
15046                rate: 100,
15047                window: Duration::from_secs(1),
15048            }),
15049            ..Default::default()
15050        };
15051        let json = serde_json::to_string(&policy).unwrap();
15052        assert!(json.contains("\"100/s\""));
15053        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15054        assert_eq!(back.rate_limit.unwrap().rate, 100);
15055        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
15056    }
15057
15058    #[test]
15059    fn rate_limit_round_trip_minutes() {
15060        let policy = MeshPolicy {
15061            rate_limit: Some(RateLimit {
15062                rate: 5000,
15063                window: Duration::from_secs(60),
15064            }),
15065            ..Default::default()
15066        };
15067        let json = serde_json::to_string(&policy).unwrap();
15068        assert!(json.contains("\"5000/m\""));
15069    }
15070
15071    #[test]
15072    fn circuit_breaker_round_trip() {
15073        let policy = MeshPolicy {
15074            circuit_breaker: Some(CircuitBreaker {
15075                max_failures: 5,
15076                window: Duration::from_secs(60),
15077            }),
15078            ..Default::default()
15079        };
15080        let json = serde_json::to_string(&policy).unwrap();
15081        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15082        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
15083        assert_eq!(
15084            back.circuit_breaker.unwrap().window,
15085            Duration::from_secs(60)
15086        );
15087    }
15088
15089    #[test]
15090    fn rejects_http_contrato_without_endpoint() {
15091        let mut s = three_member_spec();
15092        s.contratos.push(WitContract {
15093            de: "cart".into(),
15094            para: "catalog".into(),
15095            wit: "wasi:http/proxy".into(),
15096            endpoint: None,
15097            subject: None,
15098            slot: None,
15099        });
15100        let err = s.validate().unwrap_err();
15101        assert!(matches!(
15102            err,
15103            AplicacaoError::ContratoMissingTarget {
15104                expected: WitTarget::HTTP_FIELD_NAME,
15105                ..
15106            }
15107        ));
15108    }
15109
15110    #[test]
15111    fn rejects_http_contrato_with_subject() {
15112        let mut s = three_member_spec();
15113        s.contratos.push(WitContract {
15114            de: "cart".into(),
15115            para: "catalog".into(),
15116            wit: "wasi:http/proxy".into(),
15117            endpoint: Some("/x".into()),
15118            subject: Some("not.allowed.here".into()),
15119            slot: None,
15120        });
15121        let err = s.validate().unwrap_err();
15122        assert!(matches!(
15123            err,
15124            AplicacaoError::ContratoWrongTarget {
15125                expected: WitTarget::HTTP_FIELD_NAME,
15126                ..
15127            }
15128        ));
15129    }
15130
15131    #[test]
15132    fn rejects_pubsub_contrato_without_subject() {
15133        let mut s = three_member_spec();
15134        s.contratos.push(WitContract {
15135            de: "cart".into(),
15136            para: "catalog".into(),
15137            wit: "nats:pub-sub".into(),
15138            endpoint: None,
15139            subject: None,
15140            slot: None,
15141        });
15142        let err = s.validate().unwrap_err();
15143        assert!(matches!(
15144            err,
15145            AplicacaoError::ContratoMissingTarget {
15146                expected: WitTarget::PUBSUB_FIELD_NAME,
15147                ..
15148            }
15149        ));
15150    }
15151
15152    #[test]
15153    fn rejects_pubsub_contrato_with_endpoint() {
15154        let mut s = three_member_spec();
15155        s.contratos.push(WitContract {
15156            de: "cart".into(),
15157            para: "catalog".into(),
15158            wit: "kafka:topic".into(),
15159            endpoint: Some("/wrong".into()),
15160            subject: Some("topic.x".into()),
15161            slot: None,
15162        });
15163        let err = s.validate().unwrap_err();
15164        assert!(matches!(
15165            err,
15166            AplicacaoError::ContratoWrongTarget {
15167                expected: WitTarget::PUBSUB_FIELD_NAME,
15168                ..
15169            }
15170        ));
15171    }
15172
15173    #[test]
15174    fn rejects_store_contrato_without_slot() {
15175        let mut s = three_member_spec();
15176        s.contratos.push(WitContract {
15177            de: "cart".into(),
15178            para: "catalog".into(),
15179            wit: "wasi:keyvalue/store".into(),
15180            endpoint: None,
15181            subject: None,
15182            slot: None,
15183        });
15184        let err = s.validate().unwrap_err();
15185        assert!(matches!(
15186            err,
15187            AplicacaoError::ContratoMissingTarget {
15188                expected: WitTarget::STORE_FIELD_NAME,
15189                ..
15190            }
15191        ));
15192    }
15193
15194    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
15195
15196    #[test]
15197    fn rejects_http_contrato_with_empty_endpoint() {
15198        // `Some("")` for an HTTP endpoint passes the presence check
15199        // (target() previously returned WitTarget::Http { endpoint: "" })
15200        // but renders as a `path: ""` Cilium L7 rule that matches no
15201        // traffic. Same value-shape footgun closed for :entrada :paths
15202        // entries (eb3456d).
15203        let mut s = three_member_spec();
15204        s.contratos.push(WitContract {
15205            de: "cart".into(),
15206            para: "catalog".into(),
15207            wit: "wasi:http/proxy".into(),
15208            endpoint: Some(String::new()),
15209            subject: None,
15210            slot: None,
15211        });
15212        let err = s.validate().unwrap_err();
15213        assert!(
15214            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
15215                if de == "cart" && para == "catalog"),
15216            "got {err:?}"
15217        );
15218    }
15219
15220    #[test]
15221    fn rejects_http_contrato_with_relative_endpoint() {
15222        // Cilium L7 :path + Gateway API PathPrefix both require a
15223        // leading `/`. Same shape required of :entrada :paths
15224        // (eb3456d). Lifted into target() so every consumer of the
15225        // typed WitTarget view inherits the guarantee.
15226        let mut s = three_member_spec();
15227        s.contratos.push(WitContract {
15228            de: "cart".into(),
15229            para: "catalog".into(),
15230            wit: "wasi:http/proxy".into(),
15231            endpoint: Some("products/:id".into()),
15232            subject: None,
15233            slot: None,
15234        });
15235        let err = s.validate().unwrap_err();
15236        assert!(
15237            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
15238                if endpoint == "products/:id"),
15239            "got {err:?}"
15240        );
15241    }
15242
15243    #[test]
15244    fn rejects_pubsub_contrato_with_empty_subject() {
15245        // NATS / Kafka publish without a subject is a no-op subscribe;
15246        // never the author's intent. Same empty-string rejection as
15247        // :membros :caixa, :placement :clusters entries, :entrada
15248        // :paths entries — every value carried by every typed slot is
15249        // value-shape-checked at validate().
15250        let mut s = three_member_spec();
15251        s.contratos.push(WitContract {
15252            de: "cart".into(),
15253            para: "catalog".into(),
15254            wit: "nats:pub-sub".into(),
15255            endpoint: None,
15256            subject: Some(String::new()),
15257            slot: None,
15258        });
15259        let err = s.validate().unwrap_err();
15260        assert!(
15261            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
15262                if de == "cart" && para == "catalog"),
15263            "got {err:?}"
15264        );
15265    }
15266
15267    #[test]
15268    fn rejects_store_contrato_with_empty_slot() {
15269        // An empty slot template addresses the bucket root, defeating
15270        // the per-key isolation the slot exists for — a footgun on
15271        // `wasi:keyvalue/store` whose closest analog is the empty
15272        // shard-key rejected on :placement Sharded (c7c7799).
15273        let mut s = three_member_spec();
15274        s.contratos.push(WitContract {
15275            de: "cart".into(),
15276            para: "catalog".into(),
15277            wit: "wasi:keyvalue/store".into(),
15278            endpoint: None,
15279            subject: None,
15280            slot: Some(String::new()),
15281        });
15282        let err = s.validate().unwrap_err();
15283        assert!(
15284            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
15285                if de == "cart" && para == "catalog"),
15286            "got {err:?}"
15287        );
15288    }
15289
15290    #[test]
15291    fn http_contrato_root_endpoint_validates() {
15292        // Pin the boundary case: a single-`/` endpoint is the catch-all
15293        // form the Gateway HTTPRoute renderer falls back to when
15294        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
15295        // must remain a valid contrato endpoint too.
15296        let mut s = three_member_spec();
15297        s.contratos.push(contract_http("cart", "catalog", "/"));
15298        s.validate().unwrap();
15299    }
15300
15301    // ── :contratos :endpoint value-shape gate ────────────────────────────
15302    //
15303    // Mirrors the `:entrada :paths` value-shape suite on the peer
15304    // HTTP-path axis. Until this gate landed `WitContract::target()`
15305    // only refused the empty string + the missing-leading-`/` form
15306    // (c4213a4); a structurally invalid endpoint passed validate and
15307    // landed verbatim as a Cilium L7 `path:` rule
15308    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
15309    // traffic or was rejected at apply time by Cilium policy admission.
15310    // Every authoring footgun the K8s Gateway API webhook / Cilium
15311    // policy validator would catch on admission now becomes a caixa-
15312    // build-time `ContratoEndpointInvalid` with the offending
15313    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
15314    // shape as `EntradaPathInvalid` on the sibling axis; same shared
15315    // predicate (`crate::render::is_gateway_api_http_path`) ensures
15316    // drift between the two axes' rule enforcement is a build error
15317    // at the predicate.
15318
15319    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
15320        // Fresh spec per call so the would-be-duplicate edge
15321        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
15322        // `three_member_spec`'s pre-existing
15323        // `(cart, catalog, …, /products/:id)` entry — only the
15324        // endpoint payload differs.
15325        let mut s = three_member_spec();
15326        s.contratos.push(contract_http("cart", "catalog", ep));
15327        s.validate().unwrap_err()
15328    }
15329
15330    #[test]
15331    fn rejects_http_contrato_endpoint_with_query() {
15332        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
15333        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
15334        // rule the L7 matcher would never satisfy.
15335        let err = contrato_endpoint_err("/charge?token=X");
15336        assert!(
15337            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15338                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
15339            "got {err:?}"
15340        );
15341    }
15342
15343    #[test]
15344    fn rejects_http_contrato_endpoint_with_fragment() {
15345        let err = contrato_endpoint_err("/charge#frag");
15346        assert!(
15347            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15348                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
15349            "got {err:?}"
15350        );
15351    }
15352
15353    #[test]
15354    fn rejects_http_contrato_endpoint_with_whitespace() {
15355        let err = contrato_endpoint_err("/foo bar");
15356        assert!(
15357            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15358                if endpoint == "/foo bar" && reason.contains("whitespace")),
15359            "got {err:?}"
15360        );
15361    }
15362
15363    #[test]
15364    fn rejects_http_contrato_endpoint_with_control_char() {
15365        let err = contrato_endpoint_err("/api/\x01bar");
15366        assert!(
15367            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15368                if endpoint == "/api/\x01bar" && reason.contains("control character")),
15369            "got {err:?}"
15370        );
15371    }
15372
15373    #[test]
15374    fn rejects_http_contrato_endpoint_with_non_ascii() {
15375        let err = contrato_endpoint_err("/api/café");
15376        assert!(
15377            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15378                if endpoint == "/api/café" && reason.contains("non-ASCII")),
15379            "got {err:?}"
15380        );
15381    }
15382
15383    #[test]
15384    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
15385        let err = contrato_endpoint_err("/api//cart");
15386        assert!(
15387            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15388                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
15389            "got {err:?}"
15390        );
15391    }
15392
15393    #[test]
15394    fn rejects_http_contrato_endpoint_with_dot_segment() {
15395        let err = contrato_endpoint_err("/api/./cart");
15396        assert!(
15397            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15398                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
15399            "got {err:?}"
15400        );
15401    }
15402
15403    #[test]
15404    fn rejects_http_contrato_endpoint_with_parent_segment() {
15405        // Path-traversal in a contrato endpoint is the canonical
15406        // "L7 rule that the workload's HTTP server's path-resolution
15407        // logic interprets differently than the policy enforcer"
15408        // footgun. Rejected outright at validate time.
15409        let err = contrato_endpoint_err("/api/../etc");
15410        assert!(
15411            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15412                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
15413            "got {err:?}"
15414        );
15415    }
15416
15417    #[test]
15418    fn rejects_http_contrato_endpoint_too_long() {
15419        // 1025-byte endpoint — one over the Gateway API
15420        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
15421        // path matcher has no inherent length limit but the policy
15422        // CR itself rides through the K8s apiserver, which enforces
15423        // ConfigMap-shaped limits; sharing the Gateway API cap is the
15424        // conservative floor.
15425        let big = format!("/api/{}", "a".repeat(1020));
15426        assert_eq!(big.len(), 1025);
15427        let err = contrato_endpoint_err(&big);
15428        assert!(
15429            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15430                if endpoint == &big && reason.contains("max length of 1024")),
15431            "got {err:?}"
15432        );
15433    }
15434
15435    #[test]
15436    fn http_contrato_endpoint_max_length_validates() {
15437        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
15438        // in the cap surfaces here and at
15439        // `rejects_http_contrato_endpoint_too_long` simultaneously,
15440        // mirroring `entrada_path_max_length_validates` on the peer
15441        // axis.
15442        let big = format!("/api/{}", "a".repeat(1019));
15443        assert_eq!(big.len(), 1024);
15444        let mut s = three_member_spec();
15445        s.contratos.push(contract_http("cart", "catalog", &big));
15446        s.validate().unwrap();
15447    }
15448
15449    #[test]
15450    fn http_contrato_endpoint_accepts_canonical_forms() {
15451        // Positive-set sweep: every canonical HTTP-path shape the
15452        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
15453        // plain paths, hidden-file-style `.config` segments distinct
15454        // from the `.` segment, digit-bearing segments, the canonical
15455        // route-template `:param` form, trailing-slash form,
15456        // percent-encoded segments, the `/foo..bar` interior-`..`-
15457        // substring forms that are NOT `..` segments) must remain a
15458        // valid contrato endpoint too. Drift between this list and
15459        // the entrada path positive sweep surfaces at the shared
15460        // `is_gateway_api_http_path` substrate-side suite — one
15461        // source of truth. Uses a fresh `(payment, catalog)` edge so
15462        // none of the swept endpoints collide with the pre-existing
15463        // `(cart, catalog, /products/:id)` / `(cart, payment,
15464        // /charge)` entries in `three_member_spec`.
15465        for ep in [
15466            "/",
15467            "/charge",
15468            "/v1/charge",
15469            "/api/.config",
15470            "/products/:id",
15471            "/api/cart/",
15472            "/api/caf%C3%A9",
15473            "/foo..bar",
15474            "/...",
15475        ] {
15476            let mut s = three_member_spec();
15477            s.contratos.push(contract_http("payment", "catalog", ep));
15478            s.validate()
15479                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
15480        }
15481    }
15482
15483    #[test]
15484    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
15485        // Ordering pin: `ContratoEndpointEmpty` is the more self-
15486        // locating diagnostic on `""` and must lead — the value-
15487        // shape gate is only reached after the empty-check fires.
15488        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
15489        // on the peer axis.
15490        let mut s = three_member_spec();
15491        s.contratos.push(WitContract {
15492            de: "cart".into(),
15493            para: "catalog".into(),
15494            wit: "wasi:http/proxy".into(),
15495            endpoint: Some(String::new()),
15496            subject: None,
15497            slot: None,
15498        });
15499        let err = s.validate().unwrap_err();
15500        assert!(
15501            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
15502            "got {err:?}"
15503        );
15504    }
15505
15506    #[test]
15507    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
15508        // Ordering pin: an endpoint without a leading `/` surfaces the
15509        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
15510        // value-shape gate is only consulted on endpoints that already
15511        // satisfy the absolute-prefix invariant. Mirrors
15512        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
15513        let err = contrato_endpoint_err("bad path");
15514        assert!(
15515            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
15516                if endpoint == "bad path"),
15517            "got {err:?}"
15518        );
15519    }
15520
15521    #[test]
15522    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
15523        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
15524        // `:para` + a non-empty reason flow through verbatim so the
15525        // author can grep their caixa.lisp for the offending contrato
15526        // block and fix it in one edit. Same shape as
15527        // `entrada_path_diagnostic_carries_offending_path`.
15528        let err = contrato_endpoint_err("/api?q=1");
15529        match err {
15530            AplicacaoError::ContratoEndpointInvalid {
15531                de,
15532                para,
15533                endpoint,
15534                reason,
15535            } => {
15536                assert_eq!(de, "cart");
15537                assert_eq!(para, "catalog");
15538                assert_eq!(endpoint, "/api?q=1");
15539                assert!(!reason.is_empty(), "reason field must be non-empty");
15540            }
15541            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
15542        }
15543    }
15544
15545    #[test]
15546    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
15547        // The compounding theorem: every &str inside a WitTarget
15548        // returned by target() is non-empty (and absolute, for Http).
15549        // Renderers downstream of typed_view() can rely on this
15550        // without re-checking — the type system carries the proof.
15551        let http = contract_http("cart", "catalog", "/x");
15552        match http.target().unwrap() {
15553            WitTarget::Http { endpoint } => {
15554                assert!(!endpoint.is_empty());
15555                assert!(endpoint.starts_with('/'));
15556            }
15557            other => panic!("expected Http, got {other:?}"),
15558        }
15559        let nats = WitContract {
15560            de: "a".into(),
15561            para: "b".into(),
15562            wit: "nats:pub-sub".into(),
15563            endpoint: None,
15564            subject: Some("topic.x".into()),
15565            slot: None,
15566        };
15567        match nats.target().unwrap() {
15568            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
15569            other => panic!("expected PubSub, got {other:?}"),
15570        }
15571        let kv = WitContract {
15572            de: "a".into(),
15573            para: "b".into(),
15574            wit: "wasi:keyvalue/store".into(),
15575            endpoint: None,
15576            subject: None,
15577            slot: Some("checkout/$orderId".into()),
15578        };
15579        match kv.target().unwrap() {
15580            WitTarget::Store { slot } => assert!(!slot.is_empty()),
15581            other => panic!("expected Store, got {other:?}"),
15582        }
15583    }
15584
15585    #[test]
15586    fn target_diagnostic_names_offending_endpoint_value() {
15587        // When the malformed endpoint string is non-trivial, the
15588        // diagnostic carries the actual value back to the author —
15589        // not a generic "endpoint malformed" error.
15590        let bad = WitContract {
15591            de: "src".into(),
15592            para: "dst".into(),
15593            wit: "wasi:http/proxy".into(),
15594            endpoint: Some("api/v1/charge".into()),
15595            subject: None,
15596            slot: None,
15597        };
15598        match bad.target().unwrap_err() {
15599            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
15600                assert_eq!(de, "src");
15601                assert_eq!(para, "dst");
15602                assert_eq!(endpoint, "api/v1/charge");
15603            }
15604            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
15605        }
15606    }
15607
15608    #[test]
15609    fn rejects_unknown_wit_with_target_set() {
15610        let mut s = three_member_spec();
15611        s.contratos.push(WitContract {
15612            de: "cart".into(),
15613            para: "catalog".into(),
15614            wit: "custom:exchange".into(),
15615            endpoint: Some("/leaked".into()),
15616            subject: None,
15617            slot: None,
15618        });
15619        let err = s.validate().unwrap_err();
15620        assert!(matches!(
15621            err,
15622            AplicacaoError::ContratoWrongTarget {
15623                expected: WitTarget::CAPABILITY_EXPECTED,
15624                ..
15625            }
15626        ));
15627    }
15628
15629    #[test]
15630    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
15631        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
15632        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
15633        // fourth arm of the same "which payload field name goes in the
15634        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
15635        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15636        // consts cover on the peer HTTP / PubSub / Store arms
15637        // (`wit_target_field_name_pins_per_variant`). Until this lift
15638        // landed the byte-string sat twice — once inline in the
15639        // [`WitContract::target`] Capability-arm rejection at the
15640        // production dispatch, once in `rejects_unknown_wit_with_target_set`
15641        // pinning against the same literal — with no compile-time link
15642        // between them. Same "one canonical declaration, next to the
15643        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
15644        // lift established for the payload-less arm's human-readable
15645        // label axis; this test is the shape peer of
15646        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
15647        // pair (routes-through-const + scalar-value pin) on the
15648        // wrong-target diagnostic-scalar axis.
15649        //
15650        // Fail-before-pass-after was verified locally by mutating the
15651        // const declaration to `"capability"` — the scalar-value pin
15652        // below fires (`"capability" != "none"`) and the routes-through
15653        // assertion below still holds (production and const walk in
15654        // lockstep), which is the correct behavior: a rename on the
15655        // const drifts here first, not at a downstream consumer.
15656        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
15657
15658        let mut s = three_member_spec();
15659        s.contratos.push(WitContract {
15660            de: "cart".into(),
15661            para: "catalog".into(),
15662            wit: "custom:exchange".into(),
15663            endpoint: Some("/leaked".into()),
15664            subject: None,
15665            slot: None,
15666        });
15667        match s.validate().unwrap_err() {
15668            AplicacaoError::ContratoWrongTarget { expected, .. } => {
15669                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
15670            }
15671            other => panic!("expected ContratoWrongTarget, got {other:?}"),
15672        }
15673    }
15674
15675    #[test]
15676    fn unknown_wit_capability_only_validates() {
15677        let mut s = three_member_spec();
15678        s.contratos.push(WitContract {
15679            de: "cart".into(),
15680            para: "catalog".into(),
15681            // A WIT world we haven't yet shaped — accept it as a typed
15682            // capability edge so authors aren't blocked while the WIT
15683            // registry catches up. No payload field may be carried.
15684            wit: "custom:exchange".into(),
15685            endpoint: None,
15686            subject: None,
15687            slot: None,
15688        });
15689        s.validate().unwrap();
15690        let added = s.contratos.last().unwrap();
15691        assert_eq!(added.target().unwrap(), WitTarget::Capability);
15692    }
15693
15694    #[test]
15695    fn target_typed_view_round_trips_each_shape() {
15696        let http = contract_http("cart", "catalog", "/products/:id");
15697        assert_eq!(
15698            http.target().unwrap(),
15699            WitTarget::Http {
15700                endpoint: "/products/:id"
15701            }
15702        );
15703        let nats = WitContract {
15704            de: "a".into(),
15705            para: "b".into(),
15706            wit: "nats:pub-sub".into(),
15707            endpoint: None,
15708            subject: Some("topic.x".into()),
15709            slot: None,
15710        };
15711        assert_eq!(
15712            nats.target().unwrap(),
15713            WitTarget::PubSub { subject: "topic.x" }
15714        );
15715        let kv = WitContract {
15716            de: "a".into(),
15717            para: "b".into(),
15718            wit: "wasi:keyvalue/store".into(),
15719            endpoint: None,
15720            subject: None,
15721            slot: Some("checkout/$orderId".into()),
15722        };
15723        assert_eq!(
15724            kv.target().unwrap(),
15725            WitTarget::Store {
15726                slot: "checkout/$orderId"
15727            }
15728        );
15729    }
15730
15731    #[test]
15732    fn wit_contract_kind_predicates() {
15733        let http = contract_http("a", "b", "/x");
15734        assert!(http.is_http());
15735        assert!(!http.is_pubsub());
15736        assert!(!http.is_store());
15737        assert!(!http.is_capability());
15738
15739        let nats = WitContract {
15740            de: "a".into(),
15741            para: "b".into(),
15742            wit: "nats:pub-sub".into(),
15743            endpoint: None,
15744            subject: Some("topic.x".into()),
15745            slot: None,
15746        };
15747        assert!(nats.is_pubsub());
15748        assert!(!nats.is_http());
15749        assert!(!nats.is_capability());
15750
15751        let kv = WitContract {
15752            de: "a".into(),
15753            para: "b".into(),
15754            wit: "wasi:keyvalue/store".into(),
15755            endpoint: None,
15756            subject: None,
15757            slot: Some("checkout/$orderId".into()),
15758        };
15759        assert!(kv.is_store());
15760        assert!(!kv.is_http());
15761        assert!(!kv.is_capability());
15762
15763        // Fourth arm on the paired closed-set predicate family: the
15764        // payload-less capability edge that projects to the payload-
15765        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
15766        // Extends the 3-arm predicate sweep this test opened to cover
15767        // the closed 4-way partition [`WitContract::is_capability`]
15768        // closes on the pre-projection WIT-shape axis, matched with the
15769        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
15770        // 4-arm predicate set.
15771        let cap = WitContract {
15772            de: "a".into(),
15773            para: "b".into(),
15774            wit: "custom:capability-only".into(),
15775            endpoint: None,
15776            subject: None,
15777            slot: None,
15778        };
15779        assert!(cap.is_capability());
15780        assert!(!cap.is_http());
15781        assert!(!cap.is_pubsub());
15782        assert!(!cap.is_store());
15783    }
15784
15785    // ── :contratos :wit value-shape gate ─────────────────────────────────
15786    //
15787    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
15788    // dispatch-discriminator axis. Until this gate landed
15789    // `WitContract::target()` accepted any non-empty string and
15790    // silently demoted unrecognized shapes to a capability-only L4
15791    // edge — the canonical "I thought I had L7 HTTP routing, got
15792    // L4-only" footgun. Every authoring footgun the WIT registry's
15793    // own grammar rejects (uppercase, hyphen-for-colon typo,
15794    // whitespace, empty package, doubled `@`, …) now becomes a
15795    // caixa-build-time `ContratoWitInvalid` with the offending
15796    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
15797    // as `ContratoEndpointInvalid` on the sibling axis; same shared
15798    // predicate (`crate::render::is_wit_world_ref`) ensures drift
15799    // between any two axes' rule enforcement is a build error at the
15800    // predicate, not piecemeal across renderers.
15801
15802    fn contrato_wit_err(wit: &str) -> AplicacaoError {
15803        // Fresh spec per call so the new contract doesn't collide on
15804        // identity with `three_member_spec`'s pre-existing entries.
15805        // The new edge uses `(payment, catalog)` — a pair the fixture
15806        // doesn't already declare — with no payload field set, so the
15807        // wit-shape gate fires before any payload-shape arm.
15808        let mut s = three_member_spec();
15809        s.contratos.push(WitContract {
15810            de: "payment".into(),
15811            para: "catalog".into(),
15812            wit: wit.into(),
15813            endpoint: None,
15814            subject: None,
15815            slot: None,
15816        });
15817        s.validate().unwrap_err()
15818    }
15819
15820    #[test]
15821    fn rejects_wit_with_uppercase_namespace() {
15822        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
15823        // didn't match the lowercase `wasi:http/` prefix is_http() keys
15824        // off, so the dispatch fell through to the capability arm and
15825        // the contract silently rendered as an L4-only Cilium edge.
15826        // The new gate surfaces the uppercase typo at validate time
15827        // with the offending `:wit` named.
15828        let err = contrato_wit_err("WASI:http/proxy");
15829        assert!(
15830            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15831                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
15832            "got {err:?}"
15833        );
15834    }
15835
15836    #[test]
15837    fn rejects_wit_with_hyphen_for_colon_typo() {
15838        // The canonical "I forgot the `:` separator" typo — pre-gate
15839        // this passed as Capability silently, so the renderer emitted
15840        // an L4-only policy where the author expected L7 HTTP rules.
15841        let err = contrato_wit_err("wasi-http/proxy");
15842        assert!(
15843            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15844                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
15845            "got {err:?}"
15846        );
15847    }
15848
15849    #[test]
15850    fn rejects_wit_with_multiple_colons() {
15851        // Doubled `:` — the namespace/package split has nowhere to
15852        // anchor, so the dispatch silently demotes to Capability.
15853        let err = contrato_wit_err("wasi:http:proxy");
15854        assert!(
15855            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15856                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
15857            "got {err:?}"
15858        );
15859    }
15860
15861    #[test]
15862    fn rejects_wit_with_empty_package() {
15863        // `wasi:` — namespace alone with no package. Pre-gate this
15864        // failed neither the is_http nor is_pubsub nor is_store
15865        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
15866        // a bare `wasi:`), so it silently demoted to Capability.
15867        let err = contrato_wit_err("wasi:");
15868        assert!(
15869            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15870                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
15871            "got {err:?}"
15872        );
15873    }
15874
15875    #[test]
15876    fn rejects_wit_with_underscore() {
15877        // Underscore — WIT identifiers are kebab-case, same rule
15878        // DNS-1123 enforces on its peer axes. The diagnostic carries
15879        // the explicit "use `-` instead" remediation.
15880        let err = contrato_wit_err("wasi:http_proxy");
15881        assert!(
15882            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15883                if wit == "wasi:http_proxy" && reason.contains('_')),
15884            "got {err:?}"
15885        );
15886    }
15887
15888    #[test]
15889    fn rejects_wit_with_whitespace() {
15890        // Whitespace mid-token — the prefix check matches but the
15891        // package-and-onward parse silently demoted to Capability.
15892        let err = contrato_wit_err("wasi:http proxy");
15893        assert!(
15894            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15895                if wit == "wasi:http proxy" && reason.contains("whitespace")),
15896            "got {err:?}"
15897        );
15898    }
15899
15900    #[test]
15901    fn rejects_wit_with_non_ascii() {
15902        // Un-percent-encoded non-ASCII byte — the canonical "I copied
15903        // the package name from a doc with smart quotes / accented
15904        // characters" footgun.
15905        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
15906        assert!(
15907            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15908                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
15909            "got {err:?}"
15910        );
15911    }
15912
15913    #[test]
15914    fn rejects_wit_with_consecutive_hyphens() {
15915        // `pub--sub` — WIT identifiers join words with single hyphens.
15916        let err = contrato_wit_err("nats:pub--sub");
15917        assert!(
15918            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15919                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
15920            "got {err:?}"
15921        );
15922    }
15923
15924    #[test]
15925    fn rejects_wit_with_trailing_at_no_version() {
15926        // `wasi:http/proxy@` — the version-suffix author started to
15927        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
15928        // parser would reject this; surface it at validate time.
15929        let err = contrato_wit_err("wasi:http/proxy@");
15930        assert!(
15931            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15932                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
15933            "got {err:?}"
15934        );
15935    }
15936
15937    #[test]
15938    fn rejects_wit_too_long() {
15939        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
15940        // The legitimate-shape arms all pass (lowercase, single `:`,
15941        // kebab-case identifiers); only the cap arm fires. Surfaces
15942        // the paste-from-binary / accidental-multi-line-blob landing
15943        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
15944        // on the peer axis.
15945        let big = format!("wasi:{}", "a".repeat(124));
15946        assert_eq!(big.len(), 129);
15947        let err = contrato_wit_err(&big);
15948        assert!(
15949            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
15950                if wit == &big && reason.contains("max length of 128")),
15951            "got {err:?}"
15952        );
15953    }
15954
15955    #[test]
15956    fn wit_max_length_validates() {
15957        // 128-byte WIT reference — exactly the cap. Boundary pin:
15958        // drift in the cap surfaces here and at `rejects_wit_too_long`
15959        // simultaneously, mirroring
15960        // `http_contrato_endpoint_max_length_validates` on the peer
15961        // axis.
15962        let big = format!("wasi:{}", "a".repeat(123));
15963        assert_eq!(big.len(), 128);
15964        let mut s = three_member_spec();
15965        s.contratos.push(WitContract {
15966            de: "payment".into(),
15967            para: "catalog".into(),
15968            wit: big,
15969            endpoint: None,
15970            subject: None,
15971            slot: None,
15972        });
15973        s.validate().unwrap();
15974    }
15975
15976    #[test]
15977    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
15978        // Positive-set sweep through the AplicacaoSpec::validate
15979        // surface (rather than the substrate-side predicate directly)
15980        // — pins every shape the existing test fixtures + the
15981        // checkout-aplicacao example carry, so the gate's accept-set
15982        // matches the substrate's emit-set. Drift between this list
15983        // and `render::tests::wit_world_ref_accepts_canonical_forms`
15984        // surfaces at the substrate layer's positive sweep — one
15985        // source of truth for the rule.
15986        for wit in [
15987            "wasi:http/proxy",
15988            "wasi:keyvalue/store",
15989            "nats:pub-sub",
15990            "kafka:topic",
15991            "custom:exchange",
15992            "pleme:cap/audit",
15993            "wasi:http/proxy@0.2.0",
15994        ] {
15995            // Payload field paired to the dispatched WIT shape so the
15996            // shape-↔-target arm doesn't fire instead of the wit-shape
15997            // arm we're exercising. Routes off the same
15998            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
15999            // `wit_shape_is_store` free functions the production
16000            // `WitContract::is_http` / `is_pubsub` / `is_store`
16001            // methods delegate to (both consult the lifted
16002            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
16003            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
16004            // future prefix addition to the routing accept-set
16005            // reaches this test's payload-dispatch arm by
16006            // construction — no per-test-site drift can hide a
16007            // shape-→-target-slot mismatch that would silently
16008            // demote a canonical `:wit` value to the
16009            // `(None, None, None)` capability-only arm and let the
16010            // `AplicacaoSpec::validate` positive sweep pass on a
16011            // shape it should exercise as HTTP / pub-sub / store.
16012            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
16013                (Some("/x".into()), None, None)
16014            } else if wit_shape_is_pubsub(wit) {
16015                (None, Some("topic.x".into()), None)
16016            } else if wit_shape_is_store(wit) {
16017                (None, None, Some("bucket/$key".into()))
16018            } else {
16019                (None, None, None)
16020            };
16021            let mut s = three_member_spec();
16022            s.contratos.push(WitContract {
16023                de: "payment".into(),
16024                para: "catalog".into(),
16025                wit: wit.into(),
16026                endpoint,
16027                subject,
16028                slot,
16029            });
16030            s.validate()
16031                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
16032        }
16033    }
16034
16035    #[test]
16036    fn wit_shape_predicates_accept_canonical_prefix_set() {
16037        // Positive-set sweep pinning every prefix in
16038        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
16039        // WIT_STORE_SHAPE_PREFIXES against the three free-function
16040        // dispatch predicates. The six prefixes are the load-bearing
16041        // routing keys the substrate's WIT-shape dispatch consults
16042        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
16043        // key/value-store-slot admission); any drift between the
16044        // free-function accept-set and this list surfaces here
16045        // rather than at apply time as a silent
16046        // shape-→-capability-only demotion.
16047        assert!(wit_shape_is_http("wasi:http/proxy"));
16048        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
16049        assert!(wit_shape_is_http("http:incoming"));
16050
16051        assert!(wit_shape_is_pubsub("nats:pub-sub"));
16052        assert!(wit_shape_is_pubsub("kafka:topic"));
16053
16054        assert!(wit_shape_is_store("wasi:keyvalue/store"));
16055        assert!(wit_shape_is_store("kv:cache/session"));
16056    }
16057
16058    #[test]
16059    fn wit_shape_predicates_reject_uncanonical_forms() {
16060        // Negative-set pin: the six canonical prefixes are
16061        // lowercase-only (mirrors the `is_wit_world_ref` substrate
16062        // predicate's lowercase invariant — see its docstring on the
16063        // "I thought I had L7 HTTP routing, got L4-only" footgun).
16064        // The empty string, an uppercase-prefixed form, a hyphen-
16065        // instead-of-colon typo, and a bare kebab identifier all miss
16066        // every shape arm — reachable-by-construction only via the
16067        // `is_wit_world_ref` gate that admission-checks the `:wit`
16068        // value first, but pinned here so any future
16069        // free-function change (e.g. a case-insensitive
16070        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
16071        // this unit level.
16072        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
16073            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
16074            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
16075            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
16076        }
16077    }
16078
16079    #[test]
16080    fn wit_shape_predicates_partition_canonical_set() {
16081        // Every canonical prefix routes to exactly one shape arm —
16082        // the three prefix sets are pairwise disjoint. Pins the
16083        // routing property [`WitContract::target`] relies on: an
16084        // `is_http()` return of `true` guarantees `is_pubsub()` and
16085        // `is_store()` return `false`, so the shape-→-target-slot
16086        // dispatch (endpoint vs subject vs slot) is unambiguous.
16087        // Drift (e.g. a future `"kv:"` moved into the HTTP set
16088        // without removal from the store set) would silently route
16089        // one prefix to two arms and the first-matching-arm order
16090        // becomes load-bearing — this pin surfaces it as a build
16091        // error instead.
16092        for prefix in WIT_HTTP_SHAPE_PREFIXES {
16093            let sample = format!("{prefix}x");
16094            assert!(wit_shape_is_http(&sample));
16095            assert!(!wit_shape_is_pubsub(&sample));
16096            assert!(!wit_shape_is_store(&sample));
16097        }
16098        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
16099            let sample = format!("{prefix}x");
16100            assert!(!wit_shape_is_http(&sample));
16101            assert!(wit_shape_is_pubsub(&sample));
16102            assert!(!wit_shape_is_store(&sample));
16103        }
16104        for prefix in WIT_STORE_SHAPE_PREFIXES {
16105            let sample = format!("{prefix}x");
16106            assert!(!wit_shape_is_http(&sample));
16107            assert!(!wit_shape_is_pubsub(&sample));
16108            assert!(wit_shape_is_store(&sample));
16109        }
16110    }
16111
16112    #[test]
16113    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
16114        // Positive pin: [`wit_shape_matches`] is exactly the
16115        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
16116        // parameterized on the accept-set. Two-prefix accept-set,
16117        // one-prefix accept-set, and empty accept-set (which must
16118        // reject everything, including the empty string — an empty
16119        // `any()` fold returns `false`) all pinned so a future
16120        // reimplementation that swaps `starts_with` for `contains`,
16121        // `==`, or a case-folded comparator surfaces at unit-test
16122        // time.
16123        let two = &["wasi:http/", "http:"];
16124        assert!(wit_shape_matches("wasi:http/proxy", two));
16125        assert!(wit_shape_matches("http:incoming", two));
16126        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
16127
16128        let one = &["nats:"];
16129        assert!(wit_shape_matches("nats:pub-sub", one));
16130        assert!(!wit_shape_matches("kafka:topic", one));
16131
16132        // Empty accept-set matches nothing — the identity element
16133        // for the disjunctive `any()` fold across the prefix set.
16134        // Reachable via a future `wit_shape_is_<name>` const paired
16135        // to a still-empty prefix table on a nascent shape-arm draft.
16136        let empty: &[&str] = &[];
16137        assert!(!wit_shape_matches("wasi:http/proxy", empty));
16138        assert!(!wit_shape_matches("", empty));
16139
16140        // starts_with, not contains: a prefix embedded mid-string
16141        // never matches. Pins the routing invariant [`WitContract::target`]
16142        // relies on (an authored `:wit "custom:wasi:http/"` string
16143        // does not silently route through the HTTP arm just because
16144        // it happens to contain the canonical HTTP prefix).
16145        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
16146    }
16147
16148    #[test]
16149    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
16150        // Equivalence pin: each per-shape predicate is exactly
16151        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
16152        // every canonical prefix + the empty string + one negative
16153        // sample against every peer so a future predicate that grew
16154        // its own inline `iter().any(starts_with)` (rather than
16155        // delegating through the lifted combinator) drifts loudly here
16156        // — the peer-const table's contents must agree with the
16157        // predicate's accept-set by construction.
16158        let samples = [
16159            String::new(),
16160            "wasi:http/proxy".to_string(),
16161            "http:incoming".to_string(),
16162            "nats:pub-sub".to_string(),
16163            "kafka:topic".to_string(),
16164            "wasi:keyvalue/store".to_string(),
16165            "kv:cache/session".to_string(),
16166            "custom-shape".to_string(),
16167            "WASI:HTTP/proxy".to_string(),
16168        ];
16169        for wit in &samples {
16170            assert_eq!(
16171                wit_shape_is_http(wit),
16172                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
16173                "wit_shape_is_http drifted from combinator on {wit:?}",
16174            );
16175            assert_eq!(
16176                wit_shape_is_pubsub(wit),
16177                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
16178                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
16179            );
16180            assert_eq!(
16181                wit_shape_is_store(wit),
16182                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
16183                "wit_shape_is_store drifted from combinator on {wit:?}",
16184            );
16185        }
16186    }
16187
16188    #[test]
16189    fn wit_contract_shape_methods_delegate_to_free_functions() {
16190        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
16191        // `is_store` are `&self` conveniences on top of the free
16192        // functions — for every canonical prefix the method's return
16193        // matches its free-function peer. Sweeps the union of the
16194        // three prefix sets so a future method that grew its own
16195        // inline prefix logic (rather than delegating) drifts loudly
16196        // here on the first prefix the free function accepts and the
16197        // method doesn't.
16198        for shape_set in [
16199            WIT_HTTP_SHAPE_PREFIXES,
16200            WIT_PUBSUB_SHAPE_PREFIXES,
16201            WIT_STORE_SHAPE_PREFIXES,
16202        ] {
16203            for prefix in shape_set {
16204                let c = WitContract {
16205                    de: "cart".into(),
16206                    para: "catalog".into(),
16207                    wit: format!("{prefix}x"),
16208                    endpoint: None,
16209                    subject: None,
16210                    slot: None,
16211                };
16212                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
16213                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
16214                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
16215                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
16216            }
16217        }
16218        // Capability-arm delegation sweep: two representative
16219        // Capability-shaped `:wit` values (a bare non-prefix-matching
16220        // WIT world, the deliberately-shaped empty string
16221        // [`WitContract::is_capability`]'s docstring calls out as
16222        // syntactically Capability). Extends the free-function
16223        // delegation pin onto the fourth arm so a future
16224        // [`WitContract::is_capability`] rewrite that grew an inline
16225        // prefix-set scan (rather than delegating through
16226        // [`wit_shape_is_capability`]) drifts loudly here on the first
16227        // Capability-shaped sample.
16228        for wit in ["custom:capability-only", ""] {
16229            let c = WitContract {
16230                de: "cart".into(),
16231                para: "catalog".into(),
16232                wit: wit.into(),
16233                endpoint: None,
16234                subject: None,
16235                slot: None,
16236            };
16237            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
16238        }
16239    }
16240
16241    #[test]
16242    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
16243        // 4-way partition-witness pin on the raw `&str` axis: for every
16244        // canonical prefix in the three payload-arm accept-sets,
16245        // exactly one of the four [`wit_shape_is_http`] /
16246        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
16247        // [`wit_shape_is_capability`] free functions returns `true` and
16248        // the other three return `false` — the four-arm partition
16249        // witness that locks the free-function WIT-shape-classifier
16250        // family into a partition of the `:contratos :wit` axis
16251        // load-bearing. Peer of the sibling [`WitContract`]-surface
16252        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
16253        // partition pin — extends the discipline onto the raw `&str`
16254        // axis so any future arm addition (a hypothetical
16255        // `wasi:sockets/*` transport-layer shape, an `oci:*`
16256        // capability-import carrier per the sibling
16257        // [`wit_shape_matches`] docstring's trajectory bullet) that
16258        // landed on one of the payload-arm free functions without
16259        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
16260        // here as two arms returning `true` simultaneously at
16261        // caixa-core build time rather than a silent per-consumer
16262        // misclassification at renderer emit time.
16263        for shape_set in [
16264            WIT_HTTP_SHAPE_PREFIXES,
16265            WIT_PUBSUB_SHAPE_PREFIXES,
16266            WIT_STORE_SHAPE_PREFIXES,
16267        ] {
16268            for prefix in shape_set {
16269                let wit = format!("{prefix}x");
16270                let hits = [
16271                    wit_shape_is_http(&wit),
16272                    wit_shape_is_pubsub(&wit),
16273                    wit_shape_is_store(&wit),
16274                    wit_shape_is_capability(&wit),
16275                ]
16276                .iter()
16277                .filter(|&&b| b)
16278                .count();
16279                assert_eq!(
16280                    hits,
16281                    1,
16282                    "raw-&str WIT-shape 4-way predicate partition must \
16283                     admit exactly one arm per canonical prefix; got {hits} \
16284                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
16285                     is_capability={})",
16286                    wit_shape_is_http(&wit),
16287                    wit_shape_is_pubsub(&wit),
16288                    wit_shape_is_store(&wit),
16289                    wit_shape_is_capability(&wit),
16290                );
16291            }
16292        }
16293        // Capability-arm sweep on the raw `&str` axis: two
16294        // representative Capability-shaped `:wit` values (a bare non-
16295        // prefix-matching WIT world, the deliberately-shaped empty
16296        // string the pure classifier still admits per
16297        // [`wit_shape_is_capability`]'s docstring). Both must land on
16298        // the fourth arm exclusively so the partition witness holds
16299        // across the full 4-arm closure on the raw `&str` axis.
16300        for wit in ["custom:capability-only", ""] {
16301            let hits = [
16302                wit_shape_is_http(wit),
16303                wit_shape_is_pubsub(wit),
16304                wit_shape_is_store(wit),
16305                wit_shape_is_capability(wit),
16306            ]
16307            .iter()
16308            .filter(|&&b| b)
16309            .count();
16310            assert_eq!(
16311                hits, 1,
16312                "raw-&str WIT-shape 4-way predicate partition must \
16313                 admit exactly one arm on Capability-shaped wit={wit:?}"
16314            );
16315            assert!(
16316                wit_shape_is_capability(wit),
16317                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
16318            );
16319        }
16320    }
16321
16322    #[test]
16323    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
16324        // Composition-witness pin: [`wit_shape_is_capability`] is the
16325        // exact-inverse disjunction of the sibling payload-arm free-
16326        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
16327        // / [`wit_shape_is_store`]. A future reimplementation that
16328        // grew its own prefix-set scan (e.g. inlining a fourth
16329        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
16330        // not own today) rather than delegating to the sibling trio
16331        // would drift loudly here — the composition contract binds the
16332        // fourth-arm free-function predicate to the exact-inverse of
16333        // the three payload-arm free-function predicates, so any
16334        // rebrand of any prefix-set const flows through
16335        // [`wit_shape_is_capability`] by construction without a
16336        // coordinated per-consumer rewrite. Peer of the sibling
16337        // [`WitContract`]-surface
16338        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
16339        // composition pin — extends the discipline onto the raw
16340        // `&str` axis.
16341        let mut cases: Vec<String> = Vec::new();
16342        for shape_set in [
16343            WIT_HTTP_SHAPE_PREFIXES,
16344            WIT_PUBSUB_SHAPE_PREFIXES,
16345            WIT_STORE_SHAPE_PREFIXES,
16346        ] {
16347            for prefix in shape_set {
16348                cases.push(format!("{prefix}x"));
16349            }
16350        }
16351        cases.push("custom:capability-only".to_string());
16352        cases.push(String::new());
16353        for wit in cases {
16354            assert_eq!(
16355                wit_shape_is_capability(&wit),
16356                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
16357                "wit_shape_is_capability must equal \
16358                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
16359                 at wit={wit:?}"
16360            );
16361        }
16362    }
16363
16364    #[test]
16365    fn wit_shape_classifier_family_is_const_fn() {
16366        // Fail-before-pass-after pin on the 4-arm free-function WIT-
16367        // shape classifier family's `const`-eval posture. Each of the
16368        // four peer classifiers ([`wit_shape_is_http`] /
16369        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
16370        // [`wit_shape_is_capability`]) and the underlying combinator
16371        // [`wit_shape_matches`] must be `pub const fn` — any future
16372        // accidental downgrade to non-`const` fails the `const fn`
16373        // wrappers below at caixa-core build time with E0015
16374        // (`cannot call non-const function`), strictly stronger than
16375        // a runtime `assert!` and strictly stronger than the module-
16376        // scope `const _: () = assert!(…)` pins immediately after the
16377        // classifier declarations (those anchor specific accept-set
16378        // truth-table entries; this pin anchors the `const` posture
16379        // itself via `const fn` wrappers that are only well-formed
16380        // when the callee is itself `const fn`).
16381        //
16382        // Verified fail-before-pass-after by locally reverting
16383        // `pub const fn` → `pub fn` on each classifier and observing
16384        // E0015 at every corresponding wrapper call site (build
16385        // error, no test-time surface), then restoring `pub const fn`
16386        // and observing the pin pass at test time. Peer of the
16387        // sibling M3
16388        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
16389        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
16390        // M2
16391        // [`child_spec_restart_accessor_is_const_fn`] /
16392        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
16393        // and M3
16394        // [`placement_estrategia_accessor_is_const_fn`] /
16395        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
16396        // sibling `const`-eval-surface-pass axes.
16397        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
16398            wit_shape_matches(wit, prefixes)
16399        }
16400        const fn http_via_const_fn(wit: &str) -> bool {
16401            wit_shape_is_http(wit)
16402        }
16403        const fn pubsub_via_const_fn(wit: &str) -> bool {
16404            wit_shape_is_pubsub(wit)
16405        }
16406        const fn store_via_const_fn(wit: &str) -> bool {
16407            wit_shape_is_store(wit)
16408        }
16409        const fn capability_via_const_fn(wit: &str) -> bool {
16410            wit_shape_is_capability(wit)
16411        }
16412        // Sweep one canonical accept-set sample per arm plus the
16413        // payload-less/empty capability samples, asserting the
16414        // wrapper and direct dispatches agree byte-for-byte across
16415        // the closed 4-arm partition.
16416        let cases: [(&str, bool, bool, bool, bool); 6] = [
16417            ("wasi:http/proxy", true, false, false, false),
16418            ("http:incoming", true, false, false, false),
16419            ("nats:events", false, true, false, false),
16420            ("kafka:topic", false, true, false, false),
16421            ("wasi:keyvalue/store", false, false, true, false),
16422            ("kv:cache", false, false, true, false),
16423        ];
16424        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
16425            assert_eq!(
16426                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
16427                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
16428                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
16429            );
16430            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
16431            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
16432            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
16433            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
16434            assert_eq!(wit_shape_is_http(wit), is_http);
16435            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
16436            assert_eq!(wit_shape_is_store(wit), is_store);
16437        }
16438        // Payload-less capability arm (the 4th partition arm).
16439        let capability_samples: [&str; 3] =
16440            ["wasi:filesystem/preopens", "custom:capability-only", ""];
16441        for wit in capability_samples {
16442            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
16443            assert!(wit_shape_is_capability(wit));
16444            assert!(!wit_shape_is_http(wit));
16445            assert!(!wit_shape_is_pubsub(wit));
16446            assert!(!wit_shape_is_store(wit));
16447        }
16448    }
16449
16450    // Canonical `(wit, expected)` sweep the four [`WitShape`] pins below
16451    // key off — one accept-set sample per prefix in each of the three
16452    // payload-arm prefix sets [`WIT_HTTP_SHAPE_PREFIXES`] /
16453    // [`WIT_PUBSUB_SHAPE_PREFIXES`] / [`WIT_STORE_SHAPE_PREFIXES`], plus
16454    // three canonical Capability-arm samples (a non-prefix-matching WIT
16455    // world, an empty string, a partial-match probe that lands after
16456    // the accepted prefix boundary). Declared once so a future arm
16457    // addition or prefix-set edit grows the truth table at one
16458    // authored site and every downstream pin picks up the new row by
16459    // construction.
16460    const WIT_SHAPE_CLASSIFY_TRUTH_TABLE: &[(&str, WitShape)] = &[
16461        ("wasi:http/proxy", WitShape::Http),
16462        ("http:incoming", WitShape::Http),
16463        ("nats:events", WitShape::PubSub),
16464        ("kafka:topic", WitShape::PubSub),
16465        ("wasi:keyvalue/store", WitShape::Store),
16466        ("kv:cache", WitShape::Store),
16467        ("wasi:filesystem/preopens", WitShape::Capability),
16468        ("custom:capability-only", WitShape::Capability),
16469        ("", WitShape::Capability),
16470    ];
16471
16472    #[test]
16473    fn wit_shape_all_matches_declaration_order_and_covers_every_arm() {
16474        // Fail-before-pass-after pin on [`WitShape::ALL`]: the slice
16475        // must enumerate every arm exactly once in declaration order
16476        // (`Http` → `PubSub` → `Store` → `Capability`), so downstream
16477        // consumers that walk the shape space through the const slice
16478        // reach every arm and see them in the canonical order the
16479        // paired [`WitShape::classify`] arm-preference dispatches on.
16480        // A future variant addition that forgets to grow the slice
16481        // trips here (the length no longer matches the number of arms
16482        // touched by the `match self` below); a rearrangement of the
16483        // declaration order without updating the slice trips too.
16484        let expected: [WitShape; 4] = [
16485            WitShape::Http,
16486            WitShape::PubSub,
16487            WitShape::Store,
16488            WitShape::Capability,
16489        ];
16490        assert_eq!(WitShape::ALL.len(), expected.len());
16491        assert_eq!(WitShape::ALL, &expected[..]);
16492        // Exhaustive-match witness: touch every arm so a future
16493        // variant addition without a matching `WitShape::ALL` extension
16494        // trips at compile time here on the missing arm.
16495        for arm in WitShape::ALL {
16496            match arm {
16497                WitShape::Http | WitShape::PubSub | WitShape::Store | WitShape::Capability => {}
16498            }
16499        }
16500    }
16501
16502    #[test]
16503    fn wit_shape_classify_pins_the_canonical_truth_table() {
16504        // Pin the [`WitShape::classify`] arm-dispatch against the
16505        // shared truth table [`WIT_SHAPE_CLASSIFY_TRUTH_TABLE`]. A
16506        // future prefix-set edit that reroutes any canonical sample
16507        // onto the wrong arm trips at exactly the offending row.
16508        for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
16509            assert_eq!(
16510                WitShape::classify(wit),
16511                *expected,
16512                "WitShape::classify({wit:?}) drifted from truth table",
16513            );
16514        }
16515    }
16516
16517    #[test]
16518    fn wit_shape_classify_partitions_via_is_variant_predicates() {
16519        // Fail-before-pass-after pin: for every canonical truth-table
16520        // row, the classified arm satisfies exactly one of the four
16521        // [`gen_platform::IsVariant`]-derived arm-discriminator
16522        // predicates ([`WitShape::is_http`] / [`is_pubsub`] /
16523        // [`is_store`] / [`is_capability`]) — the observed 4-slot
16524        // predicate row must equal a one-hot row with the `true` at
16525        // exactly the same index as the declared arm's slot in
16526        // [`WitShape::ALL`]. A future rebind (an `#[is_variant(name =
16527        // "…")]` drift, a manual `impl` shadowing the derive, an arm
16528        // rename that reroutes one arm through the wrong predicate
16529        // lane) trips here at exactly the offending row rather than
16530        // surfacing far from the derive commit.
16531        for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
16532            let arm = WitShape::classify(wit);
16533            let observed = [
16534                arm.is_http(),
16535                arm.is_pubsub(),
16536                arm.is_store(),
16537                arm.is_capability(),
16538            ];
16539            let mut expected_row = [false; 4];
16540            let idx = WitShape::ALL
16541                .iter()
16542                .position(|a| a == expected)
16543                .expect("truth-table arm appears in WitShape::ALL");
16544            expected_row[idx] = true;
16545            assert_eq!(
16546                observed, expected_row,
16547                "WitShape::classify({wit:?}).is_* row must be one-hot at slot {idx}",
16548            );
16549        }
16550    }
16551
16552    #[test]
16553    fn wit_shape_classify_agrees_with_free_predicates() {
16554        // Equivalence pin against the four free classifier predicates
16555        // ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
16556        // [`wit_shape_is_store`] / [`wit_shape_is_capability`]) — after
16557        // this lift the free predicates route through
16558        // `matches!(WitShape::classify(wit), WitShape::<arm>)`, so this
16559        // pin proves the delegation preserves each predicate's
16560        // accept-set on the canonical truth table. A future accidental
16561        // reintroduction of an open-coded free-predicate body (or a
16562        // classify-side arm reorder that shifts arm preference in a
16563        // way that breaks disjointness) trips here at the offending
16564        // row rather than at a downstream consumer.
16565        for (wit, _expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
16566            let arm = WitShape::classify(wit);
16567            assert_eq!(arm.is_http(), wit_shape_is_http(wit));
16568            assert_eq!(arm.is_pubsub(), wit_shape_is_pubsub(wit));
16569            assert_eq!(arm.is_store(), wit_shape_is_store(wit));
16570            assert_eq!(arm.is_capability(), wit_shape_is_capability(wit));
16571        }
16572    }
16573
16574    #[test]
16575    fn wit_shape_as_str_display_and_asref_route_through_one_source() {
16576        // Fail-before-pass-after pin on the canonical-projection triple
16577        // [`WitShape::as_str`] / [`std::fmt::Display for WitShape`] /
16578        // [`AsRef<str> for WitShape`]: every arm's `Display`-formatted
16579        // and `AsRef<str>`-borrowed output must byte-equal its
16580        // `as_str` output. Same discipline the sibling
16581        // [`crate::CaixaKind`] / [`crate::dialeto::CaixaDialeto`] /
16582        // [`PlacementStrategy`] / [`RateLimitUnit`] canonical-projection
16583        // triples carry — a future accidental hand-rolled `Display`
16584        // body that diverges from `as_str` trips here.
16585        let expected: &[(WitShape, &str)] = &[
16586            (WitShape::Http, "http"),
16587            (WitShape::PubSub, "pubsub"),
16588            (WitShape::Store, "store"),
16589            (WitShape::Capability, "capability"),
16590        ];
16591        for (arm, want) in expected {
16592            assert_eq!(arm.as_str(), *want, "WitShape::as_str({arm:?}) drifted");
16593            assert_eq!(
16594                format!("{arm}"),
16595                *want,
16596                "Display for WitShape drifted from as_str at {arm:?}",
16597            );
16598            assert_eq!(
16599                AsRef::<str>::as_ref(arm),
16600                *want,
16601                "AsRef<str> for WitShape drifted from as_str at {arm:?}",
16602            );
16603        }
16604    }
16605
16606    #[test]
16607    fn wit_shape_classify_is_const_fn() {
16608        // Fail-before-pass-after pin on [`WitShape::classify`]'s
16609        // `const`-eval posture. The classifier must be `pub const fn`
16610        // — any future accidental downgrade to non-`const` fails the
16611        // wrapper below with E0015 at caixa-core build time, strictly
16612        // stronger than a runtime `assert!`. Peer of the sibling
16613        // [`wit_shape_classifier_family_is_const_fn`] pin on the
16614        // free-function classifier family.
16615        const fn classify_via_const_fn(wit: &str) -> WitShape {
16616            WitShape::classify(wit)
16617        }
16618        // Compile-time truth-table pin: every canonical row's
16619        // classification is reachable at const-eval time, so any
16620        // downstream `const`-context consumer (a module-scope
16621        // `const _: () = assert!(matches!(WitShape::classify(<lit>),
16622        // WitShape::<arm>))` invariant pin on a typed fixture, a
16623        // future `const fn` per-`:contratos :wit` arm-resolver over a
16624        // static wit literal) reaches the classifier through one
16625        // dispatch on the substrate primitive without an intermediate
16626        // non-`const` step.
16627        const _: () = assert!(matches!(
16628            classify_via_const_fn("wasi:http/proxy"),
16629            WitShape::Http
16630        ));
16631        const _: () = assert!(matches!(
16632            classify_via_const_fn("nats:events"),
16633            WitShape::PubSub
16634        ));
16635        const _: () = assert!(matches!(
16636            classify_via_const_fn("wasi:keyvalue/store"),
16637            WitShape::Store
16638        ));
16639        const _: () = assert!(matches!(classify_via_const_fn(""), WitShape::Capability));
16640        // Also assert const `as_str` routes through the const `classify`
16641        // on the same const path.
16642        const _: () = assert!(matches!(
16643            classify_via_const_fn("wasi:http/proxy").as_str().as_bytes(),
16644            b"http"
16645        ));
16646    }
16647
16648    #[test]
16649    fn wit_shape_from_wire_accepts_every_as_str_output() {
16650        // Fail-before-pass-after per-arm accept pin on the newly lifted
16651        // [`WitShape::from_wire`] reverse projection: every arm in
16652        // [`WitShape::ALL`] must parse back through `from_wire` when fed
16653        // its own [`WitShape::as_str`] output, landing on
16654        // `Some(same_variant)`. A regression that hand-rolled either
16655        // side's per-arm match without threading through the shared
16656        // four-string closed set would silently disagree on any future
16657        // arm rename (or a new arm the WIT-shape space grows — a
16658        // hypothetical `wasi:sockets/*` transport-layer shape, an
16659        // `oci:*` capability-import carrier per the sibling
16660        // [`wit_shape_matches`] docstring's trajectory bullet) and this
16661        // pin flags it at caixa-core build time rather than at a
16662        // downstream `feira app graph --by-wit-shape` consumer's silent
16663        // tag misclassification.
16664        //
16665        // Peer of the sibling
16666        // `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_accepts_every_variant_slug_output`
16667        // (1e4cc81) /
16668        // `caixa_theme::style::tests::semantic_from_wire_accepts_every_as_str_output`
16669        // (e7bca7b) /
16670        // `caixa_lint::diagnostic::tests::fix_safety_from_wire_accepts_every_as_str_output`
16671        // (bd505a1) /
16672        // `caixa_lint::diagnostic::tests::severity_from_wire_accepts_every_as_str_output`
16673        // (5afff0e) /
16674        // `caixa_arch::report::tests::arch_verdict_from_wire_accepts_every_as_str_output`
16675        // (6afe564) /
16676        // `caixa_arch::invariants::tests::invariant_kind_from_wire_accepts_every_as_str_output`
16677        // (b9e4e61) round-trip pins on the peer caixa-provedor /
16678        // caixa-theme / caixa-lint / caixa-arch closed-set-enum
16679        // reverse-projection axes, and of the sibling
16680        // `crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`
16681        // (2aa6d23) /
16682        // `crate::dialeto::tests::caixa_dialeto_from_wire_accepts_every_as_str_output`
16683        // (d0e65ea) /
16684        // `placement_strategy_from_wire_accepts_every_lifted_constant`
16685        // (18c7342) /
16686        // `crate::dep::tests::dep_list_round_trips_through_as_str_and_from_wire`
16687        // (45ee563) /
16688        // `crate::render::tests::path_shape_violation_from_wire_accepts_every_as_str_output`
16689        // (aebd9c6) round-trip pins on the sibling caixa-core closed-
16690        // set typed-enum reverse-projection axes.
16691        for &variant in WitShape::ALL {
16692            let wire = variant.as_str();
16693            let parsed = WitShape::from_wire(wire).unwrap_or_else(|| {
16694                panic!(
16695                    "WitShape::from_wire({wire:?}) must accept every \
16696                     WitShape::as_str output — got None for the wire \
16697                     byte-string of {variant:?}"
16698                )
16699            });
16700            assert_eq!(
16701                parsed, variant,
16702                "WitShape::from_wire(WitShape::{variant:?}.as_str()) must \
16703                 return WitShape::{variant:?} — the (as_str, from_wire) \
16704                 pair must form a total round-trip on the closed four-arm \
16705                 WitShape arm-set",
16706            );
16707        }
16708        // Pin the exact per-arm accept-set so a future rebrand of the
16709        // census-label byte-strings ("http" / "pubsub" / "store" /
16710        // "capability") surfaces at this pin rather than at a downstream
16711        // consumer's silent tag drift.
16712        assert_eq!(WitShape::from_wire("http"), Some(WitShape::Http));
16713        assert_eq!(WitShape::from_wire("pubsub"), Some(WitShape::PubSub));
16714        assert_eq!(WitShape::from_wire("store"), Some(WitShape::Store));
16715        assert_eq!(
16716            WitShape::from_wire("capability"),
16717            Some(WitShape::Capability),
16718        );
16719    }
16720
16721    #[test]
16722    fn wit_shape_from_wire_rejects_unknown_byte_strings() {
16723        // Rejection pin on the [`WitShape::from_wire`] parser's
16724        // accept-set: any string outside the four-arm
16725        // [`WitShape::as_str`] output set must return [`None`]. A future
16726        // accidental widening of the accept-set (a case-insensitive
16727        // match that accepts `"HTTP"` / `"Http"`, a silent acceptance of
16728        // the PascalCase Debug-derived shapes `"Http"` / `"PubSub"` /
16729        // `"Store"` / `"Capability"` on the wire axis, a Levenshtein-
16730        // forgiving arm-lookup that admits typos, a silent absorption of
16731        // the sibling raw `:contratos :wit` identifiers [`Self::classify`]
16732        // consumes on the peer classifier axis — `"wasi:http/proxy"`,
16733        // `"nats:events"`, `"wasi:keyvalue/store"`, `"kafka:topic"`,
16734        // `"kv:cache"`, `"http:incoming"` — a silent absorption of the
16735        // paired [`WitTarget::label`] short-form tags every downstream
16736        // renderer already handles on the post-validation axis) would
16737        // silently drift the parser's accept-set from the emitter's — a
16738        // downstream re-loader that bound a prior emission's
16739        // [`Self::as_str`] output back to the typed enum through this
16740        // parser would then bind a malformed byte-string to a
16741        // plausibly-wrong typed arm the caller does not route through
16742        // any fallback, silently misclassifying the reloaded row.
16743        //
16744        // The raw `:contratos :wit` identifier vectors are load-bearing:
16745        // [`WitShape::classify`] is a *total* function on every `&str`
16746        // (falling through to [`WitShape::Capability`] on unknown
16747        // prefixes), so a caller who confuses the two axes and routes a
16748        // raw WIT identifier through [`from_wire`] instead of
16749        // [`classify`] must observe [`None`] here rather than a plausibly-
16750        // wrong `Some(WitShape::Capability)` silently — the peer axes
16751        // carry different accept-sets by design.
16752        //
16753        // Peer of the sibling
16754        // `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_rejects_unknown_byte_strings`
16755        // (1e4cc81) /
16756        // `caixa_theme::style::tests::semantic_from_wire_rejects_unknown_byte_strings`
16757        // (e7bca7b) /
16758        // `caixa_lint::diagnostic::tests::fix_safety_from_wire_rejects_unknown_byte_strings`
16759        // (bd505a1) /
16760        // `caixa_lint::diagnostic::tests::severity_from_wire_rejects_unknown_byte_strings`
16761        // (5afff0e) /
16762        // `caixa_arch::report::tests::arch_verdict_from_wire_rejects_unknown_byte_strings`
16763        // (6afe564) /
16764        // `caixa_arch::invariants::tests::invariant_kind_from_wire_rejects_unknown_byte_strings`
16765        // (b9e4e61) rejection pins on the peer caixa-provedor /
16766        // caixa-theme / caixa-lint / caixa-arch axes, and of the sibling
16767        // `caixa_kind_from_wire_rejects_unknown_byte_strings` (2aa6d23),
16768        // `caixa_dialeto_from_wire_rejects_unknown_byte_strings`
16769        // (d0e65ea),
16770        // `placement_strategy_from_wire_rejects_unknown_byte_strings`
16771        // (18c7342),
16772        // `dep_list_from_wire_returns_none_on_unknown_wire_scalar`
16773        // (45ee563), and
16774        // `path_shape_violation_from_wire_rejects_unknown_byte_strings`
16775        // (aebd9c6) rejection pins on the sibling caixa-core axes.
16776        for bad in [
16777            "",
16778            " ",
16779            "http ",
16780            " http",
16781            "HTTP",
16782            "Http",
16783            "PUBSUB",
16784            "PubSub",
16785            "pub_sub",
16786            "pub-sub",
16787            "STORE",
16788            "Store",
16789            "CAPABILITY",
16790            "Capability",
16791            "kv",
16792            "nats",
16793            "kafka",
16794            "wasi:http/proxy",
16795            "wasi:http/",
16796            "http:",
16797            "http:incoming",
16798            "nats:events",
16799            "kafka:topic",
16800            "wasi:keyvalue/store",
16801            "wasi:keyvalue/",
16802            "kv:cache",
16803            "kv:",
16804            "oci:capability",
16805            "wasi:sockets/tcp",
16806            "\u{200b}http",
16807            "http\u{200b}",
16808        ] {
16809            assert!(
16810                WitShape::from_wire(bad).is_none(),
16811                "WitShape::from_wire({bad:?}) must reject byte-strings \
16812                 outside the four-arm WitShape::as_str output set — got \
16813                 {:?}",
16814                WitShape::from_wire(bad),
16815            );
16816        }
16817    }
16818
16819    #[test]
16820    fn wit_shape_from_wire_and_classify_partition_the_axis() {
16821        // Cross-axis discipline pin: [`WitShape::classify`] is a total
16822        // function on the raw `:contratos :wit` identifier axis (every
16823        // `&str` classifies), while [`WitShape::from_wire`] is a partial
16824        // function on the census-label axis (the four
16825        // [`WitShape::as_str`] outputs and nothing else). The two axes
16826        // meet on exactly zero strings by construction — the four
16827        // census labels (`"http"` / `"pubsub"` / `"store"` /
16828        // `"capability"`) are not prefix-matched by any of
16829        // [`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
16830        // [`WIT_STORE_SHAPE_PREFIXES`], so on the shared four-string
16831        // census-label set:
16832        //
16833        //   * [`WitShape::from_wire`] returns `Some(<matching arm>)`
16834        //     per [`WitShape::as_str`]'s output;
16835        //   * [`WitShape::classify`] falls through to the
16836        //     [`WitShape::Capability`] catch-all fallback (since none of
16837        //     the payload-arm prefix sets begin with `"http"` /
16838        //     `"pubsub"` / `"store"` / `"capability"`).
16839        //
16840        // A future WIT-prefix set edit that accidentally started with
16841        // one of the four census labels (a hypothetical
16842        // `"http"` prefix directly, a `"pubsub://"` scheme addition, a
16843        // `"store:"` capability-carrier extension) would silently
16844        // collide the two axes on the same string — [`from_wire`] would
16845        // still yield the census-label arm while [`classify`] would
16846        // route the payload-arm dispatch through the accidental overlap.
16847        // Locking the partition here means such a prefix-set edit
16848        // trips this pin at caixa-core build time before the collision
16849        // becomes observable at any downstream consumer.
16850        for &variant in WitShape::ALL {
16851            let label = variant.as_str();
16852            // The census-label axis half — [`from_wire`] resolves to
16853            // the emitter's arm identity.
16854            assert_eq!(
16855                WitShape::from_wire(label),
16856                Some(variant),
16857                "WitShape::from_wire({label:?}) must resolve to the \
16858                 emitter's arm identity on the census-label axis",
16859            );
16860            // The raw-classifier axis half — [`classify`] falls through
16861            // to [`WitShape::Capability`] on every census label under
16862            // the current prefix set. Any future overlap trips here.
16863            assert_eq!(
16864                WitShape::classify(label),
16865                WitShape::Capability,
16866                "WitShape::classify({label:?}) must fall through to \
16867                 WitShape::Capability on every census label — a match \
16868                 to any payload arm here means a payload-prefix set \
16869                 has silently collided the census-label axis with the \
16870                 raw-classifier axis",
16871            );
16872        }
16873    }
16874
16875    #[test]
16876    fn wit_shape_try_from_str_routes_through_from_wire_accessor() {
16877        // Fail-before-pass-after byte-parity pin on the newly lifted
16878        // `impl TryFrom<&str> for WitShape` — asserts the standard-
16879        // library trait impl and the substrate-primitive
16880        // [`WitShape::from_wire`] `Option<Self>` accessor resolve to the
16881        // same four-arm census-label accept-set across every arm the
16882        // exhaustive [`WitShape::ALL`] slice enumerates. Any future
16883        // silent detour that routes the trait impl through a divergent
16884        // projection (a per-arm inline `match s { "http" =>
16885        // Ok(Self::Http), … }` re-inlining that opens a compile-time
16886        // link to the un-lifted arm-literal, a stray attribute drift
16887        // that silently splits the wire byte-string from every consumer
16888        // that reaches for this typed dispatch) trips at caixa-core test
16889        // time under `assert_eq!` rather than at a downstream
16890        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
16891        // every one of the four arms [`WitShape::ALL`] carries so no
16892        // arm's projection is covered only by the sibling method-named
16893        // `from_wire` path.
16894        //
16895        // Peer of the sibling
16896        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
16897        // (3c83606),
16898        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
16899        // (bf33136),
16900        // [`tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
16901        // (6fd00cd),
16902        // [`crate::supervisor::tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
16903        // (5b828ed), and
16904        // [`crate::supervisor::tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
16905        // (6fdd0d9) round-trip pins on the sibling caixa-core closed-
16906        // set typed-enum trait-idiomatic reverse-projection axes.
16907        for &variant in WitShape::ALL {
16908            let wire = variant.as_str();
16909            assert_eq!(
16910                <WitShape as TryFrom<&str>>::try_from(wire),
16911                Ok(variant),
16912                "TryFrom<&str> impl on WitShape must round-trip \
16913                 WitShape::{variant:?}.as_str() = {wire:?} back to \
16914                 Ok(WitShape::{variant:?}) — divergence from \
16915                 WitShape::from_wire signals a silent detour off the \
16916                 substrate-primitive accessor"
16917            );
16918            assert_eq!(
16919                <WitShape as TryFrom<&str>>::try_from(wire).ok(),
16920                WitShape::from_wire(wire),
16921                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
16922                 WitShape::from_wire on the same input"
16923            );
16924        }
16925    }
16926
16927    #[test]
16928    fn wit_shape_try_from_str_rejects_unknown_byte_strings() {
16929        // Rejection witness on the `impl TryFrom<&str> for WitShape` —
16930        // sweeps a candidate set of byte-strings outside the four-arm
16931        // census-label wire accept-set the sibling [`WitShape::as_str`]
16932        // emits and asserts every one lands on `Err(())`, so a future
16933        // accidental widening of the trait impl's accept-set (a stray
16934        // additional `_ if s.eq_ignore_ascii_case("http") => Ok(…)`
16935        // case-fold path, a silent inclusion of a PascalCase rebrand of
16936        // the wire byte-string that would collide the two-axis split the
16937        // sibling `wit_shape_from_wire_rejects_unknown_byte_strings` pin
16938        // makes load-bearing, a silent overlap with the raw WIT
16939        // identifier accept-set the paired [`WitShape::classify`] total
16940        // function consumes on the sibling axis that the
16941        // `wit_shape_from_wire_and_classify_partition_the_axis` cross-
16942        // axis discipline pin locks the accept-sets against) trips at
16943        // caixa-core test time. The candidate set includes the empty
16944        // string, whitespace-only padding, PascalCase rebrand candidates
16945        // (`"Http"`, `"PubSub"`), snake_case rebrand candidates
16946        // (`"pub_sub"`), uppercase rebrand candidates (`"HTTP"`,
16947        // `"CAPABILITY"`), kebab-case rebrand candidates (`"pub-sub"`),
16948        // trailing/leading-whitespace-padded canonical scalars, the
16949        // trailing-newline shape, English-rebrand candidates
16950        // (`"messaging"`, `"cache"`), raw `:contratos :wit` identifiers
16951        // the sibling [`WitShape::classify`] axis consumes
16952        // (`"wasi:http/proxy"`, `"nats:events"`,
16953        // `"wasi:keyvalue/store"`) that must not silently leak across
16954        // the two-axis partition, the residual `"?"` and JSON-quoted
16955        // `"\"http\""` shape.
16956        //
16957        // Peer of the sibling
16958        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
16959        // (3c83606),
16960        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_rejects_unknown_byte_strings`]
16961        // (bf33136),
16962        // [`tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
16963        // (6fd00cd),
16964        // [`crate::supervisor::tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
16965        // (5b828ed), and
16966        // [`crate::supervisor::tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
16967        // (6fdd0d9) rejection witnesses.
16968        let rejected: &[&str] = &[
16969            "",
16970            " ",
16971            "\n",
16972            "\t",
16973            "Http",
16974            "HTTP",
16975            "PubSub",
16976            "PUBSUB",
16977            "Store",
16978            "STORE",
16979            "Capability",
16980            "CAPABILITY",
16981            "pub-sub",
16982            "pub_sub",
16983            "pubSub",
16984            "http ",
16985            " http",
16986            " store ",
16987            "capability\n",
16988            "http/",
16989            "messaging",
16990            "cache",
16991            "wasi:http/proxy",
16992            "wasi:keyvalue/store",
16993            "nats:events",
16994            "?",
16995            "\"http\"",
16996        ];
16997        for &input in rejected {
16998            assert_eq!(
16999                <WitShape as TryFrom<&str>>::try_from(input),
17000                Err(()),
17001                "TryFrom<&str> impl on WitShape must reject the \
17002                 non-wire byte-string {input:?} — silent acceptance \
17003                 signals an accept-set widening off the paired \
17004                 WitShape::from_wire resolver, or a cross-axis leak \
17005                 from the raw-identifier axis WitShape::classify consumes"
17006            );
17007        }
17008    }
17009
17010    #[test]
17011    fn wit_shape_try_from_str_and_from_wire_partition_the_accept_set() {
17012        // Cross-axis partition pin locking the newly lifted
17013        // `impl TryFrom<&str> for WitShape` and the substrate-primitive
17014        // [`WitShape::from_wire`] accessor to the same `Option<Self>`
17015        // output on every input — the two axes converge on the same
17016        // partition of `&str` by construction, and this pin asserts
17017        // that convergence directly rather than only through
17018        // [`WitShape::ALL`]'s per-arm sweep. Any future divergence (a
17019        // stray case-fold path on the trait axis that widens acceptance
17020        // past what `from_wire` admits, a silent per-arm short-circuit
17021        // that returns `Err(())` on an input `from_wire` accepts) trips
17022        // here under `assert_eq!` on every input in the sweep.
17023        //
17024        // Sweeps the four accepted census labels plus a representative
17025        // rejection set covering the same categories the sibling
17026        // `wit_shape_try_from_str_rejects_unknown_byte_strings` pin
17027        // enumerates, so a regression on either axis surfaces at the
17028        // partition pin rather than at a downstream consumer's silent
17029        // observation split.
17030        //
17031        // Peer of the sibling
17032        // [`crate::supervisor::tests::restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
17033        // (5b828ed) and
17034        // [`crate::supervisor::tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
17035        // (6fdd0d9) cross-axis partition pins.
17036        let inputs: &[&str] = &[
17037            "http",
17038            "pubsub",
17039            "store",
17040            "capability",
17041            "",
17042            " ",
17043            "Http",
17044            "PubSub",
17045            "HTTP",
17046            "pub-sub",
17047            "http ",
17048            "wasi:http/proxy",
17049            "wasi:keyvalue/store",
17050            "nats:events",
17051            "messaging",
17052            "?",
17053        ];
17054        for &input in inputs {
17055            assert_eq!(
17056                <WitShape as TryFrom<&str>>::try_from(input).ok(),
17057                WitShape::from_wire(input),
17058                "TryFrom<&str> and from_wire must agree on WitShape \
17059                 for {input:?} — the trait-idiomatic and method-named \
17060                 axes must partition the accept-set identically"
17061            );
17062        }
17063    }
17064
17065    #[test]
17066    fn wit_shape_from_into_static_str_routes_through_as_str_accessor() {
17067        // Fail-before-pass-after byte-parity pin on the newly lifted
17068        // `impl From<WitShape> for &'static str` — asserts the standard-
17069        // library trait impl and the substrate-primitive
17070        // [`WitShape::as_str`] `pub const fn` accessor resolve to the
17071        // same four-arm census-label emit-set across every arm the
17072        // exhaustive [`WitShape::ALL`] slice enumerates. Any future
17073        // silent detour that routes the trait impl through a divergent
17074        // projection (a per-arm inline `match shape { Http => "http", …
17075        // }` re-inlining that opens a compile-time link to the un-lifted
17076        // arm-literal outside the paired [`WitShape::as_str`] dispatch,
17077        // an accidental swap onto the sibling raw-identifier axis
17078        // [`WitShape::classify`] consumes that would collide the two-axis
17079        // wire/classifier split the sibling
17080        // `wit_shape_from_wire_and_classify_partition_the_axis` pin makes
17081        // load-bearing) trips at caixa-core test time under `assert_eq!`
17082        // rather than at a downstream `impl Into<&'static str>`-bound
17083        // consumer's silent split. Sweeps every one of the four arms
17084        // [`WitShape::ALL`] carries so no arm's projection is covered
17085        // only by the sibling method-named `as_str` /
17086        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
17087        // `<&'static str as From<WitShape>>::from` output in four
17088        // `const`-shape bindings against the paired [`WitShape::as_str`]
17089        // `pub const fn` accessor to make the `'static` lifetime promise
17090        // a build-time invariant — a future accidental downgrade of any
17091        // of the four arms' inline census-label byte-strings to a non-
17092        // `&'static str` (a `String::leak()`-produced return, a
17093        // `Box::leak`-cast, an intermediate lifetime-erasing helper)
17094        // trips at caixa-core build time rather than at a downstream
17095        // `'static`-bound consumer.
17096        //
17097        // Peer of the sibling
17098        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
17099        // (523157d),
17100        // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
17101        // (9fb37d0),
17102        // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
17103        // (edb827b),
17104        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
17105        // (c189a6f), and
17106        // [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
17107        // (afa3562) pins on the sibling closed-set typed-enum forward-
17108        // projection axes — extends the trait-idiomatic forward-
17109        // projection axis onto the sixth closed-set fieldless typed
17110        // enum on the caixa surface (the second M3-mesh-primitive-
17111        // defining slot enum, the `:contratos :wit` census-label axis
17112        // the caixa-mesh renderer keys off end-to-end).
17113        const HTTP: &str = WitShape::Http.as_str();
17114        const PUBSUB: &str = WitShape::PubSub.as_str();
17115        const STORE: &str = WitShape::Store.as_str();
17116        const CAPABILITY: &str = WitShape::Capability.as_str();
17117        for &variant in WitShape::ALL {
17118            let via_trait: &'static str = <&'static str as From<WitShape>>::from(variant);
17119            let via_method: &'static str = variant.as_str();
17120            assert_eq!(
17121                via_trait, via_method,
17122                "From<WitShape> for &'static str impl must round-trip \
17123                 WitShape::{variant:?} to the same census-label \
17124                 byte-string WitShape::as_str returns — divergence \
17125                 signals a silent detour off the substrate-primitive \
17126                 accessor"
17127            );
17128            let via_into: &'static str = variant.into();
17129            assert_eq!(
17130                via_into, via_method,
17131                "Into<&'static str>::into on WitShape::{variant:?} must \
17132                 byte-equal WitShape::as_str on the same input — the \
17133                 blanket-derived Into shape must resolve to the same \
17134                 as_str dispatch as the explicit From impl"
17135            );
17136        }
17137        assert_eq!(
17138            [HTTP, PUBSUB, STORE, CAPABILITY],
17139            ["http", "pubsub", "store", "capability"],
17140            "const-context WitShape::as_str must resolve to the four \
17141             canonical census-label byte-strings — a future accidental \
17142             downgrade of any arm to a non-const or non-static byte-\
17143             string breaks the `&'static str`-lifetime promise the \
17144             paired From<WitShape> for &'static str impl carries by \
17145             construction"
17146        );
17147    }
17148
17149    #[test]
17150    fn wit_shape_from_into_static_str_and_as_str_partition_the_emit_set() {
17151        // Cross-axis partition pin: the paired trait-idiomatic
17152        // `From<WitShape> for &'static str` forward projection and the
17153        // method-named [`WitShape::as_str`] forward projection must
17154        // resolve identically on *every* arm, not just the ones named
17155        // in the primary byte-parity pin above. Sweeps every
17156        // [`WitShape::ALL`] arm and asserts the trait's `From::from`
17157        // output byte-equals the method-named accessor's return-value
17158        // on each, locking the two forward-projection paths together by
17159        // construction so any future detour (a stray `From` special-case
17160        // that lands on a divergent per-arm literal outside the paired
17161        // `as_str` dispatch, a hypothetical rebrand touching one axis
17162        // without the other) trips at caixa-core test time.
17163        //
17164        // Peer of the sibling forward-projection partition pins
17165        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
17166        // (523157d),
17167        // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
17168        // (9fb37d0),
17169        // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
17170        // (edb827b),
17171        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
17172        // (c189a6f), and
17173        // [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
17174        // (afa3562) — extends the round-trip discipline onto the sixth
17175        // closed-set typed enum on the caixa surface, closing the two-
17176        // way `Self ↔ &'static str` round-trip on the trait-idiomatic
17177        // pair (`From<Self> for &'static str` + `TryFrom<&str> for
17178        // Self`) as well as the pre-existing method-named pair
17179        // (`as_str` + `from_wire`).
17180        for &variant in WitShape::ALL {
17181            let via_trait: &'static str = <&'static str as From<WitShape>>::from(variant);
17182            let via_method: &'static str = variant.as_str();
17183            assert_eq!(
17184                via_trait, via_method,
17185                "From<WitShape> for &'static str and WitShape::as_str \
17186                 must resolve identically on WitShape::{variant:?} — \
17187                 divergence signals the two forward-projection paths \
17188                 have drifted onto different emit-sets"
17189            );
17190        }
17191        // Round-trip witness: every arm's forward `From` output re-parses
17192        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
17193        // to the original variant. Closes the two-way `WitShape ↔
17194        // &'static str` round-trip on the trait-idiomatic axis pair
17195        // directly (no wire-vocab intermediate the peer [`CaixaKind`]
17196        // axis pair requires — the emit-side [`WitShape::as_str`] and
17197        // the parse-side [`WitShape::from_wire`] dispatch on the same
17198        // four inline census-label byte-strings by construction), and
17199        // in the same way the peer [`PlacementStrategy`] axis pair
17200        // (afa3562) closes on its three-arm surface — mirroring the
17201        // pre-existing method-named `as_str` + `from_wire` round-trip
17202        // on the substrate-primitive axis pair.
17203        for &variant in WitShape::ALL {
17204            let emitted: &'static str = variant.into();
17205            let re_parsed: Result<WitShape, ()> = <WitShape as TryFrom<&str>>::try_from(emitted);
17206            assert_eq!(
17207                re_parsed,
17208                Ok(variant),
17209                "trait-idiomatic axis pair must round-trip \
17210                 WitShape::{variant:?} through `.into::<&'static \
17211                 str>()` and back through `TryFrom<&str>` — a break \
17212                 signals the forward-emit and reverse-parse axes have \
17213                 drifted onto different vocabularies"
17214            );
17215        }
17216    }
17217
17218    #[test]
17219    fn wit_shape_from_borrowed_into_static_str_routes_through_as_str_accessor() {
17220        // Fail-before-pass-after byte-parity pin on the newly lifted
17221        // `impl From<&WitShape> for &'static str` — asserts the
17222        // borrowed-input standard-library trait impl and the
17223        // substrate-primitive [`WitShape::as_str`] `pub const fn`
17224        // accessor resolve to the same four-arm census-label emit-set
17225        // across every arm the exhaustive [`WitShape::ALL`] slice
17226        // enumerates. Rust's `From` trait does not auto-derive the
17227        // borrowed-input sibling from a paired owned-input impl (no
17228        // `impl<T, U> From<&T> for U where T: Copy, U: From<T>`
17229        // blanket in `core`), so the borrowed-input axis is a distinct
17230        // trait-idiomatic surface that a `.iter().map(Into::into)`
17231        // shape over [`WitShape::ALL`] (whose iterator yields
17232        // `&WitShape`, not `WitShape`) reaches through this impl and
17233        // no other — the paired owned-input [`From<WitShape>`] impl
17234        // requires an explicit `.copied()` / dereference before the
17235        // trait fires. Materializes the `<&'static str as
17236        // From<&WitShape>>::from` output in a `const`-shape binding to
17237        // make the `'static` lifetime promise a build-time invariant.
17238        // Peer of the sibling
17239        // [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
17240        // (64aa742) /
17241        // [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
17242        // (5ab993a) /
17243        // [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
17244        // (807b0b5) /
17245        // [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
17246        // (e941836) /
17247        // [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
17248        // (842c7f3) /
17249        // [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
17250        // (4d941d8) pins on the sibling closed-set typed-enum
17251        // borrowed-input forward-projection axes — extends the
17252        // borrowed-input axis onto the second M3-mesh-primitive-
17253        // defining closed-set typed enum on the caixa surface (the
17254        // `:contratos :wit` census-label axis the caixa-mesh renderer
17255        // keys off end-to-end for per-edge programs.yaml fan-out).
17256        const HTTP: &str = WitShape::Http.as_str();
17257        const PUBSUB: &str = WitShape::PubSub.as_str();
17258        const STORE: &str = WitShape::Store.as_str();
17259        const CAPABILITY: &str = WitShape::Capability.as_str();
17260        for variant in WitShape::ALL {
17261            let via_trait: &'static str = <&'static str as From<&WitShape>>::from(variant);
17262            let via_method: &'static str = variant.as_str();
17263            assert_eq!(
17264                via_trait, via_method,
17265                "From<&WitShape> for &'static str impl must round-trip \
17266                 &WitShape::{variant:?} to the same census-label \
17267                 byte-string WitShape::as_str returns — divergence \
17268                 signals a silent detour off the substrate-primitive \
17269                 accessor"
17270            );
17271            let via_into: &'static str = variant.into();
17272            assert_eq!(
17273                via_into, via_method,
17274                "Into<&'static str>::into on &WitShape::{variant:?} \
17275                 must byte-equal WitShape::as_str on the same input — \
17276                 the blanket-derived Into shape must resolve to the \
17277                 same as_str dispatch as the explicit From impl"
17278            );
17279        }
17280        assert_eq!(
17281            [HTTP, PUBSUB, STORE, CAPABILITY],
17282            ["http", "pubsub", "store", "capability"],
17283            "const-context WitShape::as_str must resolve to the four \
17284             canonical census-label byte-strings — the borrowed-input \
17285             From<&WitShape> for &'static str impl inherits its \
17286             `'static` lifetime promise from the same accessor the \
17287             owned-input sibling routes through"
17288        );
17289    }
17290
17291    #[test]
17292    fn wit_shape_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
17293        // Cross-axis partition pin: the paired trait-idiomatic
17294        // owned-input `From<WitShape> for &'static str` (56998ec
17295        // campaign-shape) and borrowed-input `From<&WitShape> for
17296        // &'static str` (this lift) forward projections must resolve
17297        // identically on every arm, locking the two input-shape paths
17298        // together so any future detour trips at caixa-core test time.
17299        // Then a witness that a `.iter().map(Into::into)` pipe over
17300        // [`WitShape::ALL`] (whose iterator yields `&WitShape`)
17301        // materializes the four-arm accept-set through the borrowed-
17302        // input axis alone — the exact shape a future M4 admission-
17303        // webhook rejection body's accepted-set enumeration, a future
17304        // substrate-wide per-arm diagnostic column, or a
17305        // `HashMap::<&'static str, WitShape>::from_iter(
17306        //     WitShape::ALL.iter().map(|s| (s.into(), *s)))`-style
17307        // per-shape lookup reaches through — closing the two-way
17308        // owned/borrowed input-shape symmetry on the M3 slot enum's
17309        // forward-projection trait-idiomatic axis. Peer of the sibling
17310        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
17311        // (64aa742) /
17312        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
17313        // (5ab993a) /
17314        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
17315        // (807b0b5) /
17316        // [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
17317        // (e941836) /
17318        // [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
17319        // (842c7f3) /
17320        // [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
17321        // (4d941d8) partition pins on the sibling closed-set typed-
17322        // enum discriminator axes — extends the borrowed-input axis
17323        // discipline onto the second M3-mesh-primitive-defining
17324        // closed-set typed enum on the caixa surface (the `:contratos
17325        // :wit` census-label axis). Also closes the direct two-way
17326        // `&Self → &'static str → Self` round-trip via the paired
17327        // [`TryFrom<&str>`] axis — unlike the peer [`crate::CaixaKind`]
17328        // axis pair (whose forward `From` emits lowercase Portuguese
17329        // diagnostic bytes while the reverse `TryFrom` parses
17330        // `PascalCase` wire bytes, forcing the round-trip through an
17331        // intermediate wire-vocab hop), the [`WitShape::as_str`] emit
17332        // and [`WitShape::from_wire`] parse share the same census-
17333        // label vocabulary by construction, so the borrowed-input
17334        // forward axis and the reverse axis compose directly.
17335        for &variant in WitShape::ALL {
17336            let owned: &'static str = <&'static str as From<WitShape>>::from(variant);
17337            let borrowed: &'static str = <&'static str as From<&WitShape>>::from(&variant);
17338            assert_eq!(
17339                owned, borrowed,
17340                "From<WitShape> and From<&WitShape> for &'static str \
17341                 must resolve identically on WitShape::{variant:?} — \
17342                 divergence signals the owned-input and borrowed-input \
17343                 forward-projection paths have drifted onto different \
17344                 emit-sets"
17345            );
17346        }
17347        let via_iter: Vec<&'static str> = WitShape::ALL.iter().map(Into::into).collect();
17348        let via_method: Vec<&'static str> = WitShape::ALL.iter().map(|s| s.as_str()).collect();
17349        assert_eq!(
17350            via_iter, via_method,
17351            "`.iter().map(Into::into)` over WitShape::ALL must \
17352             byte-equal `.iter().map(|s| s.as_str())` on every arm — \
17353             the borrowed-input `From<&WitShape> for &'static str` \
17354             axis is what makes the `.iter().map(Into::into)` shape \
17355             route through the substrate-primitive `WitShape::as_str` \
17356             accessor rather than through a per-call-site `.copied()` \
17357             / dereference detour"
17358        );
17359        for variant in WitShape::ALL {
17360            let emitted: &'static str = variant.into();
17361            let re_parsed: Result<WitShape, ()> = <WitShape as TryFrom<&str>>::try_from(emitted);
17362            assert_eq!(
17363                re_parsed,
17364                Ok(*variant),
17365                "trait-idiomatic borrowed-input forward-projection + \
17366                 reverse-projection axis pair must round-trip \
17367                 &WitShape::{variant:?} through `.into::<&'static \
17368                 str>()` (via the borrowed-input axis) and back \
17369                 through `TryFrom<&str>` — a break signals the \
17370                 borrowed-input forward-emit and reverse-parse axes \
17371                 have drifted onto different vocabularies"
17372            );
17373        }
17374    }
17375
17376    #[test]
17377    fn wit_shape_from_into_owned_string_routes_through_as_str_accessor() {
17378        // Fail-before-pass-after byte-parity pin on the newly lifted
17379        // `impl From<WitShape> for String` — asserts the owned-`String`-
17380        // returning standard-library trait impl and the substrate-
17381        // primitive [`WitShape::as_str`] `pub const fn` accessor
17382        // resolve to the same four-arm census-label emit-set across
17383        // every arm the exhaustive [`WitShape::ALL`] slice enumerates.
17384        // Rust's standard library does not carry a blanket
17385        // `impl<T: AsRef<str>> From<T> for String` (nor an
17386        // `impl<T: fmt::Display> From<T> for String`), so the
17387        // owned-`String` forward-projection axis is a distinct trait-
17388        // idiomatic surface that a `let key: String = shape.into();`-
17389        // shaped call site reaches through this impl and no other —
17390        // the paired sibling `From<WitShape> for &'static str` impl
17391        // forces every owned-`String` call site through an explicit
17392        // `.to_owned()` / `String::from` restatement. Peer of the
17393        // first-mover
17394        // [`crate::supervisor::tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
17395        // (7baa18a), the second-peer
17396        // [`crate::supervisor::tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
17397        // (7851725), the third-peer
17398        // [`crate::kind::tests::caixa_kind_from_into_owned_string_routes_through_as_str_accessor`]
17399        // (231a18c), the fourth-peer
17400        // [`crate::dialeto::tests::caixa_dialeto_from_into_owned_string_routes_through_as_str_accessor`]
17401        // (88942cd), the fifth-peer
17402        // [`crate::dep::tests::dep_list_from_into_owned_string_routes_through_as_str_accessor`]
17403        // (32b0ee8), and the sixth-peer
17404        // [`tests::placement_strategy_from_into_owned_string_routes_through_as_str_accessor`]
17405        // (1154c2f) — extends the trait-idiomatic owned-`String`
17406        // forward-projection axis onto the seventh closed-set fieldless
17407        // typed enum on the caixa surface (the second
17408        // M3-mesh-primitive-defining `:contratos :wit` census-label
17409        // axis).
17410        for &variant in WitShape::ALL {
17411            let via_trait: String = <String as From<WitShape>>::from(variant);
17412            let via_method: &'static str = variant.as_str();
17413            assert_eq!(
17414                via_trait.as_str(),
17415                via_method,
17416                "From<WitShape> for String impl must round-trip \
17417                 WitShape::{variant:?} to the same four-arm census-label \
17418                 byte-string WitShape::as_str returns — divergence \
17419                 signals a silent detour off the substrate-primitive \
17420                 accessor"
17421            );
17422            let via_into: String = variant.into();
17423            assert_eq!(
17424                via_into.as_str(),
17425                via_method,
17426                "Into<String>::into on WitShape::{variant:?} must \
17427                 byte-equal WitShape::as_str on the same input — the \
17428                 blanket-derived Into shape must resolve to the same \
17429                 as_str dispatch as the explicit From impl"
17430            );
17431        }
17432    }
17433
17434    #[test]
17435    fn wit_shape_from_into_owned_string_and_static_str_agree_on_every_arm() {
17436        // Cross-axis partition pin: the paired trait-idiomatic
17437        // owned-`String` `From<WitShape> for String` (this lift) and
17438        // owned-`&'static str` `From<WitShape> for &'static str`
17439        // (56998ec) forward projections must resolve identically on
17440        // every arm, locking the two return-type-shape paths together
17441        // so any future detour trips at caixa-core test time. Also
17442        // byte-parity witness against the sibling
17443        // [`ToString::to_string`] surface routed through
17444        // [`std::fmt::Display`] — the three owned-heap-string paths
17445        // (`.into::<String>()`, `String::from`, `.to_string()`) must
17446        // resolve identically on every arm so a future consumer that
17447        // picks any of the three lands on the same four-arm inline
17448        // census-label accept-set. Then a
17449        // `.iter().copied().map(String::from)` pipe witness over
17450        // [`WitShape::ALL`] that materializes the four-arm accept-set
17451        // through the owned-`String` axis alone — the exact shape a
17452        // future M4 admission-webhook rejection body composer or a
17453        // `HashMap::<String, WitShape>::from_iter(WitShape::ALL.iter()
17454        //     .copied().map(|s| (s.into(), s)))`-style owned-key
17455        // per-shape lookup reaches through — closing the owned-`String`
17456        // forward-projection axis's iterator-pipe shape. Then a direct
17457        // round-trip witness through the paired trait-idiomatic reverse
17458        // [`TryFrom<&str>`] axis on the owned-`String`'s
17459        // [`String::as_str`] borrow that closes the two-way `Self →
17460        // String → Self` round-trip on the trait-idiomatic
17461        // owned-`String` forward + reverse axis pair.
17462        //
17463        // Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
17464        // `From` emit lands on the lowercase Portuguese `as_str`
17465        // diagnostic vocabulary while the reverse `TryFrom<&str>`
17466        // parses the `PascalCase` `wire_name` author-surface
17467        // vocabulary, forcing the round-trip through an intermediate
17468        // [`crate::CaixaKind::wire_name`] hop), [`WitShape`]'s
17469        // [`WitShape::as_str`] emit and [`WitShape::from_wire`] parse
17470        // resolve through the same four inline census-label
17471        // byte-strings by construction (there is no wire/diagnostic
17472        // axis split on this enum), so the owned-`String` forward axis
17473        // and the reverse axis compose directly — matching the peer
17474        // [`crate::supervisor::RestartStrategy`] /
17475        // [`crate::supervisor::RestartPolicy`] /
17476        // [`crate::CaixaDialeto`] / [`crate::dep::DepList`] /
17477        // [`PlacementStrategy`] owned-`String` axis pairs.
17478        for &variant in WitShape::ALL {
17479            let owned_string: String = <String as From<WitShape>>::from(variant);
17480            let owned_static: &'static str = <&'static str as From<WitShape>>::from(variant);
17481            assert_eq!(
17482                owned_string.as_str(),
17483                owned_static,
17484                "From<WitShape> for String and From<WitShape> for \
17485                 &'static str must resolve identically on \
17486                 WitShape::{variant:?} — divergence signals the \
17487                 owned-`String` and owned-`&'static str` forward-\
17488                 projection return-type-shape paths have drifted onto \
17489                 different emit-sets"
17490            );
17491            let via_to_string: String = variant.to_string();
17492            assert_eq!(
17493                owned_string, via_to_string,
17494                "From<WitShape> for String must byte-equal \
17495                 WitShape::to_string on WitShape::{variant:?} — \
17496                 divergence signals the trait-idiomatic owned-`String` \
17497                 forward-projection axis and the ToString-through-\
17498                 Display axis have drifted onto different emit-sets"
17499            );
17500        }
17501        let via_iter: Vec<String> = WitShape::ALL.iter().copied().map(String::from).collect();
17502        let via_method: Vec<String> = WitShape::ALL
17503            .iter()
17504            .map(|s| s.as_str().to_owned())
17505            .collect();
17506        assert_eq!(
17507            via_iter, via_method,
17508            "`.iter().copied().map(String::from)` over WitShape::ALL \
17509             must byte-equal `.iter().map(|s| s.as_str().to_owned())` \
17510             on every arm — the owned-`String` `From<WitShape> for \
17511             String` axis is what makes the `String::from` composition \
17512             route through the substrate-primitive `WitShape::as_str` \
17513             accessor rather than through a per-call-site `.to_owned()` \
17514             / `String::from(shape.as_str())` detour"
17515        );
17516        for &variant in WitShape::ALL {
17517            let emitted: String = variant.into();
17518            let re_parsed: Result<WitShape, ()> =
17519                <WitShape as TryFrom<&str>>::try_from(emitted.as_str());
17520            assert_eq!(
17521                re_parsed,
17522                Ok(variant),
17523                "trait-idiomatic owned-`String` forward-projection + \
17524                 reverse-projection axis pair must round-trip \
17525                 WitShape::{variant:?} through `.into::<String>()` and \
17526                 back through `TryFrom<&str>` on the owned-`String`'s \
17527                 String::as_str borrow — a break signals the \
17528                 owned-`String` forward-emit and reverse-parse axes \
17529                 have drifted onto different vocabularies (unlike the \
17530                 peer CaixaKind axis pair, WitShape's forward emit and \
17531                 reverse parse share the same four inline census-label \
17532                 byte-strings by construction, so the round-trip \
17533                 composes directly)"
17534            );
17535        }
17536    }
17537
17538    #[test]
17539    fn wit_shape_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
17540        // Fail-before-pass-after byte-parity pin on the newly lifted
17541        // `impl From<&WitShape> for String` — asserts the borrowed-input
17542        // owned-`String`-returning standard-library trait impl and the
17543        // substrate-primitive [`WitShape::as_str`] `pub const fn`
17544        // accessor resolve to the same four-arm census-label emit-set
17545        // across every arm the exhaustive [`WitShape::ALL`] slice
17546        // enumerates. Rust's standard library does not carry a blanket
17547        // `impl<T: AsRef<str>> From<&T> for String` (nor an
17548        // `impl<T: fmt::Display> From<&T> for String`), so the
17549        // borrowed-input owned-`String` forward-projection axis is a
17550        // distinct trait-idiomatic surface that a
17551        // `let key: String = (&shape).into();`-shaped call site reaches
17552        // through this impl and no other — the paired sibling
17553        // `From<WitShape> for String` impl forces every borrowed-input
17554        // call site through an explicit `Copy` deref
17555        // (`String::from(*shape)`) or an `.as_str().to_owned()` /
17556        // `.to_string()` detour. Peer of the first-mover
17557        // [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
17558        // (579385f), the second-peer
17559        // [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
17560        // (8465740), the third-peer
17561        // [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
17562        // (e0cb617), the fourth-peer
17563        // [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
17564        // (e76436d), the fifth-peer
17565        // [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
17566        // (d3c0d1d), and the sixth-peer
17567        // [`tests::placement_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
17568        // (d3dc000) — extends the trait-idiomatic borrowed-input owned-
17569        // `String` forward-projection axis onto the seventh closed-set
17570        // fieldless typed enum on the caixa surface (the second
17571        // M3-mesh-primitive-defining `:contratos :wit` census-label
17572        // axis).
17573        for &variant in WitShape::ALL {
17574            let via_trait: String = <String as From<&WitShape>>::from(&variant);
17575            let via_method: &'static str = variant.as_str();
17576            assert_eq!(
17577                via_trait.as_str(),
17578                via_method,
17579                "From<&WitShape> for String impl must round-trip \
17580                 &WitShape::{variant:?} to the same four-arm census-\
17581                 label byte-string WitShape::as_str returns — \
17582                 divergence signals a silent detour off the substrate-\
17583                 primitive accessor"
17584            );
17585            let via_into: String = (&variant).into();
17586            assert_eq!(
17587                via_into.as_str(),
17588                via_method,
17589                "Into<String>::into on &WitShape::{variant:?} must \
17590                 byte-equal WitShape::as_str on the same input — the \
17591                 blanket-derived Into shape must resolve to the same \
17592                 as_str dispatch as the explicit From impl"
17593            );
17594        }
17595    }
17596
17597    #[test]
17598    fn wit_shape_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
17599        // Cross-axis partition pin: the newly lifted trait-idiomatic
17600        // borrowed-input owned-`String` `From<&WitShape> for String`
17601        // (this lift), the paired owned-input owned-`String`
17602        // `From<WitShape> for String` (79a8723), the paired
17603        // borrowed-input owned-`&'static str`
17604        // `From<&WitShape> for &'static str` (3187bd0), and the paired
17605        // owned-input owned-`&'static str` `From<WitShape> for &'static
17606        // str` (56998ec) — every corner of the
17607        // `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
17608        // projection family — must resolve identically on every arm,
17609        // locking the four return-shape × input-shape paths together so
17610        // any future detour trips at caixa-core test time. Also
17611        // byte-parity witness against the sibling
17612        // [`ToString::to_string`] surface routed through
17613        // [`std::fmt::Display`] and a direct round-trip witness through
17614        // the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
17615        // the owned-`String`'s [`String::as_str`] borrow that closes
17616        // the two-way `&Self → String → Self` round-trip on the trait-
17617        // idiomatic borrowed-input owned-`String` forward + reverse
17618        // axis pair. Peer of the first-mover
17619        // [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
17620        // (579385f), the second-peer
17621        // [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
17622        // (8465740), the third-peer
17623        // [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
17624        // (e0cb617), the fourth-peer
17625        // [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
17626        // (e76436d), the fifth-peer
17627        // [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
17628        // (d3c0d1d), and the sixth-peer
17629        // [`tests::placement_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
17630        // (d3dc000) — closes the whole
17631        // `{Self, &Self} × {&'static str, String}` 2×2 projection
17632        // corner on the seventh substrate-wide closed-set fieldless
17633        // typed enum peer (the second M3-mesh-primitive-defining
17634        // `:contratos :wit` census-label axis, second M3 slot enum to
17635        // reach the 2×2-completion corner).
17636        //
17637        // Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
17638        // `From` emit lands on the lowercase Portuguese `as_str`
17639        // diagnostic vocabulary while the reverse `TryFrom<&str>`
17640        // parses the `PascalCase` `wire_name` author-surface
17641        // vocabulary, forcing the round-trip through an intermediate
17642        // [`crate::CaixaKind::wire_name`] hop), [`WitShape`]'s
17643        // [`WitShape::as_str`] emit and [`WitShape::from_wire`] parse
17644        // resolve through the same four inline census-label byte-\
17645        // strings by construction (there is no wire/diagnostic axis
17646        // split on this M3 slot enum), so the borrowed-input owned-\
17647        // `String` forward axis and the reverse axis compose directly
17648        // — matching the peer [`crate::supervisor::RestartStrategy`] /
17649        // [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`]
17650        // / [`crate::CaixaDialeto`] / [`PlacementStrategy`] borrowed-\
17651        // input owned-`String` axis pairs.
17652        for &variant in WitShape::ALL {
17653            let borrowed_string: String = <String as From<&WitShape>>::from(&variant);
17654            let owned_string: String = <String as From<WitShape>>::from(variant);
17655            let borrowed_static: &'static str = <&'static str as From<&WitShape>>::from(&variant);
17656            let owned_static: &'static str = <&'static str as From<WitShape>>::from(variant);
17657            assert_eq!(
17658                borrowed_string, owned_string,
17659                "From<&WitShape> for String and From<WitShape> for \
17660                 String must resolve identically on WitShape::\
17661                 {variant:?} — divergence signals the borrowed-input \
17662                 and owned-input owned-`String` forward-projection \
17663                 input-shape paths have drifted onto different \
17664                 emit-sets"
17665            );
17666            assert_eq!(
17667                borrowed_string.as_str(),
17668                borrowed_static,
17669                "From<&WitShape> for String and From<&WitShape> for \
17670                 &'static str must resolve identically on WitShape::\
17671                 {variant:?} — divergence signals the borrowed-input \
17672                 `&'static str` and owned-`String` return-shape paths \
17673                 have drifted onto different emit-sets"
17674            );
17675            assert_eq!(
17676                borrowed_string.as_str(),
17677                owned_static,
17678                "From<&WitShape> for String and From<WitShape> for \
17679                 &'static str must resolve identically on WitShape::\
17680                 {variant:?} — divergence signals a break in the \
17681                 diagonal corner of the {{Self, &Self}} × {{&'static \
17682                 str, String}} 2×2 trait-idiomatic projection family"
17683            );
17684            let via_to_string: String = variant.to_string();
17685            assert_eq!(
17686                borrowed_string, via_to_string,
17687                "From<&WitShape> for String must byte-equal WitShape::\
17688                 to_string on WitShape::{variant:?} — divergence \
17689                 signals the trait-idiomatic borrowed-input owned-\
17690                 `String` forward-projection axis and the ToString-\
17691                 through-Display axis have drifted onto different \
17692                 emit-sets"
17693            );
17694        }
17695        let via_iter: Vec<String> = WitShape::ALL.iter().map(String::from).collect();
17696        let via_method: Vec<String> = WitShape::ALL
17697            .iter()
17698            .map(|s| s.as_str().to_owned())
17699            .collect();
17700        assert_eq!(
17701            via_iter, via_method,
17702            "`.iter().map(String::from)` over WitShape::ALL — a call \
17703             site whose iteration axis holds `&WitShape` by \
17704             construction — must byte-equal `.iter().map(|s| \
17705             s.as_str().to_owned())` on every arm — the borrowed-input \
17706             owned-`String` `From<&WitShape> for String` axis is what \
17707             makes the `String::from` composition route through the \
17708             substrate-primitive `WitShape::as_str` accessor without a \
17709             spurious `Copy` deref (which would only be reachable \
17710             through the owned-input `From<WitShape> for String` axis \
17711             by first calling `.copied()` on the iterator)"
17712        );
17713        for &variant in WitShape::ALL {
17714            let emitted: String = (&variant).into();
17715            let re_parsed: Result<WitShape, ()> =
17716                <WitShape as TryFrom<&str>>::try_from(emitted.as_str());
17717            assert_eq!(
17718                re_parsed,
17719                Ok(variant),
17720                "trait-idiomatic borrowed-input owned-`String` \
17721                 forward-projection + reverse-projection axis pair \
17722                 must round-trip &WitShape::{variant:?} through \
17723                 `.into::<String>()` on the borrowed-input surface and \
17724                 back through `TryFrom<&str>` on the owned-`String`'s \
17725                 String::as_str borrow — a break signals the borrowed-\
17726                 input owned-`String` forward-emit and reverse-parse \
17727                 axes have drifted onto different vocabularies (unlike \
17728                 the peer CaixaKind axis pair, WitShape's forward emit \
17729                 and reverse parse share the same four inline census-\
17730                 label byte-strings by construction, so the round-trip \
17731                 composes directly)"
17732            );
17733        }
17734    }
17735
17736    #[test]
17737    fn wit_shape_from_into_static_cow_str_routes_through_as_str_accessor() {
17738        // Fail-before-pass-after byte-parity pin on the newly lifted
17739        // `impl From<WitShape> for std::borrow::Cow<'static, str>` —
17740        // asserts the standard-library trait impl and the substrate-
17741        // primitive [`super::WitShape::as_str`] `pub const fn`
17742        // accessor resolve to the same four-arm emit-set across every
17743        // arm the exhaustive [`super::WitShape::ALL`] slice
17744        // enumerates. Rust's standard library does not carry a
17745        // blanket `impl<T: AsRef<str>> From<T> for Cow<'static, str>`
17746        // (nor an `impl<T: fmt::Display> From<T> for
17747        // Cow<'static, str>`), so the `Cow<'static, str>` forward-
17748        // projection axis is a distinct trait-idiomatic surface that
17749        // a `let key: Cow<'static, str> = shape.into();`-shaped call
17750        // site reaches through this impl and no other — the paired
17751        // sibling `From<WitShape> for &'static str` and
17752        // `From<WitShape> for String` impls force every
17753        // `Cow<'static, str>`-parameterized call site through a
17754        // `Cow::Borrowed(shape.as_str())` /
17755        // `Cow::Owned(shape.to_string())` composition whose type
17756        // bounds have no compile-time link back to the substrate
17757        // primitive.
17758        //
17759        // Also asserts the projection lands on the zero-alloc
17760        // [`std::borrow::Cow::Borrowed`] arm (not the
17761        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
17762        // [`super::WitShape::as_str`] accessor's `&'static str`
17763        // return lifetime by construction (inline `"http"` /
17764        // `"pubsub"` / `"store"` / `"capability"` byte-string
17765        // literals) makes the borrowed arm the type-correct
17766        // projection with no runtime allocation. Any future silent
17767        // detour that routes the impl through the owned arm (an
17768        // accidental `Cow::Owned(shape.to_string())` rewrite that
17769        // would allocate on every call site where the `&'static str`
17770        // return of [`super::WitShape::as_str`] makes the zero-alloc
17771        // borrowed projection type-correct) trips at caixa-core test
17772        // time under the [`std::borrow::Cow::Borrowed`] discriminator
17773        // witness rather than at a downstream
17774        // `Cow<'static, str>`-bound consumer's silent allocation.
17775        //
17776        // First-mover on the M3 mesh-shape tier of the substrate-wide
17777        // trait-idiomatic [`std::borrow::Cow<'static, str>`] forward-
17778        // projection campaign — extends the axis off the M2 OTP-shape
17779        // tier (whose whole peer set — CaixaKind first-mover 99c1735
17780        // + d45c409, RestartStrategy 7dd28b3 + 9b3e4b3, RestartPolicy
17781        // 0612398 + ee577fd — closed on the {Self, &Self} corner)
17782        // onto the first M3-mesh-primitive-defining slot enum. Every
17783        // remaining M3 slot enum peer ([`PlacementStrategy`],
17784        // [`RateLimitUnit`]) and the outside-M3 substrate-wide peers
17785        // are future targets.
17786        for &variant in WitShape::ALL {
17787            let via_trait: std::borrow::Cow<'static, str> =
17788                <std::borrow::Cow<'static, str> as From<WitShape>>::from(variant);
17789            let via_method: &'static str = variant.as_str();
17790            assert_eq!(
17791                via_trait.as_ref(),
17792                via_method,
17793                "From<WitShape> for Cow<'static, str> impl must \
17794                 round-trip WitShape::{variant:?} to the same inline \
17795                 census-label byte-string WitShape::as_str returns — \
17796                 divergence signals a silent detour off the \
17797                 substrate-primitive accessor"
17798            );
17799            assert!(
17800                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
17801                "From<WitShape> for Cow<'static, str> impl must land \
17802                 on the zero-alloc Cow::Borrowed arm on WitShape::\
17803                 {variant:?} — a Cow::Owned outcome signals the \
17804                 projection has silently allocated where the \
17805                 substrate-primitive WitShape::as_str `&'static str` \
17806                 return makes the borrowed arm the type-correct \
17807                 projection"
17808            );
17809            let via_into: std::borrow::Cow<'static, str> = variant.into();
17810            assert_eq!(
17811                via_into.as_ref(),
17812                via_method,
17813                "Into<Cow<'static, str>>::into on WitShape::\
17814                 {variant:?} must byte-equal WitShape::as_str on the \
17815                 same input — the blanket-derived Into shape must \
17816                 resolve to the same as_str dispatch as the explicit \
17817                 From impl"
17818            );
17819            assert!(
17820                matches!(via_into, std::borrow::Cow::Borrowed(_)),
17821                "Into<Cow<'static, str>>::into on WitShape::\
17822                 {variant:?} must land on the zero-alloc \
17823                 Cow::Borrowed arm — the blanket-derived Into shape \
17824                 must resolve to the same Cow::Borrowed dispatch as \
17825                 the explicit From impl"
17826            );
17827        }
17828    }
17829
17830    #[test]
17831    fn wit_shape_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
17832        // Cross-axis partition pin: the newly lifted trait-idiomatic
17833        // `From<WitShape> for std::borrow::Cow<'static, str>` (this
17834        // lift), the paired owned-input `From<WitShape> for &'static
17835        // str`, and the paired owned-input `From<WitShape> for
17836        // String` forward projections must resolve identically on
17837        // every arm, locking the three return-shape paths together by
17838        // construction so any future detour trips at caixa-core test
17839        // time. Also byte-parity witness against the sibling
17840        // [`ToString::to_string`] surface routed through
17841        // [`std::fmt::Display`] — every owned-heap-string path (the
17842        // `Cow::Owned` promotion of this axis's `.into_owned()`,
17843        // `From<WitShape> for String`, and `.to_string()`) resolves
17844        // to the same four-arm inline census-label byte-string per
17845        // arm.
17846        //
17847        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
17848        // witness over [`super::WitShape::ALL`] that materializes the
17849        // four-arm accept-set through the [`std::borrow::Cow<'static,
17850        // str>`] axis alone — the exact shape a future M4
17851        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
17852        // rejection body's accepted-`:contratos :wit` census-label
17853        // enumeration, a future substrate-wide per-arm diagnostic
17854        // surface whose typing rules out the sibling [`AsRef<str>`]
17855        // borrowed return, or a future per-arm WIT-shape emitter that
17856        // binds through a [`Cow<'static, str>`] boundary reaches
17857        // through — closing the composable-projection axis on the
17858        // first M3 mesh-primitive-defining closed-set fieldless typed
17859        // enum peer on the caixa surface. The pipe witness also pins
17860        // the zero-alloc discipline: every element in the collected
17861        // vector satisfies the [`std::borrow::Cow::Borrowed`] arm
17862        // predicate, so a future accidental silent-allocation
17863        // regression on the pipe's iteration axis is a caixa-core-
17864        // test-time failure.
17865        for &variant in WitShape::ALL {
17866            let via_cow: std::borrow::Cow<'static, str> =
17867                <std::borrow::Cow<'static, str> as From<WitShape>>::from(variant);
17868            let via_static: &'static str = <&'static str as From<WitShape>>::from(variant);
17869            let via_string: String = <String as From<WitShape>>::from(variant);
17870            assert_eq!(
17871                via_cow.as_ref(),
17872                via_static,
17873                "From<WitShape> for Cow<'static, str> and \
17874                 From<WitShape> for &'static str must resolve \
17875                 identically on WitShape::{variant:?} — divergence \
17876                 signals the Cow<'static, str> and &'static str \
17877                 return-shape paths have drifted onto different \
17878                 emit-sets"
17879            );
17880            assert_eq!(
17881                via_cow.as_ref(),
17882                via_string.as_str(),
17883                "From<WitShape> for Cow<'static, str> and \
17884                 From<WitShape> for String must resolve identically \
17885                 on WitShape::{variant:?} — divergence signals the \
17886                 Cow<'static, str> and String return-shape paths \
17887                 have drifted onto different emit-sets"
17888            );
17889            let via_to_string: String = variant.to_string();
17890            assert_eq!(
17891                via_cow.as_ref(),
17892                via_to_string.as_str(),
17893                "From<WitShape> for Cow<'static, str> must byte-\
17894                 equal WitShape::to_string on WitShape::{variant:?} \
17895                 — divergence signals the trait-idiomatic \
17896                 Cow<'static, str> forward-projection axis and the \
17897                 ToString-through-Display axis have drifted onto \
17898                 different emit-sets"
17899            );
17900        }
17901        let via_iter: Vec<std::borrow::Cow<'static, str>> = WitShape::ALL
17902            .iter()
17903            .copied()
17904            .map(std::borrow::Cow::from)
17905            .collect();
17906        let via_method: Vec<std::borrow::Cow<'static, str>> = WitShape::ALL
17907            .iter()
17908            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
17909            .collect();
17910        assert_eq!(
17911            via_iter, via_method,
17912            "`.iter().copied().map(Cow::from)` over WitShape::ALL \
17913             must byte-equal `.iter().map(|s| \
17914             Cow::Borrowed(s.as_str()))` on every arm — the trait-\
17915             idiomatic `From<WitShape> for Cow<'static, str>` axis \
17916             is what makes the `Cow::from` composition route through \
17917             the substrate-primitive `WitShape::as_str` accessor \
17918             with the zero-alloc Cow::Borrowed arm by construction, \
17919             rather than a per-call-site \
17920             `Cow::Owned(shape.to_string())` allocation"
17921        );
17922        for cow in &via_iter {
17923            assert!(
17924                matches!(cow, std::borrow::Cow::Borrowed(_)),
17925                "every element of the .iter().copied().map(Cow::from) \
17926                 pipe over WitShape::ALL must land on the zero-alloc \
17927                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
17928                 signals the pipe's iteration axis has silently \
17929                 allocated where the substrate-primitive \
17930                 WitShape::as_str `&'static str` return makes the \
17931                 borrowed arm the type-correct projection"
17932            );
17933        }
17934    }
17935
17936    #[test]
17937    fn wit_shape_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
17938        // Fail-before-pass-after byte-parity pin on the newly lifted
17939        // `impl From<&WitShape> for std::borrow::Cow<'static, str>` —
17940        // asserts the borrowed-input standard-library trait impl and
17941        // the substrate-primitive [`super::WitShape::as_str`]
17942        // `pub const fn` accessor resolve to the same four-arm emit-
17943        // set across every arm the exhaustive
17944        // [`super::WitShape::ALL`] slice enumerates. Rust's standard
17945        // library does not carry a blanket
17946        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
17947        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
17948        // so the borrowed-input `Cow<'static, str>` forward-
17949        // projection axis is a distinct trait-idiomatic surface that
17950        // a `let key: Cow<'static, str> = (&shape).into();`-shaped
17951        // call site or a
17952        // `WitShape::ALL.iter().map(Cow::from)`-shaped pipe reaches
17953        // through this impl and no other — the paired owned-input
17954        // `From<WitShape> for Cow<'static, str>` impl (8634dec)
17955        // forces every borrowed-input call site through an explicit
17956        // `Copy` deref (`Cow::from(*shape)`) or a
17957        // `Cow::Borrowed(shape.as_str())` open-code whose type bounds
17958        // have no compile-time link back to the substrate primitive.
17959        //
17960        // Also asserts the projection lands on the zero-alloc
17961        // [`std::borrow::Cow::Borrowed`] arm (not the
17962        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
17963        // [`super::WitShape::as_str`] accessor's `&'static str`
17964        // return lifetime by construction (inline `"http"` /
17965        // `"pubsub"` / `"store"` / `"capability"` byte-string
17966        // literals) makes the borrowed arm the type-correct
17967        // projection with no runtime allocation on the borrowed-input
17968        // surface just as on the paired owned-input surface.
17969        //
17970        // Closes the `{Self, &Self}` input-shape corner on the M3-
17971        // mesh-shape `:contratos :wit` census-label
17972        // [`Cow<'static, str>`] axis on the first M3-mesh-primitive-
17973        // defining closed-set fieldless typed enum peer on the caixa
17974        // surface, exactly as d45c409 closed it on the top-level
17975        // [`super::CaixaKind`] one commit after the owning half
17976        // (99c1735) landed and as 9b3e4b3 / ee577fd closed it on the
17977        // M2 OTP-shape [`crate::supervisor::RestartStrategy`] /
17978        // [`crate::supervisor::RestartPolicy`] sibling peers one
17979        // commit after (7dd28b3 / 0612398) landed.
17980        for &variant in WitShape::ALL {
17981            let via_trait: std::borrow::Cow<'static, str> =
17982                <std::borrow::Cow<'static, str> as From<&WitShape>>::from(&variant);
17983            let via_method: &'static str = variant.as_str();
17984            assert_eq!(
17985                via_trait.as_ref(),
17986                via_method,
17987                "From<&WitShape> for Cow<'static, str> impl must \
17988                 round-trip &WitShape::{variant:?} to the same inline \
17989                 census-label byte-string WitShape::as_str returns — \
17990                 divergence signals a silent detour off the \
17991                 substrate-primitive accessor"
17992            );
17993            assert!(
17994                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
17995                "From<&WitShape> for Cow<'static, str> impl must land \
17996                 on the zero-alloc Cow::Borrowed arm on \
17997                 &WitShape::{variant:?} — a Cow::Owned outcome \
17998                 signals the projection has silently allocated where \
17999                 the substrate-primitive WitShape::as_str `&'static \
18000                 str` return makes the borrowed arm the type-correct \
18001                 projection"
18002            );
18003            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
18004            assert_eq!(
18005                via_into.as_ref(),
18006                via_method,
18007                "Into<Cow<'static, str>>::into on \
18008                 &WitShape::{variant:?} must byte-equal \
18009                 WitShape::as_str on the same input — the blanket-\
18010                 derived Into shape must resolve to the same as_str \
18011                 dispatch as the explicit From impl"
18012            );
18013            assert!(
18014                matches!(via_into, std::borrow::Cow::Borrowed(_)),
18015                "Into<Cow<'static, str>>::into on \
18016                 &WitShape::{variant:?} must land on the zero-alloc \
18017                 Cow::Borrowed arm — the blanket-derived Into shape \
18018                 must resolve to the same Cow::Borrowed dispatch as \
18019                 the explicit From impl"
18020            );
18021        }
18022    }
18023
18024    #[test]
18025    fn wit_shape_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
18026        // Cross-axis partition pin: the newly lifted trait-idiomatic
18027        // borrowed-input `From<&WitShape> for std::borrow::Cow<'static,
18028        // str>` (this lift), the paired owned-input `From<WitShape>
18029        // for std::borrow::Cow<'static, str>` (8634dec), the paired
18030        // borrowed-input owned-`&'static str` `From<&WitShape> for
18031        // &'static str`, and the paired borrowed-input owned-`String`
18032        // `From<&WitShape> for String` must resolve identically on
18033        // every arm, locking the four return-shape × input-shape
18034        // paths together by construction so any future detour trips
18035        // at caixa-core test time. Also byte-parity witness against
18036        // the sibling [`ToString::to_string`] surface routed through
18037        // [`std::fmt::Display`] — every owned-heap-string path (this
18038        // axis's `.into_owned()` promotion, the paired
18039        // [`From<&WitShape> for String`], and `.to_string()`)
18040        // resolves to the same four-arm inline census-label byte-
18041        // string per arm.
18042        //
18043        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
18044        // over [`super::WitShape::ALL`] — whose iterator yields
18045        // `&WitShape` by construction, so the borrowed-input
18046        // [`Cow<'static, str>`] axis is what routes the pipe through
18047        // the substrate-primitive [`super::WitShape::as_str`]
18048        // accessor without a spurious [`Copy`] deref (which would
18049        // only be reachable through the owned-input
18050        // [`From<WitShape> for Cow<'static, str>`] axis by first
18051        // calling `.copied()` on the iterator). The pipe witness
18052        // also pins the zero-alloc discipline: every element in the
18053        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
18054        // arm predicate, so a future accidental silent-allocation
18055        // regression on the pipe's iteration axis is a caixa-core-
18056        // test-time failure. Peer of the sibling
18057        // [`restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
18058        // (ee577fd) on the M2 OTP-shape per-child-restart axis —
18059        // extends the whole borrowed-input `Cow<'static, str>` +
18060        // paired `{&'static str, String}` cross-axis-parity corner
18061        // onto the first M3 mesh-primitive-defining closed-set
18062        // fieldless typed enum peer on the caixa surface.
18063        for &shape in WitShape::ALL {
18064            let borrowed_cow: std::borrow::Cow<'static, str> =
18065                <std::borrow::Cow<'static, str> as From<&WitShape>>::from(&shape);
18066            let owned_cow: std::borrow::Cow<'static, str> =
18067                <std::borrow::Cow<'static, str> as From<WitShape>>::from(shape);
18068            let borrowed_static: &'static str = <&'static str as From<&WitShape>>::from(&shape);
18069            let borrowed_string: String = <String as From<&WitShape>>::from(&shape);
18070            assert_eq!(
18071                borrowed_cow, owned_cow,
18072                "From<&WitShape> for Cow<'static, str> and \
18073                 From<WitShape> for Cow<'static, str> must resolve \
18074                 identically on WitShape::{shape:?} — divergence \
18075                 signals the borrowed-input and owned-input \
18076                 Cow<'static, str> forward-projection input-shape \
18077                 paths have drifted onto different emit-sets"
18078            );
18079            assert_eq!(
18080                borrowed_cow.as_ref(),
18081                borrowed_static,
18082                "From<&WitShape> for Cow<'static, str> and \
18083                 From<&WitShape> for &'static str must resolve \
18084                 identically on WitShape::{shape:?} — divergence \
18085                 signals the borrowed-input Cow<'static, str> and \
18086                 &'static str return-shape paths have drifted onto \
18087                 different emit-sets"
18088            );
18089            assert_eq!(
18090                borrowed_cow.as_ref(),
18091                borrowed_string.as_str(),
18092                "From<&WitShape> for Cow<'static, str> and \
18093                 From<&WitShape> for String must resolve identically \
18094                 on WitShape::{shape:?} — divergence signals the \
18095                 borrowed-input Cow<'static, str> and owned-`String` \
18096                 return-shape paths have drifted onto different \
18097                 emit-sets"
18098            );
18099            let via_to_string: String = shape.to_string();
18100            assert_eq!(
18101                borrowed_cow.as_ref(),
18102                via_to_string.as_str(),
18103                "From<&WitShape> for Cow<'static, str> must byte-\
18104                 equal WitShape::to_string on WitShape::{shape:?} — \
18105                 divergence signals the trait-idiomatic borrowed-\
18106                 input Cow<'static, str> forward-projection axis and \
18107                 the ToString-through-Display axis have drifted onto \
18108                 different emit-sets"
18109            );
18110        }
18111        let via_iter: Vec<std::borrow::Cow<'static, str>> =
18112            WitShape::ALL.iter().map(std::borrow::Cow::from).collect();
18113        let via_method: Vec<std::borrow::Cow<'static, str>> = WitShape::ALL
18114            .iter()
18115            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
18116            .collect();
18117        assert_eq!(
18118            via_iter, via_method,
18119            "`.iter().map(Cow::from)` over WitShape::ALL — a call \
18120             site whose iteration axis holds `&WitShape` by \
18121             construction — must byte-equal `.iter().map(|s| \
18122             Cow::Borrowed(s.as_str()))` on every arm — the \
18123             borrowed-input Cow<'static, str> `From<&WitShape> for \
18124             Cow<'static, str>` axis is what makes the `Cow::from` \
18125             composition route through the substrate-primitive \
18126             `WitShape::as_str` accessor with the zero-alloc \
18127             Cow::Borrowed arm by construction and without a \
18128             spurious `Copy` deref (which would only be reachable \
18129             through the owned-input `From<WitShape> for Cow<'static, \
18130             str>` axis by first calling `.copied()` on the iterator)"
18131        );
18132        for cow in &via_iter {
18133            assert!(
18134                matches!(cow, std::borrow::Cow::Borrowed(_)),
18135                "every element of the .iter().map(Cow::from) pipe \
18136                 over WitShape::ALL must land on the zero-alloc \
18137                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
18138                 signals the pipe's iteration axis has silently \
18139                 allocated where the substrate-primitive \
18140                 WitShape::as_str `&'static str` return makes the \
18141                 borrowed arm the type-correct projection"
18142            );
18143        }
18144    }
18145
18146    #[test]
18147    fn wit_shape_classify_matches_wit_contract_target_arm_on_valid_inputs() {
18148        // Cross-surface equivalence pin: for every canonical
18149        // truth-table row that also validates cleanly through
18150        // [`WitContract::target`], the pre-projection [`WitShape`] arm
18151        // matches the post-projection [`WitTarget`] arm — the pre- and
18152        // post-validation classifications agree on the arm identity
18153        // even though the payload-carrying view carries additional
18154        // per-arm information. A future edit that reroutes
18155        // `WitContract::target`'s HTTP/pubsub/store dispatch through a
18156        // different predicate than the [`WitShape::classify`] the free
18157        // predicates now route through would trip here at the offending
18158        // row rather than at a downstream renderer.
18159        //
18160        // The Capability arm is excluded from the paired sweep: an
18161        // arbitrary Capability-classified string need not pass
18162        // [`crate::render::is_wit_world_ref`]'s value-shape gate, so
18163        // `WitContract::target` would raise `ContratoWitInvalid`
18164        // rather than return `WitTarget::Capability`; the arm-identity
18165        // agreement lives in the payload-arm rows.
18166        //
18167        // Per-row shape: `(wit, endpoint, subject, slot)` — one row per
18168        // payload arm with its shape's canonical payload field filled
18169        // and the peer fields `None`. Named type-alias closes the
18170        // `clippy::type_complexity` warning the raw tuple triggers.
18171        type WitTargetArmRow = (
18172            &'static str,
18173            Option<&'static str>,
18174            Option<&'static str>,
18175            Option<&'static str>,
18176        );
18177        let cases: [WitTargetArmRow; 6] = [
18178            ("wasi:http/proxy", Some("/x"), None, None),
18179            ("http:incoming", Some("/x"), None, None),
18180            ("nats:events", None, Some("subject.x"), None),
18181            ("kafka:topic", None, Some("subject.x"), None),
18182            ("wasi:keyvalue/store", None, None, Some("bucket/x")),
18183            ("kv:cache", None, None, Some("bucket/x")),
18184        ];
18185        for (wit, endpoint, subject, slot) in cases {
18186            let c = WitContract {
18187                de: "cart".into(),
18188                para: "catalog".into(),
18189                wit: wit.to_string(),
18190                endpoint: endpoint.map(str::to_string),
18191                subject: subject.map(str::to_string),
18192                slot: slot.map(str::to_string),
18193            };
18194            let target = c.target().unwrap_or_else(|e| {
18195                panic!("expected target() to validate for wit={wit:?}, got: {e}")
18196            });
18197            let shape = WitShape::classify(wit);
18198            // Match arm-for-arm — the raw &str classifier and the
18199            // validated payload view must agree on which arm carries
18200            // the edge.
18201            let agree = matches!(
18202                (shape, target),
18203                (WitShape::Http, WitTarget::Http { .. })
18204                    | (WitShape::PubSub, WitTarget::PubSub { .. })
18205                    | (WitShape::Store, WitTarget::Store { .. })
18206                    | (WitShape::Capability, WitTarget::Capability)
18207            );
18208            assert!(
18209                agree,
18210                "WitShape::classify({wit:?}) and WitContract::target arm-identity disagree",
18211            );
18212        }
18213    }
18214
18215    #[test]
18216    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
18217        // Composition-witness pin: [`wit_shape_matches`] agrees with
18218        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
18219        // dispatch (the prior non-`const` implementation) across
18220        // boundary lengths — empty `wit`, empty prefix, one-byte
18221        // slack, prefix longer than `wit`, one-byte trailing slack.
18222        // The rewrite to a byte-level manual starts_with loop (the
18223        // enabler for the `pub const fn` posture) must not change any
18224        // truth-table entry on the canonical accept-set — this pin
18225        // sweeps a targeted boundary corpus and asserts byte-for-byte
18226        // agreement, locking the const-fn rewrite's semantics against
18227        // the prior iterator body by construction.
18228        let prefixes = &["wasi:http/", "http:"][..];
18229        let cases: [(&str, bool); 12] = [
18230            ("wasi:http/proxy", true),
18231            ("wasi:http/", true), // exact-length match on prefix
18232            ("wasi:http", false), // one byte short
18233            ("http:", true),
18234            ("http:incoming", true),
18235            ("http", false), // one byte short
18236            ("", false),
18237            ("wasi:https/proxy", false),
18238            ("nats:events", false),
18239            ("HTTPS:", false), // uppercase — no case-fold in classifier
18240            ("wasi:HTTP/proxy", false),
18241            ("wasi:http", false),
18242        ];
18243        for (wit, expected) in cases {
18244            assert_eq!(
18245                wit_shape_matches(wit, prefixes),
18246                expected,
18247                "wit_shape_matches disagrees with reference at wit={wit:?}",
18248            );
18249            // Byte-equal to the iterator body it replaced.
18250            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
18251            assert_eq!(
18252                wit_shape_matches(wit, prefixes),
18253                via_iter,
18254                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
18255            );
18256        }
18257        // Empty prefix set → always false regardless of `wit`.
18258        let empty: &[&str] = &[];
18259        assert!(!wit_shape_matches("", empty));
18260        assert!(!wit_shape_matches("wasi:http/proxy", empty));
18261        // Empty prefix inside a non-empty set → always true (every
18262        // string starts with the empty string, matching the
18263        // iterator body's semantics on `str::starts_with("")`).
18264        let contains_empty: &[&str] = &["nats:", ""];
18265        assert!(wit_shape_matches("", contains_empty));
18266        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
18267    }
18268
18269    #[test]
18270    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
18271        // 4-way partition-witness pin: for every canonical prefix in
18272        // the payload-arm accept-sets, exactly one of the four
18273        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
18274        // [`WitContract::is_store`] / [`WitContract::is_capability`]
18275        // predicates returns `true` and the other three return `false`
18276        // — the four-arm partition witness that locks the substrate's
18277        // WIT-shape-space closure on the pre-projection axis load-
18278        // bearing. A future arm addition (a hypothetical fourth
18279        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
18280        // shape) that landed on one of the payload-arm predicates
18281        // without shrinking [`WitContract::is_capability`]'s accept-set
18282        // would surface here as two arms returning `true` simultaneously
18283        // — a partition-witness break the pin catches at caixa-core
18284        // build time rather than a silent per-consumer misclassification
18285        // at renderer emit time. Peer of the sibling `WitTarget`-side
18286        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
18287        // partition-witness pin on the post-projection payload-scalar
18288        // arm-set — extends the discipline onto the pre-projection
18289        // 4-arm shape-space.
18290        for shape_set in [
18291            WIT_HTTP_SHAPE_PREFIXES,
18292            WIT_PUBSUB_SHAPE_PREFIXES,
18293            WIT_STORE_SHAPE_PREFIXES,
18294        ] {
18295            for prefix in shape_set {
18296                let c = WitContract {
18297                    de: "cart".into(),
18298                    para: "catalog".into(),
18299                    wit: format!("{prefix}x"),
18300                    endpoint: None,
18301                    subject: None,
18302                    slot: None,
18303                };
18304                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
18305                    .iter()
18306                    .filter(|&&b| b)
18307                    .count();
18308                assert_eq!(
18309                    hits,
18310                    1,
18311                    "WitContract WIT-shape 4-way predicate partition must \
18312                     admit exactly one arm per canonical prefix; got {hits} \
18313                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
18314                     is_capability={})",
18315                    c.wit,
18316                    c.is_http(),
18317                    c.is_pubsub(),
18318                    c.is_store(),
18319                    c.is_capability(),
18320                );
18321            }
18322        }
18323        // Capability-arm sweep: two representative capability shapes
18324        // (a bare WIT world outside the three payload-arm prefix sets,
18325        // and the deliberately-shaped empty string that
18326        // [`crate::render::is_wit_world_ref`] rejects at
18327        // [`WitContract::target`] time but which the pure classifier
18328        // still admits — see the method docstring's "purely syntactic
18329        // classification" note). Both must land on the fourth arm
18330        // exclusively, so the partition witness holds across the full
18331        // 4-arm closure.
18332        for wit in ["custom:capability-only", ""] {
18333            let c = WitContract {
18334                de: "cart".into(),
18335                para: "catalog".into(),
18336                wit: wit.into(),
18337                endpoint: None,
18338                subject: None,
18339                slot: None,
18340            };
18341            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
18342                .iter()
18343                .filter(|&&b| b)
18344                .count();
18345            assert_eq!(
18346                hits, 1,
18347                "WitContract WIT-shape 4-way predicate partition must \
18348                 admit exactly one arm on Capability-shaped wit={wit:?}"
18349            );
18350            assert!(
18351                c.is_capability(),
18352                "wit={wit:?} must project onto the Capability arm"
18353            );
18354        }
18355    }
18356
18357    #[test]
18358    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
18359        // Composition-witness pin: [`WitContract::is_capability`] is the
18360        // exact-inverse disjunction of the sibling payload-arm predicate
18361        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
18362        // [`WitContract::is_store`]. A future reimplementation that
18363        // grew its own prefix-set scan (e.g. inlining a fourth
18364        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
18365        // own today) rather than delegating to the sibling trio would
18366        // drift loudly here — the composition contract binds the
18367        // fourth-arm predicate to the exact-inverse of the three
18368        // payload-arm predicates, so any rebrand of any prefix-set const
18369        // flows through this method by construction without a
18370        // coordinated per-consumer rewrite. Sweeps the union of the
18371        // three payload-arm prefix sets plus two Capability-shaped
18372        // shapes (a bare non-prefix-matching WIT world, the deliberately-
18373        // empty string the pure classifier still admits per the method
18374        // docstring's "purely syntactic classification" note).
18375        let mut cases: Vec<String> = Vec::new();
18376        for shape_set in [
18377            WIT_HTTP_SHAPE_PREFIXES,
18378            WIT_PUBSUB_SHAPE_PREFIXES,
18379            WIT_STORE_SHAPE_PREFIXES,
18380        ] {
18381            for prefix in shape_set {
18382                cases.push(format!("{prefix}x"));
18383            }
18384        }
18385        cases.push("custom:capability-only".to_string());
18386        cases.push(String::new());
18387        for wit in cases {
18388            let c = WitContract {
18389                de: "cart".into(),
18390                para: "catalog".into(),
18391                wit: wit.clone(),
18392                endpoint: None,
18393                subject: None,
18394                slot: None,
18395            };
18396            assert_eq!(
18397                c.is_capability(),
18398                !c.is_http() && !c.is_pubsub() && !c.is_store(),
18399                "WitContract::is_capability must equal \
18400                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
18401            );
18402        }
18403    }
18404
18405    #[test]
18406    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
18407        // Cross-projection-witness pin: whenever [`WitContract::target`]
18408        // succeeds, the pre-projection [`WitContract::is_capability`]
18409        // classification agrees with the post-projection
18410        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
18411        // predicate — the 4-arm typed partition on the substrate's
18412        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
18413        // partition on the pre-projection axis line up by construction.
18414        // A future divergence between the two axes (a peer
18415        // [`WitTarget`] variant addition that landed on the typed-view
18416        // surface without a peer prefix-set + [`WitContract`] predicate
18417        // extension, or vice versa) would surface here at caixa-core
18418        // build time rather than a silent per-consumer split at renderer
18419        // emit time. Peer of the sibling pre-/post-projection
18420        // agreement pins the payload-carrier trio
18421        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
18422        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
18423        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
18424        // post-projection — b11bb49 trio lift) already carry across the
18425        // three payload arms — this pin closes the pair on the fourth
18426        // payload-less arm.
18427        let http = WitContract {
18428            de: "cart".into(),
18429            para: "catalog".into(),
18430            wit: "wasi:http/proxy".into(),
18431            endpoint: Some("/x".into()),
18432            subject: None,
18433            slot: None,
18434        };
18435        assert!(!http.is_capability());
18436        assert!(!http.target().unwrap().is_capability());
18437
18438        let nats = WitContract {
18439            de: "cart".into(),
18440            para: "catalog".into(),
18441            wit: "nats:pub-sub".into(),
18442            endpoint: None,
18443            subject: Some("events.x".into()),
18444            slot: None,
18445        };
18446        assert!(!nats.is_capability());
18447        assert!(!nats.target().unwrap().is_capability());
18448
18449        let kv = WitContract {
18450            de: "cart".into(),
18451            para: "catalog".into(),
18452            wit: "wasi:keyvalue/store".into(),
18453            endpoint: None,
18454            subject: None,
18455            slot: Some("checkout/$orderId".into()),
18456        };
18457        assert!(!kv.is_capability());
18458        assert!(!kv.target().unwrap().is_capability());
18459
18460        let cap = WitContract {
18461            de: "cart".into(),
18462            para: "catalog".into(),
18463            wit: "custom:capability-only".into(),
18464            endpoint: None,
18465            subject: None,
18466            slot: None,
18467        };
18468        assert!(cap.is_capability());
18469        assert!(cap.target().unwrap().is_capability());
18470    }
18471
18472    #[test]
18473    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
18474        // Fail-before-pass-after pin on the [`WitContract`] pre-
18475        // projection accessor family's `const`-eval-surface posture.
18476        // Each of the three per-`:contratos` byte-string scalar
18477        // accessors ([`WitContract::source`] / [`WitContract::destination`]
18478        // / [`WitContract::world_ref`], each projecting through
18479        // `String::as_str` — const-stable since Rust 1.87, well within
18480        // the workspace MSRV) and each of the four peer WIT-shape
18481        // predicates ([`WitContract::is_http`] /
18482        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
18483        // [`WitContract::is_capability`], each composing
18484        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
18485        // free-function classifier family the sibling
18486        // [`wit_shape_classifier_family_is_const_fn`] pin already
18487        // anchors on the raw `&str → bool` axis) must be `pub const fn`
18488        // — any future accidental downgrade to non-`const` fails the
18489        // `const fn` wrappers below at caixa-core build time with E0015
18490        // (`cannot call non-const function`), strictly stronger than a
18491        // runtime `assert!` and strictly stronger than a
18492        // module-scope `const _: () = assert!(…)` pin (which cannot be
18493        // formed on a `&WitContract` fixture because the type's
18494        // `String` / `Option<String>` carriers rule out `const`-context
18495        // construction; the `const fn` wrapper is the load-bearing
18496        // shape that side-steps the destructor-in-const restriction on
18497        // the value axis while still pinning the `const`-fn posture on
18498        // the callee).
18499        //
18500        // Peer of the sibling free-function classifier pin
18501        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
18502        // raw `&str → bool` axis — this pin extends the same
18503        // `const`-eval-surface discipline onto the peer method surface
18504        // that composes through those free-function classifiers, and
18505        // simultaneously onto the underlying per-`:contratos`
18506        // byte-string scalar-accessor trio each predicate reads
18507        // through. Sibling of the peer M3
18508        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
18509        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
18510        // M2
18511        // [`child_spec_restart_accessor_is_const_fn`] /
18512        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
18513        // and M3
18514        // [`placement_estrategia_accessor_is_const_fn`] /
18515        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
18516        // sibling `const`-eval-surface-pass axes.
18517        const fn source_via_const_fn(c: &WitContract) -> &str {
18518            c.source()
18519        }
18520        const fn destination_via_const_fn(c: &WitContract) -> &str {
18521            c.destination()
18522        }
18523        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
18524            c.world_ref()
18525        }
18526        const fn is_http_via_const_fn(c: &WitContract) -> bool {
18527            c.is_http()
18528        }
18529        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
18530            c.is_pubsub()
18531        }
18532        const fn is_store_via_const_fn(c: &WitContract) -> bool {
18533            c.is_store()
18534        }
18535        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
18536            c.is_capability()
18537        }
18538        // Sweep one canonical accept-set sample per WIT-shape arm plus
18539        // a payload-less capability sample, asserting the wrapper and
18540        // direct dispatches agree byte-for-byte across the closed
18541        // 4-arm partition on both the scalar-accessor trio and the
18542        // WIT-shape-predicate family.
18543        for (wit, is_http, is_pubsub, is_store, is_capability) in [
18544            ("wasi:http/proxy", true, false, false, false),
18545            ("http:incoming", true, false, false, false),
18546            ("nats:events", false, true, false, false),
18547            ("kafka:topic", false, true, false, false),
18548            ("wasi:keyvalue/store", false, false, true, false),
18549            ("kv:cache", false, false, true, false),
18550            ("custom:capability-only", false, false, false, true),
18551            ("", false, false, false, true),
18552        ] {
18553            let c = WitContract {
18554                de: "cart".into(),
18555                para: "catalog".into(),
18556                wit: wit.into(),
18557                endpoint: None,
18558                subject: None,
18559                slot: None,
18560            };
18561            assert_eq!(source_via_const_fn(&c), c.source());
18562            assert_eq!(destination_via_const_fn(&c), c.destination());
18563            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
18564            assert_eq!(is_http_via_const_fn(&c), c.is_http());
18565            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
18566            assert_eq!(is_store_via_const_fn(&c), c.is_store());
18567            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
18568            assert_eq!(c.source(), "cart");
18569            assert_eq!(c.destination(), "catalog");
18570            assert_eq!(c.world_ref(), wit);
18571            assert_eq!(c.is_http(), is_http);
18572            assert_eq!(c.is_pubsub(), is_pubsub);
18573            assert_eq!(c.is_store(), is_store);
18574            assert_eq!(c.is_capability(), is_capability);
18575        }
18576    }
18577
18578    #[test]
18579    fn wit_contract_identity_projection_accessor_is_const_fn() {
18580        // Fail-before-pass-after pin on the [`WitContract::identity`]
18581        // six-arm composite-projection accessor's `const`-eval-surface
18582        // posture. The accessor projects the typed edge's six identity
18583        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
18584        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
18585        // every callee is itself `pub const fn` ([`WitContract::source`]
18586        // / [`WitContract::destination`] / [`WitContract::world_ref`]
18587        // through `String::as_str`, const-stable since Rust 1.87;
18588        // [`WitContract::endpoint`] / [`WitContract::subject`] /
18589        // [`WitContract::slot`] through the sibling `match &self
18590        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
18591        // 0650f64 closed the const-eval surface on) and the tuple
18592        // constructor from borrowed-reference / `Option`-of-borrowed-
18593        // reference arms is trivially const. Any future accidental
18594        // downgrade fails the `identity_via_const_fn` wrapper at
18595        // caixa-core build time with E0015 (`cannot call non-const
18596        // method`), strictly stronger than a runtime `assert!` and
18597        // strictly stronger than a module-scope `const _: () =
18598        // assert!(…)` pin (which cannot be formed on a `&WitContract`
18599        // fixture because the type's `String` / `Option<String>`
18600        // carriers rule out `const`-context value construction; the
18601        // `const fn` wrapper is the load-bearing shape that side-steps
18602        // the destructor-in-const restriction on the value axis while
18603        // still pinning the `const`-fn posture on the callee — mirror
18604        // of the sibling
18605        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
18606        // pin's discipline verbatim on the peer scalar-accessor
18607        // surface).
18608        //
18609        // Peer of the sibling
18610        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
18611        // (279823b) pin on the six per-`:contratos` scalar-accessor
18612        // callees this composite-projection reads through — where that
18613        // pin anchors the const-eval surface at the six individual
18614        // scalar-accessor arms, this pin extends the same posture onto
18615        // the composite six-tuple projection every consumer that dedups
18616        // typed edges on the [`ContratoIdentity`] axis keys off (the
18617        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
18618        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
18619        // materializer's per-edge identity-based admission webhook; a
18620        // future L7 policy-emitter that shards CNPs by identity-tuple
18621        // rather than by name). Same fail-before-pass-after wrapper
18622        // discipline as the peer M2 / M3 accessor-family pins on the
18623        // sibling `const`-eval-surface passes.
18624        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
18625            c.identity()
18626        }
18627        // Sweep one canonical WIT-shape sample per payload-carrier arm
18628        // plus a payload-less capability sample so the pin exercises
18629        // both `Some(_)`-carrying and `None`-carrying arms on all three
18630        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
18631        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
18632        // with the direct method call on every arm of the closed WIT-
18633        // shape partition.
18634        for (wit, endpoint, subject, slot) in [
18635            ("wasi:http/proxy", Some("/checkout"), None, None),
18636            ("http:incoming", Some("/api"), None, None),
18637            ("nats:events", None, Some("orders.placed"), None),
18638            ("kafka:topic", None, Some("orders.stream"), None),
18639            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
18640            ("kv:cache", None, None, Some("session/{token}")),
18641            ("custom:capability-only", None, None, None),
18642        ] {
18643            let c = WitContract {
18644                de: "cart".into(),
18645                para: "catalog".into(),
18646                wit: wit.into(),
18647                endpoint: endpoint.map(str::to_string),
18648                subject: subject.map(str::to_string),
18649                slot: slot.map(str::to_string),
18650            };
18651            assert_eq!(identity_via_const_fn(&c), c.identity());
18652            assert_eq!(
18653                c.identity(),
18654                ("cart", "catalog", wit, endpoint, subject, slot,),
18655            );
18656        }
18657    }
18658
18659    #[test]
18660    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
18661        // Fail-before-pass-after pin on the four M3 mesh-slot
18662        // `String → &str` scalar accessors ([`Membro::nome`] /
18663        // [`Membro::versao_requirement`] on the per-`:membros` axis,
18664        // [`Entrada::hostname`] / [`Entrada::destination`] on the
18665        // per-`:entrada` axis) — each projects the typed slot's
18666        // [`String`] storage through the `pub const fn`
18667        // [`String::as_str`] (const-stable since Rust 1.87, well
18668        // within the workspace MSRV) and any future accidental
18669        // downgrade to non-`const` fails the corresponding
18670        // `<name>_via_const_fn` wrapper at caixa-core build time with
18671        // E0015 (`cannot call non-const method`), strictly stronger
18672        // than a runtime `assert!` and strictly stronger than a
18673        // module-scope `const _: () = assert!(…)` pin (which cannot
18674        // be formed on `&Membro` / `&Entrada` fixtures because the
18675        // types' `String` carriers rule out `const`-context value
18676        // construction; the `const fn` wrapper is the load-bearing
18677        // shape that side-steps the destructor-in-const restriction
18678        // on the value axis while still pinning the `const`-fn
18679        // posture on the callee — mirror of the sibling
18680        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
18681        // (279823b) pin on the per-`:contratos` axis). Peer of the
18682        // sibling per-M2/M3/universal-axis `String → &str` accessor
18683        // family pins on the sibling `const`-eval-surface passes
18684        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
18685        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
18686        // typed-newtype wrapper,
18687        // [`crate::supervisor::ChildSpec::nome`] /
18688        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
18689        // M2 supervisor-tree axis,
18690        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
18691        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
18692        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
18693        // axis, and the sibling per-`:contratos`
18694        // [`WitContract::source`] / [`WitContract::destination`] /
18695        // [`WitContract::world_ref`] trio at 279823b).
18696        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
18697            m.nome()
18698        }
18699        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
18700            m.versao_requirement()
18701        }
18702        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
18703            e.hostname()
18704        }
18705        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
18706            e.destination()
18707        }
18708        for (caixa, versao) in [
18709            ("cart", "^0.1"),
18710            ("catalog-v2", "~0.2.3"),
18711            ("checkout", "*"),
18712        ] {
18713            let m = Membro {
18714                caixa: caixa.into(),
18715                versao: versao.into(),
18716            };
18717            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
18718            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
18719            assert_eq!(m.nome(), caixa);
18720            assert_eq!(m.versao_requirement(), versao);
18721        }
18722        for (host, para) in [
18723            ("cart.example.com", "cart"),
18724            ("api.checkout.io", "checkout"),
18725        ] {
18726            let e = Entrada {
18727                host: host.into(),
18728                para: para.into(),
18729                paths: vec![],
18730                port: DEFAULT_SERVICO_PORT,
18731            };
18732            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
18733            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
18734            assert_eq!(e.hostname(), host);
18735            assert_eq!(e.destination(), para);
18736        }
18737    }
18738
18739    #[test]
18740    fn m3_option_string_scalar_accessor_family_is_const_fn() {
18741        // Fail-before-pass-after pin on the five M3 mesh-slot
18742        // `Option<String> → Option<&str>` scalar accessors
18743        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
18744        // [`WitContract::slot`] on the per-`:contratos` HTTP /
18745        // pub-sub / key-value payload-carrier trio,
18746        // [`Placement::shard_key`] / [`Placement::affinity`] on the
18747        // per-`:placement` Akka-sharding-key + Adaptive-compression-
18748        // hint pair). Each accessor destructures the typed slot's
18749        // `Option<String>` storage through the `match &self.<field> {
18750        // Some(s) => Some(s.as_str()), None => None }` shape —
18751        // routing through [`String::as_str`] (const-stable since Rust
18752        // 1.87, well within the workspace MSRV) rather than the
18753        // non-const [`Option::as_deref`] the pre-lift bodies carried
18754        // — and any future accidental downgrade to non-`const` fails
18755        // the corresponding `<name>_via_const_fn` wrapper at
18756        // caixa-core build time with E0015 (`cannot call non-const
18757        // method`), strictly stronger than a runtime `assert!` and
18758        // strictly stronger than a module-scope `const _: () =
18759        // assert!(…)` pin (which cannot be formed on `&WitContract`
18760        // / `&Placement` fixtures because the types' `String` /
18761        // `Option<String>` carriers rule out `const`-context value
18762        // construction; the `const fn` wrapper is the load-bearing
18763        // shape that side-steps the destructor-in-const restriction
18764        // on the value axis while still pinning the `const`-fn
18765        // posture on the callee — mirror of the sibling
18766        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
18767        // (279823b) and
18768        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
18769        // (29c5d7e) pins on the peer `String → &str` axes at the same
18770        // structs).
18771        //
18772        // Peer of the sibling per-`Caixa` `Option<String> →
18773        // Option<&str>` accessor family pin
18774        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
18775        // on the top-level manifest's optional universal-axis surface
18776        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
18777        // `:restart-window`).
18778        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
18779            w.endpoint()
18780        }
18781        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
18782            w.subject()
18783        }
18784        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
18785            w.slot()
18786        }
18787        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
18788            p.shard_key()
18789        }
18790        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
18791            p.affinity()
18792        }
18793        // Sweep every closed shape-arm partition on the
18794        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
18795        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
18796        // pair None), key-value (`:slot` Some, sibling pair None),
18797        // and Capability (all three None) so each accessor's
18798        // Some/None arm carries a pin through the const dispatch.
18799        for (wit, endpoint, subject, slot) in [
18800            ("wasi:http/proxy", Some("/api"), None, None),
18801            ("nats:pub-sub", None, Some("orders.paid"), None),
18802            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
18803            ("custom:capability-only", None, None, None),
18804        ] {
18805            let c = WitContract {
18806                de: "cart".into(),
18807                para: "catalog".into(),
18808                wit: wit.into(),
18809                endpoint: endpoint.map(str::to_string),
18810                subject: subject.map(str::to_string),
18811                slot: slot.map(str::to_string),
18812            };
18813            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
18814            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
18815            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
18816            assert_eq!(c.endpoint(), endpoint);
18817            assert_eq!(c.subject(), subject);
18818            assert_eq!(c.slot(), slot);
18819        }
18820        // Sweep both `Some`/`None` arms on each per-`:placement`
18821        // optional-scalar so the shard-key + affinity pair carries a
18822        // const-dispatch pin on both arms.
18823        for (shard_key, affinity) in [
18824            (Some("tenantId"), Some("data-locality")),
18825            (Some("$tenantId"), None),
18826            (None, Some("low-latency")),
18827            (None, None),
18828        ] {
18829            let p = Placement {
18830                estrategia: PlacementStrategy::default(),
18831                clusters: vec![],
18832                affinity: affinity.map(str::to_string),
18833                shard_key: shard_key.map(str::to_string),
18834            };
18835            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
18836            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
18837            assert_eq!(p.shard_key(), shard_key);
18838            assert_eq!(p.affinity(), affinity);
18839        }
18840    }
18841
18842    #[test]
18843    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
18844        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
18845        // composite `Vec → &[String]` slice-return accessors on
18846        // [`Placement::clusters`] and [`Entrada::paths`]. Each
18847        // destructures the typed slot's `Vec<String>` storage through
18848        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
18849        // 1.66, well within the workspace MSRV) — any future accidental
18850        // downgrade to non-`const` fails the corresponding
18851        // `<name>_via_const_fn` wrapper at caixa-core build time with
18852        // E0015 (`cannot call non-const method`), strictly stronger
18853        // than a runtime `assert!`. Sibling of the peer
18854        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
18855        // pin on the outer-`AplicacaoSpec` reference-return family
18856        // (`:membros` / `:contratos` slice-return + `:politicas` /
18857        // `:placement` / `:entrada` composite-reference), and of the
18858        // peer M2 slice-return axis pins
18859        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
18860        // (on `SupervisorSpec::children`) and
18861        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
18862        // (on `UpgradeFromEntry::instructions`). Together the four
18863        // pins close the last unlifted reference-return accessor
18864        // family across the substrate primitive.
18865        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
18866            p.clusters()
18867        }
18868        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
18869            e.paths()
18870        }
18871        // Sweep both the empty-Vec (no author-declared entries) and
18872        // the populated-Vec arms on every slice-return accessor so
18873        // each carries a const-dispatch pin on both arms.
18874        let p_empty = Placement {
18875            estrategia: PlacementStrategy::default(),
18876            clusters: vec![],
18877            affinity: None,
18878            shard_key: None,
18879        };
18880        let p_full = Placement {
18881            estrategia: PlacementStrategy::default(),
18882            clusters: vec!["prod-a".into(), "prod-b".into()],
18883            affinity: None,
18884            shard_key: None,
18885        };
18886        assert_eq!(
18887            placement_clusters_via_const_fn(&p_empty),
18888            p_empty.clusters()
18889        );
18890        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
18891        assert!(p_empty.clusters().is_empty());
18892        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
18893        let e_empty = Entrada {
18894            host: "web.example.com".into(),
18895            para: "web".into(),
18896            paths: vec![],
18897            port: DEFAULT_SERVICO_PORT,
18898        };
18899        let e_full = Entrada {
18900            host: "web.example.com".into(),
18901            para: "web".into(),
18902            paths: vec!["/api".into(), "/health".into()],
18903            port: DEFAULT_SERVICO_PORT,
18904        };
18905        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
18906        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
18907        assert!(e_empty.paths().is_empty());
18908        assert_eq!(e_full.paths(), &["/api", "/health"]);
18909    }
18910
18911    #[test]
18912    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
18913        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
18914        // reference-return accessors — the two `Vec → &[T]` slice-
18915        // return accessors on [`AplicacaoSpec::membros`] and
18916        // [`AplicacaoSpec::contratos`] (each routes through the
18917        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
18918        // 1.66), the two `&Composite` composite-reference accessors
18919        // on [`AplicacaoSpec::politicas`] and
18920        // [`AplicacaoSpec::placement`] (each routes through a raw
18921        // `&self.<field>` borrow, trivially const), and the one
18922        // `Option<&Composite>` optional-composite-reference accessor
18923        // on [`AplicacaoSpec::entrada`] (routes through the
18924        // `pub const fn` [`Option::as_ref`], const-stable since Rust
18925        // 1.83). Any future accidental downgrade to non-`const` fails
18926        // the corresponding `<name>_via_const_fn` wrapper at caixa-
18927        // core build time with E0015 (`cannot call non-const
18928        // method`), strictly stronger than a runtime `assert!`.
18929        // Sibling of the peer inner-composite pin
18930        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
18931        // on the `Placement::clusters` + `Entrada::paths` slice-
18932        // return pair, and of the peer M2 axis pins on
18933        // [`crate::supervisor::SupervisorSpec::children`] and
18934        // [`crate::upgrade::UpgradeFromEntry::instructions`].
18935        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
18936            s.membros()
18937        }
18938        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
18939            s.contratos()
18940        }
18941        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
18942            s.politicas()
18943        }
18944        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
18945            s.placement()
18946        }
18947        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
18948            s.entrada()
18949        }
18950        // Construct both a minimal "no :entrada" (internal-only
18951        // mesh) and a full "with :entrada" (external-gateway)
18952        // fixture so the family pins both the `None`-arm (author-
18953        // omitted `:entrada`) and the `Some`-arm (author-declared
18954        // `:entrada`) on the optional-composite axis.
18955        let membro = Membro {
18956            caixa: "web".into(),
18957            versao: "^0.1".into(),
18958        };
18959        let entrada_full = Entrada {
18960            host: "web.example.com".into(),
18961            para: "web".into(),
18962            paths: vec!["/api".into()],
18963            port: DEFAULT_SERVICO_PORT,
18964        };
18965        let internal_only = AplicacaoSpec {
18966            membros: vec![membro.clone()],
18967            contratos: vec![],
18968            politicas: MeshPolicy::default(),
18969            placement: Placement::default(),
18970            entrada: None,
18971        };
18972        let with_entrada = AplicacaoSpec {
18973            membros: vec![membro],
18974            contratos: vec![],
18975            politicas: MeshPolicy::default(),
18976            placement: Placement::default(),
18977            entrada: Some(entrada_full),
18978        };
18979        assert_eq!(
18980            aplicacao_membros_via_const_fn(&internal_only),
18981            internal_only.membros()
18982        );
18983        assert_eq!(
18984            aplicacao_membros_via_const_fn(&with_entrada),
18985            with_entrada.membros()
18986        );
18987        assert_eq!(
18988            aplicacao_contratos_via_const_fn(&internal_only),
18989            internal_only.contratos()
18990        );
18991        assert!(std::ptr::eq(
18992            aplicacao_politicas_via_const_fn(&internal_only),
18993            internal_only.politicas(),
18994        ));
18995        assert!(std::ptr::eq(
18996            aplicacao_placement_via_const_fn(&internal_only),
18997            internal_only.placement(),
18998        ));
18999        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
19000        match (
19001            aplicacao_entrada_via_const_fn(&with_entrada),
19002            with_entrada.entrada(),
19003        ) {
19004            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
19005            _ => panic!(
19006                "aplicacao_entrada_via_const_fn must agree with \
19007                 AplicacaoSpec::entrada on the Some-arm reference"
19008            ),
19009        }
19010    }
19011
19012    #[test]
19013    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
19014        // Load-bearing contract pin: on every canonical
19015        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
19016        // [`WitContract::target_projected`] returns byte-equal to
19017        // [`WitContract::target`]`().unwrap()` — the post-validation
19018        // projection accessor is a thin panicking wrapper over the
19019        // pre-validation validator, no extra work in the projection
19020        // path. Any future divergence (a validator-side normalization
19021        // the projection doesn't route through, an accessor-side
19022        // caching layer the validator doesn't populate) would surface
19023        // here at caixa-core build time rather than a silent per-consumer
19024        // split at renderer emit time. Sweeps the closed 4-arm
19025        // [`WitTarget`] partition ([`WitTarget::Http`] /
19026        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
19027        // [`WitTarget::Capability`]) so every arm carries a byte-equality
19028        // pin on the two-accessor pair.
19029        for (wit, endpoint, subject, slot) in [
19030            ("wasi:http/proxy", Some("/x"), None, None),
19031            ("nats:pub-sub", None, Some("events.x"), None),
19032            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
19033            ("custom:capability-only", None, None, None),
19034        ] {
19035            let c = WitContract {
19036                de: "cart".into(),
19037                para: "catalog".into(),
19038                wit: wit.into(),
19039                endpoint: endpoint.map(str::to_string),
19040                subject: subject.map(str::to_string),
19041                slot: slot.map(str::to_string),
19042            };
19043            assert_eq!(
19044                c.target_projected(),
19045                c.target().unwrap(),
19046                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
19047            );
19048        }
19049    }
19050
19051    #[test]
19052    #[should_panic(expected = "validated by typed_view")]
19053    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
19054        // Panic-path pin: [`WitContract::target_projected`] threads the
19055        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
19056        // through its expect-panic when called on a contract whose
19057        // (`:wit`, payload) shape has not been crossed by
19058        // [`AplicacaoSpec::validate`] — a contract with a structurally-
19059        // invalid `:wit` (hyphen-for-colon typo) that would surface
19060        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
19061        // A future rebrand on the panic-message axis would land at one
19062        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
19063        // and this pin's [`should_panic(expected = …)`] literal would
19064        // migrate alongside — the pin catches drift between the const
19065        // and the accessor's `expect(…)` call by construction.
19066        let c = WitContract {
19067            de: "cart".into(),
19068            para: "catalog".into(),
19069            // Hyphen-for-colon typo: `WitContract::target` returns
19070            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
19071            // driving the [`WitContract::target_projected`] expect-panic.
19072            wit: "wasi-http/proxy".into(),
19073            endpoint: Some("/x".into()),
19074            subject: None,
19075            slot: None,
19076        };
19077        let _ = c.target_projected();
19078    }
19079
19080    #[test]
19081    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
19082        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
19083        // carries the exact byte-string the two prior open-coded
19084        // `.target().expect("validated by typed_view")` production
19085        // consumers threaded through inline before this lift converged
19086        // them onto [`WitContract::target_projected`] — the caixa-mesh
19087        // per-`(:de, :para)` CNP L7 introspection branch at
19088        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
19089        // graph` per-`:contratos` payload-column printer at
19090        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
19091        // byte-string load-bearing so a well-meaning const-side rebrand
19092        // that didn't carry a matched pin migration would surface here
19093        // at caixa-core build time rather than a silent per-consumer
19094        // panic-message drift at cluster-apply time. Peer of the
19095        // sibling [`WitTarget::CAPABILITY_LABEL`] /
19096        // [`WitTarget::CAPABILITY_EXPECTED`] /
19097        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
19098        // the paired payload-less-arm scalar-const family.
19099        assert_eq!(
19100            WitContract::PROJECTED_INVARIANT_MSG,
19101            "validated by typed_view"
19102        );
19103    }
19104
19105    #[test]
19106    fn empty_wit_takes_precedence_over_invalid() {
19107        // Ordering pin: `EmptyWit` is the more self-locating
19108        // diagnostic on `""` and must lead — the value-shape gate is
19109        // only reached after the empty-check fires. Mirrors
19110        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
19111        // the peer payload axis.
19112        let mut s = three_member_spec();
19113        s.contratos.push(WitContract {
19114            de: "payment".into(),
19115            para: "catalog".into(),
19116            wit: String::new(),
19117            endpoint: None,
19118            subject: None,
19119            slot: None,
19120        });
19121        let err = s.validate().unwrap_err();
19122        assert!(
19123            matches!(err, AplicacaoError::EmptyWit { .. }),
19124            "got {err:?}"
19125        );
19126    }
19127
19128    #[test]
19129    fn wit_invalid_fires_before_payload_shape_arm() {
19130        // Ordering pin: a malformed `:wit` surfaces *its own*
19131        // diagnostic (which names the offending wit verbatim) before
19132        // any payload-field check — a contrato whose wit is
19133        // structurally invalid AND carries a wrong target field
19134        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
19135        // because the dispatch on the wit is what decides which
19136        // payload field is "right" in the first place. Without this
19137        // ordering, the author would see "wrong target field" for a
19138        // wit that hasn't even been parsed, which doesn't name the
19139        // root cause.
19140        let mut s = three_member_spec();
19141        s.contratos.push(WitContract {
19142            de: "payment".into(),
19143            para: "catalog".into(),
19144            // Hyphen-for-colon typo + endpoint set: pre-gate this
19145            // raised `ContratoWrongTarget { expected: "none" }` (the
19146            // Capability arm rejecting the endpoint), masking the
19147            // real authoring mistake (the wit isn't `wasi:http/proxy`).
19148            wit: "wasi-http/proxy".into(),
19149            endpoint: Some("/x".into()),
19150            subject: None,
19151            slot: None,
19152        });
19153        let err = s.validate().unwrap_err();
19154        assert!(
19155            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
19156                if wit == "wasi-http/proxy"),
19157            "got {err:?}"
19158        );
19159    }
19160
19161    #[test]
19162    fn wit_invalid_diagnostic_carries_offending_wit() {
19163        // Diagnostic-shape pin — the offending `:wit` + `:de` +
19164        // `:para` + a non-empty reason flow through verbatim so the
19165        // author can grep their caixa.lisp for the offending contrato
19166        // block and fix it in one edit. Same shape as
19167        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
19168        let err = contrato_wit_err("WASI:HTTP/proxy");
19169        match err {
19170            AplicacaoError::ContratoWitInvalid {
19171                de,
19172                para,
19173                wit,
19174                reason,
19175            } => {
19176                assert_eq!(de, "payment");
19177                assert_eq!(para, "catalog");
19178                assert_eq!(wit, "WASI:HTTP/proxy");
19179                assert!(!reason.is_empty(), "reason field must be non-empty");
19180            }
19181            other => panic!("expected ContratoWitInvalid, got {other:?}"),
19182        }
19183    }
19184
19185    // ── :contratos :subject value-shape gate ─────────────────────────────
19186    //
19187    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
19188    // suites on the peer payload axes. Until this gate landed
19189    // `WitContract::target()` only refused the empty string; a
19190    // structurally invalid subject silently passed validate and the
19191    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
19192    // Subject'` on publish / subscribe, or as a silent message drop,
19193    // far from the source caixa.lisp. Every authoring footgun the
19194    // NATS server's subject parser would catch on admission now
19195    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
19196    // offending `:subject` + `:de` + `:para` named verbatim. Same
19197    // diagnostic shape as `ContratoEndpointInvalid` /
19198    // `ContratoWitInvalid` on the peer payload axes; same shared
19199    // predicate (`crate::render::is_nats_subject`) ensures drift
19200    // between any two axes' rule enforcement is a build error at the
19201    // predicate, not piecemeal across renderers.
19202
19203    fn contrato_subject_err(subject: &str) -> AplicacaoError {
19204        // Fresh spec per call so the new contract doesn't collide on
19205        // identity with `three_member_spec`'s pre-existing entries.
19206        // The new edge uses `(payment, catalog)` — a pair the fixture
19207        // doesn't already declare — with `:wit "nats:pub-sub"` and the
19208        // varying `:subject`, so the subject-shape gate fires cleanly
19209        // after the wit-shape gate (which `"nats:pub-sub"` passes).
19210        let mut s = three_member_spec();
19211        s.contratos.push(WitContract {
19212            de: "payment".into(),
19213            para: "catalog".into(),
19214            wit: "nats:pub-sub".into(),
19215            endpoint: None,
19216            subject: Some(subject.into()),
19217            slot: None,
19218        });
19219        s.validate().unwrap_err()
19220    }
19221
19222    #[test]
19223    fn rejects_pubsub_contrato_subject_with_whitespace() {
19224        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
19225        // landed at the NATS server as a malformed subject the parser
19226        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
19227        // source caixa.lisp.
19228        let err = contrato_subject_err("foo bar");
19229        assert!(
19230            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19231                if subject == "foo bar" && reason.contains("whitespace")),
19232            "got {err:?}"
19233        );
19234    }
19235
19236    #[test]
19237    fn rejects_pubsub_contrato_subject_with_control_char() {
19238        let err = contrato_subject_err("foo\x01bar");
19239        assert!(
19240            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19241                if subject == "foo\x01bar" && reason.contains("control character")),
19242            "got {err:?}"
19243        );
19244    }
19245
19246    #[test]
19247    fn rejects_pubsub_contrato_subject_with_non_ascii() {
19248        // Un-percent-encoded non-ASCII byte — the canonical "I copied
19249        // the subject from a doc with smart quotes / accented
19250        // characters" footgun.
19251        let err = contrato_subject_err("foo.caf\u{e9}");
19252        assert!(
19253            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19254                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
19255            "got {err:?}"
19256        );
19257    }
19258
19259    #[test]
19260    fn rejects_pubsub_contrato_subject_with_leading_dot() {
19261        // Empty leading token — NATS rejects.
19262        let err = contrato_subject_err(".foo");
19263        assert!(
19264            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19265                if subject == ".foo" && reason.contains("must not start with `.`")),
19266            "got {err:?}"
19267        );
19268    }
19269
19270    #[test]
19271    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
19272        // Empty trailing token — NATS rejects. The remediation
19273        // (use `>` instead) is in the reason string.
19274        let err = contrato_subject_err("foo.");
19275        assert!(
19276            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19277                if subject == "foo." && reason.contains("must not end with `.`")),
19278            "got {err:?}"
19279        );
19280    }
19281
19282    #[test]
19283    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
19284        // The canonical "I forgot to fill in the middle segment"
19285        // typo — `"foo..bar"`. NATS rejects empty tokens.
19286        let err = contrato_subject_err("foo..bar");
19287        assert!(
19288            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19289                if subject == "foo..bar" && reason.contains("consecutive `.`")),
19290            "got {err:?}"
19291        );
19292    }
19293
19294    #[test]
19295    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
19296        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
19297        // as the final segment. Pre-gate this passed as a typed edge
19298        // and surfaced at runtime as a NATS subscribe rejection.
19299        let err = contrato_subject_err("foo.>.bar");
19300        assert!(
19301            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19302                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
19303            "got {err:?}"
19304        );
19305    }
19306
19307    #[test]
19308    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
19309        // `foo*.bar` — NATS wildcards are standalone tokens. The
19310        // remediation is in the reason string.
19311        let err = contrato_subject_err("foo*.bar");
19312        assert!(
19313            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19314                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
19315            "got {err:?}"
19316        );
19317    }
19318
19319    #[test]
19320    fn rejects_pubsub_contrato_subject_with_invalid_char() {
19321        // `foo,bar` — comma is not a valid NATS subject character.
19322        // Pinned separately from the wildcard arms so the invalid-
19323        // character diagnostic is in force.
19324        let err = contrato_subject_err("foo,bar");
19325        assert!(
19326            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19327                if subject == "foo,bar" && reason.contains("invalid character")),
19328            "got {err:?}"
19329        );
19330    }
19331
19332    #[test]
19333    fn rejects_pubsub_contrato_subject_too_long() {
19334        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
19335        // The legitimate-shape arms all pass (one all-`a` token, no
19336        // `.`, no wildcards); only the cap arm fires. Surfaces the
19337        // paste-from-binary / accidental-multi-line-blob landing
19338        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
19339        // on the peer axis.
19340        let big = "a".repeat(257);
19341        assert_eq!(big.len(), 257);
19342        let err = contrato_subject_err(&big);
19343        assert!(
19344            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
19345                if subject == &big && reason.contains("max length of 256")),
19346            "got {err:?}"
19347        );
19348    }
19349
19350    #[test]
19351    fn pubsub_contrato_subject_max_length_validates() {
19352        // 256-byte subject — exactly the cap. Boundary pin: drift in
19353        // the cap surfaces here and at
19354        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
19355        // mirroring `http_contrato_endpoint_max_length_validates` and
19356        // `wit_max_length_validates` on the peer axes.
19357        let big = "a".repeat(256);
19358        assert_eq!(big.len(), 256);
19359        let mut s = three_member_spec();
19360        s.contratos.push(WitContract {
19361            de: "payment".into(),
19362            para: "catalog".into(),
19363            wit: "nats:pub-sub".into(),
19364            endpoint: None,
19365            subject: Some(big),
19366            slot: None,
19367        });
19368        s.validate().unwrap();
19369    }
19370
19371    #[test]
19372    fn pubsub_contrato_subject_accepts_canonical_forms() {
19373        // Positive-set sweep: every canonical NATS subject shape the
19374        // substrate-side `is_nats_subject` predicate accepts (the
19375        // multi-dot `events.order.charged`, the snake_case / kebab-
19376        // case / mixed-case tokens, the digit-bearing tokens, the
19377        // single-token wildcard `*` at every segment position, and
19378        // the trailing `>` multi-token wildcard) must remain a valid
19379        // contrato subject too. Drift between this list and the
19380        // substrate-side `nats_subject_accepts_canonical_forms` sweep
19381        // surfaces at the shared predicate — one source of truth.
19382        // Uses a fresh `(payment, catalog)` edge so none of the swept
19383        // subjects collide with the pre-existing entries in
19384        // `three_member_spec`.
19385        for subject in [
19386            "checkout.events.charge.failed",
19387            "rio.events.order.charged",
19388            "orders",
19389            "orders.123",
19390            "snake_case.token",
19391            "kebab-case.token",
19392            "MixedCase.Token",
19393            "orders.*.charged",
19394            "*.events.*",
19395            "orders.>",
19396        ] {
19397            let mut s = three_member_spec();
19398            s.contratos.push(WitContract {
19399                de: "payment".into(),
19400                para: "catalog".into(),
19401                wit: "nats:pub-sub".into(),
19402                endpoint: None,
19403                subject: Some(subject.into()),
19404                slot: None,
19405            });
19406            s.validate()
19407                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
19408        }
19409    }
19410
19411    #[test]
19412    fn contrato_subject_empty_takes_precedence_over_invalid() {
19413        // Ordering pin: `ContratoSubjectEmpty` is the more self-
19414        // locating diagnostic on `""` and must lead — the value-shape
19415        // gate is only reached after the empty-check fires. Mirrors
19416        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
19417        // the peer payload axis.
19418        let mut s = three_member_spec();
19419        s.contratos.push(WitContract {
19420            de: "payment".into(),
19421            para: "catalog".into(),
19422            wit: "nats:pub-sub".into(),
19423            endpoint: None,
19424            subject: Some(String::new()),
19425            slot: None,
19426        });
19427        let err = s.validate().unwrap_err();
19428        assert!(
19429            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
19430            "got {err:?}"
19431        );
19432    }
19433
19434    #[test]
19435    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
19436        // Diagnostic-shape pin — the offending `:subject` + `:de` +
19437        // `:para` + a non-empty reason flow through verbatim so the
19438        // author can grep their caixa.lisp for the offending contrato
19439        // block and fix it in one edit. Same shape as
19440        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
19441        // and `wit_invalid_diagnostic_carries_offending_wit`.
19442        let err = contrato_subject_err("foo..bar");
19443        match err {
19444            AplicacaoError::ContratoSubjectInvalid {
19445                de,
19446                para,
19447                subject,
19448                reason,
19449            } => {
19450                assert_eq!(de, "payment");
19451                assert_eq!(para, "catalog");
19452                assert_eq!(subject, "foo..bar");
19453                assert!(!reason.is_empty(), "reason field must be non-empty");
19454            }
19455            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
19456        }
19457    }
19458
19459    #[test]
19460    fn target_view_pubsub_subject_passes_through_to_typed_view() {
19461        // The compounding theorem on the pub-sub axis: every
19462        // `WitTarget::PubSub { subject }` returned by `target()` carries
19463        // a NATS-server-accepted subject. Renderers downstream of
19464        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
19465        // NATS Stream/Consumer CR emitter, the future `feira app graph`
19466        // view's subject labeller) can rely on this without re-checking
19467        // — the type system carries the proof. Mirrors
19468        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
19469        // on the peer axes.
19470        let nats = WitContract {
19471            de: "a".into(),
19472            para: "b".into(),
19473            wit: "nats:pub-sub".into(),
19474            endpoint: None,
19475            subject: Some("orders.events.*.charged".into()),
19476            slot: None,
19477        };
19478        match nats.target().unwrap() {
19479            WitTarget::PubSub { subject } => {
19480                assert_eq!(subject, "orders.events.*.charged");
19481            }
19482            other => panic!("expected PubSub, got {other:?}"),
19483        }
19484    }
19485
19486    // ── :contratos :slot value-shape gate ────────────────────────────────
19487    //
19488    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
19489    // (63e18a0) value-shape suites on the peer payload axes. Until this
19490    // gate landed `WitContract::target()` only refused the empty string
19491    // for the Store arm; a structurally invalid slot (raw whitespace,
19492    // control character, non-ASCII byte, paste-from-binary multi-line
19493    // blob) silently passed validate and surfaced at runtime as a
19494    // per-backend kv write rejection or a silent next-read corruption,
19495    // far from the source caixa.lisp with no field naming which
19496    // `:contratos` edge carried the typo. Every authoring footgun the
19497    // kv backend intersection-floor would catch on write now becomes a
19498    // caixa-build-time `ContratoSlotInvalid` with the offending
19499    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
19500    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
19501    // peer payload axes; same shared predicate
19502    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
19503    // any two axes' rule enforcement is a build error at the
19504    // predicate, not piecemeal across renderers. Closes the typed
19505    // payload-axis value-shape trajectory across all three legs of the
19506    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
19507
19508    fn contrato_slot_err(slot: &str) -> AplicacaoError {
19509        // Fresh spec per call so the new contract doesn't collide on
19510        // identity with `three_member_spec`'s pre-existing entries
19511        // and doesn't close a synchronous cycle the cycle detector
19512        // would reject before the slot-shape gate fires. The new edge
19513        // uses `(payment, catalog)` — a pair the fixture doesn't
19514        // already declare in either direction (the fixture carries
19515        // `cart -> catalog` and `cart -> payment`, so `payment ->
19516        // catalog` doesn't form a cycle on the sync subgraph) — with
19517        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
19518        // slot-shape gate fires cleanly after the wit-shape gate
19519        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
19520        // peer `contrato_subject_err` helper uses (63e18a0).
19521        let mut s = three_member_spec();
19522        s.contratos.push(WitContract {
19523            de: "payment".into(),
19524            para: "catalog".into(),
19525            wit: "wasi:keyvalue/store".into(),
19526            endpoint: None,
19527            subject: None,
19528            slot: Some(slot.into()),
19529        });
19530        s.validate().unwrap_err()
19531    }
19532
19533    #[test]
19534    fn rejects_store_contrato_slot_with_whitespace() {
19535        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
19536        // silently landed at the kv backend with whitespace whose
19537        // runtime behavior varies unpredictably across backends (etcd
19538        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
19539        // rejects on write). Now caught at the source caixa.lisp.
19540        let err = contrato_slot_err("check out/$order");
19541        assert!(
19542            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
19543                if slot == "check out/$order" && reason.contains("whitespace")),
19544            "got {err:?}"
19545        );
19546    }
19547
19548    #[test]
19549    fn rejects_store_contrato_slot_with_tab() {
19550        // Tab byte arm-pinned separately from the space arm so a
19551        // future relaxation that admits one but not the other surfaces
19552        // here.
19553        let err = contrato_slot_err("check\tout");
19554        assert!(
19555            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
19556                if slot == "check\tout" && reason.contains("whitespace")),
19557            "got {err:?}"
19558        );
19559    }
19560
19561    #[test]
19562    fn rejects_store_contrato_slot_with_control_char() {
19563        // SOH (0x01) — distinct from the whitespace arm. Redis admits
19564        // and corrupts on RESP protocol framing; DynamoDB rejects on
19565        // write.
19566        let err = contrato_slot_err("checkout/\x01order");
19567        assert!(
19568            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
19569                if slot == "checkout/\x01order" && reason.contains("control character")),
19570            "got {err:?}"
19571        );
19572    }
19573
19574    #[test]
19575    fn rejects_store_contrato_slot_with_newline() {
19576        // Embedded newline — the canonical "the paste-from-binary slug
19577        // spans multiple lines" footgun. Distinct from the whitespace
19578        // arm because `\n` is a control character (0x0A).
19579        let err = contrato_slot_err("checkout\norder");
19580        assert!(
19581            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
19582                if slot == "checkout\norder" && reason.contains("control character")),
19583            "got {err:?}"
19584        );
19585    }
19586
19587    #[test]
19588    fn rejects_store_contrato_slot_with_non_ascii() {
19589        // Un-percent-encoded non-ASCII byte — the canonical "I copied
19590        // the slot from a doc with accented characters" footgun. Each
19591        // kv backend re-encodes non-ASCII differently (etcd preserves
19592        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
19593        // rejects), so the typed slot's value set is the intersection-
19594        // floor every backend admits identically (printable ASCII).
19595        let err = contrato_slot_err("ch\u{e9}ckout/$order");
19596        assert!(
19597            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
19598                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
19599            "got {err:?}"
19600        );
19601    }
19602
19603    #[test]
19604    fn rejects_store_contrato_slot_too_long() {
19605        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
19606        // legitimate-shape arms all pass (a single all-`a` token, no
19607        // separators); only the cap arm fires. Surfaces the paste-
19608        // from-binary / accidental-multi-line-blob landing footgun.
19609        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
19610        // `rejects_http_contrato_endpoint_too_long` on the peer
19611        // payload axes.
19612        let big = "a".repeat(513);
19613        assert_eq!(big.len(), 513);
19614        let err = contrato_slot_err(&big);
19615        assert!(
19616            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
19617                if slot == &big && reason.contains("max length of 512")),
19618            "got {err:?}"
19619        );
19620    }
19621
19622    #[test]
19623    fn store_contrato_slot_max_length_validates() {
19624        // 512-byte slot — exactly the cap. Boundary pin: drift in the
19625        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
19626        // simultaneously, mirroring
19627        // `pubsub_contrato_subject_max_length_validates` and
19628        // `http_contrato_endpoint_max_length_validates` on the peer
19629        // payload axes.
19630        let big = "a".repeat(512);
19631        assert_eq!(big.len(), 512);
19632        let mut s = three_member_spec();
19633        s.contratos.push(WitContract {
19634            de: "payment".into(),
19635            para: "catalog".into(),
19636            wit: "wasi:keyvalue/store".into(),
19637            endpoint: None,
19638            subject: None,
19639            slot: Some(big),
19640        });
19641        s.validate().unwrap();
19642    }
19643
19644    #[test]
19645    fn store_contrato_slot_accepts_canonical_forms() {
19646        // Positive-set sweep: every canonical kv slot template the
19647        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
19648        // (single-token identifiers, path-namespaced `$`-templates,
19649        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
19650        // snake_case / kebab-case / MixedCase tokens, digit-bearing
19651        // tokens, percent-encoded fragments) must remain valid
19652        // contrato slots too. Drift between this list and the
19653        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
19654        // surfaces at the shared predicate — one source of truth.
19655        // Uses a fresh `(payment, catalog)` edge so none of the swept
19656        // slots collide with the pre-existing entries in
19657        // `three_member_spec`.
19658        for slot in [
19659            "checkout",
19660            "checkout/$orderId",
19661            "users:{tenant}/{id}",
19662            "session.<sid>",
19663            "session.tokens.<sid>",
19664            "snake_case_key",
19665            "kebab-case-key",
19666            "MixedCase",
19667            "shard0",
19668            "v2/key",
19669            "users/caf%C3%A9",
19670        ] {
19671            let mut s = three_member_spec();
19672            s.contratos.push(WitContract {
19673                de: "payment".into(),
19674                para: "catalog".into(),
19675                wit: "wasi:keyvalue/store".into(),
19676                endpoint: None,
19677                subject: None,
19678                slot: Some(slot.into()),
19679            });
19680            s.validate()
19681                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
19682        }
19683    }
19684
19685    #[test]
19686    fn contrato_slot_empty_takes_precedence_over_invalid() {
19687        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
19688        // diagnostic on `""` and must lead — the value-shape gate is
19689        // only reached after the empty-check fires. Mirrors
19690        // `contrato_subject_empty_takes_precedence_over_invalid` and
19691        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
19692        // the peer payload axes.
19693        let mut s = three_member_spec();
19694        s.contratos.push(WitContract {
19695            de: "payment".into(),
19696            para: "catalog".into(),
19697            wit: "wasi:keyvalue/store".into(),
19698            endpoint: None,
19699            subject: None,
19700            slot: Some(String::new()),
19701        });
19702        let err = s.validate().unwrap_err();
19703        assert!(
19704            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
19705            "got {err:?}"
19706        );
19707    }
19708
19709    #[test]
19710    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
19711        // Diagnostic-shape pin — the offending `:slot` + `:de` +
19712        // `:para` + a non-empty reason flow through verbatim so the
19713        // author can grep their caixa.lisp for the offending contrato
19714        // block and fix it in one edit. Same shape as
19715        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
19716        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
19717        // on the peer payload axes.
19718        let err = contrato_slot_err("check out/$order");
19719        match err {
19720            AplicacaoError::ContratoSlotInvalid {
19721                de,
19722                para,
19723                slot,
19724                reason,
19725            } => {
19726                assert_eq!(de, "payment");
19727                assert_eq!(para, "catalog");
19728                assert_eq!(slot, "check out/$order");
19729                assert!(!reason.is_empty(), "reason field must be non-empty");
19730            }
19731            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
19732        }
19733    }
19734
19735    #[test]
19736    fn target_view_store_slot_passes_through_to_typed_view() {
19737        // The compounding theorem on the store axis: every
19738        // `WitTarget::Store { slot }` returned by `target()` carries a
19739        // kv-backend-accepted slot template. Renderers downstream of
19740        // `typed_view()` (the future per-Servico `:capabilities
19741        // wasi:keyvalue/store` axis emitter, the future `feira app
19742        // graph` view's slot labeller, the future kv-provider CR
19743        // materializer) can rely on this without re-checking — the
19744        // type system carries the proof. Mirrors
19745        // `target_view_pubsub_subject_passes_through_to_typed_view` on
19746        // the peer payload axis.
19747        let store = WitContract {
19748            de: "a".into(),
19749            para: "b".into(),
19750            wit: "wasi:keyvalue/store".into(),
19751            endpoint: None,
19752            subject: None,
19753            slot: Some("checkout/$orderId".into()),
19754        };
19755        match store.target().unwrap() {
19756            WitTarget::Store { slot } => {
19757                assert_eq!(slot, "checkout/$orderId");
19758            }
19759            other => panic!("expected Store, got {other:?}"),
19760        }
19761    }
19762
19763    #[test]
19764    fn rejects_self_loop_in_synchronous_contratos() {
19765        // A synchronous self-edge (`cart → cart` over HTTP) is now
19766        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
19767        // "this edge is degenerate" diagnostic — rather than incidentally
19768        // by the cycle detector framing it as a `["cart", "cart"]`
19769        // multi-node deadlock.
19770        let mut s = three_member_spec();
19771        s.contratos.push(contract_http("cart", "cart", "/loop"));
19772        let err = s.validate().unwrap_err();
19773        match err {
19774            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
19775                assert_eq!(caixa, "cart");
19776                assert_eq!(wit, "wasi:http/proxy");
19777            }
19778            other => panic!("expected ContratoSelfLoop, got {other:?}"),
19779        }
19780    }
19781
19782    #[test]
19783    fn rejects_self_loop_in_pubsub_contratos() {
19784        // The cycle detector excludes pub-sub edges (acyclic by
19785        // construction), so before the explicit gate a `nats:pub-sub`
19786        // self-edge silently validated and rendered a self-allow CNP.
19787        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
19788        let mut s = three_member_spec();
19789        s.contratos.push(WitContract {
19790            de: "payment".into(),
19791            para: "payment".into(),
19792            wit: "nats:pub-sub".into(),
19793            endpoint: None,
19794            subject: Some("rio.events.payment".into()),
19795            slot: None,
19796        });
19797        let err = s.validate().unwrap_err();
19798        match err {
19799            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
19800                assert_eq!(caixa, "payment");
19801                assert_eq!(wit, "nats:pub-sub");
19802            }
19803            other => panic!("expected ContratoSelfLoop, got {other:?}"),
19804        }
19805    }
19806
19807    #[test]
19808    fn self_loop_fires_before_payload_shape_check() {
19809        // The structural "this edge can't exist" error precedes the
19810        // narrower payload-shape diagnostics: a self-edge carrying an
19811        // otherwise-malformed endpoint still reports ContratoSelfLoop,
19812        // not ContratoEndpointInvalid.
19813        let mut s = three_member_spec();
19814        s.contratos.push(WitContract {
19815            de: "cart".into(),
19816            para: "cart".into(),
19817            wit: "wasi:http/proxy".into(),
19818            endpoint: Some("not-absolute".into()),
19819            subject: None,
19820            slot: None,
19821        });
19822        match s.validate().unwrap_err() {
19823            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
19824            other => panic!("expected ContratoSelfLoop, got {other:?}"),
19825        }
19826    }
19827
19828    #[test]
19829    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
19830        // A self-edge naming a non-member reports the more fundamental
19831        // ContratoMemberMissing first (the member doesn't exist), so the
19832        // self-loop gate is reached only once both endpoints resolve.
19833        let mut s = three_member_spec();
19834        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
19835        match s.validate().unwrap_err() {
19836            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
19837            other => panic!("expected ContratoMemberMissing, got {other:?}"),
19838        }
19839    }
19840
19841    #[test]
19842    fn rejects_two_node_synchronous_cycle() {
19843        let mut s = three_member_spec();
19844        // existing edges: cart → catalog, cart → payment
19845        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
19846        s.contratos
19847            .push(contract_http("catalog", "cart", "/refresh"));
19848        let err = s.validate().unwrap_err();
19849        match err {
19850            AplicacaoError::ContratoCycle { cycle } => {
19851                // Cycle traversal should mention both endpoints, with
19852                // the back-edge target appearing as both first and last
19853                // element to close the loop.
19854                assert!(cycle.len() >= 3);
19855                assert_eq!(cycle.first(), cycle.last());
19856                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
19857                assert!(body.contains("cart"));
19858                assert!(body.contains("catalog"));
19859            }
19860            other => panic!("expected ContratoCycle, got {other:?}"),
19861        }
19862    }
19863
19864    #[test]
19865    fn rejects_three_node_synchronous_cycle() {
19866        let mut s = three_member_spec();
19867        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
19868        s.contratos = vec![
19869            contract_http("catalog", "cart", "/x"),
19870            contract_http("cart", "payment", "/y"),
19871            contract_http("payment", "catalog", "/z"),
19872        ];
19873        let err = s.validate().unwrap_err();
19874        match err {
19875            AplicacaoError::ContratoCycle { cycle } => {
19876                assert_eq!(cycle.first(), cycle.last());
19877                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
19878                assert_eq!(body.len(), 3);
19879                assert!(body.contains("cart"));
19880                assert!(body.contains("catalog"));
19881                assert!(body.contains("payment"));
19882            }
19883            other => panic!("expected ContratoCycle, got {other:?}"),
19884        }
19885    }
19886
19887    #[test]
19888    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
19889        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
19890        // "acyclic by construction" — so a cycle whose closing edge
19891        // is pub-sub should NOT raise ContratoCycle.
19892        let mut s = three_member_spec();
19893        s.contratos = vec![
19894            contract_http("catalog", "cart", "/x"),
19895            contract_http("cart", "payment", "/y"),
19896            // Closing edge is pub-sub — async; not a sync deadlock.
19897            WitContract {
19898                de: "payment".into(),
19899                para: "catalog".into(),
19900                wit: "nats:pub-sub".into(),
19901                endpoint: None,
19902                subject: Some("checkout.events.charge.completed".into()),
19903                slot: None,
19904            },
19905        ];
19906        s.validate().expect("pub-sub edge breaks the sync cycle");
19907    }
19908
19909    #[test]
19910    fn store_edge_counts_as_synchronous_for_cycle_detection() {
19911        // wasi:keyvalue/store is request/response; a cycle through one
19912        // *is* a sync deadlock, just like HTTP.
19913        let mut s = three_member_spec();
19914        s.contratos = vec![
19915            contract_http("catalog", "cart", "/x"),
19916            WitContract {
19917                de: "cart".into(),
19918                para: "catalog".into(),
19919                wit: "wasi:keyvalue/store".into(),
19920                endpoint: None,
19921                subject: None,
19922                slot: Some("session/$id".into()),
19923            },
19924        ];
19925        let err = s.validate().unwrap_err();
19926        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
19927    }
19928
19929    #[test]
19930    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
19931        // Capability-only edges (unknown WIT shape, no payload) default
19932        // to synchronous — safer; authors with truly async capability
19933        // semantics can model them as pub-sub explicitly.
19934        let mut s = three_member_spec();
19935        s.contratos = vec![
19936            contract_http("catalog", "cart", "/x"),
19937            WitContract {
19938                de: "cart".into(),
19939                para: "catalog".into(),
19940                wit: "custom:exchange".into(),
19941                endpoint: None,
19942                subject: None,
19943                slot: None,
19944            },
19945        ];
19946        let err = s.validate().unwrap_err();
19947        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
19948    }
19949
19950    #[test]
19951    fn long_acyclic_chain_validates() {
19952        // A long sync chain (no back-edges) must validate even when
19953        // every node is reachable from the first.
19954        let mut s = three_member_spec();
19955        s.membros = vec![
19956            membro("a", "^0.1"),
19957            membro("b", "^0.1"),
19958            membro("c", "^0.1"),
19959            membro("d", "^0.1"),
19960            membro("e", "^0.1"),
19961        ];
19962        s.contratos = vec![
19963            contract_http("a", "b", "/1"),
19964            contract_http("b", "c", "/2"),
19965            contract_http("c", "d", "/3"),
19966            contract_http("d", "e", "/4"),
19967        ];
19968        s.entrada.as_mut().unwrap().para = "a".into();
19969        s.validate().unwrap();
19970    }
19971
19972    #[test]
19973    fn diamond_acyclic_validates() {
19974        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
19975        let mut s = three_member_spec();
19976        s.membros = vec![
19977            membro("a", "^0.1"),
19978            membro("b", "^0.1"),
19979            membro("c", "^0.1"),
19980            membro("d", "^0.1"),
19981        ];
19982        s.contratos = vec![
19983            contract_http("a", "b", "/1"),
19984            contract_http("a", "c", "/2"),
19985            contract_http("b", "d", "/3"),
19986            contract_http("c", "d", "/4"),
19987        ];
19988        s.entrada.as_mut().unwrap().para = "a".into();
19989        s.validate().unwrap();
19990    }
19991
19992    // ── duplicate-`:contratos` build-error gate ──────────────────────────
19993
19994    #[test]
19995    fn rejects_duplicate_http_contrato() {
19996        // Fail-before-pass-after pin: the fixture's `cart → catalog`
19997        // HTTP edge appears once. Push an identical entry — same
19998        // (de, para, wit, endpoint) — and validate() must reject it.
19999        // Until this gate landed the typed surface accepted the
20000        // duplicate silently and caixa-mesh's `cilium_network_policies`
20001        // emitted two ``CiliumNetworkPolicy`` objects with identical
20002        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
20003        // admission rejects on `kubectl apply` far from the source.
20004        let mut s = three_member_spec();
20005        s.contratos
20006            .push(contract_http("cart", "catalog", "/products/:id"));
20007        let err = s.validate().unwrap_err();
20008        assert!(
20009            matches!(
20010                err,
20011                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
20012                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
20013            ),
20014            "got {err:?}"
20015        );
20016    }
20017
20018    #[test]
20019    fn rejects_duplicate_pubsub_contrato() {
20020        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
20021        // edges with identical (de, para, subject) are degenerate;
20022        // pin that the typed surface refuses both at validate time.
20023        let mut s = three_member_spec();
20024        let pubsub = WitContract {
20025            de: "payment".into(),
20026            para: "cart".into(),
20027            wit: "nats:pub-sub".into(),
20028            endpoint: None,
20029            subject: Some("checkout.events.charge.failed".into()),
20030            slot: None,
20031        };
20032        s.contratos.push(pubsub.clone());
20033        s.contratos.push(pubsub);
20034        let err = s.validate().unwrap_err();
20035        assert!(
20036            matches!(
20037                err,
20038                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
20039                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
20040            ),
20041            "got {err:?}"
20042        );
20043    }
20044
20045    #[test]
20046    fn rejects_duplicate_store_contrato() {
20047        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
20048        // edges with identical (de, para, slot) collapse to one mesh-
20049        // policy edge; pin the build error.
20050        let mut s = three_member_spec();
20051        let store = WitContract {
20052            de: "cart".into(),
20053            para: "payment".into(),
20054            wit: "wasi:keyvalue/store".into(),
20055            endpoint: None,
20056            subject: None,
20057            slot: Some("checkout/$orderId".into()),
20058        };
20059        // Drop the conflicting HTTP `cart → payment` edge from the
20060        // fixture so the duplicate-store pair is the only one
20061        // distinguishable on this pair.
20062        s.contratos
20063            .retain(|c| !(c.de == "cart" && c.para == "payment"));
20064        s.contratos.push(store.clone());
20065        s.contratos.push(store);
20066        let err = s.validate().unwrap_err();
20067        assert!(
20068            matches!(
20069                err,
20070                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
20071                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
20072            ),
20073            "got {err:?}"
20074        );
20075    }
20076
20077    #[test]
20078    fn rejects_duplicate_capability_contrato() {
20079        // Same gate on the pure-capability axis (no payload selector).
20080        // Two contracts with identical (de, para, wit) and no
20081        // endpoint/subject/slot are duplicate edges; pin so a future
20082        // `target_label` change can't accidentally collapse the
20083        // capability arm into a None-shaped key that compares equal
20084        // to a populated one.
20085        let mut s = three_member_spec();
20086        let capability = WitContract {
20087            de: "cart".into(),
20088            para: "catalog".into(),
20089            wit: "pleme:cap/audit".into(),
20090            endpoint: None,
20091            subject: None,
20092            slot: None,
20093        };
20094        s.contratos.push(capability.clone());
20095        s.contratos.push(capability);
20096        let err = s.validate().unwrap_err();
20097        match err {
20098            AplicacaoError::ContratoDuplicate {
20099                de,
20100                para,
20101                wit,
20102                target,
20103            } => {
20104                assert_eq!(de, "cart");
20105                assert_eq!(para, "catalog");
20106                assert_eq!(wit, "pleme:cap/audit");
20107                assert!(
20108                    target.contains("capability"),
20109                    "capability-edge duplicate diagnostic must surface the \
20110                     no-payload shape (got target = {target:?})"
20111                );
20112            }
20113            other => panic!("expected ContratoDuplicate, got {other:?}"),
20114        }
20115    }
20116
20117    #[test]
20118    fn accepts_distinct_http_paths_between_same_pair() {
20119        // Negative pin: two HTTP contracts cart → catalog at distinct
20120        // endpoints (`/products/:id` and `/search`) are *not*
20121        // duplicates — they're distinct typed edges differing on the
20122        // payload axis. The duplicate-gate must not over-match here,
20123        // since the cart-calls-catalog-on-multiple-paths shape is the
20124        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
20125        // example: cart calls catalog at /products/:id, payment at
20126        // /charge — same shape extends to two paths on one para).
20127        let mut s = three_member_spec();
20128        s.contratos
20129            .push(contract_http("cart", "catalog", "/search"));
20130        s.validate()
20131            .expect("distinct endpoints between same (de, para) must validate");
20132    }
20133
20134    #[test]
20135    fn accepts_same_endpoint_on_different_pairs() {
20136        // Negative pin: the same `/charge` endpoint reused on two
20137        // different (de, para) pairs is two distinct edges, not a
20138        // duplicate. Pinning this shape so the gate's identity key
20139        // includes both `de` and `para` (not just `(wit, endpoint)`).
20140        let mut s = three_member_spec();
20141        s.contratos
20142            .push(contract_http("payment", "catalog", "/charge"));
20143        s.validate()
20144            .expect("same endpoint reused on distinct (de, para) must validate");
20145    }
20146
20147    #[test]
20148    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
20149        // Pin the diagnostic shape: the duplicate-edge error names
20150        // *which* target field carried the conflict, so the author
20151        // doesn't have to re-grep the source caixa.lisp to find it.
20152        // Same self-locating diagnostic discipline as
20153        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
20154        let mut s = three_member_spec();
20155        s.contratos
20156            .push(contract_http("cart", "catalog", "/products/:id"));
20157        let err = s.validate().unwrap_err();
20158        let msg = format!("{err}");
20159        assert!(
20160            msg.contains("\"/products/:id\""),
20161            "duplicate-contrato diagnostic must name the offending \
20162             :endpoint payload (got: {msg:?})"
20163        );
20164        assert!(
20165            msg.contains("cart") && msg.contains("catalog"),
20166            "diagnostic must name both endpoints of the duplicate edge \
20167             (got: {msg:?})"
20168        );
20169    }
20170
20171    #[test]
20172    fn duplicate_contrato_gate_runs_after_membership_check() {
20173        // Order pin: a duplicate contract whose `:de` is *also* not in
20174        // `:membros` surfaces the membership error first — the
20175        // missing-member diagnostic is more locating than the
20176        // duplicate-edge one (the author has to fix the membership
20177        // before the duplicate is meaningful). Same ordering
20178        // discipline as `membros_validation_runs_before_contratos_membership_check`.
20179        let mut s = three_member_spec();
20180        s.contratos.push(contract_http("phantom", "catalog", "/x"));
20181        s.contratos.push(contract_http("phantom", "catalog", "/x"));
20182        let err = s.validate().unwrap_err();
20183        assert!(
20184            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
20185            "membership-missing must fire before duplicate-edge (got {err:?})"
20186        );
20187    }
20188
20189    #[test]
20190    fn duplicate_contrato_gate_runs_after_target_shape_check() {
20191        // Order pin: a contract with a malformed target (e.g. an HTTP
20192        // wit world with an empty :endpoint) surfaces the target-shape
20193        // error first, not the duplicate one. Even when two such
20194        // malformed entries are identical, the per-contract `target()`
20195        // check fires inside the loop *before* the duplicate-key
20196        // insert, so the diagnostic remains the most-locating one.
20197        let mut s = three_member_spec();
20198        let malformed = WitContract {
20199            de: "cart".into(),
20200            para: "catalog".into(),
20201            wit: "wasi:http/proxy".into(),
20202            endpoint: Some(String::new()),
20203            subject: None,
20204            slot: None,
20205        };
20206        s.contratos.push(malformed.clone());
20207        s.contratos.push(malformed);
20208        let err = s.validate().unwrap_err();
20209        assert!(
20210            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
20211            "endpoint-empty must fire before duplicate-edge (got {err:?})"
20212        );
20213    }
20214
20215    #[test]
20216    fn wit_target_label_pins_per_variant_format() {
20217        // Label format is the single source of truth every duplicate-
20218        // `:contratos` diagnostic + every future `feira app graph`
20219        // consumer routes through. Pin the shape per variant so a
20220        // future edit to `WitTarget::label` (e.g. a JSON emitter that
20221        // strips the leading `:`, or a rename from `endpoint` →
20222        // `path`) surfaces as a red-red test rather than as a silent
20223        // downstream diagnostic drift. Together with the exhaustive
20224        // `match` on `WitTarget` inside `label()`, adding a future
20225        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
20226        // peer, per-edge WIT registry variants) is a compile error at
20227        // the label site — not a fall-through into the `Capability`
20228        // "no payload" default the prior raw-field-probe helper
20229        // silently landed on.
20230        assert_eq!(
20231            WitTarget::Http {
20232                endpoint: "/charge",
20233            }
20234            .label(),
20235            "\
20236:endpoint \"/charge\""
20237        );
20238        assert_eq!(
20239            WitTarget::PubSub {
20240                subject: "events.checkout.paid",
20241            }
20242            .label(),
20243            "\
20244:subject \"events.checkout.paid\""
20245        );
20246        assert_eq!(
20247            WitTarget::Store {
20248                slot: "checkout/$order",
20249            }
20250            .label(),
20251            "\
20252:slot \"checkout/$order\""
20253        );
20254        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
20255        // Capability-arm label routes through the lifted
20256        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
20257        // declaration per arm, next to the variant" discipline the
20258        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
20259        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
20260        // consts already carry extends to the payload-less arm; the
20261        // byte-string equality pin below plus this label-routes-
20262        // through-the-const pin make a future rebrand on either the
20263        // const declaration or the `label()` template a build error
20264        // here rather than a downstream consumer surprise.
20265        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
20266        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
20267    }
20268
20269    #[test]
20270    fn wit_target_display_routes_through_label_helper() {
20271        // Fail-before-pass-after pin on the fourth (and only remaining)
20272        // typed-shape-discriminator axis to converge onto the
20273        // three-path-convergence discipline the sibling M3
20274        // [`PlacementStrategy`] (0a2f653) and M2
20275        // [`crate::supervisor::RestartStrategy`] /
20276        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
20277        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
20278        // through [`WitTarget::label`], so every consumer reaching for
20279        // `format!("{v}")` on a typed payload target lands on the same
20280        // stable author-facing byte-string [`WitTarget::label`] returns
20281        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
20282        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
20283        // `:contratos` gate seeds via [`WitTarget::label`] at
20284        // aplicacao.rs:5491 already threads through.
20285        //
20286        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
20287        // through to the `Debug` derive's structural output
20288        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
20289        // rather than the [`WitTarget::label`] helper's stable byte-
20290        // string (`:endpoint "/charge"` — the author-facing `:contratos`
20291        // keyword form). Every future consumer that reaches for
20292        // `format!("{target}")` — the canonical shape every user-facing
20293        // pretty-print site on the sibling typed-enum axes
20294        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
20295        // [`crate::supervisor::RestartPolicy`]) already uses — would
20296        // silently land under a different byte-string than the
20297        // [`WitTarget::label`] callers that the duplicate-`:contratos`
20298        // diagnostic already threads through, with the mismatch
20299        // surfacing as a downstream diagnostic / graph / audit line
20300        // reading one spelling while the substrate's own gate emitted
20301        // another.
20302        //
20303        // Pin the routing here so a future
20304        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
20305        // that hand-rolls the per-arm formatting instead of delegating
20306        // to [`WitTarget::label`] fails at caixa-core build time.
20307        for variant in [
20308            WitTarget::Http {
20309                endpoint: "/charge",
20310            },
20311            WitTarget::PubSub {
20312                subject: "events.checkout.paid",
20313            },
20314            WitTarget::Store {
20315                slot: "checkout/$order",
20316            },
20317            WitTarget::Capability,
20318        ] {
20319            assert_eq!(
20320                variant.to_string(),
20321                variant.label(),
20322                "WitTarget::{variant:?} Display must route through \
20323                 WitTarget::label (single source of truth: the lifted \
20324                 payload_pair 4-arm dispatch the label helper already \
20325                 threads through)"
20326            );
20327        }
20328    }
20329
20330    #[test]
20331    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
20332        // Consumer-side pin on the three-path convergence:
20333        // [`std::fmt::Display`] agrees byte-for-byte with the
20334        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
20335        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
20336        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
20337        // Pre-lift the two paths were structurally independent — the
20338        // substrate-side gate reached for `target_view.label()` while a
20339        // future downstream diagnostic / graph / audit line reaching
20340        // for `format!("{target}")` would silently land on the `Debug`
20341        // derive's structural output. Pin the two paths byte-for-byte
20342        // here so any future variant addition (M4 `Rest`/`Grpc` split
20343        // of [`WitTarget::Http`], `Queue`-shaped peer of
20344        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
20345        // match error at [`WitTarget::payload_pair`] rather than a
20346        // silent per-consumer dispatch miss.
20347        for variant in [
20348            WitTarget::Http {
20349                endpoint: "/charge",
20350            },
20351            WitTarget::PubSub {
20352                subject: "events.checkout.paid",
20353            },
20354            WitTarget::Store {
20355                slot: "checkout/$order",
20356            },
20357            WitTarget::Capability,
20358        ] {
20359            assert_eq!(
20360                format!("{variant}"),
20361                variant.label(),
20362                "WitTarget::{variant:?} Display byte-string must match \
20363                 the AplicacaoError::ContratoDuplicate `target:` carrier \
20364                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
20365                 seeds via WitTarget::label — three-path convergence: \
20366                 Display + label + payload_pair all resolve to the same \
20367                 per-arm byte-string"
20368            );
20369        }
20370    }
20371
20372    #[test]
20373    fn wit_target_payload_pair_pins_per_variant() {
20374        // Pin the per-arm `(field-name, payload)` pair single-sourced
20375        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
20376        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
20377        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
20378        // and [`WitTarget::field_name`] (returns the first component)
20379        // route through. Until this lift landed [`WitTarget::label`]
20380        // dispatched on the same three arms with a per-arm
20381        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
20382        // paired [`WitTarget::HTTP_FIELD_NAME`] /
20383        // [`WitTarget::PUBSUB_FIELD_NAME`] /
20384        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
20385        // canonical "same shape, written N times" duplication
20386        // THEORY.md §I.3.5 promotes to a build-time concern. A future
20387        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
20388        // [`WitTarget::Http`], `Queue`-shaped peer of
20389        // [`WitTarget::Store`]) is one match-arm edit at
20390        // [`WitTarget::payload_pair`], visible here as a compile-time
20391        // exhaustiveness error on both this pin and the label-format
20392        // pin above.
20393        assert_eq!(
20394            WitTarget::Http {
20395                endpoint: "/charge"
20396            }
20397            .payload_pair(),
20398            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
20399        );
20400        assert_eq!(
20401            WitTarget::PubSub {
20402                subject: "events.x",
20403            }
20404            .payload_pair(),
20405            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
20406        );
20407        assert_eq!(
20408            WitTarget::Store {
20409                slot: "checkout/$order",
20410            }
20411            .payload_pair(),
20412            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
20413        );
20414        assert_eq!(WitTarget::Capability.payload_pair(), None);
20415    }
20416
20417    #[test]
20418    fn wit_target_field_name_pins_per_variant() {
20419        // Pin the per-arm author-facing `:contratos` payload field
20420        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
20421        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
20422        // + returned by [`WitTarget::field_name`]. Every downstream
20423        // consumer (the [`WitContract::target`] gate's `expected:`
20424        // scalar, the [`WitTarget::label`] template's keyword prefix,
20425        // the `feira app graph` verb's `endpoint=…` prefix) routes
20426        // through the same three peer consts, so a rename on the
20427        // author-surface `(defcaixa … :contratos ((:de … :para …
20428        // :wit … :endpoint …)))` field lands in exactly one place.
20429        assert_eq!(
20430            WitTarget::Http {
20431                endpoint: "/charge"
20432            }
20433            .field_name(),
20434            Some(WitTarget::HTTP_FIELD_NAME),
20435        );
20436        assert_eq!(
20437            WitTarget::PubSub {
20438                subject: "events.x",
20439            }
20440            .field_name(),
20441            Some(WitTarget::PUBSUB_FIELD_NAME),
20442        );
20443        assert_eq!(
20444            WitTarget::Store {
20445                slot: "checkout/$order",
20446            }
20447            .field_name(),
20448            Some(WitTarget::STORE_FIELD_NAME),
20449        );
20450        // Capability arm carries no payload field — the diagnostic
20451        // never reports `expected: "capability"` because the gate's
20452        // Capability arm accepts no payload at all (it fires the
20453        // "expected: none" WrongTarget error instead), so the field-
20454        // name method returns None here rather than a placeholder.
20455        assert_eq!(WitTarget::Capability.field_name(), None);
20456
20457        // Peer const scalar values pinned so a rename on either side
20458        // (author-surface field name in the `(defcaixa …)` DSL, or
20459        // the diagnostic's `expected:` scalar) can't drift without
20460        // failing here first.
20461        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
20462        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
20463        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
20464    }
20465
20466    #[test]
20467    fn wit_target_payload_pins_per_variant() {
20468        // Pin the per-arm payload scalar single-sourced onto the
20469        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
20470        // [`WitTarget::payload`] — the peer per-half projection to
20471        // [`WitTarget::field_name`] on the paired sub-selector axis. The
20472        // three payload-carrying arms round-trip their author-declared
20473        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
20474        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
20475        // the payload-less [`WitTarget::Capability`] arm returns `None`.
20476        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
20477        // (c6ec2af) pin on the Component-0 projection axis, extended
20478        // onto the Component-1 projection axis so both per-half readers
20479        // on the paired dispatch carry their own byte-shape pin.
20480        assert_eq!(
20481            WitTarget::Http {
20482                endpoint: "/charge",
20483            }
20484            .payload(),
20485            Some("/charge"),
20486        );
20487        assert_eq!(
20488            WitTarget::PubSub {
20489                subject: "events.x",
20490            }
20491            .payload(),
20492            Some("events.x"),
20493        );
20494        assert_eq!(
20495            WitTarget::Store {
20496                slot: "checkout/$order",
20497            }
20498            .payload(),
20499            Some("checkout/$order"),
20500        );
20501        assert_eq!(WitTarget::Capability.payload(), None);
20502    }
20503
20504    #[test]
20505    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
20506        // Per-variant equivalence pin: for every arm of [`WitTarget`],
20507        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
20508        // byte-for-byte. Guards the drift surface where a future refactor
20509        // that split one accessor off the shared match onto its own
20510        // dispatch — a well-meaning "inline the pair back into per-half
20511        // fields for one crate-internal caller who only wanted one half"
20512        // or a scratch `impl` shadowing the derived projection — would
20513        // silently desynchronize [`WitTarget::payload`] from the
20514        // authoritative [`WitTarget::payload_pair`] dispatch, and every
20515        // downstream consumer that thinks "the payload half of the pair"
20516        // would drift from the diagnostic / graph consumers reading the
20517        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
20518        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
20519        // per-half projection pin (`gitrefspec_ref_pair_projects_
20520        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
20521        // FluxCD source-controller `spec.ref.<field>` axis — same "one
20522        // paired dispatch, both per-half projections agree byte-for-
20523        // byte" discipline extended onto the M3 `:contratos` payload-
20524        // arm surface.
20525        for variant in [
20526            WitTarget::Http {
20527                endpoint: "/charge",
20528            },
20529            WitTarget::PubSub {
20530                subject: "events.checkout.paid",
20531            },
20532            WitTarget::Store {
20533                slot: "checkout/$order",
20534            },
20535            WitTarget::Capability,
20536        ] {
20537            let via_projection = variant.payload();
20538            let via_pair = variant.payload_pair().map(|(_, p)| p);
20539            assert_eq!(
20540                via_projection, via_pair,
20541                "WitTarget::{variant:?} payload() must equal \
20542                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
20543                 regression that splits the two per-half projections off \
20544                 their shared match would silently desynchronize the \
20545                 payload accessor from the paired dispatch every \
20546                 diagnostic / graph consumer reads through",
20547            );
20548        }
20549    }
20550
20551    #[test]
20552    fn wit_target_http_endpoint_pins_per_variant() {
20553        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
20554        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
20555        // substrate-primitive per-arm post-projection accessor every
20556        // L7-HTTP-facing consumer routes through, sibling to the peer
20557        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
20558        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
20559        // arm round-trips its author-declared endpoint verbatim as
20560        // `Some("/charge")`; the three sibling arms
20561        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
20562        // [`WitTarget::Capability`]) each return `None` because they
20563        // carry no HTTP endpoint by definition. Same fail-before-pass-
20564        // after per-variant discipline as the sibling
20565        // `wit_target_payload_pins_per_variant` (5d6dc92) /
20566        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
20567        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
20568        // the peer pan-arm / per-half projection axes — extended onto
20569        // the per-arm HTTP-shape post-projection axis so a future
20570        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
20571        // [`WitTarget::Http`], a `Queue`-shaped peer of
20572        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
20573        // error on the sibling [`WitTarget::http_endpoint`] match arms
20574        // whose payload the L7-HTTP-shape accept-set is meant to bound.
20575        assert_eq!(
20576            WitTarget::Http {
20577                endpoint: "/charge",
20578            }
20579            .http_endpoint(),
20580            Some("/charge"),
20581        );
20582        assert_eq!(
20583            WitTarget::PubSub {
20584                subject: "events.checkout.paid",
20585            }
20586            .http_endpoint(),
20587            None,
20588        );
20589        assert_eq!(
20590            WitTarget::Store {
20591                slot: "checkout/$order",
20592            }
20593            .http_endpoint(),
20594            None,
20595        );
20596        assert_eq!(WitTarget::Capability.http_endpoint(), None);
20597    }
20598
20599    #[test]
20600    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
20601        // Per-variant coherence pin: for every arm of [`WitTarget`],
20602        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
20603        // arm (both project the same author-declared request-path
20604        // scalar), and returns `None` on every sibling arm regardless of
20605        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
20606        // Store carry their own payload the pan-arm accessor surfaces,
20607        // but that payload is not an HTTP endpoint — the per-arm
20608        // accessor must not leak it through the HTTP-shape channel).
20609        // Guards the drift surface where a future refactor that
20610        // conflated the per-arm HTTP projection with the pan-arm
20611        // [`WitTarget::payload`] projection — a well-meaning "one
20612        // accessor for the L7 branch, one for the graph" collapse that
20613        // routes both through the same 4-arm dispatch — would silently
20614        // widen the L7-HTTP-shape accept-set onto pub-sub / store
20615        // payloads at the caixa-mesh L7 emit branch, admitting a
20616        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
20617        // rule with the operator-side apply-time symptom (Cilium's
20618        // eBPF data-plane rejects every ingress edge whose L7 filter
20619        // doesn't match the wire-format HTTP request line) far from
20620        // the source refactor. Sibling to the peer
20621        // `wit_target_payload_matches_payload_pair_second_component_
20622        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
20623        // extended onto the per-arm HTTP specialization axis so both
20624        // the pan-arm and the per-arm projections carry their own
20625        // byte-shape coherence witness against the substrate's typed
20626        // arm-family accept-set.
20627        for variant in [
20628            WitTarget::Http {
20629                endpoint: "/charge",
20630            },
20631            WitTarget::PubSub {
20632                subject: "events.checkout.paid",
20633            },
20634            WitTarget::Store {
20635                slot: "checkout/$order",
20636            },
20637            WitTarget::Capability,
20638        ] {
20639            let per_arm = variant.http_endpoint();
20640            let pan_arm = variant.payload();
20641            if variant.is_http() {
20642                assert_eq!(
20643                    per_arm, pan_arm,
20644                    "WitTarget::{variant:?} http_endpoint() must equal \
20645                     payload() on the Http arm — a per-arm-vs-pan-arm \
20646                     split would silently drift the L7 emit branch's \
20647                     path-scalar source from the graph verb's payload \
20648                     scalar source",
20649                );
20650            } else {
20651                assert_eq!(
20652                    per_arm, None,
20653                    "WitTarget::{variant:?} http_endpoint() must return \
20654                     None on non-Http arms — a leak that surfaced a \
20655                     pub-sub :subject or a key/value :slot through the \
20656                     HTTP-endpoint accessor would silently widen the \
20657                     Cilium L7 HTTP `path:` rule accept-set onto \
20658                     protocol shapes Cilium's eBPF data-plane can't \
20659                     introspect",
20660                );
20661            }
20662        }
20663    }
20664
20665    #[test]
20666    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
20667        // Per-variant coherence pin: for every arm of [`WitTarget`],
20668        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
20669        // drift surface where a future extension of the
20670        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
20671        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
20672        // accessor to cover both peers) landed without a paired
20673        // extension of the [`gen_platform::IsVariant`]-derived
20674        // `is_http()` predicate's accept-set, or vice versa — a
20675        // regression that split the "which arms count as HTTP-shaped
20676        // for L7-path emission?" answer between two dispatch surfaces
20677        // the substrate ships. Sibling to the peer
20678        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
20679        // on the paired dispatch axis — extended onto the per-arm
20680        // predicate-vs-accessor coherence axis so the gen-platform
20681        // IsVariant predicate and the substrate-lifted per-arm
20682        // accessor carry one shared answer to "is this the HTTP arm?".
20683        for variant in [
20684            WitTarget::Http {
20685                endpoint: "/charge",
20686            },
20687            WitTarget::PubSub {
20688                subject: "events.checkout.paid",
20689            },
20690            WitTarget::Store {
20691                slot: "checkout/$order",
20692            },
20693            WitTarget::Capability,
20694        ] {
20695            assert_eq!(
20696                variant.http_endpoint().is_some(),
20697                variant.is_http(),
20698                "WitTarget::{variant:?} http_endpoint().is_some() must \
20699                 equal is_http() — a drift would split the L7 emit \
20700                 branch's arm-set gate from the substrate-derived \
20701                 shape-discrimination predicate on the same axis",
20702            );
20703        }
20704    }
20705
20706    #[test]
20707    fn wit_target_pubsub_subject_pins_per_variant() {
20708        // Fail-before-pass-after pin: the substrate-canonical per-arm
20709        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
20710        // is the single dispatch every future pub-sub-facing consumer
20711        // routes through, sibling to the peer [`WitContract::subject`]
20712        // (63e18a0) pre-projection scalar accessor on the raw-field
20713        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
20714        // post-projection per-arm accessor on the sibling HTTP-shape
20715        // axis. The [`WitTarget::PubSub`] arm round-trips its
20716        // author-declared subject verbatim as
20717        // `Some("events.checkout.paid")`; the three sibling arms each
20718        // return `None` because they carry no NATS-shaped subject by
20719        // definition. Same fail-before-pass-after per-variant discipline
20720        // as the sibling `wit_target_http_endpoint_pins_per_variant`
20721        // pin on the peer per-arm axis — extended onto the per-arm
20722        // pub-sub-shape post-projection axis so a future [`WitTarget`]
20723        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
20724        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
20725        // compile-time exhaustiveness error on the sibling
20726        // [`WitTarget::pubsub_subject`] match arms whose payload the
20727        // pub-sub-shape accept-set is meant to bound.
20728        assert_eq!(
20729            WitTarget::PubSub {
20730                subject: "events.checkout.paid",
20731            }
20732            .pubsub_subject(),
20733            Some("events.checkout.paid"),
20734        );
20735        assert_eq!(
20736            WitTarget::Http {
20737                endpoint: "/charge",
20738            }
20739            .pubsub_subject(),
20740            None,
20741        );
20742        assert_eq!(
20743            WitTarget::Store {
20744                slot: "checkout/$order",
20745            }
20746            .pubsub_subject(),
20747            None,
20748        );
20749        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
20750    }
20751
20752    #[test]
20753    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
20754        // Per-variant coherence pin: for every arm of [`WitTarget`],
20755        // `.pubsub_subject()` equals `.payload()` on the
20756        // [`WitTarget::PubSub`] arm (both project the same
20757        // author-declared subject scalar), and returns `None` on every
20758        // sibling arm regardless of whether [`WitTarget::payload`]
20759        // itself returns `Some` (Http / Store carry their own payload
20760        // the pan-arm accessor surfaces, but that payload is not a
20761        // pub-sub subject — the per-arm accessor must not leak it
20762        // through the pub-sub-shape channel). Sibling to the peer
20763        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
20764        // coherence pin on the per-arm HTTP-shape axis — extended onto
20765        // the per-arm pub-sub specialization axis so both per-arm
20766        // projections carry their own byte-shape coherence witness
20767        // against the substrate's typed arm-family accept-set.
20768        for variant in [
20769            WitTarget::Http {
20770                endpoint: "/charge",
20771            },
20772            WitTarget::PubSub {
20773                subject: "events.checkout.paid",
20774            },
20775            WitTarget::Store {
20776                slot: "checkout/$order",
20777            },
20778            WitTarget::Capability,
20779        ] {
20780            let per_arm = variant.pubsub_subject();
20781            let pan_arm = variant.payload();
20782            if variant.is_pubsub() {
20783                assert_eq!(
20784                    per_arm, pan_arm,
20785                    "WitTarget::{variant:?} pubsub_subject() must equal \
20786                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
20787                     split would silently drift the pub-sub-shape emit \
20788                     branch's subject-scalar source from the graph verb's \
20789                     payload scalar source",
20790                );
20791            } else {
20792                assert_eq!(
20793                    per_arm, None,
20794                    "WitTarget::{variant:?} pubsub_subject() must return \
20795                     None on non-PubSub arms — a leak that surfaced an \
20796                     HTTP :endpoint or a key/value :slot through the \
20797                     pub-sub-subject accessor would silently widen the \
20798                     downstream NATS-shape accept-set onto protocol \
20799                     shapes NATS servers can't route",
20800                );
20801            }
20802        }
20803    }
20804
20805    #[test]
20806    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
20807        // Per-variant coherence pin: for every arm of [`WitTarget`],
20808        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
20809        // drift surface where a future extension of the
20810        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
20811        // without a paired extension of the [`gen_platform::IsVariant`]-
20812        // derived `is_pubsub()` predicate's accept-set, or vice versa
20813        // — a regression that split the "which arms count as pub-sub-
20814        // shaped for subject emission?" answer between two dispatch
20815        // surfaces the substrate ships. Sibling to the peer
20816        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
20817        // pin on the per-arm HTTP-shape axis — extended onto the
20818        // per-arm pub-sub predicate-vs-accessor coherence axis so the
20819        // gen-platform IsVariant predicate and the substrate-lifted
20820        // per-arm accessor carry one shared answer to "is this the
20821        // PubSub arm?".
20822        for variant in [
20823            WitTarget::Http {
20824                endpoint: "/charge",
20825            },
20826            WitTarget::PubSub {
20827                subject: "events.checkout.paid",
20828            },
20829            WitTarget::Store {
20830                slot: "checkout/$order",
20831            },
20832            WitTarget::Capability,
20833        ] {
20834            assert_eq!(
20835                variant.pubsub_subject().is_some(),
20836                variant.is_pubsub(),
20837                "WitTarget::{variant:?} pubsub_subject().is_some() must \
20838                 equal is_pubsub() — a drift would split the pub-sub \
20839                 emit branch's arm-set gate from the substrate-derived \
20840                 shape-discrimination predicate on the same axis",
20841            );
20842        }
20843    }
20844
20845    #[test]
20846    fn wit_target_store_slot_pins_per_variant() {
20847        // Fail-before-pass-after pin: the substrate-canonical per-arm
20848        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
20849        // is the single dispatch every future store-facing consumer
20850        // routes through, sibling to the peer [`WitContract::slot`]
20851        // pre-projection scalar accessor on the raw-field axis and to
20852        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
20853        // [`WitTarget::pubsub_subject`] post-projection per-arm
20854        // accessors on the sibling per-payload-arm axes. The
20855        // [`WitTarget::Store`] arm round-trips its author-declared
20856        // slot verbatim as `Some("checkout/$order")`; the three
20857        // sibling arms each return `None` because they carry no
20858        // WASI-key/value slot by definition. Same fail-before-pass-
20859        // after per-variant discipline as the sibling
20860        // `wit_target_http_endpoint_pins_per_variant` +
20861        // `wit_target_pubsub_subject_pins_per_variant` pins on the
20862        // peer per-arm axes — extended onto the per-arm store-shape
20863        // post-projection axis so a future [`WitTarget`] variant
20864        // addition trips a compile-time exhaustiveness error on the
20865        // sibling [`WitTarget::store_slot`] match arms whose payload
20866        // the store-shape accept-set is meant to bound.
20867        assert_eq!(
20868            WitTarget::Store {
20869                slot: "checkout/$order",
20870            }
20871            .store_slot(),
20872            Some("checkout/$order"),
20873        );
20874        assert_eq!(
20875            WitTarget::Http {
20876                endpoint: "/charge",
20877            }
20878            .store_slot(),
20879            None,
20880        );
20881        assert_eq!(
20882            WitTarget::PubSub {
20883                subject: "events.checkout.paid",
20884            }
20885            .store_slot(),
20886            None,
20887        );
20888        assert_eq!(WitTarget::Capability.store_slot(), None);
20889    }
20890
20891    #[test]
20892    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
20893        // Per-variant coherence pin: for every arm of [`WitTarget`],
20894        // `.store_slot()` equals `.payload()` on the
20895        // [`WitTarget::Store`] arm (both project the same
20896        // author-declared slot scalar), and returns `None` on every
20897        // sibling arm regardless of whether [`WitTarget::payload`]
20898        // itself returns `Some`. Sibling to the peer
20899        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
20900        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
20901        // pins on the per-arm HTTP and PubSub axes — closes the
20902        // per-arm-vs-pan-arm byte-shape coherence trio across all
20903        // three payload arms.
20904        for variant in [
20905            WitTarget::Http {
20906                endpoint: "/charge",
20907            },
20908            WitTarget::PubSub {
20909                subject: "events.checkout.paid",
20910            },
20911            WitTarget::Store {
20912                slot: "checkout/$order",
20913            },
20914            WitTarget::Capability,
20915        ] {
20916            let per_arm = variant.store_slot();
20917            let pan_arm = variant.payload();
20918            if variant.is_store() {
20919                assert_eq!(
20920                    per_arm, pan_arm,
20921                    "WitTarget::{variant:?} store_slot() must equal \
20922                     payload() on the Store arm — a per-arm-vs-pan-arm \
20923                     split would silently drift the store-shape emit \
20924                     branch's slot-scalar source from the graph verb's \
20925                     payload scalar source",
20926                );
20927            } else {
20928                assert_eq!(
20929                    per_arm, None,
20930                    "WitTarget::{variant:?} store_slot() must return \
20931                     None on non-Store arms — a leak that surfaced an \
20932                     HTTP :endpoint or a NATS :subject through the \
20933                     key/value-slot accessor would silently widen the \
20934                     downstream WASI-key/value slot accept-set onto \
20935                     protocol shapes the kv backends can't route",
20936                );
20937            }
20938        }
20939    }
20940
20941    #[test]
20942    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
20943        // Per-variant coherence pin: for every arm of [`WitTarget`],
20944        // `.store_slot().is_some()` iff `.is_store()`. Guards the
20945        // drift surface where a future extension of the
20946        // [`WitTarget::store_slot`] accessor's accept-set landed
20947        // without a paired extension of the [`gen_platform::IsVariant`]-
20948        // derived `is_store()` predicate's accept-set. Sibling to the
20949        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
20950        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
20951        // pins — closes the per-arm predicate-vs-accessor coherence
20952        // trio across all three payload arms so the gen-platform
20953        // IsVariant predicate and the substrate-lifted per-arm
20954        // accessor carry one shared answer to "is this the Store arm?".
20955        for variant in [
20956            WitTarget::Http {
20957                endpoint: "/charge",
20958            },
20959            WitTarget::PubSub {
20960                subject: "events.checkout.paid",
20961            },
20962            WitTarget::Store {
20963                slot: "checkout/$order",
20964            },
20965            WitTarget::Capability,
20966        ] {
20967            assert_eq!(
20968                variant.store_slot().is_some(),
20969                variant.is_store(),
20970                "WitTarget::{variant:?} store_slot().is_some() must \
20971                 equal is_store() — a drift would split the store-shape \
20972                 emit branch's arm-set gate from the substrate-derived \
20973                 shape-discrimination predicate on the same axis",
20974            );
20975        }
20976    }
20977
20978    #[test]
20979    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
20980        // Fail-before-pass-after cross-axis pin on the trio
20981        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
20982        // payload-carrying arm of [`WitTarget`], exactly one per-arm
20983        // accessor returns `Some(payload)` and the two peers return
20984        // `None`; and on the payload-less [`WitTarget::Capability`]
20985        // arm, all three return `None`. Guards the drift surface where
20986        // a future extension of one per-arm accessor's accept-set (e.g.
20987        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
20988        // that widened `http_endpoint` to cover both peers without
20989        // narrowing the peer `pubsub_subject` / `store_slot` accept-
20990        // sets to keep the partition mutually exclusive) landed without
20991        // threading through the peer per-arm accessors — the resulting
20992        // silent overlap would land the same edge's payload on two
20993        // downstream per-shape emit branches at once, or leak a
20994        // pub-sub subject through the store-slot channel, at renderer
20995        // emit time far from the substrate primitive's arm-widening
20996        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
20997        // 3-way pin on the payload-field-name axis — extended onto the
20998        // per-arm-accessor payload-projection axis so the substrate-
20999        // owned partition invariant is load-bearing at every per-arm
21000        // consumer's read site.
21001        let payload_variants = [
21002            (
21003                WitTarget::Http {
21004                    endpoint: "/charge",
21005                },
21006                "http",
21007            ),
21008            (
21009                WitTarget::PubSub {
21010                    subject: "events.checkout.paid",
21011                },
21012                "pubsub",
21013            ),
21014            (
21015                WitTarget::Store {
21016                    slot: "checkout/$order",
21017                },
21018                "store",
21019            ),
21020        ];
21021        for (variant, own_arm_label) in payload_variants {
21022            let own_arm_hit = match own_arm_label {
21023                "http" => variant.is_http(),
21024                "pubsub" => variant.is_pubsub(),
21025                "store" => variant.is_store(),
21026                other => panic!("unknown own-arm label {other:?}"),
21027            };
21028            let per_arm_results = [
21029                ("http_endpoint", variant.http_endpoint()),
21030                ("pubsub_subject", variant.pubsub_subject()),
21031                ("store_slot", variant.store_slot()),
21032            ];
21033            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
21034            assert_eq!(
21035                some_count, 1,
21036                "WitTarget::{variant:?} must land exactly one per-arm \
21037                 post-projection accessor's Some result — the trio \
21038                 (http_endpoint, pubsub_subject, store_slot) must \
21039                 partition the payload arm-set; got {per_arm_results:?}",
21040            );
21041            assert!(
21042                own_arm_hit,
21043                "WitTarget::{variant:?} own-arm gen-platform predicate \
21044                 must return true on its own arm — a partition failure \
21045                 upstream of this pin",
21046            );
21047            assert!(
21048                variant.payload().is_some(),
21049                "WitTarget::{variant:?} pan-arm payload() must return \
21050                 Some on every payload-carrying arm the trio partitions",
21051            );
21052        }
21053        // The payload-less Capability arm must return None on every
21054        // per-arm accessor — the partition's terminal-fallback shape.
21055        let cap = WitTarget::Capability;
21056        assert_eq!(cap.http_endpoint(), None);
21057        assert_eq!(cap.pubsub_subject(), None);
21058        assert_eq!(cap.store_slot(), None);
21059        assert_eq!(
21060            cap.payload(),
21061            None,
21062            "WitTarget::Capability pan-arm payload() must return None — \
21063             the trio's payload-less-arm coherence witness",
21064        );
21065    }
21066
21067    #[test]
21068    fn wit_target_field_names_are_pairwise_distinct() {
21069        // Distinctness pin: if any two of the three payload-field-name
21070        // scalars ever collapse (e.g. an accidental `endpoint` copy-
21071        // paste over the `subject` const), the [`WitContract::target`]
21072        // gate's diagnostic would point authors at the wrong field —
21073        // an "expected `:endpoint`" error on a pub-sub edge would
21074        // silently misroute the fix. Same cross-axis-distinctness
21075        // discipline as the peer M3 `:placement :estrategia` variant-
21076        // discriminator scalar-value pins (cc8f749) applied to the
21077        // payload-field-name axis.
21078        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
21079        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
21080        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
21081    }
21082
21083    #[test]
21084    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
21085        // Fail-before-pass-after pin: the graph-verb payload column's
21086        // per-arm `{field}={payload}` byte-string is derived through the
21087        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
21088        // payload-carrying arms, not through a hand-rolled per-arm match
21089        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
21090        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
21091        // inline. A future variant addition — the M4-and-later per-edge
21092        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
21093        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
21094        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
21095        // and both [`WitTarget::label`] (duplicate-`:contratos`
21096        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
21097        // payload column) pick up the new arm from the same dispatch.
21098        // Prior to this lift the graph verb open-coded the 4-arm match
21099        // in caixa-feira, so a variant addition would have to be threaded
21100        // through both projections in lockstep or the graph verb would
21101        // silently drop the new arm to `(capability-only)`.
21102        for variant in [
21103            WitTarget::Http {
21104                endpoint: "/charge",
21105            },
21106            WitTarget::PubSub {
21107                subject: "events.checkout.paid",
21108            },
21109            WitTarget::Store {
21110                slot: "checkout/$order",
21111            },
21112        ] {
21113            let (field, payload) = variant
21114                .payload_pair()
21115                .expect("payload arm must expose (field, payload)");
21116            assert_eq!(
21117                variant.graph_label(),
21118                format!("{field}={payload}"),
21119                "WitTarget::{variant:?} graph_label must route the \
21120                 `{{field}}={{payload}}` template through payload_pair — \
21121                 a regression to a hand-rolled per-arm match at the graph \
21122                 verb would silently disagree with a future variant \
21123                 addition landed only at payload_pair"
21124            );
21125        }
21126    }
21127
21128    #[test]
21129    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
21130        // Fail-before-pass-after pin on the payload-less arm: the graph
21131        // verb's `(capability-only)` byte-string routes through the
21132        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
21133        // [`WitTarget::Capability`] arm, not through an inline
21134        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
21135        // per-`:contratos` payload column. Peer of the sibling
21136        // [`wit_target_label_pins_per_variant_format`] Capability-arm
21137        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
21138        // extended here onto the third payload-less-arm consumer axis
21139        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
21140        // axis and the wrong-target diagnostic axis).
21141        assert_eq!(
21142            WitTarget::Capability.graph_label(),
21143            WitTarget::CAPABILITY_GRAPH_LABEL,
21144        );
21145        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
21146    }
21147
21148    #[test]
21149    fn wit_target_capability_graph_label_distinct_from_capability_label() {
21150        // Cross-consumer-axis distinctness pin: the graph-verb
21151        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
21152        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
21153        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
21154        // payload)`) surface the payload-less arm on two distinct
21155        // consumer axes; a collapse (an accidental rebrand that lands
21156        // one spelling on both consts, a copy-paste that unifies them
21157        // "for consistency") would silently merge the two byte-strings
21158        // and lose the vocabulary distinction the graph verb's
21159        // compact-column form and the diagnostic's descriptive-clause
21160        // form each carry on purpose. Peer of the sibling 4-way
21161        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
21162        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
21163        // extended here onto the cross-consumer-axis distinctness of the
21164        // two payload-less-arm consts.
21165        assert_ne!(
21166            WitTarget::CAPABILITY_GRAPH_LABEL,
21167            WitTarget::CAPABILITY_LABEL,
21168            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
21169             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
21170             diagnostic) must remain distinct — a collapse would silently \
21171             merge two consumer axes onto one spelling"
21172        );
21173    }
21174
21175    #[test]
21176    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
21177        // 4-way distinctness pin extending the sibling
21178        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
21179        // (which covers only the HTTP / PubSub / Store payload arms)
21180        // onto the fourth scalar the shared
21181        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
21182        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
21183        // (`"none"`), the payload-less Capability-arm rejection scalar.
21184        //
21185        // All four [`WitTarget::HTTP_FIELD_NAME`] /
21186        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
21187        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
21188        // dispatch surface [`WitContract::target`] writes onto the
21189        // `ContratoWrongTarget::expected` field — the same `&'static
21190        // str` axis authors read as "this WIT world's shape admits
21191        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
21192        // downstream consumers rely on: an `expected: "endpoint"`
21193        // diagnostic on a Capability-shaped edge tells the author to
21194        // add a `:endpoint "…"` slot to a WIT world that admits none,
21195        // silently misrouting the fix. Until this pin landed the three
21196        // payload-arm consts were distinctness-guarded by the sibling
21197        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
21198        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
21199        // author-facing vocabulary shift from `"none"` to `"endpoint"`
21200        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
21201        // into per-shape peers) would have silently landed one
21202        // Capability-arm rejection on a payload-arm's `expected:` byte-
21203        // string and desynchronized the diagnostic from the author's
21204        // typed shape.
21205        //
21206        // Same 4-way pairwise-distinctness pin discipline as the peer
21207        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
21208        // (cc8f749) applies on the sibling M3 closed-set typed-enum
21209        // scalar-value dispatch axis; extends the pin trajectory the
21210        // sibling `wit_target_field_names_are_pairwise_distinct`
21211        // 3-way pin opened to cover the last unguarded corner on the
21212        // `ContratoWrongTarget::expected` scalar-value axis.
21213        //
21214        // Fail-before-pass-after locally verified by mutating
21215        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
21216        // — this pin fires as expected; restoring passes.
21217        let all = [
21218            WitTarget::HTTP_FIELD_NAME,
21219            WitTarget::PUBSUB_FIELD_NAME,
21220            WitTarget::STORE_FIELD_NAME,
21221            WitTarget::CAPABILITY_EXPECTED,
21222        ];
21223        for (i, a) in all.iter().enumerate() {
21224            for (j, b) in all.iter().enumerate() {
21225                if i != j {
21226                    assert_ne!(
21227                        a, b,
21228                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
21229                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
21230                         pairwise distinct — got duplicate {a:?} at indices \
21231                         {i} and {j}; all four scalars thread through the \
21232                         shared `AplicacaoError::ContratoWrongTarget::expected` \
21233                         &'static str axis, so a collapse silently misdirects \
21234                         the diagnostic on which typed shape the WIT world admits",
21235                    );
21236                }
21237            }
21238        }
21239    }
21240
21241    #[test]
21242    fn wit_target_is_variant_predicates_partition_the_arm_set() {
21243        // Fail-before-pass-after pin on the
21244        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
21245        // each of the four variants exactly one of the generated
21246        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
21247        // predicates returns `true` and the other three return
21248        // `false`. Prior to this derive the only production
21249        // arm-discriminator on [`WitTarget`] — the sync-cycle
21250        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
21251        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
21252        // the variant that expressed no compile-time link back to
21253        // the closed-set typed dispatch a future fifth
21254        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
21255        // split of [`WitTarget::PubSub`] into shape-specific peers,
21256        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
21257        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
21258        // to thread through in lockstep or the DFS exclusion would
21259        // silently disagree with the peer diagnostic templates on
21260        // which arms carry sync-versus-async semantics. Peer of the
21261        // sibling [`crate::CaixaKind`] (f5bba80),
21262        // [`PlacementStrategy`] (766ec63),
21263        // [`crate::supervisor::RestartStrategy`],
21264        // [`crate::supervisor::RestartPolicy`], and
21265        // [`crate::upgrade::UpgradeInstruction`] (915a934)
21266        // `IsVariant` derives on the sibling closed-set typed-enum
21267        // discriminator axes — extends the same one-typed-dispatch-
21268        // per-variant discipline onto the last unlifted closed-set
21269        // typed-enum discriminator on the caixa surface (the M3
21270        // mesh-slot per-`:contratos` target-arm axis), closing the
21271        // arm-discriminator convergence trajectory across every
21272        // closed-set typed enum in caixa-core.
21273        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
21274            (
21275                WitTarget::Http { endpoint: "/x" },
21276                [true, false, false, false],
21277            ),
21278            (
21279                WitTarget::PubSub {
21280                    subject: "events.x",
21281                },
21282                [false, true, false, false],
21283            ),
21284            (
21285                WitTarget::Store { slot: "kv/x" },
21286                [false, false, true, false],
21287            ),
21288            (WitTarget::Capability, [false, false, false, true]),
21289        ];
21290        for (variant, expected) in rows {
21291            let observed = [
21292                variant.is_http(),
21293                variant.is_pubsub(),
21294                variant.is_store(),
21295                variant.is_capability(),
21296            ];
21297            assert_eq!(
21298                observed, expected,
21299                "WitTarget::{variant:?} is_* predicates must partition \
21300                 the arm set (http, pubsub, store, capability); got {observed:?}"
21301            );
21302        }
21303    }
21304
21305    #[test]
21306    fn wit_target_is_variant_predicates_are_const_fn() {
21307        // The [`gen_platform::IsVariant`] derive emits `const fn`
21308        // predicates on the peer [`crate::CaixaKind`] +
21309        // [`crate::upgrade::UpgradeInstruction`] +
21310        // [`crate::supervisor::RestartStrategy`] +
21311        // [`crate::supervisor::RestartPolicy`] +
21312        // [`PlacementStrategy`] closed-set typed enums — pin the
21313        // same posture on [`WitTarget`] so a future accidental
21314        // downgrade to non-`const` (an added runtime helper reachable
21315        // only from a non-`const` context, a manual hand-rolled
21316        // `impl` that shadows the derive-generated method) trips at
21317        // caixa-core build time rather than surfacing as a downstream
21318        // `const`-context regression far from the derive declaration.
21319        //
21320        // Unlike the peer unit-variant enums (`CaixaKind` /
21321        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
21322        // whose `const` constructors need no arguments, the three
21323        // payload-carrying [`WitTarget`] arms are const-constructed
21324        // through `&'static str` payloads — the same `'static`
21325        // lifetime the closed-set typed enum's four-arm partition
21326        // pin above already threads through.
21327        //
21328        // The pin lives inside a `const { assert!(..) }` block so the
21329        // compiler enforces both halves (arm predicate is `const`-
21330        // callable AND returns `true` for the matching arm) at
21331        // caixa-core compile time — peer to the sibling
21332        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
21333        // typed enum arm-predicate const-callability axis.
21334        const {
21335            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
21336            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
21337            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
21338            assert!(WitTarget::Capability.is_capability());
21339        }
21340    }
21341
21342    #[test]
21343    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
21344        // Consumer-side pin on the sole production converge site:
21345        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
21346        // edges from the synchronous-subgraph DFS via the lifted
21347        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
21348        // predicate (rebound from the prior raw
21349        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
21350        // variant). Byte-equivalent today (`is_pubsub` is the
21351        // derive-generated `matches!(self, Self::PubSub { .. })` by
21352        // construction, the `#[is_variant(name = "pubsub")]` override
21353        // aliasing the auto-derived `is_pub_sub` back to the sibling
21354        // [`WitContract::is_pubsub`] name); pin the behavior so a
21355        // future accidental drift (a rebind onto a peer arm
21356        // predicate, a manual hand-rolled `impl` that shadows the
21357        // derive-generated method with different semantics, a peer
21358        // arm rename that shifts which variant carries sync-versus-
21359        // async semantics) trips at caixa-core test time rather than
21360        // at some downstream operator's runtime dispatch far from the
21361        // rebind commit.
21362        //
21363        // The fixture constructs a two-Servico Aplicacao with one
21364        // pub-sub edge that would close a sync-cycle if the DFS did
21365        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
21366        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
21367        // edge, which is not a cycle. A regression in the converge
21368        // (a rebind that reads the pub-sub arm as sync) would report
21369        // `AplicacaoError::ContratoCycle`.
21370        let s = AplicacaoSpec {
21371            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
21372            contratos: vec![
21373                // Pub-sub edge: DFS must skip via is_pubsub().
21374                WitContract {
21375                    de: "a".into(),
21376                    para: "b".into(),
21377                    wit: "nats:pub-sub".into(),
21378                    endpoint: None,
21379                    subject: Some("events.x".into()),
21380                    slot: None,
21381                },
21382                // HTTP edge: DFS must include.
21383                WitContract {
21384                    de: "b".into(),
21385                    para: "a".into(),
21386                    wit: "wasi:http/proxy".into(),
21387                    endpoint: Some("/x".into()),
21388                    subject: None,
21389                    slot: None,
21390                },
21391            ],
21392            politicas: MeshPolicy::default(),
21393            placement: Placement {
21394                estrategia: PlacementStrategy::Replicated,
21395                clusters: vec!["rio".into()],
21396                affinity: None,
21397                shard_key: None,
21398            },
21399            entrada: None,
21400        };
21401        s.validate()
21402            .expect("pub-sub edge must be excluded from sync-cycle DFS");
21403    }
21404
21405    #[test]
21406    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
21407        // Consumer-side pin: the same three peer consts thread through
21408        // both the [`WitTarget::label`] template (leading-`:` keyword
21409        // prefix in the duplicate-`:contratos` diagnostic) and the
21410        // [`WitContract::target`] gate's [`AplicacaoError::
21411        // ContratoMissingTarget`] `expected:` scalar (the field the
21412        // author needs to add). Pin both routes at once so a future
21413        // refactor can't accidentally split them onto separate string
21414        // literals — the "one place, everywhere reaches for it"
21415        // invariant the peer const set carries.
21416        let http_label = WitTarget::Http { endpoint: "/x" }.label();
21417        assert!(
21418            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
21419            "label must lead with :{} keyword (got {http_label:?})",
21420            WitTarget::HTTP_FIELD_NAME,
21421        );
21422
21423        let mut s = three_member_spec();
21424        s.contratos.push(WitContract {
21425            de: "cart".into(),
21426            para: "catalog".into(),
21427            wit: "kafka:topic".into(),
21428            endpoint: None,
21429            subject: None,
21430            slot: None,
21431        });
21432        match s.validate().unwrap_err() {
21433            AplicacaoError::ContratoMissingTarget { expected, .. } => {
21434                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
21435            }
21436            other => panic!("expected ContratoMissingTarget, got {other:?}"),
21437        }
21438    }
21439
21440    #[test]
21441    fn duplicate_pubsub_diagnostic_names_offending_subject() {
21442        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
21443        // on the pub-sub target axis: the duplicate-edge diagnostic
21444        // must name the `:subject` payload verbatim (not just the
21445        // `(de, para, wit)` triple). Prior to lifting the label onto
21446        // [`WitTarget::label`] the diagnostic derived the label from
21447        // raw [`WitContract`] `Option<String>` probes — a future
21448        // `WitTarget` variant addition (M4 per-edge WIT registry)
21449        // would silently fall through to the `Capability` "no
21450        // payload" default without a compiler warning. Pinning the
21451        // pub-sub arm's format closes the second of three
21452        // payload-carrying `WitTarget` arms this diagnostic threads
21453        // through.
21454        let mut s = three_member_spec();
21455        let pubsub = WitContract {
21456            de: "payment".into(),
21457            para: "cart".into(),
21458            wit: "nats:pub-sub".into(),
21459            endpoint: None,
21460            subject: Some("events.checkout.paid".into()),
21461            slot: None,
21462        };
21463        s.contratos.push(pubsub.clone());
21464        s.contratos.push(pubsub);
21465        let err = s.validate().unwrap_err();
21466        let msg = format!("{err}");
21467        assert!(
21468            msg.contains(":subject \"events.checkout.paid\""),
21469            "duplicate-pubsub diagnostic must name the offending \
21470             :subject payload (got: {msg:?})"
21471        );
21472    }
21473
21474    #[test]
21475    fn duplicate_store_diagnostic_names_offending_slot() {
21476        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
21477        // key-value target axis: the diagnostic must name the `:slot`
21478        // payload verbatim. Third of three payload-carrying
21479        // `WitTarget` arms this diagnostic threads through, closing
21480        // the per-arm label pin trilogy (`Http` — 6841,
21481        // `PubSub` + `Store` — this test + peer above).
21482        let mut s = three_member_spec();
21483        let store = WitContract {
21484            de: "cart".into(),
21485            para: "payment".into(),
21486            wit: "wasi:keyvalue/store".into(),
21487            endpoint: None,
21488            subject: None,
21489            slot: Some("checkout/$orderId".into()),
21490        };
21491        s.contratos
21492            .retain(|c| !(c.de == "cart" && c.para == "payment"));
21493        s.contratos.push(store.clone());
21494        s.contratos.push(store);
21495        let err = s.validate().unwrap_err();
21496        let msg = format!("{err}");
21497        assert!(
21498            msg.contains(":slot \"checkout/$orderId\""),
21499            "duplicate-store diagnostic must name the offending :slot \
21500             payload (got: {msg:?})"
21501        );
21502    }
21503
21504    #[test]
21505    fn rejects_entrada_path_without_leading_slash() {
21506        let mut s = three_member_spec();
21507        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
21508        let err = s.validate().unwrap_err();
21509        assert!(
21510            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
21511            "got {err:?}"
21512        );
21513    }
21514
21515    #[test]
21516    fn rejects_empty_entrada_path() {
21517        let mut s = three_member_spec();
21518        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
21519        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
21520    }
21521
21522    #[test]
21523    fn rejects_duplicate_entrada_paths() {
21524        let mut s = three_member_spec();
21525        s.entrada.as_mut().unwrap().paths = vec![
21526            "/api/cart".into(),
21527            "/api/products".into(),
21528            "/api/cart".into(),
21529        ];
21530        let err = s.validate().unwrap_err();
21531        assert!(
21532            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
21533            "got {err:?}"
21534        );
21535    }
21536
21537    #[test]
21538    fn rejects_zero_entrada_port() {
21539        let mut s = three_member_spec();
21540        s.entrada.as_mut().unwrap().port = 0;
21541        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
21542    }
21543
21544    // ── :entrada :paths value-shape gate ─────────────────────────────
21545    //
21546    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
21547    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
21548    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
21549    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
21550    // time now becomes a caixa-build-time `EntradaPathInvalid` with
21551    // the offending `:paths` entry named verbatim.
21552
21553    #[test]
21554    fn rejects_entrada_path_with_query() {
21555        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
21556        // silently passed validate and the Gateway API webhook
21557        // rejected it at apply time with no source citation.
21558        let mut s = three_member_spec();
21559        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
21560        let err = s.validate().unwrap_err();
21561        assert!(
21562            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21563                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
21564            "got {err:?}"
21565        );
21566    }
21567
21568    #[test]
21569    fn rejects_entrada_path_with_fragment() {
21570        let mut s = three_member_spec();
21571        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
21572        let err = s.validate().unwrap_err();
21573        assert!(
21574            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21575                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
21576            "got {err:?}"
21577        );
21578    }
21579
21580    #[test]
21581    fn rejects_entrada_path_with_space() {
21582        let mut s = three_member_spec();
21583        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
21584        let err = s.validate().unwrap_err();
21585        assert!(
21586            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21587                if path == "/api/my cart" && reason.contains("whitespace")),
21588            "got {err:?}"
21589        );
21590    }
21591
21592    #[test]
21593    fn rejects_entrada_path_with_tab() {
21594        let mut s = three_member_spec();
21595        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
21596        let err = s.validate().unwrap_err();
21597        assert!(
21598            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21599                if path == "/api/\tcart" && reason.contains("whitespace")),
21600            "got {err:?}"
21601        );
21602    }
21603
21604    #[test]
21605    fn rejects_entrada_path_with_control_char() {
21606        // 0x01 (SOH) — a non-whitespace control char surfaces the
21607        // distinct "control character" reason arm, separate from
21608        // the whitespace arm. Pinned so a future refactor that
21609        // collapses the two arms can't accidentally drop the more
21610        // self-locating diagnostic.
21611        let mut s = three_member_spec();
21612        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
21613        let err = s.validate().unwrap_err();
21614        assert!(
21615            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21616                if path == "/api/\x01cart" && reason.contains("control character")),
21617            "got {err:?}"
21618        );
21619    }
21620
21621    #[test]
21622    fn rejects_entrada_path_with_non_ascii() {
21623        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
21624        // unreserved-set rule rejects. The Gateway API webhook
21625        // rejects literal non-ASCII bytes; percent-encoding is the
21626        // only way to author non-ASCII in a path.
21627        let mut s = three_member_spec();
21628        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
21629        let err = s.validate().unwrap_err();
21630        assert!(
21631            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21632                if path == "/api/café" && reason.contains("non-ASCII")),
21633            "got {err:?}"
21634        );
21635    }
21636
21637    #[test]
21638    fn rejects_entrada_path_with_consecutive_slashes() {
21639        let mut s = three_member_spec();
21640        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
21641        let err = s.validate().unwrap_err();
21642        assert!(
21643            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21644                if path == "/api//cart" && reason.contains("consecutive `/`")),
21645            "got {err:?}"
21646        );
21647    }
21648
21649    #[test]
21650    fn rejects_entrada_path_with_dot_segment() {
21651        let mut s = three_member_spec();
21652        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
21653        let err = s.validate().unwrap_err();
21654        assert!(
21655            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21656                if path == "/api/./cart" && reason.contains("`.` segment")),
21657            "got {err:?}"
21658        );
21659    }
21660
21661    #[test]
21662    fn rejects_entrada_path_with_trailing_dot_segment() {
21663        // The bare `/.` and the trailing `/foo/.` are both rejected
21664        // by the Gateway API webhook; pinned separately so a future
21665        // narrowing that catches only the inner form surfaces here.
21666        let mut s = three_member_spec();
21667        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
21668        let err = s.validate().unwrap_err();
21669        assert!(
21670            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21671                if path == "/api/." && reason.contains("`.` segment")),
21672            "got {err:?}"
21673        );
21674    }
21675
21676    #[test]
21677    fn rejects_entrada_path_with_parent_segment() {
21678        let mut s = three_member_spec();
21679        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
21680        let err = s.validate().unwrap_err();
21681        assert!(
21682            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21683                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
21684            "got {err:?}"
21685        );
21686    }
21687
21688    #[test]
21689    fn rejects_entrada_path_with_trailing_parent_segment() {
21690        // Trailing `/..` — symmetric arm of the parent-segment rule,
21691        // pinned separately so a future relaxation that only checks
21692        // the inner form (`/../`) surfaces here.
21693        let mut s = three_member_spec();
21694        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
21695        let err = s.validate().unwrap_err();
21696        assert!(
21697            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21698                if path == "/api/.." && reason.contains("`..` parent-segment")),
21699            "got {err:?}"
21700        );
21701    }
21702
21703    #[test]
21704    fn rejects_entrada_path_too_long() {
21705        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
21706        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
21707        // ASCII-alphanumeric body so only the length rule fires.
21708        let mut s = three_member_spec();
21709        let big = format!("/api/{}", "a".repeat(1020));
21710        assert_eq!(big.len(), 1025);
21711        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
21712        let err = s.validate().unwrap_err();
21713        assert!(
21714            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21715                if path == &big && reason.contains("max length of 1024")),
21716            "got {err:?}"
21717        );
21718    }
21719
21720    #[test]
21721    fn entrada_path_max_length_validates() {
21722        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
21723        // maxLength cap. Boundary pin: drift in the cap surfaces here
21724        // and at `rejects_entrada_path_too_long` simultaneously.
21725        let mut s = three_member_spec();
21726        let big = format!("/api/{}", "a".repeat(1019));
21727        assert_eq!(big.len(), 1024);
21728        s.entrada.as_mut().unwrap().paths = vec![big];
21729        s.validate().unwrap();
21730    }
21731
21732    #[test]
21733    fn entrada_accepts_canonical_paths() {
21734        // Positive-control sweep — every form the Gateway API
21735        // apiserver accepts must round-trip through validate. Covers
21736        // the root catch-all, plain paths, dot-prefixed segments
21737        // (hidden-file-style, distinct from `.` and `..` segments
21738        // which are rejected), digit-bearing segments, the canonical
21739        // route-template `:param` form (`:` is RFC 3986 reserved-set
21740        // valid in paths), trailing-slash form, percent-encoded
21741        // segments, and an interior `..` *substring* (`/foo..bar` is
21742        // not the `..` segment and is allowed).
21743        for path in [
21744            "/",
21745            "/api/cart",
21746            "/healthz",
21747            "/api/.config",
21748            "/v1/products",
21749            "/products/:id",
21750            "/api/cart/",
21751            "/api/caf%C3%A9",
21752            "/foo..bar",
21753            "/...",
21754        ] {
21755            let mut s = three_member_spec();
21756            s.entrada.as_mut().unwrap().paths = vec![path.into()];
21757            s.validate()
21758                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
21759        }
21760    }
21761
21762    #[test]
21763    fn entrada_path_empty_takes_precedence_over_invalid() {
21764        // Ordering pin: `EntradaPathEmpty` is the more self-locating
21765        // diagnostic on `""` and must lead — `validate_entrada_path`
21766        // is only reached after the empty-check fires at the call
21767        // site. (The predicate itself defends against direct
21768        // invocation by returning the same error on `""`.)
21769        let mut s = three_member_spec();
21770        s.entrada.as_mut().unwrap().paths = vec![String::new()];
21771        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
21772    }
21773
21774    #[test]
21775    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
21776        // Ordering pin: a path without a leading `/` surfaces the
21777        // narrower `EntradaPathNotAbsolute` diagnostic first; the
21778        // value-shape gate is only consulted on paths that already
21779        // satisfy the absolute-prefix invariant.
21780        let mut s = three_member_spec();
21781        // `bad path` would fire the whitespace rule under the
21782        // value-shape gate, but missing-leading-`/` is the more
21783        // self-locating diagnostic.
21784        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
21785        let err = s.validate().unwrap_err();
21786        assert!(
21787            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
21788            "got {err:?}"
21789        );
21790    }
21791
21792    #[test]
21793    fn entrada_path_invalid_fires_before_duplicate_check() {
21794        // Ordering pin: a malformed path on the *first* entry of a
21795        // would-be duplicate pair fires the value-shape gate before
21796        // the duplicate gate, mirroring the
21797        // `placement_cluster_invalid_fires_before_duplicate_check`
21798        // (6cbb900) pattern on the peer axis.
21799        let mut s = three_member_spec();
21800        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
21801        let err = s.validate().unwrap_err();
21802        assert!(
21803            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
21804            "got {err:?}"
21805        );
21806    }
21807
21808    #[test]
21809    fn entrada_path_diagnostic_carries_offending_path() {
21810        // Diagnostic-shape pin — the offending path + a non-empty
21811        // reason flow through verbatim so the author can grep their
21812        // caixa.lisp for `:paths` and fix it in one edit. Same shape
21813        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
21814        let mut s = three_member_spec();
21815        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
21816        let err = s.validate().unwrap_err();
21817        match err {
21818            AplicacaoError::EntradaPathInvalid { path, reason } => {
21819                assert_eq!(path, "/api?q=1");
21820                assert!(!reason.is_empty(), "reason field must be non-empty");
21821            }
21822            other => panic!("expected EntradaPathInvalid, got {other:?}"),
21823        }
21824    }
21825
21826    #[test]
21827    fn rejects_entrada_path_with_curly_brace_template_form() {
21828        // Per-axis pin on the shared `is_gateway_api_http_path`
21829        // reserved-byte arm: the canonical "I wrote an OpenAPI
21830        // path-template `{id}` instead of the Gateway API `:id` form"
21831        // footgun the K8s apiserver would otherwise catch at admission
21832        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
21833        // landing site, far from the caixa.lisp. Surfaces as
21834        // `EntradaPathInvalid` carrying the offending path verbatim
21835        // plus the canonical `%7B`/`%7D` percent-encoding remediation
21836        // — the substrate-side `gateway_api_http_path_rejects_every_
21837        // reserved_printable_ascii_byte` predicate-level sweep pins the
21838        // full eleven-byte set; this per-axis pin confirms the
21839        // diagnostic flows through to the `EntradaPathInvalid` variant.
21840        let mut s = three_member_spec();
21841        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
21842        let err = s.validate().unwrap_err();
21843        assert!(
21844            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
21845                if path == "/api/cart/{id}"
21846                    && reason.contains("reserved character")
21847                    && reason.contains("'{'")
21848                    && reason.contains("%7B")),
21849            "got {err:?}"
21850        );
21851    }
21852
21853    #[test]
21854    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
21855        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
21856        // template_form` on the sibling `:contratos :endpoint` axis.
21857        // Same shared `is_gateway_api_http_path` reserved-byte arm
21858        // fires through `ContratoEndpointInvalid`, with the offending
21859        // endpoint + `:de` + `:para` + reason flowing through verbatim.
21860        // Pins that the lifted predicate's tightening lands on both
21861        // caller axes simultaneously — one source of truth for the
21862        // Gateway API HTTPPathMatch.value accepted set.
21863        let err = contrato_endpoint_err("/api/cart/{id}");
21864        assert!(
21865            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
21866                if endpoint == "/api/cart/{id}"
21867                    && reason.contains("reserved character")
21868                    && reason.contains("'{'")
21869                    && reason.contains("%7B")),
21870            "got {err:?}"
21871        );
21872    }
21873
21874    // ── :entrada :host value-shape gate ──────────────────────────────
21875    //
21876    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
21877    // the sibling `:host` axis. Every authoring footgun the K8s
21878    // Gateway API v1 apiserver would catch at admission time becomes
21879    // a caixa-build-time `EntradaHostInvalid` with the offending
21880    // `:host` named verbatim. Same diagnostic shape as
21881    // `MembroVersaoInvalid` (9888b13).
21882
21883    #[test]
21884    fn rejects_entrada_host_with_scheme() {
21885        // Fail-before-pass-after pin — pre-gate codebases silently
21886        // accepted `https://…` and the apiserver rejected it at apply
21887        // time with no source citation.
21888        let mut s = three_member_spec();
21889        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
21890        let err = s.validate().unwrap_err();
21891        assert!(
21892            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
21893                if host == "https://checkout.quero.cloud"),
21894            "got {err:?}"
21895        );
21896    }
21897
21898    #[test]
21899    fn rejects_entrada_host_with_port() {
21900        // The `:8080` port suffix is the canonical "I forgot the port
21901        // belongs in `:entrada :port`" footgun. The top-level `:` arm
21902        // (introduced after the per-label loop-only impl silently
21903        // surfaced a deep "label \"cloud:8080\" contains invalid
21904        // character ':'" leak) names the canonical fix verbatim — the
21905        // `:entrada :port` slot.
21906        let mut s = three_member_spec();
21907        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
21908        let err = s.validate().unwrap_err();
21909        assert!(
21910            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
21911                if host == "checkout.quero.cloud:8080"
21912                && reason.contains(":entrada :port")),
21913            "got {err:?}"
21914        );
21915    }
21916
21917    #[test]
21918    fn rejects_entrada_host_with_trailing_colon() {
21919        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
21920        // edit) — the per-label loop would land it as a deep
21921        // "label \"com:\" must start and end with an alphanumeric"
21922        // / "contains invalid character ':'" leak. The top-level
21923        // `:` arm pre-empts with the canonical `:port` slot
21924        // diagnostic.
21925        let mut s = three_member_spec();
21926        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
21927        let err = s.validate().unwrap_err();
21928        assert!(
21929            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
21930                if host == "checkout.quero.cloud:"
21931                && reason.contains(":entrada :port")),
21932            "got {err:?}"
21933        );
21934    }
21935
21936    #[test]
21937    fn rejects_entrada_host_unbracketed_ipv6_literal() {
21938        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
21939        // literals across the board (peer with `rejects_entrada_host_
21940        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
21941        // Before this top-level `:` arm landed the per-label loop
21942        // surfaced a single-label byte-class diagnostic that named the
21943        // `:` byte but not the IP-literal prohibition. The top-level
21944        // `:` arm names both the `:port` slot and the IP-literal
21945        // prohibition verbatim, so an author whose `:host "2001:..."`
21946        // value lands here gets a self-locating fix either way.
21947        let mut s = three_member_spec();
21948        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
21949        let err = s.validate().unwrap_err();
21950        assert!(
21951            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
21952                if host == "2001:db8::1"
21953                && reason.contains("IPv6")),
21954            "got {err:?}"
21955        );
21956    }
21957
21958    #[test]
21959    fn rejects_entrada_host_wildcard_with_port() {
21960        // Wildcard host with port suffix — the `*.` strip and the
21961        // per-label loop on `["foo", "quero", "cloud:8080"]` would
21962        // surface the deep byte-class leak. The top-level `:` arm sits
21963        // upstream of the `*.` strip, so it names the canonical `:port`
21964        // fix verbatim regardless of whether the host is wildcard-led.
21965        let mut s = three_member_spec();
21966        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
21967        let err = s.validate().unwrap_err();
21968        assert!(
21969            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
21970                if host == "*.quero.cloud:8080"
21971                && reason.contains(":entrada :port")),
21972            "got {err:?}"
21973        );
21974    }
21975
21976    #[test]
21977    fn rejects_entrada_host_with_path() {
21978        let mut s = three_member_spec();
21979        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
21980        let err = s.validate().unwrap_err();
21981        assert!(
21982            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
21983                if host == "checkout.quero.cloud/api"),
21984            "got {err:?}"
21985        );
21986    }
21987
21988    #[test]
21989    fn rejects_entrada_host_with_uppercase() {
21990        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
21991        // rejected, not silently lower-cased.
21992        let mut s = three_member_spec();
21993        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
21994        let err = s.validate().unwrap_err();
21995        assert!(
21996            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
21997                if reason.contains("uppercase")),
21998            "got {err:?}"
21999        );
22000    }
22001
22002    #[test]
22003    fn rejects_entrada_host_with_underscore() {
22004        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
22005        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
22006        let mut s = three_member_spec();
22007        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
22008        let err = s.validate().unwrap_err();
22009        assert!(
22010            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22011                if reason.contains('_')),
22012            "got {err:?}"
22013        );
22014    }
22015
22016    #[test]
22017    fn rejects_entrada_host_ipv4_literal() {
22018        // Gateway API v1 explicitly forbids IP literals as Hostnames.
22019        let mut s = three_member_spec();
22020        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
22021        let err = s.validate().unwrap_err();
22022        assert!(
22023            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22024                if reason.contains("IPv4")),
22025            "got {err:?}"
22026        );
22027    }
22028
22029    #[test]
22030    fn rejects_entrada_host_with_trailing_dot() {
22031        // The Gateway API regex anchors at end-of-string with no
22032        // trailing `.` allowance — the FQDN root-dot form is rejected.
22033        let mut s = three_member_spec();
22034        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
22035        let err = s.validate().unwrap_err();
22036        assert!(
22037            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
22038                if host == "checkout.quero.cloud."),
22039            "got {err:?}"
22040        );
22041    }
22042
22043    #[test]
22044    fn rejects_entrada_host_with_leading_dot() {
22045        let mut s = three_member_spec();
22046        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
22047        let err = s.validate().unwrap_err();
22048        assert!(
22049            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22050                if reason.contains("empty label")),
22051            "got {err:?}"
22052        );
22053    }
22054
22055    #[test]
22056    fn rejects_entrada_host_with_consecutive_dots() {
22057        let mut s = three_member_spec();
22058        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
22059        let err = s.validate().unwrap_err();
22060        assert!(
22061            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22062                if reason.contains("empty label")),
22063            "got {err:?}"
22064        );
22065    }
22066
22067    #[test]
22068    fn rejects_entrada_host_with_leading_hyphen_label() {
22069        let mut s = three_member_spec();
22070        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
22071        let err = s.validate().unwrap_err();
22072        assert!(
22073            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22074                if reason.contains("alphanumeric")),
22075            "got {err:?}"
22076        );
22077    }
22078
22079    #[test]
22080    fn rejects_entrada_host_with_trailing_hyphen_label() {
22081        let mut s = three_member_spec();
22082        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
22083        let err = s.validate().unwrap_err();
22084        assert!(
22085            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22086                if reason.contains("alphanumeric")),
22087            "got {err:?}"
22088        );
22089    }
22090
22091    #[test]
22092    fn rejects_entrada_host_with_inner_wildcard() {
22093        // Gateway API allows `*` only as the first label (`*.foo`);
22094        // any inner or trailing `*` is rejected.
22095        let mut s = three_member_spec();
22096        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
22097        let err = s.validate().unwrap_err();
22098        assert!(
22099            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22100                if reason.contains("wildcard")),
22101            "got {err:?}"
22102        );
22103    }
22104
22105    #[test]
22106    fn rejects_entrada_host_bare_wildcard() {
22107        // `*.` with no domain is meaningless; Gateway API rejects it.
22108        let mut s = three_member_spec();
22109        s.entrada.as_mut().unwrap().host = "*.".into();
22110        let err = s.validate().unwrap_err();
22111        assert!(
22112            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22113                if reason.contains("wildcard")),
22114            "got {err:?}"
22115        );
22116    }
22117
22118    #[test]
22119    fn rejects_entrada_host_with_whitespace() {
22120        let mut s = three_member_spec();
22121        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
22122        let err = s.validate().unwrap_err();
22123        assert!(
22124            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22125                if reason.contains("whitespace")),
22126            "got {err:?}"
22127        );
22128    }
22129
22130    #[test]
22131    fn rejects_entrada_host_space_names_offending_byte() {
22132        // Embedded space in the `:entrada :host` axis surfaces the
22133        // byte-naming diagnostic through the lifted
22134        // `find_ascii_whitespace_byte` predicate. Peer with the
22135        // sibling `parse_rejects_leading_whitespace` pins on
22136        // `supervisor::duration_codec` (a7ae622) — same "the
22137        // diagnostic carries the offending byte's `0x{b:02x}` shape"
22138        // discipline extended from the shared duration codec to the
22139        // Gateway API v1 Hostname axis.
22140        let mut s = three_member_spec();
22141        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
22142        let err = s.validate().unwrap_err();
22143        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
22144            panic!("expected EntradaHostInvalid, got {err:?}");
22145        };
22146        assert!(
22147            reason.contains("ASCII whitespace byte"),
22148            "expected byte-naming diagnostic, got {reason:?}"
22149        );
22150        assert!(
22151            reason.contains("0x20"),
22152            "expected offending space byte 0x20, got {reason:?}"
22153        );
22154    }
22155
22156    #[test]
22157    fn rejects_entrada_host_tab_names_offending_byte() {
22158        // Embedded tab byte in the `:entrada :host` axis — the
22159        // canonical paste-from-YAML-block-scalar / paste-from-
22160        // indented-doc footgun. Pins that the lifted predicate covers
22161        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
22162        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
22163        // not just the leading-space case the pre-lift `.bytes().any`
22164        // arm's opaque "must not contain whitespace" reason already
22165        // covered. Peer with `parse_rejects_tab_byte` on
22166        // `supervisor::duration_codec` (a7ae622).
22167        let mut s = three_member_spec();
22168        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
22169        let err = s.validate().unwrap_err();
22170        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
22171            panic!("expected EntradaHostInvalid, got {err:?}");
22172        };
22173        assert!(
22174            reason.contains("ASCII whitespace byte"),
22175            "expected byte-naming diagnostic, got {reason:?}"
22176        );
22177        assert!(
22178            reason.contains("0x09"),
22179            "expected offending tab byte 0x09, got {reason:?}"
22180        );
22181    }
22182
22183    #[test]
22184    fn rejects_entrada_host_lf_names_offending_byte() {
22185        // Embedded LF byte in the `:entrada :host` axis — the
22186        // canonical paste-from-shell-heredoc / paste-from-multiline-
22187        // doc footgun the caixa-mesh YAML emitter would silently
22188        // reinterpret at the Gateway API v1 HTTPRoute admission
22189        // layer (an embedded LF byte in a YAML plain scalar either
22190        // truncates the value at the emitter or crashes the parser
22191        // on the k8s-apiserver side). Pins the third representative
22192        // of the full ASCII-whitespace set through the shared
22193        // predicate.
22194        let mut s = three_member_spec();
22195        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
22196        let err = s.validate().unwrap_err();
22197        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
22198            panic!("expected EntradaHostInvalid, got {err:?}");
22199        };
22200        assert!(
22201            reason.contains("ASCII whitespace byte"),
22202            "expected byte-naming diagnostic, got {reason:?}"
22203        );
22204        assert!(
22205            reason.contains("0x0a"),
22206            "expected offending LF byte 0x0a, got {reason:?}"
22207        );
22208    }
22209
22210    #[test]
22211    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
22212        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
22213        // axis — the canonical paste-from-typography /
22214        // paste-from-word-processor footgun. Before the non-ASCII
22215        // Unicode `White_Space` scan lifted through the shared
22216        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
22217        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
22218        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
22219        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
22220        // with the far-from-source `label "…" must start and end
22221        // with an alphanumeric` diagnostic — burying the
22222        // paste-from-typography origin under a label-shape leak.
22223        // Peer with the sibling non-ASCII-whitespace pins at
22224        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
22225        // — 1b75b38), `limits::parse_duration`,
22226        // `limits::parse_millicores`, and the shared duration codec
22227        // — same "the diagnostic carries the offending Unicode
22228        // codepoint's `U+XXXX` shape" discipline extended from every
22229        // typed-magnitude codec to the Gateway API v1 Hostname axis.
22230        let mut s = three_member_spec();
22231        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
22232        let err = s.validate().unwrap_err();
22233        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
22234            panic!("expected EntradaHostInvalid, got {err:?}");
22235        };
22236        assert!(
22237            reason.contains("non-ASCII Unicode whitespace character"),
22238            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
22239        );
22240        assert!(
22241            reason.contains("U+00A0"),
22242            "expected offending NBSP codepoint U+00A0, got {reason:?}"
22243        );
22244    }
22245
22246    #[test]
22247    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
22248        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
22249        // `:entrada :host` axis — the canonical paste-from-web-doc /
22250        // paste-from-published-HTML footgun. `char::is_whitespace`
22251        // returns true for `U+2028` per the Unicode `White_Space`
22252        // property, so `str::trim` at any downstream site would
22253        // silently strip it — same drift class as NBSP but on a
22254        // different codepoint region. Pins the second representative
22255        // (non-Latin-1 `char::is_whitespace` member) through the
22256        // shared predicate. Peer with
22257        // `parse_byte_size_rejects_internal_line_separator` on
22258        // `limits::parse_byte_size` (1b75b38).
22259        let mut s = three_member_spec();
22260        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
22261        let err = s.validate().unwrap_err();
22262        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
22263            panic!("expected EntradaHostInvalid, got {err:?}");
22264        };
22265        assert!(
22266            reason.contains("non-ASCII Unicode whitespace character"),
22267            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
22268        );
22269        assert!(
22270            reason.contains("U+2028"),
22271            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
22272        );
22273    }
22274
22275    #[test]
22276    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
22277        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
22278        // labels in the `:entrada :host` axis — the canonical
22279        // paste-from-CJK-typography footgun (CJK IMEs default to
22280        // full-width whitespace when the space bar is pressed in
22281        // Japanese / Chinese input modes). Pins the third
22282        // representative of the non-ASCII Unicode `White_Space` set
22283        // through the shared predicate: the CJK block, distinct from
22284        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
22285        // SEPARATOR `U+2028` — covering the same axis breadth the
22286        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
22287        // (1b75b38) pins on `limits::parse_byte_size`.
22288        let mut s = three_member_spec();
22289        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
22290        let err = s.validate().unwrap_err();
22291        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
22292            panic!("expected EntradaHostInvalid, got {err:?}");
22293        };
22294        assert!(
22295            reason.contains("non-ASCII Unicode whitespace character"),
22296            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
22297        );
22298        assert!(
22299            reason.contains("U+3000"),
22300            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
22301        );
22302    }
22303
22304    #[test]
22305    fn rejects_entrada_host_too_long() {
22306        // Total length cap = 253; build a 254-byte host out of two
22307        // 63-byte labels + one 62-byte label + dots.
22308        let mut s = three_member_spec();
22309        let big = format!(
22310            "{}.{}.{}.{}",
22311            "a".repeat(63),
22312            "b".repeat(63),
22313            "c".repeat(63),
22314            "d".repeat(254 - 63 * 3 - 3)
22315        );
22316        assert_eq!(big.len(), 254);
22317        s.entrada.as_mut().unwrap().host = big;
22318        let err = s.validate().unwrap_err();
22319        assert!(
22320            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22321                if reason.contains("max length of 253")),
22322            "got {err:?}"
22323        );
22324    }
22325
22326    #[test]
22327    fn rejects_entrada_host_label_too_long() {
22328        let mut s = three_member_spec();
22329        // 64-byte label — one over the per-label cap.
22330        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
22331        let err = s.validate().unwrap_err();
22332        assert!(
22333            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
22334                if reason.contains("label max length of 63")),
22335            "got {err:?}"
22336        );
22337    }
22338
22339    #[test]
22340    fn entrada_host_diagnostic_carries_offending_host() {
22341        // Diagnostic-shape pin — the offending host + a non-empty
22342        // reason flow through verbatim so the author can grep their
22343        // caixa.lisp for `:host "<host>"` and fix it in one edit.
22344        let mut s = three_member_spec();
22345        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
22346        let err = s.validate().unwrap_err();
22347        match err {
22348            AplicacaoError::EntradaHostInvalid { host, reason } => {
22349                assert_eq!(host, "checkout.quero.cloud:8080");
22350                assert!(!reason.is_empty(), "reason field must be non-empty");
22351            }
22352            other => panic!("expected EntradaHostInvalid, got {other:?}"),
22353        }
22354    }
22355
22356    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
22357    // substrate primitive that folds the fourteen
22358    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
22359    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
22360    // one dispatch — peer with the sixteen equivalence pins the
22361    // [`crate::LayoutError`] `_violation` constructor family carries in
22362    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
22363    // fixture host + reason are fixed `&'static str`s so both fields of
22364    // both constructed variants pin verbatim: the `host` axis is pinned
22365    // through the shared `host.to_string()` wrap (the ctor's uniform
22366    // one-slot construction) and the `reason` axis is pinned through
22367    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
22368    // routing). Any future regression on the lift (an extra field
22369    // introduced without updating the ctor, a diverging string
22370    // conversion at either arm) surfaces at this pin's diagnostic
22371    // rather than at a per-wire-up struct-literal reintroduction.
22372    #[test]
22373    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
22374        let host = "checkout.quero.cloud:8080";
22375        let reason = "sample reason text";
22376        assert_eq!(
22377            AplicacaoError::entrada_host_invalid(host, reason),
22378            AplicacaoError::EntradaHostInvalid {
22379                host: host.to_string(),
22380                reason: reason.to_string(),
22381            },
22382            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
22383        );
22384    }
22385
22386    // Routing pin — the ctor's `host: &str` argument threads through
22387    // `.to_string()` verbatim on the `host` field, so the constructed
22388    // variant carries the offending host bytes without any wrapper-
22389    // side transformation (no `.to_ascii_lowercase()` normalization,
22390    // no `.trim()` strip, no truncation) — the same "diagnostic carries
22391    // the offending value verbatim so the author can grep their
22392    // caixa.lisp" discipline every peer typed-slot ctor at this
22393    // altitude carries.
22394    #[test]
22395    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
22396        // Uppercase + trailing whitespace + port suffix — three
22397        // wrapper-side transformations the ctor must *not* apply.
22398        let host = " Checkout.quero.CLOUD:8080 ";
22399        let err = AplicacaoError::entrada_host_invalid(host, "sample");
22400        match err {
22401            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
22402                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
22403            }
22404            other => panic!("expected EntradaHostInvalid, got {other:?}"),
22405        }
22406    }
22407
22408    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
22409    // `&str` literals and `format!(…)` outputs identically and both
22410    // route through `Into::into` verbatim onto the `reason` field.
22411    // Pins both codepaths against the same host to prove the two
22412    // shapes the fourteen wire-up sites use at their per-arm diagnostic
22413    // (ten `&str` literals — some with `.to_string()` at the caller,
22414    // some without — plus four `format!(…)` outputs) each produce
22415    // byte-equal `reason` fields against the same offending host.
22416    #[test]
22417    fn entrada_host_invalid_ctor_routes_reason_through_into() {
22418        let host = "checkout.quero.cloud";
22419        // `&str` literal — the ctor's `impl Into<String>` accepts it
22420        // without a caller-side `.to_string()`.
22421        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
22422        // Owned `String` from `format!` — the peer `format!(…)`-shaped
22423        // wire-up arm.
22424        let from_format =
22425            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
22426        // `String` from `.to_string()` on a literal — the peer
22427        // `"literal".to_string()`-shaped wire-up arm the pre-lift
22428        // sites carried.
22429        let from_to_string =
22430            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
22431        match (&from_literal, &from_format, &from_to_string) {
22432            (
22433                AplicacaoError::EntradaHostInvalid {
22434                    reason: r_lit,
22435                    host: h_lit,
22436                },
22437                AplicacaoError::EntradaHostInvalid {
22438                    reason: r_fmt,
22439                    host: h_fmt,
22440                },
22441                AplicacaoError::EntradaHostInvalid {
22442                    reason: r_ts,
22443                    host: h_ts,
22444                },
22445            ) => {
22446                assert_eq!(r_lit, "literal reason text");
22447                assert_eq!(r_fmt, "literal reason text");
22448                assert_eq!(r_ts, "literal reason text");
22449                assert_eq!(h_lit, host);
22450                assert_eq!(h_fmt, host);
22451                assert_eq!(h_ts, host);
22452            }
22453            _ => panic!("expected three EntradaHostInvalid variants"),
22454        }
22455        // Cross-arm equivalence — the three shapes must produce
22456        // byte-equal `AplicacaoError` values, so the fourteen wire-up
22457        // sites' mixed per-arm shapes fold onto one canonical form.
22458        assert_eq!(from_literal, from_format);
22459        assert_eq!(from_literal, from_to_string);
22460    }
22461
22462    // Equivalence pins for the six sibling
22463    // [`aplicacao_field_reason_ctors!`]-generated constructors that
22464    // fold the peer `{ <field>: String, reason: String }` variants
22465    // onto the same substrate-primitive family
22466    // `entrada_host_invalid` (17dd504) already carries pins for.
22467    // Each ctor's fixture pair (a fixed `&'static str` value and a
22468    // fixed `&'static str` reason) pins both fields verbatim so any
22469    // future regression on the macro (an extra field introduced
22470    // without updating the macro, a diverging string conversion at
22471    // either arm, a field-name typo on one variant that dropped it
22472    // off the shared shape) surfaces at the affected variant's pin
22473    // rather than at a per-wire-up struct-literal reintroduction. Peer
22474    // discipline of the sixteen `LayoutError` _violation ctor pins in
22475    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
22476    // and the paired
22477    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
22478    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
22479    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
22480    // (8580068) equivalence pins on the sibling `AplicacaoError`
22481    // ctor macros.
22482    #[test]
22483    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
22484        let caixa = "cart-svc";
22485        let reason = "sample reason text";
22486        assert_eq!(
22487            AplicacaoError::membro_caixa_invalid(caixa, reason),
22488            AplicacaoError::MembroCaixaInvalid {
22489                caixa: caixa.to_string(),
22490                reason: reason.to_string(),
22491            },
22492        );
22493    }
22494
22495    #[test]
22496    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
22497        let para = "checkout";
22498        let reason = "sample reason text";
22499        assert_eq!(
22500            AplicacaoError::entrada_para_invalid(para, reason),
22501            AplicacaoError::EntradaParaInvalid {
22502                para: para.to_string(),
22503                reason: reason.to_string(),
22504            },
22505        );
22506    }
22507
22508    #[test]
22509    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
22510        let path = "/api/cart";
22511        let reason = "sample reason text";
22512        assert_eq!(
22513            AplicacaoError::entrada_path_invalid(path, reason),
22514            AplicacaoError::EntradaPathInvalid {
22515                path: path.to_string(),
22516                reason: reason.to_string(),
22517            },
22518        );
22519    }
22520
22521    #[test]
22522    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
22523        let cluster = "rio";
22524        let reason = "sample reason text";
22525        assert_eq!(
22526            AplicacaoError::placement_cluster_invalid(cluster, reason),
22527            AplicacaoError::PlacementClusterInvalid {
22528                cluster: cluster.to_string(),
22529                reason: reason.to_string(),
22530            },
22531        );
22532    }
22533
22534    #[test]
22535    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
22536        let affinity = "data-locality";
22537        let reason = "sample reason text";
22538        assert_eq!(
22539            AplicacaoError::placement_affinity_invalid(affinity, reason),
22540            AplicacaoError::PlacementAffinityInvalid {
22541                affinity: affinity.to_string(),
22542                reason: reason.to_string(),
22543            },
22544        );
22545    }
22546
22547    #[test]
22548    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
22549        let shard_key = "tenantId";
22550        let reason = "sample reason text";
22551        assert_eq!(
22552            AplicacaoError::shard_key_invalid(shard_key, reason),
22553            AplicacaoError::ShardKeyInvalid {
22554                shard_key: shard_key.to_string(),
22555                reason: reason.to_string(),
22556            },
22557        );
22558    }
22559
22560    // Pin the three-slot per-`:contratos <slot>` sibling of the
22561    // two-slot `aplicacao_field_reason_ctors!` family — the sole
22562    // per-axis ctor carrying the extra `slot: &'static str` axis-tag
22563    // distinguishing the two-arm `:de` / `:para` cascade. Sweeps both
22564    // canonical author-side slot tags through the ctor and asserts
22565    // byte-equality against the pre-lift struct-literal shape so no
22566    // per-arm wrapper transformation drifts in against the sole
22567    // in-crate wire-up.
22568    #[test]
22569    fn contrato_caixa_invalid_ctor_matches_struct_literal_wrap() {
22570        let caixa = "cart-svc";
22571        let reason = "sample reason text";
22572        for slot in [
22573            crate::render::CONTRATO_AUTHOR_KEY_DE,
22574            crate::render::CONTRATO_AUTHOR_KEY_PARA,
22575        ] {
22576            assert_eq!(
22577                AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
22578                AplicacaoError::ContratoCaixaInvalid {
22579                    slot,
22580                    caixa: caixa.to_string(),
22581                    reason: reason.to_string(),
22582                },
22583            );
22584        }
22585    }
22586
22587    // The `reason: impl Into<String>` bound accepts both a `&str`
22588    // literal and a `format!(…)` owned-`String` output verbatim,
22589    // matching the peer `aplicacao_field_reason_ctors!` family's
22590    // reason-axis invariance so the sole in-crate wire-up's
22591    // `require_valid_dns_1123_label`-delivered owned-`String` return
22592    // and any future `&str` literal caller land on the same variant.
22593    #[test]
22594    fn contrato_caixa_invalid_ctor_routes_reason_through_into_uniformly() {
22595        let via_literal = "literal reason text";
22596        let via_format = format!("{} reason text", "literal");
22597        for slot in [
22598            crate::render::CONTRATO_AUTHOR_KEY_DE,
22599            crate::render::CONTRATO_AUTHOR_KEY_PARA,
22600        ] {
22601            assert_eq!(
22602                AplicacaoError::contrato_caixa_invalid(slot, "c", via_literal),
22603                AplicacaoError::contrato_caixa_invalid(slot, "c", via_format.clone()),
22604            );
22605        }
22606    }
22607
22608    // Pin the paired one-slot empty-arm sibling of the three-slot
22609    // `contrato_caixa_invalid` per-`:contratos <slot>` ctor — the sole
22610    // closure-form empty-arm on the shared
22611    // [`crate::render::require_valid_dns_1123_label`] two-closure
22612    // cascade at [`validate_contrato_caixa`], carrying the same
22613    // `slot: &'static str` axis-tag that distinguishes the two-arm
22614    // `:de` / `:para` cascade. Sweeps both canonical author-side slot
22615    // tags through the ctor and asserts byte-equality against the
22616    // pre-lift struct-literal shape so no per-arm wrapper transformation
22617    // drifts in against the sole in-crate wire-up. Peer of the sibling
22618    // [`crate::behavior::BehaviorError::empty_path`] one-slot
22619    // `{ slot: &'static str }` equivalence pin on the paired
22620    // `BehaviorError` envelope's four-arm sandboxed-lisp-path cascade
22621    // ([`crate::render::require_sandboxed_lisp_path`]) — extended here
22622    // onto the sibling `AplicacaoError` envelope's two-arm
22623    // DNS-1123-label cascade so both empty-arm axes carry a
22624    // substrate-primitive equivalence pin rather than the pre-lift
22625    // hand-open struct-literal.
22626    #[test]
22627    fn contrato_caixa_empty_ctor_matches_struct_literal_wrap() {
22628        for slot in [
22629            crate::render::CONTRATO_AUTHOR_KEY_DE,
22630            crate::render::CONTRATO_AUTHOR_KEY_PARA,
22631        ] {
22632            assert_eq!(
22633                AplicacaoError::contrato_caixa_empty(slot),
22634                AplicacaoError::ContratoCaixaEmpty { slot },
22635                "generated contrato_caixa_empty ctor must produce \
22636                 byte-equal AplicacaoError to the open-coded \
22637                 struct-literal wrap on the same &'static str fixture \
22638                 (slot = {slot:?})",
22639            );
22640        }
22641    }
22642
22643    // Cross-axis pin: sweep the constructor's single input axis (`slot:
22644    // &'static str`) through every canonical
22645    // [`crate::render::CONTRATO_AUTHOR_KEY_*`] tag *plus* a non-canonical
22646    // `&'static str` value (`":phantom"`), so any wrapper-side lowercase
22647    // / trim / truncate / re-order / fixed-slot substitution on the
22648    // one-field construction surfaces here rather than at a downstream
22649    // diagnostic-shape mismatch. The non-canonical arm proves the
22650    // constructor does not silently clamp `slot` to the `:de` /
22651    // `:para` roster (a future third `:contratos <slot>` axis lands on
22652    // this ctor without a per-arm rewrite), matching the discipline the
22653    // sibling [`Self::contrato_caixa_invalid`] ctor's tri-slot sweep
22654    // establishes at
22655    // `contrato_caixa_invalid_ctor_matches_struct_literal_wrap`
22656    // (18114) on the paired three-slot invalid-arm envelope.
22657    #[test]
22658    fn contrato_caixa_empty_ctor_routes_slot_verbatim_across_both_axes() {
22659        for slot in [
22660            crate::render::CONTRATO_AUTHOR_KEY_DE,
22661            crate::render::CONTRATO_AUTHOR_KEY_PARA,
22662            ":phantom",
22663        ] {
22664            assert_eq!(
22665                AplicacaoError::contrato_caixa_empty(slot),
22666                AplicacaoError::ContratoCaixaEmpty { slot },
22667            );
22668        }
22669    }
22670
22671    // End-to-end wire-up pin: `AplicacaoSpec::validate` on an empty
22672    // `:contratos :de` value must surface a diagnostic byte-equal to
22673    // the substrate primitive `AplicacaoError::contrato_caixa_empty`'s
22674    // output on the same slot fixture. Proves the sole in-crate
22675    // closure-form wire-up inside [`validate_contrato_caixa`]'s
22676    // [`crate::render::require_valid_dns_1123_label`] empty-arm routes
22677    // through the ctor rather than the pre-lift open-coded
22678    // struct-literal block, matching the sibling per-arm
22679    // `end_to_end_wire_up_routes_through_ctor` discipline the peer
22680    // per-envelope ctor pins the recent
22681    // [`Self::policy_rate_limit_cannot_admit_retry_burst`] (9703bd6),
22682    // [`Self::policy_breaker_trips_before_retries_exhausted`] (f54c539),
22683    // [`Self::policy_breaker_cannot_trip_under_rate_limit`] (6bb4e46),
22684    // and [`Self::policy_breaker_window_below_timeout`] (9b30c07)
22685    // cross-axis Policy* variants carry. Complements the two axis-tag
22686    // arms already pinned above the `:contratos` value-shape gate
22687    // block (`rejects_contrato_de_empty`, `rejects_contrato_para_empty`)
22688    // which anchor via the shape; this pin additionally verifies the
22689    // ctor is the exclusive construction path.
22690    #[test]
22691    fn contrato_caixa_empty_end_to_end_wire_up_routes_through_ctor() {
22692        // Empty `:de` — the sole in-crate wire-up hits the empty-arm
22693        // closure at the first `:contratos` value-shape gate, threading
22694        // the `CONTRATO_AUTHOR_KEY_DE` label through the ctor.
22695        let mut s_de = three_member_spec();
22696        s_de.contratos.push(contract_http("", "catalog", "/x"));
22697        assert_eq!(
22698            s_de.validate().unwrap_err(),
22699            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_DE),
22700        );
22701        // Symmetric arm: an empty `:para` on a valid `:de` fires the
22702        // same closure with the `CONTRATO_AUTHOR_KEY_PARA` label.
22703        let mut s_para = three_member_spec();
22704        s_para.contratos.push(contract_http("cart", "", "/x"));
22705        assert_eq!(
22706            s_para.validate().unwrap_err(),
22707            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_PARA),
22708        );
22709    }
22710
22711    // Cross-family invariance pin — the six sibling ctors and
22712    // `entrada_host_invalid` all route `reason: impl Into<String>` +
22713    // `<field>: &str` verbatim onto their respective typed variants
22714    // through the shared [`aplicacao_field_reason_ctors!`] macro.
22715    // Sweeps a fixture pair (`&str` literal, `format!` output) against
22716    // every ctor to pin that no per-arm wrapper transformation drifted
22717    // in against the uniform macro-generated body.
22718    #[test]
22719    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
22720        let via_literal = "literal reason text";
22721        let via_format = format!("{} reason text", "literal");
22722        assert_eq!(
22723            AplicacaoError::membro_caixa_invalid("m", via_literal),
22724            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
22725        );
22726        assert_eq!(
22727            AplicacaoError::entrada_para_invalid("p", via_literal),
22728            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
22729        );
22730        assert_eq!(
22731            AplicacaoError::entrada_path_invalid("/a", via_literal),
22732            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
22733        );
22734        assert_eq!(
22735            AplicacaoError::placement_cluster_invalid("c", via_literal),
22736            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
22737        );
22738        assert_eq!(
22739            AplicacaoError::placement_affinity_invalid("a", via_literal),
22740            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
22741        );
22742        assert_eq!(
22743            AplicacaoError::shard_key_invalid("k", via_literal),
22744            AplicacaoError::shard_key_invalid("k", via_format.clone()),
22745        );
22746        assert_eq!(
22747            AplicacaoError::entrada_host_invalid("h", via_literal),
22748            AplicacaoError::entrada_host_invalid("h", via_format),
22749        );
22750    }
22751
22752    #[test]
22753    fn entrada_host_empty_takes_precedence_over_invalid() {
22754        // Ordering pin: `EmptyEntradaHost` is the more self-locating
22755        // diagnostic on `""` and must lead — `validate_entrada_host`
22756        // is only reached after the empty-check fires at the call
22757        // site. (The predicate itself defends against direct
22758        // invocation by returning the same error on `""`.)
22759        let mut s = three_member_spec();
22760        s.entrada.as_mut().unwrap().host = String::new();
22761        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
22762    }
22763
22764    #[test]
22765    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
22766        // Ordering pin: a missing :para member is the more
22767        // self-locating diagnostic and fires before the host gate.
22768        let mut s = three_member_spec();
22769        let e = s.entrada.as_mut().unwrap();
22770        e.para = "ghost".into();
22771        e.host = "BAD HOST".into();
22772        let err = s.validate().unwrap_err();
22773        assert!(
22774            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
22775            "got {err:?}"
22776        );
22777    }
22778
22779    #[test]
22780    fn entrada_host_invalid_fires_before_port_zero() {
22781        // Ordering pin: the host gate fires before the port gate so
22782        // a malformed host is named even when the port is also wrong.
22783        let mut s = three_member_spec();
22784        let e = s.entrada.as_mut().unwrap();
22785        e.host = "Checkout.quero.cloud".into();
22786        e.port = 0;
22787        let err = s.validate().unwrap_err();
22788        assert!(
22789            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
22790                if host == "Checkout.quero.cloud"),
22791            "got {err:?}"
22792        );
22793    }
22794
22795    #[test]
22796    fn entrada_accepts_canonical_hosts() {
22797        // Positive-control sweep — every form the Gateway API
22798        // apiserver accepts must round-trip through validate. Covers
22799        // a plain DNS subdomain, a leading wildcard, a single-label
22800        // host (cluster-internal), a max-length-edge label, a
22801        // hyphen-bearing label, and a Punycode IDN label.
22802        for host in [
22803            "checkout.quero.cloud",
22804            "*.quero.cloud",
22805            "checkout",
22806            // 63-byte label — exactly the per-label cap.
22807            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
22808            "foo-bar.quero.cloud",
22809            // Punycode IDN — valid because the author pre-encoded.
22810            "xn--bcher-kva.example.com",
22811        ] {
22812            let mut s = three_member_spec();
22813            s.entrada.as_mut().unwrap().host = host.into();
22814            s.validate()
22815                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
22816        }
22817    }
22818
22819    #[test]
22820    fn entrada_host_max_length_validates() {
22821        // 253-byte host is the cap exactly — must validate. Build a
22822        // 253-byte host out of three 63-byte labels + one 61-byte
22823        // label + 3 dots = 252 bytes, then pad one byte to 253.
22824        let mut s = three_member_spec();
22825        let host = format!(
22826            "{}.{}.{}.{}",
22827            "a".repeat(63),
22828            "b".repeat(63),
22829            "c".repeat(63),
22830            "d".repeat(253 - 63 * 3 - 3)
22831        );
22832        assert_eq!(host.len(), 253);
22833        s.entrada.as_mut().unwrap().host = host;
22834        s.validate().unwrap();
22835    }
22836
22837    #[test]
22838    fn entrada_host_total_length_cap_threads_lifted_render_const() {
22839        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
22840        // total-length gate now reads the K8s Gateway API v1 Hostname
22841        // `maxLength: 253` cap from the lifted
22842        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
22843        // of truth — the same constant every future Gateway-API-Hostname
22844        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
22845        // materializer's per-host validator, the future per-`Certificate`
22846        // SAN emitter for cert-manager, the multi-`:entrada`
22847        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
22848        // from. Before the lift, the aplicacao-side reader consumed a
22849        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
22850        // 253-byte value as the peer render-side canonical bounds
22851        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
22852        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
22853        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
22854        // module boundary — a future 253-byte drift on either side would
22855        // silently split into two axes' worth of admission-schema mismatch
22856        // without a build-time signal. Pin the cap through a fresh 254-
22857        // byte host that hits the total-length arm, then read the reason
22858        // for the exact byte count the shared constant carries: any future
22859        // regression on the lift (a private alias reintroduced, a hard-
22860        // coded literal at the arm, a mismatch between the aplicacao-side
22861        // and render-side canonicals) surfaces as this pin's diagnostic
22862        // failing to match, not as a per-cluster admission rejection far
22863        // from the caixa.lisp source line.
22864        let mut s = three_member_spec();
22865        let over_cap = format!(
22866            "{}.{}.{}.{}",
22867            "a".repeat(63),
22868            "b".repeat(63),
22869            "c".repeat(63),
22870            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
22871        );
22872        assert_eq!(
22873            over_cap.len(),
22874            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
22875        );
22876        s.entrada.as_mut().unwrap().host = over_cap;
22877        let err = s.validate().unwrap_err();
22878        match err {
22879            AplicacaoError::EntradaHostInvalid { reason, .. } => {
22880                let needle = format!(
22881                    "max length of {} bytes",
22882                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
22883                );
22884                assert!(
22885                    reason.contains(&needle),
22886                    "diagnostic must name the lifted \
22887                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
22888                );
22889            }
22890            other => panic!("expected EntradaHostInvalid, got {other:?}"),
22891        }
22892    }
22893
22894    #[test]
22895    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
22896        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
22897        // on the per-label-cap axis. Before the lift, the aplicacao-side
22898        // per-label arm consumed a private const alias
22899        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
22900        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
22901        // split from it at the module boundary — every `.`-separated
22902        // label in a Gateway API v1 Hostname is a DNS-1123 label under
22903        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
22904        // so the private alias's 63 and the canonical const's 63 were
22905        // pinning the same underlying rule twice. Pin the cap through a
22906        // 64-byte label that hits the per-label arm, then read the reason
22907        // for the exact byte count the shared constant carries: any
22908        // future drift on either side (a private alias reintroduced, a
22909        // hard-coded literal at the arm, a mismatch between the two
22910        // 63-byte pins) surfaces at this pin's diagnostic rather than at
22911        // a per-cluster admission rejection whose "field is invalid"
22912        // opacity misframes the root cause.
22913        let mut s = three_member_spec();
22914        let over_cap_label = format!(
22915            "{}.quero.cloud",
22916            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
22917        );
22918        s.entrada.as_mut().unwrap().host = over_cap_label;
22919        let err = s.validate().unwrap_err();
22920        match err {
22921            AplicacaoError::EntradaHostInvalid { reason, .. } => {
22922                let needle = format!(
22923                    "label max length of {} bytes",
22924                    crate::render::DNS_1123_LABEL_MAX_LEN,
22925                );
22926                assert!(
22927                    reason.contains(&needle),
22928                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
22929                     cap verbatim on the per-label arm, got: {reason:?}",
22930                );
22931            }
22932            other => panic!("expected EntradaHostInvalid, got {other:?}"),
22933        }
22934    }
22935
22936    #[test]
22937    fn entrada_with_empty_paths_validates() {
22938        // Empty `:paths` is the documented "match every path" form;
22939        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
22940        let mut s = three_member_spec();
22941        s.entrada.as_mut().unwrap().paths = vec![];
22942        s.validate().unwrap();
22943    }
22944
22945    #[test]
22946    fn entrada_root_path_validates() {
22947        // The author-supplied bare-root `:entrada :paths` entry is the
22948        // same byte-shape the peer emit-side catch-all constant
22949        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
22950        // the author's `:paths` list is empty — sweeping the test-side
22951        // probe literal onto the lifted const closes the two-axis pin
22952        // (author-side admit + emit-side canonical fallback) around
22953        // one `&'static str`, so a future rebrand of the catch-all
22954        // reaches both consumers by construction. Peer to
22955        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
22956        // on the canonical-literal pin surface.
22957        let mut s = three_member_spec();
22958        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
22959        s.validate().unwrap();
22960    }
22961
22962    #[test]
22963    fn placement_strategy_variants_round_trip() {
22964        for s in [
22965            PlacementStrategy::SingleNode,
22966            PlacementStrategy::Replicated,
22967            PlacementStrategy::Sharded,
22968        ] {
22969            let p = Placement {
22970                estrategia: s,
22971                clusters: vec!["rio".into()],
22972                affinity: None,
22973                // Route the paired `:shard-key` fixture-builder through the
22974                // typed cross-slot invariant predicate
22975                // [`PlacementStrategy::requires_shard_key`] rather than the
22976                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
22977                // arm-identity predicate — the two answer the same
22978                // question under today's closed accept-set but a future
22979                // arm addition that consumed `:shard-key` under a
22980                // non-`Sharded` name would silently mis-attach the
22981                // fixture's `:shard-key` if the builder read through the
22982                // arm-identity predicate. The cross-slot-invariant
22983                // predicate migrates through one caixa-core edit on any
22984                // future arm addition; the fixture keeps producing a
22985                // `validate()`-passing round-trip by construction.
22986                shard_key: if s.requires_shard_key() {
22987                    Some("$key".into())
22988                } else {
22989                    None
22990                },
22991            };
22992            let json = serde_json::to_string(&p).unwrap();
22993            let back: Placement = serde_json::from_str(&json).unwrap();
22994            assert_eq!(back, p);
22995        }
22996    }
22997
22998    #[test]
22999    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
23000        // The fail-before-pass-after pin: pre-lift there was no
23001        // single-source binding between the [`PlacementStrategy`]
23002        // variant name the `Serialize` derive emits and the byte-
23003        // string every downstream cluster-side dispatcher (the
23004        // `lareira-fleet-programs` aggregator's per-entry strategy
23005        // branch, the future `app-operator` reconciler, the M3
23006        // Adaptive compression pass's per-strategy weighting) probes
23007        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
23008        // future `#[serde(rename_all = "kebab-case")]` attribute on
23009        // the enum — or a variant rename in the source — would
23010        // silently rebrand the emitted scalar under one spelling
23011        // while every downstream dispatcher still probed the other,
23012        // with the failure surfacing at the aggregator's dispatch
23013        // step or the operator's reconcile posture (workloads coming
23014        // up under the `default()` `Replicated` arm rather than the
23015        // typed slot's declared strategy) far from the source
23016        // rebrand commit and with no field naming the drift. Pinning
23017        // the two paths (the `Serialize` derive's serialized string
23018        // AND the [`PlacementStrategy::as_str`] helper) to the same
23019        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
23020        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
23021        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
23022        // makes any future drift on either endpoint fail here at
23023        // caixa-core build time.
23024        for (variant, expected) in [
23025            (
23026                PlacementStrategy::SingleNode,
23027                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
23028            ),
23029            (
23030                PlacementStrategy::Replicated,
23031                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
23032            ),
23033            (
23034                PlacementStrategy::Sharded,
23035                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
23036            ),
23037        ] {
23038            let json = serde_json::to_string(&variant).unwrap();
23039            assert_eq!(
23040                json,
23041                format!("\"{expected}\""),
23042                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
23043            );
23044            assert_eq!(
23045                variant.as_str(),
23046                expected,
23047                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
23048                 M3_PLACEMENT_ESTRATEGIA_* constant"
23049            );
23050        }
23051    }
23052
23053    #[test]
23054    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
23055        // Cross-arm drift-detection pin on the M3
23056        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
23057        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
23058        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
23059        // scalar-value pentad: a future collapse of two canonical
23060        // variant byte-strings onto the same value (an accidental
23061        // copy-paste flip of
23062        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
23063        // read `"SingleNode"`, a per-arm rebrand that lands one const
23064        // without touching its paired peer) would silently reroute
23065        // every downstream operator's per-strategy dispatch onto the
23066        // sibling arm's reconcile branch and pass every
23067        // propagation-probe test that expected only the stale arm's
23068        // value — a `Replicated`-declared Aplicacao would come up
23069        // under the `SingleNode` primary-and-standby reconcile
23070        // posture, so every-cluster active-active workload would
23071        // silently collapse onto one-cluster-runs-at-a-time takeover
23072        // semantics against its declared strategy, with no field
23073        // naming the strategy-value drift root cause. Peer of the
23074        // sibling
23075        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
23076        // (09ffb2d) /
23077        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
23078        // (ccdf955) /
23079        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
23080        // (d739850) distinctness pins on the sibling OTP-shape /
23081        // caixa-kind closed-set typed-enum discriminator axes — the
23082        // fourth (and structurally the M3 mesh-primitive-defining)
23083        // closed-set typed-enum axis to converge on the same
23084        // "pairwise-distinct-by-construction" discipline.
23085        //
23086        // Fail-before-pass-after locally verified by mutating
23087        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
23088        // also read `"SingleNode"` — this pin fires as expected;
23089        // restoring passes.
23090        let all = [
23091            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
23092            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
23093            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
23094        ];
23095        for (i, a) in all.iter().enumerate() {
23096            for (j, b) in all.iter().enumerate() {
23097                if i != j {
23098                    assert_ne!(
23099                        a, b,
23100                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
23101                         distinct — got duplicate {a:?} at indices {i} and {j}",
23102                    );
23103                }
23104            }
23105        }
23106    }
23107
23108    #[test]
23109    fn placement_strategy_display_routes_through_as_str_helper() {
23110        // The fail-before-pass-after pin: pre-lift the sibling
23111        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
23112        // / [`crate::supervisor::RestartPolicy`] both carried a stable
23113        // [`std::fmt::Display`] surface via their
23114        // `#[discriminant(also_display)]` gen-platform derive, but
23115        // [`PlacementStrategy`] did not — every consumer reaching for
23116        // a strategy byte-string past the wire format had to pick
23117        // between three paths ([`PlacementStrategy::as_str`], the
23118        // `Serialize` derive's serialized string, or `format!("{v:?}")`
23119        // on the `Debug` derive), any two of which a future variant
23120        // rename or `#[serde(rename_all = "kebab-case")]` attribute
23121        // would silently desynchronize. Wiring [`std::fmt::Display`]
23122        // through [`PlacementStrategy::as_str`] closes the third path:
23123        // every `format!("{v}")` call reaches the same lifted
23124        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
23125        // and the [`PlacementStrategy::as_str`] helper already route
23126        // through, so a future variant rename lands at exactly one
23127        // place. Pin the routing here so a future
23128        // `impl std::fmt::Display for PlacementStrategy` reimplementation
23129        // that hand-rolls the arms instead of delegating to
23130        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
23131        for variant in [
23132            PlacementStrategy::SingleNode,
23133            PlacementStrategy::Replicated,
23134            PlacementStrategy::Sharded,
23135        ] {
23136            assert_eq!(
23137                variant.to_string(),
23138                variant.as_str(),
23139                "PlacementStrategy::{variant:?} Display must route through \
23140                 PlacementStrategy::as_str (single source of truth: the lifted \
23141                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
23142            );
23143        }
23144    }
23145
23146    #[test]
23147    fn placement_strategy_display_matches_serialized_wire_byte_string() {
23148        // The fail-before-pass-after pin on the second half of the
23149        // three-path convergence: `Display` (user-facing text) agrees
23150        // byte-for-byte with the `Serialize` derive's wire format
23151        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
23152        // scalar) on every variant. Pre-lift the two paths were
23153        // structurally independent — a future
23154        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
23155        // would silently rebrand the emitted wire scalar
23156        // (`single-node`, `replicated`, `sharded`) while every consumer
23157        // that pretty-prints the strategy (the M3 diagnostic templates,
23158        // the future `feira app graph` per-Aplicacao strategy line,
23159        // the future M4 CR materializer's admission-webhook rejection
23160        // body) would still emit the TitleCase form the `as_str` /
23161        // `Display` route returns, with the mismatch surfacing at
23162        // consumer parse time / operator dispatch time far from the
23163        // source rebrand commit. Pin the two paths byte-for-byte here
23164        // so any future serde-attribute or variant-rename drift is a
23165        // caixa-core-build-time test failure at this call, not a
23166        // silent per-consumer dispatch miss.
23167        for variant in [
23168            PlacementStrategy::SingleNode,
23169            PlacementStrategy::Replicated,
23170            PlacementStrategy::Sharded,
23171        ] {
23172            let wire = serde_json::to_string(&variant).unwrap();
23173            // Strip the outer `"…"` the JSON string form carries — the
23174            // wire scalar the K8s / YAML apiserver consumes is the
23175            // enclosed byte-string, not the quote wrapper.
23176            let unquoted = wire
23177                .strip_prefix('"')
23178                .and_then(|s| s.strip_suffix('"'))
23179                .expect("serialized PlacementStrategy is a JSON string");
23180            assert_eq!(
23181                variant.to_string(),
23182                unquoted,
23183                "PlacementStrategy::{variant:?} Display byte-string must match the \
23184                 Serialize derive's wire byte-string (three-path convergence: \
23185                 Display + as_str + Serialize all resolve to the same \
23186                 M3_PLACEMENT_ESTRATEGIA_* const)"
23187            );
23188        }
23189    }
23190
23191    #[test]
23192    fn placement_strategy_as_ref_str_routes_through_as_str_accessor() {
23193        // Fail-before-pass-after byte-parity pin on the lifted
23194        // `impl AsRef<str> for PlacementStrategy` — asserts the
23195        // standard-library trait impl and the substrate-primitive
23196        // [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
23197        // to the same `&str` per instance across the three-arm closed
23198        // set, so any future silent detour that routes the impl through
23199        // a divergent projection (a per-arm inline
23200        // `match self { PlacementStrategy::Sharded => "Sharded", … }`
23201        // re-inlining that opens a compile-time link to the un-lifted
23202        // arm-literal, a swap onto the kebab-case
23203        // [`gen_platform::Discriminant`] catalog identity that would
23204        // collide the wire axis with the dispatcher-catalog axis) trips
23205        // at caixa-core test time under `PartialEq` rather than at a
23206        // downstream `impl AsRef<str>`-bound consumer's silent split.
23207        // Sweeps every one of the three arms [`PlacementStrategy::ALL`]
23208        // carries so no arm's projection is covered only by the sibling
23209        // wire-format `Serialize` derive path. Peer of the sibling
23210        // [`crate::supervisor::tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
23211        // (419ea81) / `restart_strategy_as_ref_str_routes_through_as_str_accessor`
23212        // (63eb1a4) on the paired M2 per-supervisor closed-set typed
23213        // enums, and the [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
23214        // (16d5c7e) pin on the paired top-level `:versao` typed newtype
23215        // — the four pins together close the substrate primitive's
23216        // `AsRef<str>` projection axis on every closed-set typed enum
23217        // /newtype on the M2/M3 mesh + supervision + version surface.
23218        for &variant in PlacementStrategy::ALL {
23219            assert_eq!(
23220                <PlacementStrategy as AsRef<str>>::as_ref(&variant),
23221                variant.as_str(),
23222                "AsRef<str> impl on PlacementStrategy::{variant:?} must \
23223                 byte-equal PlacementStrategy::as_str on the same instance \
23224                 — divergence signals a silent detour off the substrate-\
23225                 primitive accessor"
23226            );
23227        }
23228    }
23229
23230    #[test]
23231    fn placement_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
23232        // Fail-before-pass-after byte-parity pin on the three-path
23233        // convergence discipline the M3 per-Aplicacao distribution-
23234        // strategy primitive now carries on the `&str`-projection axis:
23235        // `<PlacementStrategy as AsRef<str>>::as_ref(&v)` (the newly
23236        // lifted impl), `format!("{v}")` (the pre-existing
23237        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
23238        // primitive `pub const fn` accessor both trait impls delegate
23239        // through) must resolve to the same byte-string on every
23240        // instance across the three-arm closed set. Refuses any future
23241        // divergence between the two trait impls (a stray
23242        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms rather
23243        // than delegating through the shared accessor; a hypothetical
23244        // `AsRef<str>` rewrite that inlines a per-arm literal cascade)
23245        // that would silently split the two projection paths of the
23246        // same closed-set typed enum. Mirrors the sibling three-path-
23247        // convergence discipline the peer
23248        // [`crate::supervisor::RestartPolicy`] typed enum carries on its
23249        // `AsRef<str>` / `Display` / `as_str` triple (supervisor.rs pin
23250        // `restart_policy_as_ref_str_routes_through_display_via_shared_accessor`,
23251        // 419ea81), the peer [`crate::supervisor::RestartStrategy`]
23252        // triple (supervisor.rs pin
23253        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
23254        // 63eb1a4), and the [`crate::CaixaVersion`] typed newtype
23255        // triple (version.rs pin
23256        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
23257        // 16d5c7e).
23258        for &variant in PlacementStrategy::ALL {
23259            let via_as_ref: &str = <PlacementStrategy as AsRef<str>>::as_ref(&variant);
23260            let via_display: String = format!("{variant}");
23261            let via_accessor: &str = variant.as_str();
23262            assert_eq!(via_as_ref, via_accessor);
23263            assert_eq!(via_display, via_accessor);
23264            assert_eq!(via_as_ref, via_display.as_str());
23265        }
23266    }
23267
23268    #[test]
23269    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
23270        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
23271        // derive on [`PlacementStrategy`]: for each of the three variants
23272        // exactly one of the generated `is_single_node` / `is_replicated`
23273        // / `is_sharded` predicates returns `true` and the other two
23274        // return `false`. Prior to this derive the three per-arm
23275        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
23276        // (the `placement_strategy_variants_round_trip` fixture, the
23277        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23278        // fixture, and the
23279        // `validate_placement_reads_through_lifted_estrategia_accessor`
23280        // fixture) each open-coded a per-arm PartialEq compare against
23281        // the enum variant — three sites that expressed no compile-time
23282        // link back to the closed-set typed dispatch a future fourth
23283        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
23284        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
23285        // would have to thread through in lockstep or one fixture would
23286        // silently disagree with the others on which arms consume the
23287        // `:shard-key` axis. Peer of the sibling
23288        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
23289        // / [`crate::supervisor::RestartPolicy`] /
23290        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
23291        // the sibling closed-set typed-enum discriminator axes — extends
23292        // the same one-typed-dispatch-per-variant discipline onto the
23293        // fifth (and only remaining) closed-set typed-enum discriminator
23294        // on the caixa surface, closing the axis on the M3 mesh-slot
23295        // family.
23296        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
23297            (PlacementStrategy::SingleNode, [true, false, false]),
23298            (PlacementStrategy::Replicated, [false, true, false]),
23299            (PlacementStrategy::Sharded, [false, false, true]),
23300        ];
23301        for (variant, expected) in rows {
23302            let observed = [
23303                variant.is_single_node(),
23304                variant.is_replicated(),
23305                variant.is_sharded(),
23306            ];
23307            assert_eq!(
23308                observed, expected,
23309                "PlacementStrategy::{variant:?} is_* predicates must partition \
23310                 the arm set (single_node, replicated, sharded); got {observed:?}"
23311            );
23312        }
23313    }
23314
23315    #[test]
23316    fn placement_strategy_is_variant_predicates_are_const_fn() {
23317        // The [`gen_platform::IsVariant`] derive emits `const fn`
23318        // predicates on the peer [`crate::CaixaKind`] +
23319        // [`crate::upgrade::UpgradeInstruction`] +
23320        // [`crate::supervisor::RestartStrategy`] +
23321        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
23322        // pin the same posture on [`PlacementStrategy`] so a future
23323        // accidental downgrade to non-`const` (an added runtime helper
23324        // reachable only from a non-`const` context, a manual hand-rolled
23325        // `impl` that shadows the derive-generated method) trips at
23326        // caixa-core build time rather than surfacing as a downstream
23327        // `const`-context regression far from the derive declaration.
23328        //
23329        // The pin lives inside a `const { assert!(..) }` block so the
23330        // compiler enforces both halves (arm predicate is `const`-
23331        // callable AND returns `true` for the matching arm) at
23332        // caixa-core compile time — peer to the sibling
23333        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
23334        // pins on the closed-set typed enum arm-predicate const-
23335        // callability axis.
23336        const {
23337            assert!(PlacementStrategy::SingleNode.is_single_node());
23338            assert!(PlacementStrategy::Replicated.is_replicated());
23339            assert!(PlacementStrategy::Sharded.is_sharded());
23340        }
23341    }
23342
23343    #[test]
23344    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
23345        // Fail-before-pass-after pin on the substrate-lifted
23346        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
23347        // per-arm predicate: for each variant in the closed accept-set the
23348        // predicate returns `true` iff the variant consumes the paired
23349        // [`Placement::shard_key`] axis under
23350        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
23351        // partition. Today the accept-set is the singleton `{Sharded}` —
23352        // `Sharded` is the Akka-style hash-keyed distribution arm
23353        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
23354        // §II.1) and `Replicated` (active-active) refuse the axis through
23355        // [`AplicacaoError::ShardKeyOnNonSharded`].
23356        //
23357        // Pins the per-arm truth-table so a future arm addition (an
23358        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
23359        // roadmap names, a `WeightedShard` promotion the future M5
23360        // adaptive-placement engine acknowledges) that landed a variant
23361        // without extending this predicate's arm-set would surface as a
23362        // caixa-core build-time exhaustiveness error at the
23363        // `match self { … }` arm-fan below rather than a silent per-consumer
23364        // mis-classification at renderer emit time. The paired
23365        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
23366        // predicate stays a distinct question — arm-identity (which the
23367        // sibling
23368        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
23369        // pin already locks) is not cross-slot-invariant consumption; today
23370        // they trip on the same singleton but the pair migrates through
23371        // one caixa-core edit on any future arm addition.
23372        //
23373        // Peer of the sibling per-arm classifier pins
23374        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
23375        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
23376        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
23377        // derived paired predicate on the post-projection typed-view axis
23378        // — same "per-arm semantic-classification predicate paired with
23379        // the arm-identity predicate the derive already emits" discipline
23380        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
23381        // `:placement :shard-key` cross-slot-invariant axis.
23382        let rows: [(PlacementStrategy, bool); 3] = [
23383            (PlacementStrategy::SingleNode, false),
23384            (PlacementStrategy::Replicated, false),
23385            (PlacementStrategy::Sharded, true),
23386        ];
23387        for (variant, expected) in rows {
23388            assert_eq!(
23389                variant.requires_shard_key(),
23390                expected,
23391                "PlacementStrategy::{variant:?}.requires_shard_key() must \
23392                 be {expected} (the substrate-canonical cross-slot invariant \
23393                 on the :placement :shard-key axis; today `Sharded` is the \
23394                 singleton consuming arm — MESH-COMPOSITION §II.4)",
23395            );
23396        }
23397    }
23398
23399    #[test]
23400    fn placement_strategy_requires_shard_key_is_const_fn() {
23401        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
23402        // invariant per-arm predicate is declared `#[must_use] pub const
23403        // fn` — pin the `const`-eval posture here so a future accidental
23404        // downgrade to non-`const` (an added runtime helper reachable
23405        // only from a non-`const` context, a manual hand-rolled `impl`
23406        // that shadows the current three-arm `match self { … }` dispatch)
23407        // trips at caixa-core build time rather than surfacing as a
23408        // downstream `const`-context regression far from the declaration.
23409        // Same shape as the sibling
23410        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
23411        // the peer [`gen_platform::IsVariant`]-derived arm-identity
23412        // predicate axis, but here the load-bearing assertions live in
23413        // module-scope `const _: () = assert!(…)` items so a violation
23414        // fails at compile time (const-eval trip) rather than test time —
23415        // strictly stronger than the runtime `assert!(CONST)` pattern the
23416        // sibling pin uses, and side-steps the
23417        // `clippy::assertions_on_constants` lint the runtime pattern
23418        // otherwise accumulates on the module baseline.
23419        //
23420        // The test body simply witnesses that the module-scope items
23421        // compiled and the runtime dispatch agrees with the const-eval
23422        // dispatch on every arm — the runtime read gives the test a
23423        // failure surface (rather than an empty test body clippy would
23424        // flag as a no-op).
23425        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
23426        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
23427        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
23428        assert_eq!(
23429            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
23430            [
23431                PlacementStrategy::SingleNode.requires_shard_key(),
23432                PlacementStrategy::Replicated.requires_shard_key(),
23433                PlacementStrategy::Sharded.requires_shard_key(),
23434            ],
23435            "runtime and const-eval dispatch on \
23436             PlacementStrategy::requires_shard_key must agree on every arm",
23437        );
23438    }
23439
23440    #[test]
23441    fn placement_estrategia_accessor_is_const_fn() {
23442        // The [`Placement::estrategia`] per-`:placement` distribution-
23443        // strategy `Copy`-return scalar accessor is declared
23444        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
23445        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
23446        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
23447        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
23448        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
23449        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
23450        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
23451        // [`RateLimit`], every one a `pub const fn`). Pin the
23452        // `const`-eval posture here so a future accidental downgrade to
23453        // non-`const` (an added runtime helper reachable only from a
23454        // non-`const` context, a slot promotion to a non-`Copy` return
23455        // that would silently drop the `const` qualifier, a manual
23456        // hand-rolled shadow) trips at caixa-core build time rather
23457        // than surfacing as a downstream `const`-context regression far
23458        // from the declaration.
23459        //
23460        // Same shape as the sibling
23461        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
23462        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
23463        // predicate axis — the load-bearing witness lives in the
23464        // module-scope `const fn` wrapper `estrategia_via_const_fn`
23465        // below: a body that calls [`Placement::estrategia`] under a
23466        // `const fn` signature is well-formed only when the callee is
23467        // itself `const fn`, so any future accidental downgrade of
23468        // [`Placement::estrategia`] to non-`const` fails at caixa-core
23469        // build time (const-eval E0015 / E0658 depending on the arm),
23470        // strictly stronger than a runtime `assert!(CONST)` and
23471        // side-stepping the destructor-in-const restriction that
23472        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
23473        // items on `Placement`'s `Vec<String>` / `Option<String>`
23474        // carriers.
23475        //
23476        // The runtime body witnesses that the const-eval-shaped
23477        // wrapper agrees with a direct call on every closed-set arm.
23478        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
23479            p.estrategia()
23480        }
23481        for estrategia in [
23482            PlacementStrategy::SingleNode,
23483            PlacementStrategy::Replicated,
23484            PlacementStrategy::Sharded,
23485        ] {
23486            let placement = Placement {
23487                estrategia,
23488                clusters: Vec::new(),
23489                affinity: None,
23490                shard_key: None,
23491            };
23492            assert_eq!(
23493                estrategia_via_const_fn(&placement),
23494                placement.estrategia(),
23495                "const-fn-wrapped and direct dispatch on \
23496                 Placement::estrategia must agree for {estrategia:?}",
23497            );
23498        }
23499    }
23500
23501    #[test]
23502    fn entrada_port_accessor_is_const_fn() {
23503        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
23504        // scalar accessor is declared `#[must_use] pub const fn` —
23505        // matching the peer M3 mesh-slot `Copy`-return accessor family
23506        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
23507        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
23508        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
23509        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
23510        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
23511        // [`RateLimit::window`] on the sibling [`RateLimit`], the
23512        // sibling per-`:placement` [`Placement::estrategia`] pinned by
23513        // [`placement_estrategia_accessor_is_const_fn`] above — every
23514        // one a `pub const fn`). Pin the `const`-eval posture here so
23515        // a future accidental downgrade to non-`const` (an added
23516        // runtime helper reachable only from a non-`const` context, an
23517        // `Option<u16>`-shape migration once the substrate grows
23518        // per-`:membros` heterogeneous listener ports that would
23519        // silently drop the `const` qualifier, a manual hand-rolled
23520        // shadow) trips at caixa-core build time rather than surfacing
23521        // as a downstream `const`-context regression far from the
23522        // declaration.
23523        //
23524        // Same shape as the sibling
23525        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
23526        // load-bearing witness lives in the module-scope `const fn`
23527        // wrapper `port_via_const_fn`: a body that calls
23528        // [`Entrada::port`] under a `const fn` signature is well-formed
23529        // only when the callee is itself `const fn`, side-stepping the
23530        // destructor-in-const restriction that would otherwise block a
23531        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
23532        // `String` / `Vec<String>` carriers.
23533        //
23534        // The runtime body sweeps a representative port set spanning
23535        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
23536        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
23537        // ceiling — the const-fn-wrapped call must agree with a direct
23538        // call on every fixture (a violation trips the test) and every
23539        // returned scalar must byte-equal the input `port` (a violation
23540        // means the accessor stopped being a raw field-return copy).
23541        const fn port_via_const_fn(e: &Entrada) -> u16 {
23542            e.port()
23543        }
23544        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
23545            let entrada = Entrada {
23546                host: String::new(),
23547                para: String::new(),
23548                port,
23549                paths: Vec::new(),
23550            };
23551            assert_eq!(
23552                port_via_const_fn(&entrada),
23553                entrada.port(),
23554                "const-fn-wrapped and direct dispatch on Entrada::port \
23555                 must agree for port={port}",
23556            );
23557            assert_eq!(
23558                entrada.port(),
23559                port,
23560                "Entrada::port must return the storage-side u16 verbatim \
23561                 for port={port}",
23562            );
23563        }
23564    }
23565
23566    #[test]
23567    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
23568        // Load-bearing cross-slot-partition pin closing the loop between
23569        // the substrate-lifted
23570        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
23571        // the closed-set typed enum and the actual
23572        // [`AplicacaoSpec::validate_placement`] runtime behavior across
23573        // the paired `:placement :shard-key` axis: every validated
23574        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
23575        // satisfies `placement.shard_key().is_some() ==
23576        // placement.estrategia().requires_shard_key()`. The four-cell
23577        // shape witness sweeps every combination of (variant in the
23578        // closed accept-set, `:shard-key` Some/None) and pins:
23579        //
23580        //   * variant.requires_shard_key() && shard_key.is_some() →
23581        //     validate() passes; the paired shape is the sole
23582        //     `requires_shard_key` arm-family accepted shape.
23583        //   * variant.requires_shard_key() && shard_key.is_none() →
23584        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
23585        //     the paired shape is the refused missing-key shape on
23586        //     Sharded-family arms.
23587        //   * !variant.requires_shard_key() && shard_key.is_some() →
23588        //     validate() fails with
23589        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
23590        //     is the refused declared-but-inert shape on non-Sharded-
23591        //     family arms.
23592        //   * !variant.requires_shard_key() && shard_key.is_none() →
23593        //     validate() passes; the paired shape is the sole
23594        //     non-`requires_shard_key` arm-family accepted shape.
23595        //
23596        // The compile-time-exhaustive `match p.estrategia()` dispatch at
23597        // [`AplicacaoSpec::validate_placement`] preserves its structural
23598        // arm-fan (a future arm addition still surfaces a build-time
23599        // exhaustiveness error there); this pin closes the semantic loop
23600        // between the arm-fan's shape-gate cascades and the substrate-
23601        // canonical predicate every downstream consumer of the paired
23602        // shape reads through. Fail-before-pass-after locally verified by
23603        // mutating the predicate's `Sharded => true` arm to `false` — the
23604        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
23605        // `validate() must pass` assertion; restoring passes. Same "close
23606        // the loop between the typed predicate and the runtime behavior"
23607        // discipline as the sibling
23608        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
23609        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
23610        // per-arm classifier axis.
23611        for variant in [
23612            PlacementStrategy::SingleNode,
23613            PlacementStrategy::Replicated,
23614            PlacementStrategy::Sharded,
23615        ] {
23616            for present in [false, true] {
23617                let mut spec = three_member_spec();
23618                spec.placement.estrategia = variant;
23619                spec.placement.shard_key = present.then(|| "tenantId".into());
23620                let expects_ok = variant.requires_shard_key() == present;
23621                let result = spec.validate();
23622                match (expects_ok, &result) {
23623                    (true, Ok(())) => {}
23624                    (false, Err(err)) => {
23625                        // Cross-check the refusal diagnostic names the
23626                        // right cell of the four-cell shape witness — the
23627                        // `requires_shard_key && !present` cell must trip
23628                        // [`AplicacaoError::ShardedWithoutKey`]; the
23629                        // `!requires_shard_key && present` cell must trip
23630                        // [`AplicacaoError::ShardKeyOnNonSharded`].
23631                        match (variant.requires_shard_key(), present, err) {
23632                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
23633                            (
23634                                false,
23635                                true,
23636                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
23637                            ) => {
23638                                assert_eq!(
23639                                    *e, variant,
23640                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
23641                                     the paired PlacementStrategy",
23642                                );
23643                            }
23644                            _ => panic!(
23645                                "unexpected refusal for estrategia={variant:?} \
23646                                 present={present}: {err:?}"
23647                            ),
23648                        }
23649                    }
23650                    (true, Err(err)) => panic!(
23651                        "validate() must pass for estrategia={variant:?} \
23652                         present={present} (requires_shard_key={} == present={present}), \
23653                         got {err:?}",
23654                        variant.requires_shard_key(),
23655                    ),
23656                    (false, Ok(())) => panic!(
23657                        "validate() must fail for estrategia={variant:?} \
23658                         present={present} (requires_shard_key={} != present={present})",
23659                        variant.requires_shard_key(),
23660                    ),
23661                }
23662            }
23663        }
23664    }
23665
23666    #[test]
23667    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
23668        // Pin the M3 diagnostic template routes through the typed
23669        // [`PlacementStrategy`] Display byte-string (rebound from the
23670        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
23671        // routes emitted identical bytes (the `Debug` derive on a
23672        // unit variant emits the variant name verbatim, exactly what
23673        // `as_str` returns), but the two paths were structurally
23674        // independent — a future `#[serde(rename_all = "…")]`
23675        // attribute or variant rename would coordinate the wire /
23676        // `Display` / `as_str` triple through the lifted const but
23677        // leave the `Debug` route on the compiler-derived variant name,
23678        // silently desynchronizing the diagnostic byte-string from the
23679        // wire byte-string. Rebinding the template onto `Display`
23680        // ties the diagnostic to the same lifted
23681        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
23682        // emits — drift becomes structurally impossible. Pin the
23683        // byte-string here so a future edit that reverts the template
23684        // to `{estrategia:?}` is caught at caixa-core test time, not
23685        // at consumer dispatch time.
23686        for (variant, expected_scalar) in [
23687            (
23688                PlacementStrategy::SingleNode,
23689                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
23690            ),
23691            (
23692                PlacementStrategy::Replicated,
23693                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
23694            ),
23695            (
23696                PlacementStrategy::Sharded,
23697                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
23698            ),
23699        ] {
23700            let err = AplicacaoError::PlacementWithoutClusters {
23701                estrategia: variant,
23702            };
23703            let msg = err.to_string();
23704            assert!(
23705                msg.starts_with(&format!(":placement {expected_scalar} requires")),
23706                "PlacementWithoutClusters diagnostic for {variant:?} must open \
23707                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
23708            );
23709        }
23710    }
23711
23712    #[test]
23713    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
23714        // Peer of
23715        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
23716        // on the second M3 diagnostic that carries the typed
23717        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
23718        // diagnostics now route the strategy scalar through the same
23719        // [`std::fmt::Display`] surface, tying the diagnostic
23720        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
23721        // const set the wire format also emits. The two non-Sharded
23722        // arms are exercised here (the diagnostic exists to flag a
23723        // `:shard-key` slot the current strategy will never consume);
23724        // the peer `Sharded` arm never reaches this diagnostic (the
23725        // `Sharded` strategy consumes `:shard-key` — the
23726        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
23727        // slot instead).
23728        for (variant, expected_scalar) in [
23729            (
23730                PlacementStrategy::SingleNode,
23731                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
23732            ),
23733            (
23734                PlacementStrategy::Replicated,
23735                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
23736            ),
23737        ] {
23738            let err = AplicacaoError::ShardKeyOnNonSharded {
23739                estrategia: variant,
23740                shard_key: "$tenantId".into(),
23741            };
23742            let msg = err.to_string();
23743            assert!(
23744                msg.starts_with(&format!(":placement {expected_scalar} carries")),
23745                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
23746                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
23747            );
23748        }
23749    }
23750
23751    #[test]
23752    fn placement_strategy_all_enumerates_every_variant_once() {
23753        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
23754        // exhaustive-iteration surface: every variant appears exactly
23755        // once, and the slice length matches the arm count of the
23756        // closed set. Every consumer that walks the accepted-strategy
23757        // set (a future `feira app placement --list` CLI-side surfacing,
23758        // a future M4 admission-webhook's rejection body naming the
23759        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
23760        // reverse-projection consumers that iterate the accept-set for
23761        // a "did you mean" hint) reads through this slice, so a future
23762        // variant addition (an `Anycast` mesh-anycast arm the
23763        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
23764        // grows the enum but forgets to grow [`Self::ALL`] silently
23765        // truncates every downstream consumer's accept-set at the same
23766        // pre-addition boundary — this pin fails at caixa-core build
23767        // time on the pairwise-distinct + arm-count invariants.
23768        //
23769        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
23770        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
23771        // pins on the peer closed-set typed-enum axes.
23772        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
23773        assert_eq!(
23774            all.len(),
23775            3,
23776            "PlacementStrategy::ALL must enumerate every variant of the \
23777             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
23778        );
23779        for (i, a) in all.iter().enumerate() {
23780            for (j, b) in all.iter().enumerate() {
23781                if i != j {
23782                    assert_ne!(
23783                        a, b,
23784                        "PlacementStrategy::ALL must carry every variant exactly \
23785                         once — got duplicate {a:?} at indices {i} and {j}"
23786                    );
23787                }
23788            }
23789        }
23790        for variant in [
23791            PlacementStrategy::SingleNode,
23792            PlacementStrategy::Replicated,
23793            PlacementStrategy::Sharded,
23794        ] {
23795            assert!(
23796                all.contains(&variant),
23797                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
23798                 addition that grows the enum but forgets to grow the ALL slice \
23799                 silently truncates every downstream consumer's accept-set at the \
23800                 pre-addition boundary"
23801            );
23802        }
23803    }
23804
23805    #[test]
23806    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
23807        // Fail-before-pass-after pin on the forward accept-set of the
23808        // [`PlacementStrategy::from_wire`] reverse projection: every
23809        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
23810        // constant the [`PlacementStrategy::as_str`] emitter walks
23811        // parses back to its paired variant. Any future arm addition
23812        // that grows the emitter's `as_str` match but forgets to grow
23813        // the parser's `from_str` match silently splits the two halves
23814        // of the round-trip — the wire byte-string one non-serde
23815        // consumer parses from the one the emitter wrote — with the
23816        // failure surfacing at parse time far from the rebrand commit.
23817        // Pinning the three-arm accept-set here catches the drift at
23818        // caixa-core build time.
23819        //
23820        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
23821        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
23822        // closed-set typed-enum `str → Self` axes.
23823        for (wire, expected) in [
23824            (
23825                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
23826                PlacementStrategy::SingleNode,
23827            ),
23828            (
23829                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
23830                PlacementStrategy::Replicated,
23831            ),
23832            (
23833                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
23834                PlacementStrategy::Sharded,
23835            ),
23836        ] {
23837            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
23838                panic!(
23839                    "PlacementStrategy::from_wire({wire:?}) must accept every \
23840                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
23841                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
23842                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
23843                )
23844            });
23845            assert_eq!(
23846                parsed, expected,
23847                "PlacementStrategy::from_wire({wire:?}) must return \
23848                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
23849            );
23850        }
23851    }
23852
23853    #[test]
23854    fn placement_strategy_from_wire_round_trips_through_as_str() {
23855        // Fail-before-pass-after pin on the closed round-trip between
23856        // the forward [`PlacementStrategy::as_str`] emitter and the
23857        // reverse [`PlacementStrategy::from_wire`] parser: for every
23858        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
23859        // output must return exactly the same variant. Any per-arm
23860        // divergence — a future arm added to `as_str` but not
23861        // `from_str`, an accidental copy-paste flip in one but not the
23862        // other — silently splits the emit and parse halves and the
23863        // failure surfaces at consumer parse time far from the drift
23864        // site. The `ALL`-iterating shape means a future variant
23865        // addition picks up the coverage by construction.
23866        //
23867        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
23868        // [`crate::CaixaKind::from_wire`] and the
23869        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
23870        // sibling round-trip pin on [`RateLimitUnit`].
23871        for &variant in PlacementStrategy::ALL {
23872            let wire = variant.as_str();
23873            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
23874                panic!(
23875                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
23876                     must be Some({variant:?}) — the two halves of the round-trip \
23877                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
23878                     got None on wire byte-string {wire:?}"
23879                )
23880            });
23881            assert_eq!(
23882                parsed, variant,
23883                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
23884                 must round-trip to the same variant; got {parsed:?}"
23885            );
23886        }
23887    }
23888
23889    #[test]
23890    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
23891        // Fail-before-pass-after pin on the closed-set refusal
23892        // discipline of [`PlacementStrategy::from_wire`]: every
23893        // byte-string outside the three-arm accept-set returns `None`
23894        // rather than silently collapsing onto the [`Default`]
23895        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
23896        // exercised here sweeps the load-bearing drift shapes: the
23897        // empty string (a stripped serde-attribute drift), an all-
23898        // whitespace string (the canonical text-editor accidental
23899        // padding shape), the lowercased kebab-case forms a future
23900        // `#[serde(rename_all = "kebab-case")]` attribute would emit
23901        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
23902        // coincidentally match the accepted canonical scalars, so only
23903        // `"single-node"` fires as a refusal, but pinning the case-
23904        // sensitivity of the accepted arms via the peer [`SingleNode`]
23905        // assertion in the round-trip pin makes the discipline
23906        // structurally clear), the lowercased single-word forms
23907        // (`"singlenode"`), the padded canonical scalar
23908        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
23909        // (`"Sharded\n"`), and a pointer-different `&'static str` that
23910        // happens to alias a canonical byte-string by content but not
23911        // by identity (validated implicitly by the emitter's routing
23912        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
23913        // identity a paired [`crate::assert_str_reexport_identity`] pin
23914        // in caixa-core's per-const declaration surface would catch).
23915        //
23916        // Peer of the sibling
23917        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
23918        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
23919        for bad in [
23920            "",
23921            " ",
23922            "\n",
23923            "\t",
23924            "single-node",
23925            "singlenode",
23926            "SingleNodes",
23927            "single_node",
23928            "single node",
23929            "SINGLENODE",
23930            "SingleNode ",
23931            " SingleNode",
23932            " Sharded ",
23933            "Sharded\n",
23934            "replicated ",
23935            "sharded",
23936            "REPLICATED",
23937            "Anycast",
23938            "Global",
23939            "?",
23940        ] {
23941            assert!(
23942                PlacementStrategy::from_wire(bad).is_none(),
23943                "PlacementStrategy::from_wire({bad:?}) must return None — the \
23944                 parser's accept-set is exactly the three PlacementStrategy::as_str \
23945                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
23946                 is outside that closed set"
23947            );
23948        }
23949    }
23950
23951    #[test]
23952    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
23953        // Fail-before-pass-after pin on the third path of the four-path
23954        // convergence: `from_str` (the reverse projection) inverts the
23955        // `Serialize` derive's wire byte-string on every variant.
23956        // Together with the pre-existing three-path convergence
23957        // (`Display` + `as_str` + `Serialize` all resolve to the same
23958        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
23959        // the peer
23960        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
23961        // this closes the round-trip: the wire byte-string the
23962        // `Serialize` derive emits parses back to the same variant
23963        // through `from_str`, so any future serde-attribute or variant-
23964        // rename drift on the emit half now surfaces as a matched drift
23965        // on the parse half at caixa-core build time — the two halves
23966        // migrate as a unit through the lifted consts on any future
23967        // rename, and the round-trip cannot silently split.
23968        //
23969        // Peer of the sibling
23970        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
23971        // wire-format pin — extends the three-path convergence
23972        // (`Display` + `as_str` + `Serialize`) onto the fourth path
23973        // (`from_str`), closing the `str ↔ Self` round-trip on the
23974        // M3 `:placement :estrategia` closed-set axis.
23975        for &variant in PlacementStrategy::ALL {
23976            let wire = serde_json::to_string(&variant).unwrap();
23977            let unquoted = wire
23978                .strip_prefix('"')
23979                .and_then(|s| s.strip_suffix('"'))
23980                .expect("serialized PlacementStrategy is a JSON string");
23981            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
23982                panic!(
23983                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
23984                     Serialize derive's wire byte-string for \
23985                     PlacementStrategy::{variant:?} — the four-path convergence \
23986                     (Display + as_str + Serialize + from_str) resolves through \
23987                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
23988                )
23989            });
23990            assert_eq!(
23991                parsed, variant,
23992                "PlacementStrategy::from_wire of the Serialize derive's wire \
23993                 byte-string for PlacementStrategy::{variant:?} must round-trip \
23994                 to the same variant; got {parsed:?}"
23995            );
23996        }
23997    }
23998
23999    #[test]
24000    fn placement_strategy_try_from_str_routes_through_from_wire_accessor() {
24001        // Fail-before-pass-after byte-parity pin on the newly lifted
24002        // `impl TryFrom<&str> for PlacementStrategy` — asserts the
24003        // standard-library trait impl and the substrate-primitive
24004        // [`PlacementStrategy::from_wire`] `Option<Self>` accessor
24005        // resolve to the same three-arm accept-set across every arm the
24006        // exhaustive [`PlacementStrategy::ALL`] slice enumerates. Any
24007        // future silent detour that routes the trait impl through a
24008        // divergent projection (a per-arm inline `match s { "SingleNode"
24009        // => Ok(Self::SingleNode), … }` re-inlining that opens a
24010        // compile-time link to the un-lifted arm-literal, a stray
24011        // `#[serde(rename_all = "…")]` attribute drift that silently
24012        // splits the wire byte-string from every consumer that reaches
24013        // for this typed dispatch) trips at caixa-core test time under
24014        // `assert_eq!` rather than at a downstream `impl TryFrom<&str>`-
24015        // bound consumer's silent split. Sweeps every one of the three
24016        // arms [`PlacementStrategy::ALL`] carries so no arm's projection
24017        // is covered only by the sibling method-named `from_wire` path.
24018        // Peer of the sibling
24019        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
24020        // (3c83606) and
24021        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
24022        // (bf33136) — extends the trait-idiomatic reverse-projection
24023        // axis onto the first M3-mesh-primitive-defining slot enum on
24024        // the caixa surface.
24025        for &variant in PlacementStrategy::ALL {
24026            let wire = variant.as_str();
24027            assert_eq!(
24028                <PlacementStrategy as TryFrom<&str>>::try_from(wire),
24029                Ok(variant),
24030                "TryFrom<&str> impl on PlacementStrategy must round-trip \
24031                 PlacementStrategy::{variant:?}.as_str() = {wire:?} back to \
24032                 Ok(PlacementStrategy::{variant:?}) — divergence from \
24033                 PlacementStrategy::from_wire signals a silent detour off \
24034                 the substrate-primitive accessor"
24035            );
24036            assert_eq!(
24037                <PlacementStrategy as TryFrom<&str>>::try_from(wire).ok(),
24038                PlacementStrategy::from_wire(wire),
24039                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
24040                 PlacementStrategy::from_wire on the same input"
24041            );
24042        }
24043    }
24044
24045    #[test]
24046    fn placement_strategy_try_from_str_rejects_unknown_byte_strings() {
24047        // Rejection witness on the `impl TryFrom<&str> for
24048        // PlacementStrategy` — sweeps a candidate set of byte-strings
24049        // outside the three-arm camelCase-schema wire accept-set the
24050        // sibling [`PlacementStrategy::as_str`] emits and asserts every
24051        // one lands on `Err(())`, so a future accidental widening of the
24052        // trait impl's accept-set (a stray additional
24053        // `_ if s.eq_ignore_ascii_case("SingleNode") => Ok(…)` case-
24054        // fold path, a silent inclusion of a kebab-case rebrand of the
24055        // wire byte-string that would collide the two-axis split the
24056        // sibling `placement_strategy_from_wire_rejects_unknown_byte_strings`
24057        // pin makes load-bearing) trips at caixa-core test time. The
24058        // candidate set includes the empty string, whitespace-only
24059        // padding, kebab-case rebrand candidates (`"single-node"`),
24060        // snake_case rebrand candidates (`"single_node"`), uppercase
24061        // rebrand candidates, trailing/leading-whitespace-padded
24062        // canonical scalars, the trailing-newline shape, English-rebrand
24063        // candidates (`"Anycast"`, `"Global"`), and the residual `"?"`
24064        // to trip on any future accidental widening onto the sentinel
24065        // shape sibling enums use for unknown-arm diagnostics.
24066        // Peer of the sibling
24067        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
24068        // (3c83606) rejection witness.
24069        let rejected: &[&str] = &[
24070            "",
24071            " ",
24072            "\n",
24073            "\t",
24074            "single-node",
24075            "singlenode",
24076            "SingleNodes",
24077            "single_node",
24078            "single node",
24079            "SINGLENODE",
24080            "SingleNode ",
24081            " SingleNode",
24082            " Sharded ",
24083            "Sharded\n",
24084            "replicated ",
24085            "sharded",
24086            "REPLICATED",
24087            "Anycast",
24088            "Global",
24089            "?",
24090            "\"Sharded\"",
24091        ];
24092        for &input in rejected {
24093            assert_eq!(
24094                <PlacementStrategy as TryFrom<&str>>::try_from(input),
24095                Err(()),
24096                "TryFrom<&str> impl on PlacementStrategy must reject the \
24097                 non-wire byte-string {input:?} — silent acceptance signals \
24098                 an accept-set widening off the paired \
24099                 PlacementStrategy::from_wire resolver"
24100            );
24101        }
24102    }
24103
24104    #[test]
24105    fn placement_strategy_from_into_static_str_routes_through_as_str_accessor() {
24106        // Fail-before-pass-after byte-parity pin on the newly lifted
24107        // `impl From<PlacementStrategy> for &'static str` — asserts the
24108        // standard-library trait impl and the substrate-primitive
24109        // [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
24110        // to the same three-arm emit-set across every arm the exhaustive
24111        // [`PlacementStrategy::ALL`] slice enumerates. Any future silent
24112        // detour that routes the trait impl through a divergent
24113        // projection (a per-arm inline `match strategy { SingleNode =>
24114        // "SingleNode", … }` re-inlining that opens a compile-time link
24115        // to the un-lifted arm-literal outside the paired
24116        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] lifted constants,
24117        // an accidental swap onto the sibling kebab-case
24118        // [`gen_platform::Discriminant`] catalog identity that would
24119        // collide the wire axis with the dispatcher-catalog axis the
24120        // sibling [`PlacementStrategy::as_str`] doc block makes load-
24121        // bearing) trips at caixa-core test time under `assert_eq!`
24122        // rather than at a downstream `impl Into<&'static str>`-bound
24123        // consumer's silent split. Sweeps every one of the three arms
24124        // [`PlacementStrategy::ALL`] carries so no arm's projection is
24125        // covered only by the sibling method-named `as_str` /
24126        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
24127        // `<&'static str as From<PlacementStrategy>>::from` output in
24128        // three `const`-shape bindings to make the `'static` lifetime
24129        // promise a build-time invariant — a future accidental downgrade
24130        // of any of the three arms'
24131        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants to a
24132        // non-`&'static str` (a `String::leak()`-produced return, a
24133        // `Box::leak`-cast, an intermediate lifetime-erasing helper)
24134        // trips at caixa-core build time rather than at a downstream
24135        // `'static`-bound consumer. Peer of the sibling
24136        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
24137        // (523157d) /
24138        // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
24139        // (9fb37d0) /
24140        // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
24141        // (edb827b) /
24142        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
24143        // (c189a6f) pins on the sibling closed-set typed-enum forward-
24144        // projection axes — extends the trait-idiomatic forward-
24145        // projection axis onto the fifth closed-set fieldless typed
24146        // enum on the caixa surface (the M3-mesh-primitive-defining
24147        // `:placement :estrategia` axis, first-of-many on the M3 mesh
24148        // slot family the caixa-mesh renderer keys off end-to-end).
24149        const SINGLE_NODE: &str = PlacementStrategy::SingleNode.as_str();
24150        const REPLICATED: &str = PlacementStrategy::Replicated.as_str();
24151        const SHARDED: &str = PlacementStrategy::Sharded.as_str();
24152        for &variant in PlacementStrategy::ALL {
24153            let via_trait: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
24154            let via_method: &'static str = variant.as_str();
24155            assert_eq!(
24156                via_trait, via_method,
24157                "From<PlacementStrategy> for &'static str impl must \
24158                 round-trip PlacementStrategy::{variant:?} to the same \
24159                 lifted M3_PLACEMENT_ESTRATEGIA_* const \
24160                 PlacementStrategy::as_str returns — divergence signals \
24161                 a silent detour off the substrate-primitive accessor"
24162            );
24163            let via_into: &'static str = variant.into();
24164            assert_eq!(
24165                via_into, via_method,
24166                "Into<&'static str>::into on PlacementStrategy::{variant:?} \
24167                 must byte-equal PlacementStrategy::as_str on the same \
24168                 input — the blanket-derived Into shape must resolve to \
24169                 the same as_str dispatch as the explicit From impl"
24170            );
24171        }
24172        assert_eq!(
24173            [SINGLE_NODE, REPLICATED, SHARDED],
24174            [
24175                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
24176                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
24177                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
24178            ],
24179            "const-context PlacementStrategy::as_str must resolve to the \
24180             three lifted M3_PLACEMENT_ESTRATEGIA_* consts — a future \
24181             accidental downgrade of any arm to a non-const or non-static \
24182             byte-string breaks the `&'static str`-lifetime promise the \
24183             paired From<PlacementStrategy> for &'static str impl carries \
24184             by construction"
24185        );
24186    }
24187
24188    #[test]
24189    fn placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
24190        // Cross-axis partition pin: the paired trait-idiomatic
24191        // `From<PlacementStrategy> for &'static str` forward projection
24192        // and the method-named [`PlacementStrategy::as_str`] forward
24193        // projection must resolve identically on *every* arm, not just
24194        // the ones named in the primary byte-parity pin above. Sweeps
24195        // every [`PlacementStrategy::ALL`] arm and asserts the trait's
24196        // `From::from` output byte-equals the method-named accessor's
24197        // return-value on each, locking the two forward-projection paths
24198        // together by construction so any future detour (a stray `From`
24199        // special-case that lands on a divergent per-arm literal outside
24200        // the paired `as_str` dispatch, a hypothetical rebrand touching
24201        // one axis without the other) trips at caixa-core test time.
24202        // Peer of the sibling forward-projection partition pins
24203        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
24204        // (523157d) /
24205        // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
24206        // (9fb37d0) /
24207        // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
24208        // (edb827b) /
24209        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
24210        // (c189a6f) — extends the round-trip discipline onto the fifth
24211        // closed-set typed enum on the caixa surface, closing the two-way
24212        // `Self ↔ &'static str` round-trip on the trait-idiomatic pair
24213        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
24214        // well as the pre-existing method-named pair (`as_str` +
24215        // `from_wire`).
24216        for &variant in PlacementStrategy::ALL {
24217            let via_trait: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
24218            let via_method: &'static str = variant.as_str();
24219            assert_eq!(
24220                via_trait, via_method,
24221                "From<PlacementStrategy> for &'static str and \
24222                 PlacementStrategy::as_str must resolve identically on \
24223                 PlacementStrategy::{variant:?} — divergence signals the \
24224                 two forward-projection paths have drifted onto different \
24225                 emit-sets"
24226            );
24227        }
24228        // Round-trip witness: every arm's forward `From` output re-parses
24229        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
24230        // to the original variant. Closes the two-way `PlacementStrategy
24231        // ↔ &'static str` round-trip on the trait-idiomatic axis pair
24232        // directly (no wire-vocab intermediate the peer [`CaixaKind`]
24233        // axis pair requires — the emit-side
24234        // [`PlacementStrategy::as_str`] and the parse-side
24235        // [`PlacementStrategy::from_wire`] dispatch on the same three
24236        // lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants
24237        // by construction), mirroring the pre-existing method-named
24238        // `as_str` + `from_wire` round-trip on the substrate-primitive
24239        // axis pair.
24240        for &variant in PlacementStrategy::ALL {
24241            let emitted: &'static str = variant.into();
24242            let re_parsed: Result<PlacementStrategy, ()> =
24243                <PlacementStrategy as TryFrom<&str>>::try_from(emitted);
24244            assert_eq!(
24245                re_parsed,
24246                Ok(variant),
24247                "trait-idiomatic axis pair must round-trip \
24248                 PlacementStrategy::{variant:?} through `.into::<&'static \
24249                 str>()` and back through `TryFrom<&str>` — a break \
24250                 signals the forward-emit and reverse-parse axes have \
24251                 drifted onto different vocabularies"
24252            );
24253        }
24254    }
24255
24256    #[test]
24257    fn placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
24258        // Fail-before-pass-after byte-parity pin on the newly lifted
24259        // `impl From<&PlacementStrategy> for &'static str` — asserts
24260        // the borrowed-input standard-library trait impl and the
24261        // substrate-primitive [`PlacementStrategy::as_str`] `pub const
24262        // fn` accessor resolve to the same three-arm emit-set across
24263        // every arm the exhaustive [`PlacementStrategy::ALL`] slice
24264        // enumerates. Rust's `From` trait does not auto-derive the
24265        // borrowed-input sibling from a paired owned-input impl (no
24266        // `impl<T, U> From<&T> for U where T: Copy, U: From<T>`
24267        // blanket in `core`), so the borrowed-input axis is a distinct
24268        // trait-idiomatic surface that a `.iter().map(Into::into)`
24269        // shape over [`PlacementStrategy::ALL`] (whose iterator yields
24270        // `&PlacementStrategy`, not `PlacementStrategy`) reaches
24271        // through this impl and no other — the paired owned-input
24272        // [`From<PlacementStrategy>`] impl requires an explicit
24273        // `.copied()` / dereference before the trait fires.
24274        // Materializes the `<&'static str as
24275        // From<&PlacementStrategy>>::from` output in a `const`-shape
24276        // binding to make the `'static` lifetime promise a build-time
24277        // invariant. Peer of the sibling
24278        // [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24279        // (64aa742) /
24280        // [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24281        // (5ab993a) /
24282        // [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24283        // (807b0b5) /
24284        // [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24285        // (e941836) /
24286        // [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24287        // (842c7f3) pins on the sibling closed-set typed-enum
24288        // borrowed-input forward-projection axes — extends the
24289        // borrowed-input axis onto the first M3-mesh-primitive-defining
24290        // closed-set typed enum on the caixa surface.
24291        const SINGLE_NODE: &str = PlacementStrategy::SingleNode.as_str();
24292        const REPLICATED: &str = PlacementStrategy::Replicated.as_str();
24293        const SHARDED: &str = PlacementStrategy::Sharded.as_str();
24294        for variant in PlacementStrategy::ALL {
24295            let via_trait: &'static str = <&'static str as From<&PlacementStrategy>>::from(variant);
24296            let via_method: &'static str = variant.as_str();
24297            assert_eq!(
24298                via_trait, via_method,
24299                "From<&PlacementStrategy> for &'static str impl must \
24300                 round-trip &PlacementStrategy::{variant:?} to the same \
24301                 lifted M3_PLACEMENT_ESTRATEGIA_* const \
24302                 PlacementStrategy::as_str returns — divergence signals \
24303                 a silent detour off the substrate-primitive accessor"
24304            );
24305            let via_into: &'static str = variant.into();
24306            assert_eq!(
24307                via_into, via_method,
24308                "Into<&'static str>::into on &PlacementStrategy::{variant:?} \
24309                 must byte-equal PlacementStrategy::as_str on the same \
24310                 input — the blanket-derived Into shape must resolve to \
24311                 the same as_str dispatch as the explicit From impl"
24312            );
24313        }
24314        assert_eq!(
24315            [SINGLE_NODE, REPLICATED, SHARDED],
24316            [
24317                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
24318                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
24319                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
24320            ],
24321            "const-context PlacementStrategy::as_str must resolve to the \
24322             three lifted M3_PLACEMENT_ESTRATEGIA_* consts — the \
24323             borrowed-input From<&PlacementStrategy> for &'static str \
24324             impl inherits its `'static` lifetime promise from the same \
24325             accessor the owned-input sibling routes through"
24326        );
24327    }
24328
24329    #[test]
24330    fn placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
24331        // Cross-axis partition pin: the paired trait-idiomatic
24332        // owned-input `From<PlacementStrategy> for &'static str`
24333        // (afa3562 campaign-shape) and borrowed-input
24334        // `From<&PlacementStrategy> for &'static str` (this lift)
24335        // forward projections must resolve identically on every arm,
24336        // locking the two input-shape paths together so any future
24337        // detour trips at caixa-core test time. Then a witness that a
24338        // `.iter().map(Into::into)` pipe over
24339        // [`PlacementStrategy::ALL`] (whose iterator yields
24340        // `&PlacementStrategy`) materializes the three-arm accept-set
24341        // through the borrowed-input axis alone — the exact shape a
24342        // future M4 admission-webhook rejection body's accepted-set
24343        // enumeration, a future substrate-wide per-arm diagnostic
24344        // column, or a
24345        // `HashMap::<&'static str, PlacementStrategy>::from_iter(
24346        //     PlacementStrategy::ALL.iter().map(|s| (s.into(), *s)))`-
24347        // style per-strategy lookup reaches through — closing the
24348        // two-way owned/borrowed input-shape symmetry on the M3 slot
24349        // enum's forward-projection trait-idiomatic axis. Peer of the
24350        // sibling
24351        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24352        // (64aa742) /
24353        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24354        // (5ab993a) /
24355        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24356        // (807b0b5) /
24357        // [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24358        // (e941836) /
24359        // [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24360        // (842c7f3) partition pins on the sibling closed-set typed-enum
24361        // discriminator axes — extends the borrowed-input axis
24362        // discipline onto the first M3-mesh-primitive-defining closed-
24363        // set typed enum on the caixa surface (the `:placement
24364        // :estrategia` axis). Also closes the direct two-way `&Self →
24365        // &'static str → Self` round-trip via the paired
24366        // [`TryFrom<&str>`] axis — unlike the peer [`crate::CaixaKind`]
24367        // axis pair (whose forward `From` emits lowercase Portuguese
24368        // diagnostic bytes while the reverse `TryFrom` parses
24369        // `PascalCase` wire bytes, forcing the round-trip through an
24370        // intermediate wire-vocab hop), the
24371        // [`PlacementStrategy::as_str`] emit and
24372        // [`PlacementStrategy::from_wire`] parse share the same
24373        // `PascalCase` vocabulary by construction, so the borrowed-
24374        // input forward axis and the reverse axis compose directly.
24375        for &variant in PlacementStrategy::ALL {
24376            let owned: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
24377            let borrowed: &'static str = <&'static str as From<&PlacementStrategy>>::from(&variant);
24378            assert_eq!(
24379                owned, borrowed,
24380                "From<PlacementStrategy> and From<&PlacementStrategy> \
24381                 for &'static str must resolve identically on \
24382                 PlacementStrategy::{variant:?} — divergence signals \
24383                 the owned-input and borrowed-input forward-projection \
24384                 paths have drifted onto different emit-sets"
24385            );
24386        }
24387        let via_iter: Vec<&'static str> = PlacementStrategy::ALL.iter().map(Into::into).collect();
24388        let via_method: Vec<&'static str> =
24389            PlacementStrategy::ALL.iter().map(|s| s.as_str()).collect();
24390        assert_eq!(
24391            via_iter, via_method,
24392            "`.iter().map(Into::into)` over PlacementStrategy::ALL must \
24393             byte-equal `.iter().map(|s| s.as_str())` on every arm — \
24394             the borrowed-input `From<&PlacementStrategy> for &'static \
24395             str` axis is what makes the `.iter().map(Into::into)` \
24396             shape route through the substrate-primitive \
24397             `PlacementStrategy::as_str` accessor rather than through a \
24398             per-call-site `.copied()` / dereference detour"
24399        );
24400        for variant in PlacementStrategy::ALL {
24401            let emitted: &'static str = variant.into();
24402            let re_parsed: Result<PlacementStrategy, ()> =
24403                <PlacementStrategy as TryFrom<&str>>::try_from(emitted);
24404            assert_eq!(
24405                re_parsed,
24406                Ok(*variant),
24407                "trait-idiomatic borrowed-input forward-projection + \
24408                 reverse-projection axis pair must round-trip \
24409                 &PlacementStrategy::{variant:?} through `.into::<&'static \
24410                 str>()` (via the borrowed-input axis) and back through \
24411                 `TryFrom<&str>` — a break signals the borrowed-input \
24412                 forward-emit and reverse-parse axes have drifted onto \
24413                 different vocabularies"
24414            );
24415        }
24416    }
24417
24418    #[test]
24419    fn placement_strategy_from_into_owned_string_routes_through_as_str_accessor() {
24420        // Fail-before-pass-after byte-parity pin on the newly lifted
24421        // `impl From<PlacementStrategy> for String` — asserts the
24422        // owned-`String`-returning standard-library trait impl and the
24423        // substrate-primitive [`PlacementStrategy::as_str`] `pub const
24424        // fn` accessor resolve to the same three-arm emit-set across
24425        // every arm the exhaustive [`PlacementStrategy::ALL`] slice
24426        // enumerates. Rust's standard library does not carry a blanket
24427        // `impl<T: AsRef<str>> From<T> for String` (nor an
24428        // `impl<T: fmt::Display> From<T> for String`), so the
24429        // owned-`String` forward-projection axis is a distinct trait-
24430        // idiomatic surface that a `let key: String = strategy.into();`-
24431        // shaped call site reaches through this impl and no other — the
24432        // paired sibling `From<PlacementStrategy> for &'static str` impl
24433        // forces every owned-`String` call site through an explicit
24434        // `.to_owned()` / `String::from` restatement. Peer of the
24435        // first-mover
24436        // [`crate::supervisor::tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
24437        // (7baa18a), the second-peer
24438        // [`crate::supervisor::tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
24439        // (7851725), the third-peer
24440        // [`crate::kind::tests::caixa_kind_from_into_owned_string_routes_through_as_str_accessor`]
24441        // (231a18c), the fourth-peer
24442        // [`crate::dialeto::tests::caixa_dialeto_from_into_owned_string_routes_through_as_str_accessor`]
24443        // (88942cd), and the fifth-peer
24444        // [`crate::dep::tests::dep_list_from_into_owned_string_routes_through_as_str_accessor`]
24445        // (32b0ee8) — extends the trait-idiomatic owned-`String`
24446        // forward-projection axis onto the sixth closed-set fieldless
24447        // typed enum on the caixa surface (the first
24448        // M3-mesh-primitive-defining `:placement :estrategia`
24449        // distribution-strategy axis).
24450        for &variant in PlacementStrategy::ALL {
24451            let via_trait: String = <String as From<PlacementStrategy>>::from(variant);
24452            let via_method: &'static str = variant.as_str();
24453            assert_eq!(
24454                via_trait.as_str(),
24455                via_method,
24456                "From<PlacementStrategy> for String impl must round-trip \
24457                 PlacementStrategy::{variant:?} to the same lifted \
24458                 M3_PLACEMENT_ESTRATEGIA_* const PlacementStrategy::as_str \
24459                 returns — divergence signals a silent detour off the \
24460                 substrate-primitive accessor"
24461            );
24462            let via_into: String = variant.into();
24463            assert_eq!(
24464                via_into.as_str(),
24465                via_method,
24466                "Into<String>::into on PlacementStrategy::{variant:?} must \
24467                 byte-equal PlacementStrategy::as_str on the same input — \
24468                 the blanket-derived Into shape must resolve to the same \
24469                 as_str dispatch as the explicit From impl"
24470            );
24471        }
24472    }
24473
24474    #[test]
24475    fn placement_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
24476        // Cross-axis partition pin: the paired trait-idiomatic
24477        // owned-`String` `From<PlacementStrategy> for String` (this
24478        // lift) and owned-`&'static str` `From<PlacementStrategy> for
24479        // &'static str` (afa3562) forward projections must resolve
24480        // identically on every arm, locking the two return-type-shape
24481        // paths together so any future detour trips at caixa-core test
24482        // time. Also byte-parity witness against the sibling
24483        // [`ToString::to_string`] surface routed through
24484        // [`std::fmt::Display`] — the three owned-heap-string paths
24485        // (`.into::<String>()`, `String::from`, `.to_string()`) must
24486        // resolve identically on every arm so a future consumer that
24487        // picks any of the three lands on the same three-arm lifted
24488        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] accept-set. Then
24489        // a `.iter().copied().map(String::from)` pipe witness over
24490        // [`PlacementStrategy::ALL`] that materializes the three-arm
24491        // accept-set through the owned-`String` axis alone — the exact
24492        // shape a future M4 admission-webhook rejection body composer
24493        // or a `HashMap::<String,
24494        // PlacementStrategy>::from_iter(PlacementStrategy::ALL.iter()
24495        //     .copied().map(|s| (s.into(), s)))`-style owned-key
24496        // per-strategy lookup reaches through — closing the
24497        // owned-`String` forward-projection axis's iterator-pipe shape.
24498        // Then a direct round-trip witness through the paired trait-
24499        // idiomatic reverse [`TryFrom<&str>`] axis on the
24500        // owned-`String`'s [`String::as_str`] borrow that closes the
24501        // two-way `Self → String → Self` round-trip on the trait-
24502        // idiomatic owned-`String` forward + reverse axis pair.
24503        //
24504        // Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
24505        // `From` emit lands on the lowercase Portuguese `as_str`
24506        // diagnostic vocabulary while the reverse `TryFrom<&str>`
24507        // parses the `PascalCase` `wire_name` author-surface
24508        // vocabulary, forcing the round-trip through an intermediate
24509        // [`crate::CaixaKind::wire_name`] hop), [`PlacementStrategy`]'s
24510        // [`PlacementStrategy::as_str`] emit and
24511        // [`PlacementStrategy::from_wire`] parse resolve through the
24512        // same three lifted
24513        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] consts by
24514        // construction (there is no wire/diagnostic axis split on this
24515        // enum), so the owned-`String` forward axis and the reverse
24516        // axis compose directly — matching the peer
24517        // [`crate::supervisor::RestartStrategy`] /
24518        // [`crate::supervisor::RestartPolicy`] /
24519        // [`crate::CaixaDialeto`] / [`crate::dep::DepList`]
24520        // owned-`String` axis pairs.
24521        for &variant in PlacementStrategy::ALL {
24522            let owned_string: String = <String as From<PlacementStrategy>>::from(variant);
24523            let owned_static: &'static str =
24524                <&'static str as From<PlacementStrategy>>::from(variant);
24525            assert_eq!(
24526                owned_string.as_str(),
24527                owned_static,
24528                "From<PlacementStrategy> for String and \
24529                 From<PlacementStrategy> for &'static str must resolve \
24530                 identically on PlacementStrategy::{variant:?} — \
24531                 divergence signals the owned-`String` and \
24532                 owned-`&'static str` forward-projection return-type-\
24533                 shape paths have drifted onto different emit-sets"
24534            );
24535            let via_to_string: String = variant.to_string();
24536            assert_eq!(
24537                owned_string, via_to_string,
24538                "From<PlacementStrategy> for String must byte-equal \
24539                 PlacementStrategy::to_string on \
24540                 PlacementStrategy::{variant:?} — divergence signals the \
24541                 trait-idiomatic owned-`String` forward-projection axis \
24542                 and the ToString-through-Display axis have drifted onto \
24543                 different emit-sets"
24544            );
24545        }
24546        let via_iter: Vec<String> = PlacementStrategy::ALL
24547            .iter()
24548            .copied()
24549            .map(String::from)
24550            .collect();
24551        let via_method: Vec<String> = PlacementStrategy::ALL
24552            .iter()
24553            .map(|s| s.as_str().to_owned())
24554            .collect();
24555        assert_eq!(
24556            via_iter, via_method,
24557            "`.iter().copied().map(String::from)` over \
24558             PlacementStrategy::ALL must byte-equal `.iter().map(|s| \
24559             s.as_str().to_owned())` on every arm — the owned-`String` \
24560             `From<PlacementStrategy> for String` axis is what makes the \
24561             `String::from` composition route through the substrate-\
24562             primitive `PlacementStrategy::as_str` accessor rather than \
24563             through a per-call-site `.to_owned()` / \
24564             `String::from(strategy.as_str())` detour"
24565        );
24566        for &variant in PlacementStrategy::ALL {
24567            let emitted: String = variant.into();
24568            let re_parsed: Result<PlacementStrategy, ()> =
24569                <PlacementStrategy as TryFrom<&str>>::try_from(emitted.as_str());
24570            assert_eq!(
24571                re_parsed,
24572                Ok(variant),
24573                "trait-idiomatic owned-`String` forward-projection + \
24574                 reverse-projection axis pair must round-trip \
24575                 PlacementStrategy::{variant:?} through `.into::<String>()` \
24576                 and back through `TryFrom<&str>` on the owned-`String`'s \
24577                 String::as_str borrow — a break signals the owned-\
24578                 `String` forward-emit and reverse-parse axes have \
24579                 drifted onto different vocabularies (unlike the peer \
24580                 CaixaKind axis pair, PlacementStrategy's forward emit \
24581                 and reverse parse share the same lifted \
24582                 M3_PLACEMENT_ESTRATEGIA_* consts by construction, so \
24583                 the round-trip composes directly)"
24584            );
24585        }
24586    }
24587
24588    #[test]
24589    fn placement_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
24590        // Fail-before-pass-after byte-parity pin on the newly lifted
24591        // `impl From<&PlacementStrategy> for String` — asserts the
24592        // borrowed-input owned-`String`-returning standard-library trait
24593        // impl and the substrate-primitive [`PlacementStrategy::as_str`]
24594        // `pub const fn` accessor resolve to the same three-arm emit-set
24595        // across every arm the exhaustive [`PlacementStrategy::ALL`]
24596        // slice enumerates. Rust's standard library does not carry a
24597        // blanket `impl<T: AsRef<str>> From<&T> for String` (nor an
24598        // `impl<T: fmt::Display> From<&T> for String`), so the
24599        // borrowed-input owned-`String` forward-projection axis is a
24600        // distinct trait-idiomatic surface that a
24601        // `let key: String = (&strategy).into();`-shaped call site
24602        // reaches through this impl and no other — the paired sibling
24603        // `From<PlacementStrategy> for String` impl forces every
24604        // borrowed-input call site through an explicit `Copy` deref
24605        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
24606        // `.to_string()` detour. Peer of the first-mover
24607        // [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
24608        // (579385f), the second-peer
24609        // [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
24610        // (8465740), the third-peer
24611        // [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
24612        // (e0cb617), the fourth-peer
24613        // [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
24614        // (e76436d), and the fifth-peer
24615        // [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
24616        // (d3c0d1d) — extends the trait-idiomatic borrowed-input owned-
24617        // `String` forward-projection axis onto the sixth closed-set
24618        // fieldless typed enum on the caixa surface (the first
24619        // M3-mesh-primitive-defining `:placement :estrategia`
24620        // distribution-strategy axis).
24621        for &variant in PlacementStrategy::ALL {
24622            let via_trait: String = <String as From<&PlacementStrategy>>::from(&variant);
24623            let via_method: &'static str = variant.as_str();
24624            assert_eq!(
24625                via_trait.as_str(),
24626                via_method,
24627                "From<&PlacementStrategy> for String impl must round-trip \
24628                 &PlacementStrategy::{variant:?} to the same lifted \
24629                 M3_PLACEMENT_ESTRATEGIA_* const PlacementStrategy::as_str \
24630                 returns — divergence signals a silent detour off the \
24631                 substrate-primitive accessor"
24632            );
24633            let via_into: String = (&variant).into();
24634            assert_eq!(
24635                via_into.as_str(),
24636                via_method,
24637                "Into<String>::into on &PlacementStrategy::{variant:?} \
24638                 must byte-equal PlacementStrategy::as_str on the same \
24639                 input — the blanket-derived Into shape must resolve to \
24640                 the same as_str dispatch as the explicit From impl"
24641            );
24642        }
24643    }
24644
24645    #[test]
24646    fn placement_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
24647        // Cross-axis partition pin: the newly lifted trait-idiomatic
24648        // borrowed-input owned-`String`
24649        // `From<&PlacementStrategy> for String` (this lift), the paired
24650        // owned-input owned-`String`
24651        // `From<PlacementStrategy> for String` (1154c2f), the paired
24652        // borrowed-input owned-`&'static str`
24653        // `From<&PlacementStrategy> for &'static str` (4d941d8), and the
24654        // paired owned-input owned-`&'static str`
24655        // `From<PlacementStrategy> for &'static str` (afa3562) — every
24656        // corner of the `{Self, &Self} × {&'static str, String}` 2×2
24657        // trait-idiomatic projection family — must resolve identically
24658        // on every arm, locking the four return-shape × input-shape
24659        // paths together so any future detour trips at caixa-core test
24660        // time. Also byte-parity witness against the sibling
24661        // [`ToString::to_string`] surface routed through
24662        // [`std::fmt::Display`] and a direct round-trip witness through
24663        // the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
24664        // the owned-`String`'s [`String::as_str`] borrow that closes
24665        // the two-way `&Self → String → Self` round-trip on the trait-
24666        // idiomatic borrowed-input owned-`String` forward + reverse
24667        // axis pair. Peer of the first-mover
24668        // [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
24669        // (579385f), the second-peer
24670        // [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
24671        // (8465740), the third-peer
24672        // [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
24673        // (e0cb617), the fourth-peer
24674        // [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
24675        // (e76436d), and the fifth-peer
24676        // [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
24677        // (d3c0d1d) — closes the whole `{Self, &Self} × {&'static str,
24678        // String}` 2×2 projection corner on the sixth substrate-wide
24679        // closed-set fieldless typed enum peer (the first
24680        // M3-mesh-primitive-defining `:placement :estrategia`
24681        // distribution-strategy axis, first M3 slot enum to reach the
24682        // 2×2-completion corner).
24683        //
24684        // Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
24685        // `From` emit lands on the lowercase Portuguese `as_str`
24686        // diagnostic vocabulary while the reverse `TryFrom<&str>`
24687        // parses the `PascalCase` `wire_name` author-surface
24688        // vocabulary, forcing the round-trip through an intermediate
24689        // [`crate::CaixaKind::wire_name`] hop), [`PlacementStrategy`]'s
24690        // [`PlacementStrategy::as_str`] emit and
24691        // [`PlacementStrategy::from_wire`] parse resolve through the
24692        // same three lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
24693        // consts by construction (there is no wire/diagnostic axis
24694        // split on this M3 slot enum), so the borrowed-input
24695        // owned-`String` forward axis and the reverse axis compose
24696        // directly — matching the peer
24697        // [`crate::supervisor::RestartStrategy`] /
24698        // [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`]
24699        // / [`crate::CaixaDialeto`] borrowed-input owned-`String` axis
24700        // pairs.
24701        for &variant in PlacementStrategy::ALL {
24702            let borrowed_string: String = <String as From<&PlacementStrategy>>::from(&variant);
24703            let owned_string: String = <String as From<PlacementStrategy>>::from(variant);
24704            let borrowed_static: &'static str =
24705                <&'static str as From<&PlacementStrategy>>::from(&variant);
24706            let owned_static: &'static str =
24707                <&'static str as From<PlacementStrategy>>::from(variant);
24708            assert_eq!(
24709                borrowed_string, owned_string,
24710                "From<&PlacementStrategy> for String and \
24711                 From<PlacementStrategy> for String must resolve \
24712                 identically on PlacementStrategy::{variant:?} — \
24713                 divergence signals the borrowed-input and owned-input \
24714                 owned-`String` forward-projection input-shape paths \
24715                 have drifted onto different emit-sets"
24716            );
24717            assert_eq!(
24718                borrowed_string.as_str(),
24719                borrowed_static,
24720                "From<&PlacementStrategy> for String and \
24721                 From<&PlacementStrategy> for &'static str must resolve \
24722                 identically on PlacementStrategy::{variant:?} — \
24723                 divergence signals the borrowed-input `&'static str` \
24724                 and owned-`String` return-shape paths have drifted \
24725                 onto different emit-sets"
24726            );
24727            assert_eq!(
24728                borrowed_string.as_str(),
24729                owned_static,
24730                "From<&PlacementStrategy> for String and \
24731                 From<PlacementStrategy> for &'static str must resolve \
24732                 identically on PlacementStrategy::{variant:?} — \
24733                 divergence signals a break in the diagonal corner of \
24734                 the {{Self, &Self}} × {{&'static str, String}} 2×2 \
24735                 trait-idiomatic projection family"
24736            );
24737            let via_to_string: String = variant.to_string();
24738            assert_eq!(
24739                borrowed_string, via_to_string,
24740                "From<&PlacementStrategy> for String must byte-equal \
24741                 PlacementStrategy::to_string on \
24742                 PlacementStrategy::{variant:?} — divergence signals \
24743                 the trait-idiomatic borrowed-input owned-`String` \
24744                 forward-projection axis and the ToString-through-\
24745                 Display axis have drifted onto different emit-sets"
24746            );
24747        }
24748        let via_iter: Vec<String> = PlacementStrategy::ALL.iter().map(String::from).collect();
24749        let via_method: Vec<String> = PlacementStrategy::ALL
24750            .iter()
24751            .map(|s| s.as_str().to_owned())
24752            .collect();
24753        assert_eq!(
24754            via_iter, via_method,
24755            "`.iter().map(String::from)` over PlacementStrategy::ALL — \
24756             a call site whose iteration axis holds \
24757             `&PlacementStrategy` by construction — must byte-equal \
24758             `.iter().map(|s| s.as_str().to_owned())` on every arm — \
24759             the borrowed-input owned-`String` \
24760             `From<&PlacementStrategy> for String` axis is what makes \
24761             the `String::from` composition route through the \
24762             substrate-primitive `PlacementStrategy::as_str` accessor \
24763             without a spurious `Copy` deref (which would only be \
24764             reachable through the owned-input \
24765             `From<PlacementStrategy> for String` axis by first \
24766             calling `.copied()` on the iterator)"
24767        );
24768        for &variant in PlacementStrategy::ALL {
24769            let emitted: String = (&variant).into();
24770            let re_parsed: Result<PlacementStrategy, ()> =
24771                <PlacementStrategy as TryFrom<&str>>::try_from(emitted.as_str());
24772            assert_eq!(
24773                re_parsed,
24774                Ok(variant),
24775                "trait-idiomatic borrowed-input owned-`String` \
24776                 forward-projection + reverse-projection axis pair \
24777                 must round-trip &PlacementStrategy::{variant:?} \
24778                 through `.into::<String>()` on the borrowed-input \
24779                 surface and back through `TryFrom<&str>` on the \
24780                 owned-`String`'s String::as_str borrow — a break \
24781                 signals the borrowed-input owned-`String` \
24782                 forward-emit and reverse-parse axes have drifted onto \
24783                 different vocabularies (unlike the peer CaixaKind \
24784                 axis pair, PlacementStrategy's forward emit and \
24785                 reverse parse share the same lifted \
24786                 M3_PLACEMENT_ESTRATEGIA_* consts by construction, so \
24787                 the round-trip composes directly)"
24788            );
24789        }
24790    }
24791
24792    #[test]
24793    fn placement_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
24794        // Fail-before-pass-after byte-parity pin on the newly lifted
24795        // `impl From<PlacementStrategy> for
24796        // std::borrow::Cow<'static, str>` — asserts the standard-
24797        // library trait impl and the substrate-primitive
24798        // [`super::PlacementStrategy::as_str`] `pub const fn`
24799        // accessor resolve to the same three-arm emit-set across
24800        // every arm the exhaustive [`super::PlacementStrategy::ALL`]
24801        // slice enumerates. Rust's standard library does not carry a
24802        // blanket `impl<T: AsRef<str>> From<T> for Cow<'static, str>`
24803        // (nor an `impl<T: fmt::Display> From<T> for
24804        // Cow<'static, str>`), so the `Cow<'static, str>` forward-
24805        // projection axis is a distinct trait-idiomatic surface that
24806        // a `let key: Cow<'static, str> = strategy.into();`-shaped
24807        // call site reaches through this impl and no other — the
24808        // paired sibling `From<PlacementStrategy> for &'static str`
24809        // and `From<PlacementStrategy> for String` impls force every
24810        // `Cow<'static, str>`-parameterized call site through a
24811        // `Cow::Borrowed(strategy.as_str())` /
24812        // `Cow::Owned(strategy.to_string())` composition whose type
24813        // bounds have no compile-time link back to the substrate
24814        // primitive.
24815        //
24816        // Also asserts the projection lands on the zero-alloc
24817        // [`std::borrow::Cow::Borrowed`] arm (not the
24818        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
24819        // [`super::PlacementStrategy::as_str`] accessor's
24820        // `&'static str` return lifetime by construction (each match
24821        // arm resolves to one of the three lifted
24822        // [`super::render::M3_PLACEMENT_ESTRATEGIA_*`] `pub const
24823        // &str` values) makes the borrowed arm the type-correct
24824        // projection with no runtime allocation. Any future silent
24825        // detour that routes the impl through the owned arm trips at
24826        // caixa-core test time under the
24827        // [`std::borrow::Cow::Borrowed`] discriminator witness
24828        // rather than at a downstream `Cow<'static, str>`-bound
24829        // consumer's silent allocation.
24830        //
24831        // Second M3-mesh-primitive-defining peer on the substrate-
24832        // wide trait-idiomatic [`std::borrow::Cow<'static, str>`]
24833        // forward-projection campaign — extends the axis off the
24834        // first M3-mesh-primitive peer (the [`super::WitShape`]
24835        // `:contratos :wit` census-label axis: 8634dec owned-input +
24836        // 25690ef borrowed-input) onto the second M3-slot-enum peer,
24837        // ahead of the sibling [`super::RateLimitUnit`] whose
24838        // Cow<'static, str> axis remains a future target.
24839        for &variant in PlacementStrategy::ALL {
24840            let via_trait: std::borrow::Cow<'static, str> =
24841                <std::borrow::Cow<'static, str> as From<PlacementStrategy>>::from(variant);
24842            let via_method: &'static str = variant.as_str();
24843            assert_eq!(
24844                via_trait.as_ref(),
24845                via_method,
24846                "From<PlacementStrategy> for Cow<'static, str> impl \
24847                 must round-trip PlacementStrategy::{variant:?} to \
24848                 the same lifted M3_PLACEMENT_ESTRATEGIA_* const \
24849                 PlacementStrategy::as_str returns — divergence \
24850                 signals a silent detour off the substrate-primitive \
24851                 accessor"
24852            );
24853            assert!(
24854                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
24855                "From<PlacementStrategy> for Cow<'static, str> impl \
24856                 must land on the zero-alloc Cow::Borrowed arm on \
24857                 PlacementStrategy::{variant:?} — a Cow::Owned \
24858                 outcome signals the projection has silently \
24859                 allocated where the substrate-primitive \
24860                 PlacementStrategy::as_str `&'static str` return \
24861                 makes the borrowed arm the type-correct projection"
24862            );
24863            let via_into: std::borrow::Cow<'static, str> = variant.into();
24864            assert_eq!(
24865                via_into.as_ref(),
24866                via_method,
24867                "Into<Cow<'static, str>>::into on \
24868                 PlacementStrategy::{variant:?} must byte-equal \
24869                 PlacementStrategy::as_str on the same input — the \
24870                 blanket-derived Into shape must resolve to the same \
24871                 as_str dispatch as the explicit From impl"
24872            );
24873            assert!(
24874                matches!(via_into, std::borrow::Cow::Borrowed(_)),
24875                "Into<Cow<'static, str>>::into on \
24876                 PlacementStrategy::{variant:?} must land on the \
24877                 zero-alloc Cow::Borrowed arm — the blanket-derived \
24878                 Into shape must resolve to the same Cow::Borrowed \
24879                 dispatch as the explicit From impl"
24880            );
24881        }
24882    }
24883
24884    #[test]
24885    fn placement_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
24886        // Cross-axis partition pin: the newly lifted trait-idiomatic
24887        // `From<PlacementStrategy> for std::borrow::Cow<'static, str>`
24888        // (this lift), the paired owned-input `From<PlacementStrategy>
24889        // for &'static str`, and the paired owned-input
24890        // `From<PlacementStrategy> for String` forward projections
24891        // must resolve identically on every arm, locking the three
24892        // return-shape paths together by construction so any future
24893        // detour trips at caixa-core test time. Also byte-parity
24894        // witness against the sibling [`ToString::to_string`] surface
24895        // routed through [`std::fmt::Display`] — every owned-heap-
24896        // string path (the `Cow::Owned` promotion of this axis's
24897        // `.into_owned()`, `From<PlacementStrategy> for String`, and
24898        // `.to_string()`) resolves to the same three-arm lifted
24899        // M3_PLACEMENT_ESTRATEGIA_* byte-string per arm.
24900        //
24901        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
24902        // witness over [`super::PlacementStrategy::ALL`] that
24903        // materializes the three-arm accept-set through the
24904        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
24905        // shape a future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
24906        // admission-webhook rejection body's accepted-`:placement
24907        // :estrategia` enumeration, a future substrate-wide per-arm
24908        // diagnostic surface whose typing rules out the sibling
24909        // [`AsRef<str>`] borrowed return, or a future per-arm
24910        // placement-strategy emitter that binds through a
24911        // [`Cow<'static, str>`] boundary reaches through — closing
24912        // the composable-projection axis on the second
24913        // M3-mesh-primitive-defining closed-set fieldless typed enum
24914        // peer on the caixa surface. The pipe witness also pins the
24915        // zero-alloc discipline: every element in the collected
24916        // vector satisfies the [`std::borrow::Cow::Borrowed`] arm
24917        // predicate, so a future accidental silent-allocation
24918        // regression on the pipe's iteration axis is a caixa-core-
24919        // test-time failure.
24920        for &variant in PlacementStrategy::ALL {
24921            let via_cow: std::borrow::Cow<'static, str> =
24922                <std::borrow::Cow<'static, str> as From<PlacementStrategy>>::from(variant);
24923            let via_static: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
24924            let via_string: String = <String as From<PlacementStrategy>>::from(variant);
24925            assert_eq!(
24926                via_cow.as_ref(),
24927                via_static,
24928                "From<PlacementStrategy> for Cow<'static, str> and \
24929                 From<PlacementStrategy> for &'static str must \
24930                 resolve identically on PlacementStrategy::\
24931                 {variant:?} — divergence signals the \
24932                 Cow<'static, str> and &'static str return-shape \
24933                 paths have drifted onto different emit-sets"
24934            );
24935            assert_eq!(
24936                via_cow.as_ref(),
24937                via_string.as_str(),
24938                "From<PlacementStrategy> for Cow<'static, str> and \
24939                 From<PlacementStrategy> for String must resolve \
24940                 identically on PlacementStrategy::{variant:?} — \
24941                 divergence signals the Cow<'static, str> and String \
24942                 return-shape paths have drifted onto different \
24943                 emit-sets"
24944            );
24945            let via_to_string: String = variant.to_string();
24946            assert_eq!(
24947                via_cow.as_ref(),
24948                via_to_string.as_str(),
24949                "From<PlacementStrategy> for Cow<'static, str> must \
24950                 byte-equal PlacementStrategy::to_string on \
24951                 PlacementStrategy::{variant:?} — divergence signals \
24952                 the trait-idiomatic Cow<'static, str> forward-\
24953                 projection axis and the ToString-through-Display \
24954                 axis have drifted onto different emit-sets"
24955            );
24956        }
24957        let via_iter: Vec<std::borrow::Cow<'static, str>> = PlacementStrategy::ALL
24958            .iter()
24959            .copied()
24960            .map(std::borrow::Cow::from)
24961            .collect();
24962        let via_method: Vec<std::borrow::Cow<'static, str>> = PlacementStrategy::ALL
24963            .iter()
24964            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
24965            .collect();
24966        assert_eq!(
24967            via_iter, via_method,
24968            "`.iter().copied().map(Cow::from)` over \
24969             PlacementStrategy::ALL must byte-equal \
24970             `.iter().map(|s| Cow::Borrowed(s.as_str()))` on every \
24971             arm — the trait-idiomatic `From<PlacementStrategy> for \
24972             Cow<'static, str>` axis is what makes the `Cow::from` \
24973             composition route through the substrate-primitive \
24974             `PlacementStrategy::as_str` accessor with the zero-alloc \
24975             Cow::Borrowed arm by construction, rather than a per-\
24976             call-site `Cow::Owned(strategy.to_string())` allocation"
24977        );
24978        for cow in &via_iter {
24979            assert!(
24980                matches!(cow, std::borrow::Cow::Borrowed(_)),
24981                "every element of the .iter().copied().map(Cow::from) \
24982                 pipe over PlacementStrategy::ALL must land on the \
24983                 zero-alloc Cow::Borrowed arm — a Cow::Owned outcome \
24984                 on any arm signals the pipe's iteration axis has \
24985                 silently allocated where the substrate-primitive \
24986                 PlacementStrategy::as_str `&'static str` return \
24987                 makes the borrowed arm the type-correct projection"
24988            );
24989        }
24990    }
24991
24992    #[test]
24993    fn placement_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
24994        // Fail-before-pass-after byte-parity pin on the newly lifted
24995        // `impl From<&PlacementStrategy> for
24996        // std::borrow::Cow<'static, str>` — asserts the borrowed-input
24997        // standard-library trait impl and the substrate-primitive
24998        // [`super::PlacementStrategy::as_str`] `pub const fn`
24999        // accessor resolve to the same three-arm emit-set across
25000        // every arm the exhaustive [`super::PlacementStrategy::ALL`]
25001        // slice enumerates. Rust's standard library does not carry a
25002        // blanket `impl<T: AsRef<str>> From<&T> for Cow<'static, str>`
25003        // (nor a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for
25004        // U`), so the borrowed-input `Cow<'static, str>` forward-
25005        // projection axis is a distinct trait-idiomatic surface that
25006        // a `let key: Cow<'static, str> = (&strategy).into();`-shaped
25007        // call site or a `PlacementStrategy::ALL.iter().map(Cow::from)`
25008        // -shaped pipe reaches through this impl and no other — the
25009        // paired owned-input `From<PlacementStrategy> for
25010        // Cow<'static, str>` impl (eee504d) forces every borrowed-
25011        // input call site through an explicit `Copy` deref
25012        // (`Cow::from(*strategy)`) or a
25013        // `Cow::Borrowed(strategy.as_str())` open-code whose type
25014        // bounds have no compile-time link back to the substrate
25015        // primitive.
25016        //
25017        // Also asserts the projection lands on the zero-alloc
25018        // [`std::borrow::Cow::Borrowed`] arm (not the
25019        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
25020        // [`super::PlacementStrategy::as_str`] accessor's `&'static
25021        // str` return lifetime by construction (each match arm
25022        // resolves to one of the three lifted
25023        // [`super::render::M3_PLACEMENT_ESTRATEGIA_*`] `pub const
25024        // &str` values) makes the borrowed arm the type-correct
25025        // projection with no runtime allocation on the borrowed-input
25026        // surface just as on the paired owned-input surface.
25027        //
25028        // Closes the `{Self, &Self}` input-shape corner on the M3-
25029        // mesh-shape `:placement :estrategia` distribution-strategy
25030        // [`Cow<'static, str>`] axis on the second M3-mesh-primitive-
25031        // defining closed-set fieldless typed enum peer on the caixa
25032        // surface, exactly as 25690ef closed it on the first M3-mesh-
25033        // primitive peer ([`super::WitShape`]) one commit after the
25034        // owning half (8634dec) landed, as d45c409 closed it on the
25035        // top-level [`super::CaixaKind`] one commit after the owning
25036        // half (99c1735) landed, and as 9b3e4b3 / ee577fd closed it
25037        // on the M2 OTP-shape [`crate::supervisor::RestartStrategy`] /
25038        // [`crate::supervisor::RestartPolicy`] sibling peers one
25039        // commit after (7dd28b3 / 0612398) landed.
25040        for &variant in PlacementStrategy::ALL {
25041            let via_trait: std::borrow::Cow<'static, str> =
25042                <std::borrow::Cow<'static, str> as From<&PlacementStrategy>>::from(&variant);
25043            let via_method: &'static str = variant.as_str();
25044            assert_eq!(
25045                via_trait.as_ref(),
25046                via_method,
25047                "From<&PlacementStrategy> for Cow<'static, str> impl \
25048                 must round-trip &PlacementStrategy::{variant:?} to \
25049                 the same lifted M3_PLACEMENT_ESTRATEGIA_* const \
25050                 PlacementStrategy::as_str returns — divergence \
25051                 signals a silent detour off the substrate-primitive \
25052                 accessor"
25053            );
25054            assert!(
25055                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
25056                "From<&PlacementStrategy> for Cow<'static, str> impl \
25057                 must land on the zero-alloc Cow::Borrowed arm on \
25058                 &PlacementStrategy::{variant:?} — a Cow::Owned \
25059                 outcome signals the projection has silently \
25060                 allocated where the substrate-primitive \
25061                 PlacementStrategy::as_str `&'static str` return \
25062                 makes the borrowed arm the type-correct projection"
25063            );
25064            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
25065            assert_eq!(
25066                via_into.as_ref(),
25067                via_method,
25068                "Into<Cow<'static, str>>::into on \
25069                 &PlacementStrategy::{variant:?} must byte-equal \
25070                 PlacementStrategy::as_str on the same input — the \
25071                 blanket-derived Into shape must resolve to the same \
25072                 as_str dispatch as the explicit From impl"
25073            );
25074            assert!(
25075                matches!(via_into, std::borrow::Cow::Borrowed(_)),
25076                "Into<Cow<'static, str>>::into on \
25077                 &PlacementStrategy::{variant:?} must land on the \
25078                 zero-alloc Cow::Borrowed arm — the blanket-derived \
25079                 Into shape must resolve to the same Cow::Borrowed \
25080                 dispatch as the explicit From impl"
25081            );
25082        }
25083    }
25084
25085    #[test]
25086    fn placement_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
25087        // Cross-axis partition pin: the newly lifted trait-idiomatic
25088        // borrowed-input `From<&PlacementStrategy> for
25089        // std::borrow::Cow<'static, str>` (this lift), the paired
25090        // owned-input `From<PlacementStrategy> for
25091        // std::borrow::Cow<'static, str>` (eee504d), the paired
25092        // borrowed-input owned-`&'static str` `From<&PlacementStrategy>
25093        // for &'static str`, and the paired borrowed-input owned-
25094        // `String` `From<&PlacementStrategy> for String` must resolve
25095        // identically on every arm, locking the four return-shape ×
25096        // input-shape paths together by construction so any future
25097        // detour trips at caixa-core test time. Also byte-parity
25098        // witness against the sibling [`ToString::to_string`] surface
25099        // routed through [`std::fmt::Display`] — every owned-heap-
25100        // string path (this axis's `.into_owned()` promotion, the
25101        // paired [`From<&PlacementStrategy> for String`], and
25102        // `.to_string()`) resolves to the same three-arm lifted
25103        // M3_PLACEMENT_ESTRATEGIA_* byte-string per arm.
25104        //
25105        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
25106        // over [`super::PlacementStrategy::ALL`] — whose iterator
25107        // yields `&PlacementStrategy` by construction, so the
25108        // borrowed-input [`Cow<'static, str>`] axis is what routes
25109        // the pipe through the substrate-primitive
25110        // [`super::PlacementStrategy::as_str`] accessor without a
25111        // spurious [`Copy`] deref (which would only be reachable
25112        // through the owned-input [`From<PlacementStrategy> for
25113        // Cow<'static, str>`] axis by first calling `.copied()` on
25114        // the iterator). The pipe witness also pins the zero-alloc
25115        // discipline: every element in the collected vector
25116        // satisfies the [`std::borrow::Cow::Borrowed`] arm predicate,
25117        // so a future accidental silent-allocation regression on the
25118        // pipe's iteration axis is a caixa-core-test-time failure.
25119        // Peer of the sibling
25120        // [`wit_shape_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
25121        // (25690ef) on the M3 mesh-shape `:contratos :wit` axis —
25122        // extends the whole borrowed-input `Cow<'static, str>` +
25123        // paired `{&'static str, String}` cross-axis-parity corner
25124        // onto the second M3-mesh-primitive-defining closed-set
25125        // fieldless typed enum peer on the caixa surface.
25126        for &variant in PlacementStrategy::ALL {
25127            let borrowed_cow: std::borrow::Cow<'static, str> =
25128                <std::borrow::Cow<'static, str> as From<&PlacementStrategy>>::from(&variant);
25129            let owned_cow: std::borrow::Cow<'static, str> =
25130                <std::borrow::Cow<'static, str> as From<PlacementStrategy>>::from(variant);
25131            let borrowed_static: &'static str =
25132                <&'static str as From<&PlacementStrategy>>::from(&variant);
25133            let borrowed_string: String = <String as From<&PlacementStrategy>>::from(&variant);
25134            assert_eq!(
25135                borrowed_cow, owned_cow,
25136                "From<&PlacementStrategy> for Cow<'static, str> and \
25137                 From<PlacementStrategy> for Cow<'static, str> must \
25138                 resolve identically on PlacementStrategy::\
25139                 {variant:?} — divergence signals the borrowed-input \
25140                 and owned-input Cow<'static, str> forward-projection \
25141                 input-shape paths have drifted onto different \
25142                 emit-sets"
25143            );
25144            assert_eq!(
25145                borrowed_cow.as_ref(),
25146                borrowed_static,
25147                "From<&PlacementStrategy> for Cow<'static, str> and \
25148                 From<&PlacementStrategy> for &'static str must \
25149                 resolve identically on PlacementStrategy::\
25150                 {variant:?} — divergence signals the borrowed-input \
25151                 Cow<'static, str> and &'static str return-shape paths \
25152                 have drifted onto different emit-sets"
25153            );
25154            assert_eq!(
25155                borrowed_cow.as_ref(),
25156                borrowed_string.as_str(),
25157                "From<&PlacementStrategy> for Cow<'static, str> and \
25158                 From<&PlacementStrategy> for String must resolve \
25159                 identically on PlacementStrategy::{variant:?} — \
25160                 divergence signals the borrowed-input \
25161                 Cow<'static, str> and owned-`String` return-shape \
25162                 paths have drifted onto different emit-sets"
25163            );
25164            let via_to_string: String = variant.to_string();
25165            assert_eq!(
25166                borrowed_cow.as_ref(),
25167                via_to_string.as_str(),
25168                "From<&PlacementStrategy> for Cow<'static, str> must \
25169                 byte-equal PlacementStrategy::to_string on \
25170                 PlacementStrategy::{variant:?} — divergence signals \
25171                 the trait-idiomatic borrowed-input Cow<'static, str> \
25172                 forward-projection axis and the ToString-through-\
25173                 Display axis have drifted onto different emit-sets"
25174            );
25175        }
25176        let via_iter: Vec<std::borrow::Cow<'static, str>> = PlacementStrategy::ALL
25177            .iter()
25178            .map(std::borrow::Cow::from)
25179            .collect();
25180        let via_method: Vec<std::borrow::Cow<'static, str>> = PlacementStrategy::ALL
25181            .iter()
25182            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
25183            .collect();
25184        assert_eq!(
25185            via_iter, via_method,
25186            "`.iter().map(Cow::from)` over PlacementStrategy::ALL — a \
25187             call site whose iteration axis holds &PlacementStrategy \
25188             by construction — must byte-equal `.iter().map(|s| \
25189             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
25190             input Cow<'static, str> `From<&PlacementStrategy> for \
25191             Cow<'static, str>` axis is what makes the `Cow::from` \
25192             composition route through the substrate-primitive \
25193             `PlacementStrategy::as_str` accessor with the zero-alloc \
25194             Cow::Borrowed arm by construction and without a spurious \
25195             `Copy` deref (which would only be reachable through the \
25196             owned-input `From<PlacementStrategy> for Cow<'static, \
25197             str>` axis by first calling `.copied()` on the iterator)"
25198        );
25199        for cow in &via_iter {
25200            assert!(
25201                matches!(cow, std::borrow::Cow::Borrowed(_)),
25202                "every element of the .iter().map(Cow::from) pipe \
25203                 over PlacementStrategy::ALL must land on the zero-\
25204                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
25205                 any arm signals the pipe's iteration axis has \
25206                 silently allocated where the substrate-primitive \
25207                 PlacementStrategy::as_str `&'static str` return \
25208                 makes the borrowed arm the type-correct projection"
25209            );
25210        }
25211    }
25212
25213    #[test]
25214    fn rejects_zero_policy_timeout() {
25215        let mut s = three_member_spec();
25216        s.politicas.timeout = Some(Duration::ZERO);
25217        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
25218    }
25219
25220    #[test]
25221    fn rejects_zero_policy_retries() {
25222        let mut s = three_member_spec();
25223        s.politicas.retries = Some(0);
25224        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
25225    }
25226
25227    #[test]
25228    fn rejects_policy_retries_above_cap() {
25229        // The fail-before-pass-after pin: `Some(11)` is structurally
25230        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
25231        // passed validate on every pre-gate codebase because the
25232        // typed slot's only check was the zero-floor arm. The
25233        // thundering-herd amplification vector only surfaced at the
25234        // runtime substrate (Envoy / Cilium L7 retry overlay)
25235        // far from the source caixa.lisp with no field naming the
25236        // offending policy.
25237        let mut s = three_member_spec();
25238        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
25239        assert_eq!(
25240            s.validate().unwrap_err(),
25241            AplicacaoError::PolicyRetriesExceedsCap {
25242                retries: POLICY_RETRIES_MAX + 1
25243            }
25244        );
25245    }
25246
25247    #[test]
25248    fn rejects_policy_retries_far_above_cap() {
25249        // The `u32::MAX` worst case — the four-billion-retry policy
25250        // a typo (`(:retries 4294967295)`) or struct-literal
25251        // copy-paste lands in the slot. Pin the cap arm's coverage
25252        // explicitly across the full `u32` overflow so a future
25253        // relaxation that drops the upper bound surfaces here.
25254        let mut s = three_member_spec();
25255        s.politicas.retries = Some(u32::MAX);
25256        assert_eq!(
25257            s.validate().unwrap_err(),
25258            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
25259        );
25260    }
25261
25262    #[test]
25263    fn accepts_policy_retries_at_cap() {
25264        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
25265        // must validate. The cap is inclusive on the top edge,
25266        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
25267        // discipline on the sibling [`crate::LimitsSpec::memory`]
25268        // axis. Pin the boundary explicitly so a future off-by-one
25269        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
25270        // surfaces here as a test failure rather than a silent
25271        // contract narrowing.
25272        let mut s = three_member_spec();
25273        s.politicas.retries = Some(POLICY_RETRIES_MAX);
25274        s.validate()
25275            .expect("retries == POLICY_RETRIES_MAX must validate");
25276    }
25277
25278    #[test]
25279    fn accepts_policy_retries_typical_values() {
25280        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
25281        // every value in the validated set must pass. The
25282        // Envoy / Istio production-playbook recommendation band
25283        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
25284        // (`maxRetries ≤ 10`) both lie within this set.
25285        for r in 1..=POLICY_RETRIES_MAX {
25286            let mut s = three_member_spec();
25287            s.politicas.retries = Some(r);
25288            s.validate()
25289                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
25290        }
25291    }
25292
25293    #[test]
25294    fn policy_retries_zero_takes_precedence_over_cap() {
25295        // The cross-arm ordering pin: `Some(0)` is structurally
25296        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
25297        // (cap), but the zero-floor diagnostic is the more
25298        // self-locating one (it directly names the omit-axis
25299        // remediation), so the validate gate must fire on zero
25300        // first. Pin the order so a future refactor that reorders
25301        // the arms surfaces here as a test failure rather than a
25302        // silent diagnostic regression. Same shape every other
25303        // zero-then-shape ordering on this surface uses
25304        // ([`AplicacaoError::PolicyTimeoutZero`] then
25305        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
25306        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
25307        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
25308        let mut s = three_member_spec();
25309        s.politicas.retries = Some(0);
25310        assert_eq!(
25311            s.validate().unwrap_err(),
25312            AplicacaoError::PolicyRetriesZero,
25313            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
25314        );
25315    }
25316
25317    #[test]
25318    fn policy_retries_cap_diagnostic_carries_offending_value() {
25319        // The diagnostic-shape pin: the offending `u32` is carried
25320        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
25321        // variant so the surfaced error message names the value the
25322        // author wrote (`":politicas :retries (47) exceeds the
25323        // mesh-policy ceiling …"`), not just the cap. Same
25324        // self-locating diagnostic shape every other typed-cap arm
25325        // on this surface carries
25326        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
25327        // offending byte count verbatim).
25328        let mut s = three_member_spec();
25329        s.politicas.retries = Some(47);
25330        let err = s.validate().unwrap_err();
25331        assert!(
25332            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
25333            "got {err:?}"
25334        );
25335        let msg = err.to_string();
25336        assert!(
25337            msg.contains("47"),
25338            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
25339        );
25340    }
25341
25342    #[test]
25343    fn policy_retries_cap_is_aws_app_mesh_aligned() {
25344        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
25345        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
25346        // schema cap — the only upstream mesh-policy schema that
25347        // documents an explicit hard cap. Pinning the literal value
25348        // here surfaces a future drift (a relaxation to 20, a
25349        // tightening to 5) as a deliberate test edit, not a silent
25350        // contract narrowing.
25351        assert_eq!(POLICY_RETRIES_MAX, 10);
25352    }
25353
25354    #[test]
25355    fn rejects_circuit_breaker_zero_max_failures() {
25356        let mut s = three_member_spec();
25357        s.politicas.circuit_breaker = Some(CircuitBreaker {
25358            max_failures: 0,
25359            window: Duration::from_secs(60),
25360        });
25361        assert_eq!(
25362            s.validate().unwrap_err(),
25363            AplicacaoError::PolicyBreakerZeroFailures
25364        );
25365    }
25366
25367    #[test]
25368    fn rejects_circuit_breaker_max_failures_above_cap() {
25369        // The fail-before-pass-after pin: `1001` is structurally one
25370        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
25371        // silently passed validate on every pre-gate codebase
25372        // because the typed slot's only check was the zero-floor
25373        // arm. The breaker-no-op vector only surfaced at the runtime
25374        // substrate (Envoy / Cilium L7 outlier-detection overlay)
25375        // far from the source caixa.lisp with no field naming the
25376        // offending policy.
25377        let mut s = three_member_spec();
25378        s.politicas.circuit_breaker = Some(CircuitBreaker {
25379            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
25380            window: Duration::from_secs(60),
25381        });
25382        assert_eq!(
25383            s.validate().unwrap_err(),
25384            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
25385                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
25386            }
25387        );
25388    }
25389
25390    #[test]
25391    fn rejects_circuit_breaker_max_failures_far_above_cap() {
25392        // The `u32::MAX` worst case — the four-billion-failure
25393        // threshold a typo (`(:max-failures 4294967295)`) or a
25394        // struct-literal copy-paste lands in the slot. Pin the cap
25395        // arm's coverage explicitly across the full `u32` overflow
25396        // so a future relaxation that drops the upper bound surfaces
25397        // here.
25398        let mut s = three_member_spec();
25399        s.politicas.circuit_breaker = Some(CircuitBreaker {
25400            max_failures: u32::MAX,
25401            window: Duration::from_secs(60),
25402        });
25403        assert_eq!(
25404            s.validate().unwrap_err(),
25405            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
25406                max_failures: u32::MAX,
25407            }
25408        );
25409    }
25410
25411    #[test]
25412    fn accepts_circuit_breaker_max_failures_at_cap() {
25413        // The boundary value — exactly
25414        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
25415        // cap is inclusive on the top edge, matching the
25416        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
25417        // discipline on the sibling capped axes. Pin the boundary
25418        // explicitly so a future off-by-one tightening
25419        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
25420        // surfaces here as a test failure rather than a silent
25421        // contract narrowing.
25422        let mut s = three_member_spec();
25423        s.politicas.circuit_breaker = Some(CircuitBreaker {
25424            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25425            window: Duration::from_secs(60),
25426        });
25427        s.validate()
25428            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
25429    }
25430
25431    #[test]
25432    fn accepts_circuit_breaker_max_failures_typical_values() {
25433        // The documented production-playbook band positive-control
25434        // sweep — every value Hystrix / Istio / Envoy / Polly /
25435        // Resilience4j recommend (5..=50) must pass, plus a sweep
25436        // through the hyperscale band (100, 500, 1000) the cap
25437        // accepts. Pin the inclusive validated set explicitly so a
25438        // future tightening of the ceiling surfaces here.
25439        //
25440        // Clears the fixture's `:retries` (which is `Some(3)`) so this
25441        // per-axis sweep is pure: the sibling cross-axis
25442        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
25443        // gate rejects any `max_failures <= retries` pair, so the
25444        // `max_failures = 1` boundary at the head of the sweep would
25445        // otherwise trip on the fixture-inherited retry policy rather
25446        // than the per-axis boundary this test names. Same discipline
25447        // the sibling per-axis `accepts_circuit_breaker_window_*`
25448        // sweeps take against the fixture's `:timeout` for the
25449        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
25450        // cross-axis arm.
25451        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
25452            let mut s = three_member_spec();
25453            s.politicas.retries = None;
25454            s.politicas.circuit_breaker = Some(CircuitBreaker {
25455                max_failures: n,
25456                window: Duration::from_secs(60),
25457            });
25458            s.validate()
25459                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
25460        }
25461    }
25462
25463    #[test]
25464    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
25465        // The cross-arm ordering pin: `0` is structurally outside
25466        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
25467        // (cap), but the zero-floor diagnostic is the more
25468        // self-locating one (it directly names the omit-axis
25469        // remediation), so the validate gate must fire on zero
25470        // first. Same shape every other zero-then-shape ordering on
25471        // this surface uses
25472        // ([`AplicacaoError::PolicyRetriesZero`] then
25473        // [`AplicacaoError::PolicyRetriesExceedsCap`];
25474        // [`AplicacaoError::PolicyTimeoutZero`] then
25475        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
25476        let mut s = three_member_spec();
25477        s.politicas.circuit_breaker = Some(CircuitBreaker {
25478            max_failures: 0,
25479            window: Duration::from_secs(60),
25480        });
25481        assert_eq!(
25482            s.validate().unwrap_err(),
25483            AplicacaoError::PolicyBreakerZeroFailures,
25484            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
25485        );
25486    }
25487
25488    #[test]
25489    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
25490        // The cross-arm ordering pin between the cap and the
25491        // sibling `:window` gates (zero-window, canonical-window).
25492        // A breaker carrying both an over-cap `max_failures` AND a
25493        // structurally invalid window (zero, sub-ms) must surface
25494        // the cap diagnostic first — the cap arm is wired
25495        // immediately after the zero-failure arm and strictly
25496        // before the window arms, so the offending value the
25497        // diagnostic names matches the order the author would
25498        // discover the gates by reading top-to-bottom through
25499        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
25500        // future refactor that reorders the arms surfaces here as a
25501        // test failure rather than a silent diagnostic regression.
25502        let mut s = three_member_spec();
25503        s.politicas.circuit_breaker = Some(CircuitBreaker {
25504            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
25505            window: Duration::ZERO,
25506        });
25507        assert_eq!(
25508            s.validate().unwrap_err(),
25509            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
25510                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
25511            },
25512            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
25513        );
25514    }
25515
25516    #[test]
25517    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
25518        // The diagnostic-shape pin: the offending `u32` is carried
25519        // verbatim into the
25520        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
25521        // variant so the surfaced error message names the value the
25522        // author wrote (`":politicas :circuit-breaker :max-failures
25523        // (50000) exceeds the mesh-policy ceiling …"`), not just
25524        // the cap. Same self-locating diagnostic shape every other
25525        // typed-cap arm on this surface carries
25526        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
25527        // offending retry count verbatim,
25528        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
25529        // offending byte count verbatim).
25530        let mut s = three_member_spec();
25531        s.politicas.circuit_breaker = Some(CircuitBreaker {
25532            max_failures: 50_000,
25533            window: Duration::from_secs(60),
25534        });
25535        let err = s.validate().unwrap_err();
25536        assert!(
25537            matches!(
25538                err,
25539                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
25540                    max_failures: 50_000
25541                }
25542            ),
25543            "got {err:?}"
25544        );
25545        let msg = err.to_string();
25546        assert!(
25547            msg.contains("50000"),
25548            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
25549        );
25550    }
25551
25552    #[test]
25553    fn policy_breaker_max_failures_cap_pins_canonical_value() {
25554        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
25555        // value at 1000 — an order of magnitude above every
25556        // documented production-playbook recommendation band
25557        // (Hystrix `requestVolumeThreshold` default 20, Istio
25558        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
25559        // `outlier_detection.consecutive_5xx` default 5, Polly /
25560        // Resilience4j typical 5..=50) and below the
25561        // clearly-pathological "effectively no protection" floor
25562        // (10_000, 100_000, u32::MAX). Pinning the literal value
25563        // here surfaces a future drift (a relaxation to 10_000, a
25564        // tightening to 100) as a deliberate test edit, not a
25565        // silent contract narrowing.
25566        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
25567    }
25568
25569    #[test]
25570    fn rejects_circuit_breaker_zero_window() {
25571        let mut s = three_member_spec();
25572        s.politicas.circuit_breaker = Some(CircuitBreaker {
25573            max_failures: 5,
25574            window: Duration::ZERO,
25575        });
25576        assert_eq!(
25577            s.validate().unwrap_err(),
25578            AplicacaoError::PolicyBreakerZeroWindow
25579        );
25580    }
25581
25582    #[test]
25583    fn rejects_zero_rate_limit() {
25584        let mut s = three_member_spec();
25585        s.politicas.rate_limit = Some(RateLimit {
25586            rate: 0,
25587            window: Duration::from_secs(1),
25588        });
25589        assert_eq!(
25590            s.validate().unwrap_err(),
25591            AplicacaoError::PolicyRateLimitZero
25592        );
25593    }
25594
25595    #[test]
25596    fn rejects_rate_limit_zero_window() {
25597        // `RateLimit { rate: 100, window: Duration::ZERO }` is
25598        // constructible programmatically (the typed `Duration` field
25599        // imposes no nonzero invariant) but renders through
25600        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
25601        // codec's `parse` rejects as `unknown rate-limit window unit
25602        // "0s"`. Until this validate-time gate landed the typed slot
25603        // accepted the value silently and the round-trip break only
25604        // surfaced at deserialize time (potentially in a downstream
25605        // consumer that never re-validates). Pin the rejection at
25606        // `AplicacaoSpec::validate` so the typed slot's valid set
25607        // matches the codec's round-trippable set structurally.
25608        let mut s = three_member_spec();
25609        s.politicas.rate_limit = Some(RateLimit {
25610            rate: 100,
25611            window: Duration::ZERO,
25612        });
25613        assert_eq!(
25614            s.validate().unwrap_err(),
25615            AplicacaoError::PolicyRateLimitWindowNotCanonical {
25616                window: Duration::ZERO
25617            }
25618        );
25619    }
25620
25621    #[test]
25622    fn rejects_rate_limit_arbitrary_seconds_window() {
25623        // 45 seconds is a valid `Duration` but not one of the three
25624        // canonical rate-limit windows the codec round-trips
25625        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
25626        // refuses on round-trip — same round-trip-break shape the
25627        // zero-window arm above pins, with a non-zero magnitude to
25628        // guard against a future "reject only zero" half-measure.
25629        let mut s = three_member_spec();
25630        let window = Duration::from_secs(45);
25631        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
25632        assert_eq!(
25633            s.validate().unwrap_err(),
25634            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
25635        );
25636    }
25637
25638    #[test]
25639    fn rejects_rate_limit_two_minute_window() {
25640        // 120 seconds = 2 minutes is a "looks-canonical" but
25641        // not-canonical window: it's a clean integer multiple of the
25642        // minute unit, but the codec only round-trips the
25643        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
25644        // A `Duration::from_secs(120)` window renders as `"100/120s"`
25645        // which the parser rejects. Pinning this case rules out a
25646        // future "accept any clean multiple of s/m/h" relaxation
25647        // that would silently break the codec contract.
25648        let mut s = three_member_spec();
25649        let window = Duration::from_secs(120);
25650        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
25651        assert_eq!(
25652            s.validate().unwrap_err(),
25653            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
25654        );
25655    }
25656
25657    #[test]
25658    fn rejects_rate_limit_subsecond_window() {
25659        // A sub-second window (e.g. 500ms) is a valid `Duration` but
25660        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
25661        // Pin the rejection so a future relaxation can't silently
25662        // admit fractional-second windows that the codec can't
25663        // round-trip.
25664        let mut s = three_member_spec();
25665        let window = Duration::from_millis(500);
25666        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
25667        assert_eq!(
25668            s.validate().unwrap_err(),
25669            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
25670        );
25671    }
25672
25673    #[test]
25674    fn rejects_policy_rate_limit_above_cap() {
25675        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
25676        // is structurally one past the cap and silently passed
25677        // validate on every pre-gate codebase because the typed slot's
25678        // only `rate` check was the zero-floor arm. The no-op-limiter
25679        // shape only surfaced at the runtime substrate (Envoy's
25680        // `local_rate_limit.token_bucket.max_tokens`, the future
25681        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
25682        // with no field naming the offending policy.
25683        let mut s = three_member_spec();
25684        s.politicas.rate_limit = Some(RateLimit {
25685            rate: POLICY_RATE_LIMIT_MAX + 1,
25686            window: Duration::from_secs(1),
25687        });
25688        assert_eq!(
25689            s.validate().unwrap_err(),
25690            AplicacaoError::PolicyRateLimitExceedsCap {
25691                rate: POLICY_RATE_LIMIT_MAX + 1
25692            }
25693        );
25694    }
25695
25696    #[test]
25697    fn rejects_policy_rate_limit_far_above_cap() {
25698        // The `u32::MAX` worst case — the four-billion-token rate-limit
25699        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
25700        // copy-paste lands in the slot. Pin the cap arm's coverage
25701        // explicitly across the full `u32` overflow so a future
25702        // relaxation that drops the upper bound surfaces here. Peer to
25703        // `rejects_policy_retries_far_above_cap` on the sibling
25704        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
25705        // on the sibling `:max-failures` axis.
25706        let mut s = three_member_spec();
25707        s.politicas.rate_limit = Some(RateLimit {
25708            rate: u32::MAX,
25709            window: Duration::from_secs(1),
25710        });
25711        assert_eq!(
25712            s.validate().unwrap_err(),
25713            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
25714        );
25715    }
25716
25717    #[test]
25718    fn accepts_policy_rate_limit_at_cap() {
25719        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
25720        // must validate. The cap is inclusive on the top edge, matching
25721        // every other typed upper bound in this crate
25722        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
25723        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
25724        // across all three canonical windows so a future off-by-one
25725        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
25726        // window-conditional cap surfaces here as a test failure rather
25727        // than a silent contract narrowing.
25728        for secs in [1u64, 60, 3600] {
25729            let mut s = three_member_spec();
25730            s.politicas.rate_limit = Some(RateLimit {
25731                rate: POLICY_RATE_LIMIT_MAX,
25732                window: Duration::from_secs(secs),
25733            });
25734            s.validate().unwrap_or_else(|e| {
25735                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
25736            });
25737        }
25738    }
25739
25740    #[test]
25741    fn accepts_policy_rate_limit_typical_values() {
25742        // The documented production-playbook recommendation band —
25743        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
25744        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
25745        // Enterprise ~1M per-hour. Every value in the validated set
25746        // must pass; pin the band explicitly so a future tightening
25747        // surfaces here.
25748        //
25749        // Clears the fixture's `:retries` (which is `Some(3)`) so this
25750        // per-axis sweep is pure: the sibling cross-axis
25751        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
25752        // rejects any `rate <= retries` pair, so the `rate = 1`
25753        // boundary at the head of the sweep would otherwise trip on the
25754        // fixture-inherited retry policy rather than the per-axis
25755        // boundary this test names. Same discipline the sibling per-axis
25756        // `accepts_circuit_breaker_max_failures_typical_values` sweep
25757        // takes against the fixture's `:retries` for the peer cross-axis
25758        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
25759        // arm.
25760        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
25761            for secs in [1u64, 60, 3600] {
25762                let mut s = three_member_spec();
25763                s.politicas.retries = None;
25764                s.politicas.rate_limit = Some(RateLimit {
25765                    rate,
25766                    window: Duration::from_secs(secs),
25767                });
25768                s.validate().unwrap_or_else(|e| {
25769                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
25770                });
25771            }
25772        }
25773    }
25774
25775    #[test]
25776    fn policy_rate_limit_zero_takes_precedence_over_cap() {
25777        // The cross-arm ordering pin: `rate == 0` is structurally
25778        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
25779        // (cap), but the zero-floor diagnostic is the more
25780        // self-locating one (it directly names the omit-axis
25781        // remediation). Pin the order so a future refactor that
25782        // reorders the arms surfaces here as a test failure rather
25783        // than a silent diagnostic regression. Same shape every other
25784        // zero-then-cap ordering on this surface uses
25785        // ([`AplicacaoError::PolicyRetriesZero`] then
25786        // [`AplicacaoError::PolicyRetriesExceedsCap`];
25787        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
25788        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
25789        let mut s = three_member_spec();
25790        s.politicas.rate_limit = Some(RateLimit {
25791            rate: 0,
25792            window: Duration::from_secs(1),
25793        });
25794        assert_eq!(
25795            s.validate().unwrap_err(),
25796            AplicacaoError::PolicyRateLimitZero,
25797            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
25798        );
25799    }
25800
25801    #[test]
25802    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
25803        // Two-axis-bad pin: rate above cap *and* window non-canonical.
25804        // The validate gate must fire on the rate cap first — the
25805        // amplification-shape (no-op limiter) diagnostic is the more
25806        // fundamental one; the window-canonical diagnostic is the
25807        // narrower codec-round-trip shape. Pin the ordering so a future
25808        // refactor that reorders the rate-then-window check arms
25809        // surfaces here as a test failure rather than a silent
25810        // diagnostic regression.
25811        let mut s = three_member_spec();
25812        s.politicas.rate_limit = Some(RateLimit {
25813            rate: POLICY_RATE_LIMIT_MAX + 1,
25814            window: Duration::from_secs(45),
25815        });
25816        assert_eq!(
25817            s.validate().unwrap_err(),
25818            AplicacaoError::PolicyRateLimitExceedsCap {
25819                rate: POLICY_RATE_LIMIT_MAX + 1
25820            },
25821            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
25822        );
25823    }
25824
25825    #[test]
25826    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
25827        // The diagnostic-shape pin: the offending `u32` is carried
25828        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
25829        // variant so the surfaced error message names the value the
25830        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
25831        // the mesh-policy ceiling …"`), not just the cap. Same
25832        // self-locating diagnostic shape every other typed-cap arm on
25833        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
25834        // carries the offending retries count verbatim,
25835        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
25836        // the offending failure count verbatim).
25837        let mut s = three_member_spec();
25838        s.politicas.rate_limit = Some(RateLimit {
25839            rate: 5_000_000,
25840            window: Duration::from_secs(1),
25841        });
25842        let err = s.validate().unwrap_err();
25843        assert!(
25844            matches!(
25845                err,
25846                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
25847            ),
25848            "got {err:?}"
25849        );
25850        let msg = err.to_string();
25851        assert!(
25852            msg.contains("5000000"),
25853            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
25854        );
25855    }
25856
25857    #[test]
25858    fn policy_rate_limit_cap_pins_canonical_value() {
25859        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
25860        // 1_000_000 — two-to-three orders of magnitude above every
25861        // documented production-playbook recommendation band (Envoy /
25862        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
25863        // Gateway 10_000..=100_000 per-minute) and below the
25864        // clearly-pathological "paste-from-binary blob" floor
25865        // (100_000_000, u32::MAX). Pinning the literal value here
25866        // surfaces a future drift (a relaxation to 10_000_000, a
25867        // tightening to 100_000) as a deliberate test edit, not a
25868        // silent contract narrowing.
25869        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
25870    }
25871
25872    #[test]
25873    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
25874        // Both axes are invalid here: rate == 0 *and* window is
25875        // non-canonical. The validate gate must fire on rate first
25876        // (matching the existing `rejects_zero_rate_limit` ordering),
25877        // so the existing diagnostic continues to lead with the
25878        // simpler "zero rate" framing. Pinning the order of checks
25879        // so a future refactor that reorders the arms surfaces here
25880        // as a test failure rather than a silent diagnostic
25881        // regression.
25882        let mut s = three_member_spec();
25883        s.politicas.rate_limit = Some(RateLimit {
25884            rate: 0,
25885            window: Duration::from_secs(45),
25886        });
25887        assert_eq!(
25888            s.validate().unwrap_err(),
25889            AplicacaoError::PolicyRateLimitZero
25890        );
25891    }
25892
25893    #[test]
25894    fn rate_limit_canonical_windows_validate() {
25895        // The three canonical windows the codec round-trips
25896        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
25897        // unchanged. Pin the full canonical set as a positive case
25898        // (the existing `rate_limit_round_trip_seconds` /
25899        // `rate_limit_round_trip_minutes` tests pin the
25900        // serialize-then-deserialize property at the codec layer; this
25901        // test pins the validate-side complement so a future tightening
25902        // of the canonical set — e.g. dropping `:hour` — surfaces here
25903        // as a test failure rather than a silent contract narrowing).
25904        for secs in [1u64, 60, 3600] {
25905            let mut s = three_member_spec();
25906            s.politicas.rate_limit = Some(RateLimit {
25907                rate: 100,
25908                window: Duration::from_secs(secs),
25909            });
25910            s.validate().expect("canonical window must validate");
25911        }
25912    }
25913
25914    #[test]
25915    fn rate_limit_validated_value_round_trips_through_codec() {
25916        // The structural property the validate gate enforces:
25917        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
25918        // losslessly through the `rate_limit_codec` (serialize → string
25919        // → deserialize → equal value). Pin this end-to-end so a future
25920        // change to either side (the validate gate's accepted window
25921        // set, the codec's parse/render unit set) that breaks the
25922        // alignment surfaces here. The previous-state shape (typed
25923        // slot accepts arbitrary `Duration`, codec only round-trips
25924        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
25925        // window — the validate gate now forecloses that.
25926        for secs in [1u64, 60, 3600] {
25927            let mut s = three_member_spec();
25928            s.politicas.rate_limit = Some(RateLimit {
25929                rate: 250,
25930                window: Duration::from_secs(secs),
25931            });
25932            s.validate().unwrap();
25933            let json = serde_json::to_string(&s.politicas).unwrap();
25934            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
25935            assert_eq!(
25936                back.rate_limit, s.politicas.rate_limit,
25937                "every validated :rate-limit must round-trip losslessly through the codec"
25938            );
25939        }
25940    }
25941
25942    #[test]
25943    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
25944        // The hour-window canonical form (`"<n>/h"`) was missing from
25945        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
25946        // pair. Now that the validate gate pins 3600s as part of the
25947        // canonical set, pin its serialize-side render shape too so
25948        // the third leg of the s/m/h tripod is explicitly tested.
25949        let policy = MeshPolicy {
25950            rate_limit: Some(RateLimit {
25951                rate: 10000,
25952                window: Duration::from_secs(3600),
25953            }),
25954            ..Default::default()
25955        };
25956        let json = serde_json::to_string(&policy).unwrap();
25957        assert!(
25958            json.contains("\"10000/h\""),
25959            "hour-window canonical form must render with `h` suffix (got: {json})"
25960        );
25961        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
25962        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
25963    }
25964
25965    #[test]
25966    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
25967        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
25968        // typed accessor's accepted-window set against the codec's
25969        // accepted set explicitly. A future addition to the codec
25970        // (e.g. accepting `:day`/`:week` as authoring units) must be
25971        // accompanied by a parallel addition here, and a regression
25972        // that drops one of the three canonical units from either
25973        // side surfaces as a test failure. The accessor is the
25974        // single source of truth for the canonical-window set —
25975        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
25976        // gate and [`rate_limit_codec::render`]'s canonical arm both
25977        // read through it — this test enshrines that its
25978        // `Duration → Option<RateLimitUnit>` projection matches the
25979        // codec's parse / render arms' accepted-window set exactly.
25980        //
25981        // Predecessor: this pin previously read the module-private
25982        // free helper `is_canonical_rate_limit_window` — a delegate
25983        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
25984        // — but the helper had no production consumers left after the
25985        // validate-gate migration onto [`RateLimit::canonical_unit`]
25986        // and was deleted; the closed-set arm-window bijection now
25987        // lives on exactly one typed dispatch on the substrate
25988        // primitive.
25989        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
25990            RateLimit { rate: 1, window }.canonical_unit()
25991        };
25992        assert!(canonical_unit(Duration::from_secs(1)).is_some());
25993        assert!(canonical_unit(Duration::from_secs(60)).is_some());
25994        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
25995        // Non-canonical windows the accessor rejects.
25996        assert!(canonical_unit(Duration::ZERO).is_none());
25997        assert!(canonical_unit(Duration::from_secs(2)).is_none());
25998        assert!(canonical_unit(Duration::from_secs(30)).is_none());
25999        assert!(canonical_unit(Duration::from_secs(120)).is_none());
26000        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
26001        // Sub-second windows: even `Duration::from_millis(1000)` is
26002        // exactly 1s and accepted; `Duration::from_millis(500)` is
26003        // sub-second and rejected.
26004        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
26005        assert!(canonical_unit(Duration::from_millis(500)).is_none());
26006        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
26007    }
26008
26009    #[test]
26010    fn rate_limit_unit_table_projections_are_mutual_inverses() {
26011        // Bidirection pin against the closed-set typed enum
26012        // [`RateLimitUnit`] arm-table (the canonical
26013        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
26014        // of the rate-limit unit surface reads from). The two
26015        // projection directions [`RateLimitUnit::from_suffix`] /
26016        // [`RateLimitUnit::window`] (str → Duration, exposed as one
26017        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
26018        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
26019        // (Duration → str, exposed as one typed dispatch through
26020        // [`RateLimit::canonical_unit`] composed with
26021        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
26022        // codec's parse arm ([`rate_limit_codec::parse`] via
26023        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
26024        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
26025        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
26026        // via [`RateLimit::canonical_unit`]) all key off. A future
26027        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
26028        // sub-second window) is one variant + one arm per method on the
26029        // closed-set enum; the compiler-enforced exhaustiveness on
26030        // every consumer's `match self` arms picks it up by
26031        // construction. This pin enshrines that both projection
26032        // directions agree on every canonical arm row and neither
26033        // leaks a spurious entry the other doesn't recognize.
26034        //
26035        // Predecessor: this test previously read the two vestigial
26036        // module-private free helpers `rate_limit_window_unit` and
26037        // `rate_limit_window_from_unit` on the `Duration → &str` and
26038        // `&str → Duration` axes; the former was deleted after its
26039        // sole production consumer ([`rate_limit_codec::render`])
26040        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
26041        // the latter is folded here into the substrate primitive
26042        // [`RateLimitUnit::window_from_suffix`] so both projection
26043        // directions live on the closed-set enum's arm-table.
26044        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
26045            let window = super::RateLimitUnit::window_from_suffix(unit)
26046                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
26047            assert_eq!(
26048                window,
26049                Duration::from_secs(secs),
26050                "unit {unit:?} must resolve to {secs}s"
26051            );
26052            let projected_suffix = RateLimit { rate: 1, window }
26053                .canonical_unit()
26054                .map(super::RateLimitUnit::as_suffix);
26055            assert_eq!(
26056                projected_suffix,
26057                Some(unit),
26058                "Duration({secs}s) must render as {unit:?} \
26059                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
26060            );
26061        }
26062        // Non-table units yield None on the `unit → Duration`
26063        // projection — a future `"d"` addition to the table would
26064        // flip this arm; today it pins the current three-row table's
26065        // rejection semantics.
26066        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
26067        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
26068        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
26069        // Non-table Durations yield None on the `Duration → unit`
26070        // projection — pins that the two projections agree on the
26071        // "not in the table" semantic too, so a drift where the
26072        // parse-side accepts a value the render-side can't emit is
26073        // a build error at the two-arm pair, not a silent codec
26074        // round-trip break.
26075        let projected_suffix = |window: Duration| -> Option<&'static str> {
26076            RateLimit { rate: 1, window }
26077                .canonical_unit()
26078                .map(super::RateLimitUnit::as_suffix)
26079        };
26080        assert!(projected_suffix(Duration::from_secs(2)).is_none());
26081        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
26082        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
26083    }
26084
26085    #[test]
26086    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
26087        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
26088        // substrate-primitive `&str → Duration` associated method the
26089        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
26090        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
26091        // to the same [`Duration`] the two-step composition
26092        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
26093        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
26094        // `"MIN"`) must project to [`None`] on both paths. A future
26095        // implementation of `window_from_suffix` that took a shortcut
26096        // through a per-suffix `match` table (bypassing the arm-table's
26097        // `Self::from_suffix` scan and the arm-table's `Self::window`
26098        // dispatch) would silently split the accept-set — the parse
26099        // arm would accept a suffix the enum's arm-table doesn't know,
26100        // or reject a suffix the enum's arm-table does; this pin
26101        // surfaces that drift at caixa-core build time rather than at a
26102        // downstream serde round-trip audit on a live `MeshPolicy`.
26103        //
26104        // Same byte-parity discipline the sibling
26105        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
26106        // pin carries on the peer `Duration → RateLimitUnit` axis via
26107        // [`RateLimit::canonical_unit`], and the peer
26108        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
26109        // carries on the bidirectional arm-table axis — extended here
26110        // onto the fifth (and last unlifted) projection axis on the
26111        // closed-set enum's arm-table.
26112        let composition = |suffix: &str| -> Option<Duration> {
26113            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
26114        };
26115        for suffix in ["s", "m", "h"] {
26116            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
26117            let via_composition = composition(suffix);
26118            assert_eq!(
26119                via_method, via_composition,
26120                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
26121                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
26122                 method must delegate to the arm-table's two typed dispatches, \
26123                 not shortcut through a per-suffix match table"
26124            );
26125            assert!(
26126                via_method.is_some(),
26127                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
26128                 RateLimitUnit::window_from_suffix"
26129            );
26130        }
26131        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
26132            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
26133            let via_composition = composition(suffix);
26134            assert_eq!(
26135                via_method, via_composition,
26136                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
26137                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
26138                 axis too"
26139            );
26140            assert!(
26141                via_method.is_none(),
26142                "non-arm suffix {suffix:?} must project to None via \
26143                 RateLimitUnit::window_from_suffix — a future extension that \
26144                 accepted this suffix without a corresponding arm on the enum \
26145                 would split the codec's parse-accepted set from the enum's \
26146                 arm-table"
26147            );
26148        }
26149        // And the codec's parse arm now reads through this method: a
26150        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
26151        // the same `Duration` the method returns for its unit, closing
26152        // the two-consumer drift surface (the codec's parse arm and the
26153        // enum's arm-table) with one typed dispatch on the substrate
26154        // primitive.
26155        for suffix in ["s", "m", "h"] {
26156            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
26157            let mp: MeshPolicy = serde_json::from_str(&wire)
26158                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
26159            let parsed = mp.rate_limit().expect("rate_limit payload present");
26160            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
26161                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
26162            assert_eq!(
26163                parsed.window(),
26164                via_method,
26165                "codec parse arm on {wire:?} must resolve the window through \
26166                 RateLimitUnit::window_from_suffix, not a divergent path"
26167            );
26168        }
26169    }
26170
26171    #[test]
26172    fn rate_limit_unit_all_enumerates_every_arm_once() {
26173        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
26174        // enumerate every arm of the closed-set enum exactly once, in
26175        // the canonical shortest-to-longest window order (Second before
26176        // Minute before Hour) — the same order the sibling
26177        // [`crate::supervisor::RestartStrategy`] /
26178        // [`crate::supervisor::RestartPolicy`] /
26179        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
26180        // typed enums carry (the arm declared first is the arm listed
26181        // first). A future variant addition that extends the enum
26182        // without appending to [`RateLimitUnit::ALL`] leaves the
26183        // exhaustive iteration surface silently short one arm — the
26184        // codec's parse arm would then reject the new suffix even
26185        // though the enum knows it. This pin closes the drift.
26186        assert_eq!(
26187            super::RateLimitUnit::ALL,
26188            &[
26189                super::RateLimitUnit::Second,
26190                super::RateLimitUnit::Minute,
26191                super::RateLimitUnit::Hour,
26192            ],
26193            "RateLimitUnit::ALL must enumerate every arm exactly once, \
26194             in canonical shortest-to-longest window order"
26195        );
26196    }
26197
26198    #[test]
26199    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
26200        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
26201        // every arm's [`RateLimitUnit::as_suffix`] output must parse
26202        // back through [`RateLimitUnit::from_suffix`] to the same
26203        // variant. A future arm addition that lands `as_suffix` but
26204        // forgets `from_suffix` (`from_suffix` iterates
26205        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
26206        // is the load-bearing carrier of the round-trip; the sibling
26207        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
26208        // the `ALL` half) trips here at caixa-core build time rather
26209        // than surfacing as a codec round-trip miss (a `render` emit
26210        // that lands a suffix the paired `parse` cannot decode).
26211        for unit in super::RateLimitUnit::ALL {
26212            let suffix = unit.as_suffix();
26213            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
26214                panic!(
26215                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
26216                     RateLimitUnit::as_suffix output — got None for {unit:?}"
26217                )
26218            });
26219            assert_eq!(
26220                parsed, *unit,
26221                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
26222                 must return RateLimitUnit::{unit:?}"
26223            );
26224        }
26225    }
26226
26227    #[test]
26228    fn rate_limit_unit_from_window_and_window_round_trip() {
26229        // Total round-trip pin on the `(from_window, window)` pair:
26230        // every arm's [`RateLimitUnit::window`] output must parse back
26231        // through [`RateLimitUnit::from_window`] to the same variant.
26232        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
26233        // on the peer `Duration` axis — the two round-trip pins
26234        // together enshrine that both projections of the typed
26235        // canonical-unit bijection are total on the arm-set.
26236        for unit in super::RateLimitUnit::ALL {
26237            let window = unit.window();
26238            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
26239                panic!(
26240                    "RateLimitUnit::from_window({window:?}) must accept every \
26241                     RateLimitUnit::window output — got None for {unit:?}"
26242                )
26243            });
26244            assert_eq!(
26245                parsed, *unit,
26246                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
26247                 must return RateLimitUnit::{unit:?}"
26248            );
26249        }
26250    }
26251
26252    #[test]
26253    fn rate_limit_unit_from_window_accessor_is_const_fn() {
26254        // Fail-before-pass-after pin: witnesses the
26255        // [`RateLimitUnit::from_window`] `const`-eval posture via a
26256        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
26257        // -> Option<RateLimitUnit>` whose body calls
26258        // `RateLimitUnit::from_window(window)`, well-formed only when
26259        // the callee is itself `const fn` (any future downgrade to
26260        // non-`const` fails at caixa-core build time with E0015 `cannot
26261        // call non-const function`, strictly stronger than a runtime
26262        // `assert!`, side-stepping the destructor-in-const restriction
26263        // that blocks direct `const _: Option<RateLimitUnit> =
26264        // RateLimitUnit::from_window(...)` items on `Duration`'s
26265        // carrier). The runtime body sweeps every closed-set
26266        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
26267        // rejection sample (`Duration::from_millis(500)` sub-second
26268        // residue) and asserts the wrapped and direct dispatches agree
26269        // — a violation means the wrapper stopped compiling under a
26270        // future `const`-posture downgrade, or the reverse resolver's
26271        // arm-set silently split from the peer `Self::window` emitter's
26272        // arm-set. Peer of the sibling
26273        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
26274        // (152c868) /
26275        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
26276        // (152c868) /
26277        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
26278        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
26279        // `const`-eval-surface pins on the peer M2 / M3 substrate-
26280        // primitive `Copy`-return accessor axes, extended onto the
26281        // reverse `Duration → RateLimitUnit` projection axis on the
26282        // M3 mesh-slot rate-limit closed-set typed enum.
26283        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
26284            super::RateLimitUnit::from_window(window)
26285        }
26286        for unit in super::RateLimitUnit::ALL {
26287            let window = unit.window();
26288            let via_wrapper = from_window_via_const_fn(window);
26289            let direct = super::RateLimitUnit::from_window(window);
26290            assert_eq!(
26291                via_wrapper, direct,
26292                "RateLimitUnit::from_window({window:?}) via const fn \
26293                 wrapper must agree with direct dispatch for {unit:?}"
26294            );
26295            assert_eq!(
26296                via_wrapper,
26297                Some(*unit),
26298                "RateLimitUnit::from_window({window:?}) via const fn \
26299                 wrapper must return Some({unit:?}) for the peer \
26300                 window() output"
26301            );
26302        }
26303        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
26304        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
26305    }
26306
26307    #[test]
26308    fn rate_limit_unit_from_window_composes_through_window_accessor() {
26309        // Composition-witness pin on the routing-through-peer discipline:
26310        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
26311        // through the peer `pub const fn` [`RateLimitUnit::window`]
26312        // canonical-`Duration` projection rather than a hand-authored
26313        // per-arm second-magnitude literal — a future arm-magnitude edit
26314        // on the sibling `window()` accessor (a `Second → 2s` typo, a
26315        // `Hour → 3599s` off-by-one) must therefore reach this reverse
26316        // resolver by construction. A pin that hard-coded the three
26317        // second-magnitudes here would silently split from the peer
26318        // emitter on any such edit; instead, this pin asserts the
26319        // composition invariant `from_window(u.window()) == Some(u)`
26320        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
26321        // arm — a violation means either the peer `Self::window`
26322        // accessor drifted (breaking every downstream consumer that
26323        // reads through it), or the reverse resolver stopped routing
26324        // through the peer (introducing a hand-authored literal that
26325        // silently disagrees with the emitter). Either failure is a
26326        // caixa-core-build-time surface, not a downstream renderer
26327        // round-trip regression.
26328        //
26329        // Peer of the sibling
26330        // [`crate::render::assert_str_reexport_identity`] discipline on
26331        // the substrate-primitive `&'static str` re-export axis and the
26332        // [`rate_limit_unit_from_window_and_window_round_trip`]
26333        // round-trip pin on the peer projection direction; extends the
26334        // one-canonical-dispatch-per-projection discipline onto the
26335        // reverse-resolver's per-arm probe axis.
26336        for unit in super::RateLimitUnit::ALL {
26337            let window_via_peer = unit.window();
26338            let resolved = super::RateLimitUnit::from_window(window_via_peer);
26339            assert_eq!(
26340                resolved,
26341                Some(*unit),
26342                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
26343                 must return Some({unit:?}) — the reverse resolver's per-arm \
26344                 probes must route through the peer `Self::window` accessor \
26345                 so any future arm-magnitude edit reaches both projection \
26346                 directions by construction"
26347            );
26348        }
26349    }
26350
26351    #[test]
26352    fn rate_limit_canonical_unit_accessor_is_const_fn() {
26353        // Fail-before-pass-after pin: witnesses the
26354        // [`RateLimit::canonical_unit`] `const`-eval posture via a
26355        // `const fn` wrapper
26356        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
26357        // whose body calls `rl.canonical_unit()`, well-formed only when
26358        // the callee is itself `const fn` (any future downgrade to
26359        // non-`const` fails at caixa-core build time with E0015 `cannot
26360        // call non-const method`). The runtime body sweeps every
26361        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
26362        // constructs a typed [`RateLimit`] with the peer `Self::window`
26363        // canonical `Duration`, then asserts both the wrapper and the
26364        // direct dispatch agree and both return `Some(unit)`. Composes
26365        // with the sibling
26366        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
26367        // typed [`RateLimit`] projection layer's `const`-posture is
26368        // load-bearing on the reverse resolver's `const`-posture, and
26369        // both must migrate together (a downgrade of either surface
26370        // splits the paired `const`-eval-surface pass on the M3
26371        // mesh-slot rate-limit `Duration ↔ Self` bijection).
26372        const fn canonical_unit_via_const_fn(
26373            rl: &super::RateLimit,
26374        ) -> Option<super::RateLimitUnit> {
26375            rl.canonical_unit()
26376        }
26377        for unit in super::RateLimitUnit::ALL {
26378            let rl = super::RateLimit {
26379                rate: 1,
26380                window: unit.window(),
26381            };
26382            let via_wrapper = canonical_unit_via_const_fn(&rl);
26383            let direct = rl.canonical_unit();
26384            assert_eq!(
26385                via_wrapper, direct,
26386                "RateLimit::canonical_unit() via const fn wrapper must \
26387                 agree with direct dispatch for {unit:?}"
26388            );
26389            assert_eq!(
26390                via_wrapper,
26391                Some(*unit),
26392                "RateLimit::canonical_unit() via const fn wrapper must \
26393                 return Some({unit:?}) for a RateLimit whose window is \
26394                 the peer RateLimitUnit::{unit:?}.window() output"
26395            );
26396        }
26397    }
26398
26399    #[test]
26400    fn rate_limit_unit_projections_are_pairwise_distinct() {
26401        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
26402        // [`RateLimitUnit::window`] outputs must be pairwise distinct
26403        // across every arm — an accidental copy-paste flip that
26404        // reroutes one arm's suffix or window to also match another
26405        // silently collapses two arms onto one, so
26406        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
26407        // (both using `find` on `Self::ALL`) would return whichever
26408        // arm the linear scan lands on first — a match-arm-ordering-
26409        // dependent outcome the closed-set typed-enum shape is meant
26410        // to rule out structurally. Peer of the sibling
26411        // `caixa_kind_wire_consts_are_pairwise_distinct` /
26412        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
26413        // other closed-set typed-enum discriminator axes.
26414        let all = super::RateLimitUnit::ALL;
26415        for (i, a) in all.iter().enumerate() {
26416            for (j, b) in all.iter().enumerate() {
26417                if i != j {
26418                    assert_ne!(
26419                        a.as_suffix(),
26420                        b.as_suffix(),
26421                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
26422                         must be distinct — a collision silently collapses two \
26423                         arms onto one under from_suffix's linear scan"
26424                    );
26425                    assert_ne!(
26426                        a.window(),
26427                        b.window(),
26428                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
26429                         must be distinct — a collision silently collapses two \
26430                         arms onto one under from_window's linear scan"
26431                    );
26432                }
26433            }
26434        }
26435    }
26436
26437    #[test]
26438    fn rate_limit_unit_display_routes_through_as_suffix() {
26439        // Route pin: [`std::fmt::Display`] must byte-equal
26440        // [`RateLimitUnit::as_suffix`] on every arm — the single
26441        // source of truth for the canonical suffix. A future
26442        // reimplementation that hand-rolls the arms instead of
26443        // delegating to [`RateLimitUnit::as_suffix`] would silently
26444        // desynchronize `format!("{u}")` from the codec's parse arm
26445        // (which uses `as_suffix` to compare suffixes). Peer of the
26446        // sibling `caixa_kind_display_routes_through_as_str_helper` /
26447        // `placement_strategy_display_routes_through_as_str_helper`
26448        // pins on the peer closed-set typed-enum Display axes.
26449        for unit in super::RateLimitUnit::ALL {
26450            assert_eq!(
26451                unit.to_string(),
26452                unit.as_suffix(),
26453                "RateLimitUnit::{unit:?} Display must route through \
26454                 as_suffix (single source of truth: the canonical suffix \
26455                 the codec parses and renders)"
26456            );
26457        }
26458    }
26459
26460    #[test]
26461    fn rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor() {
26462        // Fail-before-pass-after byte-parity pin on the lifted
26463        // `impl AsRef<str> for RateLimitUnit` — asserts the standard-
26464        // library trait impl and the substrate-primitive
26465        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
26466        // resolve to the same `&str` per instance across the three-arm
26467        // closed set, so any future silent detour that routes the impl
26468        // through a divergent projection (a per-arm inline
26469        // `match self { RateLimitUnit::Second => "s", … }` re-inlining
26470        // that opens a compile-time link to the un-lifted arm-literal,
26471        // a swap onto the second-magnitude
26472        // [`super::RateLimitUnit::window`] axis that would collide the
26473        // canonical-suffix / token-bucket-refill two-axis split) trips
26474        // at caixa-core test time under `PartialEq` rather than at a
26475        // downstream `impl AsRef<str>`-bound consumer's silent split.
26476        // Sweeps every one of the three arms
26477        // [`super::RateLimitUnit::ALL`] carries so no arm's projection
26478        // is covered only by the sibling `Display` path. Peer of the
26479        // sibling
26480        // `placement_strategy_as_ref_str_routes_through_as_str_accessor`
26481        // (d86edd2) on the M3 mesh-placement closed-set typed enum,
26482        // and the peer
26483        // [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
26484        // (cd2091f) pin on the top-level closed-set typed
26485        // discriminator — the pins together close the substrate
26486        // primitive's `AsRef<str>` projection axis on every closed-set
26487        // typed enum with a `fmt::Display` surface across the M2 / M3
26488        // typed slots plus the top-level `:kind` + `:versao`
26489        // primitives.
26490        for &unit in super::RateLimitUnit::ALL {
26491            assert_eq!(
26492                <super::RateLimitUnit as AsRef<str>>::as_ref(&unit),
26493                unit.as_suffix(),
26494                "AsRef<str> impl on RateLimitUnit::{unit:?} must \
26495                 byte-equal RateLimitUnit::as_suffix on the same \
26496                 instance — divergence signals a silent detour off the \
26497                 substrate-primitive accessor"
26498            );
26499        }
26500    }
26501
26502    #[test]
26503    fn rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor() {
26504        // Fail-before-pass-after byte-parity pin on the three-path
26505        // convergence discipline the M3 `:politicas :rate-limit`
26506        // canonical-unit primitive now carries on the `&str`-projection
26507        // axis: `<RateLimitUnit as AsRef<str>>::as_ref(&v)` (the newly
26508        // lifted impl), `format!("{v}")` (the pre-existing
26509        // [`fmt::Display`] impl), and `v.as_suffix()` (the substrate-
26510        // primitive `pub const fn` accessor both trait impls delegate
26511        // through) must resolve to the same byte-string on every
26512        // instance across the three-arm closed set. Refuses any future
26513        // divergence between the two trait impls (a stray
26514        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
26515        // rather than delegating through the shared accessor; a
26516        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
26517        // literal cascade) that would silently split the two
26518        // projection paths of the same closed-set typed enum. Mirrors
26519        // the sibling three-path-convergence discipline the peer
26520        // [`super::PlacementStrategy`] typed enum carries
26521        // (`placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
26522        // d86edd2), the peer [`crate::CaixaKind`] triple
26523        // (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
26524        // cd2091f), and the [`crate::CaixaVersion`] typed newtype
26525        // triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
26526        // 16d5c7e).
26527        for &unit in super::RateLimitUnit::ALL {
26528            let via_as_ref: &str = <super::RateLimitUnit as AsRef<str>>::as_ref(&unit);
26529            let via_display: String = format!("{unit}");
26530            let via_accessor: &str = unit.as_suffix();
26531            assert_eq!(via_as_ref, via_accessor);
26532            assert_eq!(via_display, via_accessor);
26533            assert_eq!(via_as_ref, via_display.as_str());
26534        }
26535    }
26536
26537    #[test]
26538    fn rate_limit_unit_from_window_rejects_non_canonical() {
26539        // Rejection pin on the parser's accept-set: any Duration
26540        // outside the three-arm [`RateLimitUnit::window`] output set
26541        // (sub-second residue, or a second-magnitude outside `{1, 60,
26542        // 3600}`) must return `None`. A future accidental widening of
26543        // the accept-set (rounding down sub-second residue to the
26544        // nearest arm, admitting `Duration::from_secs(30)` as a
26545        // half-minute unit) would silently drift the parser's accept-
26546        // set from the emitter's — a validated slot with a
26547        // non-canonical window would then round-trip through the
26548        // codec to a canonical form the author never wrote.
26549        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
26550        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
26551        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
26552        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
26553        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
26554        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
26555        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
26556    }
26557
26558    #[test]
26559    fn rate_limit_unit_from_suffix_rejects_unknown() {
26560        // Rejection pin on the suffix parser's accept-set: any string
26561        // outside the three-arm [`RateLimitUnit::as_suffix`] output
26562        // set must return `None`. Peer of the sibling
26563        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
26564        // the [`crate::CaixaKind`] `from_wire` accept-set.
26565        for bad in [
26566            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
26567            " s",
26568        ] {
26569            assert!(
26570                super::RateLimitUnit::from_suffix(bad).is_none(),
26571                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
26572                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
26573                 outputs"
26574            );
26575        }
26576    }
26577
26578    #[test]
26579    fn rate_limit_unit_try_from_str_routes_through_from_suffix_accessor() {
26580        // Fail-before-pass-after byte-parity pin on the newly lifted
26581        // `impl TryFrom<&str> for RateLimitUnit` — asserts the standard-
26582        // library trait impl and the substrate-primitive
26583        // [`super::RateLimitUnit::from_suffix`] `Option<Self>` accessor
26584        // resolve to the same three-arm accept-set across every arm the
26585        // exhaustive [`super::RateLimitUnit::ALL`] slice enumerates. Any
26586        // future silent detour that routes the trait impl through a
26587        // divergent projection (a per-arm inline
26588        // `match s { "s" => Ok(Self::Second), … }` re-inlining that
26589        // opens a compile-time link to the un-lifted arm-literal, a
26590        // silent case-fold that admits `"S"` / `"M"` / `"H"` and would
26591        // collide the canonical-suffix accept-set the codec's parse arm
26592        // dispatches on) trips at caixa-core test time under
26593        // `assert_eq!` rather than at a downstream `impl TryFrom<&str>`-
26594        // bound consumer's silent split. Sweeps every one of the three
26595        // arms [`super::RateLimitUnit::ALL`] carries so no arm's
26596        // projection is covered only by the sibling method-named
26597        // `from_suffix` path. Peer of the sibling
26598        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
26599        // (3c83606),
26600        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
26601        // (bf33136), and
26602        // `placement_strategy_try_from_str_routes_through_from_wire_accessor`
26603        // (6fd00cd) — extends the trait-idiomatic reverse-projection
26604        // axis onto the third M3-mesh-primitive-defining slot enum on
26605        // the caixa surface (the `:politicas :rate-limit` unit-suffix
26606        // closed set the caixa-mesh renderer keys off end-to-end).
26607        for &unit in super::RateLimitUnit::ALL {
26608            let suffix = unit.as_suffix();
26609            assert_eq!(
26610                <super::RateLimitUnit as TryFrom<&str>>::try_from(suffix),
26611                Ok(unit),
26612                "TryFrom<&str> impl on RateLimitUnit must round-trip \
26613                 RateLimitUnit::{unit:?}.as_suffix() = {suffix:?} back to \
26614                 Ok(RateLimitUnit::{unit:?}) — divergence from \
26615                 RateLimitUnit::from_suffix signals a silent detour off \
26616                 the substrate-primitive accessor"
26617            );
26618            assert_eq!(
26619                <super::RateLimitUnit as TryFrom<&str>>::try_from(suffix).ok(),
26620                super::RateLimitUnit::from_suffix(suffix),
26621                "TryFrom<&str> ok()-projection on {suffix:?} must \
26622                 byte-equal RateLimitUnit::from_suffix on the same input"
26623            );
26624        }
26625    }
26626
26627    #[test]
26628    fn rate_limit_unit_try_from_str_rejects_unknown_byte_strings() {
26629        // Rejection witness on the `impl TryFrom<&str> for RateLimitUnit`
26630        // — sweeps a candidate set of byte-strings outside the three-arm
26631        // canonical-suffix wire accept-set the sibling
26632        // [`super::RateLimitUnit::as_suffix`] emits and asserts every
26633        // one lands on `Err(())`, so a future accidental widening of the
26634        // trait impl's accept-set (a stray additional
26635        // `_ if s.eq_ignore_ascii_case("s") => Ok(…)` case-fold path, a
26636        // silent inclusion of a long-form English rebrand of the
26637        // canonical suffix like `"second"` / `"minute"` / `"hour"` that
26638        // would collide the one-letter-suffix discipline the sibling
26639        // [`super::RateLimitUnit::from_suffix`] carries, a silent
26640        // acceptance of the `"1s"` / `"1m"` / `"1h"` full-rate-limit
26641        // shape that would collide the codec-composed `<n>/<unit>` axis
26642        // onto the unit-suffix axis) trips at caixa-core test time. The
26643        // candidate set includes the empty string, whitespace-only
26644        // padding, uppercase rebrand candidates, long-form English
26645        // rebrand candidates (`"second"`, `"minute"`, `"hour"`),
26646        // trailing/leading-whitespace-padded canonical suffixes,
26647        // sub-second and multi-day trajectory-item candidates
26648        // (`"ms"`, `"d"`, `"week"`), digits-prefixed shapes that would
26649        // collide with the `<n>/<unit>` parent codec, the quoted-shape
26650        // (`"\"s\""`) that would signal a stray serde-quote survival,
26651        // and the `"?"` sentinel. Peer of the sibling
26652        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
26653        // (3c83606) rejection witness, and
26654        // `placement_strategy_try_from_str_rejects_unknown_byte_strings`
26655        // (6fd00cd).
26656        let rejected: &[&str] = &[
26657            "", " ", "\n", "\t", "S", "M", "H", "s ", " s", "m ", " h", "s\n", "second", "minute",
26658            "hour", "sec", "min", "hr", "d", "ms", "ns", "us", "week", "1s", "1m", "1h", "100/s",
26659            "s/", "?", "\"s\"",
26660        ];
26661        for &input in rejected {
26662            assert_eq!(
26663                <super::RateLimitUnit as TryFrom<&str>>::try_from(input),
26664                Err(()),
26665                "TryFrom<&str> impl on RateLimitUnit must reject the \
26666                 non-suffix byte-string {input:?} — silent acceptance \
26667                 signals an accept-set widening off the paired \
26668                 RateLimitUnit::from_suffix resolver"
26669            );
26670        }
26671    }
26672
26673    #[test]
26674    fn rate_limit_unit_try_from_str_and_from_suffix_partition_the_accept_set() {
26675        // Cross-axis partition pin on the two `str → Option<Self>` /
26676        // `str → Result<Self, ()>` projections on
26677        // [`super::RateLimitUnit`]: the trait-idiomatic
26678        // [`TryFrom<&str>`] axis (newly lifted) and the method-named
26679        // [`super::RateLimitUnit::from_suffix`] axis (pre-existing) must
26680        // partition every input into the same accept-set / reject-set
26681        // — a `TryFrom<&str>` `Ok(v)` outcome iff `from_suffix` returns
26682        // `Some(v)`, and a `TryFrom<&str>` `Err(())` outcome iff
26683        // `from_suffix` returns `None`. Sweeps a mixed input set of
26684        // canonical accepts + rejections so any future divergence
26685        // between the two projection paths (a hand-rolled `try_from`
26686        // rewrite that no longer routes through `from_suffix`, a
26687        // hypothetical `from_suffix` widening that admits a byte-string
26688        // the trait impl still rejects) surfaces here at caixa-core
26689        // test time rather than at a downstream consumer's silent
26690        // split. Peer of the sibling
26691        // `wit_shape_try_from_str_and_from_wire_partition_the_accept_set`
26692        // (5472902) cross-axis partition pin on the sibling M3-mesh-
26693        // primitive closed-set typed enum.
26694        let inputs: &[&str] = &[
26695            "s", "m", "h", "", " ", "S", "second", "d", "ms", "1s", "?", "\"s\"", "sec",
26696        ];
26697        for &input in inputs {
26698            let via_try_from: Option<super::RateLimitUnit> =
26699                <super::RateLimitUnit as TryFrom<&str>>::try_from(input).ok();
26700            let via_from_suffix: Option<super::RateLimitUnit> =
26701                super::RateLimitUnit::from_suffix(input);
26702            assert_eq!(
26703                via_try_from, via_from_suffix,
26704                "TryFrom<&str> and from_suffix must partition the \
26705                 accept-set identically on input {input:?} — got \
26706                 TryFrom = {via_try_from:?}, from_suffix = {via_from_suffix:?}"
26707            );
26708        }
26709    }
26710
26711    #[test]
26712    fn rate_limit_unit_from_into_static_str_routes_through_as_suffix_accessor() {
26713        // Fail-before-pass-after byte-parity pin on the newly lifted
26714        // `impl From<RateLimitUnit> for &'static str` — asserts the
26715        // standard-library trait impl and the substrate-primitive
26716        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
26717        // resolve to the same three-arm canonical-suffix emit-set across
26718        // every arm the exhaustive [`super::RateLimitUnit::ALL`] slice
26719        // enumerates. Any future silent detour that routes the trait
26720        // impl through a divergent projection (a per-arm inline
26721        // `match unit { Second => "s", … }` re-inlining that opens a
26722        // compile-time link to the un-lifted arm-literal outside the
26723        // paired [`super::RateLimitUnit::as_suffix`] dispatch, a swap
26724        // onto the second-magnitude [`super::RateLimitUnit::window`]
26725        // axis that would collide the canonical-suffix /
26726        // token-bucket-refill two-axis split) trips at caixa-core test
26727        // time under `assert_eq!` rather than at a downstream
26728        // `impl Into<&'static str>`-bound consumer's silent split.
26729        // Sweeps every one of the three arms
26730        // [`super::RateLimitUnit::ALL`] carries so no arm's projection
26731        // is covered only by the sibling method-named `as_suffix` /
26732        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
26733        // `<&'static str as From<RateLimitUnit>>::from` output in three
26734        // `const`-shape bindings against the paired
26735        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor to
26736        // make the `'static` lifetime promise a build-time invariant —
26737        // a future accidental downgrade of any of the three arms'
26738        // inline canonical-suffix byte-strings to a non-`&'static str`
26739        // (a `String::leak()`-produced return, a `Box::leak`-cast, an
26740        // intermediate lifetime-erasing helper) trips at caixa-core
26741        // build time rather than at a downstream `'static`-bound
26742        // consumer.
26743        //
26744        // Peer of the sibling
26745        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
26746        // (523157d),
26747        // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
26748        // (9fb37d0),
26749        // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
26750        // (edb827b),
26751        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
26752        // (c189a6f),
26753        // [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
26754        // (afa3562), and
26755        // [`tests::wit_shape_from_into_static_str_routes_through_as_str_accessor`]
26756        // (56998ec) pins on the sibling closed-set typed-enum forward-
26757        // projection axes — extends the trait-idiomatic forward-
26758        // projection axis onto the seventh closed-set fieldless typed
26759        // enum on the caixa surface (the third M3-mesh-primitive-
26760        // defining slot enum, the `:politicas :rate-limit`
26761        // canonical-suffix axis the caixa-mesh renderer keys off end-
26762        // to-end for per-Aplicacao Envoy
26763        // `local_rate_limit.token_bucket.fill_interval` overlay
26764        // emission).
26765        const SECOND: &str = super::RateLimitUnit::Second.as_suffix();
26766        const MINUTE: &str = super::RateLimitUnit::Minute.as_suffix();
26767        const HOUR: &str = super::RateLimitUnit::Hour.as_suffix();
26768        for &unit in super::RateLimitUnit::ALL {
26769            let via_trait: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
26770            let via_method: &'static str = unit.as_suffix();
26771            assert_eq!(
26772                via_trait, via_method,
26773                "From<RateLimitUnit> for &'static str impl must \
26774                 round-trip RateLimitUnit::{unit:?} to the same \
26775                 canonical-suffix byte-string RateLimitUnit::as_suffix \
26776                 returns — divergence signals a silent detour off the \
26777                 substrate-primitive accessor"
26778            );
26779            let via_into: &'static str = unit.into();
26780            assert_eq!(
26781                via_into, via_method,
26782                "Into<&'static str>::into on RateLimitUnit::{unit:?} \
26783                 must byte-equal RateLimitUnit::as_suffix on the same \
26784                 input — the blanket-derived Into shape must resolve to \
26785                 the same as_suffix dispatch as the explicit From impl"
26786            );
26787        }
26788        assert_eq!(
26789            [SECOND, MINUTE, HOUR],
26790            ["s", "m", "h"],
26791            "const-context RateLimitUnit::as_suffix must resolve to the \
26792             three canonical-suffix byte-strings — a future accidental \
26793             downgrade of any arm to a non-const or non-static \
26794             byte-string breaks the `&'static str`-lifetime promise the \
26795             paired From<RateLimitUnit> for &'static str impl carries \
26796             by construction"
26797        );
26798    }
26799
26800    #[test]
26801    fn rate_limit_unit_from_into_static_str_and_as_suffix_partition_the_emit_set() {
26802        // Cross-axis partition pin: the paired trait-idiomatic
26803        // `From<RateLimitUnit> for &'static str` forward projection and
26804        // the method-named [`super::RateLimitUnit::as_suffix`] forward
26805        // projection must resolve identically on *every* arm, not just
26806        // the ones named in the primary byte-parity pin above. Sweeps
26807        // every [`super::RateLimitUnit::ALL`] arm and asserts the
26808        // trait's `From::from` output byte-equals the method-named
26809        // accessor's return-value on each, locking the two forward-
26810        // projection paths together by construction so any future
26811        // detour (a stray `From` special-case that lands on a divergent
26812        // per-arm literal outside the paired `as_suffix` dispatch, a
26813        // hypothetical rebrand touching one axis without the other)
26814        // trips at caixa-core test time.
26815        //
26816        // Peer of the sibling forward-projection partition pins
26817        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
26818        // (523157d),
26819        // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
26820        // (9fb37d0),
26821        // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
26822        // (edb827b),
26823        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
26824        // (c189a6f),
26825        // [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
26826        // (afa3562), and
26827        // [`tests::wit_shape_from_into_static_str_and_as_str_partition_the_emit_set`]
26828        // (56998ec) — extends the round-trip discipline onto the seventh
26829        // closed-set typed enum on the caixa surface, closing the two-
26830        // way `Self ↔ &'static str` round-trip on the trait-idiomatic
26831        // pair (`From<Self> for &'static str` + `TryFrom<&str> for
26832        // Self`) as well as the pre-existing method-named pair
26833        // (`as_suffix` + `from_suffix`).
26834        for &unit in super::RateLimitUnit::ALL {
26835            let via_trait: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
26836            let via_method: &'static str = unit.as_suffix();
26837            assert_eq!(
26838                via_trait, via_method,
26839                "From<RateLimitUnit> for &'static str and \
26840                 RateLimitUnit::as_suffix must resolve identically on \
26841                 RateLimitUnit::{unit:?} — divergence signals the two \
26842                 forward-projection paths have drifted onto different \
26843                 emit-sets"
26844            );
26845        }
26846        // Round-trip witness: every arm's forward `From` output re-parses
26847        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
26848        // to the original variant. Closes the two-way `RateLimitUnit ↔
26849        // &'static str` round-trip on the trait-idiomatic axis pair
26850        // directly (no wire-vocab intermediate the peer [`CaixaKind`]
26851        // axis pair requires — the emit-side
26852        // [`super::RateLimitUnit::as_suffix`] and the parse-side
26853        // [`super::RateLimitUnit::from_suffix`] dispatch on the same
26854        // three inline canonical-suffix byte-strings by construction),
26855        // mirroring the pre-existing method-named `as_suffix` +
26856        // `from_suffix` round-trip on the substrate-primitive axis pair
26857        // and the peer [`super::WitShape`] round-trip (56998ec) on the
26858        // sibling M3-mesh-primitive-defining slot enum.
26859        for &unit in super::RateLimitUnit::ALL {
26860            let emitted: &'static str = unit.into();
26861            let re_parsed: Result<super::RateLimitUnit, ()> =
26862                <super::RateLimitUnit as TryFrom<&str>>::try_from(emitted);
26863            assert_eq!(
26864                re_parsed,
26865                Ok(unit),
26866                "trait-idiomatic axis pair must round-trip \
26867                 RateLimitUnit::{unit:?} through `.into::<&'static \
26868                 str>()` and back through `TryFrom<&str>` — a break \
26869                 signals the forward-emit and reverse-parse axes have \
26870                 drifted onto different vocabularies"
26871            );
26872        }
26873    }
26874
26875    #[test]
26876    fn rate_limit_unit_from_borrowed_into_static_str_routes_through_as_suffix_accessor() {
26877        // Fail-before-pass-after byte-parity pin on the newly lifted
26878        // `impl From<&RateLimitUnit> for &'static str` — asserts the
26879        // borrowed-input standard-library trait impl and the substrate-
26880        // primitive [`super::RateLimitUnit::as_suffix`] `pub const fn`
26881        // accessor resolve to the same three-arm canonical-suffix
26882        // emit-set across every arm the exhaustive
26883        // [`super::RateLimitUnit::ALL`] slice enumerates. Rust's `From`
26884        // trait does not auto-derive the borrowed-input sibling from a
26885        // paired owned-input impl (no `impl<T, U> From<&T> for U where
26886        // T: Copy, U: From<T>` blanket in `core`), so the borrowed-input
26887        // axis is a distinct trait-idiomatic surface that a
26888        // `.iter().map(Into::into)` shape over
26889        // [`super::RateLimitUnit::ALL`] (whose iterator yields
26890        // `&RateLimitUnit`, not `RateLimitUnit`) reaches through this
26891        // impl and no other — the paired owned-input
26892        // [`From<RateLimitUnit>`] impl requires an explicit `.copied()`
26893        // / dereference before the trait fires. Materializes the
26894        // `<&'static str as From<&RateLimitUnit>>::from` output in three
26895        // `const`-shape bindings against the paired
26896        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor to
26897        // make the `'static` lifetime promise a build-time invariant —
26898        // a future accidental downgrade of any of the three arms'
26899        // inline canonical-suffix byte-strings to a non-`&'static str`
26900        // (a `String::leak()`-produced return, a `Box::leak`-cast, an
26901        // intermediate lifetime-erasing helper) trips at caixa-core
26902        // build time rather than at a downstream `'static`-bound
26903        // consumer.
26904        //
26905        // Peer of the sibling
26906        // [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
26907        // (64aa742),
26908        // [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
26909        // (5ab993a),
26910        // [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
26911        // (807b0b5),
26912        // [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
26913        // (e941836),
26914        // [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
26915        // (842c7f3),
26916        // [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
26917        // (4d941d8), and
26918        // [`tests::wit_shape_from_borrowed_into_static_str_routes_through_as_str_accessor`]
26919        // (3187bd0) pins on the sibling closed-set typed-enum
26920        // borrowed-input forward-projection axes — extends the
26921        // borrowed-input axis onto the third (and last) M3-mesh-
26922        // primitive-defining closed-set typed enum on the caixa surface
26923        // (the `:politicas :rate-limit` canonical-suffix axis the
26924        // caixa-mesh renderer keys off end-to-end for per-Aplicacao
26925        // Envoy `local_rate_limit.token_bucket.fill_interval` overlay
26926        // emission).
26927        const SECOND: &str = super::RateLimitUnit::Second.as_suffix();
26928        const MINUTE: &str = super::RateLimitUnit::Minute.as_suffix();
26929        const HOUR: &str = super::RateLimitUnit::Hour.as_suffix();
26930        for unit in super::RateLimitUnit::ALL {
26931            let via_trait: &'static str = <&'static str as From<&super::RateLimitUnit>>::from(unit);
26932            let via_method: &'static str = unit.as_suffix();
26933            assert_eq!(
26934                via_trait, via_method,
26935                "From<&RateLimitUnit> for &'static str impl must \
26936                 round-trip &RateLimitUnit::{unit:?} to the same \
26937                 canonical-suffix byte-string RateLimitUnit::as_suffix \
26938                 returns — divergence signals a silent detour off the \
26939                 substrate-primitive accessor"
26940            );
26941            let via_into: &'static str = unit.into();
26942            assert_eq!(
26943                via_into, via_method,
26944                "Into<&'static str>::into on &RateLimitUnit::{unit:?} \
26945                 must byte-equal RateLimitUnit::as_suffix on the same \
26946                 input — the blanket-derived Into shape must resolve to \
26947                 the same as_suffix dispatch as the explicit From impl"
26948            );
26949        }
26950        assert_eq!(
26951            [SECOND, MINUTE, HOUR],
26952            ["s", "m", "h"],
26953            "const-context RateLimitUnit::as_suffix must resolve to the \
26954             three canonical-suffix byte-strings — the borrowed-input \
26955             From<&RateLimitUnit> for &'static str impl inherits its \
26956             `'static` lifetime promise from the same accessor the \
26957             owned-input sibling routes through"
26958        );
26959    }
26960
26961    #[test]
26962    fn rate_limit_unit_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
26963        // Cross-axis partition pin: the paired trait-idiomatic
26964        // owned-input `From<RateLimitUnit> for &'static str` (7fdfbf4
26965        // campaign-shape) and borrowed-input `From<&RateLimitUnit> for
26966        // &'static str` (this lift) forward projections must resolve
26967        // identically on every arm, locking the two input-shape paths
26968        // together so any future detour trips at caixa-core test time.
26969        // Then a witness that a `.iter().map(Into::into)` pipe over
26970        // [`super::RateLimitUnit::ALL`] (whose iterator yields
26971        // `&RateLimitUnit`) materializes the three-arm accept-set
26972        // through the borrowed-input axis alone — the exact shape a
26973        // future M4 admission-webhook rejection body's accepted-set
26974        // enumeration, a future substrate-wide per-arm diagnostic
26975        // column, or a `HashMap::<&'static str,
26976        // RateLimitUnit>::from_iter(RateLimitUnit::ALL.iter().map(|u|
26977        // (u.into(), *u)))`-style per-unit lookup reaches through —
26978        // closing the two-way owned/borrowed input-shape symmetry on
26979        // the M3 slot enum's forward-projection trait-idiomatic axis.
26980        // Peer of the sibling
26981        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
26982        // (64aa742),
26983        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
26984        // (5ab993a),
26985        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
26986        // (807b0b5),
26987        // [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
26988        // (e941836),
26989        // [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
26990        // (842c7f3),
26991        // [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
26992        // (4d941d8), and
26993        // [`tests::wit_shape_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
26994        // (3187bd0) partition pins on the sibling closed-set typed-enum
26995        // discriminator axes — extends the borrowed-input axis
26996        // discipline onto the third (and last) M3-mesh-primitive-
26997        // defining closed-set typed enum on the caixa surface (the
26998        // `:politicas :rate-limit` canonical-suffix axis). Also closes
26999        // the direct two-way `&Self → &'static str → Self` round-trip
27000        // via the paired [`TryFrom<&str>`] axis — unlike the peer
27001        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
27002        // lowercase Portuguese diagnostic bytes while the reverse
27003        // `TryFrom` parses `PascalCase` wire bytes, forcing the
27004        // round-trip through an intermediate wire-vocab hop), the
27005        // [`super::RateLimitUnit::as_suffix`] emit and
27006        // [`super::RateLimitUnit::from_suffix`] parse share the same
27007        // three inline canonical-suffix byte-strings by construction,
27008        // so the borrowed-input forward axis and the reverse axis
27009        // compose directly.
27010        for &unit in super::RateLimitUnit::ALL {
27011            let owned: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
27012            let borrowed: &'static str = <&'static str as From<&super::RateLimitUnit>>::from(&unit);
27013            assert_eq!(
27014                owned, borrowed,
27015                "From<RateLimitUnit> and From<&RateLimitUnit> for \
27016                 &'static str must resolve identically on \
27017                 RateLimitUnit::{unit:?} — divergence signals the \
27018                 owned-input and borrowed-input forward-projection paths \
27019                 have drifted onto different emit-sets"
27020            );
27021        }
27022        let via_iter: Vec<&'static str> =
27023            super::RateLimitUnit::ALL.iter().map(Into::into).collect();
27024        let via_method: Vec<&'static str> = super::RateLimitUnit::ALL
27025            .iter()
27026            .map(|u| u.as_suffix())
27027            .collect();
27028        assert_eq!(
27029            via_iter, via_method,
27030            "`.iter().map(Into::into)` over RateLimitUnit::ALL must \
27031             byte-equal `.iter().map(|u| u.as_suffix())` on every arm — \
27032             the borrowed-input `From<&RateLimitUnit> for &'static str` \
27033             axis is what makes the `.iter().map(Into::into)` shape \
27034             route through the substrate-primitive \
27035             RateLimitUnit::as_suffix accessor rather than through a \
27036             per-call-site `.copied()` / dereference detour"
27037        );
27038        for unit in super::RateLimitUnit::ALL {
27039            let emitted: &'static str = unit.into();
27040            let re_parsed: Result<super::RateLimitUnit, ()> =
27041                <super::RateLimitUnit as TryFrom<&str>>::try_from(emitted);
27042            assert_eq!(
27043                re_parsed,
27044                Ok(*unit),
27045                "trait-idiomatic borrowed-input forward-projection + \
27046                 reverse-projection axis pair must round-trip \
27047                 &RateLimitUnit::{unit:?} through `.into::<&'static \
27048                 str>()` (via the borrowed-input axis) and back through \
27049                 `TryFrom<&str>` — a break signals the borrowed-input \
27050                 forward-emit and reverse-parse axes have drifted onto \
27051                 different vocabularies"
27052            );
27053        }
27054    }
27055
27056    #[test]
27057    fn rate_limit_unit_from_into_owned_string_routes_through_as_suffix_accessor() {
27058        // Fail-before-pass-after byte-parity pin on the newly lifted
27059        // `impl From<RateLimitUnit> for String` — asserts the
27060        // owned-`String`-returning standard-library trait impl and the
27061        // substrate-primitive [`super::RateLimitUnit::as_suffix`]
27062        // `pub const fn` accessor resolve to the same three-arm
27063        // canonical-suffix emit-set across every arm the exhaustive
27064        // [`super::RateLimitUnit::ALL`] slice enumerates. Rust's standard
27065        // library does not carry a blanket
27066        // `impl<T: AsRef<str>> From<T> for String` (nor an
27067        // `impl<T: fmt::Display> From<T> for String`), so the
27068        // owned-`String` forward-projection axis is a distinct trait-
27069        // idiomatic surface that a `let key: String = unit.into();`-
27070        // shaped call site reaches through this impl and no other — the
27071        // paired sibling `From<RateLimitUnit> for &'static str` impl
27072        // forces every owned-`String` call site through an explicit
27073        // `.to_owned()` / `String::from` restatement. Peer of the
27074        // first-mover
27075        // [`crate::supervisor::tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
27076        // (7baa18a), the second-peer
27077        // [`crate::supervisor::tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
27078        // (7851725), the third-peer
27079        // [`crate::kind::tests::caixa_kind_from_into_owned_string_routes_through_as_str_accessor`]
27080        // (231a18c), the fourth-peer
27081        // [`crate::dialeto::tests::caixa_dialeto_from_into_owned_string_routes_through_as_str_accessor`]
27082        // (88942cd), the fifth-peer
27083        // [`crate::dep::tests::dep_list_from_into_owned_string_routes_through_as_str_accessor`]
27084        // (32b0ee8), the sixth-peer
27085        // [`tests::placement_strategy_from_into_owned_string_routes_through_as_str_accessor`]
27086        // (1154c2f), and the seventh-peer
27087        // [`tests::wit_shape_from_into_owned_string_routes_through_as_str_accessor`]
27088        // (79a8723) — extends the trait-idiomatic owned-`String`
27089        // forward-projection axis onto the eighth closed-set fieldless
27090        // typed enum on the caixa surface (the third — and last —
27091        // M3-mesh-primitive-defining `:politicas :rate-limit`
27092        // canonical-suffix axis).
27093        for &unit in super::RateLimitUnit::ALL {
27094            let via_trait: String = <String as From<super::RateLimitUnit>>::from(unit);
27095            let via_method: &'static str = unit.as_suffix();
27096            assert_eq!(
27097                via_trait.as_str(),
27098                via_method,
27099                "From<RateLimitUnit> for String impl must round-trip \
27100                 RateLimitUnit::{unit:?} to the same three-arm \
27101                 canonical-suffix byte-string RateLimitUnit::as_suffix \
27102                 returns — divergence signals a silent detour off the \
27103                 substrate-primitive accessor"
27104            );
27105            let via_into: String = unit.into();
27106            assert_eq!(
27107                via_into.as_str(),
27108                via_method,
27109                "Into<String>::into on RateLimitUnit::{unit:?} must \
27110                 byte-equal RateLimitUnit::as_suffix on the same input — \
27111                 the blanket-derived Into shape must resolve to the same \
27112                 as_suffix dispatch as the explicit From impl"
27113            );
27114        }
27115    }
27116
27117    #[test]
27118    fn rate_limit_unit_from_into_owned_string_and_static_str_agree_on_every_arm() {
27119        // Cross-axis partition pin: the paired trait-idiomatic
27120        // owned-`String` `From<RateLimitUnit> for String` (this lift)
27121        // and owned-`&'static str` `From<RateLimitUnit> for &'static
27122        // str` (7fdfbf4) forward projections must resolve identically
27123        // on every arm, locking the two return-type-shape paths together
27124        // so any future detour trips at caixa-core test time. Also
27125        // byte-parity witness against the sibling [`ToString::to_string`]
27126        // surface routed through [`std::fmt::Display`] — the three
27127        // owned-heap-string paths (`.into::<String>()`, `String::from`,
27128        // `.to_string()`) must resolve identically on every arm so a
27129        // future consumer that picks any of the three lands on the same
27130        // three-arm inline canonical-suffix accept-set. Then a
27131        // `.iter().copied().map(String::from)` pipe witness over
27132        // [`super::RateLimitUnit::ALL`] that materializes the three-arm
27133        // accept-set through the owned-`String` axis alone — the exact
27134        // shape a future M4 admission-webhook rejection body composer
27135        // or a `HashMap::<String, RateLimitUnit>::from_iter(
27136        //   RateLimitUnit::ALL.iter().copied().map(|u| (u.into(),
27137        //   u)))`-style owned-key per-unit lookup reaches through —
27138        // closing the owned-`String` forward-projection axis's
27139        // iterator-pipe shape. Then a direct round-trip witness through
27140        // the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
27141        // the owned-`String`'s [`String::as_str`] borrow that closes the
27142        // two-way `Self → String → Self` round-trip on the trait-
27143        // idiomatic owned-`String` forward + reverse axis pair.
27144        //
27145        // Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
27146        // `From` emit lands on the lowercase Portuguese `as_str`
27147        // diagnostic vocabulary while the reverse `TryFrom<&str>`
27148        // parses the `PascalCase` `wire_name` author-surface
27149        // vocabulary, forcing the round-trip through an intermediate
27150        // [`crate::CaixaKind::wire_name`] hop),
27151        // [`super::RateLimitUnit`]'s [`super::RateLimitUnit::as_suffix`]
27152        // emit and [`super::RateLimitUnit::from_suffix`] parse resolve
27153        // through the same three inline canonical-suffix byte-strings
27154        // by construction (there is no wire/diagnostic axis split on
27155        // this enum), so the owned-`String` forward axis and the reverse
27156        // axis compose directly — matching the peer
27157        // [`crate::supervisor::RestartStrategy`] /
27158        // [`crate::supervisor::RestartPolicy`] /
27159        // [`crate::CaixaDialeto`] / [`crate::dep::DepList`] /
27160        // [`super::PlacementStrategy`] / [`super::WitShape`]
27161        // owned-`String` axis pairs.
27162        for &unit in super::RateLimitUnit::ALL {
27163            let owned_string: String = <String as From<super::RateLimitUnit>>::from(unit);
27164            let owned_static: &'static str =
27165                <&'static str as From<super::RateLimitUnit>>::from(unit);
27166            assert_eq!(
27167                owned_string.as_str(),
27168                owned_static,
27169                "From<RateLimitUnit> for String and From<RateLimitUnit> \
27170                 for &'static str must resolve identically on \
27171                 RateLimitUnit::{unit:?} — divergence signals the \
27172                 owned-`String` and owned-`&'static str` forward-\
27173                 projection return-type-shape paths have drifted onto \
27174                 different emit-sets"
27175            );
27176            let via_to_string: String = unit.to_string();
27177            assert_eq!(
27178                owned_string, via_to_string,
27179                "From<RateLimitUnit> for String must byte-equal \
27180                 RateLimitUnit::to_string on RateLimitUnit::{unit:?} — \
27181                 divergence signals the trait-idiomatic owned-`String` \
27182                 forward-projection axis and the ToString-through-\
27183                 Display axis have drifted onto different emit-sets"
27184            );
27185        }
27186        let via_iter: Vec<String> = super::RateLimitUnit::ALL
27187            .iter()
27188            .copied()
27189            .map(String::from)
27190            .collect();
27191        let via_method: Vec<String> = super::RateLimitUnit::ALL
27192            .iter()
27193            .map(|u| u.as_suffix().to_owned())
27194            .collect();
27195        assert_eq!(
27196            via_iter, via_method,
27197            "`.iter().copied().map(String::from)` over RateLimitUnit::ALL \
27198             must byte-equal `.iter().map(|u| u.as_suffix().to_owned())` \
27199             on every arm — the owned-`String` `From<RateLimitUnit> for \
27200             String` axis is what makes the `String::from` composition \
27201             route through the substrate-primitive \
27202             RateLimitUnit::as_suffix accessor rather than through a \
27203             per-call-site `.to_owned()` / `String::from(unit.as_suffix())` \
27204             detour"
27205        );
27206        for &unit in super::RateLimitUnit::ALL {
27207            let emitted: String = unit.into();
27208            let re_parsed: Result<super::RateLimitUnit, ()> =
27209                <super::RateLimitUnit as TryFrom<&str>>::try_from(emitted.as_str());
27210            assert_eq!(
27211                re_parsed,
27212                Ok(unit),
27213                "trait-idiomatic owned-`String` forward-projection + \
27214                 reverse-projection axis pair must round-trip \
27215                 RateLimitUnit::{unit:?} through `.into::<String>()` and \
27216                 back through `TryFrom<&str>` on the owned-`String`'s \
27217                 String::as_str borrow — a break signals the \
27218                 owned-`String` forward-emit and reverse-parse axes have \
27219                 drifted onto different vocabularies (unlike the peer \
27220                 CaixaKind axis pair, RateLimitUnit's forward emit and \
27221                 reverse parse share the same three inline canonical-\
27222                 suffix byte-strings by construction, so the round-trip \
27223                 composes directly)"
27224            );
27225        }
27226    }
27227
27228    #[test]
27229    fn rate_limit_unit_from_into_borrowed_owned_string_routes_through_as_suffix_accessor() {
27230        // Fail-before-pass-after byte-parity pin on the newly lifted
27231        // `impl From<&RateLimitUnit> for String` — asserts the
27232        // borrowed-input owned-`String`-returning standard-library
27233        // trait impl and the substrate-primitive
27234        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
27235        // resolve to the same three-arm canonical-suffix emit-set across
27236        // every arm the exhaustive [`super::RateLimitUnit::ALL`] slice
27237        // enumerates. Rust's standard library does not carry a blanket
27238        // `impl<T: AsRef<str>> From<&T> for String` (nor an
27239        // `impl<T: fmt::Display> From<&T> for String`), so the
27240        // borrowed-input owned-`String` forward-projection axis is a
27241        // distinct trait-idiomatic surface that a
27242        // `let key: String = (&unit).into();`-shaped call site reaches
27243        // through this impl and no other — the paired sibling
27244        // `From<RateLimitUnit> for String` impl forces every borrowed-\
27245        // input call site through an explicit `Copy` deref
27246        // (`String::from(*unit)`) or an `.as_suffix().to_owned()` /
27247        // `.to_string()` detour. Peer of the first-mover
27248        // [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
27249        // (579385f), the second-peer
27250        // [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
27251        // (8465740), the third-peer
27252        // [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
27253        // (e0cb617), the fourth-peer
27254        // [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
27255        // (e76436d), the fifth-peer
27256        // [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
27257        // (d3c0d1d), the sixth-peer
27258        // [`tests::placement_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
27259        // (d3dc000), and the seventh-peer
27260        // [`tests::wit_shape_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
27261        // (d638fd3) — extends the trait-idiomatic borrowed-input owned-\
27262        // `String` forward-projection axis onto the eighth closed-set
27263        // fieldless typed enum on the caixa surface (the third — and
27264        // last — M3-mesh-primitive-defining `:politicas :rate-limit`
27265        // canonical-suffix axis).
27266        for &unit in super::RateLimitUnit::ALL {
27267            let via_trait: String = <String as From<&super::RateLimitUnit>>::from(&unit);
27268            let via_method: &'static str = unit.as_suffix();
27269            assert_eq!(
27270                via_trait.as_str(),
27271                via_method,
27272                "From<&RateLimitUnit> for String impl must round-trip \
27273                 &RateLimitUnit::{unit:?} to the same three-arm \
27274                 canonical-suffix byte-string RateLimitUnit::as_suffix \
27275                 returns — divergence signals a silent detour off the \
27276                 substrate-primitive accessor"
27277            );
27278            let via_into: String = (&unit).into();
27279            assert_eq!(
27280                via_into.as_str(),
27281                via_method,
27282                "Into<String>::into on &RateLimitUnit::{unit:?} must \
27283                 byte-equal RateLimitUnit::as_suffix on the same input — \
27284                 the blanket-derived Into shape must resolve to the same \
27285                 as_suffix dispatch as the explicit From impl"
27286            );
27287        }
27288    }
27289
27290    #[test]
27291    fn rate_limit_unit_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
27292        // Cross-axis partition pin: the newly lifted trait-idiomatic
27293        // borrowed-input owned-`String` `From<&RateLimitUnit> for String`
27294        // (this lift), the paired owned-input owned-`String`
27295        // `From<RateLimitUnit> for String` (c7d687d), the paired
27296        // borrowed-input owned-`&'static str`
27297        // `From<&RateLimitUnit> for &'static str` (f4b9e6b), and the
27298        // paired owned-input owned-`&'static str`
27299        // `From<RateLimitUnit> for &'static str` (7fdfbf4) — every
27300        // corner of the `{Self, &Self} × {&'static str, String}` 2×2
27301        // trait-idiomatic projection family — must resolve identically
27302        // on every arm, locking the four return-shape × input-shape
27303        // paths together so any future detour trips at caixa-core test
27304        // time. Also byte-parity witness against the sibling
27305        // [`ToString::to_string`] surface routed through
27306        // [`std::fmt::Display`] and a direct round-trip witness through
27307        // the paired trait-idiomatic reverse [`TryFrom<&str>`] axis on
27308        // the owned-`String`'s [`String::as_str`] borrow that closes the
27309        // two-way `&Self → String → Self` round-trip on the trait-\
27310        // idiomatic borrowed-input owned-`String` forward + reverse
27311        // axis pair. Peer of the first-mover
27312        // [`crate::supervisor::tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
27313        // (579385f), the second-peer
27314        // [`crate::supervisor::tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
27315        // (8465740), the third-peer
27316        // [`crate::dep::tests::dep_list_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
27317        // (e0cb617), the fourth-peer
27318        // [`crate::kind::tests::caixa_kind_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
27319        // (e76436d), the fifth-peer
27320        // [`crate::dialeto::tests::caixa_dialeto_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
27321        // (d3c0d1d), the sixth-peer
27322        // [`tests::placement_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
27323        // (d3dc000), and the seventh-peer
27324        // [`tests::wit_shape_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
27325        // (d638fd3) — closes the whole
27326        // `{Self, &Self} × {&'static str, String}` 2×2 projection
27327        // corner across the whole M3 mesh-primitive triple on the
27328        // eighth substrate-wide closed-set fieldless typed enum peer
27329        // (the third — and last — M3-mesh-primitive-defining
27330        // `:politicas :rate-limit` canonical-suffix axis).
27331        //
27332        // Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
27333        // `From` emit lands on the lowercase Portuguese `as_str`
27334        // diagnostic vocabulary while the reverse `TryFrom<&str>`
27335        // parses the `PascalCase` `wire_name` author-surface
27336        // vocabulary, forcing the round-trip through an intermediate
27337        // [`crate::CaixaKind::wire_name`] hop),
27338        // [`super::RateLimitUnit`]'s [`super::RateLimitUnit::as_suffix`]
27339        // emit and [`super::RateLimitUnit::from_suffix`] parse resolve
27340        // through the same three inline canonical-suffix byte-strings
27341        // by construction (there is no wire/diagnostic axis split on
27342        // this M3 slot enum), so the borrowed-input owned-`String`
27343        // forward axis and the reverse axis compose directly — matching
27344        // the peer [`crate::supervisor::RestartStrategy`] /
27345        // [`crate::supervisor::RestartPolicy`] / [`crate::dep::DepList`]
27346        // / [`crate::CaixaDialeto`] / [`super::PlacementStrategy`] /
27347        // [`super::WitShape`] borrowed-input owned-`String` axis pairs.
27348        for &unit in super::RateLimitUnit::ALL {
27349            let borrowed_string: String = <String as From<&super::RateLimitUnit>>::from(&unit);
27350            let owned_string: String = <String as From<super::RateLimitUnit>>::from(unit);
27351            let borrowed_static: &'static str =
27352                <&'static str as From<&super::RateLimitUnit>>::from(&unit);
27353            let owned_static: &'static str =
27354                <&'static str as From<super::RateLimitUnit>>::from(unit);
27355            assert_eq!(
27356                borrowed_string, owned_string,
27357                "From<&RateLimitUnit> for String and From<RateLimitUnit> \
27358                 for String must resolve identically on RateLimitUnit::\
27359                 {unit:?} — divergence signals the borrowed-input and \
27360                 owned-input owned-`String` forward-projection input-\
27361                 shape paths have drifted onto different emit-sets"
27362            );
27363            assert_eq!(
27364                borrowed_string.as_str(),
27365                borrowed_static,
27366                "From<&RateLimitUnit> for String and From<&RateLimitUnit> \
27367                 for &'static str must resolve identically on \
27368                 RateLimitUnit::{unit:?} — divergence signals the \
27369                 borrowed-input `&'static str` and owned-`String` \
27370                 return-shape paths have drifted onto different \
27371                 emit-sets"
27372            );
27373            assert_eq!(
27374                borrowed_string.as_str(),
27375                owned_static,
27376                "From<&RateLimitUnit> for String and From<RateLimitUnit> \
27377                 for &'static str must resolve identically on \
27378                 RateLimitUnit::{unit:?} — divergence signals a break \
27379                 in the diagonal corner of the {{Self, &Self}} × \
27380                 {{&'static str, String}} 2×2 trait-idiomatic \
27381                 projection family"
27382            );
27383            let via_to_string: String = unit.to_string();
27384            assert_eq!(
27385                borrowed_string, via_to_string,
27386                "From<&RateLimitUnit> for String must byte-equal \
27387                 RateLimitUnit::to_string on RateLimitUnit::{unit:?} — \
27388                 divergence signals the trait-idiomatic borrowed-input \
27389                 owned-`String` forward-projection axis and the \
27390                 ToString-through-Display axis have drifted onto \
27391                 different emit-sets"
27392            );
27393        }
27394        let via_iter: Vec<String> = super::RateLimitUnit::ALL.iter().map(String::from).collect();
27395        let via_method: Vec<String> = super::RateLimitUnit::ALL
27396            .iter()
27397            .map(|u| u.as_suffix().to_owned())
27398            .collect();
27399        assert_eq!(
27400            via_iter, via_method,
27401            "`.iter().map(String::from)` over RateLimitUnit::ALL — a \
27402             call site whose iteration axis holds `&RateLimitUnit` by \
27403             construction — must byte-equal `.iter().map(|u| \
27404             u.as_suffix().to_owned())` on every arm — the borrowed-\
27405             input owned-`String` `From<&RateLimitUnit> for String` \
27406             axis is what makes the `String::from` composition route \
27407             through the substrate-primitive RateLimitUnit::as_suffix \
27408             accessor without a spurious `Copy` deref (which would \
27409             only be reachable through the owned-input \
27410             `From<RateLimitUnit> for String` axis by first calling \
27411             `.copied()` on the iterator)"
27412        );
27413        for &unit in super::RateLimitUnit::ALL {
27414            let emitted: String = (&unit).into();
27415            let re_parsed: Result<super::RateLimitUnit, ()> =
27416                <super::RateLimitUnit as TryFrom<&str>>::try_from(emitted.as_str());
27417            assert_eq!(
27418                re_parsed,
27419                Ok(unit),
27420                "trait-idiomatic borrowed-input owned-`String` \
27421                 forward-projection + reverse-projection axis pair \
27422                 must round-trip &RateLimitUnit::{unit:?} through \
27423                 `.into::<String>()` on the borrowed-input surface and \
27424                 back through `TryFrom<&str>` on the owned-`String`'s \
27425                 String::as_str borrow — a break signals the \
27426                 borrowed-input owned-`String` forward-emit and \
27427                 reverse-parse axes have drifted onto different \
27428                 vocabularies (unlike the peer CaixaKind axis pair, \
27429                 RateLimitUnit's forward emit and reverse parse share \
27430                 the same three inline canonical-suffix byte-strings \
27431                 by construction, so the round-trip composes directly)"
27432            );
27433        }
27434    }
27435
27436    #[test]
27437    fn rate_limit_unit_from_into_static_cow_str_routes_through_as_suffix_accessor() {
27438        // Fail-before-pass-after byte-parity pin on the newly lifted
27439        // `impl From<RateLimitUnit> for
27440        // std::borrow::Cow<'static, str>` — asserts the standard-
27441        // library trait impl and the substrate-primitive
27442        // [`super::RateLimitUnit::as_suffix`] `pub const fn`
27443        // accessor resolve to the same three-arm emit-set across
27444        // every arm the exhaustive [`super::RateLimitUnit::ALL`]
27445        // slice enumerates. Rust's standard library does not carry a
27446        // blanket `impl<T: AsRef<str>> From<T> for Cow<'static, str>`
27447        // (nor an `impl<T: fmt::Display> From<T> for
27448        // Cow<'static, str>`), so the `Cow<'static, str>` forward-
27449        // projection axis is a distinct trait-idiomatic surface that
27450        // a `let key: Cow<'static, str> = unit.into();`-shaped call
27451        // site reaches through this impl and no other — the paired
27452        // sibling `From<RateLimitUnit> for &'static str` and
27453        // `From<RateLimitUnit> for String` impls force every
27454        // `Cow<'static, str>`-parameterized call site through a
27455        // `Cow::Borrowed(unit.as_suffix())` /
27456        // `Cow::Owned(unit.to_string())` composition whose type
27457        // bounds have no compile-time link back to the substrate
27458        // primitive.
27459        //
27460        // Also asserts the projection lands on the zero-alloc
27461        // [`std::borrow::Cow::Borrowed`] arm (not the
27462        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
27463        // [`super::RateLimitUnit::as_suffix`] accessor's
27464        // `&'static str` return lifetime by construction (each match
27465        // arm resolves to one of the three inline `"s"` / `"m"` /
27466        // `"h"` canonical-suffix `&'static str` values) makes the
27467        // borrowed arm the type-correct projection with no runtime
27468        // allocation. Any future silent detour that routes the impl
27469        // through the owned arm trips at caixa-core test time under
27470        // the [`std::borrow::Cow::Borrowed`] discriminator witness
27471        // rather than at a downstream `Cow<'static, str>`-bound
27472        // consumer's silent allocation.
27473        //
27474        // Third — and last — M3-mesh-primitive-defining peer on the
27475        // substrate-wide trait-idiomatic
27476        // [`std::borrow::Cow<'static, str>`] forward-projection
27477        // campaign — extends the axis off the paired
27478        // [`super::WitShape`] `:contratos :wit` census-label first-
27479        // mover (8634dec + 25690ef) and the paired
27480        // [`super::PlacementStrategy`] `:placement :estrategia`
27481        // distribution-strategy second-peer (eee504d + afdf0f4) onto
27482        // the third — and last — M3-slot-enum peer, closing the M3-
27483        // mesh-shape tier of the campaign's owned-input corner.
27484        for &variant in super::RateLimitUnit::ALL {
27485            let via_trait: std::borrow::Cow<'static, str> =
27486                <std::borrow::Cow<'static, str> as From<super::RateLimitUnit>>::from(variant);
27487            let via_method: &'static str = variant.as_suffix();
27488            assert_eq!(
27489                via_trait.as_ref(),
27490                via_method,
27491                "From<RateLimitUnit> for Cow<'static, str> impl must \
27492                 round-trip RateLimitUnit::{variant:?} to the same \
27493                 inline canonical-suffix byte-string \
27494                 RateLimitUnit::as_suffix returns — divergence \
27495                 signals a silent detour off the substrate-primitive \
27496                 accessor"
27497            );
27498            assert!(
27499                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
27500                "From<RateLimitUnit> for Cow<'static, str> impl must \
27501                 land on the zero-alloc Cow::Borrowed arm on \
27502                 RateLimitUnit::{variant:?} — a Cow::Owned outcome \
27503                 signals the projection has silently allocated where \
27504                 the substrate-primitive RateLimitUnit::as_suffix \
27505                 `&'static str` return makes the borrowed arm the \
27506                 type-correct projection"
27507            );
27508            let via_into: std::borrow::Cow<'static, str> = variant.into();
27509            assert_eq!(
27510                via_into.as_ref(),
27511                via_method,
27512                "Into<Cow<'static, str>>::into on RateLimitUnit::\
27513                 {variant:?} must byte-equal RateLimitUnit::as_suffix \
27514                 on the same input — the blanket-derived Into shape \
27515                 must resolve to the same as_suffix dispatch as the \
27516                 explicit From impl"
27517            );
27518            assert!(
27519                matches!(via_into, std::borrow::Cow::Borrowed(_)),
27520                "Into<Cow<'static, str>>::into on RateLimitUnit::\
27521                 {variant:?} must land on the zero-alloc \
27522                 Cow::Borrowed arm — the blanket-derived Into shape \
27523                 must resolve to the same Cow::Borrowed dispatch as \
27524                 the explicit From impl"
27525            );
27526        }
27527    }
27528
27529    #[test]
27530    fn rate_limit_unit_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
27531        // Cross-axis partition pin: the newly lifted trait-idiomatic
27532        // `From<RateLimitUnit> for std::borrow::Cow<'static, str>`
27533        // (this lift), the paired owned-input `From<RateLimitUnit>
27534        // for &'static str` (7fdfbf4), and the paired owned-input
27535        // `From<RateLimitUnit> for String` (c7d687d) forward
27536        // projections must resolve identically on every arm, locking
27537        // the three return-shape paths together by construction so
27538        // any future detour trips at caixa-core test time. Also
27539        // byte-parity witness against the sibling
27540        // [`ToString::to_string`] surface routed through
27541        // [`std::fmt::Display`] — every owned-heap-string path (the
27542        // `Cow::Owned` promotion of this axis's `.into_owned()`,
27543        // `From<RateLimitUnit> for String`, and `.to_string()`)
27544        // resolves to the same three-arm inline canonical-suffix
27545        // byte-string per arm.
27546        //
27547        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
27548        // witness over [`super::RateLimitUnit::ALL`] that
27549        // materializes the three-arm accept-set through the
27550        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
27551        // shape a future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
27552        // admission-webhook rejection body's accepted-`:politicas
27553        // :rate-limit` canonical-suffix enumeration, a future
27554        // substrate-wide per-arm diagnostic surface whose typing
27555        // rules out the sibling [`AsRef<str>`] borrowed return, or a
27556        // future per-arm rate-limit-suffix emitter that binds
27557        // through a [`Cow<'static, str>`] boundary reaches through —
27558        // closing the composable-projection axis on the third — and
27559        // last — M3-mesh-primitive-defining closed-set fieldless
27560        // typed enum peer on the caixa surface. The pipe witness
27561        // also pins the zero-alloc discipline: every element in the
27562        // collected vector satisfies the
27563        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
27564        // accidental silent-allocation regression on the pipe's
27565        // iteration axis is a caixa-core-test-time failure.
27566        for &variant in super::RateLimitUnit::ALL {
27567            let via_cow: std::borrow::Cow<'static, str> =
27568                <std::borrow::Cow<'static, str> as From<super::RateLimitUnit>>::from(variant);
27569            let via_static: &'static str =
27570                <&'static str as From<super::RateLimitUnit>>::from(variant);
27571            let via_string: String = <String as From<super::RateLimitUnit>>::from(variant);
27572            assert_eq!(
27573                via_cow.as_ref(),
27574                via_static,
27575                "From<RateLimitUnit> for Cow<'static, str> and \
27576                 From<RateLimitUnit> for &'static str must resolve \
27577                 identically on RateLimitUnit::{variant:?} — \
27578                 divergence signals the Cow<'static, str> and \
27579                 &'static str return-shape paths have drifted onto \
27580                 different emit-sets"
27581            );
27582            assert_eq!(
27583                via_cow.as_ref(),
27584                via_string.as_str(),
27585                "From<RateLimitUnit> for Cow<'static, str> and \
27586                 From<RateLimitUnit> for String must resolve \
27587                 identically on RateLimitUnit::{variant:?} — \
27588                 divergence signals the Cow<'static, str> and String \
27589                 return-shape paths have drifted onto different \
27590                 emit-sets"
27591            );
27592            let via_to_string: String = variant.to_string();
27593            assert_eq!(
27594                via_cow.as_ref(),
27595                via_to_string.as_str(),
27596                "From<RateLimitUnit> for Cow<'static, str> must \
27597                 byte-equal RateLimitUnit::to_string on \
27598                 RateLimitUnit::{variant:?} — divergence signals the \
27599                 trait-idiomatic Cow<'static, str> forward-\
27600                 projection axis and the ToString-through-Display \
27601                 axis have drifted onto different emit-sets"
27602            );
27603        }
27604        let via_iter: Vec<std::borrow::Cow<'static, str>> = super::RateLimitUnit::ALL
27605            .iter()
27606            .copied()
27607            .map(std::borrow::Cow::from)
27608            .collect();
27609        let via_method: Vec<std::borrow::Cow<'static, str>> = super::RateLimitUnit::ALL
27610            .iter()
27611            .map(|u| std::borrow::Cow::Borrowed(u.as_suffix()))
27612            .collect();
27613        assert_eq!(
27614            via_iter, via_method,
27615            "`.iter().copied().map(Cow::from)` over \
27616             RateLimitUnit::ALL must byte-equal `.iter().map(|u| \
27617             Cow::Borrowed(u.as_suffix()))` on every arm — the \
27618             trait-idiomatic `From<RateLimitUnit> for \
27619             Cow<'static, str>` axis is what makes the `Cow::from` \
27620             composition route through the substrate-primitive \
27621             `RateLimitUnit::as_suffix` accessor with the zero-alloc \
27622             Cow::Borrowed arm by construction, rather than a per-\
27623             call-site `Cow::Owned(unit.to_string())` allocation"
27624        );
27625        for cow in &via_iter {
27626            assert!(
27627                matches!(cow, std::borrow::Cow::Borrowed(_)),
27628                "every element of the .iter().copied().map(Cow::from) \
27629                 pipe over RateLimitUnit::ALL must land on the zero-\
27630                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
27631                 any arm signals the pipe's iteration axis has \
27632                 silently allocated where the substrate-primitive \
27633                 RateLimitUnit::as_suffix `&'static str` return makes \
27634                 the borrowed arm the type-correct projection"
27635            );
27636        }
27637    }
27638
27639    #[test]
27640    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
27641        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
27642        // every canonical `:window` magnitude the validate gate
27643        // accepts must map to the paired [`RateLimitUnit`] arm through
27644        // this accessor. A future validate-gate rebrand that widened
27645        // the accepted-window set without extending [`RateLimitUnit`]
27646        // would silently split the accessor's `Some`-return set from
27647        // the validate gate's accept-set — a slot that satisfies
27648        // validate would land at the accessor with `None`, so a
27649        // consumer past validate that pattern-matches on the returned
27650        // `Some` would silently miss the newly-accepted magnitude.
27651        for (window_secs, expected) in [
27652            (1u64, super::RateLimitUnit::Second),
27653            (60, super::RateLimitUnit::Minute),
27654            (3600, super::RateLimitUnit::Hour),
27655        ] {
27656            let rl = RateLimit {
27657                rate: 100,
27658                window: Duration::from_secs(window_secs),
27659            };
27660            assert_eq!(
27661                rl.canonical_unit(),
27662                Some(expected),
27663                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
27664                 must return Some({expected:?})"
27665            );
27666        }
27667        // Non-canonical windows the validate gate rejects also return
27668        // None here — the accessor is the typed-enum projection of
27669        // the sibling `is_canonical_rate_limit_window` predicate.
27670        let bad = RateLimit {
27671            rate: 100,
27672            window: Duration::from_secs(30),
27673        };
27674        assert!(
27675            bad.canonical_unit().is_none(),
27676            "RateLimit with a non-canonical window must return None from \
27677             canonical_unit — the validate gate rejects the same set"
27678        );
27679    }
27680
27681    #[test]
27682    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
27683        // Fail-before-pass-after byte-parity pin: for every canonical
27684        // window the [`rate_limit_codec::render`] arm's emitted string
27685        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
27686        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
27687        // the vestigial free helper [`rate_limit_window_unit`] (a
27688        // `find_map`-walked `Duration → &'static str` delegate) onto the
27689        // substrate primitive [`RateLimit::canonical_unit`] typed method
27690        // (a closed-set `match self.window` arm on
27691        // [`RateLimitUnit::from_window`], projected through
27692        // [`RateLimitUnit::as_suffix`] via the enum's
27693        // [`std::fmt::Display`] impl). A future re-routing of the render
27694        // arm through a differently-computed unit projection would break
27695        // this pin at build time rather than as a silent per-consumer
27696        // codec round-trip drift far from the substrate primitive edit.
27697        //
27698        // Sibling to the peer
27699        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
27700        // on the free-helper axis: that pin locks the two projections
27701        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
27702        // on the closed-set arm table; this pin locks the codec's render
27703        // arm reads through the typed accessor rather than the free
27704        // helper. Two production consumers of the canonical-unit axis
27705        // now key off one typed dispatch on the substrate primitive.
27706        for (window_secs, unit) in [
27707            (1u64, super::RateLimitUnit::Second),
27708            (60, super::RateLimitUnit::Minute),
27709            (3600, super::RateLimitUnit::Hour),
27710        ] {
27711            let rl = RateLimit {
27712                rate: 42,
27713                window: Duration::from_secs(window_secs),
27714            };
27715            let policy = MeshPolicy {
27716                rate_limit: Some(rl),
27717                ..Default::default()
27718            };
27719            let json = serde_json::to_string(&policy).unwrap();
27720            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
27721            assert!(
27722                json.contains(&expected),
27723                "rate_limit_codec::render must emit {expected} (via \
27724                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
27725                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
27726            );
27727            // And the accessor route resolves to the same typed unit
27728            // the render arm's Display formatting is asked to produce —
27729            // so a future edit that split the two paths (one through
27730            // the accessor, one through a re-introduced free helper)
27731            // trips this pin.
27732            assert_eq!(
27733                rl.canonical_unit(),
27734                Some(unit),
27735                "RateLimit::canonical_unit must return Some({unit:?}) for a \
27736                 {window_secs}s window; the codec render arm reads the same \
27737                 typed unit through this accessor"
27738            );
27739        }
27740    }
27741
27742    #[test]
27743    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
27744        // Fail-before-pass-after byte-parity pin on the validate gate's
27745        // canonical-window shape probe: every non-canonical `:window`
27746        // the free-helper predicate [`is_canonical_rate_limit_window`]
27747        // rejects is also rejected by the substrate primitive
27748        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
27749        // gate now reads through, and vice versa on the accepted set
27750        // (the three canonical windows). Locks the migration from the
27751        // free helper onto the substrate primitive: a future re-routing
27752        // of one of the two paths through a differently-computed unit
27753        // projection would silently split the codec's accepted set from
27754        // the validate gate's accepted set — a two-consumer drift the
27755        // codec-round-trip pin
27756        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
27757        // above closes on the render arm and this pin closes on the
27758        // validate arm.
27759        for canonical_window_secs in [1u64, 60, 3600] {
27760            let mut s = three_member_spec();
27761            let rl = RateLimit {
27762                rate: 100,
27763                window: Duration::from_secs(canonical_window_secs),
27764            };
27765            s.politicas.rate_limit = Some(rl);
27766            assert!(
27767                s.validate().is_ok(),
27768                "canonical {canonical_window_secs}s window must pass \
27769                 validate_politicas — the validate gate now reads \
27770                 RateLimit::canonical_unit().is_none() and the accessor \
27771                 returns Some on every canonical arm"
27772            );
27773            assert!(
27774                rl.canonical_unit().is_some(),
27775                "canonical {canonical_window_secs}s window must resolve to \
27776                 Some on RateLimit::canonical_unit — the validate gate reads \
27777                 this accessor directly"
27778            );
27779        }
27780        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
27781            let mut s = three_member_spec();
27782            let rl = RateLimit {
27783                rate: 100,
27784                window: Duration::from_secs(non_canonical_window_secs),
27785            };
27786            s.politicas.rate_limit = Some(rl);
27787            assert_eq!(
27788                s.validate().unwrap_err(),
27789                AplicacaoError::PolicyRateLimitWindowNotCanonical {
27790                    window: rl.window(),
27791                },
27792                "non-canonical {non_canonical_window_secs}s window must be \
27793                 rejected by validate_politicas — the validate gate now \
27794                 keys off RateLimit::canonical_unit().is_none()"
27795            );
27796            assert!(
27797                rl.canonical_unit().is_none(),
27798                "non-canonical {non_canonical_window_secs}s window must \
27799                 resolve to None on RateLimit::canonical_unit — the two \
27800                 paths (the free helper the validate gate previously read \
27801                 and the substrate primitive the validate gate now reads) \
27802                 must agree on the same rejected set"
27803            );
27804        }
27805        // And the substrate-primitive [`RateLimit::canonical_unit`]
27806        // accessor's accepted-window set matches the codec's parse arm's
27807        // accepted-suffix set on every canonical / non-canonical shape,
27808        // so a future silent drift between the codec's accepted set and
27809        // the validate gate's accepted set is a build error at test time
27810        // (both consumers key off the same closed-set enum's `match self`
27811        // arms). The predecessor free helper `is_canonical_rate_limit_window`
27812        // — a delegate that composed [`RateLimitUnit::from_window`] with
27813        // `.is_some()` — was deleted after this migration; the
27814        // canonical-window set now lives on exactly one typed dispatch
27815        // on the substrate primitive.
27816        for (secs, expected) in [
27817            (1u64, true),
27818            (60, true),
27819            (3600, true),
27820            (2, false),
27821            (30, false),
27822            (86_400, false),
27823        ] {
27824            let window = Duration::from_secs(secs);
27825            let rl = RateLimit { rate: 1, window };
27826            assert_eq!(
27827                rl.canonical_unit().is_some(),
27828                expected,
27829                "RateLimit::canonical_unit().is_some() must agree with the \
27830                 codec-accepted canonical-window set on {secs}s"
27831            );
27832            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
27833                1 => "s",
27834                60 => "m",
27835                3600 => "h",
27836                _ => return,
27837            })
27838            .is_some_and(|d| d == window);
27839            if expected {
27840                assert!(
27841                    suffix_from_axis,
27842                    "the codec's `&str → Duration` axis \
27843                     ({secs}s) must round-trip to the same Duration the \
27844                     substrate primitive's accessor returns Some on"
27845                );
27846            }
27847        }
27848    }
27849
27850    #[test]
27851    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
27852        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
27853        // derive: for each of the three variants, exactly one of the
27854        // generated `is_second` / `is_minute` / `is_hour` predicates
27855        // returns `true` and the other two return `false`. Peer of
27856        // the sibling
27857        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
27858        // sibling `IsVariant`-derived closed-set typed-enum pins.
27859        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
27860            (super::RateLimitUnit::Second, [true, false, false]),
27861            (super::RateLimitUnit::Minute, [false, true, false]),
27862            (super::RateLimitUnit::Hour, [false, false, true]),
27863        ];
27864        for (variant, expected) in rows {
27865            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
27866            assert_eq!(
27867                observed, expected,
27868                "RateLimitUnit::{variant:?} is_* predicates must partition \
27869                 the arm set (second, minute, hour); got {observed:?}"
27870            );
27871        }
27872    }
27873
27874    #[test]
27875    fn rejects_policy_timeout_sub_millisecond() {
27876        // A purely sub-millisecond `Duration` (`from_micros(500)` =
27877        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
27878        // arm passes — but `as_millis() == 0`, so the shared codec's
27879        // `render` arm returns the literal `"0s"`, which the
27880        // codec's `parse` arm then deserializes as `Duration::ZERO`
27881        // and the `PolicyTimeoutZero` zero-floor gate would reject
27882        // on re-validate. Pin the rejection at the typed slot's
27883        // canonical-floor gate so the round-trip break surfaces at
27884        // validate time, naming the offending `Duration`, rather
27885        // than at the next serialize → deserialize round-trip far
27886        // from the source `caixa.lisp`.
27887        let mut s = three_member_spec();
27888        let timeout = Duration::from_micros(500);
27889        s.politicas.timeout = Some(timeout);
27890        assert_eq!(
27891            s.validate().unwrap_err(),
27892            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
27893        );
27894    }
27895
27896    #[test]
27897    fn rejects_policy_timeout_non_integer_millisecond() {
27898        // A `Duration` with non-integer-millisecond residue
27899        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
27900        // through the shared codec's `render` arm as `"1ms"` (the
27901        // `as_millis()` floor truncates), which the codec's `parse`
27902        // arm then deserializes as `Duration::from_millis(1)` =
27903        // 1_000_000 ns — silently *different* from the original.
27904        // Pin the rejection so this round-trip break surfaces at
27905        // validate time, where the offending `Duration` is named,
27906        // rather than as a silent value-laundered round-trip on the
27907        // next codec round-trip.
27908        let mut s = three_member_spec();
27909        let timeout = Duration::from_micros(1500);
27910        s.politicas.timeout = Some(timeout);
27911        assert_eq!(
27912            s.validate().unwrap_err(),
27913            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
27914        );
27915    }
27916
27917    #[test]
27918    fn accepts_policy_timeout_integer_millisecond_forms() {
27919        // The codec's accepted set — integer multiples of 1ms — is
27920        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
27921        // `1h` all pass the canonical gate. Pin the canonical-forms
27922        // sweep so a future tightening of the codec's grammar (e.g.
27923        // dropping `:ms`) surfaces here as a test failure rather
27924        // than a silent contract narrowing on the typed slot.
27925        for timeout in [
27926            Duration::from_millis(1),
27927            Duration::from_millis(500),
27928            Duration::from_millis(1500),
27929            Duration::from_secs(30),
27930            Duration::from_secs(120),
27931            Duration::from_secs(3600),
27932        ] {
27933            let mut s = three_member_spec();
27934            s.politicas.timeout = Some(timeout);
27935            s.validate()
27936                .expect("integer-millisecond :timeout must validate");
27937        }
27938    }
27939
27940    #[test]
27941    fn policy_timeout_zero_takes_precedence_over_canonical() {
27942        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
27943        // pass the canonical-millisecond gate; the more self-locating
27944        // `PolicyTimeoutZero` arm (which names the omit-axis
27945        // remediation directly) must fire first. Pin the ordering so
27946        // a future refactor that reorders the arms surfaces here as a
27947        // test failure rather than a silent diagnostic regression.
27948        let mut s = three_member_spec();
27949        s.politicas.timeout = Some(Duration::ZERO);
27950        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
27951    }
27952
27953    #[test]
27954    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
27955        // The diagnostic envelope carries the offending `Duration`
27956        // verbatim so the author can grep their `caixa.lisp` for
27957        // `:timeout "<value>"` and fix it in one edit. Same
27958        // diagnostic shape every other typed-slot canonical-form
27959        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
27960        // peer `:rate-limit :window` axis.
27961        let mut s = three_member_spec();
27962        let timeout = Duration::from_nanos(1_000_001);
27963        s.politicas.timeout = Some(timeout);
27964        match s.validate().unwrap_err() {
27965            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
27966                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
27967            }
27968            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
27969        }
27970    }
27971
27972    #[test]
27973    fn rejects_policy_timeout_above_cap() {
27974        // The fail-before-pass-after pin: 3601s = 1h + 1s is
27975        // structurally one canonical-tick past the
27976        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
27977        // integer-millisecond magnitude the canonical-form arm above
27978        // accepts cleanly, that the codec round-trips losslessly as
27979        // `"3601s"`, and that silently passed validate on every
27980        // pre-gate codebase because the typed slot's only checks were
27981        // the zero-floor and canonical-form arms. The mesh-level
27982        // deadline degenerates only at the runtime substrate (Envoy
27983        // / Cilium L7 timeout overlay) far from the source
27984        // `caixa.lisp` with no field naming the offending policy.
27985        let mut s = three_member_spec();
27986        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
27987        s.politicas.timeout = Some(timeout);
27988        assert_eq!(
27989            s.validate().unwrap_err(),
27990            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
27991        );
27992    }
27993
27994    #[test]
27995    fn rejects_policy_timeout_one_millisecond_above_cap() {
27996        // Boundary case: exactly 1ms past the cap (the granularity
27997        // the canonical-form gate enforces). Catches a future
27998        // "strictly less than" half-measure and pins the diagnostic
27999        // to name the offending `Duration` verbatim. Peer of
28000        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
28001        // boundary pin on the sibling `:limits :memory` top edge.
28002        let mut s = three_member_spec();
28003        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
28004        s.politicas.timeout = Some(timeout);
28005        assert_eq!(
28006            s.validate().unwrap_err(),
28007            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
28008        );
28009    }
28010
28011    #[test]
28012    fn rejects_policy_timeout_far_above_cap() {
28013        // The "obvious authoring footgun" case: a `(:timeout "24h")`
28014        // or `(:timeout "86400s")` — values the canonical-form arm
28015        // accepts as integer-millisecond magnitudes, the codec
28016        // round-trips losslessly through serde, but the mesh-level
28017        // policy cannot honor (a 24-hour synchronous-`:contratos`
28018        // deadline is operationally indistinguishable from
28019        // omit-the-axis). Until this gate landed validate accepted
28020        // it. Pin both common above-cap values (24h, 7d) so a future
28021        // relaxation that drops the upper bound surfaces here.
28022        for timeout in [
28023            Duration::from_secs(86_400),    // 24h
28024            Duration::from_secs(604_800),   // 7d
28025            Duration::from_secs(1_000_000), // ~11.5 days
28026        ] {
28027            let mut s = three_member_spec();
28028            s.politicas.timeout = Some(timeout);
28029            assert_eq!(
28030                s.validate().unwrap_err(),
28031                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
28032            );
28033        }
28034    }
28035
28036    #[test]
28037    fn accepts_policy_timeout_at_cap() {
28038        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
28039        // must validate. The cap is inclusive on the top edge,
28040        // matching the [`POLICY_RETRIES_MAX`] /
28041        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
28042        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
28043        // sibling capped axes. Pin the boundary explicitly so a
28044        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
28045        // instead of `>`) surfaces here as a test failure rather
28046        // than a silent contract narrowing.
28047        let mut s = three_member_spec();
28048        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
28049        s.validate()
28050            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
28051    }
28052
28053    #[test]
28054    fn accepts_policy_timeout_typical_values() {
28055        // The documented production-playbook band positive-control
28056        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
28057        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
28058        // plus a sweep through the long-running-workflow band
28059        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
28060        // validated set explicitly so a future tightening of the
28061        // ceiling surfaces here as a deliberate test edit, not a
28062        // silent contract narrowing.
28063        for timeout in [
28064            Duration::from_millis(1),
28065            Duration::from_millis(500),
28066            Duration::from_secs(1),
28067            Duration::from_secs(10),
28068            Duration::from_secs(15), // Envoy default
28069            Duration::from_secs(30),
28070            Duration::from_secs(60), // AWS App Mesh typical
28071            Duration::from_secs(300),
28072            Duration::from_secs(900),
28073            Duration::from_secs(1800),
28074            Duration::from_secs(3600), // exactly 1h, the cap
28075        ] {
28076            let mut s = three_member_spec();
28077            s.politicas.timeout = Some(timeout);
28078            s.validate()
28079                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
28080        }
28081    }
28082
28083    #[test]
28084    fn policy_timeout_zero_takes_precedence_over_cap() {
28085        // The cross-arm ordering pin: `Duration::ZERO` is
28086        // structurally outside both `>= 1ms` (zero-floor) and
28087        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
28088        // diagnostic is the more self-locating one (it directly
28089        // names the omit-axis remediation), so the validate gate
28090        // must fire on zero first. Same shape every other
28091        // zero-then-shape ordering on this surface uses
28092        // ([`AplicacaoError::PolicyRetriesZero`] then
28093        // [`AplicacaoError::PolicyRetriesExceedsCap`];
28094        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
28095        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
28096        let mut s = three_member_spec();
28097        s.politicas.timeout = Some(Duration::ZERO);
28098        assert_eq!(
28099            s.validate().unwrap_err(),
28100            AplicacaoError::PolicyTimeoutZero,
28101            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
28102        );
28103    }
28104
28105    #[test]
28106    fn policy_timeout_canonical_takes_precedence_over_cap() {
28107        // The cross-arm ordering pin: a `Duration` that is *both*
28108        // sub-millisecond (non-canonical-form) and structurally
28109        // above the cap surfaces the canonical-form diagnostic
28110        // first, because the round-trip-shape break is the more
28111        // fundamental issue (the value can't even round-trip
28112        // through the codec, so the cap diagnostic naming
28113        // `1ms..=1h` would be misleading — there's no integer-ms
28114        // form of the offending value). Pin the order so a future
28115        // refactor that reorders the arms surfaces here as a test
28116        // failure rather than a silent diagnostic regression.
28117        let mut s = three_member_spec();
28118        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
28119        // *and* total magnitude above the 1h cap.
28120        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
28121        s.politicas.timeout = Some(timeout);
28122        assert_eq!(
28123            s.validate().unwrap_err(),
28124            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
28125            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
28126        );
28127    }
28128
28129    #[test]
28130    fn policy_timeout_cap_diagnostic_carries_offending_value() {
28131        // The diagnostic-shape pin: the offending `Duration` is
28132        // carried verbatim into the
28133        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
28134        // surfaced error message names the value the author wrote
28135        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
28136        // exceeds the mesh-policy ceiling …"`), not just the cap.
28137        // Same self-locating diagnostic shape every other typed-cap
28138        // arm on this surface carries
28139        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
28140        // offending retry count verbatim).
28141        let mut s = three_member_spec();
28142        let timeout = Duration::from_secs(7200); // 2h
28143        s.politicas.timeout = Some(timeout);
28144        let err = s.validate().unwrap_err();
28145        assert!(
28146            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
28147            "got {err:?}"
28148        );
28149        let msg = err.to_string();
28150        assert!(
28151            msg.contains("7200"),
28152            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
28153        );
28154    }
28155
28156    #[test]
28157    fn policy_timeout_cap_pins_canonical_value() {
28158        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
28159        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
28160        // the shared duration codec emits as a clean canonical
28161        // string (`"<n>h"`). Pinning the literal value here surfaces
28162        // a future drift (a relaxation to 24h, a tightening to 5m)
28163        // as a deliberate test edit, not a silent contract
28164        // narrowing. Same shape every other typed-cap value pin on
28165        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
28166        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
28167        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
28168    }
28169
28170    #[test]
28171    fn policy_timeout_cap_value_round_trips_through_codec() {
28172        // The codec round-trip property the cap arm preserves: the
28173        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
28174        // the shared duration codec — every value at the cap renders
28175        // to a clean canonical string (`"1h"`) and parses back to
28176        // the same `Duration`. Pin this so a future drift between
28177        // the cap constant and the codec's largest emitted unit
28178        // surfaces here. Same shape every other typed boundary pin
28179        // on this surface uses
28180        // (`wasm32_memory_cap_matches_parsed_4_gib`).
28181        let policy = MeshPolicy {
28182            timeout: Some(POLICY_TIMEOUT_MAX),
28183            ..Default::default()
28184        };
28185        let json = serde_json::to_string(&policy).unwrap();
28186        // The codec emits `"1h"` for the canonical 1-hour magnitude.
28187        assert!(
28188            json.contains("\"1h\""),
28189            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
28190        );
28191        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
28192        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
28193    }
28194
28195    #[test]
28196    fn rejects_circuit_breaker_window_sub_millisecond() {
28197        // Peer of the `:timeout` sub-millisecond arm on the second
28198        // typed-`Duration` `:politicas` axis: a purely sub-ms
28199        // `Duration` (`from_micros(500)`) renders through the shared
28200        // codec as `"0s"`, which the codec parses back to
28201        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
28202        // zero-floor gate then rejects on re-validate.
28203        let mut s = three_member_spec();
28204        let window = Duration::from_micros(500);
28205        s.politicas.circuit_breaker = Some(CircuitBreaker {
28206            max_failures: 5,
28207            window,
28208        });
28209        assert_eq!(
28210            s.validate().unwrap_err(),
28211            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
28212        );
28213    }
28214
28215    #[test]
28216    fn rejects_circuit_breaker_window_non_integer_millisecond() {
28217        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
28218        // with non-integer-millisecond residue renders through the
28219        // shared codec as the truncated `"<n>ms"` form, parsing back
28220        // to a *different* `Duration` on the next round-trip.
28221        let mut s = three_member_spec();
28222        let window = Duration::from_micros(1500);
28223        s.politicas.circuit_breaker = Some(CircuitBreaker {
28224            max_failures: 5,
28225            window,
28226        });
28227        assert_eq!(
28228            s.validate().unwrap_err(),
28229            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
28230        );
28231    }
28232
28233    #[test]
28234    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
28235        // The canonical-forms sweep on the breaker axis: every
28236        // integer-ms multiple the codec round-trips losslessly
28237        // passes the canonical gate.
28238        //
28239        // Clears `:timeout` from the fixture so this per-axis sweep
28240        // covers windows shorter than the fixture's 30s timeout
28241        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
28242        // structurally-inert breaker
28243        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
28244        // the cross-axis gate at the end of
28245        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
28246        // `(:timeout, :window)` shape, not on the per-axis
28247        // integer-millisecond canonical-form shape this test pins.
28248        // The paired shape is covered by
28249        // `rejects_circuit_breaker_window_below_timeout`.
28250        for window in [
28251            Duration::from_millis(1),
28252            Duration::from_millis(500),
28253            Duration::from_millis(1500),
28254            Duration::from_secs(30),
28255            Duration::from_secs(60),
28256            Duration::from_secs(3600),
28257        ] {
28258            let mut s = three_member_spec();
28259            s.politicas.timeout = None;
28260            s.politicas.circuit_breaker = Some(CircuitBreaker {
28261                max_failures: 5,
28262                window,
28263            });
28264            s.validate()
28265                .expect("integer-millisecond :circuit-breaker :window must validate");
28266        }
28267    }
28268
28269    #[test]
28270    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
28271        // `Duration::ZERO` would pass the canonical-ms gate (the
28272        // sub-ns residue is zero) but must surface the narrower
28273        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
28274        // remediation.
28275        let mut s = three_member_spec();
28276        s.politicas.circuit_breaker = Some(CircuitBreaker {
28277            max_failures: 5,
28278            window: Duration::ZERO,
28279        });
28280        assert_eq!(
28281            s.validate().unwrap_err(),
28282            AplicacaoError::PolicyBreakerZeroWindow
28283        );
28284    }
28285
28286    #[test]
28287    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
28288        // Both axes invalid: max_failures == 0 *and* window is
28289        // sub-ms. The validate gate must fire on max_failures first
28290        // (matching the existing ordering pin
28291        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
28292        // the existing diagnostic continues to lead with the simpler
28293        // "zero threshold" framing.
28294        let mut s = three_member_spec();
28295        s.politicas.circuit_breaker = Some(CircuitBreaker {
28296            max_failures: 0,
28297            window: Duration::from_micros(500),
28298        });
28299        assert_eq!(
28300            s.validate().unwrap_err(),
28301            AplicacaoError::PolicyBreakerZeroFailures
28302        );
28303    }
28304
28305    #[test]
28306    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
28307        let mut s = three_member_spec();
28308        let window = Duration::from_nanos(60_000_000_001);
28309        s.politicas.circuit_breaker = Some(CircuitBreaker {
28310            max_failures: 5,
28311            window,
28312        });
28313        match s.validate().unwrap_err() {
28314            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
28315                assert_eq!(w, window, "diagnostic must carry the offending Duration");
28316            }
28317            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
28318        }
28319    }
28320
28321    #[test]
28322    fn rejects_circuit_breaker_window_above_cap() {
28323        // The fail-before-pass-after pin: 3601s = 1h + 1s is
28324        // structurally one canonical-tick past the
28325        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
28326        // integer-millisecond magnitude the canonical-form arm above
28327        // accepts cleanly, that the codec round-trips losslessly as
28328        // `"3601s"`, and that silently passed validate on every
28329        // pre-gate codebase because the typed slot's only checks were
28330        // the zero-floor and canonical-form arms. The
28331        // rolling-window-to-lifetime-counter degeneration surfaces
28332        // only at the runtime substrate (Envoy's outlier_detection
28333        // interval, the future CiliumClusterwideEnvoyConfig overlay)
28334        // far from the source `caixa.lisp` with no field naming the
28335        // offending policy.
28336        let mut s = three_member_spec();
28337        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
28338        s.politicas.circuit_breaker = Some(CircuitBreaker {
28339            max_failures: 5,
28340            window,
28341        });
28342        assert_eq!(
28343            s.validate().unwrap_err(),
28344            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
28345        );
28346    }
28347
28348    #[test]
28349    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
28350        // Boundary case: exactly 1ms past the cap (the granularity the
28351        // canonical-form gate enforces). Catches a future "strictly
28352        // less than" half-measure and pins the diagnostic to name the
28353        // offending `Duration` verbatim. Peer of
28354        // `rejects_policy_timeout_one_millisecond_above_cap` on the
28355        // sibling duration-typed `:politicas :timeout` top edge.
28356        let mut s = three_member_spec();
28357        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
28358        s.politicas.circuit_breaker = Some(CircuitBreaker {
28359            max_failures: 5,
28360            window,
28361        });
28362        assert_eq!(
28363            s.validate().unwrap_err(),
28364            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
28365        );
28366    }
28367
28368    #[test]
28369    fn rejects_circuit_breaker_window_far_above_cap() {
28370        // The "obvious authoring footgun" case: a `(:window "24h")` or
28371        // `(:window "86400s")` — values the canonical-form arm
28372        // accepts as integer-millisecond magnitudes, the codec
28373        // round-trips losslessly through serde, but the
28374        // rolling-window breaker contract cannot honor (a 24-hour
28375        // rolling failure window is operationally a lifetime counter).
28376        // Until this gate landed validate accepted it. Pin both common
28377        // above-cap values (24h, 7d) so a future relaxation that
28378        // drops the upper bound surfaces here.
28379        for window in [
28380            Duration::from_secs(86_400),    // 24h
28381            Duration::from_secs(604_800),   // 7d
28382            Duration::from_secs(1_000_000), // ~11.5 days
28383        ] {
28384            let mut s = three_member_spec();
28385            s.politicas.circuit_breaker = Some(CircuitBreaker {
28386                max_failures: 5,
28387                window,
28388            });
28389            assert_eq!(
28390                s.validate().unwrap_err(),
28391                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
28392            );
28393        }
28394    }
28395
28396    #[test]
28397    fn accepts_circuit_breaker_window_at_cap() {
28398        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
28399        // (1h) — must validate. The cap is inclusive on the top edge,
28400        // matching the [`POLICY_TIMEOUT_MAX`] /
28401        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
28402        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
28403        // sibling capped axes. Pin the boundary explicitly so a
28404        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
28405        // instead of `>`) surfaces here as a test failure rather than
28406        // a silent contract narrowing.
28407        let mut s = three_member_spec();
28408        s.politicas.circuit_breaker = Some(CircuitBreaker {
28409            max_failures: 5,
28410            window: POLICY_BREAKER_WINDOW_MAX,
28411        });
28412        s.validate()
28413            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
28414    }
28415
28416    #[test]
28417    fn accepts_circuit_breaker_window_typical_values() {
28418        // The documented production-playbook band positive-control
28419        // sweep — every value Hystrix / resilience4j / Istio / Envoy
28420        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
28421        // through the long-tail failure-detection band (15m, 30m, 1h)
28422        // the cap accepts. Pin the inclusive validated set explicitly
28423        // so a future tightening of the ceiling surfaces here as a
28424        // deliberate test edit, not a silent contract narrowing.
28425        //
28426        // Clears `:timeout` from the fixture so this per-axis sweep
28427        // covers windows shorter than the fixture's 30s timeout
28428        // (Hystrix's 10s default, resilience4j's 30s, and the
28429        // sub-second warm-up band) — every such value is a
28430        // structurally-inert breaker under the cross-axis gate at the
28431        // end of [`AplicacaoSpec::validate_politicas`]
28432        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
28433        // the paired `(:timeout, :window)` shape is covered by
28434        // `rejects_circuit_breaker_window_below_timeout`; this
28435        // per-axis pin ranges only over the per-axis-bracket accept set.
28436        for window in [
28437            Duration::from_millis(1),
28438            Duration::from_millis(500),
28439            Duration::from_secs(1),
28440            Duration::from_secs(10), // Hystrix / Istio / Envoy default
28441            Duration::from_secs(30),
28442            Duration::from_secs(60),  // resilience4j typical
28443            Duration::from_secs(300), // AWS App Mesh typical
28444            Duration::from_secs(900),
28445            Duration::from_secs(1800),
28446            Duration::from_secs(3600), // exactly 1h, the cap
28447        ] {
28448            let mut s = three_member_spec();
28449            s.politicas.timeout = None;
28450            s.politicas.circuit_breaker = Some(CircuitBreaker {
28451                max_failures: 5,
28452                window,
28453            });
28454            s.validate()
28455                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
28456        }
28457    }
28458
28459    #[test]
28460    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
28461        // The cross-arm ordering pin: `Duration::ZERO` is structurally
28462        // outside both `>= 1ms` (zero-floor) and
28463        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
28464        // diagnostic is the more self-locating one (it directly names
28465        // the omit-axis remediation), so the validate gate must fire
28466        // on zero first. Same shape every other zero-then-cap
28467        // ordering on this surface uses
28468        // ([`AplicacaoError::PolicyTimeoutZero`] then
28469        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
28470        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
28471        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
28472        let mut s = three_member_spec();
28473        s.politicas.circuit_breaker = Some(CircuitBreaker {
28474            max_failures: 5,
28475            window: Duration::ZERO,
28476        });
28477        assert_eq!(
28478            s.validate().unwrap_err(),
28479            AplicacaoError::PolicyBreakerZeroWindow,
28480            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
28481        );
28482    }
28483
28484    #[test]
28485    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
28486        // The cross-arm ordering pin: a `Duration` that is *both*
28487        // sub-millisecond (non-canonical-form) and structurally above
28488        // the cap surfaces the canonical-form diagnostic first,
28489        // because the round-trip-shape break is the more fundamental
28490        // issue (the value can't even round-trip through the codec, so
28491        // the cap diagnostic naming `1ms..=1h` would be misleading —
28492        // there's no integer-ms form of the offending value). Pin the
28493        // order so a future refactor that reorders the arms surfaces
28494        // here as a test failure rather than a silent diagnostic
28495        // regression. Peer of
28496        // `policy_timeout_canonical_takes_precedence_over_cap` on the
28497        // sibling duration-typed `:politicas :timeout` axis.
28498        let mut s = three_member_spec();
28499        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
28500        s.politicas.circuit_breaker = Some(CircuitBreaker {
28501            max_failures: 5,
28502            window,
28503        });
28504        assert_eq!(
28505            s.validate().unwrap_err(),
28506            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
28507            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
28508        );
28509    }
28510
28511    #[test]
28512    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
28513        // The cross-arm ordering pin between the two breaker axes: a
28514        // `CircuitBreaker` whose *both* `max_failures` is above its
28515        // cap *and* `window` is above its cap surfaces the
28516        // max-failures cap diagnostic first, because the validate
28517        // gate visits the failures arm before the window arm. Pin the
28518        // order so a future refactor that reorders the breaker arms
28519        // surfaces here.
28520        let mut s = three_member_spec();
28521        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
28522        s.politicas.circuit_breaker = Some(CircuitBreaker {
28523            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
28524            window,
28525        });
28526        assert_eq!(
28527            s.validate().unwrap_err(),
28528            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
28529                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
28530            },
28531            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
28532        );
28533    }
28534
28535    #[test]
28536    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
28537        // The diagnostic-shape pin: the offending `Duration` is
28538        // carried verbatim into the
28539        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
28540        // the surfaced error message names the value the author wrote
28541        // (`":politicas :circuit-breaker :window (Duration { secs:
28542        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
28543        // just the cap. Same self-locating diagnostic shape every
28544        // other typed-cap arm on this surface carries
28545        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
28546        // offending `Duration` verbatim).
28547        let mut s = three_member_spec();
28548        let window = Duration::from_secs(7200); // 2h
28549        s.politicas.circuit_breaker = Some(CircuitBreaker {
28550            max_failures: 5,
28551            window,
28552        });
28553        let err = s.validate().unwrap_err();
28554        assert!(
28555            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
28556            "got {err:?}"
28557        );
28558        let msg = err.to_string();
28559        assert!(
28560            msg.contains("7200"),
28561            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
28562        );
28563    }
28564
28565    #[test]
28566    fn circuit_breaker_window_cap_pins_canonical_value() {
28567        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
28568        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
28569        // shared duration codec emits as a clean canonical string
28570        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
28571        // the sibling duration-typed `:politicas :timeout` axis (the
28572        // two duration-typed `:politicas` axes share a uniform top
28573        // edge). Pinning the literal value here surfaces a future
28574        // drift (a relaxation to 24h, a tightening to 5m) as a
28575        // deliberate test edit, not a silent contract narrowing. Same
28576        // shape every other typed-cap value pin on this surface uses
28577        // (`policy_timeout_cap_pins_canonical_value`).
28578        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
28579        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
28580        assert_eq!(
28581            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
28582            "the two duration-typed `:politicas` caps share the same top edge"
28583        );
28584    }
28585
28586    #[test]
28587    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
28588        // The codec round-trip property the cap arm preserves: the
28589        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
28590        // through the shared duration codec — every value at the cap
28591        // renders to a clean canonical string (`"1h"`) and parses back
28592        // to the same `Duration`. Pin this so a future drift between
28593        // the cap constant and the codec's largest emitted unit
28594        // surfaces here. Same shape every other typed boundary pin on
28595        // this surface uses
28596        // (`policy_timeout_cap_value_round_trips_through_codec`).
28597        let policy = MeshPolicy {
28598            circuit_breaker: Some(CircuitBreaker {
28599                max_failures: 5,
28600                window: POLICY_BREAKER_WINDOW_MAX,
28601            }),
28602            ..Default::default()
28603        };
28604        let json = serde_json::to_string(&policy).unwrap();
28605        // The codec emits `"1h"` for the canonical 1-hour magnitude.
28606        assert!(
28607            json.contains("\"1h\""),
28608            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
28609        );
28610        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
28611        assert_eq!(
28612            back.circuit_breaker.unwrap().window,
28613            POLICY_BREAKER_WINDOW_MAX
28614        );
28615    }
28616
28617    #[test]
28618    fn is_integer_millisecond_duration_predicate_tracks_codec() {
28619        // Pin the predicate's accepted set against the codec's
28620        // accepted set explicitly. The codec parses
28621        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
28622        // accepted value is an integer-millisecond multiple — so the
28623        // predicate must accept exactly that set. Same shape every
28624        // other predicate-on-the-typed-slot helper carries
28625        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
28626        // Read directly from the codec-owned predicate — the crate's
28627        // single source of truth every typed-`Duration` axis now routes
28628        // through via
28629        // [`crate::render::require_positive_canonical_bounded_duration`].
28630        use super::supervisor::duration_codec::is_integer_millisecond_duration;
28631        assert!(is_integer_millisecond_duration(Duration::ZERO));
28632        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
28633        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
28634        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
28635        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
28636        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
28637        // Non-integer-millisecond residue: rejected.
28638        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
28639        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
28640        assert!(!is_integer_millisecond_duration(Duration::from_micros(
28641            1500
28642        )));
28643        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
28644        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
28645            999_999
28646        )));
28647        // The 1-ns-past-1ms boundary: rejected (no longer a clean
28648        // integer-millisecond multiple).
28649        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
28650            1_000_001
28651        )));
28652    }
28653
28654    #[test]
28655    fn policy_timeout_validated_value_round_trips_through_codec() {
28656        // The structural property the canonical-ms gate enforces:
28657        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
28658        // round-trips losslessly through the shared `duration_codec`
28659        // (serialize → string → deserialize → equal value). Pin this
28660        // end-to-end so a future change to either side (the validate
28661        // gate's accepted granularity, the codec's parse/render unit
28662        // set) that breaks the alignment surfaces here. The
28663        // previous-state shape (typed slot accepts arbitrary
28664        // `Duration`, codec only round-trips integer-ms) would fail
28665        // this test for any `Duration::from_micros(1500)` timeout —
28666        // the validate gate now forecloses that.
28667        for timeout in [
28668            Duration::from_millis(1),
28669            Duration::from_millis(1500),
28670            Duration::from_secs(30),
28671            Duration::from_secs(3600),
28672        ] {
28673            let mut s = three_member_spec();
28674            s.politicas.timeout = Some(timeout);
28675            s.validate().unwrap();
28676            let json = serde_json::to_string(&s.politicas).unwrap();
28677            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
28678            assert_eq!(
28679                back.timeout, s.politicas.timeout,
28680                "every validated :timeout must round-trip losslessly through the codec"
28681            );
28682        }
28683    }
28684
28685    #[test]
28686    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
28687        // Peer of the `:timeout` round-trip property on the breaker
28688        // axis.
28689        //
28690        // Clears `:timeout` from the fixture so the round-trip pin
28691        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
28692        // cross-axis gate would otherwise reject as structurally-inert
28693        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
28694        // the paired `(:timeout, :window)` cross-axis relation is
28695        // pinned separately by
28696        // `rejects_circuit_breaker_window_below_timeout`, and this
28697        // property is a pure serde-codec round-trip on the per-axis
28698        // slot.
28699        for window in [
28700            Duration::from_millis(1),
28701            Duration::from_millis(1500),
28702            Duration::from_secs(30),
28703            Duration::from_secs(3600),
28704        ] {
28705            let mut s = three_member_spec();
28706            s.politicas.timeout = None;
28707            s.politicas.circuit_breaker = Some(CircuitBreaker {
28708                max_failures: 5,
28709                window,
28710            });
28711            s.validate().unwrap();
28712            let json = serde_json::to_string(&s.politicas).unwrap();
28713            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
28714            assert_eq!(
28715                back.circuit_breaker.unwrap().window,
28716                window,
28717                "every validated :circuit-breaker :window must round-trip losslessly"
28718            );
28719        }
28720    }
28721
28722    #[test]
28723    fn rejects_circuit_breaker_window_below_timeout() {
28724        // The fail-before-pass-after pin on the cross-axis
28725        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
28726        // is individually well-formed under its own per-axis bracket
28727        // (both integer-millisecond, both above the zero floor, both
28728        // below the cap), but the pair is a structurally-inert
28729        // breaker: a call dispatched at t=0 is declared failed at
28730        // t=30s, by which point the 10s rolling window open at
28731        // dispatch has already rolled twice, so no window can hold
28732        // a timeout-derived failure however high the call volume.
28733        //
28734        // Envoy's `outlier_detection.interval` against the per-route
28735        // request timeout carries the identical relation; Hystrix
28736        // ships the canonical ratio in its defaults (10s window
28737        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
28738        //
28739        // Pin both the diagnostic arm and the payload values so a
28740        // future re-shape of the arm surfaces here as a deliberate
28741        // test edit.
28742        let mut s = three_member_spec();
28743        s.politicas.timeout = Some(Duration::from_secs(30));
28744        s.politicas.circuit_breaker = Some(CircuitBreaker {
28745            max_failures: 5,
28746            window: Duration::from_secs(10),
28747        });
28748        assert_eq!(
28749            s.validate().unwrap_err(),
28750            AplicacaoError::PolicyBreakerWindowBelowTimeout {
28751                window: Duration::from_secs(10),
28752                timeout: Duration::from_secs(30),
28753            }
28754        );
28755    }
28756
28757    #[test]
28758    fn accepts_circuit_breaker_window_equal_to_timeout() {
28759        // Boundary pin: `:window == :timeout` is the smallest window
28760        // that structurally admits at least one full timeout-derived
28761        // failure before the rolling interval closes (the invariant
28762        // is `:window >= :timeout`, not strict inequality). Catches
28763        // a future off-by-one tightening that would drift the accept
28764        // set away from the codified [`MeshPolicy::breaker_window_
28765        // observes_timeout`] predicate.
28766        let mut s = three_member_spec();
28767        s.politicas.timeout = Some(Duration::from_secs(30));
28768        s.politicas.circuit_breaker = Some(CircuitBreaker {
28769            max_failures: 5,
28770            window: Duration::from_secs(30),
28771        });
28772        s.validate()
28773            .expect("window == timeout is the boundary accept case");
28774    }
28775
28776    #[test]
28777    fn accepts_circuit_breaker_window_above_timeout() {
28778        // Positive-control sweep across the production-playbook band —
28779        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
28780        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
28781        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
28782        // playbook recommends must validate under the cross-axis gate.
28783        for (timeout, window) in [
28784            (Duration::from_secs(1), Duration::from_secs(10)),
28785            (Duration::from_secs(5), Duration::from_secs(30)),
28786            (Duration::from_secs(10), Duration::from_secs(60)),
28787            (Duration::from_secs(30), Duration::from_secs(300)),
28788            (Duration::from_secs(60), Duration::from_secs(300)),
28789        ] {
28790            let mut s = three_member_spec();
28791            s.politicas.timeout = Some(timeout);
28792            s.politicas.circuit_breaker = Some(CircuitBreaker {
28793                max_failures: 5,
28794                window,
28795            });
28796            s.validate().unwrap_or_else(|e| {
28797                panic!(
28798                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
28799                     validate; got {e:?}"
28800                )
28801            });
28802        }
28803    }
28804
28805    #[test]
28806    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
28807        // Off-by-one boundary pin: a window exactly 1ms shy of the
28808        // timeout is still structurally inert under the invariant
28809        // (the dispatch-to-report lag is `timeout`, so the window
28810        // must span at least one such lag). Catches a future
28811        // strict-inequality relaxation that would silently drift
28812        // the accept boundary.
28813        let timeout = Duration::from_secs(30);
28814        let window = Duration::from_millis(29_999);
28815        let mut s = three_member_spec();
28816        s.politicas.timeout = Some(timeout);
28817        s.politicas.circuit_breaker = Some(CircuitBreaker {
28818            max_failures: 5,
28819            window,
28820        });
28821        assert_eq!(
28822            s.validate().unwrap_err(),
28823            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
28824        );
28825    }
28826
28827    #[test]
28828    fn cross_axis_gate_vacuous_when_timeout_absent() {
28829        // The predicate is vacuously `true` when `:timeout` is None —
28830        // a `:circuit-breaker` alone declares no relation to a
28831        // substrate-imposed deadline (the failure signal reaches the
28832        // breaker from the transport's own error surface, so no
28833        // dispatch-to-report lag is knowable at author time). Pin so
28834        // a future tightening that made the gate opinionated on
28835        // half-declared pairs surfaces here.
28836        let mut s = three_member_spec();
28837        s.politicas.timeout = None;
28838        s.politicas.circuit_breaker = Some(CircuitBreaker {
28839            max_failures: 5,
28840            window: Duration::from_millis(1),
28841        });
28842        s.validate().expect(
28843            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
28844        );
28845    }
28846
28847    #[test]
28848    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
28849        // Peer of the sibling `:timeout`-absent case: a `:timeout`
28850        // without a `:circuit-breaker` declares a per-call deadline
28851        // without any rolling-window failure accounting, so the pair
28852        // is undeclared and the cross-axis gate has nothing to check.
28853        let mut s = three_member_spec();
28854        s.politicas.timeout = Some(Duration::from_secs(3600));
28855        s.politicas.circuit_breaker = None;
28856        s.validate().expect(
28857            "cross-axis gate must be vacuous when :circuit-breaker is None, \
28858             however large :timeout is",
28859        );
28860    }
28861
28862    #[test]
28863    fn cross_axis_gate_runs_after_per_axis_brackets() {
28864        // Ordering pin: a pair whose window is *both* zero-floor-
28865        // violating and structurally below the timeout must surface
28866        // the per-axis zero-floor arm first — the zero-floor
28867        // diagnostic is more self-locating (its omit-axis remediation
28868        // is directly named), where the cross-axis arm would send the
28869        // author to reconcile two values one of which is not a
28870        // meaningful window at all. Same ordering discipline every
28871        // per-axis bracket carries internally (zero-floor before
28872        // canonical-form before cap).
28873        let mut s = three_member_spec();
28874        s.politicas.timeout = Some(Duration::from_secs(30));
28875        s.politicas.circuit_breaker = Some(CircuitBreaker {
28876            max_failures: 5,
28877            window: Duration::ZERO,
28878        });
28879        assert_eq!(
28880            s.validate().unwrap_err(),
28881            AplicacaoError::PolicyBreakerZeroWindow,
28882            "per-axis zero-floor arm must fire before the cross-axis gate"
28883        );
28884    }
28885
28886    #[test]
28887    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
28888        // Equivalence pin: the substrate-canonical
28889        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
28890        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
28891        // arm must discriminate the same set on every pair covered
28892        // by their shared invariant. A future refactor of either
28893        // side that breaks the equivalence trips here rather than as
28894        // a divergence between the predicate's Boolean answer and
28895        // the validate gate's Ok/Err arm — the same
28896        // predicate-vs-gate coherence discipline the peer
28897        // [`PlacementStrategy::is_shard_keyed`] predicate carries
28898        // against `AplicacaoSpec::validate_placement`. The sweep
28899        // covers both arms of the invariant (below, equal, above)
28900        // and both vacuous arms (None `:timeout`, None
28901        // `:circuit-breaker`), so the equivalence holds
28902        // exhaustively over the axis-covered accept and reject sets.
28903        let cases: &[(Option<Duration>, Option<Duration>)] = &[
28904            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
28905            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
28906            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
28907            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
28908            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
28909            (None, Some(Duration::from_secs(1))),
28910            (Some(Duration::from_secs(30)), None),
28911            (None, None),
28912        ];
28913        for (timeout, window) in cases.iter().copied() {
28914            let politicas = MeshPolicy {
28915                timeout,
28916                circuit_breaker: window.map(|w| CircuitBreaker {
28917                    max_failures: 5,
28918                    window: w,
28919                }),
28920                ..Default::default()
28921            };
28922            let predicate = politicas.breaker_window_observes_timeout();
28923
28924            let mut s = three_member_spec();
28925            s.politicas = politicas.clone();
28926            let gate_ok = !matches!(
28927                s.validate(),
28928                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
28929            );
28930
28931            assert_eq!(
28932                predicate, gate_ok,
28933                "predicate must agree with validate arm on pair \
28934                 (timeout={timeout:?}, window={window:?})"
28935            );
28936        }
28937    }
28938
28939    #[test]
28940    fn rejects_rate_limit_starves_circuit_breaker() {
28941        // The fail-before-pass-after pin on the cross-axis
28942        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
28943        // individually well-formed under its own per-axis bracket
28944        // (both above the zero floor, both below the cap, rate-limit
28945        // window canonical), but the pair is a structurally-inert
28946        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
28947        // calls per rolling breaker window, so no window can
28948        // accumulate five failures however catastrophic the upstream
28949        // failure rate.
28950        //
28951        // Envoy's `outlier_detection.consecutive_5xx` paired against
28952        // `local_rate_limit.token_bucket.max_tokens` /
28953        // `fill_interval` carries the identical relation; every
28954        // production playbook that pairs the two axes (Envoy, Istio,
28955        // AWS App Mesh, Kong) sizes the rate at or above the
28956        // breaker's minimum-request-volume threshold for exactly this
28957        // reason.
28958        //
28959        // Pin both the diagnostic arm and the payload values so a
28960        // future re-shape of the arm surfaces here as a deliberate
28961        // test edit. Clears `:timeout` so the sibling
28962        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
28963        // does not fire first on the ordering-precedent it holds
28964        // over this arm.
28965        let mut s = three_member_spec();
28966        s.politicas.timeout = None;
28967        s.politicas.circuit_breaker = Some(CircuitBreaker {
28968            max_failures: 5,
28969            window: Duration::from_secs(10),
28970        });
28971        s.politicas.rate_limit = Some(RateLimit {
28972            rate: 1,
28973            window: Duration::from_secs(3600),
28974        });
28975        assert_eq!(
28976            s.validate().unwrap_err(),
28977            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
28978                rate: 1,
28979                rl_window: Duration::from_secs(3600),
28980                max_failures: 5,
28981                cb_window: Duration::from_secs(10),
28982            }
28983        );
28984    }
28985
28986    #[test]
28987    fn accepts_rate_limit_can_trip_circuit_breaker() {
28988        // Positive-control sweep across the production-playbook band
28989        // — every pair a real playbook recommends where the rate
28990        // clearly admits enough calls per breaker window to reach
28991        // `:max-failures` must validate. Envoy default 5 failures
28992        // in 10s with 100/s (1000 calls / window, 200× the threshold),
28993        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
28994        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
28995        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
28996        // the sibling cross-axis arm is vacuous on this sweep.
28997        for (rate, rl_window, max_failures, cb_window) in [
28998            (
28999                100u32,
29000                Duration::from_secs(1),
29001                5u32,
29002                Duration::from_secs(10),
29003            ),
29004            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
29005            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
29006            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
29007            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
29008        ] {
29009            let mut s = three_member_spec();
29010            s.politicas.timeout = None;
29011            s.politicas.circuit_breaker = Some(CircuitBreaker {
29012                max_failures,
29013                window: cb_window,
29014            });
29015            s.politicas.rate_limit = Some(RateLimit {
29016                rate,
29017                window: rl_window,
29018            });
29019            s.validate().unwrap_or_else(|e| {
29020                panic!(
29021                    "production-playbook pair rate={rate}/{rl_window:?} \
29022                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
29023                )
29024            });
29025        }
29026    }
29027
29028    #[test]
29029    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
29030        // Boundary pin: `rate × cb_window == max_failures × rl_window`
29031        // is the smallest bucket capacity that structurally admits
29032        // exactly `max_failures` calls per rolling breaker window
29033        // (the invariant is `≥`, not strict inequality). Catches a
29034        // future off-by-one tightening to strict inequality that
29035        // would drift the accept set away from the codified
29036        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
29037        // 5 calls/s over a 1s breaker window == 5 max_failures.
29038        let mut s = three_member_spec();
29039        s.politicas.timeout = None;
29040        s.politicas.circuit_breaker = Some(CircuitBreaker {
29041            max_failures: 5,
29042            window: Duration::from_secs(1),
29043        });
29044        s.politicas.rate_limit = Some(RateLimit {
29045            rate: 5,
29046            window: Duration::from_secs(1),
29047        });
29048        s.validate()
29049            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
29050    }
29051
29052    #[test]
29053    fn rejects_rate_limit_one_call_short_per_cb_window() {
29054        // Off-by-one boundary pin: exactly one call short of the trip
29055        // threshold per breaker window is still structurally inert
29056        // (the invariant is `≥`, so `<` refuses even a one-call
29057        // shortfall). 4 calls/s over a 1s window == 4 admissible
29058        // failures, one shy of the 5-`max_failures` threshold.
29059        // Catches a future strict-inequality relaxation that would
29060        // silently drift the accept boundary.
29061        let mut s = three_member_spec();
29062        s.politicas.timeout = None;
29063        s.politicas.circuit_breaker = Some(CircuitBreaker {
29064            max_failures: 5,
29065            window: Duration::from_secs(1),
29066        });
29067        s.politicas.rate_limit = Some(RateLimit {
29068            rate: 4,
29069            window: Duration::from_secs(1),
29070        });
29071        assert_eq!(
29072            s.validate().unwrap_err(),
29073            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
29074                rate: 4,
29075                rl_window: Duration::from_secs(1),
29076                max_failures: 5,
29077                cb_window: Duration::from_secs(1),
29078            }
29079        );
29080    }
29081
29082    #[test]
29083    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
29084        // The predicate is vacuously `true` when `:rate-limit` is
29085        // None — a `:circuit-breaker` alone declares no relation to
29086        // a substrate-imposed call rate (the failure signal reaches
29087        // the breaker from the transport's own error surface, at
29088        // whatever rate upstream callers push traffic). Pin so a
29089        // future tightening that made the gate opinionated on
29090        // half-declared pairs surfaces here.
29091        let mut s = three_member_spec();
29092        s.politicas.timeout = None;
29093        s.politicas.circuit_breaker = Some(CircuitBreaker {
29094            max_failures: 1000,
29095            window: Duration::from_millis(1),
29096        });
29097        s.politicas.rate_limit = None;
29098        s.validate().expect(
29099            "cross-axis starve gate must be vacuous when :rate-limit is None, \
29100             however high :max-failures and however small :window are",
29101        );
29102    }
29103
29104    #[test]
29105    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
29106        // Peer of the sibling `:rate-limit`-absent case: a
29107        // `:rate-limit` without a `:circuit-breaker` declares a
29108        // per-edge token-bucket rate without any failure counter to
29109        // starve, so the pair is undeclared and the cross-axis gate
29110        // has nothing to check.
29111        //
29112        // Also clears the fixture's `:retries` (which is `Some(3)`) so
29113        // the sibling cross-axis
29114        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
29115        // (which reasons across the paired `(:retries, :rate-limit)`
29116        // pair independent of `:circuit-breaker`) is vacuous on this
29117        // pin — this test names the *starve* arm's vacuity on the
29118        // `:circuit-breaker`-absent case, not the burst arm's.
29119        let mut s = three_member_spec();
29120        s.politicas.timeout = None;
29121        s.politicas.retries = None;
29122        s.politicas.circuit_breaker = None;
29123        s.politicas.rate_limit = Some(RateLimit {
29124            rate: 1,
29125            window: Duration::from_secs(3600),
29126        });
29127        s.validate().expect(
29128            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
29129             however low :rate is",
29130        );
29131    }
29132
29133    #[test]
29134    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
29135        // Ordering pin: a pair whose rate is *both* zero-floor-
29136        // violating and structurally below the trip threshold must
29137        // surface the per-axis zero-floor arm first — the zero-floor
29138        // diagnostic is more self-locating (its omit-axis remediation
29139        // is directly named), where the cross-axis arm would send the
29140        // author to reconcile four values one of which is not a
29141        // meaningful rate at all. Same ordering discipline every
29142        // per-axis bracket carries internally (zero-floor before
29143        // canonical-form before cap), and the sibling cross-axis
29144        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
29145        // ordering pins on the `(:timeout, :window)` pair.
29146        let mut s = three_member_spec();
29147        s.politicas.timeout = None;
29148        s.politicas.circuit_breaker = Some(CircuitBreaker {
29149            max_failures: 5,
29150            window: Duration::from_secs(10),
29151        });
29152        s.politicas.rate_limit = Some(RateLimit {
29153            rate: 0,
29154            window: Duration::from_secs(1),
29155        });
29156        assert_eq!(
29157            s.validate().unwrap_err(),
29158            AplicacaoError::PolicyRateLimitZero,
29159            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
29160        );
29161    }
29162
29163    #[test]
29164    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
29165        // Cross-axis ordering pin: a `:politicas` whose axes trip
29166        // BOTH cross-axis arms — `:window < :timeout` (the sibling
29167        // `PolicyBreakerWindowBelowTimeout` invariant) AND
29168        // `:rate-limit` starves the breaker within `:window` (this
29169        // arm) — must surface the timeout-relation diagnostic first.
29170        // The timeout arm is the per-call-deadline invariant every
29171        // synchronous edge carries whether or not `:rate-limit` is
29172        // declared, so its diagnostic is more self-locating; the
29173        // starve arm needs the reader to reason across three axes,
29174        // where the timeout arm names only two.
29175        //
29176        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
29177        // pair trips both: the window is below the timeout, and the
29178        // rate (1 call/hour) admits far fewer than 5 calls per 10s
29179        // breaker window.
29180        let mut s = three_member_spec();
29181        s.politicas.timeout = Some(Duration::from_secs(30));
29182        s.politicas.circuit_breaker = Some(CircuitBreaker {
29183            max_failures: 5,
29184            window: Duration::from_secs(10),
29185        });
29186        s.politicas.rate_limit = Some(RateLimit {
29187            rate: 1,
29188            window: Duration::from_secs(3600),
29189        });
29190        assert_eq!(
29191            s.validate().unwrap_err(),
29192            AplicacaoError::PolicyBreakerWindowBelowTimeout {
29193                window: Duration::from_secs(10),
29194                timeout: Duration::from_secs(30),
29195            },
29196            "sibling :window<:timeout cross-axis arm must fire before the \
29197             starve arm when both apply"
29198        );
29199    }
29200
29201    #[test]
29202    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
29203        // Equivalence pin: the substrate-canonical
29204        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
29205        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
29206        // arm must discriminate the same set on every pair covered
29207        // by their shared invariant. A future refactor of either
29208        // side that breaks the equivalence trips here rather than as
29209        // a divergence between the predicate's Boolean answer and
29210        // the validate gate's Ok/Err arm — the same
29211        // predicate-vs-gate coherence discipline the sibling
29212        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
29213        // carries against `AplicacaoSpec::validate_politicas`. The
29214        // sweep covers both arms of the invariant (strictly below,
29215        // exactly at, strictly above) and both vacuous arms (None
29216        // `:rate-limit`, None `:circuit-breaker`), so the
29217        // equivalence holds exhaustively over the axis-covered
29218        // accept and reject sets. Clears `:timeout` throughout so
29219        // the sibling `:window<:timeout` gate is vacuous on every
29220        // input.
29221        let rl = |rate: u32, secs: u64| {
29222            Some(RateLimit {
29223                rate,
29224                window: Duration::from_secs(secs),
29225            })
29226        };
29227        let cb = |max_failures: u32, secs: u64| {
29228            Some(CircuitBreaker {
29229                max_failures,
29230                window: Duration::from_secs(secs),
29231            })
29232        };
29233        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
29234            // starving pairs (predicate = false, gate = Err)
29235            (rl(1, 3600), cb(5, 10)),
29236            (rl(4, 1), cb(5, 1)),
29237            // boundary + coherent pairs (predicate = true, gate = Ok)
29238            (rl(5, 1), cb(5, 1)),
29239            (rl(100, 1), cb(5, 10)),
29240            // vacuous arms
29241            (None, cb(5, 10)),
29242            (rl(1, 3600), None),
29243            (None, None),
29244        ];
29245        for (rate_limit, circuit_breaker) in cases.iter().copied() {
29246            let politicas = MeshPolicy {
29247                circuit_breaker,
29248                rate_limit,
29249                ..Default::default()
29250            };
29251            let predicate = politicas.breaker_can_trip_under_rate_limit();
29252
29253            let mut s = three_member_spec();
29254            s.politicas = politicas.clone();
29255            s.politicas.timeout = None;
29256            let gate_ok = !matches!(
29257                s.validate(),
29258                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
29259            );
29260
29261            assert_eq!(
29262                predicate, gate_ok,
29263                "predicate must agree with validate arm on pair \
29264                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
29265            );
29266        }
29267    }
29268
29269    #[test]
29270    fn rejects_retries_saturate_breaker_trip_threshold() {
29271        // The fail-before-pass-after pin on the cross-axis
29272        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
29273        // axis is individually well-formed under its own per-axis
29274        // bracket (both above the zero floor, both below the cap), but
29275        // the pair is a structurally-truncated retry policy: one
29276        // client's `retries + 1 = 4` failing attempts hit the trip
29277        // threshold on the third attempt, the breaker opens, and the
29278        // fourth attempt (the last declared retry) is blocked by the
29279        // open breaker — the substrate declared four attempts and
29280        // structurally allows three.
29281        //
29282        // Envoy's `retry_policy.num_retries` paired against
29283        // `outlier_detection.consecutive_5xx` carries the identical
29284        // relation; every production playbook that pairs the two axes
29285        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
29286        // trip threshold strictly above any single client's retry
29287        // budget so the breaker distinguishes one persistently-failing
29288        // client from sustained multi-client failure.
29289        //
29290        // Pin both the diagnostic arm and the payload values so a
29291        // future re-shape of the arm surfaces here as a deliberate
29292        // test edit. Clears `:timeout` and `:rate-limit` so the
29293        // sibling cross-axis
29294        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
29295        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
29296        // arms do not fire first on the ordering-precedent they hold
29297        // over this arm.
29298        let mut s = three_member_spec();
29299        s.politicas.timeout = None;
29300        s.politicas.retries = Some(3);
29301        s.politicas.circuit_breaker = Some(CircuitBreaker {
29302            max_failures: 3,
29303            window: Duration::from_secs(1),
29304        });
29305        s.politicas.rate_limit = None;
29306        assert_eq!(
29307            s.validate().unwrap_err(),
29308            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
29309                retries: 3,
29310                max_failures: 3,
29311            }
29312        );
29313    }
29314
29315    #[test]
29316    fn accepts_retries_below_breaker_trip_threshold() {
29317        // Positive-control sweep across the production-playbook band
29318        // — every pair a real playbook recommends where the breaker's
29319        // trip threshold is strictly above the client's retry budget
29320        // must validate. Envoy default `num_retries: 3` with
29321        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
29322        // opens on multi-client failures beyond that); Istio
29323        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
29324        // `execution.isolation.thread.timeoutInMilliseconds` + 3
29325        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
29326        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
29327        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
29328        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
29329        // arms are vacuous on this sweep.
29330        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
29331        {
29332            let mut s = three_member_spec();
29333            s.politicas.timeout = None;
29334            s.politicas.retries = Some(retries);
29335            s.politicas.circuit_breaker = Some(CircuitBreaker {
29336                max_failures,
29337                window: Duration::from_secs(60),
29338            });
29339            s.politicas.rate_limit = None;
29340            s.validate().unwrap_or_else(|e| {
29341                panic!(
29342                    "production-playbook pair retries={retries} \
29343                     max_failures={max_failures} must validate; got {e:?}"
29344                )
29345            });
29346        }
29347    }
29348
29349    #[test]
29350    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
29351        // Boundary pin: `max_failures == retries + 1` is the smallest
29352        // trip threshold that admits one client's exhausted retries
29353        // through completion (the R+1th failure — the last declared
29354        // retry — trips the breaker exactly as it completes, so
29355        // retries fully executed). The invariant is `>`, not `>=`,
29356        // stated in the coherent direction `max_failures > retries`.
29357        // Catches a future off-by-one tightening to
29358        // `max_failures > retries + 1` that would drift the accept set
29359        // away from the codified
29360        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
29361        // predicate.
29362        let mut s = three_member_spec();
29363        s.politicas.timeout = None;
29364        s.politicas.retries = Some(3);
29365        s.politicas.circuit_breaker = Some(CircuitBreaker {
29366            max_failures: 4,
29367            window: Duration::from_secs(60),
29368        });
29369        s.politicas.rate_limit = None;
29370        s.validate()
29371            .expect("max_failures == retries + 1 is the boundary accept case");
29372    }
29373
29374    #[test]
29375    fn rejects_retries_equal_to_breaker_trip_threshold() {
29376        // Off-by-one boundary pin: exactly at the trip threshold is
29377        // still structurally truncating (the invariant is `>`, so `<=`
29378        // refuses even the tight boundary). `retries = 3` with
29379        // `max_failures = 3` means the breaker trips on the third
29380        // failure — the last declared retry attempt is blocked.
29381        // Catches a future relaxation to `>=` that would silently
29382        // drift the accept boundary.
29383        let mut s = three_member_spec();
29384        s.politicas.timeout = None;
29385        s.politicas.retries = Some(3);
29386        s.politicas.circuit_breaker = Some(CircuitBreaker {
29387            max_failures: 3,
29388            window: Duration::from_secs(60),
29389        });
29390        s.politicas.rate_limit = None;
29391        assert_eq!(
29392            s.validate().unwrap_err(),
29393            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
29394                retries: 3,
29395                max_failures: 3,
29396            }
29397        );
29398    }
29399
29400    #[test]
29401    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
29402        // The predicate is vacuously `true` when `:retries` is None —
29403        // a `:circuit-breaker` alone declares a failure counter whose
29404        // per-client attempt count is unconstrained by the substrate,
29405        // so no per-client saturation bound on failures-per-client-call
29406        // is knowable at author time. The substrate takes no position
29407        // on whether an omitted `:retries` axis means zero retries or
29408        // "the client picks its own retry policy" — either way, the
29409        // pair is undeclared and the cross-axis gate has nothing to
29410        // check. Pin so a future tightening that made the gate
29411        // opinionated on half-declared pairs surfaces here.
29412        let mut s = three_member_spec();
29413        s.politicas.timeout = None;
29414        s.politicas.retries = None;
29415        s.politicas.circuit_breaker = Some(CircuitBreaker {
29416            max_failures: 1,
29417            window: Duration::from_secs(60),
29418        });
29419        s.politicas.rate_limit = None;
29420        s.validate().expect(
29421            "cross-axis retries gate must be vacuous when :retries is None, \
29422             however low :max-failures is",
29423        );
29424    }
29425
29426    #[test]
29427    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
29428        // Peer of the sibling `:retries`-absent case: a `:retries`
29429        // without a `:circuit-breaker` declares a client-retry policy
29430        // with no failure counter to trip, so the pair is undeclared
29431        // and the cross-axis gate has nothing to check.
29432        let mut s = three_member_spec();
29433        s.politicas.timeout = None;
29434        s.politicas.retries = Some(POLICY_RETRIES_MAX);
29435        s.politicas.circuit_breaker = None;
29436        s.politicas.rate_limit = None;
29437        s.validate().expect(
29438            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
29439             however high :retries is",
29440        );
29441    }
29442
29443    #[test]
29444    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
29445        // Ordering pin: a pair whose retries is *both* zero-floor-
29446        // violating and structurally at-or-below the trip threshold
29447        // must surface the per-axis zero-floor arm first — the
29448        // zero-floor diagnostic is more self-locating (its omit-axis
29449        // remediation is directly named), where the cross-axis arm
29450        // would send the author to reconcile two values one of which
29451        // is not a meaningful retry count at all. Same ordering
29452        // discipline every per-axis bracket carries internally
29453        // (zero-floor before canonical-form before cap), and the
29454        // sibling cross-axis
29455        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
29456        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
29457        let mut s = three_member_spec();
29458        s.politicas.timeout = None;
29459        s.politicas.retries = Some(0);
29460        s.politicas.circuit_breaker = Some(CircuitBreaker {
29461            max_failures: 3,
29462            window: Duration::from_secs(60),
29463        });
29464        s.politicas.rate_limit = None;
29465        assert_eq!(
29466            s.validate().unwrap_err(),
29467            AplicacaoError::PolicyRetriesZero,
29468            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
29469        );
29470    }
29471
29472    #[test]
29473    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
29474        // Cross-axis ordering pin: a `:politicas` whose axes trip
29475        // BOTH cross-axis arms — `:rate-limit` starves the breaker
29476        // within `:window` (the sibling
29477        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
29478        // `:retries + 1` saturates `:max-failures` (this arm) — must
29479        // surface the rate-limit-starve diagnostic first. The
29480        // rate-limit-starve arm reasons across the token-bucket
29481        // admission axis every rate-limited edge carries whether or
29482        // not `:retries` is declared, so its diagnostic is more
29483        // self-locating; the retries-saturate arm reasons across a
29484        // per-client retry-policy budget the starve arm does not
29485        // touch.
29486        //
29487        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
29488        // pair trips both: the rate structurally cannot deliver 5
29489        // failures per 10s breaker window, and simultaneously
29490        // one client's `retries + 1 = 6` attempts alone would
29491        // saturate the 5-`max_failures` threshold.
29492        let mut s = three_member_spec();
29493        s.politicas.timeout = None;
29494        s.politicas.retries = Some(5);
29495        s.politicas.circuit_breaker = Some(CircuitBreaker {
29496            max_failures: 5,
29497            window: Duration::from_secs(10),
29498        });
29499        s.politicas.rate_limit = Some(RateLimit {
29500            rate: 1,
29501            window: Duration::from_secs(3600),
29502        });
29503        assert_eq!(
29504            s.validate().unwrap_err(),
29505            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
29506                rate: 1,
29507                rl_window: Duration::from_secs(3600),
29508                max_failures: 5,
29509                cb_window: Duration::from_secs(10),
29510            },
29511            "sibling :rate-limit-starve cross-axis arm must fire before the \
29512             retries-saturate arm when both apply"
29513        );
29514    }
29515
29516    #[test]
29517    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
29518        // Equivalence pin: the substrate-canonical
29519        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
29520        // predicate and the [`AplicacaoSpec::validate_politicas`]
29521        // cross-axis arm must discriminate the same set on every pair
29522        // covered by their shared invariant. A future refactor of
29523        // either side that breaks the equivalence trips here rather
29524        // than as a divergence between the predicate's Boolean answer
29525        // and the validate gate's Ok/Err arm — the same
29526        // predicate-vs-gate coherence discipline the sibling
29527        // [`MeshPolicy::breaker_window_observes_timeout`] and
29528        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
29529        // carry against `AplicacaoSpec::validate_politicas`. The
29530        // sweep covers both arms of the invariant (strictly below,
29531        // exactly at the boundary, strictly above) and both vacuous
29532        // arms (None `:retries`, None `:circuit-breaker`), so the
29533        // equivalence holds exhaustively over the axis-covered accept
29534        // and reject sets. Clears `:timeout` and `:rate-limit`
29535        // throughout so the sibling cross-axis arms are vacuous on
29536        // every input.
29537        let cb = |max_failures: u32| {
29538            Some(CircuitBreaker {
29539                max_failures,
29540                window: Duration::from_secs(60),
29541            })
29542        };
29543        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
29544            // saturating pairs (predicate = false, gate = Err)
29545            (Some(3), cb(3)),
29546            (Some(3), cb(1)),
29547            (Some(10), cb(5)),
29548            // boundary + coherent pairs (predicate = true, gate = Ok)
29549            (Some(3), cb(4)),
29550            (Some(1), cb(5)),
29551            (Some(3), cb(20)),
29552            // vacuous arms
29553            (None, cb(1)),
29554            (Some(10), None),
29555            (None, None),
29556        ];
29557        for (retries, circuit_breaker) in cases.iter().copied() {
29558            let politicas = MeshPolicy {
29559                retries,
29560                circuit_breaker,
29561                ..Default::default()
29562            };
29563            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
29564
29565            let mut s = three_member_spec();
29566            s.politicas = politicas.clone();
29567            let gate_ok = !matches!(
29568                s.validate(),
29569                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
29570            );
29571
29572            assert_eq!(
29573                predicate, gate_ok,
29574                "predicate must agree with validate arm on pair \
29575                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
29576            );
29577        }
29578    }
29579
29580    #[test]
29581    fn rejects_rate_limit_cannot_admit_retry_burst() {
29582        // The fail-before-pass-after pin on the cross-axis
29583        // `(:retries, :rate-limit)` invariant. Each axis is
29584        // individually well-formed under its own per-axis bracket (both
29585        // above the zero floor, both below the cap), but the pair is a
29586        // structurally-truncated retry policy: one client's
29587        // `retries + 1 = 6` failing attempts consume 6 tokens from a
29588        // bucket that admits at most 3 per refill window, so the fourth
29589        // attempt onward is 429ed by the local rate limiter and the
29590        // declared retry policy is silently truncated by the same rate
29591        // limiter it feeds through — the substrate declared six
29592        // attempts and structurally allows three.
29593        //
29594        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
29595        // against `retry_policy.num_retries` carries the identical
29596        // relation; every production playbook that pairs the two axes
29597        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
29598        // capacity strictly above any single client's retry budget so
29599        // the limiter distinguishes one client's declared retries from
29600        // sustained multi-client load.
29601        //
29602        // Pin both the diagnostic arm and the payload values so a
29603        // future re-shape of the arm surfaces here as a deliberate
29604        // test edit. Clears `:timeout` and `:circuit-breaker` so the
29605        // sibling cross-axis
29606        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
29607        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
29608        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
29609        // arms do not fire first on the ordering-precedent they hold
29610        // over this arm.
29611        let mut s = three_member_spec();
29612        s.politicas.timeout = None;
29613        s.politicas.retries = Some(5);
29614        s.politicas.circuit_breaker = None;
29615        s.politicas.rate_limit = Some(RateLimit {
29616            rate: 3,
29617            window: Duration::from_secs(1),
29618        });
29619        assert_eq!(
29620            s.validate().unwrap_err(),
29621            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
29622                retries: 5,
29623                rate: 3,
29624            }
29625        );
29626    }
29627
29628    #[test]
29629    fn accepts_rate_limit_admits_retry_burst() {
29630        // Positive-control sweep across the production-playbook band
29631        // — every pair a real playbook recommends where the bucket
29632        // capacity is strictly above the client's retry budget must
29633        // validate. Envoy default `num_retries: 3` with 100/s (100
29634        // tokens per window admits 4 attempts per client with 96 to
29635        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
29636        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
29637        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
29638        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
29639        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
29640        // arms are vacuous on this sweep.
29641        for (retries, rate, secs) in [
29642            (3u32, 100u32, 1u64),
29643            (3, 50, 1),
29644            (2, 10, 1),
29645            (5, 1000, 1),
29646            (3, 1_000_000, 3600),
29647            (10, POLICY_RATE_LIMIT_MAX, 1),
29648        ] {
29649            let mut s = three_member_spec();
29650            s.politicas.timeout = None;
29651            s.politicas.retries = Some(retries);
29652            s.politicas.circuit_breaker = None;
29653            s.politicas.rate_limit = Some(RateLimit {
29654                rate,
29655                window: Duration::from_secs(secs),
29656            });
29657            s.validate().unwrap_or_else(|e| {
29658                panic!(
29659                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
29660                     must validate; got {e:?}"
29661                )
29662            });
29663        }
29664    }
29665
29666    #[test]
29667    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
29668        // Boundary pin: `rate == retries + 1` is the smallest bucket
29669        // capacity that structurally admits one client's exhausted
29670        // retries through completion (each attempt draws exactly one
29671        // token; `retries + 1` tokens available admits `retries + 1`
29672        // attempts, retries fully executed). The invariant is `>=`,
29673        // stated in the coherent direction `rate >= retries + 1`.
29674        // Catches a future off-by-one tightening to `rate > retries + 1`
29675        // that would drift the accept set away from the codified
29676        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
29677        let mut s = three_member_spec();
29678        s.politicas.timeout = None;
29679        s.politicas.retries = Some(3);
29680        s.politicas.circuit_breaker = None;
29681        s.politicas.rate_limit = Some(RateLimit {
29682            rate: 4,
29683            window: Duration::from_secs(1),
29684        });
29685        s.validate()
29686            .expect("rate == retries + 1 is the boundary accept case");
29687    }
29688
29689    #[test]
29690    fn rejects_rate_one_below_retry_burst() {
29691        // Off-by-one boundary pin: exactly one token short of the
29692        // retry burst is still structurally truncating (the invariant
29693        // is `>=`, so `<` refuses even a one-token shortfall).
29694        // `retries = 3` with `rate = 3` means one client's four
29695        // attempts consume four tokens from a three-token bucket —
29696        // the fourth attempt is 429ed. Catches a future relaxation to
29697        // `>` on the wrong side (`rate > retries`, accepting equal)
29698        // that would silently drift the accept boundary and admit a
29699        // structurally-truncated retry policy at the emit boundary.
29700        let mut s = three_member_spec();
29701        s.politicas.timeout = None;
29702        s.politicas.retries = Some(3);
29703        s.politicas.circuit_breaker = None;
29704        s.politicas.rate_limit = Some(RateLimit {
29705            rate: 3,
29706            window: Duration::from_secs(1),
29707        });
29708        assert_eq!(
29709            s.validate().unwrap_err(),
29710            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
29711                retries: 3,
29712                rate: 3,
29713            }
29714        );
29715    }
29716
29717    #[test]
29718    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
29719        // The predicate is vacuously `true` when `:retries` is None —
29720        // a `:rate-limit` alone declares a token-bucket rate whose
29721        // per-client attempt count is unconstrained by the substrate,
29722        // so no per-client saturation bound on tokens-per-client-call
29723        // is knowable at author time. The substrate takes no position
29724        // on whether an omitted `:retries` axis means zero retries or
29725        // "the client picks its own retry policy" — either way, the
29726        // pair is undeclared and the cross-axis gate has nothing to
29727        // check. Pin so a future tightening that made the gate
29728        // opinionated on half-declared pairs surfaces here.
29729        let mut s = three_member_spec();
29730        s.politicas.timeout = None;
29731        s.politicas.retries = None;
29732        s.politicas.circuit_breaker = None;
29733        s.politicas.rate_limit = Some(RateLimit {
29734            rate: 1,
29735            window: Duration::from_secs(1),
29736        });
29737        s.validate().expect(
29738            "cross-axis burst gate must be vacuous when :retries is None, \
29739             however low :rate is",
29740        );
29741    }
29742
29743    #[test]
29744    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
29745        // Peer of the sibling `:retries`-absent case: a `:retries`
29746        // without a `:rate-limit` declares a client-retry policy with
29747        // no rate limiter to saturate, so the pair is undeclared and
29748        // the cross-axis gate has nothing to check. Uses
29749        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
29750        // authored retry budget the per-axis cap admits — a `:retries
29751        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
29752        // or not `:rate-limit` is declared.
29753        let mut s = three_member_spec();
29754        s.politicas.timeout = None;
29755        s.politicas.retries = Some(POLICY_RETRIES_MAX);
29756        s.politicas.circuit_breaker = None;
29757        s.politicas.rate_limit = None;
29758        s.validate().expect(
29759            "cross-axis burst gate must be vacuous when :rate-limit is None, \
29760             however high :retries is",
29761        );
29762    }
29763
29764    #[test]
29765    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
29766        // Ordering pin: a pair whose retries is *both* zero-floor-
29767        // violating and structurally below the retry-burst threshold
29768        // must surface the per-axis zero-floor arm first — the
29769        // zero-floor diagnostic is more self-locating (its omit-axis
29770        // remediation is directly named), where the cross-axis arm
29771        // would send the author to reconcile two values one of which
29772        // is not a meaningful retry count at all. Same ordering
29773        // discipline every per-axis bracket carries internally
29774        // (zero-floor before canonical-form before cap), and the
29775        // sibling cross-axis
29776        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
29777        // ordering pin on the `(:retries, :max-failures)` pair.
29778        let mut s = three_member_spec();
29779        s.politicas.timeout = None;
29780        s.politicas.retries = Some(0);
29781        s.politicas.circuit_breaker = None;
29782        s.politicas.rate_limit = Some(RateLimit {
29783            rate: 1,
29784            window: Duration::from_secs(1),
29785        });
29786        assert_eq!(
29787            s.validate().unwrap_err(),
29788            AplicacaoError::PolicyRetriesZero,
29789            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
29790        );
29791    }
29792
29793    #[test]
29794    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
29795        // Cross-axis ordering pin: a `:politicas` whose axes trip
29796        // BOTH cross-axis arms — `:rate-limit` starves the breaker
29797        // within `:window` (the sibling
29798        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
29799        // `:retries + 1` exceeds the bucket capacity (this arm) —
29800        // must surface the rate-limit-starve diagnostic first. The
29801        // starve arm is the token-bucket admission invariant every
29802        // rate-limited edge carries against the breaker whether or
29803        // not `:retries` is declared, so its diagnostic is more
29804        // self-locating; the burst arm reasons across a per-client
29805        // retry-policy budget the starve arm does not touch. Same
29806        // "more foundational cross-axis first" ordering discipline the
29807        // sibling
29808        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
29809        // pin on the peer pair carries.
29810        //
29811        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
29812        // pair trips both: the rate structurally cannot deliver 5
29813        // failures per 10s breaker window (starve arm), and
29814        // simultaneously one client's `retries + 1 = 6` attempts alone
29815        // would exhaust the 1-token bucket (burst arm).
29816        let mut s = three_member_spec();
29817        s.politicas.timeout = None;
29818        s.politicas.retries = Some(5);
29819        s.politicas.circuit_breaker = Some(CircuitBreaker {
29820            max_failures: 5,
29821            window: Duration::from_secs(10),
29822        });
29823        s.politicas.rate_limit = Some(RateLimit {
29824            rate: 1,
29825            window: Duration::from_secs(3600),
29826        });
29827        assert_eq!(
29828            s.validate().unwrap_err(),
29829            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
29830                rate: 1,
29831                rl_window: Duration::from_secs(3600),
29832                max_failures: 5,
29833                cb_window: Duration::from_secs(10),
29834            },
29835            "sibling :rate-limit-starve cross-axis arm must fire before the \
29836             burst arm when both apply"
29837        );
29838    }
29839
29840    #[test]
29841    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
29842        // Cross-axis ordering pin: a `:politicas` whose axes trip
29843        // BOTH the retries-saturate arm and this burst arm — one
29844        // client's `retries + 1` failures saturate the breaker's trip
29845        // threshold (the sibling
29846        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
29847        // `retries + 1` exceeds the bucket capacity (this arm) —
29848        // must surface the retries-saturate diagnostic first. The
29849        // saturate arm is the per-client-vs-breaker relation every
29850        // retry-with-breaker pair carries whether or not `:rate-limit`
29851        // is declared, so its diagnostic is more self-locating; the
29852        // burst arm reasons across the rate-limit token-bucket
29853        // admission axis the saturate arm does not touch. Same
29854        // "more foundational cross-axis first" ordering discipline
29855        // carries here.
29856        //
29857        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
29858        // rate: 3/s }` pair trips both: the breaker's `max_failures
29859        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
29860        // one client's `retries + 1 = 6` attempts alone would exhaust
29861        // the 3-token bucket (burst arm). Clears `:timeout` so the
29862        // sibling `:window<:timeout` gate is vacuous, and the
29863        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
29864        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
29865        // the arm that fires first.
29866        let mut s = three_member_spec();
29867        s.politicas.timeout = None;
29868        s.politicas.retries = Some(5);
29869        s.politicas.circuit_breaker = Some(CircuitBreaker {
29870            max_failures: 3,
29871            window: Duration::from_secs(60),
29872        });
29873        s.politicas.rate_limit = Some(RateLimit {
29874            rate: 3,
29875            window: Duration::from_secs(1),
29876        });
29877        assert_eq!(
29878            s.validate().unwrap_err(),
29879            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
29880                retries: 5,
29881                max_failures: 3,
29882            },
29883            "sibling :retries-saturate cross-axis arm must fire before the \
29884             burst arm when both apply"
29885        );
29886    }
29887
29888    #[test]
29889    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
29890        // Equivalence pin: the substrate-canonical
29891        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
29892        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
29893        // must discriminate the same set on every pair covered by
29894        // their shared invariant. A future refactor of either side
29895        // that breaks the equivalence trips here rather than as a
29896        // divergence between the predicate's Boolean answer and the
29897        // validate gate's Ok/Err arm — the same predicate-vs-gate
29898        // coherence discipline the three sibling cross-axis
29899        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
29900        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
29901        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
29902        // carry against `AplicacaoSpec::validate_politicas`. The sweep
29903        // covers both arms of the invariant (strictly below, exactly
29904        // at the boundary, strictly above) and both vacuous arms
29905        // (None `:retries`, None `:rate-limit`), so the equivalence
29906        // holds exhaustively over the axis-covered accept and reject
29907        // sets. Clears `:timeout` and `:circuit-breaker` throughout
29908        // so the three sibling cross-axis arms are vacuous on every
29909        // input.
29910        let rl = |rate: u32, secs: u64| {
29911            Some(RateLimit {
29912                rate,
29913                window: Duration::from_secs(secs),
29914            })
29915        };
29916        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
29917            // burst-exceeding pairs (predicate = false, gate = Err)
29918            (Some(3), rl(3, 1)),
29919            (Some(5), rl(1, 1)),
29920            (Some(10), rl(5, 1)),
29921            // boundary + coherent pairs (predicate = true, gate = Ok)
29922            (Some(3), rl(4, 1)),
29923            (Some(1), rl(5, 1)),
29924            (Some(3), rl(1_000_000, 3600)),
29925            // vacuous arms
29926            (None, rl(1, 1)),
29927            (Some(10), None),
29928            (None, None),
29929        ];
29930        for (retries, rate_limit) in cases.iter().copied() {
29931            let politicas = MeshPolicy {
29932                retries,
29933                rate_limit,
29934                ..Default::default()
29935            };
29936            let predicate = politicas.rate_limit_admits_retry_burst();
29937
29938            let mut s = three_member_spec();
29939            s.politicas = politicas.clone();
29940            let gate_ok = !matches!(
29941                s.validate(),
29942                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
29943            );
29944
29945            assert_eq!(
29946                predicate, gate_ok,
29947                "predicate must agree with validate arm on pair \
29948                 (retries={retries:?}, rate_limit={rate_limit:?})"
29949            );
29950        }
29951    }
29952
29953    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
29954    /// equivalence pin — assert that on each `(label, politicas,
29955    /// expected)` case the substrate-canonical fold and the validate
29956    /// cascade agree byte-for-byte. Extracted so each pin's own body
29957    /// stays under `clippy::too_many_lines`.
29958    fn assert_first_cross_axis_violation_agrees_with_gate(
29959        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
29960    ) {
29961        for (label, politicas, expected) in cases {
29962            let fold = politicas.first_cross_axis_violation();
29963            assert_eq!(
29964                fold.as_ref(),
29965                expected.as_ref(),
29966                "fold must return {expected:?} on `{label}`; got {fold:?}"
29967            );
29968
29969            let mut s = three_member_spec();
29970            s.politicas = politicas.clone();
29971            let gate = s.validate();
29972            match expected {
29973                None => {
29974                    // No cross-axis violation: validate must pass (the
29975                    // per-axis brackets pass by construction on every
29976                    // fixture above; every fixture's non-`:politicas`
29977                    // slots come from `three_member_spec`).
29978                    gate.as_ref()
29979                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
29980                }
29981                Some(want) => {
29982                    let got =
29983                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
29984                    assert_eq!(
29985                        &got, want,
29986                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
29987                    );
29988                }
29989            }
29990        }
29991    }
29992
29993    #[test]
29994    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
29995        // Equivalence pin on the compound cross-axis fold: the
29996        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
29997        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
29998        // cascade must return identical `AplicacaoError` variants on
29999        // every axis-covered input — the "compound-fold ≡ gate"
30000        // contract that generalizes the four sibling per-arm pins
30001        // onto the compound primitive that folds all four. A future
30002        // refactor of either side that breaks the equivalence trips
30003        // here rather than as a divergence between what the substrate
30004        // primitive answers and what `feira build` accepts.
30005        //
30006        // Half-A of the sweep: every single-arm violation (one arm
30007        // fires with the three sibling arms vacuous), the vacuous
30008        // shape (empty policy — no arm fires), and the fully-coherent
30009        // shape (every axis declared inside the coherence surface —
30010        // no arm fires). Half-B (pairwise-ordering coverage — the
30011        // "which arm wins when two apply" contract) lives in the
30012        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
30013        // pin; splitting keeps each pin's body under
30014        // `clippy::too_many_lines`.
30015        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
30016            max_failures,
30017            window: Duration::from_secs(secs),
30018        };
30019        let rl = |rate: u32, secs: u64| RateLimit {
30020            rate,
30021            window: Duration::from_secs(secs),
30022        };
30023        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
30024            (
30025                "window-below-timeout only",
30026                MeshPolicy {
30027                    timeout: Some(Duration::from_secs(30)),
30028                    circuit_breaker: Some(cb(5, 10)),
30029                    ..Default::default()
30030                },
30031                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
30032                    window: Duration::from_secs(10),
30033                    timeout: Duration::from_secs(30),
30034                }),
30035            ),
30036            (
30037                "starve only",
30038                MeshPolicy {
30039                    rate_limit: Some(rl(1, 3600)),
30040                    circuit_breaker: Some(cb(5, 10)),
30041                    ..Default::default()
30042                },
30043                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
30044                    rate: 1,
30045                    rl_window: Duration::from_secs(3600),
30046                    max_failures: 5,
30047                    cb_window: Duration::from_secs(10),
30048                }),
30049            ),
30050            (
30051                "retries-saturate only",
30052                MeshPolicy {
30053                    retries: Some(3),
30054                    circuit_breaker: Some(cb(3, 60)),
30055                    ..Default::default()
30056                },
30057                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
30058                    retries: 3,
30059                    max_failures: 3,
30060                }),
30061            ),
30062            (
30063                "retries-burst only",
30064                MeshPolicy {
30065                    retries: Some(5),
30066                    rate_limit: Some(rl(3, 1)),
30067                    ..Default::default()
30068                },
30069                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
30070                    retries: 5,
30071                    rate: 3,
30072                }),
30073            ),
30074            ("empty policy", MeshPolicy::default(), None),
30075            (
30076                "fully-coherent policy",
30077                MeshPolicy {
30078                    timeout: Some(Duration::from_secs(30)),
30079                    retries: Some(3),
30080                    circuit_breaker: Some(cb(5, 60)),
30081                    mtls_required: Some(true),
30082                    rate_limit: Some(rl(100, 1)),
30083                },
30084                None,
30085            ),
30086        ];
30087        assert_first_cross_axis_violation_agrees_with_gate(cases);
30088    }
30089
30090    #[test]
30091    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
30092        // Half-B of the compound-fold ≡ gate equivalence pin: the
30093        // load-bearing pairwise-ordering coverage. Every ordered pair
30094        // of the four cross-axis arms — six combinations — where two
30095        // arms are simultaneously eligible must surface the
30096        // more-foundational arm's diagnostic verbatim. Pins the fold's
30097        // arm-ordering byte-for-byte against the validate cascade's
30098        // arm-ordering, so a future reshuffle of either side that
30099        // silently drifts the ordering trips here rather than as a
30100        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
30101        // pins cannot catch (they clear every sibling arm, so their
30102        // sweeps are pairwise-ordering-agnostic by construction).
30103        //
30104        // The six pairs the four-arm cascade admits:
30105        // window-before-starve, window-before-saturate,
30106        // window-before-burst, starve-before-saturate,
30107        // starve-before-burst, saturate-before-burst.
30108        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
30109            max_failures,
30110            window: Duration::from_secs(secs),
30111        };
30112        let rl = |rate: u32, secs: u64| RateLimit {
30113            rate,
30114            window: Duration::from_secs(secs),
30115        };
30116        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
30117            (
30118                "window+starve → window wins",
30119                MeshPolicy {
30120                    timeout: Some(Duration::from_secs(30)),
30121                    rate_limit: Some(rl(1, 3600)),
30122                    circuit_breaker: Some(cb(5, 10)),
30123                    ..Default::default()
30124                },
30125                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
30126                    window: Duration::from_secs(10),
30127                    timeout: Duration::from_secs(30),
30128                }),
30129            ),
30130            (
30131                "window+retries-saturate → window wins",
30132                MeshPolicy {
30133                    timeout: Some(Duration::from_secs(30)),
30134                    retries: Some(5),
30135                    circuit_breaker: Some(cb(3, 10)),
30136                    ..Default::default()
30137                },
30138                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
30139                    window: Duration::from_secs(10),
30140                    timeout: Duration::from_secs(30),
30141                }),
30142            ),
30143            (
30144                "window+retries-burst → window wins",
30145                MeshPolicy {
30146                    timeout: Some(Duration::from_secs(30)),
30147                    retries: Some(5),
30148                    rate_limit: Some(rl(3, 1)),
30149                    circuit_breaker: Some(cb(5, 10)),
30150                    ..Default::default()
30151                },
30152                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
30153                    window: Duration::from_secs(10),
30154                    timeout: Duration::from_secs(30),
30155                }),
30156            ),
30157            (
30158                "starve+retries-saturate → starve wins",
30159                MeshPolicy {
30160                    retries: Some(5),
30161                    rate_limit: Some(rl(1, 3600)),
30162                    circuit_breaker: Some(cb(5, 10)),
30163                    ..Default::default()
30164                },
30165                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
30166                    rate: 1,
30167                    rl_window: Duration::from_secs(3600),
30168                    max_failures: 5,
30169                    cb_window: Duration::from_secs(10),
30170                }),
30171            ),
30172            (
30173                "starve+retries-burst → starve wins",
30174                MeshPolicy {
30175                    retries: Some(5),
30176                    rate_limit: Some(rl(1, 3600)),
30177                    circuit_breaker: Some(cb(10, 10)),
30178                    ..Default::default()
30179                },
30180                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
30181                    rate: 1,
30182                    rl_window: Duration::from_secs(3600),
30183                    max_failures: 10,
30184                    cb_window: Duration::from_secs(10),
30185                }),
30186            ),
30187            (
30188                "retries-saturate+retries-burst → saturate wins",
30189                MeshPolicy {
30190                    retries: Some(5),
30191                    rate_limit: Some(rl(3, 1)),
30192                    circuit_breaker: Some(cb(3, 60)),
30193                    ..Default::default()
30194                },
30195                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
30196                    retries: 5,
30197                    max_failures: 3,
30198                }),
30199            ),
30200        ];
30201        assert_first_cross_axis_violation_agrees_with_gate(cases);
30202    }
30203
30204    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
30205    /// equivalence pin — assert that on each `(label, politicas,
30206    /// expected)` case both the substrate primitive
30207    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
30208    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
30209    /// same `three_member_spec` fixture whose non-`:politicas` slots
30210    /// always validate cleanly) return identical `AplicacaoError` variants.
30211    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
30212    /// the sibling cross-axis-only surface — extended here onto the
30213    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
30214    /// own body stays under `clippy::too_many_lines`.
30215    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
30216        for (label, politicas, expected) in cases {
30217            let direct = politicas.validate();
30218            match (expected, &direct) {
30219                (None, Ok(())) => {}
30220                (None, Err(got)) => {
30221                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
30222                }
30223                (Some(want), Ok(())) => {
30224                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
30225                }
30226                (Some(want), Err(got)) => assert_eq!(
30227                    got, want,
30228                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
30229                ),
30230            }
30231
30232            let mut s = three_member_spec();
30233            s.politicas = politicas.clone();
30234            let gate = s.validate();
30235            match (expected, &gate) {
30236                (None, Ok(())) => {}
30237                (None, Err(got)) => {
30238                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
30239                }
30240                (Some(want), Ok(())) => {
30241                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
30242                }
30243                (Some(want), Err(got)) => assert_eq!(
30244                    got, want,
30245                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
30246                ),
30247            }
30248        }
30249    }
30250
30251    #[test]
30252    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
30253        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
30254        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
30255        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
30256        // :max-failures`, `:rate-limit` rate) that discriminate the
30257        // "per-axis phase fires" arm of the compound gate, plus one
30258        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
30259        // ZERO }`) that pins the phase-boundary ordering — the per-axis
30260        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
30261        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
30262        // diagnostic wins over the window-below-timeout diagnostic. Peer
30263        // of the sibling
30264        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
30265        // + `_on_pairwise_orderings` pins on the compound cross-axis
30266        // fold, extended here onto the outer compound entry gate that
30267        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
30268        // clean-pass surfaces) lives in the sibling
30269        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
30270        // pin; splitting keeps each pin's body under
30271        // `clippy::too_many_lines`.
30272        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
30273            (
30274                "per-axis: timeout zero",
30275                MeshPolicy {
30276                    timeout: Some(Duration::ZERO),
30277                    ..Default::default()
30278                },
30279                Some(AplicacaoError::PolicyTimeoutZero),
30280            ),
30281            (
30282                "per-axis: retries zero",
30283                MeshPolicy {
30284                    retries: Some(0),
30285                    ..Default::default()
30286                },
30287                Some(AplicacaoError::PolicyRetriesZero),
30288            ),
30289            (
30290                "per-axis: breaker max-failures zero",
30291                MeshPolicy {
30292                    circuit_breaker: Some(CircuitBreaker {
30293                        max_failures: 0,
30294                        window: Duration::from_secs(60),
30295                    }),
30296                    ..Default::default()
30297                },
30298                Some(AplicacaoError::PolicyBreakerZeroFailures),
30299            ),
30300            (
30301                "per-axis: rate-limit rate zero",
30302                MeshPolicy {
30303                    rate_limit: Some(RateLimit {
30304                        rate: 0,
30305                        window: Duration::from_secs(1),
30306                    }),
30307                    ..Default::default()
30308                },
30309                Some(AplicacaoError::PolicyRateLimitZero),
30310            ),
30311            (
30312                "per-axis before cross-axis: zero-window wins over window-below-timeout",
30313                MeshPolicy {
30314                    timeout: Some(Duration::from_secs(30)),
30315                    circuit_breaker: Some(CircuitBreaker {
30316                        max_failures: 5,
30317                        window: Duration::ZERO,
30318                    }),
30319                    ..Default::default()
30320                },
30321                Some(AplicacaoError::PolicyBreakerZeroWindow),
30322            ),
30323        ];
30324        assert_validate_matches_gate(cases);
30325    }
30326
30327    #[test]
30328    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
30329        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
30330        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
30331        // arm that discriminates the "cross-axis phase fires" arm of
30332        // the compound gate (window-below-timeout — sibling per-arm
30333        // coverage lives in the two
30334        // `first_cross_axis_violation_matches_gate_on_*` pins above),
30335        // plus the two clean-pass shapes (empty policy — every axis
30336        // absent — and fully-coherent — every axis inside the coherence
30337        // surface) that pin the compound gate's `Ok(())` arm. Half-A
30338        // (per-axis + phase-boundary surfaces) lives in the sibling
30339        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
30340        // pin; splitting keeps each pin's body under
30341        // `clippy::too_many_lines`.
30342        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
30343            (
30344                "cross-axis: window-below-timeout",
30345                MeshPolicy {
30346                    timeout: Some(Duration::from_secs(30)),
30347                    circuit_breaker: Some(CircuitBreaker {
30348                        max_failures: 5,
30349                        window: Duration::from_secs(10),
30350                    }),
30351                    ..Default::default()
30352                },
30353                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
30354                    window: Duration::from_secs(10),
30355                    timeout: Duration::from_secs(30),
30356                }),
30357            ),
30358            ("clean pass: empty policy", MeshPolicy::default(), None),
30359            (
30360                "clean pass: every axis coherent",
30361                MeshPolicy {
30362                    timeout: Some(Duration::from_secs(30)),
30363                    retries: Some(3),
30364                    circuit_breaker: Some(CircuitBreaker {
30365                        max_failures: 5,
30366                        window: Duration::from_secs(60),
30367                    }),
30368                    mtls_required: Some(true),
30369                    rate_limit: Some(RateLimit {
30370                        rate: 100,
30371                        window: Duration::from_secs(1),
30372                    }),
30373                },
30374                None,
30375            ),
30376        ];
30377        assert_validate_matches_gate(cases);
30378    }
30379
30380    #[test]
30381    fn empty_politicas_validates() {
30382        // Omitting every policy axis is fine — defaults express "no
30383        // policy on this axis", not "policy = 0". The fixture's typical
30384        // values continue to validate; this test pins that
30385        // MeshPolicy::default() is a clean pass through validate().
30386        let mut s = three_member_spec();
30387        s.politicas = MeshPolicy::default();
30388        s.validate().unwrap();
30389    }
30390
30391    #[test]
30392    fn typical_politicas_validates_with_every_axis_set() {
30393        // The full §III.1 example block (timeout + retries + breaker +
30394        // mtls + rate-limit) — every axis nonzero — must remain a
30395        // clean pass.
30396        let mut s = three_member_spec();
30397        s.politicas = MeshPolicy {
30398            timeout: Some(Duration::from_secs(30)),
30399            retries: Some(3),
30400            circuit_breaker: Some(CircuitBreaker {
30401                max_failures: 5,
30402                window: Duration::from_secs(60),
30403            }),
30404            mtls_required: Some(true),
30405            rate_limit: Some(RateLimit {
30406                rate: 100,
30407                window: Duration::from_secs(1),
30408            }),
30409        };
30410        s.validate().unwrap();
30411    }
30412
30413    #[test]
30414    fn rejects_empty_cluster_name() {
30415        let mut s = three_member_spec();
30416        s.placement.clusters = vec!["rio".into(), String::new()];
30417        assert_eq!(
30418            s.validate().unwrap_err(),
30419            AplicacaoError::PlacementClusterEmpty
30420        );
30421    }
30422
30423    #[test]
30424    fn rejects_duplicate_cluster_names() {
30425        let mut s = three_member_spec();
30426        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
30427        let err = s.validate().unwrap_err();
30428        assert!(
30429            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
30430            "got {err:?}"
30431        );
30432    }
30433
30434    #[test]
30435    fn rejects_placement_cluster_with_uppercase() {
30436        // The canonical "I copied the cluster's display name verbatim"
30437        // typo — K8s context names are lowercase per DNS-1123 label
30438        // rule, but org docs often round-trip a TitleCase identifier
30439        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
30440        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
30441        // on the peer name axis.
30442        let mut s = three_member_spec();
30443        s.placement.clusters = vec!["Rio".into(), "mar".into()];
30444        let err = s.validate().unwrap_err();
30445        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
30446            panic!("expected PlacementClusterInvalid, got other variant");
30447        };
30448        assert_eq!(cluster, "Rio");
30449        assert!(
30450            reason.contains("uppercase"),
30451            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
30452        );
30453        assert!(
30454            reason.contains("\"rio\""),
30455            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
30456        );
30457    }
30458
30459    #[test]
30460    fn rejects_placement_cluster_with_underscore() {
30461        // The canonical "I'm thinking of an env var / hostname slug"
30462        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
30463        // schema. K8s context filtering on `my_cluster` silently misses
30464        // the cluster the author intended; the gate moves it to caixa-
30465        // build time. Same shape as `rejects_membro_caixa_with_underscore`
30466        // (3f9d7a0).
30467        let mut s = three_member_spec();
30468        s.placement.clusters = vec!["my_cluster".into()];
30469        let err = s.validate().unwrap_err();
30470        assert!(
30471            matches!(
30472                err,
30473                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
30474                    if cluster == "my_cluster" && reason.contains('_')
30475            ),
30476            "got {err:?}"
30477        );
30478    }
30479
30480    #[test]
30481    fn rejects_placement_cluster_with_dot() {
30482        // A `:placement :clusters` entry is a single DNS-1123 *label*,
30483        // not a subdomain — even though K8s context names sometimes
30484        // carry a dotted form via kubeconfig conventions, the strictest
30485        // floor among the use sites (DNS-1035 cluster.x-k8s.io
30486        // `metadata.name`, Cilium identity label values) wins. The "I
30487        // want to namespace my cluster names with `.`" intent is
30488        // expressed via `-` (`mar-east`).
30489        let mut s = three_member_spec();
30490        s.placement.clusters = vec!["team.rio".into()];
30491        let err = s.validate().unwrap_err();
30492        assert!(
30493            matches!(
30494                err,
30495                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
30496                    if cluster == "team.rio" && reason.contains('.')
30497            ),
30498            "got {err:?}"
30499        );
30500    }
30501
30502    #[test]
30503    fn rejects_placement_cluster_with_leading_hyphen() {
30504        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
30505        // with an alphanumeric. The K8s apiserver rejects `-rio`
30506        // outright; the rendered fan-out would emit a `metadata.name:
30507        // "-rio"` that fails admission far from the source caixa.lisp.
30508        let mut s = three_member_spec();
30509        s.placement.clusters = vec!["-rio".into()];
30510        let err = s.validate().unwrap_err();
30511        assert!(
30512            matches!(
30513                err,
30514                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
30515                    if cluster == "-rio" && reason.contains("start and end")
30516            ),
30517            "got {err:?}"
30518        );
30519    }
30520
30521    #[test]
30522    fn rejects_placement_cluster_with_trailing_hyphen() {
30523        // The symmetric arm of the boundary rule. Pin separately so
30524        // both ends are covered against a future relaxation that only
30525        // checks one boundary (parallel to
30526        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
30527        let mut s = three_member_spec();
30528        s.placement.clusters = vec!["rio-".into()];
30529        let err = s.validate().unwrap_err();
30530        assert!(
30531            matches!(
30532                err,
30533                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
30534                    if cluster == "rio-"
30535            ),
30536            "got {err:?}"
30537        );
30538    }
30539
30540    #[test]
30541    fn rejects_placement_cluster_with_unicode() {
30542        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
30543        // before it reaches K8s. The byte-by-byte ASCII validity check
30544        // rejects multi-byte UTF-8 sequences by the first byte that
30545        // fails `[a-z0-9-]`.
30546        let mut s = three_member_spec();
30547        s.placement.clusters = vec!["rió".into()];
30548        let err = s.validate().unwrap_err();
30549        assert!(
30550            matches!(
30551                err,
30552                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
30553                    if cluster == "rió"
30554            ),
30555            "got {err:?}"
30556        );
30557    }
30558
30559    #[test]
30560    fn rejects_placement_cluster_with_whitespace() {
30561        // Whitespace is the canonical "I pasted from a sketch / doc"
30562        // footgun. The apiserver rejects every cluster `metadata.name`
30563        // value carrying whitespace.
30564        let mut s = three_member_spec();
30565        s.placement.clusters = vec!["rio cluster".into()];
30566        let err = s.validate().unwrap_err();
30567        assert!(
30568            matches!(
30569                err,
30570                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
30571                    if cluster == "rio cluster"
30572            ),
30573            "got {err:?}"
30574        );
30575    }
30576
30577    #[test]
30578    fn rejects_placement_cluster_too_long() {
30579        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
30580        // pin. The diagnostic names both the cap (63) and the actual
30581        // length so the author can shorten in one edit. Mirrors
30582        // `rejects_membro_caixa_too_long` (3f9d7a0).
30583        let mut s = three_member_spec();
30584        let too_long = "a".repeat(64);
30585        s.placement.clusters = vec![too_long.clone()];
30586        let err = s.validate().unwrap_err();
30587        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
30588            panic!("expected PlacementClusterInvalid");
30589        };
30590        assert_eq!(cluster, too_long);
30591        assert!(
30592            reason.contains("63") && reason.contains("64"),
30593            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
30594        );
30595    }
30596
30597    #[test]
30598    fn placement_cluster_max_length_validates() {
30599        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
30600        // future tightening (e.g. dropping to 62) surfaces here as a
30601        // regression, mirroring `membro_caixa_max_length_validates`
30602        // (3f9d7a0).
30603        let mut s = three_member_spec();
30604        s.placement.clusters = vec!["a".repeat(63)];
30605        s.validate().unwrap();
30606    }
30607
30608    #[test]
30609    fn accepts_canonical_placement_cluster_forms() {
30610        // The DNS-1123 label shapes a caixa author is realistically
30611        // going to write for cluster names: single-word lowercase
30612        // (`rio`), regional hyphen-joined (`mar-east`), single
30613        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
30614        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
30615        // Pin every leg so a future tightening that bans (e.g.) digit-
30616        // start identifiers surfaces here.
30617        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
30618            let mut s = three_member_spec();
30619            s.placement.clusters = vec![form.into()];
30620            s.validate().unwrap_or_else(|e| {
30621                panic!("canonical cluster form {form:?} must validate, got {e:?}")
30622            });
30623        }
30624    }
30625
30626    #[test]
30627    fn placement_cluster_empty_takes_precedence_over_invalid() {
30628        // Order pin: the existing `PlacementClusterEmpty` diagnostic
30629        // (which doesn't try to parse) fires before the new
30630        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
30631        // `:clusters` entry keeps its narrower error message — the new
30632        // gate would also reject `""`, but the empty-string arm is the
30633        // more self-locating diagnostic. Mirrors the
30634        // `membro_caixa_empty_takes_precedence_over_invalid` pin
30635        // (3f9d7a0).
30636        let mut s = three_member_spec();
30637        s.placement.clusters = vec!["rio".into(), String::new()];
30638        let err = s.validate().unwrap_err();
30639        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
30640    }
30641
30642    #[test]
30643    fn placement_cluster_invalid_fires_before_duplicate_check() {
30644        // Order pin: a malformed-shape `:clusters` entry surfaces *its
30645        // own* diagnostic, even when a later entry would otherwise
30646        // collapse onto a duplicate name. The per-entry shape gate runs
30647        // inline before the duplicate-key insert, parallel to
30648        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
30649        let mut s = three_member_spec();
30650        s.placement.clusters = vec!["Rio".into(), "rio".into()];
30651        let err = s.validate().unwrap_err();
30652        assert!(
30653            matches!(
30654                err,
30655                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
30656            ),
30657            "got {err:?}"
30658        );
30659    }
30660
30661    #[test]
30662    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
30663        // The diagnostic-shape pin: the error names the offending
30664        // `:clusters` value verbatim so the author can grep their
30665        // caixa.lisp without re-running the build, and carries a
30666        // non-empty `reason` naming the specific violation. Same shape
30667        // every typed-shape gate enshrines
30668        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
30669        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
30670        let mut s = three_member_spec();
30671        s.placement.clusters = vec!["BAD_CLUSTER".into()];
30672        let err = s.validate().unwrap_err();
30673        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
30674            panic!("expected PlacementClusterInvalid");
30675        };
30676        assert_eq!(cluster, "BAD_CLUSTER");
30677        assert!(
30678            !reason.is_empty(),
30679            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
30680        );
30681    }
30682
30683    #[test]
30684    fn rejects_sharded_with_empty_clusters() {
30685        // §III.1: Sharded uses :clusters as the shard pool. An empty
30686        // pool means "shard across no clusters" — meaningless, same as
30687        // Replicated with no hosts.
30688        let mut s = three_member_spec();
30689        s.placement.estrategia = PlacementStrategy::Sharded;
30690        s.placement.shard_key = Some("$tenantId".into());
30691        s.placement.clusters = vec![];
30692        assert!(matches!(
30693            s.validate().unwrap_err(),
30694            AplicacaoError::PlacementWithoutClusters {
30695                estrategia: PlacementStrategy::Sharded
30696            }
30697        ));
30698    }
30699
30700    #[test]
30701    fn rejects_sharded_with_empty_shard_key() {
30702        let mut s = three_member_spec();
30703        s.placement.estrategia = PlacementStrategy::Sharded;
30704        s.placement.shard_key = Some(String::new());
30705        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
30706    }
30707
30708    #[test]
30709    fn rejects_shard_key_under_replicated_strategy() {
30710        // The fail-before-pass-after pin: a `:placement (:estrategia
30711        // Replicated :shard-key "tenantId")` manifest carries the
30712        // hash-keyed-distribution slot on a strategy that never consumes
30713        // it. Before the gate the typed slot's value silently vanished
30714        // at the renderer layer (caixa-mesh emits `placement.shardKey`
30715        // verbatim regardless of strategy; the Akka-style cluster-
30716        // sharding reconciler keys off `estrategia == Sharded` and
30717        // ignores the slot otherwise), with no diagnostic. Lifting the
30718        // rejection to a build-time gate makes the
30719        // `shard_key.is_some() == matches!(estrategia, Sharded)`
30720        // partition a structural property of every validated
30721        // [`Placement`].
30722        let mut s = three_member_spec();
30723        // The fixture already uses Replicated; just add a shard-key.
30724        s.placement.shard_key = Some("$tenantId".into());
30725        let err = s.validate().unwrap_err();
30726        let AplicacaoError::ShardKeyOnNonSharded {
30727            estrategia,
30728            shard_key,
30729        } = err
30730        else {
30731            panic!("expected ShardKeyOnNonSharded, got {err:?}");
30732        };
30733        assert_eq!(estrategia, PlacementStrategy::Replicated);
30734        assert_eq!(shard_key, "$tenantId");
30735    }
30736
30737    #[test]
30738    fn rejects_shard_key_under_singlenode_strategy() {
30739        // Peer of the Replicated case above on the SingleNode arm: OTP
30740        // distributed-app takeover (one cluster runs at a time) has no
30741        // hash-keyed routing axis to consume `:shard-key` either, so
30742        // the rejection fires on both non-Sharded arms uniformly.
30743        let mut s = three_member_spec();
30744        s.placement.estrategia = PlacementStrategy::SingleNode;
30745        s.placement.shard_key = Some("$tenantId".into());
30746        let err = s.validate().unwrap_err();
30747        let AplicacaoError::ShardKeyOnNonSharded {
30748            estrategia,
30749            shard_key,
30750        } = err
30751        else {
30752            panic!("expected ShardKeyOnNonSharded, got {err:?}");
30753        };
30754        assert_eq!(estrategia, PlacementStrategy::SingleNode);
30755        assert_eq!(shard_key, "$tenantId");
30756    }
30757
30758    #[test]
30759    fn rejects_empty_shard_key_under_replicated_strategy() {
30760        // The `Some("")` case under non-Sharded is rejected by
30761        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
30762        // fires before the empty-value gate), not
30763        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
30764        // the `Sharded` arm). Pin the partition so a future reorder of
30765        // the validate_placement match arms doesn't silently swap which
30766        // diagnostic the author sees — both are author errors, but
30767        // ShardKeyOnNonSharded names which strategy is the actual fix
30768        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
30769        // only says "pick a non-empty key".
30770        let mut s = three_member_spec();
30771        s.placement.shard_key = Some(String::new());
30772        let err = s.validate().unwrap_err();
30773        assert!(
30774            matches!(
30775                err,
30776                AplicacaoError::ShardKeyOnNonSharded {
30777                    estrategia: PlacementStrategy::Replicated,
30778                    ref shard_key,
30779                } if shard_key.is_empty()
30780            ),
30781            "got {err:?}"
30782        );
30783    }
30784
30785    #[test]
30786    fn replicated_without_shard_key_validates() {
30787        // The complement of the rejection: `:placement :estrategia
30788        // Replicated` with `:shard-key None` is the canonical happy
30789        // path on every existing fixture. Pin the no-shard-key case so
30790        // the new gate doesn't accidentally fire on `None`.
30791        let mut s = three_member_spec();
30792        assert!(matches!(
30793            s.placement.estrategia,
30794            PlacementStrategy::Replicated
30795        ));
30796        s.placement.shard_key = None;
30797        s.validate().unwrap();
30798    }
30799
30800    #[test]
30801    fn singlenode_without_shard_key_validates() {
30802        // Peer of the Replicated no-shard-key case on the SingleNode
30803        // arm — both non-Sharded strategies must validate cleanly when
30804        // the slot is omitted.
30805        let mut s = three_member_spec();
30806        s.placement.estrategia = PlacementStrategy::SingleNode;
30807        s.placement.shard_key = None;
30808        s.validate().unwrap();
30809    }
30810
30811    #[test]
30812    fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
30813        // Fail-before-pass-after pin on
30814        // [`AplicacaoError::shard_key_on_non_sharded`]'s
30815        // substrate-primitive posture: byte-identity + `Display`
30816        // byte-string parity against the open-coded struct-literal
30817        // for every non-`Sharded` [`PlacementStrategy`] arm across a
30818        // representative `:shard-key` value the sole in-crate wire-up
30819        // site (`AplicacaoSpec::validate_placement`'s
30820        // `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
30821        // arm) emits. Any wrapper-side silent normalization, `.into()`
30822        // divergence, or accidental field rebrand on the ctor body
30823        // surfaces at assert time rather than at a downstream consumer
30824        // that reads `err.estrategia` / `err.shard_key` back and gets a
30825        // different value than the one it stored.
30826        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
30827            let placement = Placement {
30828                estrategia,
30829                clusters: vec!["cluster-a".to_string()],
30830                shard_key: Some("$tenantId".to_string()),
30831                affinity: None,
30832            };
30833            let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
30834            let via_literal = AplicacaoError::ShardKeyOnNonSharded {
30835                estrategia,
30836                shard_key: "$tenantId".to_string(),
30837            };
30838            assert_eq!(
30839                via_ctor, via_literal,
30840                "shard_key_on_non_sharded(&placement, k) must byte-equal the \
30841                 open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
30842            );
30843            assert_eq!(
30844                via_ctor.to_string(),
30845                via_literal.to_string(),
30846                "Display byte-string must byte-equal the open-coded struct-literal \
30847                 for {estrategia:?}"
30848            );
30849        }
30850    }
30851
30852    #[test]
30853    fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
30854        // Boundary-sweep pin on the ctor's substrate-primitive
30855        // projection: the `estrategia` slot is stored verbatim from
30856        // [`Placement::estrategia`] on every arm the accessor can
30857        // return, and the `shard_key` slot preserves the caller-side
30858        // `&str` byte-for-byte. Sweeping every arm of
30859        // [`PlacementStrategy::ALL`] (including the `Sharded` arm the
30860        // current caller never reaches, since the ctor is a substrate
30861        // primitive independent of any single caller's dispatch gate)
30862        // catches a future silent field-rebrand or per-arm ctor
30863        // divergence at caixa-core build time rather than at a
30864        // downstream consumer far from the wire-up commit.
30865        for &estrategia in PlacementStrategy::ALL {
30866            let placement = Placement {
30867                estrategia,
30868                clusters: vec!["cluster-a".to_string()],
30869                shard_key: Some("$tenantId".to_string()),
30870                affinity: None,
30871            };
30872            let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
30873            let AplicacaoError::ShardKeyOnNonSharded {
30874                estrategia: stored_estrategia,
30875                shard_key: stored_shard_key,
30876            } = err
30877            else {
30878                panic!(
30879                    "shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
30880                );
30881            };
30882            assert_eq!(
30883                stored_estrategia, estrategia,
30884                "estrategia slot must round-trip verbatim through Placement::estrategia \
30885                 for {estrategia:?}"
30886            );
30887            assert_eq!(
30888                stored_shard_key, "$tenantId",
30889                "shard_key slot must preserve the caller-side &str byte-for-byte \
30890                 for {estrategia:?}"
30891            );
30892        }
30893    }
30894
30895    #[test]
30896    fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
30897        // End-to-end pin: the sole in-crate wire-up site
30898        // (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
30899        // refusal) routes through
30900        // [`AplicacaoError::shard_key_on_non_sharded`] and the observed
30901        // `Err` byte-equals the ctor's output on the same non-`Sharded`
30902        // fixture. A future silent de-lift of the wire-up back to the
30903        // open-coded struct-literal trips this test at caixa-core build
30904        // time rather than at a downstream diagnostic consumer far from
30905        // the wire-up commit.
30906        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
30907            let mut s = three_member_spec();
30908            s.placement.estrategia = estrategia;
30909            s.placement.shard_key = Some("$tenantId".to_string());
30910            let observed = s.validate().unwrap_err();
30911            let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
30912            assert_eq!(
30913                observed, expected,
30914                "validate_placement's non-Sharded-arm Err must byte-equal \
30915                 shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
30916            );
30917            assert_eq!(
30918                observed.to_string(),
30919                expected.to_string(),
30920                "Display byte-string parity for {estrategia:?}"
30921            );
30922        }
30923    }
30924
30925    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
30926        // Fixture builder for the `:placement :shard-key` shape gate
30927        // tests: a three-member Aplicacao on the `Sharded` strategy
30928        // with the supplied `:shard-key` slot. Co-locates the
30929        // arm-construction so every test below carries one line of
30930        // setup (the offending `:shard-key` value) and the assertion.
30931        let mut s = three_member_spec();
30932        s.placement.estrategia = PlacementStrategy::Sharded;
30933        s.placement.shard_key = Some(key.into());
30934        s
30935    }
30936
30937    #[test]
30938    fn rejects_shard_key_with_embedded_space() {
30939        // The canonical paste-from-aligned-doc footgun:
30940        // `:shard-key "$tenant Id"` — the Akka-style entity-id
30941        // extractor reads the slot as a single-token reference, and an
30942        // embedded space breaks the token boundary at the runtime
30943        // hash-extractor pass with no diagnostic naming the offending
30944        // entry.
30945        let s = sharded_spec_with_key("$tenant Id");
30946        let err = s.validate().unwrap_err();
30947        assert!(
30948            matches!(
30949                err,
30950                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
30951                    if shard_key == "$tenant Id" && reason.contains("space")
30952            ),
30953            "got {err:?}"
30954        );
30955    }
30956
30957    #[test]
30958    fn rejects_shard_key_with_leading_space() {
30959        // Leading-space arm of the embedded-whitespace footgun — the
30960        // paste-from-aligned-doc / paste-from-CSV-cell variant where
30961        // the leading column-padding leaked into the slot.
30962        let s = sharded_spec_with_key(" $tenantId");
30963        let err = s.validate().unwrap_err();
30964        assert!(
30965            matches!(
30966                err,
30967                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
30968                    if shard_key == " $tenantId"
30969            ),
30970            "got {err:?}"
30971        );
30972    }
30973
30974    #[test]
30975    fn rejects_shard_key_with_trailing_newline() {
30976        // The canonical paste-from-shell-heredoc footgun — every
30977        // `<<EOF` heredoc terminator paste leaves a trailing newline
30978        // the YAML emitter then folds away inconsistently across
30979        // emitter implementations.
30980        let s = sharded_spec_with_key("$tenantId\n");
30981        let err = s.validate().unwrap_err();
30982        assert!(
30983            matches!(
30984                err,
30985                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
30986                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
30987            ),
30988            "got {err:?}"
30989        );
30990    }
30991
30992    #[test]
30993    fn rejects_shard_key_with_embedded_tab() {
30994        // The paste-from-aligned-doc tab-stop variant — tabs land
30995        // alongside spaces in copy-paste from formatted columns.
30996        let s = sharded_spec_with_key("$tenant\tId");
30997        let err = s.validate().unwrap_err();
30998        assert!(
30999            matches!(
31000                err,
31001                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
31002                    if shard_key == "$tenant\tId" && reason.contains("tab")
31003            ),
31004            "got {err:?}"
31005        );
31006    }
31007
31008    #[test]
31009    fn rejects_shard_key_with_control_character() {
31010        // The paste-from-binary / paste-from-screen-cleared-terminal
31011        // footgun — an embedded `\x01` (SOH) byte that some YAML
31012        // emitters silently strip and others escape as ``,
31013        // breaking round-trip across emitter implementations.
31014        let s = sharded_spec_with_key("$tenant\u{0001}Id");
31015        let err = s.validate().unwrap_err();
31016        assert!(
31017            matches!(
31018                err,
31019                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
31020                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
31021            ),
31022            "got {err:?}"
31023        );
31024    }
31025
31026    #[test]
31027    fn rejects_shard_key_with_non_ascii() {
31028        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
31029        // footgun — non-ASCII bytes normalize differently between the
31030        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
31031        // YAML parser, the same entity ID can silently map to two
31032        // distinct shards on a re-render.
31033        let s = sharded_spec_with_key("$tenàntId");
31034        let err = s.validate().unwrap_err();
31035        assert!(
31036            matches!(
31037                err,
31038                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
31039                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
31040            ),
31041            "got {err:?}"
31042        );
31043    }
31044
31045    #[test]
31046    fn rejects_shard_key_too_long() {
31047        // Length cap pin: 64 bytes — one byte over the
31048        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
31049        // here is a paste-from-doc multi-line blob landing in
31050        // `:shard-key` instead of a single-token extractor expression.
31051        let too_long = "a".repeat(64);
31052        let s = sharded_spec_with_key(&too_long);
31053        let err = s.validate().unwrap_err();
31054        let AplicacaoError::ShardKeyInvalid {
31055            ref shard_key,
31056            ref reason,
31057        } = err
31058        else {
31059            panic!("expected ShardKeyInvalid, got {err:?}");
31060        };
31061        assert_eq!(shard_key, &too_long);
31062        assert!(
31063            reason.contains("63") && reason.contains("64"),
31064            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
31065        );
31066    }
31067
31068    #[test]
31069    fn shard_key_max_length_validates() {
31070        // Boundary pin: 63 bytes exactly — the
31071        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
31072        // dropping to 62) surfaces here as a regression, mirroring
31073        // `placement_cluster_max_length_validates` /
31074        // `placement_affinity_max_length_validates` on the peer
31075        // identifier-shaped slots.
31076        let s = sharded_spec_with_key(&"a".repeat(63));
31077        s.validate().unwrap();
31078    }
31079
31080    #[test]
31081    fn accepts_canonical_shard_key_forms() {
31082        // The Akka-style entity-id extractor shapes a caixa author is
31083        // realistically going to write — pin every leg so a future
31084        // tightening that bans (e.g.) the `${...}` interpolation
31085        // variant or the `metadata.<field>` JSONPath form surfaces
31086        // here as a regression. The canonical forms span:
31087        //
31088        //   - bare property name (`tenantId`, `customerId`)
31089        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
31090        //   - JSONPath-style nested reference (`metadata.tenantId`,
31091        //     `$.user.id`)
31092        //   - interpolation-style template (`${tenant}`)
31093        //   - snake_case property name (`customer_id`)
31094        //   - kebab-case property name (`customer-id` — accepted
31095        //     because the slot is a printable-ASCII single-token
31096        //     reference, not a DNS-1123 label like
31097        //     `:placement :affinity` / `:clusters`)
31098        //   - single character (`a`, `$` — boundary)
31099        for form in [
31100            "tenantId",
31101            "customerId",
31102            "$tenantId",
31103            "metadata.tenantId",
31104            "$.user.id",
31105            "${tenant}",
31106            "customer_id",
31107            "customer-id",
31108            "a",
31109            "$",
31110        ] {
31111            let s = sharded_spec_with_key(form);
31112            s.validate().unwrap_or_else(|e| {
31113                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
31114            });
31115        }
31116    }
31117
31118    #[test]
31119    fn shard_key_empty_takes_precedence_over_invalid() {
31120        // Order pin: the existing `ShardedKeyEmpty` diagnostic
31121        // (reserved for the `Sharded` `Some("")` arm) fires before the
31122        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
31123        // `:shard-key` keeps its narrower error message — the new gate
31124        // would also reject `""` defensively, but the empty-string arm
31125        // is the more self-locating diagnostic. Mirrors the
31126        // `placement_cluster_empty_takes_precedence_over_invalid` pin
31127        // on the peer identifier-shaped slot.
31128        let s = sharded_spec_with_key("");
31129        let err = s.validate().unwrap_err();
31130        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
31131    }
31132
31133    #[test]
31134    fn shard_key_invalid_diagnostic_carries_offending_value() {
31135        // The diagnostic-shape pin: the error names the offending
31136        // `:shard-key` value verbatim so the author can grep their
31137        // caixa.lisp without re-running the build, and carries a
31138        // parser-shaped `reason:` naming the specific violation —
31139        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
31140        // on the peer identifier-shaped slot.
31141        let s = sharded_spec_with_key("$tenant Id");
31142        let err = s.validate().unwrap_err();
31143        let AplicacaoError::ShardKeyInvalid {
31144            ref shard_key,
31145            ref reason,
31146        } = err
31147        else {
31148            panic!("expected ShardKeyInvalid, got {err:?}");
31149        };
31150        assert_eq!(shard_key, "$tenant Id");
31151        assert!(
31152            !reason.is_empty(),
31153            "reason must name the specific violation, got empty string"
31154        );
31155    }
31156
31157    #[test]
31158    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
31159        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
31160        // `:shard-key` carried on non-Sharded strategies) fires before
31161        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
31162        // a `Replicated` strategy surfaces the more self-locating
31163        // strategy-mismatch diagnostic (naming the actual fix — drop
31164        // the slot, or switch to Sharded) rather than the shape
31165        // diagnostic. The strategy-mismatch arm is the more actionable
31166        // diagnostic: a malformed shard-key on Replicated is "you
31167        // shouldn't have a :shard-key here at all", not "your
31168        // :shard-key value is malformed".
31169        let mut s = three_member_spec();
31170        // Replicated is the default fixture strategy.
31171        s.placement.shard_key = Some("$tenant Id".into());
31172        let err = s.validate().unwrap_err();
31173        assert!(
31174            matches!(
31175                err,
31176                AplicacaoError::ShardKeyOnNonSharded {
31177                    estrategia: PlacementStrategy::Replicated,
31178                    ..
31179                }
31180            ),
31181            "got {err:?}"
31182        );
31183    }
31184
31185    #[test]
31186    fn rejects_empty_affinity_hint() {
31187        let mut s = three_member_spec();
31188        s.placement.affinity = Some(String::new());
31189        assert_eq!(
31190            s.validate().unwrap_err(),
31191            AplicacaoError::PlacementAffinityEmpty
31192        );
31193    }
31194
31195    #[test]
31196    fn placement_without_affinity_validates() {
31197        // Omitting :affinity is fine — the placement engine falls back
31198        // to the default heuristic. Pin the no-hint case so the
31199        // affinity-empty rejection doesn't accidentally fire on `None`.
31200        let mut s = three_member_spec();
31201        s.placement.affinity = None;
31202        s.validate().unwrap();
31203    }
31204
31205    #[test]
31206    fn rejects_placement_affinity_with_uppercase() {
31207        // The canonical "I copied the ADR's display name verbatim" typo
31208        // — placement hints land verbatim in K8s label-selector
31209        // territory, where the apiserver enforces the DNS-1123 label
31210        // rule (lowercase-only) on every identity-keyed admission axis.
31211        // Mirrors `rejects_placement_cluster_with_uppercase` on the
31212        // sibling slot.
31213        let mut s = three_member_spec();
31214        s.placement.affinity = Some("DataLocality".into());
31215        let err = s.validate().unwrap_err();
31216        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
31217            panic!("expected PlacementAffinityInvalid, got other variant");
31218        };
31219        assert_eq!(affinity, "DataLocality");
31220        assert!(
31221            reason.contains("uppercase"),
31222            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
31223        );
31224        assert!(
31225            reason.contains("\"datalocality\""),
31226            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
31227        );
31228    }
31229
31230    #[test]
31231    fn rejects_placement_affinity_with_underscore() {
31232        // The canonical "I'm thinking of an env var / Python identifier"
31233        // leak — `_` is forbidden by every DNS-1123 label schema. Same
31234        // shape as `rejects_placement_cluster_with_underscore` on the
31235        // sibling slot.
31236        let mut s = three_member_spec();
31237        s.placement.affinity = Some("data_locality".into());
31238        let err = s.validate().unwrap_err();
31239        assert!(
31240            matches!(
31241                err,
31242                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
31243                    if affinity == "data_locality" && reason.contains('_')
31244            ),
31245            "got {err:?}"
31246        );
31247    }
31248
31249    #[test]
31250    fn rejects_placement_affinity_with_dot() {
31251        // A `:placement :affinity` value is a single DNS-1123 *label*
31252        // (it lands as a K8s label value selector key), not a subdomain.
31253        // The "I want to namespace my hint with `.`" intent is expressed
31254        // via `-` (`data-locality-east`).
31255        let mut s = three_member_spec();
31256        s.placement.affinity = Some("data.locality".into());
31257        let err = s.validate().unwrap_err();
31258        assert!(
31259            matches!(
31260                err,
31261                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
31262                    if affinity == "data.locality" && reason.contains('.')
31263            ),
31264            "got {err:?}"
31265        );
31266    }
31267
31268    #[test]
31269    fn rejects_placement_affinity_with_unicode() {
31270        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
31271        // before it reaches K8s. The byte-by-byte ASCII validity check
31272        // rejects multi-byte UTF-8 sequences by the first byte that
31273        // fails `[a-z0-9-]`.
31274        let mut s = three_member_spec();
31275        s.placement.affinity = Some("data-localité".into());
31276        let err = s.validate().unwrap_err();
31277        assert!(
31278            matches!(
31279                err,
31280                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
31281                    if affinity == "data-localité"
31282            ),
31283            "got {err:?}"
31284        );
31285    }
31286
31287    #[test]
31288    fn rejects_placement_affinity_with_leading_hyphen() {
31289        // DNS-1123 boundary rule: labels must start with an
31290        // alphanumeric. Pin separately from the trailing-hyphen arm so
31291        // a future relaxation that only checks one boundary surfaces
31292        // here as a regression (parallel to
31293        // `rejects_placement_cluster_with_leading_hyphen`).
31294        let mut s = three_member_spec();
31295        s.placement.affinity = Some("-data-locality".into());
31296        let err = s.validate().unwrap_err();
31297        assert!(
31298            matches!(
31299                err,
31300                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
31301                    if affinity == "-data-locality" && reason.contains("start and end")
31302            ),
31303            "got {err:?}"
31304        );
31305    }
31306
31307    #[test]
31308    fn rejects_placement_affinity_with_trailing_hyphen() {
31309        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
31310        // ends are covered against a future relaxation.
31311        let mut s = three_member_spec();
31312        s.placement.affinity = Some("data-locality-".into());
31313        let err = s.validate().unwrap_err();
31314        assert!(
31315            matches!(
31316                err,
31317                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
31318                    if affinity == "data-locality-"
31319            ),
31320            "got {err:?}"
31321        );
31322    }
31323
31324    #[test]
31325    fn rejects_placement_affinity_with_whitespace() {
31326        // Whitespace is the canonical "I pasted from a sketch / doc"
31327        // footgun. The apiserver rejects every label-selector value
31328        // carrying whitespace.
31329        let mut s = three_member_spec();
31330        s.placement.affinity = Some("data locality".into());
31331        let err = s.validate().unwrap_err();
31332        assert!(
31333            matches!(
31334                err,
31335                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
31336                    if affinity == "data locality"
31337            ),
31338            "got {err:?}"
31339        );
31340    }
31341
31342    #[test]
31343    fn rejects_placement_affinity_too_long() {
31344        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
31345        // pin. The diagnostic names both the cap (63) and the actual
31346        // length so the author can shorten in one edit. Mirrors
31347        // `rejects_placement_cluster_too_long`.
31348        let mut s = three_member_spec();
31349        let too_long = "a".repeat(64);
31350        s.placement.affinity = Some(too_long.clone());
31351        let err = s.validate().unwrap_err();
31352        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
31353            panic!("expected PlacementAffinityInvalid");
31354        };
31355        assert_eq!(affinity, too_long);
31356        assert!(
31357            reason.contains("63") && reason.contains("64"),
31358            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
31359        );
31360    }
31361
31362    #[test]
31363    fn placement_affinity_max_length_validates() {
31364        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
31365        // future tightening (e.g. dropping to 62) surfaces here as a
31366        // regression, mirroring `placement_cluster_max_length_validates`.
31367        let mut s = three_member_spec();
31368        s.placement.affinity = Some("a".repeat(63));
31369        s.validate().unwrap();
31370    }
31371
31372    #[test]
31373    fn accepts_canonical_placement_affinity_forms() {
31374        // The DNS-1123 label shapes a caixa author is realistically
31375        // going to write for placement hints: the M3 canonical examples
31376        // (`data-locality`, `low-latency`, `anti-affinity`), the
31377        // single-token form (`affinity`), the single-character boundary
31378        // (`a`), the digit-start (DNS-1123 allows this, unlike
31379        // DNS-1035), and a regional-suffixed form. Pin every leg so a
31380        // future tightening that bans (e.g.) digit-start identifiers
31381        // surfaces here.
31382        for form in [
31383            "data-locality",
31384            "low-latency",
31385            "anti-affinity",
31386            "affinity",
31387            "a",
31388            "3-tier",
31389            "locality-east",
31390        ] {
31391            let mut s = three_member_spec();
31392            s.placement.affinity = Some(form.into());
31393            s.validate().unwrap_or_else(|e| {
31394                panic!("canonical affinity form {form:?} must validate, got {e:?}")
31395            });
31396        }
31397    }
31398
31399    #[test]
31400    fn placement_affinity_empty_takes_precedence_over_invalid() {
31401        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
31402        // (which doesn't try to parse) fires before the new
31403        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
31404        // `:affinity` keeps its narrower error message — the new gate
31405        // would also reject `""`, but the empty-string arm is the more
31406        // self-locating diagnostic. Mirrors the
31407        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
31408        let mut s = three_member_spec();
31409        s.placement.affinity = Some(String::new());
31410        let err = s.validate().unwrap_err();
31411        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
31412    }
31413
31414    #[test]
31415    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
31416        // The diagnostic shape pin: every rejection carries the offending
31417        // `affinity:` verbatim plus a parser-shaped `reason:` so the
31418        // author can grep their caixa.lisp for `:affinity "<hint>"` and
31419        // fix it in one edit. Mirrors the
31420        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
31421        // pin on the sibling slot.
31422        let mut s = three_member_spec();
31423        s.placement.affinity = Some("Data_Locality".into());
31424        let err = s.validate().unwrap_err();
31425        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
31426            panic!("expected PlacementAffinityInvalid");
31427        };
31428        assert_eq!(affinity, "Data_Locality");
31429        assert!(
31430            !reason.is_empty(),
31431            "diagnostic reason must not be empty (got: {reason:?})"
31432        );
31433    }
31434
31435    #[test]
31436    fn singlenode_with_takeover_candidates_validates() {
31437        // OTP distributed-application convention (MESH-COMPOSITION
31438        // §II.1): SingleNode runs on one cluster at a time but the
31439        // :clusters list enumerates the takeover candidates. Multiple
31440        // entries are not a contradiction — they are the failover pool.
31441        let mut s = three_member_spec();
31442        s.placement.estrategia = PlacementStrategy::SingleNode;
31443        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
31444        s.validate().unwrap();
31445    }
31446
31447    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
31448
31449    #[test]
31450    fn mesh_policy_default_is_empty() {
31451        // The Default impl carries None on every axis — the typed
31452        // analog of an unset `:politicas (())` slot. Renderers that
31453        // overlay the policy onto a cluster artifact key off this
31454        // predicate to skip the slot entirely; pinning so a future
31455        // axis added to MeshPolicy can't silently break the contract
31456        // (a new field whose Default is non-None would flip is_empty
31457        // to false on every existing caixa, surfacing here).
31458        assert!(MeshPolicy::default().is_empty());
31459    }
31460
31461    #[test]
31462    fn mesh_policy_with_only_timeout_is_not_empty() {
31463        let p = MeshPolicy {
31464            timeout: Some(Duration::from_secs(30)),
31465            ..Default::default()
31466        };
31467        assert!(!p.is_empty());
31468    }
31469
31470    #[test]
31471    fn mesh_policy_with_only_retries_is_not_empty() {
31472        let p = MeshPolicy {
31473            retries: Some(3),
31474            ..Default::default()
31475        };
31476        assert!(!p.is_empty());
31477    }
31478
31479    #[test]
31480    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
31481        let p = MeshPolicy {
31482            circuit_breaker: Some(CircuitBreaker {
31483                max_failures: 5,
31484                window: Duration::from_secs(60),
31485            }),
31486            ..Default::default()
31487        };
31488        assert!(!p.is_empty());
31489    }
31490
31491    #[test]
31492    fn mesh_policy_with_only_mtls_required_is_not_empty() {
31493        // Even `mtls_required: Some(false)` (an explicit opt-out) is
31494        // not empty — the author *named* the axis, the renderer needs
31495        // to honor that vs. fall back to the cluster default.
31496        let p = MeshPolicy {
31497            mtls_required: Some(false),
31498            ..Default::default()
31499        };
31500        assert!(!p.is_empty());
31501    }
31502
31503    #[test]
31504    fn mesh_policy_with_only_rate_limit_is_not_empty() {
31505        let p = MeshPolicy {
31506            rate_limit: Some(RateLimit {
31507                rate: 100,
31508                window: Duration::from_secs(1),
31509            }),
31510            ..Default::default()
31511        };
31512        assert!(!p.is_empty());
31513    }
31514
31515    #[test]
31516    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
31517        // The three-member happy-path fixture sets timeout + retries +
31518        // mtls_required — every populated axis must read non-empty.
31519        // Pin the round-trip so the M3.x per-:politicas emitter (the
31520        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
31521        // on is_empty() to decide whether to emit at all without
31522        // re-deriving the contract from inline field probes.
31523        assert!(!three_member_spec().politicas.is_empty());
31524    }
31525
31526    #[test]
31527    fn mesh_policy_empty_is_the_all_none_arm_and_is_empty() {
31528        // Fail-before-pass-after round-trip pin on the paired
31529        // ([`MeshPolicy::empty`], [`MeshPolicy::is_empty`]) constructor /
31530        // predicate on the [`MeshPolicy`] typed slot: the lifted
31531        // constructor must materialize a value whose every one of the
31532        // five `Option<_>`-carrying per-axis fields is `None`, so the
31533        // paired [`MeshPolicy::is_empty`] predicate returns `true` on
31534        // the constructor's output by construction. A future silent
31535        // regression that omits a `None` arm from the constructor's
31536        // struct-literal (a sixth axis added to the type whose
31537        // constructor arm is forgotten, an accidental `Some(0)` on the
31538        // `retries` arm that would silently violate the
31539        // [`AplicacaoError::PolicyRetriesZero`] admission floor) trips
31540        // here at caixa-core test time rather than surfacing as a
31541        // downstream consumer's per-`:politicas` overlay-emit path
31542        // reading a `MeshPolicy::empty()` output that fails the
31543        // emptiness predicate and lands an unexpected `spec.policies.
31544        // <axis>` field in the emitted Cilium/Envoy overlay. Peer of
31545        // the sibling
31546        // [`crate::limits::tests::limits_spec_empty_is_the_all_none_arm_and_is_empty`]
31547        // pin on the M2 `:limits` typed slot — extends the same
31548        // "the canonical unset baseline satisfies the paired
31549        // emptiness predicate" round-trip discipline onto the M3
31550        // `:politicas` slot.
31551        let empty = MeshPolicy::empty();
31552        assert!(
31553            empty.is_empty(),
31554            "MeshPolicy::empty() must return a value whose is_empty() \
31555             predicate is true — got {empty:?}",
31556        );
31557        assert_eq!(empty.timeout(), None);
31558        assert_eq!(empty.retries(), None);
31559        assert_eq!(empty.circuit_breaker(), None);
31560        assert_eq!(empty.mtls_required(), None);
31561        assert_eq!(empty.rate_limit(), None);
31562    }
31563
31564    #[test]
31565    fn mesh_policy_empty_byte_equals_default() {
31566        // Fail-before-pass-after byte-parity pin on the two-path
31567        // convergence: the lifted `pub const fn` [`MeshPolicy::empty`]
31568        // constructor must byte-equal the derived (non-`const`)
31569        // [`Default::default`] on every one of the five
31570        // `Option<_>`-carrying per-axis fields under `PartialEq`. The
31571        // two paths are semantically identical (both name the
31572        // "canonical unset [`MeshPolicy`]" shape) but structurally
31573        // distinct (the derived [`Default::default`] threads through
31574        // the derive-generated per-field `<Option<_> as Default>::default`
31575        // cascade, resolving to `None` on each; the lifted
31576        // constructor's struct-literal names each `None` arm
31577        // verbatim). A future regression on either path — an
31578        // accidental `Some(0)` on the constructor's `retries` arm
31579        // that would silently drift the constructor's output from the
31580        // derived default (surfacing here as the pin's first-arm
31581        // inequality), a future substrate-wide field-default rebrand
31582        // that lands on the derived path's per-field
31583        // `<Option<_> as Default>::default` but forgets to extend the
31584        // constructor's struct-literal (surfacing here as the pin's
31585        // per-arm inequality on the newly rebranded axis) — trips
31586        // here at caixa-core test time. The `const` binding on the
31587        // LHS forces the lifted constructor through the `const`-eval
31588        // surface at compile time, so any future accidental downgrade
31589        // to `pub fn` fires E0015 at the binding rather than at a
31590        // downstream `const`-context consumer's dispatch site. Peer
31591        // of the sibling
31592        // [`crate::limits::tests::limits_spec_empty_byte_equals_default`]
31593        // pin on the M2 `:limits` typed slot.
31594        const EMPTY: MeshPolicy = MeshPolicy::empty();
31595        assert_eq!(
31596            EMPTY,
31597            MeshPolicy::default(),
31598            "MeshPolicy::empty() must byte-equal MeshPolicy::default() on \
31599             every per-axis field — the two paths name the same canonical \
31600             unset baseline; a mismatch means one path drifted from the \
31601             other on some per-axis default",
31602        );
31603    }
31604
31605    #[test]
31606    fn mesh_policy_empty_ctor_is_const_fn() {
31607        // Const-eval-surface pin on the lifted [`MeshPolicy::empty`]
31608        // constructor: the constructor must remain `pub const fn` so
31609        // downstream consumers can materialize a canonical unset
31610        // baseline in `const` context (a `const EMPTY: MeshPolicy =
31611        // MeshPolicy::empty();` module-scope binding for a
31612        // fixture-builder table, a `const`-context per-arm predicate
31613        // that folds emptiness over the constructor's output at
31614        // compile time, a compile-time lookup table the LSP hover
31615        // renderer materializes per typed-slot fixture). A future
31616        // accidental downgrade to non-`const` (an added runtime
31617        // helper reachable only from a non-`const` context in the
31618        // body, a manual hand-rolled `impl` that shadows this method)
31619        // trips at caixa-core build time — E0015 at the `const EMPTY`
31620        // binding below — rather than surfacing as a downstream
31621        // `const`-context regression far from the constructor's
31622        // declaration. The paired [`Self::is_empty`] predicate call
31623        // inside the `const { assert!(..) }` block enforces both
31624        // halves of the round-trip (constructor is `const`-callable
31625        // AND its output satisfies the paired emptiness predicate at
31626        // `const`-eval time) at caixa-core compile time. Peer of the
31627        // sibling
31628        // [`crate::limits::tests::limits_spec_empty_ctor_is_const_fn`]
31629        // pin on the M2 `:limits` typed slot.
31630        const EMPTY: MeshPolicy = MeshPolicy::empty();
31631        const {
31632            assert!(EMPTY.is_empty());
31633        }
31634    }
31635
31636    #[test]
31637    fn mesh_policy_default_routes_through_empty_ctor() {
31638        // Fail-before-pass-after byte-parity pin on the two-path
31639        // convergence discipline lifted onto the [`Default`] impl:
31640        // pre-fold the derive-generated [`Default::default`] and the
31641        // `pub const fn` [`MeshPolicy::empty`] constructor were
31642        // byte-equal by *coincidence* (each hand-authored or derive-
31643        // authored `None` per axis, pinned load-bearing by the
31644        // pre-existing [`mesh_policy_empty_byte_equals_default`]
31645        // sibling pin), while the folded impl now routes
31646        // [`Default::default`] through the substrate-canonical
31647        // [`Self::empty`] constructor — the two paths are byte-equal
31648        // by *construction*, one delegates to the other. This pin
31649        // sharpens the pre-existing byte-parity invariant into a
31650        // structural-delegation invariant: any future silent regression
31651        // that re-derives [`Default`] on the type (a `#[derive(Default)]`
31652        // re-addition that shadows the manual impl, a swap of the
31653        // manual impl's body onto a divergent struct-literal that
31654        // diverges from [`Self::empty`]'s output on a new field's
31655        // non-`None` canonical baseline) trips here at caixa-core test
31656        // time under `PartialEq` rather than at a downstream consumer
31657        // of the derived-until-now [`Default::default`] surface (the
31658        // five per-axis-only `..Default::default()` fixtures at
31659        // [`mesh_policy_with_only_timeout_is_not_empty`] /
31660        // [`mesh_policy_with_only_retries_is_not_empty`] /
31661        // [`mesh_policy_with_only_circuit_breaker_is_not_empty`] /
31662        // [`mesh_policy_with_only_mtls_required_is_not_empty`] /
31663        // [`mesh_policy_with_only_rate_limit_is_not_empty`], the
31664        // `MeshPolicy::default().is_empty()` round-trip at
31665        // [`mesh_policy_default_is_empty`], every future consumer of
31666        // a hypothetical `..MeshPolicy::default()` overlay-elision
31667        // arm). Peer of the sibling
31668        // [`crate::limits::tests::limits_spec_default_routes_through_empty_ctor`]
31669        // pin on the M2 `:limits` typed slot (abd52c2).
31670        assert_eq!(
31671            MeshPolicy::default(),
31672            MeshPolicy::empty(),
31673            "MeshPolicy::default() must delegate through MeshPolicy::empty() \
31674             on every per-axis field — a mismatch means the manual Default \
31675             impl drifted off the substrate-canonical empty() constructor \
31676             (or the constructor drifted off the impl's expected shape)",
31677        );
31678    }
31679
31680    #[test]
31681    fn mesh_policy_empty_validates_ok() {
31682        // Fail-before-pass-after invariant pin on the empty-baseline
31683        // validate composition: the canonical unset [`MeshPolicy`]
31684        // (every one of the five `Option<_>`-carrying per-axis fields
31685        // set to `None`) must pass every gate on
31686        // [`MeshPolicy::validate`]. The invariant is structurally
31687        // guaranteed today — every per-axis value-shape gate on the
31688        // validate dispatch is `if let Some(_) = self.<axis>()` guarded
31689        // and every cross-axis arm on
31690        // [`MeshPolicy::first_cross_axis_violation`] is a
31691        // `let (Some(_), Some(_))` pattern, so an all-`None` input
31692        // short-circuits every arm before any zero-floor / canonical-
31693        // form / cap / pairwise-ordering check fires. Pinning the
31694        // composition here makes the invariant load-bearing so a
31695        // future extension of the validate surface that adds a
31696        // non-`Option`-guarded gate (a hypothetical cross-slot
31697        // coherence gate a future per-axis / per-slot fold on the M3
31698        // `:politicas` slot establishes on top of the current
31699        // pairwise-cross-axis composition per
31700        // `theory/MESH-COMPOSITION.md` §III.2, a per-arm
31701        // `mtls_required`-defaults-to-`true` admission overlay a
31702        // future admission webhook lands) that fires on the all-`None`
31703        // input trips here at caixa-core test time rather than at a
31704        // downstream consumer that composed [`MeshPolicy::default`]
31705        // (which now routes through [`MeshPolicy::empty`]) with
31706        // [`MeshPolicy::validate`] as its "no-op axis short-circuit"
31707        // and observed a spurious rejection on the canonical unset
31708        // baseline. Peer of the sibling
31709        // [`crate::limits::tests::limits_spec_empty_validates_ok`] pin
31710        // on the M2 `:limits` typed slot (abd52c2) — that one anchors
31711        // the invariant on the folded [`Default`] impl the
31712        // [`crate::LimitsSpec::empty`] constructor now backs; this one
31713        // extends it onto the M3 `:politicas` slot's folded impl.
31714        MeshPolicy::empty().validate().expect(
31715            "MeshPolicy::empty() must satisfy MeshPolicy::validate — \
31716             every per-axis value-shape gate is `if let Some(_)` guarded \
31717             and every cross-axis arm is a `let (Some(_), Some(_))` pattern, \
31718             so an all-`None` input short-circuits every arm; a spurious \
31719             rejection on the canonical unset baseline means a future \
31720             validate-side extension added a non-`Option`-guarded gate that \
31721             fires on empty input",
31722        );
31723    }
31724
31725    // ── shared duration codec: cross-slot integer-magnitude gate ──
31726    //
31727    // The integer-magnitude discipline applied to
31728    // `supervisor::duration_codec::parse` lifts onto every typed slot
31729    // that routes through the shared codec — `MeshPolicy::timeout`
31730    // (`:politicas :timeout`) and `CircuitBreaker::window`
31731    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
31732    // These cross-slot tests pin that the gate fires at the serde
31733    // layer for both typed slots, not just for the supervisor side.
31734
31735    #[test]
31736    fn policy_timeout_serde_rejects_fractional_seconds() {
31737        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
31738        // so the shared codec's integer-magnitude gate applies on
31739        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
31740        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
31741        // deserialize with the canonical-form diagnostic naming the
31742        // offending `"1.5"` and the remediation `"1500ms"`.
31743        let payload = r#"{"timeout":"1.5s"}"#;
31744        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31745        let msg = err.to_string();
31746        assert!(
31747            msg.contains("not a non-negative integer"),
31748            "expected integer-magnitude diagnostic in {msg:?}"
31749        );
31750        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
31751        assert!(
31752            msg.contains("\"1500ms\""),
31753            "missing canonical-form remediation in {msg:?}"
31754        );
31755    }
31756
31757    #[test]
31758    fn policy_timeout_serde_rejects_leading_plus_sign() {
31759        // Pin the leading-`+` arm cross-slot — the prior f64 parser
31760        // accepted `"+30s"` silently and round-tripped to `"30s"`.
31761        let payload = r#"{"timeout":"+30s"}"#;
31762        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31763        let msg = err.to_string();
31764        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
31765    }
31766
31767    #[test]
31768    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
31769        // `CircuitBreaker::window` uses `with =
31770        // "supervisor::duration_codec_required"` (the required-Duration
31771        // variant that delegates to the same shared parser). `"0.5m"`
31772        // parsed to 30s and round-tripped to `"30s"` on next emit —
31773        // DRIFT closed.
31774        let payload = format!(
31775            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
31776            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31777            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
31778        );
31779        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
31780        let msg = err.to_string();
31781        assert!(
31782            msg.contains("not a non-negative integer"),
31783            "expected integer-magnitude diagnostic in {msg:?}"
31784        );
31785        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
31786        assert!(
31787            msg.contains("\"30s\""),
31788            "missing canonical-form remediation in {msg:?}"
31789        );
31790    }
31791
31792    #[test]
31793    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
31794        // Pin the happy-path on the cross-slot side: every canonical
31795        // author shape `render` ever emits parses cleanly through the
31796        // shared codec on the `CircuitBreaker` slot. The
31797        // codec's accepted set (post-gate) is exactly its emitted set
31798        // for the integer-magnitude class.
31799        for window_lit in ["30s", "500ms", "2m", "1h"] {
31800            let payload = format!(
31801                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
31802                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31803                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
31804            );
31805            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
31806                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
31807            });
31808            assert_eq!(cb.max_failures, 5);
31809        }
31810    }
31811
31812    // ── rate_limit_codec: integer-magnitude gate ──
31813    //
31814    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
31815    // / 737a676 / d53c922 trajectory landed on every typed-duration /
31816    // typed-byte-size codec in caixa-core lifts onto the fifth typed
31817    // codec — `rate_limit_codec` — through the digit-only magnitude
31818    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
31819    // These tests pin the gate at the serde layer for `:politicas
31820    // :rate-limit` (the only typed slot the codec backs), and at the
31821    // codec-internal `parse` layer for the canonical positive cases.
31822
31823    #[test]
31824    fn rate_limit_serde_rejects_fractional_rate() {
31825        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
31826        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
31827        // wording, which didn't name the canonical-form remediation or
31828        // the round-trip drift the next emit would produce. Now refused
31829        // at deserialize with the canonical-form diagnostic naming the
31830        // offending `"1.5"` magnitude and the round-trip drift wording.
31831        let payload = r#"{"rateLimit":"1.5/s"}"#;
31832        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31833        let msg = err.to_string();
31834        assert!(
31835            msg.contains("not a non-negative integer"),
31836            "expected integer-magnitude diagnostic in {msg:?}"
31837        );
31838        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
31839        assert!(
31840            msg.contains("THEORY.md"),
31841            "missing render-determinism contract citation in {msg:?}"
31842        );
31843    }
31844
31845    #[test]
31846    fn rate_limit_serde_rejects_leading_plus_sign() {
31847        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
31848        // permissive-`+` parse), so `"+100/s"` silently parsed to
31849        // `RateLimit { 100, 1s }` and round-tripped through `render` to
31850        // `"100/s"` — a *different* canonical string on the next emit,
31851        // breaking the THEORY.md Part V render-determinism contract
31852        // exactly the way the peer duration codecs' `"+30s"` case did.
31853        // This is the load-bearing class the digit-only gate closes
31854        // beyond what `u32::from_str`'s strictness covers on its own.
31855        let payload = r#"{"rateLimit":"+100/s"}"#;
31856        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31857        let msg = err.to_string();
31858        assert!(
31859            msg.contains("not a non-negative integer"),
31860            "expected integer-magnitude diagnostic in {msg:?}"
31861        );
31862        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
31863    }
31864
31865    #[test]
31866    fn rate_limit_serde_rejects_leading_minus_sign() {
31867        // The signed-negative arm: `"-1/s"` lands on the
31868        // non-canonical-but-numeric branch via the `i64` fallback (the
31869        // `f64` parse also succeeds), surfacing the canonical-form
31870        // diagnostic. Replaces the prior value-laundered "not a u32"
31871        // wording with the unified diagnostic across signs.
31872        let payload = r#"{"rateLimit":"-1/s"}"#;
31873        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31874        let msg = err.to_string();
31875        assert!(
31876            msg.contains("not a non-negative integer"),
31877            "expected integer-magnitude diagnostic in {msg:?}"
31878        );
31879        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
31880    }
31881
31882    #[test]
31883    fn rate_limit_serde_rejects_decimal_shaped_integer() {
31884        // `"100.0/s"` is integer-valued numerically but not in the
31885        // codec's accepted set — `render` emits `"100/s"`, so the
31886        // round-trip would drift. Lifted to the canonical-form
31887        // diagnostic peer with the duration codec's `"1.0s"` case
31888        // (1c55a2a).
31889        let payload = r#"{"rateLimit":"100.0/s"}"#;
31890        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31891        let msg = err.to_string();
31892        assert!(
31893            msg.contains("not a non-negative integer"),
31894            "expected integer-magnitude diagnostic in {msg:?}"
31895        );
31896        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
31897    }
31898
31899    #[test]
31900    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
31901        // Non-numeric, non-digit-only input lands on the existing
31902        // narrower `"not a u32"` arm (preserved for diagnostic-shape
31903        // stability on the parser-shape footgun case). Pin this so a
31904        // future relaxation of the numeric-fallback predicate doesn't
31905        // silently collapse garbage onto the canonical-form arm — same
31906        // partition the peer duration codecs draw between
31907        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
31908        let payload = r#"{"rateLimit":"abc/s"}"#;
31909        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31910        let msg = err.to_string();
31911        assert!(
31912            msg.contains("not a u32"),
31913            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
31914        );
31915        assert!(
31916            !msg.contains("not a non-negative integer"),
31917            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
31918        );
31919    }
31920
31921    #[test]
31922    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
31923        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
31924        // u32's range. The digit-only gate passes; `u32::from_str`
31925        // fails on overflow. Surface that with the overflow-shaped
31926        // diagnostic naming the offending magnitude verbatim, peer
31927        // with `supervisor::duration_codec`'s overflow arm. Pinning
31928        // the wording so a future refactor doesn't silently collapse
31929        // overflow onto the canonical-form arm.
31930        let payload = r#"{"rateLimit":"4294967296/s"}"#;
31931        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31932        let msg = err.to_string();
31933        assert!(
31934            msg.contains("overflows u32"),
31935            "expected overflow diagnostic in {msg:?}"
31936        );
31937        assert!(
31938            msg.contains("\"4294967296\""),
31939            "missing offending magnitude in {msg:?}"
31940        );
31941    }
31942
31943    #[test]
31944    fn rate_limit_serde_rejects_leading_zero_magnitude() {
31945        // `"0100/s"` is digit-only, so the existing
31946        // non-digit-only / sign / fractional arm doesn't catch it —
31947        // `u32::from_str("0100")` returns `Ok(100)`, so before this
31948        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
31949        // round-tripped through `render` to `"100/s"` — a *different*
31950        // canonical string on the next emit, breaking the THEORY.md
31951        // Part V render-determinism contract exactly the way the
31952        // peer `"+100/s"` case did before the leading-`+` arm landed.
31953        // This is the load-bearing class the leading-zero gate closes
31954        // beyond what the existing digit-only / sign / fractional
31955        // gates cover, and the peer arm to the leading-`+` test
31956        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
31957        // canonical-form-drift axis.
31958        let payload = r#"{"rateLimit":"0100/s"}"#;
31959        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31960        let msg = err.to_string();
31961        assert!(
31962            msg.contains("non-canonical leading zero"),
31963            "expected leading-zero diagnostic in {msg:?}"
31964        );
31965        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
31966        assert!(
31967            msg.contains("THEORY.md"),
31968            "missing render-determinism contract citation in {msg:?}"
31969        );
31970    }
31971
31972    #[test]
31973    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
31974        // `"00/s"` is the degenerate leading-zero case — every byte
31975        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
31976        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
31977        // a *different* canonical string, same render-determinism
31978        // violation. The single-byte `"0/s"` itself is in the
31979        // accepted set (round-trips losslessly through `render`,
31980        // refused downstream by `PolicyRateLimitZero`); the
31981        // multi-byte `"00/s"` is not. Pins the boundary between the
31982        // accepted single-`0` and the rejected leading-zero class.
31983        let payload = r#"{"rateLimit":"00/s"}"#;
31984        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
31985        let msg = err.to_string();
31986        assert!(
31987            msg.contains("non-canonical leading zero"),
31988            "expected leading-zero diagnostic in {msg:?}"
31989        );
31990        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
31991    }
31992
31993    #[test]
31994    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
31995        // Cross-window pin — the gate is window-agnostic; the
31996        // leading-zero class is a property of the magnitude, not the
31997        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
31998        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
31999        // single-window coverage extended across the three canonical
32000        // windows the codec accepts.
32001        let payload = r#"{"rateLimit":"007/h"}"#;
32002        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
32003        let msg = err.to_string();
32004        assert!(
32005            msg.contains("non-canonical leading zero"),
32006            "expected leading-zero diagnostic in {msg:?}"
32007        );
32008        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
32009    }
32010
32011    #[test]
32012    fn rate_limit_serde_rejects_leading_whitespace() {
32013        // `" 100/s"` — the canonical paste-from-aligned-doc /
32014        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
32015        // the top-level `s.trim()` silently ate the leading space and
32016        // parsed the value to `RateLimit { 100, 1s }`, which then
32017        // round-tripped through `render` to `"100/s"` (a *different*
32018        // canonical string on the next emit) — the exact
32019        // canonical-form-drift class the leading-`+` / leading-zero
32020        // arms already close, extended to the whitespace byte class.
32021        let payload = r#"{"rateLimit":" 100/s"}"#;
32022        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
32023        let msg = err.to_string();
32024        assert!(
32025            msg.contains("contains whitespace byte"),
32026            "expected whitespace diagnostic in {msg:?}"
32027        );
32028        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
32029        assert!(
32030            msg.contains("THEORY.md"),
32031            "missing render-determinism contract citation in {msg:?}"
32032        );
32033    }
32034
32035    #[test]
32036    fn rate_limit_serde_rejects_trailing_whitespace() {
32037        // `"100/s "` — the canonical shell-history / trailing-space
32038        // paste footgun. Before this gate the top-level `s.trim()`
32039        // silently ate the trailing space and parsed to
32040        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
32041        // next emit — same canonical-form drift as the leading-space
32042        // sibling, closed on the same whitespace-byte arm.
32043        let payload = r#"{"rateLimit":"100/s "}"#;
32044        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
32045        let msg = err.to_string();
32046        assert!(
32047            msg.contains("contains whitespace byte"),
32048            "expected whitespace diagnostic in {msg:?}"
32049        );
32050        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
32051    }
32052
32053    #[test]
32054    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
32055        // `"100 / s"` — the canonical typographically-spaced author
32056        // shape (the same idiom every prose reference to a rate limit
32057        // renders as, mistakenly retained when the value is pasted
32058        // into a codec-shaped slot). Before this gate the per-part
32059        // `rate_str.trim()` / `unit.trim()` calls silently ate both
32060        // spaces on either side of `/` and parsed to
32061        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
32062        // codec's *internal* whitespace-tolerance vector, orthogonal
32063        // to the leading / trailing surface but the same canonical-
32064        // form-drift class. Pins the arm as strictly stronger than the
32065        // pre-existing top-level `s.trim()` behavior: it fires on
32066        // whitespace anywhere in the value, not just at the string
32067        // boundary.
32068        let payload = r#"{"rateLimit":"100 / s"}"#;
32069        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
32070        let msg = err.to_string();
32071        assert!(
32072            msg.contains("contains whitespace byte"),
32073            "expected whitespace diagnostic in {msg:?}"
32074        );
32075        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
32076    }
32077
32078    #[test]
32079    fn rate_limit_serde_rejects_tab_byte() {
32080        // `"\t100/s"` — the canonical paste-from-indented-doc /
32081        // paste-from-YAML-block-scalar footgun where a tab byte leads
32082        // the magnitude. Pins that the gate covers tab (`0x09`) as
32083        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
32084        // members and both would be silently swallowed by `s.trim()`
32085        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
32086        // space alone to the full ASCII-whitespace set (space `0x20`,
32087        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
32088        // the tab arm as a representative of the non-space members.
32089        let payload = r#"{"rateLimit":"\t100/s"}"#;
32090        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
32091        let msg = err.to_string();
32092        assert!(
32093            msg.contains("contains whitespace byte"),
32094            "expected whitespace diagnostic in {msg:?}"
32095        );
32096        assert!(
32097            msg.contains("0x09"),
32098            "missing offending tab byte in {msg:?}"
32099        );
32100    }
32101
32102    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
32103    //
32104    // Successor to the ASCII-whitespace arm (1ad7755) on
32105    // `rate_limit_codec` — closes the strictly-complementary class the
32106    // byte-scan cannot see, through the lifted
32107    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
32108
32109    #[test]
32110    fn rate_limit_serde_rejects_leading_nbsp() {
32111        // NBSP prefix — paste-from-typography footgun. Byte-scan
32112        // misses, `str::trim` silently strips it, value drifts to
32113        // `"100/s"` on next serialize.
32114        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
32115        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
32116        let msg = err.to_string();
32117        assert!(
32118            msg.contains("non-ASCII Unicode whitespace character"),
32119            "expected non-ASCII whitespace diagnostic in {msg:?}"
32120        );
32121        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
32122    }
32123
32124    #[test]
32125    fn rate_limit_serde_rejects_internal_em_space() {
32126        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
32127        // paste-from-typography footgun on the `<integer>/<unit>`
32128        // shape.
32129        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
32130        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
32131        let msg = err.to_string();
32132        assert!(
32133            msg.contains("non-ASCII Unicode whitespace character"),
32134            "expected non-ASCII whitespace diagnostic in {msg:?}"
32135        );
32136        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
32137    }
32138
32139    #[test]
32140    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
32141        // Positive-control pin: every ASCII-only canonical form the
32142        // renderer emits stays accepted through the new arm.
32143        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
32144            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
32145            let p: MeshPolicy = serde_json::from_str(&payload)
32146                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
32147            assert!(p.rate_limit.is_some());
32148        }
32149    }
32150
32151    #[test]
32152    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
32153        // The boundary case — `"0/s"` is the canonical form
32154        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
32155        // it at the parse layer; the downstream
32156        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
32157        // `rate == 0` at the typed-validate layer above. Pins the
32158        // partition: the leading-zero gate at the codec layer does
32159        // not poach the rate-zero semantic-validation arm at the
32160        // typed-validate layer above (a future stricter codec must
32161        // not reject `"0/s"` here, or it'd collapse the diagnostic
32162        // partitioning that lets `PolicyRateLimitZero` name the
32163        // offending typed slot).
32164        let payload = r#"{"rateLimit":"0/s"}"#;
32165        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
32166            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
32167        });
32168        let rl = policy.rate_limit.expect("rate_limit must be Some");
32169        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
32170        assert_eq!(
32171            rl.window,
32172            Duration::from_secs(1),
32173            "single-`0` magnitude with `s` unit must parse to window=1s"
32174        );
32175    }
32176
32177    #[test]
32178    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
32179        // The complementary boundary pin — every magnitude
32180        // `render` emits starts with `[1-9]` (or is the single byte
32181        // `"0"`), so the canonical-form predicate is `(len == 1) ||
32182        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
32183        // '1'` case explicitly so a future tightening of the gate
32184        // (e.g. an over-eager "no leading digit < 5" rule, or a
32185        // mistakenly anchored start-of-magnitude byte check) lands
32186        // here before the canonical-forms-iterating test would catch
32187        // it.
32188        let payload = r#"{"rateLimit":"100/s"}"#;
32189        let policy: MeshPolicy = serde_json::from_str(payload)
32190            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
32191        let rl = policy.rate_limit.expect("rate_limit must be Some");
32192        assert_eq!(
32193            rl.rate, 100,
32194            "canonical-100 magnitude must parse to rate=100"
32195        );
32196    }
32197
32198    #[test]
32199    fn rate_limit_serde_accepts_integer_canonical_forms() {
32200        // Pin the happy-path: every canonical author shape `render`
32201        // ever emits parses cleanly through the codec post-gate. The
32202        // codec's accepted set (post-gate) is exactly its emitted set
32203        // for the integer-magnitude class — same property
32204        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
32205        // gates guarantee on the peer codecs. Iterating across rate
32206        // magnitudes (including `"0"`, which the codec accepts even
32207        // though `validate_politicas` rejects `rate == 0` at the typed
32208        // layer above) closes the codec contract at the parse layer
32209        // independently of the validate layer.
32210        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
32211            for unit_lit in ["s", "m", "h"] {
32212                let lit = format!("{rate_lit}/{unit_lit}");
32213                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
32214                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
32215                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
32216                });
32217                let rl = policy.rate_limit.expect("rate_limit must be Some");
32218                assert_eq!(
32219                    rl.rate,
32220                    rate_lit.parse::<u32>().unwrap(),
32221                    "rate mismatch for {lit:?}"
32222                );
32223            }
32224        }
32225    }
32226
32227    #[test]
32228    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
32229        // The structural property the gate enforces: serialize ∘
32230        // deserialize is the identity on every canonical author shape.
32231        // Peer of `parse_byte_size`'s and `parse_duration`'s
32232        // `_round_trips_through_render_for_every_canonical_form` tests
32233        // on the rate-limit axis. Before the gate, `"+100/s"` violated
32234        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
32235        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
32236        for rate in [1u32, 100, 5000, 1_000_000] {
32237            for (window, unit) in [
32238                (Duration::from_secs(1), "s"),
32239                (Duration::from_secs(60), "m"),
32240                (Duration::from_secs(3600), "h"),
32241            ] {
32242                let policy = MeshPolicy {
32243                    rate_limit: Some(RateLimit { rate, window }),
32244                    ..Default::default()
32245                };
32246                let json = serde_json::to_string(&policy).unwrap();
32247                let expected = format!("\"{rate}/{unit}\"");
32248                assert!(
32249                    json.contains(&expected),
32250                    "expected {expected:?} in {json:?}"
32251                );
32252                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
32253                assert_eq!(
32254                    back.rate_limit, policy.rate_limit,
32255                    "round-trip for {json:?}"
32256                );
32257            }
32258        }
32259    }
32260
32261    // ── self-membership cross-slot gate ──────────────────────────────
32262
32263    #[test]
32264    fn validate_no_self_membership_rejects_self_named_membro() {
32265        // An Aplicacao whose `:membros` lists its own `:nome` is a
32266        // one-node lacre-closure recursion — rejected, naming the parent.
32267        let membros = vec![
32268            membro("catalog", "^0.1"),
32269            membro("checkout", "^0.1"),
32270            membro("cart", "^0.1"),
32271        ];
32272        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
32273        assert!(
32274            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
32275            "got {err:?}"
32276        );
32277    }
32278
32279    #[test]
32280    fn validate_no_self_membership_accepts_distinct_membros() {
32281        // Positive control: distinct member names (including a member
32282        // that is itself an Aplicacao — recursive composition is valid,
32283        // MESH-COMPOSITION §V) pass the gate.
32284        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
32285        validate_no_self_membership(&membros, "checkout").unwrap();
32286    }
32287
32288    #[test]
32289    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
32290        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
32291        // `NoMembros` arm (the more-fundamental "graph must have nodes"
32292        // gate), not by this cross-slot self-edge gate. Keeping the
32293        // self-membership predicate vacuously-ok on the empty input
32294        // matches its supervisor-axis peer
32295        // (`validate_no_self_supervision_empty_children_is_ok`) and
32296        // makes the gate composable from any future call site (an M4
32297        // CR materializer's per-membros validator) without re-checking
32298        // emptiness.
32299        validate_no_self_membership(&[], "checkout").unwrap();
32300    }
32301
32302    #[test]
32303    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
32304        // Pinning the Display: the self-membership diagnostic must name
32305        // the offending caixa verbatim + the "lists itself" framing the
32306        // author can grep for, so the cluster-far failure surfaces at
32307        // build time with one-line remediation. Same diagnostic shape
32308        // as the supervisor-axis `ChildSupervisesSelf` peer.
32309        let membros = vec![membro("orquestra", "^0.1")];
32310        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
32311        let msg = err.to_string();
32312        assert!(
32313            msg.contains("orquestra"),
32314            "diagnostic must name the offending caixa nome (got: {msg:?})"
32315        );
32316        assert!(
32317            msg.contains("lists itself"),
32318            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
32319        );
32320    }
32321
32322    #[test]
32323    fn default_servico_port_constant_pins_canonical_8080_literal() {
32324        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
32325        // at the verbatim `8080` literal both consumers (the
32326        // `Entrada::port` serde default via [`default_port`] and the
32327        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
32328        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
32329        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
32330        // discipline (a085b26) on the per-renderer canonical-K8s-axis
32331        // string-constant axis: a future refactor that drifts the
32332        // constant out from under either consumer surfaces here ahead
32333        // of every per-renderer's first emission. The literal value
32334        // matches the well-known HTTP-alt port the `pleme-computeunit`
32335        // library chart already emits as its `trigger.service.port`
32336        // default — by construction the same value the substrate
32337        // assumes about every Servico's in-cluster L4 listener.
32338        assert_eq!(
32339            DEFAULT_SERVICO_PORT, 8080,
32340            "canonical Servico port literal must remain `8080` verbatim — \
32341             this is the value both the `Entrada::port` serde default and the \
32342             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
32343        );
32344    }
32345
32346    #[test]
32347    fn default_port_helper_returns_canonical_servico_port_constant() {
32348        // The bridge-arm — pins that the [`default_port`] helper
32349        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
32350        // attribute hooks routes through the lifted
32351        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
32352        // literal. A future refactor that re-introduces the `8080`
32353        // literal at the helper's return site (silently re-opening
32354        // the drift footgun this lift closed) surfaces here ahead of
32355        // every author-side `(:entrada (:host … :para …))` slot
32356        // without an explicit `:port`. Peer with the
32357        // `default_namespace_re_export_points_at_caixa_core_canonical`
32358        // pin on the caixa-mesh-side re-export axis.
32359        assert_eq!(
32360            default_port(),
32361            DEFAULT_SERVICO_PORT,
32362            "the serde-default helper must route through the lifted constant"
32363        );
32364    }
32365
32366    #[test]
32367    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
32368        // The end-to-end pin — an author-surface `(:entrada (:host …
32369        // :para …))` without an explicit `:port` slot deserializes to
32370        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
32371        // verbatim. Routes the canonical lifted constant through both
32372        // the serde-default machinery (the `#[serde(default =
32373        // "default_port")]` attribute) and the typed-value-shape
32374        // contract (the resulting [`Entrada::port`] value). A future
32375        // refactor that drifts either axis — replacing the serde
32376        // hook's helper, changing the typed slot's wire shape — would
32377        // surface here before any per-renderer's CNP / Gateway /
32378        // HTTPRoute emission consumed the drifted default.
32379        let entrada: Entrada =
32380            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
32381        assert_eq!(
32382            entrada.port, DEFAULT_SERVICO_PORT,
32383            "the serde default must materialize as the lifted canonical Servico port"
32384        );
32385    }
32386
32387    #[test]
32388    fn servico_port_min_pins_canonical_accept_set_floor() {
32389        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
32390        // verbatim `1` literal every typed `:entrada :port` acceptance
32391        // gate keys off. Peer with the
32392        // [`default_servico_port_constant_pins_canonical_8080_literal`]
32393        // discipline on the canonical-Servico-port-constant axis: a
32394        // future refactor that drifts the accept-set floor out from
32395        // under the sole consumer at [`AplicacaoSpec::validate`]'s
32396        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
32397        // every per-`:entrada` `EntradaPortZero` diagnostic. The
32398        // literal value matches the IANA-registered TCP/UDP port
32399        // space floor (`1..=65535` — port `0` is the "any ephemeral"
32400        // sentinel, not a well-defined destination the substrate's
32401        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
32402        // axis can honor).
32403        assert_eq!(
32404            SERVICO_PORT_MIN, 1,
32405            "canonical Servico port accept-set floor must remain `1` verbatim — \
32406             this is the value the `AplicacaoSpec::validate` gate at \
32407             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
32408        );
32409    }
32410
32411    #[test]
32412    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
32413        // The cross-const invariant pin — the substrate's canonical
32414        // default port must satisfy its own accept-set floor by
32415        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
32416        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
32417        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
32418        // override the operator pins through a future
32419        // `:placement :default-port` slot that lands out-of-range, a
32420        // per-edition Servico-port migration that lifted the floor
32421        // above the previous default without coordinating the pair —
32422        // would silently invalidate the serde-default emission at
32423        // every author-side `(:entrada (:host … :para …))` slot
32424        // without an explicit `:port`: the default port would fall
32425        // below the accept-set floor, the `AplicacaoSpec::validate`
32426        // gate would reject every default-carrying Aplicacao as
32427        // `EntradaPortZero`, and the substrate's typed
32428        // `(defcaixa … :kind Aplicacao)` surface would fail validate
32429        // on every Aplicacao whose author omitted `:entrada :port`
32430        // for the substrate's chosen default — a class of authoring-
32431        // surface footguns the compile-time pin structurally closes.
32432        // Peer with the
32433        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
32434        // (27f9b34) cross-const invariant pin discipline on the peer
32435        // canonical-Helm-per-values-block child-chart-enablement-toggle
32436        // axis pair.
32437        const {
32438            assert!(
32439                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
32440                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
32441                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
32442                 every default-carrying `(:entrada (:host … :para …))` slot \
32443                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
32444                 through the serde default hook and must pass the \
32445                 `AplicacaoSpec::validate` floor gate by construction",
32446            );
32447        }
32448    }
32449
32450    #[test]
32451    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
32452        // The gate-site pin — asserts the `AplicacaoSpec::validate`
32453        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
32454        // `EntradaPortZero` diagnostic on the below-floor input
32455        // `port: 0` (the only below-floor value the `u16` field can
32456        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
32457        // is the singleton `{0}`). A future refactor that drifts the
32458        // gate off the lifted const (silently re-introducing an
32459        // inline `if e.port == 0` byte-check) surfaces here — the
32460        // pin cannot distinguish `< 1` from `== 0` on the current
32461        // floor, but it *does* pin that the diagnostic fires on `0`
32462        // through whichever gate is wired, so any future accept-set
32463        // floor migration (a hypothetical unprivileged-only
32464        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
32465        // update this test alongside the const declaration —
32466        // structurally guaranteeing the gate + accept-set + pin
32467        // trio move together. Peer with the
32468        // [`rejects_zero_entrada_port`] behavioral pin on the same
32469        // per-`:entrada :port` axis — that pin asserts the pre-lift
32470        // behavioral contract (`port: 0` → `EntradaPortZero`); this
32471        // pin adds the structural link to the lifted floor const.
32472        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
32473        let mut s = three_member_spec();
32474        s.entrada.as_mut().unwrap().port = 0;
32475        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
32476    }
32477
32478    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
32479
32480    #[test]
32481    fn membro_serde_keys_match_lifted_membro_key_consts() {
32482        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
32483        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
32484        // name the exact camelCase JSON keys the
32485        // `#[serde(rename_all = "camelCase")]` attribute on
32486        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
32487        // that each canonical byte-sequence appears verbatim in the
32488        // JSON — a future accidental `rename_all = "snake_case"` /
32489        // `"kebab-case"` / verbatim-field-name flip at the derive
32490        // attribute (any of which would silently break every downstream
32491        // JSON consumer that reaches for one of the two consts via
32492        // `Value::get(...)`) surfaces here as a build-time test failure
32493        // at `aplicacao.rs`, not as an apply-time
32494        // `.get(<stale-canonical-const>)` returning `None` far from the
32495        // derive-attr drift's commit. Peer with the sibling
32496        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
32497        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
32498        // same discipline the SupervisorSpec top-level lift established,
32499        // extended here to the M3 [`Membro`] per-`:membros` axis.
32500        let m = Membro {
32501            caixa: "catalog".into(),
32502            versao: "^0.1".into(),
32503        };
32504        let json = serde_json::to_string(&m).unwrap();
32505        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
32506            let quoted = format!("\"{key}\"");
32507            assert!(
32508                json.contains(&quoted),
32509                "serialized Membro must carry the lifted MEMBRO_KEY_* \
32510                 byte-sequence {quoted} verbatim in the JSON emission \
32511                 (got: {json})",
32512            );
32513        }
32514    }
32515
32516    #[test]
32517    fn membro_key_consts_are_pairwise_distinct() {
32518        // Cross-axis drift-detection pin: a future collapse of the two
32519        // canonical [`Membro`] per-entry byte-strings onto the same
32520        // value (e.g. an accidental copy-paste flip of
32521        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
32522        // silently reroute every downstream probe on one axis onto the
32523        // sibling axis's overlay entry and pass every propagation-probe
32524        // test that expected only the stale axis's value. Peer of the
32525        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
32526        // (40cc4e5).
32527        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
32528        for (i, a) in all.iter().enumerate() {
32529            for b in all.iter().skip(i + 1) {
32530                assert_ne!(
32531                    a, b,
32532                    "MEMBRO_KEY_* consts must be pairwise-distinct \
32533                     canonical byte-sequences — got `{a}` == `{b}`",
32534                );
32535            }
32536        }
32537    }
32538
32539    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
32540    //    URL-path fallback resolver every HTTPRoute-aware renderer
32541    //    reaching for a per-rule path-list resolution routes through.
32542    //    The four pin tests below fix the four-way accept-set the
32543    //    resolver must always honor: (:paths-non-empty-verbatim,
32544    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
32545    //    :paths-preserves-order-across-multiple-entries) — drift on any
32546    //    arm surfaces at caixa-core build time rather than at cluster-
32547    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
32548    //    sibling `:politicas` typed-primitive dispatch axis.
32549
32550    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
32551        Entrada {
32552            host: "example.com".into(),
32553            para: "cart".into(),
32554            paths: paths.into_iter().map(String::from).collect(),
32555            port: DEFAULT_SERVICO_PORT,
32556        }
32557    }
32558
32559    #[test]
32560    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
32561        // The typed `:entrada :paths` slot carries an author-declared
32562        // list — the resolver returns each entry verbatim, no
32563        // catch-all substitution. The canonical "author declared
32564        // paths, honor them verbatim" arm of the path-list dispatch.
32565        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
32566        assert_eq!(
32567            e.resolved_paths(),
32568            vec!["/api/cart", "/api/products"],
32569            "resolved_paths must return each `:entrada :paths` entry \
32570             verbatim when the typed slot is non-empty (got {:?})",
32571            e.resolved_paths(),
32572        );
32573    }
32574
32575    #[test]
32576    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
32577        // Empty `:entrada :paths` slot — the resolver substitutes the
32578        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
32579        // catch-all fallback verbatim. Pins the empty-arm of the
32580        // resolver's four-way accept-set against a future silent
32581        // detour that returned an empty Vec (which would emit an
32582        // HTTPRoute with zero rules — silently dropping every
32583        // external `:entrada` flow at admission time), routed to a
32584        // different fallback shape, or dropped the catch-all
32585        // altogether.
32586        let e = entrada_with_paths(vec![]);
32587        assert_eq!(
32588            e.resolved_paths(),
32589            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
32590            "resolved_paths on empty `:entrada :paths` must fall back \
32591             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
32592             all — got {:?}",
32593            e.resolved_paths(),
32594        );
32595    }
32596
32597    #[test]
32598    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
32599        // Single-entry `:entrada :paths` — the resolver returns the
32600        // single declared path verbatim, NOT the catch-all fallback
32601        // (author declared a path, honor it — the empty-arm and the
32602        // len-1 arm are semantically distinct axes of the resolver's
32603        // accept-set). Pins that the resolver treats "author declared
32604        // one path" as authored input, not as the empty case.
32605        let e = entrada_with_paths(vec!["/api/only"]);
32606        assert_eq!(
32607            e.resolved_paths(),
32608            vec!["/api/only"],
32609            "resolved_paths on single-entry `:entrada :paths` must \
32610             return the declared path verbatim, NOT the catch-all \
32611             fallback (got {:?})",
32612            e.resolved_paths(),
32613        );
32614    }
32615
32616    #[test]
32617    fn resolved_paths_preserves_author_declared_order() {
32618        // The `:entrada :paths` list is author-ordered — the resolver
32619        // preserves the author's declaration order verbatim, since
32620        // per-rule dispatch order at the K8s Gateway API HTTPRoute
32621        // consumer is significant (first-match-wins under the
32622        // path-prefix matcher). Pins against a future silent
32623        // re-sort / dedup / normalize detour that reordered author
32624        // input.
32625        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
32626        assert_eq!(
32627            e.resolved_paths(),
32628            vec!["/z/last", "/a/first", "/m/mid"],
32629            "resolved_paths must preserve author-declared `:entrada \
32630             :paths` order verbatim — got {:?}",
32631            e.resolved_paths(),
32632        );
32633    }
32634
32635    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
32636    //    slot `&[String]` slice accessor every per-`:entrada` consumer
32637    //    that must see the author's declaration verbatim (not the
32638    //    fallback-applied projection the sibling `resolved_paths`
32639    //    returns) routes through. The three pin tests below fix the
32640    //    accept-set the accessor must honor: (:non-empty-byte-equal,
32641    //    :empty-projects-empty-slice, :preserves-author-declared-order)
32642    //    — drift on any arm surfaces at caixa-core build time rather
32643    //    than at cluster-apply time. Peer discipline with the sibling
32644    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
32645    //    peer M3 mesh-slot `Vec<String>`-carry axis.
32646
32647    #[test]
32648    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
32649        // Byte-equal pin: [`Entrada::paths`] must project the raw
32650        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
32651        // slice borrowed from the typed slot's own [`Vec<String>`]
32652        // storage — no re-ordering, no dedup, no per-entry normalization,
32653        // no fallback substitution (the fallback-applying projection is
32654        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
32655        // a future silent detour that re-normalized the list, dropped
32656        // duplicates the [`AplicacaoSpec::validate`]
32657        // `EntradaPathDuplicate` refusal already rejects at build time,
32658        // or (most severe) accidentally routed through the fallback-
32659        // applying sibling and returned the substrate catch-all when
32660        // the author declared an empty list — collapsing the raw-slot
32661        // and fallback-applied axes into one and breaking the
32662        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
32663        //
32664        // Peer of the sibling
32665        // [`Placement::clusters`]-shape byte-equal pin
32666        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
32667        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
32668        let fixtures: Vec<Vec<String>> = vec![
32669            Vec::new(),
32670            vec!["/api/cart".into()],
32671            vec!["/api/cart".into(), "/api/products".into()],
32672            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
32673        ];
32674        for paths in fixtures {
32675            let e = Entrada {
32676                host: "example.com".into(),
32677                para: "cart".into(),
32678                paths: paths.clone(),
32679                port: DEFAULT_SERVICO_PORT,
32680            };
32681            assert_eq!(
32682                e.paths(),
32683                paths.as_slice(),
32684                "Entrada::paths must return :entrada :paths verbatim \
32685                 (got {:?}, expected {:?})",
32686                e.paths(),
32687                paths.as_slice(),
32688            );
32689            assert_eq!(
32690                e.paths(),
32691                e.paths.as_slice(),
32692                "Entrada::paths accessor and .paths.as_slice() field \
32693                 access must byte-equal — the accessor is the substrate-\
32694                 primitive typed dispatch every downstream per-`:entrada` \
32695                 raw-slot path-list consumer must route through",
32696            );
32697            assert_eq!(
32698                e.paths().len(),
32699                e.paths.len(),
32700                "Entrada::paths().len() must byte-equal self.paths.len() \
32701                 — a length drift would silently split the paired \
32702                 pre-flight cascade-head `.is_empty()` probe input in \
32703                 the sibling [`Entrada::resolved_paths`] resolver from \
32704                 the per-entry validate loop's traversal input in \
32705                 [`AplicacaoSpec::validate`]",
32706            );
32707        }
32708    }
32709
32710    #[test]
32711    fn resolved_paths_reads_through_lifted_paths_accessor() {
32712        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
32713        // pre-flight `.paths().is_empty()` cascade-head probe (which
32714        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
32715        // catch-all fallback arm when the accessor projects the empty
32716        // slice) and the per-entry `.paths().iter().map(String::as_str)`
32717        // projection (which must reach every entry in the same order
32718        // the accessor projects, so the sibling
32719        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
32720        // per-entry projection stay in lockstep by construction) must
32721        // both key off the lifted accessor. Pins the two-site coherence
32722        // by exercising each production consumer end-to-end: (1) the
32723        // catch-all-fallback arm under the empty slice, (2) the
32724        // author-declared-verbatim arm under a two-entry cohort whose
32725        // per-entry projection must byte-equal the input's per-entry
32726        // author-declared paths in the author's declared order.
32727        //
32728        // Peer of the sibling M3
32729        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
32730        // `validate_placement_reads_through_lifted_clusters_accessor`
32731        // on the sibling `Placement::clusters` reader-site convergence.
32732        let empty = entrada_with_paths(vec![]);
32733        assert_eq!(
32734            empty.resolved_paths(),
32735            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
32736            "resolved_paths on empty :entrada :paths must trip the \
32737             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
32738             catch-all fallback — routing through the lifted paths() \
32739             accessor must not silently drop the fallback arm",
32740        );
32741
32742        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
32743        assert_eq!(
32744            declared.resolved_paths(),
32745            vec!["/api/cart", "/api/products"],
32746            "resolved_paths on non-empty :entrada :paths must return each \
32747             entry verbatim in the author's declared order — routing \
32748             through the lifted paths() accessor must not silently \
32749             reorder or drop entries",
32750        );
32751        // Byte-equal pin against the raw-slot accessor to keep the
32752        // fallback-applying resolver's per-entry projection input in
32753        // lockstep with the raw-slot accessor's projection.
32754        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
32755        assert_eq!(
32756            declared.resolved_paths(),
32757            raw_projected,
32758            "resolved_paths non-empty projection must byte-equal the \
32759             lifted paths() accessor's per-entry String::as_str projection \
32760             — the two projections share the same input slice by \
32761             construction, so any drift here would surface a silent \
32762             re-ordering / dedup / normalization detour in the resolver",
32763        );
32764    }
32765
32766    #[test]
32767    fn validate_reads_through_lifted_entrada_paths_accessor() {
32768        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
32769        // per-entry value-shape gate's `for p in e.paths()` traversal
32770        // (which must reach every entry in the same order the accessor
32771        // projects, so both the per-entry `EntradaPathEmpty` /
32772        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
32773        // the duplicate-detection HashSet insert that trips
32774        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
32775        // projection) must route through the lifted accessor. Pins the
32776        // coherence by exercising each production consumer end-to-end:
32777        // (1) the `EntradaPathEmpty` refusal fires on the second entry
32778        // of a two-entry cohort whose head is valid but tail is empty
32779        // (which requires the loop to reach the second entry through
32780        // the accessor), and (2) the `EntradaPathDuplicate` refusal
32781        // fires on the second entry of a two-entry cohort that shares
32782        // a path (which requires the loop to reach both entries — a
32783        // first-entry-only projection would silently pass since the
32784        // dedup HashSet has room for the first insert).
32785        //
32786        // Peer of the sibling
32787        // `validate_placement_reads_through_lifted_clusters_accessor`
32788        // on the sibling `Placement::clusters` reader-site convergence.
32789        let base = crate::AplicacaoSpec {
32790            membros: vec![crate::Membro {
32791                caixa: "cart".into(),
32792                versao: "^0.1".into(),
32793            }],
32794            contratos: Vec::new(),
32795            politicas: crate::MeshPolicy::default(),
32796            placement: crate::Placement {
32797                estrategia: crate::PlacementStrategy::SingleNode,
32798                clusters: vec!["rio".into()],
32799                shard_key: None,
32800                affinity: None,
32801            },
32802            entrada: Some(Entrada {
32803                host: "example.com".into(),
32804                para: "cart".into(),
32805                paths: vec!["/api/cart".into(), String::new()],
32806                port: DEFAULT_SERVICO_PORT,
32807            }),
32808        };
32809        assert_eq!(
32810            base.validate(),
32811            Err(crate::AplicacaoError::EntradaPathEmpty),
32812            "validate must trip EntradaPathEmpty on the second entry of \
32813             a two-entry cohort — routing through the lifted paths() \
32814             accessor must not silently short-circuit the loop at the \
32815             valid head entry",
32816        );
32817
32818        let mut dup = base;
32819        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
32820        assert_eq!(
32821            dup.validate(),
32822            Err(crate::AplicacaoError::EntradaPathDuplicate {
32823                path: "/api/cart".into(),
32824            }),
32825            "validate must trip EntradaPathDuplicate on the second entry \
32826             of a two-entry cohort that shares a path — routing through \
32827             the lifted paths() accessor must not silently short-circuit \
32828             the dedup HashSet insert at the first entry",
32829        );
32830    }
32831
32832    // ── Entrada::hostname / Entrada::hostnames — the substrate-
32833    //    canonical per-`:entrada` DNS-hostname resolver pair every
32834    //    Gateway-API-aware renderer reaching for a per-listener
32835    //    singular `hostname:` filter (Gateway) or a per-route plural
32836    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
32837    //    The three pin tests below fix the two-way accept-set the pair
32838    //    must always honor: (:singular-byte-equal-to-host,
32839    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
32840    //    on any arm surfaces at caixa-core build time rather than at
32841    //    cluster-apply time when the API server refuses the HTTPRoute
32842    //    for non-intersecting hostname filters. Peer discipline with
32843    //    the sibling `resolved_paths` accept-set pin block above on the
32844    //    per-`:entrada` path-list resolver axis.
32845
32846    fn entrada_with_host(host: &str) -> Entrada {
32847        Entrada {
32848            host: host.into(),
32849            para: "cart".into(),
32850            paths: Vec::new(),
32851            port: DEFAULT_SERVICO_PORT,
32852        }
32853    }
32854
32855    #[test]
32856    fn hostname_returns_entrada_host_byte_equal() {
32857        // The canonical singular-axis pin: [`Entrada::hostname`] must
32858        // return the `:entrada :host` field byte-for-byte, borrowed
32859        // from the typed slot's own [`String`] storage. Pins against a
32860        // future silent detour that re-normalized the host (an
32861        // accidental `.to_lowercase()` — validate_entrada_host already
32862        // enforces lowercase, so any re-normalization is redundant + a
32863        // drift surface between the validator and the accessor), a
32864        // trailing-`.` fully-qualified DNS shape substitution, or a
32865        // Punycode round-trip that lowered a Unicode host through IDNA.
32866        let e = entrada_with_host("checkout.quero.cloud");
32867        assert_eq!(
32868            e.hostname(),
32869            "checkout.quero.cloud",
32870            "Entrada::hostname must return :entrada :host verbatim \
32871             (got {:?})",
32872            e.hostname(),
32873        );
32874        assert_eq!(
32875            e.hostname(),
32876            e.host.as_str(),
32877            "Entrada::hostname must byte-equal the .host field access",
32878        );
32879    }
32880
32881    #[test]
32882    fn hostnames_returns_singleton_of_hostname_accessor() {
32883        // The pair-invariant pin: [`Entrada::hostnames`] must always
32884        // return exactly `vec![hostname()]` — the singleton list whose
32885        // sole entry is the substrate's canonical per-`:entrada`
32886        // singular hostname. Pins the two-consumer coherence axis: the
32887        // Gateway listener's singular `hostname:` filter and the
32888        // HTTPRoute's plural `spec.hostnames[]` filter list must
32889        // agree, else the Gateway API v1.x conformance layer rejects
32890        // the HTTPRoute at attach time with
32891        // `Accepted:False/NoMatchingParent` (the parent Gateway's
32892        // listener hostname doesn't intersect the route's hostname
32893        // filter list) — a divergence whose apply-time symptom is far
32894        // from any single-site commit and never surfaces in the
32895        // emitted YAML. Pinning the pair-invariant here makes any
32896        // future accidental split (an accidental `.to_string() + "."`
32897        // trailing-`.` on the plural side that didn't land on the
32898        // singular side, an accidental prefix stripping on one axis,
32899        // an accidental wildcard prepend the SNI fan-out overlay
32900        // authors on the plural side without a paired singular
32901        // migration) trip at caixa-core build time.
32902        let e = entrada_with_host("checkout.quero.cloud");
32903        assert_eq!(
32904            e.hostnames(),
32905            vec![e.hostname()],
32906            "Entrada::hostnames must return `vec![hostname()]` under \
32907             the pair-invariant — got {:?} vs. singleton {:?}",
32908            e.hostnames(),
32909            vec![e.hostname()],
32910        );
32911    }
32912
32913    #[test]
32914    fn hostnames_is_singleton_under_single_host_author_surface() {
32915        // The singleton-shape pin: under today's single-hostname-per-
32916        // `:entrada` author surface (the `:host` slot is a single
32917        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
32918        // must always return a list of length exactly one. Pins
32919        // against a future silent detour that returned an empty list
32920        // (which would emit an HTTPRoute with `spec.hostnames: []` —
32921        // matching every incoming Host header regardless of the
32922        // Aplicacao's declared ingress apex, silently over-matching
32923        // every foreign VirtualHost the parent Gateway also fronts) or
32924        // a duplicated entry (which the Gateway API v1.x parser
32925        // accepts as a `[]-length-2 list of equal hostnames]` but
32926        // whose semantics differ from the intended singleton). The
32927        // author-surface extension point ("a future `:entrada
32928        // :alt-hosts` list overlay" the docstring names) is the sole
32929        // future axis that flips this pin — that migration will re-
32930        // author this test to pin the new plural cardinality.
32931        let e = entrada_with_host("checkout.quero.cloud");
32932        assert_eq!(
32933            e.hostnames().len(),
32934            1,
32935            "Entrada::hostnames must be a singleton under today's \
32936             single-hostname-per-`:entrada` author surface — got \
32937             length {}: {:?}",
32938            e.hostnames().len(),
32939            e.hostnames(),
32940        );
32941    }
32942
32943    // ── Entrada::destination — the substrate-canonical per-`:entrada`
32944    //    destination-Servico scalar accessor every Gateway-API
32945    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
32946    //    discriminator arg (HTTPRoute name composer) or a per-rule
32947    //    `backendRefs[0].name` axis routes through. The two pin tests
32948    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
32949    //    either arm surfaces at caixa-core build time rather than at
32950    //    cluster-apply time when an HTTPRoute's `metadata.name` and
32951    //    `backendRefs[]` silently disagree on which destination Servico
32952    //    the ingress fronts. Peer discipline with the sibling
32953    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
32954    //    blocks above on the per-`:entrada` path-list / DNS-hostname
32955    //    resolver axes.
32956
32957    #[test]
32958    fn destination_returns_entrada_para_byte_equal() {
32959        // The canonical destination-scalar pin: [`Entrada::destination`]
32960        // must return the `:entrada :para` field byte-for-byte, borrowed
32961        // from the typed slot's own [`String`] storage. Pins against a
32962        // future silent detour that re-normalized the destination (an
32963        // accidental `.to_lowercase()` — the destination Servico is
32964        // already validated as a DNS-1123 label upstream, so any
32965        // re-normalization is redundant + a drift surface between the
32966        // validator and the accessor), a namespace-prefix rewrite (an
32967        // accidental `format!("{namespace}/{para}")` per-CR fully-
32968        // qualified rewrite that didn't land on the peer axis), or a
32969        // per-cluster suffix stamp the operator authors on one
32970        // consumer without the other.
32971        for para in ["cart", "checkout", "catalog", "orders-v2"] {
32972            let e = Entrada {
32973                host: "checkout.quero.cloud".into(),
32974                para: para.into(),
32975                paths: Vec::new(),
32976                port: DEFAULT_SERVICO_PORT,
32977            };
32978            assert_eq!(
32979                e.destination(),
32980                para,
32981                "Entrada::destination must return :entrada :para verbatim \
32982                 (got {:?}, expected {para:?})",
32983                e.destination(),
32984            );
32985            assert_eq!(
32986                e.destination(),
32987                e.para.as_str(),
32988                "Entrada::destination must byte-equal the .para field access",
32989            );
32990        }
32991    }
32992
32993    #[test]
32994    fn destination_borrows_from_entrada_para_storage() {
32995        // The borrow-not-copy pin: [`Entrada::destination`] must
32996        // return a `&str` slice that borrows from the typed slot's
32997        // own [`String`] storage — same-address invariant with
32998        // `entrada.para.as_str()`. Pins against a future silent detour
32999        // that allocated a fresh `String` (`self.para.clone()` in the
33000        // body would type-check but silently drop the borrow, and
33001        // every downstream consumer that assumed the returned slice
33002        // outlives `&self` would break on a stale-reference use-after-
33003        // free). Peer with the sibling `hostname_returns_entrada_
33004        // host_byte_equal` on the singular-DNS-hostname axis.
33005        let e = entrada_with_host("checkout.quero.cloud");
33006        let dest = e.destination();
33007        let para_slice = e.para.as_str();
33008        assert_eq!(
33009            dest.as_ptr(),
33010            para_slice.as_ptr(),
33011            "Entrada::destination must borrow from the .para String's \
33012             backing storage — a fresh allocation here means the \
33013             accessor no longer names the substrate-primitive typed \
33014             dispatch and every downstream consumer would silently \
33015             carry a detached copy",
33016        );
33017        assert_eq!(
33018            dest.len(),
33019            para_slice.len(),
33020            "Entrada::destination and .para.as_str() must byte-equal in \
33021             length as well as in address",
33022        );
33023    }
33024
33025    #[test]
33026    fn port_returns_entrada_port_verbatim_across_permutations() {
33027        // The canonical L4-port-scalar pin: [`Entrada::port`] must
33028        // return the `:entrada :port` field verbatim as a `u16` across
33029        // every author-declared value in the validated accept-set
33030        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
33031        // silent detour that clamped the port (an accidental
33032        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
33033        // land on the peer [`AplicacaoSpec::port_for_destination`]
33034        // resolver), rewrote it through a per-cluster port-remap table
33035        // the operator authors on one consumer without the other, or
33036        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
33037        // serde-default value (which would silently collapse the
33038        // distinction between "author explicitly declared `:port 8080`"
33039        // and "author omitted the slot and inherited the default" the
33040        // future per-cluster override slot depends on). Peer with the
33041        // sibling `destination_returns_entrada_para_byte_equal` +
33042        // `hostname_returns_entrada_host_byte_equal` pins on the
33043        // per-`:entrada` `&str` scalar axes.
33044        for port in [
33045            SERVICO_PORT_MIN,
33046            DEFAULT_SERVICO_PORT,
33047            8443u16,
33048            9090u16,
33049            u16::MAX,
33050        ] {
33051            let e = Entrada {
33052                host: "checkout.quero.cloud".into(),
33053                para: "cart".into(),
33054                paths: Vec::new(),
33055                port,
33056            };
33057            assert_eq!(
33058                e.port(),
33059                port,
33060                "Entrada::port must return :entrada :port verbatim \
33061                 (got {}, expected {port})",
33062                e.port(),
33063            );
33064            assert_eq!(
33065                e.port(),
33066                e.port,
33067                "Entrada::port accessor and .port field access must \
33068                 byte-equal — the accessor is the substrate-primitive \
33069                 typed dispatch every downstream L4-port consumer must \
33070                 route through",
33071            );
33072        }
33073    }
33074
33075    #[test]
33076    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
33077        // Two-consumer coherence pin: the
33078        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
33079        // (which reads through [`Entrada::port`] to compare against
33080        // [`SERVICO_PORT_MIN`]) and the
33081        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
33082        // through [`Entrada::port`] to emit the per-destination
33083        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
33084        // lifted accessor, so any future rebrand on the typed slot's
33085        // reader shape lands at exactly one place. Pins the two-site
33086        // coherence by exercising a below-floor port through validate
33087        // (which must reject) and a validated in-accept-set port through
33088        // port_for_destination (which must emit the same value the
33089        // accessor returns).
33090        let mut spec = three_member_spec();
33091        if let Some(e) = spec.entrada.as_mut() {
33092            e.port = 0;
33093        }
33094        assert_eq!(
33095            spec.validate().unwrap_err(),
33096            AplicacaoError::EntradaPortZero,
33097            "validate must reject `:entrada :port 0` through the lifted \
33098             Entrada::port accessor — port zero lies below \
33099             SERVICO_PORT_MIN and the validator routes through port() \
33100             to name the floor",
33101        );
33102
33103        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
33104            let mut spec = three_member_spec();
33105            if let Some(e) = spec.entrada.as_mut() {
33106                e.port = port;
33107            }
33108            spec.validate().expect(
33109                "entrada with in-accept-set :port must validate — the \
33110                 structural-floor gate reads through Entrada::port",
33111            );
33112            let entrada_ref = spec.entrada().expect(":entrada present");
33113            assert_eq!(
33114                spec.port_for_destination(entrada_ref.destination()),
33115                entrada_ref.port(),
33116                "port_for_destination(entrada.destination()) must equal \
33117                 entrada.port() — the two consumers of the per-:entrada \
33118                 L4-port axis (validator, per-destination resolver) both \
33119                 route through Entrada::port",
33120            );
33121        }
33122    }
33123
33124    #[test]
33125    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
33126        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
33127        // must return the `:contratos :de` field byte-for-byte, borrowed
33128        // from the typed slot's own [`String`] storage. Peer of the
33129        // sibling `destination_returns_entrada_para_byte_equal` pin on
33130        // the per-`:entrada` axis — same "the substrate-primitive
33131        // accessor must byte-equal the raw field access verbatim across
33132        // every author-declared value" discipline extended to the
33133        // per-`:contratos` caller arm. Pins against a future silent
33134        // detour that re-normalized the caller (an accidental
33135        // `.to_lowercase()` — every `:contratos :de` is validated as a
33136        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
33137        // re-normalization is redundant + a drift surface between the
33138        // validator and the accessor), a namespace-prefix rewrite (an
33139        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
33140        // rewrite that didn't land on the peer axis), or a per-cluster
33141        // suffix stamp the operator authors on one consumer without the
33142        // other.
33143        for de in ["cart", "checkout", "catalog", "orders-v2"] {
33144            let c = WitContract {
33145                de: de.into(),
33146                para: "downstream".into(),
33147                wit: "wasi:http/proxy".into(),
33148                endpoint: Some("/lookup".into()),
33149                subject: None,
33150                slot: None,
33151            };
33152            assert_eq!(
33153                c.source(),
33154                de,
33155                "WitContract::source must return :contratos :de verbatim \
33156                 (got {:?}, expected {de:?})",
33157                c.source(),
33158            );
33159            assert_eq!(
33160                c.source(),
33161                c.de.as_str(),
33162                "WitContract::source must byte-equal the .de field access",
33163            );
33164        }
33165    }
33166
33167    #[test]
33168    fn wit_contract_source_borrows_from_de_storage() {
33169        // The borrow-not-copy pin: [`WitContract::source`] must return a
33170        // `&str` slice that borrows from the typed slot's own [`String`]
33171        // storage — same-address invariant with `c.de.as_str()`. Pins
33172        // against a future silent detour that allocated a fresh `String`
33173        // (`self.de.clone()` in the body would type-check but silently
33174        // drop the borrow, and every downstream consumer that assumed
33175        // the returned slice outlives `&self` would break on a stale-
33176        // reference use-after-free). Peer of the sibling
33177        // `destination_borrows_from_entrada_para_storage` on the
33178        // per-`:entrada` axis.
33179        let c = WitContract {
33180            de: "cart".into(),
33181            para: "catalog".into(),
33182            wit: "wasi:http/proxy".into(),
33183            endpoint: Some("/lookup".into()),
33184            subject: None,
33185            slot: None,
33186        };
33187        let src = c.source();
33188        let de_slice = c.de.as_str();
33189        assert_eq!(
33190            src.as_ptr(),
33191            de_slice.as_ptr(),
33192            "WitContract::source must borrow from the .de String's \
33193             backing storage — a fresh allocation here means the \
33194             accessor no longer names the substrate-primitive typed \
33195             dispatch and every downstream consumer would silently \
33196             carry a detached copy",
33197        );
33198        assert_eq!(
33199            src.len(),
33200            de_slice.len(),
33201            "WitContract::source and .de.as_str() must byte-equal in \
33202             length as well as in address",
33203        );
33204    }
33205
33206    #[test]
33207    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
33208        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
33209        // must return the `:contratos :para` field byte-for-byte,
33210        // borrowed from the typed slot's own [`String`] storage. Peer of
33211        // the sibling `destination_returns_entrada_para_byte_equal` on
33212        // the per-`:entrada` axis — both accessors name "the destination-
33213        // Servico byte-string" concept on their respective mesh-slot
33214        // atoms (per-ingress apex vs. per-typed-edge callee) and both
33215        // must project the underlying `.para` field verbatim so every
33216        // downstream renderer that composes them with peer accessors
33217        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
33218        // per-edge L4 port emit site) reads the same byte-string the
33219        // author declared.
33220        for para in ["catalog", "payment", "orders", "inventory-v3"] {
33221            let c = WitContract {
33222                de: "cart".into(),
33223                para: para.into(),
33224                wit: "wasi:http/proxy".into(),
33225                endpoint: Some("/lookup".into()),
33226                subject: None,
33227                slot: None,
33228            };
33229            assert_eq!(
33230                c.destination(),
33231                para,
33232                "WitContract::destination must return :contratos :para \
33233                 verbatim (got {:?}, expected {para:?})",
33234                c.destination(),
33235            );
33236            assert_eq!(
33237                c.destination(),
33238                c.para.as_str(),
33239                "WitContract::destination must byte-equal the .para \
33240                 field access",
33241            );
33242        }
33243    }
33244
33245    #[test]
33246    fn wit_contract_destination_borrows_from_para_storage() {
33247        // The borrow-not-copy pin: [`WitContract::destination`] must
33248        // return a `&str` slice that borrows from the typed slot's own
33249        // [`String`] storage — same-address invariant with
33250        // `c.para.as_str()`. Peer of the sibling
33251        // `destination_borrows_from_entrada_para_storage` on the
33252        // per-`:entrada` axis.
33253        let c = WitContract {
33254            de: "cart".into(),
33255            para: "catalog".into(),
33256            wit: "wasi:http/proxy".into(),
33257            endpoint: Some("/lookup".into()),
33258            subject: None,
33259            slot: None,
33260        };
33261        let dest = c.destination();
33262        let para_slice = c.para.as_str();
33263        assert_eq!(
33264            dest.as_ptr(),
33265            para_slice.as_ptr(),
33266            "WitContract::destination must borrow from the .para \
33267             String's backing storage — a fresh allocation here means \
33268             the accessor no longer names the substrate-primitive typed \
33269             dispatch and every downstream consumer would silently \
33270             carry a detached copy",
33271        );
33272        assert_eq!(
33273            dest.len(),
33274            para_slice.len(),
33275            "WitContract::destination and .para.as_str() must byte-equal \
33276             in length as well as in address",
33277        );
33278    }
33279
33280    #[test]
33281    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
33282        // The canonical per-`:contratos` WIT-world-reference scalar pin:
33283        // [`WitContract::world_ref`] must return the `:contratos :wit`
33284        // field byte-for-byte, borrowed from the typed slot's own
33285        // [`String`] storage. Sibling of the peer per-`:contratos`
33286        // [`WitContract::source`] / [`WitContract::destination`]
33287        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
33288        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
33289        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
33290        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
33291        // "the substrate-primitive accessor must byte-equal the raw
33292        // field access verbatim across every author-declared value"
33293        // discipline extended to the per-`:contratos` WIT-world arm.
33294        // Pins against a future silent detour that re-canonicalized the
33295        // WIT world reference (an accidental `.to_lowercase()` pass that
33296        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
33297        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
33298        // gate is already lowercase-prefixed so any re-normalization is
33299        // redundant + a drift surface between the validator and the
33300        // accessor), an M4-promotion-shape rewrite that formatted a
33301        // typed WIT-world enum through [`Display`] and silently drifted
33302        // the printer output from the source `caixa.lisp`, or a per-
33303        // cluster WIT-alias rewrite that didn't land on the peer field-
33304        // access sites. Five values sweep the shape-dispatch accept-set
33305        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
33306        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
33307        // `wasi:keyvalue/`).
33308        for (wit, endpoint, subject, slot) in [
33309            ("wasi:http/proxy", Some("/lookup"), None, None),
33310            ("http:proxy", Some("/health"), None, None),
33311            ("nats:pub-sub", None, Some("orders.paid"), None),
33312            ("kafka:events", None, Some("checkout-events"), None),
33313            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
33314        ] {
33315            let c = WitContract {
33316                de: "cart".into(),
33317                para: "downstream".into(),
33318                wit: wit.into(),
33319                endpoint: endpoint.map(str::to_string),
33320                subject: subject.map(str::to_string),
33321                slot: slot.map(str::to_string),
33322            };
33323            assert_eq!(
33324                c.world_ref(),
33325                wit,
33326                "WitContract::world_ref must return :contratos :wit \
33327                 verbatim (got {:?}, expected {wit:?})",
33328                c.world_ref(),
33329            );
33330            assert_eq!(
33331                c.world_ref(),
33332                c.wit.as_str(),
33333                "WitContract::world_ref must byte-equal the .wit field \
33334                 access",
33335            );
33336        }
33337    }
33338
33339    #[test]
33340    fn wit_contract_world_ref_borrows_from_wit_storage() {
33341        // The borrow-not-copy pin: [`WitContract::world_ref`] must
33342        // return a `&str` slice that borrows from the typed slot's own
33343        // [`String`] storage — same-address invariant with
33344        // `c.wit.as_str()`. Pins against a future silent detour that
33345        // allocated a fresh `String` (`self.wit.clone()` in the body
33346        // would type-check but silently drop the borrow, and every
33347        // downstream consumer that assumed the returned slice outlives
33348        // `&self` would break on a stale-reference use-after-free — the
33349        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
33350        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
33351        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
33352        // / [`is_pubsub`][WitContract::is_pubsub] /
33353        // [`is_store`][WitContract::is_store] methods route through —
33354        // each borrow from the WitContract's own storage and each would
33355        // silently misbehave if this accessor produced a detached copy).
33356        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
33357        // [`WitContract::destination`] and per-`:entrada`
33358        // [`Entrada::destination`] / [`Entrada::hostname`] and
33359        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
33360        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
33361        let c = WitContract {
33362            de: "cart".into(),
33363            para: "catalog".into(),
33364            wit: "wasi:http/proxy".into(),
33365            endpoint: Some("/lookup".into()),
33366            subject: None,
33367            slot: None,
33368        };
33369        let world = c.world_ref();
33370        let wit_slice = c.wit.as_str();
33371        assert_eq!(
33372            world.as_ptr(),
33373            wit_slice.as_ptr(),
33374            "WitContract::world_ref must borrow from the .wit String's \
33375             backing storage — a fresh allocation here means the \
33376             accessor no longer names the substrate-primitive typed \
33377             dispatch and every downstream consumer would silently carry \
33378             a detached copy",
33379        );
33380        assert_eq!(
33381            world.len(),
33382            wit_slice.len(),
33383            "WitContract::world_ref and .wit.as_str() must byte-equal in \
33384             length as well as in address",
33385        );
33386    }
33387
33388    #[test]
33389    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
33390        // Sibling-triple invariant pin composing all three per-`:contratos`
33391        // substrate-primitive typed dispatches — [`WitContract::source`]
33392        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
33393        // [`WitContract::world_ref`] — at the joint
33394        // `(source(), destination(), world_ref())` call shape every
33395        // renderer that fans on per-edge caller-callee-shape identity
33396        // keys off. The invariant, evaluated per-contract:
33397        //
33398        //   (c.source(), c.destination(), c.world_ref())
33399        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
33400        //
33401        // Closes the last unlifted per-`:contratos` scalar axis — every
33402        // downstream consumer that reads the triple now routes through
33403        // exactly three typed dispatches on the substrate primitive,
33404        // not two typed + one open-coded field access. A future refactor
33405        // that silently split any one accessor's projection (an
33406        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
33407        // canonicalization that didn't reach the peer `source`/
33408        // `destination` arms, an accidental `source()` per-cluster
33409        // caller-alias rewrite that didn't land on the `world_ref` peer)
33410        // surfaces at caixa-core build time. Peer of the sibling per-
33411        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
33412        // per-`:entrada` `(hostname(), destination())` (6db982c /
33413        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
33414        // axes, extended to the per-`:contratos` triple.
33415        for (de, para, wit, endpoint, subject, slot) in [
33416            (
33417                "cart",
33418                "catalog",
33419                "wasi:http/proxy",
33420                Some("/lookup"),
33421                None,
33422                None,
33423            ),
33424            (
33425                "checkout",
33426                "orders",
33427                "nats:pub-sub",
33428                None,
33429                Some("orders.paid"),
33430                None,
33431            ),
33432            (
33433                "cart",
33434                "kv",
33435                "wasi:keyvalue/store",
33436                None,
33437                None,
33438                Some("carts/{cart_id}"),
33439            ),
33440            (
33441                "orders-v2",
33442                "inventory-v3",
33443                "http:proxy",
33444                Some("/reserve"),
33445                None,
33446                None,
33447            ),
33448        ] {
33449            let c = WitContract {
33450                de: de.into(),
33451                para: para.into(),
33452                wit: wit.into(),
33453                endpoint: endpoint.map(str::to_string),
33454                subject: subject.map(str::to_string),
33455                slot: slot.map(str::to_string),
33456            };
33457            assert_eq!(
33458                (c.source(), c.destination(), c.world_ref()),
33459                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
33460                "(WitContract::source, ::destination, ::world_ref) must \
33461                 project (.de, .para, .wit) verbatim across every author-\
33462                 declared triple (got ({:?}, {:?}, {:?}), expected \
33463                 ({de:?}, {para:?}, {wit:?}))",
33464                c.source(),
33465                c.destination(),
33466                c.world_ref(),
33467            );
33468        }
33469    }
33470
33471    #[test]
33472    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
33473        // The canonical per-`:contratos` owned-form caller-callee-pair
33474        // pin: [`WitContract::edge_pair`] must return the
33475        // `(source(), destination())` tuple in owned form byte-for-byte,
33476        // projected through the lifted [`WitContract::source`] /
33477        // [`WitContract::destination`] scalar accessors. Pins the
33478        // composite-projection invariant on the per-`:contratos`
33479        // mesh-slot atom — every author-declared `(de, para)` pair must
33480        // round-trip verbatim through the substrate primitive's typed
33481        // dispatch, so the nine [`AplicacaoError`] diagnostic-
33482        // construction sites the accessor now feeds
33483        // ([`AplicacaoError::EmptyWit`],
33484        // [`AplicacaoError::ContratoEndpointEmpty`],
33485        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
33486        // [`AplicacaoError::ContratoEndpointInvalid`],
33487        // [`AplicacaoError::ContratoSubjectEmpty`],
33488        // [`AplicacaoError::ContratoSubjectInvalid`],
33489        // [`AplicacaoError::ContratoSlotEmpty`],
33490        // [`AplicacaoError::ContratoSlotInvalid`],
33491        // [`AplicacaoError::ContratoDuplicate`]) all read the same
33492        // `(de, para)` label pair every author sees at the source
33493        // `caixa.lisp`. Pins against a future silent detour that swapped
33494        // the `.0` / `.1` arms (an accidental `(destination(),
33495        // source())` re-order in the body would silently invert every
33496        // downstream diagnostic's `de:` / `para:` label pair, silently
33497        // reversing the direction of every operator-facing typed error
33498        // arrow), a fresh-allocation shape drift (an accidental
33499        // `.to_string()` on one arm but not the other would leave the
33500        // owned/borrowed pair mismatched vs. the sibling `source()` /
33501        // `destination()` returns), or an M4 per-cluster caller/callee-
33502        // alias rewrite that landed on `source()` without reaching
33503        // `destination()` (or vice versa). Peer of the sibling per-
33504        // `:contratos` `(source, destination, world_ref)` triple
33505        // pin above on the mesh-slot-atom scalar-value axes, extended
33506        // to the owned-form pair-projection axis.
33507        for (de, para, wit, endpoint, subject, slot) in [
33508            (
33509                "cart",
33510                "catalog",
33511                "wasi:http/proxy",
33512                Some("/lookup"),
33513                None,
33514                None,
33515            ),
33516            (
33517                "checkout",
33518                "orders",
33519                "nats:pub-sub",
33520                None,
33521                Some("orders.paid"),
33522                None,
33523            ),
33524            (
33525                "cart",
33526                "kv",
33527                "wasi:keyvalue/store",
33528                None,
33529                None,
33530                Some("carts/{cart_id}"),
33531            ),
33532            (
33533                "orders-v2",
33534                "inventory-v3",
33535                "http:proxy",
33536                Some("/reserve"),
33537                None,
33538                None,
33539            ),
33540        ] {
33541            let c = WitContract {
33542                de: de.into(),
33543                para: para.into(),
33544                wit: wit.into(),
33545                endpoint: endpoint.map(str::to_string),
33546                subject: subject.map(str::to_string),
33547                slot: slot.map(str::to_string),
33548            };
33549            assert_eq!(
33550                c.edge_pair(),
33551                (de.to_string(), para.to_string()),
33552                "WitContract::edge_pair must return (:contratos :de, \
33553                 :contratos :para) as an owned tuple verbatim (got {:?}, \
33554                 expected ({de:?}, {para:?}))",
33555                c.edge_pair(),
33556            );
33557        }
33558    }
33559
33560    #[test]
33561    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
33562        // The composition pin: [`WitContract::edge_pair`] must return
33563        // exactly `(source().to_string(), destination().to_string())` —
33564        // the owned form of the sibling accessor pair — so any future
33565        // refactor that silently re-authored the caller-arm / callee-arm
33566        // projection to bypass the lifted scalar accessors (an accidental
33567        // `(self.de.clone(), self.para.clone())` regression back to the
33568        // raw field-access shape, an M4-typed-caller-enum `Display`
33569        // re-canonicalization on `source()` that didn't reach
33570        // `edge_pair()`, a per-cluster alias rewrite the operator lands
33571        // on `destination()` without reaching this composite projection)
33572        // trips at caixa-core build time. Pins the "typed dispatch
33573        // composes with typed dispatch, not with raw field access"
33574        // discipline every downstream diagnostic-construction site now
33575        // routes through — a `de:` / `para:` label pair whose
33576        // projection silently drifted off the substrate primitive's
33577        // scalar accessors would silently split the diagnostic's self-
33578        // locating signal from the source `caixa.lisp` author's view.
33579        // Peer of the sibling per-`:politicas` `is_empty` /
33580        // `validate_politicas` accessor-routing-pin family on the M3
33581        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
33582        let c = WitContract {
33583            de: "cart".into(),
33584            para: "catalog".into(),
33585            wit: "wasi:http/proxy".into(),
33586            endpoint: Some("/lookup".into()),
33587            subject: None,
33588            slot: None,
33589        };
33590        assert_eq!(
33591            c.edge_pair(),
33592            (c.source().to_string(), c.destination().to_string()),
33593            "WitContract::edge_pair must compose exactly \
33594             (source().to_string(), destination().to_string()) — a \
33595             bypass of either sibling accessor here would silently \
33596             decouple the composite-projection axis from the \
33597             substrate-primitive scalar accessors every downstream \
33598             consumer routes through",
33599        );
33600    }
33601
33602    #[test]
33603    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
33604     {
33605        // The canonical per-`:contratos` owned-form
33606        // caller-callee-world-ref-triple pin:
33607        // [`WitContract::edge_triple`] must return the
33608        // `(source(), destination(), world_ref())` tuple in owned form
33609        // byte-for-byte, projected through the lifted
33610        // [`WitContract::source`] / [`WitContract::destination`] /
33611        // [`WitContract::world_ref`] scalar accessors. Pins the
33612        // composite-projection invariant on the per-`:contratos`
33613        // mesh-slot atom — every author-declared `(de, para, wit)`
33614        // triple must round-trip verbatim through the substrate
33615        // primitive's typed dispatch, so the nine
33616        // [`AplicacaoError`] diagnostic-construction sites the
33617        // accessor now feeds (the [`WitTarget`]-dispatch's eight
33618        // wrong-target / missing-target / invalid-wit / capability-
33619        // with-payload arms in [`WitContract::target`], plus the
33620        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
33621        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
33622        // read the same `(de, para, wit)` triple every author sees at
33623        // the source `caixa.lisp`. Pins against a future silent
33624        // detour that swapped any two arms (an accidental `(destination(),
33625        // source(), world_ref())` re-order in the body would silently
33626        // invert every downstream diagnostic's `de:` / `para:` label
33627        // pair, silently reversing the direction of every operator-
33628        // facing typed error arrow), a fresh-allocation shape drift
33629        // (an accidental `.to_string()` skipped on one arm would leave
33630        // the owned/borrowed triple mismatched vs. the sibling
33631        // `source()` / `destination()` / `world_ref()` returns), or an
33632        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
33633        // canonicalization pass that landed on one accessor without
33634        // reaching the peers. Peer of the sibling per-`:contratos`
33635        // caller-callee-pair
33636        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
33637        // pin on the mesh-slot-atom composite-projection axis,
33638        // extended to the triple-projection axis.
33639        for (de, para, wit, endpoint, subject, slot) in [
33640            (
33641                "cart",
33642                "catalog",
33643                "wasi:http/proxy",
33644                Some("/lookup"),
33645                None,
33646                None,
33647            ),
33648            (
33649                "checkout",
33650                "orders",
33651                "nats:pub-sub",
33652                None,
33653                Some("orders.paid"),
33654                None,
33655            ),
33656            (
33657                "cart",
33658                "kv",
33659                "wasi:keyvalue/store",
33660                None,
33661                None,
33662                Some("carts/{cart_id}"),
33663            ),
33664            (
33665                "orders-v2",
33666                "inventory-v3",
33667                "http:proxy",
33668                Some("/reserve"),
33669                None,
33670                None,
33671            ),
33672        ] {
33673            let c = WitContract {
33674                de: de.into(),
33675                para: para.into(),
33676                wit: wit.into(),
33677                endpoint: endpoint.map(str::to_string),
33678                subject: subject.map(str::to_string),
33679                slot: slot.map(str::to_string),
33680            };
33681            assert_eq!(
33682                c.edge_triple(),
33683                (de.to_string(), para.to_string(), wit.to_string()),
33684                "WitContract::edge_triple must return (:contratos :de, \
33685                 :contratos :para, :contratos :wit) as an owned triple \
33686                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
33687                c.edge_triple(),
33688            );
33689        }
33690    }
33691
33692    #[test]
33693    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
33694        // The composition pin: [`WitContract::edge_triple`] must return
33695        // exactly `(source().to_string(), destination().to_string(),
33696        // world_ref().to_string())` — the owned form of the sibling
33697        // scalar-accessor triple — so any future refactor that silently
33698        // re-authored one arm's projection to bypass the lifted scalar
33699        // accessors (an accidental `(self.de.clone(), self.para.clone(),
33700        // self.wit.clone())` regression back to the raw field-access
33701        // shape the internal `edge` closure and the ContratoDuplicate
33702        // diagnostic both carried before this lift landed, an
33703        // M4-typed-caller-enum `Display` re-canonicalization on
33704        // `source()` that didn't reach `edge_triple()`, a per-cluster
33705        // alias rewrite the operator lands on `destination()` /
33706        // `world_ref()` without reaching this composite projection)
33707        // trips at caixa-core build time. Pins the "typed dispatch
33708        // composes with typed dispatch, not with raw field access"
33709        // discipline every downstream diagnostic-construction site now
33710        // routes through — a `de:` / `para:` / `wit:` triple whose
33711        // projection silently drifted off the substrate primitive's
33712        // scalar accessors would silently split the diagnostic's self-
33713        // locating signal from the source `caixa.lisp` author's view.
33714        // Peer of the sibling per-`:contratos` edge_pair composition-
33715        // pin above on the mesh-slot-atom composite-projection axis.
33716        let c = WitContract {
33717            de: "cart".into(),
33718            para: "catalog".into(),
33719            wit: "wasi:http/proxy".into(),
33720            endpoint: Some("/lookup".into()),
33721            subject: None,
33722            slot: None,
33723        };
33724        assert_eq!(
33725            c.edge_triple(),
33726            (
33727                c.source().to_string(),
33728                c.destination().to_string(),
33729                c.world_ref().to_string(),
33730            ),
33731            "WitContract::edge_triple must compose exactly \
33732             (source().to_string(), destination().to_string(), \
33733             world_ref().to_string()) — a bypass of any sibling accessor \
33734             here would silently decouple the composite-projection axis \
33735             from the substrate-primitive scalar accessors every \
33736             downstream consumer routes through",
33737        );
33738    }
33739
33740    #[test]
33741    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
33742        // The canonical semantics-pin: [`WitContract::edge_triple`] must
33743        // project the full `(de, para, wit)` identity of a `:contratos`
33744        // edge — the sub-triple every triple-carrying
33745        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
33746        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
33747        // missing-target, capability-with-payload, invalid-wit, and the
33748        // duplicate-gate). Rejects a drift in shape (an accidental
33749        // silent detour that returned a `(de, para)` pair or added an
33750        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
33751        // would trip here because the return type would no longer
33752        // pattern-match the eight `let (de, para, wit) = edge();`
33753        // destructures the [`WitContract::target`] dispatch feeds off
33754        // + the paired duplicate-gate `let (de, para, wit) =
33755        // c.edge_triple();` destructure in
33756        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
33757        // `:contratos` caller-callee-pair pin above extended to the
33758        // triple projection surface: closes the "one composite
33759        // accessor per typed diagnostic-construction sub-tuple"
33760        // discipline on the per-`:contratos` mesh-slot-atom axis.
33761        let c = WitContract {
33762            de: "checkout".into(),
33763            para: "orders".into(),
33764            wit: "nats:pub-sub".into(),
33765            endpoint: None,
33766            subject: Some("orders.paid".into()),
33767            slot: None,
33768        };
33769        let (de, para, wit) = c.edge_triple();
33770        assert_eq!(de, "checkout");
33771        assert_eq!(para, "orders");
33772        assert_eq!(wit, "nats:pub-sub");
33773    }
33774
33775    #[test]
33776    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
33777     {
33778        // The composition pin: [`WitContract::identity`] must return
33779        // exactly `(source(), destination(), world_ref(), endpoint(),
33780        // subject(), slot())` — the borrowed form of the six-scalar-
33781        // accessor identity axis. Any future refactor that silently
33782        // re-authored one arm's projection to bypass a scalar accessor
33783        // (a `self.de.as_str()` regression back to raw field access on
33784        // any of the three required arms, a `self.endpoint.as_deref()`
33785        // regression on any of the three optional arms, an M4 per-
33786        // cluster caller/callee-alias rewrite the operator lands on
33787        // `source()` / `destination()` without reaching this composite
33788        // projection) trips at caixa-core build time. Sweeps four
33789        // permutations of the WIT-shape × payload lattice — HTTP with
33790        // endpoint, pub-sub with subject, store with slot, payload-less
33791        // capability — so every payload arm is exercised. Peer of the
33792        // sibling per-`:contratos`
33793        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
33794        // composition pin on the mesh-slot-atom composite-projection
33795        // axis; extends the discipline from the (de, para, wit) prefix
33796        // onto the full-identity axis carrying the three payload arms.
33797        for (de, para, wit, endpoint, subject, slot) in [
33798            (
33799                "cart",
33800                "catalog",
33801                "wasi:http/proxy",
33802                Some("/lookup"),
33803                None,
33804                None,
33805            ),
33806            (
33807                "checkout",
33808                "orders",
33809                "nats:pub-sub",
33810                None,
33811                Some("orders.paid"),
33812                None,
33813            ),
33814            (
33815                "cart",
33816                "kv",
33817                "wasi:keyvalue/store",
33818                None,
33819                None,
33820                Some("carts/{cart_id}"),
33821            ),
33822            ("audit", "sink", "wasi:logging", None, None, None),
33823        ] {
33824            let c = WitContract {
33825                de: de.into(),
33826                para: para.into(),
33827                wit: wit.into(),
33828                endpoint: endpoint.map(str::to_owned),
33829                subject: subject.map(str::to_owned),
33830                slot: slot.map(str::to_owned),
33831            };
33832            assert_eq!(
33833                c.identity(),
33834                (
33835                    c.source(),
33836                    c.destination(),
33837                    c.world_ref(),
33838                    c.endpoint(),
33839                    c.subject(),
33840                    c.slot(),
33841                ),
33842                "WitContract::identity must compose exactly \
33843                 (source(), destination(), world_ref(), endpoint(), \
33844                 subject(), slot()) — a bypass of any sibling accessor \
33845                 here would silently decouple the identity-projection \
33846                 axis from the substrate-primitive scalar accessors \
33847                 every dedup-key consumer routes through",
33848            );
33849        }
33850    }
33851
33852    #[test]
33853    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
33854        // The canonical semantics-pin: [`WitContract::identity`] must
33855        // project the six-axis (de, para, wit, endpoint, subject, slot)
33856        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
33857        // gate keys off — two `WitContract`s that agree on all six axes
33858        // are the same typed edge declared twice, the graph-edge
33859        // analogue of duplicate `:membros` / `:placement :clusters` /
33860        // `:entrada :paths` entries. Rejects a shape drift (an
33861        // accidental silent detour that returned a prefix tuple or
33862        // added an extra field) by pattern-matching the six-arm shape.
33863        // Peer of the sibling per-`:contratos`
33864        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
33865        // pin extended from the (de, para, wit) prefix onto the full
33866        // six-axis identity that the dedup key rides.
33867        let c = WitContract {
33868            de: "cart".into(),
33869            para: "catalog".into(),
33870            wit: "wasi:http/proxy".into(),
33871            endpoint: Some("/products/:id".into()),
33872            subject: None,
33873            slot: None,
33874        };
33875        let (de, para, wit, endpoint, subject, slot) = c.identity();
33876        assert_eq!(de, "cart");
33877        assert_eq!(para, "catalog");
33878        assert_eq!(wit, "wasi:http/proxy");
33879        assert_eq!(endpoint, Some("/products/:id"));
33880        assert_eq!(subject, None);
33881        assert_eq!(slot, None);
33882
33883        // Two byte-identical contracts must produce equal identities —
33884        // the dedup key's foundational invariant.
33885        let c2 = c.clone();
33886        assert_eq!(c.identity(), c2.identity());
33887
33888        // Any change on any of the six axes must break the identity —
33889        // sweeps by mutating one axis at a time.
33890        let mut mutated = c.clone();
33891        mutated.de = "search".into();
33892        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
33893        let mut mutated = c.clone();
33894        mutated.para = "warehouse".into();
33895        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
33896        let mut mutated = c.clone();
33897        mutated.wit = "http:legacy".into();
33898        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
33899        let mut mutated = c.clone();
33900        mutated.endpoint = Some("/search".into());
33901        assert_ne!(
33902            c.identity(),
33903            mutated.identity(),
33904            "endpoint axis must partition"
33905        );
33906        let mut mutated = c.clone();
33907        mutated.subject = Some("orders.paid".into());
33908        assert_ne!(
33909            c.identity(),
33910            mutated.identity(),
33911            "subject axis must partition"
33912        );
33913        let mut mutated = c;
33914        mutated.slot = Some("carts/{id}".into());
33915        assert_ne!(mutated.identity().5, None, "slot axis must partition");
33916    }
33917
33918    #[test]
33919    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
33920        // The canonical per-`:contratos` structural-self-edge pin:
33921        // [`WitContract::is_self_loop`] must return `true` when the
33922        // `:de` and `:para` fields agree byte-for-byte, across every
33923        // WIT-shape variant the per-edge shape family carries. Pins
33924        // the shape-agnostic identity-space partition the
33925        // [`AplicacaoSpec::validate`] self-edge gate at
33926        // caixa-core/src/aplicacao.rs:5559 fires against — all four
33927        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
33928        // under the same one predicate. Four permutations sweep the
33929        // accept-set: HTTP with endpoint, pub-sub with subject, KV
33930        // store with slot, and payload-less capability.
33931        for (nome, wit, endpoint, subject, slot) in [
33932            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
33933            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
33934            (
33935                "kv",
33936                "wasi:keyvalue/store",
33937                None,
33938                None,
33939                Some("carts/{cart_id}"),
33940            ),
33941            ("audit", "wasi:logging", None, None, None),
33942        ] {
33943            let c = WitContract {
33944                de: nome.into(),
33945                para: nome.into(),
33946                wit: wit.into(),
33947                endpoint: endpoint.map(str::to_string),
33948                subject: subject.map(str::to_string),
33949                slot: slot.map(str::to_string),
33950            };
33951            assert!(
33952                c.is_self_loop(),
33953                "WitContract::is_self_loop must return true when \
33954                 :contratos :de == :contratos :para (got false on \
33955                 {nome:?} under {wit:?})",
33956            );
33957        }
33958    }
33959
33960    #[test]
33961    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
33962        // The complement pin: [`WitContract::is_self_loop`] must return
33963        // `false` on every well-shaped inter-Servico contract (the
33964        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
33965        // names — "Servico A calls Servico B" between two distinct
33966        // graph nodes). Pins against a future silent detour that
33967        // inverted the predicate (an accidental `!= ` swap for `==`
33968        // would silently reject every legitimate inter-Servico edge
33969        // and admit every self-edge — the exact inversion of the
33970        // author-intended shape). Four permutations sweep the same
33971        // WIT-shape accept-set the sibling positive-arm test carries.
33972        for (de, para, wit, endpoint, subject, slot) in [
33973            (
33974                "cart",
33975                "catalog",
33976                "wasi:http/proxy",
33977                Some("/lookup"),
33978                None,
33979                None,
33980            ),
33981            (
33982                "checkout",
33983                "orders",
33984                "nats:pub-sub",
33985                None,
33986                Some("orders.paid"),
33987                None,
33988            ),
33989            (
33990                "cart",
33991                "kv",
33992                "wasi:keyvalue/store",
33993                None,
33994                None,
33995                Some("carts/{cart_id}"),
33996            ),
33997            ("audit", "sink", "wasi:logging", None, None, None),
33998        ] {
33999            let c = WitContract {
34000                de: de.into(),
34001                para: para.into(),
34002                wit: wit.into(),
34003                endpoint: endpoint.map(str::to_string),
34004                subject: subject.map(str::to_string),
34005                slot: slot.map(str::to_string),
34006            };
34007            assert!(
34008                !c.is_self_loop(),
34009                "WitContract::is_self_loop must return false when \
34010                 :contratos :de differs from :contratos :para (got true \
34011                 on {de:?} → {para:?} under {wit:?})",
34012            );
34013        }
34014    }
34015
34016    #[test]
34017    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
34018        // The composition pin: [`WitContract::is_self_loop`] must
34019        // resolve to exactly `self.source() == self.destination()` —
34020        // the equality probe of the sibling scalar-accessor pair — so
34021        // any future refactor that silently re-authored the predicate
34022        // to bypass the lifted scalar accessors (an accidental
34023        // `self.de == self.para` regression back to the raw field-
34024        // access shape, an M4-typed-caller-enum identity-comparison
34025        // rule that landed on `source()` without reaching
34026        // `destination()`, a per-cluster alias rewrite the operator
34027        // pins on `destination()` without reaching this predicate)
34028        // trips at caixa-core build time. Pins the "typed dispatch
34029        // composes with typed dispatch, not with raw field access"
34030        // discipline the sibling [`WitContract::edge_pair`] /
34031        // [`WitContract::edge_triple`] composite-projection accessors
34032        // already carry, extended onto the per-edge endpoint-equality
34033        // predicate axis. Positive and complement arms both fire.
34034        let self_edge = WitContract {
34035            de: "cart".into(),
34036            para: "cart".into(),
34037            wit: "wasi:http/proxy".into(),
34038            endpoint: Some("/lookup".into()),
34039            subject: None,
34040            slot: None,
34041        };
34042        assert_eq!(
34043            self_edge.is_self_loop(),
34044            self_edge.source() == self_edge.destination(),
34045            "WitContract::is_self_loop must compose exactly \
34046             `source() == destination()` — a bypass of either sibling \
34047             accessor here would silently decouple the endpoint-\
34048             equality predicate from the substrate-primitive scalar \
34049             accessors every downstream consumer routes through",
34050        );
34051        let inter_edge = WitContract {
34052            de: "cart".into(),
34053            para: "catalog".into(),
34054            wit: "wasi:http/proxy".into(),
34055            endpoint: Some("/lookup".into()),
34056            subject: None,
34057            slot: None,
34058        };
34059        assert_eq!(
34060            inter_edge.is_self_loop(),
34061            inter_edge.source() == inter_edge.destination(),
34062            "WitContract::is_self_loop must compose exactly \
34063             `source() == destination()` on the complement arm too",
34064        );
34065    }
34066
34067    #[test]
34068    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
34069        // The composition pin: [`WitContract::target`]'s invalid-wit
34070        // value-shape gate must feed the reason string through the
34071        // lifted [`WitContract::world_ref`] scalar accessor — the same
34072        // typed dispatch on the substrate primitive every peer
34073        // per-`:contratos` payload-carrier extraction in the same
34074        // method body already routes through
34075        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
34076        // [`WitContract::subject`] on the pub-sub-arm target extraction,
34077        // [`WitContract::slot`] on the store-arm target extraction) and
34078        // every peer composite-projection accessor
34079        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
34080        // [`WitContract::identity`]) already composes from. Any future
34081        // refactor that silently re-authored the gate to bypass the
34082        // lifted accessor (an accidental `&self.wit` regression back to
34083        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
34084        // re-canonicalization on `world_ref()` that didn't reach this
34085        // gate, a per-CR lowercasing canonicalization pass the M4
34086        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
34087        // per-tenant that lands on `world_ref()` without reaching this
34088        // gate) would silently split the invalid-wit diagnostic reason
34089        // from the substrate-primitive projection every downstream
34090        // consumer routes through. Same "typed dispatch composes with
34091        // typed dispatch, not with raw field access" discipline the
34092        // sibling
34093        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
34094        // pin already carries on the endpoint-equality predicate axis,
34095        // extended onto the invalid-wit value-shape gate axis inside
34096        // the same [`WitContract::target`] body. Closes the last
34097        // unlifted raw-field-access site inside `impl WitContract`.
34098        //
34099        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
34100        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
34101        // to a capability-only edge; the value-shape gate rejects it
34102        // through [`crate::render::is_wit_world_ref`] on the substrate
34103        // primitive's ASCII-lowercase-only accept-set, with a
34104        // parser-shaped reason string the test asserts round-trips
34105        // byte-for-byte between the direct-dispatch call (through the
34106        // predicate on the accessor's projection) and the
34107        // [`WitContract::target`] gate's produced reason field.
34108        let c = WitContract {
34109            de: "cart".into(),
34110            para: "catalog".into(),
34111            wit: "WASI:HTTP/proxy".into(),
34112            endpoint: Some("/lookup".into()),
34113            subject: None,
34114            slot: None,
34115        };
34116        let err = c.target().unwrap_err();
34117        let AplicacaoError::ContratoWitInvalid {
34118            ref de,
34119            ref para,
34120            ref wit,
34121            ref reason,
34122        } = err
34123        else {
34124            panic!("expected ContratoWitInvalid, got {err:?}");
34125        };
34126        assert_eq!(de, "cart");
34127        assert_eq!(para, "catalog");
34128        assert_eq!(wit, "WASI:HTTP/proxy");
34129        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
34130        assert_eq!(
34131            *reason, expected_reason,
34132            "WitContract::target's invalid-wit value-shape gate reason \
34133             must compose exactly is_wit_world_ref(self.world_ref()) — \
34134             a bypass here (e.g. a raw `&self.wit` field-access \
34135             regression, or a divergent predicate on a different \
34136             projection) would silently decouple the invalid-wit \
34137             diagnostic's reason field from the substrate-primitive \
34138             scalar accessor every peer per-`:contratos` extraction in \
34139             the same method body already routes through",
34140        );
34141    }
34142
34143    #[test]
34144    fn wit_contract_is_self_loop_predicate_is_const_fn() {
34145        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
34146        // caller-callee identity-space predicate's `const`-eval-surface
34147        // posture. The wrapper below dispatches through
34148        // [`WitContract::is_self_loop`] and is well-formed only when the
34149        // callee is itself `pub const fn` — any future accidental
34150        // downgrade to non-`const` fails the wrapper at caixa-core build
34151        // time with E0015 (`cannot call non-const method`), strictly
34152        // stronger than a runtime `assert!` and strictly stronger than a
34153        // module-scope `const _: () = assert!(…)` pin (the type's
34154        // `String` / `Option<String>` carriers rule out `const`-context
34155        // value construction; the `const fn` wrapper is the load-bearing
34156        // shape that side-steps the destructor-in-const restriction on
34157        // the value axis while still pinning the `const`-fn posture on
34158        // the callee — mirror of the sibling
34159        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
34160        // (279823b) and
34161        // [`wit_contract_identity_projection_accessor_is_const_fn`]
34162        // (1ab648c) pins' discipline verbatim on the peer scalar-
34163        // accessor and composite-projection surfaces). Closes the last
34164        // unlifted per-`:contratos` shape/identity predicate on the
34165        // const-eval surface — the peer WIT-shape-partition family
34166        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
34167        // [`WitContract::is_store`] / [`WitContract::is_capability`]
34168        // already carried the `pub const fn` posture on the peer
34169        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
34170        // this pin extends the same posture onto the caller-callee
34171        // identity-space partition. Sweeps every WIT-shape arm on both
34172        // the equal-endpoints (self-edge) and distinct-endpoints
34173        // (inter-edge) arms of the identity-space partition, plus one
34174        // same-length distinct-byte pair to pin the mid-loop `!=` arm
34175        // past the leading length-mismatch shortcut.
34176        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
34177            c.is_self_loop()
34178        }
34179        let mk = |de: &str, para: &str, wit: &str| WitContract {
34180            de: de.into(),
34181            para: para.into(),
34182            wit: wit.into(),
34183            endpoint: None,
34184            subject: None,
34185            slot: None,
34186        };
34187        for (nome, wit) in [
34188            ("cart", "wasi:http/proxy"),
34189            ("checkout", "nats:pub-sub"),
34190            ("kv", "wasi:keyvalue/store"),
34191            ("audit", "wasi:logging"),
34192        ] {
34193            let self_edge = mk(nome, nome, wit);
34194            assert!(
34195                is_self_loop_via_const_fn(&self_edge),
34196                "self-edge {nome:?} under {wit:?}"
34197            );
34198            assert_eq!(
34199                is_self_loop_via_const_fn(&self_edge),
34200                self_edge.is_self_loop()
34201            );
34202        }
34203        for (de, para, wit) in [
34204            ("cart", "catalog", "wasi:http/proxy"),
34205            ("checkout", "orders", "nats:pub-sub"),
34206            ("cart", "kv", "wasi:keyvalue/store"),
34207            ("audit", "sink", "wasi:logging"),
34208        ] {
34209            let inter_edge = mk(de, para, wit);
34210            assert!(
34211                !is_self_loop_via_const_fn(&inter_edge),
34212                "inter-edge {de:?}→{para:?} under {wit:?}",
34213            );
34214            assert_eq!(
34215                is_self_loop_via_const_fn(&inter_edge),
34216                inter_edge.is_self_loop()
34217            );
34218        }
34219        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
34220        // past the leading `a.len() != b.len()` shortcut so the const-fn
34221        // wrapper exercises every arm of the byte-slice equality loop.
34222        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
34223        assert!(
34224            !is_self_loop_via_const_fn(&same_len_pair),
34225            "same-length distinct-byte"
34226        );
34227        assert_eq!(
34228            is_self_loop_via_const_fn(&same_len_pair),
34229            same_len_pair.is_self_loop()
34230        );
34231    }
34232
34233    #[test]
34234    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
34235        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
34236        // pin: [`WitContract::endpoint`] must return the `:contratos
34237        // :endpoint` field byte-for-byte, borrowed from the typed slot's
34238        // own `Option<String>` storage. Peer of the sibling
34239        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
34240        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
34241        // mesh-slot `Option<String>` optional-scalar axes — same "the
34242        // substrate-primitive accessor must byte-equal the raw field
34243        // access verbatim across every author-declared value" discipline
34244        // extended to the per-`:contratos` HTTP-payload-carrier arm.
34245        // Pins against a future silent detour that re-canonicalized the
34246        // endpoint (an accidental percent-encoding pass that didn't
34247        // reach the peer field-access site at the dedup key, a per-CR
34248        // fully-qualified prefix rewrite the operator authors on one
34249        // consumer without the other, or an M4 typed-path-template
34250        // `Display` re-canonicalization that silently drifted the
34251        // printer output from the source `caixa.lisp`). Four values
34252        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
34253        // gate upstream admits (short root-path, dashed, param-shaped,
34254        // deep-hierarchy).
34255        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
34256            let c = WitContract {
34257                de: "cart".into(),
34258                para: "catalog".into(),
34259                wit: "wasi:http/proxy".into(),
34260                endpoint: Some(endpoint.into()),
34261                subject: None,
34262                slot: None,
34263            };
34264            assert_eq!(
34265                c.endpoint(),
34266                Some(endpoint),
34267                "WitContract::endpoint must return :contratos :endpoint \
34268                 verbatim (got {:?}, expected Some({endpoint:?}))",
34269                c.endpoint(),
34270            );
34271            assert_eq!(
34272                c.endpoint(),
34273                c.endpoint.as_deref(),
34274                "WitContract::endpoint must byte-equal the .endpoint \
34275                 field's `.as_deref()` projection",
34276            );
34277        }
34278    }
34279
34280    #[test]
34281    fn wit_contract_endpoint_none_when_field_is_none() {
34282        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
34283        // payload-carrier accessor pin: when the typed slot is absent —
34284        // the canonical shape under a non-HTTP `:wit` world per the
34285        // [`WitContract::target`]-enforced shape ↔ target partition
34286        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
34287        // carries `:slot`, [`WitTarget::Capability`] carries none) —
34288        // [`WitContract::endpoint`] must return `None`. Pins against a
34289        // future silent detour that projected the absent slot to a
34290        // `Some("")` empty-string default (the canonical `Option<String>`
34291        // → `String` collapse footgun the sibling M2
34292        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
34293        // emptiness predicates already guard on the peer M2 typed-slot
34294        // surfaces), a `Some("None")` stringified-None round-trip, or a
34295        // `Some` arm whose contents were derived from a sibling slot (an
34296        // accidental fallback to the `:subject` / `:slot` payload that
34297        // read the pub-sub / store payload into the endpoint axis).
34298        // Three contracts sweep the accept-set every non-HTTP `:wit`
34299        // world lands on — pub-sub NATS, key/value, and payload-less
34300        // capability.
34301        for (wit, subject, slot) in [
34302            ("nats:pub-sub", Some("orders.paid"), None),
34303            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
34304            ("wasi:cli/environment", None, None),
34305        ] {
34306            let c = WitContract {
34307                de: "cart".into(),
34308                para: "downstream".into(),
34309                wit: wit.into(),
34310                endpoint: None,
34311                subject: subject.map(str::to_string),
34312                slot: slot.map(str::to_string),
34313            };
34314            assert!(
34315                c.endpoint().is_none(),
34316                "WitContract::endpoint must return None when the typed \
34317                 slot is absent under :wit {wit:?} (got {:?})",
34318                c.endpoint(),
34319            );
34320            assert_eq!(
34321                c.endpoint(),
34322                c.endpoint.as_deref(),
34323                "WitContract::endpoint must byte-equal the .endpoint \
34324                 field's `.as_deref()` projection in the absent arm",
34325            );
34326        }
34327    }
34328
34329    #[test]
34330    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
34331        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
34332        // an `Option<&str>` whose `Some` arm borrows from the typed
34333        // slot's own [`String`] storage — same-address invariant with
34334        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
34335        // detour that allocated a fresh `String`
34336        // (`self.endpoint.clone().map(...)` in the body would type-check
34337        // but silently drop the borrow, and every downstream consumer
34338        // that assumed the returned slice outlives `&self` would break
34339        // on a stale-reference use-after-free — the [`WitContract::target`]
34340        // Http-arm payload extraction rebinds the returned `Option<&str>`
34341        // through `.ok_or_else(...)` and threads the `&str` payload into
34342        // [`WitTarget::Http { endpoint: &'a str }`], the
34343        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
34344        // [`ContratoIdentity`] dedup key threads the returned
34345        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
34346        // from the WitContract's own storage and each would silently
34347        // misbehave if this accessor produced a detached copy). Peer of
34348        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
34349        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
34350        // shaped optional-scalar axes — first extension of the
34351        // `Option<&str>` borrow-not-copy discipline onto the
34352        // per-`:contratos` HTTP-shaped payload-carrier axis.
34353        let c = WitContract {
34354            de: "cart".into(),
34355            para: "catalog".into(),
34356            wit: "wasi:http/proxy".into(),
34357            endpoint: Some("/lookup".into()),
34358            subject: None,
34359            slot: None,
34360        };
34361        let ep = c.endpoint().expect("Some arm");
34362        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
34363        assert_eq!(
34364            ep.as_ptr(),
34365            storage_slice.as_ptr(),
34366            "WitContract::endpoint must borrow from the .endpoint \
34367             String's backing storage — a fresh allocation here means \
34368             the accessor no longer names the substrate-primitive typed \
34369             dispatch and every downstream consumer would silently \
34370             carry a detached copy",
34371        );
34372        assert_eq!(
34373            ep.len(),
34374            storage_slice.len(),
34375            "WitContract::endpoint and .endpoint.as_deref() must byte-\
34376             equal in length as well as in address",
34377        );
34378    }
34379
34380    #[test]
34381    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
34382        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
34383        // pin: [`WitContract::subject`] must return the `:contratos
34384        // :subject` field byte-for-byte, borrowed from the typed slot's
34385        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
34386        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
34387        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
34388        // optional-scalar axis — same "the substrate-primitive accessor
34389        // must byte-equal the raw field access verbatim across every
34390        // author-declared value" discipline extended to the pub-sub arm.
34391        // Pins against a future silent detour that re-canonicalized the
34392        // subject (an accidental `.to_lowercase()` normalization that
34393        // didn't reach the peer field-access site at the dedup key, a
34394        // per-CR fully-qualified prefix rewrite the operator authors on
34395        // one consumer without the other, or an M4 typed-subject-template
34396        // `Display` re-canonicalization that silently drifted the printer
34397        // output from the source `caixa.lisp`). Four values sweep the
34398        // NATS accept-set every pub-sub author-declared subject lands on
34399        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
34400        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
34401            let c = WitContract {
34402                de: "cart".into(),
34403                para: "notifier".into(),
34404                wit: "nats:pub-sub".into(),
34405                endpoint: None,
34406                subject: Some(subject.into()),
34407                slot: None,
34408            };
34409            assert_eq!(
34410                c.subject(),
34411                Some(subject),
34412                "WitContract::subject must return :contratos :subject \
34413                 verbatim (got {:?}, expected Some({subject:?}))",
34414                c.subject(),
34415            );
34416            assert_eq!(
34417                c.subject(),
34418                c.subject.as_deref(),
34419                "WitContract::subject must byte-equal the .subject \
34420                 field's `.as_deref()` projection",
34421            );
34422        }
34423    }
34424
34425    #[test]
34426    fn wit_contract_subject_none_when_field_is_none() {
34427        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
34428        // shaped payload-carrier accessor pin: when the typed slot is
34429        // absent — the canonical shape under a non-pub-sub `:wit` world
34430        // per the [`WitContract::target`]-enforced shape ↔ target
34431        // partition ([`WitTarget::Http`] carries `:endpoint`,
34432        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
34433        // carries none) — [`WitContract::subject`] must return `None`.
34434        // Pins against a future silent detour that projected the absent
34435        // slot to a `Some("")` empty-string default (the canonical
34436        // `Option<String>` → `String` collapse footgun the sibling M2
34437        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
34438        // emptiness predicates already guard on the peer M2 typed-slot
34439        // surfaces), a `Some("None")` stringified-None round-trip, or a
34440        // `Some` arm whose contents were derived from a sibling slot (an
34441        // accidental fallback to the `:endpoint` / `:slot` payload that
34442        // read the HTTP / store payload into the subject axis). Three
34443        // contracts sweep the accept-set every non-pub-sub `:wit` world
34444        // lands on — HTTP proxy, key/value store, and payload-less
34445        // capability.
34446        for (wit, endpoint, slot) in [
34447            ("wasi:http/proxy", Some("/lookup"), None),
34448            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
34449            ("wasi:cli/environment", None, None),
34450        ] {
34451            let c = WitContract {
34452                de: "cart".into(),
34453                para: "downstream".into(),
34454                wit: wit.into(),
34455                endpoint: endpoint.map(str::to_string),
34456                subject: None,
34457                slot: slot.map(str::to_string),
34458            };
34459            assert!(
34460                c.subject().is_none(),
34461                "WitContract::subject must return None when the typed \
34462                 slot is absent under :wit {wit:?} (got {:?})",
34463                c.subject(),
34464            );
34465            assert_eq!(
34466                c.subject(),
34467                c.subject.as_deref(),
34468                "WitContract::subject must byte-equal the .subject \
34469                 field's `.as_deref()` projection in the absent arm",
34470            );
34471        }
34472    }
34473
34474    #[test]
34475    fn wit_contract_subject_borrows_from_subject_storage() {
34476        // The borrow-not-copy pin: [`WitContract::subject`] must return
34477        // an `Option<&str>` whose `Some` arm borrows from the typed
34478        // slot's own [`String`] storage — same-address invariant with
34479        // `c.subject.as_deref().unwrap()`. Pins against a future silent
34480        // detour that allocated a fresh `String`
34481        // (`self.subject.clone().map(...)` in the body would type-check
34482        // but silently drop the borrow, and every downstream consumer
34483        // that assumed the returned slice outlives `&self` would break
34484        // on a stale-reference use-after-free — the [`WitContract::target`]
34485        // PubSub-arm payload extraction rebinds the returned
34486        // `Option<&str>` through `.ok_or_else(...)` and threads the
34487        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
34488        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
34489        // [`ContratoIdentity`] dedup key threads the returned
34490        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
34491        // from the WitContract's own storage and each would silently
34492        // misbehave if this accessor produced a detached copy). Peer of
34493        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
34494        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
34495        // shaped optional-scalar axis — second extension of the
34496        // `Option<&str>` borrow-not-copy discipline onto the
34497        // per-`:contratos` payload-carrier family, this time on the
34498        // pub-sub arm.
34499        let c = WitContract {
34500            de: "cart".into(),
34501            para: "notifier".into(),
34502            wit: "nats:pub-sub".into(),
34503            endpoint: None,
34504            subject: Some("orders.paid".into()),
34505            slot: None,
34506        };
34507        let sub = c.subject().expect("Some arm");
34508        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
34509        assert_eq!(
34510            sub.as_ptr(),
34511            storage_slice.as_ptr(),
34512            "WitContract::subject must borrow from the .subject \
34513             String's backing storage — a fresh allocation here means \
34514             the accessor no longer names the substrate-primitive typed \
34515             dispatch and every downstream consumer would silently \
34516             carry a detached copy",
34517        );
34518        assert_eq!(
34519            sub.len(),
34520            storage_slice.len(),
34521            "WitContract::subject and .subject.as_deref() must byte-\
34522             equal in length as well as in address",
34523        );
34524    }
34525
34526    #[test]
34527    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
34528        // The canonical per-`:contratos` key/value-store-shaped
34529        // `:slot`-scalar pin: [`WitContract::slot`] must return the
34530        // `:contratos :slot` field byte-for-byte, borrowed from the
34531        // typed slot's own `Option<String>` storage. Peer of the
34532        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
34533        // [`WitContract::subject`] (90de675) accessor pins on the M3
34534        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
34535        // optional-scalar axis — same "the substrate-primitive
34536        // accessor must byte-equal the raw field access verbatim
34537        // across every author-declared value" discipline extended to
34538        // the store arm. Pins against a future silent detour that
34539        // re-canonicalized the slot template (an accidental
34540        // `.to_lowercase()` bucket-prefix normalization that didn't
34541        // reach the peer field-access site at the dedup key, a per-CR
34542        // fully-qualified prefix rewrite the operator authors on one
34543        // consumer without the other, or an M4 typed-key-template
34544        // `Display` re-canonicalization that silently drifted the
34545        // printer output from the source `caixa.lisp`). Four values
34546        // sweep the wasi:keyvalue accept-set every store-shaped
34547        // author-declared slot lands on (flat bucket, single-param
34548        // template, multi-param template, nested-hierarchy template).
34549        for slot in [
34550            "sessions",
34551            "carts/{cart_id}",
34552            "orders/{tenant}/{order_id}",
34553            "cache/tenant-a/orders/{id}",
34554        ] {
34555            let c = WitContract {
34556                de: "cart".into(),
34557                para: "kv".into(),
34558                wit: "wasi:keyvalue/store".into(),
34559                endpoint: None,
34560                subject: None,
34561                slot: Some(slot.into()),
34562            };
34563            assert_eq!(
34564                c.slot(),
34565                Some(slot),
34566                "WitContract::slot must return :contratos :slot \
34567                 verbatim (got {:?}, expected Some({slot:?}))",
34568                c.slot(),
34569            );
34570            assert_eq!(
34571                c.slot(),
34572                c.slot.as_deref(),
34573                "WitContract::slot must byte-equal the .slot field's \
34574                 `.as_deref()` projection",
34575            );
34576        }
34577    }
34578
34579    #[test]
34580    fn wit_contract_slot_none_when_field_is_none() {
34581        // The absent-`:slot` arm of the per-`:contratos` store-shaped
34582        // payload-carrier accessor pin: when the typed slot is absent —
34583        // the canonical shape under a non-store `:wit` world per the
34584        // [`WitContract::target`]-enforced shape ↔ target partition
34585        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
34586        // carries `:subject`, [`WitTarget::Capability`] carries none) —
34587        // [`WitContract::slot`] must return `None`. Pins against a
34588        // future silent detour that projected the absent slot to a
34589        // `Some("")` empty-string default (the canonical
34590        // `Option<String>` → `String` collapse footgun the sibling M2
34591        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
34592        // emptiness predicates already guard on the peer M2 typed-slot
34593        // surfaces), a `Some("None")` stringified-None round-trip, or
34594        // a `Some` arm whose contents were derived from a sibling
34595        // slot (an accidental fallback to the `:endpoint` / `:subject`
34596        // payload that read the HTTP / pub-sub payload into the store
34597        // axis). Three contracts sweep the accept-set every non-store
34598        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
34599        // payload-less capability.
34600        for (wit, endpoint, subject) in [
34601            ("wasi:http/proxy", Some("/lookup"), None),
34602            ("nats:pub-sub", None, Some("orders.paid")),
34603            ("wasi:cli/environment", None, None),
34604        ] {
34605            let c = WitContract {
34606                de: "cart".into(),
34607                para: "downstream".into(),
34608                wit: wit.into(),
34609                endpoint: endpoint.map(str::to_string),
34610                subject: subject.map(str::to_string),
34611                slot: None,
34612            };
34613            assert!(
34614                c.slot().is_none(),
34615                "WitContract::slot must return None when the typed \
34616                 slot is absent under :wit {wit:?} (got {:?})",
34617                c.slot(),
34618            );
34619            assert_eq!(
34620                c.slot(),
34621                c.slot.as_deref(),
34622                "WitContract::slot must byte-equal the .slot field's \
34623                 `.as_deref()` projection in the absent arm",
34624            );
34625        }
34626    }
34627
34628    #[test]
34629    fn wit_contract_slot_borrows_from_slot_storage() {
34630        // The borrow-not-copy pin: [`WitContract::slot`] must return
34631        // an `Option<&str>` whose `Some` arm borrows from the typed
34632        // slot's own [`String`] storage — same-address invariant with
34633        // `c.slot.as_deref().unwrap()`. Pins against a future silent
34634        // detour that allocated a fresh `String`
34635        // (`self.slot.clone().map(...)` in the body would type-check
34636        // but silently drop the borrow, and every downstream consumer
34637        // that assumed the returned slice outlives `&self` would
34638        // break on a stale-reference use-after-free — the
34639        // [`WitContract::target`] Store-arm payload extraction rebinds
34640        // the returned `Option<&str>` through `.ok_or_else(...)` and
34641        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
34642        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
34643        // [`ContratoIdentity`] dedup key threads the returned
34644        // `Option<&str>` into the six-tuple's store arm — each borrow
34645        // from the WitContract's own storage and each would silently
34646        // misbehave if this accessor produced a detached copy). Peer
34647        // of the sibling per-`:contratos` [`WitContract::endpoint`]
34648        // (7020470) / [`WitContract::subject`] (90de675)
34649        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
34650        // shaped optional-scalar axis — third and final extension of
34651        // the `Option<&str>` borrow-not-copy discipline onto the
34652        // per-`:contratos` payload-carrier family, this time on the
34653        // store arm.
34654        let c = WitContract {
34655            de: "cart".into(),
34656            para: "kv".into(),
34657            wit: "wasi:keyvalue/store".into(),
34658            endpoint: None,
34659            subject: None,
34660            slot: Some("carts/{cart_id}".into()),
34661        };
34662        let slot = c.slot().expect("Some arm");
34663        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
34664        assert_eq!(
34665            slot.as_ptr(),
34666            storage_slice.as_ptr(),
34667            "WitContract::slot must borrow from the .slot String's \
34668             backing storage — a fresh allocation here means the \
34669             accessor no longer names the substrate-primitive typed \
34670             dispatch and every downstream consumer would silently \
34671             carry a detached copy",
34672        );
34673        assert_eq!(
34674            slot.len(),
34675            storage_slice.len(),
34676            "WitContract::slot and .slot.as_deref() must byte-equal \
34677             in length as well as in address",
34678        );
34679    }
34680
34681    #[test]
34682    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
34683        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
34684        // [`Membro::nome`] must return the `:membros :caixa` field
34685        // byte-for-byte, borrowed from the typed slot's own [`String`]
34686        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
34687        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
34688        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
34689        // slot-atom scalar-value axes — same "the substrate-primitive
34690        // accessor must byte-equal the raw field access verbatim across
34691        // every author-declared value" discipline extended to the
34692        // per-`:membros` member-identity arm. Pins against a future
34693        // silent detour that re-normalized the member identity (an
34694        // accidental `.to_lowercase()` — every `:membros :caixa` is
34695        // validated as a DNS-1123 label upstream via
34696        // [`validate_membro_caixa`], so any re-normalization is
34697        // redundant + a drift surface between the validator and the
34698        // accessor), a namespace-prefix rewrite (an accidental
34699        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
34700        // rewrite that didn't land on the peer axes), or a per-cluster
34701        // alias stamp the operator authors on one consumer without the
34702        // other. Four values sweep the accept-set the DNS-1123 gate
34703        // upstream admits (short single-word / dashed / v-suffixed
34704        // member names).
34705        for name in ["cart", "checkout", "catalog", "orders-v2"] {
34706            let m = Membro {
34707                caixa: name.into(),
34708                versao: "^0.1".into(),
34709            };
34710            assert_eq!(
34711                m.nome(),
34712                name,
34713                "Membro::nome must return :membros :caixa verbatim \
34714                 (got {:?}, expected {name:?})",
34715                m.nome(),
34716            );
34717            assert_eq!(
34718                m.nome(),
34719                m.caixa.as_str(),
34720                "Membro::nome must byte-equal the .caixa field access",
34721            );
34722        }
34723    }
34724
34725    #[test]
34726    fn membro_nome_borrows_from_caixa_storage() {
34727        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
34728        // slice that borrows from the typed slot's own [`String`]
34729        // storage — same-address invariant with `m.caixa.as_str()`. Pins
34730        // against a future silent detour that allocated a fresh `String`
34731        // (`self.caixa.clone()` in the body would type-check but
34732        // silently drop the borrow, and every downstream consumer that
34733        // assumed the returned slice outlives `&self` would break on a
34734        // stale-reference use-after-free — the `HashSet<&str>` collector
34735        // at [`AplicacaoSpec::validate`]'s `names` seed, the
34736        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
34737        // [`AplicacaoSpec::detect_sync_cycles`], the
34738        // [`crate::render::insert_first_seen`] dedup key at
34739        // [`AplicacaoSpec::validate_membros`] — each borrow from the
34740        // Membro's own storage and each would silently misbehave if
34741        // this accessor produced a detached copy). Peer of the sibling
34742        // per-`:contratos` [`WitContract::source`] /
34743        // [`WitContract::destination`] and per-`:entrada`
34744        // [`Entrada::destination`] borrow-invariant pins on the mesh-
34745        // slot-atom scalar-value axes.
34746        let m = Membro {
34747            caixa: "checkout".into(),
34748            versao: "^0.1".into(),
34749        };
34750        let name = m.nome();
34751        let caixa_slice = m.caixa.as_str();
34752        assert_eq!(
34753            name.as_ptr(),
34754            caixa_slice.as_ptr(),
34755            "Membro::nome must borrow from the .caixa String's backing \
34756             storage — a fresh allocation here means the accessor no \
34757             longer names the substrate-primitive typed dispatch and \
34758             every downstream consumer would silently carry a detached \
34759             copy",
34760        );
34761        assert_eq!(
34762            name.len(),
34763            caixa_slice.len(),
34764            "Membro::nome and .caixa.as_str() must byte-equal in length \
34765             as well as in address",
34766        );
34767    }
34768
34769    #[test]
34770    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
34771        // The canonical per-`:membros` member-`:versao`-scalar pin:
34772        // [`Membro::versao_requirement`] must return the
34773        // `:membros :versao` field byte-for-byte, borrowed from the typed
34774        // slot's own [`String`] storage. Sibling of the peer
34775        // `membro_nome_returns_caixa_byte_equal_across_permutations`
34776        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
34777        // — same "the substrate-primitive accessor must byte-equal the
34778        // raw field access verbatim across every author-declared value"
34779        // discipline extended to the per-`:membros` member-`:versao`
34780        // requirement-string arm. Pins against a future silent detour
34781        // that re-canonicalized the requirement (an accidental
34782        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
34783        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
34784        // drifted the printer output away from the source `caixa.lisp`,
34785        // an accidental whitespace trim on `"^ 0.1"` that no consumer
34786        // ever produced from the field-access side, an accidental
34787        // per-cluster lacre-projected concrete-version rewrite that
34788        // didn't land on the peer field-access sites). Five values sweep
34789        // the accept-set the shared
34790        // [`crate::render::require_valid_versao_requirement`] gate
34791        // admits (caret / tilde / exact / wildcard / bare-major).
34792        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
34793            let m = Membro {
34794                caixa: "cart".into(),
34795                versao: req.into(),
34796            };
34797            assert_eq!(
34798                m.versao_requirement(),
34799                req,
34800                "Membro::versao_requirement must return :membros :versao \
34801                 verbatim (got {:?}, expected {req:?})",
34802                m.versao_requirement(),
34803            );
34804            assert_eq!(
34805                m.versao_requirement(),
34806                m.versao.as_str(),
34807                "Membro::versao_requirement must byte-equal the .versao \
34808                 field access",
34809            );
34810        }
34811    }
34812
34813    #[test]
34814    fn membro_versao_requirement_borrows_from_versao_storage() {
34815        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
34816        // return a `&str` slice that borrows from the typed slot's own
34817        // [`String`] storage — same-address invariant with
34818        // `m.versao.as_str()`. Pins against a future silent detour that
34819        // allocated a fresh `String` (`self.versao.clone()` in the body
34820        // would type-check but silently drop the borrow, and every
34821        // downstream consumer that assumed the returned slice outlives
34822        // `&self` would break on a stale-reference use-after-free). Peer
34823        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
34824        // per-`:contratos` [`WitContract::source`] /
34825        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
34826        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
34827        // the mesh-slot-atom scalar-value axes.
34828        let m = Membro {
34829            caixa: "checkout".into(),
34830            versao: "^0.1".into(),
34831        };
34832        let req = m.versao_requirement();
34833        let versao_slice = m.versao.as_str();
34834        assert_eq!(
34835            req.as_ptr(),
34836            versao_slice.as_ptr(),
34837            "Membro::versao_requirement must borrow from the .versao \
34838             String's backing storage — a fresh allocation here means \
34839             the accessor no longer names the substrate-primitive typed \
34840             dispatch and every downstream consumer would silently carry \
34841             a detached copy",
34842        );
34843        assert_eq!(
34844            req.len(),
34845            versao_slice.len(),
34846            "Membro::versao_requirement and .versao.as_str() must byte-\
34847             equal in length as well as in address",
34848        );
34849    }
34850
34851    #[test]
34852    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
34853        // Sibling-pair invariant pin composing both per-`:membros`
34854        // substrate-primitive typed dispatches — [`Membro::nome`]
34855        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
34856        // `(nome(), versao_requirement())` call shape every renderer
34857        // that fans on per-member identity + version pin keys off. The
34858        // invariant, evaluated per-member:
34859        //
34860        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
34861        //
34862        // Closes the last unlifted per-`:membros` scalar axis — every
34863        // downstream consumer that reads the pair now routes through
34864        // exactly two typed dispatches on the substrate primitive, not
34865        // one typed + one open-coded field access. A future refactor
34866        // that silently split either accessor's projection (an
34867        // accidental `nome()` namespace-prefix rewrite that didn't
34868        // reach the peer, an accidental `versao_requirement()` lacre-
34869        // projected concrete-version rewrite that didn't land on the
34870        // `nome()` peer) surfaces at caixa-core build time. Peer of the
34871        // sibling per-`:entrada` `(hostname(), destination())` and
34872        // per-`:contratos` `(source(), destination())` pair invariants
34873        // on the mesh-slot-atom scalar-value axes.
34874        for (caixa, versao) in [
34875            ("cart", "^0.1"),
34876            ("checkout", "~0.1.2"),
34877            ("catalog", "0.1.0"),
34878            ("orders-v2", "*"),
34879        ] {
34880            let m = Membro {
34881                caixa: caixa.into(),
34882                versao: versao.into(),
34883            };
34884            assert_eq!(
34885                (m.nome(), m.versao_requirement()),
34886                (m.caixa.as_str(), m.versao.as_str()),
34887                "(Membro::nome, Membro::versao_requirement) must project \
34888                 (.caixa, .versao) verbatim across every author-declared \
34889                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
34890                m.nome(),
34891                m.versao_requirement(),
34892            );
34893        }
34894    }
34895
34896    #[test]
34897    fn validate_membros_empty_gate_routes_through_nome_accessor() {
34898        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
34899        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
34900        // not the raw `.caixa` field access. Structurally: setting
34901        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
34902        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
34903        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
34904        // (i.e. the empty string) — so the emptiness predicate the
34905        // refusal arm reaches under is the accessor-projected value,
34906        // not a peer field that would silently drift under a future
34907        // accessor-side rewrite.
34908        //
34909        // Pins against a future silent detour that (a) re-derived the
34910        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
34911        // instead of `self.nome().is_empty()`, silently disagreeing with
34912        // every peer consumer (the `validate_membro_caixa(m.nome())`
34913        // per-slot helper — which now owns the emptiness arm outright —
34914        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
34915        // below, and the emit-side per-`programs[]` entry-`name:` at
34916        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
34917        // per-tenant alias arm the caller was unaware of, silently
34918        // rewriting an author-declared `:caixa "checkout"` to `""` —
34919        // the raw-field-access gate would fail-open while the
34920        // accessor-routed peer consumers would fail-closed, splitting
34921        // the diagnostic from the actual failure surface.
34922        //
34923        // Peer of the sibling
34924        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
34925        // (c0110f1) composition pin — same "the shape-gate predicate
34926        // must route through the substrate-primitive typed dispatch"
34927        // discipline extended onto the per-`:membros` empty-`:caixa`
34928        // refusal-arm axis. Closes the last unlifted `.caixa` production-
34929        // code read site on `Membro` — after this converge every
34930        // caixa-core `.caixa` field access outside the accessor's own
34931        // body is either a test-side field-setter (in-module tests
34932        // constructing invalid-shape inputs) or a doc-comment reference.
34933        let mut s = three_member_spec();
34934        s.membros[1].caixa = String::new();
34935        assert!(
34936            s.membros[1].nome().is_empty(),
34937            "Membro::nome must byte-equal the .caixa field access — an \
34938             accessor-side detour that no longer projects the raw field \
34939             would silently split this drift-detection test from the \
34940             validate() refusal arm",
34941        );
34942        assert_eq!(
34943            s.membros[1].nome(),
34944            s.membros[1].caixa.as_str(),
34945            "Membro::nome and .caixa.as_str() must byte-equal on an \
34946             empty-`:caixa` entry — the emptiness gate keys off the \
34947             accessor by construction",
34948        );
34949        assert_eq!(
34950            s.validate().unwrap_err(),
34951            AplicacaoError::MembroCaixaEmpty,
34952            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
34953             on an entry whose accessor-projected `nome()` is empty",
34954        );
34955    }
34956
34957    #[test]
34958    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
34959        // Convergence pin, paired with the deletion of the redundant
34960        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
34961        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
34962        // after the collapse, the `MembroCaixaEmpty` refusal on every
34963        // empty-`:caixa` per-member input is owned solely by the shared
34964        // [`validate_membro_caixa`] helper — the same per-slot substrate
34965        // primitive routing empty + shape arms uniformly onto
34966        // [`crate::render::require_valid_dns_1123_label`] that every
34967        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
34968        // on `:placement :clusters`, [`validate_entrada_para`] on
34969        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
34970        // :de`/`:para`) already funnels its own empty arm through.
34971        //
34972        // Two arms pin the collapse:
34973        //
34974        //   (1) The per-slot helper called with the empty string returns
34975        //       byte-equal to the previous inline arm's diagnostic — so
34976        //       a future rebrand of [`validate_membro_caixa`] that
34977        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
34978        //       empty input (an inadvertent switch to
34979        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
34980        //       `on_invalid` arm, an accidental re-routing to a shared
34981        //       `MembroError::Empty` under a future error-hierarchy
34982        //       flattening) would silently split the drift from the
34983        //       [`validate_membros`] caller and surface the wrong
34984        //       diagnostic on the author-facing empty-`:caixa` footgun.
34985        //
34986        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
34987        //       anywhere in the `:membros` fan-out still trips
34988        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
34989        //       no outer inline guard needed. Same shape as the
34990        //       whole-spec arm on [`validate_placement_cluster`] /
34991        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
34992        //       one substrate primitive per axis, folding empty + shape.
34993        //
34994        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
34995        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
34996        // MeshPolicy::validate) already extend across the M3 mesh-slot
34997        // family — closes the last per-slot gate on the family carrying
34998        // an inline empty guard duplicating its own helper.
34999        assert_eq!(
35000            validate_membro_caixa(""),
35001            Err(AplicacaoError::MembroCaixaEmpty),
35002            "validate_membro_caixa must own the empty arm outright — a \
35003             regression here would silently split MembroCaixaEmpty from \
35004             validate_membros' end-to-end refusal shape after the outer \
35005             inline `if m.nome().is_empty()` guard collapse",
35006        );
35007        let mut s = three_member_spec();
35008        s.membros[0].caixa = String::new();
35009        assert_eq!(
35010            s.validate().unwrap_err(),
35011            AplicacaoError::MembroCaixaEmpty,
35012            "an empty-`:caixa` :membros head entry must trip \
35013             MembroCaixaEmpty end-to-end via validate() with the outer \
35014             inline guard removed — the per-slot helper alone is now \
35015             load-bearing",
35016        );
35017        let mut s = three_member_spec();
35018        s.membros[2].caixa = String::new();
35019        assert_eq!(
35020            s.validate().unwrap_err(),
35021            AplicacaoError::MembroCaixaEmpty,
35022            "an empty-`:caixa` :membros tail entry must trip \
35023             MembroCaixaEmpty end-to-end via validate() with the outer \
35024             inline guard removed — the per-slot helper alone reaches \
35025             every fan-out position",
35026        );
35027    }
35028
35029    #[test]
35030    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
35031        // The canonical per-`:placement` Akka-cluster-sharding
35032        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
35033        // the `:placement :shard-key` field byte-for-byte, borrowed
35034        // from the typed slot's own `Option<String>` storage. Peer of
35035        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
35036        // per-`:contratos` [`WitContract::source`] /
35037        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
35038        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
35039        // slot-atom scalar-value axes — same "the substrate-primitive
35040        // accessor must byte-equal the raw field access verbatim across
35041        // every author-declared value" discipline extended to the
35042        // per-`:placement` Akka-cluster-sharding key extractor arm.
35043        // Pins against a future silent detour that re-normalized the
35044        // key (an accidental `.to_lowercase()` — every non-empty
35045        // `:shard-key` is validated as a printable-ASCII single-token
35046        // reference upstream via [`validate_placement_shard_key`], so
35047        // any re-normalization is redundant + a drift surface between
35048        // the validator and the accessor), a per-cluster alias rewrite
35049        // the operator authors on one consumer without the other, or an
35050        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
35051        // that didn't land on the peer field-access sites. Four values
35052        // sweep the accept-set the shape gate admits — bare identifier,
35053        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
35054        // the four canonical Akka-style entity-id extractor shapes the
35055        // future M4 cluster-sharding reconciler hashes.
35056        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
35057            let p = Placement {
35058                estrategia: PlacementStrategy::Sharded,
35059                clusters: vec!["rio".into()],
35060                affinity: None,
35061                shard_key: Some(key.into()),
35062            };
35063            assert_eq!(
35064                p.shard_key(),
35065                Some(key),
35066                "Placement::shard_key must return :placement :shard-key \
35067                 verbatim (got {:?}, expected Some({key:?}))",
35068                p.shard_key(),
35069            );
35070            assert_eq!(
35071                p.shard_key(),
35072                p.shard_key.as_deref(),
35073                "Placement::shard_key must byte-equal the .shard_key \
35074                 field's `.as_deref()` projection",
35075            );
35076        }
35077    }
35078
35079    #[test]
35080    fn placement_shard_key_none_when_field_is_none() {
35081        // The absent-`:shard-key` arm of the per-`:placement`
35082        // Akka-cluster-sharding accessor pin: when the typed slot is
35083        // absent — the canonical shape under `:estrategia Replicated` /
35084        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
35085        // enforced `shard_key.is_some() == matches!(estrategia,
35086        // Sharded)` partition — [`Placement::shard_key`] must return
35087        // `None`. Pins against a future silent detour that projected
35088        // the absent slot to a `Some("")` empty-string default (the
35089        // canonical `Option<String>` → `String` collapse footgun the
35090        // sibling M2 [`crate::LimitsSpec::is_empty`] /
35091        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
35092        // already guard on the peer M2 typed-slot surfaces), a
35093        // `Some("None")` stringified-None round-trip, or a `Some` arm
35094        // whose contents were derived from a sibling slot (an
35095        // accidental fallback to `estrategia.as_str()` that read the
35096        // strategy discriminator into the key axis). Two placements
35097        // sweep the accept-set every `validate`-passing non-`Sharded`
35098        // shape lands on — `Replicated` (Erlang/OTP distributed-app
35099        // takeover) and `SingleNode` (single-node hosting).
35100        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
35101            let p = Placement {
35102                estrategia,
35103                clusters: vec!["rio".into()],
35104                affinity: None,
35105                shard_key: None,
35106            };
35107            assert!(
35108                p.shard_key().is_none(),
35109                "Placement::shard_key must return None when the typed \
35110                 slot is absent under :estrategia {estrategia:?} (got {:?})",
35111                p.shard_key(),
35112            );
35113            assert_eq!(
35114                p.shard_key(),
35115                p.shard_key.as_deref(),
35116                "Placement::shard_key must byte-equal the .shard_key \
35117                 field's `.as_deref()` projection in the absent arm",
35118            );
35119        }
35120    }
35121
35122    #[test]
35123    fn placement_shard_key_borrows_from_shard_key_storage() {
35124        // The borrow-not-copy pin: [`Placement::shard_key`] must return
35125        // an `Option<&str>` whose `Some` arm borrows from the typed
35126        // slot's own [`String`] storage — same-address invariant with
35127        // `p.shard_key.as_deref().unwrap()`. Pins against a future
35128        // silent detour that allocated a fresh `String`
35129        // (`self.shard_key.clone().map(...)` in the body would type-
35130        // check but silently drop the borrow, and every downstream
35131        // consumer that assumed the returned slice outlives `&self`
35132        // would break on a stale-reference use-after-free — the
35133        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
35134        // gate's `Some(k)`-bound match arm reads `k: &str` under the
35135        // accessor's return type and would silently misbehave if this
35136        // accessor produced a detached copy). Peer of the sibling
35137        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
35138        // [`WitContract::source`] / [`WitContract::destination`]
35139        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
35140        // (6db982c) borrow-invariant pins on the mesh-slot-atom
35141        // scalar-value axes — first extension of the discipline onto
35142        // an `Option<String>`-shaped optional-scalar axis.
35143        let p = Placement {
35144            estrategia: PlacementStrategy::Sharded,
35145            clusters: vec!["rio".into()],
35146            affinity: None,
35147            shard_key: Some("tenantId".into()),
35148        };
35149        let key = p.shard_key().expect("Some arm");
35150        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
35151        assert_eq!(
35152            key.as_ptr(),
35153            storage_slice.as_ptr(),
35154            "Placement::shard_key must borrow from the .shard_key \
35155             String's backing storage — a fresh allocation here means \
35156             the accessor no longer names the substrate-primitive typed \
35157             dispatch and every downstream consumer would silently \
35158             carry a detached copy",
35159        );
35160        assert_eq!(
35161            key.len(),
35162            storage_slice.len(),
35163            "Placement::shard_key and .shard_key.as_deref() must byte-\
35164             equal in length as well as in address",
35165        );
35166    }
35167
35168    #[test]
35169    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
35170        // The canonical per-`:placement` M3-Adaptive-compression-hint
35171        // scalar pin: [`Placement::affinity`] must return the
35172        // `:placement :affinity` field byte-for-byte, borrowed from the
35173        // typed slot's own `Option<String>` storage. Peer of the sibling
35174        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
35175        // pin on the sibling `Option<&str>` optional-scalar axis — same
35176        // "the substrate-primitive accessor must byte-equal the raw
35177        // field access verbatim across every author-declared value"
35178        // discipline extended to the peer per-`:placement` M3-Adaptive-
35179        // compression-hint arm. Pins against a future silent detour
35180        // that re-normalized the hint (an accidental `.to_lowercase()`
35181        // — every `:affinity` is already validated as a DNS-1123 label
35182        // upstream via [`validate_placement_affinity`], so any re-
35183        // normalization is redundant + a drift surface between the
35184        // validator and the accessor), a per-cluster alias rewrite the
35185        // operator authors on one consumer without the other, or an
35186        // accidental hint-family collapse (`low-latency` → `latency`
35187        // that dropped the qualifier prefix). Four values sweep the
35188        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
35189        // canonical adaptive-compression-weight biases the future M4
35190        // placement engine reads.
35191        for hint in [
35192            "data-locality",
35193            "low-latency",
35194            "high-throughput",
35195            "cost-optimized",
35196        ] {
35197            let p = Placement {
35198                estrategia: PlacementStrategy::Replicated,
35199                clusters: vec!["rio".into()],
35200                affinity: Some(hint.into()),
35201                shard_key: None,
35202            };
35203            assert_eq!(
35204                p.affinity(),
35205                Some(hint),
35206                "Placement::affinity must return :placement :affinity \
35207                 verbatim (got {:?}, expected Some({hint:?}))",
35208                p.affinity(),
35209            );
35210            assert_eq!(
35211                p.affinity(),
35212                p.affinity.as_deref(),
35213                "Placement::affinity must byte-equal the .affinity \
35214                 field's `.as_deref()` projection",
35215            );
35216        }
35217    }
35218
35219    #[test]
35220    fn placement_affinity_none_when_field_is_none() {
35221        // The absent-`:affinity` arm of the per-`:placement`
35222        // M3-Adaptive-compression-hint accessor pin: when the typed
35223        // slot is absent — the canonical shape of an Aplicacao that
35224        // leaves the compression weighting up to the placement engine's
35225        // cluster-default arm — [`Placement::affinity`] must return
35226        // `None`. Pins against a future silent detour that projected
35227        // the absent slot to a `Some("")` empty-string default (the
35228        // canonical `Option<String>` → `String` collapse footgun the
35229        // sibling M2 [`crate::LimitsSpec::is_empty`] /
35230        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
35231        // already guard on the peer M2 typed-slot surfaces), a
35232        // `Some("None")` stringified-None round-trip, a `Some` arm
35233        // whose contents were derived from a sibling slot (an
35234        // accidental fallback to `estrategia.as_str()` that read the
35235        // strategy discriminator into the hint axis), or a
35236        // `Some("default")` implicit-default that would silently biases
35237        // the routing without the author having written one. Three
35238        // placements sweep the accept-set every `validate`-passing
35239        // `:affinity None` shape lands on — one per PlacementStrategy
35240        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
35241        // with a shard-key), since `:affinity` is orthogonal to
35242        // `:estrategia` in the typed grammar.
35243        for (estrategia, shard_key) in [
35244            (PlacementStrategy::SingleNode, None),
35245            (PlacementStrategy::Replicated, None),
35246            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
35247        ] {
35248            let p = Placement {
35249                estrategia,
35250                clusters: vec!["rio".into()],
35251                affinity: None,
35252                shard_key,
35253            };
35254            assert!(
35255                p.affinity().is_none(),
35256                "Placement::affinity must return None when the typed \
35257                 slot is absent under :estrategia {estrategia:?} (got {:?})",
35258                p.affinity(),
35259            );
35260            assert_eq!(
35261                p.affinity(),
35262                p.affinity.as_deref(),
35263                "Placement::affinity must byte-equal the .affinity \
35264                 field's `.as_deref()` projection in the absent arm",
35265            );
35266        }
35267    }
35268
35269    #[test]
35270    fn placement_affinity_borrows_from_affinity_storage() {
35271        // The borrow-not-copy pin: [`Placement::affinity`] must return
35272        // an `Option<&str>` whose `Some` arm borrows from the typed
35273        // slot's own [`String`] storage — same-address invariant with
35274        // `p.affinity.as_deref().unwrap()`. Pins against a future
35275        // silent detour that allocated a fresh `String`
35276        // (`self.affinity.clone().map(...)` in the body would type-
35277        // check but silently drop the borrow, and every downstream
35278        // consumer that assumed the returned slice outlives `&self`
35279        // would break on a stale-reference use-after-free — the
35280        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
35281        // gate reads the accessor's `&str` return through the
35282        // [`validate_placement_affinity`] `&str` parameter and would
35283        // silently misbehave if this accessor produced a detached
35284        // copy). Peer of the sibling per-`:placement`
35285        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
35286        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
35287        // extends the discipline onto the sibling per-`:placement`
35288        // M3-Adaptive-compression-hint arm.
35289        let p = Placement {
35290            estrategia: PlacementStrategy::Replicated,
35291            clusters: vec!["rio".into()],
35292            affinity: Some("data-locality".into()),
35293            shard_key: None,
35294        };
35295        let hint = p.affinity().expect("Some arm");
35296        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
35297        assert_eq!(
35298            hint.as_ptr(),
35299            storage_slice.as_ptr(),
35300            "Placement::affinity must borrow from the .affinity \
35301             String's backing storage — a fresh allocation here means \
35302             the accessor no longer names the substrate-primitive typed \
35303             dispatch and every downstream consumer would silently \
35304             carry a detached copy",
35305        );
35306        assert_eq!(
35307            hint.len(),
35308            storage_slice.len(),
35309            "Placement::affinity and .affinity.as_deref() must byte-\
35310             equal in length as well as in address",
35311        );
35312    }
35313
35314    #[test]
35315    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
35316        // The canonical per-`:placement` distribution-strategy-scalar
35317        // pin: [`Placement::estrategia`] must return the `:placement
35318        // :estrategia` field verbatim as a [`PlacementStrategy`],
35319        // `Copy`-projected from the typed slot's own `PlacementStrategy`
35320        // storage across every variant in the closed accept-set
35321        // (`SingleNode` — Erlang/OTP distributed-app takeover;
35322        // `Replicated` — active-active across every named cluster;
35323        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
35324        // against a future silent detour that re-derived the strategy
35325        // from a peer axis (an accidental fallback to
35326        // `if shard_key.is_some() { Sharded } else { Replicated }`
35327        // collapse that read the shard-key axis into the strategy
35328        // discriminator), a variant remap the operator authors on one
35329        // consumer without the other, or a stale-derive detour that
35330        // substituted [`PlacementStrategy::default`] when the field
35331        // held any explicit variant (which would silently collapse the
35332        // distinction between "author explicitly declared `:estrategia
35333        // Replicated`" and "author omitted the slot and inherited the
35334        // default" the future per-cluster override slot depends on).
35335        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
35336        // pin on the `Copy`-return `u16` scalar axis — same "the
35337        // substrate-primitive accessor must byte-equal the raw field
35338        // access verbatim across every author-declared value" discipline
35339        // extended onto the per-`:placement` distribution-strategy
35340        // `Copy`-composite-enum scalar axis.
35341        for estrategia in [
35342            PlacementStrategy::SingleNode,
35343            PlacementStrategy::Replicated,
35344            PlacementStrategy::Sharded,
35345        ] {
35346            // Route the paired `:shard-key` fixture-builder through the
35347            // typed cross-slot invariant predicate
35348            // [`PlacementStrategy::requires_shard_key`] rather than the
35349            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
35350            // arm-identity predicate — same discipline the sibling
35351            // `placement_strategy_variants_round_trip` fixture builder now
35352            // reads through.
35353            let shard_key = estrategia
35354                .requires_shard_key()
35355                .then(|| "tenantId".to_string());
35356            let p = Placement {
35357                estrategia,
35358                clusters: vec!["rio".into()],
35359                affinity: None,
35360                shard_key,
35361            };
35362            assert_eq!(
35363                p.estrategia(),
35364                estrategia,
35365                "Placement::estrategia must return :placement :estrategia \
35366                 verbatim (got {:?}, expected {estrategia:?})",
35367                p.estrategia(),
35368            );
35369            assert_eq!(
35370                p.estrategia(),
35371                p.estrategia,
35372                "Placement::estrategia accessor and .estrategia field \
35373                 access must byte-equal — the accessor is the substrate-\
35374                 primitive typed dispatch every downstream distribution-\
35375                 strategy consumer must route through",
35376            );
35377        }
35378    }
35379
35380    #[test]
35381    fn validate_placement_reads_through_lifted_estrategia_accessor() {
35382        // Three-consumer coherence pin: the
35383        // [`AplicacaoSpec::validate_placement`]
35384        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
35385        // `estrategia:` field (which reads through
35386        // [`Placement::estrategia`] to name the strategy the empty
35387        // `:clusters` list was declared against), the same method's
35388        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
35389        // reads through [`Placement::estrategia`] to fan across the
35390        // shape-gate cascades), and the non-`Sharded`-arm
35391        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
35392        // `estrategia:` field (which reads through
35393        // [`Placement::estrategia`] to name the strategy the declared-
35394        // but-inert `:shard-key` was authored under) must all key off
35395        // the lifted accessor, so any future rebrand on the typed
35396        // slot's reader shape lands at exactly one place. Pins the
35397        // three-site coherence by exercising each error surface end-
35398        // to-end and asserting the surfaced `estrategia:` field byte-
35399        // equals the accessor's return. Peer of the sibling per-
35400        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
35401        // pin on the M3 mesh-slot `Copy`-return scalar axis.
35402
35403        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
35404        // whose `estrategia:` field must byte-equal the accessor's return
35405        // for every variant in the closed accept-set.
35406        for estrategia in [
35407            PlacementStrategy::SingleNode,
35408            PlacementStrategy::Replicated,
35409            PlacementStrategy::Sharded,
35410        ] {
35411            let mut spec = three_member_spec();
35412            spec.placement.estrategia = estrategia;
35413            spec.placement.clusters = Vec::new();
35414            // Route the paired `:shard-key` spec-mutator through the typed
35415            // cross-slot invariant predicate
35416            // [`PlacementStrategy::requires_shard_key`] rather than the
35417            // [`gen_platform::IsVariant`]-derived
35418            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
35419            // same discipline the sibling
35420            // `placement_strategy_variants_round_trip` and
35421            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
35422            // fixture builders now read through.
35423            spec.placement.shard_key = estrategia
35424                .requires_shard_key()
35425                .then(|| "tenantId".to_string());
35426            let err = spec.validate().unwrap_err();
35427            match err {
35428                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
35429                    assert_eq!(
35430                        e,
35431                        spec.placement.estrategia(),
35432                        "PlacementWithoutClusters.estrategia must byte-equal \
35433                         Placement::estrategia() — the error carrier reads \
35434                         through the lifted accessor",
35435                    );
35436                }
35437                other => panic!(
35438                    "expected PlacementWithoutClusters, got {other:?} for \
35439                     estrategia={estrategia:?}"
35440                ),
35441            }
35442        }
35443
35444        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
35445        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
35446        // must byte-equal the accessor's return for both non-`Sharded`
35447        // strategies.
35448        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
35449            let mut spec = three_member_spec();
35450            spec.placement.estrategia = estrategia;
35451            spec.placement.shard_key = Some("tenantId".into());
35452            let err = spec.validate().unwrap_err();
35453            match err {
35454                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
35455                    assert_eq!(
35456                        e,
35457                        spec.placement.estrategia(),
35458                        "ShardKeyOnNonSharded.estrategia must byte-equal \
35459                         Placement::estrategia() — the non-Sharded-arm \
35460                         refusal reads through the lifted accessor",
35461                    );
35462                }
35463                other => panic!(
35464                    "expected ShardKeyOnNonSharded, got {other:?} for \
35465                     estrategia={estrategia:?}"
35466                ),
35467            }
35468        }
35469    }
35470
35471    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
35472    //
35473    // The [`Placement::clusters`] accessor lift is the second slice-return
35474    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
35475    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
35476    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
35477    // below cover (1) the accessor's byte-equal projection against the raw
35478    // field access across the empty / singleton / cohort fixtures the
35479    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
35480    // and the per-cluster validate loop fan between, and (2) the two-
35481    // consumer coherence of the paired pre-flight refusal probe and the
35482    // per-cluster validate loop routing through the accessor on both arms.
35483
35484    #[test]
35485    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
35486        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
35487        // [`Placement::clusters`] must return the `:placement :clusters`
35488        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
35489        // the same backing buffer the raw `self.clusters.as_slice()`
35490        // field access borrows from, byte-equal across every
35491        // representative fixture in the accept-set — the empty slice
35492        // (the pre-validation sentinel every
35493        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
35494        // the singleton slice (the minimal `SingleNode`-shape cohort),
35495        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
35496        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
35497        //
35498        // Pins against a future silent detour that returned
35499        // `&Vec<String>` (which would type-check but leak the storage-
35500        // side `Vec`'s grow/push/reserve surface no consumer of the
35501        // typed view reaches for), a fresh-allocated `Vec<String>` copy
35502        // (which would type-check via a coercion but silently break
35503        // every downstream caller that relied on the slice sharing the
35504        // backing buffer's identity), or an out-of-order or length-
35505        // drifted projection (which would silently split the paired
35506        // pre-flight `.is_empty()` refusal probe's input from the per-
35507        // cluster validate loop's traversal input).
35508        //
35509        // Peer of the sibling M2
35510        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
35511        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
35512        // `:supervisor` static-child-list axis, extended onto the M3
35513        // per-`:placement` distribution-target-list `Vec`-carry axis.
35514        let fixtures: Vec<Vec<String>> = vec![
35515            Vec::new(),
35516            vec!["rio".into()],
35517            vec!["rio".into(), "mar".into()],
35518            vec!["rio".into(), "mar".into(), "plo".into()],
35519        ];
35520        for clusters in fixtures {
35521            let p = Placement {
35522                clusters: clusters.clone(),
35523                ..Placement::default()
35524            };
35525            assert_eq!(
35526                p.clusters(),
35527                clusters.as_slice(),
35528                "Placement::clusters must return :placement :clusters \
35529                 verbatim (got {:?}, expected {:?})",
35530                p.clusters(),
35531                clusters.as_slice(),
35532            );
35533            assert_eq!(
35534                p.clusters(),
35535                p.clusters.as_slice(),
35536                "Placement::clusters accessor and .clusters.as_slice() \
35537                 field access must byte-equal — the accessor is the \
35538                 substrate-primitive typed dispatch every downstream \
35539                 cluster-pool consumer must route through",
35540            );
35541            assert_eq!(
35542                p.clusters().len(),
35543                p.clusters.len(),
35544                "Placement::clusters().len() must byte-equal \
35545                 self.clusters.len() — a length-drift would silently \
35546                 split the paired pre-flight `.is_empty()` refusal \
35547                 probe input from the per-cluster validate loop's \
35548                 traversal input",
35549            );
35550        }
35551    }
35552
35553    #[test]
35554    fn validate_placement_reads_through_lifted_clusters_accessor() {
35555        // Two-consumer coherence pin: the
35556        // [`AplicacaoSpec::validate_placement`] pre-flight
35557        // `self.placement.clusters().is_empty()` refusal probe (which
35558        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
35559        // the accessor projects the empty slice) and the per-cluster
35560        // validate loop's `for c in self.placement.clusters()`
35561        // traversal (which must reach every entry in the same order
35562        // the accessor projects, so both the per-entry value-shape
35563        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
35564        // and the duplicate-detection HashSet insert that trips
35565        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
35566        // accessor's projection) must both key off the lifted
35567        // accessor, so any future rebrand on the typed slot's reader
35568        // shape lands at exactly one place. Pins the two-site
35569        // coherence by exercising each production consumer end-to-end:
35570        // (1) the `PlacementWithoutClusters` refusal under the empty
35571        // slice, (2) the `PlacementClusterInvalid` refusal fires on
35572        // the second entry of a two-cluster cohort whose head is
35573        // valid but tail is not (which requires the loop to reach the
35574        // second entry through the accessor), and (3) the
35575        // `PlacementClusterDuplicate` refusal fires on the second
35576        // entry of a two-cluster cohort that shares a name (which
35577        // requires the loop to reach both entries — a first-entry-only
35578        // projection would silently pass since the dedup HashSet has
35579        // room for the first insert).
35580        //
35581        // Peer of the sibling M2
35582        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
35583        // (bc92bce) coherence pin on the per-`:supervisor` static-
35584        // child-list axis, extended onto the M3 per-`:placement`
35585        // distribution-target-list `Vec`-carry axis.
35586
35587        // (1) Pre-flight `.is_empty()` probe: the empty slice must
35588        // trip `PlacementWithoutClusters`.
35589        let mut spec = three_member_spec();
35590        spec.placement.clusters = Vec::new();
35591        match spec.validate().unwrap_err() {
35592            AplicacaoError::PlacementWithoutClusters { .. } => {}
35593            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
35594        }
35595        assert!(
35596            spec.placement.clusters().is_empty(),
35597            "the pre-flight refusal input must be the empty slice per \
35598             the accessor's projection",
35599        );
35600
35601        // (2) Per-cluster validate loop: a two-cluster cohort with an
35602        // invalid tail entry must trip `PlacementClusterInvalid` on
35603        // the tail — the loop must reach the second entry through
35604        // the accessor.
35605        let mut spec = three_member_spec();
35606        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
35607        match spec.validate().unwrap_err() {
35608            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
35609                assert_eq!(
35610                    cluster, "BAD_CLUSTER",
35611                    "PlacementClusterInvalid.cluster must carry the \
35612                     tail entry the loop reached through the accessor",
35613                );
35614            }
35615            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
35616        }
35617        assert_eq!(
35618            spec.placement.clusters().len(),
35619            2,
35620            "the per-cluster validate loop's traversal input must be \
35621             a two-element slice per the accessor's projection",
35622        );
35623
35624        // (3) Per-cluster validate loop: a two-cluster cohort that
35625        // shares a name must trip `PlacementClusterDuplicate` on the
35626        // second entry — the loop must reach both entries through the
35627        // accessor for the dedup HashSet's second insert to collide.
35628        let mut spec = three_member_spec();
35629        spec.placement.clusters = vec!["rio".into(), "rio".into()];
35630        match spec.validate().unwrap_err() {
35631            AplicacaoError::PlacementClusterDuplicate { cluster } => {
35632                assert_eq!(
35633                    cluster, "rio",
35634                    "PlacementClusterDuplicate.cluster must carry the \
35635                     shared cluster name verbatim",
35636                );
35637            }
35638            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
35639        }
35640        assert_eq!(
35641            spec.placement.clusters().len(),
35642            2,
35643            "the per-cluster validate loop's traversal input must be \
35644             a two-element slice per the accessor's projection",
35645        );
35646    }
35647
35648    #[test]
35649    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
35650        // The canonical per-`:membros` member-list-slice-shape pin:
35651        // [`AplicacaoSpec::membros`] must return the `:membros` typed
35652        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
35653        // same backing buffer the raw `self.membros.as_slice()` field
35654        // access borrows from, byte-equal across every representative
35655        // fixture in the accept-set — the empty slice (the pre-
35656        // validation sentinel every [`AplicacaoError::NoMembros`]
35657        // refusal keys off), the singleton slice (the minimal one-
35658        // Servico Aplicacao shape), and multi-entry cohorts (the peer
35659        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
35660        // load-bearing identity of the application graph).
35661        //
35662        // Pins against a future silent detour that returned
35663        // `&Vec<Membro>` (which would type-check but leak the storage-
35664        // side `Vec`'s grow/push/reserve surface no consumer of the
35665        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
35666        // (which would type-check via a coercion but silently break
35667        // every downstream caller that relied on the slice sharing the
35668        // backing buffer's identity), or an out-of-order or length-
35669        // drifted projection (which would silently split the paired
35670        // `HashSet<&str>` name-set seed's collect input from the
35671        // pre-flight `.is_empty()` refusal probe's input from the per-
35672        // member validate loop's traversal input from the
35673        // programs.yaml emitter's per-entry fan-out loop's input from
35674        // the `feira app graph` per-member print traversal's input).
35675        //
35676        // Peer of the sibling M2
35677        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
35678        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
35679        // `:supervisor` static-child-list axis and the sibling M3
35680        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
35681        // (a6e18d7) `&[String]` byte-equal pin on the per-
35682        // `:placement` distribution-target-list axis — extends the
35683        // slice-return-accessor byte-equal-projection discipline onto
35684        // the outermost M3 mesh-slot type's per-Aplicacao member-list
35685        // `Vec`-carry axis.
35686        let fixtures: Vec<Vec<Membro>> = vec![
35687            Vec::new(),
35688            vec![membro("catalog", "^0.1")],
35689            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
35690            vec![
35691                membro("catalog", "^0.1"),
35692                membro("cart", "^0.1"),
35693                membro("payment", "^0.2"),
35694            ],
35695        ];
35696        for membros in fixtures {
35697            let s = AplicacaoSpec {
35698                membros: membros.clone(),
35699                contratos: Vec::new(),
35700                politicas: MeshPolicy::default(),
35701                placement: Placement::default(),
35702                entrada: None,
35703            };
35704            assert_eq!(
35705                s.membros(),
35706                membros.as_slice(),
35707                "AplicacaoSpec::membros must return :membros verbatim \
35708                 (got {:?}, expected {:?})",
35709                s.membros(),
35710                membros.as_slice(),
35711            );
35712            assert_eq!(
35713                s.membros(),
35714                s.membros.as_slice(),
35715                "AplicacaoSpec::membros accessor and .membros.as_slice() \
35716                 field access must byte-equal — the accessor is the \
35717                 substrate-primitive typed dispatch every downstream \
35718                 member-list consumer must route through",
35719            );
35720            assert_eq!(
35721                s.membros().len(),
35722                s.membros.len(),
35723                "AplicacaoSpec::membros().len() must byte-equal \
35724                 self.membros.len() — a length-drift would silently \
35725                 split the paired `HashSet<&str>` name-set seed's \
35726                 collect input from the pre-flight `.is_empty()` \
35727                 refusal probe input from the per-member validate \
35728                 loop's traversal input",
35729            );
35730        }
35731    }
35732
35733    #[test]
35734    fn validate_reads_through_lifted_membros_accessor() {
35735        // Three-consumer coherence pin: the
35736        // [`AplicacaoSpec::validate_membros`] pre-flight
35737        // `self.membros().is_empty()` refusal probe (which must trip
35738        // [`AplicacaoError::NoMembros`] when the accessor projects the
35739        // empty slice), the same method's per-member validate loop's
35740        // `for m in self.membros()` traversal (which must reach every
35741        // entry in the same order the accessor projects, so both the
35742        // per-entry empty-`:caixa` gate that trips
35743        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
35744        // detection `insert_first_seen` that trips
35745        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
35746        // projection), and the peer [`AplicacaoSpec::validate`]'s
35747        // `HashSet<&str>` name-set seed's
35748        // `self.membros().iter().map(Membro::nome).collect()` collect
35749        // input (which every `:contratos` `:de` / `:para` membership
35750        // lookup rejects an unknown name against) must all three key
35751        // off the lifted accessor, so any future rebrand on the typed
35752        // slot's reader shape lands at exactly one place. Pins the
35753        // three-site coherence by exercising each production consumer
35754        // end-to-end: (1) the `NoMembros` refusal under the empty
35755        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
35756        // second entry of a two-member cohort whose head is valid but
35757        // tail has an empty `:caixa` (which requires the loop to
35758        // reach the second entry through the accessor), and (3) the
35759        // `MembroDuplicate` refusal fires on the second entry of a
35760        // two-member cohort that shares a `:caixa` name (which
35761        // requires the loop to reach both entries through the
35762        // accessor for the dedup HashSet's second insert to collide).
35763        //
35764        // Peer of the sibling M2
35765        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
35766        // (bc92bce) coherence pin on the per-`:supervisor` static-
35767        // child-list axis and the sibling M3
35768        // `validate_placement_reads_through_lifted_clusters_accessor`
35769        // (a6e18d7) coherence pin on the per-`:placement` distribution-
35770        // target-list axis — extends the slice-return-accessor
35771        // multi-consumer coherence discipline onto the outermost M3
35772        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
35773
35774        // (1) Pre-flight `.is_empty()` probe: the empty slice must
35775        // trip `NoMembros`.
35776        let mut spec = three_member_spec();
35777        spec.membros = Vec::new();
35778        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
35779        assert!(
35780            spec.membros().is_empty(),
35781            "the pre-flight refusal input must be the empty slice per \
35782             the accessor's projection",
35783        );
35784
35785        // (2) Per-member validate loop: a two-member cohort with an
35786        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
35787        // the tail — the loop must reach the second entry through
35788        // the accessor.
35789        let mut spec = three_member_spec();
35790        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
35791        assert_eq!(
35792            spec.validate().unwrap_err(),
35793            AplicacaoError::MembroCaixaEmpty,
35794        );
35795        assert_eq!(
35796            spec.membros().len(),
35797            2,
35798            "the per-member validate loop's traversal input must be \
35799             a two-element slice per the accessor's projection",
35800        );
35801
35802        // (3) Per-member validate loop: a two-member cohort that
35803        // shares a `:caixa` name must trip `MembroDuplicate` on the
35804        // second entry — the loop must reach both entries through the
35805        // accessor for the dedup HashSet's second insert to collide.
35806        let mut spec = three_member_spec();
35807        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
35808        match spec.validate().unwrap_err() {
35809            AplicacaoError::MembroDuplicate { caixa } => {
35810                assert_eq!(
35811                    caixa, "catalog",
35812                    "MembroDuplicate.caixa must carry the shared \
35813                     member name verbatim",
35814                );
35815            }
35816            other => panic!("expected MembroDuplicate, got {other:?}"),
35817        }
35818        assert_eq!(
35819            spec.membros().len(),
35820            2,
35821            "the per-member validate loop's traversal input must be \
35822             a two-element slice per the accessor's projection",
35823        );
35824    }
35825
35826    #[test]
35827    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
35828        // The canonical per-`:contratos` contract-list-slice-shape pin:
35829        // [`AplicacaoSpec::contratos`] must return the `:contratos`
35830        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
35831        // slice-view over the same backing buffer the raw
35832        // `self.contratos.as_slice()` field access borrows from, byte-
35833        // equal across every representative fixture in the accept-set —
35834        // the empty slice (the pre-validation "internal-only mesh" shape
35835        // an Aplicacao whose members exchange no typed edges renders
35836        // through), the singleton slice (the minimal one-edge Aplicacao
35837        // shape), and multi-entry cohorts (the peer multi-edge shapes
35838        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
35839        // of the application graph).
35840        //
35841        // Pins against a future silent detour that returned
35842        // `&Vec<WitContract>` (which would type-check but leak the
35843        // storage-side `Vec`'s grow/push/reserve surface no consumer of
35844        // the typed view reaches for), a fresh-allocated
35845        // `Vec<WitContract>` copy (which would type-check via a coercion
35846        // but silently break every downstream caller that relied on the
35847        // slice sharing the backing buffer's identity), or an out-of-
35848        // order or length-drifted projection (which would silently split
35849        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
35850        // seed's traversal input from the `detect_sync_cycles` per-edge
35851        // adjacency-list seed's traversal input from the
35852        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
35853        // BTreeMap grouping loop's traversal input from the
35854        // `feira app graph` per-contract print traversal's input).
35855        //
35856        // Peer of the immediately-adjacent sibling M3
35857        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
35858        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
35859        // node-list axis, the sibling M3
35860        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
35861        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
35862        // distribution-target-list axis, and the sibling M2
35863        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
35864        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
35865        // `:supervisor` static-child-list axis — extends the slice-
35866        // return-accessor byte-equal-projection discipline onto the
35867        // outermost M3 mesh-slot type's per-Aplicacao contract-list
35868        // `Vec`-carry axis, closing the last unlifted per-
35869        // `AplicacaoSpec` `Vec`-carry axis.
35870        let fixtures: Vec<Vec<WitContract>> = vec![
35871            Vec::new(),
35872            vec![contract_http("cart", "catalog", "/products/:id")],
35873            vec![
35874                contract_http("cart", "catalog", "/products/:id"),
35875                contract_http("cart", "payment", "/charge"),
35876            ],
35877            vec![
35878                contract_http("cart", "catalog", "/products/:id"),
35879                contract_http("cart", "payment", "/charge"),
35880                contract_http("payment", "catalog", "/audit"),
35881            ],
35882        ];
35883        for contratos in fixtures {
35884            let s = AplicacaoSpec {
35885                membros: vec![
35886                    membro("catalog", "^0.1"),
35887                    membro("cart", "^0.1"),
35888                    membro("payment", "^0.2"),
35889                ],
35890                contratos: contratos.clone(),
35891                politicas: MeshPolicy::default(),
35892                placement: Placement::default(),
35893                entrada: None,
35894            };
35895            assert_eq!(
35896                s.contratos(),
35897                contratos.as_slice(),
35898                "AplicacaoSpec::contratos must return :contratos verbatim \
35899                 (got {:?}, expected {:?})",
35900                s.contratos(),
35901                contratos.as_slice(),
35902            );
35903            assert_eq!(
35904                s.contratos(),
35905                s.contratos.as_slice(),
35906                "AplicacaoSpec::contratos accessor and \
35907                 .contratos.as_slice() field access must byte-equal — \
35908                 the accessor is the substrate-primitive typed dispatch \
35909                 every downstream contract-list consumer must route \
35910                 through",
35911            );
35912            assert_eq!(
35913                s.contratos().len(),
35914                s.contratos.len(),
35915                "AplicacaoSpec::contratos().len() must byte-equal \
35916                 self.contratos.len() — a length-drift would silently \
35917                 split the paired per-edge validate-loop's traversal \
35918                 input from the sync-cycle adjacency-list seed's \
35919                 traversal input from the cilium_network_policies \
35920                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
35921                 input from the `feira app graph` per-contract print \
35922                 traversal's input",
35923            );
35924        }
35925    }
35926
35927    #[test]
35928    fn validate_reads_through_lifted_contratos_accessor() {
35929        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
35930        // per-`:contratos` validate-loop's `for c in self.contratos()`
35931        // traversal (which must reach every entry in the same order the
35932        // accessor projects, so both the per-entry
35933        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
35934        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
35935        // dedup `HashSet` insert key off the accessor's projection),
35936        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
35937        // `for c in self.contratos()` adjacency-list seed (which drives
35938        // the sync-subgraph deadlock-detection gate via
35939        // [`AplicacaoError::SyncCycle`]), and the peer
35940        // [`caixa_mesh::cilium_network_policies`]'s
35941        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
35942        // grouping loop (which drives the per-CNP fan-out) must all
35943        // three key off the lifted accessor, so any future rebrand on
35944        // the typed slot's reader shape lands at exactly one place. Pins
35945        // the three-site coherence by exercising the two caixa-core
35946        // production consumers end-to-end: (1) the empty-`:contratos`
35947        // slice must validate without a per-edge diagnostic (the
35948        // per-edge loop is a no-op under the empty projection), (2) the
35949        // `ContratoMemberMissing` refusal fires on the second entry of a
35950        // two-edge cohort whose head references a valid member but tail
35951        // references a phantom name (which requires the loop to reach
35952        // the second entry through the accessor), and (3) the
35953        // `SyncCycle` refusal fires on a self-referential two-edge
35954        // cohort through the sync-cycle detector's peer projection
35955        // (which requires the detector to iterate the accessor's
35956        // projection to add the back-edge to its adjacency list).
35957        //
35958        // Peer of the sibling M3
35959        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
35960        // three-consumer coherence pin on the per-`:membros` node-list
35961        // axis and the sibling M3
35962        // `validate_placement_reads_through_lifted_clusters_accessor`
35963        // (a6e18d7) coherence pin on the per-`:placement` distribution-
35964        // target-list axis — extends the slice-return-accessor multi-
35965        // consumer coherence discipline onto the outermost M3 mesh-slot
35966        // type's per-Aplicacao contract-list `Vec`-carry axis.
35967
35968        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
35969        // and no per-edge diagnostic surfaces. Validate succeeds on
35970        // the well-formed `:membros` head.
35971        let mut spec = three_member_spec();
35972        spec.contratos = Vec::new();
35973        assert!(
35974            spec.validate().is_ok(),
35975            "empty :contratos must validate — the per-edge loop is a \
35976             no-op under the accessor's empty projection",
35977        );
35978        assert!(
35979            spec.contratos().is_empty(),
35980            "the per-edge validate loop's traversal input must be the \
35981             empty slice per the accessor's projection",
35982        );
35983
35984        // (2) Per-edge validate loop: a two-edge cohort whose tail
35985        // references a phantom `:para` member must trip
35986        // `ContratoMemberMissing` on the tail — the loop must reach
35987        // the second entry through the accessor for the membership
35988        // lookup to fail on the phantom name.
35989        let mut spec = three_member_spec();
35990        spec.contratos = vec![
35991            contract_http("cart", "catalog", "/products/:id"),
35992            contract_http("cart", "phantom", "/x"),
35993        ];
35994        let err = spec.validate().unwrap_err();
35995        assert!(
35996            matches!(
35997                err,
35998                AplicacaoError::ContratoMemberMissing { ref caixa }
35999                    if caixa == "phantom"
36000            ),
36001            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
36002        );
36003        assert_eq!(
36004            spec.contratos().len(),
36005            2,
36006            "the per-edge validate loop's traversal input must be \
36007             a two-element slice per the accessor's projection",
36008        );
36009
36010        // (3) Sync-cycle detector: a two-edge synchronous cohort
36011        // whose second edge closes the sync-subgraph back onto the
36012        // first must trip [`AplicacaoError::ContratoCycle`] — the
36013        // detector must iterate the accessor's projection to add
36014        // both edges to its adjacency list, so a length-drift on
36015        // the accessor's projection would silently disagree with
36016        // the sync-cycle detector on which edge closes the loop.
36017        // Peer projection to the `validate` per-edge loop above:
36018        // the sync-cycle detector routes through the same lifted
36019        // accessor, so a rebrand of the reader shape lands at one
36020        // place. Uses a two-edge cohort (cart → catalog → cart)
36021        // because the per-edge `ContratoSelfLoop` gate fires before
36022        // the sync-cycle detector on a single self-referential edge
36023        // (`cart → cart`) — the cycle-detector's input must be a
36024        // multi-edge cohort for its per-edge traversal input to be
36025        // observably wider than the per-edge validate loop's input.
36026        let mut spec = three_member_spec();
36027        spec.contratos = vec![
36028            contract_http("cart", "catalog", "/products/:id"),
36029            contract_http("catalog", "cart", "/callback"),
36030        ];
36031        let err = spec.validate().unwrap_err();
36032        assert!(
36033            matches!(err, AplicacaoError::ContratoCycle { .. }),
36034            "expected ContratoCycle from the sync-cycle detector on a \
36035             two-edge back-edge cohort, got {err:?}",
36036        );
36037        assert_eq!(
36038            spec.contratos().len(),
36039            2,
36040            "the sync-cycle detector's traversal input must be a \
36041             two-element slice per the accessor's projection",
36042        );
36043    }
36044
36045    #[test]
36046    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
36047        // The canonical per-`:politicas` outer-composite-reference-shape
36048        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
36049        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
36050        // the same backing storage the raw `&self.politicas` field
36051        // access borrows from, byte-equal across every representative
36052        // fixture in the accept-set — the default `MeshPolicy` (the
36053        // author-empty "no policy on any axis" shape whose
36054        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
36055        // shapes carrying one axis at a time
36056        // (`{mtls_required, timeout, retries, circuit_breaker,
36057        // rate_limit}` — the minimal five-axis fan-out over the
36058        // per-axis lifted accessor family every downstream mesh-artifact
36059        // emitter dispatches on), and the multi-axis composite (the
36060        // canonical `three_member_spec` fixture's `{timeout, retries,
36061        // mtls_required}` triple — the load-bearing shape every
36062        // Aplicacao-scoped fixture in this suite constructs).
36063        //
36064        // Pins against a future silent detour that returned a fresh-
36065        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
36066        // impl but silently break every downstream caller that relied
36067        // on the reference sharing the composite's backing identity), a
36068        // reference to an operator-resolved overlay (the future
36069        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
36070        // acknowledges — its resolution must land at exactly this
36071        // accessor body, not silently divert the raw slot away from a
36072        // second consumer), or an axis-shuffled projection (a future
36073        // detour that swapped `timeout` and `retries` through the
36074        // accessor would silently split the paired `validate_politicas`
36075        // per-axis bracket-dispatch's traversal input from the peer
36076        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
36077        // emitter's fan-out input from the peer
36078        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
36079        // overlay emitter's fan-out input).
36080        //
36081        // Peer of the sibling M3
36082        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
36083        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
36084        // node-list `Vec`-carry axis and the sibling M3
36085        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
36086        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
36087        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
36088        // accessor byte-equal-projection discipline onto the outermost
36089        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
36090        // reference axis, the first `&Composite`-return accessor on the
36091        // outer [`AplicacaoSpec`] type.
36092        let fixtures: Vec<MeshPolicy> = vec![
36093            MeshPolicy::default(),
36094            MeshPolicy {
36095                mtls_required: Some(true),
36096                ..MeshPolicy::default()
36097            },
36098            MeshPolicy {
36099                mtls_required: Some(false),
36100                ..MeshPolicy::default()
36101            },
36102            MeshPolicy {
36103                timeout: Some(Duration::from_secs(30)),
36104                ..MeshPolicy::default()
36105            },
36106            MeshPolicy {
36107                retries: Some(3),
36108                ..MeshPolicy::default()
36109            },
36110            MeshPolicy {
36111                circuit_breaker: Some(CircuitBreaker {
36112                    max_failures: 5,
36113                    window: Duration::from_secs(30),
36114                }),
36115                ..MeshPolicy::default()
36116            },
36117            MeshPolicy {
36118                rate_limit: Some(RateLimit {
36119                    rate: 100,
36120                    window: Duration::from_secs(1),
36121                }),
36122                ..MeshPolicy::default()
36123            },
36124            MeshPolicy {
36125                timeout: Some(Duration::from_secs(30)),
36126                retries: Some(3),
36127                mtls_required: Some(true),
36128                ..MeshPolicy::default()
36129            },
36130        ];
36131        for politicas in fixtures {
36132            let s = AplicacaoSpec {
36133                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
36134                contratos: Vec::new(),
36135                politicas: politicas.clone(),
36136                placement: Placement::default(),
36137                entrada: None,
36138            };
36139            assert_eq!(
36140                *s.politicas(),
36141                politicas,
36142                "AplicacaoSpec::politicas must return :politicas verbatim \
36143                 (got {:?}, expected {:?})",
36144                s.politicas(),
36145                politicas,
36146            );
36147            assert!(
36148                std::ptr::eq(s.politicas(), &s.politicas),
36149                "AplicacaoSpec::politicas accessor and &self.politicas \
36150                 field access must borrow the same backing storage — \
36151                 the accessor is the substrate-primitive typed dispatch \
36152                 every downstream mesh-policy composite consumer must \
36153                 route through, and a reference-identity split would \
36154                 silently break every consumer that relied on the \
36155                 borrow sharing the composite's storage",
36156            );
36157            assert_eq!(
36158                s.politicas().is_empty(),
36159                s.politicas.is_empty(),
36160                "AplicacaoSpec::politicas().is_empty() must byte-equal \
36161                 self.politicas.is_empty() — an emptiness-drift would \
36162                 silently split the paired `validate_politicas` \
36163                 per-axis bracket-dispatch's seed from the peer \
36164                 caixa-mesh CNP mTLS-overlay emitter's key from the \
36165                 peer caixa-mesh HTTPRoute timeout+retry overlay \
36166                 emitter's key",
36167            );
36168        }
36169    }
36170
36171    #[test]
36172    fn validate_politicas_reads_through_lifted_politicas_accessor() {
36173        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
36174        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
36175        // followed by the per-axis fan-out `p.timeout()` /
36176        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
36177        // the lifted axis-level accessor family) must key off the
36178        // lifted outer accessor, so any future rebrand on the typed
36179        // slot's outer-composite reader shape lands at exactly one
36180        // place. Pins the multi-axis coherence by exercising each
36181        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
36182        // a `Some(Duration::ZERO)` timeout under the outer accessor's
36183        // reference projection, (2) `PolicyRetriesZero` fires on a
36184        // `Some(0)` retries under the same projection, and (3) an
36185        // empty [`MeshPolicy::default`] passes `validate_politicas` —
36186        // the outer accessor's reference-projection reaches every
36187        // per-axis branch without silently short-circuiting any.
36188        //
36189        // Peer of the sibling M3
36190        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
36191        // three-consumer coherence pin on the per-`:membros` node-list
36192        // axis and the sibling M3
36193        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
36194        // three-consumer coherence pin on the per-`:contratos`
36195        // edge-list axis — extends the multi-consumer coherence
36196        // discipline onto the outermost M3 mesh-slot type's per-
36197        // Aplicacao mesh-policy composite-reference axis, the first
36198        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
36199        // type.
36200
36201        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
36202        // reference projection: a `Some(Duration::ZERO)` timeout must
36203        // trip the zero-floor gate. The bracket-dispatch's first arm
36204        // reads `p.timeout()` on the reference returned by the outer
36205        // accessor.
36206        let mut spec = three_member_spec();
36207        spec.politicas.timeout = Some(Duration::ZERO);
36208        spec.politicas.retries = None;
36209        spec.politicas.circuit_breaker = None;
36210        spec.politicas.rate_limit = None;
36211        assert_eq!(
36212            spec.validate().unwrap_err(),
36213            AplicacaoError::PolicyTimeoutZero,
36214        );
36215        assert!(
36216            std::ptr::eq(spec.politicas(), &spec.politicas),
36217            "the `validate_politicas` per-axis bracket-dispatch's \
36218             traversal input must be the same backing composite the \
36219             accessor's reference projection borrows from",
36220        );
36221
36222        // (2) `PolicyRetriesZero` refusal under the outer accessor's
36223        // reference projection: a `Some(0)` retries must trip the
36224        // zero-floor gate. The bracket-dispatch's second arm reads
36225        // `p.retries()` on the reference returned by the outer accessor.
36226        let mut spec = three_member_spec();
36227        spec.politicas.timeout = None;
36228        spec.politicas.retries = Some(0);
36229        spec.politicas.circuit_breaker = None;
36230        spec.politicas.rate_limit = None;
36231        assert_eq!(
36232            spec.validate().unwrap_err(),
36233            AplicacaoError::PolicyRetriesZero,
36234        );
36235
36236        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
36237        // — every per-axis arm short-circuits on `None`, so the outer
36238        // accessor's reference projection reaches the fall-through
36239        // `Ok(())` without any per-axis refusal firing.
36240        let mut spec = three_member_spec();
36241        spec.politicas = MeshPolicy::default();
36242        assert!(
36243            spec.validate().is_ok(),
36244            "an empty `MeshPolicy` must pass `validate_politicas` — \
36245             every per-axis arm short-circuits on `None` under the \
36246             outer accessor's reference projection",
36247        );
36248        assert!(
36249            spec.politicas().is_empty(),
36250            "the outer accessor's reference projection must be the \
36251             empty composite per the `MeshPolicy::default()` fixture",
36252        );
36253    }
36254
36255    #[test]
36256    #[allow(clippy::too_many_lines)]
36257    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
36258        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
36259        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
36260        // must both key off the lifted axis-level accessors
36261        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
36262        // the peer `:circuit-breaker` / `:rate-limit` arms already
36263        // routing through [`MeshPolicy::circuit_breaker`] /
36264        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
36265        // per axis on the substrate primitive" shape at the fan-out
36266        // (four axes, four accessors, no raw-field-access site
36267        // anywhere on the bracket-dispatch). Pins the per-axis
36268        // coherence at the accept-set boundaries the bracket carves:
36269        //   1. accessor byte-equal to raw field on every representative
36270        //      accept-set value (`None`, sub-cap, at-cap, past-cap
36271        //      sentinel) — a future accessor drift that no longer
36272        //      shipped the raw slot verbatim would surface here,
36273        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
36274        //      routed through the accessor's projection, proving the
36275        //      first arm reads through the accessor rather than a
36276        //      silent-detour peer-axis field access,
36277        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
36278        //      through the accessor's projection, proving the second
36279        //      arm reads through the accessor,
36280        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
36281        //      passes validate under the accessor projection (paired
36282        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
36283        //      sibling axis), pinning the upper-boundary accept-arm
36284        //      also routes through the accessor.
36285        //
36286        // Peer of the sibling M3
36287        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
36288        // outer-composite-reference coherence pin (which asserts the
36289        // `let p = self.politicas()` seed); extends the discipline onto
36290        // the per-axis fan-out layer that consumes the seed's
36291        // reference. Same shape as
36292        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
36293        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
36294        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
36295        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
36296
36297        // (1) Accessor byte-equal to raw field on the `:timeout` axis
36298        // across the accept-set boundaries the bracket dispatch's
36299        // three-arm gate carves out
36300        // ([`crate::render::require_positive_canonical_bounded_duration`]
36301        // — zero-floor + canonical-form + upper-cap).
36302        for timeout in [
36303            None,
36304            Some(Duration::ZERO),
36305            Some(Duration::from_millis(1)),
36306            Some(POLICY_TIMEOUT_MAX),
36307        ] {
36308            let p = MeshPolicy {
36309                timeout,
36310                ..MeshPolicy::default()
36311            };
36312            assert_eq!(
36313                p.timeout(),
36314                p.timeout,
36315                "MeshPolicy::timeout accessor must byte-equal the raw \
36316                 .timeout field across every accept-set boundary the \
36317                 validate_politicas :timeout arm carves out — a drift \
36318                 here would silently split the validate bracket's arm \
36319                 from the peer caixa-mesh HTTPRoute timeout-overlay \
36320                 emitter's read",
36321            );
36322        }
36323
36324        // (2) Accessor byte-equal to raw field on the `:retries` axis
36325        // across the accept-set boundaries the bracket dispatch's
36326        // two-arm gate carves out
36327        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
36328        // + upper-cap).
36329        for retries in [
36330            None,
36331            Some(0u32),
36332            Some(1u32),
36333            Some(POLICY_RETRIES_MAX),
36334            Some(POLICY_RETRIES_MAX + 1),
36335            Some(u32::MAX),
36336        ] {
36337            let p = MeshPolicy {
36338                retries,
36339                ..MeshPolicy::default()
36340            };
36341            assert_eq!(
36342                p.retries(),
36343                p.retries,
36344                "MeshPolicy::retries accessor must byte-equal the raw \
36345                 .retries field across every accept-set boundary the \
36346                 validate_politicas :retries arm carves out — a drift \
36347                 here would silently split the validate bracket's arm \
36348                 from the peer caixa-mesh HTTPRoute retry-overlay \
36349                 emitter's read",
36350            );
36351        }
36352
36353        // (3) `PolicyTimeoutZero` fires on the accessor-projected
36354        // zero-floor boundary. A silent detour that no longer read
36355        // through `p.timeout()` (a peer-axis field read, an accidental
36356        // Option::and-then chain that collapsed the None arm to Some,
36357        // an accessor rebrand that clamped the return through the
36358        // upper cap) would fail to refuse here.
36359        let mut spec = three_member_spec();
36360        spec.politicas.timeout = Some(Duration::ZERO);
36361        spec.politicas.retries = None;
36362        spec.politicas.circuit_breaker = None;
36363        spec.politicas.rate_limit = None;
36364        assert_eq!(
36365            spec.politicas().timeout(),
36366            Some(Duration::ZERO),
36367            "the accessor projection must reflect the fixture's \
36368             `Some(Duration::ZERO)` :timeout verbatim",
36369        );
36370        assert_eq!(
36371            spec.validate().unwrap_err(),
36372            AplicacaoError::PolicyTimeoutZero,
36373            "the validate_politicas :timeout zero-floor arm must fire \
36374             through the lifted accessor's projection — a silent \
36375             detour to a peer-axis field would fail to refuse",
36376        );
36377
36378        // (4) `PolicyRetriesZero` fires on the accessor-projected
36379        // zero-floor boundary on the sibling `:retries` axis.
36380        let mut spec = three_member_spec();
36381        spec.politicas.timeout = None;
36382        spec.politicas.retries = Some(0);
36383        spec.politicas.circuit_breaker = None;
36384        spec.politicas.rate_limit = None;
36385        assert_eq!(
36386            spec.politicas().retries(),
36387            Some(0),
36388            "the accessor projection must reflect the fixture's \
36389             `Some(0)` :retries verbatim",
36390        );
36391        assert_eq!(
36392            spec.validate().unwrap_err(),
36393            AplicacaoError::PolicyRetriesZero,
36394            "the validate_politicas :retries zero-floor arm must fire \
36395             through the lifted accessor's projection — a silent \
36396             detour to a peer-axis field would fail to refuse",
36397        );
36398
36399        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
36400        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
36401        // must pass validate under the accessor projection — pins the
36402        // upper-boundary accept-arm also routes through the lifted
36403        // accessor (a drift that clamped or short-circuited at the
36404        // upper boundary would fail the whole-spec validate here).
36405        let mut spec = three_member_spec();
36406        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
36407        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
36408        spec.politicas.circuit_breaker = None;
36409        spec.politicas.rate_limit = None;
36410        assert_eq!(
36411            spec.politicas().timeout(),
36412            Some(POLICY_TIMEOUT_MAX),
36413            "the accessor projection must reflect the fixture's \
36414             at-cap :timeout verbatim",
36415        );
36416        assert_eq!(
36417            spec.politicas().retries(),
36418            Some(POLICY_RETRIES_MAX),
36419            "the accessor projection must reflect the fixture's \
36420             at-cap :retries verbatim",
36421        );
36422        assert!(
36423            spec.validate().is_ok(),
36424            "at-cap :timeout + :retries must pass validate under the \
36425             accessor projection — the upper-boundary accept-arm on \
36426             both axes routes through the lifted accessor",
36427        );
36428    }
36429
36430    #[test]
36431    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
36432        // The canonical per-`:placement` outer-composite-reference-shape
36433        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
36434        // typed `Placement` verbatim as a `&Placement` reference over the
36435        // same backing storage the raw `&self.placement` field access
36436        // borrows from, byte-equal across every representative fixture in
36437        // the accept-set — the default `Placement` (the substrate seed
36438        // shape whose [`PlacementStrategy::default`] evaluates to
36439        // `SingleNode` with an empty `:clusters` pool and both
36440        // optional-scalar axes `None`), and every canonical strategy /
36441        // cluster-pool / optional-scalar combination the
36442        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
36443        // three [`PlacementStrategy`] variants — `SingleNode`,
36444        // `Replicated`, `Sharded` — cross-projected with a non-empty
36445        // `:clusters` pool and, on the `Sharded` arm, a non-empty
36446        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
36447        // canonical `three_member_spec` `Replicated` fixture's
36448        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
36449        //
36450        // Pins against a future silent detour that returned a fresh-
36451        // cloned `Placement` copy (which would type-check via a `Clone`
36452        // impl but silently break every downstream caller that relied on
36453        // the reference sharing the composite's backing identity), a
36454        // reference to an operator-resolved overlay (the future per-
36455        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
36456        // acknowledges — its resolution must land at exactly this
36457        // accessor body, not silently divert the raw slot away from a
36458        // second consumer), or an axis-shuffled projection (a future
36459        // detour that swapped `clusters` and `affinity` through the
36460        // accessor would silently split the paired `validate_placement`
36461        // per-axis bracket-dispatch's traversal input from the peer
36462        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
36463        // programs.yaml distribution-annotation emitter's fan-out input
36464        // from the peer `feira app graph` per-Aplicacao print line's
36465        // input).
36466        //
36467        // Peer of the sibling M3
36468        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
36469        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
36470        // outer mesh-policy composite-reference axis, and of the sibling
36471        // slice-return `aplicacao_spec_membros_returns_membros_slice_
36472        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
36473        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
36474        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
36475        // the outer-accessor byte-equal-projection discipline onto the
36476        // outermost M3 mesh-slot type's per-Aplicacao distribution
36477        // composite-reference axis, the second `&Composite`-return
36478        // accessor on the outer [`AplicacaoSpec`] type.
36479        let fixtures: Vec<Placement> = vec![
36480            Placement::default(),
36481            Placement {
36482                estrategia: PlacementStrategy::SingleNode,
36483                clusters: vec!["rio".into()],
36484                affinity: None,
36485                shard_key: None,
36486            },
36487            Placement {
36488                estrategia: PlacementStrategy::Replicated,
36489                clusters: vec!["rio".into(), "mar".into()],
36490                affinity: None,
36491                shard_key: None,
36492            },
36493            Placement {
36494                estrategia: PlacementStrategy::Replicated,
36495                clusters: vec!["rio".into(), "mar".into()],
36496                affinity: Some("data-locality".into()),
36497                shard_key: None,
36498            },
36499            Placement {
36500                estrategia: PlacementStrategy::Sharded,
36501                clusters: vec!["rio".into(), "mar".into()],
36502                affinity: None,
36503                shard_key: Some("tenantId".into()),
36504            },
36505            Placement {
36506                estrategia: PlacementStrategy::Sharded,
36507                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
36508                affinity: Some("low-latency".into()),
36509                shard_key: Some("metadata.tenantId".into()),
36510            },
36511        ];
36512        for placement in fixtures {
36513            let s = AplicacaoSpec {
36514                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
36515                contratos: Vec::new(),
36516                politicas: MeshPolicy::default(),
36517                placement: placement.clone(),
36518                entrada: None,
36519            };
36520            assert_eq!(
36521                *s.placement(),
36522                placement,
36523                "AplicacaoSpec::placement must return :placement verbatim \
36524                 (got {:?}, expected {:?})",
36525                s.placement(),
36526                placement,
36527            );
36528            assert!(
36529                std::ptr::eq(s.placement(), &s.placement),
36530                "AplicacaoSpec::placement accessor and &self.placement \
36531                 field access must borrow the same backing storage — the \
36532                 accessor is the substrate-primitive typed dispatch every \
36533                 downstream distribution-composite consumer must route \
36534                 through, and a reference-identity split would silently \
36535                 break every consumer that relied on the borrow sharing \
36536                 the composite's storage",
36537            );
36538            assert_eq!(
36539                s.placement().estrategia(),
36540                s.placement.estrategia,
36541                "AplicacaoSpec::placement().estrategia() must byte-equal \
36542                 self.placement.estrategia — a strategy-drift would \
36543                 silently split the paired `validate_placement` \
36544                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
36545                 peer caixa-mesh programs.yaml `placement.estrategia` \
36546                 emitter's key from the peer `feira app graph` printer's \
36547                 strategy label",
36548            );
36549            assert_eq!(
36550                s.placement().clusters(),
36551                s.placement.clusters.as_slice(),
36552                "AplicacaoSpec::placement().clusters() must byte-equal \
36553                 self.placement.clusters — a cluster-pool drift would \
36554                 silently split the paired `validate_placement` \
36555                 pre-flight `.is_empty()` refusal probe's traversal from \
36556                 the peer caixa-mesh programs.yaml `placement.clusters` \
36557                 emitter's fan-out from the peer `feira app graph` \
36558                 printer's cluster list",
36559            );
36560        }
36561    }
36562
36563    #[test]
36564    fn validate_placement_reads_through_lifted_placement_accessor() {
36565        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
36566        // per-axis bracket-dispatch seed (`let p = self.placement();`,
36567        // followed by the per-axis fan-out `p.clusters()` /
36568        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
36569        // lifted axis-level accessor family) must key off the lifted
36570        // outer accessor, so any future rebrand on the typed slot's
36571        // outer-composite reader shape lands at exactly one place. Pins
36572        // the multi-axis coherence by exercising each per-axis refusal
36573        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
36574        // `:clusters` pool under the outer accessor's reference
36575        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
36576        // strategy with a `None` `:shard-key` under the same projection,
36577        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
36578        // with a `Some` `:shard-key` under the same projection, and
36579        // (4) the canonical `three_member_spec` `Replicated` fixture
36580        // passes `validate_placement` under the outer accessor's
36581        // reference projection — the accessor's reference-projection
36582        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
36583        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
36584        // without silently short-circuiting any.
36585        //
36586        // Peer of the sibling M3
36587        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
36588        // (534dc21) multi-axis coherence pin on the per-`:politicas`
36589        // outer mesh-policy composite-reference axis — extends the
36590        // multi-consumer coherence discipline onto the outermost M3
36591        // mesh-slot type's per-Aplicacao distribution composite-
36592        // reference axis, the second `&Composite`-return accessor on
36593        // the outer [`AplicacaoSpec`] type.
36594
36595        // (1) `PlacementWithoutClusters` refusal under the outer
36596        // accessor's reference projection: an empty `:clusters` pool
36597        // must trip the pre-flight refusal probe. The bracket-dispatch's
36598        // first arm reads `p.clusters()` on the reference returned by
36599        // the outer accessor.
36600        let mut spec = three_member_spec();
36601        spec.placement.clusters = Vec::new();
36602        assert_eq!(
36603            spec.validate().unwrap_err(),
36604            AplicacaoError::PlacementWithoutClusters {
36605                estrategia: PlacementStrategy::Replicated,
36606            },
36607        );
36608        assert!(
36609            std::ptr::eq(spec.placement(), &spec.placement),
36610            "the `validate_placement` per-axis bracket-dispatch's \
36611             traversal input must be the same backing composite the \
36612             accessor's reference projection borrows from",
36613        );
36614
36615        // (2) `ShardedWithoutKey` refusal under the outer accessor's
36616        // reference projection: a `Sharded` strategy with a `None`
36617        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
36618        // The bracket-dispatch's third arm reads `p.estrategia()` for
36619        // the match scrutinee then `p.shard_key()` for the cascade
36620        // scrutinee, both on the reference returned by the outer
36621        // accessor.
36622        let mut spec = three_member_spec();
36623        spec.placement.estrategia = PlacementStrategy::Sharded;
36624        spec.placement.shard_key = None;
36625        assert_eq!(
36626            spec.validate().unwrap_err(),
36627            AplicacaoError::ShardedWithoutKey,
36628        );
36629
36630        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
36631        // reference projection: a non-`Sharded` strategy with a `Some`
36632        // `:shard-key` must trip the declared-but-inert refusal. The
36633        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
36634        // + `p.estrategia()` for the diagnostic on the reference
36635        // returned by the outer accessor.
36636        let mut spec = three_member_spec();
36637        spec.placement.estrategia = PlacementStrategy::Replicated;
36638        spec.placement.shard_key = Some("tenantId".into());
36639        assert_eq!(
36640            spec.validate().unwrap_err(),
36641            AplicacaoError::ShardKeyOnNonSharded {
36642                estrategia: PlacementStrategy::Replicated,
36643                shard_key: "tenantId".into(),
36644            },
36645        );
36646
36647        // (4) Canonical `three_member_spec` `Replicated` fixture passes
36648        // `validate_placement` — every per-axis arm reaches the fall-
36649        // through `Ok(())` without any per-axis refusal firing under the
36650        // outer accessor's reference projection.
36651        let spec = three_member_spec();
36652        assert!(
36653            spec.validate().is_ok(),
36654            "the canonical Replicated placement fixture must pass \
36655             `validate_placement` — every per-axis arm short-circuits on \
36656             valid input under the outer accessor's reference projection",
36657        );
36658        assert_eq!(
36659            spec.placement().estrategia(),
36660            PlacementStrategy::Replicated,
36661            "the outer accessor's reference projection must be the \
36662             canonical Replicated fixture's strategy",
36663        );
36664        assert_eq!(
36665            spec.placement().clusters(),
36666            &["rio", "mar"],
36667            "the outer accessor's reference projection must be the \
36668             canonical Replicated fixture's cluster pool",
36669        );
36670    }
36671
36672    #[test]
36673    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
36674        // The canonical per-`:entrada` outer-composite-optional-
36675        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
36676        // the `:entrada` typed `Option<Entrada>` verbatim as an
36677        // `Option<&Entrada>` reference over the same backing storage
36678        // the raw `self.entrada.as_ref()` field access borrows from,
36679        // byte-equal across every representative fixture in the
36680        // accept-set — the author-omitted `None` shape (the
36681        // "internal-only mesh" partition every downstream external-
36682        // gateway emitter treats as "emit nothing"), the minimal
36683        // singleton `:entrada` composite (host + destination + empty
36684        // paths + default port), the paths-carrying composite (the
36685        // canonical `three_member_spec` fixture's ["/api" "/health"]
36686        // path-list shape every HTTPRoute per-rule fan-out emitter
36687        // reads), and the non-default port composite (the canonical
36688        // custom-port shape the port-fallback resolver reads).
36689        //
36690        // Pins against a future silent detour that returned a fresh-
36691        // cloned `Entrada` copy (which would type-check via a `Clone`
36692        // impl but silently break every downstream caller that
36693        // relied on the reference sharing the composite's backing
36694        // identity), a reference to an operator-resolved overlay
36695        // (the future per-cluster `:entrada-overrides` slot the
36696        // MESH-COMPOSITION §V federation roadmap acknowledges — its
36697        // resolution must land at exactly this accessor body, not
36698        // silently divert the raw slot away from a second consumer),
36699        // a `None` → `Some(Entrada::default)` cluster-default
36700        // projection (which would collapse the load-bearing
36701        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
36702        // the peer `gateway_routes` early-return + `feira app graph`
36703        // internal-only-mesh partition both read), or an axis-
36704        // shuffled projection (a future detour that swapped
36705        // `host` and `para` through the accessor would silently
36706        // split the paired `validate` per-`:entrada` shape-and-
36707        // membership gate's traversal input from the peer
36708        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
36709        // fan-out input from the peer `feira app graph` external-
36710        // gateway summary line).
36711        //
36712        // Peer of the sibling M3
36713        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
36714        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
36715        // `:politicas` outer mesh-policy composite-reference axis
36716        // and of the sibling M3
36717        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
36718        // (9abb8f0) `&Placement` byte-equal pin on the per-
36719        // `:placement` outer distribution-composite composite-
36720        // reference axis — extends the outer-accessor byte-equal-
36721        // projection discipline onto the last unlifted outermost M3
36722        // mesh-slot type's per-Aplicacao external-gateway composite-
36723        // reference axis, the third and final `&Composite`-return
36724        // accessor on the outer [`AplicacaoSpec`] type.
36725        let fixtures: Vec<Option<Entrada>> = vec![
36726            None,
36727            Some(Entrada {
36728                host: "checkout.quero.cloud".into(),
36729                para: "cart".into(),
36730                paths: Vec::new(),
36731                port: DEFAULT_SERVICO_PORT,
36732            }),
36733            Some(Entrada {
36734                host: "checkout.quero.cloud".into(),
36735                para: "cart".into(),
36736                paths: vec!["/api".into(), "/health".into()],
36737                port: DEFAULT_SERVICO_PORT,
36738            }),
36739            Some(Entrada {
36740                host: "checkout.quero.cloud".into(),
36741                para: "cart".into(),
36742                paths: vec!["/api".into()],
36743                port: 9443,
36744            }),
36745        ];
36746        for entrada in fixtures {
36747            let s = AplicacaoSpec {
36748                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
36749                contratos: Vec::new(),
36750                politicas: MeshPolicy::default(),
36751                placement: Placement::default(),
36752                entrada: entrada.clone(),
36753            };
36754            assert_eq!(
36755                s.entrada(),
36756                entrada.as_ref(),
36757                "AplicacaoSpec::entrada must return :entrada verbatim \
36758                 (got {:?}, expected {:?})",
36759                s.entrada(),
36760                entrada.as_ref(),
36761            );
36762            match (s.entrada(), s.entrada.as_ref()) {
36763                (Some(a), Some(b)) => assert!(
36764                    std::ptr::eq(a, b),
36765                    "AplicacaoSpec::entrada accessor and \
36766                     self.entrada.as_ref() field access must borrow \
36767                     the same backing storage — the accessor is the \
36768                     substrate-primitive typed dispatch every \
36769                     downstream external-gateway composite consumer \
36770                     must route through, and a reference-identity \
36771                     split would silently break every consumer that \
36772                     relied on the borrow sharing the composite's \
36773                     storage",
36774                ),
36775                (None, None) => {}
36776                _ => panic!(
36777                    "AplicacaoSpec::entrada presence bit must byte-\
36778                     equal self.entrada.is_some() — a presence-bit \
36779                     drift would silently split the paired `validate` \
36780                     per-`:entrada` shape-and-membership gate's \
36781                     traversal head from the peer \
36782                     caixa-mesh gateway_routes early-return partition \
36783                     from the peer `feira app graph` internal-only-\
36784                     mesh partition",
36785                ),
36786            }
36787            assert_eq!(
36788                s.entrada().is_some(),
36789                s.entrada.is_some(),
36790                "AplicacaoSpec::entrada().is_some() must byte-equal \
36791                 self.entrada.is_some() — a presence-bit drift would \
36792                 silently split every downstream `Option<&Entrada>` \
36793                 consumer's partition on the internal-only-mesh arm",
36794            );
36795        }
36796    }
36797
36798    #[test]
36799    fn validate_reads_through_lifted_entrada_accessor() {
36800        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
36801        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
36802        // self.entrada() { … }`, followed by the per-axis fan-out
36803        // `validate_entrada_para(&e.para)` /
36804        // `EntradaMemberMissing` membership lookup /
36805        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
36806        // per-`e.paths` `validate_entrada_path` traversal) must key
36807        // off the lifted outer accessor, so any future rebrand on
36808        // the typed slot's outer-composite reader shape lands at
36809        // exactly one place. Pins the multi-axis coherence by
36810        // exercising each per-axis refusal end-to-end: (1) the
36811        // author-omitted `None` shape short-circuits past every
36812        // per-`:entrada` refusal (the internal-only mesh partition
36813        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
36814        // fires on a well-shaped but phantom `:para` under the outer
36815        // accessor's reference projection, and (3) the canonical
36816        // `three_member_spec` `:entrada` fixture passes `validate`
36817        // under the outer accessor's reference projection.
36818        //
36819        // Peer of the sibling M3
36820        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
36821        // (534dc21) multi-axis coherence pin on the per-`:politicas`
36822        // outer mesh-policy composite-reference axis and the sibling
36823        // M3
36824        // [`validate_placement_reads_through_lifted_placement_accessor`]
36825        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
36826        // outer distribution-composite composite-reference axis —
36827        // extends the multi-consumer coherence discipline onto the
36828        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
36829        // external-gateway composite-reference axis, the third and
36830        // final `&Composite`-return accessor on the outer
36831        // [`AplicacaoSpec`] type.
36832
36833        // (1) `None` :entrada — the internal-only-mesh partition
36834        // short-circuits past every per-`:entrada` refusal. The outer
36835        // accessor's reference projection reaches the fall-through
36836        // `Ok(())` on the `None` arm without any per-axis refusal
36837        // firing.
36838        let mut spec = three_member_spec();
36839        spec.entrada = None;
36840        assert!(
36841            spec.validate().is_ok(),
36842            "an author-omitted `:entrada` must pass `validate` — the \
36843             internal-only-mesh partition short-circuits past every \
36844             per-`:entrada` refusal under the outer accessor's \
36845             reference projection",
36846        );
36847        assert!(
36848            spec.entrada().is_none(),
36849            "the outer accessor's reference projection must name the \
36850             internal-only-mesh partition per the `None` fixture",
36851        );
36852
36853        // (2) `EntradaMemberMissing` refusal under the outer accessor's
36854        // reference projection: a well-shaped but phantom `:para` must
36855        // trip the membership-lookup refusal. The gate's second arm
36856        // reads `e.para` on the reference returned by the outer
36857        // accessor.
36858        let mut spec = three_member_spec();
36859        if let Some(e) = spec.entrada.as_mut() {
36860            e.para = "phantom".into();
36861        }
36862        assert_eq!(
36863            spec.validate().unwrap_err(),
36864            AplicacaoError::EntradaMemberMissing {
36865                para: "phantom".into(),
36866            },
36867        );
36868        match (spec.entrada(), spec.entrada.as_ref()) {
36869            (Some(a), Some(b)) => assert!(
36870                std::ptr::eq(a, b),
36871                "the `validate` per-`:entrada` gate's traversal head \
36872                 must be the same backing composite the accessor's \
36873                 reference projection borrows from",
36874            ),
36875            _ => panic!("fixture must carry Some(:entrada)"),
36876        }
36877
36878        // (3) Canonical `three_member_spec` `:entrada` fixture passes
36879        // `validate` — every per-axis arm reaches the fall-through
36880        // `Ok(())` without any per-axis refusal firing under the
36881        // outer accessor's reference projection.
36882        let spec = three_member_spec();
36883        assert!(
36884            spec.validate().is_ok(),
36885            "the canonical `:entrada` fixture must pass `validate` — \
36886             every per-axis arm short-circuits on valid input under \
36887             the outer accessor's reference projection",
36888        );
36889        assert!(
36890            spec.entrada().is_some(),
36891            "the outer accessor's reference projection must be the \
36892             canonical `:entrada` fixture's composite",
36893        );
36894    }
36895
36896    #[test]
36897    fn membro_names_matches_inline_membros_projection() {
36898        // Substrate-primitive ≡ inline-projection pin on
36899        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
36900        // must be byte-for-byte the set the pre-lift inline
36901        // `self.membros().iter().map(Membro::nome).collect()` builder
36902        // produced, on every membership shape the three
36903        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
36904        // :para`, `:entrada :para`) resolve against. Pins the
36905        // projection so a future rebrand of the node-identity axis
36906        // lands at the primitive rather than diverging between the
36907        // per-`:contratos` membership arms still inline at `validate`
36908        // and the lifted `validate_entrada` gate.
36909        for membros in [
36910            vec![],
36911            vec![membro("cart", "^0.1")],
36912            vec![
36913                membro("catalog", "^0.1"),
36914                membro("cart", "^0.1"),
36915                membro("payment", "^0.2"),
36916            ],
36917        ] {
36918            let mut spec = three_member_spec();
36919            spec.membros = membros;
36920            let inline: std::collections::HashSet<&str> =
36921                spec.membros().iter().map(Membro::nome).collect();
36922            assert_eq!(
36923                spec.membro_names(),
36924                inline,
36925                "the lifted membership oracle must discriminate the \
36926                 same node set as the pre-lift inline projection",
36927            );
36928        }
36929    }
36930
36931    #[test]
36932    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
36933        // Per-slot-gate ≡ validate equivalence pin on the lifted
36934        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
36935        // must discriminate the same set as [`AplicacaoSpec::validate`]
36936        // on every `:entrada`-covered input, so a future consumer that
36937        // re-validates the one slot (the M4 admission webhook
36938        // re-checking `:entrada` after a gateway-host patch) accepts
36939        // exactly what `feira build` accepts and surfaces the same
36940        // diagnostic on the same input. Covers each of the five gated
36941        // axes plus the two clean-pass shapes (`None` — the
36942        // internal-only-mesh partition — and the canonical fixture).
36943        //
36944        // Peer of the sibling per-slot equivalence pins
36945        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
36946        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
36947        // `:politicas` slot's compound entry gate, extended here onto
36948        // the `:entrada` slot's newly-named per-slot gate.
36949        /// One `:entrada` equivalence case: a label, the per-axis
36950        /// mutation applied to the canonical fixture's composite, and
36951        /// the diagnostic both the per-slot gate and `validate` must
36952        /// surface on it (`None` = clean pass).
36953        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
36954
36955        let cases: &[EntradaCase] = &[
36956            (
36957                ":para shape — empty",
36958                |e| e.para = String::new(),
36959                Some(AplicacaoError::EntradaParaEmpty),
36960            ),
36961            (
36962                ":para membership — well-shaped phantom",
36963                |e| e.para = "phantom".into(),
36964                Some(AplicacaoError::EntradaMemberMissing {
36965                    para: "phantom".into(),
36966                }),
36967            ),
36968            (
36969                ":host emptiness",
36970                |e| e.host = String::new(),
36971                Some(AplicacaoError::EmptyEntradaHost),
36972            ),
36973            (
36974                ":port structural floor",
36975                |e| e.port = 0,
36976                Some(AplicacaoError::EntradaPortZero),
36977            ),
36978            (
36979                ":paths per-entry emptiness",
36980                |e| e.paths = vec![String::new()],
36981                Some(AplicacaoError::EntradaPathEmpty),
36982            ),
36983            (
36984                ":paths leading-slash grammar",
36985                |e| e.paths = vec!["api/cart".into()],
36986                Some(AplicacaoError::EntradaPathNotAbsolute {
36987                    path: "api/cart".into(),
36988                }),
36989            ),
36990            (
36991                ":paths set-not-multiset",
36992                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
36993                Some(AplicacaoError::EntradaPathDuplicate {
36994                    path: "/api/cart".into(),
36995                }),
36996            ),
36997            ("clean pass — canonical fixture", |_| {}, None),
36998        ];
36999        for (label, mutate, expected) in cases {
37000            let mut spec = three_member_spec();
37001            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
37002            assert_eq!(
37003                spec.validate_entrada().err(),
37004                *expected,
37005                "per-slot gate disagreed with the expected diagnostic on {label}",
37006            );
37007            assert_eq!(
37008                spec.validate().err(),
37009                *expected,
37010                "`validate` disagreed with the per-slot gate on {label}",
37011            );
37012        }
37013
37014        // The `None` arm is the internal-only-mesh partition: a clean
37015        // pass through both the per-slot gate and `validate`, not a
37016        // refusal.
37017        let mut spec = three_member_spec();
37018        spec.entrada = None;
37019        assert_eq!(spec.validate_entrada().err(), None);
37020        assert_eq!(spec.validate().err(), None);
37021    }
37022
37023    #[test]
37024    fn validate_entrada_resolves_membership_through_own_oracle() {
37025        // Self-containment pin on the lifted per-slot gate:
37026        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
37027        // against the oracle *it* builds through
37028        // [`AplicacaoSpec::membro_names`], not one threaded down from
37029        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
37030        // longer contains the `:entrada :para` target must trip
37031        // `EntradaMemberMissing` when the per-slot gate is called
37032        // directly — the shape a future single-slot re-validator
37033        // (the M4 admission webhook) reaches the axis through, without
37034        // re-walking `:membros` / `:contratos` / the sync-cycle
37035        // detector first. Same self-contained posture
37036        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
37037        // the M4 per-edge policy resolver.
37038        let mut spec = three_member_spec();
37039        spec.membros.retain(|m| m.nome() != "cart");
37040        assert_eq!(
37041            spec.validate_entrada().unwrap_err(),
37042            AplicacaoError::EntradaMemberMissing {
37043                para: "cart".into(),
37044            },
37045            "the per-slot gate must resolve `:para` against the oracle \
37046             it builds itself, with no membership set threaded in",
37047        );
37048        assert!(
37049            !spec.membro_names().contains("cart"),
37050            "fixture must have dropped the `:entrada :para` target \
37051             from the graph's node set",
37052        );
37053    }
37054
37055    #[test]
37056    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
37057        // Per-slot-gate ≡ validate equivalence pin on the lifted
37058        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
37059        // gate must discriminate the same set as
37060        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
37061        // input, so a future consumer that re-validates the one slot
37062        // (the M4 admission webhook re-checking `:contratos` after a
37063        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
37064        // `:politicas` override MESH-COMPOSITION §III.2 #3
37065        // acknowledges — which resolves an effective per-edge
37066        // [`MeshPolicy`] and must re-check the edge's identity closure
37067        // before it can key a per-edge override off the endpoint
37068        // tuple) accepts exactly what `feira build` accepts and
37069        // surfaces the same diagnostic on the same input. Covers each
37070        // of the six gated axes (`:de`/`:para` per-arm shape,
37071        // per-arm graph-membership, structural self-loop, `:wit`
37072        // emptiness) plus the clean-pass canonical fixture; the
37073        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
37074        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
37075        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
37076        // `target:` carriers depend on library implementation
37077        // details are pinned separately below with a `matches!`
37078        // predicate on the arm identity plus the mirror equivalence
37079        // between the two entry points.
37080        //
37081        // Peer of the sibling per-slot equivalence pins
37082        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
37083        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
37084        // `:politicas` slot's compound entry gate, and
37085        // `validate_entrada_matches_gate_on_every_per_axis_shape`
37086        // (20cd523) on the `:entrada` slot's per-slot gate — extended
37087        // here onto the `:contratos` slot's newly-named per-slot gate,
37088        // closing the last unlifted per-slot gate on the M3 mesh-slot
37089        // family.
37090        /// One `:contratos` equivalence case: a label, the per-axis
37091        /// mutation applied to the canonical fixture's spec, and the
37092        /// diagnostic both the per-slot gate and `validate` must
37093        /// surface on it (`None` = clean pass).
37094        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
37095
37096        let cases: &[ContratoCase] = &[
37097            (
37098                ":de shape — empty",
37099                |s| s.contratos[0].de = String::new(),
37100                Some(AplicacaoError::ContratoCaixaEmpty {
37101                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
37102                }),
37103            ),
37104            (
37105                ":para shape — empty",
37106                |s| s.contratos[0].para = String::new(),
37107                Some(AplicacaoError::ContratoCaixaEmpty {
37108                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
37109                }),
37110            ),
37111            (
37112                ":de membership — well-shaped phantom",
37113                |s| s.contratos[0].de = "phantom".into(),
37114                Some(AplicacaoError::ContratoMemberMissing {
37115                    caixa: "phantom".into(),
37116                }),
37117            ),
37118            (
37119                ":para membership — well-shaped phantom",
37120                |s| s.contratos[0].para = "phantom".into(),
37121                Some(AplicacaoError::ContratoMemberMissing {
37122                    caixa: "phantom".into(),
37123                }),
37124            ),
37125            (
37126                "structural self-loop",
37127                |s| s.contratos[0].para = "cart".into(),
37128                Some(AplicacaoError::ContratoSelfLoop {
37129                    caixa: "cart".into(),
37130                    wit: "wasi:http/proxy".into(),
37131                }),
37132            ),
37133            (
37134                ":wit emptiness",
37135                |s| s.contratos[0].wit = String::new(),
37136                Some(AplicacaoError::EmptyWit {
37137                    de: "cart".into(),
37138                    para: "catalog".into(),
37139                }),
37140            ),
37141            ("clean pass — canonical fixture", |_| {}, None),
37142        ];
37143        for (label, mutate, expected) in cases {
37144            let mut spec = three_member_spec();
37145            mutate(&mut spec);
37146            assert_eq!(
37147                spec.validate_contratos().err(),
37148                *expected,
37149                "per-slot gate disagreed with the expected diagnostic on {label}",
37150            );
37151            assert_eq!(
37152                spec.validate().err(),
37153                *expected,
37154                "`validate` disagreed with the per-slot gate on {label}",
37155            );
37156        }
37157    }
37158
37159    #[test]
37160    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
37161        // Companion pin to
37162        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
37163        // the per-slot gate ≡ `validate` equivalence on the three
37164        // `:contratos` refusal arms whose diagnostic carries a
37165        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
37166        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
37167        // `is_dns_1123_label` / `WitContract::target` shape helpers,
37168        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
37169        // library-formatted `target:` scalar). Value equality between
37170        // the per-slot gate and `validate` outputs pins the full
37171        // `Option<AplicacaoError>` (including reason-strings), and the
37172        // per-arm `matches!` predicate pins the arm-discriminator
37173        // identity on the specific `Contrato*` variant. Split from
37174        // the primary equivalence pin so each pin body stays under
37175        // [`clippy::too_many_lines`], the same shape the peer
37176        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
37177        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
37178        // carries on the `:politicas` slot's compound entry gate.
37179        type ContratoReasonCase = (
37180            &'static str,
37181            fn(&mut AplicacaoSpec),
37182            fn(&AplicacaoError) -> bool,
37183        );
37184        let cases: &[ContratoReasonCase] = &[
37185            (
37186                ":de shape — DNS-1123 invalid",
37187                |s| s.contratos[0].de = "Cart".into(),
37188                |err| {
37189                    matches!(
37190                        err,
37191                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
37192                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
37193                    )
37194                },
37195            ),
37196            (
37197                ":wit target-shape mismatch — payload on capability arm",
37198                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
37199                |err| {
37200                    matches!(
37201                        err,
37202                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
37203                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
37204                    )
37205                },
37206            ),
37207            (
37208                "whole-edge dedup — six-axis identity collision",
37209                |s| {
37210                    let dup = s.contratos[0].clone();
37211                    s.contratos.push(dup);
37212                },
37213                |err| {
37214                    matches!(
37215                        err,
37216                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
37217                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
37218                    )
37219                },
37220            ),
37221        ];
37222        for (label, mutate, arm_matches) in cases {
37223            let mut spec = three_member_spec();
37224            mutate(&mut spec);
37225            let per_slot = spec.validate_contratos().err();
37226            let gate = spec.validate().err();
37227            assert_eq!(
37228                per_slot, gate,
37229                "per-slot gate and `validate` must return byte-equal \
37230                 `Option<AplicacaoError>` on {label} (including \
37231                 library-owned reason strings)",
37232            );
37233            let err = per_slot
37234                .as_ref()
37235                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
37236            assert!(
37237                arm_matches(err),
37238                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
37239            );
37240        }
37241    }
37242
37243    #[test]
37244    fn validate_contratos_resolves_membership_through_own_oracle() {
37245        // Self-containment pin on the lifted per-slot gate:
37246        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
37247        // `:de` / `:para` against the oracle *it* builds through
37248        // [`AplicacaoSpec::membro_names`], not one threaded down from
37249        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
37250        // longer contains a `:contratos` edge's endpoint must trip
37251        // `ContratoMemberMissing` when the per-slot gate is called
37252        // directly — the shape a future single-slot re-validator
37253        // (the M4 admission webhook re-checking `:contratos` after a
37254        // per-`(:de, :para)` edge patch, the M4 per-edge policy
37255        // resolver on the `:politicas` override axis) reaches the
37256        // axis through, without re-walking `:membros` / `:entrada` /
37257        // `:placement` / `:politicas` first. Same self-contained
37258        // posture the peer per-slot gates
37259        // [`AplicacaoSpec::detect_sync_cycles`] and
37260        // [`AplicacaoSpec::validate_entrada`] already carry for the
37261        // same M4 consumers.
37262        let mut spec = three_member_spec();
37263        spec.membros.retain(|m| m.nome() != "catalog");
37264        assert_eq!(
37265            spec.validate_contratos().unwrap_err(),
37266            AplicacaoError::ContratoMemberMissing {
37267                caixa: "catalog".into(),
37268            },
37269            "the per-slot gate must resolve `:de` / `:para` against \
37270             the oracle it builds itself, with no membership set \
37271             threaded in",
37272        );
37273        assert!(
37274            !spec.membro_names().contains("catalog"),
37275            "fixture must have dropped the `:contratos` edge's \
37276             `:para` target from the graph's node set",
37277        );
37278    }
37279
37280    #[test]
37281    fn validate_contratos_folds_cycle_axis_matches_gate() {
37282        // Fold-into-per-slot-gate equivalence pin on the
37283        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
37284        // surfaces byte-equal through both
37285        // [`AplicacaoSpec::validate_contratos`] and
37286        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
37287        // a synchronous-edge cycle in `:contratos`. Pins the fold that
37288        // moved the cross-edge cycle axis onto the per-slot gate — a
37289        // future silent regression that de-folded the axis back to the
37290        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
37291        // a peer per-slot gate lift that skipped the cross-axis half of
37292        // the [`MeshPolicy::validate`]-analogous discipline) would
37293        // surface here as `Some(ContratoCycle)` from `validate` and
37294        // `None` from `validate_contratos`.
37295        //
37296        // Cycle fixture is the same shape as the peer
37297        // [`rejects_three_node_synchronous_cycle`] test carries: a
37298        // clean 3-cycle over the HTTP subgraph (catalog → cart →
37299        // payment → catalog), so the per-entry cascade (shape +
37300        // membership + self-loop + `:wit` emptiness + WIT-target +
37301        // whole-edge dedup) passes cleanly and the sole surviving
37302        // refusal shape is the cross-edge cycle axis. The `cycle`
37303        // vector is normalized to a sorted body set for the equality
37304        // compare (the traversal path's starting node depends on
37305        // BTreeMap iteration order, which is deterministic but is not
37306        // the load-bearing property this pin covers).
37307        //
37308        // Peer of the sibling per-slot ≡ `validate` equivalence pins
37309        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
37310        // (per-entry axes) and
37311        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
37312        // (parser-owned reason arms) already carry on the six
37313        // per-entry axes — this extends the discipline onto the
37314        // cross-edge cycle axis newly folded into the per-slot gate,
37315        // matching the peer per-slot compound gate
37316        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
37317        // both per-axis and cross-axis surfaces on `:politicas`.
37318        let mut spec = three_member_spec();
37319        spec.contratos = vec![
37320            contract_http("catalog", "cart", "/x"),
37321            contract_http("cart", "payment", "/y"),
37322            contract_http("payment", "catalog", "/z"),
37323        ];
37324        let per_slot_err = spec.validate_contratos().unwrap_err();
37325        let gate_err = spec.validate().unwrap_err();
37326        assert_eq!(
37327            per_slot_err, gate_err,
37328            "the per-slot gate and `validate` must return byte-equal \
37329             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
37330             — the fold pins the cross-edge axis onto the per-slot \
37331             gate the same way the peer `validate_politicas` fold \
37332             pinned the `:politicas` cross-axis surface",
37333        );
37334        match per_slot_err {
37335            AplicacaoError::ContratoCycle { ref cycle } => {
37336                assert_eq!(
37337                    cycle.first(),
37338                    cycle.last(),
37339                    "cycle traversal must close on the back-edge \
37340                     target — the diagnostic shape the peer \
37341                     `rejects_three_node_synchronous_cycle` pins",
37342                );
37343                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
37344                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
37345                assert!(body.contains("cart"));
37346                assert!(body.contains("catalog"));
37347                assert!(body.contains("payment"));
37348            }
37349            other => panic!("expected ContratoCycle, got {other:?}"),
37350        }
37351    }
37352
37353    #[test]
37354    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
37355        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
37356        // carrying *both* a per-entry defect (a self-loop, the
37357        // structural-self-edge arm on the per-entry cascade — chosen
37358        // because it never masks or is masked by the cycle diagnostic
37359        // on the peer arms) *and* a would-be synchronous-edge cycle in
37360        // the remaining edges must surface the per-entry diagnostic
37361        // first through both [`AplicacaoSpec::validate_contratos`] and
37362        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
37363        // per-entry-before-cross-edge dispatch ordering, byte-equal to
37364        // the pre-fold `validate`-side sequence
37365        // (`validate_contratos()? → detect_sync_cycles()?`) the
37366        // dispatch encoded verbatim. A silent regression that reversed
37367        // the ordering inside the fold would surface here as a cycle
37368        // diagnostic on a fixture carrying an earlier per-entry defect
37369        // — masking the narrower "this edge is degenerate" arm behind
37370        // the coarser "this graph deadlocks" arm.
37371        //
37372        // Peer of the diagnostic-ordering property the pre-fold
37373        // dispatch encoded at the [`AplicacaoSpec::validate`]
37374        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
37375        // now enforced inside the per-slot gate's own body, so a future
37376        // consumer that reaches only the per-slot gate (the M4
37377        // admission webhook re-checking `:contratos` after a per-edge
37378        // patch) inherits the ordering property by construction.
37379        let mut spec = three_member_spec();
37380        // The three-member fixture already has cart → catalog and
37381        // cart → payment; adding catalog → cart closes a 2-cycle on
37382        // the HTTP subgraph.
37383        spec.contratos
37384            .push(contract_http("catalog", "cart", "/refresh"));
37385        // Add a self-loop on `payment` — the per-entry structural-
37386        // self-edge arm — which must surface first.
37387        spec.contratos
37388            .push(contract_http("payment", "payment", "/loop"));
37389        let per_slot_err = spec.validate_contratos().unwrap_err();
37390        let gate_err = spec.validate().unwrap_err();
37391        assert_eq!(
37392            per_slot_err, gate_err,
37393            "per-slot gate and `validate` must agree on the ordering \
37394             fixture's surfaced diagnostic — a divergence here means \
37395             the fold reshaped one dispatch's ordering without the \
37396             other",
37397        );
37398        assert!(
37399            matches!(
37400                per_slot_err,
37401                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
37402                    if caixa == "payment"
37403            ),
37404            "the per-entry structural-self-edge arm must fire before \
37405             the cross-edge cycle arm — pinning the fold's per-entry-\
37406             before-cross-edge dispatch ordering byte-equal to the \
37407             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
37408             sequence; got {per_slot_err:?}",
37409        );
37410    }
37411
37412    #[test]
37413    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
37414        // Self-containment pin on the folded cross-edge cycle axis:
37415        // [`AplicacaoSpec::validate_contratos`] surfaces
37416        // [`AplicacaoError::ContratoCycle`] directly against `&self`
37417        // without depending on the peer per-slot gates
37418        // ([`AplicacaoSpec::validate_membros`],
37419        // [`AplicacaoSpec::validate_entrada`],
37420        // [`AplicacaoSpec::validate_placement`],
37421        // [`AplicacaoSpec::validate_politicas`]) running first — the
37422        // shape a future single-slot re-validator (the M4 admission
37423        // webhook re-checking `:contratos` after a per-`(:de, :para)`
37424        // edge patch, the per-edge policy resolver MESH-COMPOSITION
37425        // §III.2 #3 acknowledges) reaches *both* structural axes on
37426        // the slot through one call. A spec with a per-`:politicas`
37427        // refusal shape (zero `:timeout`, the first per-axis arm the
37428        // peer [`MeshPolicy::validate`] gate covers) AND a
37429        // synchronous-edge cycle in `:contratos` must:
37430        //
37431        //   - surface [`AplicacaoError::ContratoCycle`] through the
37432        //     per-slot gate `validate_contratos` directly (proves the
37433        //     cycle axis reaches the per-slot altitude without the
37434        //     peer `:politicas` gate running first);
37435        //   - surface [`AplicacaoError::ContratoCycle`] through
37436        //     `validate` (which reaches `validate_contratos` before
37437        //     `validate_politicas` per the fixed dispatch order), so
37438        //     the fold's cross-slot ordering (`:membros` →
37439        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
37440        //     is byte-equal to the pre-fold dispatch's ordering.
37441        //
37442        // Same self-contained-on-`&self` posture the peer per-slot
37443        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
37444        // [`AplicacaoSpec::validate_contratos`] per-entry axis
37445        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
37446        // (f03a154) already carry — extended here onto the newly-
37447        // folded cross-edge cycle axis. Peer of the sibling per-slot
37448        // self-containment pins
37449        // `validate_entrada_resolves_membership_through_own_oracle`
37450        // and `validate_contratos_resolves_membership_through_own_oracle`
37451        // on the per-entry membership axis — extends the discipline
37452        // onto the cross-edge cycle axis of the same per-slot gate.
37453        let mut spec = three_member_spec();
37454        // Poison `:politicas` — zero-`:timeout` trips the first per-
37455        // axis arm the [`MeshPolicy::validate`] gate covers, so any
37456        // dispatch that reached `:politicas` would surface a
37457        // `:politicas` diagnostic instead of `ContratoCycle`.
37458        spec.politicas.timeout = Some(Duration::from_secs(0));
37459        // Close a synchronous-edge cycle on the HTTP subgraph.
37460        spec.contratos
37461            .push(contract_http("catalog", "cart", "/refresh"));
37462        let per_slot_err = spec.validate_contratos().unwrap_err();
37463        assert!(
37464            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
37465            "the per-slot gate must surface `ContratoCycle` directly \
37466             against `&self` — a peer per-slot gate's regression \
37467             would surface a non-`ContratoCycle` diagnostic here; \
37468             got {per_slot_err:?}",
37469        );
37470        let gate_err = spec.validate().unwrap_err();
37471        assert!(
37472            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
37473            "`validate`'s five-slot dispatch must reach the fold's \
37474             cross-edge cycle axis on `:contratos` before the peer \
37475             `:politicas` gate — a dispatch-order regression would \
37476             surface a `:politicas` diagnostic here; got {gate_err:?}",
37477        );
37478        // Sanity: the poisoned `:politicas` alone would trip
37479        // [`MeshPolicy::validate`] under the peer per-slot gate, so
37480        // the cycle-first surfacing above is a real ordering property,
37481        // not a case where the `:politicas` axis silently accepts the
37482        // fixture.
37483        let mut politicas_only = three_member_spec();
37484        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
37485        assert!(
37486            politicas_only.validate_politicas().is_err(),
37487            "the poisoned `:politicas` fixture must trip the peer \
37488             per-slot gate on its own — otherwise the self-contained \
37489             cycle-first surfacing above would not be an ordering \
37490             property",
37491        );
37492    }
37493
37494    #[test]
37495    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
37496        // Fail-before-pass-after equivalence pin on the lifted
37497        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
37498        // both arms (`:de` phantom and `:para` phantom) must fire the
37499        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
37500        // `caixa` carrier byte-equal to the offending accessor's
37501        // projection, and `:de` must fire before `:para` when both
37502        // arms would trip on the same call — preserving the canonical
37503        // edge-direction order the peer per-arm shape gate
37504        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
37505        // diagnostic, and every peer per-arm ordering in
37506        // [`AplicacaoSpec::validate_contratos`] already carry.
37507        //
37508        // Two-endpoint oracle covers exactly enough graph nodes to
37509        // exercise each arm in isolation: the `:de` arm fires when
37510        // the source is off-oracle and the destination is on-oracle,
37511        // the `:para` arm fires when the source is on-oracle and the
37512        // destination is off-oracle, and the `:de`-before-`:para`
37513        // ordering falls out from a probe where *both* endpoints are
37514        // off-oracle — the diagnostic's `caixa` field must byte-equal
37515        // the source, not the destination, pinning the primitive's
37516        // arm ordering as `:de` first.
37517        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
37518        names.insert("cart");
37519        names.insert("catalog");
37520
37521        // `:de` phantom, `:para` on-oracle
37522        let de_phantom = contract_http("phantom-de", "catalog", "/x");
37523        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
37524        assert_eq!(
37525            err,
37526            AplicacaoError::ContratoMemberMissing {
37527                caixa: de_phantom.source().to_string(),
37528            },
37529            "the `:de` phantom arm must fire ContratoMemberMissing \
37530             with `caixa` byte-equal to `WitContract::source` — a \
37531             bypass here (a raw `.de.clone()` regression, a divergent \
37532             accessor on a per-CR alias table) would silently split \
37533             the primitive's diagnostic from the substrate-primitive \
37534             scalar accessor every downstream consumer routes through",
37535        );
37536
37537        // `:de` on-oracle, `:para` phantom
37538        let para_phantom = contract_http("cart", "phantom-para", "/x");
37539        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
37540        assert_eq!(
37541            err,
37542            AplicacaoError::ContratoMemberMissing {
37543                caixa: para_phantom.destination().to_string(),
37544            },
37545            "the `:para` phantom arm must fire ContratoMemberMissing \
37546             with `caixa` byte-equal to `WitContract::destination` — \
37547             symmetric callee-side pin to the `:de` arm above",
37548        );
37549
37550        // Both endpoints off-oracle: the `:de` arm must fire first,
37551        // pinning the primitive's canonical edge-direction order.
37552        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
37553        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
37554        assert_eq!(
37555            err,
37556            AplicacaoError::ContratoMemberMissing {
37557                caixa: both_phantom.source().to_string(),
37558            },
37559            "when both endpoints are off-oracle, the `:de` arm must \
37560             fire before the `:para` arm — preserving byte-equal \
37561             ordering with the pre-lift inline cascade in \
37562             `validate_contratos` and with every peer per-arm \
37563             ordering the sibling per-edge substrate primitives \
37564             already carry",
37565        );
37566
37567        // Both endpoints on-oracle: clean pass.
37568        let clean = contract_http("cart", "catalog", "/x");
37569        clean.require_endpoints_in(&names).unwrap();
37570    }
37571
37572    #[test]
37573    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
37574        // Convergence pin: the whole-spec end-to-end route through
37575        // [`AplicacaoSpec::validate_contratos`] must reach the
37576        // per-edge substrate primitive
37577        // [`WitContract::require_endpoints_in`] on every membership
37578        // arm — the diagnostic fired at the per-slot altitude must
37579        // byte-equal the diagnostic the primitive fires when called
37580        // directly on the same edge and the same oracle. Pins the
37581        // primitive as the sole load-bearing gate on the membership
37582        // axis, so any future silent detour that re-inlined the twin
37583        // `if !names.contains(...)` cascade back into the per-slot
37584        // gate (a rebase-artifact regression, an M4 admission-webhook
37585        // consumer that bypassed the primitive) would surface here as
37586        // a byte-equal miss between the two dispatches.
37587        //
37588        // Same equivalence-pin discipline the peer
37589        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
37590        // pin already carries on the per-slot gate ≡ `validate` axis,
37591        // extended here onto the per-slot gate ≡ per-edge primitive
37592        // axis at one altitude deeper.
37593        for phantom_edge in [
37594            contract_http("phantom-de", "catalog", "/x"),
37595            contract_http("cart", "phantom-para", "/x"),
37596        ] {
37597            let mut spec = three_member_spec();
37598            spec.contratos.push(phantom_edge.clone());
37599            let per_slot_err = spec.validate_contratos().unwrap_err();
37600            let primitive_err = phantom_edge
37601                .require_endpoints_in(&spec.membro_names())
37602                .unwrap_err();
37603            assert_eq!(
37604                per_slot_err, primitive_err,
37605                "the per-slot gate must reach the per-edge substrate \
37606                 primitive on every membership arm — a bypass here \
37607                 would silently split the two dispatches on the \
37608                 same edge + same oracle input",
37609            );
37610            // And the diagnostic's `caixa` carrier must byte-equal
37611            // the offending accessor's projection at both altitudes,
37612            // pinning the accessor routing across the whole-spec
37613            // path.
37614            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
37615                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
37616            };
37617            let expected = if spec.membro_names().contains(phantom_edge.source()) {
37618                phantom_edge.destination()
37619            } else {
37620                phantom_edge.source()
37621            };
37622            assert_eq!(
37623                caixa, expected,
37624                "the whole-spec ContratoMemberMissing.caixa carrier \
37625                 must byte-equal the offending edge's accessor \
37626                 projection — a bypass here would silently split \
37627                 the wrap envelope's `caixa` field from the \
37628                 substrate-primitive scalar accessor every \
37629                 downstream consumer routes through",
37630            );
37631        }
37632    }
37633
37634    #[test]
37635    fn port_for_destination_reads_through_lifted_entrada_accessor() {
37636        // Peer coherence pin: the
37637        // [`AplicacaoSpec::port_for_destination`] per-destination
37638        // L4-port fallback resolver's composite-projection seed
37639        // (`self.entrada().filter(…).map_or(…)`) must key off the
37640        // lifted outer accessor. Pins the coherence by exercising
37641        // the resolver end-to-end: (1) the `None` `:entrada` shape
37642        // falls through to `DEFAULT_SERVICO_PORT` under the outer
37643        // accessor's reference projection, (2) a non-matching
37644        // destination falls through to `DEFAULT_SERVICO_PORT` under
37645        // the outer accessor's reference projection, and (3) the
37646        // matching destination resolves to the `:entrada :port`
37647        // value under the outer accessor's reference projection.
37648        //
37649        // Peer of the sibling
37650        // [`validate_reads_through_lifted_entrada_accessor`] multi-
37651        // consumer coherence pin on the same per-`:entrada` outer-
37652        // composite axis — extends the multi-consumer coherence
37653        // discipline onto the second per-`:entrada` production
37654        // consumer, the L4-port fallback resolver.
37655
37656        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
37657        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
37658        // arm under the outer accessor's reference projection.
37659        let mut spec = three_member_spec();
37660        spec.entrada = None;
37661        assert_eq!(
37662            spec.port_for_destination("cart"),
37663            DEFAULT_SERVICO_PORT,
37664            "the port-fallback resolver must fall through to \
37665             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
37666             under the outer accessor's reference projection",
37667        );
37668
37669        // (2) Non-matching destination — the resolver's `filter(…)`
37670        // arm rejects a mismatched destination and falls through
37671        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
37672        // reference projection.
37673        let mut spec = three_member_spec();
37674        if let Some(e) = spec.entrada.as_mut() {
37675            e.para = "cart".into();
37676            e.port = 9443;
37677        }
37678        assert_eq!(
37679            spec.port_for_destination("catalog"),
37680            DEFAULT_SERVICO_PORT,
37681            "the port-fallback resolver must fall through to \
37682             DEFAULT_SERVICO_PORT on a non-matching destination \
37683             under the outer accessor's reference projection",
37684        );
37685
37686        // (3) Matching destination — the resolver's `map_or(…)` arm
37687        // returns the `:entrada :port` value under the outer
37688        // accessor's reference projection.
37689        let mut spec = three_member_spec();
37690        if let Some(e) = spec.entrada.as_mut() {
37691            e.para = "cart".into();
37692            e.port = 9443;
37693        }
37694        assert_eq!(
37695            spec.port_for_destination("cart"),
37696            9443,
37697            "the port-fallback resolver must return the \
37698             `:entrada :port` value on a matching destination \
37699             under the outer accessor's reference projection",
37700        );
37701    }
37702
37703    #[test]
37704    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
37705        // The canonical per-`:politicas` `:mtls-required` mTLS-
37706        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
37707        // must return the `:politicas :mtls-required` typed bool
37708        // verbatim as an `Option<bool>`, byte-equal to the raw field
37709        // access across every value in the three-way accept-set —
37710        // `None` (cluster default applies), `Some(true)` (mTLS
37711        // handshake enforced — the sandboxing-by-default arm the
37712        // MeshPolicy's docstring names), `Some(false)` (handshake
37713        // skipped — the explicit debug-edge opt-out).
37714        //
37715        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
37716        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
37717        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
37718        // shape — first `Option<Copy-T>`-return accessor on the M3
37719        // mesh-slot family. Pins against a future silent detour that
37720        // re-derived the toggle from a peer axis (an accidental
37721        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
37722        // whenever a breaker is set), a `None` → `Some(false)` cluster-
37723        // default projection (the canonical `Option<bool>` → `bool`
37724        // collapse footgun the surrounding `is_empty()` predicate
37725        // guards on the peer emptiness axis), or a `Some(true)` /
37726        // `Some(false)` variant swap that landed on one consumer
37727        // without the other.
37728        for required in [None, Some(true), Some(false)] {
37729            let p = MeshPolicy {
37730                mtls_required: required,
37731                ..MeshPolicy::default()
37732            };
37733            assert_eq!(
37734                p.mtls_required(),
37735                required,
37736                "MeshPolicy::mtls_required must return :politicas \
37737                 :mtls-required verbatim (got {:?}, expected {required:?})",
37738                p.mtls_required(),
37739            );
37740            assert_eq!(
37741                p.mtls_required(),
37742                p.mtls_required,
37743                "MeshPolicy::mtls_required must byte-equal the raw \
37744                 .mtls_required field access across every value in the \
37745                 three-way accept-set",
37746            );
37747        }
37748    }
37749
37750    #[test]
37751    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
37752        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
37753        // arm must key off [`MeshPolicy::mtls_required`], not the raw
37754        // `.mtls_required` field access. Structurally: toggling ONLY
37755        // the `mtls_required` slot on an otherwise-default MeshPolicy
37756        // must flip `is_empty()` from `true` (all-`None`) to `false`
37757        // (one axis carries a value); the flip must be observed for
37758        // both `Some(true)` and `Some(false)` since the emptiness
37759        // semantic reads "any axis carries a value" — not "any axis
37760        // carries a truthy value" — the same non-collapsing shape the
37761        // sibling M2 [`crate::LimitsSpec::is_empty`] /
37762        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
37763        // peer `Option<T>`-typed slot surfaces.
37764        //
37765        // Pins against a future silent detour that re-derived the
37766        // emptiness predicate off a peer axis (an accidental
37767        // `.rate_limit.is_none()`-only chain that dropped the
37768        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
37769        // collapse to a truthy-only check (which would silently
37770        // classify `Some(false)` as empty), or an accessor-side
37771        // detour that no longer names the substrate-primitive typed
37772        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
37773        // == false` fallback in the accessor that would silently
37774        // classify both `None` and `Some(false)` as the same value).
37775        //
37776        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
37777        // (7cd2a28) accessor-composition pin on the sibling optional-
37778        // scalar axis — same "the emptiness / shape-gate predicate
37779        // must route through the substrate-primitive typed dispatch"
37780        // discipline extended onto the peer per-`:politicas` emptiness
37781        // predicate.
37782        let empty = MeshPolicy::default();
37783        assert!(
37784            empty.is_empty(),
37785            "MeshPolicy::default() must be is_empty() — every axis \
37786             defaults to None",
37787        );
37788        for required in [Some(true), Some(false)] {
37789            let p = MeshPolicy {
37790                mtls_required: required,
37791                ..MeshPolicy::default()
37792            };
37793            assert!(
37794                !p.is_empty(),
37795                "MeshPolicy::is_empty must return false when \
37796                 :mtls-required is {required:?} — the emptiness \
37797                 predicate reads \"any axis carries a value\", not \
37798                 \"any axis carries a truthy value\"",
37799            );
37800            assert_eq!(
37801                p.mtls_required().is_none(),
37802                p.is_empty(),
37803                "when :mtls-required is the only set axis, \
37804                 is_empty() must equal mtls_required().is_none() — \
37805                 the accessor and the emptiness predicate must \
37806                 route through the same substrate-primitive typed \
37807                 dispatch on the :mtls-required arm",
37808            );
37809        }
37810    }
37811
37812    #[test]
37813    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
37814        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
37815        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
37816        // accessor must return by value, not by reference. Peer of the
37817        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
37818        // borrow-invariant pin on the sibling `Option<String>` slot,
37819        // but extended onto the peer `Option<bool>` copy-invariant
37820        // shape — the accessor's returned `Option<bool>` must outlive
37821        // `&self` (multiple calls must return equal values from a
37822        // dropped-`&self` copy, since the returned Option carries no
37823        // borrow), and calling the accessor twice on the same
37824        // MeshPolicy must yield the same `Option<bool>` verbatim
37825        // (idempotent, no side effects on `&self`).
37826        //
37827        // Pins against a future silent detour that returned
37828        // `Option<&bool>` (which would type-check but silently break
37829        // every downstream caller — [`single_field_overlay`]'s first
37830        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
37831        // detached copy at the call site), an accidental
37832        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
37833        // would also type-check but return `Option<&bool>`), or a
37834        // one-arm-only accessor that reads `Some(*b)` in the Some arm
37835        // but reads a fresh Default::default() in the None arm.
37836        for required in [None, Some(true), Some(false)] {
37837            let p = MeshPolicy {
37838                mtls_required: required,
37839                ..MeshPolicy::default()
37840            };
37841            let first = p.mtls_required();
37842            let second = p.mtls_required();
37843            assert_eq!(
37844                first, second,
37845                "MeshPolicy::mtls_required must be idempotent — two \
37846                 successive calls on the same &self must return the \
37847                 same Option<bool>",
37848            );
37849            assert_eq!(
37850                first, required,
37851                "MeshPolicy::mtls_required must return :politicas \
37852                 :mtls-required verbatim by copy — got {first:?}, \
37853                 expected {required:?}",
37854            );
37855        }
37856    }
37857
37858    #[test]
37859    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
37860        // The canonical per-`:politicas` `:retries` transient-failure-
37861        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
37862        // the `:politicas :retries` typed `u32` verbatim as an
37863        // `Option<u32>`, byte-equal to the raw field access across every
37864        // representative value in the accept-set — `None` (cluster
37865        // default applies — typically "no retries beyond a single
37866        // dispatch attempt" the caixa-mesh `retry_overlay` builder
37867        // documents), `Some(1)` (the lower boundary of the
37868        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
37869        // `AplicacaoSpec::validate_politicas` gate carves out on the
37870        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
37871        // (the upper boundary the same gate carves out on the sibling
37872        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
37873        // past-the-guard sentinel that pins the accessor doesn't perform
37874        // a silent bounds-collapse at the return path).
37875        //
37876        // Sibling of the peer per-`:politicas`
37877        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
37878        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
37879        // peer per-`:politicas` `Option<u32>` shape — second
37880        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
37881        // Pins against a future silent detour that re-derived the retry
37882        // cap from a peer axis (an accidental `.circuit_breaker
37883        // .as_ref().map(|b| b.max_failures)` collapse that read the
37884        // breaker's max-failure count as a retry budget), a
37885        // `None → Some(0)` cluster-default projection (which would
37886        // silently re-introduce the `PolicyRetriesZero` refusal case at
37887        // the emit boundary), or a bounds-collapsing accessor that
37888        // clamped the return through `POLICY_RETRIES_MAX` (the
37889        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
37890        // must ship the raw slot verbatim so a validate-time gate
37891        // regression surfaces at the emit boundary rather than being
37892        // silently absorbed).
37893        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
37894            let p = MeshPolicy {
37895                retries,
37896                ..MeshPolicy::default()
37897            };
37898            assert_eq!(
37899                p.retries(),
37900                retries,
37901                "MeshPolicy::retries must return :politicas :retries \
37902                 verbatim (got {:?}, expected {retries:?})",
37903                p.retries(),
37904            );
37905            assert_eq!(
37906                p.retries(),
37907                p.retries,
37908                "MeshPolicy::retries must byte-equal the raw .retries \
37909                 field access across every value in the accept-set",
37910            );
37911        }
37912    }
37913
37914    #[test]
37915    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
37916        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
37917        // must key off [`MeshPolicy::retries`], not the raw `.retries`
37918        // field access. Structurally: toggling ONLY the `retries` slot
37919        // on an otherwise-default MeshPolicy must flip `is_empty()`
37920        // from `true` (all-`None`) to `false` (one axis carries a
37921        // value); the flip must be observed for every value in the
37922        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
37923        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
37924        // the emptiness semantic reads "any axis carries a value" —
37925        // not "any axis carries a value the validate gate accepts" —
37926        // the same non-collapsing shape the peer M2
37927        // [`crate::LimitsSpec::is_empty`] /
37928        // [`crate::BehaviorSpec::is_empty`] predicates carry.
37929        //
37930        // Pins against a future silent detour that re-derived the
37931        // emptiness predicate off a peer axis (an accidental
37932        // `.rate_limit.is_none()`-only chain that dropped the
37933        // `retries` arm entirely), a `retries == Some(_)` collapse
37934        // that key-off a validate-gate-clamped bounds check (which
37935        // would silently classify a past-the-guard `Some(u32::MAX)`
37936        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
37937        // check), or an accessor-side detour that no longer names the
37938        // substrate-primitive typed dispatch.
37939        //
37940        // Sibling of the peer per-`:politicas`
37941        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
37942        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
37943        // same "the emptiness predicate must route through the
37944        // substrate-primitive typed dispatch" discipline extended onto
37945        // the peer per-`:politicas` `Option<u32>` axis.
37946        let empty = MeshPolicy::default();
37947        assert!(
37948            empty.is_empty(),
37949            "MeshPolicy::default() must be is_empty() — every axis \
37950             defaults to None",
37951        );
37952        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
37953            let p = MeshPolicy {
37954                retries,
37955                ..MeshPolicy::default()
37956            };
37957            assert!(
37958                !p.is_empty(),
37959                "MeshPolicy::is_empty must return false when \
37960                 :retries is {retries:?} — the emptiness \
37961                 predicate reads \"any axis carries a value\", not \
37962                 \"any axis carries a value the validate gate \
37963                 accepts\"",
37964            );
37965            assert_eq!(
37966                p.retries().is_none(),
37967                p.is_empty(),
37968                "when :retries is the only set axis, is_empty() \
37969                 must equal retries().is_none() — the accessor and \
37970                 the emptiness predicate must route through the same \
37971                 substrate-primitive typed dispatch on the :retries \
37972                 arm",
37973            );
37974        }
37975    }
37976
37977    #[test]
37978    fn mesh_policy_retries_projects_option_u32_by_copy() {
37979        // The by-copy pin: [`MeshPolicy::retries`] returns
37980        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
37981        // accessor must return by value, not by reference. Sibling of
37982        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
37983        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
37984        // extended onto the sibling `Option<u32>` copy-invariant
37985        // shape — the accessor's returned `Option<u32>` must outlive
37986        // `&self` (multiple calls must return equal values from a
37987        // dropped-`&self` copy, since the returned Option carries no
37988        // borrow), and calling the accessor twice on the same
37989        // MeshPolicy must yield the same `Option<u32>` verbatim
37990        // (idempotent, no side effects on `&self`).
37991        //
37992        // Pins against a future silent detour that returned
37993        // `Option<&u32>` (which would type-check but silently break
37994        // every downstream caller — [`crate::render::single_field_overlay`]'s
37995        // first parameter is `Option<T: Clone>`, and `&u32` would
37996        // fold to a detached copy at the call site), an accidental
37997        // `Option::as_ref()` projection (`self.retries.as_ref()` would
37998        // also type-check but return `Option<&u32>`), or a one-arm-
37999        // only accessor that reads `Some(*n)` in the Some arm but
38000        // reads a fresh `Default::default()` (`0_u32`) in the None
38001        // arm.
38002        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
38003            let p = MeshPolicy {
38004                retries,
38005                ..MeshPolicy::default()
38006            };
38007            let first = p.retries();
38008            let second = p.retries();
38009            assert_eq!(
38010                first, second,
38011                "MeshPolicy::retries must be idempotent — two \
38012                 successive calls on the same &self must return the \
38013                 same Option<u32>",
38014            );
38015            assert_eq!(
38016                first, retries,
38017                "MeshPolicy::retries must return :politicas :retries \
38018                 verbatim by copy — got {first:?}, expected {retries:?}",
38019            );
38020        }
38021    }
38022
38023    #[test]
38024    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
38025        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
38026        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
38027        // return the `:politicas :timeout` typed [`Duration`] verbatim
38028        // as an `Option<Duration>`, byte-equal to the raw field access
38029        // across every representative value in the accept-set — `None`
38030        // (cluster default applies — typically the gateway class's
38031        // implementation-side per-request wall-clock cap the caixa-mesh
38032        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
38033        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
38034        // set the surrounding `AplicacaoSpec::validate_politicas` gate
38035        // carves out on the sibling `PolicyTimeoutZero` /
38036        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
38037        // (the upper boundary the same gate carves out on the sibling
38038        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
38039        // (a past-the-guard sentinel that pins the accessor doesn't
38040        // perform a silent bounds-collapse into `None` on the zero-
38041        // Duration arm — validate rejects zero but the accessor must
38042        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
38043        // past-the-guard sentinel that pins the accessor doesn't
38044        // perform a silent bounds-collapse at the return path).
38045        //
38046        // Sibling of the peer per-`:politicas`
38047        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
38048        // `Option<u32>` optional-scalar axis and the peer per-
38049        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
38050        // pin on the sibling `Option<bool>` optional-scalar axis,
38051        // extended onto the peer per-`:politicas` `Option<Duration>`
38052        // shape — third `Option<Copy-T>`-return accessor on the M3
38053        // mesh-slot family. Pins against a future silent detour that
38054        // re-derived the per-call cap from a peer axis (an accidental
38055        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
38056        // read the breaker's rolling-window duration as a per-call
38057        // deadline), a `None → Some(Duration::MAX)` cluster-default
38058        // projection (which would silently re-introduce the
38059        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
38060        // blocking" arm at the emit boundary), or a bounds-collapsing
38061        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
38062        // (the `AplicacaoSpec::validate` gate owns the bounds; the
38063        // accessor must ship the raw slot verbatim so a validate-time
38064        // gate regression surfaces at the emit boundary rather than
38065        // being silently absorbed).
38066        for timeout in [
38067            None,
38068            Some(Duration::from_millis(1)),
38069            Some(POLICY_TIMEOUT_MAX),
38070            Some(Duration::ZERO),
38071            Some(Duration::MAX),
38072        ] {
38073            let p = MeshPolicy {
38074                timeout,
38075                ..MeshPolicy::default()
38076            };
38077            assert_eq!(
38078                p.timeout(),
38079                timeout,
38080                "MeshPolicy::timeout must return :politicas :timeout \
38081                 verbatim (got {:?}, expected {timeout:?})",
38082                p.timeout(),
38083            );
38084            assert_eq!(
38085                p.timeout(),
38086                p.timeout,
38087                "MeshPolicy::timeout must byte-equal the raw .timeout \
38088                 field access across every value in the accept-set",
38089            );
38090        }
38091    }
38092
38093    #[test]
38094    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
38095        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
38096        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
38097        // field access. Structurally: toggling ONLY the `timeout` slot
38098        // on an otherwise-default MeshPolicy must flip `is_empty()`
38099        // from `true` (all-`None`) to `false` (one axis carries a
38100        // value); the flip must be observed for every value in the
38101        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
38102        // gate accepts (`Some(Duration::from_millis(1))`,
38103        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
38104        // reads "any axis carries a value" — not "any axis carries a
38105        // value the validate gate accepts" — the same non-collapsing
38106        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
38107        // [`crate::BehaviorSpec::is_empty`] predicates carry.
38108        //
38109        // Pins against a future silent detour that re-derived the
38110        // emptiness predicate off a peer axis (an accidental
38111        // `.rate_limit.is_none()`-only chain that dropped the
38112        // `timeout` arm entirely), a `timeout == Some(_)` collapse
38113        // that key-off a validate-gate-clamped bounds check (which
38114        // would silently classify a past-the-guard `Some(Duration::MAX)`
38115        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
38116        // check), or an accessor-side detour that no longer names the
38117        // substrate-primitive typed dispatch.
38118        //
38119        // Sibling of the peer per-`:politicas`
38120        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
38121        // the sibling `Option<u32>` optional-scalar axis and the peer
38122        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
38123        // accessor-composition pin on the sibling `Option<bool>`
38124        // optional-scalar axis — same "the emptiness predicate must
38125        // route through the substrate-primitive typed dispatch"
38126        // discipline extended onto the peer per-`:politicas`
38127        // `Option<Duration>` axis.
38128        let empty = MeshPolicy::default();
38129        assert!(
38130            empty.is_empty(),
38131            "MeshPolicy::default() must be is_empty() — every axis \
38132             defaults to None",
38133        );
38134        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
38135            let p = MeshPolicy {
38136                timeout,
38137                ..MeshPolicy::default()
38138            };
38139            assert!(
38140                !p.is_empty(),
38141                "MeshPolicy::is_empty must return false when \
38142                 :timeout is {timeout:?} — the emptiness \
38143                 predicate reads \"any axis carries a value\", not \
38144                 \"any axis carries a value the validate gate \
38145                 accepts\"",
38146            );
38147            assert_eq!(
38148                p.timeout().is_none(),
38149                p.is_empty(),
38150                "when :timeout is the only set axis, is_empty() \
38151                 must equal timeout().is_none() — the accessor and \
38152                 the emptiness predicate must route through the same \
38153                 substrate-primitive typed dispatch on the :timeout \
38154                 arm",
38155            );
38156        }
38157    }
38158
38159    #[test]
38160    fn mesh_policy_timeout_projects_option_duration_by_copy() {
38161        // The by-copy pin: [`MeshPolicy::timeout`] returns
38162        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
38163        // and the accessor must return by value, not by reference.
38164        // Sibling of the peer per-`:politicas`
38165        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
38166        // sibling `Option<u32>` optional-scalar axis and the peer
38167        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
38168        // by-copy pin on the sibling `Option<bool>` optional-scalar
38169        // axis, extended onto the peer per-`:politicas`
38170        // `Option<Duration>` copy-invariant shape — the accessor's
38171        // returned `Option<Duration>` must outlive `&self` (multiple
38172        // calls must return equal values from a dropped-`&self`
38173        // copy, since the returned Option carries no borrow), and
38174        // calling the accessor twice on the same MeshPolicy must
38175        // yield the same `Option<Duration>` verbatim (idempotent, no
38176        // side effects on `&self`).
38177        //
38178        // Pins against a future silent detour that returned
38179        // `Option<&Duration>` (which would type-check but silently
38180        // break every downstream caller — [`crate::render::single_field_overlay`]'s
38181        // first parameter is `Option<T: Clone>`, and `&Duration`
38182        // would fold to a detached copy at the call site), an
38183        // accidental `Option::as_ref()` projection
38184        // (`self.timeout.as_ref()` would also type-check but return
38185        // `Option<&Duration>`), or a one-arm-only accessor that
38186        // reads `Some(*d)` in the Some arm but reads a fresh
38187        // `Default::default()` (`Duration::ZERO`) in the None arm
38188        // (which would silently re-classify every unset `:timeout`
38189        // as the `PolicyTimeoutZero`-refused zero-Duration value at
38190        // the accessor boundary).
38191        for timeout in [
38192            None,
38193            Some(Duration::from_millis(1)),
38194            Some(POLICY_TIMEOUT_MAX),
38195            Some(Duration::ZERO),
38196            Some(Duration::MAX),
38197        ] {
38198            let p = MeshPolicy {
38199                timeout,
38200                ..MeshPolicy::default()
38201            };
38202            let first = p.timeout();
38203            let second = p.timeout();
38204            assert_eq!(
38205                first, second,
38206                "MeshPolicy::timeout must be idempotent — two \
38207                 successive calls on the same &self must return the \
38208                 same Option<Duration>",
38209            );
38210            assert_eq!(
38211                first, timeout,
38212                "MeshPolicy::timeout must return :politicas :timeout \
38213                 verbatim by copy — got {first:?}, expected {timeout:?}",
38214            );
38215        }
38216    }
38217
38218    #[test]
38219    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
38220        // The canonical per-`:politicas` `:rate-limit` Envoy-
38221        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
38222        // [`MeshPolicy::rate_limit`] must return the `:politicas
38223        // :rate-limit` typed [`RateLimit`] verbatim as an
38224        // `Option<RateLimit>`, byte-equal to the raw field access
38225        // across every representative value in the accept-set — `None`
38226        // (cluster default applies — no per-Aplicacao rate declaration,
38227        // the gateway-class per-listener default arm the future caixa-
38228        // mesh `local_rate_limit_overlay` emitter documents),
38229        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
38230        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
38231        // accept-set the surrounding
38232        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
38233        // sibling `PolicyRateLimitZero` refusal, paired with the
38234        // canonical-window "1 second" arm of the three-unit
38235        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
38236        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
38237        // (the upper boundary the same gate carves out on the sibling
38238        // `PolicyRateLimitExceedsCap` refusal, paired with the
38239        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
38240        // (a past-the-guard sentinel that pins the accessor doesn't
38241        // perform a silent bounds-collapse into `None` on the
38242        // zero-rate/zero-window arm — validate rejects zero but the
38243        // accessor must ship the raw slot verbatim so a validate-time
38244        // gate regression surfaces at the emit boundary rather than
38245        // being silently absorbed), and
38246        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
38247        // (a past-the-guard sentinel that pins the accessor doesn't
38248        // perform a silent bounds-collapse at the return path).
38249        //
38250        // First `Option<Copy-composite-T>`-return accessor pin on the
38251        // M3 mesh-slot family (peer of the sibling per-`:politicas`
38252        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
38253        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
38254        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
38255        // Copy accessor pins, extended onto the peer per-`:politicas`
38256        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
38257        // and the accessor returns by value). Pins against a future
38258        // silent detour that re-derived the rate declaration from a
38259        // peer axis (an accidental
38260        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
38261        // collapse that read the breaker's trip threshold + rolling
38262        // window as a rate declaration), a `None → Some(default())`
38263        // cluster-default projection (which would silently re-
38264        // introduce a "cluster default is 0/s" arm the emit boundary
38265        // would take as "declared but inert" — the canonical
38266        // declared-but-inert footgun the sibling
38267        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
38268        // amplification-shape axis), a bounds-collapsing accessor
38269        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
38270        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
38271        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
38272        // accessor must ship the raw slot verbatim), or a
38273        // by-reference detour (`Option<&RateLimit>`) that broke every
38274        // downstream consumer keying off `Option<RateLimit>` by-copy.
38275        for rl in [
38276            None,
38277            Some(RateLimit {
38278                rate: 1,
38279                window: Duration::from_secs(1),
38280            }),
38281            Some(RateLimit {
38282                rate: POLICY_RATE_LIMIT_MAX,
38283                window: Duration::from_secs(3600),
38284            }),
38285            Some(RateLimit {
38286                rate: 0,
38287                window: Duration::ZERO,
38288            }),
38289            Some(RateLimit {
38290                rate: u32::MAX,
38291                window: Duration::MAX,
38292            }),
38293        ] {
38294            let p = MeshPolicy {
38295                rate_limit: rl,
38296                ..MeshPolicy::default()
38297            };
38298            assert_eq!(
38299                p.rate_limit(),
38300                rl,
38301                "MeshPolicy::rate_limit must return :politicas :rate-limit \
38302                 verbatim (got {:?}, expected {rl:?})",
38303                p.rate_limit(),
38304            );
38305            assert_eq!(
38306                p.rate_limit(),
38307                p.rate_limit,
38308                "MeshPolicy::rate_limit must byte-equal the raw \
38309                 .rate_limit field access across every value in the \
38310                 accept-set",
38311            );
38312        }
38313    }
38314
38315    #[test]
38316    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
38317        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
38318        // must key off [`MeshPolicy::rate_limit`], not the raw
38319        // `.rate_limit` field access. Structurally: toggling ONLY the
38320        // `rate_limit` slot on an otherwise-default MeshPolicy must
38321        // flip `is_empty()` from `true` (all-`None`) to `false` (one
38322        // axis carries a value); the flip must be observed for every
38323        // representative value in the accept-set the surrounding
38324        // [`AplicacaoSpec::validate_politicas`] gate accepts
38325        // (`Some(RateLimit { rate: 1, window: 1s })`,
38326        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
38327        // since the emptiness semantic reads "any axis carries a
38328        // value" — not "any axis carries a value the validate gate
38329        // accepts" — the same non-collapsing shape the peer M2
38330        // [`crate::LimitsSpec::is_empty`] /
38331        // [`crate::BehaviorSpec::is_empty`] predicates carry.
38332        //
38333        // Pins against a future silent detour that re-derived the
38334        // emptiness predicate off a peer axis (an accidental
38335        // `.timeout.is_none()`-only chain that dropped the
38336        // `rate_limit` arm entirely — the last unlifted inline field
38337        // access on `is_empty` before this lift), a `rate_limit ==
38338        // Some(_)` collapse that key-off a validate-gate-clamped
38339        // bounds check (which would silently classify a past-the-
38340        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
38341        // because it fails the value-shape gate), or an accessor-
38342        // side detour that no longer names the substrate-primitive
38343        // typed dispatch.
38344        //
38345        // Fourth "the emptiness predicate must route through the
38346        // substrate-primitive typed dispatch" composition pin on the
38347        // M3 mesh-slot family — closes the last unlifted composition
38348        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
38349        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
38350        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
38351        // 7073d0f is_empty-composition pins on the sibling primitive-
38352        // Copy axes, extended onto the peer per-`:politicas`
38353        // composite-Copy `Option<RateLimit>` axis).
38354        let empty = MeshPolicy::default();
38355        assert!(
38356            empty.is_empty(),
38357            "MeshPolicy::default() must be is_empty() — every axis \
38358             defaults to None",
38359        );
38360        for rl in [
38361            RateLimit {
38362                rate: 1,
38363                window: Duration::from_secs(1),
38364            },
38365            RateLimit {
38366                rate: POLICY_RATE_LIMIT_MAX,
38367                window: Duration::from_secs(3600),
38368            },
38369        ] {
38370            let p = MeshPolicy {
38371                rate_limit: Some(rl),
38372                ..MeshPolicy::default()
38373            };
38374            assert!(
38375                !p.is_empty(),
38376                "MeshPolicy::is_empty must return false when \
38377                 :rate-limit is {rl:?} — the emptiness predicate \
38378                 reads \"any axis carries a value\", not \"any axis \
38379                 carries a value the validate gate accepts\"",
38380            );
38381            assert_eq!(
38382                p.rate_limit().is_none(),
38383                p.is_empty(),
38384                "when :rate-limit is the only set axis, is_empty() \
38385                 must equal rate_limit().is_none() — the accessor \
38386                 and the emptiness predicate must route through the \
38387                 same substrate-primitive typed dispatch on the \
38388                 :rate-limit arm",
38389            );
38390        }
38391    }
38392
38393    #[test]
38394    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
38395        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
38396        // `:rate-limit` value-shape gate must key off
38397        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
38398        // field bind. Structurally: a `MeshPolicy` whose only set
38399        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
38400        // the `PolicyRateLimitZero` refusal exactly, and the same
38401        // MeshPolicy with the rate at the canonical lower boundary
38402        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
38403        // The pair jointly pins the accessor + validate-gate
38404        // composition: any future silent detour that had the accessor
38405        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
38406        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
38407        // silently absorb the `PolicyRateLimitZero` refusal at the
38408        // accessor boundary — the composition pin catches that at
38409        // caixa-core build time.
38410        //
38411        // Sibling of the peer [`validate_politicas`]
38412        // `:mtls-required` / `:retries` / `:timeout` composition pins
38413        // on the sibling primitive-Copy optional-scalar axes — same
38414        // "the validate / shape-gate predicate must route through the
38415        // substrate-primitive typed dispatch" discipline extended
38416        // onto the peer per-`:politicas` composite-Copy
38417        // `Option<RateLimit>` axis. Second composition-with-accessor
38418        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
38419        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
38420        let mut spec = three_member_spec();
38421        spec.politicas = MeshPolicy {
38422            rate_limit: Some(RateLimit {
38423                rate: 0,
38424                window: Duration::from_secs(1),
38425            }),
38426            ..MeshPolicy::default()
38427        };
38428        assert!(
38429            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
38430            "validate_politicas must reject rate == 0 with \
38431             PolicyRateLimitZero — the accessor and the validate gate \
38432             must route through the same substrate-primitive typed \
38433             dispatch on the :rate-limit zero-floor arm",
38434        );
38435        spec.politicas = MeshPolicy {
38436            rate_limit: Some(RateLimit {
38437                rate: 1,
38438                window: Duration::from_secs(1),
38439            }),
38440            ..MeshPolicy::default()
38441        };
38442        assert!(
38443            spec.validate().is_ok(),
38444            "validate_politicas must accept rate == 1 (the canonical \
38445             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
38446             set) with a canonical 1s window",
38447        );
38448    }
38449
38450    #[test]
38451    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
38452        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
38453        // `outlier_detection`-mesh consecutive-failure-ejection scalar
38454        // pin: [`MeshPolicy::circuit_breaker`] must return the
38455        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
38456        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
38457        // raw field access across every representative value in the
38458        // accept-set — `None` (cluster default applies — no
38459        // per-Aplicacao breaker declaration, the gateway-class per-
38460        // listener default arm the future caixa-mesh
38461        // `outlier_detection_overlay` emitter documents),
38462        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
38463        // (the lower boundary of the accept-set the surrounding
38464        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
38465        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
38466        // refusals),
38467        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
38468        // (the upper boundary the same gate carves out on the sibling
38469        // `PolicyBreakerMaxFailuresExceedsCap` /
38470        // `PolicyBreakerWindowExceedsCap` refusals),
38471        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
38472        // (a past-the-guard sentinel that pins the accessor doesn't
38473        // perform a silent bounds-collapse into `None` on the
38474        // zero-failures/zero-window arm — validate rejects zero but
38475        // the accessor must ship the raw slot verbatim so a validate-
38476        // time gate regression surfaces at the emit boundary rather
38477        // than being silently absorbed), and
38478        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
38479        // (a past-the-guard sentinel that pins the accessor doesn't
38480        // perform a silent bounds-collapse at the return path).
38481        //
38482        // Second `Option<Copy-composite-T>`-return accessor pin on the
38483        // M3 mesh-slot family (peer of the sibling per-`:politicas`
38484        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
38485        // composite-Copy accessor pin, and of the sibling per-
38486        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
38487        // [`MeshPolicy::retries`] bdfb399 /
38488        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
38489        // accessor pins). Pins against a future silent detour that
38490        // re-derived the breaker declaration from a peer axis (an
38491        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
38492        // collapse that read the rate-limit's bucket capacity + refill
38493        // period as a breaker declaration), a `None → Some(default())`
38494        // cluster-default projection (which would silently re-
38495        // introduce the `PolicyBreakerZeroFailures` /
38496        // `PolicyBreakerZeroWindow` refusal cases at the emit
38497        // boundary), a bounds-collapsing accessor that clamped
38498        // `cb.max_failures` through
38499        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
38500        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
38501        // [`AplicacaoSpec::validate`] gate owns the bounds; the
38502        // accessor must ship the raw slot verbatim), or a
38503        // by-reference detour (`Option<&CircuitBreaker>`) that broke
38504        // every downstream consumer keying off `Option<CircuitBreaker>`
38505        // by-copy.
38506        for cb in [
38507            None,
38508            Some(CircuitBreaker {
38509                max_failures: 1,
38510                window: Duration::from_millis(1),
38511            }),
38512            Some(CircuitBreaker {
38513                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
38514                window: POLICY_BREAKER_WINDOW_MAX,
38515            }),
38516            Some(CircuitBreaker {
38517                max_failures: 0,
38518                window: Duration::ZERO,
38519            }),
38520            Some(CircuitBreaker {
38521                max_failures: u32::MAX,
38522                window: Duration::MAX,
38523            }),
38524        ] {
38525            let p = MeshPolicy {
38526                circuit_breaker: cb,
38527                ..MeshPolicy::default()
38528            };
38529            assert_eq!(
38530                p.circuit_breaker(),
38531                cb,
38532                "MeshPolicy::circuit_breaker must return :politicas \
38533                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
38534                p.circuit_breaker(),
38535            );
38536            assert_eq!(
38537                p.circuit_breaker(),
38538                p.circuit_breaker,
38539                "MeshPolicy::circuit_breaker must byte-equal the raw \
38540                 .circuit_breaker field access across every value in \
38541                 the accept-set",
38542            );
38543        }
38544    }
38545
38546    #[test]
38547    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
38548        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
38549        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
38550        // `.circuit_breaker` field access. Structurally: toggling ONLY
38551        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
38552        // must flip `is_empty()` from `true` (all-`None`) to `false`
38553        // (one axis carries a value); the flip must be observed for
38554        // every representative value in the accept-set the surrounding
38555        // [`AplicacaoSpec::validate_politicas`] gate accepts
38556        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
38557        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
38558        // since the emptiness semantic reads "any axis carries a
38559        // value" — not "any axis carries a value the validate gate
38560        // accepts" — the same non-collapsing shape the peer M2
38561        // [`crate::LimitsSpec::is_empty`] /
38562        // [`crate::BehaviorSpec::is_empty`] predicates carry.
38563        //
38564        // Pins against a future silent detour that re-derived the
38565        // emptiness predicate off a peer axis (an accidental
38566        // `.rate_limit.is_none()`-only chain that dropped the
38567        // `circuit_breaker` arm entirely — the last unlifted inline
38568        // field access on `is_empty` before this lift), a
38569        // `circuit_breaker == Some(_)` collapse that key-off a
38570        // validate-gate-clamped bounds check (which would silently
38571        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
38572        // 0, window: 0s })` as empty because it fails the value-shape
38573        // gate), or an accessor-side detour that no longer names the
38574        // substrate-primitive typed dispatch.
38575        //
38576        // Fifth "the emptiness predicate must route through the
38577        // substrate-primitive typed dispatch" composition pin on the
38578        // M3 mesh-slot family — closes the last unlifted composition
38579        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
38580        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
38581        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
38582        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
38583        // composition pins on the sibling primitive-Copy + composite-
38584        // Copy axes, extended onto the peer per-`:politicas`
38585        // composite-Copy `Option<CircuitBreaker>` axis).
38586        let empty = MeshPolicy::default();
38587        assert!(
38588            empty.is_empty(),
38589            "MeshPolicy::default() must be is_empty() — every axis \
38590             defaults to None",
38591        );
38592        for cb in [
38593            CircuitBreaker {
38594                max_failures: 1,
38595                window: Duration::from_millis(1),
38596            },
38597            CircuitBreaker {
38598                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
38599                window: POLICY_BREAKER_WINDOW_MAX,
38600            },
38601        ] {
38602            let p = MeshPolicy {
38603                circuit_breaker: Some(cb),
38604                ..MeshPolicy::default()
38605            };
38606            assert!(
38607                !p.is_empty(),
38608                "MeshPolicy::is_empty must return false when \
38609                 :circuit-breaker is {cb:?} — the emptiness predicate \
38610                 reads \"any axis carries a value\", not \"any axis \
38611                 carries a value the validate gate accepts\"",
38612            );
38613            assert_eq!(
38614                p.circuit_breaker().is_none(),
38615                p.is_empty(),
38616                "when :circuit-breaker is the only set axis, \
38617                 is_empty() must equal circuit_breaker().is_none() — \
38618                 the accessor and the emptiness predicate must route \
38619                 through the same substrate-primitive typed dispatch \
38620                 on the :circuit-breaker arm",
38621            );
38622        }
38623    }
38624
38625    #[test]
38626    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
38627        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
38628        // `:circuit-breaker` value-shape gate must key off
38629        // [`MeshPolicy::circuit_breaker`], not the raw
38630        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
38631        // whose only set axis is a `Some(CircuitBreaker { max_failures:
38632        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
38633        // refusal exactly, and the same MeshPolicy with the breaker at
38634        // the canonical lower boundary
38635        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
38636        // pass validate. The pair jointly pins the accessor +
38637        // validate-gate composition: any future silent detour that had
38638        // the accessor omit the `Some(CircuitBreaker { max_failures:
38639        // 0, .. })` arm (a
38640        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
38641        // collapse) would silently absorb the
38642        // `PolicyBreakerZeroFailures` refusal at the accessor
38643        // boundary — the composition pin catches that at caixa-core
38644        // build time.
38645        //
38646        // Sibling of the peer [`validate_politicas`]
38647        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
38648        // composition pins on the sibling primitive-Copy + composite-
38649        // Copy optional-scalar axes — same "the validate / shape-gate
38650        // predicate must route through the substrate-primitive typed
38651        // dispatch" discipline extended onto the peer per-`:politicas`
38652        // composite-Copy `Option<CircuitBreaker>` axis. Second
38653        // composition-with-accessor pin on the M3 mesh-slot
38654        // `Option<CircuitBreaker>` arm alongside the
38655        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
38656        let mut spec = three_member_spec();
38657        spec.politicas = MeshPolicy {
38658            circuit_breaker: Some(CircuitBreaker {
38659                max_failures: 0,
38660                window: Duration::from_millis(1),
38661            }),
38662            ..MeshPolicy::default()
38663        };
38664        assert!(
38665            matches!(
38666                spec.validate(),
38667                Err(AplicacaoError::PolicyBreakerZeroFailures)
38668            ),
38669            "validate_politicas must reject max_failures == 0 with \
38670             PolicyBreakerZeroFailures — the accessor and the validate \
38671             gate must route through the same substrate-primitive \
38672             typed dispatch on the :circuit-breaker zero-floor arm",
38673        );
38674        spec.politicas = MeshPolicy {
38675            circuit_breaker: Some(CircuitBreaker {
38676                max_failures: 1,
38677                window: Duration::from_millis(1),
38678            }),
38679            ..MeshPolicy::default()
38680        };
38681        assert!(
38682            spec.validate().is_ok(),
38683            "validate_politicas must accept a CircuitBreaker at the \
38684             canonical lower boundary (max_failures = 1, window = \
38685             1ms) — the accessor and the validate gate must route \
38686             through the same substrate-primitive typed dispatch on \
38687             the :circuit-breaker arm",
38688        );
38689    }
38690
38691    #[test]
38692    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
38693        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
38694        // Envoy-outlier-detection trip-threshold scalar pin:
38695        // [`CircuitBreaker::max_failures`] must return the
38696        // `:politicas :circuit-breaker :max-failures` typed `u32`
38697        // verbatim, byte-equal to the raw field access across every
38698        // representative value in the accept-set — `1` (the lower
38699        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
38700        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
38701        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
38702        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
38703        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
38704        // refusal), `0` (a past-the-guard sentinel that pins the accessor
38705        // doesn't perform a silent bounds-collapse into `1` on the zero
38706        // arm — validate rejects zero but the accessor must ship the
38707        // raw slot verbatim so a validate-time gate regression surfaces
38708        // at the emit boundary rather than being silently absorbed),
38709        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
38710        // doesn't perform a silent bounds-collapse through
38711        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
38712        //
38713        // First sub-struct required-scalar accessor pin on the M3
38714        // mesh-slot family — sibling in shape to the peer per-`:membros`
38715        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
38716        // (a40b0e3) required-`String`-carry accessor pins and the peer
38717        // per-`:contratos` [`WitContract::source`] /
38718        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
38719        // accessor pins, extended onto the peer per-`CircuitBreaker`
38720        // required-`u32` scalar-value axis. Pins against a future silent
38721        // detour that re-derived the trip threshold from a peer axis (an
38722        // accidental `self.window.as_secs() as u32` collapse that read
38723        // the breaker's rolling-window duration as a failure count), a
38724        // `0 → 1` cluster-default projection (which would silently absorb
38725        // the `PolicyBreakerZeroFailures` refusal case at the accessor
38726        // boundary), or a bounds-collapsing accessor that clamped the
38727        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
38728        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
38729        // must ship the raw slot verbatim).
38730        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
38731            let cb = CircuitBreaker {
38732                max_failures,
38733                window: Duration::from_secs(60),
38734            };
38735            assert_eq!(
38736                cb.max_failures(),
38737                max_failures,
38738                "CircuitBreaker::max_failures must return :politicas \
38739                 :circuit-breaker :max-failures verbatim (got {}, \
38740                 expected {max_failures})",
38741                cb.max_failures(),
38742            );
38743            assert_eq!(
38744                cb.max_failures(),
38745                cb.max_failures,
38746                "CircuitBreaker::max_failures must byte-equal the raw \
38747                 .max_failures field access across every value in the \
38748                 u32 accept-set",
38749            );
38750        }
38751    }
38752
38753    #[test]
38754    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
38755        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
38756        // `:circuit-breaker :max-failures` zero-floor arm must key off
38757        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
38758        // field access. Structurally: a `CircuitBreaker { max_failures:
38759        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
38760        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
38761        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
38762        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
38763        // pass validate. The pair jointly pins the accessor +
38764        // validate-gate composition: any future silent detour that had
38765        // the accessor return a fresh `1` on the zero arm (a
38766        // `.max_failures().max(1)` collapse) would silently absorb the
38767        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
38768        // and the validate gate would accept a struct-literal
38769        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
38770        // catches that at caixa-core build time.
38771        //
38772        // Peer of the sibling per-`:politicas`
38773        // [`MeshPolicy::mtls_required`] (c0110f1) /
38774        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
38775        // (7073d0f) accessor-composition pins on the sibling optional-
38776        // scalar axes — same "the validate / shape-gate predicate must
38777        // route through the substrate-primitive typed dispatch"
38778        // discipline extended onto the peer per-`CircuitBreaker`
38779        // required-scalar composition axis.
38780        let mut spec = three_member_spec();
38781        spec.politicas = MeshPolicy {
38782            circuit_breaker: Some(CircuitBreaker {
38783                max_failures: 0,
38784                window: Duration::from_secs(60),
38785            }),
38786            ..MeshPolicy::default()
38787        };
38788        assert!(
38789            matches!(
38790                spec.validate(),
38791                Err(AplicacaoError::PolicyBreakerZeroFailures)
38792            ),
38793            "validate_politicas must reject max_failures == 0 with \
38794             PolicyBreakerZeroFailures — the accessor and the validate \
38795             gate must route through the same substrate-primitive typed \
38796             dispatch on the :max-failures zero-floor arm",
38797        );
38798        spec.politicas = MeshPolicy {
38799            circuit_breaker: Some(CircuitBreaker {
38800                max_failures: 1,
38801                window: Duration::from_secs(60),
38802            }),
38803            ..MeshPolicy::default()
38804        };
38805        assert!(
38806            spec.validate().is_ok(),
38807            "validate_politicas must accept max_failures == 1 (the \
38808             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
38809             accept-set)",
38810        );
38811    }
38812
38813    #[test]
38814    fn circuit_breaker_max_failures_projects_u32_by_copy() {
38815        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
38816        // `u32` by copy — `u32` is `Copy` and the accessor must return
38817        // by value, not by reference. Peer of the sibling
38818        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
38819        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
38820        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
38821        // optional-scalar axes, extended onto the peer
38822        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
38823        // the accessor's returned `u32` must outlive `&self` (multiple
38824        // calls must return equal values from a dropped-`&self` copy,
38825        // since the returned scalar carries no borrow), and calling
38826        // the accessor twice on the same CircuitBreaker must yield the
38827        // same `u32` verbatim (idempotent, no side effects on `&self`).
38828        //
38829        // Pins against a future silent detour that returned `&u32`
38830        // (which would type-check but silently break every downstream
38831        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
38832        // first parameter is `u32`, and `&u32` would fold to a detached
38833        // copy at the call site with a `*` deref the sibling accessors
38834        // don't need), an accidental `.max_failures.wrapping_add(0)`
38835        // detour that returned a fresh copy through an arithmetic
38836        // no-op (breaking a future `const fn` regression), or a
38837        // one-arm-only accessor that returned a saturating value on
38838        // some sentinel input (breaking the pass-through invariant the
38839        // sibling required-scalar accessors carry).
38840        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
38841            let cb = CircuitBreaker {
38842                max_failures,
38843                window: Duration::from_secs(60),
38844            };
38845            let first = cb.max_failures();
38846            let second = cb.max_failures();
38847            assert_eq!(
38848                first, second,
38849                "CircuitBreaker::max_failures must be idempotent — two \
38850                 successive calls on the same &self must return the \
38851                 same u32",
38852            );
38853            assert_eq!(
38854                first, max_failures,
38855                "CircuitBreaker::max_failures must return :politicas \
38856                 :circuit-breaker :max-failures verbatim by copy — \
38857                 got {first}, expected {max_failures}",
38858            );
38859        }
38860    }
38861
38862    #[test]
38863    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
38864        // The canonical per-`:politicas :circuit-breaker` `:window`
38865        // Envoy-outlier-detection rolling-observation-interval scalar
38866        // pin: [`CircuitBreaker::window`] must return the
38867        // `:politicas :circuit-breaker :window` typed `Duration`
38868        // verbatim, byte-equal to the raw field access across every
38869        // representative value in the accept-set — `Duration::from_millis(1)`
38870        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
38871        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
38872        // gate carves out on the sibling `PolicyBreakerZeroWindow`
38873        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
38874        // same gate carves out on the sibling
38875        // `PolicyBreakerWindowExceedsCap` refusal),
38876        // `Duration::ZERO` (a past-the-guard sentinel that pins the
38877        // accessor doesn't perform a silent bounds-collapse into
38878        // `Duration::from_millis(1)` on the zero arm — validate rejects
38879        // zero but the accessor must ship the raw slot verbatim so a
38880        // validate-time gate regression surfaces at the emit boundary
38881        // rather than being silently absorbed),
38882        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
38883        // far above the 1h cap — that pins the accessor doesn't perform
38884        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
38885        // at the return path).
38886        //
38887        // Second sub-struct required-scalar accessor pin on the M3
38888        // mesh-slot family — sibling in shape to the just-landed
38889        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
38890        // (3a74062) required-`u32` accessor pin on the peer
38891        // per-`CircuitBreaker` required-axis, extended onto the
38892        // per-sub-struct required-`Duration` axis. Pins against a
38893        // future silent detour that re-derived the observation window
38894        // from a peer axis (an accidental
38895        // `Duration::from_secs(self.max_failures as u64)` collapse that
38896        // read the breaker's trip count as an observation-interval
38897        // duration), a `Duration::ZERO → Duration::from_millis(1)`
38898        // cluster-default projection (which would silently absorb the
38899        // `PolicyBreakerZeroWindow` refusal case at the accessor
38900        // boundary), or a bounds-collapsing accessor that clamped the
38901        // return through `POLICY_BREAKER_WINDOW_MAX` (the
38902        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
38903        // must ship the raw slot verbatim).
38904        for window in [
38905            Duration::from_millis(1),
38906            POLICY_BREAKER_WINDOW_MAX,
38907            Duration::ZERO,
38908            Duration::from_secs(86_400),
38909        ] {
38910            let cb = CircuitBreaker {
38911                max_failures: 5,
38912                window,
38913            };
38914            assert_eq!(
38915                cb.window(),
38916                window,
38917                "CircuitBreaker::window must return :politicas \
38918                 :circuit-breaker :window verbatim (got {:?}, \
38919                 expected {window:?})",
38920                cb.window(),
38921            );
38922            assert_eq!(
38923                cb.window(),
38924                cb.window,
38925                "CircuitBreaker::window must byte-equal the raw \
38926                 .window field access across every value in the \
38927                 Duration accept-set",
38928            );
38929        }
38930    }
38931
38932    #[test]
38933    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
38934        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
38935        // `:circuit-breaker :window` zero-floor arm must key off
38936        // [`CircuitBreaker::window`], not the raw `.window` field
38937        // access. Structurally: a `CircuitBreaker { window:
38938        // Duration::ZERO, .. }` embedded in a
38939        // `:politicas :circuit-breaker` slot must surface the
38940        // `PolicyBreakerZeroWindow` refusal exactly, and a
38941        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
38942        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
38943        // accept-set) must pass validate. The pair jointly pins the
38944        // accessor + validate-gate composition: any future silent
38945        // detour that had the accessor return a fresh
38946        // `Duration::from_millis(1)` on the zero arm (a
38947        // `.window().max(Duration::from_millis(1))` collapse) would
38948        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
38949        // accessor boundary and the validate gate would accept a
38950        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
38951        // — the composition pin catches that at caixa-core build time.
38952        //
38953        // Peer of the sibling per-`CircuitBreaker`
38954        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
38955        // pin on the peer required-scalar `:max-failures` axis — same
38956        // "the validate / shape-gate predicate must route through the
38957        // substrate-primitive typed dispatch" discipline extended onto
38958        // the peer per-`CircuitBreaker` required-`Duration` composition
38959        // axis.
38960        let mut spec = three_member_spec();
38961        spec.politicas = MeshPolicy {
38962            circuit_breaker: Some(CircuitBreaker {
38963                max_failures: 5,
38964                window: Duration::ZERO,
38965            }),
38966            ..MeshPolicy::default()
38967        };
38968        assert!(
38969            matches!(
38970                spec.validate(),
38971                Err(AplicacaoError::PolicyBreakerZeroWindow)
38972            ),
38973            "validate_politicas must reject window == Duration::ZERO \
38974             with PolicyBreakerZeroWindow — the accessor and the \
38975             validate gate must route through the same substrate-\
38976             primitive typed dispatch on the :window zero-floor arm",
38977        );
38978        spec.politicas = MeshPolicy {
38979            circuit_breaker: Some(CircuitBreaker {
38980                max_failures: 5,
38981                window: Duration::from_millis(1),
38982            }),
38983            ..MeshPolicy::default()
38984        };
38985        assert!(
38986            spec.validate().is_ok(),
38987            "validate_politicas must accept window == \
38988             Duration::from_millis(1) (the lower boundary of the \
38989             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
38990        );
38991    }
38992
38993    #[test]
38994    fn circuit_breaker_window_projects_duration_by_copy() {
38995        // The by-copy pin: [`CircuitBreaker::window`] returns
38996        // `Duration` by copy — `Duration` is `Copy` and the accessor
38997        // must return by value, not by reference. Peer of the sibling
38998        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
38999        // (3a74062) by-copy pin on the peer required-scalar
39000        // `:max-failures` axis, extended onto the peer
39001        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
39002        // — the accessor's returned `Duration` must outlive `&self`
39003        // (multiple calls must return equal values from a
39004        // dropped-`&self` copy, since the returned scalar carries no
39005        // borrow), and calling the accessor twice on the same
39006        // CircuitBreaker must yield the same `Duration` verbatim
39007        // (idempotent, no side effects on `&self`).
39008        //
39009        // Pins against a future silent detour that returned
39010        // `&Duration` (which would type-check but silently break every
39011        // downstream `Duration`-by-value consumer —
39012        // [`crate::render::require_positive_canonical_bounded_duration`]'s
39013        // first parameter is `Duration`, and `&Duration` would fold to
39014        // a detached copy at the call site with a `*` deref the sibling
39015        // accessors don't need), an accidental `.window + Duration::ZERO`
39016        // detour that returned a fresh copy through an arithmetic
39017        // no-op (breaking a future `const fn` regression), or a
39018        // one-arm-only accessor that returned a saturating value on
39019        // some sentinel input (breaking the pass-through invariant the
39020        // sibling required-scalar accessors carry).
39021        for window in [
39022            Duration::from_millis(1),
39023            POLICY_BREAKER_WINDOW_MAX,
39024            Duration::ZERO,
39025            Duration::from_secs(86_400),
39026        ] {
39027            let cb = CircuitBreaker {
39028                max_failures: 5,
39029                window,
39030            };
39031            let first = cb.window();
39032            let second = cb.window();
39033            assert_eq!(
39034                first, second,
39035                "CircuitBreaker::window must be idempotent — two \
39036                 successive calls on the same &self must return the \
39037                 same Duration",
39038            );
39039            assert_eq!(
39040                first, window,
39041                "CircuitBreaker::window must return :politicas \
39042                 :circuit-breaker :window verbatim by copy — \
39043                 got {first:?}, expected {window:?}",
39044            );
39045        }
39046    }
39047
39048    #[test]
39049    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
39050        // Apex-identity pair-invariant pin composing both substrate-
39051        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
39052        // and [`WitContract::destination`] — at the emit-side call shape
39053        // every per-`(:de, :para)` CNP L4 port reader now takes. The
39054        // invariant, evaluated per-edge:
39055        //
39056        //   spec.port_for_destination(c.destination()) == expected_port
39057        //
39058        // where `expected_port` is `entrada.port` when
39059        // `c.destination() == entrada.destination()` and
39060        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
39061        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
39062        // pin on the per-`:entrada` axis — that pin encodes the apex
39063        // ingress L4 identity via `entrada.destination()`; this pin
39064        // encodes the per-edge L4 identity via `c.destination()`, and
39065        // both compose on the same substrate-primitive resolver so a
39066        // future refactor that silently split either accessor's apex
39067        // behavior surfaces at caixa-core build time.
39068        let mut spec = three_member_spec();
39069        if let Some(e) = spec.entrada.as_mut() {
39070            e.para = "cart".into();
39071            e.port = 8443;
39072        }
39073        let apex_contract = WitContract {
39074            de: "checkout".into(),
39075            para: "cart".into(),
39076            wit: "wasi:http/proxy".into(),
39077            endpoint: Some("/hello".into()),
39078            subject: None,
39079            slot: None,
39080        };
39081        assert_eq!(
39082            spec.port_for_destination(apex_contract.destination()),
39083            8443,
39084            "`spec.port_for_destination(c.destination())` must equal \
39085             `entrada.port` when the contract callee names the ingress \
39086             apex — the CNP per-edge L4 port and the HTTPRoute apex \
39087             backendRef port share this substrate-primitive resolver.",
39088        );
39089        let non_apex_contract = WitContract {
39090            de: "cart".into(),
39091            para: "payment".into(),
39092            wit: "wasi:http/proxy".into(),
39093            endpoint: Some("/charge".into()),
39094            subject: None,
39095            slot: None,
39096        };
39097        assert_eq!(
39098            spec.port_for_destination(non_apex_contract.destination()),
39099            DEFAULT_SERVICO_PORT,
39100            "`spec.port_for_destination(c.destination())` must fall back \
39101             to the substrate-canonical port floor when the contract \
39102             callee is not the ingress apex — the resolver's non-apex \
39103             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
39104        );
39105    }
39106
39107    #[test]
39108    fn membro_key_consts_are_lower_camel_case_shape() {
39109        // Shape-pin: every `MEMBRO_KEY_*` const must be a
39110        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
39111        // `kebab-case` hyphens, no leading colon, no `PascalCase`
39112        // leading capital, no whitespace / dots) — the canonical shape
39113        // the `#[serde(rename_all = "camelCase")]` derive produces on
39114        // [`Membro`]. A future flip to a non-camelCase attribute at
39115        // the derive surfaces both here (this test fails on the
39116        // stale-constant shape) and at
39117        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
39118        // fails on the mismatch between const and derive). Peer with
39119        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
39120        // on the sibling `SupervisorSpec` top-level axis.
39121        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
39122            assert!(
39123                !key.is_empty(),
39124                "MEMBRO_KEY_* must be non-empty (got {key:?})"
39125            );
39126            let first = key.chars().next().unwrap();
39127            assert!(
39128                first.is_ascii_lowercase(),
39129                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
39130                 (got {key:?}, leads with {first:?})",
39131            );
39132            assert!(
39133                key.chars().all(|c| c.is_ascii_alphanumeric()),
39134                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
39135                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
39136            );
39137        }
39138    }
39139
39140    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
39141
39142    #[test]
39143    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
39144        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
39145        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
39146        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
39147        // keys the `#[serde(rename_all = "camelCase")]` attribute on
39148        // [`WitContract`] emits for the required-triad. The three
39149        // sibling payload-arm keys already pin under
39150        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
39151        // `STORE_FIELD_NAME` — pin all six alongside so a future
39152        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
39153        // verbatim-field-name flip at the derive attribute (any of which
39154        // would silently break every downstream JSON consumer that
39155        // reaches for one of the six via `Value::get(...)`) surfaces
39156        // here as a build-time test failure at `aplicacao.rs`, not as an
39157        // apply-time `.get(<stale-canonical-const>)` returning `None`
39158        // far from the derive-attr drift's commit. Peer with the sibling
39159        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
39160        // pin on the M3 `:membros` per-entry axis — same discipline the
39161        // `Membro` per-entry lift established, extended here to the
39162        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
39163        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
39164        // axis on the Aplicacao surface without a lifted serde-key peer.
39165        let c = WitContract {
39166            de: "cart".into(),
39167            para: "catalog".into(),
39168            wit: "wasi:http/proxy".into(),
39169            endpoint: Some("/lookup".into()),
39170            subject: None,
39171            slot: None,
39172        };
39173        let json = serde_json::to_string(&c).unwrap();
39174        for key in [
39175            crate::CONTRATO_KEY_DE,
39176            crate::CONTRATO_KEY_PARA,
39177            crate::CONTRATO_KEY_WIT,
39178            WitTarget::HTTP_FIELD_NAME,
39179        ] {
39180            let quoted = format!("\"{key}\"");
39181            assert!(
39182                json.contains(&quoted),
39183                "serialized WitContract must carry the lifted \
39184                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
39185                 {quoted} verbatim in the JSON emission (got: {json})",
39186            );
39187        }
39188
39189        // Pin the two remaining payload-arm keys by round-tripping a
39190        // `WitContract` under each payload-shape (pub-sub, store) — the
39191        // required-triad appears on every emission but the payload arms
39192        // only surface when their `Option<String>` field is `Some`.
39193        let pubsub = WitContract {
39194            de: "cart".into(),
39195            para: "events".into(),
39196            wit: "nats:pub-sub".into(),
39197            endpoint: None,
39198            subject: Some("orders.placed".into()),
39199            slot: None,
39200        };
39201        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
39202        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
39203        assert!(
39204            pubsub_json.contains(&pubsub_quoted),
39205            "serialized pub-sub WitContract must carry the lifted \
39206             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
39207             verbatim in the JSON emission (got: {pubsub_json})",
39208        );
39209        let store = WitContract {
39210            de: "cart".into(),
39211            para: "sessions".into(),
39212            wit: "wasi:keyvalue/store".into(),
39213            endpoint: None,
39214            subject: None,
39215            slot: Some("cart/$id".into()),
39216        };
39217        let store_json = serde_json::to_string(&store).unwrap();
39218        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
39219        assert!(
39220            store_json.contains(&store_quoted),
39221            "serialized store WitContract must carry the lifted \
39222             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
39223             verbatim in the JSON emission (got: {store_json})",
39224        );
39225    }
39226
39227    #[test]
39228    fn contrato_key_consts_are_pairwise_distinct() {
39229        // Cross-axis drift-detection pin: a future collapse of the six
39230        // canonical [`WitContract`] per-entry byte-strings onto the same
39231        // value (e.g. an accidental copy-paste flip of
39232        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
39233        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
39234        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
39235        // every downstream probe on one axis onto the sibling axis's
39236        // overlay entry and pass every propagation-probe test that
39237        // expected only the stale axis's value. Peer of the sibling
39238        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
39239        // widened here to the six-way axis the `WitContract`
39240        // required-triad + `WitTarget` payload-triad jointly cover.
39241        let all = [
39242            crate::CONTRATO_KEY_DE,
39243            crate::CONTRATO_KEY_PARA,
39244            crate::CONTRATO_KEY_WIT,
39245            WitTarget::HTTP_FIELD_NAME,
39246            WitTarget::PUBSUB_FIELD_NAME,
39247            WitTarget::STORE_FIELD_NAME,
39248        ];
39249        for (i, a) in all.iter().enumerate() {
39250            for b in all.iter().skip(i + 1) {
39251                assert_ne!(
39252                    a, b,
39253                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
39254                     must be pairwise-distinct canonical byte-sequences \
39255                     — got `{a}` == `{b}`",
39256                );
39257            }
39258        }
39259    }
39260
39261    #[test]
39262    fn contrato_key_consts_are_lower_camel_case_shape() {
39263        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
39264        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
39265        // byte-sequence (no `snake_case` underscores, no `kebab-case`
39266        // hyphens, no leading colon, no `PascalCase` leading capital, no
39267        // whitespace / dots) — the canonical shape the
39268        // `#[serde(rename_all = "camelCase")]` derive produces on
39269        // [`WitContract`]. A future flip to a non-camelCase attribute at
39270        // the derive surfaces both here (this test fails on the
39271        // stale-constant shape) and at
39272        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
39273        // (that test fails on the mismatch between const and derive).
39274        // Peer with `membro_key_consts_are_lower_camel_case_shape`
39275        // (ce80ca0) on the sibling `Membro` per-entry axis.
39276        for key in [
39277            crate::CONTRATO_KEY_DE,
39278            crate::CONTRATO_KEY_PARA,
39279            crate::CONTRATO_KEY_WIT,
39280            WitTarget::HTTP_FIELD_NAME,
39281            WitTarget::PUBSUB_FIELD_NAME,
39282            WitTarget::STORE_FIELD_NAME,
39283        ] {
39284            assert!(
39285                !key.is_empty(),
39286                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
39287                 non-empty (got {key:?})"
39288            );
39289            let first = key.chars().next().unwrap();
39290            assert!(
39291                first.is_ascii_lowercase(),
39292                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
39293                 with an ASCII-lowercase byte (got {key:?}, leads with \
39294                 {first:?})",
39295            );
39296            assert!(
39297                key.chars().all(|c| c.is_ascii_alphanumeric()),
39298                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
39299                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
39300                 whitespace (got {key:?})",
39301            );
39302        }
39303    }
39304
39305    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
39306
39307    #[test]
39308    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
39309        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
39310        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
39311        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
39312        // name the exact camelCase JSON keys the
39313        // `#[serde(rename_all = "camelCase")]` attribute on
39314        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
39315        // pin that each canonical byte-sequence appears verbatim in the
39316        // JSON — a future accidental `rename_all = "snake_case"` /
39317        // `"kebab-case"` / verbatim-field-name flip at the derive
39318        // attribute (any of which would silently break every downstream
39319        // JSON consumer that reaches for one of the four consts via
39320        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
39321        // emitter's per-Aplicacao hostname/paths/port projection, the
39322        // future `app-operator` reconciler's per-Aplicacao ingress
39323        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
39324        // materializer's admission-time cross-check) surfaces here as
39325        // a build-time test failure at `aplicacao.rs`, not as an
39326        // apply-time `.get(<stale-canonical-const>)` returning `None`
39327        // far from the derive-attr drift's commit. Peer with the
39328        // sibling
39329        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
39330        // (ca463a4) and
39331        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
39332        // pins on the M3 collection-slot atom axes — same discipline
39333        // both collection-slot lifts established, extended here to the
39334        // singleton `:entrada` mesh-slot atom axis, the last M3
39335        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
39336        // axis on the Aplicacao surface without a lifted serde-key
39337        // peer.
39338        let e = Entrada {
39339            host: "checkout.quero.cloud".into(),
39340            para: "cart".into(),
39341            paths: vec!["/cart".into()],
39342            port: 8080,
39343        };
39344        let json = serde_json::to_string(&e).unwrap();
39345        for key in [
39346            crate::ENTRADA_KEY_HOST,
39347            crate::ENTRADA_KEY_PARA,
39348            crate::ENTRADA_KEY_PATHS,
39349            crate::ENTRADA_KEY_PORT,
39350        ] {
39351            let quoted = format!("\"{key}\"");
39352            assert!(
39353                json.contains(&quoted),
39354                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
39355                 byte-sequence {quoted} verbatim in the JSON emission \
39356                 (got: {json})",
39357            );
39358        }
39359    }
39360
39361    #[test]
39362    fn entrada_key_consts_are_pairwise_distinct() {
39363        // Cross-axis drift-detection pin: a future collapse of the four
39364        // canonical [`Entrada`] singleton byte-strings onto the same
39365        // value (e.g. an accidental copy-paste flip of
39366        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
39367        // silently reroute every downstream probe on one axis onto the
39368        // sibling axis's overlay entry and pass every propagation-probe
39369        // test that expected only the stale axis's value — the
39370        // Gateway/HTTPRoute emitter would read the hostname string
39371        // where the destination-Servico name was expected (or vice
39372        // versa), the admission-webhook cross-check would compare the
39373        // wrong pair of values, and the resulting Gateway resource
39374        // would either be admitted with garbage or rejected at the
39375        // controller far from the rebrand commit's source. Peer of the
39376        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
39377        // tetrad (40cc4e5), the two-way distinct pin on the
39378        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
39379        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
39380        // triad (ca463a4).
39381        let all = [
39382            crate::ENTRADA_KEY_HOST,
39383            crate::ENTRADA_KEY_PARA,
39384            crate::ENTRADA_KEY_PATHS,
39385            crate::ENTRADA_KEY_PORT,
39386        ];
39387        for (i, a) in all.iter().enumerate() {
39388            for b in all.iter().skip(i + 1) {
39389                assert_ne!(
39390                    a, b,
39391                    "ENTRADA_KEY_* consts must be pairwise-distinct \
39392                     canonical byte-sequences — got `{a}` == `{b}`",
39393                );
39394            }
39395        }
39396    }
39397
39398    #[test]
39399    fn entrada_key_consts_are_lower_camel_case_shape() {
39400        // Shape-pin: every `ENTRADA_KEY_*` const must be a
39401        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
39402        // `kebab-case` hyphens, no leading colon, no `PascalCase`
39403        // leading capital, no whitespace / dots) — the canonical shape
39404        // the `#[serde(rename_all = "camelCase")]` derive produces on
39405        // [`Entrada`]. A future flip to a non-camelCase attribute at
39406        // the derive surfaces both here (this test fails on the
39407        // stale-constant shape) and at
39408        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
39409        // test fails on the mismatch between const and derive). Peer
39410        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
39411        // and `contrato_key_consts_are_lower_camel_case_shape`
39412        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
39413        // entry axes.
39414        for key in [
39415            crate::ENTRADA_KEY_HOST,
39416            crate::ENTRADA_KEY_PARA,
39417            crate::ENTRADA_KEY_PATHS,
39418            crate::ENTRADA_KEY_PORT,
39419        ] {
39420            assert!(
39421                !key.is_empty(),
39422                "ENTRADA_KEY_* must be non-empty (got {key:?})"
39423            );
39424            let first = key.chars().next().unwrap();
39425            assert!(
39426                first.is_ascii_lowercase(),
39427                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
39428                 (got {key:?}, leads with {first:?})",
39429            );
39430            assert!(
39431                key.chars().all(|c| c.is_ascii_alphanumeric()),
39432                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
39433                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
39434            );
39435        }
39436    }
39437
39438    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
39439
39440    #[test]
39441    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
39442        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
39443        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
39444        // [`crate::POLITICAS_KEY_RETRIES`] /
39445        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
39446        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
39447        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
39448        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
39449        // on [`MeshPolicy`] emits. Three of the five axes
39450        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
39451        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
39452        // camelCase transforms — the derive-attribute is load-bearing
39453        // on those, unlike the sibling `Entrada` / `Membro` /
39454        // `WitContract` structs whose fields are all lowercase-single-
39455        // word and where the derive is a no-op on every axis.
39456        // Serialize a fully-populated [`MeshPolicy`] (every axis
39457        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
39458        // on none of the five slots) and pin that each canonical
39459        // byte-sequence appears verbatim in the JSON — a future
39460        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
39461        // verbatim-field-name flip at the derive attribute (any of
39462        // which would silently break every downstream JSON consumer
39463        // that reaches for one of the five consts via
39464        // `Value::get(...)` — the future M4 per-edge `:politicas`
39465        // overlay projection onto Cilium `L7Rules` and Gateway API
39466        // `HTTPRoute` backend timeouts, the future
39467        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
39468        // admission-time mesh-policy cross-check, the future
39469        // `feira lint` per-`:politicas` bound-check gate) surfaces here
39470        // as a build-time test failure at `aplicacao.rs`, not as an
39471        // apply-time `.get(<stale-canonical-const>)` returning `None`
39472        // far from the derive-attr drift's commit. Peer with the
39473        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
39474        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
39475        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
39476        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
39477        // atom axes — same discipline every M3 sibling lift
39478        // established, extended here to the singleton `:politicas`
39479        // mesh-slot atom axis, closing the last M3 typed-struct
39480        // top-level `#[serde(rename_all = "camelCase")]` axis on the
39481        // Aplicacao surface without a lifted serde-key peer.
39482        let p = MeshPolicy {
39483            timeout: Some(Duration::from_secs(30)),
39484            retries: Some(3),
39485            circuit_breaker: Some(CircuitBreaker {
39486                max_failures: 5,
39487                window: Duration::from_secs(60),
39488            }),
39489            mtls_required: Some(true),
39490            rate_limit: Some(RateLimit {
39491                rate: 100,
39492                window: Duration::from_secs(1),
39493            }),
39494        };
39495        let json = serde_json::to_string(&p).unwrap();
39496        for key in [
39497            crate::POLITICAS_KEY_TIMEOUT,
39498            crate::POLITICAS_KEY_RETRIES,
39499            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
39500            crate::POLITICAS_KEY_MTLS_REQUIRED,
39501            crate::POLITICAS_KEY_RATE_LIMIT,
39502        ] {
39503            let quoted = format!("\"{key}\"");
39504            assert!(
39505                json.contains(&quoted),
39506                "serialized MeshPolicy must carry the lifted \
39507                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
39508                 JSON emission (got: {json})",
39509            );
39510        }
39511    }
39512
39513    #[test]
39514    fn politicas_key_consts_are_pairwise_distinct() {
39515        // Cross-axis drift-detection pin: a future collapse of the five
39516        // canonical [`MeshPolicy`] singleton byte-strings onto the same
39517        // value (e.g. an accidental copy-paste flip of
39518        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
39519        // would silently reroute every downstream probe on one axis
39520        // onto the sibling axis's overlay entry and pass every
39521        // propagation-probe test that expected only the stale axis's
39522        // value — the M4 per-edge `:politicas` overlay projection would
39523        // read the retry-count string where the timeout duration was
39524        // expected (or vice versa), the CR materializer's admission
39525        // cross-check would compare the wrong pair of values, and the
39526        // resulting mesh reconciler would either bind the wrong axis
39527        // or reject the resource at reconcile far from the rebrand
39528        // commit's source. Peer of the sibling four-way distinct pin
39529        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
39530        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
39531        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
39532        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
39533        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
39534        let all = [
39535            crate::POLITICAS_KEY_TIMEOUT,
39536            crate::POLITICAS_KEY_RETRIES,
39537            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
39538            crate::POLITICAS_KEY_MTLS_REQUIRED,
39539            crate::POLITICAS_KEY_RATE_LIMIT,
39540        ];
39541        for (i, a) in all.iter().enumerate() {
39542            for b in all.iter().skip(i + 1) {
39543                assert_ne!(
39544                    a, b,
39545                    "POLITICAS_KEY_* consts must be pairwise-distinct \
39546                     canonical byte-sequences — got `{a}` == `{b}`",
39547                );
39548            }
39549        }
39550    }
39551
39552    #[test]
39553    fn politicas_key_consts_are_lower_camel_case_shape() {
39554        // Shape-pin: every `POLITICAS_KEY_*` const must be a
39555        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
39556        // `kebab-case` hyphens, no leading colon, no `PascalCase`
39557        // leading capital, no whitespace / dots) — the canonical shape
39558        // the `#[serde(rename_all = "camelCase")]` derive produces on
39559        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
39560        // at the derive surfaces both here (this test fails on the
39561        // stale-constant shape) and at
39562        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
39563        // (that test fails on the mismatch between const and derive).
39564        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
39565        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
39566        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
39567        // (ca463a4) on the sibling M3 typed-struct axes.
39568        for key in [
39569            crate::POLITICAS_KEY_TIMEOUT,
39570            crate::POLITICAS_KEY_RETRIES,
39571            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
39572            crate::POLITICAS_KEY_MTLS_REQUIRED,
39573            crate::POLITICAS_KEY_RATE_LIMIT,
39574        ] {
39575            assert!(
39576                !key.is_empty(),
39577                "POLITICAS_KEY_* must be non-empty (got {key:?})"
39578            );
39579            let first = key.chars().next().unwrap();
39580            assert!(
39581                first.is_ascii_lowercase(),
39582                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
39583                 byte (got {key:?}, leads with {first:?})",
39584            );
39585            assert!(
39586                key.chars().all(|c| c.is_ascii_alphanumeric()),
39587                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
39588                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
39589            );
39590        }
39591    }
39592
39593    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
39594
39595    #[test]
39596    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
39597        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
39598        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
39599        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
39600        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
39601        // [`CircuitBreaker`] emits inside the
39602        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
39603        // two axes (`max_failures` → `maxFailures`) is a non-trivial
39604        // camelCase transform — the derive-attribute is load-bearing on
39605        // that axis, unlike the sibling `window` field where the derive
39606        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
39607        // pin that each canonical byte-sequence appears verbatim in the
39608        // JSON — a future accidental `rename_all = "snake_case"` /
39609        // `"kebab-case"` / verbatim-field-name flip at the derive
39610        // attribute (any of which would silently break every downstream
39611        // JSON consumer that reaches for one of the two consts via
39612        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
39613        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
39614        // per-edge `:politicas` overlay projection onto the mesh's
39615        // per-backend consecutive-failure-counter tripping threshold, the
39616        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
39617        // admission-time breaker cross-check, the future `feira lint`
39618        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
39619        // here as a build-time test failure at `aplicacao.rs`, not as an
39620        // apply-time `.get(<stale-canonical-const>)` returning `None`
39621        // far from the derive-attr drift's commit. Peer with the sibling
39622        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
39623        // (b55cca7) parent-axis pin — that test pins the outer
39624        // sub-block key the derive on [`MeshPolicy`] emits, this test
39625        // pins the inner keys the derive on the payload type emits, so
39626        // the two together lock the whole [`MeshPolicy`] breaker-tuning
39627        // shape end-to-end at build time.
39628        let cb = CircuitBreaker {
39629            max_failures: 5,
39630            window: Duration::from_secs(60),
39631        };
39632        let json = serde_json::to_string(&cb).unwrap();
39633        for key in [
39634            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
39635            crate::CIRCUIT_BREAKER_KEY_WINDOW,
39636        ] {
39637            let quoted = format!("\"{key}\"");
39638            assert!(
39639                json.contains(&quoted),
39640                "serialized CircuitBreaker must carry the lifted \
39641                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
39642                 in the JSON emission (got: {json})",
39643            );
39644        }
39645    }
39646
39647    #[test]
39648    fn circuit_breaker_key_consts_are_pairwise_distinct() {
39649        // Cross-axis drift-detection pin: a future collapse of the two
39650        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
39651        // same value (e.g. an accidental copy-paste flip of
39652        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
39653        // `"maxFailures"`) would silently reroute every downstream
39654        // probe on one axis onto the sibling axis's overlay entry and
39655        // pass every propagation-probe test that expected only the
39656        // stale axis's value — the M4 per-edge `:politicas` overlay
39657        // projection would read the failure-count where the window
39658        // duration was expected (or vice versa), the CR materializer's
39659        // admission cross-check would compare the wrong pair of values,
39660        // and the resulting mesh reconciler would either bind the wrong
39661        // axis or reject the resource at reconcile far from the rebrand
39662        // commit's source. Peer of the sibling five-way distinct pin on
39663        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
39664        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
39665        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
39666        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
39667        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
39668        let all = [
39669            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
39670            crate::CIRCUIT_BREAKER_KEY_WINDOW,
39671        ];
39672        for (i, a) in all.iter().enumerate() {
39673            for b in all.iter().skip(i + 1) {
39674                assert_ne!(
39675                    a, b,
39676                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
39677                     canonical byte-sequences — got `{a}` == `{b}`",
39678                );
39679            }
39680        }
39681    }
39682
39683    #[test]
39684    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
39685        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
39686        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
39687        // `kebab-case` hyphens, no leading colon, no `PascalCase`
39688        // leading capital, no whitespace / dots) — the canonical shape
39689        // the `#[serde(rename_all = "camelCase")]` derive produces on
39690        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
39691        // at the derive surfaces both here (this test fails on the
39692        // stale-constant shape) and at
39693        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
39694        // (that test fails on the mismatch between const and derive).
39695        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
39696        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
39697        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
39698        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
39699        // (ca463a4) on the sibling M3 typed-struct axes.
39700        for key in [
39701            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
39702            crate::CIRCUIT_BREAKER_KEY_WINDOW,
39703        ] {
39704            assert!(
39705                !key.is_empty(),
39706                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
39707            );
39708            let first = key.chars().next().unwrap();
39709            assert!(
39710                first.is_ascii_lowercase(),
39711                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
39712                 byte (got {key:?}, leads with {first:?})",
39713            );
39714            assert!(
39715                key.chars().all(|c| c.is_ascii_alphanumeric()),
39716                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
39717                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
39718            );
39719        }
39720    }
39721
39722    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
39723
39724    #[test]
39725    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
39726        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
39727        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
39728        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
39729        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
39730        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
39731        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
39732        // [`Placement`] emits. One of the four axes (`shard_key` →
39733        // `shardKey`) is a non-trivial camelCase transform — the
39734        // derive-attribute is load-bearing on that axis, unlike the
39735        // sibling `estrategia` / `clusters` / `affinity` axes whose
39736        // source-side field names carry no `_` and where the derive is a
39737        // no-op. Serialize a fully-populated [`Placement`] (both
39738        // `Option`-carrying axes `Some(_)` so
39739        // `skip_serializing_if = "Option::is_none"` fires on neither of
39740        // the two optional slots) and pin that each canonical
39741        // byte-sequence appears verbatim in the JSON — a future
39742        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
39743        // verbatim-field-name flip at the derive attribute (any of which
39744        // would silently break every downstream consumer that reaches
39745        // for one of the four consts via
39746        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
39747        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
39748        // aggregator's per-cluster fanout filter keying off
39749        // `placement.clusters`, the M3 shard-pool dispatch materializer
39750        // keying off `placement.shardKey`, the M3 Adaptive compression
39751        // pass weighting off `placement.affinity`, every downstream
39752        // dispatcher branching on `placement.estrategia`, the future
39753        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
39754        // admission-time placement cross-check, the future `feira lint`
39755        // per-`:placement` bound-check gate) surfaces here as a
39756        // build-time test failure at `aplicacao.rs`, not as an
39757        // apply-time `.get(<stale-canonical-const>)` returning `None`
39758        // far from the derive-attr drift's commit. Peer with the sibling
39759        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
39760        // (b55cca7),
39761        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
39762        // (468e959),
39763        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
39764        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
39765        // (ca463a4), and
39766        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
39767        // pins on the M3 collection-slot / singleton-slot atom axes —
39768        // closes the last M3 typed-struct top-level
39769        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
39770        // surface without a drift-detection pin.
39771        let p = Placement {
39772            estrategia: PlacementStrategy::Sharded,
39773            clusters: vec!["rio".into(), "mar".into()],
39774            affinity: Some("data-locality".into()),
39775            shard_key: Some("$tenantId".into()),
39776        };
39777        let json = serde_json::to_string(&p).unwrap();
39778        for key in [
39779            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
39780            crate::M3_PLACEMENT_KEY_CLUSTERS,
39781            crate::M3_PLACEMENT_KEY_AFFINITY,
39782            crate::M3_PLACEMENT_KEY_SHARD_KEY,
39783        ] {
39784            let quoted = format!("\"{key}\"");
39785            assert!(
39786                json.contains(&quoted),
39787                "serialized Placement must carry the lifted \
39788                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
39789                 the JSON emission (got: {json})",
39790            );
39791        }
39792    }
39793
39794    #[test]
39795    fn m3_placement_key_consts_are_pairwise_distinct() {
39796        // Cross-axis drift-detection pin: a future collapse of the four
39797        // canonical [`Placement`] sub-block byte-strings onto the same
39798        // value (e.g. an accidental copy-paste flip of
39799        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
39800        // `"affinity"`) would silently reroute every downstream probe on
39801        // one axis onto the sibling axis's overlay entry and pass every
39802        // propagation-probe test that expected only the stale axis's
39803        // value — the M3 shard-pool dispatch materializer would read the
39804        // affinity placement-hint where the shard-selection template was
39805        // expected (or vice versa), the M3 Adaptive compression pass's
39806        // cross-check would compare the wrong pair of values, and the
39807        // resulting placement engine would either bind the wrong axis or
39808        // reject the resource at reconcile far from the rebrand commit's
39809        // source. Peer of the sibling two-way distinct pin on the
39810        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
39811        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
39812        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
39813        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
39814        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
39815        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
39816        let all = [
39817            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
39818            crate::M3_PLACEMENT_KEY_CLUSTERS,
39819            crate::M3_PLACEMENT_KEY_AFFINITY,
39820            crate::M3_PLACEMENT_KEY_SHARD_KEY,
39821        ];
39822        for (i, a) in all.iter().enumerate() {
39823            for b in all.iter().skip(i + 1) {
39824                assert_ne!(
39825                    a, b,
39826                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
39827                     canonical byte-sequences — got `{a}` == `{b}`",
39828                );
39829            }
39830        }
39831    }
39832
39833    #[test]
39834    fn m3_placement_key_consts_are_lower_camel_case_shape() {
39835        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
39836        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
39837        // `kebab-case` hyphens, no leading colon, no `PascalCase`
39838        // leading capital, no whitespace / dots) — the canonical shape
39839        // the `#[serde(rename_all = "camelCase")]` derive produces on
39840        // [`Placement`]. A future flip to a non-camelCase attribute at
39841        // the derive surfaces both here (this test fails on the stale-
39842        // constant shape) and at
39843        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
39844        // (that test fails on the mismatch between const and derive).
39845        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
39846        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
39847        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
39848        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
39849        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
39850        // (ca463a4) on the sibling M3 typed-struct axes.
39851        for key in [
39852            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
39853            crate::M3_PLACEMENT_KEY_CLUSTERS,
39854            crate::M3_PLACEMENT_KEY_AFFINITY,
39855            crate::M3_PLACEMENT_KEY_SHARD_KEY,
39856        ] {
39857            assert!(
39858                !key.is_empty(),
39859                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
39860            );
39861            let first = key.chars().next().unwrap();
39862            assert!(
39863                first.is_ascii_lowercase(),
39864                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
39865                 byte (got {key:?}, leads with {first:?})",
39866            );
39867            assert!(
39868                key.chars().all(|c| c.is_ascii_alphanumeric()),
39869                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
39870                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
39871            );
39872        }
39873    }
39874
39875    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
39876    //    destination-facing L4 port resolver every per-Aplicacao renderer
39877    //    reaching for a per-destination Servico TCP port axis routes
39878    //    through. The four pin tests below fix the four-way accept-set
39879    //    the resolver must always honor: (:entrada-para-matches,
39880    //    :entrada-para-mismatches, :entrada-none-so-fallback,
39881    //    :entrada-port-non-default-honored) — drift on any arm surfaces
39882    //    at caixa-core build time rather than at cluster-apply time.
39883
39884    #[test]
39885    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
39886        // The typed `:entrada` block's `:para "cart"` matches the
39887        // queried destination, so the resolver returns the author-
39888        // declared `:port` scalar verbatim — the canonical "the
39889        // destination Servico IS the ingress apex, honor the typed
39890        // listener port" arm of the port-resolution dispatch.
39891        let mut spec = three_member_spec();
39892        if let Some(e) = spec.entrada.as_mut() {
39893            e.para = "cart".into();
39894            e.port = 9090;
39895        }
39896        assert_eq!(
39897            spec.port_for_destination("cart"),
39898            9090,
39899            "port_for_destination(entrada.para) must return entrada.port \
39900             verbatim, not the DEFAULT_SERVICO_PORT fallback"
39901        );
39902    }
39903
39904    #[test]
39905    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
39906        // The typed `:entrada` block names `:para "cart"`, but the
39907        // queried destination is `"payment"` — a Servico that
39908        // participates in the mesh graph but is not the ingress apex.
39909        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
39910        // canonical port floor, closing the "non-apex destination reads
39911        // the substrate default" arm. Same fixture the peer
39912        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
39913        // pin at caixa-mesh exercises through the CNP emit-side path;
39914        // this pin exercises the shared underlying resolver directly.
39915        let spec = three_member_spec();
39916        assert_eq!(
39917            spec.port_for_destination("payment"),
39918            DEFAULT_SERVICO_PORT,
39919            "port_for_destination(non-apex-destination) must route \
39920             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
39921        );
39922    }
39923
39924    #[test]
39925    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
39926        // Internal-only Aplicacao — no `:entrada` block declared. Every
39927        // per-destination port query falls back to the lifted
39928        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
39929        // the Aplicacao surface admits `:entrada None` (internal mesh
39930        // with no external gateway); every downstream renderer's per-
39931        // destination port axis must still resolve to a well-defined
39932        // scalar even without an ingress apex.
39933        let mut spec = three_member_spec();
39934        spec.entrada = None;
39935        assert_eq!(
39936            spec.port_for_destination("cart"),
39937            DEFAULT_SERVICO_PORT,
39938            "port_for_destination on an internal-only Aplicacao must \
39939             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
39940             every destination"
39941        );
39942        assert_eq!(
39943            spec.port_for_destination("payment"),
39944            DEFAULT_SERVICO_PORT,
39945            "port_for_destination on an internal-only Aplicacao must \
39946             fall back uniformly across every destination — the fallback \
39947             is not entrada-shape-conditional"
39948        );
39949    }
39950
39951    #[test]
39952    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
39953        // Structural pin against a hypothetical future refactor that
39954        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
39955        // the resolver (a "normalize to the default when the author's
39956        // port matches the substrate default" collapse) — that would
39957        // break renderer sites that carry meaning on the emitted port
39958        // value beyond bare equality (a future per-cluster listener-
39959        // audit that keys off the author-declared port, not the
39960        // resolved-with-fallback port). Pin that a non-default
39961        // entrada.port is returned verbatim so drift here surfaces at
39962        // caixa-core build time.
39963        let mut spec = three_member_spec();
39964        if let Some(e) = spec.entrada.as_mut() {
39965            e.para = "cart".into();
39966            e.port = 8443;
39967        }
39968        assert_ne!(
39969            8443, DEFAULT_SERVICO_PORT,
39970            "test fixture must probe a port distinct from \
39971             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
39972        );
39973        assert_eq!(
39974            spec.port_for_destination("cart"),
39975            8443,
39976            "port_for_destination(entrada.para) must return entrada.port \
39977             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
39978        );
39979    }
39980
39981    #[test]
39982    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
39983        // Apex-identity pair-invariant pin composing both substrate-
39984        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
39985        // and [`Entrada::destination`] — at the emit-side call shape
39986        // every per-Aplicacao renderer's ingress-apex L4 port reader
39987        // now takes. The invariant:
39988        //
39989        //   spec.port_for_destination(entrada.destination()) == entrada.port
39990        //
39991        // holds by construction under today's single-destination
39992        // `:entrada` slot (`destination()` returns `entrada.para`, and
39993        // the resolver's apex arm matches `para == destination` and
39994        // returns `entrada.port`), and every downstream consumer that
39995        // composes the two accessors at the ingress apex — the
39996        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
39997        // `backendRefs[0].port` emit-site path, the peer future M4 CR
39998        // materializer's admission-webhook that promotes the scalar to
39999        // a per-CR override overlay, every future per-Aplicacao snapshot
40000        // renderer's apex-facing L4 port reader — reaches through the
40001        // same composition. Pin the identity across four permutations
40002        // (`:para` × `:port` including a non-default port to exercise
40003        // the honor-verbatim arm and a non-cart `:para` to exercise
40004        // destination-agnostic identity) so a future refactor that
40005        // silently split either accessor's apex behavior surfaces at
40006        // caixa-core build time — a subtle `destination()` renaming
40007        // that returned `entrada.host.as_str()` instead of
40008        // `entrada.para.as_str()` would blow this pin loudly, closing
40009        // the last quiet failure mode the two lifts admit in composition.
40010        //
40011        // Peer discipline with the sibling caixa-mesh cross-crate pin
40012        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
40013        // on the two-renderer pair-invariant axis; this pin encodes the
40014        // same two-consumer coherence rule at the substrate-primitive
40015        // level so the invariant survives even if every renderer is
40016        // deleted.
40017        for (para, port) in [
40018            ("cart", DEFAULT_SERVICO_PORT),
40019            ("cart", 8443u16),
40020            ("payment", 9090u16),
40021            ("catalog", 443u16),
40022        ] {
40023            let mut spec = three_member_spec();
40024            if let Some(e) = spec.entrada.as_mut() {
40025                e.para = para.into();
40026                e.port = port;
40027            }
40028            let expected_port = spec
40029                .entrada()
40030                .expect("three_member_spec carries a typed `:entrada` block")
40031                .port();
40032            let composed_port = {
40033                let entrada = spec.entrada().expect("entrada present");
40034                spec.port_for_destination(entrada.destination())
40035            };
40036            assert_eq!(
40037                composed_port, expected_port,
40038                "`spec.port_for_destination(entrada.destination())` must \
40039                 equal `entrada.port` under today's single-destination \
40040                 `:entrada` slot — this is the apex-identity contract \
40041                 every downstream ingress-apex L4 port reader relies on. \
40042                 Input :entrada :para: {para:?}, :entrada :port: {port}"
40043            );
40044        }
40045    }
40046
40047    #[test]
40048    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
40049        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
40050        // per-`:entrada` apex-arm membership probe must key off
40051        // [`Entrada::destination`], not the raw `.para` field access.
40052        // Structurally: setting ONLY the `:entrada :para` field to a
40053        // fresh non-cart destination on an otherwise-well-formed
40054        // Aplicacao must (1) leave `e.destination()` byte-equal to
40055        // `e.para.as_str()` (the accessor is byte-projective by
40056        // definition), and (2) cause the resolver's apex arm to fire
40057        // and return `entrada.port` at exactly that new destination
40058        // while every other destination string falls through to
40059        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
40060        // membership check. Pins against a future silent detour that
40061        // (a) re-derived the apex-arm membership probe off
40062        // `e.para == destination` in `port_for_destination` instead of
40063        // `e.destination() == destination`, silently disagreeing with
40064        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
40065        // consumers (`entrada.destination()` at
40066        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
40067        // caixa-mesh/src/lib.rs:2739) that already reach through the
40068        // accessor, (b) accessor-side introduced a per-tenant alias
40069        // arm the caller was unaware of, silently rewriting an
40070        // author-declared `:para "cart"` value to a canary-aliased
40071        // form — the raw-field-access resolver would fall through to
40072        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
40073        // while the peer emit-site consumers landed on the aliased
40074        // destination, splitting the ingress-apex L4 port at
40075        // cluster-apply time.
40076        //
40077        // Peer of the sibling
40078        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
40079        // (d0de220) composition pin on the per-`:membros` refusal-arm
40080        // axis — same "the shape-gate predicate must route through the
40081        // substrate-primitive typed dispatch" discipline extended onto
40082        // the per-`:entrada` apex-arm membership-probe axis. Closes
40083        // the last unlifted `.para` production-code read site on
40084        // `Entrada` in `caixa-core` — after this converge every
40085        // `caixa-core` `.para` field access outside the accessor's own
40086        // body and outside the `WitContract` per-`:contratos` sibling
40087        // axis is either a test-side field-setter or a doc-comment
40088        // reference.
40089        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
40090            let mut spec = three_member_spec();
40091            if let Some(e) = spec.entrada.as_mut() {
40092                e.para = para.into();
40093                e.port = port;
40094            }
40095            let e = spec
40096                .entrada
40097                .as_ref()
40098                .expect("three_member_spec carries a typed `:entrada` block");
40099            assert_eq!(
40100                e.destination(),
40101                e.para.as_str(),
40102                "Entrada::destination must byte-equal the .para field \
40103                 access — an accessor-side detour that no longer \
40104                 projects the raw field would silently split this \
40105                 drift-detection test from the port_for_destination \
40106                 apex-arm membership probe",
40107            );
40108            assert_eq!(
40109                spec.port_for_destination(para),
40110                port,
40111                "port_for_destination must key off the accessor-projected \
40112                 destination and return `entrada.port` on the apex arm — \
40113                 input :entrada :para: {para:?}, :entrada :port: {port}",
40114            );
40115            assert_eq!(
40116                spec.port_for_destination("ghost-destination-never-a-member"),
40117                DEFAULT_SERVICO_PORT,
40118                "port_for_destination must fall through to \
40119                 DEFAULT_SERVICO_PORT on a non-matching destination \
40120                 under the accessor-projected membership check — input \
40121                 :entrada :para: {para:?}, :entrada :port: {port}",
40122            );
40123        }
40124    }
40125
40126    #[test]
40127    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
40128        // The canonical per-`:politicas :rate-limit` `:rate`
40129        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
40130        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
40131        // typed `u32` verbatim, byte-equal to the raw field access
40132        // across every representative value in the accept-set — `1` (the
40133        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
40134        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
40135        // carves out on the sibling `PolicyRateLimitZero` refusal),
40136        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
40137        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
40138        // `0` (a past-the-guard sentinel that pins the accessor doesn't
40139        // perform a silent bounds-collapse into `1` on the zero arm —
40140        // validate rejects zero but the accessor must ship the raw slot
40141        // verbatim so a validate-time gate regression surfaces at the
40142        // emit boundary rather than being silently absorbed), `u32::MAX`
40143        // (a past-the-guard sentinel that pins the accessor doesn't
40144        // perform a silent bounds-collapse through
40145        // `POLICY_RATE_LIMIT_MAX` at the return path).
40146        //
40147        // First sub-struct required-scalar accessor pin on the
40148        // `RateLimit` axis — sibling in shape to the peer
40149        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
40150        // required-`u32` accessor pin on the peer per-sub-struct
40151        // required-axis. Pins against a future silent detour that
40152        // re-derived the token capacity from a peer axis (an accidental
40153        // `self.window.as_secs() as u32` collapse that read the
40154        // rate-limit window duration as a token count), a `0 → 1`
40155        // cluster-default projection (which would silently absorb the
40156        // `PolicyRateLimitZero` refusal case at the accessor boundary),
40157        // or a bounds-collapsing accessor that clamped the return
40158        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
40159        // gate owns the bounds; the accessor must ship the raw slot
40160        // verbatim).
40161        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
40162            let rl = RateLimit {
40163                rate,
40164                window: Duration::from_secs(1),
40165            };
40166            assert_eq!(
40167                rl.rate(),
40168                rate,
40169                "RateLimit::rate must return :politicas :rate-limit :rate \
40170                 verbatim (got {}, expected {rate})",
40171                rl.rate(),
40172            );
40173            assert_eq!(
40174                rl.rate(),
40175                rl.rate,
40176                "RateLimit::rate must byte-equal the raw .rate field \
40177                 access across every value in the u32 accept-set",
40178            );
40179        }
40180    }
40181
40182    #[test]
40183    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
40184        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
40185        // `:rate-limit :rate` zero-floor arm must key off
40186        // [`RateLimit::rate`], not the raw `.rate` field access.
40187        // Structurally: a `RateLimit { rate: 0, window:
40188        // Duration::from_secs(1) }` embedded in a `:politicas
40189        // :rate-limit` slot must surface the `PolicyRateLimitZero`
40190        // refusal exactly, and a `RateLimit { rate: 1, window:
40191        // Duration::from_secs(1) }` (the lower boundary of the
40192        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
40193        // The pair jointly pins the accessor + validate-gate composition:
40194        // any future silent detour that had the accessor return a fresh
40195        // `1` on the zero arm (a `.rate().max(1)` collapse) would
40196        // silently absorb the `PolicyRateLimitZero` refusal at the
40197        // accessor boundary and the validate gate would accept a
40198        // struct-literal `RateLimit { rate: 0, .. }` — the composition
40199        // pin catches that at caixa-core build time.
40200        //
40201        // Peer of the sibling per-`CircuitBreaker`
40202        // [`CircuitBreaker::max_failures`] (3a74062) /
40203        // [`CircuitBreaker::window`] (373957f) accessor-composition
40204        // pins on the peer required-scalar axes — same "the validate /
40205        // shape-gate predicate must route through the substrate-primitive
40206        // typed dispatch" discipline extended onto the peer
40207        // per-`RateLimit` required-`u32` composition axis.
40208        let mut spec = three_member_spec();
40209        spec.politicas = MeshPolicy {
40210            rate_limit: Some(RateLimit {
40211                rate: 0,
40212                window: Duration::from_secs(1),
40213            }),
40214            ..MeshPolicy::default()
40215        };
40216        assert!(
40217            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
40218            "validate_politicas must reject rate == 0 with \
40219             PolicyRateLimitZero — the accessor and the validate gate \
40220             must route through the same substrate-primitive typed \
40221             dispatch on the :rate zero-floor arm",
40222        );
40223        spec.politicas = MeshPolicy {
40224            rate_limit: Some(RateLimit {
40225                rate: 1,
40226                window: Duration::from_secs(1),
40227            }),
40228            ..MeshPolicy::default()
40229        };
40230        assert!(
40231            spec.validate().is_ok(),
40232            "validate_politicas must accept rate == 1 (the lower \
40233             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
40234        );
40235    }
40236
40237    #[test]
40238    fn rate_limit_rate_projects_u32_by_copy() {
40239        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
40240        // `u32` is `Copy` and the accessor must return by value, not by
40241        // reference. Peer of the sibling per-`CircuitBreaker`
40242        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
40243        // peer required-scalar `:max-failures` axis, extended onto the
40244        // peer per-`RateLimit` required-`u32` copy-invariant shape —
40245        // the accessor's returned `u32` must outlive `&self` (multiple
40246        // calls must return equal values from a dropped-`&self` copy,
40247        // since the returned scalar carries no borrow), and calling the
40248        // accessor twice on the same RateLimit must yield the same
40249        // `u32` verbatim (idempotent, no side effects on `&self`).
40250        //
40251        // Pins against a future silent detour that returned `&u32`
40252        // (which would type-check but silently break every downstream
40253        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
40254        // first parameter is `u32`, and `&u32` would fold to a detached
40255        // copy at the call site with a `*` deref the sibling accessors
40256        // don't need), an accidental `.rate.wrapping_add(0)` detour that
40257        // returned a fresh copy through an arithmetic no-op (breaking a
40258        // future `const fn` regression), or a one-arm-only accessor
40259        // that returned a saturating value on some sentinel input
40260        // (breaking the pass-through invariant the sibling required-
40261        // scalar accessors carry).
40262        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
40263            let rl = RateLimit {
40264                rate,
40265                window: Duration::from_secs(1),
40266            };
40267            let first = rl.rate();
40268            let second = rl.rate();
40269            assert_eq!(
40270                first, second,
40271                "RateLimit::rate must be idempotent — two successive \
40272                 calls on the same &self must return the same u32",
40273            );
40274            assert_eq!(
40275                first, rate,
40276                "RateLimit::rate must return :politicas :rate-limit :rate \
40277                 verbatim by copy — got {first}, expected {rate}",
40278            );
40279        }
40280    }
40281
40282    #[test]
40283    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
40284        // The canonical per-`:politicas :rate-limit` `:window`
40285        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
40286        // pin: [`RateLimit::window`] must return the
40287        // `:politicas :rate-limit :window` typed `Duration` verbatim,
40288        // byte-equal to the raw field access across every
40289        // representative value in the accept-set — `Duration::from_secs(1)`
40290        // (the `"s"` canonical window, the lower row of
40291        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
40292        // [`AplicacaoSpec::validate_politicas`] gate accepts via
40293        // [`is_canonical_rate_limit_window`]),
40294        // `Duration::from_secs(60)` (the `"m"` canonical window, the
40295        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
40296        // window, the upper row), `Duration::ZERO` (a past-the-guard
40297        // sentinel that pins the accessor doesn't perform a silent
40298        // bounds-collapse into `Duration::from_secs(1)` on the zero
40299        // arm — validate rejects an off-set window through
40300        // `PolicyRateLimitWindowNotCanonical` but the accessor must
40301        // ship the raw slot verbatim so a validate-time gate
40302        // regression surfaces at the emit boundary rather than being
40303        // silently absorbed), `Duration::from_millis(500)` (a
40304        // sub-canonical past-the-guard sentinel that pins the accessor
40305        // doesn't silently normalize a non-canonical fractional
40306        // magnitude onto the nearest canonical row).
40307        //
40308        // Second sub-struct required-scalar accessor pin on the
40309        // `RateLimit` axis — sibling in shape to the just-landed
40310        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
40311        // accessor pin on the peer per-sub-struct required-axis,
40312        // extended onto the per-`RateLimit` required-`Duration` axis.
40313        // Pins against a future silent detour that re-derived the
40314        // refill period from a peer axis (an accidental
40315        // `Duration::from_secs(self.rate as u64)` collapse that read
40316        // the rate-limit token capacity as a refill-interval
40317        // duration), a `Duration::ZERO → Duration::from_secs(1)`
40318        // canonical-default projection (which would silently absorb
40319        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
40320        // accessor boundary), or a canonical-set-collapsing accessor
40321        // that clamped the return through [`rate_limit_window_unit`]
40322        // (the `AplicacaoSpec::validate` gate owns the canonical-set
40323        // membership; the accessor must ship the raw slot verbatim).
40324        for window in [
40325            Duration::from_secs(1),
40326            Duration::from_secs(60),
40327            Duration::from_secs(3600),
40328            Duration::ZERO,
40329            Duration::from_millis(500),
40330        ] {
40331            let rl = RateLimit { rate: 100, window };
40332            assert_eq!(
40333                rl.window(),
40334                window,
40335                "RateLimit::window must return :politicas :rate-limit :window \
40336                 verbatim (got {:?}, expected {window:?})",
40337                rl.window(),
40338            );
40339            assert_eq!(
40340                rl.window(),
40341                rl.window,
40342                "RateLimit::window must byte-equal the raw .window field \
40343                 access across every value in the Duration accept-set",
40344            );
40345        }
40346    }
40347
40348    #[test]
40349    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
40350        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
40351        // `:rate-limit :window` canonical-set arm must key off
40352        // [`RateLimit::window`], not the raw `.window` field access.
40353        // Structurally: a `RateLimit { window: Duration::from_millis(500),
40354        // .. }` embedded in a `:politicas :rate-limit` slot must
40355        // surface the `PolicyRateLimitWindowNotCanonical` refusal
40356        // exactly (with the sub-canonical `Duration::from_millis(500)`
40357        // magnitude carried through verbatim), and a `RateLimit
40358        // { window: Duration::from_secs(1), .. }` (the lower row of
40359        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
40360        // The pair jointly pins the accessor + validate-gate
40361        // composition: any future silent detour that had the accessor
40362        // normalize the off-set window to the nearest canonical row
40363        // (a `.window().max(Duration::from_secs(1))` collapse, or a
40364        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
40365        // collapse) would silently absorb the
40366        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
40367        // boundary — including a drift in the error's `window` payload
40368        // (the emit-side diagnostic reader keys off the offending
40369        // magnitude verbatim, so a normalization at the accessor
40370        // boundary would silently pin the wrong magnitude in the
40371        // refusal). The composition pin catches that at caixa-core
40372        // build time.
40373        //
40374        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
40375        // (7f81a60) accessor-composition pin on the peer required-
40376        // scalar `:rate` axis — same "the validate / shape-gate
40377        // predicate must route through the substrate-primitive typed
40378        // dispatch, and the error payload must project through the
40379        // same accessor" discipline extended onto the peer
40380        // per-`RateLimit` required-`Duration` composition axis.
40381        let mut spec = three_member_spec();
40382        spec.politicas = MeshPolicy {
40383            rate_limit: Some(RateLimit {
40384                rate: 100,
40385                window: Duration::from_millis(500),
40386            }),
40387            ..MeshPolicy::default()
40388        };
40389        match spec.validate() {
40390            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
40391                assert_eq!(
40392                    window,
40393                    Duration::from_millis(500),
40394                    "PolicyRateLimitWindowNotCanonical must carry the \
40395                     offending :window magnitude verbatim through the \
40396                     accessor — got {window:?}, expected 500ms",
40397                );
40398            }
40399            other => panic!(
40400                "validate_politicas must reject non-canonical :window \
40401                 with PolicyRateLimitWindowNotCanonical — the accessor \
40402                 and the validate gate must route through the same \
40403                 substrate-primitive typed dispatch on the :window \
40404                 canonical-set arm; got {other:?}",
40405            ),
40406        }
40407        spec.politicas = MeshPolicy {
40408            rate_limit: Some(RateLimit {
40409                rate: 100,
40410                window: Duration::from_secs(1),
40411            }),
40412            ..MeshPolicy::default()
40413        };
40414        assert!(
40415            spec.validate().is_ok(),
40416            "validate_politicas must accept window == Duration::from_secs(1) \
40417             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
40418        );
40419    }
40420
40421    #[test]
40422    fn rate_limit_window_projects_duration_by_copy() {
40423        // The by-copy pin: [`RateLimit::window`] returns `Duration`
40424        // by copy — `Duration` is `Copy` and the accessor must return
40425        // by value, not by reference. Peer of the sibling per-`RateLimit`
40426        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
40427        // required-scalar `:rate` axis, extended onto the peer
40428        // per-`RateLimit` required-`Duration` copy-invariant shape —
40429        // the accessor's returned `Duration` must outlive `&self`
40430        // (multiple calls must return equal values from a
40431        // dropped-`&self` copy, since the returned scalar carries no
40432        // borrow), and calling the accessor twice on the same
40433        // RateLimit must yield the same `Duration` verbatim
40434        // (idempotent, no side effects on `&self`).
40435        //
40436        // Pins against a future silent detour that returned
40437        // `&Duration` (which would type-check but silently break every
40438        // downstream `Duration`-by-value consumer —
40439        // [`is_canonical_rate_limit_window`]'s first parameter is
40440        // `Duration`, and `&Duration` would fold to a detached copy at
40441        // the call site with a `*` deref the sibling accessors don't
40442        // need), an accidental `.window + Duration::ZERO` detour that
40443        // returned a fresh copy through an arithmetic no-op (breaking
40444        // a future `const fn` regression), or a one-arm-only accessor
40445        // that returned a canonical fallback on some sentinel input
40446        // (breaking the pass-through invariant the sibling required-
40447        // scalar accessors carry).
40448        for window in [
40449            Duration::from_secs(1),
40450            Duration::from_secs(60),
40451            Duration::from_secs(3600),
40452            Duration::ZERO,
40453            Duration::from_millis(500),
40454        ] {
40455            let rl = RateLimit { rate: 100, window };
40456            let first = rl.window();
40457            let second = rl.window();
40458            assert_eq!(
40459                first, second,
40460                "RateLimit::window must be idempotent — two successive \
40461                 calls on the same &self must return the same Duration",
40462            );
40463            assert_eq!(
40464                first, window,
40465                "RateLimit::window must return :politicas :rate-limit :window \
40466                 verbatim by copy — got {first:?}, expected {window:?}",
40467            );
40468        }
40469    }
40470
40471    #[test]
40472    fn placement_estrategia_default_pins_m3_canonical_value() {
40473        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
40474        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
40475        // active-active-across-every-named-cluster arm, the closest
40476        // canonical M3 production reference the substrate carries and
40477        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
40478        // for every un-`:placement`-declared Aplicacao. Pinning the arm
40479        // here surfaces a future rebrand of the M3-canonical
40480        // distribution default (a widening to `Sharded` once the
40481        // substrate discovers hash-keyed distribution as the more
40482        // common production shape, a tightening to `SingleNode` for
40483        // stateful Erlang/OTP distributed-app-takeover semantics
40484        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
40485        // operator pins through a future `:placement-overrides` slot)
40486        // as a deliberate test edit, not a silent contract migration.
40487        // Peer of the sibling M2 per-supervisor value pins
40488        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
40489        // /
40490        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
40491        // extended onto the M3 mesh-primitive-defining `:placement
40492        // :estrategia` axis.
40493        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
40494    }
40495
40496    #[test]
40497    fn placement_strategy_default_routes_through_lifted_default() {
40498        // Composition pin: the [`Default for PlacementStrategy`] impl's
40499        // return arm must route through the substrate-canonical
40500        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
40501        // a raw `Self::Replicated` arm. Prior to the lift the impl
40502        // carried an inline `Self::Replicated` arm with no compile-time
40503        // link back to the shared M3-canonical `Replicated` arm the
40504        // paired [`Default for Placement`] impl's struct-literal
40505        // `estrategia` field, the serde-side `#[serde(default)]` on
40506        // [`Placement::estrategia`] that resolves an author-omitted
40507        // wire-form `:placement :estrategia` scalar through the impl,
40508        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
40509        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
40510        // routes through [`Placement::default`] which routes through the
40511        // strategy default) all key off — so a future rebrand of the
40512        // M3-canonical distribution default would have had to be threaded
40513        // through the `Default` impl and the three peer routes in
40514        // lockstep or the four consumers would silently split. Byte-
40515        // parity against the lifted constant closes the split. Peer of
40516        // the sibling
40517        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
40518        // /
40519        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
40520        // composition pins on the M2 per-supervisor axes.
40521        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
40522    }
40523
40524    #[test]
40525    fn placement_default_estrategia_routes_through_lifted_default() {
40526        // Composition pin: the [`Default for Placement`] impl's
40527        // struct-literal `estrategia` field must route through the
40528        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
40529        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
40530        // impl that the sibling
40531        // `placement_strategy_default_routes_through_lifted_default` pin
40532        // already routes onto the constant). Structurally: every
40533        // `Placement::default()` call must yield an `estrategia` field
40534        // byte-equal to the lifted constant so the two paired defaults —
40535        // the [`Default for PlacementStrategy`] impl arm and the
40536        // struct-literal default arm here — cannot silently split on any
40537        // future M3-canonical distribution-default rebrand. Peer of the
40538        // sibling M2
40539        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
40540        // byte-parity pin on the [`Default for SupervisorSpec`]
40541        // struct-literal `estrategia` field extended onto the M3
40542        // mesh-primitive-defining slot family.
40543        assert_eq!(
40544            Placement::default().estrategia,
40545            PLACEMENT_ESTRATEGIA_DEFAULT,
40546        );
40547    }
40548
40549    #[test]
40550    fn placement_serde_default_estrategia_routes_through_lifted_default() {
40551        // Composition pin: the serde-side `#[serde(default)]` on
40552        // [`Placement::estrategia`] — the wire-format author-omitted
40553        // `:placement :estrategia` arm — must resolve onto the substrate-
40554        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
40555        // (via the [`Default for PlacementStrategy`] impl the sibling
40556        // `placement_strategy_default_routes_through_lifted_default` pin
40557        // already routes onto the constant). Structurally: a `Placement`
40558        // deserialized from a payload that omits the `estrategia` key
40559        // must yield an `estrategia` field byte-equal to the lifted
40560        // constant, so the wire-format author-omitted arm and the
40561        // [`PlacementStrategy::default`] impl arm cannot silently split
40562        // on any future M3-canonical distribution-default rebrand. Peer
40563        // of the sibling M2
40564        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
40565        // byte-parity pin on the wire-format author-omitted `:children
40566        // :restart` scalar extended onto the M3 mesh-primitive-defining
40567        // slot family.
40568        let omitted: Placement = serde_json::from_str("{}")
40569            .expect("Placement must deserialize with the estrategia key omitted");
40570        assert_eq!(
40571            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
40572            "an author-omitted :placement :estrategia slot must degrade onto \
40573             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
40574             {:?}, expected {:?})",
40575            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
40576        );
40577    }
40578
40579    // ── contrato_target_ctors! fold pins ────────────────────────────────
40580    //
40581    // Fixture edge triple + payload-field-name label pair for every
40582    // `contrato_target_ctors!`-generated ctor pin below. Kept as
40583    // non-default `("cart", "catalog", "wasi:http/proxy")` +
40584    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
40585    // the fixture default doesn't silently pass. Peer of the sibling
40586    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
40587    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
40588    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
40589    // `missing_entry_ctor_matches_struct_literal_wrap` /
40590    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
40591    // four `LayoutError` constructor families each closed on their
40592    // sibling envelopes.
40593    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
40594        (
40595            "cart".to_string(),
40596            "catalog".to_string(),
40597            "wasi:http/proxy".to_string(),
40598            WitTarget::HTTP_FIELD_NAME,
40599        )
40600    }
40601
40602    #[test]
40603    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
40604        // Equivalence pin: the ctor produces byte-equal
40605        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
40606        // coded struct-literal on the same edge fixture, so the fold
40607        // cannot silently drift on any future field-addition /
40608        // reordering / string-conversion tweak on the variant. Peer of
40609        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
40610        // (17dd504) / the four `LayoutError` family equivalence pins.
40611        let (de, para, wit, expected) = contrato_target_ctor_fixture();
40612        let lifted = AplicacaoError::contrato_wrong_target(
40613            (de.clone(), para.clone(), wit.clone()),
40614            expected,
40615        );
40616        let struct_literal = AplicacaoError::ContratoWrongTarget {
40617            de,
40618            para,
40619            wit,
40620            expected,
40621        };
40622        assert_eq!(lifted, struct_literal);
40623    }
40624
40625    #[test]
40626    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
40627        // Equivalence pin peer of the sibling
40628        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
40629        // on the paired `ContratoMissingTarget` variant of the same
40630        // four-slot envelope shape the `contrato_target_ctors!` macro
40631        // closes.
40632        let (de, para, wit, expected) = contrato_target_ctor_fixture();
40633        let lifted = AplicacaoError::contrato_missing_target(
40634            (de.clone(), para.clone(), wit.clone()),
40635            expected,
40636        );
40637        let struct_literal = AplicacaoError::ContratoMissingTarget {
40638            de,
40639            para,
40640            wit,
40641            expected,
40642        };
40643        assert_eq!(lifted, struct_literal);
40644    }
40645
40646    #[test]
40647    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
40648        // Routing pin: the `(de, para, wit)` triple threads verbatim
40649        // onto same-named fields on both generated ctors, no wrapper-
40650        // side lowercase / trim / re-order. Sweeps a non-default triple
40651        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
40652        // wrapper-side transformation surfaces here rather than at a
40653        // downstream diagnostic-shape drift. Sibling of
40654        // `entrada_host_invalid_ctor_routes_host_through_to_string`
40655        // (17dd504) on the paired triple-carrying envelope.
40656        let edge = (
40657            "cart-svc".to_string(),
40658            "catalog-v2".to_string(),
40659            "nats:pub-sub".to_string(),
40660        );
40661        let wrong =
40662            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
40663        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
40664        let AplicacaoError::ContratoWrongTarget {
40665            de: wde,
40666            para: wpara,
40667            wit: wwit,
40668            ..
40669        } = wrong
40670        else {
40671            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
40672        };
40673        let AplicacaoError::ContratoMissingTarget {
40674            de: mde,
40675            para: mpara,
40676            wit: mwit,
40677            ..
40678        } = missing
40679        else {
40680            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
40681        };
40682        assert_eq!(wde, "cart-svc");
40683        assert_eq!(wpara, "catalog-v2");
40684        assert_eq!(wwit, "nats:pub-sub");
40685        assert_eq!(mde, "cart-svc");
40686        assert_eq!(mpara, "catalog-v2");
40687        assert_eq!(mwit, "nats:pub-sub");
40688    }
40689
40690    #[test]
40691    fn contrato_target_ctors_route_expected_through_verbatim() {
40692        // Routing pin: the `expected: &'static str` label threads
40693        // verbatim (identity, not copy-and-transform) onto the
40694        // `expected` field of both variants, so the four canonical
40695        // labels [`WitTarget::HTTP_FIELD_NAME`] /
40696        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
40697        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
40698        // pointer-equal (not merely value-equal) references — a wrapper-
40699        // side `.to_string()` / `Cow::Owned` promotion would break the
40700        // `&'static str` contract downstream consumers depend on.
40701        for label in [
40702            WitTarget::HTTP_FIELD_NAME,
40703            WitTarget::PUBSUB_FIELD_NAME,
40704            WitTarget::STORE_FIELD_NAME,
40705            WitTarget::CAPABILITY_EXPECTED,
40706        ] {
40707            let (de, para, wit, _) = contrato_target_ctor_fixture();
40708            let wrong = AplicacaoError::contrato_wrong_target(
40709                (de.clone(), para.clone(), wit.clone()),
40710                label,
40711            );
40712            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
40713            match wrong {
40714                AplicacaoError::ContratoWrongTarget { expected, .. } => {
40715                    assert!(
40716                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
40717                            && expected.len() == label.len(),
40718                        "contrato_wrong_target must thread the &'static str \
40719                         label pointer-equal onto the `expected` field \
40720                         (label = {label:?})",
40721                    );
40722                }
40723                other => panic!("expected ContratoWrongTarget, got {other:?}"),
40724            }
40725            match missing {
40726                AplicacaoError::ContratoMissingTarget { expected, .. } => {
40727                    assert!(
40728                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
40729                            && expected.len() == label.len(),
40730                        "contrato_missing_target must thread the &'static \
40731                         str label pointer-equal onto the `expected` field \
40732                         (label = {label:?})",
40733                    );
40734                }
40735                other => panic!("expected ContratoMissingTarget, got {other:?}"),
40736            }
40737        }
40738    }
40739
40740    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
40741    //
40742    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
40743    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
40744    // byte-equality mistake against the fixture default doesn't silently
40745    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
40746    // triple + expected-label envelope on
40747    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
40748    // struct_literal_wrap` (17dd504, host + reason envelope on
40749    // `entrada_host_invalid`) / the four `LayoutError` family
40750    // equivalence pins.
40751    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
40752        ("cart".to_string(), "catalog".to_string())
40753    }
40754
40755    #[test]
40756    fn empty_wit_ctor_matches_struct_literal_wrap() {
40757        // Equivalence pin: the ctor produces byte-equal
40758        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
40759        // struct-literal on the same edge pair, so the fold cannot
40760        // silently drift on any future field-addition / reordering /
40761        // string-conversion tweak on the variant. Peer of the sibling
40762        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
40763        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
40764        // (17dd504) / the four `LayoutError` family equivalence pins.
40765        let (de, para) = contrato_empty_pair_ctor_fixture();
40766        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
40767        let struct_literal = AplicacaoError::EmptyWit { de, para };
40768        assert_eq!(lifted, struct_literal);
40769    }
40770
40771    #[test]
40772    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
40773        // Equivalence pin peer of the sibling
40774        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
40775        // paired `ContratoEndpointEmpty` variant of the same two-slot
40776        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
40777        let (de, para) = contrato_empty_pair_ctor_fixture();
40778        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
40779        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
40780        assert_eq!(lifted, struct_literal);
40781    }
40782
40783    #[test]
40784    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
40785        // Equivalence pin peer of the sibling
40786        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
40787        // above on the paired `ContratoSubjectEmpty` variant of the
40788        // same two-slot envelope shape.
40789        let (de, para) = contrato_empty_pair_ctor_fixture();
40790        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
40791        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
40792        assert_eq!(lifted, struct_literal);
40793    }
40794
40795    #[test]
40796    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
40797        // Equivalence pin peer of the sibling
40798        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
40799        // above on the paired `ContratoSlotEmpty` variant of the same
40800        // two-slot envelope shape.
40801        let (de, para) = contrato_empty_pair_ctor_fixture();
40802        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
40803        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
40804        assert_eq!(lifted, struct_literal);
40805    }
40806
40807    #[test]
40808    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
40809        // Routing pin: the `(de, para)` pair threads verbatim onto
40810        // same-named fields on all four generated ctors, no wrapper-
40811        // side lowercase / trim / re-order. Sweeps a non-default pair
40812        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
40813        // transformation surfaces here rather than at a downstream
40814        // diagnostic-shape drift. Sibling of
40815        // `contrato_target_ctors_route_edge_triple_through_verbatim`
40816        // (14b81d5) on the paired triple-carrying envelope and of
40817        // `entrada_host_invalid_ctor_routes_host_through_to_string`
40818        // (17dd504) on the sibling `{ host, reason }` envelope.
40819        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
40820        let variants: [(AplicacaoError, &'static str); 4] = [
40821            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
40822            (
40823                AplicacaoError::contrato_endpoint_empty(edge.clone()),
40824                "ContratoEndpointEmpty",
40825            ),
40826            (
40827                AplicacaoError::contrato_subject_empty(edge.clone()),
40828                "ContratoSubjectEmpty",
40829            ),
40830            (
40831                AplicacaoError::contrato_slot_empty(edge.clone()),
40832                "ContratoSlotEmpty",
40833            ),
40834        ];
40835        for (built, label) in variants {
40836            let (de, para) = match built {
40837                AplicacaoError::EmptyWit { de, para }
40838                | AplicacaoError::ContratoEndpointEmpty { de, para }
40839                | AplicacaoError::ContratoSubjectEmpty { de, para }
40840                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
40841                other => panic!("expected {label} pair variant, got {other:?}"),
40842            };
40843            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
40844            assert_eq!(
40845                para, "catalog-v2",
40846                "para field on {label} must thread verbatim",
40847            );
40848        }
40849    }
40850
40851    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
40852    //
40853    // Fixture edge pair + value + reason for every
40854    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
40855    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
40856    // fixed per-axis `<val>` / reason so a byte-equality mistake against
40857    // the fixture default doesn't silently pass. Peer of the sibling
40858    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
40859    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
40860    // (14b81d5, triple + expected-label envelope on
40861    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
40862    // struct_literal_wrap` (17dd504, host + reason envelope on
40863    // `entrada_host_invalid`).
40864    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
40865        ("cart".to_string(), "catalog".to_string())
40866    }
40867
40868    #[test]
40869    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
40870        // Equivalence pin: the ctor produces byte-equal
40871        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
40872        // open-coded struct-literal on the same
40873        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
40874        // silently drift on any future field-addition / reordering /
40875        // string-conversion tweak on the variant. Peer of the sibling
40876        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
40877        // (8580068) on the paired two-slot envelope of the same
40878        // `{ de, para, ... }` prefix, and of
40879        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
40880        // (17dd504) on the sibling `{ <field>: String, reason: String }`
40881        // two-slot envelope.
40882        let (de, para) = contrato_pair_value_reason_ctor_fixture();
40883        let endpoint = "/charge";
40884        let reason = "sample reason text";
40885        let lifted =
40886            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
40887        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
40888            de,
40889            para,
40890            endpoint: endpoint.to_string(),
40891            reason: reason.to_string(),
40892        };
40893        assert_eq!(lifted, struct_literal);
40894    }
40895
40896    #[test]
40897    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
40898        // Equivalence pin peer of the sibling
40899        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
40900        // above on the paired `ContratoSubjectInvalid` variant of the
40901        // same four-slot envelope shape the
40902        // `contrato_pair_value_reason_ctors!` macro closes.
40903        let (de, para) = contrato_pair_value_reason_ctor_fixture();
40904        let subject = "checkout.events.charge.failed";
40905        let reason = "sample reason text";
40906        let lifted =
40907            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
40908        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
40909            de,
40910            para,
40911            subject: subject.to_string(),
40912            reason: reason.to_string(),
40913        };
40914        assert_eq!(lifted, struct_literal);
40915    }
40916
40917    #[test]
40918    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
40919        // Equivalence pin peer of the sibling
40920        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
40921        // above on the paired `ContratoSlotInvalid` variant of the same
40922        // four-slot envelope shape.
40923        let (de, para) = contrato_pair_value_reason_ctor_fixture();
40924        let slot = "checkout/$orderId";
40925        let reason = "sample reason text";
40926        let lifted =
40927            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
40928        let struct_literal = AplicacaoError::ContratoSlotInvalid {
40929            de,
40930            para,
40931            slot: slot.to_string(),
40932            reason: reason.to_string(),
40933        };
40934        assert_eq!(lifted, struct_literal);
40935    }
40936
40937    #[test]
40938    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
40939        // Equivalence pin peer of the sibling
40940        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
40941        // on the paired `ContratoWitInvalid` variant of the same four-
40942        // slot envelope shape the `contrato_pair_value_reason_ctors!`
40943        // macro closes. Fold pinned this test lands with the last
40944        // `{ de, para, <field>: String, reason: String }` open-coded
40945        // struct-literal inside [`WitContract::target`] rewritten to
40946        // route through the macro-generated
40947        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
40948        // between the ctor and the pre-lift struct-literal trips this
40949        // pin ahead of any downstream diagnostic-shape drift on the
40950        // `:contratos :wit` axis.
40951        let (de, para) = contrato_pair_value_reason_ctor_fixture();
40952        let wit = "wasi-http/proxy";
40953        let reason = "sample reason text";
40954        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
40955        let struct_literal = AplicacaoError::ContratoWitInvalid {
40956            de,
40957            para,
40958            wit: wit.to_string(),
40959            reason: reason.to_string(),
40960        };
40961        assert_eq!(lifted, struct_literal);
40962    }
40963
40964    #[test]
40965    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
40966        // Routing pin: the `(de, para)` pair threads verbatim onto
40967        // same-named fields on all four generated ctors, no wrapper-
40968        // side lowercase / trim / re-order. Sweeps a non-default pair
40969        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
40970        // transformation surfaces here rather than at a downstream
40971        // diagnostic-shape drift. Sibling of
40972        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
40973        // (8580068) on the paired two-slot envelope and of
40974        // `contrato_target_ctors_route_edge_triple_through_verbatim`
40975        // (14b81d5) on the paired triple-carrying envelope.
40976        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
40977        let variants: [(AplicacaoError, &'static str); 4] = [
40978            (
40979                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
40980                "ContratoEndpointInvalid",
40981            ),
40982            (
40983                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
40984                "ContratoSubjectInvalid",
40985            ),
40986            (
40987                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
40988                "ContratoSlotInvalid",
40989            ),
40990            (
40991                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
40992                "ContratoWitInvalid",
40993            ),
40994        ];
40995        for (built, label) in variants {
40996            let (de, para) = match built {
40997                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
40998                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
40999                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
41000                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
41001                other => panic!("expected {label} pair variant, got {other:?}"),
41002            };
41003            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
41004            assert_eq!(
41005                para, "catalog-v2",
41006                "para field on {label} must thread verbatim",
41007            );
41008        }
41009    }
41010
41011    #[test]
41012    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
41013        // Cross-arm invariance pin — the four ctors all route
41014        // `reason: impl Into<String>` verbatim onto their respective
41015        // typed variants through the shared
41016        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
41017        // pair (`&str` literal, `format!` output) against every ctor to
41018        // pin that no per-arm wrapper transformation drifted in against
41019        // the uniform macro-generated body. Peer of
41020        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
41021        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
41022        let edge = || ("cart".to_string(), "catalog".to_string());
41023        let via_literal = "literal reason text";
41024        let via_format = format!("{} reason text", "literal");
41025        assert_eq!(
41026            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
41027            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
41028        );
41029        assert_eq!(
41030            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
41031            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
41032        );
41033        assert_eq!(
41034            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
41035            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
41036        );
41037        assert_eq!(
41038            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
41039            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
41040        );
41041    }
41042
41043    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
41044    //
41045    // Fail-before-pass-after pins for the standalone
41046    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
41047    // (see the paired doc-block above the ctor definition) — the fold of
41048    // the last open-coded three-slot `{ de, para, endpoint: <val>
41049    // .to_string() }` struct-literal inside [`WitContract::target`]'s
41050    // HTTP-arm leading-slash gate onto one substrate primitive on the
41051    // envelope. A byte-mismatched ctor body would trip the equivalence
41052    // pin first, ahead of any downstream diagnostic-shape drift.
41053    //
41054    // Peer of the sibling standalone-ctor equivalence pins on the peer
41055    // one-off variants across caixa-core:
41056    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
41057    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
41058    // on the paired two-slot and four-slot per-`:contratos :endpoint`
41059    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
41060    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
41061    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
41062    // reason }` two- and three-slot envelopes; the
41063    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
41064    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
41065    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
41066        ("cart".to_string(), "catalog".to_string())
41067    }
41068
41069    #[test]
41070    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
41071        // Equivalence pin: the ctor produces byte-equal
41072        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
41073        // open-coded struct-literal on the same `(edge_pair, endpoint)`
41074        // pair, so the fold cannot silently drift on any future
41075        // field-addition / reordering / string-conversion tweak on the
41076        // variant. Same equivalence-pin shape as the sibling
41077        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
41078        // (8580068) on the paired two-slot envelope and
41079        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
41080        // (14e13f1) on the paired four-slot envelope of the same
41081        // `{ de, para, ... }`-prefix `:endpoint` axis.
41082        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
41083        let endpoint = "charge";
41084        let lifted =
41085            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
41086        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
41087            de,
41088            para,
41089            endpoint: endpoint.to_string(),
41090        };
41091        assert_eq!(lifted, struct_literal);
41092    }
41093
41094    #[test]
41095    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
41096        // Routing pin on the `(de, para)` axis: sweep a non-default
41097        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
41098        // lowercase / trim / re-order surfaces here rather than at a
41099        // downstream diagnostic-shape drift. Peer of
41100        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
41101        // (8580068) on the paired two-slot envelope and
41102        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
41103        // (14e13f1) on the paired four-slot envelope of the same
41104        // `{ de, para, ... }`-prefix `:contratos` axis.
41105        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
41106        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
41107        match built {
41108            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
41109                assert_eq!(de, "cart-svc", "de field must thread verbatim");
41110                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
41111            }
41112            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
41113        }
41114    }
41115
41116    #[test]
41117    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
41118        // Routing pin on the `endpoint: &str` axis: sweep a non-default
41119        // value (`"charge"` — no leading `/`, the exact shape the
41120        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
41121        // through the sole payload-carrier constructor axis so any
41122        // wrapper-side transformation on the `endpoint.to_string()`
41123        // one-field construction surfaces here rather than at a
41124        // downstream diagnostic-shape mismatch. Sibling of
41125        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
41126        // (14e13f1) on the sibling four-slot envelope's payload-carrier
41127        // routing pin.
41128        let edge = || ("cart".to_string(), "catalog".to_string());
41129        let via_literal = "charge";
41130        let via_string = String::from("charge");
41131        assert_eq!(
41132            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
41133            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
41134        );
41135    }
41136
41137    // ── contrato_self_loop standalone ctor pins ─────────────────────────
41138    //
41139    // Fail-before-pass-after pins for the standalone
41140    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
41141    // doc-block above the ctor definition) — the fold of the last
41142    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
41143    // <ct>.world_ref().to_string() }` struct-literal inside
41144    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
41145    // arm onto one substrate primitive on the [`AplicacaoError`]
41146    // envelope, projecting through the paired [`WitContract::source`] /
41147    // [`WitContract::world_ref`] scalar accessors on the substrate
41148    // primitive. A byte-mismatched ctor body would trip the equivalence
41149    // pin first, ahead of any downstream diagnostic-shape drift.
41150    //
41151    // Peer of the sibling standalone-ctor equivalence pins on the peer
41152    // one-off variants across caixa-core:
41153    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
41154    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
41155    // envelope, the sibling
41156    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
41157    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
41158    // the paired two-slot and four-slot per-`:contratos :endpoint`
41159    // envelopes, and the sibling
41160    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
41161    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
41162    fn contrato_self_loop_ctor_fixture() -> WitContract {
41163        WitContract {
41164            de: "cart".to_string(),
41165            para: "cart".to_string(),
41166            wit: "wasi:http/proxy".to_string(),
41167            endpoint: Some("/self".to_string()),
41168            subject: None,
41169            slot: None,
41170        }
41171    }
41172
41173    #[test]
41174    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
41175        // Equivalence pin: the ctor produces byte-equal
41176        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
41177        // struct-literal that read the same two fields through
41178        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
41179        // any future field-addition / reordering / string-conversion
41180        // tweak on the variant. Same equivalence-pin shape as the
41181        // sibling `contrato_endpoint_not_absolute_ctor_matches_
41182        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
41183        // per-`:contratos :endpoint` envelope.
41184        let contract = contrato_self_loop_ctor_fixture();
41185        let lifted = AplicacaoError::contrato_self_loop(&contract);
41186        let struct_literal = AplicacaoError::ContratoSelfLoop {
41187            caixa: contract.source().to_string(),
41188            wit: contract.world_ref().to_string(),
41189        };
41190        assert_eq!(lifted, struct_literal);
41191    }
41192
41193    #[test]
41194    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
41195        // Routing pin sweeping non-default `caixa` and `:wit` values
41196        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
41197        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
41198        // axes so any wrapper-side lowercase / trim / re-order surfaces
41199        // here rather than at a downstream diagnostic-shape drift.
41200        // Peer of the sibling
41201        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
41202        // (cdf1a2c) routing pin on the sibling three-slot envelope.
41203        let contract = WitContract {
41204            de: "catalog-v2".to_string(),
41205            para: "catalog-v2".to_string(),
41206            wit: "nats:pub-sub".to_string(),
41207            endpoint: None,
41208            subject: Some("orders.>".to_string()),
41209            slot: None,
41210        };
41211        let built = AplicacaoError::contrato_self_loop(&contract);
41212        match built {
41213            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
41214                assert_eq!(
41215                    caixa, "catalog-v2",
41216                    "caixa slot must thread WitContract::source() verbatim"
41217                );
41218                assert_eq!(
41219                    wit, "nats:pub-sub",
41220                    "wit slot must thread WitContract::world_ref() verbatim"
41221                );
41222            }
41223            other => panic!("expected ContratoSelfLoop, got {other:?}"),
41224        }
41225    }
41226
41227    #[test]
41228    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
41229        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
41230        // [`WitContract::source`] accessor (matching the pre-lift open-
41231        // coded body's field selection), not [`WitContract::destination`].
41232        // Under today's `WitContract::is_self_loop()`-gated call site
41233        // the two are equal by that predicate's own contract, but a
41234        // future consumer that constructs the ctor against a not-yet-
41235        // gated candidate contract — an M4
41236        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
41237        // checking a per-`(:de, :para)`-patched candidate before the
41238        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
41239        // resolver rejecting a self-edge introduced by a cluster-local
41240        // `:contratos` override — needs the pre-lift field selection
41241        // pinned so a silent `.destination()` swap at the ctor body
41242        // surfaces here rather than at a downstream diagnostic mis-
41243        // attribution far from the self-loop diagnostic's owner
41244        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
41245        // direction).
41246        //
41247        // Deliberately constructs a non-self-loop pair (`"cart" →
41248        // "catalog"`) so the two accessors yield distinct bytes on the
41249        // fixture — a `.destination()` swap at the ctor body would land
41250        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
41251        // the assertion here.
41252        let contract = WitContract {
41253            de: "cart".to_string(),
41254            para: "catalog".to_string(),
41255            wit: "wasi:http/proxy".to_string(),
41256            endpoint: Some("/charge".to_string()),
41257            subject: None,
41258            slot: None,
41259        };
41260        let built = AplicacaoError::contrato_self_loop(&contract);
41261        match built {
41262            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
41263                assert_eq!(
41264                    caixa, "cart",
41265                    "caixa slot must project WitContract::source() (not destination)"
41266                );
41267            }
41268            other => panic!("expected ContratoSelfLoop, got {other:?}"),
41269        }
41270    }
41271
41272    // Pin the four-slot `{ de, para, wit, target }` per-`:contratos`
41273    // whole-edge-dedup sibling of the two-slot per-`:contratos` envelope
41274    // family — the sole per-axis ctor projecting through both
41275    // [`WitContract::edge_triple`] (on the leading `de` / `para` / `wit`
41276    // triple) and [`WitTarget::label`] (on the trailing `target` slot).
41277    // Equivalence pin locks the ctor body to the pre-lift struct-literal
41278    // shape under `PartialEq`, so any accessor-side field-selection drift
41279    // or per-arm wrapper transformation surfaces here as a build-time
41280    // test failure rather than at a downstream diagnostic-shape mismatch
41281    // far from the substrate primitive. Peer of the sibling
41282    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe)
41283    // equivalence pin on the paired two-slot `{ caixa, wit }` per-self-
41284    // edge envelope's `WitContract`-projection ctor.
41285    #[test]
41286    fn contrato_duplicate_ctor_matches_struct_literal_wrap() {
41287        let contract = contrato_self_loop_ctor_fixture();
41288        let target = contract.target_projected();
41289        let lifted = AplicacaoError::contrato_duplicate(&contract, &target);
41290        let (de, para, wit) = contract.edge_triple();
41291        let struct_literal = AplicacaoError::ContratoDuplicate {
41292            de,
41293            para,
41294            wit,
41295            target: target.label(),
41296        };
41297        assert_eq!(lifted, struct_literal);
41298    }
41299
41300    // Routing pin sweeping a non-self-loop pair (`"cart" → "catalog"`) so
41301    // the paired [`WitContract::edge_triple`] projection's three axes
41302    // (`de`, `para`, `wit`) and the [`WitTarget::label`] projection on
41303    // the `target` axis all yield distinct bytes on the fixture — any
41304    // wrapper-side re-order / accessor-swap on the four axes surfaces
41305    // here rather than at a downstream diagnostic-shape drift. Peer of
41306    // the sibling
41307    // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
41308    // (b30edfe) routing pin on the paired two-slot envelope.
41309    #[test]
41310    fn contrato_duplicate_ctor_routes_edge_triple_and_target_label_verbatim() {
41311        let contract = WitContract {
41312            de: "cart".to_string(),
41313            para: "catalog".to_string(),
41314            wit: "wasi:http/proxy".to_string(),
41315            endpoint: Some("/charge".to_string()),
41316            subject: None,
41317            slot: None,
41318        };
41319        let target = contract.target_projected();
41320        let built = AplicacaoError::contrato_duplicate(&contract, &target);
41321        match built {
41322            AplicacaoError::ContratoDuplicate {
41323                de,
41324                para,
41325                wit,
41326                target,
41327            } => {
41328                assert_eq!(
41329                    de, "cart",
41330                    "de slot must thread WitContract::edge_triple().0 verbatim"
41331                );
41332                assert_eq!(
41333                    para, "catalog",
41334                    "para slot must thread WitContract::edge_triple().1 verbatim"
41335                );
41336                assert_eq!(
41337                    wit, "wasi:http/proxy",
41338                    "wit slot must thread WitContract::edge_triple().2 verbatim"
41339                );
41340                assert!(
41341                    target.contains("/charge"),
41342                    "target slot must project through WitTarget::label() \
41343                     (got target = {target:?})"
41344                );
41345            }
41346            other => panic!("expected ContratoDuplicate, got {other:?}"),
41347        }
41348    }
41349
41350    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
41351    // macro definition (see the paired doc-block above the macro definition)
41352    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
41353    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
41354    // struct-literal onto one substrate primitive. The four per-variant
41355    // equivalence pins below (fail-before-pass-after by construction — a
41356    // byte-mismatched macro arm would trip its equivalence pin first) lock
41357    // each generated constructor to its struct-literal peer under
41358    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
41359    // [`AplicacaoSpec::validate_membros`], and
41360    // [`validate_no_self_membership`] on that variant produces a byte-equal
41361    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
41362    // cross-axis pin that follows (non-default caixa name) routes the sole
41363    // constructor input axis through `.to_string()`, so the fold does not
41364    // silently collapse onto a fixed name.
41365    //
41366    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
41367    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
41368    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
41369    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
41370    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
41371    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
41372    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
41373    // of the peer M2 `:behavior` envelope fold (67c31ec,
41374    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
41375    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
41376    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
41377
41378    #[test]
41379    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
41380        assert_eq!(
41381            AplicacaoError::contrato_member_missing("cart"),
41382            AplicacaoError::ContratoMemberMissing {
41383                caixa: "cart".to_string(),
41384            },
41385            "generated contrato_member_missing ctor must produce byte-equal \
41386             AplicacaoError to the open-coded struct-literal wrap on the \
41387             same &str fixture",
41388        );
41389    }
41390
41391    #[test]
41392    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
41393        assert_eq!(
41394            AplicacaoError::membro_versao_empty("cart"),
41395            AplicacaoError::MembroVersaoEmpty {
41396                caixa: "cart".to_string(),
41397            },
41398            "generated membro_versao_empty ctor must produce byte-equal \
41399             AplicacaoError to the open-coded struct-literal wrap on the \
41400             same &str fixture",
41401        );
41402    }
41403
41404    #[test]
41405    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
41406        assert_eq!(
41407            AplicacaoError::membro_duplicate("cart"),
41408            AplicacaoError::MembroDuplicate {
41409                caixa: "cart".to_string(),
41410            },
41411            "generated membro_duplicate ctor must produce byte-equal \
41412             AplicacaoError to the open-coded struct-literal wrap on the \
41413             same &str fixture",
41414        );
41415    }
41416
41417    #[test]
41418    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
41419        assert_eq!(
41420            AplicacaoError::membro_is_self_aplicacao("checkout"),
41421            AplicacaoError::MembroIsSelfAplicacao {
41422                caixa: "checkout".to_string(),
41423            },
41424            "generated membro_is_self_aplicacao ctor must produce byte-equal \
41425             AplicacaoError to the open-coded struct-literal wrap on the \
41426             same &str fixture",
41427        );
41428    }
41429
41430    #[test]
41431    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
41432        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
41433        // &str`) through a non-default fixture name against every generated
41434        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
41435        // wrapper-side lowercase / trim / truncate / re-order on the
41436        // `caixa.to_string()` sole-field construction surfaces here rather
41437        // than at a downstream diagnostic-shape mismatch. Peer of the
41438        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
41439        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
41440        // envelope (db09650), extended here onto the peer `AplicacaoError`
41441        // `{ caixa: String }` envelope so every substrate-primitive ctor
41442        // family in caixa-core carrying a single-slot `{ caixa: String }`
41443        // shape guarantees the sole-field construction routes the caller's
41444        // `&str` through `.to_string()` verbatim.
41445        let name = "cache-v2";
41446        assert_eq!(
41447            AplicacaoError::contrato_member_missing(name),
41448            AplicacaoError::ContratoMemberMissing {
41449                caixa: name.to_string(),
41450            },
41451        );
41452        assert_eq!(
41453            AplicacaoError::membro_versao_empty(name),
41454            AplicacaoError::MembroVersaoEmpty {
41455                caixa: name.to_string(),
41456            },
41457        );
41458        assert_eq!(
41459            AplicacaoError::membro_duplicate(name),
41460            AplicacaoError::MembroDuplicate {
41461                caixa: name.to_string(),
41462            },
41463        );
41464        assert_eq!(
41465            AplicacaoError::membro_is_self_aplicacao(name),
41466            AplicacaoError::MembroIsSelfAplicacao {
41467                caixa: name.to_string(),
41468            },
41469        );
41470    }
41471
41472    #[test]
41473    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
41474        assert_eq!(
41475            AplicacaoError::entrada_path_not_absolute("api/cart"),
41476            AplicacaoError::EntradaPathNotAbsolute {
41477                path: "api/cart".to_string(),
41478            },
41479            "generated entrada_path_not_absolute ctor must produce byte-equal \
41480             AplicacaoError to the open-coded struct-literal wrap on the \
41481             same &str fixture",
41482        );
41483    }
41484
41485    #[test]
41486    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
41487        assert_eq!(
41488            AplicacaoError::entrada_path_duplicate("/api/cart"),
41489            AplicacaoError::EntradaPathDuplicate {
41490                path: "/api/cart".to_string(),
41491            },
41492            "generated entrada_path_duplicate ctor must produce byte-equal \
41493             AplicacaoError to the open-coded struct-literal wrap on the \
41494             same &str fixture",
41495        );
41496    }
41497
41498    // ── membro_versao_invalid ctor pins ────────────────────────────────
41499    //
41500    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
41501    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
41502    // produces an `AplicacaoError` structurally identical to the pre-lift
41503    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
41504    // versao.to_string(), reason: reason.into() }` open-coded three-slot
41505    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
41506    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
41507    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
41508    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
41509    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
41510    // extended here onto the paired per-`:membros :versao` axis on the
41511    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
41512    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
41513    // typed-error surface guarantee the shared three-field construction
41514    // routes through one substrate primitive per envelope.
41515
41516    #[test]
41517    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
41518        let caixa = "cart";
41519        let versao = "not-a-req";
41520        let reason = "sample reason text";
41521        assert_eq!(
41522            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
41523            AplicacaoError::MembroVersaoInvalid {
41524                caixa: caixa.to_string(),
41525                versao: versao.to_string(),
41526                reason: reason.to_string(),
41527            },
41528            "lifted membro_versao_invalid ctor must produce byte-equal \
41529             AplicacaoError to the open-coded struct-literal wrap on the \
41530             same (&str, &str, reason) fixture",
41531        );
41532    }
41533
41534    #[test]
41535    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
41536        // Cross-axis pin: sweep the two `&str`-shaped constructor input
41537        // axes (`caixa`, `versao`) through non-default fixtures so any
41538        // wrapper-side lowercase / trim / truncate / re-order on either
41539        // `.to_string()` field construction surfaces here rather than at
41540        // a downstream diagnostic-shape mismatch. Peer of the sibling
41541        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
41542        // routing pin on the peer `SupervisorError` envelope.
41543        let caixa = "Cart-V2";
41544        let versao = "0.1.0-alpha+build.42";
41545        let reason = "constructed reason";
41546        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
41547        let AplicacaoError::MembroVersaoInvalid {
41548            caixa: got_caixa,
41549            versao: got_versao,
41550            reason: got_reason,
41551        } = err
41552        else {
41553            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
41554        };
41555        assert_eq!(got_caixa, caixa.to_string());
41556        assert_eq!(got_versao, versao.to_string());
41557        assert_eq!(got_reason, reason.to_string());
41558    }
41559
41560    #[test]
41561    fn membro_versao_invalid_ctor_routes_reason_through_into() {
41562        // Route pin: the `reason: impl Into<String>` bound accepts both
41563        // `&str` literals and `format!(…)` / `String` outputs verbatim,
41564        // matching the sibling
41565        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
41566        // routing pin on the peer `SupervisorError::child_versao_invalid`.
41567        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
41568        // `require_valid_versao_requirement`-delivered `reason` closure
41569        // parameter (typed `String`) picks the ctor up without a per-arm
41570        // wrapper transformation, and every future consumer that
41571        // constructs the variant from a `format!(…)` reason surfaces
41572        // byte-equal to the `&str`-literal path.
41573        let caixa = "cart";
41574        let versao = "not-a-req";
41575        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
41576        let from_format =
41577            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
41578        let from_string =
41579            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
41580        assert_eq!(from_literal, from_format);
41581        assert_eq!(from_literal, from_string);
41582    }
41583
41584    #[test]
41585    fn aplicacao_path_only_ctors_route_path_through_to_string() {
41586        // Cross-axis pin: sweep the sole constructor input axis (`path:
41587        // &str`) through a non-default fixture path against every generated
41588        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
41589        // wrapper-side lowercase / trim / truncate / re-order on the
41590        // `path.to_string()` sole-field construction surfaces here rather
41591        // than at a downstream diagnostic-shape mismatch. Peer of the
41592        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
41593        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
41594        // envelope (d9f6867), extended here onto the sibling
41595        // `AplicacaoError` `{ path: String }` envelope so every substrate-
41596        // primitive ctor family in caixa-core carrying a single-slot
41597        // `{ <slot>: String }` shape guarantees the sole-field construction
41598        // routes the caller's `&str` through `.to_string()` verbatim.
41599        let path = "/api/v2/checkout";
41600        assert_eq!(
41601            AplicacaoError::entrada_path_not_absolute(path),
41602            AplicacaoError::EntradaPathNotAbsolute {
41603                path: path.to_string(),
41604            },
41605        );
41606        assert_eq!(
41607            AplicacaoError::entrada_path_duplicate(path),
41608            AplicacaoError::EntradaPathDuplicate {
41609                path: path.to_string(),
41610            },
41611        );
41612    }
41613
41614    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
41615    //
41616    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
41617    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
41618    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
41619    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
41620    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
41621    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
41622    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
41623    // substitution on any one variant surfaces here rather than at a downstream
41624    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
41625    // pins on `aplicacao_field_reason_ctors!` (981060b),
41626    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
41627    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
41628    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
41629    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
41630    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
41631    // per-envelope ctor-macro pins.
41632
41633    #[test]
41634    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
41635        let timeout = Duration::from_micros(1_500);
41636        assert_eq!(
41637            AplicacaoError::policy_timeout_not_canonical(timeout),
41638            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
41639            "generated policy_timeout_not_canonical ctor must produce byte-equal \
41640             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
41641             struct-literal wrap on the same `Copy`-`Duration` fixture",
41642        );
41643    }
41644
41645    #[test]
41646    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
41647        let timeout = Duration::from_secs(3_601);
41648        assert_eq!(
41649            AplicacaoError::policy_timeout_exceeds_cap(timeout),
41650            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
41651            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
41652             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
41653             struct-literal wrap on the same `Copy`-`Duration` fixture",
41654        );
41655    }
41656
41657    #[test]
41658    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
41659        let retries = 47_u32;
41660        assert_eq!(
41661            AplicacaoError::policy_retries_exceeds_cap(retries),
41662            AplicacaoError::PolicyRetriesExceedsCap { retries },
41663            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
41664             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
41665             struct-literal wrap on the same `Copy`-`u32` fixture",
41666        );
41667    }
41668
41669    #[test]
41670    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
41671        let max_failures = 1_337_u32;
41672        assert_eq!(
41673            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
41674            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
41675            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
41676             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
41677             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
41678        );
41679    }
41680
41681    #[test]
41682    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
41683        let window = Duration::from_micros(500);
41684        assert_eq!(
41685            AplicacaoError::policy_breaker_window_not_canonical(window),
41686            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
41687            "generated policy_breaker_window_not_canonical ctor must produce \
41688             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
41689             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
41690        );
41691    }
41692
41693    #[test]
41694    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
41695        let window = Duration::from_secs(3_700);
41696        assert_eq!(
41697            AplicacaoError::policy_breaker_window_exceeds_cap(window),
41698            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
41699            "generated policy_breaker_window_exceeds_cap ctor must produce \
41700             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
41701             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
41702        );
41703    }
41704
41705    #[test]
41706    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
41707        let rate = 1_000_001_u32;
41708        assert_eq!(
41709            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
41710            AplicacaoError::PolicyRateLimitExceedsCap { rate },
41711            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
41712             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
41713             struct-literal wrap on the same `Copy`-`u32` fixture",
41714        );
41715    }
41716
41717    #[test]
41718    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
41719        let window = Duration::from_secs(15);
41720        assert_eq!(
41721            AplicacaoError::policy_rate_limit_window_not_canonical(window),
41722            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
41723            "generated policy_rate_limit_window_not_canonical ctor must produce \
41724             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
41725             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
41726             fixture",
41727        );
41728    }
41729
41730    #[test]
41731    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
41732        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
41733        // constructor input axis through a non-default `Copy` fixture against
41734        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
41735        // wrapper-side silent `.into()` / silent constant-substitution / silent
41736        // field re-name away from the canonical `timeout | retries |
41737        // max_failures | window | rate` axes on any one variant, or a
41738        // `Duration | u32` axis silently rerouted through some other `Copy`
41739        // coercion, surfaces here rather than at a downstream per-`:politicas`
41740        // diagnostic-shape drift. Peer of the sibling
41741        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
41742        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
41743        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
41744        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
41745        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
41746        // families, extended here onto the last M3 per-`:politicas` per-axis
41747        // `AplicacaoError` variant family folded onto a substrate primitive.
41748        //
41749        // Fixtures picked out of each variant's accept-set boundary rather
41750        // than the default value so a silent constant-substitution to `0` /
41751        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
41752        // structural-equality assertion. The two `Duration` fixtures pick the
41753        // sub-millisecond and above-cap ends respectively; the three `u32`
41754        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
41755        // `rate` respectively (each variant's cap sits well below the fixture
41756        // so the pre-lift struct-literal wrap the fixture is compared against
41757        // is the same shape the pre-lift wire-up produced).
41758        let sub_ms = Duration::from_micros(1_500);
41759        let above_hour = Duration::from_secs(3_700);
41760        let non_canonical_rl_window = Duration::from_secs(15);
41761        assert_eq!(
41762            AplicacaoError::policy_timeout_not_canonical(sub_ms),
41763            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
41764        );
41765        assert_eq!(
41766            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
41767            AplicacaoError::PolicyTimeoutExceedsCap {
41768                timeout: above_hour,
41769            },
41770        );
41771        assert_eq!(
41772            AplicacaoError::policy_retries_exceeds_cap(47),
41773            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
41774        );
41775        assert_eq!(
41776            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
41777            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
41778                max_failures: 1_337,
41779            },
41780        );
41781        assert_eq!(
41782            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
41783            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
41784        );
41785        assert_eq!(
41786            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
41787            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
41788        );
41789        assert_eq!(
41790            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
41791            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
41792        );
41793        assert_eq!(
41794            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
41795            AplicacaoError::PolicyRateLimitWindowNotCanonical {
41796                window: non_canonical_rl_window,
41797            },
41798        );
41799    }
41800
41801    #[test]
41802    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
41803        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
41804        // every generated ctor `const fn` so a caller can pin an
41805        // `AplicacaoError` at compile time — the same zero-runtime-work
41806        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
41807        // closure carried on its `Copy`-pass-through construction path (no
41808        // `.to_string()` / `.into()` allocation, no branching). If any future
41809        // edit silently drops the `const` qualifier from the macro body the
41810        // per-arm `const` bindings below fail to compile, which surfaces the
41811        // regression at the substrate-primitive definition rather than at
41812        // some downstream consumer that had come to rely on the `const`-
41813        // constructibility. Peer of the sibling per-variant
41814        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
41815        // equality axis; this pin closes the compile-time-const axis on the
41816        // same generated family.
41817        const TIMEOUT_NC: AplicacaoError =
41818            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
41819        const TIMEOUT_CAP: AplicacaoError =
41820            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
41821        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
41822        const MAX_FAIL_CAP: AplicacaoError =
41823            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
41824        const CB_WIN_NC: AplicacaoError =
41825            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
41826        const CB_WIN_CAP: AplicacaoError =
41827            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
41828        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
41829        const RL_WIN_NC: AplicacaoError =
41830            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
41831        assert!(matches!(
41832            TIMEOUT_NC,
41833            AplicacaoError::PolicyTimeoutNotCanonical { .. }
41834        ));
41835        assert!(matches!(
41836            TIMEOUT_CAP,
41837            AplicacaoError::PolicyTimeoutExceedsCap { .. }
41838        ));
41839        assert!(matches!(
41840            RETRIES_CAP,
41841            AplicacaoError::PolicyRetriesExceedsCap { .. }
41842        ));
41843        assert!(matches!(
41844            MAX_FAIL_CAP,
41845            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
41846        ));
41847        assert!(matches!(
41848            CB_WIN_NC,
41849            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
41850        ));
41851        assert!(matches!(
41852            CB_WIN_CAP,
41853            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
41854        ));
41855        assert!(matches!(
41856            RATE_CAP,
41857            AplicacaoError::PolicyRateLimitExceedsCap { .. }
41858        ));
41859        assert!(matches!(
41860            RL_WIN_NC,
41861            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
41862        ));
41863    }
41864
41865    // Per-variant equivalence + routing pins for the
41866    // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
41867    // (see the paired doc-block above the ctor definition) — the
41868    // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
41869    // Self` inherent constructor folds the uniform
41870    // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
41871    // one-field struct-literal onto one substrate primitive. Same
41872    // shape as the sibling
41873    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
41874    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
41875    // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
41876    // ctors — extended here onto the single-slot per-`:placement
41877    // :clusters` dedup-envelope.
41878
41879    #[test]
41880    fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
41881        // Equivalence pin: the ctor produces byte-equal
41882        // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
41883        // open-coded struct-literal that read the same field through
41884        // `c.clone()` at the caller site inside
41885        // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
41886        // field-addition / reordering / string-conversion tweak on the
41887        // variant.
41888        let cluster = "rio";
41889        let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
41890        let struct_literal = AplicacaoError::PlacementClusterDuplicate {
41891            cluster: cluster.to_string(),
41892        };
41893        assert_eq!(lifted, struct_literal);
41894    }
41895
41896    #[test]
41897    fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
41898        // Routing pin: sweep the sole constructor input axis
41899        // (`cluster: &str`) through a non-default fixture name so any
41900        // wrapper-side lowercase / trim / truncate / re-order on the
41901        // `cluster.to_string()` sole-field construction surfaces here
41902        // rather than at a downstream diagnostic-shape mismatch. Peer of
41903        // the sibling
41904        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
41905        // (d9f6867) cross-axis pin on the sibling one-slot
41906        // `{ caixa: String }` envelope — extended here onto the sibling
41907        // `{ cluster: String }` envelope so the sole `String`-slot
41908        // construction routes the caller's `&str` through `.to_string()`
41909        // verbatim.
41910        let cluster = "sao-paulo-2";
41911        let built = AplicacaoError::placement_cluster_duplicate(cluster);
41912        match built {
41913            AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
41914                assert_eq!(
41915                    c, cluster,
41916                    "cluster slot must thread the caller's `&str` verbatim through .to_string()"
41917                );
41918            }
41919            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
41920        }
41921    }
41922
41923    // Per-variant equivalence + routing pins for the
41924    // [`AplicacaoError::placement_without_clusters`] standalone ctor
41925    // (see the paired doc-block above the ctor definition) — the
41926    // generated `pub const fn placement_without_clusters(placement:
41927    // &Placement) -> Self` inherent constructor folds the uniform
41928    // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
41929    // }` one-field `Copy`-pass-through struct-literal onto one substrate
41930    // primitive. Same shape as the sibling
41931    // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
41932    // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
41933    // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
41934    // ctors — extended here onto the one-slot per-`:placement`
41935    // empty-clusters envelope.
41936
41937    #[test]
41938    fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
41939        // Equivalence pin: the ctor produces byte-equal
41940        // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
41941        // open-coded struct-literal that read the same field through
41942        // `p.estrategia()` at the caller site inside
41943        // [`AplicacaoSpec::validate_placement`]. Guards any future
41944        // field-addition / reordering / accessor-return tweak on the
41945        // variant.
41946        let placement = Placement {
41947            estrategia: PlacementStrategy::Replicated,
41948            clusters: vec![],
41949            affinity: None,
41950            shard_key: None,
41951        };
41952        let lifted = AplicacaoError::placement_without_clusters(&placement);
41953        let struct_literal = AplicacaoError::PlacementWithoutClusters {
41954            estrategia: placement.estrategia(),
41955        };
41956        assert_eq!(lifted, struct_literal);
41957    }
41958
41959    #[test]
41960    fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
41961        // Routing pin: sweep the sole constructor input axis
41962        // (`placement: &Placement`) through every variant in the closed
41963        // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
41964        // re-derivation / off-by-one arm-swap / stale-field read on the
41965        // `placement.estrategia()` sole-field projection surfaces here
41966        // rather than at a downstream diagnostic-shape mismatch. Peer of
41967        // the sibling
41968        // `validate_placement_reads_through_lifted_estrategia_accessor`
41969        // three-consumer coherence pin — extended here onto the ctor
41970        // itself so the accessor-projection posture is byte-witnessed at
41971        // the substrate primitive rather than only at the caller-site
41972        // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
41973        // future addition to the closed accept-set surfaces as an
41974        // exhaustiveness gap on this iteration list.
41975        for estrategia in [
41976            PlacementStrategy::SingleNode,
41977            PlacementStrategy::Replicated,
41978            PlacementStrategy::Sharded,
41979        ] {
41980            let placement = Placement {
41981                estrategia,
41982                clusters: vec![],
41983                affinity: None,
41984                shard_key: None,
41985            };
41986            let built = AplicacaoError::placement_without_clusters(&placement);
41987            match built {
41988                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
41989                    assert_eq!(
41990                        e,
41991                        placement.estrategia(),
41992                        "estrategia slot must thread the caller's `Placement` verbatim \
41993                         through Placement::estrategia() — the ctor reads through the \
41994                         lifted accessor",
41995                    );
41996                    assert_eq!(
41997                        e, estrategia,
41998                        "estrategia slot must byte-equal the fixture-declared variant",
41999                    );
42000                }
42001                other => panic!("expected PlacementWithoutClusters, got {other:?}"),
42002            }
42003        }
42004    }
42005
42006    #[test]
42007    fn placement_without_clusters_ctor_is_const_fn() {
42008        // Fail-before-pass-after pin on
42009        // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
42010        // surface posture. The ctor threads the paired
42011        // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
42012        // return through one `const fn` construction — any future
42013        // accidental downgrade to non-`const` (a `.clone()` on the
42014        // `Copy`-scalar `estrategia:` field expression, an owned-`String`
42015        // materialization on the sibling non-`estrategia:` axis) fails
42016        // `placement_without_clusters_via_const_fn` at caixa-core build
42017        // time with E0015 (`cannot call non-const method`), strictly
42018        // stronger than a runtime `assert!`. Sibling of the peer
42019        // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
42020        // posture on the sibling per-`:politicas` cap-scalar envelopes
42021        // and the peer [`Placement::estrategia`] const-fn accessor pin at
42022        // [`placement_estrategia_accessor_is_const_fn`] on the paired
42023        // substrate primitive.
42024        const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
42025            AplicacaoError::placement_without_clusters(p)
42026        }
42027        let placement = Placement {
42028            estrategia: PlacementStrategy::Sharded,
42029            clusters: vec![],
42030            affinity: None,
42031            shard_key: Some("tenantId".into()),
42032        };
42033        assert_eq!(
42034            placement_without_clusters_via_const_fn(&placement),
42035            AplicacaoError::placement_without_clusters(&placement),
42036        );
42037    }
42038
42039    #[test]
42040    fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
42041        // Equivalence pin: the ctor produces byte-equal
42042        // `AplicacaoError::EntradaMemberMissing` to the pre-lift
42043        // open-coded struct-literal that read the same `:para` value
42044        // through `e.destination().to_string()` at the caller site
42045        // inside [`AplicacaoSpec::validate_entrada`]. Guards any future
42046        // field-addition / reordering / accessor-return tweak on the
42047        // variant. Sibling of the peer
42048        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
42049        // and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
42050        // pins on the sibling per-`:placement` envelope, and sibling of
42051        // the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
42052        // pin on the sibling per-`:membros :caixa` envelope.
42053        let entrada = Entrada {
42054            host: "checkout.quero.cloud".into(),
42055            para: "phantom-shim".into(),
42056            paths: vec!["/api".into()],
42057            port: 8080,
42058        };
42059        let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
42060        let via_literal = AplicacaoError::EntradaMemberMissing {
42061            para: entrada.destination().to_string(),
42062        };
42063        assert_eq!(
42064            via_ctor, via_literal,
42065            "entrada_member_missing(&entrada) must byte-equal the open-coded \
42066             EntradaMemberMissing struct-literal on the same &Entrada fixture"
42067        );
42068        assert_eq!(
42069            via_ctor.to_string(),
42070            via_literal.to_string(),
42071            "Display byte-string must byte-equal the open-coded struct-literal"
42072        );
42073    }
42074
42075    #[test]
42076    fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
42077        // Boundary-sweep pin on the ctor's substrate-primitive
42078        // projection: the `para` slot is stored verbatim from
42079        // [`Entrada::destination`] across a representative set of
42080        // `:entrada :para` byte-strings, so any wrapper-side silent
42081        // normalization, `.into()` divergence, accidental field
42082        // rebrand, or per-arm ctor divergence on the sole-field
42083        // projection surfaces at caixa-core build time rather than at
42084        // a downstream diagnostic consumer that reads `err.para` back
42085        // and gets a different value than the one it stored. Peer of
42086        // the sibling
42087        // `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
42088        // boundary-sweep pin on the sibling per-`:placement :shard-key`
42089        // envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
42090        // sweep on the sibling per-`:placement` empty-clusters envelope
42091        // — extended here onto the [`Entrada`]-borrow-projected sole
42092        // `para` slot on the sibling per-`:entrada :para` envelope. The
42093        // sweep list carries a mixed set (well-shaped phantom, hyphen-
42094        // digit tail, single-character floor, and the digit-start form
42095        // the peer `accepts_canonical_entrada_para_forms` positive-
42096        // control test also sweeps) so a future silent per-input
42097        // normalization surfaces on the arm that diverges.
42098        for para in [
42099            "phantom-shim",
42100            "cart-v2",
42101            "a",
42102            "c0",
42103            "3rd-party-shim",
42104            "x-1-2-3-4",
42105        ] {
42106            let entrada = Entrada {
42107                host: "checkout.quero.cloud".into(),
42108                para: para.into(),
42109                paths: vec!["/api".into()],
42110                port: 8080,
42111            };
42112            let err = AplicacaoError::entrada_member_missing(&entrada);
42113            let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
42114                panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
42115            };
42116            assert_eq!(
42117                stored_para,
42118                entrada.destination(),
42119                "para slot must round-trip verbatim through Entrada::destination() \
42120                 for {para:?}"
42121            );
42122            assert_eq!(
42123                stored_para, para,
42124                "para slot must byte-equal the fixture-declared value for {para:?}"
42125            );
42126        }
42127    }
42128
42129    #[test]
42130    fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
42131        // End-to-end pin: the sole in-crate wire-up site
42132        // (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
42133        // routes through [`AplicacaoError::entrada_member_missing`] and
42134        // the observed `Err` byte-equals the ctor's output on the same
42135        // well-shaped-phantom `:para` fixture. A future silent de-lift
42136        // of the wire-up back to the open-coded struct-literal trips
42137        // this test at caixa-core build time rather than at a
42138        // downstream diagnostic consumer far from the wire-up commit.
42139        // Sibling of the peer
42140        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
42141        // end-to-end pin on the sibling per-`:placement :shard-key`
42142        // envelope, and sibling of the peer
42143        // `entrada_para_well_shaped_phantom_still_raises_member_missing`
42144        // pattern-match pin on the same wire-up — extended here from a
42145        // `matches!` shape check to a byte-identity + Display parity
42146        // route through the ctor.
42147        let mut s = three_member_spec();
42148        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
42149        let observed = s.validate().unwrap_err();
42150        let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
42151        assert_eq!(
42152            observed, expected,
42153            "validate_entrada's phantom-reference-arm Err must byte-equal \
42154             entrada_member_missing(&entrada)"
42155        );
42156        assert_eq!(
42157            observed.to_string(),
42158            expected.to_string(),
42159            "Display byte-string parity"
42160        );
42161    }
42162
42163    #[test]
42164    fn contrato_cycle_ctor_matches_struct_literal_wrap() {
42165        // Equivalence pin: the ctor produces byte-equal
42166        // `AplicacaoError::ContratoCycle` to the pre-lift open-coded
42167        // struct-literal that stored the caller-side reconstructed
42168        // cycle path verbatim at the gray-arm cycle-close return inside
42169        // [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
42170        // field-addition / reordering / re-collect divergence on the
42171        // variant. Sibling of the peer
42172        // `entrada_member_missing_ctor_matches_struct_literal_wrap`
42173        // (deeae5c) pin on the sibling per-`:entrada :para`
42174        // phantom-reference envelope, and sibling of the peer
42175        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
42176        // pin on the sibling per-`:placement` empty-clusters envelope.
42177        let cycle = vec![
42178            "cart".to_string(),
42179            "catalog".to_string(),
42180            "cart".to_string(),
42181        ];
42182        let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
42183        let via_literal = AplicacaoError::ContratoCycle {
42184            cycle: cycle.clone(),
42185        };
42186        assert_eq!(
42187            via_ctor, via_literal,
42188            "contrato_cycle(cycle) must byte-equal the open-coded \
42189             ContratoCycle struct-literal on the same Vec<String> fixture"
42190        );
42191        assert_eq!(
42192            via_ctor.to_string(),
42193            via_literal.to_string(),
42194            "Display byte-string must byte-equal the open-coded struct-literal"
42195        );
42196    }
42197
42198    #[test]
42199    fn contrato_cycle_ctor_routes_path_verbatim() {
42200        // Boundary-sweep pin on the ctor's substrate-primitive
42201        // pass-through: the `cycle` slot is stored verbatim across a
42202        // representative set of reconstructed cycle paths (two-node
42203        // closed loop; three-node loop; long chain with repeated
42204        // interior nodes; a fixture whose first/last coincide by the
42205        // gray-arm's own append-target-once-more discipline), so any
42206        // wrapper-side silent normalization, dedup, sort, `.into()`
42207        // divergence, accidental field rebrand, or re-collect on the
42208        // sole-field pass-through surfaces at caixa-core build time
42209        // rather than at a downstream diagnostic consumer that reads
42210        // `err.cycle` back and gets a different value than the one it
42211        // stored. Peer of the sibling
42212        // `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
42213        // (deeae5c) boundary-sweep pin on the sibling per-`:entrada
42214        // :para` envelope — extended here onto the owned-[`Vec<String>`]
42215        // pass-through on the sibling per-`:contratos` cycle envelope.
42216        for cycle in [
42217            vec![
42218                "cart".to_string(),
42219                "catalog".to_string(),
42220                "cart".to_string(),
42221            ],
42222            vec![
42223                "cart".to_string(),
42224                "catalog".to_string(),
42225                "payment".to_string(),
42226                "cart".to_string(),
42227            ],
42228            vec![
42229                "a".to_string(),
42230                "b".to_string(),
42231                "c".to_string(),
42232                "d".to_string(),
42233                "b".to_string(),
42234            ],
42235            vec!["only".to_string(), "only".to_string()],
42236        ] {
42237            let err = AplicacaoError::contrato_cycle(cycle.clone());
42238            let AplicacaoError::ContratoCycle { cycle: stored } = err else {
42239                panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
42240            };
42241            assert_eq!(
42242                stored, cycle,
42243                "cycle slot must round-trip the caller-side Vec<String> verbatim \
42244                 for {cycle:?}"
42245            );
42246        }
42247    }
42248
42249    #[test]
42250    fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
42251        // End-to-end pin: the sole in-crate wire-up site
42252        // (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
42253        // return) routes through [`AplicacaoError::contrato_cycle`] and
42254        // the observed `Err` byte-equals the ctor's output on the same
42255        // reconstructed cycle path. A future silent de-lift of the
42256        // wire-up back to the open-coded `AplicacaoError::ContratoCycle
42257        // { cycle }` struct-literal trips this test at caixa-core build
42258        // time rather than at a downstream diagnostic consumer far from
42259        // the wire-up commit. Sibling of the peer
42260        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
42261        // (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
42262        // envelope, and sibling of the peer
42263        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
42264        // (14bafca) end-to-end pin on the sibling per-`:placement
42265        // :shard-key` envelope — extended here from a bare
42266        // `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
42267        // check to a byte-identity route through the ctor.
42268        let mut s = three_member_spec();
42269        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
42270        s.contratos = vec![
42271            contract_http("catalog", "cart", "/x"),
42272            contract_http("cart", "payment", "/y"),
42273            contract_http("payment", "catalog", "/z"),
42274        ];
42275        let observed = s.validate().unwrap_err();
42276        let AplicacaoError::ContratoCycle { ref cycle } = observed else {
42277            panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
42278        };
42279        let expected = AplicacaoError::contrato_cycle(cycle.clone());
42280        assert_eq!(
42281            observed, expected,
42282            "detect_sync_cycles's gray-arm Err must byte-equal \
42283             contrato_cycle(cycle) on the reconstructed cycle path"
42284        );
42285        assert_eq!(
42286            observed.to_string(),
42287            expected.to_string(),
42288            "Display byte-string parity"
42289        );
42290    }
42291
42292    // ── policy_breaker_window_below_timeout standalone ctor pins ────────
42293    //
42294    // Fail-before-pass-after pins for the standalone
42295    // [`AplicacaoError::policy_breaker_window_below_timeout`] inherent
42296    // ctor (see the paired doc-block above the ctor definition) — the
42297    // fold of the last open-coded two-slot `{ window: cb.window(),
42298    // timeout: t }` struct-literal inside
42299    // [`MeshPolicy::first_cross_axis_violation`]'s window-below-timeout
42300    // arm onto one substrate primitive on the [`AplicacaoError`]
42301    // envelope, projecting through the [`CircuitBreaker::window`] scalar
42302    // accessor on the substrate primitive. A byte-mismatched ctor body
42303    // would trip the equivalence pin first, ahead of any downstream
42304    // diagnostic-shape drift.
42305    //
42306    // Peer of the sibling standalone-ctor equivalence pins on the peer
42307    // per-envelope substrate-primitive-projection ctors across
42308    // caixa-core: `contrato_self_loop_ctor_matches_struct_literal_wrap`
42309    // (b30edfe) on the sibling `{ caixa: String, wit: String }` two-slot
42310    // per-`:contratos` self-edge envelope,
42311    // `entrada_member_missing_ctor_matches_struct_literal_wrap` (deeae5c)
42312    // on the sibling `{ para: String }` one-slot per-`:entrada :para`
42313    // phantom-reference envelope, and
42314    // `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
42315    // (14bafca) on the sibling `{ estrategia, shard_key }` two-slot
42316    // per-`:placement :shard-key` envelope.
42317
42318    #[test]
42319    fn policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap() {
42320        // Equivalence pin: the ctor produces byte-equal
42321        // `AplicacaoError::PolicyBreakerWindowBelowTimeout` to the pre-
42322        // lift open-coded struct-literal that read the same two fields
42323        // through [`CircuitBreaker::window`] and the paired
42324        // `:politicas :timeout` destructure. Guards any future
42325        // field-addition / reordering / accessor-swap tweak on the
42326        // variant. Same equivalence-pin shape as the sibling
42327        // `contrato_self_loop_ctor_matches_struct_literal_wrap`
42328        // (b30edfe) on the sibling per-`:contratos` self-edge envelope.
42329        let cb = CircuitBreaker {
42330            max_failures: 5,
42331            window: Duration::from_secs(10),
42332        };
42333        let timeout = Duration::from_secs(30);
42334        let via_ctor = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
42335        let via_literal = AplicacaoError::PolicyBreakerWindowBelowTimeout {
42336            window: cb.window(),
42337            timeout,
42338        };
42339        assert_eq!(
42340            via_ctor, via_literal,
42341            "policy_breaker_window_below_timeout(&cb, t) must byte-equal \
42342             the open-coded PolicyBreakerWindowBelowTimeout struct-literal \
42343             on the same Copy-Duration fixture"
42344        );
42345        assert_eq!(
42346            via_ctor.to_string(),
42347            via_literal.to_string(),
42348            "Display byte-string must byte-equal the open-coded struct-literal"
42349        );
42350    }
42351
42352    #[test]
42353    fn policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim() {
42354        // Routing pin sweeping non-default `:circuit-breaker :window`
42355        // and `:timeout` pairs (below-boundary window / above-boundary
42356        // window; sub-second window / multi-minute timeout;
42357        // millisecond-precision fixture) through the paired
42358        // [`CircuitBreaker::window`] accessor and the direct `timeout`
42359        // parameter, so any wrapper-side silent normalization,
42360        // rounding, argument re-order, or accidental slot rebrand on
42361        // the two-slot pass-through surfaces at caixa-core build time
42362        // rather than at a downstream diagnostic consumer that reads
42363        // the two [`Duration`]s back and gets different values than
42364        // the ones it stored.
42365        //
42366        // Deliberately routes through a fixture whose `cb.window` and
42367        // `timeout` are distinct — a silent accessor swap
42368        // (`cb.max_failures` casting to `Duration` would fail to
42369        // compile; a hypothetical field-rename swap swapping the two
42370        // slots at the ctor body would land `timeout` in the `window`
42371        // slot instead of `cb.window()` and vice-versa, tripping the
42372        // per-field assertion here). Peer of the sibling
42373        // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
42374        // (b30edfe) routing pin on the sibling two-slot per-`:contratos`
42375        // envelope.
42376        for (max_failures, window, timeout) in [
42377            (5_u32, Duration::from_secs(10), Duration::from_secs(30)),
42378            (
42379                1_u32,
42380                Duration::from_millis(29_999),
42381                Duration::from_secs(30),
42382            ),
42383            (42_u32, Duration::from_millis(500), Duration::from_secs(120)),
42384            (7_u32, Duration::from_secs(1), Duration::from_secs(60)),
42385        ] {
42386            let cb = CircuitBreaker {
42387                max_failures,
42388                window,
42389            };
42390            let built = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
42391            let AplicacaoError::PolicyBreakerWindowBelowTimeout {
42392                window: stored_window,
42393                timeout: stored_timeout,
42394            } = built
42395            else {
42396                panic!(
42397                    "policy_breaker_window_below_timeout must construct \
42398                     PolicyBreakerWindowBelowTimeout for cb={cb:?}/timeout={timeout:?}"
42399                );
42400            };
42401            assert_eq!(
42402                stored_window, window,
42403                "window slot must thread CircuitBreaker::window() verbatim \
42404                 for cb={cb:?}/timeout={timeout:?}"
42405            );
42406            assert_eq!(
42407                stored_timeout, timeout,
42408                "timeout slot must thread the caller-side :timeout scalar verbatim \
42409                 for cb={cb:?}/timeout={timeout:?}"
42410            );
42411        }
42412    }
42413
42414    #[test]
42415    fn first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor() {
42416        // End-to-end pin: the sole in-crate wire-up site
42417        // ([`MeshPolicy::first_cross_axis_violation`]'s
42418        // window-below-timeout arm) routes through
42419        // [`AplicacaoError::policy_breaker_window_below_timeout`] and
42420        // the observed `Err` byte-equals the ctor's output on the same
42421        // sub-boundary `(:window, :timeout)` fixture. A future silent
42422        // de-lift of the wire-up back to the open-coded
42423        // `AplicacaoError::PolicyBreakerWindowBelowTimeout { window,
42424        // timeout }` struct-literal trips this test at caixa-core build
42425        // time rather than at a downstream diagnostic consumer far from
42426        // the wire-up commit. Sibling of the peer
42427        // `detect_sync_cycles_arm_routes_through_contrato_cycle_ctor`
42428        // (5cfcab8) end-to-end pin on the sibling per-`:contratos`
42429        // cross-edge cycle envelope,
42430        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
42431        // (deeae5c) on the sibling per-`:entrada :para` phantom-
42432        // reference envelope, and
42433        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
42434        // (14bafca) on the sibling per-`:placement :shard-key`
42435        // envelope — extended here from a bare `matches!(err,
42436        // AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })`
42437        // shape check to a byte-identity route through the ctor.
42438        let mut s = three_member_spec();
42439        s.politicas.timeout = Some(Duration::from_secs(30));
42440        s.politicas.circuit_breaker = Some(CircuitBreaker {
42441            max_failures: 5,
42442            window: Duration::from_secs(10),
42443        });
42444        let observed = s.validate().unwrap_err();
42445        let cb = s.politicas.circuit_breaker.unwrap();
42446        let timeout = s.politicas.timeout.unwrap();
42447        let expected = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
42448        assert_eq!(
42449            observed, expected,
42450            "MeshPolicy::first_cross_axis_violation's window-below-timeout \
42451             arm's Err must byte-equal policy_breaker_window_below_timeout(&cb, t)"
42452        );
42453        assert_eq!(
42454            observed.to_string(),
42455            expected.to_string(),
42456            "Display byte-string parity"
42457        );
42458    }
42459
42460    #[test]
42461    fn policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap() {
42462        // Equivalence pin: the ctor produces byte-equal
42463        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit` to the
42464        // pre-lift open-coded struct-literal that read the same four fields
42465        // through [`RateLimit::rate`], [`RateLimit::window`],
42466        // [`CircuitBreaker::max_failures`], and [`CircuitBreaker::window`].
42467        // Guards any future field-addition / reordering / accessor-swap
42468        // tweak on the variant. Same equivalence-pin shape as the sibling
42469        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
42470        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
42471        // cross-axis envelope.
42472        let rl = RateLimit {
42473            rate: 1,
42474            window: Duration::from_secs(3600),
42475        };
42476        let cb = CircuitBreaker {
42477            max_failures: 5,
42478            window: Duration::from_secs(10),
42479        };
42480        let via_ctor = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
42481        let via_literal = AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
42482            rate: rl.rate(),
42483            rl_window: rl.window(),
42484            max_failures: cb.max_failures(),
42485            cb_window: cb.window(),
42486        };
42487        assert_eq!(
42488            via_ctor, via_literal,
42489            "policy_breaker_cannot_trip_under_rate_limit(&rl, &cb) must \
42490             byte-equal the open-coded PolicyBreakerCannotTripUnderRateLimit \
42491             struct-literal on the same Copy-(u32|Duration) fixture"
42492        );
42493        assert_eq!(
42494            via_ctor.to_string(),
42495            via_literal.to_string(),
42496            "Display byte-string must byte-equal the open-coded struct-literal"
42497        );
42498    }
42499
42500    #[test]
42501    fn policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim() {
42502        // Routing pin sweeping non-default `(:rate, :rate-limit :window,
42503        // :max-failures, :circuit-breaker :window)` tuples across the
42504        // production-playbook starve band — Envoy 5-in-10s vs 1/hour,
42505        // sub-second breaker window, multi-minute rate-limit window,
42506        // multi-tenant per-cluster ratio — through the paired
42507        // [`RateLimit::rate`] / [`RateLimit::window`] /
42508        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
42509        // accessors, so any wrapper-side silent normalization, rounding,
42510        // argument re-order, or accidental slot rebrand on the four-slot
42511        // pass-through surfaces at caixa-core build time rather than at a
42512        // downstream diagnostic consumer that reads the four scalars back
42513        // and gets different values than the ones it stored.
42514        //
42515        // Deliberately routes through fixtures whose four scalars are
42516        // pairwise distinct (`rate ≠ max_failures`, `rl_window ≠
42517        // cb_window`) — a hypothetical field-rename swap swapping any
42518        // two adjacent slots at the ctor body would land the value from
42519        // the wrong axis, tripping the per-field assertion here. Peer of
42520        // the sibling
42521        // `policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim`
42522        // (9b30c07) routing pin on the sibling two-slot per-`(:timeout,
42523        // :circuit-breaker)` cross-axis envelope.
42524        for (rate, rl_window, max_failures, cb_window) in [
42525            (
42526                1_u32,
42527                Duration::from_secs(3600),
42528                5_u32,
42529                Duration::from_secs(10),
42530            ),
42531            (4_u32, Duration::from_secs(1), 5_u32, Duration::from_secs(1)),
42532            (
42533                2_u32,
42534                Duration::from_millis(500),
42535                10_u32,
42536                Duration::from_secs(300),
42537            ),
42538            (
42539                7_u32,
42540                Duration::from_secs(120),
42541                42_u32,
42542                Duration::from_millis(750),
42543            ),
42544        ] {
42545            let rl = RateLimit {
42546                rate,
42547                window: rl_window,
42548            };
42549            let cb = CircuitBreaker {
42550                max_failures,
42551                window: cb_window,
42552            };
42553            let built = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
42554            let AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
42555                rate: stored_rate,
42556                rl_window: stored_rl_window,
42557                max_failures: stored_max_failures,
42558                cb_window: stored_cb_window,
42559            } = built
42560            else {
42561                panic!(
42562                    "policy_breaker_cannot_trip_under_rate_limit must \
42563                     construct PolicyBreakerCannotTripUnderRateLimit for \
42564                     rl={rl:?}/cb={cb:?}"
42565                );
42566            };
42567            assert_eq!(
42568                stored_rate, rate,
42569                "rate slot must thread RateLimit::rate() verbatim for \
42570                 rl={rl:?}/cb={cb:?}"
42571            );
42572            assert_eq!(
42573                stored_rl_window, rl_window,
42574                "rl_window slot must thread RateLimit::window() verbatim \
42575                 for rl={rl:?}/cb={cb:?}"
42576            );
42577            assert_eq!(
42578                stored_max_failures, max_failures,
42579                "max_failures slot must thread CircuitBreaker::max_failures() \
42580                 verbatim for rl={rl:?}/cb={cb:?}"
42581            );
42582            assert_eq!(
42583                stored_cb_window, cb_window,
42584                "cb_window slot must thread CircuitBreaker::window() verbatim \
42585                 for rl={rl:?}/cb={cb:?}"
42586            );
42587        }
42588    }
42589
42590    #[test]
42591    fn first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor()
42592     {
42593        // End-to-end pin: the sole in-crate wire-up site
42594        // ([`MeshPolicy::first_cross_axis_violation`]'s
42595        // starve-under-rate-limit arm) routes through
42596        // [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
42597        // and the observed `Err` byte-equals the ctor's output on the same
42598        // token-bucket-starves-breaker fixture. A future silent de-lift of
42599        // the wire-up back to the open-coded
42600        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { rate,
42601        // rl_window, max_failures, cb_window }` struct-literal trips this
42602        // test at caixa-core build time rather than at a downstream
42603        // diagnostic consumer far from the wire-up commit. Sibling of the
42604        // peer
42605        // `first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor`
42606        // (9b30c07) end-to-end pin on the sibling per-`(:timeout,
42607        // :circuit-breaker)` cross-axis envelope — extended here from a
42608        // bare `matches!(err,
42609        // AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })`
42610        // shape check to a byte-identity route through the ctor. Clears
42611        // `:timeout` so the sibling window-below-timeout arm does not
42612        // fire first on the ordering-precedent it holds over this arm.
42613        let mut s = three_member_spec();
42614        s.politicas.timeout = None;
42615        s.politicas.circuit_breaker = Some(CircuitBreaker {
42616            max_failures: 5,
42617            window: Duration::from_secs(10),
42618        });
42619        s.politicas.rate_limit = Some(RateLimit {
42620            rate: 1,
42621            window: Duration::from_secs(3600),
42622        });
42623        let observed = s.validate().unwrap_err();
42624        let rl = s.politicas.rate_limit.unwrap();
42625        let cb = s.politicas.circuit_breaker.unwrap();
42626        let expected = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
42627        assert_eq!(
42628            observed, expected,
42629            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit \
42630             arm's Err must byte-equal \
42631             policy_breaker_cannot_trip_under_rate_limit(&rl, &cb)"
42632        );
42633        assert_eq!(
42634            observed.to_string(),
42635            expected.to_string(),
42636            "Display byte-string parity"
42637        );
42638    }
42639
42640    #[test]
42641    fn policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap() {
42642        // Equivalence pin: the ctor produces byte-equal
42643        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted` to the
42644        // pre-lift open-coded struct-literal that read the same two fields
42645        // through the bare `retries` destructure and
42646        // [`CircuitBreaker::max_failures`]. Guards any future field-addition
42647        // / reordering / accessor-swap tweak on the variant. Same
42648        // equivalence-pin shape as the sibling
42649        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
42650        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
42651        // second cross-axis envelope and
42652        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
42653        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)` first
42654        // cross-axis envelope.
42655        let retries = 5_u32;
42656        let cb = CircuitBreaker {
42657            max_failures: 3,
42658            window: Duration::from_secs(60),
42659        };
42660        let via_ctor = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
42661        let via_literal = AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
42662            retries,
42663            max_failures: cb.max_failures(),
42664        };
42665        assert_eq!(
42666            via_ctor, via_literal,
42667            "policy_breaker_trips_before_retries_exhausted(retries, &cb) must \
42668             byte-equal the open-coded PolicyBreakerTripsBeforeRetriesExhausted \
42669             struct-literal on the same Copy-u32 fixture"
42670        );
42671        assert_eq!(
42672            via_ctor.to_string(),
42673            via_literal.to_string(),
42674            "Display byte-string must byte-equal the open-coded struct-literal"
42675        );
42676    }
42677
42678    #[test]
42679    fn policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim() {
42680        // Routing pin sweeping non-default `(retries, max_failures)` tuples
42681        // across the production-playbook retries-saturate band — Envoy 5
42682        // retries vs 3 max-failures, boundary retries==max_failures pair (a
42683        // rejecting arm on the strict-inequality invariant), multi-tenant
42684        // high-retries-vs-low-trip ratio, sub-cap high-max-failures ceiling —
42685        // through the paired bare-`retries` destructure and
42686        // [`CircuitBreaker::max_failures`] accessor, so any wrapper-side
42687        // silent normalization, rounding, argument re-order, or accidental
42688        // slot rebrand on the two-slot pass-through surfaces at caixa-core
42689        // build time rather than at a downstream diagnostic consumer that
42690        // reads the two scalars back and gets different values than the ones
42691        // it stored.
42692        //
42693        // Deliberately routes through fixtures whose two scalars are
42694        // pairwise distinct (`retries ≠ max_failures` on every non-boundary
42695        // arm) — a hypothetical field-rename swap swapping the two slots at
42696        // the ctor body would land the value from the wrong axis, tripping
42697        // the per-field assertion here. Peer of the sibling
42698        // `policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim`
42699        // (6bb4e46) routing pin on the sibling four-slot per-`(:rate-limit,
42700        // :circuit-breaker)` second cross-axis envelope.
42701        for (retries, max_failures) in [
42702            (5_u32, 3_u32),
42703            (3_u32, 3_u32),
42704            (100_u32, 1_u32),
42705            (7_u32, 42_u32),
42706        ] {
42707            let cb = CircuitBreaker {
42708                max_failures,
42709                window: Duration::from_secs(60),
42710            };
42711            let built = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
42712            let AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
42713                retries: stored_retries,
42714                max_failures: stored_max_failures,
42715            } = built
42716            else {
42717                panic!(
42718                    "policy_breaker_trips_before_retries_exhausted must \
42719                     construct PolicyBreakerTripsBeforeRetriesExhausted for \
42720                     retries={retries}/cb={cb:?}"
42721                );
42722            };
42723            assert_eq!(
42724                stored_retries, retries,
42725                "retries slot must thread the bare-`retries` destructure \
42726                 verbatim for retries={retries}/cb={cb:?}"
42727            );
42728            assert_eq!(
42729                stored_max_failures, max_failures,
42730                "max_failures slot must thread CircuitBreaker::max_failures() \
42731                 verbatim for retries={retries}/cb={cb:?}"
42732            );
42733        }
42734    }
42735
42736    #[test]
42737    fn first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor()
42738     {
42739        // End-to-end pin: the sole in-crate wire-up site
42740        // ([`MeshPolicy::first_cross_axis_violation`]'s retries-saturate
42741        // arm) routes through
42742        // [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
42743        // and the observed `Err` byte-equals the ctor's output on the same
42744        // retries-saturate fixture. A future silent de-lift of the wire-up
42745        // back to the open-coded
42746        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { retries,
42747        // max_failures }` struct-literal trips this test at caixa-core build
42748        // time rather than at a downstream diagnostic consumer far from the
42749        // wire-up commit. Sibling of the peer
42750        // `first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor`
42751        // (6bb4e46) end-to-end pin on the sibling per-`(:rate-limit,
42752        // :circuit-breaker)` second cross-axis envelope — extended here from
42753        // a bare `matches!(err,
42754        // AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })`
42755        // shape check to a byte-identity route through the ctor. Clears
42756        // `:timeout` and `:rate-limit` so the sibling window-below-timeout
42757        // and starve-under-rate-limit arms do not fire first on the
42758        // ordering-precedent they hold over this arm.
42759        let mut s = three_member_spec();
42760        s.politicas.timeout = None;
42761        s.politicas.rate_limit = None;
42762        s.politicas.retries = Some(5);
42763        s.politicas.circuit_breaker = Some(CircuitBreaker {
42764            max_failures: 3,
42765            window: Duration::from_secs(60),
42766        });
42767        let observed = s.validate().unwrap_err();
42768        let retries = s.politicas.retries.unwrap();
42769        let cb = s.politicas.circuit_breaker.unwrap();
42770        let expected = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
42771        assert_eq!(
42772            observed, expected,
42773            "MeshPolicy::first_cross_axis_violation's retries-saturate arm's \
42774             Err must byte-equal \
42775             policy_breaker_trips_before_retries_exhausted(retries, &cb)"
42776        );
42777        assert_eq!(
42778            observed.to_string(),
42779            expected.to_string(),
42780            "Display byte-string parity"
42781        );
42782    }
42783
42784    #[test]
42785    fn policy_rate_limit_cannot_admit_retry_burst_ctor_matches_struct_literal_wrap() {
42786        // Equivalence pin: the ctor produces byte-equal
42787        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst` to the
42788        // pre-lift open-coded struct-literal that read the same two fields
42789        // through the bare `retries` destructure and [`RateLimit::rate`].
42790        // Guards any future field-addition / reordering / accessor-swap
42791        // tweak on the variant. Same equivalence-pin shape as the sibling
42792        // `policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap`
42793        // (f54c539) on the sibling per-`(:retries, :circuit-breaker)`
42794        // third cross-axis envelope,
42795        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
42796        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
42797        // second cross-axis envelope, and
42798        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
42799        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
42800        // first cross-axis envelope.
42801        let retries = 3_u32;
42802        let rl = RateLimit {
42803            rate: 3,
42804            window: Duration::from_secs(1),
42805        };
42806        let via_ctor = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
42807        let via_literal = AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
42808            retries,
42809            rate: rl.rate(),
42810        };
42811        assert_eq!(
42812            via_ctor, via_literal,
42813            "policy_rate_limit_cannot_admit_retry_burst(retries, &rl) must \
42814             byte-equal the open-coded PolicyRateLimitCannotAdmitRetryBurst \
42815             struct-literal on the same Copy-u32 fixture"
42816        );
42817        assert_eq!(
42818            via_ctor.to_string(),
42819            via_literal.to_string(),
42820            "Display byte-string must byte-equal the open-coded struct-literal"
42821        );
42822    }
42823
42824    #[test]
42825    fn policy_rate_limit_cannot_admit_retry_burst_ctor_routes_retries_and_rl_verbatim() {
42826        // Routing pin sweeping non-default `(retries, rate)` tuples across
42827        // the production-playbook rate-limit-starve band — boundary
42828        // `retries==rate` (a rejecting arm on the `>=` invariant stated as
42829        // `rate >= retries + 1`), one-below-boundary pair, multi-tenant
42830        // high-retries-vs-low-rate ratio, and sub-cap high-rate ceiling —
42831        // through the paired bare-`retries` destructure and
42832        // [`RateLimit::rate`] accessor, so any wrapper-side silent
42833        // normalization, rounding, argument re-order, or accidental slot
42834        // rebrand on the two-slot pass-through surfaces at caixa-core
42835        // build time rather than at a downstream diagnostic consumer that
42836        // reads the two scalars back and gets different values than the
42837        // ones it stored.
42838        //
42839        // Deliberately routes through fixtures whose two scalars are
42840        // pairwise distinct on every non-boundary arm — a hypothetical
42841        // field-rename swap swapping the two slots at the ctor body would
42842        // land the value from the wrong axis, tripping the per-field
42843        // assertion here. Peer of the sibling
42844        // `policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim`
42845        // (f54c539) routing pin on the sibling two-slot per-`(:retries,
42846        // :circuit-breaker)` third cross-axis envelope.
42847        for (retries, rate) in [
42848            (3_u32, 3_u32),
42849            (5_u32, 4_u32),
42850            (100_u32, 50_u32),
42851            (2_u32, POLICY_RATE_LIMIT_MAX),
42852        ] {
42853            let rl = RateLimit {
42854                rate,
42855                window: Duration::from_secs(1),
42856            };
42857            let built = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
42858            let AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
42859                retries: stored_retries,
42860                rate: stored_rate,
42861            } = built
42862            else {
42863                panic!(
42864                    "policy_rate_limit_cannot_admit_retry_burst must \
42865                     construct PolicyRateLimitCannotAdmitRetryBurst for \
42866                     retries={retries}/rl={rl:?}"
42867                );
42868            };
42869            assert_eq!(
42870                stored_retries, retries,
42871                "retries slot must thread the bare-`retries` destructure \
42872                 verbatim for retries={retries}/rl={rl:?}"
42873            );
42874            assert_eq!(
42875                stored_rate, rate,
42876                "rate slot must thread RateLimit::rate() verbatim for \
42877                 retries={retries}/rl={rl:?}"
42878            );
42879        }
42880    }
42881
42882    #[test]
42883    fn first_cross_axis_violation_arm_routes_through_policy_rate_limit_cannot_admit_retry_burst_ctor()
42884     {
42885        // End-to-end pin: the sole in-crate wire-up site
42886        // ([`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
42887        // limit arm) routes through
42888        // [`AplicacaoError::policy_rate_limit_cannot_admit_retry_burst`]
42889        // and the observed `Err` byte-equals the ctor's output on the same
42890        // rate-limit-starve fixture. A future silent de-lift of the
42891        // wire-up back to the open-coded
42892        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { retries,
42893        // rate }` struct-literal trips this test at caixa-core build time
42894        // rather than at a downstream diagnostic consumer far from the
42895        // wire-up commit. Sibling of the peer
42896        // `first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor`
42897        // (f54c539) end-to-end pin on the sibling per-`(:retries,
42898        // :circuit-breaker)` third cross-axis envelope. Clears `:timeout`
42899        // and `:circuit-breaker` so the sibling window-below-timeout /
42900        // starve-under-rate-limit / trips-before-retries-exhausted arms
42901        // do not fire first on the ordering-precedent they hold over this
42902        // arm.
42903        let mut s = three_member_spec();
42904        s.politicas.timeout = None;
42905        s.politicas.circuit_breaker = None;
42906        s.politicas.retries = Some(5);
42907        s.politicas.rate_limit = Some(RateLimit {
42908            rate: 3,
42909            window: Duration::from_secs(1),
42910        });
42911        let observed = s.validate().unwrap_err();
42912        let retries = s.politicas.retries.unwrap();
42913        let rl = s.politicas.rate_limit.unwrap();
42914        let expected = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
42915        assert_eq!(
42916            observed, expected,
42917            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit arm's \
42918             Err must byte-equal \
42919             policy_rate_limit_cannot_admit_retry_burst(retries, &rl)"
42920        );
42921        assert_eq!(
42922            observed.to_string(),
42923            expected.to_string(),
42924            "Display byte-string parity"
42925        );
42926    }
42927}