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    /// The keyword an author should write for this dialect, once the
176    /// migration named in [`Self::consumidor`] completes.
177    #[must_use]
178    pub const fn palavra_canonica(self) -> &'static str {
179        match self {
180            Self::Pacote => "defcaixa",
181            Self::Molde | Self::MoldePosicional => "defmolde",
182            Self::Desconhecido => "?",
183        }
184    }
185
186    /// Who reads this dialect.
187    #[must_use]
188    pub const fn consumidor(self) -> &'static str {
189        match self {
190            Self::Pacote => "caixa-core / feira",
191            Self::Molde | Self::MoldePosicional => "pleme-doc-gen",
192            Self::Desconhecido => "nobody known",
193        }
194    }
195
196    /// A one-line description for a census row or an error message.
197    #[must_use]
198    pub const fn descricao(self) -> &'static str {
199        match self {
200            Self::Pacote => "tatara-lisp package manifest (:nome :versao :kind :deps …)",
201            Self::Molde => "repo-surface declaration (:name :ecosystem :package {…} …)",
202            Self::MoldePosicional => {
203                "repo-surface declaration, positional name (defcaixa <nome> :kind …)"
204            }
205            Self::Desconhecido => "unrecognised — matches no known defcaixa schema",
206        }
207    }
208
209    /// True when this arm belongs to the `defmolde` declaration family —
210    /// the two-arity closure of [`Self::Molde`] and [`Self::MoldePosicional`]
211    /// under the shared `defmolde` head keyword the sibling
212    /// [`Self::palavra_canonica`] projection already collapses onto
213    /// `"defmolde"` for both arms (and the sibling [`Self::consumidor`]
214    /// projection collapses onto `"pleme-doc-gen"` for the same two arms).
215    /// False on [`Self::Pacote`] (the sibling `defcaixa` tatara-lisp
216    /// package manifest, [`Self::palavra_canonica`] `→ "defcaixa"`) and
217    /// on [`Self::Desconhecido`] (the residue that names no known
218    /// declaration, [`Self::palavra_canonica`] `→ "?"`).
219    ///
220    /// The [`Self::Molde`] / [`Self::MoldePosicional`] split is one
221    /// declaration written two ways ([`Self::MoldePosicional`]'s
222    /// variant-declaration docstring at [`Self::MoldePosicional`] frames
223    /// it exactly: "the same declaration as [`Self::Molde`], written with
224    /// the package name as a bare positional symbol … this is one arity
225    /// of one declaration, not a third schema"). Every downstream gate
226    /// that keys off "does this dialect belong to the `defmolde` family"
227    /// (as distinct from the four-arm-per-arm census-counter axis the
228    /// sibling `feira dialeto` verb already fans on separately at
229    /// `caixa-feira/src/cmd/dialeto.rs:110-127`) previously hand-rolled
230    /// the two-arm collapse inline as `matches!(d, CaixaDialeto::Molde |
231    /// CaixaDialeto::MoldePosicional)` — a compile-time-anonymous
232    /// two-arm literal set with no link back to the [`CaixaDialeto`]
233    /// variant declaration nor to the sibling
234    /// [`Self::palavra_canonica`] / [`Self::consumidor`] projections
235    /// that already carry the same two-arm collapse under the shared
236    /// `defmolde` / `pleme-doc-gen` axis. The `feira dialeto` verb's
237    /// [`caixa-feira/src/cmd/dialeto.rs`] carried the same
238    /// `matches!` twice — once in the `--strict-palavra` gate that
239    /// refuses a repo-surface declaration still written as
240    /// `(defcaixa …)`, once in the wrong-declaration-under-`caixa.lisp`
241    /// gate that refuses a repo-surface declaration under the filename
242    /// `feira` loads as a package manifest — with no compile-time link
243    /// between the two hand-rolled arm sets. A future arm addition (the
244    /// module doc's "third dialect" hazard actualises as a fifth arm
245    /// [`CaixaDialeto`] that belongs to the `defmolde` declaration
246    /// family — a third arity variant, an alias-declaration family
247    /// pleme-doc-gen sharpens as its schema evolves) would silently
248    /// split the two hand-rolled `matches!` arm-sets from each other
249    /// and from the paired [`Self::palavra_canonica`] projection: one
250    /// call site picks up the new arm, one does not, and the disagreement
251    /// surfaces far from the arm-addition commit as a `feira dialeto`
252    /// consumer reporting a repo-surface declaration under one gate but
253    /// not the other. Routing every "belongs to the `defmolde` family"
254    /// predicate through this one substrate primitive closes the axis:
255    /// a future arm addition lands one match arm here (a compile-time
256    /// exhaustiveness error otherwise), not a coordinated per-`matches!`
257    /// rewrite across every caller.
258    ///
259    /// Peer of the sibling [`crate::CaixaKind::requires_lib`] (0421c22)
260    /// per-arm-set predicate on the [`crate::CaixaKind`] closed-set
261    /// discriminator's "kind requires a `lib/` surface" axis — extends
262    /// the same "one canonical typed predicate per per-arm-set gate,
263    /// one dispatch on the substrate primitive" discipline onto the
264    /// [`CaixaDialeto`] closed-set discriminator's "belongs to the
265    /// `defmolde` declaration family" axis. The dialect-classification
266    /// axis's second per-arm-set predicate (first being the implicit
267    /// palavra_canonica-through-consumidor-through-descricao arm-set
268    /// collapse already carried on the sibling projections) — the first
269    /// explicitly-typed per-arm-set predicate on the axis, matching the
270    /// discipline the sibling M2 [`crate::CaixaKind`] closed-set
271    /// discriminator already carries with `requires_lib`.
272    ///
273    /// Three consumers now route through this one typed dispatch: the
274    /// [`caixa-feira`](../../caixa_feira/cmd/dialeto/index.html) verb's
275    /// `--strict-palavra` gate (refusing a repo-surface declaration
276    /// still written as `(defcaixa …)`), the same verb's wrong-
277    /// declaration-under-`caixa.lisp` gate (refusing a repo-surface
278    /// declaration under the filename `feira` loads as a package
279    /// manifest), and [`crate::Caixa::from_lisp`]'s foreign-dialect
280    /// gate (raising [`crate::ManifestError::DialetoEstrangeiro`] before
281    /// the derive's `parse_kwargs_strict` walk on any `defmolde`-family
282    /// classification — the pre-lift hand-rolled three-arm
283    /// `match { Pacote => {}, Desconhecido => {}, foreign => Err(…) }`
284    /// literal whose `foreign =>` wildcard silently absorbed anything
285    /// non-Pacote-non-Desconhecido, now the third external consumer of
286    /// the `defmolde`-family partition).
287    #[must_use]
288    pub const fn is_molde_family(self) -> bool {
289        // Routed through the derive-generated per-arm predicates
290        // [`Self::is_molde`] + [`Self::is_molde_posicional`] so the
291        // two-arm collapse links compile-time back to the closed-set
292        // typed dispatch every peer arm-set predicate on the caixa
293        // surface (e.g. [`crate::CaixaKind::requires_lib`] on the
294        // sibling `:kind` axis) now carries. Byte-equivalent to the
295        // pre-lift `matches!(self, Self::Molde | Self::MoldePosicional)`
296        // form (the derived `is_*` predicates each expand to the same
297        // `matches!(self, Self::X)` shape by construction), but a
298        // future arm rename or IsVariant `#[is_variant(name = "…")]`
299        // override lands at exactly one dispatch on the substrate
300        // primitive rather than a hand-rolled two-arm literal.
301        self.is_molde() || self.is_molde_posicional()
302    }
303}
304
305/// [`std::fmt::Display`] routed through [`CaixaDialeto::as_str`], so the
306/// pretty-printed byte-string every consumer that formats the dialect as
307/// user-facing / census text lands on (the `feira dialeto` per-manifest
308/// `--list` row, the `feira dialeto` census summary line's per-arm
309/// counters, a future M4 admission-webhook's rejection body naming the
310/// accepted-dialect set) reaches for the same `PascalCase` per-arm
311/// byte-string the [`CaixaDialeto::as_str`] helper returns.
312///
313/// Prior to this lift the [`std::fmt::Display`] impl hand-rolled its own
314/// four-arm literal-string match — the one hand-rolled per-arm dispatch
315/// on the closed [`CaixaDialeto`] discriminator that had NO substrate
316/// primitive accessor to defer to (the sibling [`CaixaDialeto::palavra_canonica`] /
317/// [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`] projections
318/// carry distinct byte-shapes per axis, so none of them could serve as
319/// the Display source). A future variant addition (a fifth dialect the
320/// module doc's "third dialect" hazard actualises) would land one arm at
321/// the enum and per-arm returns at the paired accessors, but a hand-rolled
322/// [`std::fmt::Display`] match would silently drop the new arm to compile-
323/// fail-at-the-match-arm-site rather than through the shared substrate
324/// primitive. Routing [`std::fmt::Display`] through [`CaixaDialeto::as_str`]
325/// closes the last unlifted per-arm `PascalCase`-name projection on the
326/// caixa surface — the seventh (and last unlifted) closed-set fieldless
327/// typed enum on the caixa surface to converge onto the same
328/// `Display`-through-`as_str` discipline the six siblings
329/// ([`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`] /
330/// [`crate::supervisor::RestartPolicy`] /
331/// [`crate::aplicacao::PlacementStrategy`] / [`crate::aplicacao::RateLimitUnit`]
332/// / [`crate::dep::DepList`]) already carry.
333impl std::fmt::Display for CaixaDialeto {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        f.write_str(self.as_str())
336    }
337}
338
339/// Substrate-canonical [`AsRef<str>`] projection on the [`CaixaDialeto`]
340/// closed-set fieldless typed dialect-classification enum — routes through
341/// the same [`CaixaDialeto::as_str`] `pub const fn` scalar accessor the
342/// paired [`std::fmt::Display`] impl already delegates through, so any
343/// future consumer that binds a [`CaixaDialeto`] through the standard-
344/// library `impl AsRef<str>` bound (a [`std::process::Command::arg`]
345/// shell-out that composes the canonical `PascalCase` variant-name into a
346/// `feira dialeto --strict-palavra <Pacote|Molde|MoldePosicional|Desconhecido>`
347/// diagnostic overlay, a `tracing::field::Value::Str`-arm structured-log
348/// recorder on the [`crate::Caixa::from_lisp`] foreign-dialect
349/// [`crate::ManifestError::DialetoEstrangeiro`] refusal path, a
350/// [`std::collections::HashMap`] lookup keyed on the canonical name
351/// through `map.get::<str>(dialeto.as_ref())` on a future M4 admission-
352/// webhook's per-dialect rejection-body composition table) reaches the
353/// paired `"Pacote"` / `"Molde"` / `"MoldePosicional"` / `"Desconhecido"`
354/// byte-string through one substrate-primitive dispatch rather than an
355/// open-coded `.as_str()` re-inlining at every wire-up.
356///
357/// Same "route the trait impl through the substrate-primitive accessor"
358/// discipline the sibling [`crate::CaixaVersion`] [`AsRef<str>`] impl
359/// (16d5c7e), the paired M2 [`crate::supervisor::RestartStrategy`]
360/// [`AsRef<str>`] impl (63eb1a4), the paired M2
361/// [`crate::supervisor::RestartPolicy`] [`AsRef<str>`] impl (419ea81),
362/// the M3 [`crate::aplicacao::PlacementStrategy`] [`AsRef<str>`] impl
363/// (d86edd2), the M3 [`crate::aplicacao::RateLimitUnit`] [`AsRef<str>`]
364/// impl (d8136db), and the top-level [`crate::CaixaKind`] [`AsRef<str>`]
365/// impl (cd2091f) carry — extends the substrate primitive's
366/// [`AsRef<str>`] projection axis onto the seventh closed-set typed enum
367/// on the caixa surface: the dialect-classification axis previously
368/// carried [`fmt::Display`]-through-`as_str` but not yet the paired
369/// [`AsRef<str>`] impl, so a downstream consumer that bound the enum
370/// through the standard-library `AsRef<str>` trait had to reach the
371/// canonical byte-string through an open-coded `.as_str()` call rather
372/// than the trait-idiomatic `.as_ref()` the peer closed-set typed enums
373/// already admit.
374///
375/// Pinned load-bearing by
376/// [`tests::caixa_dialeto_as_ref_str_routes_through_as_str_accessor`]
377/// (byte-parity pin against [`CaixaDialeto::as_str`] across the four-arm
378/// closed set) and
379/// [`tests::caixa_dialeto_as_ref_str_routes_through_display_via_shared_accessor`]
380/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
381/// resolve to the same byte-string per arm) — any future silent detour
382/// that routes the impl through a divergent projection (a per-arm inline
383/// `match self { CaixaDialeto::Pacote => "Pacote", … }` re-inlining that
384/// opens a compile-time link to the un-lifted arm-literal, a swap onto
385/// the second-axis [`CaixaDialeto::palavra_canonica`] /
386/// [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`] accessors
387/// that carry distinct byte-shapes per axis) trips at caixa-core test
388/// time under `assert_eq!` rather than at a downstream
389/// `impl AsRef<str>`-bound consumer's silent split.
390impl AsRef<str> for CaixaDialeto {
391    fn as_ref(&self) -> &str {
392        self.as_str()
393    }
394}
395
396/// A source that is not a `(defcaixa …)` / `(defmolde …)` form at all.
397#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
398pub enum DialetoError {
399    #[error("source has no top-level form")]
400    Vazio,
401    #[error("top-level form is not a list — a manifest is `(defcaixa …)`")]
402    NaoEhLista,
403    #[error(
404        "top-level form is headed by `{encontrado}`, not `defcaixa` or `defmolde` \
405         (a manifest's first form must be the declaration itself)"
406    )]
407    CabecaErrada { encontrado: String },
408    #[error("manifest does not parse as tatara-lisp: {0}")]
409    Leitura(String),
410}
411
412impl DialetoError {
413    /// Construct a [`DialetoError::CabecaErrada`] naming the offending
414    /// head symbol found at the top-level form.
415    ///
416    /// Substrate primitive every [`classify_form`] wrong-head fallthrough
417    /// wire-up site now routes through, folding the pre-lift uniform
418    /// three-line `Self::CabecaErrada { encontrado: <head>.to_string() }`
419    /// one-field struct-literal onto one substrate primitive matching the
420    /// peer `LimitsError::unknown_byte_unit(unit: &str)` /
421    /// `LimitsError::unknown_duration_unit(unit: &str)`
422    /// (`limits_codec_unit_only_ctors!` — 29fac09) single-slot
423    /// discipline on the sibling one-field `{ <field>: String }` envelope
424    /// axis, and matching the peer `ManifestError::code_path_empty` /
425    /// `BehaviorError::empty_path` / `UpgradeError::duplicate_from` /
426    /// `AplicacaoError::placement_cluster_duplicate` (94dabc8 / 0e33b37 /
427    /// 7e52aec / 92b1c92) single-slot inherent-ctor discipline every
428    /// sibling `{ <field>: <T> }` error-envelope variant on caixa-core's
429    /// error surface now carries.
430    ///
431    /// The one open-coded wire-up site — `classify_form`'s wrong-head
432    /// fallthrough arm on the `head: &str` binding read from the
433    /// top-level form via [`tatara_lisp::Sexp::as_symbol`] — opened the
434    /// identical three-line
435    /// `Self::CabecaErrada { encontrado: <head>.to_string() }` block
436    /// against the codec-scoped `<head>: &str` binding. Now routes
437    /// through `DialetoError::cabeca_errada(head)`, byte-equal to the
438    /// pre-lift struct-literal on the same `&str` fixture, so any future
439    /// widening of the diagnostic shape (e.g. carrying the source-file
440    /// path alongside the head symbol, carrying the head symbol's
441    /// position offset for an authoring-surface caret pointer) lands at
442    /// exactly one dispatch on the substrate primitive rather than re-
443    /// inlining the struct-literal at every wrong-head fallthrough
444    /// consumer.
445    #[must_use]
446    pub fn cabeca_errada(encontrado: &str) -> Self {
447        Self::CabecaErrada {
448            encontrado: encontrado.to_string(),
449        }
450    }
451
452    /// Construct a [`DialetoError::Leitura`] carrying the offending
453    /// tatara-lisp reader-error message `reason` verbatim in the
454    /// variant's tuple-newtype payload.
455    ///
456    /// Substrate primitive every [`classify`] tatara-lisp-reader
457    /// map-err wire-up site now routes through, folding the pre-lift
458    /// uniform `Self::Leitura(<into-String-expr>)` tuple-newtype
459    /// construction onto one substrate primitive matching the peer
460    /// `LimitsError::empty_byte_size` / `LimitsError::empty_duration`
461    /// (7a4b003 / 319216c) `(String)` single-slot tuple-newtype
462    /// discipline on the sibling
463    /// [`crate::limits::LimitsError`] envelope's empty-shape axis of
464    /// the paired codec-magnitude family. Peer to the sibling
465    /// [`DialetoError::cabeca_errada`] ctor on the same envelope's
466    /// wrong-head axis but on the tatara-lisp-reader axis rather than
467    /// the classifier-fallthrough axis. Closes the last un-lifted
468    /// variant on [`DialetoError`] — every one of the sole wire-up
469    /// sites (the [`classify`] tatara-lisp-reader `.map_err(|e|
470    /// Self::Leitura(e.to_string()))` arm) opened the identical
471    /// `DialetoError::Leitura(<into-String-expr>)` block against the
472    /// codec-scoped `String` (`e.to_string()`) binding, so the fold
473    /// routes the site through one dispatch on a uniform
474    /// `impl Into<String>` param, byte-equal to the pre-lift
475    /// tuple-newtype construction on the same argument.
476    ///
477    /// The `impl Into<String>` bound covers both wire-up shapes on
478    /// [`classify`] — a `String` binding (`e.to_string()` on the
479    /// [`tatara_lisp::Error`]-carrying `e` binding) and a `&str`
480    /// binding (a future admission-webhook consumer probing a
481    /// caller-scoped `&'static str` fixture, a future
482    /// `feira lint --tatara-reader-round-trip` verb sweeping every
483    /// `tatara_lisp::read` return through the same shape gate) —
484    /// without forcing the caller to spell the conversion at the
485    /// wire-up site. Same shape the peer
486    /// [`crate::limits::LimitsError::empty_byte_size`] /
487    /// [`crate::limits::LimitsError::empty_duration`] /
488    /// [`crate::limits::LimitsError::bad_millicores`] /
489    /// [`crate::limits::LimitsError::bad_byte_magnitude`] /
490    /// [`crate::limits::LimitsError::bad_duration_magnitude`] folds
491    /// carry on the peer bad-magnitude and empty-shape axes of the
492    /// same paired `(String)` tuple-newtype codec-magnitude family.
493    /// `#[must_use]` fires a compile warning at any wire-up that
494    /// mistakenly discards the constructed error.
495    ///
496    /// Every future consumer that wants to construct this variant
497    /// outside [`classify`] (a deferred `feira lint --tatara-reader-
498    /// round-trip` per-caixa admission verb probing each authored
499    /// manifest against the tatara-lisp-reader shape gate, an M4
500    /// typed `mesh.pleme.io/v1alpha1/Servico` CR materializer's
501    /// per-manifest admission validator re-checking one edited
502    /// `caixa.lisp` against the reader floor, a per-`caixa.lisp`
503    /// value-shape pre-emitter probing each declared manifest ahead
504    /// of the operator's admit-cycle) now reaches the variant
505    /// through one call rather than re-inlining the tuple-newtype
506    /// block in lockstep with the pre-existing wire-up.
507    #[must_use]
508    pub fn leitura(reason: impl Into<String>) -> Self {
509        Self::Leitura(reason.into())
510    }
511}
512
513/// Classify a manifest source without committing to either schema.
514///
515/// Deliberately reads only the head symbol and the set of top-level keywords —
516/// enough to route, never enough to half-parse. A classifier that started
517/// validating would grow into a third parser, which is the shape of the problem
518/// it exists to name.
519///
520/// # Errors
521/// [`DialetoError`] when the source is not a manifest declaration at all.
522pub fn classify(src: &str) -> Result<CaixaDialeto, DialetoError> {
523    let forms = tatara_lisp::read(src).map_err(|e| DialetoError::leitura(e.to_string()))?;
524    let first = forms.first().ok_or(DialetoError::Vazio)?;
525    classify_form(first)
526}
527
528/// [`classify`] over an already-read form.
529///
530/// # Errors
531/// [`DialetoError`] when the form is not a manifest declaration.
532pub fn classify_form(form: &Sexp) -> Result<CaixaDialeto, DialetoError> {
533    let list = form.as_list().ok_or(DialetoError::NaoEhLista)?;
534    let head = list
535        .first()
536        .and_then(Sexp::as_symbol)
537        .ok_or(DialetoError::NaoEhLista)?;
538
539    match head {
540        // `defmolde` is unambiguous by construction — it exists precisely so a
541        // consumer never has to infer which declaration it holds. Both arities
542        // are the same declaration; the positional one keeps its own variant
543        // only so a census can report the split.
544        "defmolde" => {
545            return Ok(if starts_with_positional_name(&list[1..]) {
546                CaixaDialeto::MoldePosicional
547            } else {
548                CaixaDialeto::Molde
549            });
550        }
551        "defcaixa" => {}
552        other => {
553            return Err(DialetoError::cabeca_errada(other));
554        }
555    }
556
557    let args = &list[1..];
558
559    // `(defcaixa <symbol> :kind … :ecosystem …)`. Only the Molde dialect has a
560    // positional arity; `Caixa` is keyword-only, so a leading bare symbol
561    // settles it without looking further.
562    if starts_with_positional_name(args) {
563        return Ok(CaixaDialeto::MoldePosicional);
564    }
565
566    let keys = top_level_keywords(args);
567    let has = |k: &str| keys.iter().any(|s| s == k);
568
569    // Order matters, and it is not arbitrary: `:nome` and `:name` are the two
570    // required head slots and no file in the measured corpus carries both.
571    // Checking them FIRST means the decision rests on the one slot each schema
572    // makes mandatory, rather than on optional evidence like `:ecosystem`.
573    if has("nome") {
574        return Ok(CaixaDialeto::Pacote);
575    }
576    if has("name") || has("ecosystem") || has("package") {
577        return Ok(CaixaDialeto::Molde);
578    }
579    Ok(CaixaDialeto::Desconhecido)
580}
581
582/// True when the first argument is a bare symbol rather than a keyword — the
583/// positional-name arity.
584fn starts_with_positional_name(args: &[Sexp]) -> bool {
585    matches!(args.first(), Some(Sexp::Atom(Atom::Symbol(_))))
586}
587
588/// The top-level keyword names (without the leading `:`) of a kwarg list.
589///
590/// Steps in pairs so a keyword appearing as a VALUE — `:kind :Biblioteca`, or a
591/// nested `(:nome "dep" :versao "^0.1")` inside `:deps` — is never counted as a
592/// top-level slot. A naive scan for `:nome` anywhere in the source classifies
593/// every Molde manifest with a `:deps` list as a Pacote.
594fn top_level_keywords(args: &[Sexp]) -> Vec<String> {
595    let mut out = Vec::new();
596    let mut i = 0;
597    while i < args.len() {
598        if let Sexp::Atom(Atom::Keyword(k)) = &args[i] {
599            out.push(k.clone());
600            i += 2;
601        } else {
602            i += 1;
603        }
604    }
605    out
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611
612    const PACOTE: &str = r#"
613      (defcaixa
614        :nome   "checkout"
615        :versao "0.1.0"
616        :kind   Servico
617        :deps   ((:nome "caixa-teia" :versao "^0.1")))
618    "#;
619
620    const MOLDE: &str = r#"
621      (defcaixa
622        :name "base64"
623        :kind :Biblioteca
624        :ecosystem :rust-single-crate
625        :package {:name "base64" :version "0.22.1"}
626        :workflows [:auto-release])
627    "#;
628
629    const MOLDE_POSICIONAL: &str = r#"
630      (defcaixa todoku-go
631        :kind :Biblioteca
632        :ecosystem :go
633        :package {:name "todoku-go" :version "0.3.0"})
634    "#;
635
636    #[test]
637    fn the_package_dialect_is_recognised() {
638        assert_eq!(classify(PACOTE), Ok(CaixaDialeto::Pacote));
639    }
640
641    #[test]
642    fn the_repo_surface_dialect_is_recognised() {
643        assert_eq!(classify(MOLDE), Ok(CaixaDialeto::Molde));
644    }
645
646    #[test]
647    fn the_positional_arity_is_recognised() {
648        assert_eq!(
649            classify(MOLDE_POSICIONAL),
650            Ok(CaixaDialeto::MoldePosicional)
651        );
652    }
653
654    #[test]
655    fn defmolde_classifies_without_inference() {
656        // The whole point of the new keyword: no schema sniffing required.
657        let src = r#"(defmolde :name "x" :kind :Biblioteca :ecosystem :go)"#;
658        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
659        let pos = r"(defmolde todoku-go :kind :Biblioteca :ecosystem :go)";
660        assert_eq!(classify(pos), Ok(CaixaDialeto::MoldePosicional));
661    }
662
663    #[test]
664    fn a_nested_nome_does_not_make_a_repo_surface_look_like_a_package() {
665        // The exact failure a substring scan produces: `:deps ((:nome …))`
666        // contains `:nome`, but not as a top-level slot.
667        let src = r#"
668          (defcaixa
669            :name "x"
670            :ecosystem :rust-single-crate
671            :deps ((:nome "inner" :versao "^0.1")))
672        "#;
673        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
674    }
675
676    #[test]
677    fn a_keyword_in_value_position_is_not_a_slot() {
678        // `:kind :Biblioteca` — the value is itself a keyword. Stepping one at
679        // a time would read `:Biblioteca` as a top-level slot.
680        let src = r#"(defcaixa :kind :Biblioteca :name "x")"#;
681        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
682    }
683
684    #[test]
685    fn an_unrecognised_defcaixa_is_reported_not_guessed() {
686        let src = r#"(defcaixa :licenca "MIT")"#;
687        assert_eq!(classify(src), Ok(CaixaDialeto::Desconhecido));
688    }
689
690    #[test]
691    fn a_form_that_is_not_a_manifest_is_an_error_not_a_dialect() {
692        assert_eq!(
693            classify("(defflake :nome \"x\")"),
694            Err(DialetoError::cabeca_errada("defflake"))
695        );
696        assert_eq!(classify(""), Err(DialetoError::Vazio));
697    }
698
699    #[test]
700    fn every_dialect_names_its_consumer_and_its_canonical_keyword() {
701        // Guards the routing table itself: a new variant added without an arm
702        // here is a compile error in the match, and a variant that claims
703        // `defcaixa` while being read by pleme-doc-gen would re-open the
704        // collision this module closes. Sweeps [`CaixaDialeto::ALL`] rather
705        // than the pre-lift open-coded four-arm literal list — a future arm
706        // addition extends the slice as one edit and this pin picks it up
707        // by construction.
708        for &d in CaixaDialeto::ALL {
709            assert!(!d.descricao().is_empty(), "{d}");
710            assert!(!d.consumidor().is_empty(), "{d}");
711        }
712        assert_eq!(CaixaDialeto::Pacote.palavra_canonica(), "defcaixa");
713        assert_eq!(CaixaDialeto::Molde.palavra_canonica(), "defmolde");
714        assert_ne!(
715            CaixaDialeto::Pacote.palavra_canonica(),
716            CaixaDialeto::Molde.palavra_canonica(),
717            "the two dialects must not share a canonical keyword — that IS the defect"
718        );
719    }
720
721    #[test]
722    fn caixa_dialeto_all_enumerates_every_variant_exactly_once() {
723        // Three-legged exhaustiveness pin, peer of the sibling
724        // `caixa_kind_all_enumerates_every_variant_exactly_once`
725        // (caixa-core/src/kind.rs) /
726        // `restart_strategy_all_enumerates_every_variant_exactly_once`
727        // (caixa-core/src/supervisor.rs) shape.
728        //
729        // 1. arm-count invariant: `ALL.len()` matches the declared arm
730        //    count (four — a fifth arm added without extending `ALL`
731        //    fails this pin at caixa-core test time);
732        // 2. pairwise-distinctness invariant: every variant appears at
733        //    most once in the slice (a duplicate arm would silently
734        //    double-count in the census consumer, so the pin rejects
735        //    duplicates outright);
736        // 3. coverage invariant: every literal `CaixaDialeto::X` is in
737        //    the slice (the compiler-checked exhaustiveness on the peer
738        //    per-arm `match self` in the accessors keeps the enum arm
739        //    set and the `ALL` slice mutually aligned).
740        assert_eq!(
741            CaixaDialeto::ALL.len(),
742            4,
743            "ALL must list every arm exactly once; a fifth arm added \
744             without extending ALL fails this pin — extend ALL alongside \
745             the new variant"
746        );
747
748        let mut seen: Vec<CaixaDialeto> = Vec::new();
749        for &d in CaixaDialeto::ALL {
750            assert!(
751                !seen.contains(&d),
752                "ALL contains a duplicate arm: {d}. Every variant appears \
753                 exactly once — a duplicate would double-count in every \
754                 iteration consumer"
755            );
756            seen.push(d);
757        }
758
759        // Coverage: exhaustively assert every literal variant is somewhere
760        // in the slice. Written as an exhaustive `match` so a future arm
761        // addition fails to compile here (missing match arm) until the
762        // corresponding `assert` is added — the compiler enforces the pin's
763        // completeness rather than a hand-maintained variant list.
764        for variant in [
765            CaixaDialeto::Pacote,
766            CaixaDialeto::Molde,
767            CaixaDialeto::MoldePosicional,
768            CaixaDialeto::Desconhecido,
769        ] {
770            let coverage_probe = match variant {
771                CaixaDialeto::Pacote
772                | CaixaDialeto::Molde
773                | CaixaDialeto::MoldePosicional
774                | CaixaDialeto::Desconhecido => variant,
775            };
776            assert!(
777                CaixaDialeto::ALL.contains(&coverage_probe),
778                "ALL is missing variant {coverage_probe} — extend the slice"
779            );
780        }
781    }
782
783    #[test]
784    fn caixa_dialeto_all_is_const_and_matches_iteration_count() {
785        // Pins the const-ness of the slice at const-fold time. A future
786        // change that promoted `ALL` to a non-const initializer (a lazy-
787        // static, a runtime-computed Vec) would fail to compile here —
788        // the pin locks in the compile-time-known iteration surface
789        // every consumer builds against. Peer of the sibling
790        // `caixa_kind_all_is_const_and_matches_iteration_count` (kind.rs)
791        // / `restart_strategy_all_is_const_and_matches_iteration_count`
792        // (supervisor.rs) shape.
793        const ALL: &[CaixaDialeto] = CaixaDialeto::ALL;
794        assert_eq!(ALL.len(), CaixaDialeto::ALL.len());
795        // Sweep the iterator without collapsing to `.len()` so a future
796        // change to `ALL`'s carrier that decouples `.len()` from the
797        // iteration count (a lazy-computed shape, an alias `impl Iterator`
798        // return, a wrapper newtype) still passes here iff the two agree
799        // arm-for-arm; the `#[allow]` opts this local pin out of the
800        // clippy `iter_count` collapse that would defeat the intent.
801        #[allow(clippy::iter_count)]
802        let iterated = ALL.iter().count();
803        assert_eq!(iterated, CaixaDialeto::ALL.len());
804    }
805
806    #[test]
807    fn caixa_dialeto_all_covers_every_variant_by_display_probe() {
808        // Fanning `Display` over the slice sweeps the paired accessors
809        // ([`CaixaDialeto::palavra_canonica`] / [`CaixaDialeto::consumidor`]
810        // / [`CaixaDialeto::descricao`]) at every arm — every returned
811        // byte-string is non-empty (the accessors' contract). A future
812        // arm added without extending its per-arm `match self` return
813        // would compile-fail at the accessor call inside the loop;
814        // together with the `ALL.len() == 4` pin above, this locks the
815        // accessor arm-set and the `ALL` slice mutually.
816        for &d in CaixaDialeto::ALL {
817            let display_form = d.to_string();
818            assert!(
819                !display_form.is_empty(),
820                "Display must render a non-empty byte-string for every \
821                 arm; empty: {d:?}"
822            );
823            // Consumidor / descricao / palavra-canonica must each surface
824            // a non-empty scalar; every downstream diagnostic consumer
825            // reaches through these accessors.
826            assert!(!d.palavra_canonica().is_empty(), "{d}");
827            assert!(!d.consumidor().is_empty(), "{d}");
828            assert!(!d.descricao().is_empty(), "{d}");
829        }
830    }
831
832    #[test]
833    fn caixa_dialeto_as_str_returns_pascal_case_variant_name() {
834        // Fail-before-pass-after per-arm shape pin: the four
835        // [`CaixaDialeto::as_str`] arms must return the canonical
836        // `PascalCase` byte-string that names the variant. Pre-lift this
837        // byte-string existed only inside the hand-rolled Display impl's
838        // four-arm literal-string match — every consumer that wanted the
839        // `PascalCase` name reached through `format!("{d}")`'s allocation
840        // path. Pinning the four arms explicitly here refuses a future
841        // regression that ever reroutes an arm to a distinct spelling
842        // (`"pacote"` lowercase, `"MoldePositional"` English rebrand,
843        // `"Unknown"` for `Desconhecido`) — the census output and the
844        // typed accessor would silently disagree until a downstream
845        // consumer surfaced the drift at census time. Peer of the sibling
846        // [`crate::supervisor::tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
847        // / `placement_strategy_variants_serialize_to_lifted_scalar_values`
848        // / `caixa_kind_as_str_returns_lifted_peer_const` shape on the
849        // sibling closed-set typed-enum discriminator axes — the seventh
850        // (and last unlifted) closed-set typed enum on the caixa surface
851        // to converge onto the same per-arm-shape-pin discipline.
852        for (variant, expected) in [
853            (CaixaDialeto::Pacote, "Pacote"),
854            (CaixaDialeto::Molde, "Molde"),
855            (CaixaDialeto::MoldePosicional, "MoldePosicional"),
856            (CaixaDialeto::Desconhecido, "Desconhecido"),
857        ] {
858            assert_eq!(
859                variant.as_str(),
860                expected,
861                "CaixaDialeto::{variant:?}.as_str() must return the \
862                 canonical `PascalCase` variant-name byte-string; drift here \
863                 splits the census-facing text from the substrate \
864                 primitive every downstream consumer will read"
865            );
866        }
867    }
868
869    #[test]
870    fn caixa_dialeto_display_routes_through_as_str_helper() {
871        // Fail-before-pass-after convergence pin: for every arm in
872        // [`CaixaDialeto::ALL`], the [`std::fmt::Display`] rendered form
873        // must byte-equal [`CaixaDialeto::as_str`]'s return value. Pre-
874        // lift these two paths were structurally independent — the
875        // Display impl hand-rolled its own four-arm literal-string
876        // match with no compile-time link back to any substrate accessor
877        // — so a future variant rename could land at `Display` without
878        // touching a paired accessor (or vice versa), silently splitting
879        // the two paths on the renamed arm. Pinning the byte-equality
880        // here makes any such split a caixa-core build-time failure at
881        // this test rather than surfacing far from the rename commit as
882        // a downstream census consumer emitting one spelling while the
883        // typed accessor returned another. Peer of the sibling
884        // [`crate::kind::tests::caixa_kind_display_routes_through_as_str_helper`]
885        // (which pins the same convergence on the [`crate::CaixaKind`]
886        // closed-set axis) — extends the discipline onto the seventh
887        // (and last unlifted) closed-set fieldless typed enum on the
888        // caixa surface.
889        for &variant in CaixaDialeto::ALL {
890            assert_eq!(
891                variant.to_string(),
892                variant.as_str(),
893                "CaixaDialeto::{variant:?} Display must route through \
894                 CaixaDialeto::as_str (single source of truth: the \
895                 lifted per-arm `PascalCase` variant-name byte-string)"
896            );
897        }
898    }
899
900    #[test]
901    fn caixa_dialeto_as_ref_str_routes_through_as_str_accessor() {
902        // Fail-before-pass-after byte-parity pin on the lifted
903        // `impl AsRef<str> for CaixaDialeto` — asserts the standard-
904        // library trait impl and the substrate-primitive
905        // [`CaixaDialeto::as_str`] `pub const fn` accessor resolve to
906        // the same `&str` per instance across the four-arm closed set,
907        // so any future silent detour that routes the impl through a
908        // divergent projection (a per-arm inline
909        // `match self { CaixaDialeto::Pacote => "Pacote", … }` re-inlining
910        // that opens a compile-time link to the un-lifted arm-literal,
911        // a swap onto the second-axis
912        // [`CaixaDialeto::palavra_canonica`] /
913        // [`CaixaDialeto::consumidor`] / [`CaixaDialeto::descricao`]
914        // accessors that carry distinct byte-shapes per axis) trips at
915        // caixa-core test time under `PartialEq` rather than at a
916        // downstream `impl AsRef<str>`-bound consumer's silent split.
917        // Sweeps every one of the four arms [`CaixaDialeto::ALL`]
918        // carries so no arm's projection is covered only by the sibling
919        // `Display` path. Peer of the sibling
920        // `rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`
921        // (d8136db) on the M3 `:politicas :rate-limit` closed-set typed
922        // enum, and the peer
923        // [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
924        // (cd2091f) pin on the top-level closed-set typed
925        // discriminator — the pins together close the substrate
926        // primitive's `AsRef<str>` projection axis onto the seventh
927        // closed-set fieldless typed enum on the caixa surface.
928        for &variant in CaixaDialeto::ALL {
929            assert_eq!(
930                <CaixaDialeto as AsRef<str>>::as_ref(&variant),
931                variant.as_str(),
932                "AsRef<str> impl on CaixaDialeto::{variant:?} must \
933                 byte-equal CaixaDialeto::as_str on the same instance \
934                 — divergence signals a silent detour off the \
935                 substrate-primitive accessor"
936            );
937        }
938    }
939
940    #[test]
941    fn caixa_dialeto_as_ref_str_routes_through_display_via_shared_accessor() {
942        // Fail-before-pass-after byte-parity pin on the three-path
943        // convergence discipline the [`CaixaDialeto`] closed-set
944        // dialect-classification enum now carries on the `&str`-
945        // projection axis: `<CaixaDialeto as AsRef<str>>::as_ref(&v)`
946        // (the newly lifted impl), `format!("{v}")` (the pre-existing
947        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
948        // primitive `pub const fn` accessor both trait impls delegate
949        // through) must resolve to the same byte-string on every
950        // instance across the four-arm closed set. Refuses any future
951        // divergence between the two trait impls (a stray
952        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
953        // rather than delegating through the shared accessor; a
954        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
955        // literal cascade) that would silently split the two
956        // projection paths of the same closed-set typed enum. Mirrors
957        // the sibling three-path-convergence discipline the peer
958        // [`crate::aplicacao::RateLimitUnit`] typed enum carries
959        // (`rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`,
960        // d8136db), the peer [`crate::CaixaKind`] triple
961        // (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
962        // cd2091f), and the [`crate::CaixaVersion`] typed newtype
963        // triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
964        // 16d5c7e).
965        for &variant in CaixaDialeto::ALL {
966            let via_as_ref: &str = <CaixaDialeto as AsRef<str>>::as_ref(&variant);
967            let via_display: String = format!("{variant}");
968            let via_accessor: &str = variant.as_str();
969            assert_eq!(via_as_ref, via_accessor);
970            assert_eq!(via_display, via_accessor);
971            assert_eq!(via_as_ref, via_display.as_str());
972        }
973    }
974
975    #[test]
976    fn caixa_dialeto_is_molde_family_returns_true_on_molde_and_positional_arms() {
977        // Fail-before-pass-after per-arm shape pin on the two `defmolde`
978        // declaration-family arms: [`CaixaDialeto::is_molde_family`] must
979        // return `true` for [`CaixaDialeto::Molde`] and
980        // [`CaixaDialeto::MoldePosicional`] — the two-arity closure of
981        // one declaration ([`CaixaDialeto::MoldePosicional`]'s docstring:
982        // "same declaration as [`Self::Molde`], written with the package
983        // name as a bare positional symbol … one arity of one
984        // declaration, not a third schema"). A future accidental flip that
985        // reversed a per-arm arm's return without touching the paired
986        // false-arm pin would silently open the substrate primitive to
987        // false-positive on either arm — the `feira dialeto` verb's
988        // `--strict-palavra` gate would then silently accept
989        // repo-surface declarations under `(defcaixa …)` on one arm and
990        // reject them on the other. Pinning the two true arms explicitly
991        // here refuses that split at caixa-core build time.
992        assert!(
993            CaixaDialeto::Molde.is_molde_family(),
994            "CaixaDialeto::Molde.is_molde_family() must return true — \
995             Molde is the primary `defmolde` arm"
996        );
997        assert!(
998            CaixaDialeto::MoldePosicional.is_molde_family(),
999            "CaixaDialeto::MoldePosicional.is_molde_family() must return \
1000             true — MoldePosicional is the positional-arity form of the \
1001             same `defmolde` declaration Molde carries"
1002        );
1003    }
1004
1005    #[test]
1006    fn caixa_dialeto_is_molde_family_returns_false_on_pacote_and_desconhecido_arms() {
1007        // Fail-before-pass-after per-arm shape pin on the two non-`defmolde`
1008        // arms: [`CaixaDialeto::is_molde_family`] must return `false` for
1009        // [`CaixaDialeto::Pacote`] (the sibling `defcaixa` tatara-lisp
1010        // package manifest, `palavra_canonica → "defcaixa"`) and for
1011        // [`CaixaDialeto::Desconhecido`] (the residue that names no
1012        // known declaration, `palavra_canonica → "?"`). Pinning the two
1013        // false arms explicitly here refuses a future accidental flip
1014        // that let the predicate widen to include either arm — the
1015        // `feira dialeto` verb's `--strict-palavra` gate would then
1016        // spuriously refuse every `(defcaixa …)` package manifest as if
1017        // it were a repo-surface declaration.
1018        assert!(
1019            !CaixaDialeto::Pacote.is_molde_family(),
1020            "CaixaDialeto::Pacote.is_molde_family() must return false — \
1021             Pacote is the `defcaixa` tatara-lisp package manifest, not \
1022             the `defmolde` repo-surface declaration"
1023        );
1024        assert!(
1025            !CaixaDialeto::Desconhecido.is_molde_family(),
1026            "CaixaDialeto::Desconhecido.is_molde_family() must return \
1027             false — the residue arm names no known declaration; it is \
1028             not silently promoted into the `defmolde` family"
1029        );
1030    }
1031
1032    #[test]
1033    fn caixa_dialeto_is_molde_family_agrees_with_palavra_canonica_defmolde_projection() {
1034        // Load-bearing pin: for every arm in [`CaixaDialeto::ALL`], the
1035        // typed [`CaixaDialeto::is_molde_family`] predicate must agree
1036        // byte-for-byte with the paired [`CaixaDialeto::palavra_canonica`]
1037        // projection's `== "defmolde"` classifier — i.e. the two paths
1038        // partition the four-arm discriminator set into the same
1039        // `{Molde, MoldePosicional}` and `{Pacote, Desconhecido}` halves.
1040        // Pre-lift the sibling [`CaixaDialeto::palavra_canonica`] projection
1041        // (which returns `"defmolde"` for `Molde | MoldePosicional`,
1042        // `"defcaixa"` for `Pacote`, `"?"` for `Desconhecido`) was the
1043        // only substrate-side surface carrying the two-arm collapse; the
1044        // hand-rolled `matches!(d, CaixaDialeto::Molde |
1045        // CaixaDialeto::MoldePosicional)` sites in the `feira dialeto`
1046        // verb expressed no compile-time link back to it. A future arm
1047        // addition — the module doc's "third dialect" hazard actualises
1048        // as a fifth arm belonging to the `defmolde` family — would land
1049        // one match arm at [`Self::palavra_canonica`]'s `defmolde` return
1050        // (extending the sibling projection) but silently split the
1051        // hand-rolled two-arm `matches!` predicate sites if the new arm's
1052        // `is_molde_family` return were forgotten. Pinning byte-equality
1053        // between the two paths here makes any such split a caixa-core
1054        // build-time failure at this test rather than surfacing far from
1055        // the arm-addition commit as a downstream `--strict-palavra` /
1056        // `caixa.lisp`-holds-wrong-declaration gate silently ignoring the
1057        // new arm.
1058        for &d in CaixaDialeto::ALL {
1059            let via_palavra_canonica = d.palavra_canonica() == "defmolde";
1060            let via_is_molde_family = d.is_molde_family();
1061            assert_eq!(
1062                via_is_molde_family, via_palavra_canonica,
1063                "CaixaDialeto::{d:?}.is_molde_family() ({via_is_molde_family}) \
1064                 must agree with CaixaDialeto::{d:?}.palavra_canonica() == \
1065                 \"defmolde\" ({via_palavra_canonica}) — a split between the \
1066                 typed predicate and the sibling keyword projection would let \
1067                 a future arm addition land at one path and drift at the other, \
1068                 which is exactly the drift this pin refuses"
1069            );
1070        }
1071    }
1072
1073    #[test]
1074    fn caixa_dialeto_is_molde_family_is_const_fn() {
1075        // Const-context pin: [`CaixaDialeto::is_molde_family`] must remain
1076        // `const fn` (its match is a fieldless-arm literal-pattern
1077        // discriminator, so no non-const operation exists on the resolution
1078        // path). Downstream consumers reaching for the predicate from a
1079        // `const` context (a future substrate-wide const-fold-driven audit
1080        // table that materializes per-arm gate-membership at build time,
1081        // a per-arm CR-admission-webhook gate registration in a `const`
1082        // context) rely on the const-ness. A future accidental downgrade
1083        // to non-`const` (an added runtime helper reachable only from a
1084        // non-`const` context) trips at caixa-core build time rather than
1085        // surfacing as a downstream `const`-context regression far from
1086        // the predicate declaration. Peer of the sibling
1087        // [`caixa_dialeto_as_str_is_const_fn`] pin on the paired
1088        // [`CaixaDialeto::as_str`] byte-string axis.
1089        const ARMS: [(CaixaDialeto, bool); 4] = [
1090            (CaixaDialeto::Pacote, CaixaDialeto::Pacote.is_molde_family()),
1091            (CaixaDialeto::Molde, CaixaDialeto::Molde.is_molde_family()),
1092            (
1093                CaixaDialeto::MoldePosicional,
1094                CaixaDialeto::MoldePosicional.is_molde_family(),
1095            ),
1096            (
1097                CaixaDialeto::Desconhecido,
1098                CaixaDialeto::Desconhecido.is_molde_family(),
1099            ),
1100        ];
1101        // Materialize the const-fold-evaluated table into a runtime slice
1102        // assertion — carries the same `bool = const fn call` shape a raw
1103        // `assert!(const_bool)` would, without tripping the
1104        // `assertions_on_constants` clippy lint that a per-arm
1105        // `assert!(CONST)` on a `const bool` triggers when the arm-count
1106        // is enumerated flat rather than compared as a whole-table shape.
1107        assert_eq!(
1108            ARMS,
1109            [
1110                (CaixaDialeto::Pacote, false),
1111                (CaixaDialeto::Molde, true),
1112                (CaixaDialeto::MoldePosicional, true),
1113                (CaixaDialeto::Desconhecido, false),
1114            ],
1115            "CaixaDialeto::is_molde_family() must evaluate in const context \
1116             for every arm and land on the {{false, true, true, false}} \
1117             partition — a future accidental downgrade to non-`const` \
1118             would trip the const-context array-initializer here"
1119        );
1120    }
1121
1122    #[test]
1123    fn caixa_dialeto_as_str_is_const_fn() {
1124        // Const-context pin: [`CaixaDialeto::as_str`] must remain
1125        // `const fn` (its match arms return `pub const` byte-strings, so
1126        // no non-const operation exists on the resolution path).
1127        // Downstream consumers reaching for the accessor from a `const`
1128        // context (a future substrate-wide const-fold-driven audit table
1129        // that materializes every dialect's census label at build time,
1130        // a per-arm CR-admission-webhook message registration in a
1131        // `const` gate) rely on the const-ness. A future accidental
1132        // downgrade to non-`const` (an added runtime helper reachable
1133        // only from a non-`const` context, a manual hand-rolled `impl`
1134        // that shadows this method) trips at caixa-core build time
1135        // rather than surfacing as a downstream `const`-context
1136        // regression far from the accessor declaration. Peer of the
1137        // sibling [`crate::kind::tests::caixa_kind_wire_name_is_const_fn`]
1138        // pin on the paired [`crate::CaixaKind`] byte-string axis.
1139        const PACOTE: &str = CaixaDialeto::Pacote.as_str();
1140        const MOLDE: &str = CaixaDialeto::Molde.as_str();
1141        const MOLDE_POSICIONAL: &str = CaixaDialeto::MoldePosicional.as_str();
1142        const DESCONHECIDO: &str = CaixaDialeto::Desconhecido.as_str();
1143        assert_eq!(PACOTE, "Pacote");
1144        assert_eq!(MOLDE, "Molde");
1145        assert_eq!(MOLDE_POSICIONAL, "MoldePosicional");
1146        assert_eq!(DESCONHECIDO, "Desconhecido");
1147    }
1148
1149    #[test]
1150    fn caixa_dialeto_is_variant_predicates_partition_the_arm_set() {
1151        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
1152        // derive: for each of the four variants at [`CaixaDialeto::ALL`]`[idx]`
1153        // the observed four-slot predicate row must equal a one-hot row
1154        // with the `true` at exactly `idx`. Pre-derive the closed four-arm
1155        // dialect-classification partition lived only inside the paired
1156        // per-arm projections' four-arm match resolvers ([`Self::as_str`] /
1157        // [`Self::palavra_canonica`] / [`Self::consumidor`] /
1158        // [`Self::descricao`]) plus the two-arm [`Self::is_molde_family`]
1159        // hand-rolled `matches!` (now routed through the derived
1160        // predicates); a future rebrand (an accidental
1161        // `#[is_variant(name = "…")]` drift, a manual hand-rolled `impl`
1162        // that shadows the derive-generated method, an arm rename that
1163        // reroutes one arm through the wrong predicate lane) trips this
1164        // pin at caixa-core build time rather than surfacing far from the
1165        // derive declaration as a downstream [`Self::is_molde_family`]
1166        // consumer accepting the wrong arm-set. The expected row is
1167        // generated live from the [`Self::ALL`] declaration order rather
1168        // than transcribed by hand so a copy-paste flip reroutes at the
1169        // identity-diagonal assertion.
1170        //
1171        // Peer of the sibling
1172        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
1173        // / [`crate::supervisor::tests::restart_strategy_is_variant_predicates_partition_the_arm_set`]
1174        // / [`crate::aplicacao::tests::placement_strategy_is_variant_predicates_partition_the_arm_set`]
1175        // / [`crate::upgrade::tests::upgrade_instruction_is_variant_predicates_partition_the_arm_set`]
1176        // pins on the sibling closed-set typed-enum discriminator axes.
1177        for (idx, &variant) in CaixaDialeto::ALL.iter().enumerate() {
1178            let observed = [
1179                variant.is_pacote(),
1180                variant.is_molde(),
1181                variant.is_molde_posicional(),
1182                variant.is_desconhecido(),
1183            ];
1184            let mut expected = [false; 4];
1185            expected[idx] = true;
1186            assert_eq!(
1187                observed, expected,
1188                "CaixaDialeto::{variant:?} at ALL[{idx}] is_* predicates \
1189                 must fire only on their own arm lane (identity diagonal); \
1190                 got {observed:?}",
1191            );
1192        }
1193    }
1194
1195    #[test]
1196    fn caixa_dialeto_is_variant_predicates_are_const_fn() {
1197        // The [`gen_platform::IsVariant`] derive emits `const fn`
1198        // predicates on the peer [`crate::CaixaKind`] +
1199        // [`crate::upgrade::UpgradeInstruction`] +
1200        // [`crate::supervisor::RestartStrategy`] +
1201        // [`crate::supervisor::RestartPolicy`] +
1202        // [`crate::aplicacao::PlacementStrategy`] +
1203        // [`crate::aplicacao::RateLimitUnit`] +
1204        // [`crate::dep::DepList`] closed-set typed enums — pin the same
1205        // posture on [`CaixaDialeto`] so a future accidental downgrade
1206        // to non-`const` (an added runtime helper reachable only from a
1207        // non-`const` context, a manual hand-rolled `impl` that shadows
1208        // the derive-generated method) trips at caixa-core build time
1209        // rather than surfacing as a downstream `const`-context
1210        // regression far from the derive declaration.
1211        // Use `const { assert!(…) }` (peer of the sibling
1212        // [`crate::render::PathShapeViolation`] +
1213        // [`crate::aplicacao::RateLimitUnit`] +
1214        // [`caixa_theme::style::Semantic`] const-fn pins) so the
1215        // const-context evaluation trips at const-fold time without
1216        // opening a per-`const bool` `assertions_on_constants` clippy
1217        // debt row this crate does not carry today for `dialeto.rs`.
1218        const { assert!(CaixaDialeto::Pacote.is_pacote()) };
1219        const { assert!(CaixaDialeto::Molde.is_molde()) };
1220        const { assert!(CaixaDialeto::MoldePosicional.is_molde_posicional()) };
1221        const { assert!(CaixaDialeto::Desconhecido.is_desconhecido()) };
1222    }
1223
1224    #[test]
1225    fn cabeca_errada_ctor_matches_struct_literal_wrap() {
1226        // Fail-before-pass-after byte-identity pin: the lifted
1227        // [`DialetoError::cabeca_errada`] ctor MUST land on the exact
1228        // same struct-literal shape the pre-lift open-coded wire-up
1229        // block wrote by hand — `DialetoError::CabecaErrada {
1230        // encontrado: <head>.to_string() }`. A future accidental
1231        // divergence (`.into()` swap, per-arm constant substitution, an
1232        // added default field, an `.to_ascii_lowercase()` normalization
1233        // silently injected into the ctor body, a rebrand of the
1234        // `encontrado` field carrying a distinct byte-shape) trips this
1235        // pin at caixa-core build time rather than surfacing far from
1236        // the ctor declaration as a downstream `classify_form`
1237        // wrong-head consumer emitting one diagnostic shape while a
1238        // hand-written test peer opens another. Peer of the sibling
1239        // `unknown_byte_unit_ctor_matches_struct_literal_wrap`
1240        // (limits.rs; 29fac09) / `duplicate_from_ctor_matches_struct_
1241        // literal_wrap` (upgrade.rs; 7e52aec) shape on the sibling
1242        // single-slot `{ <field>: String }` envelope constructors.
1243        assert_eq!(
1244            DialetoError::cabeca_errada("defflake"),
1245            DialetoError::CabecaErrada {
1246                encontrado: "defflake".to_string(),
1247            },
1248            "DialetoError::cabeca_errada must byte-equal the pre-lift \
1249             open-coded struct-literal — a drift here means the ctor \
1250             stopped being a substrate primitive for the wrong-head \
1251             fallthrough site"
1252        );
1253    }
1254
1255    #[test]
1256    fn cabeca_errada_routes_encontrado_verbatim_across_boundary_inputs() {
1257        // Fail-before-pass-after boundary-sweep pin: the lifted
1258        // [`DialetoError::cabeca_errada`] ctor MUST route its
1259        // `encontrado: &str` argument verbatim into the
1260        // [`DialetoError::CabecaErrada`] `encontrado: String` field
1261        // for every boundary-covering `&str` input — empty string, a
1262        // canonical `defcaixa`-adjacent head, a non-ASCII head, a
1263        // whitespace-carrying head, a Unicode-full-width head. Any
1264        // wrapper-side truncation, silent `.trim()`, accidental
1265        // `.to_ascii_lowercase()` normalization, or `.into()` divergence
1266        // on the ctor body surfaces here as a byte-mismatch against the
1267        // input rather than at a downstream
1268        // [`DialetoError::to_string()`] diagnostic-shape drift at a
1269        // wrong-head fallthrough consumer far from the ctor declaration.
1270        // Peer of the sibling `limits_codec_unit_only_ctors_route_unit_
1271        // verbatim_across_every_variant` (limits.rs; 29fac09) shape on
1272        // the sibling single-slot `{ <field>: String }` envelope
1273        // boundary-sweep discipline.
1274        for encontrado in [
1275            "",
1276            "defflake",
1277            "def-molde",
1278            "defcaixa ",
1279            " defcaixa",
1280            "μdefcaixa",
1281            "\u{00A0}defcaixa",
1282            "\u{3000}defcaixa",
1283            "def\u{2028}caixa",
1284        ] {
1285            let via_ctor = DialetoError::cabeca_errada(encontrado);
1286            let via_literal = DialetoError::CabecaErrada {
1287                encontrado: encontrado.to_string(),
1288            };
1289            assert_eq!(
1290                via_ctor, via_literal,
1291                "DialetoError::cabeca_errada({encontrado:?}) must byte- \
1292                 equal the open-coded struct-literal on the same input — \
1293                 a drift here would let the ctor silently normalize / \
1294                 truncate the head symbol before it reached the \
1295                 CabecaErrada envelope"
1296            );
1297            let DialetoError::CabecaErrada { encontrado: routed } = via_ctor else {
1298                panic!(
1299                    "DialetoError::cabeca_errada must construct the \
1300                     CabecaErrada arm — got a different variant on \
1301                     input {encontrado:?}"
1302                );
1303            };
1304            assert_eq!(
1305                routed, encontrado,
1306                "DialetoError::cabeca_errada must route the input \
1307                 {encontrado:?} verbatim into the encontrado field — \
1308                 any wrapper-side truncation / normalization surfaces \
1309                 here rather than at a downstream diagnostic shape drift"
1310            );
1311        }
1312    }
1313
1314    #[test]
1315    fn classify_form_wrong_head_routes_through_cabeca_errada_ctor() {
1316        // Fail-before-pass-after routing pin: [`classify`]'s wrong-head
1317        // fallthrough site MUST construct its `Err(DialetoError::…)`
1318        // through the substrate-primitive [`DialetoError::cabeca_errada`]
1319        // ctor rather than through an open-coded struct-literal. Pre-
1320        // lift the wire-up hand-rolled a three-line
1321        // `Self::CabecaErrada { encontrado: other.to_string() }` block
1322        // with no compile-time link back to the substrate primitive; a
1323        // future accidental rebrand of the ctor body (an added
1324        // `.trim()` on `encontrado`, a per-arm constant prefix like
1325        // `"unknown-head:"`, a widening of the field into a
1326        // `(String, usize)` tuple carrying a caret offset) would then
1327        // silently split the two paths — the ctor consumers pick up
1328        // the new shape, the open-coded wire-up does not. Pinning
1329        // byte-equality between the observed `Err` and the ctor-
1330        // constructed `Err` refuses that split at caixa-core build
1331        // time rather than surfacing far from the wire-up commit as a
1332        // downstream diagnostic-consumer split.
1333        for head in ["defflake", "deffoobar", "defcaixaz", "let", "defmoldez"] {
1334            let src = format!("({head} :nome \"x\")");
1335            let observed = classify(&src);
1336            let via_ctor = Err(DialetoError::cabeca_errada(head));
1337            assert_eq!(
1338                observed, via_ctor,
1339                "classify({src:?}) must return the same Err shape as \
1340                 DialetoError::cabeca_errada({head:?}) — a drift here \
1341                 means the wire-up de-lifted its wrong-head fallthrough \
1342                 arm off the substrate primitive"
1343            );
1344        }
1345    }
1346
1347    #[test]
1348    fn leitura_ctor_matches_tuple_literal_wrap_on_str_binding() {
1349        // Fail-before-pass-after byte-identity pin: the lifted
1350        // [`DialetoError::leitura`] ctor MUST land on the exact same
1351        // tuple-newtype wrap the pre-lift open-coded wire-up block wrote by
1352        // hand — `DialetoError::Leitura(<into-String-expr>)`. A future
1353        // accidental divergence (an added `.trim()` on the reader reason,
1354        // a per-arm constant prefix like `"tatara-lisp:"`, a widening of
1355        // the tuple carrying a caret offset, a rebrand of the payload
1356        // carrying a distinct byte-shape) trips this pin at caixa-core
1357        // build time rather than surfacing far from the ctor declaration
1358        // as a downstream [`classify`] tatara-lisp-reader consumer
1359        // emitting one diagnostic shape while a hand-written test peer
1360        // opens another. Peer of the sibling
1361        // `cabeca_errada_ctor_matches_struct_literal_wrap` pin above on
1362        // the same [`DialetoError`] envelope's wrong-head axis, and of
1363        // the peer `LimitsError::empty_byte_size` /
1364        // `LimitsError::empty_duration` (7a4b003 / 319216c) shape on the
1365        // sibling `(String)` single-slot tuple-newtype envelope
1366        // constructors.
1367        let reason: &str = "unclosed paren at 1:12";
1368        assert_eq!(
1369            DialetoError::leitura(reason),
1370            DialetoError::Leitura(reason.to_string()),
1371            "DialetoError::leitura must byte-equal the pre-lift open-coded \
1372             tuple-newtype wrap — a drift here means the ctor stopped \
1373             being a substrate primitive for the tatara-lisp-reader \
1374             fallthrough site"
1375        );
1376    }
1377
1378    #[test]
1379    fn leitura_ctor_matches_tuple_literal_wrap_on_string_binding() {
1380        // Fail-before-pass-after byte-identity pin on the `String` wire-up
1381        // shape: the lifted [`DialetoError::leitura`] ctor MUST land on
1382        // the same tuple-newtype wrap when the caller passes an owned
1383        // `String` (the actual [`classify`] wire-up shape — `e.to_string()`
1384        // on a [`tatara_lisp::Error`]-carrying binding). Pins that the
1385        // `impl Into<String>` param covers the owned-`String` path with no
1386        // silent double-allocation or intermediate `&str` reslicing. Peer
1387        // of the sibling `_on_str_binding` pin above — together they close
1388        // the `impl Into<String>` bound's two authored wire-up shapes on
1389        // the ctor's substrate primitive.
1390        let reason: String = String::from("read: unexpected EOF at 3:1");
1391        let via_ctor = DialetoError::leitura(reason.clone());
1392        let via_literal = DialetoError::Leitura(reason.clone());
1393        assert_eq!(
1394            via_ctor, via_literal,
1395            "DialetoError::leitura must byte-equal the pre-lift open-coded \
1396             tuple-newtype wrap on the same owned-String fixture — a drift \
1397             here would let the ctor silently reshape the reader reason \
1398             before it reached the Leitura envelope"
1399        );
1400        let DialetoError::Leitura(routed) = via_ctor else {
1401            panic!(
1402                "DialetoError::leitura must construct the Leitura arm — \
1403                 got a different variant on input {reason:?}"
1404            );
1405        };
1406        assert_eq!(
1407            routed, reason,
1408            "DialetoError::leitura must route the input {reason:?} \
1409             verbatim into the tuple-newtype payload — any wrapper-side \
1410             truncation / normalization surfaces here rather than at a \
1411             downstream diagnostic shape drift"
1412        );
1413    }
1414
1415    #[test]
1416    fn leitura_routes_reason_verbatim_across_boundary_inputs() {
1417        // Fail-before-pass-after boundary-sweep pin: the lifted
1418        // [`DialetoError::leitura`] ctor MUST route its
1419        // `reason: impl Into<String>` argument verbatim into the
1420        // [`DialetoError::Leitura`] tuple-newtype `String` payload for
1421        // every boundary-covering input — empty string, a canonical
1422        // tatara-lisp reader error, a non-ASCII reason, a
1423        // whitespace-carrying reason, a Unicode-full-width reason. Any
1424        // wrapper-side truncation, silent `.trim()`, accidental
1425        // `.to_ascii_lowercase()` normalization, or `.into()` divergence
1426        // on the ctor body surfaces here as a byte-mismatch against the
1427        // input rather than at a downstream [`DialetoError::to_string()`]
1428        // diagnostic-shape drift at a tatara-lisp-reader fallthrough
1429        // consumer far from the ctor declaration. Peer of the sibling
1430        // `cabeca_errada_routes_encontrado_verbatim_across_boundary_inputs`
1431        // pin above on the same [`DialetoError`] envelope's wrong-head
1432        // axis.
1433        for reason in [
1434            "",
1435            "unclosed paren at 1:12",
1436            "unexpected token ')'",
1437            "read: eof",
1438            " leading whitespace",
1439            "trailing whitespace ",
1440            "μnicode reason",
1441            "\u{00A0}NBSP-prefixed reason",
1442            "\u{3000}ideographic-space reason",
1443            "reason\u{2028}with-line-separator",
1444        ] {
1445            let via_ctor = DialetoError::leitura(reason);
1446            let via_literal = DialetoError::Leitura(reason.to_string());
1447            assert_eq!(
1448                via_ctor, via_literal,
1449                "DialetoError::leitura({reason:?}) must byte-equal the \
1450                 open-coded tuple-newtype wrap on the same input — a \
1451                 drift here would let the ctor silently normalize / \
1452                 truncate the reader reason before it reached the \
1453                 Leitura envelope"
1454            );
1455            let DialetoError::Leitura(routed) = via_ctor else {
1456                panic!(
1457                    "DialetoError::leitura must construct the Leitura \
1458                     arm — got a different variant on input {reason:?}"
1459                );
1460            };
1461            assert_eq!(
1462                routed, reason,
1463                "DialetoError::leitura must route the input {reason:?} \
1464                 verbatim into the tuple-newtype payload — any \
1465                 wrapper-side truncation / normalization surfaces here \
1466                 rather than at a downstream diagnostic shape drift"
1467            );
1468        }
1469    }
1470
1471    #[test]
1472    fn classify_reader_error_routes_through_leitura_ctor() {
1473        // Fail-before-pass-after routing pin: [`classify`]'s
1474        // tatara-lisp-reader map-err site MUST construct its
1475        // `Err(DialetoError::…)` through the substrate-primitive
1476        // [`DialetoError::leitura`] ctor rather than through an
1477        // open-coded tuple-newtype wrap. Pre-lift the wire-up hand-rolled
1478        // a `Self::Leitura(e.to_string())` block with no compile-time
1479        // link back to the substrate primitive; a future accidental
1480        // rebrand of the ctor body (an added `.trim()` on the reader
1481        // reason, a per-arm constant prefix like `"tatara-lisp:"`, a
1482        // widening of the payload into a `(String, usize)` tuple
1483        // carrying a caret offset) would then silently split the two
1484        // paths — the ctor consumers pick up the new shape, the
1485        // open-coded wire-up does not. Pinning byte-equality between
1486        // the observed `Err` and the ctor-constructed `Err` refuses
1487        // that split at caixa-core build time rather than surfacing far
1488        // from the wire-up commit as a downstream diagnostic-consumer
1489        // split. Peer of the sibling
1490        // `classify_form_wrong_head_routes_through_cabeca_errada_ctor`
1491        // pin above on the same [`DialetoError`] envelope's wrong-head
1492        // fallthrough axis.
1493        //
1494        // The malformed sources below each name a distinct
1495        // tatara-lisp-reader failure shape (unclosed paren, stray close
1496        // paren, unterminated string), so together they sweep the
1497        // reader's rejection surface rather than pinning against one
1498        // specific error message the reader upstream is free to reword.
1499        for src in [
1500            "(defcaixa :nome \"x\"",
1501            "defcaixa :nome \"x\")",
1502            "(defcaixa :nome \"unterminated",
1503        ] {
1504            let observed = classify(src);
1505            let Err(DialetoError::Leitura(reason)) = observed.clone() else {
1506                panic!(
1507                    "classify({src:?}) must return the Leitura arm — got \
1508                     {observed:?}"
1509                );
1510            };
1511            let via_ctor: Result<CaixaDialeto, DialetoError> =
1512                Err(DialetoError::leitura(reason.clone()));
1513            assert_eq!(
1514                observed, via_ctor,
1515                "classify({src:?}) must return the same Err shape as \
1516                 DialetoError::leitura({reason:?}) — a drift here means \
1517                 the wire-up de-lifted its tatara-lisp-reader fallthrough \
1518                 arm off the substrate primitive"
1519            );
1520        }
1521    }
1522
1523    #[test]
1524    fn caixa_dialeto_is_molde_family_routes_through_is_variant_derived_predicates() {
1525        // Byte-parity pin on the post-lift [`CaixaDialeto::is_molde_family`]
1526        // convergence: for every arm in [`CaixaDialeto::ALL`], the typed
1527        // predicate must byte-equal the direct
1528        // `self.is_molde() || self.is_molde_posicional()` composition of
1529        // the two derived per-arm predicates. Pre-lift the predicate
1530        // hand-rolled `matches!(self, Self::Molde | Self::MoldePosicional)`
1531        // with no compile-time link back to the closed-set typed dispatch;
1532        // post-lift it routes through the derived predicates so a future
1533        // arm rename or `#[is_variant(name = "…")]` override lands at
1534        // exactly one dispatch on the substrate primitive. Pinning the
1535        // byte-equality here refuses a future accidental split between
1536        // the composed predicate and the paired derived predicates
1537        // (a hand-rolled shadow `impl` that overrides one path but not
1538        // the other, an accidental rebrand of `is_molde_family`'s body
1539        // back to the pre-lift `matches!` form) at caixa-core build time.
1540        for &d in CaixaDialeto::ALL {
1541            let via_derived = d.is_molde() || d.is_molde_posicional();
1542            let via_is_molde_family = d.is_molde_family();
1543            assert_eq!(
1544                via_is_molde_family, via_derived,
1545                "CaixaDialeto::{d:?}.is_molde_family() ({via_is_molde_family}) \
1546                 must byte-equal the composed derived predicates \
1547                 is_molde() || is_molde_posicional() ({via_derived}) — a \
1548                 split between the composed predicate and its derived \
1549                 building blocks would let a future arm rename land at one \
1550                 path and drift at the other, which is exactly the drift \
1551                 the IsVariant lift refuses"
1552            );
1553        }
1554    }
1555}