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/// A source that is not a `(defcaixa …)` / `(defmolde …)` form at all.
703#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
704pub enum DialetoError {
705    #[error("source has no top-level form")]
706    Vazio,
707    #[error("top-level form is not a list — a manifest is `(defcaixa …)`")]
708    NaoEhLista,
709    #[error(
710        "top-level form is headed by `{encontrado}`, not `defcaixa` or `defmolde` \
711         (a manifest's first form must be the declaration itself)"
712    )]
713    CabecaErrada { encontrado: String },
714    #[error("manifest does not parse as tatara-lisp: {0}")]
715    Leitura(String),
716}
717
718impl DialetoError {
719    /// Construct a [`DialetoError::CabecaErrada`] naming the offending
720    /// head symbol found at the top-level form.
721    ///
722    /// Substrate primitive every [`classify_form`] wrong-head fallthrough
723    /// wire-up site now routes through, folding the pre-lift uniform
724    /// three-line `Self::CabecaErrada { encontrado: <head>.to_string() }`
725    /// one-field struct-literal onto one substrate primitive matching the
726    /// peer `LimitsError::unknown_byte_unit(unit: &str)` /
727    /// `LimitsError::unknown_duration_unit(unit: &str)`
728    /// (`limits_codec_unit_only_ctors!` — 29fac09) single-slot
729    /// discipline on the sibling one-field `{ <field>: String }` envelope
730    /// axis, and matching the peer `ManifestError::code_path_empty` /
731    /// `BehaviorError::empty_path` / `UpgradeError::duplicate_from` /
732    /// `AplicacaoError::placement_cluster_duplicate` (94dabc8 / 0e33b37 /
733    /// 7e52aec / 92b1c92) single-slot inherent-ctor discipline every
734    /// sibling `{ <field>: <T> }` error-envelope variant on caixa-core's
735    /// error surface now carries.
736    ///
737    /// The one open-coded wire-up site — `classify_form`'s wrong-head
738    /// fallthrough arm on the `head: &str` binding read from the
739    /// top-level form via [`tatara_lisp::Sexp::as_symbol`] — opened the
740    /// identical three-line
741    /// `Self::CabecaErrada { encontrado: <head>.to_string() }` block
742    /// against the codec-scoped `<head>: &str` binding. Now routes
743    /// through `DialetoError::cabeca_errada(head)`, byte-equal to the
744    /// pre-lift struct-literal on the same `&str` fixture, so any future
745    /// widening of the diagnostic shape (e.g. carrying the source-file
746    /// path alongside the head symbol, carrying the head symbol's
747    /// position offset for an authoring-surface caret pointer) lands at
748    /// exactly one dispatch on the substrate primitive rather than re-
749    /// inlining the struct-literal at every wrong-head fallthrough
750    /// consumer.
751    #[must_use]
752    pub fn cabeca_errada(encontrado: &str) -> Self {
753        Self::CabecaErrada {
754            encontrado: encontrado.to_string(),
755        }
756    }
757
758    /// Construct a [`DialetoError::Leitura`] carrying the offending
759    /// tatara-lisp reader-error message `reason` verbatim in the
760    /// variant's tuple-newtype payload.
761    ///
762    /// Substrate primitive every [`classify`] tatara-lisp-reader
763    /// map-err wire-up site now routes through, folding the pre-lift
764    /// uniform `Self::Leitura(<into-String-expr>)` tuple-newtype
765    /// construction onto one substrate primitive matching the peer
766    /// `LimitsError::empty_byte_size` / `LimitsError::empty_duration`
767    /// (7a4b003 / 319216c) `(String)` single-slot tuple-newtype
768    /// discipline on the sibling
769    /// [`crate::limits::LimitsError`] envelope's empty-shape axis of
770    /// the paired codec-magnitude family. Peer to the sibling
771    /// [`DialetoError::cabeca_errada`] ctor on the same envelope's
772    /// wrong-head axis but on the tatara-lisp-reader axis rather than
773    /// the classifier-fallthrough axis. Closes the last un-lifted
774    /// variant on [`DialetoError`] — every one of the sole wire-up
775    /// sites (the [`classify`] tatara-lisp-reader `.map_err(|e|
776    /// Self::Leitura(e.to_string()))` arm) opened the identical
777    /// `DialetoError::Leitura(<into-String-expr>)` block against the
778    /// codec-scoped `String` (`e.to_string()`) binding, so the fold
779    /// routes the site through one dispatch on a uniform
780    /// `impl Into<String>` param, byte-equal to the pre-lift
781    /// tuple-newtype construction on the same argument.
782    ///
783    /// The `impl Into<String>` bound covers both wire-up shapes on
784    /// [`classify`] — a `String` binding (`e.to_string()` on the
785    /// [`tatara_lisp::Error`]-carrying `e` binding) and a `&str`
786    /// binding (a future admission-webhook consumer probing a
787    /// caller-scoped `&'static str` fixture, a future
788    /// `feira lint --tatara-reader-round-trip` verb sweeping every
789    /// `tatara_lisp::read` return through the same shape gate) —
790    /// without forcing the caller to spell the conversion at the
791    /// wire-up site. Same shape the peer
792    /// [`crate::limits::LimitsError::empty_byte_size`] /
793    /// [`crate::limits::LimitsError::empty_duration`] /
794    /// [`crate::limits::LimitsError::bad_millicores`] /
795    /// [`crate::limits::LimitsError::bad_byte_magnitude`] /
796    /// [`crate::limits::LimitsError::bad_duration_magnitude`] folds
797    /// carry on the peer bad-magnitude and empty-shape axes of the
798    /// same paired `(String)` tuple-newtype codec-magnitude family.
799    /// `#[must_use]` fires a compile warning at any wire-up that
800    /// mistakenly discards the constructed error.
801    ///
802    /// Every future consumer that wants to construct this variant
803    /// outside [`classify`] (a deferred `feira lint --tatara-reader-
804    /// round-trip` per-caixa admission verb probing each authored
805    /// manifest against the tatara-lisp-reader shape gate, an M4
806    /// typed `mesh.pleme.io/v1alpha1/Servico` CR materializer's
807    /// per-manifest admission validator re-checking one edited
808    /// `caixa.lisp` against the reader floor, a per-`caixa.lisp`
809    /// value-shape pre-emitter probing each declared manifest ahead
810    /// of the operator's admit-cycle) now reaches the variant
811    /// through one call rather than re-inlining the tuple-newtype
812    /// block in lockstep with the pre-existing wire-up.
813    #[must_use]
814    pub fn leitura(reason: impl Into<String>) -> Self {
815        Self::Leitura(reason.into())
816    }
817}
818
819/// Classify a manifest source without committing to either schema.
820///
821/// Deliberately reads only the head symbol and the set of top-level keywords —
822/// enough to route, never enough to half-parse. A classifier that started
823/// validating would grow into a third parser, which is the shape of the problem
824/// it exists to name.
825///
826/// # Errors
827/// [`DialetoError`] when the source is not a manifest declaration at all.
828pub fn classify(src: &str) -> Result<CaixaDialeto, DialetoError> {
829    let forms = tatara_lisp::read(src).map_err(|e| DialetoError::leitura(e.to_string()))?;
830    let first = forms.first().ok_or(DialetoError::Vazio)?;
831    classify_form(first)
832}
833
834/// [`classify`] over an already-read form.
835///
836/// # Errors
837/// [`DialetoError`] when the form is not a manifest declaration.
838pub fn classify_form(form: &Sexp) -> Result<CaixaDialeto, DialetoError> {
839    let list = form.as_list().ok_or(DialetoError::NaoEhLista)?;
840    let head = list
841        .first()
842        .and_then(Sexp::as_symbol)
843        .ok_or(DialetoError::NaoEhLista)?;
844
845    match head {
846        // `defmolde` is unambiguous by construction — it exists precisely so a
847        // consumer never has to infer which declaration it holds. Both arities
848        // are the same declaration; the positional one keeps its own variant
849        // only so a census can report the split.
850        "defmolde" => {
851            return Ok(if starts_with_positional_name(&list[1..]) {
852                CaixaDialeto::MoldePosicional
853            } else {
854                CaixaDialeto::Molde
855            });
856        }
857        "defcaixa" => {}
858        other => {
859            return Err(DialetoError::cabeca_errada(other));
860        }
861    }
862
863    let args = &list[1..];
864
865    // `(defcaixa <symbol> :kind … :ecosystem …)`. Only the Molde dialect has a
866    // positional arity; `Caixa` is keyword-only, so a leading bare symbol
867    // settles it without looking further.
868    if starts_with_positional_name(args) {
869        return Ok(CaixaDialeto::MoldePosicional);
870    }
871
872    let keys = top_level_keywords(args);
873    let has = |k: &str| keys.iter().any(|s| s == k);
874
875    // Order matters, and it is not arbitrary: `:nome` and `:name` are the two
876    // required head slots and no file in the measured corpus carries both.
877    // Checking them FIRST means the decision rests on the one slot each schema
878    // makes mandatory, rather than on optional evidence like `:ecosystem`.
879    if has("nome") {
880        return Ok(CaixaDialeto::Pacote);
881    }
882    if has("name") || has("ecosystem") || has("package") {
883        return Ok(CaixaDialeto::Molde);
884    }
885    Ok(CaixaDialeto::Desconhecido)
886}
887
888/// True when the first argument is a bare symbol rather than a keyword — the
889/// positional-name arity.
890fn starts_with_positional_name(args: &[Sexp]) -> bool {
891    matches!(args.first(), Some(Sexp::Atom(Atom::Symbol(_))))
892}
893
894/// The top-level keyword names (without the leading `:`) of a kwarg list.
895///
896/// Steps in pairs so a keyword appearing as a VALUE — `:kind :Biblioteca`, or a
897/// nested `(:nome "dep" :versao "^0.1")` inside `:deps` — is never counted as a
898/// top-level slot. A naive scan for `:nome` anywhere in the source classifies
899/// every Molde manifest with a `:deps` list as a Pacote.
900fn top_level_keywords(args: &[Sexp]) -> Vec<String> {
901    let mut out = Vec::new();
902    let mut i = 0;
903    while i < args.len() {
904        if let Sexp::Atom(Atom::Keyword(k)) = &args[i] {
905            out.push(k.clone());
906            i += 2;
907        } else {
908            i += 1;
909        }
910    }
911    out
912}
913
914#[cfg(test)]
915mod tests {
916    use super::*;
917
918    const PACOTE: &str = r#"
919      (defcaixa
920        :nome   "checkout"
921        :versao "0.1.0"
922        :kind   Servico
923        :deps   ((:nome "caixa-teia" :versao "^0.1")))
924    "#;
925
926    const MOLDE: &str = r#"
927      (defcaixa
928        :name "base64"
929        :kind :Biblioteca
930        :ecosystem :rust-single-crate
931        :package {:name "base64" :version "0.22.1"}
932        :workflows [:auto-release])
933    "#;
934
935    const MOLDE_POSICIONAL: &str = r#"
936      (defcaixa todoku-go
937        :kind :Biblioteca
938        :ecosystem :go
939        :package {:name "todoku-go" :version "0.3.0"})
940    "#;
941
942    #[test]
943    fn the_package_dialect_is_recognised() {
944        assert_eq!(classify(PACOTE), Ok(CaixaDialeto::Pacote));
945    }
946
947    #[test]
948    fn the_repo_surface_dialect_is_recognised() {
949        assert_eq!(classify(MOLDE), Ok(CaixaDialeto::Molde));
950    }
951
952    #[test]
953    fn the_positional_arity_is_recognised() {
954        assert_eq!(
955            classify(MOLDE_POSICIONAL),
956            Ok(CaixaDialeto::MoldePosicional)
957        );
958    }
959
960    #[test]
961    fn defmolde_classifies_without_inference() {
962        // The whole point of the new keyword: no schema sniffing required.
963        let src = r#"(defmolde :name "x" :kind :Biblioteca :ecosystem :go)"#;
964        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
965        let pos = r"(defmolde todoku-go :kind :Biblioteca :ecosystem :go)";
966        assert_eq!(classify(pos), Ok(CaixaDialeto::MoldePosicional));
967    }
968
969    #[test]
970    fn a_nested_nome_does_not_make_a_repo_surface_look_like_a_package() {
971        // The exact failure a substring scan produces: `:deps ((:nome …))`
972        // contains `:nome`, but not as a top-level slot.
973        let src = r#"
974          (defcaixa
975            :name "x"
976            :ecosystem :rust-single-crate
977            :deps ((:nome "inner" :versao "^0.1")))
978        "#;
979        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
980    }
981
982    #[test]
983    fn a_keyword_in_value_position_is_not_a_slot() {
984        // `:kind :Biblioteca` — the value is itself a keyword. Stepping one at
985        // a time would read `:Biblioteca` as a top-level slot.
986        let src = r#"(defcaixa :kind :Biblioteca :name "x")"#;
987        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
988    }
989
990    #[test]
991    fn an_unrecognised_defcaixa_is_reported_not_guessed() {
992        let src = r#"(defcaixa :licenca "MIT")"#;
993        assert_eq!(classify(src), Ok(CaixaDialeto::Desconhecido));
994    }
995
996    #[test]
997    fn a_form_that_is_not_a_manifest_is_an_error_not_a_dialect() {
998        assert_eq!(
999            classify("(defflake :nome \"x\")"),
1000            Err(DialetoError::cabeca_errada("defflake"))
1001        );
1002        assert_eq!(classify(""), Err(DialetoError::Vazio));
1003    }
1004
1005    #[test]
1006    fn every_dialect_names_its_consumer_and_its_canonical_keyword() {
1007        // Guards the routing table itself: a new variant added without an arm
1008        // here is a compile error in the match, and a variant that claims
1009        // `defcaixa` while being read by pleme-doc-gen would re-open the
1010        // collision this module closes. Sweeps [`CaixaDialeto::ALL`] rather
1011        // than the pre-lift open-coded four-arm literal list — a future arm
1012        // addition extends the slice as one edit and this pin picks it up
1013        // by construction.
1014        for &d in CaixaDialeto::ALL {
1015            assert!(!d.descricao().is_empty(), "{d}");
1016            assert!(!d.consumidor().is_empty(), "{d}");
1017        }
1018        assert_eq!(CaixaDialeto::Pacote.palavra_canonica(), "defcaixa");
1019        assert_eq!(CaixaDialeto::Molde.palavra_canonica(), "defmolde");
1020        assert_ne!(
1021            CaixaDialeto::Pacote.palavra_canonica(),
1022            CaixaDialeto::Molde.palavra_canonica(),
1023            "the two dialects must not share a canonical keyword — that IS the defect"
1024        );
1025    }
1026
1027    #[test]
1028    fn caixa_dialeto_all_enumerates_every_variant_exactly_once() {
1029        // Three-legged exhaustiveness pin, peer of the sibling
1030        // `caixa_kind_all_enumerates_every_variant_exactly_once`
1031        // (caixa-core/src/kind.rs) /
1032        // `restart_strategy_all_enumerates_every_variant_exactly_once`
1033        // (caixa-core/src/supervisor.rs) shape.
1034        //
1035        // 1. arm-count invariant: `ALL.len()` matches the declared arm
1036        //    count (four — a fifth arm added without extending `ALL`
1037        //    fails this pin at caixa-core test time);
1038        // 2. pairwise-distinctness invariant: every variant appears at
1039        //    most once in the slice (a duplicate arm would silently
1040        //    double-count in the census consumer, so the pin rejects
1041        //    duplicates outright);
1042        // 3. coverage invariant: every literal `CaixaDialeto::X` is in
1043        //    the slice (the compiler-checked exhaustiveness on the peer
1044        //    per-arm `match self` in the accessors keeps the enum arm
1045        //    set and the `ALL` slice mutually aligned).
1046        assert_eq!(
1047            CaixaDialeto::ALL.len(),
1048            4,
1049            "ALL must list every arm exactly once; a fifth arm added \
1050             without extending ALL fails this pin — extend ALL alongside \
1051             the new variant"
1052        );
1053
1054        let mut seen: Vec<CaixaDialeto> = Vec::new();
1055        for &d in CaixaDialeto::ALL {
1056            assert!(
1057                !seen.contains(&d),
1058                "ALL contains a duplicate arm: {d}. Every variant appears \
1059                 exactly once — a duplicate would double-count in every \
1060                 iteration consumer"
1061            );
1062            seen.push(d);
1063        }
1064
1065        // Coverage: exhaustively assert every literal variant is somewhere
1066        // in the slice. Written as an exhaustive `match` so a future arm
1067        // addition fails to compile here (missing match arm) until the
1068        // corresponding `assert` is added — the compiler enforces the pin's
1069        // completeness rather than a hand-maintained variant list.
1070        for variant in [
1071            CaixaDialeto::Pacote,
1072            CaixaDialeto::Molde,
1073            CaixaDialeto::MoldePosicional,
1074            CaixaDialeto::Desconhecido,
1075        ] {
1076            let coverage_probe = match variant {
1077                CaixaDialeto::Pacote
1078                | CaixaDialeto::Molde
1079                | CaixaDialeto::MoldePosicional
1080                | CaixaDialeto::Desconhecido => variant,
1081            };
1082            assert!(
1083                CaixaDialeto::ALL.contains(&coverage_probe),
1084                "ALL is missing variant {coverage_probe} — extend the slice"
1085            );
1086        }
1087    }
1088
1089    #[test]
1090    fn caixa_dialeto_all_is_const_and_matches_iteration_count() {
1091        // Pins the const-ness of the slice at const-fold time. A future
1092        // change that promoted `ALL` to a non-const initializer (a lazy-
1093        // static, a runtime-computed Vec) would fail to compile here —
1094        // the pin locks in the compile-time-known iteration surface
1095        // every consumer builds against. Peer of the sibling
1096        // `caixa_kind_all_is_const_and_matches_iteration_count` (kind.rs)
1097        // / `restart_strategy_all_is_const_and_matches_iteration_count`
1098        // (supervisor.rs) shape.
1099        const ALL: &[CaixaDialeto] = CaixaDialeto::ALL;
1100        assert_eq!(ALL.len(), CaixaDialeto::ALL.len());
1101        // Sweep the iterator without collapsing to `.len()` so a future
1102        // change to `ALL`'s carrier that decouples `.len()` from the
1103        // iteration count (a lazy-computed shape, an alias `impl Iterator`
1104        // return, a wrapper newtype) still passes here iff the two agree
1105        // arm-for-arm; the `#[allow]` opts this local pin out of the
1106        // clippy `iter_count` collapse that would defeat the intent.
1107        #[allow(clippy::iter_count)]
1108        let iterated = ALL.iter().count();
1109        assert_eq!(iterated, CaixaDialeto::ALL.len());
1110    }
1111
1112    #[test]
1113    fn caixa_dialeto_all_covers_every_variant_by_display_probe() {
1114        // Fanning `Display` over the slice sweeps the paired accessors
1115        // ([`CaixaDialeto::palavra_canonica`] / [`CaixaDialeto::consumidor`]
1116        // / [`CaixaDialeto::descricao`]) at every arm — every returned
1117        // byte-string is non-empty (the accessors' contract). A future
1118        // arm added without extending its per-arm `match self` return
1119        // would compile-fail at the accessor call inside the loop;
1120        // together with the `ALL.len() == 4` pin above, this locks the
1121        // accessor arm-set and the `ALL` slice mutually.
1122        for &d in CaixaDialeto::ALL {
1123            let display_form = d.to_string();
1124            assert!(
1125                !display_form.is_empty(),
1126                "Display must render a non-empty byte-string for every \
1127                 arm; empty: {d:?}"
1128            );
1129            // Consumidor / descricao / palavra-canonica must each surface
1130            // a non-empty scalar; every downstream diagnostic consumer
1131            // reaches through these accessors.
1132            assert!(!d.palavra_canonica().is_empty(), "{d}");
1133            assert!(!d.consumidor().is_empty(), "{d}");
1134            assert!(!d.descricao().is_empty(), "{d}");
1135        }
1136    }
1137
1138    #[test]
1139    fn caixa_dialeto_as_str_returns_pascal_case_variant_name() {
1140        // Fail-before-pass-after per-arm shape pin: the four
1141        // [`CaixaDialeto::as_str`] arms must return the canonical
1142        // `PascalCase` byte-string that names the variant. Pre-lift this
1143        // byte-string existed only inside the hand-rolled Display impl's
1144        // four-arm literal-string match — every consumer that wanted the
1145        // `PascalCase` name reached through `format!("{d}")`'s allocation
1146        // path. Pinning the four arms explicitly here refuses a future
1147        // regression that ever reroutes an arm to a distinct spelling
1148        // (`"pacote"` lowercase, `"MoldePositional"` English rebrand,
1149        // `"Unknown"` for `Desconhecido`) — the census output and the
1150        // typed accessor would silently disagree until a downstream
1151        // consumer surfaced the drift at census time. Peer of the sibling
1152        // [`crate::supervisor::tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
1153        // / `placement_strategy_variants_serialize_to_lifted_scalar_values`
1154        // / `caixa_kind_as_str_returns_lifted_peer_const` shape on the
1155        // sibling closed-set typed-enum discriminator axes — the seventh
1156        // (and last unlifted) closed-set typed enum on the caixa surface
1157        // to converge onto the same per-arm-shape-pin discipline.
1158        for (variant, expected) in [
1159            (CaixaDialeto::Pacote, "Pacote"),
1160            (CaixaDialeto::Molde, "Molde"),
1161            (CaixaDialeto::MoldePosicional, "MoldePosicional"),
1162            (CaixaDialeto::Desconhecido, "Desconhecido"),
1163        ] {
1164            assert_eq!(
1165                variant.as_str(),
1166                expected,
1167                "CaixaDialeto::{variant:?}.as_str() must return the \
1168                 canonical `PascalCase` variant-name byte-string; drift here \
1169                 splits the census-facing text from the substrate \
1170                 primitive every downstream consumer will read"
1171            );
1172        }
1173    }
1174
1175    #[test]
1176    fn caixa_dialeto_display_routes_through_as_str_helper() {
1177        // Fail-before-pass-after convergence pin: for every arm in
1178        // [`CaixaDialeto::ALL`], the [`std::fmt::Display`] rendered form
1179        // must byte-equal [`CaixaDialeto::as_str`]'s return value. Pre-
1180        // lift these two paths were structurally independent — the
1181        // Display impl hand-rolled its own four-arm literal-string
1182        // match with no compile-time link back to any substrate accessor
1183        // — so a future variant rename could land at `Display` without
1184        // touching a paired accessor (or vice versa), silently splitting
1185        // the two paths on the renamed arm. Pinning the byte-equality
1186        // here makes any such split a caixa-core build-time failure at
1187        // this test rather than surfacing far from the rename commit as
1188        // a downstream census consumer emitting one spelling while the
1189        // typed accessor returned another. Peer of the sibling
1190        // [`crate::kind::tests::caixa_kind_display_routes_through_as_str_helper`]
1191        // (which pins the same convergence on the [`crate::CaixaKind`]
1192        // closed-set axis) — extends the discipline onto the seventh
1193        // (and last unlifted) closed-set fieldless typed enum on the
1194        // caixa surface.
1195        for &variant in CaixaDialeto::ALL {
1196            assert_eq!(
1197                variant.to_string(),
1198                variant.as_str(),
1199                "CaixaDialeto::{variant:?} Display must route through \
1200                 CaixaDialeto::as_str (single source of truth: the \
1201                 lifted per-arm `PascalCase` variant-name byte-string)"
1202            );
1203        }
1204    }
1205
1206    #[test]
1207    fn caixa_dialeto_as_ref_str_routes_through_as_str_accessor() {
1208        // Fail-before-pass-after byte-parity pin on the lifted
1209        // `impl AsRef<str> for CaixaDialeto` — asserts the standard-
1210        // library trait impl and the substrate-primitive
1211        // [`CaixaDialeto::as_str`] `pub const fn` accessor resolve to
1212        // the same `&str` per instance across the four-arm closed set,
1213        // so any future silent detour that routes the impl through a
1214        // divergent projection (a per-arm inline
1215        // `match self { CaixaDialeto::Pacote => "Pacote", … }` re-inlining
1216        // that opens a compile-time link to the un-lifted arm-literal,
1217        // a swap onto the second-axis
1218        // [`CaixaDialeto::palavra_canonica`] /
1219        // [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`]
1220        // accessors that carry distinct byte-shapes per axis) trips at
1221        // caixa-core test time under `PartialEq` rather than at a
1222        // downstream `impl AsRef<str>`-bound consumer's silent split.
1223        // Sweeps every one of the four arms [`CaixaDialeto::ALL`]
1224        // carries so no arm's projection is covered only by the sibling
1225        // `Display` path. Peer of the sibling
1226        // `rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`
1227        // (d8136db) on the M3 `:politicas :rate-limit` closed-set typed
1228        // enum, and the peer
1229        // [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
1230        // (cd2091f) pin on the top-level closed-set typed
1231        // discriminator — the pins together close the substrate
1232        // primitive's `AsRef<str>` projection axis onto the seventh
1233        // closed-set fieldless typed enum on the caixa surface.
1234        for &variant in CaixaDialeto::ALL {
1235            assert_eq!(
1236                <CaixaDialeto as AsRef<str>>::as_ref(&variant),
1237                variant.as_str(),
1238                "AsRef<str> impl on CaixaDialeto::{variant:?} must \
1239                 byte-equal CaixaDialeto::as_str on the same instance \
1240                 — divergence signals a silent detour off the \
1241                 substrate-primitive accessor"
1242            );
1243        }
1244    }
1245
1246    #[test]
1247    fn caixa_dialeto_as_ref_str_routes_through_display_via_shared_accessor() {
1248        // Fail-before-pass-after byte-parity pin on the three-path
1249        // convergence discipline the [`CaixaDialeto`] closed-set
1250        // dialect-classification enum now carries on the `&str`-
1251        // projection axis: `<CaixaDialeto as AsRef<str>>::as_ref(&v)`
1252        // (the newly lifted impl), `format!("{v}")` (the pre-existing
1253        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
1254        // primitive `pub const fn` accessor both trait impls delegate
1255        // through) must resolve to the same byte-string on every
1256        // instance across the four-arm closed set. Refuses any future
1257        // divergence between the two trait impls (a stray
1258        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
1259        // rather than delegating through the shared accessor; a
1260        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
1261        // literal cascade) that would silently split the two
1262        // projection paths of the same closed-set typed enum. Mirrors
1263        // the sibling three-path-convergence discipline the peer
1264        // [`crate::aplicacao::RateLimitUnit`] typed enum carries
1265        // (`rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`,
1266        // d8136db), the peer [`crate::CaixaKind`] triple
1267        // (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
1268        // cd2091f), and the [`crate::CaixaVersion`] typed newtype
1269        // triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
1270        // 16d5c7e).
1271        for &variant in CaixaDialeto::ALL {
1272            let via_as_ref: &str = <CaixaDialeto as AsRef<str>>::as_ref(&variant);
1273            let via_display: String = format!("{variant}");
1274            let via_accessor: &str = variant.as_str();
1275            assert_eq!(via_as_ref, via_accessor);
1276            assert_eq!(via_display, via_accessor);
1277            assert_eq!(via_as_ref, via_display.as_str());
1278        }
1279    }
1280
1281    #[test]
1282    fn caixa_dialeto_is_molde_family_returns_true_on_molde_and_positional_arms() {
1283        // Fail-before-pass-after per-arm shape pin on the two `defmolde`
1284        // declaration-family arms: [`CaixaDialeto::is_molde_family`] must
1285        // return `true` for [`CaixaDialeto::Molde`] and
1286        // [`CaixaDialeto::MoldePosicional`] — the two-arity closure of
1287        // one declaration ([`CaixaDialeto::MoldePosicional`]'s docstring:
1288        // "same declaration as [`Self::Molde`], written with the package
1289        // name as a bare positional symbol … one arity of one
1290        // declaration, not a third schema"). A future accidental flip that
1291        // reversed a per-arm arm's return without touching the paired
1292        // false-arm pin would silently open the substrate primitive to
1293        // false-positive on either arm — the `feira dialeto` verb's
1294        // `--strict-palavra` gate would then silently accept
1295        // repo-surface declarations under `(defcaixa …)` on one arm and
1296        // reject them on the other. Pinning the two true arms explicitly
1297        // here refuses that split at caixa-core build time.
1298        assert!(
1299            CaixaDialeto::Molde.is_molde_family(),
1300            "CaixaDialeto::Molde.is_molde_family() must return true — \
1301             Molde is the primary `defmolde` arm"
1302        );
1303        assert!(
1304            CaixaDialeto::MoldePosicional.is_molde_family(),
1305            "CaixaDialeto::MoldePosicional.is_molde_family() must return \
1306             true — MoldePosicional is the positional-arity form of the \
1307             same `defmolde` declaration Molde carries"
1308        );
1309    }
1310
1311    #[test]
1312    fn caixa_dialeto_is_molde_family_returns_false_on_pacote_and_desconhecido_arms() {
1313        // Fail-before-pass-after per-arm shape pin on the two non-`defmolde`
1314        // arms: [`CaixaDialeto::is_molde_family`] must return `false` for
1315        // [`CaixaDialeto::Pacote`] (the sibling `defcaixa` tatara-lisp
1316        // package manifest, `palavra_canonica → "defcaixa"`) and for
1317        // [`CaixaDialeto::Desconhecido`] (the residue that names no
1318        // known declaration, `palavra_canonica → "?"`). Pinning the two
1319        // false arms explicitly here refuses a future accidental flip
1320        // that let the predicate widen to include either arm — the
1321        // `feira dialeto` verb's `--strict-palavra` gate would then
1322        // spuriously refuse every `(defcaixa …)` package manifest as if
1323        // it were a repo-surface declaration.
1324        assert!(
1325            !CaixaDialeto::Pacote.is_molde_family(),
1326            "CaixaDialeto::Pacote.is_molde_family() must return false — \
1327             Pacote is the `defcaixa` tatara-lisp package manifest, not \
1328             the `defmolde` repo-surface declaration"
1329        );
1330        assert!(
1331            !CaixaDialeto::Desconhecido.is_molde_family(),
1332            "CaixaDialeto::Desconhecido.is_molde_family() must return \
1333             false — the residue arm names no known declaration; it is \
1334             not silently promoted into the `defmolde` family"
1335        );
1336    }
1337
1338    #[test]
1339    fn caixa_dialeto_is_molde_family_agrees_with_palavra_canonica_defmolde_projection() {
1340        // Load-bearing pin: for every arm in [`CaixaDialeto::ALL`], the
1341        // typed [`CaixaDialeto::is_molde_family`] predicate must agree
1342        // byte-for-byte with the paired [`CaixaDialeto::palavra_canonica`]
1343        // projection's `== "defmolde"` classifier — i.e. the two paths
1344        // partition the four-arm discriminator set into the same
1345        // `{Molde, MoldePosicional}` and `{Pacote, Desconhecido}` halves.
1346        // Pre-lift the sibling [`CaixaDialeto::palavra_canonica`] projection
1347        // (which returns `"defmolde"` for `Molde | MoldePosicional`,
1348        // `"defcaixa"` for `Pacote`, `"?"` for `Desconhecido`) was the
1349        // only substrate-side surface carrying the two-arm collapse; the
1350        // hand-rolled `matches!(d, CaixaDialeto::Molde |
1351        // CaixaDialeto::MoldePosicional)` sites in the `feira dialeto`
1352        // verb expressed no compile-time link back to it. A future arm
1353        // addition — the module doc's "third dialect" hazard actualises
1354        // as a fifth arm belonging to the `defmolde` family — would land
1355        // one match arm at [`Self::palavra_canonica`]'s `defmolde` return
1356        // (extending the sibling projection) but silently split the
1357        // hand-rolled two-arm `matches!` predicate sites if the new arm's
1358        // `is_molde_family` return were forgotten. Pinning byte-equality
1359        // between the two paths here makes any such split a caixa-core
1360        // build-time failure at this test rather than surfacing far from
1361        // the arm-addition commit as a downstream `--strict-palavra` /
1362        // `caixa.lisp`-holds-wrong-declaration gate silently ignoring the
1363        // new arm.
1364        for &d in CaixaDialeto::ALL {
1365            let via_palavra_canonica = d.palavra_canonica() == "defmolde";
1366            let via_is_molde_family = d.is_molde_family();
1367            assert_eq!(
1368                via_is_molde_family, via_palavra_canonica,
1369                "CaixaDialeto::{d:?}.is_molde_family() ({via_is_molde_family}) \
1370                 must agree with CaixaDialeto::{d:?}.palavra_canonica() == \
1371                 \"defmolde\" ({via_palavra_canonica}) — a split between the \
1372                 typed predicate and the sibling keyword projection would let \
1373                 a future arm addition land at one path and drift at the other, \
1374                 which is exactly the drift this pin refuses"
1375            );
1376        }
1377    }
1378
1379    #[test]
1380    fn caixa_dialeto_is_molde_family_is_const_fn() {
1381        // Const-context pin: [`CaixaDialeto::is_molde_family`] must remain
1382        // `const fn` (its match is a fieldless-arm literal-pattern
1383        // discriminator, so no non-const operation exists on the resolution
1384        // path). Downstream consumers reaching for the predicate from a
1385        // `const` context (a future substrate-wide const-fold-driven audit
1386        // table that materializes per-arm gate-membership at build time,
1387        // a per-arm CR-admission-webhook gate registration in a `const`
1388        // context) rely on the const-ness. A future accidental downgrade
1389        // to non-`const` (an added runtime helper reachable only from a
1390        // non-`const` context) trips at caixa-core build time rather than
1391        // surfacing as a downstream `const`-context regression far from
1392        // the predicate declaration. Peer of the sibling
1393        // [`caixa_dialeto_as_str_is_const_fn`] pin on the paired
1394        // [`CaixaDialeto::as_str`] byte-string axis.
1395        const ARMS: [(CaixaDialeto, bool); 4] = [
1396            (CaixaDialeto::Pacote, CaixaDialeto::Pacote.is_molde_family()),
1397            (CaixaDialeto::Molde, CaixaDialeto::Molde.is_molde_family()),
1398            (
1399                CaixaDialeto::MoldePosicional,
1400                CaixaDialeto::MoldePosicional.is_molde_family(),
1401            ),
1402            (
1403                CaixaDialeto::Desconhecido,
1404                CaixaDialeto::Desconhecido.is_molde_family(),
1405            ),
1406        ];
1407        // Materialize the const-fold-evaluated table into a runtime slice
1408        // assertion — carries the same `bool = const fn call` shape a raw
1409        // `assert!(const_bool)` would, without tripping the
1410        // `assertions_on_constants` clippy lint that a per-arm
1411        // `assert!(CONST)` on a `const bool` triggers when the arm-count
1412        // is enumerated flat rather than compared as a whole-table shape.
1413        assert_eq!(
1414            ARMS,
1415            [
1416                (CaixaDialeto::Pacote, false),
1417                (CaixaDialeto::Molde, true),
1418                (CaixaDialeto::MoldePosicional, true),
1419                (CaixaDialeto::Desconhecido, false),
1420            ],
1421            "CaixaDialeto::is_molde_family() must evaluate in const context \
1422             for every arm and land on the {{false, true, true, false}} \
1423             partition — a future accidental downgrade to non-`const` \
1424             would trip the const-context array-initializer here"
1425        );
1426    }
1427
1428    #[test]
1429    fn caixa_dialeto_as_str_is_const_fn() {
1430        // Const-context pin: [`CaixaDialeto::as_str`] must remain
1431        // `const fn` (its match arms return `pub const` byte-strings, so
1432        // no non-const operation exists on the resolution path).
1433        // Downstream consumers reaching for the accessor from a `const`
1434        // context (a future substrate-wide const-fold-driven audit table
1435        // that materializes every dialect's census label at build time,
1436        // a per-arm CR-admission-webhook message registration in a
1437        // `const` gate) rely on the const-ness. A future accidental
1438        // downgrade to non-`const` (an added runtime helper reachable
1439        // only from a non-`const` context, a manual hand-rolled `impl`
1440        // that shadows this method) trips at caixa-core build time
1441        // rather than surfacing as a downstream `const`-context
1442        // regression far from the accessor declaration. Peer of the
1443        // sibling [`crate::kind::tests::caixa_kind_wire_name_is_const_fn`]
1444        // pin on the paired [`crate::CaixaKind`] byte-string axis.
1445        const PACOTE: &str = CaixaDialeto::Pacote.as_str();
1446        const MOLDE: &str = CaixaDialeto::Molde.as_str();
1447        const MOLDE_POSICIONAL: &str = CaixaDialeto::MoldePosicional.as_str();
1448        const DESCONHECIDO: &str = CaixaDialeto::Desconhecido.as_str();
1449        assert_eq!(PACOTE, "Pacote");
1450        assert_eq!(MOLDE, "Molde");
1451        assert_eq!(MOLDE_POSICIONAL, "MoldePosicional");
1452        assert_eq!(DESCONHECIDO, "Desconhecido");
1453    }
1454
1455    #[test]
1456    fn caixa_dialeto_is_variant_predicates_partition_the_arm_set() {
1457        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
1458        // derive: for each of the four variants at [`CaixaDialeto::ALL`]`[idx]`
1459        // the observed four-slot predicate row must equal a one-hot row
1460        // with the `true` at exactly `idx`. Pre-derive the closed four-arm
1461        // dialect-classification partition lived only inside the paired
1462        // per-arm projections' four-arm match resolvers ([`Self::as_str`] /
1463        // [`Self::palavra_canonica`] / [`Self::consumidor`] /
1464        // [`Self::descricao`]) plus the two-arm [`Self::is_molde_family`]
1465        // hand-rolled `matches!` (now routed through the derived
1466        // predicates); a future rebrand (an accidental
1467        // `#[is_variant(name = "…")]` drift, a manual hand-rolled `impl`
1468        // that shadows the derive-generated method, an arm rename that
1469        // reroutes one arm through the wrong predicate lane) trips this
1470        // pin at caixa-core build time rather than surfacing far from the
1471        // derive declaration as a downstream [`Self::is_molde_family`]
1472        // consumer accepting the wrong arm-set. The expected row is
1473        // generated live from the [`Self::ALL`] declaration order rather
1474        // than transcribed by hand so a copy-paste flip reroutes at the
1475        // identity-diagonal assertion.
1476        //
1477        // Peer of the sibling
1478        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
1479        // / [`crate::supervisor::tests::restart_strategy_is_variant_predicates_partition_the_arm_set`]
1480        // / [`crate::aplicacao::tests::placement_strategy_is_variant_predicates_partition_the_arm_set`]
1481        // / [`crate::upgrade::tests::upgrade_instruction_is_variant_predicates_partition_the_arm_set`]
1482        // pins on the sibling closed-set typed-enum discriminator axes.
1483        for (idx, &variant) in CaixaDialeto::ALL.iter().enumerate() {
1484            let observed = [
1485                variant.is_pacote(),
1486                variant.is_molde(),
1487                variant.is_molde_posicional(),
1488                variant.is_desconhecido(),
1489            ];
1490            let mut expected = [false; 4];
1491            expected[idx] = true;
1492            assert_eq!(
1493                observed, expected,
1494                "CaixaDialeto::{variant:?} at ALL[{idx}] is_* predicates \
1495                 must fire only on their own arm lane (identity diagonal); \
1496                 got {observed:?}",
1497            );
1498        }
1499    }
1500
1501    #[test]
1502    fn caixa_dialeto_is_variant_predicates_are_const_fn() {
1503        // The [`gen_platform::IsVariant`] derive emits `const fn`
1504        // predicates on the peer [`crate::CaixaKind`] +
1505        // [`crate::upgrade::UpgradeInstruction`] +
1506        // [`crate::supervisor::RestartStrategy`] +
1507        // [`crate::supervisor::RestartPolicy`] +
1508        // [`crate::aplicacao::PlacementStrategy`] +
1509        // [`crate::aplicacao::RateLimitUnit`] +
1510        // [`crate::dep::DepList`] closed-set typed enums — pin the same
1511        // posture on [`CaixaDialeto`] so a future accidental downgrade
1512        // to non-`const` (an added runtime helper reachable only from a
1513        // non-`const` context, a manual hand-rolled `impl` that shadows
1514        // the derive-generated method) trips at caixa-core build time
1515        // rather than surfacing as a downstream `const`-context
1516        // regression far from the derive declaration.
1517        // Use `const { assert!(…) }` (peer of the sibling
1518        // [`crate::render::PathShapeViolation`] +
1519        // [`crate::aplicacao::RateLimitUnit`] +
1520        // [`caixa_theme::style::Semantic`] const-fn pins) so the
1521        // const-context evaluation trips at const-fold time without
1522        // opening a per-`const bool` `assertions_on_constants` clippy
1523        // debt row this crate does not carry today for `dialeto.rs`.
1524        const { assert!(CaixaDialeto::Pacote.is_pacote()) };
1525        const { assert!(CaixaDialeto::Molde.is_molde()) };
1526        const { assert!(CaixaDialeto::MoldePosicional.is_molde_posicional()) };
1527        const { assert!(CaixaDialeto::Desconhecido.is_desconhecido()) };
1528    }
1529
1530    #[test]
1531    fn caixa_dialeto_from_wire_accepts_every_as_str_output() {
1532        // Fail-before-pass-after per-arm accept pin on the newly lifted
1533        // [`CaixaDialeto::from_wire`] reverse projection: every arm in
1534        // [`CaixaDialeto::ALL`] must parse back through `from_wire` when
1535        // fed its own [`CaixaDialeto::as_str`] output, landing on
1536        // `Some(same_variant)` — a regression that hand-rolled either
1537        // side's per-arm match without threading through the shared
1538        // four-string closed set would silently disagree on any future
1539        // arm rename and this pin flags it at caixa-core build time.
1540        // Peer of the sibling
1541        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
1542        // (2aa6d23) /
1543        // `placement_strategy_from_wire_accepts_every_lifted_constant`
1544        // (18c7342) /
1545        // `dep_list_round_trips_through_as_str_and_from_wire` (45ee563)
1546        // shape on the sibling closed-set typed-enum reverse-projection
1547        // axes.
1548        for &variant in CaixaDialeto::ALL {
1549            let wire = variant.as_str();
1550            let parsed = CaixaDialeto::from_wire(wire).unwrap_or_else(|| {
1551                panic!(
1552                    "CaixaDialeto::from_wire({wire:?}) must accept every \
1553                     CaixaDialeto::as_str output — got None for the \
1554                     wire byte-string of {variant:?}"
1555                )
1556            });
1557            assert_eq!(
1558                parsed, variant,
1559                "CaixaDialeto::from_wire(CaixaDialeto::{variant:?}.as_str()) \
1560                 must return CaixaDialeto::{variant:?} — the (as_str, \
1561                 from_wire) pair must form a total round-trip on the \
1562                 closed four-arm CaixaDialeto arm-set"
1563            );
1564        }
1565    }
1566
1567    #[test]
1568    fn caixa_dialeto_from_wire_rejects_unknown_byte_strings() {
1569        // Rejection pin on the parser's accept-set: any string outside
1570        // the four-arm [`CaixaDialeto::as_str`] output set must return
1571        // `None`. A future accidental widening of the accept-set (a
1572        // case-insensitive match that accepts `"pacote"` on the wire
1573        // axis, a hand-rolled Levenshtein-forgiving arm-lookup that
1574        // admits `"Pacotee"` typos, a silent acceptance of the sibling
1575        // [`Self::palavra_canonica`] `"defcaixa"` / `"defmolde"`
1576        // byte-shapes on this axis) would silently drift the parser's
1577        // accept-set from the emitter's — a downstream audit-report
1578        // re-loader that bound a prior audit's [`Self::as_str`] output
1579        // back to the typed enum through this parser would then bind a
1580        // malformed byte-string to a plausibly-wrong typed arm the
1581        // caller does not route through any fallback, silently
1582        // misclassifying the reloaded row. Also rejects the sibling
1583        // [`Self::palavra_canonica`] (`"defcaixa"` / `"defmolde"`) and
1584        // the sibling [`Self::consumidor`] (`"caixa-core / feira"`,
1585        // `"pleme-doc-gen"`, `"nobody known"`) byte-shapes, which are
1586        // the substrate's *distinct-axis* projections on the same enum
1587        // — the two-axis split the sibling
1588        // [`Self::palavra_canonica`] / [`Self::consumidor`] /
1589        // [`Self::descricao`] docstrings explicitly frame forbids
1590        // accepting one axis's byte-shapes as parseable on the other
1591        // axis. Peer of the sibling
1592        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
1593        // (2aa6d23) /
1594        // `placement_strategy_from_wire_rejects_unknown_byte_strings`
1595        // (18c7342) /
1596        // `dep_list_from_wire_returns_none_on_unknown_wire_scalar`
1597        // (45ee563) rejection pins on the sibling closed-set typed-enum
1598        // reverse-projection axes.
1599        for bad in [
1600            "",
1601            " ",
1602            "pacote",
1603            "PACOTE",
1604            "molde",
1605            "MoldePositional",
1606            "desconhecido",
1607            "Unknown",
1608            "defcaixa",
1609            "defmolde",
1610            "?",
1611            "caixa-core / feira",
1612            "pleme-doc-gen",
1613            "nobody known",
1614            "Pacote ",
1615            " Pacote",
1616        ] {
1617            assert!(
1618                CaixaDialeto::from_wire(bad).is_none(),
1619                "CaixaDialeto::from_wire({bad:?}) must return None — the \
1620                 parser's accept-set is exactly the four CaixaDialeto::as_str \
1621                 outputs; a widening would silently split the parser's \
1622                 accept-set from the emitter's arm-set"
1623            );
1624        }
1625    }
1626
1627    #[test]
1628    fn cabeca_errada_ctor_matches_struct_literal_wrap() {
1629        // Fail-before-pass-after byte-identity pin: the lifted
1630        // [`DialetoError::cabeca_errada`] ctor MUST land on the exact
1631        // same struct-literal shape the pre-lift open-coded wire-up
1632        // block wrote by hand — `DialetoError::CabecaErrada {
1633        // encontrado: <head>.to_string() }`. A future accidental
1634        // divergence (`.into()` swap, per-arm constant substitution, an
1635        // added default field, an `.to_ascii_lowercase()` normalization
1636        // silently injected into the ctor body, a rebrand of the
1637        // `encontrado` field carrying a distinct byte-shape) trips this
1638        // pin at caixa-core build time rather than surfacing far from
1639        // the ctor declaration as a downstream `classify_form`
1640        // wrong-head consumer emitting one diagnostic shape while a
1641        // hand-written test peer opens another. Peer of the sibling
1642        // `unknown_byte_unit_ctor_matches_struct_literal_wrap`
1643        // (limits.rs; 29fac09) / `duplicate_from_ctor_matches_struct_
1644        // literal_wrap` (upgrade.rs; 7e52aec) shape on the sibling
1645        // single-slot `{ <field>: String }` envelope constructors.
1646        assert_eq!(
1647            DialetoError::cabeca_errada("defflake"),
1648            DialetoError::CabecaErrada {
1649                encontrado: "defflake".to_string(),
1650            },
1651            "DialetoError::cabeca_errada must byte-equal the pre-lift \
1652             open-coded struct-literal — a drift here means the ctor \
1653             stopped being a substrate primitive for the wrong-head \
1654             fallthrough site"
1655        );
1656    }
1657
1658    #[test]
1659    fn cabeca_errada_routes_encontrado_verbatim_across_boundary_inputs() {
1660        // Fail-before-pass-after boundary-sweep pin: the lifted
1661        // [`DialetoError::cabeca_errada`] ctor MUST route its
1662        // `encontrado: &str` argument verbatim into the
1663        // [`DialetoError::CabecaErrada`] `encontrado: String` field
1664        // for every boundary-covering `&str` input — empty string, a
1665        // canonical `defcaixa`-adjacent head, a non-ASCII head, a
1666        // whitespace-carrying head, a Unicode-full-width head. Any
1667        // wrapper-side truncation, silent `.trim()`, accidental
1668        // `.to_ascii_lowercase()` normalization, or `.into()` divergence
1669        // on the ctor body surfaces here as a byte-mismatch against the
1670        // input rather than at a downstream
1671        // [`DialetoError::to_string()`] diagnostic-shape drift at a
1672        // wrong-head fallthrough consumer far from the ctor declaration.
1673        // Peer of the sibling `limits_codec_unit_only_ctors_route_unit_
1674        // verbatim_across_every_variant` (limits.rs; 29fac09) shape on
1675        // the sibling single-slot `{ <field>: String }` envelope
1676        // boundary-sweep discipline.
1677        for encontrado in [
1678            "",
1679            "defflake",
1680            "def-molde",
1681            "defcaixa ",
1682            " defcaixa",
1683            "μdefcaixa",
1684            "\u{00A0}defcaixa",
1685            "\u{3000}defcaixa",
1686            "def\u{2028}caixa",
1687        ] {
1688            let via_ctor = DialetoError::cabeca_errada(encontrado);
1689            let via_literal = DialetoError::CabecaErrada {
1690                encontrado: encontrado.to_string(),
1691            };
1692            assert_eq!(
1693                via_ctor, via_literal,
1694                "DialetoError::cabeca_errada({encontrado:?}) must byte- \
1695                 equal the open-coded struct-literal on the same input — \
1696                 a drift here would let the ctor silently normalize / \
1697                 truncate the head symbol before it reached the \
1698                 CabecaErrada envelope"
1699            );
1700            let DialetoError::CabecaErrada { encontrado: routed } = via_ctor else {
1701                panic!(
1702                    "DialetoError::cabeca_errada must construct the \
1703                     CabecaErrada arm — got a different variant on \
1704                     input {encontrado:?}"
1705                );
1706            };
1707            assert_eq!(
1708                routed, encontrado,
1709                "DialetoError::cabeca_errada must route the input \
1710                 {encontrado:?} verbatim into the encontrado field — \
1711                 any wrapper-side truncation / normalization surfaces \
1712                 here rather than at a downstream diagnostic shape drift"
1713            );
1714        }
1715    }
1716
1717    #[test]
1718    fn classify_form_wrong_head_routes_through_cabeca_errada_ctor() {
1719        // Fail-before-pass-after routing pin: [`classify`]'s wrong-head
1720        // fallthrough site MUST construct its `Err(DialetoError::…)`
1721        // through the substrate-primitive [`DialetoError::cabeca_errada`]
1722        // ctor rather than through an open-coded struct-literal. Pre-
1723        // lift the wire-up hand-rolled a three-line
1724        // `Self::CabecaErrada { encontrado: other.to_string() }` block
1725        // with no compile-time link back to the substrate primitive; a
1726        // future accidental rebrand of the ctor body (an added
1727        // `.trim()` on `encontrado`, a per-arm constant prefix like
1728        // `"unknown-head:"`, a widening of the field into a
1729        // `(String, usize)` tuple carrying a caret offset) would then
1730        // silently split the two paths — the ctor consumers pick up
1731        // the new shape, the open-coded wire-up does not. Pinning
1732        // byte-equality between the observed `Err` and the ctor-
1733        // constructed `Err` refuses that split at caixa-core build
1734        // time rather than surfacing far from the wire-up commit as a
1735        // downstream diagnostic-consumer split.
1736        for head in ["defflake", "deffoobar", "defcaixaz", "let", "defmoldez"] {
1737            let src = format!("({head} :nome \"x\")");
1738            let observed = classify(&src);
1739            let via_ctor = Err(DialetoError::cabeca_errada(head));
1740            assert_eq!(
1741                observed, via_ctor,
1742                "classify({src:?}) must return the same Err shape as \
1743                 DialetoError::cabeca_errada({head:?}) — a drift here \
1744                 means the wire-up de-lifted its wrong-head fallthrough \
1745                 arm off the substrate primitive"
1746            );
1747        }
1748    }
1749
1750    #[test]
1751    fn leitura_ctor_matches_tuple_literal_wrap_on_str_binding() {
1752        // Fail-before-pass-after byte-identity pin: the lifted
1753        // [`DialetoError::leitura`] ctor MUST land on the exact same
1754        // tuple-newtype wrap the pre-lift open-coded wire-up block wrote by
1755        // hand — `DialetoError::Leitura(<into-String-expr>)`. A future
1756        // accidental divergence (an added `.trim()` on the reader reason,
1757        // a per-arm constant prefix like `"tatara-lisp:"`, a widening of
1758        // the tuple carrying a caret offset, a rebrand of the payload
1759        // carrying a distinct byte-shape) trips this pin at caixa-core
1760        // build time rather than surfacing far from the ctor declaration
1761        // as a downstream [`classify`] tatara-lisp-reader consumer
1762        // emitting one diagnostic shape while a hand-written test peer
1763        // opens another. Peer of the sibling
1764        // `cabeca_errada_ctor_matches_struct_literal_wrap` pin above on
1765        // the same [`DialetoError`] envelope's wrong-head axis, and of
1766        // the peer `LimitsError::empty_byte_size` /
1767        // `LimitsError::empty_duration` (7a4b003 / 319216c) shape on the
1768        // sibling `(String)` single-slot tuple-newtype envelope
1769        // constructors.
1770        let reason: &str = "unclosed paren at 1:12";
1771        assert_eq!(
1772            DialetoError::leitura(reason),
1773            DialetoError::Leitura(reason.to_string()),
1774            "DialetoError::leitura must byte-equal the pre-lift open-coded \
1775             tuple-newtype wrap — a drift here means the ctor stopped \
1776             being a substrate primitive for the tatara-lisp-reader \
1777             fallthrough site"
1778        );
1779    }
1780
1781    #[test]
1782    fn leitura_ctor_matches_tuple_literal_wrap_on_string_binding() {
1783        // Fail-before-pass-after byte-identity pin on the `String` wire-up
1784        // shape: the lifted [`DialetoError::leitura`] ctor MUST land on
1785        // the same tuple-newtype wrap when the caller passes an owned
1786        // `String` (the actual [`classify`] wire-up shape — `e.to_string()`
1787        // on a [`tatara_lisp::Error`]-carrying binding). Pins that the
1788        // `impl Into<String>` param covers the owned-`String` path with no
1789        // silent double-allocation or intermediate `&str` reslicing. Peer
1790        // of the sibling `_on_str_binding` pin above — together they close
1791        // the `impl Into<String>` bound's two authored wire-up shapes on
1792        // the ctor's substrate primitive.
1793        let reason: String = String::from("read: unexpected EOF at 3:1");
1794        let via_ctor = DialetoError::leitura(reason.clone());
1795        let via_literal = DialetoError::Leitura(reason.clone());
1796        assert_eq!(
1797            via_ctor, via_literal,
1798            "DialetoError::leitura must byte-equal the pre-lift open-coded \
1799             tuple-newtype wrap on the same owned-String fixture — a drift \
1800             here would let the ctor silently reshape the reader reason \
1801             before it reached the Leitura envelope"
1802        );
1803        let DialetoError::Leitura(routed) = via_ctor else {
1804            panic!(
1805                "DialetoError::leitura must construct the Leitura arm — \
1806                 got a different variant on input {reason:?}"
1807            );
1808        };
1809        assert_eq!(
1810            routed, reason,
1811            "DialetoError::leitura must route the input {reason:?} \
1812             verbatim into the tuple-newtype payload — any wrapper-side \
1813             truncation / normalization surfaces here rather than at a \
1814             downstream diagnostic shape drift"
1815        );
1816    }
1817
1818    #[test]
1819    fn leitura_routes_reason_verbatim_across_boundary_inputs() {
1820        // Fail-before-pass-after boundary-sweep pin: the lifted
1821        // [`DialetoError::leitura`] ctor MUST route its
1822        // `reason: impl Into<String>` argument verbatim into the
1823        // [`DialetoError::Leitura`] tuple-newtype `String` payload for
1824        // every boundary-covering input — empty string, a canonical
1825        // tatara-lisp reader error, a non-ASCII reason, a
1826        // whitespace-carrying reason, a Unicode-full-width reason. Any
1827        // wrapper-side truncation, silent `.trim()`, accidental
1828        // `.to_ascii_lowercase()` normalization, or `.into()` divergence
1829        // on the ctor body surfaces here as a byte-mismatch against the
1830        // input rather than at a downstream [`DialetoError::to_string()`]
1831        // diagnostic-shape drift at a tatara-lisp-reader fallthrough
1832        // consumer far from the ctor declaration. Peer of the sibling
1833        // `cabeca_errada_routes_encontrado_verbatim_across_boundary_inputs`
1834        // pin above on the same [`DialetoError`] envelope's wrong-head
1835        // axis.
1836        for reason in [
1837            "",
1838            "unclosed paren at 1:12",
1839            "unexpected token ')'",
1840            "read: eof",
1841            " leading whitespace",
1842            "trailing whitespace ",
1843            "μnicode reason",
1844            "\u{00A0}NBSP-prefixed reason",
1845            "\u{3000}ideographic-space reason",
1846            "reason\u{2028}with-line-separator",
1847        ] {
1848            let via_ctor = DialetoError::leitura(reason);
1849            let via_literal = DialetoError::Leitura(reason.to_string());
1850            assert_eq!(
1851                via_ctor, via_literal,
1852                "DialetoError::leitura({reason:?}) must byte-equal the \
1853                 open-coded tuple-newtype wrap on the same input — a \
1854                 drift here would let the ctor silently normalize / \
1855                 truncate the reader reason before it reached the \
1856                 Leitura envelope"
1857            );
1858            let DialetoError::Leitura(routed) = via_ctor else {
1859                panic!(
1860                    "DialetoError::leitura must construct the Leitura \
1861                     arm — got a different variant on input {reason:?}"
1862                );
1863            };
1864            assert_eq!(
1865                routed, reason,
1866                "DialetoError::leitura must route the input {reason:?} \
1867                 verbatim into the tuple-newtype payload — any \
1868                 wrapper-side truncation / normalization surfaces here \
1869                 rather than at a downstream diagnostic shape drift"
1870            );
1871        }
1872    }
1873
1874    #[test]
1875    fn classify_reader_error_routes_through_leitura_ctor() {
1876        // Fail-before-pass-after routing pin: [`classify`]'s
1877        // tatara-lisp-reader map-err site MUST construct its
1878        // `Err(DialetoError::…)` through the substrate-primitive
1879        // [`DialetoError::leitura`] ctor rather than through an
1880        // open-coded tuple-newtype wrap. Pre-lift the wire-up hand-rolled
1881        // a `Self::Leitura(e.to_string())` block with no compile-time
1882        // link back to the substrate primitive; a future accidental
1883        // rebrand of the ctor body (an added `.trim()` on the reader
1884        // reason, a per-arm constant prefix like `"tatara-lisp:"`, a
1885        // widening of the payload into a `(String, usize)` tuple
1886        // carrying a caret offset) would then silently split the two
1887        // paths — the ctor consumers pick up the new shape, the
1888        // open-coded wire-up does not. Pinning byte-equality between
1889        // the observed `Err` and the ctor-constructed `Err` refuses
1890        // that split at caixa-core build time rather than surfacing far
1891        // from the wire-up commit as a downstream diagnostic-consumer
1892        // split. Peer of the sibling
1893        // `classify_form_wrong_head_routes_through_cabeca_errada_ctor`
1894        // pin above on the same [`DialetoError`] envelope's wrong-head
1895        // fallthrough axis.
1896        //
1897        // The malformed sources below each name a distinct
1898        // tatara-lisp-reader failure shape (unclosed paren, stray close
1899        // paren, unterminated string), so together they sweep the
1900        // reader's rejection surface rather than pinning against one
1901        // specific error message the reader upstream is free to reword.
1902        for src in [
1903            "(defcaixa :nome \"x\"",
1904            "defcaixa :nome \"x\")",
1905            "(defcaixa :nome \"unterminated",
1906        ] {
1907            let observed = classify(src);
1908            let Err(DialetoError::Leitura(reason)) = observed.clone() else {
1909                panic!(
1910                    "classify({src:?}) must return the Leitura arm — got \
1911                     {observed:?}"
1912                );
1913            };
1914            let via_ctor: Result<CaixaDialeto, DialetoError> =
1915                Err(DialetoError::leitura(reason.clone()));
1916            assert_eq!(
1917                observed, via_ctor,
1918                "classify({src:?}) must return the same Err shape as \
1919                 DialetoError::leitura({reason:?}) — a drift here means \
1920                 the wire-up de-lifted its tatara-lisp-reader fallthrough \
1921                 arm off the substrate primitive"
1922            );
1923        }
1924    }
1925
1926    #[test]
1927    fn caixa_dialeto_try_from_str_routes_through_from_wire_accessor() {
1928        // Fail-before-pass-after byte-parity pin on the lifted
1929        // `impl TryFrom<&str> for CaixaDialeto`: for every arm in
1930        // [`CaixaDialeto::ALL`], the `.try_into()` / `TryFrom::try_from`
1931        // path must resolve to the same variant the sibling
1932        // [`CaixaDialeto::from_wire`] resolver returns on the same
1933        // [`CaixaDialeto::as_str`] wire byte-string input. Pins the
1934        // three-path convergence discipline the [`CaixaDialeto`] closed-
1935        // set typed enum now carries on the `str → Self` reverse-
1936        // projection axis: `<CaixaDialeto as TryFrom<&str>>::try_from(s)`
1937        // (the newly lifted trait-idiomatic reverse projection),
1938        // `CaixaDialeto::from_wire(s)` (the substrate-primitive method-
1939        // named `Option<Self>` accessor the trait impl delegates through),
1940        // and the round-trip identity `variant.as_str() → variant`
1941        // (the four-arm closed accept-set shared between the emitter and
1942        // both reverse-projection consumers) must resolve to the same
1943        // typed [`CaixaDialeto`] discriminator on every arm.
1944        //
1945        // A future silent detour that routes the impl through a
1946        // divergent projection (a per-arm inline
1947        // `match s { "Pacote" => …, … }` re-inlining that opens a
1948        // compile-time link to the un-lifted arm-literal, a swap onto
1949        // the second-axis [`CaixaDialeto::palavra_canonica`] /
1950        // [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`]
1951        // accessors that carry distinct byte-shapes per axis, an accept-
1952        // set widening that silently accepts one axis's byte-shapes as
1953        // parseable on the other axis) trips at caixa-core test time
1954        // under `assert_eq!` rather than at a downstream
1955        // `TryFrom<&str>`-bound consumer's silent split. Peer of the
1956        // sibling
1957        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
1958        // (3c83606) on the top-level [`crate::CaixaKind`] closed-set
1959        // discriminator's reverse-projection axis — extends the trait-
1960        // idiomatic reverse-projection axis onto the seventh closed-set
1961        // fieldless typed enum on the caixa surface (the second one to
1962        // carry the paired `TryFrom<&str>` impl).
1963        for &variant in CaixaDialeto::ALL {
1964            let wire = variant.as_str();
1965            let via_try_from: CaixaDialeto = <CaixaDialeto as TryFrom<&str>>::try_from(wire)
1966                .unwrap_or_else(|()| {
1967                    panic!(
1968                        "CaixaDialeto::try_from({wire:?}) must accept every \
1969                         CaixaDialeto::as_str output — got Err(()) for the \
1970                         wire byte-string of {variant:?}"
1971                    )
1972                });
1973            let via_from_wire: CaixaDialeto = CaixaDialeto::from_wire(wire).unwrap_or_else(|| {
1974                panic!(
1975                    "CaixaDialeto::from_wire({wire:?}) must accept every \
1976                     CaixaDialeto::as_str output — got None for the wire \
1977                     byte-string of {variant:?}"
1978                )
1979            });
1980            assert_eq!(
1981                via_try_from, variant,
1982                "CaixaDialeto::try_from(CaixaDialeto::{variant:?}.as_str()) \
1983                 must return CaixaDialeto::{variant:?} — the trait-idiomatic \
1984                 reverse projection must land on the same arm the method-named \
1985                 from_wire resolver does",
1986            );
1987            assert_eq!(
1988                via_try_from, via_from_wire,
1989                "CaixaDialeto::try_from({wire:?}) ({via_try_from:?}) must \
1990                 byte-equal CaixaDialeto::from_wire({wire:?}) ({via_from_wire:?}) \
1991                 on the same input — divergence signals a silent detour off the \
1992                 shared substrate-primitive resolver",
1993            );
1994            assert_eq!(
1995                <CaixaDialeto as TryFrom<&str>>::try_from(wire).ok(),
1996                CaixaDialeto::from_wire(wire),
1997                "the Result::ok() projection of TryFrom<&str> must byte-equal \
1998                 the sibling from_wire Option<Self> output on {wire:?} — the \
1999                 two accessors must share the same accept-set and typed \
2000                 outcome per arm",
2001            );
2002        }
2003    }
2004
2005    #[test]
2006    fn caixa_dialeto_try_from_str_rejects_unknown_byte_strings() {
2007        // Rejection witness on the trait-idiomatic reverse-projection
2008        // axis: any string outside the four-arm [`CaixaDialeto::as_str`]
2009        // output set must resolve to `Err(())` through the lifted
2010        // [`impl TryFrom<&str> for CaixaDialeto`]. A future accidental
2011        // widening of the accept-set (a case-insensitive match that
2012        // accepts `"pacote"` on the wire axis, a hand-rolled Levenshtein-
2013        // forgiving arm-lookup that admits `"Pacotee"` typos, a silent
2014        // acceptance of the sibling [`CaixaDialeto::palavra_canonica`]
2015        // `"defcaixa"` / `"defmolde"` byte-shapes on this axis, a swap
2016        // onto the [`CaixaDialeto::consumidor`] `"pleme-doc-gen"` /
2017        // `"caixa-core / feira"` / `"nobody known"` byte-shapes) would
2018        // silently drift the trait-idiomatic parser's accept-set from
2019        // the sibling [`CaixaDialeto::from_wire`] resolver's — a
2020        // downstream `TryFrom<&str>`-bound consumer binding a malformed
2021        // byte-string through this impl would then bind a plausibly-
2022        // wrong typed arm the caller does not route through any fallback,
2023        // silently misclassifying the reloaded row.
2024        //
2025        // Sweeps the same rejection set the sibling
2026        // [`caixa_dialeto_from_wire_rejects_unknown_byte_strings`] pin
2027        // walks (the shared `from_wire` resolver both accessors delegate
2028        // through) so the trait-idiomatic axis and the method-named axis
2029        // stay locked to the same accept-set by construction. Peer of the
2030        // sibling
2031        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
2032        // (3c83606) on the top-level [`crate::CaixaKind`] closed-set
2033        // discriminator's trait-idiomatic reverse-projection axis.
2034        for bad in [
2035            "",
2036            " ",
2037            "pacote",
2038            "PACOTE",
2039            "molde",
2040            "MoldePositional",
2041            "desconhecido",
2042            "Unknown",
2043            "defcaixa",
2044            "defmolde",
2045            "?",
2046            "caixa-core / feira",
2047            "pleme-doc-gen",
2048            "nobody known",
2049            "Pacote ",
2050            " Pacote",
2051        ] {
2052            assert_eq!(
2053                <CaixaDialeto as TryFrom<&str>>::try_from(bad),
2054                Err(()),
2055                "CaixaDialeto::try_from({bad:?}) must return Err(()) — the \
2056                 trait-idiomatic parser's accept-set is exactly the four \
2057                 CaixaDialeto::as_str outputs; a widening would silently \
2058                 split the trait-idiomatic reverse-projection axis from the \
2059                 sibling from_wire resolver's arm-set"
2060            );
2061        }
2062    }
2063
2064    #[test]
2065    fn caixa_dialeto_from_into_static_str_routes_through_as_str_accessor() {
2066        // Fail-before-pass-after byte-parity pin on the newly lifted
2067        // `impl From<CaixaDialeto> for &'static str` — asserts the
2068        // standard-library trait impl and the substrate-primitive
2069        // [`CaixaDialeto::as_str`] `pub const fn` accessor resolve to
2070        // the same four-arm emit-set across every arm the exhaustive
2071        // [`CaixaDialeto::ALL`] slice enumerates. Any future silent
2072        // detour that routes the trait impl through a divergent
2073        // projection (a per-arm inline `match dialeto { Pacote =>
2074        // "Pacote", … }` re-inlining that opens a compile-time link to
2075        // the un-lifted arm-literal, an accidental swap onto the second-
2076        // axis [`CaixaDialeto::palavra_canonica`] /
2077        // [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`]
2078        // accessors that carry distinct byte-shapes per axis) trips at
2079        // caixa-core test time under `assert_eq!` rather than at a
2080        // downstream `impl Into<&'static str>`-bound consumer's silent
2081        // split. Sweeps every one of the four arms [`CaixaDialeto::ALL`]
2082        // carries so no arm's projection is covered only by the sibling
2083        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
2084        // paths. Materializes the `<&'static str as
2085        // From<CaixaDialeto>>::from` output in a `const`-shape binding
2086        // to make the `'static` lifetime promise a build-time invariant
2087        // — a future accidental downgrade of any of the four arms'
2088        // returned literals to a non-`&'static str` (a `String::leak()`-
2089        // produced return, a `Box::leak`-cast, an intermediate lifetime-
2090        // erasing helper) trips at caixa-core build time rather than at
2091        // a downstream `'static`-bound consumer. Peer of the sibling
2092        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
2093        // (523157d) /
2094        // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
2095        // (9fb37d0) /
2096        // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
2097        // (edb827b) pins on the sibling closed-set typed-enum forward-
2098        // projection axes — extends the trait-idiomatic forward-
2099        // projection axis onto the fourth closed-set fieldless typed
2100        // enum on the caixa surface (the dialect-classification axis,
2101        // second-of-two closed-set typed enums in caixa-core outside
2102        // the OTP-shape M2 slot).
2103        const PACOTE: &str = CaixaDialeto::Pacote.as_str();
2104        const MOLDE: &str = CaixaDialeto::Molde.as_str();
2105        const MOLDE_POSICIONAL: &str = CaixaDialeto::MoldePosicional.as_str();
2106        const DESCONHECIDO: &str = CaixaDialeto::Desconhecido.as_str();
2107        for &variant in CaixaDialeto::ALL {
2108            let via_trait: &'static str = <&'static str as From<CaixaDialeto>>::from(variant);
2109            let via_method: &'static str = variant.as_str();
2110            assert_eq!(
2111                via_trait, via_method,
2112                "From<CaixaDialeto> for &'static str impl must round-trip \
2113                 CaixaDialeto::{variant:?} to the same `PascalCase` byte-string \
2114                 CaixaDialeto::as_str returns — divergence signals a silent \
2115                 detour off the substrate-primitive accessor"
2116            );
2117            let via_into: &'static str = variant.into();
2118            assert_eq!(
2119                via_into, via_method,
2120                "Into<&'static str>::into on CaixaDialeto::{variant:?} must \
2121                 byte-equal CaixaDialeto::as_str on the same input — the \
2122                 blanket-derived Into shape must resolve to the same as_str \
2123                 dispatch as the explicit From impl"
2124            );
2125        }
2126        assert_eq!(
2127            [PACOTE, MOLDE, MOLDE_POSICIONAL, DESCONHECIDO],
2128            ["Pacote", "Molde", "MoldePosicional", "Desconhecido"],
2129            "const-context CaixaDialeto::as_str must resolve to the four \
2130             `PascalCase` variant-name byte-strings — a future accidental \
2131             downgrade of any arm to a non-const or non-static byte-string \
2132             breaks the `&'static str`-lifetime promise the paired \
2133             From<CaixaDialeto> for &'static str impl carries by \
2134             construction"
2135        );
2136    }
2137
2138    #[test]
2139    fn caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set() {
2140        // Cross-axis partition pin: the paired trait-idiomatic
2141        // `From<CaixaDialeto> for &'static str` forward projection and
2142        // the method-named [`CaixaDialeto::as_str`] forward projection
2143        // must resolve identically on *every* arm, not just the ones
2144        // named in the primary byte-parity pin above. Sweeps every
2145        // [`CaixaDialeto::ALL`] arm and asserts the trait's `From::from`
2146        // output byte-equals the method-named accessor's return-value on
2147        // each, locking the two forward-projection paths together by
2148        // construction so any future detour (a stray `From` special-case
2149        // that lands on a divergent per-arm literal outside the paired
2150        // `as_str` dispatch, a hypothetical rebrand touching one axis
2151        // without the other) trips at caixa-core test time. Peer of the
2152        // sibling forward-projection partition pins
2153        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
2154        // (523157d) /
2155        // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
2156        // (9fb37d0) /
2157        // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
2158        // (edb827b) — extends the round-trip discipline onto the fourth
2159        // closed-set typed enum on the caixa surface, closing the two-way
2160        // `Self ↔ &'static str` round-trip on the trait-idiomatic pair
2161        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
2162        // well as the pre-existing method-named pair (`as_str` +
2163        // `from_wire`).
2164        for &variant in CaixaDialeto::ALL {
2165            let via_trait: &'static str = <&'static str as From<CaixaDialeto>>::from(variant);
2166            let via_method: &'static str = variant.as_str();
2167            assert_eq!(
2168                via_trait, via_method,
2169                "From<CaixaDialeto> for &'static str and \
2170                 CaixaDialeto::as_str must resolve identically on \
2171                 CaixaDialeto::{variant:?} — divergence signals the \
2172                 two forward-projection paths have drifted onto different \
2173                 emit-sets"
2174            );
2175        }
2176        // Round-trip witness: every arm's forward `From` output re-parses
2177        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
2178        // to the original variant. Closes the two-way `CaixaDialeto ↔
2179        // &'static str` round-trip on the trait-idiomatic axis pair
2180        // directly (no wire-vocab intermediate the peer [`CaixaKind`]
2181        // axis pair requires — the emit-side [`CaixaDialeto::as_str`]
2182        // and the parse-side [`CaixaDialeto::from_wire`] share the same
2183        // `PascalCase` byte-string vocabulary by construction), mirroring
2184        // the pre-existing method-named `as_str` + `from_wire` round-trip
2185        // on the substrate-primitive axis pair.
2186        for &variant in CaixaDialeto::ALL {
2187            let emitted: &'static str = variant.into();
2188            let re_parsed: Result<CaixaDialeto, ()> =
2189                <CaixaDialeto as TryFrom<&str>>::try_from(emitted);
2190            assert_eq!(
2191                re_parsed,
2192                Ok(variant),
2193                "trait-idiomatic axis pair must round-trip \
2194                 CaixaDialeto::{variant:?} through `.into::<&'static \
2195                 str>()` and back through `TryFrom<&str>` — a break signals \
2196                 the forward-emit and reverse-parse axes have drifted onto \
2197                 different vocabularies"
2198            );
2199        }
2200    }
2201
2202    #[test]
2203    fn caixa_dialeto_is_molde_family_routes_through_is_variant_derived_predicates() {
2204        // Byte-parity pin on the post-lift [`CaixaDialeto::is_molde_family`]
2205        // convergence: for every arm in [`CaixaDialeto::ALL`], the typed
2206        // predicate must byte-equal the direct
2207        // `self.is_molde() || self.is_molde_posicional()` composition of
2208        // the two derived per-arm predicates. Pre-lift the predicate
2209        // hand-rolled `matches!(self, Self::Molde | Self::MoldePosicional)`
2210        // with no compile-time link back to the closed-set typed dispatch;
2211        // post-lift it routes through the derived predicates so a future
2212        // arm rename or `#[is_variant(name = "…")]` override lands at
2213        // exactly one dispatch on the substrate primitive. Pinning the
2214        // byte-equality here refuses a future accidental split between
2215        // the composed predicate and the paired derived predicates
2216        // (a hand-rolled shadow `impl` that overrides one path but not
2217        // the other, an accidental rebrand of `is_molde_family`'s body
2218        // back to the pre-lift `matches!` form) at caixa-core build time.
2219        for &d in CaixaDialeto::ALL {
2220            let via_derived = d.is_molde() || d.is_molde_posicional();
2221            let via_is_molde_family = d.is_molde_family();
2222            assert_eq!(
2223                via_is_molde_family, via_derived,
2224                "CaixaDialeto::{d:?}.is_molde_family() ({via_is_molde_family}) \
2225                 must byte-equal the composed derived predicates \
2226                 is_molde() || is_molde_posicional() ({via_derived}) — a \
2227                 split between the composed predicate and its derived \
2228                 building blocks would let a future arm rename land at one \
2229                 path and drift at the other, which is exactly the drift \
2230                 the IsVariant lift refuses"
2231            );
2232        }
2233    }
2234
2235    #[test]
2236    fn caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor() {
2237        // Fail-before-pass-after byte-parity pin on the newly lifted
2238        // `impl From<&CaixaDialeto> for &'static str` — asserts the
2239        // borrowed-input standard-library trait impl and the substrate-
2240        // primitive [`CaixaDialeto::as_str`] `pub const fn` accessor
2241        // resolve to the same four-arm emit-set across every arm the
2242        // exhaustive [`CaixaDialeto::ALL`] slice enumerates. Rust's
2243        // `From` trait does not auto-derive the borrowed-input sibling
2244        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
2245        // where T: Copy, U: From<T>` blanket in `core`), so the
2246        // borrowed-input axis is a distinct trait-idiomatic surface that
2247        // a `.iter().map(Into::into)` shape over [`CaixaDialeto::ALL`]
2248        // (whose iterator yields `&CaixaDialeto`, not `CaixaDialeto`)
2249        // reaches through this impl and no other — the paired owned-
2250        // input [`From<CaixaDialeto>`] impl requires an explicit
2251        // `.copied()` / dereference before the trait fires.
2252        // Materializes the `<&'static str as From<&CaixaDialeto>>::from`
2253        // output in a `const`-shape binding to make the `'static`
2254        // lifetime promise a build-time invariant — a future accidental
2255        // downgrade of any of the four arms' returned literals to a
2256        // non-`&'static str` trips at caixa-core build time rather than
2257        // at a downstream `'static`-bound consumer. Peer of the sibling
2258        // [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2259        // (64aa742) /
2260        // [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2261        // (5ab993a) pins on the sibling closed-set typed-enum borrowed-
2262        // input forward-projection axes — extends the borrowed-input
2263        // axis discipline onto the third peer on the substrate-wide
2264        // campaign, the dialect-classification axis.
2265        const PACOTE: &str = CaixaDialeto::Pacote.as_str();
2266        const MOLDE: &str = CaixaDialeto::Molde.as_str();
2267        const MOLDE_POSICIONAL: &str = CaixaDialeto::MoldePosicional.as_str();
2268        const DESCONHECIDO: &str = CaixaDialeto::Desconhecido.as_str();
2269        for variant in CaixaDialeto::ALL {
2270            let via_trait: &'static str = <&'static str as From<&CaixaDialeto>>::from(variant);
2271            let via_method: &'static str = variant.as_str();
2272            assert_eq!(
2273                via_trait, via_method,
2274                "From<&CaixaDialeto> for &'static str impl must round-trip \
2275                 &CaixaDialeto::{variant:?} to the same `PascalCase` byte-\
2276                 string CaixaDialeto::as_str returns — divergence signals a \
2277                 silent detour off the substrate-primitive accessor"
2278            );
2279            let via_into: &'static str = variant.into();
2280            assert_eq!(
2281                via_into, via_method,
2282                "Into<&'static str>::into on &CaixaDialeto::{variant:?} must \
2283                 byte-equal CaixaDialeto::as_str on the same input — the \
2284                 blanket-derived Into shape must resolve to the same as_str \
2285                 dispatch as the explicit From impl"
2286            );
2287        }
2288        assert_eq!(
2289            [PACOTE, MOLDE, MOLDE_POSICIONAL, DESCONHECIDO],
2290            ["Pacote", "Molde", "MoldePosicional", "Desconhecido"],
2291            "const-context CaixaDialeto::as_str must resolve to the four \
2292             `PascalCase` variant-name byte-strings — the borrowed-input \
2293             From<&CaixaDialeto> for &'static str impl inherits its \
2294             `'static` lifetime promise from the same accessor the owned-\
2295             input sibling routes through"
2296        );
2297    }
2298
2299    #[test]
2300    fn caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
2301        // Cross-axis partition pin: the paired trait-idiomatic
2302        // owned-input `From<CaixaDialeto> for &'static str` and
2303        // borrowed-input `From<&CaixaDialeto> for &'static str` (this
2304        // lift) forward projections must resolve identically on every
2305        // arm, locking the two input-shape paths together so any future
2306        // detour trips at caixa-core test time. Then a witness that a
2307        // `.iter().map(Into::into)` pipe over [`CaixaDialeto::ALL`]
2308        // (whose iterator yields `&CaixaDialeto`) materializes the four-
2309        // arm accept-set through the borrowed-input axis alone — the
2310        // exact shape a future M4 admission-webhook rejection body
2311        // composer, a future substrate-wide per-arm diagnostic column,
2312        // or a `HashMap::<&'static str, CaixaDialeto>::from_iter(
2313        //     CaixaDialeto::ALL.iter().map(|d| (d.into(), *d)))`-style
2314        // per-dialect lookup reaches through — closing the two-way
2315        // owned/borrowed input-shape symmetry on the forward-projection
2316        // trait-idiomatic axis. Peer of the sibling
2317        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2318        // (64aa742) /
2319        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2320        // (5ab993a) partition pins — extends the borrowed-input axis
2321        // discipline onto the third peer on the substrate-wide campaign.
2322        for &variant in CaixaDialeto::ALL {
2323            let owned: &'static str = <&'static str as From<CaixaDialeto>>::from(variant);
2324            let borrowed: &'static str = <&'static str as From<&CaixaDialeto>>::from(&variant);
2325            assert_eq!(
2326                owned, borrowed,
2327                "From<CaixaDialeto> and From<&CaixaDialeto> for &'static str \
2328                 must resolve identically on CaixaDialeto::{variant:?} — \
2329                 divergence signals the owned-input and borrowed-input \
2330                 forward-projection paths have drifted onto different \
2331                 emit-sets"
2332            );
2333        }
2334        let via_iter: Vec<&'static str> = CaixaDialeto::ALL.iter().map(Into::into).collect();
2335        let via_method: Vec<&'static str> = CaixaDialeto::ALL.iter().map(|d| d.as_str()).collect();
2336        assert_eq!(
2337            via_iter, via_method,
2338            "`.iter().map(Into::into)` over CaixaDialeto::ALL must byte-\
2339             equal `.iter().map(|d| d.as_str())` on every arm — the \
2340             borrowed-input `From<&CaixaDialeto> for &'static str` axis \
2341             is what makes the `.iter().map(Into::into)` shape route \
2342             through the substrate-primitive `CaixaDialeto::as_str` \
2343             accessor rather than through a per-call-site `.copied()` / \
2344             dereference detour"
2345        );
2346        // Direct round-trip witness on the borrowed-input axis: every
2347        // arm's borrowed `From` output re-parses through the paired
2348        // trait-idiomatic reverse `TryFrom<&str>` back to the original
2349        // variant. Unlike the peer [`crate::CaixaKind`] axis pair
2350        // (whose forward `From<Self> for &'static str` emits the
2351        // lowercase Portuguese `as_str` diagnostic vocabulary while
2352        // the reverse `TryFrom<&str>` parses the `PascalCase`
2353        // `wire_name` author-surface vocabulary, forcing the round-trip
2354        // through an intermediate wire-vocab hop), [`CaixaDialeto`]'s
2355        // [`CaixaDialeto::as_str`] emit and [`CaixaDialeto::from_wire`]
2356        // parse share the same `PascalCase` vocabulary by construction,
2357        // so the borrowed-input forward axis and the reverse axis
2358        // compose directly.
2359        for &variant in CaixaDialeto::ALL {
2360            let borrowed: &'static str = <&'static str as From<&CaixaDialeto>>::from(&variant);
2361            let re_parsed: Result<CaixaDialeto, ()> =
2362                <CaixaDialeto as TryFrom<&str>>::try_from(borrowed);
2363            assert_eq!(
2364                re_parsed,
2365                Ok(variant),
2366                "trait-idiomatic borrowed-input round-trip must project \
2367                 &CaixaDialeto::{variant:?} through \
2368                 `<&'static str>::from(&variant)` and back through \
2369                 `TryFrom<&str>` — a break signals the borrowed-input \
2370                 forward-emit axis and the reverse-parse axis have \
2371                 drifted onto different vocabularies"
2372            );
2373        }
2374    }
2375}