Skip to main content

caixa_core/
dialeto.rs

1//! `defcaixa` is spoken by two unrelated declarations. This module makes that
2//! a **typed fact** instead of an anonymous parse failure.
3//!
4//! # The finding
5//!
6//! Measured 2026-07-31 over the pleme-io org checkout (270 `caixa.lisp` /
7//! `*.caixa.lisp` files found with `rg --no-ignore`; a bare `rg` from the org
8//! root returns 0, which is how this stayed invisible), the corpus splits into
9//! two schemas that share zero required slots:
10//!
11//! * [`CaixaDialeto::Pacote`] — this crate's [`crate::Caixa`]. `:nome
12//!   :versao :kind :deps :bibliotecas :exe :servicos` + the supervisor/mesh
13//!   slots. It declares a **tatara-lisp package**: the thing `feira` resolves,
14//!   builds, links and publishes.
15//! * [`CaixaDialeto::Molde`] — `:name :kind :ecosystem :package {…} :workflows
16//!   […] :ci-config {…} :files […]`. It declares a **repo's generated
17//!   surface**: which foreign ecosystem (rust / go / python / …), that
18//!   ecosystem's own package metadata, the CI shims to emit, and byte-captured
19//!   file bodies. Read by `pleme-doc-gen`, never by `feira`.
20//!
21//! `:package`, `:ecosystem`, `:supports` and `:profile` have no counterpart in
22//! [`crate::Caixa`] at all — the theory doc's own D4 note records the same
23//! thing: those manifests "are authored against a schema that does not exist in
24//! Rust". They are not two spellings of one declaration. They are two domains
25//! that collided on one word, because *caixa* names a box and both are boxes.
26//!
27//! # Why this is not a bug report about broken files
28//!
29//! The Molde-dialect files are not malformed. They are correct inputs to their
30//! own consumer, and nothing in the shipped `feira` reads them, so nothing is
31//! failing today. The hazard is **latent and certain**: any new declarative
32//! surface written against "a `.caixa.lisp` is a [`crate::Caixa`]" meets a
33//! corpus where that is false for the large majority of files, and gets a flat
34//! unknown-keyword rejection that reads as "this manifest is broken" rather
35//! than "this manifest is not yours".
36//!
37//! # What this module does about it
38//!
39//! [`classify`] is total: every `(defcaixa …)` form lands in exactly one
40//! [`CaixaDialeto`], including [`CaixaDialeto::Desconhecido`] for one that
41//! matches neither. [`crate::Caixa::from_lisp`] runs it first, so a foreign
42//! dialect is [`crate::ManifestError::DialetoEstrangeiro`] — an error that
43//! names the dialect it found and the consumer that speaks it — rather than an
44//! unknown-kwarg error indistinguishable from a typo.
45//!
46//! Tier-honest: this is **parse-time rejection with a named cause**, not
47//! unrepresentability. A caller that ignores the `Err` still gets nothing
48//! useful; what it can no longer do is mistake "wrong dialect" for "bad file".
49
50use tatara_lisp::{Atom, Sexp};
51
52/// Which `(defcaixa …)` declaration a source speaks.
53///
54/// The [`gen_platform::IsVariant`] derive emits per-arm arm-discriminator
55/// predicates (`is_pacote` / `is_molde` / `is_molde_posicional` /
56/// `is_desconhecido`) as substrate-side typed dispatches on the closed
57/// four-arm dialect-classification discriminator. Peer of the sibling
58/// closed-set fieldless typed enums' [`crate::CaixaKind`] /
59/// [`crate::supervisor::RestartStrategy`] /
60/// [`crate::supervisor::RestartPolicy`] /
61/// [`crate::aplicacao::PlacementStrategy`] /
62/// [`crate::aplicacao::RateLimitUnit`] /
63/// [`crate::dep::DepList`] `IsVariant` derives on the sibling
64/// closed-set typed-enum discriminator axes.
65///
66/// The pre-lift `is_molde_family` predicate hand-rolled its own
67/// `matches!(self, Self::Molde | Self::MoldePosicional)` two-arm literal
68/// with no compile-time link back to the closed set — post-lift it routes
69/// through `self.is_molde() || self.is_molde_posicional()` so a future
70/// arm rename (e.g. `Molde → MoldeKW` under an M4 vocabulary shift) trips
71/// exhaustively at every derive-generated predicate site rather than
72/// leaving the hand-rolled `matches!` silently drifting.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant)]
74pub enum CaixaDialeto {
75    /// This crate's [`crate::Caixa`] — a tatara-lisp package manifest.
76    /// Keyword-argument form headed by `:nome`.
77    Pacote,
78    /// `pleme-doc-gen`'s repo-surface declaration, keyword-argument form
79    /// headed by `:name` (plus `:ecosystem` / `:package`).
80    Molde,
81    /// The same declaration as [`Self::Molde`], written with the package name
82    /// as a bare positional symbol — `(defcaixa todoku-go :kind :Biblioteca
83    /// :ecosystem :go …)`. `pleme-doc-gen`'s parser reads the first token
84    /// after the head as the name, so this is one arity of one declaration,
85    /// not a third schema.
86    MoldePosicional,
87    /// A `(defcaixa …)` form matching neither. Kept as a variant rather than
88    /// an error so [`classify`] is total and a census can COUNT the residue —
89    /// a classifier that threw here would report "0 unknown" by construction.
90    Desconhecido,
91}
92
93impl CaixaDialeto {
94    /// Exhaustive iteration surface for every consumer that walks the
95    /// closed four-arm [`CaixaDialeto`] discriminator set — the
96    /// [`feira dialeto`](../../caixa_feira/cmd/dialeto/index.html)
97    /// census counter's per-arm accept-set, a future
98    /// `feira dialeto --list-dialects` CLI listing of the accepted
99    /// classifications, a future M4 `mesh.pleme.io/v1alpha1/Manifesto`
100    /// CR materializer's admission-webhook rejection body naming the
101    /// accepted-dialect set, any future census-report shape probe that
102    /// sweeps every arm to compute per-arm coverage. A future arm
103    /// addition (a fifth dialect the [`crate::dialeto`] module doc's
104    /// "third dialect" hazard actualises — the module explicitly frames
105    /// its purpose as "what stops a third dialect appearing", and this
106    /// slice is the substrate-side answer: the arm-set is one edit and
107    /// every consumer picks up the new entry by construction) extends
108    /// this slice as one edit and every downstream consumer picks up
109    /// the new entry through the shared iteration; the compiler-checked
110    /// exhaustiveness on the sibling method `match` arms
111    /// ([`Self::palavra_canonica`] / [`Self::consumidor`] /
112    /// [`Self::descricao`] / [`std::fmt::Display`]) is the build-time
113    /// guarantee that no arm forgets to grow.
114    ///
115    /// Peer of the sibling closed-set typed enums'
116    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
117    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
118    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
119    /// [`crate::dep::DepList::ALL`] (45ee563) /
120    /// [`crate::supervisor::RestartStrategy::ALL`] (4eec29c) /
121    /// [`crate::supervisor::RestartPolicy::ALL`] (dd32ccf)
122    /// exhaustive-iteration surfaces — the seventh closed-set typed
123    /// enum on the caixa surface to converge onto the same
124    /// one-canonical-arm-list-per-enum discipline, and the first
125    /// dialect-classification axis (as distinct from an OTP-shape M2
126    /// slot or an M3 mesh slot) to reach it. Order matches variant
127    /// declaration order verbatim (`Pacote` → `Molde` →
128    /// `MoldePosicional` → `Desconhecido`) so the slice is the
129    /// canonical ordering every listing / rendering consumer defers to.
130    pub const ALL: &'static [Self] = &[
131        Self::Pacote,
132        Self::Molde,
133        Self::MoldePosicional,
134        Self::Desconhecido,
135    ];
136
137    /// Substrate-canonical `PascalCase` variant-name byte-string every consumer
138    /// that formats the dialect as census-facing text lands on. Returns the
139    /// per-arm `PascalCase` name of the variant (`"Pacote"` / `"Molde"` /
140    /// `"MoldePosicional"` / `"Desconhecido"`) — the one canonical
141    /// byte-string the paired [`std::fmt::Display`] impl routes through so
142    /// every downstream consumer (the `feira dialeto` census counter output
143    /// line, a future `feira dialeto --list-dialects` CLI enumeration, a
144    /// future M4 `mesh.pleme.io/v1alpha1/Manifesto` CR materializer's
145    /// admission-webhook rejection body naming the accepted-dialect set)
146    /// reaches for the same substrate primitive rather than the pre-lift
147    /// hand-rolled four-arm literal-string match every [`std::fmt::Display`]
148    /// call previously routed through in place.
149    ///
150    /// Peer of the sibling closed-set typed enums'
151    /// [`crate::CaixaKind::as_str`] / [`crate::supervisor::RestartStrategy::as_str`]
152    /// / [`crate::supervisor::RestartPolicy::as_str`] /
153    /// [`crate::aplicacao::PlacementStrategy::as_str`] /
154    /// [`crate::dep::DepList::as_str`] projections on the sibling closed-set
155    /// typed-enum discriminator axes — the seventh (and last unlifted)
156    /// closed-set fieldless typed enum on the caixa surface to converge
157    /// onto the same one-canonical-byte-string-per-arm-through-`as_str`
158    /// discipline the six siblings already carry. Unlike [`crate::CaixaKind`]
159    /// (which carries two axes: `as_str` returning lowercase Portuguese
160    /// diagnostic form vs `wire_name` returning `PascalCase` tatara-lisp
161    /// author-surface bytes), [`CaixaDialeto`] is an internal
162    /// classification with no wire surface — the `PascalCase` variant name
163    /// is the census-facing form every consumer reads, so `as_str`
164    /// suffices without a paired `wire_name` axis.
165    #[must_use]
166    pub const fn as_str(self) -> &'static str {
167        match self {
168            Self::Pacote => "Pacote",
169            Self::Molde => "Molde",
170            Self::MoldePosicional => "MoldePosicional",
171            Self::Desconhecido => "Desconhecido",
172        }
173    }
174
175    /// Substrate-canonical reverse projection on the [`CaixaDialeto`]
176    /// closed-set dialect-classification axis — parses the `PascalCase`
177    /// variant-name byte-string back to the typed variant, or `None` when
178    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
179    /// emits. Walks the same four `"Pacote"` / `"Molde"` /
180    /// `"MoldePosicional"` / `"Desconhecido"` byte-strings the sibling
181    /// [`Self::as_str`] emitter returns, so the parse and emit halves of
182    /// the round-trip migrate through one caixa-core edit on any future
183    /// arm addition (the module doc's "third dialect" hazard actualising
184    /// as a fifth arm) — the compiler-checked exhaustiveness on
185    /// [`Self::as_str`]'s `match self` arms and the round-trip pin
186    /// [`tests::caixa_dialeto_round_trips_through_as_str_and_from_wire`]
187    /// together lock the two halves mutually.
188    ///
189    /// Prior to this lift the substrate carried only the forward
190    /// `Self → &str` projection on the dialect-classification axis (the
191    /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
192    /// through it, the [`AsRef<str>`] impl routed through it) — every
193    /// future consumer that wanted to promote the census-facing text back
194    /// to the typed enum (a future `feira dialeto --filter
195    /// <Pacote|Molde|MoldePosicional|Desconhecido>` CLI arg-parse that
196    /// binds the wire form into the typed enum before dispatching to the
197    /// per-arm counter, a future M4 `mesh.pleme.io/v1alpha1/Manifesto`
198    /// CR materializer's admission-time re-parse of the per-dialect
199    /// audit body, a future audit-report re-loader that binds a prior
200    /// [`Self::as_str`] output back to the typed enum for cross-run
201    /// comparison) would have had to re-inline a four-arm `match s`
202    /// cascade that expressed no compile-time link back to the typed
203    /// [`CaixaDialeto`] enum.
204    ///
205    /// Same closed-set-reverse-projection discipline the sibling
206    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
207    /// [`crate::supervisor::RestartStrategy::from_wire`] (4eec29c) /
208    /// [`crate::supervisor::RestartPolicy::from_wire`] (dd32ccf) /
209    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
210    /// [`crate::dep::DepList::from_wire`] (45ee563) typed enums carry on
211    /// the peer wire-side `str → Self` axes — extends the family onto
212    /// the seventh closed-set fieldless typed enum on the caixa surface
213    /// (the dialect-classification axis), matching the same
214    /// two-way `str ↔ Self` round-trip every sibling closed-set enum
215    /// already carries. Method-named `from_wire` (not `from_str`) to
216    /// match the peer shapes verbatim and side-step the derived
217    /// [`std::str::FromStr`] impls the sibling
218    /// [`gen_platform::FromStrKind`]-carrying axes install on their
219    /// kebab-case dispatcher-catalog identity. Returns `Option<Self>`
220    /// (rather than `Result<Self, _>`) to match the peer shapes: the
221    /// caller picks the diagnostic form appropriate for its use site.
222    #[must_use]
223    pub fn from_wire(s: &str) -> Option<Self> {
224        match s {
225            "Pacote" => Some(Self::Pacote),
226            "Molde" => Some(Self::Molde),
227            "MoldePosicional" => Some(Self::MoldePosicional),
228            "Desconhecido" => Some(Self::Desconhecido),
229            _ => None,
230        }
231    }
232
233    /// The keyword an author should write for this dialect, once the
234    /// migration named in [`Self::consumidor`] completes.
235    #[must_use]
236    pub const fn palavra_canonica(self) -> &'static str {
237        match self {
238            Self::Pacote => "defcaixa",
239            Self::Molde | Self::MoldePosicional => "defmolde",
240            Self::Desconhecido => "?",
241        }
242    }
243
244    /// Who reads this dialect.
245    #[must_use]
246    pub const fn consumidor(self) -> &'static str {
247        match self {
248            Self::Pacote => "caixa-core / feira",
249            Self::Molde | Self::MoldePosicional => "pleme-doc-gen",
250            Self::Desconhecido => "nobody known",
251        }
252    }
253
254    /// A one-line description for a census row or an error message.
255    #[must_use]
256    pub const fn descricao(self) -> &'static str {
257        match self {
258            Self::Pacote => "tatara-lisp package manifest (:nome :versao :kind :deps …)",
259            Self::Molde => "repo-surface declaration (:name :ecosystem :package {…} …)",
260            Self::MoldePosicional => {
261                "repo-surface declaration, positional name (defcaixa <nome> :kind …)"
262            }
263            Self::Desconhecido => "unrecognised — matches no known defcaixa schema",
264        }
265    }
266
267    /// True when this arm belongs to the `defmolde` declaration family —
268    /// the two-arity closure of [`Self::Molde`] and [`Self::MoldePosicional`]
269    /// under the shared `defmolde` head keyword the sibling
270    /// [`Self::palavra_canonica`] projection already collapses onto
271    /// `"defmolde"` for both arms (and the sibling [`Self::consumidor`]
272    /// projection collapses onto `"pleme-doc-gen"` for the same two arms).
273    /// False on [`Self::Pacote`] (the sibling `defcaixa` tatara-lisp
274    /// package manifest, [`Self::palavra_canonica`] `→ "defcaixa"`) and
275    /// on [`Self::Desconhecido`] (the residue that names no known
276    /// declaration, [`Self::palavra_canonica`] `→ "?"`).
277    ///
278    /// The [`Self::Molde`] / [`Self::MoldePosicional`] split is one
279    /// declaration written two ways ([`Self::MoldePosicional`]'s
280    /// variant-declaration docstring at [`Self::MoldePosicional`] frames
281    /// it exactly: "the same declaration as [`Self::Molde`], written with
282    /// the package name as a bare positional symbol … this is one arity
283    /// of one declaration, not a third schema"). Every downstream gate
284    /// that keys off "does this dialect belong to the `defmolde` family"
285    /// (as distinct from the four-arm-per-arm census-counter axis the
286    /// sibling `feira dialeto` verb already fans on separately at
287    /// `caixa-feira/src/cmd/dialeto.rs:110-127`) previously hand-rolled
288    /// the two-arm collapse inline as `matches!(d, CaixaDialeto::Molde |
289    /// CaixaDialeto::MoldePosicional)` — a compile-time-anonymous
290    /// two-arm literal set with no link back to the [`CaixaDialeto`]
291    /// variant declaration nor to the sibling
292    /// [`Self::palavra_canonica`] / [`Self::consumidor`] projections
293    /// that already carry the same two-arm collapse under the shared
294    /// `defmolde` / `pleme-doc-gen` axis. The `feira dialeto` verb's
295    /// [`caixa-feira/src/cmd/dialeto.rs`] carried the same
296    /// `matches!` twice — once in the `--strict-palavra` gate that
297    /// refuses a repo-surface declaration still written as
298    /// `(defcaixa …)`, once in the wrong-declaration-under-`caixa.lisp`
299    /// gate that refuses a repo-surface declaration under the filename
300    /// `feira` loads as a package manifest — with no compile-time link
301    /// between the two hand-rolled arm sets. A future arm addition (the
302    /// module doc's "third dialect" hazard actualises as a fifth arm
303    /// [`CaixaDialeto`] that belongs to the `defmolde` declaration
304    /// family — a third arity variant, an alias-declaration family
305    /// pleme-doc-gen sharpens as its schema evolves) would silently
306    /// split the two hand-rolled `matches!` arm-sets from each other
307    /// and from the paired [`Self::palavra_canonica`] projection: one
308    /// call site picks up the new arm, one does not, and the disagreement
309    /// surfaces far from the arm-addition commit as a `feira dialeto`
310    /// consumer reporting a repo-surface declaration under one gate but
311    /// not the other. Routing every "belongs to the `defmolde` family"
312    /// predicate through this one substrate primitive closes the axis:
313    /// a future arm addition lands one match arm here (a compile-time
314    /// exhaustiveness error otherwise), not a coordinated per-`matches!`
315    /// rewrite across every caller.
316    ///
317    /// Peer of the sibling [`crate::CaixaKind::requires_lib`] (0421c22)
318    /// per-arm-set predicate on the [`crate::CaixaKind`] closed-set
319    /// discriminator's "kind requires a `lib/` surface" axis — extends
320    /// the same "one canonical typed predicate per per-arm-set gate,
321    /// one dispatch on the substrate primitive" discipline onto the
322    /// [`CaixaDialeto`] closed-set discriminator's "belongs to the
323    /// `defmolde` declaration family" axis. The dialect-classification
324    /// axis's second per-arm-set predicate (first being the implicit
325    /// palavra_canonica-through-consumidor-through-descricao arm-set
326    /// collapse already carried on the sibling projections) — the first
327    /// explicitly-typed per-arm-set predicate on the axis, matching the
328    /// discipline the sibling M2 [`crate::CaixaKind`] closed-set
329    /// discriminator already carries with `requires_lib`.
330    ///
331    /// Three consumers now route through this one typed dispatch: the
332    /// [`caixa-feira`](../../caixa_feira/cmd/dialeto/index.html) verb's
333    /// `--strict-palavra` gate (refusing a repo-surface declaration
334    /// still written as `(defcaixa …)`), the same verb's wrong-
335    /// declaration-under-`caixa.lisp` gate (refusing a repo-surface
336    /// declaration under the filename `feira` loads as a package
337    /// manifest), and [`crate::Caixa::from_lisp`]'s foreign-dialect
338    /// gate (raising [`crate::ManifestError::DialetoEstrangeiro`] before
339    /// the derive's `parse_kwargs_strict` walk on any `defmolde`-family
340    /// classification — the pre-lift hand-rolled three-arm
341    /// `match { Pacote => {}, Desconhecido => {}, foreign => Err(…) }`
342    /// literal whose `foreign =>` wildcard silently absorbed anything
343    /// non-Pacote-non-Desconhecido, now the third external consumer of
344    /// the `defmolde`-family partition).
345    #[must_use]
346    pub const fn is_molde_family(self) -> bool {
347        // Routed through the derive-generated per-arm predicates
348        // [`Self::is_molde`] + [`Self::is_molde_posicional`] so the
349        // two-arm collapse links compile-time back to the closed-set
350        // typed dispatch every peer arm-set predicate on the caixa
351        // surface (e.g. [`crate::CaixaKind::requires_lib`] on the
352        // sibling `:kind` axis) now carries. Byte-equivalent to the
353        // pre-lift `matches!(self, Self::Molde | Self::MoldePosicional)`
354        // form (the derived `is_*` predicates each expand to the same
355        // `matches!(self, Self::X)` shape by construction), but a
356        // future arm rename or IsVariant `#[is_variant(name = "…")]`
357        // override lands at exactly one dispatch on the substrate
358        // primitive rather than a hand-rolled two-arm literal.
359        self.is_molde() || self.is_molde_posicional()
360    }
361}
362
363/// [`std::fmt::Display`] routed through [`CaixaDialeto::as_str`], so the
364/// pretty-printed byte-string every consumer that formats the dialect as
365/// user-facing / census text lands on (the `feira dialeto` per-manifest
366/// `--list` row, the `feira dialeto` census summary line's per-arm
367/// counters, a future M4 admission-webhook's rejection body naming the
368/// accepted-dialect set) reaches for the same `PascalCase` per-arm
369/// byte-string the [`CaixaDialeto::as_str`] helper returns.
370///
371/// Prior to this lift the [`std::fmt::Display`] impl hand-rolled its own
372/// four-arm literal-string match — the one hand-rolled per-arm dispatch
373/// on the closed [`CaixaDialeto`] discriminator that had NO substrate
374/// primitive accessor to defer to (the sibling [`CaixaDialeto::palavra_canonica`] /
375/// [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`] projections
376/// carry distinct byte-shapes per axis, so none of them could serve as
377/// the Display source). A future variant addition (a fifth dialect the
378/// module doc's "third dialect" hazard actualises) would land one arm at
379/// the enum and per-arm returns at the paired accessors, but a hand-rolled
380/// [`std::fmt::Display`] match would silently drop the new arm to compile-
381/// fail-at-the-match-arm-site rather than through the shared substrate
382/// primitive. Routing [`std::fmt::Display`] through [`CaixaDialeto::as_str`]
383/// closes the last unlifted per-arm `PascalCase`-name projection on the
384/// caixa surface — the seventh (and last unlifted) closed-set fieldless
385/// typed enum on the caixa surface to converge onto the same
386/// `Display`-through-`as_str` discipline the six siblings
387/// ([`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`] /
388/// [`crate::supervisor::RestartPolicy`] /
389/// [`crate::aplicacao::PlacementStrategy`] / [`crate::aplicacao::RateLimitUnit`]
390/// / [`crate::dep::DepList`]) already carry.
391impl std::fmt::Display for CaixaDialeto {
392    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393        f.write_str(self.as_str())
394    }
395}
396
397/// Substrate-canonical [`AsRef<str>`] projection on the [`CaixaDialeto`]
398/// closed-set fieldless typed dialect-classification enum — routes through
399/// the same [`CaixaDialeto::as_str`] `pub const fn` scalar accessor the
400/// paired [`std::fmt::Display`] impl already delegates through, so any
401/// future consumer that binds a [`CaixaDialeto`] through the standard-
402/// library `impl AsRef<str>` bound (a [`std::process::Command::arg`]
403/// shell-out that composes the canonical `PascalCase` variant-name into a
404/// `feira dialeto --strict-palavra <Pacote|Molde|MoldePosicional|Desconhecido>`
405/// diagnostic overlay, a `tracing::field::Value::Str`-arm structured-log
406/// recorder on the [`crate::Caixa::from_lisp`] foreign-dialect
407/// [`crate::ManifestError::DialetoEstrangeiro`] refusal path, a
408/// [`std::collections::HashMap`] lookup keyed on the canonical name
409/// through `map.get::<str>(dialeto.as_ref())` on a future M4 admission-
410/// webhook's per-dialect rejection-body composition table) reaches the
411/// paired `"Pacote"` / `"Molde"` / `"MoldePosicional"` / `"Desconhecido"`
412/// byte-string through one substrate-primitive dispatch rather than an
413/// open-coded `.as_str()` re-inlining at every wire-up.
414///
415/// Same "route the trait impl through the substrate-primitive accessor"
416/// discipline the sibling [`crate::CaixaVersion`] [`AsRef<str>`] impl
417/// (16d5c7e), the paired M2 [`crate::supervisor::RestartStrategy`]
418/// [`AsRef<str>`] impl (63eb1a4), the paired M2
419/// [`crate::supervisor::RestartPolicy`] [`AsRef<str>`] impl (419ea81),
420/// the M3 [`crate::aplicacao::PlacementStrategy`] [`AsRef<str>`] impl
421/// (d86edd2), the M3 [`crate::aplicacao::RateLimitUnit`] [`AsRef<str>`]
422/// impl (d8136db), and the top-level [`crate::CaixaKind`] [`AsRef<str>`]
423/// impl (cd2091f) carry — extends the substrate primitive's
424/// [`AsRef<str>`] projection axis onto the seventh closed-set typed enum
425/// on the caixa surface: the dialect-classification axis previously
426/// carried [`fmt::Display`]-through-`as_str` but not yet the paired
427/// [`AsRef<str>`] impl, so a downstream consumer that bound the enum
428/// through the standard-library `AsRef<str>` trait had to reach the
429/// canonical byte-string through an open-coded `.as_str()` call rather
430/// than the trait-idiomatic `.as_ref()` the peer closed-set typed enums
431/// already admit.
432///
433/// Pinned load-bearing by
434/// [`tests::caixa_dialeto_as_ref_str_routes_through_as_str_accessor`]
435/// (byte-parity pin against [`CaixaDialeto::as_str`] across the four-arm
436/// closed set) and
437/// [`tests::caixa_dialeto_as_ref_str_routes_through_display_via_shared_accessor`]
438/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
439/// resolve to the same byte-string per arm) — any future silent detour
440/// that routes the impl through a divergent projection (a per-arm inline
441/// `match self { CaixaDialeto::Pacote => "Pacote", … }` re-inlining that
442/// opens a compile-time link to the un-lifted arm-literal, a swap onto
443/// the second-axis [`CaixaDialeto::palavra_canonica`] /
444/// [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`] accessors
445/// that carry distinct byte-shapes per axis) trips at caixa-core test
446/// time under `assert_eq!` rather than at a downstream
447/// `impl AsRef<str>`-bound consumer's silent split.
448impl AsRef<str> for CaixaDialeto {
449    fn as_ref(&self) -> &str {
450        self.as_str()
451    }
452}
453
454/// Trait-idiomatic reverse projection on the [`CaixaDialeto`] closed-set
455/// dialect-classification typed enum — routes byte-for-byte through the
456/// paired substrate-primitive [`CaixaDialeto::from_wire`] `Option<Self>`
457/// accessor so every future consumer that binds a `PascalCase` variant-
458/// name byte-string through the standard-library `.try_into()` /
459/// [`TryFrom`] axis (a future `feira dialeto --filter
460/// <Pacote|Molde|MoldePosicional|Desconhecido>` CLI arg-parse that
461/// composes into `let d: CaixaDialeto = s.try_into()?`, a future audit-
462/// report re-loader binding a prior [`CaixaDialeto::as_str`] output
463/// through `CaixaDialeto::try_from(&s)?`, a generic
464/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
465/// set typed enums) reaches the same four-arm accept-set the sibling
466/// [`CaixaDialeto::from_wire`] parses through and the sibling
467/// [`CaixaDialeto::as_str`] emits, rather than an open-coded per-arm
468/// `match s { "Pacote" => …, … }` cascade whose arm-set has no
469/// compile-time link back to the substrate primitive.
470///
471/// Complements the pre-existing forward-projection triple
472/// ([`std::fmt::Display`], [`AsRef<str>`], [`CaixaDialeto::as_str`]) with
473/// the paired trait-idiomatic reverse-projection axis: Rust-side
474/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
475/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
476/// caller who can project *out to* a `&str` can also project *in from*
477/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
478/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
479/// lint that the sibling method-named `from_wire` would trigger under a
480/// `FromStr` impl (the same design tradeoff the peer
481/// [`crate::CaixaKind`] `TryFrom<&str>` impl (3c83606) and the peer
482/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] block note)
483/// — this impl closes the trait-idiomatic reverse axis without disturbing
484/// the method-named `from_wire` shape every sibling closed-set typed
485/// enum on the substrate already carries.
486///
487/// `type Error = ()` matches the sibling [`CaixaDialeto::from_wire`]'s
488/// `Option<Self>` return-shape's deliberate deferral of error typing:
489/// the caller picks the diagnostic form appropriate for its use site
490/// (a future `feira dialeto --filter` arg-parse composes its own per-verb
491/// "unknown dialect: <arg> — accepted: {…}" message enumerating
492/// [`CaixaDialeto::ALL`], a future admission-webhook rejection body
493/// wraps the `Err(())` outcome with the accepted-set enumeration for
494/// operator diagnostics, a `Result::map_err` at the call site lifts the
495/// unit-error to a per-verb error type). Same shape the peer
496/// [`crate::CaixaKind`] `TryFrom<&str>` impl (3c83606) and the peer
497/// [`FerriteRuntime::from_wire`] doc block motivate on the sibling
498/// closed-set typed enums' reverse projections.
499///
500/// The paired [`TryFrom<&str>`] impl reaches the same four-arm accept-
501/// set the [`CaixaDialeto::from_wire`] resolver dispatches through, so
502/// any future arm addition (the module doc's "third dialect" hazard
503/// actualises as a fifth arm belonging to the `defmolde` family or a
504/// wholly new declaration) grows the trait-idiomatic axis by
505/// construction — one caixa-core edit on [`CaixaDialeto::from_wire`]
506/// extends both the method-named reverse projection every existing
507/// consumer keys off and the trait-idiomatic reverse projection this
508/// impl exposes, without a coordinated rewrite across every future
509/// `TryFrom<&str>`-bound consumer's arm-set.
510///
511/// Pinned load-bearing by
512/// [`tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
513/// (byte-parity pin against [`CaixaDialeto::from_wire`] across the four-
514/// arm accept-set) and
515/// [`tests::caixa_dialeto_try_from_str_rejects_unknown_byte_strings`]
516/// (rejection witness against silent accept-set widening).
517impl TryFrom<&str> for CaixaDialeto {
518    type Error = ();
519
520    fn try_from(s: &str) -> Result<Self, Self::Error> {
521        Self::from_wire(s).ok_or(())
522    }
523}
524
525/// Trait-idiomatic forward projection on the [`CaixaDialeto`] closed-set
526/// dialect-classification typed enum — routes byte-for-byte through the
527/// sibling substrate-primitive [`CaixaDialeto::as_str`] `pub const fn`
528/// accessor so every future consumer that needs `&'static str` lifetime
529/// bytes on the dialect-classification axis (a
530/// `tracing::field::valuable::Value::Str` recording where the `Str` arm's
531/// typing demands `&'static str`, a
532/// `Cow::Borrowed::<'static, str>(dialeto.into())` composer on the future
533/// M4 admission-webhook rejection body where the `Cow<'static, str>`
534/// typing rules out the sibling [`AsRef<str>`] borrowed return, a generic
535/// `<T: Into<&'static str>>`-bound serializer or error formatter that
536/// requires the `'static` bound) reaches the same four `"Pacote"` /
537/// `"Molde"` / `"MoldePosicional"` / `"Desconhecido"` byte-strings the
538/// sibling [`CaixaDialeto::as_str`] emitter returns, rather than an
539/// open-coded per-arm literal cascade whose arm-set has no compile-time
540/// link back to the substrate primitive.
541///
542/// Return type is `&'static str` by construction — every
543/// [`CaixaDialeto::as_str`] arm resolves to a compile-time `pub const fn`
544/// return of a `&'static str` literal, so the trait's return-type promise
545/// is upheld structurally without a `String::leak()` cast or a per-arm
546/// inline literal.
547///
548/// Complements the pre-existing reverse-projection axis pair
549/// ([`TryFrom<&str>`] above + method-named [`CaixaDialeto::from_wire`])
550/// with the trait-idiomatic forward-projection axis: Rust-side
551/// newtype/typed-enum convention pairs [`TryFrom<&str>`] with the mirror-
552/// image [`From<Self> for &'static str`] on the same primitive so a
553/// caller who can project *in from* a `&str` can also project *out to*
554/// one under a `'static`-lifetime bound. The
555/// [`AsRef<str>`] impl already carries the same emit-set on the borrowed
556/// return path; this impl closes the trait-idiomatic axis pair with the
557/// stricter `&'static str` lifetime the sibling `AsRef<str>` cannot
558/// promise (its return borrows from `&self`, not from the
559/// [`CaixaDialeto::as_str`] `pub const fn`'s static-string result).
560///
561/// Same "route the trait impl through the substrate-primitive accessor"
562/// discipline the sibling [`crate::supervisor::RestartStrategy`]
563/// `From<Self> for &'static str` impl (523157d — first-mover on this
564/// forward-projection family), [`crate::supervisor::RestartPolicy`]
565/// `From<Self> for &'static str` impl (9fb37d0 — second peer, closing
566/// the M2 OTP-shape sibling pair), and [`crate::CaixaKind`]
567/// `From<Self> for &'static str` impl (edb827b — third peer, opening
568/// the campaign onto the top-level caixa surface) carry — extends the
569/// substrate primitive's trait-idiomatic forward-projection axis onto
570/// the fourth closed-set fieldless typed enum on the caixa surface: the
571/// dialect-classification axis, previously carrying the paired
572/// [`std::fmt::Display`] / [`AsRef<str>`] / [`CaixaDialeto::as_str`] /
573/// [`TryFrom<&str>`] / [`CaixaDialeto::from_wire`] forward+reverse
574/// projections but not yet the trait-idiomatic forward projection with
575/// the `&'static str` lifetime bound.
576///
577/// Unlike the peer [`crate::CaixaKind`] impl (which carries a two-axis
578/// split between the lowercase Portuguese `as_str` diagnostic axis and
579/// the `PascalCase` `wire_name` author-surface axis, so the trait's
580/// round-trip witness must cross through the wire axis rather than
581/// composing the two trait impls directly), [`CaixaDialeto`] is an
582/// internal classification whose [`CaixaDialeto::as_str`] output and
583/// [`CaixaDialeto::from_wire`] input share the same `PascalCase`
584/// vocabulary by construction — the trait-idiomatic axis pair
585/// ([`From<Self> for &'static str`] + [`TryFrom<&str> for Self`])
586/// therefore round-trips directly, without an intermediate wire-vocab
587/// hop.
588///
589/// The paired [`CaixaDialeto::as_str`] accessor's four-arm emit-set is
590/// the single source of truth — every future arm addition (the module
591/// doc's "third dialect" hazard actualises as a fifth arm belonging to
592/// the `defmolde` family or a wholly new declaration) grows the trait-
593/// idiomatic forward axis by construction: one caixa-core edit on
594/// [`CaixaDialeto::as_str`] extends every one of the sibling forward-
595/// projection paths ([`std::fmt::Display`], [`AsRef<str>`],
596/// [`CaixaDialeto::as_str`] itself, and this
597/// [`From<Self> for &'static str`]) without a coordinated rewrite across
598/// every future `Into<&'static str>`-bound consumer's arm-set. This lift
599/// closes the fourth peer on the trait-idiomatic forward-projection
600/// campaign the recently-landed peer commits opened; the remaining ten
601/// closed-set typed enums on the caixa substrate surface
602/// (`PlacementStrategy`, `WitShape`, `RateLimitUnit`,
603/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
604/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
605/// of this campaign.
606///
607/// Pinned load-bearing by
608/// [`tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
609/// (byte-parity pin against [`CaixaDialeto::as_str`] across the four-arm
610/// emit-set, plus a `const`-context materialization witness for the
611/// `&'static str` lifetime promise, plus a paired `.into()` shape
612/// assertion covering the blanket-derived `Into<&'static str>` shape)
613/// and
614/// [`tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
615/// (partition pin asserting `<&'static str as From<CaixaDialeto>>::from`
616/// and [`CaixaDialeto::as_str`] agree on every arm, plus a two-way
617/// direct round-trip witness through the paired trait-idiomatic
618/// [`TryFrom<&str>`] axis that closes the two-way `Self ↔ &'static str`
619/// round-trip on the trait-idiomatic axis pair without the wire-vocab
620/// intermediate the peer [`crate::CaixaKind`] axis pair requires).
621impl From<CaixaDialeto> for &'static str {
622    fn from(dialeto: CaixaDialeto) -> &'static str {
623        dialeto.as_str()
624    }
625}
626
627/// Trait-idiomatic *forward* projection on [`CaixaDialeto`] from a
628/// *borrowed* input onto the `&'static str` axis — the borrowed-input
629/// companion to the paired owned-input [`From<CaixaDialeto> for &'static
630/// str`] impl immediately above. Routes byte-for-byte through the same
631/// substrate-primitive [`CaixaDialeto::as_str`] `pub const fn` accessor so
632/// every consumer that binds a `&CaixaDialeto` through the standard-
633/// library `.into()` / [`From<&Self> for &'static str`] axis (a
634/// `CaixaDialeto::ALL.iter().map(<&'static str>::from).collect::<Vec<_>>()`
635/// per-arm accept-set materializer — whose iterator over
636/// `&'static [CaixaDialeto]` yields `&CaixaDialeto`, not `CaixaDialeto`,
637/// so the owned-input [`From<CaixaDialeto>`] axis alone forces every call
638/// site through an explicit `.copied()` / dereference / [`Copy`]-bound
639/// restatement rather than the direct trait-idiomatic projection; a
640/// future generic `<T: Copy + for<'a> Into<&'static str>>`-bound
641/// diagnostic column that walks the `iter().map(Into::into)` shape
642/// verbatim over any of the substrate's closed-set typed enums; the
643/// future M4 admission-webhook rejection body composer's per-dialect
644/// accepted-set enumeration built from an iterated
645/// `CaixaDialeto::ALL.iter().map(|d| d.into())` pipe rather than a
646/// per-arm `match d { … }` cascade; a
647/// `HashMap::<&'static str, CaixaDialeto>::from_iter(
648///     CaixaDialeto::ALL.iter().map(|d| (d.into(), *d)))`-style
649/// per-dialect reverse-lookup table the sibling [`TryFrom<&str>`] impl
650/// cannot compose without this borrowed-input axis in place) reaches the
651/// same four `"Pacote"` / `"Molde"` / `"MoldePosicional"` /
652/// `"Desconhecido"` byte-strings the paired owned-input
653/// [`From<CaixaDialeto> for &'static str`], the sibling
654/// [`std::fmt::Display`], [`AsRef<str>`], and [`CaixaDialeto::as_str`]
655/// surfaces already return.
656///
657/// Third peer on the substrate-wide trait-idiomatic *borrowed-input*
658/// forward-projection family opened on
659/// [`crate::dep::DepList`] (64aa742) and extended onto
660/// [`crate::CaixaKind`] (5ab993a). Rust's `From` trait does not
661/// auto-derive the `From<&Self>` sibling from a `From<Self>` impl (the
662/// blanket `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does
663/// not exist in `core`), so every closed-set typed enum that carries
664/// the owned-input axis but not the borrowed-input axis forces every
665/// borrowed-input call site through a `.copied()` /
666/// `<&'static str>::from(*dialeto)` / `dialeto.as_str()` detour whose
667/// type bounds have no compile-time link to the substrate primitive.
668///
669/// Unlike the peer [`crate::CaixaKind`] impl (which carries a two-axis
670/// split between the lowercase Portuguese `as_str` diagnostic axis and
671/// the `PascalCase` `wire_name` author-surface axis, so a `.into()`
672/// pipe over `CaixaKind::ALL` yields the diagnostic vocabulary rather
673/// than the wire vocabulary), [`CaixaDialeto`]'s [`CaixaDialeto::as_str`]
674/// and [`CaixaDialeto::from_wire`] share the same `PascalCase`
675/// vocabulary by construction — the borrowed-input projection this impl
676/// exposes therefore composes directly with the sibling
677/// [`TryFrom<&str>`] axis to build reverse-lookup tables without the
678/// wire-vocab intermediate hop the peer axis pair requires.
679///
680/// Pinned load-bearing by
681/// [`tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
682/// (byte-parity pin against [`CaixaDialeto::as_str`] across the four-arm
683/// emit-set via a borrowed input, plus a `const`-context materialization
684/// witness for the `&'static str` lifetime promise, plus a blanket
685/// `.into()` shape assertion) and
686/// [`tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
687/// (cross-axis partition pin against the paired owned-input
688/// [`From<CaixaDialeto> for &'static str`] impl, plus a
689/// `.iter().map(Into::into)` pipe witness over [`CaixaDialeto::ALL`]
690/// that materializes the four-arm accept-set through the borrowed-input
691/// axis alone, plus a direct round-trip witness through the paired
692/// trait-idiomatic [`TryFrom<&str>`] axis that closes the two-way
693/// `&Self → &'static str → Self` round-trip on the borrowed-input axis
694/// without the wire-vocab intermediate the peer [`crate::CaixaKind`]
695/// axis pair requires).
696impl From<&CaixaDialeto> for &'static str {
697    fn from(dialeto: &CaixaDialeto) -> &'static str {
698        dialeto.as_str()
699    }
700}
701
702/// Trait-idiomatic *forward* projection on [`CaixaDialeto`] from an *owned*
703/// input onto the owned-[`String`] axis — routes byte-for-byte through the
704/// substrate-primitive [`CaixaDialeto::as_str`] `pub const fn` accessor so
705/// every consumer that binds a [`CaixaDialeto`] through the standard-library
706/// `.into()` / [`From<Self> for String`] (equivalently [`Into<String>`]) axis
707/// reaches the same four `"Pacote"` / `"Molde"` / `"MoldePosicional"` /
708/// `"Desconhecido"` byte-strings the paired owned-input
709/// [`From<CaixaDialeto> for &'static str`], the borrowed-input
710/// [`From<&CaixaDialeto> for &'static str`], the sibling [`std::fmt::Display`],
711/// [`AsRef<str>`], and [`CaixaDialeto::as_str`] surfaces already return.
712///
713/// Extends the trait-idiomatic *owned-[`String`]* forward-projection family
714/// (opened on [`crate::supervisor::RestartStrategy`] — 7baa18a — the first-
715/// mover on the M2 OTP-shape sibling-restart-strategy axis, extended onto
716/// [`crate::supervisor::RestartPolicy`] — 7851725 — the second-of-two-in-M2
717/// per-child restart-decision axis, then onto [`crate::CaixaKind`] — 231a18c
718/// — the structurally most fundamental closed-set fieldless typed enum on
719/// the caixa surface) onto the fourth peer: the dialect-classification axis
720/// [`CaixaDialeto`] carries. Rust's standard library does not carry a blanket
721/// `impl<T: AsRef<str>> From<T> for String` (nor an
722/// `impl<T: fmt::Display> From<T> for String`), so every closed-set typed
723/// enum that carries the paired `AsRef<str>` / `Display` /
724/// `From<Self> for &'static str` triple but not the owned-[`String`] axis
725/// forces every owned-string call site through a `.to_string()` /
726/// `.as_str().to_owned()` / `String::from(dialeto.as_str())` detour whose
727/// type bounds have no compile-time link to the substrate primitive.
728///
729/// Unlike the peer [`crate::CaixaKind`] enum (which carries a two-axis split
730/// between the lowercase Portuguese [`crate::CaixaKind::as_str`] diagnostic
731/// axis and the `PascalCase` [`crate::CaixaKind::wire_name`] author-surface
732/// axis, so the owned-[`String`] forward emit and the reverse
733/// [`TryFrom<&str>`] parse land on disjoint vocabularies and the round-trip
734/// crosses through [`crate::CaixaKind::wire_name`] as the reverse-axis
735/// vocabulary rather than composing the owned-[`String`] emit directly),
736/// [`CaixaDialeto`]'s [`CaixaDialeto::as_str`] emit and
737/// [`CaixaDialeto::from_wire`] parse share the same `PascalCase` vocabulary
738/// by construction (there is no wire/diagnostic axis split on this enum —
739/// it is an internal classification with no wire surface), so the
740/// owned-[`String`] forward projection this impl exposes composes directly
741/// with the sibling [`TryFrom<&str>`] axis on the owned-[`String`]'s
742/// [`String::as_str`] borrow, byte-identically to the peer
743/// [`crate::supervisor::RestartStrategy`] /
744/// [`crate::supervisor::RestartPolicy`] owned-[`String`] axis pairs
745/// (whose forward emit and reverse parse also share one `PascalCase`
746/// vocabulary by construction).
747///
748/// The remaining ten closed-set typed enums on the caixa substrate surface
749/// (`DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
750/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
751/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
752/// this campaign — each carries the same paired `AsRef<str>` / `Display` /
753/// `From<Self> for &'static str` / `From<&Self> for &'static str` quadruple
754/// that this owned-[`String`] axis extends onto.
755///
756/// Pinned load-bearing by
757/// [`tests::caixa_dialeto_from_into_owned_string_routes_through_as_str_accessor`]
758/// (byte-parity pin against [`CaixaDialeto::as_str`] across the four-arm
759/// emit-set, plus a blanket `.into::<String>()` shape witness) and
760/// [`tests::caixa_dialeto_from_into_owned_string_and_static_str_agree_on_every_arm`]
761/// (cross-axis partition pin against the paired owned-input
762/// [`From<CaixaDialeto> for &'static str`] impl and the sibling
763/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
764/// plus a `.iter().copied().map(String::from)` pipe witness over
765/// [`CaixaDialeto::ALL`], plus a direct round-trip witness through
766/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`] borrow
767/// that closes the two-way `Self → String → Self` round-trip on the
768/// trait-idiomatic owned-[`String`] forward + reverse axis pair without
769/// the wire-vocab intermediate hop the peer [`crate::CaixaKind`] axis pair
770/// requires).
771impl From<CaixaDialeto> for String {
772    fn from(dialeto: CaixaDialeto) -> String {
773        dialeto.as_str().to_owned()
774    }
775}
776
777/// A source that is not a `(defcaixa …)` / `(defmolde …)` form at all.
778#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
779pub enum DialetoError {
780    #[error("source has no top-level form")]
781    Vazio,
782    #[error("top-level form is not a list — a manifest is `(defcaixa …)`")]
783    NaoEhLista,
784    #[error(
785        "top-level form is headed by `{encontrado}`, not `defcaixa` or `defmolde` \
786         (a manifest's first form must be the declaration itself)"
787    )]
788    CabecaErrada { encontrado: String },
789    #[error("manifest does not parse as tatara-lisp: {0}")]
790    Leitura(String),
791}
792
793impl DialetoError {
794    /// Construct a [`DialetoError::CabecaErrada`] naming the offending
795    /// head symbol found at the top-level form.
796    ///
797    /// Substrate primitive every [`classify_form`] wrong-head fallthrough
798    /// wire-up site now routes through, folding the pre-lift uniform
799    /// three-line `Self::CabecaErrada { encontrado: <head>.to_string() }`
800    /// one-field struct-literal onto one substrate primitive matching the
801    /// peer `LimitsError::unknown_byte_unit(unit: &str)` /
802    /// `LimitsError::unknown_duration_unit(unit: &str)`
803    /// (`limits_codec_unit_only_ctors!` — 29fac09) single-slot
804    /// discipline on the sibling one-field `{ <field>: String }` envelope
805    /// axis, and matching the peer `ManifestError::code_path_empty` /
806    /// `BehaviorError::empty_path` / `UpgradeError::duplicate_from` /
807    /// `AplicacaoError::placement_cluster_duplicate` (94dabc8 / 0e33b37 /
808    /// 7e52aec / 92b1c92) single-slot inherent-ctor discipline every
809    /// sibling `{ <field>: <T> }` error-envelope variant on caixa-core's
810    /// error surface now carries.
811    ///
812    /// The one open-coded wire-up site — `classify_form`'s wrong-head
813    /// fallthrough arm on the `head: &str` binding read from the
814    /// top-level form via [`tatara_lisp::Sexp::as_symbol`] — opened the
815    /// identical three-line
816    /// `Self::CabecaErrada { encontrado: <head>.to_string() }` block
817    /// against the codec-scoped `<head>: &str` binding. Now routes
818    /// through `DialetoError::cabeca_errada(head)`, byte-equal to the
819    /// pre-lift struct-literal on the same `&str` fixture, so any future
820    /// widening of the diagnostic shape (e.g. carrying the source-file
821    /// path alongside the head symbol, carrying the head symbol's
822    /// position offset for an authoring-surface caret pointer) lands at
823    /// exactly one dispatch on the substrate primitive rather than re-
824    /// inlining the struct-literal at every wrong-head fallthrough
825    /// consumer.
826    #[must_use]
827    pub fn cabeca_errada(encontrado: &str) -> Self {
828        Self::CabecaErrada {
829            encontrado: encontrado.to_string(),
830        }
831    }
832
833    /// Construct a [`DialetoError::Leitura`] carrying the offending
834    /// tatara-lisp reader-error message `reason` verbatim in the
835    /// variant's tuple-newtype payload.
836    ///
837    /// Substrate primitive every [`classify`] tatara-lisp-reader
838    /// map-err wire-up site now routes through, folding the pre-lift
839    /// uniform `Self::Leitura(<into-String-expr>)` tuple-newtype
840    /// construction onto one substrate primitive matching the peer
841    /// `LimitsError::empty_byte_size` / `LimitsError::empty_duration`
842    /// (7a4b003 / 319216c) `(String)` single-slot tuple-newtype
843    /// discipline on the sibling
844    /// [`crate::limits::LimitsError`] envelope's empty-shape axis of
845    /// the paired codec-magnitude family. Peer to the sibling
846    /// [`DialetoError::cabeca_errada`] ctor on the same envelope's
847    /// wrong-head axis but on the tatara-lisp-reader axis rather than
848    /// the classifier-fallthrough axis. Closes the last un-lifted
849    /// variant on [`DialetoError`] — every one of the sole wire-up
850    /// sites (the [`classify`] tatara-lisp-reader `.map_err(|e|
851    /// Self::Leitura(e.to_string()))` arm) opened the identical
852    /// `DialetoError::Leitura(<into-String-expr>)` block against the
853    /// codec-scoped `String` (`e.to_string()`) binding, so the fold
854    /// routes the site through one dispatch on a uniform
855    /// `impl Into<String>` param, byte-equal to the pre-lift
856    /// tuple-newtype construction on the same argument.
857    ///
858    /// The `impl Into<String>` bound covers both wire-up shapes on
859    /// [`classify`] — a `String` binding (`e.to_string()` on the
860    /// [`tatara_lisp::Error`]-carrying `e` binding) and a `&str`
861    /// binding (a future admission-webhook consumer probing a
862    /// caller-scoped `&'static str` fixture, a future
863    /// `feira lint --tatara-reader-round-trip` verb sweeping every
864    /// `tatara_lisp::read` return through the same shape gate) —
865    /// without forcing the caller to spell the conversion at the
866    /// wire-up site. Same shape the peer
867    /// [`crate::limits::LimitsError::empty_byte_size`] /
868    /// [`crate::limits::LimitsError::empty_duration`] /
869    /// [`crate::limits::LimitsError::bad_millicores`] /
870    /// [`crate::limits::LimitsError::bad_byte_magnitude`] /
871    /// [`crate::limits::LimitsError::bad_duration_magnitude`] folds
872    /// carry on the peer bad-magnitude and empty-shape axes of the
873    /// same paired `(String)` tuple-newtype codec-magnitude family.
874    /// `#[must_use]` fires a compile warning at any wire-up that
875    /// mistakenly discards the constructed error.
876    ///
877    /// Every future consumer that wants to construct this variant
878    /// outside [`classify`] (a deferred `feira lint --tatara-reader-
879    /// round-trip` per-caixa admission verb probing each authored
880    /// manifest against the tatara-lisp-reader shape gate, an M4
881    /// typed `mesh.pleme.io/v1alpha1/Servico` CR materializer's
882    /// per-manifest admission validator re-checking one edited
883    /// `caixa.lisp` against the reader floor, a per-`caixa.lisp`
884    /// value-shape pre-emitter probing each declared manifest ahead
885    /// of the operator's admit-cycle) now reaches the variant
886    /// through one call rather than re-inlining the tuple-newtype
887    /// block in lockstep with the pre-existing wire-up.
888    #[must_use]
889    pub fn leitura(reason: impl Into<String>) -> Self {
890        Self::Leitura(reason.into())
891    }
892}
893
894/// Classify a manifest source without committing to either schema.
895///
896/// Deliberately reads only the head symbol and the set of top-level keywords —
897/// enough to route, never enough to half-parse. A classifier that started
898/// validating would grow into a third parser, which is the shape of the problem
899/// it exists to name.
900///
901/// # Errors
902/// [`DialetoError`] when the source is not a manifest declaration at all.
903pub fn classify(src: &str) -> Result<CaixaDialeto, DialetoError> {
904    let forms = tatara_lisp::read(src).map_err(|e| DialetoError::leitura(e.to_string()))?;
905    let first = forms.first().ok_or(DialetoError::Vazio)?;
906    classify_form(first)
907}
908
909/// [`classify`] over an already-read form.
910///
911/// # Errors
912/// [`DialetoError`] when the form is not a manifest declaration.
913pub fn classify_form(form: &Sexp) -> Result<CaixaDialeto, DialetoError> {
914    let list = form.as_list().ok_or(DialetoError::NaoEhLista)?;
915    let head = list
916        .first()
917        .and_then(Sexp::as_symbol)
918        .ok_or(DialetoError::NaoEhLista)?;
919
920    match head {
921        // `defmolde` is unambiguous by construction — it exists precisely so a
922        // consumer never has to infer which declaration it holds. Both arities
923        // are the same declaration; the positional one keeps its own variant
924        // only so a census can report the split.
925        "defmolde" => {
926            return Ok(if starts_with_positional_name(&list[1..]) {
927                CaixaDialeto::MoldePosicional
928            } else {
929                CaixaDialeto::Molde
930            });
931        }
932        "defcaixa" => {}
933        other => {
934            return Err(DialetoError::cabeca_errada(other));
935        }
936    }
937
938    let args = &list[1..];
939
940    // `(defcaixa <symbol> :kind … :ecosystem …)`. Only the Molde dialect has a
941    // positional arity; `Caixa` is keyword-only, so a leading bare symbol
942    // settles it without looking further.
943    if starts_with_positional_name(args) {
944        return Ok(CaixaDialeto::MoldePosicional);
945    }
946
947    let keys = top_level_keywords(args);
948    let has = |k: &str| keys.iter().any(|s| s == k);
949
950    // Order matters, and it is not arbitrary: `:nome` and `:name` are the two
951    // required head slots and no file in the measured corpus carries both.
952    // Checking them FIRST means the decision rests on the one slot each schema
953    // makes mandatory, rather than on optional evidence like `:ecosystem`.
954    if has("nome") {
955        return Ok(CaixaDialeto::Pacote);
956    }
957    if has("name") || has("ecosystem") || has("package") {
958        return Ok(CaixaDialeto::Molde);
959    }
960    Ok(CaixaDialeto::Desconhecido)
961}
962
963/// True when the first argument is a bare symbol rather than a keyword — the
964/// positional-name arity.
965fn starts_with_positional_name(args: &[Sexp]) -> bool {
966    matches!(args.first(), Some(Sexp::Atom(Atom::Symbol(_))))
967}
968
969/// The top-level keyword names (without the leading `:`) of a kwarg list.
970///
971/// Steps in pairs so a keyword appearing as a VALUE — `:kind :Biblioteca`, or a
972/// nested `(:nome "dep" :versao "^0.1")` inside `:deps` — is never counted as a
973/// top-level slot. A naive scan for `:nome` anywhere in the source classifies
974/// every Molde manifest with a `:deps` list as a Pacote.
975fn top_level_keywords(args: &[Sexp]) -> Vec<String> {
976    let mut out = Vec::new();
977    let mut i = 0;
978    while i < args.len() {
979        if let Sexp::Atom(Atom::Keyword(k)) = &args[i] {
980            out.push(k.clone());
981            i += 2;
982        } else {
983            i += 1;
984        }
985    }
986    out
987}
988
989#[cfg(test)]
990mod tests {
991    use super::*;
992
993    const PACOTE: &str = r#"
994      (defcaixa
995        :nome   "checkout"
996        :versao "0.1.0"
997        :kind   Servico
998        :deps   ((:nome "caixa-teia" :versao "^0.1")))
999    "#;
1000
1001    const MOLDE: &str = r#"
1002      (defcaixa
1003        :name "base64"
1004        :kind :Biblioteca
1005        :ecosystem :rust-single-crate
1006        :package {:name "base64" :version "0.22.1"}
1007        :workflows [:auto-release])
1008    "#;
1009
1010    const MOLDE_POSICIONAL: &str = r#"
1011      (defcaixa todoku-go
1012        :kind :Biblioteca
1013        :ecosystem :go
1014        :package {:name "todoku-go" :version "0.3.0"})
1015    "#;
1016
1017    #[test]
1018    fn the_package_dialect_is_recognised() {
1019        assert_eq!(classify(PACOTE), Ok(CaixaDialeto::Pacote));
1020    }
1021
1022    #[test]
1023    fn the_repo_surface_dialect_is_recognised() {
1024        assert_eq!(classify(MOLDE), Ok(CaixaDialeto::Molde));
1025    }
1026
1027    #[test]
1028    fn the_positional_arity_is_recognised() {
1029        assert_eq!(
1030            classify(MOLDE_POSICIONAL),
1031            Ok(CaixaDialeto::MoldePosicional)
1032        );
1033    }
1034
1035    #[test]
1036    fn defmolde_classifies_without_inference() {
1037        // The whole point of the new keyword: no schema sniffing required.
1038        let src = r#"(defmolde :name "x" :kind :Biblioteca :ecosystem :go)"#;
1039        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
1040        let pos = r"(defmolde todoku-go :kind :Biblioteca :ecosystem :go)";
1041        assert_eq!(classify(pos), Ok(CaixaDialeto::MoldePosicional));
1042    }
1043
1044    #[test]
1045    fn a_nested_nome_does_not_make_a_repo_surface_look_like_a_package() {
1046        // The exact failure a substring scan produces: `:deps ((:nome …))`
1047        // contains `:nome`, but not as a top-level slot.
1048        let src = r#"
1049          (defcaixa
1050            :name "x"
1051            :ecosystem :rust-single-crate
1052            :deps ((:nome "inner" :versao "^0.1")))
1053        "#;
1054        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
1055    }
1056
1057    #[test]
1058    fn a_keyword_in_value_position_is_not_a_slot() {
1059        // `:kind :Biblioteca` — the value is itself a keyword. Stepping one at
1060        // a time would read `:Biblioteca` as a top-level slot.
1061        let src = r#"(defcaixa :kind :Biblioteca :name "x")"#;
1062        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
1063    }
1064
1065    #[test]
1066    fn an_unrecognised_defcaixa_is_reported_not_guessed() {
1067        let src = r#"(defcaixa :licenca "MIT")"#;
1068        assert_eq!(classify(src), Ok(CaixaDialeto::Desconhecido));
1069    }
1070
1071    #[test]
1072    fn a_form_that_is_not_a_manifest_is_an_error_not_a_dialect() {
1073        assert_eq!(
1074            classify("(defflake :nome \"x\")"),
1075            Err(DialetoError::cabeca_errada("defflake"))
1076        );
1077        assert_eq!(classify(""), Err(DialetoError::Vazio));
1078    }
1079
1080    #[test]
1081    fn every_dialect_names_its_consumer_and_its_canonical_keyword() {
1082        // Guards the routing table itself: a new variant added without an arm
1083        // here is a compile error in the match, and a variant that claims
1084        // `defcaixa` while being read by pleme-doc-gen would re-open the
1085        // collision this module closes. Sweeps [`CaixaDialeto::ALL`] rather
1086        // than the pre-lift open-coded four-arm literal list — a future arm
1087        // addition extends the slice as one edit and this pin picks it up
1088        // by construction.
1089        for &d in CaixaDialeto::ALL {
1090            assert!(!d.descricao().is_empty(), "{d}");
1091            assert!(!d.consumidor().is_empty(), "{d}");
1092        }
1093        assert_eq!(CaixaDialeto::Pacote.palavra_canonica(), "defcaixa");
1094        assert_eq!(CaixaDialeto::Molde.palavra_canonica(), "defmolde");
1095        assert_ne!(
1096            CaixaDialeto::Pacote.palavra_canonica(),
1097            CaixaDialeto::Molde.palavra_canonica(),
1098            "the two dialects must not share a canonical keyword — that IS the defect"
1099        );
1100    }
1101
1102    #[test]
1103    fn caixa_dialeto_all_enumerates_every_variant_exactly_once() {
1104        // Three-legged exhaustiveness pin, peer of the sibling
1105        // `caixa_kind_all_enumerates_every_variant_exactly_once`
1106        // (caixa-core/src/kind.rs) /
1107        // `restart_strategy_all_enumerates_every_variant_exactly_once`
1108        // (caixa-core/src/supervisor.rs) shape.
1109        //
1110        // 1. arm-count invariant: `ALL.len()` matches the declared arm
1111        //    count (four — a fifth arm added without extending `ALL`
1112        //    fails this pin at caixa-core test time);
1113        // 2. pairwise-distinctness invariant: every variant appears at
1114        //    most once in the slice (a duplicate arm would silently
1115        //    double-count in the census consumer, so the pin rejects
1116        //    duplicates outright);
1117        // 3. coverage invariant: every literal `CaixaDialeto::X` is in
1118        //    the slice (the compiler-checked exhaustiveness on the peer
1119        //    per-arm `match self` in the accessors keeps the enum arm
1120        //    set and the `ALL` slice mutually aligned).
1121        assert_eq!(
1122            CaixaDialeto::ALL.len(),
1123            4,
1124            "ALL must list every arm exactly once; a fifth arm added \
1125             without extending ALL fails this pin — extend ALL alongside \
1126             the new variant"
1127        );
1128
1129        let mut seen: Vec<CaixaDialeto> = Vec::new();
1130        for &d in CaixaDialeto::ALL {
1131            assert!(
1132                !seen.contains(&d),
1133                "ALL contains a duplicate arm: {d}. Every variant appears \
1134                 exactly once — a duplicate would double-count in every \
1135                 iteration consumer"
1136            );
1137            seen.push(d);
1138        }
1139
1140        // Coverage: exhaustively assert every literal variant is somewhere
1141        // in the slice. Written as an exhaustive `match` so a future arm
1142        // addition fails to compile here (missing match arm) until the
1143        // corresponding `assert` is added — the compiler enforces the pin's
1144        // completeness rather than a hand-maintained variant list.
1145        for variant in [
1146            CaixaDialeto::Pacote,
1147            CaixaDialeto::Molde,
1148            CaixaDialeto::MoldePosicional,
1149            CaixaDialeto::Desconhecido,
1150        ] {
1151            let coverage_probe = match variant {
1152                CaixaDialeto::Pacote
1153                | CaixaDialeto::Molde
1154                | CaixaDialeto::MoldePosicional
1155                | CaixaDialeto::Desconhecido => variant,
1156            };
1157            assert!(
1158                CaixaDialeto::ALL.contains(&coverage_probe),
1159                "ALL is missing variant {coverage_probe} — extend the slice"
1160            );
1161        }
1162    }
1163
1164    #[test]
1165    fn caixa_dialeto_all_is_const_and_matches_iteration_count() {
1166        // Pins the const-ness of the slice at const-fold time. A future
1167        // change that promoted `ALL` to a non-const initializer (a lazy-
1168        // static, a runtime-computed Vec) would fail to compile here —
1169        // the pin locks in the compile-time-known iteration surface
1170        // every consumer builds against. Peer of the sibling
1171        // `caixa_kind_all_is_const_and_matches_iteration_count` (kind.rs)
1172        // / `restart_strategy_all_is_const_and_matches_iteration_count`
1173        // (supervisor.rs) shape.
1174        const ALL: &[CaixaDialeto] = CaixaDialeto::ALL;
1175        assert_eq!(ALL.len(), CaixaDialeto::ALL.len());
1176        // Sweep the iterator without collapsing to `.len()` so a future
1177        // change to `ALL`'s carrier that decouples `.len()` from the
1178        // iteration count (a lazy-computed shape, an alias `impl Iterator`
1179        // return, a wrapper newtype) still passes here iff the two agree
1180        // arm-for-arm; the `#[allow]` opts this local pin out of the
1181        // clippy `iter_count` collapse that would defeat the intent.
1182        #[allow(clippy::iter_count)]
1183        let iterated = ALL.iter().count();
1184        assert_eq!(iterated, CaixaDialeto::ALL.len());
1185    }
1186
1187    #[test]
1188    fn caixa_dialeto_all_covers_every_variant_by_display_probe() {
1189        // Fanning `Display` over the slice sweeps the paired accessors
1190        // ([`CaixaDialeto::palavra_canonica`] / [`CaixaDialeto::consumidor`]
1191        // / [`CaixaDialeto::descricao`]) at every arm — every returned
1192        // byte-string is non-empty (the accessors' contract). A future
1193        // arm added without extending its per-arm `match self` return
1194        // would compile-fail at the accessor call inside the loop;
1195        // together with the `ALL.len() == 4` pin above, this locks the
1196        // accessor arm-set and the `ALL` slice mutually.
1197        for &d in CaixaDialeto::ALL {
1198            let display_form = d.to_string();
1199            assert!(
1200                !display_form.is_empty(),
1201                "Display must render a non-empty byte-string for every \
1202                 arm; empty: {d:?}"
1203            );
1204            // Consumidor / descricao / palavra-canonica must each surface
1205            // a non-empty scalar; every downstream diagnostic consumer
1206            // reaches through these accessors.
1207            assert!(!d.palavra_canonica().is_empty(), "{d}");
1208            assert!(!d.consumidor().is_empty(), "{d}");
1209            assert!(!d.descricao().is_empty(), "{d}");
1210        }
1211    }
1212
1213    #[test]
1214    fn caixa_dialeto_as_str_returns_pascal_case_variant_name() {
1215        // Fail-before-pass-after per-arm shape pin: the four
1216        // [`CaixaDialeto::as_str`] arms must return the canonical
1217        // `PascalCase` byte-string that names the variant. Pre-lift this
1218        // byte-string existed only inside the hand-rolled Display impl's
1219        // four-arm literal-string match — every consumer that wanted the
1220        // `PascalCase` name reached through `format!("{d}")`'s allocation
1221        // path. Pinning the four arms explicitly here refuses a future
1222        // regression that ever reroutes an arm to a distinct spelling
1223        // (`"pacote"` lowercase, `"MoldePositional"` English rebrand,
1224        // `"Unknown"` for `Desconhecido`) — the census output and the
1225        // typed accessor would silently disagree until a downstream
1226        // consumer surfaced the drift at census time. Peer of the sibling
1227        // [`crate::supervisor::tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
1228        // / `placement_strategy_variants_serialize_to_lifted_scalar_values`
1229        // / `caixa_kind_as_str_returns_lifted_peer_const` shape on the
1230        // sibling closed-set typed-enum discriminator axes — the seventh
1231        // (and last unlifted) closed-set typed enum on the caixa surface
1232        // to converge onto the same per-arm-shape-pin discipline.
1233        for (variant, expected) in [
1234            (CaixaDialeto::Pacote, "Pacote"),
1235            (CaixaDialeto::Molde, "Molde"),
1236            (CaixaDialeto::MoldePosicional, "MoldePosicional"),
1237            (CaixaDialeto::Desconhecido, "Desconhecido"),
1238        ] {
1239            assert_eq!(
1240                variant.as_str(),
1241                expected,
1242                "CaixaDialeto::{variant:?}.as_str() must return the \
1243                 canonical `PascalCase` variant-name byte-string; drift here \
1244                 splits the census-facing text from the substrate \
1245                 primitive every downstream consumer will read"
1246            );
1247        }
1248    }
1249
1250    #[test]
1251    fn caixa_dialeto_display_routes_through_as_str_helper() {
1252        // Fail-before-pass-after convergence pin: for every arm in
1253        // [`CaixaDialeto::ALL`], the [`std::fmt::Display`] rendered form
1254        // must byte-equal [`CaixaDialeto::as_str`]'s return value. Pre-
1255        // lift these two paths were structurally independent — the
1256        // Display impl hand-rolled its own four-arm literal-string
1257        // match with no compile-time link back to any substrate accessor
1258        // — so a future variant rename could land at `Display` without
1259        // touching a paired accessor (or vice versa), silently splitting
1260        // the two paths on the renamed arm. Pinning the byte-equality
1261        // here makes any such split a caixa-core build-time failure at
1262        // this test rather than surfacing far from the rename commit as
1263        // a downstream census consumer emitting one spelling while the
1264        // typed accessor returned another. Peer of the sibling
1265        // [`crate::kind::tests::caixa_kind_display_routes_through_as_str_helper`]
1266        // (which pins the same convergence on the [`crate::CaixaKind`]
1267        // closed-set axis) — extends the discipline onto the seventh
1268        // (and last unlifted) closed-set fieldless typed enum on the
1269        // caixa surface.
1270        for &variant in CaixaDialeto::ALL {
1271            assert_eq!(
1272                variant.to_string(),
1273                variant.as_str(),
1274                "CaixaDialeto::{variant:?} Display must route through \
1275                 CaixaDialeto::as_str (single source of truth: the \
1276                 lifted per-arm `PascalCase` variant-name byte-string)"
1277            );
1278        }
1279    }
1280
1281    #[test]
1282    fn caixa_dialeto_as_ref_str_routes_through_as_str_accessor() {
1283        // Fail-before-pass-after byte-parity pin on the lifted
1284        // `impl AsRef<str> for CaixaDialeto` — asserts the standard-
1285        // library trait impl and the substrate-primitive
1286        // [`CaixaDialeto::as_str`] `pub const fn` accessor resolve to
1287        // the same `&str` per instance across the four-arm closed set,
1288        // so any future silent detour that routes the impl through a
1289        // divergent projection (a per-arm inline
1290        // `match self { CaixaDialeto::Pacote => "Pacote", … }` re-inlining
1291        // that opens a compile-time link to the un-lifted arm-literal,
1292        // a swap onto the second-axis
1293        // [`CaixaDialeto::palavra_canonica`] /
1294        // [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`]
1295        // accessors that carry distinct byte-shapes per axis) trips at
1296        // caixa-core test time under `PartialEq` rather than at a
1297        // downstream `impl AsRef<str>`-bound consumer's silent split.
1298        // Sweeps every one of the four arms [`CaixaDialeto::ALL`]
1299        // carries so no arm's projection is covered only by the sibling
1300        // `Display` path. Peer of the sibling
1301        // `rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`
1302        // (d8136db) on the M3 `:politicas :rate-limit` closed-set typed
1303        // enum, and the peer
1304        // [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
1305        // (cd2091f) pin on the top-level closed-set typed
1306        // discriminator — the pins together close the substrate
1307        // primitive's `AsRef<str>` projection axis onto the seventh
1308        // closed-set fieldless typed enum on the caixa surface.
1309        for &variant in CaixaDialeto::ALL {
1310            assert_eq!(
1311                <CaixaDialeto as AsRef<str>>::as_ref(&variant),
1312                variant.as_str(),
1313                "AsRef<str> impl on CaixaDialeto::{variant:?} must \
1314                 byte-equal CaixaDialeto::as_str on the same instance \
1315                 — divergence signals a silent detour off the \
1316                 substrate-primitive accessor"
1317            );
1318        }
1319    }
1320
1321    #[test]
1322    fn caixa_dialeto_as_ref_str_routes_through_display_via_shared_accessor() {
1323        // Fail-before-pass-after byte-parity pin on the three-path
1324        // convergence discipline the [`CaixaDialeto`] closed-set
1325        // dialect-classification enum now carries on the `&str`-
1326        // projection axis: `<CaixaDialeto as AsRef<str>>::as_ref(&v)`
1327        // (the newly lifted impl), `format!("{v}")` (the pre-existing
1328        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
1329        // primitive `pub const fn` accessor both trait impls delegate
1330        // through) must resolve to the same byte-string on every
1331        // instance across the four-arm closed set. Refuses any future
1332        // divergence between the two trait impls (a stray
1333        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
1334        // rather than delegating through the shared accessor; a
1335        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
1336        // literal cascade) that would silently split the two
1337        // projection paths of the same closed-set typed enum. Mirrors
1338        // the sibling three-path-convergence discipline the peer
1339        // [`crate::aplicacao::RateLimitUnit`] typed enum carries
1340        // (`rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`,
1341        // d8136db), the peer [`crate::CaixaKind`] triple
1342        // (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
1343        // cd2091f), and the [`crate::CaixaVersion`] typed newtype
1344        // triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
1345        // 16d5c7e).
1346        for &variant in CaixaDialeto::ALL {
1347            let via_as_ref: &str = <CaixaDialeto as AsRef<str>>::as_ref(&variant);
1348            let via_display: String = format!("{variant}");
1349            let via_accessor: &str = variant.as_str();
1350            assert_eq!(via_as_ref, via_accessor);
1351            assert_eq!(via_display, via_accessor);
1352            assert_eq!(via_as_ref, via_display.as_str());
1353        }
1354    }
1355
1356    #[test]
1357    fn caixa_dialeto_is_molde_family_returns_true_on_molde_and_positional_arms() {
1358        // Fail-before-pass-after per-arm shape pin on the two `defmolde`
1359        // declaration-family arms: [`CaixaDialeto::is_molde_family`] must
1360        // return `true` for [`CaixaDialeto::Molde`] and
1361        // [`CaixaDialeto::MoldePosicional`] — the two-arity closure of
1362        // one declaration ([`CaixaDialeto::MoldePosicional`]'s docstring:
1363        // "same declaration as [`Self::Molde`], written with the package
1364        // name as a bare positional symbol … one arity of one
1365        // declaration, not a third schema"). A future accidental flip that
1366        // reversed a per-arm arm's return without touching the paired
1367        // false-arm pin would silently open the substrate primitive to
1368        // false-positive on either arm — the `feira dialeto` verb's
1369        // `--strict-palavra` gate would then silently accept
1370        // repo-surface declarations under `(defcaixa …)` on one arm and
1371        // reject them on the other. Pinning the two true arms explicitly
1372        // here refuses that split at caixa-core build time.
1373        assert!(
1374            CaixaDialeto::Molde.is_molde_family(),
1375            "CaixaDialeto::Molde.is_molde_family() must return true — \
1376             Molde is the primary `defmolde` arm"
1377        );
1378        assert!(
1379            CaixaDialeto::MoldePosicional.is_molde_family(),
1380            "CaixaDialeto::MoldePosicional.is_molde_family() must return \
1381             true — MoldePosicional is the positional-arity form of the \
1382             same `defmolde` declaration Molde carries"
1383        );
1384    }
1385
1386    #[test]
1387    fn caixa_dialeto_is_molde_family_returns_false_on_pacote_and_desconhecido_arms() {
1388        // Fail-before-pass-after per-arm shape pin on the two non-`defmolde`
1389        // arms: [`CaixaDialeto::is_molde_family`] must return `false` for
1390        // [`CaixaDialeto::Pacote`] (the sibling `defcaixa` tatara-lisp
1391        // package manifest, `palavra_canonica → "defcaixa"`) and for
1392        // [`CaixaDialeto::Desconhecido`] (the residue that names no
1393        // known declaration, `palavra_canonica → "?"`). Pinning the two
1394        // false arms explicitly here refuses a future accidental flip
1395        // that let the predicate widen to include either arm — the
1396        // `feira dialeto` verb's `--strict-palavra` gate would then
1397        // spuriously refuse every `(defcaixa …)` package manifest as if
1398        // it were a repo-surface declaration.
1399        assert!(
1400            !CaixaDialeto::Pacote.is_molde_family(),
1401            "CaixaDialeto::Pacote.is_molde_family() must return false — \
1402             Pacote is the `defcaixa` tatara-lisp package manifest, not \
1403             the `defmolde` repo-surface declaration"
1404        );
1405        assert!(
1406            !CaixaDialeto::Desconhecido.is_molde_family(),
1407            "CaixaDialeto::Desconhecido.is_molde_family() must return \
1408             false — the residue arm names no known declaration; it is \
1409             not silently promoted into the `defmolde` family"
1410        );
1411    }
1412
1413    #[test]
1414    fn caixa_dialeto_is_molde_family_agrees_with_palavra_canonica_defmolde_projection() {
1415        // Load-bearing pin: for every arm in [`CaixaDialeto::ALL`], the
1416        // typed [`CaixaDialeto::is_molde_family`] predicate must agree
1417        // byte-for-byte with the paired [`CaixaDialeto::palavra_canonica`]
1418        // projection's `== "defmolde"` classifier — i.e. the two paths
1419        // partition the four-arm discriminator set into the same
1420        // `{Molde, MoldePosicional}` and `{Pacote, Desconhecido}` halves.
1421        // Pre-lift the sibling [`CaixaDialeto::palavra_canonica`] projection
1422        // (which returns `"defmolde"` for `Molde | MoldePosicional`,
1423        // `"defcaixa"` for `Pacote`, `"?"` for `Desconhecido`) was the
1424        // only substrate-side surface carrying the two-arm collapse; the
1425        // hand-rolled `matches!(d, CaixaDialeto::Molde |
1426        // CaixaDialeto::MoldePosicional)` sites in the `feira dialeto`
1427        // verb expressed no compile-time link back to it. A future arm
1428        // addition — the module doc's "third dialect" hazard actualises
1429        // as a fifth arm belonging to the `defmolde` family — would land
1430        // one match arm at [`Self::palavra_canonica`]'s `defmolde` return
1431        // (extending the sibling projection) but silently split the
1432        // hand-rolled two-arm `matches!` predicate sites if the new arm's
1433        // `is_molde_family` return were forgotten. Pinning byte-equality
1434        // between the two paths here makes any such split a caixa-core
1435        // build-time failure at this test rather than surfacing far from
1436        // the arm-addition commit as a downstream `--strict-palavra` /
1437        // `caixa.lisp`-holds-wrong-declaration gate silently ignoring the
1438        // new arm.
1439        for &d in CaixaDialeto::ALL {
1440            let via_palavra_canonica = d.palavra_canonica() == "defmolde";
1441            let via_is_molde_family = d.is_molde_family();
1442            assert_eq!(
1443                via_is_molde_family, via_palavra_canonica,
1444                "CaixaDialeto::{d:?}.is_molde_family() ({via_is_molde_family}) \
1445                 must agree with CaixaDialeto::{d:?}.palavra_canonica() == \
1446                 \"defmolde\" ({via_palavra_canonica}) — a split between the \
1447                 typed predicate and the sibling keyword projection would let \
1448                 a future arm addition land at one path and drift at the other, \
1449                 which is exactly the drift this pin refuses"
1450            );
1451        }
1452    }
1453
1454    #[test]
1455    fn caixa_dialeto_is_molde_family_is_const_fn() {
1456        // Const-context pin: [`CaixaDialeto::is_molde_family`] must remain
1457        // `const fn` (its match is a fieldless-arm literal-pattern
1458        // discriminator, so no non-const operation exists on the resolution
1459        // path). Downstream consumers reaching for the predicate from a
1460        // `const` context (a future substrate-wide const-fold-driven audit
1461        // table that materializes per-arm gate-membership at build time,
1462        // a per-arm CR-admission-webhook gate registration in a `const`
1463        // context) rely on the const-ness. A future accidental downgrade
1464        // to non-`const` (an added runtime helper reachable only from a
1465        // non-`const` context) trips at caixa-core build time rather than
1466        // surfacing as a downstream `const`-context regression far from
1467        // the predicate declaration. Peer of the sibling
1468        // [`caixa_dialeto_as_str_is_const_fn`] pin on the paired
1469        // [`CaixaDialeto::as_str`] byte-string axis.
1470        const ARMS: [(CaixaDialeto, bool); 4] = [
1471            (CaixaDialeto::Pacote, CaixaDialeto::Pacote.is_molde_family()),
1472            (CaixaDialeto::Molde, CaixaDialeto::Molde.is_molde_family()),
1473            (
1474                CaixaDialeto::MoldePosicional,
1475                CaixaDialeto::MoldePosicional.is_molde_family(),
1476            ),
1477            (
1478                CaixaDialeto::Desconhecido,
1479                CaixaDialeto::Desconhecido.is_molde_family(),
1480            ),
1481        ];
1482        // Materialize the const-fold-evaluated table into a runtime slice
1483        // assertion — carries the same `bool = const fn call` shape a raw
1484        // `assert!(const_bool)` would, without tripping the
1485        // `assertions_on_constants` clippy lint that a per-arm
1486        // `assert!(CONST)` on a `const bool` triggers when the arm-count
1487        // is enumerated flat rather than compared as a whole-table shape.
1488        assert_eq!(
1489            ARMS,
1490            [
1491                (CaixaDialeto::Pacote, false),
1492                (CaixaDialeto::Molde, true),
1493                (CaixaDialeto::MoldePosicional, true),
1494                (CaixaDialeto::Desconhecido, false),
1495            ],
1496            "CaixaDialeto::is_molde_family() must evaluate in const context \
1497             for every arm and land on the {{false, true, true, false}} \
1498             partition — a future accidental downgrade to non-`const` \
1499             would trip the const-context array-initializer here"
1500        );
1501    }
1502
1503    #[test]
1504    fn caixa_dialeto_as_str_is_const_fn() {
1505        // Const-context pin: [`CaixaDialeto::as_str`] must remain
1506        // `const fn` (its match arms return `pub const` byte-strings, so
1507        // no non-const operation exists on the resolution path).
1508        // Downstream consumers reaching for the accessor from a `const`
1509        // context (a future substrate-wide const-fold-driven audit table
1510        // that materializes every dialect's census label at build time,
1511        // a per-arm CR-admission-webhook message registration in a
1512        // `const` gate) rely on the const-ness. A future accidental
1513        // downgrade to non-`const` (an added runtime helper reachable
1514        // only from a non-`const` context, a manual hand-rolled `impl`
1515        // that shadows this method) trips at caixa-core build time
1516        // rather than surfacing as a downstream `const`-context
1517        // regression far from the accessor declaration. Peer of the
1518        // sibling [`crate::kind::tests::caixa_kind_wire_name_is_const_fn`]
1519        // pin on the paired [`crate::CaixaKind`] byte-string axis.
1520        const PACOTE: &str = CaixaDialeto::Pacote.as_str();
1521        const MOLDE: &str = CaixaDialeto::Molde.as_str();
1522        const MOLDE_POSICIONAL: &str = CaixaDialeto::MoldePosicional.as_str();
1523        const DESCONHECIDO: &str = CaixaDialeto::Desconhecido.as_str();
1524        assert_eq!(PACOTE, "Pacote");
1525        assert_eq!(MOLDE, "Molde");
1526        assert_eq!(MOLDE_POSICIONAL, "MoldePosicional");
1527        assert_eq!(DESCONHECIDO, "Desconhecido");
1528    }
1529
1530    #[test]
1531    fn caixa_dialeto_is_variant_predicates_partition_the_arm_set() {
1532        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
1533        // derive: for each of the four variants at [`CaixaDialeto::ALL`]`[idx]`
1534        // the observed four-slot predicate row must equal a one-hot row
1535        // with the `true` at exactly `idx`. Pre-derive the closed four-arm
1536        // dialect-classification partition lived only inside the paired
1537        // per-arm projections' four-arm match resolvers ([`Self::as_str`] /
1538        // [`Self::palavra_canonica`] / [`Self::consumidor`] /
1539        // [`Self::descricao`]) plus the two-arm [`Self::is_molde_family`]
1540        // hand-rolled `matches!` (now routed through the derived
1541        // predicates); a future rebrand (an accidental
1542        // `#[is_variant(name = "…")]` drift, a manual hand-rolled `impl`
1543        // that shadows the derive-generated method, an arm rename that
1544        // reroutes one arm through the wrong predicate lane) trips this
1545        // pin at caixa-core build time rather than surfacing far from the
1546        // derive declaration as a downstream [`Self::is_molde_family`]
1547        // consumer accepting the wrong arm-set. The expected row is
1548        // generated live from the [`Self::ALL`] declaration order rather
1549        // than transcribed by hand so a copy-paste flip reroutes at the
1550        // identity-diagonal assertion.
1551        //
1552        // Peer of the sibling
1553        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
1554        // / [`crate::supervisor::tests::restart_strategy_is_variant_predicates_partition_the_arm_set`]
1555        // / [`crate::aplicacao::tests::placement_strategy_is_variant_predicates_partition_the_arm_set`]
1556        // / [`crate::upgrade::tests::upgrade_instruction_is_variant_predicates_partition_the_arm_set`]
1557        // pins on the sibling closed-set typed-enum discriminator axes.
1558        for (idx, &variant) in CaixaDialeto::ALL.iter().enumerate() {
1559            let observed = [
1560                variant.is_pacote(),
1561                variant.is_molde(),
1562                variant.is_molde_posicional(),
1563                variant.is_desconhecido(),
1564            ];
1565            let mut expected = [false; 4];
1566            expected[idx] = true;
1567            assert_eq!(
1568                observed, expected,
1569                "CaixaDialeto::{variant:?} at ALL[{idx}] is_* predicates \
1570                 must fire only on their own arm lane (identity diagonal); \
1571                 got {observed:?}",
1572            );
1573        }
1574    }
1575
1576    #[test]
1577    fn caixa_dialeto_is_variant_predicates_are_const_fn() {
1578        // The [`gen_platform::IsVariant`] derive emits `const fn`
1579        // predicates on the peer [`crate::CaixaKind`] +
1580        // [`crate::upgrade::UpgradeInstruction`] +
1581        // [`crate::supervisor::RestartStrategy`] +
1582        // [`crate::supervisor::RestartPolicy`] +
1583        // [`crate::aplicacao::PlacementStrategy`] +
1584        // [`crate::aplicacao::RateLimitUnit`] +
1585        // [`crate::dep::DepList`] closed-set typed enums — pin the same
1586        // posture on [`CaixaDialeto`] so a future accidental downgrade
1587        // to non-`const` (an added runtime helper reachable only from a
1588        // non-`const` context, a manual hand-rolled `impl` that shadows
1589        // the derive-generated method) trips at caixa-core build time
1590        // rather than surfacing as a downstream `const`-context
1591        // regression far from the derive declaration.
1592        // Use `const { assert!(…) }` (peer of the sibling
1593        // [`crate::render::PathShapeViolation`] +
1594        // [`crate::aplicacao::RateLimitUnit`] +
1595        // [`caixa_theme::style::Semantic`] const-fn pins) so the
1596        // const-context evaluation trips at const-fold time without
1597        // opening a per-`const bool` `assertions_on_constants` clippy
1598        // debt row this crate does not carry today for `dialeto.rs`.
1599        const { assert!(CaixaDialeto::Pacote.is_pacote()) };
1600        const { assert!(CaixaDialeto::Molde.is_molde()) };
1601        const { assert!(CaixaDialeto::MoldePosicional.is_molde_posicional()) };
1602        const { assert!(CaixaDialeto::Desconhecido.is_desconhecido()) };
1603    }
1604
1605    #[test]
1606    fn caixa_dialeto_from_wire_accepts_every_as_str_output() {
1607        // Fail-before-pass-after per-arm accept pin on the newly lifted
1608        // [`CaixaDialeto::from_wire`] reverse projection: every arm in
1609        // [`CaixaDialeto::ALL`] must parse back through `from_wire` when
1610        // fed its own [`CaixaDialeto::as_str`] output, landing on
1611        // `Some(same_variant)` — a regression that hand-rolled either
1612        // side's per-arm match without threading through the shared
1613        // four-string closed set would silently disagree on any future
1614        // arm rename and this pin flags it at caixa-core build time.
1615        // Peer of the sibling
1616        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
1617        // (2aa6d23) /
1618        // `placement_strategy_from_wire_accepts_every_lifted_constant`
1619        // (18c7342) /
1620        // `dep_list_round_trips_through_as_str_and_from_wire` (45ee563)
1621        // shape on the sibling closed-set typed-enum reverse-projection
1622        // axes.
1623        for &variant in CaixaDialeto::ALL {
1624            let wire = variant.as_str();
1625            let parsed = CaixaDialeto::from_wire(wire).unwrap_or_else(|| {
1626                panic!(
1627                    "CaixaDialeto::from_wire({wire:?}) must accept every \
1628                     CaixaDialeto::as_str output — got None for the \
1629                     wire byte-string of {variant:?}"
1630                )
1631            });
1632            assert_eq!(
1633                parsed, variant,
1634                "CaixaDialeto::from_wire(CaixaDialeto::{variant:?}.as_str()) \
1635                 must return CaixaDialeto::{variant:?} — the (as_str, \
1636                 from_wire) pair must form a total round-trip on the \
1637                 closed four-arm CaixaDialeto arm-set"
1638            );
1639        }
1640    }
1641
1642    #[test]
1643    fn caixa_dialeto_from_wire_rejects_unknown_byte_strings() {
1644        // Rejection pin on the parser's accept-set: any string outside
1645        // the four-arm [`CaixaDialeto::as_str`] output set must return
1646        // `None`. A future accidental widening of the accept-set (a
1647        // case-insensitive match that accepts `"pacote"` on the wire
1648        // axis, a hand-rolled Levenshtein-forgiving arm-lookup that
1649        // admits `"Pacotee"` typos, a silent acceptance of the sibling
1650        // [`Self::palavra_canonica`] `"defcaixa"` / `"defmolde"`
1651        // byte-shapes on this axis) would silently drift the parser's
1652        // accept-set from the emitter's — a downstream audit-report
1653        // re-loader that bound a prior audit's [`Self::as_str`] output
1654        // back to the typed enum through this parser would then bind a
1655        // malformed byte-string to a plausibly-wrong typed arm the
1656        // caller does not route through any fallback, silently
1657        // misclassifying the reloaded row. Also rejects the sibling
1658        // [`Self::palavra_canonica`] (`"defcaixa"` / `"defmolde"`) and
1659        // the sibling [`Self::consumidor`] (`"caixa-core / feira"`,
1660        // `"pleme-doc-gen"`, `"nobody known"`) byte-shapes, which are
1661        // the substrate's *distinct-axis* projections on the same enum
1662        // — the two-axis split the sibling
1663        // [`Self::palavra_canonica`] / [`Self::consumidor`] /
1664        // [`Self::descricao`] docstrings explicitly frame forbids
1665        // accepting one axis's byte-shapes as parseable on the other
1666        // axis. Peer of the sibling
1667        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
1668        // (2aa6d23) /
1669        // `placement_strategy_from_wire_rejects_unknown_byte_strings`
1670        // (18c7342) /
1671        // `dep_list_from_wire_returns_none_on_unknown_wire_scalar`
1672        // (45ee563) rejection pins on the sibling closed-set typed-enum
1673        // reverse-projection axes.
1674        for bad in [
1675            "",
1676            " ",
1677            "pacote",
1678            "PACOTE",
1679            "molde",
1680            "MoldePositional",
1681            "desconhecido",
1682            "Unknown",
1683            "defcaixa",
1684            "defmolde",
1685            "?",
1686            "caixa-core / feira",
1687            "pleme-doc-gen",
1688            "nobody known",
1689            "Pacote ",
1690            " Pacote",
1691        ] {
1692            assert!(
1693                CaixaDialeto::from_wire(bad).is_none(),
1694                "CaixaDialeto::from_wire({bad:?}) must return None — the \
1695                 parser's accept-set is exactly the four CaixaDialeto::as_str \
1696                 outputs; a widening would silently split the parser's \
1697                 accept-set from the emitter's arm-set"
1698            );
1699        }
1700    }
1701
1702    #[test]
1703    fn cabeca_errada_ctor_matches_struct_literal_wrap() {
1704        // Fail-before-pass-after byte-identity pin: the lifted
1705        // [`DialetoError::cabeca_errada`] ctor MUST land on the exact
1706        // same struct-literal shape the pre-lift open-coded wire-up
1707        // block wrote by hand — `DialetoError::CabecaErrada {
1708        // encontrado: <head>.to_string() }`. A future accidental
1709        // divergence (`.into()` swap, per-arm constant substitution, an
1710        // added default field, an `.to_ascii_lowercase()` normalization
1711        // silently injected into the ctor body, a rebrand of the
1712        // `encontrado` field carrying a distinct byte-shape) trips this
1713        // pin at caixa-core build time rather than surfacing far from
1714        // the ctor declaration as a downstream `classify_form`
1715        // wrong-head consumer emitting one diagnostic shape while a
1716        // hand-written test peer opens another. Peer of the sibling
1717        // `unknown_byte_unit_ctor_matches_struct_literal_wrap`
1718        // (limits.rs; 29fac09) / `duplicate_from_ctor_matches_struct_
1719        // literal_wrap` (upgrade.rs; 7e52aec) shape on the sibling
1720        // single-slot `{ <field>: String }` envelope constructors.
1721        assert_eq!(
1722            DialetoError::cabeca_errada("defflake"),
1723            DialetoError::CabecaErrada {
1724                encontrado: "defflake".to_string(),
1725            },
1726            "DialetoError::cabeca_errada must byte-equal the pre-lift \
1727             open-coded struct-literal — a drift here means the ctor \
1728             stopped being a substrate primitive for the wrong-head \
1729             fallthrough site"
1730        );
1731    }
1732
1733    #[test]
1734    fn cabeca_errada_routes_encontrado_verbatim_across_boundary_inputs() {
1735        // Fail-before-pass-after boundary-sweep pin: the lifted
1736        // [`DialetoError::cabeca_errada`] ctor MUST route its
1737        // `encontrado: &str` argument verbatim into the
1738        // [`DialetoError::CabecaErrada`] `encontrado: String` field
1739        // for every boundary-covering `&str` input — empty string, a
1740        // canonical `defcaixa`-adjacent head, a non-ASCII head, a
1741        // whitespace-carrying head, a Unicode-full-width head. Any
1742        // wrapper-side truncation, silent `.trim()`, accidental
1743        // `.to_ascii_lowercase()` normalization, or `.into()` divergence
1744        // on the ctor body surfaces here as a byte-mismatch against the
1745        // input rather than at a downstream
1746        // [`DialetoError::to_string()`] diagnostic-shape drift at a
1747        // wrong-head fallthrough consumer far from the ctor declaration.
1748        // Peer of the sibling `limits_codec_unit_only_ctors_route_unit_
1749        // verbatim_across_every_variant` (limits.rs; 29fac09) shape on
1750        // the sibling single-slot `{ <field>: String }` envelope
1751        // boundary-sweep discipline.
1752        for encontrado in [
1753            "",
1754            "defflake",
1755            "def-molde",
1756            "defcaixa ",
1757            " defcaixa",
1758            "μdefcaixa",
1759            "\u{00A0}defcaixa",
1760            "\u{3000}defcaixa",
1761            "def\u{2028}caixa",
1762        ] {
1763            let via_ctor = DialetoError::cabeca_errada(encontrado);
1764            let via_literal = DialetoError::CabecaErrada {
1765                encontrado: encontrado.to_string(),
1766            };
1767            assert_eq!(
1768                via_ctor, via_literal,
1769                "DialetoError::cabeca_errada({encontrado:?}) must byte- \
1770                 equal the open-coded struct-literal on the same input — \
1771                 a drift here would let the ctor silently normalize / \
1772                 truncate the head symbol before it reached the \
1773                 CabecaErrada envelope"
1774            );
1775            let DialetoError::CabecaErrada { encontrado: routed } = via_ctor else {
1776                panic!(
1777                    "DialetoError::cabeca_errada must construct the \
1778                     CabecaErrada arm — got a different variant on \
1779                     input {encontrado:?}"
1780                );
1781            };
1782            assert_eq!(
1783                routed, encontrado,
1784                "DialetoError::cabeca_errada must route the input \
1785                 {encontrado:?} verbatim into the encontrado field — \
1786                 any wrapper-side truncation / normalization surfaces \
1787                 here rather than at a downstream diagnostic shape drift"
1788            );
1789        }
1790    }
1791
1792    #[test]
1793    fn classify_form_wrong_head_routes_through_cabeca_errada_ctor() {
1794        // Fail-before-pass-after routing pin: [`classify`]'s wrong-head
1795        // fallthrough site MUST construct its `Err(DialetoError::…)`
1796        // through the substrate-primitive [`DialetoError::cabeca_errada`]
1797        // ctor rather than through an open-coded struct-literal. Pre-
1798        // lift the wire-up hand-rolled a three-line
1799        // `Self::CabecaErrada { encontrado: other.to_string() }` block
1800        // with no compile-time link back to the substrate primitive; a
1801        // future accidental rebrand of the ctor body (an added
1802        // `.trim()` on `encontrado`, a per-arm constant prefix like
1803        // `"unknown-head:"`, a widening of the field into a
1804        // `(String, usize)` tuple carrying a caret offset) would then
1805        // silently split the two paths — the ctor consumers pick up
1806        // the new shape, the open-coded wire-up does not. Pinning
1807        // byte-equality between the observed `Err` and the ctor-
1808        // constructed `Err` refuses that split at caixa-core build
1809        // time rather than surfacing far from the wire-up commit as a
1810        // downstream diagnostic-consumer split.
1811        for head in ["defflake", "deffoobar", "defcaixaz", "let", "defmoldez"] {
1812            let src = format!("({head} :nome \"x\")");
1813            let observed = classify(&src);
1814            let via_ctor = Err(DialetoError::cabeca_errada(head));
1815            assert_eq!(
1816                observed, via_ctor,
1817                "classify({src:?}) must return the same Err shape as \
1818                 DialetoError::cabeca_errada({head:?}) — a drift here \
1819                 means the wire-up de-lifted its wrong-head fallthrough \
1820                 arm off the substrate primitive"
1821            );
1822        }
1823    }
1824
1825    #[test]
1826    fn leitura_ctor_matches_tuple_literal_wrap_on_str_binding() {
1827        // Fail-before-pass-after byte-identity pin: the lifted
1828        // [`DialetoError::leitura`] ctor MUST land on the exact same
1829        // tuple-newtype wrap the pre-lift open-coded wire-up block wrote by
1830        // hand — `DialetoError::Leitura(<into-String-expr>)`. A future
1831        // accidental divergence (an added `.trim()` on the reader reason,
1832        // a per-arm constant prefix like `"tatara-lisp:"`, a widening of
1833        // the tuple carrying a caret offset, a rebrand of the payload
1834        // carrying a distinct byte-shape) trips this pin at caixa-core
1835        // build time rather than surfacing far from the ctor declaration
1836        // as a downstream [`classify`] tatara-lisp-reader consumer
1837        // emitting one diagnostic shape while a hand-written test peer
1838        // opens another. Peer of the sibling
1839        // `cabeca_errada_ctor_matches_struct_literal_wrap` pin above on
1840        // the same [`DialetoError`] envelope's wrong-head axis, and of
1841        // the peer `LimitsError::empty_byte_size` /
1842        // `LimitsError::empty_duration` (7a4b003 / 319216c) shape on the
1843        // sibling `(String)` single-slot tuple-newtype envelope
1844        // constructors.
1845        let reason: &str = "unclosed paren at 1:12";
1846        assert_eq!(
1847            DialetoError::leitura(reason),
1848            DialetoError::Leitura(reason.to_string()),
1849            "DialetoError::leitura must byte-equal the pre-lift open-coded \
1850             tuple-newtype wrap — a drift here means the ctor stopped \
1851             being a substrate primitive for the tatara-lisp-reader \
1852             fallthrough site"
1853        );
1854    }
1855
1856    #[test]
1857    fn leitura_ctor_matches_tuple_literal_wrap_on_string_binding() {
1858        // Fail-before-pass-after byte-identity pin on the `String` wire-up
1859        // shape: the lifted [`DialetoError::leitura`] ctor MUST land on
1860        // the same tuple-newtype wrap when the caller passes an owned
1861        // `String` (the actual [`classify`] wire-up shape — `e.to_string()`
1862        // on a [`tatara_lisp::Error`]-carrying binding). Pins that the
1863        // `impl Into<String>` param covers the owned-`String` path with no
1864        // silent double-allocation or intermediate `&str` reslicing. Peer
1865        // of the sibling `_on_str_binding` pin above — together they close
1866        // the `impl Into<String>` bound's two authored wire-up shapes on
1867        // the ctor's substrate primitive.
1868        let reason: String = String::from("read: unexpected EOF at 3:1");
1869        let via_ctor = DialetoError::leitura(reason.clone());
1870        let via_literal = DialetoError::Leitura(reason.clone());
1871        assert_eq!(
1872            via_ctor, via_literal,
1873            "DialetoError::leitura must byte-equal the pre-lift open-coded \
1874             tuple-newtype wrap on the same owned-String fixture — a drift \
1875             here would let the ctor silently reshape the reader reason \
1876             before it reached the Leitura envelope"
1877        );
1878        let DialetoError::Leitura(routed) = via_ctor else {
1879            panic!(
1880                "DialetoError::leitura must construct the Leitura arm — \
1881                 got a different variant on input {reason:?}"
1882            );
1883        };
1884        assert_eq!(
1885            routed, reason,
1886            "DialetoError::leitura must route the input {reason:?} \
1887             verbatim into the tuple-newtype payload — any wrapper-side \
1888             truncation / normalization surfaces here rather than at a \
1889             downstream diagnostic shape drift"
1890        );
1891    }
1892
1893    #[test]
1894    fn leitura_routes_reason_verbatim_across_boundary_inputs() {
1895        // Fail-before-pass-after boundary-sweep pin: the lifted
1896        // [`DialetoError::leitura`] ctor MUST route its
1897        // `reason: impl Into<String>` argument verbatim into the
1898        // [`DialetoError::Leitura`] tuple-newtype `String` payload for
1899        // every boundary-covering input — empty string, a canonical
1900        // tatara-lisp reader error, a non-ASCII reason, a
1901        // whitespace-carrying reason, a Unicode-full-width reason. Any
1902        // wrapper-side truncation, silent `.trim()`, accidental
1903        // `.to_ascii_lowercase()` normalization, or `.into()` divergence
1904        // on the ctor body surfaces here as a byte-mismatch against the
1905        // input rather than at a downstream [`DialetoError::to_string()`]
1906        // diagnostic-shape drift at a tatara-lisp-reader fallthrough
1907        // consumer far from the ctor declaration. Peer of the sibling
1908        // `cabeca_errada_routes_encontrado_verbatim_across_boundary_inputs`
1909        // pin above on the same [`DialetoError`] envelope's wrong-head
1910        // axis.
1911        for reason in [
1912            "",
1913            "unclosed paren at 1:12",
1914            "unexpected token ')'",
1915            "read: eof",
1916            " leading whitespace",
1917            "trailing whitespace ",
1918            "μnicode reason",
1919            "\u{00A0}NBSP-prefixed reason",
1920            "\u{3000}ideographic-space reason",
1921            "reason\u{2028}with-line-separator",
1922        ] {
1923            let via_ctor = DialetoError::leitura(reason);
1924            let via_literal = DialetoError::Leitura(reason.to_string());
1925            assert_eq!(
1926                via_ctor, via_literal,
1927                "DialetoError::leitura({reason:?}) must byte-equal the \
1928                 open-coded tuple-newtype wrap on the same input — a \
1929                 drift here would let the ctor silently normalize / \
1930                 truncate the reader reason before it reached the \
1931                 Leitura envelope"
1932            );
1933            let DialetoError::Leitura(routed) = via_ctor else {
1934                panic!(
1935                    "DialetoError::leitura must construct the Leitura \
1936                     arm — got a different variant on input {reason:?}"
1937                );
1938            };
1939            assert_eq!(
1940                routed, reason,
1941                "DialetoError::leitura must route the input {reason:?} \
1942                 verbatim into the tuple-newtype payload — any \
1943                 wrapper-side truncation / normalization surfaces here \
1944                 rather than at a downstream diagnostic shape drift"
1945            );
1946        }
1947    }
1948
1949    #[test]
1950    fn classify_reader_error_routes_through_leitura_ctor() {
1951        // Fail-before-pass-after routing pin: [`classify`]'s
1952        // tatara-lisp-reader map-err site MUST construct its
1953        // `Err(DialetoError::…)` through the substrate-primitive
1954        // [`DialetoError::leitura`] ctor rather than through an
1955        // open-coded tuple-newtype wrap. Pre-lift the wire-up hand-rolled
1956        // a `Self::Leitura(e.to_string())` block with no compile-time
1957        // link back to the substrate primitive; a future accidental
1958        // rebrand of the ctor body (an added `.trim()` on the reader
1959        // reason, a per-arm constant prefix like `"tatara-lisp:"`, a
1960        // widening of the payload into a `(String, usize)` tuple
1961        // carrying a caret offset) would then silently split the two
1962        // paths — the ctor consumers pick up the new shape, the
1963        // open-coded wire-up does not. Pinning byte-equality between
1964        // the observed `Err` and the ctor-constructed `Err` refuses
1965        // that split at caixa-core build time rather than surfacing far
1966        // from the wire-up commit as a downstream diagnostic-consumer
1967        // split. Peer of the sibling
1968        // `classify_form_wrong_head_routes_through_cabeca_errada_ctor`
1969        // pin above on the same [`DialetoError`] envelope's wrong-head
1970        // fallthrough axis.
1971        //
1972        // The malformed sources below each name a distinct
1973        // tatara-lisp-reader failure shape (unclosed paren, stray close
1974        // paren, unterminated string), so together they sweep the
1975        // reader's rejection surface rather than pinning against one
1976        // specific error message the reader upstream is free to reword.
1977        for src in [
1978            "(defcaixa :nome \"x\"",
1979            "defcaixa :nome \"x\")",
1980            "(defcaixa :nome \"unterminated",
1981        ] {
1982            let observed = classify(src);
1983            let Err(DialetoError::Leitura(reason)) = observed.clone() else {
1984                panic!(
1985                    "classify({src:?}) must return the Leitura arm — got \
1986                     {observed:?}"
1987                );
1988            };
1989            let via_ctor: Result<CaixaDialeto, DialetoError> =
1990                Err(DialetoError::leitura(reason.clone()));
1991            assert_eq!(
1992                observed, via_ctor,
1993                "classify({src:?}) must return the same Err shape as \
1994                 DialetoError::leitura({reason:?}) — a drift here means \
1995                 the wire-up de-lifted its tatara-lisp-reader fallthrough \
1996                 arm off the substrate primitive"
1997            );
1998        }
1999    }
2000
2001    #[test]
2002    fn caixa_dialeto_try_from_str_routes_through_from_wire_accessor() {
2003        // Fail-before-pass-after byte-parity pin on the lifted
2004        // `impl TryFrom<&str> for CaixaDialeto`: for every arm in
2005        // [`CaixaDialeto::ALL`], the `.try_into()` / `TryFrom::try_from`
2006        // path must resolve to the same variant the sibling
2007        // [`CaixaDialeto::from_wire`] resolver returns on the same
2008        // [`CaixaDialeto::as_str`] wire byte-string input. Pins the
2009        // three-path convergence discipline the [`CaixaDialeto`] closed-
2010        // set typed enum now carries on the `str → Self` reverse-
2011        // projection axis: `<CaixaDialeto as TryFrom<&str>>::try_from(s)`
2012        // (the newly lifted trait-idiomatic reverse projection),
2013        // `CaixaDialeto::from_wire(s)` (the substrate-primitive method-
2014        // named `Option<Self>` accessor the trait impl delegates through),
2015        // and the round-trip identity `variant.as_str() → variant`
2016        // (the four-arm closed accept-set shared between the emitter and
2017        // both reverse-projection consumers) must resolve to the same
2018        // typed [`CaixaDialeto`] discriminator on every arm.
2019        //
2020        // A future silent detour that routes the impl through a
2021        // divergent projection (a per-arm inline
2022        // `match s { "Pacote" => …, … }` re-inlining that opens a
2023        // compile-time link to the un-lifted arm-literal, a swap onto
2024        // the second-axis [`CaixaDialeto::palavra_canonica`] /
2025        // [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`]
2026        // accessors that carry distinct byte-shapes per axis, an accept-
2027        // set widening that silently accepts one axis's byte-shapes as
2028        // parseable on the other axis) trips at caixa-core test time
2029        // under `assert_eq!` rather than at a downstream
2030        // `TryFrom<&str>`-bound consumer's silent split. Peer of the
2031        // sibling
2032        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
2033        // (3c83606) on the top-level [`crate::CaixaKind`] closed-set
2034        // discriminator's reverse-projection axis — extends the trait-
2035        // idiomatic reverse-projection axis onto the seventh closed-set
2036        // fieldless typed enum on the caixa surface (the second one to
2037        // carry the paired `TryFrom<&str>` impl).
2038        for &variant in CaixaDialeto::ALL {
2039            let wire = variant.as_str();
2040            let via_try_from: CaixaDialeto = <CaixaDialeto as TryFrom<&str>>::try_from(wire)
2041                .unwrap_or_else(|()| {
2042                    panic!(
2043                        "CaixaDialeto::try_from({wire:?}) must accept every \
2044                         CaixaDialeto::as_str output — got Err(()) for the \
2045                         wire byte-string of {variant:?}"
2046                    )
2047                });
2048            let via_from_wire: CaixaDialeto = CaixaDialeto::from_wire(wire).unwrap_or_else(|| {
2049                panic!(
2050                    "CaixaDialeto::from_wire({wire:?}) must accept every \
2051                     CaixaDialeto::as_str output — got None for the wire \
2052                     byte-string of {variant:?}"
2053                )
2054            });
2055            assert_eq!(
2056                via_try_from, variant,
2057                "CaixaDialeto::try_from(CaixaDialeto::{variant:?}.as_str()) \
2058                 must return CaixaDialeto::{variant:?} — the trait-idiomatic \
2059                 reverse projection must land on the same arm the method-named \
2060                 from_wire resolver does",
2061            );
2062            assert_eq!(
2063                via_try_from, via_from_wire,
2064                "CaixaDialeto::try_from({wire:?}) ({via_try_from:?}) must \
2065                 byte-equal CaixaDialeto::from_wire({wire:?}) ({via_from_wire:?}) \
2066                 on the same input — divergence signals a silent detour off the \
2067                 shared substrate-primitive resolver",
2068            );
2069            assert_eq!(
2070                <CaixaDialeto as TryFrom<&str>>::try_from(wire).ok(),
2071                CaixaDialeto::from_wire(wire),
2072                "the Result::ok() projection of TryFrom<&str> must byte-equal \
2073                 the sibling from_wire Option<Self> output on {wire:?} — the \
2074                 two accessors must share the same accept-set and typed \
2075                 outcome per arm",
2076            );
2077        }
2078    }
2079
2080    #[test]
2081    fn caixa_dialeto_try_from_str_rejects_unknown_byte_strings() {
2082        // Rejection witness on the trait-idiomatic reverse-projection
2083        // axis: any string outside the four-arm [`CaixaDialeto::as_str`]
2084        // output set must resolve to `Err(())` through the lifted
2085        // [`impl TryFrom<&str> for CaixaDialeto`]. A future accidental
2086        // widening of the accept-set (a case-insensitive match that
2087        // accepts `"pacote"` on the wire axis, a hand-rolled Levenshtein-
2088        // forgiving arm-lookup that admits `"Pacotee"` typos, a silent
2089        // acceptance of the sibling [`CaixaDialeto::palavra_canonica`]
2090        // `"defcaixa"` / `"defmolde"` byte-shapes on this axis, a swap
2091        // onto the [`CaixaDialeto::consumidor`] `"pleme-doc-gen"` /
2092        // `"caixa-core / feira"` / `"nobody known"` byte-shapes) would
2093        // silently drift the trait-idiomatic parser's accept-set from
2094        // the sibling [`CaixaDialeto::from_wire`] resolver's — a
2095        // downstream `TryFrom<&str>`-bound consumer binding a malformed
2096        // byte-string through this impl would then bind a plausibly-
2097        // wrong typed arm the caller does not route through any fallback,
2098        // silently misclassifying the reloaded row.
2099        //
2100        // Sweeps the same rejection set the sibling
2101        // [`caixa_dialeto_from_wire_rejects_unknown_byte_strings`] pin
2102        // walks (the shared `from_wire` resolver both accessors delegate
2103        // through) so the trait-idiomatic axis and the method-named axis
2104        // stay locked to the same accept-set by construction. Peer of the
2105        // sibling
2106        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
2107        // (3c83606) on the top-level [`crate::CaixaKind`] closed-set
2108        // discriminator's trait-idiomatic reverse-projection axis.
2109        for bad in [
2110            "",
2111            " ",
2112            "pacote",
2113            "PACOTE",
2114            "molde",
2115            "MoldePositional",
2116            "desconhecido",
2117            "Unknown",
2118            "defcaixa",
2119            "defmolde",
2120            "?",
2121            "caixa-core / feira",
2122            "pleme-doc-gen",
2123            "nobody known",
2124            "Pacote ",
2125            " Pacote",
2126        ] {
2127            assert_eq!(
2128                <CaixaDialeto as TryFrom<&str>>::try_from(bad),
2129                Err(()),
2130                "CaixaDialeto::try_from({bad:?}) must return Err(()) — the \
2131                 trait-idiomatic parser's accept-set is exactly the four \
2132                 CaixaDialeto::as_str outputs; a widening would silently \
2133                 split the trait-idiomatic reverse-projection axis from the \
2134                 sibling from_wire resolver's arm-set"
2135            );
2136        }
2137    }
2138
2139    #[test]
2140    fn caixa_dialeto_from_into_static_str_routes_through_as_str_accessor() {
2141        // Fail-before-pass-after byte-parity pin on the newly lifted
2142        // `impl From<CaixaDialeto> for &'static str` — asserts the
2143        // standard-library trait impl and the substrate-primitive
2144        // [`CaixaDialeto::as_str`] `pub const fn` accessor resolve to
2145        // the same four-arm emit-set across every arm the exhaustive
2146        // [`CaixaDialeto::ALL`] slice enumerates. Any future silent
2147        // detour that routes the trait impl through a divergent
2148        // projection (a per-arm inline `match dialeto { Pacote =>
2149        // "Pacote", … }` re-inlining that opens a compile-time link to
2150        // the un-lifted arm-literal, an accidental swap onto the second-
2151        // axis [`CaixaDialeto::palavra_canonica`] /
2152        // [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`]
2153        // accessors that carry distinct byte-shapes per axis) trips at
2154        // caixa-core test time under `assert_eq!` rather than at a
2155        // downstream `impl Into<&'static str>`-bound consumer's silent
2156        // split. Sweeps every one of the four arms [`CaixaDialeto::ALL`]
2157        // carries so no arm's projection is covered only by the sibling
2158        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
2159        // paths. Materializes the `<&'static str as
2160        // From<CaixaDialeto>>::from` output in a `const`-shape binding
2161        // to make the `'static` lifetime promise a build-time invariant
2162        // — a future accidental downgrade of any of the four arms'
2163        // returned literals to a non-`&'static str` (a `String::leak()`-
2164        // produced return, a `Box::leak`-cast, an intermediate lifetime-
2165        // erasing helper) trips at caixa-core build time rather than at
2166        // a downstream `'static`-bound consumer. Peer of the sibling
2167        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
2168        // (523157d) /
2169        // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
2170        // (9fb37d0) /
2171        // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
2172        // (edb827b) pins on the sibling closed-set typed-enum forward-
2173        // projection axes — extends the trait-idiomatic forward-
2174        // projection axis onto the fourth closed-set fieldless typed
2175        // enum on the caixa surface (the dialect-classification axis,
2176        // second-of-two closed-set typed enums in caixa-core outside
2177        // the OTP-shape M2 slot).
2178        const PACOTE: &str = CaixaDialeto::Pacote.as_str();
2179        const MOLDE: &str = CaixaDialeto::Molde.as_str();
2180        const MOLDE_POSICIONAL: &str = CaixaDialeto::MoldePosicional.as_str();
2181        const DESCONHECIDO: &str = CaixaDialeto::Desconhecido.as_str();
2182        for &variant in CaixaDialeto::ALL {
2183            let via_trait: &'static str = <&'static str as From<CaixaDialeto>>::from(variant);
2184            let via_method: &'static str = variant.as_str();
2185            assert_eq!(
2186                via_trait, via_method,
2187                "From<CaixaDialeto> for &'static str impl must round-trip \
2188                 CaixaDialeto::{variant:?} to the same `PascalCase` byte-string \
2189                 CaixaDialeto::as_str returns — divergence signals a silent \
2190                 detour off the substrate-primitive accessor"
2191            );
2192            let via_into: &'static str = variant.into();
2193            assert_eq!(
2194                via_into, via_method,
2195                "Into<&'static str>::into on CaixaDialeto::{variant:?} must \
2196                 byte-equal CaixaDialeto::as_str on the same input — the \
2197                 blanket-derived Into shape must resolve to the same as_str \
2198                 dispatch as the explicit From impl"
2199            );
2200        }
2201        assert_eq!(
2202            [PACOTE, MOLDE, MOLDE_POSICIONAL, DESCONHECIDO],
2203            ["Pacote", "Molde", "MoldePosicional", "Desconhecido"],
2204            "const-context CaixaDialeto::as_str must resolve to the four \
2205             `PascalCase` variant-name byte-strings — a future accidental \
2206             downgrade of any arm to a non-const or non-static byte-string \
2207             breaks the `&'static str`-lifetime promise the paired \
2208             From<CaixaDialeto> for &'static str impl carries by \
2209             construction"
2210        );
2211    }
2212
2213    #[test]
2214    fn caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set() {
2215        // Cross-axis partition pin: the paired trait-idiomatic
2216        // `From<CaixaDialeto> for &'static str` forward projection and
2217        // the method-named [`CaixaDialeto::as_str`] forward projection
2218        // must resolve identically on *every* arm, not just the ones
2219        // named in the primary byte-parity pin above. Sweeps every
2220        // [`CaixaDialeto::ALL`] arm and asserts the trait's `From::from`
2221        // output byte-equals the method-named accessor's return-value on
2222        // each, locking the two forward-projection paths together by
2223        // construction so any future detour (a stray `From` special-case
2224        // that lands on a divergent per-arm literal outside the paired
2225        // `as_str` dispatch, a hypothetical rebrand touching one axis
2226        // without the other) trips at caixa-core test time. Peer of the
2227        // sibling forward-projection partition pins
2228        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
2229        // (523157d) /
2230        // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
2231        // (9fb37d0) /
2232        // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
2233        // (edb827b) — extends the round-trip discipline onto the fourth
2234        // closed-set typed enum on the caixa surface, closing the two-way
2235        // `Self ↔ &'static str` round-trip on the trait-idiomatic pair
2236        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
2237        // well as the pre-existing method-named pair (`as_str` +
2238        // `from_wire`).
2239        for &variant in CaixaDialeto::ALL {
2240            let via_trait: &'static str = <&'static str as From<CaixaDialeto>>::from(variant);
2241            let via_method: &'static str = variant.as_str();
2242            assert_eq!(
2243                via_trait, via_method,
2244                "From<CaixaDialeto> for &'static str and \
2245                 CaixaDialeto::as_str must resolve identically on \
2246                 CaixaDialeto::{variant:?} — divergence signals the \
2247                 two forward-projection paths have drifted onto different \
2248                 emit-sets"
2249            );
2250        }
2251        // Round-trip witness: every arm's forward `From` output re-parses
2252        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
2253        // to the original variant. Closes the two-way `CaixaDialeto ↔
2254        // &'static str` round-trip on the trait-idiomatic axis pair
2255        // directly (no wire-vocab intermediate the peer [`CaixaKind`]
2256        // axis pair requires — the emit-side [`CaixaDialeto::as_str`]
2257        // and the parse-side [`CaixaDialeto::from_wire`] share the same
2258        // `PascalCase` byte-string vocabulary by construction), mirroring
2259        // the pre-existing method-named `as_str` + `from_wire` round-trip
2260        // on the substrate-primitive axis pair.
2261        for &variant in CaixaDialeto::ALL {
2262            let emitted: &'static str = variant.into();
2263            let re_parsed: Result<CaixaDialeto, ()> =
2264                <CaixaDialeto as TryFrom<&str>>::try_from(emitted);
2265            assert_eq!(
2266                re_parsed,
2267                Ok(variant),
2268                "trait-idiomatic axis pair must round-trip \
2269                 CaixaDialeto::{variant:?} through `.into::<&'static \
2270                 str>()` and back through `TryFrom<&str>` — a break signals \
2271                 the forward-emit and reverse-parse axes have drifted onto \
2272                 different vocabularies"
2273            );
2274        }
2275    }
2276
2277    #[test]
2278    fn caixa_dialeto_is_molde_family_routes_through_is_variant_derived_predicates() {
2279        // Byte-parity pin on the post-lift [`CaixaDialeto::is_molde_family`]
2280        // convergence: for every arm in [`CaixaDialeto::ALL`], the typed
2281        // predicate must byte-equal the direct
2282        // `self.is_molde() || self.is_molde_posicional()` composition of
2283        // the two derived per-arm predicates. Pre-lift the predicate
2284        // hand-rolled `matches!(self, Self::Molde | Self::MoldePosicional)`
2285        // with no compile-time link back to the closed-set typed dispatch;
2286        // post-lift it routes through the derived predicates so a future
2287        // arm rename or `#[is_variant(name = "…")]` override lands at
2288        // exactly one dispatch on the substrate primitive. Pinning the
2289        // byte-equality here refuses a future accidental split between
2290        // the composed predicate and the paired derived predicates
2291        // (a hand-rolled shadow `impl` that overrides one path but not
2292        // the other, an accidental rebrand of `is_molde_family`'s body
2293        // back to the pre-lift `matches!` form) at caixa-core build time.
2294        for &d in CaixaDialeto::ALL {
2295            let via_derived = d.is_molde() || d.is_molde_posicional();
2296            let via_is_molde_family = d.is_molde_family();
2297            assert_eq!(
2298                via_is_molde_family, via_derived,
2299                "CaixaDialeto::{d:?}.is_molde_family() ({via_is_molde_family}) \
2300                 must byte-equal the composed derived predicates \
2301                 is_molde() || is_molde_posicional() ({via_derived}) — a \
2302                 split between the composed predicate and its derived \
2303                 building blocks would let a future arm rename land at one \
2304                 path and drift at the other, which is exactly the drift \
2305                 the IsVariant lift refuses"
2306            );
2307        }
2308    }
2309
2310    #[test]
2311    fn caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor() {
2312        // Fail-before-pass-after byte-parity pin on the newly lifted
2313        // `impl From<&CaixaDialeto> for &'static str` — asserts the
2314        // borrowed-input standard-library trait impl and the substrate-
2315        // primitive [`CaixaDialeto::as_str`] `pub const fn` accessor
2316        // resolve to the same four-arm emit-set across every arm the
2317        // exhaustive [`CaixaDialeto::ALL`] slice enumerates. Rust's
2318        // `From` trait does not auto-derive the borrowed-input sibling
2319        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
2320        // where T: Copy, U: From<T>` blanket in `core`), so the
2321        // borrowed-input axis is a distinct trait-idiomatic surface that
2322        // a `.iter().map(Into::into)` shape over [`CaixaDialeto::ALL`]
2323        // (whose iterator yields `&CaixaDialeto`, not `CaixaDialeto`)
2324        // reaches through this impl and no other — the paired owned-
2325        // input [`From<CaixaDialeto>`] impl requires an explicit
2326        // `.copied()` / dereference before the trait fires.
2327        // Materializes the `<&'static str as From<&CaixaDialeto>>::from`
2328        // output in a `const`-shape binding to make the `'static`
2329        // lifetime promise a build-time invariant — a future accidental
2330        // downgrade of any of the four arms' returned literals to a
2331        // non-`&'static str` trips at caixa-core build time rather than
2332        // at a downstream `'static`-bound consumer. Peer of the sibling
2333        // [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2334        // (64aa742) /
2335        // [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2336        // (5ab993a) pins on the sibling closed-set typed-enum borrowed-
2337        // input forward-projection axes — extends the borrowed-input
2338        // axis discipline onto the third peer on the substrate-wide
2339        // campaign, the dialect-classification axis.
2340        const PACOTE: &str = CaixaDialeto::Pacote.as_str();
2341        const MOLDE: &str = CaixaDialeto::Molde.as_str();
2342        const MOLDE_POSICIONAL: &str = CaixaDialeto::MoldePosicional.as_str();
2343        const DESCONHECIDO: &str = CaixaDialeto::Desconhecido.as_str();
2344        for variant in CaixaDialeto::ALL {
2345            let via_trait: &'static str = <&'static str as From<&CaixaDialeto>>::from(variant);
2346            let via_method: &'static str = variant.as_str();
2347            assert_eq!(
2348                via_trait, via_method,
2349                "From<&CaixaDialeto> for &'static str impl must round-trip \
2350                 &CaixaDialeto::{variant:?} to the same `PascalCase` byte-\
2351                 string CaixaDialeto::as_str returns — divergence signals a \
2352                 silent detour off the substrate-primitive accessor"
2353            );
2354            let via_into: &'static str = variant.into();
2355            assert_eq!(
2356                via_into, via_method,
2357                "Into<&'static str>::into on &CaixaDialeto::{variant:?} must \
2358                 byte-equal CaixaDialeto::as_str on the same input — the \
2359                 blanket-derived Into shape must resolve to the same as_str \
2360                 dispatch as the explicit From impl"
2361            );
2362        }
2363        assert_eq!(
2364            [PACOTE, MOLDE, MOLDE_POSICIONAL, DESCONHECIDO],
2365            ["Pacote", "Molde", "MoldePosicional", "Desconhecido"],
2366            "const-context CaixaDialeto::as_str must resolve to the four \
2367             `PascalCase` variant-name byte-strings — the borrowed-input \
2368             From<&CaixaDialeto> for &'static str impl inherits its \
2369             `'static` lifetime promise from the same accessor the owned-\
2370             input sibling routes through"
2371        );
2372    }
2373
2374    #[test]
2375    fn caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
2376        // Cross-axis partition pin: the paired trait-idiomatic
2377        // owned-input `From<CaixaDialeto> for &'static str` and
2378        // borrowed-input `From<&CaixaDialeto> for &'static str` (this
2379        // lift) forward projections must resolve identically on every
2380        // arm, locking the two input-shape paths together so any future
2381        // detour trips at caixa-core test time. Then a witness that a
2382        // `.iter().map(Into::into)` pipe over [`CaixaDialeto::ALL`]
2383        // (whose iterator yields `&CaixaDialeto`) materializes the four-
2384        // arm accept-set through the borrowed-input axis alone — the
2385        // exact shape a future M4 admission-webhook rejection body
2386        // composer, a future substrate-wide per-arm diagnostic column,
2387        // or a `HashMap::<&'static str, CaixaDialeto>::from_iter(
2388        //     CaixaDialeto::ALL.iter().map(|d| (d.into(), *d)))`-style
2389        // per-dialect lookup reaches through — closing the two-way
2390        // owned/borrowed input-shape symmetry on the forward-projection
2391        // trait-idiomatic axis. Peer of the sibling
2392        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2393        // (64aa742) /
2394        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2395        // (5ab993a) partition pins — extends the borrowed-input axis
2396        // discipline onto the third peer on the substrate-wide campaign.
2397        for &variant in CaixaDialeto::ALL {
2398            let owned: &'static str = <&'static str as From<CaixaDialeto>>::from(variant);
2399            let borrowed: &'static str = <&'static str as From<&CaixaDialeto>>::from(&variant);
2400            assert_eq!(
2401                owned, borrowed,
2402                "From<CaixaDialeto> and From<&CaixaDialeto> for &'static str \
2403                 must resolve identically on CaixaDialeto::{variant:?} — \
2404                 divergence signals the owned-input and borrowed-input \
2405                 forward-projection paths have drifted onto different \
2406                 emit-sets"
2407            );
2408        }
2409        let via_iter: Vec<&'static str> = CaixaDialeto::ALL.iter().map(Into::into).collect();
2410        let via_method: Vec<&'static str> = CaixaDialeto::ALL.iter().map(|d| d.as_str()).collect();
2411        assert_eq!(
2412            via_iter, via_method,
2413            "`.iter().map(Into::into)` over CaixaDialeto::ALL must byte-\
2414             equal `.iter().map(|d| d.as_str())` on every arm — the \
2415             borrowed-input `From<&CaixaDialeto> for &'static str` axis \
2416             is what makes the `.iter().map(Into::into)` shape route \
2417             through the substrate-primitive `CaixaDialeto::as_str` \
2418             accessor rather than through a per-call-site `.copied()` / \
2419             dereference detour"
2420        );
2421        // Direct round-trip witness on the borrowed-input axis: every
2422        // arm's borrowed `From` output re-parses through the paired
2423        // trait-idiomatic reverse `TryFrom<&str>` back to the original
2424        // variant. Unlike the peer [`crate::CaixaKind`] axis pair
2425        // (whose forward `From<Self> for &'static str` emits the
2426        // lowercase Portuguese `as_str` diagnostic vocabulary while
2427        // the reverse `TryFrom<&str>` parses the `PascalCase`
2428        // `wire_name` author-surface vocabulary, forcing the round-trip
2429        // through an intermediate wire-vocab hop), [`CaixaDialeto`]'s
2430        // [`CaixaDialeto::as_str`] emit and [`CaixaDialeto::from_wire`]
2431        // parse share the same `PascalCase` vocabulary by construction,
2432        // so the borrowed-input forward axis and the reverse axis
2433        // compose directly.
2434        for &variant in CaixaDialeto::ALL {
2435            let borrowed: &'static str = <&'static str as From<&CaixaDialeto>>::from(&variant);
2436            let re_parsed: Result<CaixaDialeto, ()> =
2437                <CaixaDialeto as TryFrom<&str>>::try_from(borrowed);
2438            assert_eq!(
2439                re_parsed,
2440                Ok(variant),
2441                "trait-idiomatic borrowed-input round-trip must project \
2442                 &CaixaDialeto::{variant:?} through \
2443                 `<&'static str>::from(&variant)` and back through \
2444                 `TryFrom<&str>` — a break signals the borrowed-input \
2445                 forward-emit axis and the reverse-parse axis have \
2446                 drifted onto different vocabularies"
2447            );
2448        }
2449    }
2450
2451    #[test]
2452    fn caixa_dialeto_from_into_owned_string_routes_through_as_str_accessor() {
2453        // Fail-before-pass-after byte-parity pin on the newly lifted
2454        // `impl From<CaixaDialeto> for String` — asserts the owned-`String`
2455        // -returning standard-library trait impl and the substrate-
2456        // primitive [`CaixaDialeto::as_str`] `pub const fn` accessor
2457        // resolve to the same four-arm emit-set across every arm the
2458        // exhaustive [`CaixaDialeto::ALL`] slice enumerates. Rust's
2459        // standard library does not carry a blanket
2460        // `impl<T: AsRef<str>> From<T> for String` (nor an
2461        // `impl<T: fmt::Display> From<T> for String`), so the
2462        // owned-`String` forward-projection axis is a distinct trait-
2463        // idiomatic surface that a `let key: String = dialeto.into();`-
2464        // shaped call site reaches through this impl and no other — the
2465        // paired sibling `From<CaixaDialeto> for &'static str` impl
2466        // forces every owned-`String` call site through an explicit
2467        // `.to_owned()` / `String::from` restatement. Peer of the
2468        // first-mover
2469        // [`crate::supervisor::tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
2470        // (7baa18a), the second-peer
2471        // [`crate::supervisor::tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
2472        // (7851725), and the third-peer
2473        // [`crate::kind::tests::caixa_kind_from_into_owned_string_routes_through_as_str_accessor`]
2474        // (231a18c) — extends the trait-idiomatic owned-`String`
2475        // forward-projection axis onto the fourth closed-set fieldless
2476        // typed enum on the caixa surface (the dialect-classification
2477        // axis, second peer outside the M2 OTP-shape sibling axis).
2478        for &variant in CaixaDialeto::ALL {
2479            let via_trait: String = <String as From<CaixaDialeto>>::from(variant);
2480            let via_method: &'static str = variant.as_str();
2481            assert_eq!(
2482                via_trait.as_str(),
2483                via_method,
2484                "From<CaixaDialeto> for String impl must round-trip \
2485                 CaixaDialeto::{variant:?} to the same `PascalCase` \
2486                 arm-string CaixaDialeto::as_str returns — divergence \
2487                 signals a silent detour off the substrate-primitive \
2488                 accessor"
2489            );
2490            let via_into: String = variant.into();
2491            assert_eq!(
2492                via_into.as_str(),
2493                via_method,
2494                "Into<String>::into on CaixaDialeto::{variant:?} must \
2495                 byte-equal CaixaDialeto::as_str on the same input — the \
2496                 blanket-derived Into shape must resolve to the same \
2497                 as_str dispatch as the explicit From impl"
2498            );
2499        }
2500    }
2501
2502    #[test]
2503    fn caixa_dialeto_from_into_owned_string_and_static_str_agree_on_every_arm() {
2504        // Cross-axis partition pin: the paired trait-idiomatic
2505        // owned-`String` `From<CaixaDialeto> for String` (this lift) and
2506        // owned-`&'static str` `From<CaixaDialeto> for &'static str`
2507        // (c189a6f) forward projections must resolve identically on
2508        // every arm, locking the two return-type-shape paths together
2509        // so any future detour trips at caixa-core test time. Also
2510        // byte-parity witness against the sibling
2511        // [`ToString::to_string`] surface routed through
2512        // [`std::fmt::Display`] — the three owned-heap-string paths
2513        // (`.into::<String>()`, `String::from`, `.to_string()`) must
2514        // resolve identically on every arm so a future consumer that
2515        // picks any of the three lands on the same four-arm
2516        // `PascalCase` accept-set. Then a `.iter().copied()
2517        // .map(String::from)` pipe witness over [`CaixaDialeto::ALL`]
2518        // that materializes the four-arm accept-set through the
2519        // owned-`String` axis alone — the exact shape a future M4
2520        // admission-webhook rejection body composer or a
2521        // `HashMap::<String, CaixaDialeto>::from_iter(
2522        //     CaixaDialeto::ALL.iter().copied().map(|d| (d.into(), d)))`-
2523        // style owned-key per-dialect lookup reaches through — closing
2524        // the owned-`String` forward-projection axis's iterator-pipe
2525        // shape. Then a direct round-trip witness through the paired
2526        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
2527        // owned-`String`'s [`String::as_str`] borrow that closes the
2528        // two-way `Self → String → Self` round-trip on the trait-
2529        // idiomatic owned-`String` forward + reverse axis pair.
2530        //
2531        // Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
2532        // `From` emit lands on the lowercase Portuguese `as_str`
2533        // diagnostic vocabulary while the reverse `TryFrom<&str>` parses
2534        // the `PascalCase` `wire_name` author-surface vocabulary,
2535        // forcing the round-trip through an intermediate
2536        // [`crate::CaixaKind::wire_name`] hop), [`CaixaDialeto`]'s
2537        // [`CaixaDialeto::as_str`] emit and [`CaixaDialeto::from_wire`]
2538        // parse share the same `PascalCase` vocabulary by construction
2539        // (there is no wire/diagnostic axis split on this enum), so
2540        // the owned-`String` forward axis and the reverse axis compose
2541        // directly — matching the peer
2542        // [`crate::supervisor::RestartStrategy`] /
2543        // [`crate::supervisor::RestartPolicy`] owned-`String` axis
2544        // pairs (whose forward emit and reverse parse also share one
2545        // `PascalCase` vocabulary by construction).
2546        for &variant in CaixaDialeto::ALL {
2547            let owned_string: String = <String as From<CaixaDialeto>>::from(variant);
2548            let owned_static: &'static str = <&'static str as From<CaixaDialeto>>::from(variant);
2549            assert_eq!(
2550                owned_string.as_str(),
2551                owned_static,
2552                "From<CaixaDialeto> for String and From<CaixaDialeto> for \
2553                 &'static str must resolve identically on \
2554                 CaixaDialeto::{variant:?} — divergence signals the \
2555                 owned-`String` and owned-`&'static str` forward-\
2556                 projection return-type-shape paths have drifted onto \
2557                 different emit-sets"
2558            );
2559            let via_to_string: String = variant.to_string();
2560            assert_eq!(
2561                owned_string, via_to_string,
2562                "From<CaixaDialeto> for String must byte-equal \
2563                 CaixaDialeto::to_string on CaixaDialeto::{variant:?} — \
2564                 divergence signals the trait-idiomatic owned-`String` \
2565                 forward-projection axis and the ToString-through-\
2566                 Display axis have drifted onto different emit-sets"
2567            );
2568        }
2569        let via_iter: Vec<String> = CaixaDialeto::ALL
2570            .iter()
2571            .copied()
2572            .map(String::from)
2573            .collect();
2574        let via_method: Vec<String> = CaixaDialeto::ALL
2575            .iter()
2576            .map(|d| d.as_str().to_owned())
2577            .collect();
2578        assert_eq!(
2579            via_iter, via_method,
2580            "`.iter().copied().map(String::from)` over CaixaDialeto::ALL \
2581             must byte-equal `.iter().map(|d| d.as_str().to_owned())` on \
2582             every arm — the owned-`String` `From<CaixaDialeto> for \
2583             String` axis is what makes the `String::from` composition \
2584             route through the substrate-primitive `CaixaDialeto::as_str` \
2585             accessor rather than through a per-call-site `.to_owned()` / \
2586             `String::from(dialeto.as_str())` detour"
2587        );
2588        for &variant in CaixaDialeto::ALL {
2589            let emitted: String = variant.into();
2590            let re_parsed: Result<CaixaDialeto, ()> =
2591                <CaixaDialeto as TryFrom<&str>>::try_from(emitted.as_str());
2592            assert_eq!(
2593                re_parsed,
2594                Ok(variant),
2595                "trait-idiomatic owned-`String` forward-projection + \
2596                 reverse-projection axis pair must round-trip \
2597                 CaixaDialeto::{variant:?} through `.into::<String>()` \
2598                 and back through `TryFrom<&str>` on the owned-`String`'s \
2599                 String::as_str borrow — a break signals the owned-\
2600                 `String` forward-emit and reverse-parse axes have \
2601                 drifted onto different vocabularies (unlike the peer \
2602                 CaixaKind axis pair, CaixaDialeto's forward emit and \
2603                 reverse parse share one PascalCase vocabulary by \
2604                 construction, so the round-trip composes directly)"
2605            );
2606        }
2607    }
2608}