caixa-core 0.1.22

Manifest types, layout invariants, and version contract for the caixa tatara-lisp package system.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! `defcaixa` is spoken by two unrelated declarations. This module makes that
//! a **typed fact** instead of an anonymous parse failure.
//!
//! # The finding
//!
//! Measured 2026-07-31 over the pleme-io org checkout (270 `caixa.lisp` /
//! `*.caixa.lisp` files found with `rg --no-ignore`; a bare `rg` from the org
//! root returns 0, which is how this stayed invisible), the corpus splits into
//! two schemas that share zero required slots:
//!
//! * [`CaixaDialeto::Pacote`] — this crate's [`crate::Caixa`]. `:nome
//!   :versao :kind :deps :bibliotecas :exe :servicos` + the supervisor/mesh
//!   slots. It declares a **tatara-lisp package**: the thing `feira` resolves,
//!   builds, links and publishes.
//! * [`CaixaDialeto::Molde`] — `:name :kind :ecosystem :package {…} :workflows
//!   […] :ci-config {…} :files […]`. It declares a **repo's generated
//!   surface**: which foreign ecosystem (rust / go / python / …), that
//!   ecosystem's own package metadata, the CI shims to emit, and byte-captured
//!   file bodies. Read by `pleme-doc-gen`, never by `feira`.
//!
//! `:package`, `:ecosystem`, `:supports` and `:profile` have no counterpart in
//! [`crate::Caixa`] at all — the theory doc's own D4 note records the same
//! thing: those manifests "are authored against a schema that does not exist in
//! Rust". They are not two spellings of one declaration. They are two domains
//! that collided on one word, because *caixa* names a box and both are boxes.
//!
//! # Why this is not a bug report about broken files
//!
//! The Molde-dialect files are not malformed. They are correct inputs to their
//! own consumer, and nothing in the shipped `feira` reads them, so nothing is
//! failing today. The hazard is **latent and certain**: any new declarative
//! surface written against "a `.caixa.lisp` is a [`crate::Caixa`]" meets a
//! corpus where that is false for the large majority of files, and gets a flat
//! unknown-keyword rejection that reads as "this manifest is broken" rather
//! than "this manifest is not yours".
//!
//! # What this module does about it
//!
//! [`classify`] is total: every `(defcaixa …)` form lands in exactly one
//! [`CaixaDialeto`], including [`CaixaDialeto::Desconhecido`] for one that
//! matches neither. [`crate::Caixa::from_lisp`] runs it first, so a foreign
//! dialect is [`crate::ManifestError::DialetoEstrangeiro`] — an error that
//! names the dialect it found and the consumer that speaks it — rather than an
//! unknown-kwarg error indistinguishable from a typo.
//!
//! Tier-honest: this is **parse-time rejection with a named cause**, not
//! unrepresentability. A caller that ignores the `Err` still gets nothing
//! useful; what it can no longer do is mistake "wrong dialect" for "bad file".

use tatara_lisp::{Atom, Sexp};

/// Which `(defcaixa …)` declaration a source speaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CaixaDialeto {
    /// This crate's [`crate::Caixa`] — a tatara-lisp package manifest.
    /// Keyword-argument form headed by `:nome`.
    Pacote,
    /// `pleme-doc-gen`'s repo-surface declaration, keyword-argument form
    /// headed by `:name` (plus `:ecosystem` / `:package`).
    Molde,
    /// The same declaration as [`Self::Molde`], written with the package name
    /// as a bare positional symbol — `(defcaixa todoku-go :kind :Biblioteca
    /// :ecosystem :go …)`. `pleme-doc-gen`'s parser reads the first token
    /// after the head as the name, so this is one arity of one declaration,
    /// not a third schema.
    MoldePosicional,
    /// A `(defcaixa …)` form matching neither. Kept as a variant rather than
    /// an error so [`classify`] is total and a census can COUNT the residue —
    /// a classifier that threw here would report "0 unknown" by construction.
    Desconhecido,
}

impl CaixaDialeto {
    /// Exhaustive iteration surface for every consumer that walks the
    /// closed four-arm [`CaixaDialeto`] discriminator set — the
    /// [`feira dialeto`](../../caixa_feira/cmd/dialeto/index.html)
    /// census counter's per-arm accept-set, a future
    /// `feira dialeto --list-dialects` CLI listing of the accepted
    /// classifications, a future M4 `mesh.pleme.io/v1alpha1/Manifesto`
    /// CR materializer's admission-webhook rejection body naming the
    /// accepted-dialect set, any future census-report shape probe that
    /// sweeps every arm to compute per-arm coverage. A future arm
    /// addition (a fifth dialect the [`crate::dialeto`] module doc's
    /// "third dialect" hazard actualises — the module explicitly frames
    /// its purpose as "what stops a third dialect appearing", and this
    /// slice is the substrate-side answer: the arm-set is one edit and
    /// every consumer picks up the new entry by construction) extends
    /// this slice as one edit and every downstream consumer picks up
    /// the new entry through the shared iteration; the compiler-checked
    /// exhaustiveness on the sibling method `match` arms
    /// ([`Self::palavra_canonica`] / [`Self::consumidor`] /
    /// [`Self::descricao`] / [`std::fmt::Display`]) is the build-time
    /// guarantee that no arm forgets to grow.
    ///
    /// Peer of the sibling closed-set typed enums'
    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
    /// [`crate::dep::DepList::ALL`] (45ee563) /
    /// [`crate::supervisor::RestartStrategy::ALL`] (4eec29c) /
    /// [`crate::supervisor::RestartPolicy::ALL`] (dd32ccf)
    /// exhaustive-iteration surfaces — the seventh closed-set typed
    /// enum on the caixa surface to converge onto the same
    /// one-canonical-arm-list-per-enum discipline, and the first
    /// dialect-classification axis (as distinct from an OTP-shape M2
    /// slot or an M3 mesh slot) to reach it. Order matches variant
    /// declaration order verbatim (`Pacote` → `Molde` →
    /// `MoldePosicional` → `Desconhecido`) so the slice is the
    /// canonical ordering every listing / rendering consumer defers to.
    pub const ALL: &'static [Self] = &[
        Self::Pacote,
        Self::Molde,
        Self::MoldePosicional,
        Self::Desconhecido,
    ];

    /// The keyword an author should write for this dialect, once the
    /// migration named in [`Self::consumidor`] completes.
    #[must_use]
    pub const fn palavra_canonica(self) -> &'static str {
        match self {
            Self::Pacote => "defcaixa",
            Self::Molde | Self::MoldePosicional => "defmolde",
            Self::Desconhecido => "?",
        }
    }

    /// Who reads this dialect.
    #[must_use]
    pub const fn consumidor(self) -> &'static str {
        match self {
            Self::Pacote => "caixa-core / feira",
            Self::Molde | Self::MoldePosicional => "pleme-doc-gen",
            Self::Desconhecido => "nobody known",
        }
    }

    /// A one-line description for a census row or an error message.
    #[must_use]
    pub const fn descricao(self) -> &'static str {
        match self {
            Self::Pacote => "tatara-lisp package manifest (:nome :versao :kind :deps …)",
            Self::Molde => "repo-surface declaration (:name :ecosystem :package {…} …)",
            Self::MoldePosicional => {
                "repo-surface declaration, positional name (defcaixa <nome> :kind …)"
            }
            Self::Desconhecido => "unrecognised — matches no known defcaixa schema",
        }
    }
}

impl std::fmt::Display for CaixaDialeto {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Pacote => "Pacote",
            Self::Molde => "Molde",
            Self::MoldePosicional => "MoldePosicional",
            Self::Desconhecido => "Desconhecido",
        })
    }
}

/// A source that is not a `(defcaixa …)` / `(defmolde …)` form at all.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum DialetoError {
    #[error("source has no top-level form")]
    Vazio,
    #[error("top-level form is not a list — a manifest is `(defcaixa …)`")]
    NaoEhLista,
    #[error(
        "top-level form is headed by `{encontrado}`, not `defcaixa` or `defmolde` \
         (a manifest's first form must be the declaration itself)"
    )]
    CabecaErrada { encontrado: String },
    #[error("manifest does not parse as tatara-lisp: {0}")]
    Leitura(String),
}

/// Classify a manifest source without committing to either schema.
///
/// Deliberately reads only the head symbol and the set of top-level keywords —
/// enough to route, never enough to half-parse. A classifier that started
/// validating would grow into a third parser, which is the shape of the problem
/// it exists to name.
///
/// # Errors
/// [`DialetoError`] when the source is not a manifest declaration at all.
pub fn classify(src: &str) -> Result<CaixaDialeto, DialetoError> {
    let forms = tatara_lisp::read(src).map_err(|e| DialetoError::Leitura(e.to_string()))?;
    let first = forms.first().ok_or(DialetoError::Vazio)?;
    classify_form(first)
}

/// [`classify`] over an already-read form.
///
/// # Errors
/// [`DialetoError`] when the form is not a manifest declaration.
pub fn classify_form(form: &Sexp) -> Result<CaixaDialeto, DialetoError> {
    let list = form.as_list().ok_or(DialetoError::NaoEhLista)?;
    let head = list
        .first()
        .and_then(Sexp::as_symbol)
        .ok_or(DialetoError::NaoEhLista)?;

    match head {
        // `defmolde` is unambiguous by construction — it exists precisely so a
        // consumer never has to infer which declaration it holds. Both arities
        // are the same declaration; the positional one keeps its own variant
        // only so a census can report the split.
        "defmolde" => {
            return Ok(if starts_with_positional_name(&list[1..]) {
                CaixaDialeto::MoldePosicional
            } else {
                CaixaDialeto::Molde
            });
        }
        "defcaixa" => {}
        other => {
            return Err(DialetoError::CabecaErrada {
                encontrado: other.to_string(),
            });
        }
    }

    let args = &list[1..];

    // `(defcaixa <symbol> :kind … :ecosystem …)`. Only the Molde dialect has a
    // positional arity; `Caixa` is keyword-only, so a leading bare symbol
    // settles it without looking further.
    if starts_with_positional_name(args) {
        return Ok(CaixaDialeto::MoldePosicional);
    }

    let keys = top_level_keywords(args);
    let has = |k: &str| keys.iter().any(|s| s == k);

    // Order matters, and it is not arbitrary: `:nome` and `:name` are the two
    // required head slots and no file in the measured corpus carries both.
    // Checking them FIRST means the decision rests on the one slot each schema
    // makes mandatory, rather than on optional evidence like `:ecosystem`.
    if has("nome") {
        return Ok(CaixaDialeto::Pacote);
    }
    if has("name") || has("ecosystem") || has("package") {
        return Ok(CaixaDialeto::Molde);
    }
    Ok(CaixaDialeto::Desconhecido)
}

/// True when the first argument is a bare symbol rather than a keyword — the
/// positional-name arity.
fn starts_with_positional_name(args: &[Sexp]) -> bool {
    matches!(args.first(), Some(Sexp::Atom(Atom::Symbol(_))))
}

/// The top-level keyword names (without the leading `:`) of a kwarg list.
///
/// Steps in pairs so a keyword appearing as a VALUE — `:kind :Biblioteca`, or a
/// nested `(:nome "dep" :versao "^0.1")` inside `:deps` — is never counted as a
/// top-level slot. A naive scan for `:nome` anywhere in the source classifies
/// every Molde manifest with a `:deps` list as a Pacote.
fn top_level_keywords(args: &[Sexp]) -> Vec<String> {
    let mut out = Vec::new();
    let mut i = 0;
    while i < args.len() {
        if let Sexp::Atom(Atom::Keyword(k)) = &args[i] {
            out.push(k.clone());
            i += 2;
        } else {
            i += 1;
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    const PACOTE: &str = r#"
      (defcaixa
        :nome   "checkout"
        :versao "0.1.0"
        :kind   Servico
        :deps   ((:nome "caixa-teia" :versao "^0.1")))
    "#;

    const MOLDE: &str = r#"
      (defcaixa
        :name "base64"
        :kind :Biblioteca
        :ecosystem :rust-single-crate
        :package {:name "base64" :version "0.22.1"}
        :workflows [:auto-release])
    "#;

    const MOLDE_POSICIONAL: &str = r#"
      (defcaixa todoku-go
        :kind :Biblioteca
        :ecosystem :go
        :package {:name "todoku-go" :version "0.3.0"})
    "#;

    #[test]
    fn the_package_dialect_is_recognised() {
        assert_eq!(classify(PACOTE), Ok(CaixaDialeto::Pacote));
    }

    #[test]
    fn the_repo_surface_dialect_is_recognised() {
        assert_eq!(classify(MOLDE), Ok(CaixaDialeto::Molde));
    }

    #[test]
    fn the_positional_arity_is_recognised() {
        assert_eq!(
            classify(MOLDE_POSICIONAL),
            Ok(CaixaDialeto::MoldePosicional)
        );
    }

    #[test]
    fn defmolde_classifies_without_inference() {
        // The whole point of the new keyword: no schema sniffing required.
        let src = r#"(defmolde :name "x" :kind :Biblioteca :ecosystem :go)"#;
        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
        let pos = r"(defmolde todoku-go :kind :Biblioteca :ecosystem :go)";
        assert_eq!(classify(pos), Ok(CaixaDialeto::MoldePosicional));
    }

    #[test]
    fn a_nested_nome_does_not_make_a_repo_surface_look_like_a_package() {
        // The exact failure a substring scan produces: `:deps ((:nome …))`
        // contains `:nome`, but not as a top-level slot.
        let src = r#"
          (defcaixa
            :name "x"
            :ecosystem :rust-single-crate
            :deps ((:nome "inner" :versao "^0.1")))
        "#;
        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
    }

    #[test]
    fn a_keyword_in_value_position_is_not_a_slot() {
        // `:kind :Biblioteca` — the value is itself a keyword. Stepping one at
        // a time would read `:Biblioteca` as a top-level slot.
        let src = r#"(defcaixa :kind :Biblioteca :name "x")"#;
        assert_eq!(classify(src), Ok(CaixaDialeto::Molde));
    }

    #[test]
    fn an_unrecognised_defcaixa_is_reported_not_guessed() {
        let src = r#"(defcaixa :licenca "MIT")"#;
        assert_eq!(classify(src), Ok(CaixaDialeto::Desconhecido));
    }

    #[test]
    fn a_form_that_is_not_a_manifest_is_an_error_not_a_dialect() {
        assert_eq!(
            classify("(defflake :nome \"x\")"),
            Err(DialetoError::CabecaErrada {
                encontrado: "defflake".into()
            })
        );
        assert_eq!(classify(""), Err(DialetoError::Vazio));
    }

    #[test]
    fn every_dialect_names_its_consumer_and_its_canonical_keyword() {
        // Guards the routing table itself: a new variant added without an arm
        // here is a compile error in the match, and a variant that claims
        // `defcaixa` while being read by pleme-doc-gen would re-open the
        // collision this module closes. Sweeps [`CaixaDialeto::ALL`] rather
        // than the pre-lift open-coded four-arm literal list — a future arm
        // addition extends the slice as one edit and this pin picks it up
        // by construction.
        for &d in CaixaDialeto::ALL {
            assert!(!d.descricao().is_empty(), "{d}");
            assert!(!d.consumidor().is_empty(), "{d}");
        }
        assert_eq!(CaixaDialeto::Pacote.palavra_canonica(), "defcaixa");
        assert_eq!(CaixaDialeto::Molde.palavra_canonica(), "defmolde");
        assert_ne!(
            CaixaDialeto::Pacote.palavra_canonica(),
            CaixaDialeto::Molde.palavra_canonica(),
            "the two dialects must not share a canonical keyword — that IS the defect"
        );
    }

    #[test]
    fn caixa_dialeto_all_enumerates_every_variant_exactly_once() {
        // Three-legged exhaustiveness pin, peer of the sibling
        // `caixa_kind_all_enumerates_every_variant_exactly_once`
        // (caixa-core/src/kind.rs) /
        // `restart_strategy_all_enumerates_every_variant_exactly_once`
        // (caixa-core/src/supervisor.rs) shape.
        //
        // 1. arm-count invariant: `ALL.len()` matches the declared arm
        //    count (four — a fifth arm added without extending `ALL`
        //    fails this pin at caixa-core test time);
        // 2. pairwise-distinctness invariant: every variant appears at
        //    most once in the slice (a duplicate arm would silently
        //    double-count in the census consumer, so the pin rejects
        //    duplicates outright);
        // 3. coverage invariant: every literal `CaixaDialeto::X` is in
        //    the slice (the compiler-checked exhaustiveness on the peer
        //    per-arm `match self` in the accessors keeps the enum arm
        //    set and the `ALL` slice mutually aligned).
        assert_eq!(
            CaixaDialeto::ALL.len(),
            4,
            "ALL must list every arm exactly once; a fifth arm added \
             without extending ALL fails this pin — extend ALL alongside \
             the new variant"
        );

        let mut seen: Vec<CaixaDialeto> = Vec::new();
        for &d in CaixaDialeto::ALL {
            assert!(
                !seen.contains(&d),
                "ALL contains a duplicate arm: {d}. Every variant appears \
                 exactly once — a duplicate would double-count in every \
                 iteration consumer"
            );
            seen.push(d);
        }

        // Coverage: exhaustively assert every literal variant is somewhere
        // in the slice. Written as an exhaustive `match` so a future arm
        // addition fails to compile here (missing match arm) until the
        // corresponding `assert` is added — the compiler enforces the pin's
        // completeness rather than a hand-maintained variant list.
        for variant in [
            CaixaDialeto::Pacote,
            CaixaDialeto::Molde,
            CaixaDialeto::MoldePosicional,
            CaixaDialeto::Desconhecido,
        ] {
            let coverage_probe = match variant {
                CaixaDialeto::Pacote
                | CaixaDialeto::Molde
                | CaixaDialeto::MoldePosicional
                | CaixaDialeto::Desconhecido => variant,
            };
            assert!(
                CaixaDialeto::ALL.contains(&coverage_probe),
                "ALL is missing variant {coverage_probe} — extend the slice"
            );
        }
    }

    #[test]
    fn caixa_dialeto_all_is_const_and_matches_iteration_count() {
        // Pins the const-ness of the slice at const-fold time. A future
        // change that promoted `ALL` to a non-const initializer (a lazy-
        // static, a runtime-computed Vec) would fail to compile here —
        // the pin locks in the compile-time-known iteration surface
        // every consumer builds against. Peer of the sibling
        // `caixa_kind_all_is_const_and_matches_iteration_count` (kind.rs)
        // / `restart_strategy_all_is_const_and_matches_iteration_count`
        // (supervisor.rs) shape.
        const ALL: &[CaixaDialeto] = CaixaDialeto::ALL;
        assert_eq!(ALL.len(), CaixaDialeto::ALL.len());
        // Sweep the iterator without collapsing to `.len()` so a future
        // change to `ALL`'s carrier that decouples `.len()` from the
        // iteration count (a lazy-computed shape, an alias `impl Iterator`
        // return, a wrapper newtype) still passes here iff the two agree
        // arm-for-arm; the `#[allow]` opts this local pin out of the
        // clippy `iter_count` collapse that would defeat the intent.
        #[allow(clippy::iter_count)]
        let iterated = ALL.iter().count();
        assert_eq!(iterated, CaixaDialeto::ALL.len());
    }

    #[test]
    fn caixa_dialeto_all_covers_every_variant_by_display_probe() {
        // Fanning `Display` over the slice sweeps the paired accessors
        // ([`CaixaDialeto::palavra_canonica`] / [`CaixaDialeto::consumidor`]
        // / [`CaixaDialeto::descricao`]) at every arm — every returned
        // byte-string is non-empty (the accessors' contract). A future
        // arm added without extending its per-arm `match self` return
        // would compile-fail at the accessor call inside the loop;
        // together with the `ALL.len() == 4` pin above, this locks the
        // accessor arm-set and the `ALL` slice mutually.
        for &d in CaixaDialeto::ALL {
            let display_form = d.to_string();
            assert!(
                !display_form.is_empty(),
                "Display must render a non-empty byte-string for every \
                 arm; empty: {d:?}"
            );
            // Consumidor / descricao / palavra-canonica must each surface
            // a non-empty scalar; every downstream diagnostic consumer
            // reaches through these accessors.
            assert!(!d.palavra_canonica().is_empty(), "{d}");
            assert!(!d.consumidor().is_empty(), "{d}");
            assert!(!d.descricao().is_empty(), "{d}");
        }
    }
}