caixa_core/manifest.rs
1use std::path::{Path, PathBuf};
2
3use serde::{Deserialize, Serialize};
4use tatara_lisp::DeriveTataraDomain;
5
6use thiserror::Error;
7
8use crate::{
9 CaixaKind, Dep,
10 behavior::BehaviorSpec,
11 dep::DepError,
12 limits::LimitsSpec,
13 render::{
14 PathShapeViolation, is_computeunit_yaml_extension, is_git_repo_url, is_lisp_extension,
15 is_sandboxed_relative_path,
16 },
17 supervisor::SupervisorSpec,
18 upgrade::UpgradeFromEntry,
19};
20
21/// Top-level manifest for a caixa (a tatara-lisp package).
22///
23/// Authored as `caixa.lisp`:
24///
25/// ```lisp
26/// (defcaixa
27/// :nome "pangea-tatara-aws"
28/// :versao "0.1.0"
29/// :kind Biblioteca
30/// :edicao "2026"
31/// :descricao "AWS provider caixa for tatara-lisp"
32/// :repositorio "github:pleme-io/pangea-tatara-aws"
33/// :licenca "MIT"
34/// :autores ("pleme-io")
35/// :etiquetas ("iac" "aws" "pangea")
36/// :deps ((:nome "caixa-teia" :versao "^0.1")
37/// (:nome "iac-forge-ir" :versao "^0.5"))
38/// :deps-dev ((:nome "tatara-check" :versao "*"))
39/// :bibliotecas ("lib/pangea-tatara-aws.lisp"))
40/// ```
41///
42/// Because `Caixa` derives [`tatara_lisp::domain::TataraDomain`], the manifest
43/// is parsed directly by the tatara-lisp compiler — an ill-formed manifest is
44/// a compile error, not a runtime error.
45#[derive(DeriveTataraDomain, Serialize, Deserialize, Debug, Clone, PartialEq)]
46#[serde(rename_all = "camelCase")]
47#[tatara(keyword = "defcaixa")]
48pub struct Caixa {
49 /// Package name — the canonical string used in `:deps`, the registry, and
50 /// the default lib/exe entry names.
51 pub nome: String,
52
53 /// Package version — a semver literal like `"0.1.0"`. Parsed lazily via
54 /// [`crate::CaixaVersion::parse`].
55 pub versao: String,
56
57 /// What this caixa produces. See [`CaixaKind`].
58 pub kind: CaixaKind,
59
60 /// Language edition — determines macro surface + compatibility flags.
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub edicao: Option<String>,
63
64 /// Free-form description shown in the registry listing.
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub descricao: Option<String>,
67
68 /// Homepage or repo URL.
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub repositorio: Option<String>,
71
72 /// SPDX license expression — `"MIT"`, `"Apache-2.0 OR MIT"`, etc.
73 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub licenca: Option<String>,
75
76 /// Authors — free-form strings.
77 #[serde(default)]
78 pub autores: Vec<String>,
79
80 /// Topical tags used for registry search.
81 #[serde(default)]
82 pub etiquetas: Vec<String>,
83
84 /// Runtime dependencies.
85 #[serde(default)]
86 pub deps: Vec<Dep>,
87
88 /// Development-only dependencies (tests, lint, bench).
89 #[serde(default)]
90 pub deps_dev: Vec<Dep>,
91
92 /// Paths to executable entry points (relative to the package root).
93 /// Required when `:kind Binario`.
94 #[serde(default)]
95 pub exe: Vec<String>,
96
97 /// Paths to library entry points (relative to the package root).
98 /// First entry is the canonical `lib/<nome>.lisp`; when omitted under
99 /// `:kind Biblioteca`, the layout check expects `lib/<nome>.lisp`.
100 #[serde(default)]
101 pub bibliotecas: Vec<String>,
102
103 /// Paths to service manifests (relative to the package root).
104 /// Required when `:kind Servico`.
105 #[serde(default)]
106 pub servicos: Vec<String>,
107
108 // ── M2 typed-substrate extensions per theory/ABSORPTION-ROADMAP.md ──
109 //
110 // All four are optional + default to "absent"; existing caixas
111 // round-trip unchanged. Each maps onto a prior-art primitive named
112 // in theory/INSPIRATIONS.md:
113 //
114 // :limits — Lunatic per-process limits (§III.1)
115 // :behavior — OTP gen_server callbacks (§II.3)
116 // :upgrade-from — OTP appup migration (§II.4)
117 // :estrategia — OTP supervisor strategy (§II.2 + §III.2)
118 // :children — OTP supervisor children (§II.2 + §III.2)
119 //
120 // The supervisor slots are flat on Caixa (vs nested under a
121 // SupervisorSpec sub-form) to keep tatara-lisp authoring at one
122 // level of nesting; SupervisorSpec exists for validation +
123 // composition convenience (`Caixa::supervisor_view()`).
124 /// Lunatic-style per-process resource limits. None = unbounded.
125 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub limits: Option<LimitsSpec>,
127
128 /// OTP-shaped behavior callbacks for Servico-kind caixas.
129 /// Authored as `(:on-init "..." :on-call "..." …)`.
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub behavior: Option<BehaviorSpec>,
132
133 /// OTP appup — declarative upgrade instructions per prior version.
134 /// Empty list = no hot-upgrade path declared (caller falls back to
135 /// `:Restart` strategy).
136 #[serde(default)]
137 pub upgrade_from: Vec<UpgradeFromEntry>,
138
139 /// OTP supervisor strategy. Required when `:kind Supervisor`;
140 /// ignored otherwise.
141 #[serde(default, skip_serializing_if = "Option::is_none")]
142 pub estrategia: Option<crate::supervisor::RestartStrategy>,
143
144 /// Max restarts before the supervisor itself fails. Defaults via
145 /// SupervisorSpec at validation time.
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub max_restarts: Option<u32>,
148
149 /// Sliding window for `max_restarts`. Authored as a duration
150 /// string (`"60s"`, `"5m"`).
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub restart_window: Option<String>,
153
154 /// Static children of a supervisor. Required for OneForOne /
155 /// OneForAll / RestForOne; must be empty for SimpleOneForOne.
156 #[serde(default)]
157 pub children: Vec<crate::supervisor::ChildSpec>,
158
159 // ── M3 Aplicacao slots (theory/MESH-COMPOSITION.md) ─────────────────
160 //
161 // Required when :kind Aplicacao; ignored otherwise.
162 // Composed into a typed AplicacaoSpec via Caixa::aplicacao_view().
163 /// Member Servicos that make up this Aplicacao. Each is a
164 /// caixa-name + version-constraint pair. Required for Aplicacao.
165 #[serde(default)]
166 pub membros: Vec<crate::aplicacao::Membro>,
167
168 /// WIT-typed inter-Servico contracts. Each `:de` and `:para`
169 /// must reference a name in `:membros`.
170 #[serde(default)]
171 pub contratos: Vec<crate::aplicacao::WitContract>,
172
173 /// Mesh-level policies (timeout, retries, circuit-breaker, mTLS,
174 /// rate-limit). Apply to every contrato unless overridden per-edge
175 /// in M4.
176 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub politicas: Option<crate::aplicacao::MeshPolicy>,
178
179 /// Placement strategy across the cluster fleet
180 /// (single-node | replicated | sharded).
181 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub placement: Option<crate::aplicacao::Placement>,
183
184 /// External entry point — gateway / ingress shape. Optional;
185 /// only for public Aplicacaos.
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub entrada: Option<crate::aplicacao::Entrada>,
188
189 // ── Acao slot (CANTEIRO §7.1-C) ──────────────────────────────────────
190 //
191 // Required when :kind Acao; ignored otherwise (mirrors the M2/
192 // supervisor-tree/M3 slot triads above — a declared-but-foreign `:ci`
193 // is a `LayoutError::CiOnNonAcao` build error, not a silent drop).
194 /// Typed CI run — a repo's CI run as a set of typed nodes + their
195 /// dependency edges. Required for `:kind Acao`; validated (not
196 /// rendered) by the `caixa-actions` renderer via
197 /// `canteiro_types::decompose`. See `caixa-actions`' crate docs for
198 /// the M0 validate-only contract.
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub ci: Option<canteiro_types::CiRun>,
201}
202
203/// Why reading a manifest into a [`Caixa`] failed.
204///
205/// Split from [`ManifestError`] (which reports a *parsed* manifest that is
206/// semantically wrong) because the two answer different questions, and the
207/// distinction is the whole point of this type: `ManifestError` means "your
208/// caixa is wrong", `LeituraError::DialetoEstrangeiro` means "this file is not
209/// a caixa".
210#[derive(Debug, thiserror::Error)]
211pub enum LeituraError {
212 /// The source is not readable as a `(defcaixa …)` package manifest — bad
213 /// syntax, a wrong head symbol, an unknown or mistyped slot.
214 ///
215 /// `#[source]`, not `#[error(transparent)]`. Transparent delegates
216 /// `source()` past the inner error to ITS source, which drops the
217 /// `LispError` off the cause chain — and `feira`'s
218 /// `load_caixa_parse_error_preserves_underlying_lisp_error_on_chain`
219 /// pins that a caller can `downcast_ref::<tatara_lisp::LispError>()`
220 /// through an anyhow context to read the typed payload. That pin caught
221 /// this exact regression when the variant first landed transparent.
222 #[error("{0}")]
223 Leitura(
224 #[source]
225 #[from]
226 tatara_lisp::LispError,
227 ),
228
229 /// The source IS a well-formed `(defcaixa …)` form, but of a different
230 /// declaration than this crate's.
231 ///
232 /// The variant that did not exist before, and whose absence is the defect.
233 /// A `(defcaixa :name "x" :ecosystem :go …)` used to reach the derive's
234 /// `parse_kwargs_strict` and come back as an unknown-keyword rejection —
235 /// byte-identical in shape to a typo in a real manifest. Measured over the
236 /// org checkout on 2026-07-31, that shape is the MAJORITY of the corpus, so
237 /// the confusing error was also the common one.
238 ///
239 /// Carrying the dialect means a consumer can branch on "not mine" without
240 /// re-parsing, and a census can count it. Every user-facing byte-string
241 /// (canonical keyword, one-line description, consuming crate) is a
242 /// projection of [`crate::dialeto::CaixaDialeto`] — the variant stores the
243 /// typed dialect and the `#[error]` template calls
244 /// [`CaixaDialeto::palavra_canonica`] /
245 /// [`CaixaDialeto::descricao`] / [`CaixaDialeto::consumidor`] on it, so
246 /// the three axes cannot silently diverge from the classification. Prior
247 /// to this closure the variant carried each accessor's return value as a
248 /// stored `&'static str` snapshot alongside `dialeto`, and the sole
249 /// constructor at [`Caixa::from_lisp`] filled all four fields — a caller
250 /// could construct `DialetoEstrangeiro { dialeto: Molde,
251 /// palavra_canonica: "defcaixa", … }` and every downstream consumer
252 /// (Display, ad-hoc audit, future JSON serialization) would silently
253 /// disagree with `dialeto.palavra_canonica() == "defmolde"`. The typed
254 /// enum owns the projections; the variant only carries the axis.
255 #[error(
256 "this is a `{palavra}` declaration ({desc}), read by \
257 {cons} — not a caixa-core package manifest. `defcaixa` is the \
258 tatara-lisp package manifest (`:nome :versao :kind :deps …`); the two \
259 are different declarations that shared one keyword until 2026-07-31",
260 palavra = dialeto.palavra_canonica(),
261 desc = dialeto.descricao(),
262 cons = dialeto.consumidor()
263 )]
264 DialetoEstrangeiro {
265 /// Which declaration this actually is. Sole authoritative axis;
266 /// every user-facing projection routes through
267 /// [`crate::dialeto::CaixaDialeto`]'s typed accessors so the four
268 /// axes cannot silently disagree.
269 dialeto: crate::dialeto::CaixaDialeto,
270 },
271
272 /// Not a manifest declaration at all.
273 #[error(transparent)]
274 Dialeto(#[from] crate::dialeto::DialetoError),
275}
276
277impl Caixa {
278 /// Parse a `caixa.lisp` source string to a typed `Caixa`.
279 ///
280 /// Classifies the dialect **before** parsing. A `(defcaixa …)` of another
281 /// declaration is [`LeituraError::DialetoEstrangeiro`], naming what it is
282 /// and who reads it, instead of an unknown-keyword rejection that reads as
283 /// "your manifest is broken".
284 ///
285 /// The ordering is load-bearing. Handing a foreign dialect to the derive
286 /// first and interpreting the failure afterwards would mean guessing from
287 /// an error message, and the guess would be wrong for every file whose
288 /// first unknown slot happens to be one both schemas could plausibly carry.
289 pub fn from_lisp(src: &str) -> Result<Self, LeituraError> {
290 use tatara_lisp::domain::TataraDomain;
291 let forms = tatara_lisp::read(src).map_err(LeituraError::Leitura)?;
292 let first = forms.first().ok_or(crate::dialeto::DialetoError::Vazio)?;
293
294 // Route the foreign-dialect rejection gate through the lifted
295 // [`crate::dialeto::CaixaDialeto::is_molde_family`] (e9d2315)
296 // typed predicate rather than the pre-lift hand-rolled three-arm
297 // `match { Pacote => {}, Desconhecido => {}, foreign => Err(…) }`
298 // literal — the `defmolde` declaration-family partition (the two-
299 // arity closure of [`crate::dialeto::CaixaDialeto::Molde`] and
300 // [`crate::dialeto::CaixaDialeto::MoldePosicional`], the two arms
301 // whose sibling [`crate::dialeto::CaixaDialeto::palavra_canonica`]
302 // projection already collapses onto `"defmolde"` and whose sibling
303 // [`crate::dialeto::CaixaDialeto::consumidor`] projection already
304 // collapses onto `"pleme-doc-gen"`) resolves through one dispatch
305 // on the substrate primitive. `Pacote` (the tatara-lisp package
306 // manifest this derive can parse) and `Desconhecido` (deliberately
307 // falls through to the derive rather than short-circuiting: a
308 // `(defcaixa …)` matching neither schema is most likely a genuine
309 // package manifest with a typo in `:nome`, and the derive's
310 // diagnostic — which names the offending keyword and suggests the
311 // nearest slot — is far better than anything this classifier
312 // could say) both return `false` from `is_molde_family()` and fall
313 // through to the derive. Only the typed dialect flows into the
314 // error — the three user-facing projections (canonical keyword,
315 // description, consumer) are read at Display time through
316 // [`crate::dialeto::CaixaDialeto`]'s own accessors, so the
317 // variant cannot carry a snapshot that drifts from
318 // [`crate::dialeto::CaixaDialeto::palavra_canonica`] /
319 // `descricao` / `consumidor`. A future fifth dialect the
320 // [`crate::dialeto`] module doc's "third dialect" hazard
321 // actualises that belongs to the `defmolde` family lands one
322 // match arm at [`crate::dialeto::CaixaDialeto::is_molde_family`]
323 // and this gate picks up the new arm by construction — the pre-
324 // lift wildcard `foreign =>` was compile-time-anonymous and would
325 // silently absorb any hypothetical fifth `defcaixa`-family arm as
326 // foreign; routing the partition through the typed predicate
327 // closes both drift surfaces.
328 let dialeto = crate::dialeto::classify_form(first)?;
329 if dialeto.is_molde_family() {
330 return Err(LeituraError::DialetoEstrangeiro { dialeto });
331 }
332
333 Self::compile_from_sexp(first).map_err(LeituraError::Leitura)
334 }
335
336 /// Register `Caixa` with the global tatara-lisp domain registry so
337 /// `defcaixa` is dispatchable from any tatara-lisp binary that seeds
338 /// the registry (e.g. `tatara-check`).
339 ///
340 /// Returns the typed [`tatara_lisp::KeywordCollision`] on the second
341 /// (and every subsequent) call in the same process — one keyword,
342 /// one type, per process is a hard invariant of the upstream
343 /// registry, and a caller that hits it must fix its crate graph
344 /// rather than swallowing the error. Peer of the sibling per-crate
345 /// `register()` entry points at `caixa-flake/src/flake.rs`,
346 /// `caixa-fmt/src/lisp_config.rs`, `caixa-lacre/src/lock.rs`,
347 /// `caixa-lint/src/lisp_config.rs`, `caixa-resolver/src/lisp_config.rs`
348 /// — every substrate crate that owns a tatara-lisp keyword now
349 /// propagates the same typed error verbatim, so a downstream binary
350 /// that seeds the registry (`tatara-check`, the future LSP) reaches
351 /// for one shape at every call site.
352 ///
353 /// # Errors
354 ///
355 /// [`tatara_lisp::KeywordCollision`] when a peer type has already
356 /// claimed the `defcaixa` keyword in this process.
357 pub fn register() -> Result<(), tatara_lisp::KeywordCollision> {
358 tatara_lisp::domain::register::<Self>()
359 }
360
361 /// Substrate-canonical per-`Caixa` `:licenca` SPDX-expression scalar
362 /// accessor every consumer of the top-level manifest's license axis
363 /// keys off — returns the author-declared `:licenca` byte-string
364 /// verbatim as an `Option<&str>`, borrowed from the typed slot's own
365 /// `Option<String>` storage. `None` when the slot is absent (the
366 /// canonical "omit to defer to the caixa-helm renderer's `MIT`
367 /// fallback" shape [`Self::validate_licenca`] documents at
368 /// caixa-core/src/manifest.rs:1560; the peer [`caixa-helm`]
369 /// `build_readme` fold at caixa-helm/src/lib.rs:962 reads this
370 /// predicate too, so an authored-but-unset `:licenca` round-trips to
371 /// a rendered `lareira-<nome>` chart's `README.md` `## License`
372 /// section structurally identical to one that omits the slot).
373 ///
374 /// The `:licenca` slot carries the universal-axis SPDX-expression
375 /// license identifier every kind of caixa emits under (CAIXA-SDLC
376 /// §I — the author-facing surface every `defcaixa` form supplies) —
377 /// the typed slot's `Option<String>` accept-set (empty-string
378 /// rejected through [`ManifestError::LicencaEmpty`], SPDX-alphabet-
379 /// invalid rejected through [`ManifestError::LicencaInvalid`]) maps
380 /// onto the `lareira-<nome>` Helm chart's `README.md` `## License`
381 /// section (caixa-helm/src/lib.rs:962) and (through future
382 /// tightening documented at [`Self::validate_licenca`]) the
383 /// Chart.yaml `annotations["artifacthub.io/license"]` axis every
384 /// registry-facing chart carries. Every downstream consumer that
385 /// reads the license byte-string keys off this scalar (the
386 /// [`Self::validate_licenca`] empty-arm + SPDX-shape gate that
387 /// routes through `self.licenca.as_deref()`, the caixa-helm
388 /// `build_readme` `unwrap_or_else(|| "MIT".into())` fold that keys
389 /// the fallback off the `Option::is_none()` arm, every future
390 /// per-`Caixa` registry-facing renderer the CAIXA-SDLC §I roadmap
391 /// acknowledges).
392 ///
393 /// Prior to this lift the `.licenca` field was accessed inline at
394 /// two production sites — [`Self::validate_licenca`]'s
395 /// `self.licenca.as_deref()` empty-and-shape gate binding and the
396 /// caixa-helm `build_readme` `caixa.licenca.clone().unwrap_or_else(||
397 /// "MIT".into())` `README.md` `## License` fold — two open-coded
398 /// field-accesses that expressed no compile-time link back to the
399 /// typed slot. A future extension of the `:licenca` axis to a
400 /// richer author surface — a per-`:licenca` structured SPDX
401 /// expression parser + license-id allowlist (the future tightening
402 /// [`Self::validate_licenca`]'s docstring acknowledges), a
403 /// per-cluster license-default overlay the M4 CR materializer
404 /// resolves per-CR (the "cluster policy pins `Apache-2.0` for every
405 /// unlisted caixa" arm), a promotion of the plain
406 /// `Option<String>` byte-string to a richer `SpdxExpression` enum
407 /// once the SPDX-expression parser lands — would have had to be
408 /// threaded through both open-coded copies in lockstep or the
409 /// validate gate and the caixa-helm emit path would silently
410 /// disagree on which license a given [`Caixa`] resolves to (an
411 /// author's `:licenca "MIT OR Apache-2.0"` would satisfy validate
412 /// while the emit path silently rendered a stale `MIT` fallback,
413 /// or vice versa). Lifting the resolution to a typed method on the
414 /// substrate primitive means every downstream consumer of the
415 /// caixa's per-`Caixa` license surface reaches for exactly one
416 /// typed dispatch — the resolver's accept-set migrates as a unit
417 /// on any future axis addition.
418 ///
419 /// First `Option<&str>`-return top-level [`Caixa`] scalar accessor —
420 /// opens the "outer [`Caixa`] `Option<&str>` scalar" projection
421 /// pattern the sibling per-`Caixa` `:descricao` / `:repositorio` /
422 /// `:edicao` future lifts fold on. Same "one typed dispatch on the
423 /// substrate primitive, thin projections at each consumer"
424 /// discipline the peer per-`:placement` [`crate::aplicacao::Placement::shard_key`]
425 /// (7cd2a28) / [`crate::aplicacao::Placement::affinity`] (74ec2d3)
426 /// / per-`:contratos` [`crate::aplicacao::WitContract::endpoint`]
427 /// (7020470) / [`crate::aplicacao::WitContract::subject`] (90de675)
428 /// / [`crate::aplicacao::WitContract::slot`] (ed22b66)
429 /// `Option<&str>`-return accessors carry on the sibling M2 / M3
430 /// typed-slot atom axes, extended here to the outer top-level
431 /// `Caixa` universal-axis surface. Named `licenca()` to match the
432 /// storage field's name; the accessor's identity maps onto the
433 /// canonical CAIXA-SDLC §I vocabulary the slot's docstring already
434 /// carries.
435 #[must_use]
436 pub fn licenca(&self) -> Option<&str> {
437 self.licenca.as_deref()
438 }
439
440 /// Substrate-canonical per-`Caixa` `:repositorio` git-repo-URL scalar
441 /// accessor every consumer of the top-level manifest's homepage /
442 /// source-of-truth axis keys off — returns the author-declared
443 /// `:repositorio` byte-string verbatim as an `Option<&str>`, borrowed
444 /// from the typed slot's own `Option<String>` storage. `None` when
445 /// the slot is absent (the canonical "omit to defer to the renderer's
446 /// per-target placeholder" shape — [`caixa-helm`]'s `ChartYaml.home`
447 /// carries the `Option<String>` through verbatim so an author-omitted
448 /// `:repositorio` renders a `Chart.yaml` without a `home:` field
449 /// (`skip_serializing_if = "Option::is_none"`), while [`caixa-flux`]'s
450 /// `ClusterBundleOpts::for_caixa` folds the omitted slot through a
451 /// `format!("https://github.com/{DEFAULT_PLEME_GIT_ORG}/{nome}")`
452 /// fallback derived from `caixa.nome`).
453 ///
454 /// The `:repositorio` slot carries the universal-axis git-repo-URL
455 /// homepage identifier every kind of caixa emits under (CAIXA-SDLC
456 /// §I — the author-facing surface every `defcaixa` form supplies) —
457 /// the typed slot's `Option<String>` accept-set (empty-string
458 /// rejected through [`ManifestError::RepositorioEmpty`], git-repo-URL-
459 /// shape-invalid rejected through [`ManifestError::RepositorioInvalid`]
460 /// past the shared [`crate::render::is_git_repo_url`] predicate the
461 /// peer per-`:deps :fonte :repo` axis also routes through) maps onto
462 /// four load-bearing downstream consumers:
463 ///
464 /// - [`Self::validate_repositorio`]'s empty-arm + shape-predicate
465 /// gate binding at caixa-core/src/manifest.rs:1456 — the
466 /// universal-axis identity gate wired at caixa-build time.
467 /// - [`caixa-helm`]'s `build_chart_yaml` `ChartYaml.home` fold at
468 /// caixa-helm/src/lib.rs:840 — the rendered `lareira-<nome>`
469 /// Helm chart's `Chart.yaml` `home:` field, which every registry
470 /// that ingests the chart (ArtifactHub, chartmuseum,
471 /// `helm search repo`) surfaces as the chart's canonical source-
472 /// of-truth link.
473 /// - [`caixa-helm`]'s `build_readme` `## Source` fold at
474 /// caixa-helm/src/lib.rs:957 — the rendered `lareira-<nome>`
475 /// chart's `README.md` header link back to the source repo,
476 /// which every author who inspects the rendered chart bundle
477 /// lands at.
478 /// - [`caixa-flux`]'s `ClusterBundleOpts::for_caixa`
479 /// `GitRepository.spec.url` fold at caixa-flux/src/lib.rs:2006 —
480 /// the rendered `GitRepository` CR's `spec.url` field, which
481 /// FluxCD's `source-controller` polls to reconcile the caixa's
482 /// manifest bundle from git.
483 ///
484 /// Prior to this lift the `.repositorio` field was accessed inline
485 /// at four production sites — [`Self::validate_repositorio`]'s
486 /// `self.repositorio.as_deref()` empty-and-shape gate binding, the
487 /// caixa-helm `build_chart_yaml` `caixa.repositorio.clone()`
488 /// `Chart.yaml` `home:` field fold, the caixa-helm `build_readme`
489 /// `caixa.repositorio.clone().unwrap_or_else(|| caixa.nome.clone())`
490 /// `README.md` `## Source` fold, and the caixa-flux
491 /// `ClusterBundleOpts::for_caixa`
492 /// `caixa.repositorio.clone().unwrap_or_else(|| format!(...))`
493 /// `GitRepository.spec.url` fold — four open-coded field-accesses
494 /// that expressed no compile-time link back to the typed slot. A
495 /// future extension of the `:repositorio` axis to a richer author
496 /// surface — a per-`:repositorio` structured
497 /// [`crate::render::GitRepoUrl`]-shaped scheme+host+path parse
498 /// (the future tightening [`Self::validate_repositorio`]'s
499 /// docstring anticipates alongside the peer per-`:deps :fonte
500 /// :repo` axis), a per-cluster repo-mirror overlay the M4 CR
501 /// materializer resolves per-CR (the "cluster policy rewrites
502 /// `github:pleme-io/...` to `git.internal/mirror/pleme-io/...`"
503 /// arm the private-registry story acknowledges), a promotion of
504 /// the plain `Option<String>` byte-string to a richer
505 /// `RepoUrl` enum discriminated on scheme — would have had to be
506 /// threaded through all four open-coded copies in lockstep or the
507 /// validate gate and the three emit paths would silently disagree
508 /// on which URL a given [`Caixa`] resolves to (an author's
509 /// `:repositorio "github:pleme-io/checkout"` would satisfy validate
510 /// while one of the emit paths silently rendered a stale URL, or
511 /// vice versa). Lifting the resolution to a typed method on the
512 /// substrate primitive means every downstream consumer of the
513 /// caixa's per-`Caixa` repo-URL surface reaches for exactly one
514 /// typed dispatch — the resolver's accept-set migrates as a unit on
515 /// any future axis addition.
516 ///
517 /// Second outer top-level [`Caixa`] `Option<&str>`-return scalar
518 /// accessor — sibling of [`Self::licenca`] (6d5bc28), the accessor
519 /// that opened the "outer [`Caixa`] `Option<&str>` scalar"
520 /// projection pattern this lift folds on. Same "one typed dispatch
521 /// on the substrate primitive, thin projections at each consumer"
522 /// discipline the peer per-`:placement`
523 /// [`crate::aplicacao::Placement::shard_key`] (7cd2a28) /
524 /// [`crate::aplicacao::Placement::affinity`] (74ec2d3) /
525 /// per-`:contratos` [`crate::aplicacao::WitContract::endpoint`]
526 /// (7020470) / [`crate::aplicacao::WitContract::subject`] (90de675)
527 /// / [`crate::aplicacao::WitContract::slot`] (ed22b66)
528 /// `Option<&str>`-return accessors carry on the sibling M2 / M3
529 /// typed-slot atom axes, extended here to the second outer top-level
530 /// `Caixa` universal-axis surface. Named `repositorio()` to match
531 /// the storage field's name; the accessor's identity maps onto the
532 /// canonical CAIXA-SDLC §I vocabulary the slot's docstring already
533 /// carries.
534 #[must_use]
535 pub fn repositorio(&self) -> Option<&str> {
536 self.repositorio.as_deref()
537 }
538
539 /// Substrate-canonical per-`Caixa` **resolved-git-repo-URL** composer —
540 /// returns the caixa's canonical git-source-of-truth URL as an owned
541 /// [`String`], author-declared `:repositorio` byte-string verbatim on
542 /// the `Some` arm and the substrate's canonical pleme-org github URL
543 /// fallback ([`crate::DEFAULT_PLEME_GIT_ORG`] and [`Self::nome`]
544 /// interpolated into `https://github.com/<org>/<nome>`) on the
545 /// `None` arm. Every substrate-side consumer that resolves
546 /// "which git URL does this caixa's source live at?" reaches for
547 /// exactly one typed dispatch on the substrate primitive — the raw
548 /// `caixa.repositorio().map(str::to_owned).unwrap_or_else(|| format!(
549 /// "https://github.com/{org}/{nome}", org = DEFAULT_PLEME_GIT_ORG,
550 /// nome = caixa.nome()))` open-coded composition every prior caller
551 /// re-derived collapses onto one canonical arm.
552 ///
553 /// Distinct from [`Self::repositorio`] (`Option<&str>`, exposes the
554 /// author-omitted / author-declared partition to the caller) — this
555 /// accessor is the **resolved** URL surface, folding the fallback in
556 /// at the substrate-primitive boundary. Every consumer that keys off
557 /// the `Option::is_none()` discriminator (a [`Chart.yaml`] `home:`
558 /// field emit that must omit the field entirely on an author-omitted
559 /// `:repositorio`, per the [`Self::repositorio`] docstring's
560 /// documented four-consumer list) reaches through the raw
561 /// [`Self::repositorio`] `Option<&str>` accessor by construction — the
562 /// resolved-URL composer sits alongside it as the second projection
563 /// on the same underlying `:repositorio` slot rather than replacing
564 /// the raw accessor.
565 ///
566 /// The fallback branch is the exact byte-image of the prior inline
567 /// [`caixa-flux::ClusterBundleOpts::for_caixa`] `git_url` composer at
568 /// caixa-flux/src/lib.rs:2080 — pinned by the sibling caixa-flux
569 /// byte-parity test
570 /// `cluster_bundle_opts_for_caixa_git_url_routes_through_canonical_git_url_accessor`
571 /// against a future implementation of this method that reordered the
572 /// `format!` template arguments, migrated the `<org>` segment to a
573 /// different constant (the [`crate::DEFAULT_PLEME_GIT_ORG`] axis a
574 /// future substrate-side git-org migration may split off), or
575 /// silently absorbed the empty-string arm (a hypothetical
576 /// `Some("") → fallback` collapse the raw [`Self::repositorio`]
577 /// accessor's docstring explicitly rejects on the sibling raw
578 /// accessor).
579 ///
580 /// Peer of the sibling per-`&Caixa`-axis composed helpers
581 /// [`caixa-flux::cluster_bundle_for_caixa`] (06d52d7) on the sibling
582 /// substrate-side renderer surface — same "close the composed
583 /// substrate-primitive at one canonical arm on the single-`&Caixa`
584 /// dispatch, converge every prior open-coded caller onto the arm"
585 /// discipline extended onto the resolved-git-URL projection of the
586 /// per-`Caixa` `:repositorio` axis. Owns per-call [`String`]
587 /// allocation on both arms (the `Some` arm's `str::to_owned` and the
588 /// `None` arm's `format!`) — the by-value return matches every
589 /// downstream consumer's field-fill shape (the caixa-flux
590 /// `ClusterBundleOpts::git_url: String` field, every future
591 /// `Chart.yaml` `home:` fold's `Option<String>` field-fill on the
592 /// `Some` arm).
593 #[must_use]
594 pub fn canonical_git_url(&self) -> String {
595 self.repositorio().map_or_else(
596 || {
597 format!(
598 "https://github.com/{org}/{nome}",
599 org = crate::DEFAULT_PLEME_GIT_ORG,
600 nome = self.nome(),
601 )
602 },
603 str::to_owned,
604 )
605 }
606
607 /// Substrate-canonical per-`Caixa` **resolved-publish-tag** composer —
608 /// returns the caixa's canonical Zig-style git-publish-tag as an owned
609 /// [`String`], derived by concatenating
610 /// [`crate::DEFAULT_PUBLISH_TAG_PREFIX`] with the typed
611 /// [`Self::versao`] byte-string on a single `format!` template.
612 /// Every substrate-side consumer that resolves "which git tag does this
613 /// caixa publish under?" reaches for exactly one typed dispatch on the
614 /// substrate primitive — the raw `format!("{prefix}{versao}", prefix =
615 /// caixa_core::DEFAULT_PUBLISH_TAG_PREFIX, versao = caixa.versao())`
616 /// open-coded composition every prior caller re-derived collapses onto
617 /// one canonical arm.
618 ///
619 /// Peer of the sibling [`Self::canonical_git_url`] (124f864) resolved-
620 /// git-URL composer on the paired per-`Caixa` git-remote axis — same
621 /// "close the composed substrate-primitive at one canonical arm on the
622 /// single-`&Caixa` dispatch, converge every prior open-coded caller
623 /// onto the arm" discipline extended from the resolved-URL projection
624 /// of the per-`Caixa` `:repositorio` axis onto the resolved-tag
625 /// projection of the per-`Caixa` `:versao` axis. The two accessors
626 /// jointly close the pair of scalars every `FluxCD` `GitRepository` CR
627 /// keys off (`spec.url` via [`Self::canonical_git_url`],
628 /// `spec.ref.tag` via [`Self::publish_tag`]) at the substrate primitive
629 /// — a downstream consumer that reaches through both accessors reads
630 /// the complete published-git-identity of a caixa through two typed
631 /// dispatches, not four open-coded field accesses.
632 ///
633 /// The reader-side (`caixa-flux::cluster_bundle` /
634 /// `ClusterBundleOpts::for_caixa`'s `git_ref` field, every future
635 /// per-cluster snapshot bundle emitter, the future M4
636 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's tag-carrier
637 /// slot on the tatara `Process` intent) always resolves the tag under
638 /// the canonical [`crate::DEFAULT_PUBLISH_TAG_PREFIX`] prefix — this
639 /// method encodes that reader-side convention. The writer-side
640 /// (`caixa-feira`'s `feira publish` `--prefix` clap flag) allows the
641 /// operator to override the prefix at publish time; the two surfaces
642 /// intentionally sit on the "canonical default + operator override"
643 /// pair the sibling [`crate::DEFAULT_PUBLISH_TAG_PREFIX`] constant's
644 /// own docstring documents — a `feira publish --prefix release/`
645 /// override is the operator's explicit opt-out from the substrate
646 /// default, not a supported drift axis.
647 ///
648 /// The composition body is the exact byte-image of the prior inline
649 /// [`caixa-flux::ClusterBundleOpts::for_caixa`] `git_ref` composer at
650 /// caixa-flux/src/lib.rs:2105 — pinned by the sibling caixa-flux
651 /// byte-parity test
652 /// `cluster_bundle_opts_for_caixa_git_ref_routes_through_publish_tag_accessor`
653 /// against a future implementation of this method that reordered the
654 /// `format!` template arguments, migrated the `<prefix>` segment to a
655 /// different constant (the [`crate::DEFAULT_PUBLISH_TAG_PREFIX`] axis
656 /// a future Zig-style-tag rebrand may split off — the constant's own
657 /// docstring anticipates a substrate-side move to `release/<versao>`
658 /// or bare `<versao>` shapes once a sibling forge convention adopts a
659 /// slash-namespaced or bare-scalar form), interposed a canonicalization
660 /// pass on the `:versao` axis (a SemVer-2 build-metadata strip an OCI-
661 /// tag normalizer might apply once the M4 registry-alignment slot
662 /// lands), or silently absorbed an empty `:versao` arm (which cannot
663 /// occur past the [`Self::validate_versao`] gate but which a
664 /// hypothetical bypass on the accessor path must not silently paper
665 /// over).
666 ///
667 /// Owns per-call [`String`] allocation via the single `format!`
668 /// invocation — the by-value return matches every downstream
669 /// consumer's field-fill shape (the caixa-flux `GitRefSpec::Tag(String)`
670 /// variant's owned payload, every future `intent.aplicacao.tag: String`
671 /// field-fill on the M4 CR materializer's tag-carrier slot).
672 #[must_use]
673 pub fn publish_tag(&self) -> String {
674 format!(
675 "{prefix}{versao}",
676 prefix = crate::DEFAULT_PUBLISH_TAG_PREFIX,
677 versao = self.versao(),
678 )
679 }
680
681 /// Substrate-canonical per-`Caixa` **resolved-Helm-chart-name** composer
682 /// — returns the caixa's canonical `lareira-<nome>` per-Servico Helm
683 /// chart identity as an owned [`String`], derived by dispatching through
684 /// the substrate-canonical [`crate::lareira_chart_name`] helper against
685 /// the typed [`Self::nome`] byte-string. Every substrate-side consumer
686 /// that resolves "which Helm chart identity does this caixa render
687 /// under?" reaches for exactly one typed dispatch on the substrate
688 /// primitive — the raw `caixa_core::lareira_chart_name(caixa.nome())`
689 /// two-step compose every prior caller re-derived collapses onto one
690 /// canonical arm on the single-`&Caixa` dispatch.
691 ///
692 /// Peer of the sibling [`Self::canonical_git_url`] (124f864) resolved-
693 /// git-URL composer + [`Self::publish_tag`] (07e05b8) resolved-publish-
694 /// tag composer on the paired per-`Caixa` published-artifact-identity
695 /// axis — same "close the composed substrate-primitive at one canonical
696 /// arm on the single-`&Caixa` dispatch, converge every prior open-coded
697 /// caller onto the arm" discipline extended from the resolved-URL /
698 /// resolved-tag projections of the `:repositorio` / `:versao` axes onto
699 /// the resolved-chart-name projection of the `:nome` axis. The three
700 /// accessors jointly close the triple of scalars every per-Servico
701 /// deploy artifact keys off (git source URL via
702 /// [`Self::canonical_git_url`], git source tag via
703 /// [`Self::publish_tag`], per-Servico Helm chart identity via
704 /// [`Self::lareira_chart_name`]) at the substrate primitive — a
705 /// downstream consumer that reaches through all three reads the
706 /// complete deploy-artifact identity of a caixa through three typed
707 /// dispatches, not six open-coded compositions across three renderer
708 /// crates.
709 ///
710 /// The reader-side (three production sites at the time of the lift —
711 /// [`caixa-helm::render_chart_for_servico_with`]'s `ChartDir.name`
712 /// composer at caixa-helm/src/lib.rs:778, the peer
713 /// [`caixa-flux::cluster_bundle`]'s per-CR `chart_name` binding at
714 /// caixa-flux/src/lib.rs:2219, and
715 /// [`caixa-tatara::process_for_aplicacao`]'s `release_name`
716 /// composer at caixa-tatara/src/lib.rs:227, plus every future
717 /// per-Servico OCI publish emitter the CAIXA-SDLC §II
718 /// `caixa-publish.yml` reusable workflow's `skopeo push` step keys
719 /// off, the future per-cluster snapshot bundle emitter, the future
720 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
721 /// per-member chart-carrier slot on the tatara `Process` intent) —
722 /// always resolves the chart name under the canonical
723 /// [`crate::LAREIRA_CHART_NAME_PREFIX`] prefix; this method encodes
724 /// that reader-side convention. The joint-length invariant the peer
725 /// [`Self::validate_nome_chart_name_budget`] gate enforces at
726 /// caixa-build time (author-declared `:nome` + fixed prefix ≤
727 /// [`crate::DNS_1123_LABEL_MAX_LEN`]) is verified on the input to
728 /// this composer by construction, so the produced `lareira-<nome>`
729 /// string is a valid Helm chart-name segment on every accept-set
730 /// input.
731 ///
732 /// The composition body is the exact byte-image of the prior inline
733 /// `caixa_core::lareira_chart_name(caixa.nome())` two-step form every
734 /// prior caller re-derived — pinned by the sibling caixa-helm /
735 /// caixa-flux / caixa-tatara byte-parity tests
736 /// `<crate>_lareira_chart_name_routes_through_caixa_accessor` against
737 /// a future implementation of this method that reordered the
738 /// composition arguments, migrated the `<prefix>` segment to a
739 /// different constant (the [`crate::LAREIRA_CHART_NAME_PREFIX`] axis a
740 /// future substrate-side chart-family rebrand may split off — the
741 /// constant's own docstring anticipates a substrate-side move once
742 /// the `lareira-` scoping intent outlives the family it names),
743 /// interposed a canonicalization pass on the `:nome` axis (a per-
744 /// registry namespace-qualification an M4 CR materializer might apply
745 /// per-CR — the "`pleme-io/checkout` vs `partner-org/checkout`
746 /// collision" arm the multi-tenant-registry story acknowledges), or
747 /// silently absorbed an empty `:nome` arm (which cannot occur past
748 /// the [`Self::validate_nome`] gate but which a hypothetical bypass
749 /// on the accessor path must not silently paper over).
750 ///
751 /// Owns per-call [`String`] allocation via the single
752 /// [`crate::lareira_chart_name`] `format!` invocation — the by-value
753 /// return matches every downstream consumer's field-fill shape (the
754 /// caixa-helm `ChartDir.name: String` field, the caixa-flux per-CR
755 /// `chart_name: String` binding, the caixa-tatara
756 /// `AplicacaoIntent.release_name: Option<String>` field-fill on the
757 /// `Some` arm).
758 #[must_use]
759 pub fn lareira_chart_name(&self) -> String {
760 crate::lareira_chart_name(self.nome())
761 }
762
763 /// Substrate-canonical per-`Caixa` **resolved-OCI-chart-ref** composer
764 /// — returns the caixa's canonical `oci://<registry>/lareira-<nome>`
765 /// per-Servico Helm chart OCI artifact reference as an owned
766 /// [`String`], derived by dispatching through the substrate-canonical
767 /// [`crate::oci_chart_ref`] helper (which itself composes
768 /// [`crate::OCI_SCHEME_PREFIX`] + the caller-supplied `registry` +
769 /// [`crate::lareira_chart_name`]-of-[`Self::nome`]) against the
770 /// caller-supplied `registry` and the typed [`Self::nome`] byte-string.
771 /// Every substrate-side consumer that resolves "which OCI chart
772 /// artifact does this caixa publish under, in this registry?" reaches
773 /// for exactly one typed dispatch on the substrate primitive — the raw
774 /// `caixa_core::oci_chart_ref(registry, caixa.nome())` two-step compose
775 /// every prior caller re-derived collapses onto one canonical arm on
776 /// the single-`(&Caixa, &str)` dispatch.
777 ///
778 /// Fourth member of the paired per-`Caixa` published-artifact-identity
779 /// axis alongside [`Self::canonical_git_url`] (124f864) /
780 /// [`Self::publish_tag`] (07e05b8) / [`Self::lareira_chart_name`]
781 /// (a8f0bee) — same "close the composed substrate-primitive at one
782 /// canonical arm on the single-`&Caixa` dispatch, converge every
783 /// prior open-coded caller onto the arm" discipline extended from the
784 /// resolved-URL / resolved-tag / resolved-chart-name projections of
785 /// the `:repositorio` / `:versao` / `:nome` axes onto the resolved-
786 /// OCI-ref projection over the paired `(registry, :nome)` inputs. The
787 /// four accessors jointly close the per-`Caixa` published-artifact-
788 /// identity surface every downstream consumer of a caixa's published
789 /// deploy artifacts keys off (git source URL via
790 /// [`Self::canonical_git_url`], git source tag via
791 /// [`Self::publish_tag`], per-Servico Helm chart identity via
792 /// [`Self::lareira_chart_name`], per-registry OCI chart artifact
793 /// reference via [`Self::oci_chart_ref`]) at the substrate primitive
794 /// — a downstream consumer that reaches through all four reads the
795 /// complete deploy-artifact identity of a caixa through four typed
796 /// dispatches, not eight open-coded compositions across four renderer
797 /// crates. The unique-signature dispatch (`(&Caixa, &str)` on this
798 /// method vs. `&Caixa` on the sibling three) reflects the extra input
799 /// axis this composer folds in: unlike the git-URL / git-tag / chart-
800 /// name axes (each derived purely from a `&Caixa`), the OCI-ref axis
801 /// pairs the caixa's per-`:nome` chart identity with the caller-
802 /// supplied per-registry authority segment, so the accessor threads
803 /// the registry byte-string through as a positional `&str`.
804 ///
805 /// The reader-side (one production site at the time of the lift —
806 /// [`caixa-tatara::process_for_aplicacao`]'s `derive_chart_ref` helper
807 /// at caixa-tatara/src/lib.rs:333 that composes the emitted
808 /// `AplicacaoIntent.chart_ref` scalar the tatara-reconciler feeds into
809 /// `helm install`, plus every future per-Servico OCI publish emitter
810 /// the CAIXA-SDLC §II `caixa-publish.yml` reusable workflow's
811 /// `skopeo push` step keys off, the future per-cluster snapshot bundle
812 /// emitter's per-CR `oci://…` field-fill on the M4 registry-alignment
813 /// slot, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
814 /// materializer's per-member `chart_ref` slot on the tatara `Process`
815 /// intent, the `FluxCD` `HelmRelease` `spec.chart.spec.chart` field-fill
816 /// on the OCI-source path an M4 per-cluster registry-rewrite overlay
817 /// applies per-CR) — always resolves the OCI ref under the canonical
818 /// [`crate::OCI_SCHEME_PREFIX`] scheme prefix + the canonical
819 /// [`Self::lareira_chart_name`] chart-name segment; this method
820 /// encodes that reader-side convention.
821 ///
822 /// The composition body is the exact byte-image of the prior inline
823 /// `caixa_core::oci_chart_ref(registry, caixa.nome())` two-step form
824 /// every prior caller re-derived — pinned by the sibling caixa-tatara
825 /// byte-parity test
826 /// `derive_chart_ref_routes_through_caixa_oci_chart_ref_accessor`
827 /// against a future implementation of this method that reordered the
828 /// composition arguments, migrated the `<scheme>` segment to a
829 /// different constant (the [`crate::OCI_SCHEME_PREFIX`] axis a future
830 /// substrate-side registry-protocol rebrand may split off — the
831 /// constant's own docstring anticipates a substrate-side move once
832 /// Helm 3 / `FluxCD` introduce a successor scheme past `oci://`),
833 /// migrated the `<chart>` segment off the paired
834 /// [`crate::lareira_chart_name`] composer (a per-registry
835 /// namespace-qualification an M4 CR materializer might apply per-CR),
836 /// interposed a canonicalization pass on the `registry` axis (an OCI-
837 /// authority normalization once the M4 registry-alignment slot lands),
838 /// or silently absorbed an empty `:nome` arm (which cannot occur past
839 /// the [`Self::validate_nome`] gate but which a hypothetical bypass
840 /// on the accessor path must not silently paper over).
841 ///
842 /// Owns per-call [`String`] allocation via the single
843 /// [`crate::oci_chart_ref`] `format!` invocation — the by-value return
844 /// matches every downstream consumer's field-fill shape (the caixa-
845 /// tatara `AplicacaoIntent.chart_ref: String` field-fill, every
846 /// future `intent.aplicacao.chart_ref: String` field-fill on the M4
847 /// CR materializer's chart-ref-carrier slot, every future
848 /// `HelmRelease.spec.chart.spec.chart: String` field-fill on the OCI-
849 /// source path).
850 #[must_use]
851 pub fn oci_chart_ref(&self, registry: &str) -> String {
852 crate::oci_chart_ref(registry, self.nome())
853 }
854
855 /// Substrate-canonical per-`Caixa` `:descricao` free-form-prose
856 /// chart-description scalar accessor every consumer of the top-level
857 /// manifest's Chart.yaml `description:` axis keys off — returns the
858 /// author-declared `:descricao` byte-string verbatim as an
859 /// `Option<&str>`, borrowed from the typed slot's own
860 /// `Option<String>` storage. `None` when the slot is absent (the
861 /// canonical "omit to defer to the per-renderer `caixa.nome`-derived
862 /// fallback" shape — [`caixa-helm`]'s `build_chart_yaml` folds the
863 /// omitted slot through a `format!("Generated chart for caixa Servico
864 /// {}", caixa.nome)` fallback, [`caixa-helm`]'s `build_readme` folds
865 /// it through a `format!("caixa Servico {}", caixa.nome)` fallback,
866 /// and [`caixa-feira`]'s `render_flake` folds it through a
867 /// `format!("caixa {}", c.nome)` `flake.nix` `description = ""`
868 /// fallback — each derived from `caixa.nome` on the null-carrier arm).
869 ///
870 /// The `:descricao` slot carries the universal-axis free-form-prose
871 /// chart-description identifier every kind of caixa emits under
872 /// (CAIXA-SDLC §I — the author-facing surface every `defcaixa` form
873 /// supplies) — the typed slot's `Option<String>` accept-set
874 /// (empty-string rejected through [`ManifestError::DescricaoEmpty`],
875 /// chart-description-shape-invalid rejected through
876 /// [`ManifestError::DescricaoInvalid`] past the shared
877 /// [`crate::render::is_chart_description_shape`] predicate the peer
878 /// per-`Caixa` `:descricao` axis also routes through) maps onto four
879 /// load-bearing downstream consumers:
880 ///
881 /// - [`Self::validate_descricao`]'s empty-arm + shape-predicate
882 /// gate binding — the universal-axis identity gate wired at
883 /// caixa-build time.
884 /// - [`caixa-helm`]'s `build_chart_yaml` `ChartYaml.description`
885 /// `Chart.yaml` field fold — the rendered `lareira-<nome>` Helm
886 /// chart's `Chart.yaml` `description:` field, which
887 /// `apiVersion: v2` charts require non-empty (`helm lint` fires
888 /// `WARNING [chart.metadata.description]: description is required`
889 /// when absent) and which every registry that ingests the chart
890 /// (ArtifactHub, chartmuseum, `helm search repo`) surfaces as the
891 /// chart's canonical one-line prose descriptor.
892 /// - [`caixa-helm`]'s `build_readme` chart-`README.md` header fold
893 /// — the rendered `lareira-<nome>` chart's `README.md` prose
894 /// header directly beneath the `# <chart-name>` title, which
895 /// every author who inspects the rendered chart bundle lands at.
896 /// - [`caixa-feira`]'s `render_flake` `flake.nix` `description = ""`
897 /// top-level fold — the emitted `flake.nix`'s `description`
898 /// field, which every Nix consumer (`nix flake show`,
899 /// `nix flake metadata`, downstream flake-registry ingestors)
900 /// surfaces as the flake's canonical descriptor.
901 ///
902 /// Prior to this lift the `.descricao` field was accessed inline at
903 /// four production sites — [`Self::validate_descricao`]'s
904 /// `self.descricao.as_deref()` empty-and-shape gate binding, the
905 /// caixa-helm `build_chart_yaml`
906 /// `caixa.descricao.clone().unwrap_or_else(|| format!(...))`
907 /// `Chart.yaml` `description:` fold, the caixa-helm `build_readme`
908 /// `caixa.descricao.clone().unwrap_or_else(|| format!(...))`
909 /// `README.md` header fold, and the caixa-feira `render_flake`
910 /// `c.descricao.clone().unwrap_or_else(|| format!(...))` `flake.nix`
911 /// `description = ""` fold — four open-coded field-accesses that
912 /// expressed no compile-time link back to the typed slot. A future
913 /// extension of the `:descricao` axis to a richer author surface —
914 /// a per-`:descricao` locale-tagged multi-language descriptor map
915 /// (the "one caixa, N language-tagged prose descriptions" arm
916 /// author-tooling internationalization anticipates), a
917 /// per-registry-target length-and-shape overlay the M4 CR
918 /// materializer resolves per-CR (the "ArtifactHub caps description
919 /// at 512 bytes but the internal registry caps at 256" arm), a
920 /// promotion of the plain `Option<String>` byte-string to a richer
921 /// `ChartDescription` newtype guaranteeing the
922 /// `is_chart_description_shape` predicate at the type level — would
923 /// have had to be threaded through all four open-coded copies in
924 /// lockstep or the validate gate and the three emit paths would
925 /// silently disagree on which prose string a given [`Caixa`]
926 /// resolves to (an author's
927 /// `:descricao "Checkout flow orchestration."` would satisfy
928 /// validate while one of the emit paths silently rendered a stale
929 /// `caixa.nome`-derived fallback, or vice versa). Lifting the
930 /// resolution to a typed method on the substrate primitive means
931 /// every downstream consumer of the caixa's per-`Caixa`
932 /// chart-description surface reaches for exactly one typed dispatch
933 /// — the resolver's accept-set migrates as a unit on any future
934 /// axis addition.
935 ///
936 /// Third outer top-level [`Caixa`] `Option<&str>`-return scalar
937 /// accessor — sibling of [`Self::licenca`] (6d5bc28) and
938 /// [`Self::repositorio`] (cc7332d), the accessors that opened the
939 /// "outer [`Caixa`] `Option<&str>` scalar" projection pattern this
940 /// lift folds on. Same "one typed dispatch on the substrate
941 /// primitive, thin projections at each consumer" discipline the
942 /// peer per-`:placement`
943 /// [`crate::aplicacao::Placement::shard_key`] (7cd2a28) /
944 /// [`crate::aplicacao::Placement::affinity`] (74ec2d3) /
945 /// per-`:contratos` [`crate::aplicacao::WitContract::endpoint`]
946 /// (7020470) / [`crate::aplicacao::WitContract::subject`] (90de675)
947 /// / [`crate::aplicacao::WitContract::slot`] (ed22b66)
948 /// `Option<&str>`-return accessors carry on the sibling M2 / M3
949 /// typed-slot atom axes, extended here to the third outer top-level
950 /// `Caixa` universal-axis surface. Named `descricao()` to match the
951 /// storage field's name; the accessor's identity maps onto the
952 /// canonical CAIXA-SDLC §I vocabulary the slot's docstring already
953 /// carries. The one remaining universal `Option<String>` slot
954 /// (`:edicao`) folds on this pattern next.
955 #[must_use]
956 pub fn descricao(&self) -> Option<&str> {
957 self.descricao.as_deref()
958 }
959
960 /// Substrate-canonical per-`Caixa` `:edicao` language-edition scalar
961 /// accessor every consumer of the top-level manifest's tatara-lisp
962 /// edition-selector axis keys off — returns the author-declared
963 /// `:edicao` byte-string verbatim as an `Option<&str>`, borrowed from
964 /// the typed slot's own `Option<String>` storage. `None` when the
965 /// slot is absent (the canonical "omit the slot to defer to the
966 /// substrate's default edition" shape every existing
967 /// [`caixa-resolver`] integration test fixture carries via
968 /// `edicao: None` — see `caixa-resolver/tests/git_integration.rs`;
969 /// the peer [`Self::validate_edicao`] gate is a no-op on the omitted
970 /// arm by construction, so an author-omitted `:edicao` round-trips
971 /// to a build without triggering the year-shape predicate).
972 ///
973 /// The `:edicao` slot carries the universal-axis 4-digit-ASCII-
974 /// decimal-year language-edition identifier every kind of caixa
975 /// emits under (CAIXA-SDLC §I — the author-facing surface every
976 /// `defcaixa` form supplies) — the typed slot's `Option<String>`
977 /// accept-set (empty-string rejected through
978 /// [`ManifestError::EdicaoEmpty`], year-shape-invalid rejected
979 /// through [`ManifestError::EdicaoInvalid`] past the 4-digit-ASCII-
980 /// decimal-year predicate [`Self::validate_edicao`] enforces) maps
981 /// onto one load-bearing downstream consumer today
982 /// ([`Self::validate_edicao`]'s empty-arm + year-shape-predicate
983 /// gate binding at caixa-core/src/manifest.rs:1959) plus every
984 /// future edition-aware substrate consumer the CAIXA-SDLC §I
985 /// roadmap anticipates (the tatara-lisp compiler's macro-surface
986 /// selector every edition-aware build step keys off, the future
987 /// per-edition compatibility-flag overlay the M4 CR materializer
988 /// resolves per-CR, the peer [`Caixa::template`] canonical
989 /// `:edicao "2026"` scaffold every `feira init` emits verbatim,
990 /// and the renderer-side fixtures at `caixa-helm/src/lib.rs:978` /
991 /// `caixa-flux/src/lib.rs:2319` / `caixa-mesh/src/lib.rs:3208` that
992 /// carry `edicao: Some("2026".into())` by construction).
993 ///
994 /// Prior to this lift the `.edicao` field was accessed inline at
995 /// one production site — [`Self::validate_edicao`]'s
996 /// `self.edicao.as_deref()` empty-and-shape gate binding — one
997 /// open-coded field-access that expressed no compile-time link
998 /// back to the typed slot. A future extension of the `:edicao`
999 /// axis to a richer author surface — a per-`:edicao` known-
1000 /// edition allowlist (the future tightening
1001 /// [`Self::validate_edicao`]'s docstring acknowledges past the
1002 /// structural year-shape floor, rejecting year-shaped values that
1003 /// don't name a tatara-lisp edition the substrate actually
1004 /// understands — `"1999"` is year-shaped but no `1999` edition
1005 /// exists), a per-edition compatibility-flag overlay the M4 CR
1006 /// materializer resolves per-CR (the "edition `"2026"` enables
1007 /// macro-surface features the sibling `"2018"` gates behind a
1008 /// feature flag" arm the edition-selector story anticipates), a
1009 /// promotion of the plain `Option<String>` byte-string to a
1010 /// richer `CaixaEdition` enum discriminated on year once a sibling
1011 /// edition to `"2026"` lands — would have had to be threaded
1012 /// through the open-coded copy in lockstep with every future
1013 /// edition-aware consumer, or the validate gate and the future
1014 /// edition-aware consumer path would silently disagree on which
1015 /// edition a given [`Caixa`] resolves to (an author's
1016 /// `:edicao "2026"` would satisfy validate while a future
1017 /// edition-aware consumer silently defaulted to a stale edition,
1018 /// or vice versa). Lifting the resolution to a typed method on
1019 /// the substrate primitive means every downstream consumer of the
1020 /// caixa's per-`Caixa` edition surface reaches for exactly one
1021 /// typed dispatch — the resolver's accept-set migrates as a unit
1022 /// on any future axis addition.
1023 ///
1024 /// Fourth and final outer top-level [`Caixa`] `Option<&str>`-return
1025 /// scalar accessor — sibling of [`Self::licenca`] (6d5bc28),
1026 /// [`Self::repositorio`] (cc7332d), and [`Self::descricao`]
1027 /// (3f16e2f), the accessors that opened the "outer [`Caixa`]
1028 /// `Option<&str>` scalar" projection pattern this lift folds on.
1029 /// Same "one typed dispatch on the substrate primitive, thin
1030 /// projections at each consumer" discipline the peer per-`:placement`
1031 /// [`crate::aplicacao::Placement::shard_key`] (7cd2a28) /
1032 /// [`crate::aplicacao::Placement::affinity`] (74ec2d3) /
1033 /// per-`:contratos` [`crate::aplicacao::WitContract::endpoint`]
1034 /// (7020470) / [`crate::aplicacao::WitContract::subject`] (90de675)
1035 /// / [`crate::aplicacao::WitContract::slot`] (ed22b66)
1036 /// `Option<&str>`-return accessors carry on the sibling M2 / M3
1037 /// typed-slot atom axes, extended here to close the outer top-level
1038 /// `Caixa` universal-axis surface's last unlifted `Option<String>`
1039 /// slot. Named `edicao()` to match the storage field's name; the
1040 /// accessor's identity maps onto the canonical CAIXA-SDLC §I
1041 /// vocabulary the slot's docstring already carries.
1042 #[must_use]
1043 pub fn edicao(&self) -> Option<&str> {
1044 self.edicao.as_deref()
1045 }
1046
1047 /// Substrate-canonical per-`Caixa` `:nome` universal-axis DNS-1123-
1048 /// label caixa-identity scalar accessor every consumer of the top-
1049 /// level manifest's identity axis keys off — returns the author-
1050 /// declared `:nome` byte-string verbatim as an `&str`, borrowed from
1051 /// the typed slot's own `String` storage. Non-optional (`:nome` is
1052 /// a required-axis scalar every `defcaixa` form must supply; the
1053 /// [`Self::from_lisp`] derive rejects an omitted / non-string
1054 /// `:nome` at parse time, so a `Caixa` past parse definitionally
1055 /// carries a non-`None` `:nome`).
1056 ///
1057 /// The `:nome` slot carries the universal-axis DNS-1123-label
1058 /// caixa-identity every kind of caixa emits under (CAIXA-SDLC §I —
1059 /// the primary identity axis every `defcaixa` form supplies
1060 /// alongside `:versao` / `:kind`; the substrate-wide identity every
1061 /// other typed surface that names a caixa reaches through — `:deps`
1062 /// entries, `:membros` entries, `:children` entries, the
1063 /// `lareira-<nome>` Helm chart name every per-Servico renderer
1064 /// derives, the `pleme-program-<nome>` label every per-Aplicacao
1065 /// renderer emits) — the typed slot's `String` accept-set (empty
1066 /// rejected through [`ManifestError::NomeEmpty`], DNS-1123-shape-
1067 /// invalid rejected through [`ManifestError::NomeInvalid`] past
1068 /// the shared [`crate::render::require_valid_dns_1123_label`] gate
1069 /// the peer name axes each land on, joint-length-with-`lareira-`-
1070 /// prefix rejected through
1071 /// [`ManifestError::NomeChartNameBudgetExceeded`] past
1072 /// [`crate::render::is_lareira_chart_name_shape`]) maps onto every
1073 /// load-bearing downstream consumer the substrate carries — the
1074 /// two universal-axis validate gates at caixa-build time
1075 /// ([`Self::validate_nome`] + [`Self::validate_nome_chart_name_budget`]),
1076 /// [`crate::lareira_chart_name`]'s `lareira-<nome>` Helm chart-name
1077 /// derivation every per-Servico renderer keys off, the caixa-helm
1078 /// `Chart.yaml`'s `name:` axis, caixa-flux's `programs.yaml` entry
1079 /// `name:` axis, caixa-mesh's Cilium `CiliumNetworkPolicy` /
1080 /// `HTTPRoute` per-Aplicacao name axes at
1081 /// caixa-mesh/src/lib.rs:{2650, 2797, 2919, 2925},
1082 /// [`crate::pleme_program_selector`] /
1083 /// [`crate::pleme_program_in_aplicacao_selector`] label-selector
1084 /// derivations, and every future substrate renderer that emits an
1085 /// artifact keyed by the caixa's identity.
1086 ///
1087 /// Prior to this lift the `.nome` field was accessed inline at a
1088 /// dozen production sites across `caixa-core` (the two universal-
1089 /// axis validate gates + [`Dep::validate`]-adjacent duplicate
1090 /// tracking), `caixa-helm` (the `lareira_chart_name` fold, the
1091 /// `ChartYaml.name` / `ChartYaml.description` / `Chart.yaml`
1092 /// `keywords` fallback), `caixa-flux` (the `programs.yaml`
1093 /// entry `name:` fold, the `flux_kustomization_source_subtree`
1094 /// per-cluster subpath derivation), and `caixa-mesh` (the
1095 /// `pleme_program_in_aplicacao_selector` label-selector fold, the
1096 /// `cilium_network_policy_name` / `gateway_api_http_route_name`
1097 /// per-CR name derivations, the `LABEL_APLICACAO` labels-map
1098 /// insert) — a dozen open-coded field-accesses that expressed no
1099 /// compile-time link back to the typed slot. A future extension of
1100 /// the `:nome` axis to a richer author surface — a per-`:nome`
1101 /// structured `CaixaIdentity` newtype that carries the joint-
1102 /// length-with-prefix invariant [`Self::validate_nome_chart_name_budget`]
1103 /// enforces at the type level (rather than as a validate-time
1104 /// gate), a per-registry `:nome` namespacing overlay the M4 CR
1105 /// materializer resolves per-CR (the "`pleme-io/checkout` vs
1106 /// `partner-org/checkout` collision" arm the multi-tenant-registry
1107 /// story acknowledges), a promotion of the plain `String` byte-
1108 /// string to a richer `CaixaNome` newtype discriminated on
1109 /// namespace prefix — would have had to be threaded through every
1110 /// open-coded copy in lockstep or the two validate gates and the
1111 /// dozen emit paths would silently disagree on which identity a
1112 /// given [`Caixa`] resolves to (an author's `:nome "checkout"`
1113 /// would satisfy validate while one of the emit paths silently
1114 /// rendered a drifted other identity, or vice versa). Lifting the
1115 /// resolution to a typed method on the substrate primitive means
1116 /// every downstream consumer of the caixa's per-`Caixa` identity
1117 /// surface reaches for exactly one typed dispatch — the resolver's
1118 /// accept-set migrates as a unit on any future axis addition.
1119 ///
1120 /// First outer top-level [`Caixa`] `&str`-return required-scalar
1121 /// accessor — opens the "outer [`Caixa`] `&str` required-scalar"
1122 /// projection pattern the sibling per-`Caixa` `:versao` future lift
1123 /// folds on. Sibling in shape to the peer per-`:membros`
1124 /// [`crate::aplicacao::Membro::nome`] (4a32abf) / per-`:contratos`
1125 /// [`crate::aplicacao::WitContract::source`] /
1126 /// [`crate::aplicacao::WitContract::destination`] (7f0fd43),
1127 /// [`crate::aplicacao::WitContract::world_ref`] (0804823),
1128 /// [`crate::aplicacao::Membro::versao_requirement`] (a40b0e3),
1129 /// [`crate::aplicacao::Entrada::destination`] (6db982c),
1130 /// [`crate::aplicacao::CircuitBreaker::max_failures`] (3a74062),
1131 /// per-sub-struct required-axis accessors carry on the sibling M3
1132 /// mesh-slot-atom scalar-value axes, extended here to open the
1133 /// outer top-level [`Caixa`] `&str`-return required-scalar surface.
1134 /// Named `nome()` to match the storage field's name; the accessor's
1135 /// identity maps onto the canonical CAIXA-SDLC §I vocabulary the
1136 /// slot's docstring already carries.
1137 #[must_use]
1138 pub fn nome(&self) -> &str {
1139 &self.nome
1140 }
1141
1142 /// Substrate-canonical per-`Caixa` `:versao` universal-axis SemVer-2
1143 /// pinned-version scalar accessor every consumer of the top-level
1144 /// manifest's version axis keys off — returns the author-declared
1145 /// `:versao` byte-string verbatim as an `&str`, borrowed from the
1146 /// typed slot's own `String` storage. Non-optional (`:versao` is a
1147 /// required-axis scalar every `defcaixa` form must supply alongside
1148 /// `:nome` / `:kind`; the [`Self::from_lisp`] derive rejects an
1149 /// omitted / non-string `:versao` at parse time, so a `Caixa` past
1150 /// parse definitionally carries a non-`None` `:versao`).
1151 ///
1152 /// The `:versao` slot carries the universal-axis SemVer-2
1153 /// concrete-version body every kind of caixa emits under
1154 /// (CAIXA-SDLC §I — the required-scalar every `defcaixa` form
1155 /// supplies alongside `:nome` / `:kind`; the substrate-wide
1156 /// pinned-version every downstream artifact-emitting consumer
1157 /// composes under — the `lareira-<nome>` Helm chart's `Chart.yaml`
1158 /// `version:` + `appVersion:` axes, the `feira publish` Zig-style
1159 /// `v<versao>` git tag the [`crate::DEFAULT_PUBLISH_TAG_PREFIX`]
1160 /// prefix composes on top of, the programs.yaml entry's `versao:`
1161 /// value the `lareira-fleet-programs` aggregator carries onto each
1162 /// rendered `ComputeUnit`, the OCI image's `:v<versao>` / `:latest`
1163 /// tags every substrate-side `skopeo push` writes, the lacre
1164 /// closure's pinned `concrete_versao`, and the `:upgrade-from :from`
1165 /// prior-version references peers in the exact same SemVer-2 shape).
1166 /// The typed slot's `String` accept-set (empty rejected through
1167 /// [`ManifestError::VersaoEmpty`], SemVer-2-shape-invalid rejected
1168 /// through [`ManifestError::VersaoInvalid`] past
1169 /// [`semver::Version::parse`]) maps onto every load-bearing
1170 /// downstream consumer the substrate carries — the [`Self::validate_versao`]
1171 /// universal-axis validate gate at caixa-build time, the
1172 /// [`crate::CaixaVersion::parse`] typed-wrapper resolver,
1173 /// [`caixa-helm`]'s `Chart.yaml` `version:` / `appVersion:` fold,
1174 /// [`caixa-flux`]'s `programs.yaml` entry `versao:` fold + the
1175 /// `cluster_bundle` `GitRepository` `ref: { tag: v<versao> }`
1176 /// derivation, [`caixa-mesh`]'s per-Aplicacao `programs.yaml` fan-
1177 /// out entry `versao:` fold, [`caixa-feira`]'s `feira publish` git-
1178 /// tag derivation (`format!("{prefix}{versao}")`), and every future
1179 /// substrate renderer that emits an artifact keyed by the caixa's
1180 /// pinned version.
1181 ///
1182 /// Prior to this lift the `.versao` field was accessed inline at a
1183 /// dozen production sites across `caixa-core` (the universal-axis
1184 /// [`Self::validate_versao`] gate + [`Dep::validate`]-adjacent
1185 /// version-shape gates), `caixa-helm` (the `ChartYaml.version` /
1186 /// `ChartYaml.app_version` folds), `caixa-flux` (the `programs.yaml`
1187 /// entry `versao:` fold, the `cluster_bundle` `GitRepository` `ref:
1188 /// { tag: v<versao> }` derivation), `caixa-mesh` (the per-Aplicacao
1189 /// `programs.yaml` fan-out entry `versao:` fold), and `caixa-feira`
1190 /// (the `feira publish` git-tag derivation + the `feira app graph` /
1191 /// `feira app deploy` diagnostic renderers) — a dozen open-coded
1192 /// field-accesses that expressed no compile-time link back to the
1193 /// typed slot. A future extension of the `:versao` axis to a richer
1194 /// author surface — a per-`:versao` structured `CaixaVersion` at the
1195 /// storage layer (the substrate already carries a `CaixaVersion`
1196 /// newtype at [`crate::version::CaixaVersion`], deferred until the
1197 /// serde-transparent-newtype-through-DeriveTataraDomain path lands),
1198 /// a per-registry `:versao` immutability overlay the M4 CR
1199 /// materializer enforces per-CR, a promotion of the plain `String`
1200 /// byte-string to a richer `PinnedVersao` newtype discriminated on
1201 /// SemVer-2 pre-release / build-metadata presence — would have had
1202 /// to be threaded through every open-coded copy in lockstep or the
1203 /// validate gate and the dozen emit paths would silently disagree
1204 /// on which version a given [`Caixa`] resolves to (an author's
1205 /// `:versao "0.1.0"` would satisfy validate while one of the emit
1206 /// paths silently rendered a drifted other version, or vice versa).
1207 /// Lifting the resolution to a typed method on the substrate
1208 /// primitive means every downstream consumer of the caixa's
1209 /// per-`Caixa` pinned-version surface reaches for exactly one typed
1210 /// dispatch — the resolver's accept-set migrates as a unit on any
1211 /// future axis addition.
1212 ///
1213 /// Second outer top-level [`Caixa`] `&str`-return required-scalar
1214 /// accessor — folds on the "outer [`Caixa`] `&str` required-scalar"
1215 /// projection pattern the sibling per-`Caixa` [`Self::nome`]
1216 /// (e6b7d97) opened. Sibling in shape to the peer per-`:membros`
1217 /// [`crate::aplicacao::Membro::versao_requirement`] (4127bb6) /
1218 /// per-`:children` [`crate::supervisor::ChildSpec::versao_requirement`]
1219 /// (2c053c8) / per-`:upgrade-from` [`crate::UpgradeFromEntry::prior_versao`]
1220 /// (75d27a8) per-sub-struct `:versao`-shaped `&str`-return accessors
1221 /// on the sibling per-typed-slot version-carrier axes, extended here
1222 /// to close the second outer top-level [`Caixa`] required-`&str`-
1223 /// carrying axis so the two universal-axis identity-carrying
1224 /// scalars every `defcaixa` form supplies (`:nome` + `:versao`)
1225 /// share the same "one typed dispatch per axis" discipline. Named
1226 /// `versao()` to match the storage field's name; the accessor's
1227 /// identity maps onto the canonical CAIXA-SDLC §I vocabulary the
1228 /// slot's docstring already carries.
1229 #[must_use]
1230 pub fn versao(&self) -> &str {
1231 &self.versao
1232 }
1233
1234 /// Substrate-canonical per-`Caixa` `:kind` universal-axis
1235 /// closed-set-enum discriminant accessor every consumer of the top-
1236 /// level manifest's kind axis keys off — returns the author-declared
1237 /// `:kind` variant verbatim as a [`CaixaKind`], `Copy`-projected
1238 /// from the typed slot's own [`CaixaKind`] storage. Non-optional
1239 /// (`:kind` is a required-axis discriminant every `defcaixa` form
1240 /// must supply alongside `:nome` / `:versao`; the [`Self::from_lisp`]
1241 /// derive rejects an omitted / non-symbol `:kind` at parse time, so
1242 /// a `Caixa` past parse definitionally carries a valid [`CaixaKind`]
1243 /// variant).
1244 ///
1245 /// The `:kind` slot carries the universal-axis closed-set typed-
1246 /// discriminant every substrate-side dispatch keys off (CAIXA-SDLC
1247 /// §I — the primary shape gate every renderer / verifier /
1248 /// operator branches on; the five variants `Biblioteca` /
1249 /// `Binario` / `Servico` / `Supervisor` / `Aplicacao` partition
1250 /// the caixa surface into disjoint runtime contracts) — the typed
1251 /// slot's [`CaixaKind`] accept-set (parse-time-rejected non-symbol
1252 /// values through the derive-macro's symbol-arm gate, exhaustively
1253 /// matched at every downstream dispatch site) maps onto every
1254 /// load-bearing downstream consumer the substrate carries:
1255 ///
1256 /// - [`crate::render::require_kind`]'s per-renderer entry-gate
1257 /// predicate — the canonical two-line
1258 /// `require_kind(caixa, Servico)?` prelude every per-Servico
1259 /// renderer (`caixa-helm`, `caixa-flux`, the future `caixa-otel`
1260 /// / per-Servico OCI packager / M4 `wasm.pleme.io/v1alpha1/
1261 /// ComputeUnit` CR materializer) runs at its entry-point,
1262 /// alongside the [`crate::render::KindMismatch`] error carrier's
1263 /// `actual:` field the diagnostic surfaces to name the offending
1264 /// caixa's variant.
1265 /// - [`Self::aplicacao_view`]'s + [`Self::supervisor_view`]'s
1266 /// per-view kind-gate binding — the two `Option<TypedSpec>`
1267 /// `_view` composers that fold the flat mesh-slot / supervisor-
1268 /// slot columns into their typed sub-spec only when the kind
1269 /// matches (returns `None` otherwise); the future per-Servico
1270 /// M2-view composer (`servico_view`) will follow the same shape.
1271 /// - [`Self::declared_foreign_code_slots`]'s per-slot kind-
1272 /// coherence gate — the `!self.kind.requires_exe()` /
1273 /// `!self.kind.requires_servicos()` predicates that fence
1274 /// each code-surface slot from the wrong owning kind.
1275 /// - [`crate::LayoutInvariants::verify`]'s kind ↔ code-surface
1276 /// coherence gates — the six `caixa.kind == CaixaKind::X` /
1277 /// `caixa.kind != CaixaKind::X` predicates and the four kind-
1278 /// coherence error carriers (`SupervisorOwnsCode` /
1279 /// `AplicacaoOwnsCode` / `MeshSlotsOnNonAplicacao` /
1280 /// `SupervisorSlotsOnNonSupervisor` / `ServicoSlotsOnNonServico`
1281 /// / `ForeignCodeSlot`) which each name the offending caixa's
1282 /// variant in their `kind:` field.
1283 ///
1284 /// Prior to this lift the `.kind` field was accessed inline at
1285 /// twenty-plus production sites across `caixa-core` (the
1286 /// [`crate::render::require_kind`] entry-gate predicate + the
1287 /// [`crate::render::KindMismatch`] `actual:` field, the two `_view`
1288 /// composers, the `declared_foreign_code_slots` per-slot kind-
1289 /// coherence gate, and the six [`crate::LayoutInvariants::verify`]
1290 /// kind ↔ code-surface predicates + four error carriers) — a score
1291 /// of open-coded field-accesses that expressed no compile-time link
1292 /// back to the typed slot. A future extension of the `:kind` axis
1293 /// to a richer author surface — a per-`:kind` sub-variant discriminant
1294 /// (e.g. `Servico(ServicoRuntime)` splitting the current single
1295 /// variant across the wasm-component / legacy-container / native-
1296 /// binary runtime axes the M5 roadmap acknowledges), a per-cluster
1297 /// kind-overlay the M4 CR materializer resolves per-CR (the
1298 /// "cluster policy demotes `Aplicacao` to `Servico` on a single-
1299 /// tenant cluster" arm), a promotion of the plain [`CaixaKind`]
1300 /// enum to a richer `KindWithRuntime` discriminated on the
1301 /// component-model world axis — would have had to be threaded
1302 /// through every open-coded copy in lockstep or the entry gate,
1303 /// the view composers, and the layout invariants would silently
1304 /// disagree on which kind a given [`Caixa`] resolves to. Lifting
1305 /// the resolution to a typed method on the substrate primitive
1306 /// means every downstream consumer of the caixa's per-`Caixa`
1307 /// kind surface reaches for exactly one typed dispatch — the
1308 /// resolver's accept-set migrates as a unit on any future axis
1309 /// addition.
1310 ///
1311 /// First outer top-level [`Caixa`] `Copy`-return required-enum-
1312 /// discriminant accessor — opens the "outer [`Caixa`] `Copy`-return
1313 /// required-discriminant" projection pattern. Sibling in shape to
1314 /// the peer per-`:supervisor` [`crate::supervisor::SupervisorSpec::estrategia`]
1315 /// (eafb619), per-`:placement` [`crate::aplicacao::Placement::estrategia`]
1316 /// (921fe1b), and per-`:children` [`crate::supervisor::ChildSpec::restart`]
1317 /// (dfb4a81) `Copy`-return closed-set-enum discriminant accessors
1318 /// on the sibling nested-spec typed-slot discriminator axes,
1319 /// extended here to the outer top-level [`Caixa`] universal-axis
1320 /// surface. Named `kind()` to match the storage field's name;
1321 /// the accessor's identity maps onto the canonical CAIXA-SDLC §I
1322 /// vocabulary the slot's docstring already carries.
1323 #[must_use]
1324 pub fn kind(&self) -> CaixaKind {
1325 self.kind
1326 }
1327
1328 /// Substrate-canonical per-`Caixa` `:autores` universal-axis
1329 /// maintainer-name-list slice-accessor every consumer of the top-
1330 /// level manifest's maintainer axis keys off — returns the author-
1331 /// declared `:autores` list verbatim as a `&[String]` slice-view over
1332 /// the same backing buffer the raw `self.autores.as_slice()` field
1333 /// access borrows from. Empty-list-carrying (`:autores` is a default-
1334 /// empty axis every `defcaixa` form supplies with an empty `()` when
1335 /// unset; the [`Self::from_lisp`] derive folds an omitted `:autores`
1336 /// through `#[serde(default)]` to `Vec::new()`, so a `Caixa` past
1337 /// parse definitionally carries a `Vec<String>` slot — possibly
1338 /// empty — and the returned `&[String]` degenerates to an empty
1339 /// slice on that arm without any silent `None` collapse).
1340 ///
1341 /// The `:autores` slot carries the universal-axis maintainer-name
1342 /// list every kind of caixa emits under (CAIXA-SDLC §I — the author-
1343 /// facing surface every `defcaixa` form supplies alongside `:nome` /
1344 /// `:versao` / `:kind`; the substrate-wide contact-carrying axis
1345 /// every downstream registry-facing artifact emits under) — the
1346 /// typed slot's `Vec<String>` accept-set (empty-per-entry rejected
1347 /// through [`ManifestError::AutorEmpty`], non-chart-maintainer-shape
1348 /// rejected through [`ManifestError::AutorInvalid`], cross-entry
1349 /// duplicate rejected through [`ManifestError::AutorDuplicate`]) maps
1350 /// onto every load-bearing downstream consumer the substrate carries
1351 /// — the [`Self::validate_autores`] universal-axis empty-per-entry +
1352 /// shape + duplicate gate at caixa-core/src/manifest.rs, the
1353 /// caixa-helm `build_chart_yaml` `maintainers:` fold at
1354 /// caixa-helm/src/lib.rs that walks each entry into a `Maintainer {
1355 /// name, email: None }` record, every future per-`Caixa` registry-
1356 /// facing renderer the CAIXA-SDLC §I roadmap acknowledges (the
1357 /// future `artifacthub.io/maintainers` `Chart.yaml` annotation the
1358 /// caixa-helm docstring alludes to at [`Self::validate_licenca`],
1359 /// the future per-cluster author-notification overlay the M4 CR
1360 /// materializer resolves per-CR).
1361 ///
1362 /// Prior to this lift the `.autores` field was accessed inline at
1363 /// two production sites — [`Self::validate_autores`]'s `for autor
1364 /// in &self.autores` walk that gates every entry through
1365 /// [`ManifestError::AutorEmpty`] / `AutorInvalid` / `AutorDuplicate`,
1366 /// and the caixa-helm `build_chart_yaml` `caixa.autores.iter().map(|a|
1367 /// Maintainer { name: a.clone(), email: None }).collect()` fold that
1368 /// materializes every entry into a `Chart.yaml` `maintainers:` row —
1369 /// two open-coded field-accesses that expressed no compile-time link
1370 /// back to the typed slot. A future extension of the `:autores` axis
1371 /// to a richer author surface — a per-`:autores` structured
1372 /// `Maintainer { name, email, url }` at the storage layer once the
1373 /// substrate absorbs `artifacthub.io/maintainers`' name+email+url
1374 /// tuple, a per-registry `:autores` allowlist the M4 CR materializer
1375 /// enforces per-CR (the "cluster policy demands every author declare
1376 /// an on-file `mailto:` contact" arm), a promotion of the plain
1377 /// `Vec<String>` byte-string list to a richer
1378 /// `Vec<ChartMaintainer>` newtype discriminated on the RFC-5322
1379 /// `<name> [<email>]` grammar the `is_chart_maintainer_name_shape`
1380 /// predicate already resolves through — would have had to be
1381 /// threaded through both open-coded copies in lockstep or the
1382 /// validate gate and the caixa-helm emit path would silently
1383 /// disagree on which authors a given [`Caixa`] resolves to (an
1384 /// author's `:autores ("alice" "bob")` would satisfy validate while
1385 /// the caixa-helm emit path silently rendered a drifted other
1386 /// maintainer list, or vice versa). Lifting the resolution to a
1387 /// typed method on the substrate primitive means every downstream
1388 /// consumer of the caixa's per-`Caixa` maintainer surface reaches
1389 /// for exactly one typed dispatch — the resolver's accept-set
1390 /// migrates as a unit on any future axis addition.
1391 ///
1392 /// First outer top-level [`Caixa`] `&[T]`-return slice-accessor —
1393 /// opens the "outer [`Caixa`] `&[T]` slice" projection pattern the
1394 /// sibling per-`Caixa` `:etiquetas` / `:deps` / `:deps-dev` / `:exe`
1395 /// / `:bibliotecas` / `:servicos` / `:upgrade-from` / `:children`
1396 /// future lifts fold on. Sibling in shape to the peer per-`:supervisor`
1397 /// [`crate::supervisor::SupervisorSpec::children`] (bc92bce), per-`:placement`
1398 /// [`crate::aplicacao::Placement::clusters`] (a6e18d7), per-`:membros`
1399 /// [`crate::aplicacao::AplicacaoSpec::membros`] (6c77e36), per-`:contratos`
1400 /// [`crate::aplicacao::AplicacaoSpec::contratos`] (0dcc926), and
1401 /// per-`:upgrade-from :instructions` [`crate::upgrade::UpgradeFromEntry::instructions`]
1402 /// (0137e5a) `&[T]`-return slice accessors on the sibling per-M2 /
1403 /// per-M3 typed-slot list axes, extended here to the outer top-level
1404 /// [`Caixa`] universal-axis surface. Returns `&[String]` (not
1405 /// `&Vec<String>`) because every downstream consumer of the author
1406 /// list treats it as a read-only sequence — the slice-view is the
1407 /// narrowest borrow that supports every present + roadmapped consumer
1408 /// (`.iter()`, `.len()`, `.is_empty()`) without leaking the backing
1409 /// `Vec`'s grow/push/reserve surface no consumer of the typed view
1410 /// reaches for (the storage-side `Vec` remains reachable through the
1411 /// `pub autores` field for the mutation-carrying serde round-trip and
1412 /// per-test fixture-mutation paths). Named `autores()` to match the
1413 /// storage field's name; the accessor's identity maps onto the
1414 /// canonical CAIXA-SDLC §I vocabulary the slot's docstring already
1415 /// carries.
1416 #[must_use]
1417 pub fn autores(&self) -> &[String] {
1418 self.autores.as_slice()
1419 }
1420
1421 /// Substrate-canonical per-`Caixa` `:etiquetas` universal-axis
1422 /// registry-search-tag-list slice-accessor every consumer of the
1423 /// top-level manifest's topical-tag axis keys off — returns the
1424 /// author-declared `:etiquetas` list verbatim as a `&[String]`
1425 /// slice-view over the same backing buffer the raw
1426 /// `self.etiquetas.as_slice()` field access borrows from. Empty-
1427 /// list-carrying (`:etiquetas` is a default-empty axis every
1428 /// `defcaixa` form supplies with an empty `()` when unset; the
1429 /// [`Self::from_lisp`] derive folds an omitted `:etiquetas` through
1430 /// `#[serde(default)]` to `Vec::new()`, so a `Caixa` past parse
1431 /// definitionally carries a `Vec<String>` slot — possibly empty —
1432 /// and the returned `&[String]` degenerates to an empty slice on
1433 /// that arm without any silent `None` collapse).
1434 ///
1435 /// The `:etiquetas` slot carries the universal-axis topical-tag
1436 /// list every kind of caixa emits under (CAIXA-SDLC §I — the
1437 /// author-facing surface every `defcaixa` form supplies alongside
1438 /// `:nome` / `:versao` / `:kind`; the substrate-wide registry-
1439 /// search-facing axis every downstream registry-facing artifact
1440 /// emits under) — the typed slot's `Vec<String>` accept-set
1441 /// (empty-per-entry rejected through [`ManifestError::EtiquetaEmpty`],
1442 /// non-chart-keyword-shape rejected through
1443 /// [`ManifestError::EtiquetaInvalid`], cross-entry duplicate
1444 /// rejected through [`ManifestError::EtiquetaDuplicate`]) maps onto
1445 /// every load-bearing downstream consumer the substrate carries —
1446 /// the [`Self::validate_etiquetas`] universal-axis empty-per-entry
1447 /// + shape + duplicate gate at caixa-core/src/manifest.rs, the
1448 /// caixa-helm `build_chart_yaml` `keywords:` fold at
1449 /// caixa-helm/src/lib.rs that walks each entry into the rendered
1450 /// `Chart.yaml` `keywords:` array (chained with the
1451 /// [`crate::LAREIRA_CHART_KEYWORDS`] substrate-wide floor set and
1452 /// dedup'd through a `BTreeSet` at emit time), every future per-
1453 /// `Caixa` registry-facing renderer the CAIXA-SDLC §I roadmap
1454 /// acknowledges (the future `artifacthub.io/keywords` `Chart.yaml`
1455 /// annotation, the future per-cluster tag-notification overlay the
1456 /// M4 CR materializer resolves per-CR).
1457 ///
1458 /// Prior to this lift the `.etiquetas` field was accessed inline at
1459 /// two production sites — [`Self::validate_etiquetas`]'s `for
1460 /// etiqueta in &self.etiquetas` walk that gates every entry through
1461 /// [`ManifestError::EtiquetaEmpty`] / `EtiquetaInvalid` /
1462 /// `EtiquetaDuplicate`, and the caixa-helm `build_chart_yaml`
1463 /// `caixa.etiquetas.iter().cloned().chain(...)` fold that
1464 /// materializes every entry into a `Chart.yaml` `keywords:` row —
1465 /// two open-coded field-accesses that expressed no compile-time
1466 /// link back to the typed slot. A future extension of the
1467 /// `:etiquetas` axis to a richer tag surface — a per-`:etiquetas`
1468 /// structured `ChartKeyword { name, uri, category }` at the storage
1469 /// layer once the substrate absorbs `artifacthub.io/keywords`
1470 /// richer tag tuple, a per-registry `:etiquetas` allowlist the M4
1471 /// CR materializer enforces per-CR (the "cluster policy demands
1472 /// every tag come from a substrate-approved taxonomy" arm), a
1473 /// promotion of the plain `Vec<String>` byte-string list to a
1474 /// richer `Vec<ChartKeyword>` newtype discriminated on the DNS-
1475 /// 1123-label-shaped grammar the `is_chart_keyword_shape` predicate
1476 /// already resolves through — would have had to be threaded through
1477 /// both open-coded copies in lockstep or the validate gate and the
1478 /// caixa-helm emit path would silently disagree on which tags a
1479 /// given [`Caixa`] resolves to (an author's `:etiquetas ("demo"
1480 /// "aplicacao")` would satisfy validate while the caixa-helm emit
1481 /// path silently rendered a drifted other keyword list, or vice
1482 /// versa). Lifting the resolution to a typed method on the
1483 /// substrate primitive means every downstream consumer of the
1484 /// caixa's per-`Caixa` topical-tag surface reaches for exactly one
1485 /// typed dispatch — the resolver's accept-set migrates as a unit
1486 /// on any future axis addition.
1487 ///
1488 /// Second outer top-level [`Caixa`] `&[T]`-return slice-accessor —
1489 /// folds on the "outer [`Caixa`] `&[T]` slice" projection pattern
1490 /// [`Self::autores`] (b5d813f) opened, sibling in shape and
1491 /// idiom. The remaining unlifted outer-`Caixa` slice-carrying axes
1492 /// (`:deps` / `:deps-dev` / `:exe` / `:bibliotecas` / `:servicos`
1493 /// / `:upgrade-from` / `:children` / `:membros` / `:contratos`)
1494 /// fold onto the same pattern in future lifts. Sibling in shape to
1495 /// the peer per-`:supervisor`
1496 /// [`crate::supervisor::SupervisorSpec::children`] (bc92bce),
1497 /// per-`:placement` [`crate::aplicacao::Placement::clusters`]
1498 /// (a6e18d7), per-`:membros`
1499 /// [`crate::aplicacao::AplicacaoSpec::membros`] (6c77e36),
1500 /// per-`:contratos` [`crate::aplicacao::AplicacaoSpec::contratos`]
1501 /// (0dcc926), and per-`:upgrade-from :instructions`
1502 /// [`crate::upgrade::UpgradeFromEntry::instructions`] (0137e5a)
1503 /// `&[T]`-return slice accessors on the sibling per-M2 / per-M3
1504 /// typed-slot list axes, extended here to the outer top-level
1505 /// [`Caixa`] universal-axis surface. Returns `&[String]` (not
1506 /// `&Vec<String>`) because every downstream consumer of the tag
1507 /// list treats it as a read-only sequence — the slice-view is the
1508 /// narrowest borrow that supports every present + roadmapped
1509 /// consumer (`.iter()`, `.len()`, `.is_empty()`) without leaking
1510 /// the backing `Vec`'s grow/push/reserve surface no consumer of
1511 /// the typed view reaches for (the storage-side `Vec` remains
1512 /// reachable through the `pub etiquetas` field for the mutation-
1513 /// carrying serde round-trip and per-test fixture-mutation paths).
1514 /// Named `etiquetas()` to match the storage field's name; the
1515 /// accessor's identity maps onto the canonical CAIXA-SDLC §I
1516 /// vocabulary the slot's docstring already carries.
1517 #[must_use]
1518 pub fn etiquetas(&self) -> &[String] {
1519 self.etiquetas.as_slice()
1520 }
1521
1522 /// Substrate-canonical per-`Caixa` `:bibliotecas` universal-axis
1523 /// library-source-path-list slice-accessor every consumer of the
1524 /// top-level manifest's Biblioteca-source axis keys off — returns
1525 /// the author-declared `:bibliotecas` list verbatim as a
1526 /// `&[String]` slice-view over the same backing buffer the raw
1527 /// `self.bibliotecas.as_slice()` field access borrows from. Empty-
1528 /// list-carrying (`:bibliotecas` is a default-empty axis every
1529 /// `defcaixa` form supplies with an empty `()` when unset; the
1530 /// [`Self::from_lisp`] derive folds an omitted `:bibliotecas`
1531 /// through `#[serde(default)]` to `Vec::new()`, so a `Caixa` past
1532 /// parse definitionally carries a `Vec<String>` slot — possibly
1533 /// empty — and the returned `&[String]` degenerates to an empty
1534 /// slice on that arm without any silent `None` collapse).
1535 ///
1536 /// The `:bibliotecas` slot carries the universal-axis lisp-library
1537 /// entry-path list every `:kind Biblioteca` caixa emits under
1538 /// (CAIXA-SDLC §I — the author-facing surface every `defcaixa`
1539 /// form supplies alongside `:nome` / `:versao` / `:kind`; the
1540 /// substrate-wide library-carrier axis every downstream
1541 /// authoring-facing consumer keys off) — the typed slot's
1542 /// `Vec<String>` accept-set (empty-per-entry rejected through
1543 /// [`ManifestError::CodePathEmpty { slot: ":bibliotecas" }`],
1544 /// non-sandboxed-relative-shape rejected through
1545 /// [`ManifestError::CodePathShape`], non-`.lisp`-extension rejected
1546 /// through [`ManifestError::CodePathNonLispExtension`], cross-entry
1547 /// duplicate rejected through [`ManifestError::CodePathDuplicate`])
1548 /// maps onto every load-bearing downstream consumer the substrate
1549 /// carries — the [`crate::LayoutInvariants`] Biblioteca-arm
1550 /// empty-check + per-entry file-exists loop at
1551 /// caixa-core/src/layout.rs that gates each entry through
1552 /// [`crate::LayoutError::MissingLib`] / `MissingEntry`, the
1553 /// [`Self::validate_code_paths`] per-slot shape gate at
1554 /// caixa-core/src/manifest.rs that walks each entry through the
1555 /// sandbox-relative / `.lisp`-extension / cross-entry duplicate
1556 /// gates, the `feira build` per-entry `tatara_lisp::read` parse
1557 /// walk at caixa-feira/src/cmd/build.rs that phase-1-checks each
1558 /// declared library file for lexical / structural errors before
1559 /// downstream `importar` resolution, every future per-`Caixa`
1560 /// library-facing renderer the CAIXA-SDLC §I roadmap acknowledges
1561 /// (the future `tatara-lispc` compilation entry the docstring at
1562 /// caixa-feira/src/cmd/build.rs alludes to, the future per-cluster
1563 /// bytecode-caching overlay the M4 CR materializer resolves per-CR,
1564 /// the future `caixa-lsp` per-library semantic-token stream the
1565 /// caixa-lsp docstring roadmaps).
1566 ///
1567 /// Prior to this lift the `.bibliotecas` field was accessed inline
1568 /// at three production sites — [`crate::LayoutInvariants`]'s
1569 /// `caixa.bibliotecas.is_empty()` `MissingLib`-arm gate + `for p
1570 /// in &caixa.bibliotecas` `MissingEntry` walk that gates each
1571 /// declared library path through the on-disk-existence check,
1572 /// the compound-code-path `has_code = !caixa.bibliotecas.is_empty()
1573 /// || !caixa.exe.is_empty() || !caixa.servicos.is_empty()` OR-fold
1574 /// on the [`crate::LayoutError::SupervisorOwnsCode`] /
1575 /// `AplicacaoOwnsCode` kind-coherence gate, and the `feira build`
1576 /// per-entry `for entry in &caixa.bibliotecas` + `caixa.bibliotecas.
1577 /// len()` phase-1 tatara-lispc-precursor parse walk — three open-
1578 /// coded field-accesses that expressed no compile-time link back
1579 /// to the typed slot. A future extension of the `:bibliotecas`
1580 /// axis to a richer library surface — a per-`:bibliotecas`
1581 /// structured `BibliotecaEntry { path, edition, exports }` at the
1582 /// storage layer once the substrate absorbs the per-library
1583 /// language-edition + explicit-exports tuple the tatara-lisp
1584 /// module-system roadmap acknowledges, a per-registry
1585 /// `:bibliotecas` allowlist the M4 CR materializer enforces
1586 /// per-CR (the "cluster policy demands every biblioteca declare
1587 /// its own :edicao" arm), a promotion of the plain `Vec<String>`
1588 /// byte-string list to a richer `Vec<LibraryPath>` newtype
1589 /// discriminated on the `lib/<nome>.lisp`-shape grammar the
1590 /// [`crate::render::is_sandboxed_relative_path`] +
1591 /// [`crate::render::is_lisp_extension`] predicates already resolve
1592 /// through — would have had to be threaded through all three
1593 /// open-coded copies in lockstep or the layout gate, the shape
1594 /// validator, and the `feira build` phase-1 parse walk would
1595 /// silently disagree on which library paths a given [`Caixa`]
1596 /// resolves to (an author's `:bibliotecas ("lib/foo.lisp"
1597 /// "lib/bar.lisp")` would satisfy layout while `feira build`
1598 /// silently parsed a drifted other list, or vice versa). Lifting
1599 /// the resolution to a typed method on the substrate primitive
1600 /// means every downstream consumer of the caixa's per-`Caixa`
1601 /// library-source surface reaches for exactly one typed dispatch
1602 /// — the resolver's accept-set migrates as a unit on any future
1603 /// axis addition.
1604 ///
1605 /// Third outer top-level [`Caixa`] `&[T]`-return slice-accessor —
1606 /// folds on the "outer [`Caixa`] `&[T]` slice" projection pattern
1607 /// [`Self::autores`] (b5d813f) opened and [`Self::etiquetas`]
1608 /// (78c7d3c) folded on, sibling in shape and idiom. The remaining
1609 /// unlifted outer-`Caixa` slice-carrying axes (`:deps` /
1610 /// `:deps-dev` / `:exe` / `:servicos` / `:upgrade-from` /
1611 /// `:children` / `:membros` / `:contratos`) fold onto the same
1612 /// pattern in future lifts. Sibling in shape to the peer
1613 /// per-`:supervisor`
1614 /// [`crate::supervisor::SupervisorSpec::children`] (bc92bce),
1615 /// per-`:placement` [`crate::aplicacao::Placement::clusters`]
1616 /// (a6e18d7), per-`:membros`
1617 /// [`crate::aplicacao::AplicacaoSpec::membros`] (6c77e36),
1618 /// per-`:contratos` [`crate::aplicacao::AplicacaoSpec::contratos`]
1619 /// (0dcc926), and per-`:upgrade-from :instructions`
1620 /// [`crate::upgrade::UpgradeFromEntry::instructions`] (0137e5a)
1621 /// `&[T]`-return slice accessors on the sibling per-M2 / per-M3
1622 /// typed-slot list axes, extended here to the outer top-level
1623 /// [`Caixa`] universal-axis surface. Returns `&[String]` (not
1624 /// `&Vec<String>`) because every downstream consumer of the
1625 /// library-source list treats it as a read-only sequence — the
1626 /// slice-view is the narrowest borrow that supports every
1627 /// present + roadmapped consumer (`.iter()`, `.len()`,
1628 /// `.is_empty()`) without leaking the backing `Vec`'s
1629 /// grow/push/reserve surface no consumer of the typed view
1630 /// reaches for (the storage-side `Vec` remains reachable through
1631 /// the `pub bibliotecas` field for the mutation-carrying serde
1632 /// round-trip and per-test fixture-mutation paths). Named
1633 /// `bibliotecas()` to match the storage field's name; the
1634 /// accessor's identity maps onto the canonical CAIXA-SDLC §I
1635 /// vocabulary the slot's docstring already carries.
1636 #[must_use]
1637 pub fn bibliotecas(&self) -> &[String] {
1638 self.bibliotecas.as_slice()
1639 }
1640
1641 /// Substrate-canonical per-`Caixa` `:exe` universal-axis
1642 /// nix-built-executable-entry-path-list slice-accessor every consumer
1643 /// of the top-level manifest's Binario-executable axis keys off —
1644 /// returns the author-declared `:exe` list verbatim as a `&[String]`
1645 /// slice-view over the same backing buffer the raw
1646 /// `self.exe.as_slice()` field access borrows from. Empty-list-
1647 /// carrying (`:exe` is a default-empty axis every `defcaixa` form
1648 /// supplies with an empty `()` when unset; the [`Self::from_lisp`]
1649 /// derive folds an omitted `:exe` through `#[serde(default)]` to
1650 /// `Vec::new()`, so a `Caixa` past parse definitionally carries a
1651 /// `Vec<String>` slot — possibly empty — and the returned `&[String]`
1652 /// degenerates to an empty slice on that arm without any silent
1653 /// `None` collapse).
1654 ///
1655 /// The `:exe` slot carries the universal-axis nix-built executable
1656 /// entry-path list every `:kind Binario` caixa emits under
1657 /// (CAIXA-SDLC §I — the author-facing surface every `defcaixa`
1658 /// form supplies alongside `:nome` / `:versao` / `:kind`; the
1659 /// substrate-wide `exe/`-directory-fenced entry-carrier axis every
1660 /// downstream flake-build-facing consumer keys off) — the typed
1661 /// slot's `Vec<String>` accept-set (empty-per-entry rejected
1662 /// through [`ManifestError::CodePathEmpty { slot: ":exe" }`],
1663 /// non-sandboxed-relative-shape rejected through
1664 /// [`ManifestError::CodePathShape`], cross-entry duplicate rejected
1665 /// through [`ManifestError::CodePathDuplicate`], out-of-`exe/`-
1666 /// directory paths rejected past the layout's
1667 /// [`crate::LayoutError::ExeOutsideDir`] `starts_with` fence) maps
1668 /// onto every load-bearing downstream consumer the substrate carries
1669 /// — the [`crate::LayoutInvariants`] Binario-arm empty-check +
1670 /// per-entry file-exists + `exe/`-directory-fence loop at
1671 /// caixa-core/src/layout.rs that gates each entry through
1672 /// [`crate::LayoutError::BinarioWithoutExe`] / `MissingEntry` /
1673 /// `ExeOutsideDir`, the compound `has_code` OR-fold on the
1674 /// [`crate::LayoutError::SupervisorOwnsCode`] /
1675 /// [`crate::LayoutError::AplicacaoOwnsCode`] kind-coherence gate
1676 /// that fences code-surface slots off from the two no-code kinds,
1677 /// [`Self::declared_foreign_code_slots`]'s `!self.exe.is_empty()`
1678 /// arm on the [`crate::LayoutError::ForeignCodeSlot`] gate that
1679 /// fences the `:exe` code surface off from every non-Binario code-
1680 /// running kind, [`Self::validate_code_paths`]'s per-slot shape gate
1681 /// that walks each entry through the sandbox-relative / cross-entry
1682 /// duplicate gates, every future per-`Caixa` executable-facing
1683 /// renderer the CAIXA-SDLC §I roadmap acknowledges (the future
1684 /// `caixa-flake` per-Binario `packages.<system>.<nome>` derivation
1685 /// entry the caixa-flake docstring roadmaps, the future per-cluster
1686 /// `nix-store` overlay the M4 CR materializer resolves per-CR, the
1687 /// future `feira nix` per-executable Binario-target emit path).
1688 ///
1689 /// Prior to this lift the `.exe` field was accessed inline at three
1690 /// production sites — the compound-code-path `has_code =
1691 /// !caixa.bibliotecas().is_empty() || !caixa.exe.is_empty() ||
1692 /// !caixa.servicos.is_empty()` OR-fold on the
1693 /// [`crate::LayoutError::SupervisorOwnsCode`] /
1694 /// `AplicacaoOwnsCode` kind-coherence gate, the Binario-arm
1695 /// `caixa.exe.is_empty()` [`crate::LayoutError::BinarioWithoutExe`]
1696 /// gate, the per-entry `for p in &caixa.exe`
1697 /// `MissingEntry`/`ExeOutsideDir` walk, and the
1698 /// [`Self::declared_foreign_code_slots`]'s
1699 /// `!self.exe.is_empty()` arm on the `ForeignCodeSlot` gate — four
1700 /// open-coded field-accesses that expressed no compile-time link
1701 /// back to the typed slot. A future extension of the `:exe` axis
1702 /// to a richer executable surface — a per-`:exe` structured
1703 /// `BinarioEntry { path, wrapper, capabilities }` at the storage
1704 /// layer once the substrate absorbs the per-executable
1705 /// nix-wrapper + linux-capabilities tuple the CAIXA-SDLC §I
1706 /// executable roadmap acknowledges, a per-registry `:exe` allowlist
1707 /// the M4 CR materializer enforces per-CR (the "cluster policy
1708 /// demands every Binario declare an explicit `:wrapper`" arm), a
1709 /// promotion of the plain `Vec<String>` byte-string list to a
1710 /// richer `Vec<ExecutablePath>` newtype discriminated on the
1711 /// `exe/<nome>`-shape grammar the layout's `starts_with(exe_dir)`
1712 /// fence already resolves through — would have had to be threaded
1713 /// through all four open-coded copies in lockstep or the layout
1714 /// gate, the shape validator, and the `feira nix` emit path would
1715 /// silently disagree on which executable paths a given [`Caixa`]
1716 /// resolves to (an author's `:exe ("exe/cli" "exe/serve")` would
1717 /// satisfy layout while `feira nix` silently packaged a drifted
1718 /// other list, or vice versa). Lifting the resolution to a typed
1719 /// method on the substrate primitive means every downstream
1720 /// consumer of the caixa's per-`Caixa` executable-source surface
1721 /// reaches for exactly one typed dispatch — the resolver's accept-
1722 /// set migrates as a unit on any future axis addition.
1723 ///
1724 /// Fourth outer top-level [`Caixa`] `&[T]`-return slice-accessor —
1725 /// folds on the "outer [`Caixa`] `&[T]` slice" projection pattern
1726 /// [`Self::autores`] (b5d813f) opened, [`Self::etiquetas`]
1727 /// (78c7d3c) folded on, and [`Self::bibliotecas`] (8a36c23) closed
1728 /// the universal-axis text-tag family of. Opens the outer-`Caixa`
1729 /// foreign-code-slot `&[T]` sub-family the sibling `:servicos`
1730 /// future lift closes onto (per the trio of code-surface list slots
1731 /// the [`Self::validate_code_paths`] per-slot dispatch tuple
1732 /// already carries — `:bibliotecas` + `:exe` + `:servicos`, of which
1733 /// `:bibliotecas` landed at 8a36c23 and `:servicos` remains as the
1734 /// last unlifted code-surface slot). Sibling in shape to the peer
1735 /// per-`:supervisor` [`crate::supervisor::SupervisorSpec::children`]
1736 /// (bc92bce), per-`:placement`
1737 /// [`crate::aplicacao::Placement::clusters`] (a6e18d7),
1738 /// per-`:membros` [`crate::aplicacao::AplicacaoSpec::membros`]
1739 /// (6c77e36), per-`:contratos`
1740 /// [`crate::aplicacao::AplicacaoSpec::contratos`] (0dcc926), and
1741 /// per-`:upgrade-from :instructions`
1742 /// [`crate::upgrade::UpgradeFromEntry::instructions`] (0137e5a)
1743 /// `&[T]`-return slice accessors on the sibling per-M2 / per-M3
1744 /// typed-slot list axes, extended here to the outer top-level
1745 /// [`Caixa`] universal-axis surface. Returns `&[String]` (not
1746 /// `&Vec<String>`) because every downstream consumer of the
1747 /// executable-source list treats it as a read-only sequence — the
1748 /// slice-view is the narrowest borrow that supports every
1749 /// present + roadmapped consumer (`.iter()`, `.len()`,
1750 /// `.is_empty()`) without leaking the backing `Vec`'s
1751 /// grow/push/reserve surface no consumer of the typed view
1752 /// reaches for (the storage-side `Vec` remains reachable through
1753 /// the `pub exe` field for the mutation-carrying serde
1754 /// round-trip and per-test fixture-mutation paths). Named `exe()`
1755 /// to match the storage field's name; the accessor's identity
1756 /// maps onto the canonical CAIXA-SDLC §I vocabulary the slot's
1757 /// docstring already carries.
1758 #[must_use]
1759 pub fn exe(&self) -> &[String] {
1760 self.exe.as_slice()
1761 }
1762
1763 /// Substrate-canonical per-`Caixa` `:servicos` universal-axis
1764 /// ComputeUnit-CR-YAML-entry-path-list slice-accessor every consumer
1765 /// of the top-level manifest's Servico-component axis keys off —
1766 /// returns the author-declared `:servicos` list verbatim as a
1767 /// `&[String]` slice-view over the same backing buffer the raw
1768 /// `self.servicos.as_slice()` field access borrows from. Empty-list-
1769 /// carrying (`:servicos` is a default-empty axis every `defcaixa`
1770 /// form supplies with an empty `()` when unset; the
1771 /// [`Self::from_lisp`] derive folds an omitted `:servicos` through
1772 /// `#[serde(default)]` to `Vec::new()`, so a `Caixa` past parse
1773 /// definitionally carries a `Vec<String>` slot — possibly empty —
1774 /// and the returned `&[String]` degenerates to an empty slice on
1775 /// that arm without any silent `None` collapse).
1776 ///
1777 /// The `:servicos` slot carries the universal-axis
1778 /// `.computeunit.yaml` ComputeUnit-CR entry-path list every
1779 /// `:kind Servico` caixa emits under (CAIXA-SDLC §I — the
1780 /// author-facing surface every `defcaixa` form supplies alongside
1781 /// `:nome` / `:versao` / `:kind`; the substrate-wide
1782 /// `servicos/`-directory-fenced entry-carrier axis every downstream
1783 /// Servico-facing renderer keys off) — the typed slot's
1784 /// `Vec<String>` accept-set (empty-per-entry rejected through
1785 /// [`ManifestError::CodePathEmpty { slot: ":servicos" }`],
1786 /// non-sandboxed-relative-shape rejected through
1787 /// [`ManifestError::CodePathShape`], non-`.computeunit.yaml`
1788 /// extension rejected through
1789 /// [`ManifestError::CodePathNonComputeUnitYamlExtension`], cross-
1790 /// entry duplicate rejected through
1791 /// [`ManifestError::CodePathDuplicate`], `len != 1` rejected by the
1792 /// V0 [`crate::ServicoCountMismatch`] gate on the per-Servico
1793 /// renderer entry-points, out-of-`servicos/`-directory paths
1794 /// rejected past the layout's [`crate::LayoutError::ServicoOutsideDir`]
1795 /// `starts_with` fence) maps onto every load-bearing downstream
1796 /// consumer the substrate carries — the [`crate::LayoutInvariants`]
1797 /// Servico-arm empty-check + per-entry file-exists + `servicos/`-
1798 /// directory-fence loop at caixa-core/src/layout.rs that gates each
1799 /// entry through [`crate::LayoutError::ServicoWithoutServicos`] /
1800 /// `MissingEntry` / `ServicoOutsideDir`, the compound `has_code`
1801 /// OR-fold on the [`crate::LayoutError::SupervisorOwnsCode`] /
1802 /// [`crate::LayoutError::AplicacaoOwnsCode`] kind-coherence gate
1803 /// that fences code-surface slots off from the two no-code kinds,
1804 /// [`Self::declared_foreign_code_slots`]'s
1805 /// `!self.servicos.is_empty()` arm on the
1806 /// [`crate::LayoutError::ForeignCodeSlot`] gate that fences the
1807 /// `:servicos` code surface off from every non-Servico code-running
1808 /// kind, [`Self::validate_code_paths`]'s per-slot shape gate that
1809 /// walks each entry through the sandbox-relative / `.computeunit.
1810 /// yaml`-extension / cross-entry duplicate gates, the
1811 /// [`crate::require_single_servico`] V0 singularity gate every
1812 /// per-Servico renderer entry-point runs through
1813 /// [`crate::require_v0_servico_shape`], the `feira chart` /
1814 /// `feira deploy` per-verb `first_servico_path` walk at
1815 /// caixa-feira/src/cmd/chart.rs that resolves the singleton
1816 /// ComputeUnit-CR file, every future per-`Caixa` Servico-facing
1817 /// renderer the CAIXA-SDLC §I roadmap acknowledges (the future
1818 /// per-Servico OCI packager, the future M4
1819 /// `wasm.pleme.io/v1alpha1/ComputeUnit` CR materializer, the future
1820 /// per-Servico OTel collector-config emit).
1821 ///
1822 /// Prior to this lift the `.servicos` field was accessed inline at
1823 /// five production sites — the compound-code-path `has_code =
1824 /// !caixa.bibliotecas().is_empty() || !caixa.exe().is_empty() ||
1825 /// !caixa.servicos.is_empty()` OR-fold on the
1826 /// [`crate::LayoutError::SupervisorOwnsCode`] /
1827 /// `AplicacaoOwnsCode` kind-coherence gate, the Servico-arm
1828 /// `caixa.servicos.is_empty()`
1829 /// [`crate::LayoutError::ServicoWithoutServicos`] gate, the
1830 /// per-entry `for p in &caixa.servicos`
1831 /// `MissingEntry`/`ServicoOutsideDir` walk, the
1832 /// [`Self::declared_foreign_code_slots`]'s
1833 /// `!self.servicos.is_empty()` arm on the `ForeignCodeSlot` gate,
1834 /// and the [`crate::require_single_servico`] V0 count gate's
1835 /// `caixa.servicos.len() == 1` / `caixa.servicos.len()` count
1836 /// projection (both the accept-arm predicate and the
1837 /// diagnostic-carrying `ServicoCountMismatch { count }`
1838 /// projection) — five open-coded field-accesses across three
1839 /// crates that expressed no compile-time link back to the typed
1840 /// slot. A future extension of the `:servicos` axis to a richer
1841 /// component surface — a per-`:servicos` structured
1842 /// `ServicoEntry { path, world, capabilities }` at the storage
1843 /// layer once the substrate absorbs the per-component WIT-world +
1844 /// capability-set tuple the CAIXA-SDLC §I Servico roadmap
1845 /// acknowledges, a per-registry `:servicos` allowlist the M4 CR
1846 /// materializer enforces per-CR (the "cluster policy demands every
1847 /// Servico declare an explicit `:world`" arm), a promotion of the
1848 /// plain `Vec<String>` byte-string list to a richer
1849 /// `Vec<ComputeUnitPath>` newtype discriminated on the
1850 /// `servicos/<nome>.computeunit.yaml`-shape grammar the layout's
1851 /// `starts_with(servicos_dir)` fence and the
1852 /// [`crate::render::is_computeunit_yaml_extension`] predicate
1853 /// already resolve through, a promotion of the V0 singleton
1854 /// contract to a multi-component `Vec<ComputeUnitPath>` past the M5
1855 /// component-model multi-world boundary — would have had to be
1856 /// threaded through all five open-coded copies in lockstep or the
1857 /// layout gate, the shape validator, the V0 count gate, and the
1858 /// `feira chart` / `feira deploy` entry-point walks would silently
1859 /// disagree on which ComputeUnit-CR paths a given [`Caixa`]
1860 /// resolves to (an author's `:servicos ("servicos/foo.computeunit.
1861 /// yaml")` would satisfy layout while `feira chart` silently
1862 /// packaged a drifted other list, or vice versa). Lifting the
1863 /// resolution to a typed method on the substrate primitive means
1864 /// every downstream consumer of the caixa's per-`Caixa`
1865 /// ComputeUnit-CR-source surface reaches for exactly one typed
1866 /// dispatch — the resolver's accept-set migrates as a unit on any
1867 /// future axis addition.
1868 ///
1869 /// Fifth and final outer top-level [`Caixa`] `&[T]`-return slice-
1870 /// accessor — folds on the "outer [`Caixa`] `&[T]` slice"
1871 /// projection pattern [`Self::autores`] (b5d813f) opened,
1872 /// [`Self::etiquetas`] (78c7d3c) folded on, [`Self::bibliotecas`]
1873 /// (8a36c23) closed the universal-axis text-tag family of, and
1874 /// [`Self::exe`] (65d9527) opened the foreign-code-slot sub-family
1875 /// of. Closes the outer-`Caixa` foreign-code-slot `&[T]` sub-family
1876 /// — with `:bibliotecas`, `:exe`, and `:servicos` now each carrying
1877 /// a substrate-canonical slice accessor, the trio of code-surface
1878 /// list slots the [`Self::validate_code_paths`] per-slot dispatch
1879 /// tuple carries is complete on the typed dispatch surface (the
1880 /// internal `[(":bibliotecas", &self.bibliotecas, ..), (":exe",
1881 /// &self.exe, ..), (":servicos", &self.servicos, ..)]` per-slot
1882 /// dispatch tuple's homogeneous `&Vec<String>`-typed shape blocks a
1883 /// per-element accessor swap in isolation — a future companion lift
1884 /// promotes the tuple's element type to `&[String]` and threads the
1885 /// triple of typed dispatches through as a unit). Sibling in shape
1886 /// to the peer per-`:supervisor`
1887 /// [`crate::supervisor::SupervisorSpec::children`] (bc92bce),
1888 /// per-`:placement` [`crate::aplicacao::Placement::clusters`]
1889 /// (a6e18d7), per-`:membros`
1890 /// [`crate::aplicacao::AplicacaoSpec::membros`] (6c77e36),
1891 /// per-`:contratos`
1892 /// [`crate::aplicacao::AplicacaoSpec::contratos`] (0dcc926), and
1893 /// per-`:upgrade-from :instructions`
1894 /// [`crate::upgrade::UpgradeFromEntry::instructions`] (0137e5a)
1895 /// `&[T]`-return slice accessors on the sibling per-M2 / per-M3
1896 /// typed-slot list axes, extended here to the outer top-level
1897 /// [`Caixa`] universal-axis surface. Returns `&[String]` (not
1898 /// `&Vec<String>`) because every downstream consumer of the
1899 /// ComputeUnit-CR-source list treats it as a read-only sequence —
1900 /// the slice-view is the narrowest borrow that supports every
1901 /// present + roadmapped consumer (`.iter()`, `.len()`,
1902 /// `.is_empty()`, `.first()`) without leaking the backing `Vec`'s
1903 /// grow/push/reserve surface no consumer of the typed view reaches
1904 /// for (the storage-side `Vec` remains reachable through the
1905 /// `pub servicos` field for the mutation-carrying serde round-trip
1906 /// and per-test fixture-mutation paths, and for the
1907 /// [`Self::validate_code_paths`] per-slot dispatch tuple whose
1908 /// homogeneous-element-type shape carries the raw field access
1909 /// until the trio-closure lift promotes the tuple as a unit).
1910 /// Named `servicos()` to match the storage field's name; the
1911 /// accessor's identity maps onto the canonical CAIXA-SDLC §I
1912 /// vocabulary the slot's docstring already carries.
1913 #[must_use]
1914 pub fn servicos(&self) -> &[String] {
1915 self.servicos.as_slice()
1916 }
1917
1918 /// Substrate-canonical per-`Caixa` `:deps` universal-axis
1919 /// runtime-dependency-declaration-list slice-accessor every consumer
1920 /// of the top-level manifest's runtime-dep-graph axis keys off —
1921 /// returns the author-declared `:deps` list verbatim as a `&[Dep]`
1922 /// slice-view over the same backing buffer the raw
1923 /// `self.deps.as_slice()` field access borrows from. Empty-list-
1924 /// carrying (`:deps` is a default-empty axis every `defcaixa` form
1925 /// supplies with an empty `()` when unset; the [`Self::from_lisp`]
1926 /// derive folds an omitted `:deps` through `#[serde(default)]` to
1927 /// `Vec::new()`, so a `Caixa` past parse definitionally carries a
1928 /// `Vec<Dep>` slot — possibly empty — and the returned `&[Dep]`
1929 /// degenerates to an empty slice on that arm without any silent
1930 /// `None` collapse).
1931 ///
1932 /// The `:deps` slot carries the universal-axis runtime dependency
1933 /// list every kind of caixa emits under (CAIXA-SDLC §I — the author-
1934 /// facing surface every `defcaixa` form supplies alongside `:nome` /
1935 /// `:versao` / `:kind`; the substrate-wide runtime-closure-input axis
1936 /// every downstream resolver-facing artifact emits under) — the
1937 /// typed slot's `Vec<Dep>` accept-set (empty-`:nome` rejected through
1938 /// [`DepError::NomeEmpty`], non-DNS-1123-label `:nome` rejected
1939 /// through [`DepError::NomeInvalid`], malformed `:versao` rejected
1940 /// through [`DepError::VersaoInvalid`], empty `:fonte.repo` rejected
1941 /// through [`DepError::FonteRepoEmpty`], within-list duplicate `:nome`
1942 /// rejected through [`DepError::DuplicateNome { list: ":deps" }`])
1943 /// maps onto every load-bearing downstream consumer the substrate
1944 /// carries — the [`Self::validate_deps`] per-entry
1945 /// [`Dep::validate`] + within-list dedup walk at
1946 /// caixa-core/src/manifest.rs, the [`crate::dep::validate_no_self_dep`]
1947 /// cross-list self-reference gate at caixa-core/src/layout.rs that
1948 /// checks each entry against the caixa's own `:nome`, the
1949 /// caixa-resolver `for dep in &root.deps` closure walk at
1950 /// caixa-resolver/src/resolve.rs that seeds every git-clone target
1951 /// through the resolver's [`crate::Dep`]-keyed pipeline, the
1952 /// caixa-crd `caixa.deps.iter().map(dep_into_ref).collect()` fold at
1953 /// caixa-crd/src/conversion.rs that materializes each entry into the
1954 /// K8s `Caixa` CR's `spec.deps` field, every future per-`Caixa`
1955 /// resolver-facing renderer the CAIXA-SDLC §I roadmap acknowledges
1956 /// (the future per-cluster runtime-closure-audit overlay the M4 CR
1957 /// materializer resolves per-CR, the future `lacre.lisp` BLAKE3-
1958 /// closure emit walk the caixa-resolver docstring roadmaps).
1959 ///
1960 /// First outer top-level [`Caixa`] `&[Dep]`-return slice-accessor —
1961 /// opens the outer-`Caixa` dependency-slot `&[Dep]` sub-family the
1962 /// sibling `:deps-dev` future lift closes on. Peer of the closed
1963 /// outer-`Caixa` foreign-code-slot `&[String]` sub-family
1964 /// ([`Self::bibliotecas`] 8a36c23, [`Self::exe`] 65d9527,
1965 /// [`Self::servicos`] 611f78b) and the outer-`Caixa` universal-axis
1966 /// text-tag family ([`Self::autores`] b5d813f, [`Self::etiquetas`]
1967 /// 78c7d3c) — extends the "outer [`Caixa`] `&[T]` slice" projection
1968 /// pattern onto a novel element-type axis (`Dep` composite vs the
1969 /// prior sibling family's `String` scalar). Sibling in shape to the
1970 /// peer per-`:supervisor`
1971 /// [`crate::supervisor::SupervisorSpec::children`] (bc92bce),
1972 /// per-`:placement` [`crate::aplicacao::Placement::clusters`]
1973 /// (a6e18d7), per-`:membros`
1974 /// [`crate::aplicacao::AplicacaoSpec::membros`] (6c77e36),
1975 /// per-`:contratos` [`crate::aplicacao::AplicacaoSpec::contratos`]
1976 /// (0dcc926), and per-`:upgrade-from :instructions`
1977 /// [`crate::upgrade::UpgradeFromEntry::instructions`] (0137e5a)
1978 /// `&[T]`-return slice accessors on the sibling per-M2 / per-M3
1979 /// typed-slot list axes, extended here to the outer top-level
1980 /// [`Caixa`] universal-axis dep-graph surface. Returns `&[Dep]`
1981 /// (not `&Vec<Dep>`) because every downstream consumer of the
1982 /// runtime-dep list treats it as a read-only sequence — the slice-
1983 /// view is the narrowest borrow that supports every present +
1984 /// roadmapped consumer (`.iter()`, `.len()`, `.is_empty()`) without
1985 /// leaking the backing `Vec`'s grow/push/reserve surface no consumer
1986 /// of the typed view reaches for (the storage-side `Vec` remains
1987 /// reachable through the `pub deps` field for the mutation-carrying
1988 /// serde round-trip and per-test fixture-mutation paths). Named
1989 /// `deps()` to match the storage field's name; the accessor's
1990 /// identity maps onto the canonical CAIXA-SDLC §I vocabulary the
1991 /// slot's docstring already carries.
1992 #[must_use]
1993 pub fn deps(&self) -> &[Dep] {
1994 self.deps.as_slice()
1995 }
1996
1997 /// Substrate-canonical per-`Caixa` `:deps-dev` universal-axis
1998 /// development-only-dependency-declaration-list slice-accessor every
1999 /// consumer of the top-level manifest's dev-dep-graph axis keys off —
2000 /// returns the author-declared `:deps-dev` list verbatim as a `&[Dep]`
2001 /// slice-view over the same backing buffer the raw
2002 /// `self.deps_dev.as_slice()` field access borrows from. Empty-list-
2003 /// carrying (`:deps-dev` is a default-empty axis every `defcaixa`
2004 /// form supplies with an empty `()` when unset; the
2005 /// [`Self::from_lisp`] derive folds an omitted `:deps-dev` through
2006 /// `#[serde(default)]` to `Vec::new()`, so a `Caixa` past parse
2007 /// definitionally carries a `Vec<Dep>` slot — possibly empty — and
2008 /// the returned `&[Dep]` degenerates to an empty slice on that arm
2009 /// without any silent `None` collapse).
2010 ///
2011 /// The `:deps-dev` slot carries the universal-axis dev-only
2012 /// dependency list every kind of caixa emits under (CAIXA-SDLC §I —
2013 /// the author-facing sibling of `:deps` that every `defcaixa` form
2014 /// supplies to declare tests / lint / bench closures the runtime
2015 /// `:deps` axis does not carry; the substrate-wide dev-closure-input
2016 /// axis every downstream test-facing artifact emits under, matching
2017 /// Cargo's `[dev-dependencies]` table's dev-time-only visibility
2018 /// contract) — the typed slot's `Vec<Dep>` accept-set (empty-`:nome`
2019 /// rejected through [`DepError::NomeEmpty`], non-DNS-1123-label
2020 /// `:nome` rejected through [`DepError::NomeInvalid`], malformed
2021 /// `:versao` rejected through [`DepError::VersaoInvalid`], empty
2022 /// `:fonte.repo` rejected through [`DepError::FonteRepoEmpty`],
2023 /// within-list duplicate `:nome` rejected through
2024 /// [`DepError::DuplicateNome { list: ":deps-dev" }`]) maps onto every
2025 /// load-bearing downstream consumer the substrate carries — the
2026 /// [`Self::validate_deps`] per-entry [`Dep::validate`] + within-list
2027 /// dedup walk at caixa-core/src/manifest.rs, the
2028 /// [`crate::dep::validate_no_self_dep`] cross-list self-reference
2029 /// gate at caixa-core/src/layout.rs that checks each entry against
2030 /// the caixa's own `:nome`, the caixa-resolver
2031 /// `for dep in &root.deps_dev` closure walk at
2032 /// caixa-resolver/src/resolve.rs that seeds every dev-only git-clone
2033 /// target through the resolver's [`crate::Dep`]-keyed pipeline, and
2034 /// every future per-`Caixa` resolver-facing renderer the CAIXA-SDLC
2035 /// §I roadmap acknowledges (the future per-cluster dev-closure-audit
2036 /// overlay the M4 CR materializer resolves per-CR, the future
2037 /// `lacre.lisp` BLAKE3-closure emit walk the caixa-resolver docstring
2038 /// roadmaps).
2039 ///
2040 /// Second outer top-level [`Caixa`] `&[Dep]`-return slice-accessor —
2041 /// closes the outer-`Caixa` dependency-slot `&[Dep]` sub-family the
2042 /// sibling [`Self::deps`] (ad34b4e) opened on. The two accessors
2043 /// jointly close the two-list dep-graph surface every downstream
2044 /// resolver-facing consumer keys off (runtime `:deps` +
2045 /// dev-only `:deps-dev`, the canonical Cargo-shaped dependency-table
2046 /// pair the [`Self::validate_deps`] gate already walks in canonical
2047 /// order). Peer of the closed outer-`Caixa` foreign-code-slot
2048 /// `&[String]` sub-family ([`Self::bibliotecas`] 8a36c23,
2049 /// [`Self::exe`] 65d9527, [`Self::servicos`] 611f78b) and the outer-
2050 /// `Caixa` universal-axis text-tag family ([`Self::autores`]
2051 /// b5d813f, [`Self::etiquetas`] 78c7d3c) — folds the "outer
2052 /// [`Caixa`] `&[T]` slice" projection pattern onto the sibling
2053 /// dev-dep composite-element axis (`Dep` composite, matching the
2054 /// [`Self::deps`] element type). Sibling in shape to the peer
2055 /// per-`:supervisor` [`crate::supervisor::SupervisorSpec::children`]
2056 /// (bc92bce), per-`:placement`
2057 /// [`crate::aplicacao::Placement::clusters`] (a6e18d7),
2058 /// per-`:membros` [`crate::aplicacao::AplicacaoSpec::membros`]
2059 /// (6c77e36), per-`:contratos`
2060 /// [`crate::aplicacao::AplicacaoSpec::contratos`] (0dcc926), and
2061 /// per-`:upgrade-from :instructions`
2062 /// [`crate::upgrade::UpgradeFromEntry::instructions`] (0137e5a)
2063 /// `&[T]`-return slice accessors on the sibling per-M2 / per-M3
2064 /// typed-slot list axes, folded here to the outer top-level
2065 /// [`Caixa`] universal-axis dev-dep-graph surface. Returns `&[Dep]`
2066 /// (not `&Vec<Dep>`) because every downstream consumer of the
2067 /// dev-dep list treats it as a read-only sequence — the slice-view
2068 /// is the narrowest borrow that supports every present +
2069 /// roadmapped consumer (`.iter()`, `.len()`, `.is_empty()`) without
2070 /// leaking the backing `Vec`'s grow/push/reserve surface no consumer
2071 /// of the typed view reaches for (the storage-side `Vec` remains
2072 /// reachable through the `pub deps_dev` field for the mutation-
2073 /// carrying serde round-trip and per-test fixture-mutation paths).
2074 /// Named `deps_dev()` to match the storage field's `snake_case` name;
2075 /// the kebab-case author-surface tag `:deps-dev` is the same axis
2076 /// after tatara-lisp's kebab↔snake fold and the accessor's identity
2077 /// maps onto the canonical CAIXA-SDLC §I vocabulary the slot's
2078 /// docstring already carries.
2079 #[must_use]
2080 pub fn deps_dev(&self) -> &[Dep] {
2081 self.deps_dev.as_slice()
2082 }
2083
2084 /// Substrate-canonical per-[`Caixa`] typed-dispatch read accessor
2085 /// every consumer that walks one of the two dep-list axes keyed on a
2086 /// [`crate::dep::DepList`] discriminant reaches for — routes the
2087 /// `(list: DepList) -> &[Dep]` projection through one typed method on
2088 /// the substrate primitive rather than the prior open-coded
2089 /// `match list { Prod => caixa.deps(), Dev => caixa.deps_dev() }`
2090 /// inline dispatch every per-axis walker would otherwise carry.
2091 /// Returns the author-declared per-list `Vec<Dep>` verbatim as a
2092 /// `&[Dep]` slice-view over the same backing buffer the sibling
2093 /// [`Self::deps`] (`Prod`) / [`Self::deps_dev`] (`Dev`) per-slot
2094 /// accessors borrow from, preserving the empty-list-carrying invariant
2095 /// each per-slot accessor already establishes (`:deps` / `:deps-dev`
2096 /// are default-empty axes every `defcaixa` form supplies with an empty
2097 /// `()` when unset; the [`Self::from_lisp`] derive folds an omitted
2098 /// list through `#[serde(default)]` to `Vec::new()`, so both arms
2099 /// definitionally carry a `Vec<Dep>` slot — possibly empty — and the
2100 /// returned `&[Dep]` degenerates to an empty slice on either arm
2101 /// without any silent `None` collapse).
2102 ///
2103 /// The [`crate::dep::DepList`] closed-set typed enum is the
2104 /// substrate's canonical discriminator for the "runtime-closure
2105 /// `:deps` vs dev-only-closure `:deps-dev`" axis every dep-list
2106 /// consumer dispatches on — the compiler-checked exhaustiveness on
2107 /// the enum's `match` arms is the build-time guarantee that no future
2108 /// per-list read-site regresses to a bare-`bool`-flag inline dispatch
2109 /// that a future third dep-list axis (a `:deps-build` build-only
2110 /// closure once the substrate grows cross-artifact heterogeneous
2111 /// dep-graphs, per CAIXA-SDLC §I) would silently split at every
2112 /// consumer. Prior to this the read side carried two per-slot
2113 /// accessors ([`Self::deps`] ad34b4e, [`Self::deps_dev`]) and no
2114 /// typed dispatch that a per-axis walker could parametrise on, so
2115 /// every per-list walker (the [`Self::validate_deps`] per-list
2116 /// [`crate::render::insert_first_seen`] dedup walk, a future
2117 /// `feira app graph` per-list dep summary, a future M4 per-cluster
2118 /// dev-closure-audit overlay the CR materializer resolves per-CR)
2119 /// open-coded the same two-block "run over `:deps`, then run over
2120 /// `:deps-dev`" pattern — a silent duplication that a future third
2121 /// dep-list axis would have had to grow a third block at every site.
2122 ///
2123 /// Peer of the sibling [`Self::push_dep`] typed-mutation dispatch
2124 /// (359fba5) — closes the two-side dispatch symmetry on the outer
2125 /// [`Caixa`] two-list dep-graph surface: `push_dep` on the mutation
2126 /// side, `deps_of` on the read side, both keyed on the same
2127 /// [`crate::dep::DepList`] discriminator. Same "one typed dispatch on
2128 /// the substrate primitive, thin projections at each consumer"
2129 /// discipline the sibling per-slot read accessors ([`Self::nome`]
2130 /// e6b7d97, [`Self::versao`], [`Self::kind`]) carry — extended onto
2131 /// the outer-[`Caixa`] typed-dispatch read surface.
2132 #[must_use]
2133 pub fn deps_of(&self, list: crate::dep::DepList) -> &[Dep] {
2134 match list {
2135 crate::dep::DepList::Prod => self.deps(),
2136 crate::dep::DepList::Dev => self.deps_dev(),
2137 }
2138 }
2139
2140 /// Substrate-canonical per-[`Caixa`] typed-mutation dispatch every
2141 /// consumer that appends to one of the two dep-list axes keys off
2142 /// — routes the `(list: DepList, dep: Dep)` tuple through one typed
2143 /// method on the substrate primitive rather than the prior
2144 /// `feira add`-side open-coded `if self.dev { &mut caixa.deps_dev }
2145 /// else { &mut caixa.deps }` inline dispatch + open-coded
2146 /// `.iter().any(|d| d.nome == …)` dup-check cascade. Refuses the
2147 /// mutation with the canonical typed [`DepError::DuplicateNome`] on
2148 /// a within-list name collision — the same `list: &'static str`
2149 /// diagnostic shape [`Self::validate_deps`]'s per-list
2150 /// [`crate::render::insert_first_seen`] walk raises on the peer
2151 /// parse-time within-list dedup axis, so a future author reading a
2152 /// `feira add` refusal and a `feira build` refusal reaches for the
2153 /// same corrective surface without switching diagnostic idioms.
2154 ///
2155 /// The two-arm [`crate::dep::DepList`] enum is the substrate's
2156 /// closed-set typed carrier for the "runtime-closure `:deps` vs
2157 /// dev-only-closure `:deps-dev`" axis every dep-list consumer
2158 /// dispatches on — the compiler-checked exhaustiveness on the
2159 /// enum's `match` arms is the build-time guarantee that no future
2160 /// per-list mutation-site regresses to a bare-`bool`-flag
2161 /// (`is_dev: bool`) inline dispatch that a future third
2162 /// dep-list axis (a `:deps-build` build-only closure once the
2163 /// substrate grows cross-artifact heterogeneous dep-graphs, per
2164 /// CAIXA-SDLC §I) would silently split at every consumer.
2165 ///
2166 /// Same "one typed dispatch on the substrate primitive, thin
2167 /// projections at each consumer" discipline the sibling per-slot
2168 /// read accessors ([`Self::deps`] ad34b4e, [`Self::deps_dev`],
2169 /// [`Self::nome`] e6b7d97, [`Self::versao`], [`Self::kind`])
2170 /// carry — extended onto the outer-[`Caixa`] typed-mutation surface,
2171 /// the substrate's first typed-mutation dispatch on the top-level
2172 /// manifest. The prior `feira add` open-coded `&mut caixa.deps` /
2173 /// `&mut caixa.deps_dev` inline field-access + `bail!` string-
2174 /// diagnostic path routed no through-line back to the typed slot,
2175 /// so a future extension of either dep-list axis to a richer author
2176 /// surface (a per-cluster override the operator pins through a
2177 /// future `:placement`-scoped dep-list slot the CAIXA-SDLC §I
2178 /// roadmap acknowledges, an M4
2179 /// `mesh.pleme.io/v1alpha1/Caixa` CR materializer's per-CR
2180 /// admission-webhook that normalized the list at admission time)
2181 /// would have had to be threaded through the `feira add` mutation
2182 /// site in lockstep with every read consumer or one path would
2183 /// silently disagree with the other on which list a given dep lands
2184 /// in. Lifting the resolution rule to a typed method on the
2185 /// substrate primitive means every downstream dep-list-mutating
2186 /// consumer of the top-level manifest reaches for exactly one typed
2187 /// dispatch — the resolver's accept-set migrates as a unit on any
2188 /// future axis addition.
2189 ///
2190 /// # Errors
2191 ///
2192 /// Returns [`DepError::DuplicateNome`] with `list = list.as_str()`
2193 /// when another entry in the same list already carries the same
2194 /// `:nome` — the mutation is refused and the caller can surface the
2195 /// typed diagnostic to the author (the `feira add` verb routes the
2196 /// error through `anyhow::Error::from`, which preserves the
2197 /// canonical `#[error(...)]`-templated diagnostic body).
2198 pub fn push_dep(&mut self, list: crate::dep::DepList, dep: Dep) -> Result<(), DepError> {
2199 let target = match list {
2200 crate::dep::DepList::Prod => &mut self.deps,
2201 crate::dep::DepList::Dev => &mut self.deps_dev,
2202 };
2203 if target.iter().any(|d| d.nome() == dep.nome()) {
2204 return Err(DepError::DuplicateNome {
2205 nome: dep.nome().to_string(),
2206 list: list.as_str(),
2207 });
2208 }
2209 target.push(dep);
2210 Ok(())
2211 }
2212
2213 /// Substrate-canonical per-`Caixa` `:limits` M2 typed-slot outer-
2214 /// composite Lunatic-per-process wasm32-sandboxing-composite optional-
2215 /// composite-reference accessor every consumer of the top-level
2216 /// manifest's per-Servico [`LimitsSpec`] outer-composite reader keys
2217 /// off — returns the author-declared `:limits` typed composite
2218 /// verbatim as an `Option<&LimitsSpec>` reference over the same
2219 /// backing storage the raw `self.limits.as_ref()` field access
2220 /// borrows from, with `None` naming the "no `:limits` block
2221 /// authored — every per-axis Lunatic-sandbox cap defers to the
2222 /// wasm-engine-default arm named on the per-axis
2223 /// [`LimitsSpec::memory`] / [`LimitsSpec::fuel`] /
2224 /// [`LimitsSpec::wall_clock`] / [`LimitsSpec::cpu`] scalar-accessor
2225 /// docstrings" partition every downstream Servico-M2-overlay
2226 /// emitter treats as "emit nothing" and the sibling
2227 /// [`crate::StandardLayout::verify`] per-`:limits` shape gate
2228 /// treats as "skip the per-axis
2229 /// [`crate::LimitsError::MemoryZero`] / `MemoryBelowWasm32Page` /
2230 /// `FuelZero` / `WallClockZero` / `CpuZero` refusal cascade".
2231 ///
2232 /// The outer `:limits` slot carries the M2 Servico-runtime typed
2233 /// composite — the load-bearing container of every Lunatic-shaped
2234 /// per-process wasm32-sandbox cap axis every long-running wasm
2235 /// component's runtime dispatches on (INSPIRATIONS §III.1 —
2236 /// Lunatic per-process linear-memory / fuel / wall-clock /
2237 /// millicore cap primitives translated onto pleme-io's typed
2238 /// `:limits :memory` / `:limits :fuel` / `:limits :wall-clock` /
2239 /// `:limits :cpu` sub-slot axes; CAIXA-SDLC §II — the typed-M2
2240 /// slot algebra the wasm-engine + `pleme-computeunit` Helm-library
2241 /// chart both fan on). Every per-`:limits` axis threads through a
2242 /// lifted per-slot accessor on the [`LimitsSpec`] type: the
2243 /// [`LimitsSpec::memory`] wasm32 linear-memory byte-cap scalar
2244 /// accessor, the [`LimitsSpec::fuel`] wasmtime fuel-cap scalar
2245 /// accessor, the [`LimitsSpec::wall_clock`] per-call wall-clock
2246 /// deadline scalar accessor, and the [`LimitsSpec::cpu`]
2247 /// K8s-millicore soft-CPU-share scalar accessor. Every downstream
2248 /// consumer that reaches for a limits axis first passes through
2249 /// this outer accessor onto the composite and then dispatches
2250 /// onto the per-axis accessor — the two-level dispatch means
2251 /// every per-`:limits` reader now routes through a typed dispatch
2252 /// on the substrate primitive at both altitudes.
2253 ///
2254 /// Prior to this lift the `.limits` `Option<LimitsSpec>` composite
2255 /// was accessed inline at three production sites — the
2256 /// [`crate::StandardLayout::verify`] per-`:limits` shape gate's
2257 /// `if let Some(l) = &caixa.limits { … }` traversal head
2258 /// (caixa-core/src/layout.rs:882, which drives the per-axis
2259 /// refusal cascade on the composite: the `LimitsError::MemoryZero`
2260 /// / `MemoryBelowWasm32Page` / `MemoryExceedsWasm32Max` /
2261 /// `FuelZero` / `FuelExceedsMax` / `WallClockZero` /
2262 /// `WallClockExceedsMax` / `CpuZero` / `CpuExceedsMax` refusals
2263 /// [`LimitsSpec::validate`] fans onto), the
2264 /// [`crate::render::servico_m2_overlay`] per-Servico M2 overlay
2265 /// emitter's `if let Some(limits) = &caixa.limits { … }` traversal
2266 /// head (caixa-core/src/render.rs:18504, which drives the
2267 /// `M2_KEY_LIMITS`-keyed `limits.is_empty()`-gated `serde_yaml`
2268 /// projection every `caixa-helm` / `caixa-flux` Servico values-
2269 /// block emitter fans on), and the
2270 /// [`Self::declared_servico_slots`] per-Servico M2 declared-slot-
2271 /// set enumerator's `self.limits.is_some()` presence probe
2272 /// (caixa-core/src/manifest.rs:1788, which drives the
2273 /// `M2_AUTHOR_KEY_LIMITS` kebab-case author-label push every
2274 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] kind-coherence
2275 /// gate reads) — three open-coded outer-field accesses that
2276 /// expressed no compile-time link back to the typed slot at the
2277 /// [`Caixa`] altitude. A future extension of the `:limits` outer
2278 /// axis to a richer author surface (a multi-`:limits` list the M4
2279 /// CR materializer resolves per-CR at admission time so a Servico
2280 /// can expose a compute-heavy + IO-heavy limits pair, a per-
2281 /// cluster `:limits-overrides` slot the operator pins so a
2282 /// cluster-specific policy can tighten a caixa-declared cap
2283 /// without re-authoring the `caixa.lisp`, a promotion of the
2284 /// plain `Option<LimitsSpec>` to a richer
2285 /// `{static, dynamic}` partition once the wasm-engine's runtime-
2286 /// resolved dynamic-cap surface lands) would have had to be
2287 /// threaded through all three open-coded copies in lockstep or
2288 /// one consumer would silently disagree with the peers on which
2289 /// limits composite a given Caixa resolves to — the layout gate's
2290 /// per-axis bracket-dispatch seed reading the raw slot while the
2291 /// peer `servico_m2_overlay` emitter read an operator-resolved
2292 /// slot would silently split the build-time sandbox-shape gate
2293 /// from the runtime `ComputeUnit` CR emission gate, a three-
2294 /// consumer split at the layout gate, the M2 overlay emitter, and
2295 /// the declared-slot enumerator far from the source `caixa.lisp`
2296 /// with no field naming the limits-drift root cause. Lifting the
2297 /// resolution rule to a typed method on the substrate primitive
2298 /// means every downstream consumer of the caixa's per-`Caixa`
2299 /// Lunatic-sandboxing outer-composite surface reaches for exactly
2300 /// one typed dispatch — the resolver's accept-set migrates as a
2301 /// unit on any future axis addition.
2302 ///
2303 /// First outer top-level [`Caixa`] `Option<&Composite>`-return
2304 /// composite-reference accessor — opens the outer-`Caixa`
2305 /// `Option<&Composite>` composite-reference projection pattern the
2306 /// sibling per-`Caixa` `:behavior` [`crate::BehaviorSpec`] /
2307 /// `:politicas` [`crate::aplicacao::MeshPolicy`] / `:placement`
2308 /// [`crate::aplicacao::Placement`] / `:entrada`
2309 /// [`crate::aplicacao::Entrada`] future outer-composite lifts
2310 /// fold on. Peer of the M3 mesh-slot outer-composite family the
2311 /// sibling [`crate::AplicacaoSpec::politicas`] (534dc21) /
2312 /// [`crate::AplicacaoSpec::placement`] (9abb8f0) /
2313 /// [`crate::AplicacaoSpec::entrada`] (d32111c) composite-reference
2314 /// accessors already close on the outer [`crate::AplicacaoSpec`]
2315 /// altitude — extends that "one typed dispatch on the substrate
2316 /// primitive, thin projections at each consumer" discipline onto
2317 /// the outer top-level [`Caixa`] altitude, opening the M2 Servico-
2318 /// runtime slot family's outer-composite axis. Returns
2319 /// `Option<&LimitsSpec>` (not the owning composite by copy or
2320 /// clone) because every downstream consumer of the limits
2321 /// composite treats it as a read-only per-axis dispatch source —
2322 /// the reference-view is the narrowest borrow that supports every
2323 /// present + roadmapped consumer (per-axis accessor dispatch,
2324 /// `.is_empty()`-gated overlay projection, presence-probe early
2325 /// return on the "author-omitted `:limits` ⇒ engine-default
2326 /// applies" partition) without cloning the composite through
2327 /// every consumer's fast path. The `Option` half of the return-
2328 /// type preserves the load-bearing "author-omitted `:limits` ⇒
2329 /// engine-default applies" partition (not a default composite the
2330 /// downstream must reject on emptiness) — the accessor projects
2331 /// the raw `Option<LimitsSpec>` slot's presence bit through the
2332 /// reference-return unchanged. Named `limits()` to match the
2333 /// storage field's name verbatim and the tatara-lisp author-
2334 /// surface term (`:limits`) the field's own docstring already
2335 /// carries.
2336 #[must_use]
2337 pub fn limits(&self) -> Option<&LimitsSpec> {
2338 self.limits.as_ref()
2339 }
2340
2341 /// Substrate-canonical per-`Caixa` `:behavior` M2 typed-slot outer-
2342 /// composite OTP-`gen_server`-shaped callback-table optional-
2343 /// composite-reference accessor every consumer of the top-level
2344 /// manifest's per-Servico [`BehaviorSpec`] outer-composite reader
2345 /// keys off — returns the author-declared `:behavior` typed
2346 /// composite verbatim as an `Option<&BehaviorSpec>` reference over
2347 /// the same backing storage the raw `self.behavior.as_ref()` field
2348 /// access borrows from, with `None` naming the "no `:behavior`
2349 /// block authored — every per-callback OTP-shaped hook defers to
2350 /// the wasm-engine's runtime default arm named on the per-axis
2351 /// [`BehaviorSpec::on_init`] / [`BehaviorSpec::on_call`] /
2352 /// [`BehaviorSpec::on_cast`] / [`BehaviorSpec::on_info`] /
2353 /// [`BehaviorSpec::on_state_change`] /
2354 /// [`BehaviorSpec::on_terminate`] scalar-accessor docstrings"
2355 /// partition every downstream Servico-M2-overlay emitter treats as
2356 /// "emit nothing" and the sibling [`crate::StandardLayout::verify`]
2357 /// per-`:behavior` shape gate treats as "skip the per-arm
2358 /// [`crate::behavior::BehaviorError`] refusal cascade + the
2359 /// per-callback on-disk `MissingEntry` existence check".
2360 ///
2361 /// The outer `:behavior` slot carries the M2 Servico-runtime typed
2362 /// composite — the load-bearing container of every OTP-shaped
2363 /// per-Servico lifecycle-callback path axis every long-running wasm
2364 /// component's runtime dispatches on (INSPIRATIONS §II.3 — Erlang/
2365 /// OTP `gen_server:init/1` / `handle_call/3` / `handle_cast/2` /
2366 /// `handle_info/2` / `code_change/3` / `terminate/2` primitives
2367 /// translated onto pleme-io's typed `:behavior :on-init` /
2368 /// `:on-call` / `:on-cast` / `:on-info` / `:on-state-change` /
2369 /// `:on-terminate` sub-slot axes; CAIXA-SDLC §II — the typed-M2
2370 /// slot algebra the wasm-engine + `pleme-computeunit` Helm-library
2371 /// chart both fan on). Every per-`:behavior` axis threads through a
2372 /// lifted per-callback accessor on the [`BehaviorSpec`] type
2373 /// (9b4ecde / d66c702 / 156ddbe / 99616ac / 4846cef / 701add7).
2374 /// Every downstream consumer that reaches for a behavior axis
2375 /// first passes through this outer accessor onto the composite
2376 /// and then dispatches onto the per-callback accessor — the
2377 /// two-level dispatch means every per-`:behavior` reader now
2378 /// routes through a typed dispatch on the substrate primitive at
2379 /// both altitudes.
2380 ///
2381 /// Composes cross-slot with the M2 `:upgrade-from` gate: the
2382 /// [`crate::upgrade::validate_upgrade_from_against_behavior`]
2383 /// cross-slot composition gate at [`crate::StandardLayout::verify`]
2384 /// keys the "per-version `:state-change` instruction must have a
2385 /// `:on-state-change` callback" precondition off this accessor's
2386 /// composite (the callback-side counterpart to the
2387 /// `:upgrade-from :instructions :state-change :script` refusal at
2388 /// the appup-side). Threading that gate's traversal input through
2389 /// this accessor closes the cross-slot invariant on the substrate
2390 /// primitive, not on the raw field.
2391 ///
2392 /// Prior to this lift the `.behavior` `Option<BehaviorSpec>`
2393 /// composite was accessed inline at four production sites — the
2394 /// [`crate::StandardLayout::verify`] per-`:behavior` shape gate's
2395 /// `if let Some(b) = &caixa.behavior { … }` traversal head
2396 /// (caixa-core/src/layout.rs:896, which drives the per-arm
2397 /// `BehaviorError` refusal cascade + the per-callback on-disk
2398 /// [`crate::LayoutError::MissingEntry`] existence check under
2399 /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`]),
2400 /// the [`crate::upgrade::validate_upgrade_from_against_behavior`]
2401 /// cross-slot composition gate's `caixa.behavior.as_ref()`
2402 /// traversal-input feed (caixa-core/src/layout.rs:1008, which
2403 /// drives the `:state-change` ↔ `:on-state-change` precondition
2404 /// refusal), the [`crate::render::servico_m2_overlay`] per-Servico
2405 /// M2 overlay emitter's `if let Some(behavior) = &caixa.behavior
2406 /// { … }` traversal head (caixa-core/src/render.rs:18513, which
2407 /// drives the `M2_KEY_BEHAVIOR`-keyed `behavior.is_empty()`-gated
2408 /// `serde_yaml` projection every `caixa-helm` / `caixa-flux`
2409 /// Servico values-block emitter fans on), and the
2410 /// [`Self::declared_servico_slots`] per-Servico M2 declared-slot-
2411 /// set enumerator's `self.behavior.is_some()` presence probe
2412 /// (caixa-core/src/manifest.rs:1919, which drives the
2413 /// `M2_AUTHOR_KEY_BEHAVIOR` kebab-case author-label push every
2414 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] kind-coherence
2415 /// gate reads) — four open-coded outer-field accesses that
2416 /// expressed no compile-time link back to the typed slot at the
2417 /// [`Caixa`] altitude. A future extension of the `:behavior`
2418 /// outer axis to a richer author surface (a per-callback overlay
2419 /// resolver the operator materializes at admission time so a
2420 /// cluster-specific policy can inject a per-callback tracing
2421 /// interceptor without re-authoring the `caixa.lisp`, a promotion
2422 /// of the plain `Option<BehaviorSpec>` to a richer `{static,
2423 /// dynamic}` partition once a runtime-resolved behavior-swap
2424 /// surface lands, the M4 per-callback middleware chain the
2425 /// caixa-operator's per-Servico admission webhook keys off) would
2426 /// have had to be threaded through all four open-coded copies in
2427 /// lockstep or one consumer would silently disagree with the
2428 /// peers on which behavior composite a given Caixa resolves to —
2429 /// the layout gate's per-callback existence-check seed reading
2430 /// the raw slot while the peer `servico_m2_overlay` emitter read
2431 /// an operator-resolved slot would silently split the build-time
2432 /// callback-shape gate from the runtime `ComputeUnit` CR emission
2433 /// gate from the cross-slot `:state-change` composition gate from
2434 /// the M2 declared-slot enumerator, a four-consumer split far
2435 /// from the source `caixa.lisp` with no field naming the
2436 /// behavior-drift root cause. Lifting the resolution rule to a
2437 /// typed method on the substrate primitive means every downstream
2438 /// consumer of the caixa's per-`Caixa` OTP-callback-table outer-
2439 /// composite surface reaches for exactly one typed dispatch — the
2440 /// resolver's accept-set migrates as a unit on any future axis
2441 /// addition.
2442 ///
2443 /// Second outer top-level [`Caixa`] `Option<&Composite>`-return
2444 /// composite-reference accessor — sibling to the opening
2445 /// [`Self::limits`] (b2bd9d7) accessor on the outer-`Caixa`
2446 /// `Option<&Composite>` composite-reference sub-family, extends
2447 /// the "one typed dispatch on the substrate primitive, thin
2448 /// projections at each consumer" discipline onto the second of
2449 /// the three M2 Servico-runtime slots. The remaining
2450 /// `Option<&Composite>` axes at the outer top-level [`Caixa`]
2451 /// altitude — the M3 mesh-slot family (`:politicas`,
2452 /// `:placement`, `:entrada` — already closed on the inner
2453 /// [`crate::AplicacaoSpec`] altitude via 534dc21 / 9abb8f0 /
2454 /// d32111c) — remain the future sibling lifts on the outer
2455 /// top-level projection. Returns `Option<&BehaviorSpec>` (not
2456 /// the owning composite by copy or clone) because every
2457 /// downstream consumer of the behavior composite treats it as a
2458 /// read-only per-callback dispatch source — the reference-view is
2459 /// the narrowest borrow that supports every present + roadmapped
2460 /// consumer (per-callback accessor dispatch, `.is_empty()`-gated
2461 /// overlay projection, presence-probe early return on the
2462 /// "author-omitted `:behavior` ⇒ runtime-default applies"
2463 /// partition, cross-slot `:state-change` composition input)
2464 /// without cloning the composite through every consumer's fast
2465 /// path. The `Option` half of the return-type preserves the
2466 /// load-bearing "author-omitted `:behavior` ⇒ runtime-default
2467 /// applies" partition (not a default composite the downstream
2468 /// must reject on emptiness) — the accessor projects the raw
2469 /// `Option<BehaviorSpec>` slot's presence bit through the
2470 /// reference-return unchanged. Named `behavior()` to match the
2471 /// storage field's name verbatim and the tatara-lisp author-
2472 /// surface term (`:behavior`) the field's own docstring already
2473 /// carries.
2474 #[must_use]
2475 pub fn behavior(&self) -> Option<&crate::BehaviorSpec> {
2476 self.behavior.as_ref()
2477 }
2478
2479 /// Substrate-canonical per-`Caixa` `:politicas` M3 mesh-slot outer-
2480 /// composite MESH-COMPOSITION-shaped mesh-policy optional-composite-
2481 /// reference accessor every consumer of the top-level manifest's
2482 /// per-Aplicacao [`crate::aplicacao::MeshPolicy`] outer-composite
2483 /// reader keys off — returns the author-declared `:politicas` typed
2484 /// composite verbatim as an `Option<&MeshPolicy>` reference over the
2485 /// same backing storage the raw `self.politicas.as_ref()` field
2486 /// access borrows from, with `None` naming the "no `:politicas`
2487 /// block authored — every per-axis mesh-policy scalar defers to the
2488 /// cluster-default arm named on the per-axis
2489 /// [`crate::aplicacao::MeshPolicy::timeout`] /
2490 /// [`crate::aplicacao::MeshPolicy::retries`] /
2491 /// [`crate::aplicacao::MeshPolicy::circuit_breaker`] /
2492 /// [`crate::aplicacao::MeshPolicy::mtls_required`] /
2493 /// [`crate::aplicacao::MeshPolicy::rate_limit`] scalar-accessor
2494 /// docstrings" partition every downstream caixa-mesh /
2495 /// caixa-flux / caixa-helm Aplicacao-artifact emitter treats as
2496 /// "emit no per-`:politicas` overlay" and the sibling
2497 /// [`Self::aplicacao_view`] Aplicacao-composition seed folds through
2498 /// the [`crate::aplicacao::MeshPolicy::default`] cluster-default
2499 /// arm.
2500 ///
2501 /// The outer `:politicas` slot carries the M3 mesh-slot per-
2502 /// Aplicacao typed composite — the load-bearing container of every
2503 /// mesh-level policy axis every Cilium NetworkPolicy / Gateway API
2504 /// v1.x HTTPRoute / future M4 per-edge policy overlay emitter fans
2505 /// on (MESH-COMPOSITION §III.2 — the Aplicacao's typed mesh-policy
2506 /// composite; §V — the "no infinite blocking" per-call deadline +
2507 /// "sandboxing-by-default" mTLS-enforcement CSE invariants; §III.3
2508 /// — the typed inter-Servico contrato-edge overlay the per-`(:de,
2509 /// :para)` mesh renderer keys off). Every per-`:politicas` axis
2510 /// threads through a lifted per-slot accessor on the
2511 /// [`crate::aplicacao::MeshPolicy`] type: the
2512 /// [`crate::aplicacao::MeshPolicy::mtls_required`] (c0110f1) Cilium
2513 /// mTLS-enforcement toggle, the
2514 /// [`crate::aplicacao::MeshPolicy::retries`] (bdfb399) transient-
2515 /// failure retry budget, the [`crate::aplicacao::MeshPolicy::timeout`]
2516 /// (7073d0f) Gateway-API per-call deadline, the
2517 /// [`crate::aplicacao::MeshPolicy::circuit_breaker`] (b0e741a)
2518 /// Envoy-outlier-detection composite. Every downstream consumer
2519 /// that reaches for a mesh-policy axis first passes through this
2520 /// outer accessor onto the composite and then dispatches onto the
2521 /// per-axis accessor — the two-level dispatch means every per-
2522 /// `:politicas` reader now routes through a typed dispatch on the
2523 /// substrate primitive at both altitudes.
2524 ///
2525 /// Composes through [`Self::aplicacao_view`]'s Aplicacao-composition
2526 /// seed: the Aplicacao-view builder folds the outer `Option`'s
2527 /// author-omitted arm onto the [`crate::aplicacao::MeshPolicy::default`]
2528 /// cluster-default, so the peer inner [`crate::AplicacaoSpec::politicas`]
2529 /// (534dc21) `&MeshPolicy`-return accessor observes a typed
2530 /// composite whether or not the author declared the outer slot.
2531 /// The outer accessor preserves the "author-omitted vs authored-
2532 /// empty" partition the inner accessor's `is_empty()`-gated
2533 /// renderer overlay collapses — routing the presence bit through
2534 /// this accessor keeps the [`Self::declared_mesh_slots`] M3 kind-
2535 /// coherence enumerator's `M3_AUTHOR_KEY_POLITICAS` push separate
2536 /// from the inner `MeshPolicy::is_empty()`-gated overlay elision.
2537 ///
2538 /// Prior to this lift the `.politicas` `Option<MeshPolicy>`
2539 /// composite was accessed inline at two production sites — the
2540 /// [`Self::aplicacao_view`] Aplicacao-composition seed's
2541 /// `self.politicas.clone().unwrap_or_default()` traversal head
2542 /// (caixa-core/src/manifest.rs:1899, which drives the fold onto
2543 /// the [`crate::aplicacao::MeshPolicy::default`] cluster-default
2544 /// arm the inner [`crate::AplicacaoSpec::politicas`] accessor
2545 /// then observes), and the [`Self::declared_mesh_slots`] M3
2546 /// declared-slot-set enumerator's `self.politicas.is_some()`
2547 /// presence probe (caixa-core/src/manifest.rs:1961, which drives
2548 /// the `M3_AUTHOR_KEY_POLITICAS` kebab-case author-label push
2549 /// every [`crate::LayoutError::MeshSlotsOnNonAplicacao`] kind-
2550 /// coherence gate reads) — two open-coded outer-field accesses
2551 /// that expressed no compile-time link back to the typed slot at
2552 /// the [`Caixa`] altitude. A future extension of the `:politicas`
2553 /// outer axis to a richer author surface (a per-cluster
2554 /// `:politicas-overrides` slot the operator materializes at
2555 /// admission time so a cluster-specific policy can tighten the
2556 /// caixa-declared bound without re-authoring the `caixa.lisp`, a
2557 /// promotion of the plain `Option<MeshPolicy>` to a richer
2558 /// `{static, dynamic}` partition once the M4 per-edge
2559 /// contrato-scoped policy-override surface lands, the M5 traffic-
2560 /// shaping composition the caixa-operator's per-Aplicacao mesh
2561 /// admission webhook keys off) would have had to be threaded
2562 /// through both open-coded copies in lockstep or the Aplicacao-
2563 /// composition seed's default-fold arm would silently disagree
2564 /// with the M3 declared-slot enumerator on which policy composite
2565 /// a given Caixa resolves to — the seed reading an operator-
2566 /// resolved slot while the enumerator's presence probe read the
2567 /// raw slot would silently split the build-time mesh-artifact
2568 /// emission gate from the M3 declared-slot enumerator's kind-
2569 /// coherence gate, a two-consumer split far from the source
2570 /// `caixa.lisp` with no field naming the policy-drift root cause.
2571 /// Lifting the resolution rule to a typed method on the substrate
2572 /// primitive means every downstream consumer of the caixa's per-
2573 /// `Caixa` MESH-COMPOSITION mesh-policy outer-composite surface
2574 /// reaches for exactly one typed dispatch — the resolver's
2575 /// accept-set migrates as a unit on any future axis addition.
2576 ///
2577 /// Third outer top-level [`Caixa`] `Option<&Composite>`-return
2578 /// composite-reference accessor — sibling to the opening
2579 /// [`Self::limits`] (b2bd9d7) and [`Self::behavior`] (35d8b52)
2580 /// accessors on the outer-`Caixa` `Option<&Composite>` composite-
2581 /// reference sub-family, extends the "one typed dispatch on the
2582 /// substrate primitive, thin projections at each consumer"
2583 /// discipline onto the first of the three M3 mesh-slot axes.
2584 /// Peer of the closed inner mesh-slot outer-composite family the
2585 /// sibling [`crate::AplicacaoSpec::politicas`] (534dc21) /
2586 /// [`crate::AplicacaoSpec::placement`] (9abb8f0) /
2587 /// [`crate::AplicacaoSpec::entrada`] (d32111c) composite-reference
2588 /// accessor pins already close on the inner [`crate::AplicacaoSpec`]
2589 /// altitude — opens the outer top-level [`Caixa`] altitude's M3
2590 /// mesh-slot arm of the composite-reference family the remaining
2591 /// two axes (`:placement`, `:entrada`) fold onto in future
2592 /// sibling lifts. Returns `Option<&MeshPolicy>` (not the owning
2593 /// composite by copy or clone) because every downstream consumer
2594 /// of the mesh-policy composite treats it as a read-only per-axis
2595 /// dispatch source — the reference-view is the narrowest borrow
2596 /// that supports every present + roadmapped consumer (per-axis
2597 /// accessor dispatch, `.is_empty()`-gated overlay projection,
2598 /// presence-probe early return on the "author-omitted `:politicas`
2599 /// ⇒ cluster-default applies" partition, `Aplicacao`-composition
2600 /// seed's default-fold arm) without cloning the composite through
2601 /// every consumer's fast path. The `Option` half of the return-
2602 /// type preserves the load-bearing "author-omitted `:politicas` ⇒
2603 /// cluster-default applies" partition (not a default composite
2604 /// the downstream must reject on emptiness) — the accessor
2605 /// projects the raw `Option<MeshPolicy>` slot's presence bit
2606 /// through the reference-return unchanged. Named `politicas()` to
2607 /// match the storage field's name verbatim and the tatara-lisp
2608 /// author-surface term (`:politicas`) the field's own docstring
2609 /// already carries.
2610 #[must_use]
2611 pub fn politicas(&self) -> Option<&crate::aplicacao::MeshPolicy> {
2612 self.politicas.as_ref()
2613 }
2614
2615 /// Substrate-canonical per-`Caixa` `:placement` M3 mesh-slot outer-
2616 /// composite MESH-COMPOSITION-shaped distribution optional-composite-
2617 /// reference accessor every consumer of the top-level manifest's
2618 /// per-Aplicacao [`crate::aplicacao::Placement`] outer-composite
2619 /// reader keys off — returns the author-declared `:placement` typed
2620 /// composite verbatim as an `Option<&Placement>` reference over the
2621 /// same backing storage the raw `self.placement.as_ref()` field
2622 /// access borrows from, with `None` naming the "no `:placement`
2623 /// block authored — every per-axis placement scalar defers to the
2624 /// cluster-default arm named on the per-axis
2625 /// [`crate::aplicacao::Placement::estrategia`] /
2626 /// [`crate::aplicacao::Placement::clusters`] /
2627 /// [`crate::aplicacao::Placement::affinity`] /
2628 /// [`crate::aplicacao::Placement::shard_key`] scalar-accessor
2629 /// docstrings" partition every downstream caixa-mesh /
2630 /// caixa-flux / caixa-helm Aplicacao-artifact emitter treats as
2631 /// "emit no per-`:placement` overlay" and the sibling
2632 /// [`Self::aplicacao_view`] Aplicacao-composition seed folds through
2633 /// the [`crate::aplicacao::Placement::default`] cluster-default arm.
2634 ///
2635 /// The outer `:placement` slot carries the M3 mesh-slot per-
2636 /// Aplicacao typed distribution composite — the load-bearing
2637 /// container of every where-does-this-Aplicacao-run axis every
2638 /// caixa-mesh programs.yaml per-cluster distribution overlay /
2639 /// caixa-flux per-Aplicacao GitRepository/HelmRelease fan-out /
2640 /// future M4 per-Aplicacao Akka-style cluster-sharding entity-id
2641 /// resolver emitter fans on (MESH-COMPOSITION §II.4 — the
2642 /// Aplicacao's typed distribution composite; §V CSE invariants —
2643 /// "distribution is a first-class typed composite, not a runtime
2644 /// scheduler hint" the per-axis scalars enforce; §III.3 — the
2645 /// typed inter-Servico contrato-edge overlay the per-cluster
2646 /// mesh renderer keys off). Every per-`:placement` axis threads
2647 /// through a lifted per-slot accessor on the
2648 /// [`crate::aplicacao::Placement`] type: the
2649 /// [`crate::aplicacao::Placement::estrategia`] (921fe1b)
2650 /// MESH-COMPOSITION distribution-strategy scalar, the
2651 /// [`crate::aplicacao::Placement::clusters`] (a6e18d7) per-cluster
2652 /// distribution-target slice, the [`crate::aplicacao::Placement::affinity`]
2653 /// M3-Adaptive-compression-hint optional-scalar, and the
2654 /// [`crate::aplicacao::Placement::shard_key`] (7cd2a28) Akka-cluster-
2655 /// sharding extractor-expression optional-scalar. Every downstream
2656 /// consumer that reaches for a placement axis first passes through
2657 /// this outer accessor onto the composite and then dispatches onto
2658 /// the per-axis accessor — the two-level dispatch means every per-
2659 /// `:placement` reader now routes through a typed dispatch on the
2660 /// substrate primitive at both altitudes.
2661 ///
2662 /// Composes through [`Self::aplicacao_view`]'s Aplicacao-composition
2663 /// seed: the Aplicacao-view builder folds the outer `Option`'s
2664 /// author-omitted arm onto the [`crate::aplicacao::Placement::default`]
2665 /// cluster-default, so the peer inner [`crate::AplicacaoSpec::placement`]
2666 /// (9abb8f0) `&Placement`-return accessor observes a typed composite
2667 /// whether or not the author declared the outer slot. The outer
2668 /// accessor preserves the "author-omitted vs authored-empty" partition
2669 /// the inner accessor collapses at the cluster-default fold —
2670 /// routing the presence bit through this accessor keeps the
2671 /// [`Self::declared_mesh_slots`] M3 kind-coherence enumerator's
2672 /// `M3_AUTHOR_KEY_PLACEMENT` push separate from the inner
2673 /// [`crate::AplicacaoSpec::validate_placement`]-gated overlay
2674 /// dispatch.
2675 ///
2676 /// Prior to this lift the `.placement` `Option<Placement>`
2677 /// composite was accessed inline at two production sites — the
2678 /// [`Self::aplicacao_view`] Aplicacao-composition seed's
2679 /// `self.placement.clone().unwrap_or_default()` traversal head
2680 /// (caixa-core/src/manifest.rs:2036, which drives the fold onto
2681 /// the [`crate::aplicacao::Placement::default`] cluster-default
2682 /// arm the inner [`crate::AplicacaoSpec::placement`] accessor
2683 /// then observes), and the [`Self::declared_mesh_slots`] M3
2684 /// declared-slot-set enumerator's `self.placement.is_some()`
2685 /// presence probe (caixa-core/src/manifest.rs:2100, which drives
2686 /// the `M3_AUTHOR_KEY_PLACEMENT` kebab-case author-label push
2687 /// every [`crate::LayoutError::MeshSlotsOnNonAplicacao`] kind-
2688 /// coherence gate reads) — two open-coded outer-field accesses
2689 /// that expressed no compile-time link back to the typed slot at
2690 /// the [`Caixa`] altitude. A future extension of the `:placement`
2691 /// outer axis to a richer author surface (a per-cluster
2692 /// `:placement-overrides` slot the operator materializes at
2693 /// admission time so a cluster-specific placement can tighten the
2694 /// caixa-declared bound without re-authoring the `caixa.lisp`, a
2695 /// per-tenant placement-alias table the M4
2696 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves
2697 /// per-CR at admission time, a promotion of the plain
2698 /// `Option<Placement>` to a richer `{static, dynamic}` partition
2699 /// once Orleans-style virtual-actor dynamic placement comes into
2700 /// typed scope) would have had to be threaded through both open-
2701 /// coded copies in lockstep or the Aplicacao-composition seed's
2702 /// default-fold arm would silently disagree with the M3 declared-
2703 /// slot enumerator on which distribution composite a given Caixa
2704 /// resolves to — the seed reading an operator-resolved slot while
2705 /// the enumerator's presence probe read the raw slot would
2706 /// silently split the build-time distribution-artifact emission
2707 /// gate from the M3 declared-slot enumerator's kind-coherence
2708 /// gate, a two-consumer split far from the source `caixa.lisp`
2709 /// with no field naming the distribution-drift root cause.
2710 /// Lifting the resolution rule to a typed method on the substrate
2711 /// primitive means every downstream consumer of the caixa's per-
2712 /// `Caixa` MESH-COMPOSITION distribution outer-composite surface
2713 /// reaches for exactly one typed dispatch — the resolver's
2714 /// accept-set migrates as a unit on any future axis addition.
2715 ///
2716 /// Fourth outer top-level [`Caixa`] `Option<&Composite>`-return
2717 /// composite-reference accessor — sibling to the opening
2718 /// [`Self::limits`] (b2bd9d7) / [`Self::behavior`] (35d8b52) M2-
2719 /// Servico-runtime pair and the peer [`Self::politicas`] (5d23d29)
2720 /// M3-mesh-slot arm on the outer-`Caixa` `Option<&Composite>`
2721 /// composite-reference sub-family, folds on the "one typed
2722 /// dispatch on the substrate primitive, thin projections at each
2723 /// consumer" discipline extended onto the second of the three M3
2724 /// mesh-slot axes. Peer of the closed inner mesh-slot outer-
2725 /// composite family the sibling
2726 /// [`crate::AplicacaoSpec::politicas`] (534dc21) /
2727 /// [`crate::AplicacaoSpec::placement`] (9abb8f0) /
2728 /// [`crate::AplicacaoSpec::entrada`] (d32111c) composite-reference
2729 /// accessor pins already close on the inner
2730 /// [`crate::AplicacaoSpec`] altitude — folds on the outer top-
2731 /// level [`Caixa`] altitude's M3 mesh-slot arm the sibling
2732 /// [`Self::politicas`] opened, extending the discipline onto the
2733 /// second of the three M3 mesh-slot axes. The remaining M3
2734 /// mesh-slot axis (`:entrada`) folds onto this accessor's
2735 /// discipline in the final sibling lift, closing the outer top-
2736 /// level [`Caixa`] `Option<&Composite>` M3 mesh-slot sub-family.
2737 /// Returns `Option<&Placement>` (not the owning composite by copy
2738 /// or clone) because every downstream consumer of the placement
2739 /// composite treats it as a read-only per-axis dispatch source —
2740 /// the reference-view is the narrowest borrow that supports every
2741 /// present + roadmapped consumer (per-axis accessor dispatch,
2742 /// serde composite-serialization on the programs.yaml overlay,
2743 /// presence-probe early return on the "author-omitted `:placement`
2744 /// ⇒ cluster-default applies" partition, `Aplicacao`-composition
2745 /// seed's default-fold arm) without cloning the composite through
2746 /// every consumer's fast path. The `Option` half of the return-
2747 /// type preserves the load-bearing "author-omitted `:placement` ⇒
2748 /// cluster-default applies" partition (not a default composite
2749 /// the downstream must reject on emptiness) — the accessor
2750 /// projects the raw `Option<Placement>` slot's presence bit
2751 /// through the reference-return unchanged. Named `placement()` to
2752 /// match the storage field's name verbatim and the tatara-lisp
2753 /// author-surface term (`:placement`) the field's own docstring
2754 /// already carries.
2755 #[must_use]
2756 pub fn placement(&self) -> Option<&crate::aplicacao::Placement> {
2757 self.placement.as_ref()
2758 }
2759
2760 /// Substrate-canonical per-`Caixa` `:entrada` M3 mesh-slot outer-
2761 /// composite MESH-COMPOSITION-shaped external-gateway optional-
2762 /// composite-reference accessor every consumer of the top-level
2763 /// manifest's per-Aplicacao [`crate::aplicacao::Entrada`] outer-
2764 /// composite reader keys off — returns the author-declared
2765 /// `:entrada` typed composite verbatim as an `Option<&Entrada>`
2766 /// reference over the same backing storage the raw
2767 /// `self.entrada.as_ref()` field access borrows from, with `None`
2768 /// naming the "no `:entrada` block authored — this Aplicacao is
2769 /// cluster-internal, no `Gateway`/`HTTPRoute` fan-out emitted"
2770 /// partition every downstream caixa-mesh Gateway-API artifact
2771 /// emitter treats as "emit no gateway-listener + no `HTTPRoute`
2772 /// backend for this Aplicacao" and the sibling
2773 /// [`Self::aplicacao_view`] Aplicacao-composition seed forwards
2774 /// verbatim (unlike the peer `:politicas` / `:placement` arms,
2775 /// `:entrada` has no cluster-default fold — an omitted `:entrada`
2776 /// stays `None` on the projected [`crate::AplicacaoSpec`] and the
2777 /// peer inner [`crate::AplicacaoSpec::entrada`] accessor observes
2778 /// the same `Option<&Entrada>` presence bit unchanged).
2779 ///
2780 /// The outer `:entrada` slot carries the M3 mesh-slot per-
2781 /// Aplicacao typed external-gateway composite — the load-bearing
2782 /// container of every how-does-the-outside-world-reach-this-
2783 /// Aplicacao axis every caixa-mesh `Gateway`/`HTTPRoute` fan-out
2784 /// emitter fans on (MESH-COMPOSITION §II.5 — the Aplicacao's typed
2785 /// external-entry composite; §V CSE invariants — "the external
2786 /// gateway is a first-class typed composite, not a per-Servico
2787 /// ingress annotation" the per-axis scalars enforce; §III.4 — the
2788 /// typed hostname + backend-Servico pair the per-cluster Gateway-
2789 /// API renderer keys off). Every per-`:entrada` axis threads
2790 /// through a lifted per-slot accessor on the
2791 /// [`crate::aplicacao::Entrada`] type: the
2792 /// [`crate::aplicacao::Entrada::host`] Gateway-API `Listener.hostname`
2793 /// scalar, the [`crate::aplicacao::Entrada::para`] backend-Servico
2794 /// caixa-name scalar, the [`crate::aplicacao::Entrada::paths`]
2795 /// per-rule `HTTPPathMatch` list, the [`crate::aplicacao::Entrada::port`]
2796 /// backend `trigger.service.port` scalar, and the
2797 /// [`crate::aplicacao::Entrada::resolved_paths`] URL-path fallback
2798 /// resolver every HTTPRoute-aware renderer consumes. Every
2799 /// downstream consumer that reaches for an entry axis first passes
2800 /// through this outer accessor onto the composite and then
2801 /// dispatches onto the per-axis accessor — the two-level dispatch
2802 /// means every per-`:entrada` reader now routes through a typed
2803 /// dispatch on the substrate primitive at both altitudes.
2804 ///
2805 /// Composes through [`Self::aplicacao_view`]'s Aplicacao-composition
2806 /// seed: the Aplicacao-view builder forwards the outer `Option`
2807 /// arm verbatim (no default fold — `:entrada` is inherently
2808 /// optional; a cluster-internal Aplicacao has no external gateway
2809 /// at all, not "an external gateway that defaults to nothing"), so
2810 /// the peer inner [`crate::AplicacaoSpec::entrada`] (d32111c)
2811 /// `Option<&Entrada>`-return accessor observes the same presence
2812 /// bit whether or not the author declared the outer slot. Routing
2813 /// the presence bit through this accessor keeps the
2814 /// [`Self::declared_mesh_slots`] M3 kind-coherence enumerator's
2815 /// `M3_AUTHOR_KEY_ENTRADA` push separate from the inner
2816 /// [`crate::AplicacaoSpec::validate_entrada`]-gated
2817 /// hostname/backend/path emission dispatch.
2818 ///
2819 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
2820 /// was accessed inline at two production sites — the
2821 /// [`Self::aplicacao_view`] Aplicacao-composition seed's
2822 /// `self.entrada.clone()` traversal head (caixa-core/src/manifest.rs:2182,
2823 /// which drives the forward onto the peer inner
2824 /// [`crate::AplicacaoSpec::entrada`] accessor the caixa-mesh
2825 /// Gateway-API fan-out then observes), and the
2826 /// [`Self::declared_mesh_slots`] M3 declared-slot-set enumerator's
2827 /// `self.entrada.is_some()` presence probe (caixa-core/src/manifest.rs:2248,
2828 /// which drives the `M3_AUTHOR_KEY_ENTRADA` kebab-case author-
2829 /// label push every [`crate::LayoutError::MeshSlotsOnNonAplicacao`]
2830 /// kind-coherence gate reads) — two open-coded outer-field
2831 /// accesses that expressed no compile-time link back to the typed
2832 /// slot at the [`Caixa`] altitude. A future extension of the
2833 /// `:entrada` outer axis to a richer author surface (a per-cluster
2834 /// `:entrada-overrides` slot the operator materializes at admission
2835 /// time so a cluster-specific hostname can pin the caixa-declared
2836 /// bound without re-authoring the `caixa.lisp`, a per-tenant
2837 /// gateway-alias table the M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2838 /// CR materializer resolves per-CR at admission time, a promotion
2839 /// of the plain `Option<Entrada>` to a richer
2840 /// `{public, private, internal}` partition once Cilium-identity-
2841 /// scoped internal gateways come into typed scope) would have had
2842 /// to be threaded through both open-coded copies in lockstep or the
2843 /// Aplicacao-composition seed's forward arm would silently
2844 /// disagree with the M3 declared-slot enumerator on which external-
2845 /// gateway composite a given Caixa resolves to — the seed reading
2846 /// an operator-resolved slot while the enumerator's presence probe
2847 /// read the raw slot would silently split the build-time gateway-
2848 /// artifact emission gate from the M3 declared-slot enumerator's
2849 /// kind-coherence gate, a two-consumer split far from the source
2850 /// `caixa.lisp` with no field naming the entry-drift root cause.
2851 /// Lifting the resolution rule to a typed method on the substrate
2852 /// primitive means every downstream consumer of the caixa's per-
2853 /// `Caixa` MESH-COMPOSITION external-gateway outer-composite
2854 /// surface reaches for exactly one typed dispatch — the resolver's
2855 /// accept-set migrates as a unit on any future axis addition.
2856 ///
2857 /// Fifth and final outer top-level [`Caixa`] `Option<&Composite>`-
2858 /// return composite-reference accessor — closes the outer-`Caixa`
2859 /// `Option<&Composite>` composite-reference sub-family opened by
2860 /// [`Self::limits`] (b2bd9d7) / [`Self::behavior`] (35d8b52) on the
2861 /// M2 Servico-runtime arm and extended onto the M3 mesh-slot arm
2862 /// by [`Self::politicas`] (5d23d29) / [`Self::placement`] (4fb8074),
2863 /// folds on the "one typed dispatch on the substrate primitive,
2864 /// thin projections at each consumer" discipline extended onto the
2865 /// third and final M3 mesh-slot axis. Peer of the closed inner
2866 /// mesh-slot outer-composite family the sibling
2867 /// [`crate::AplicacaoSpec::politicas`] (534dc21) /
2868 /// [`crate::AplicacaoSpec::placement`] (9abb8f0) /
2869 /// [`crate::AplicacaoSpec::entrada`] (d32111c) composite-reference
2870 /// accessor pins already close on the inner
2871 /// [`crate::AplicacaoSpec`] altitude — this lift closes the mirror
2872 /// sub-family on the outer top-level [`Caixa`] altitude, so both
2873 /// altitudes of the outer-composite reference-return discipline
2874 /// (per-`Caixa` outer-slot presence + per-`AplicacaoSpec` inner-
2875 /// slot presence) now carry the full five-arm accept-set behind a
2876 /// typed dispatch on the substrate primitive. Returns
2877 /// `Option<&Entrada>` (not the owning composite by copy or clone)
2878 /// because every downstream consumer of the entrada composite
2879 /// treats it as a read-only per-axis dispatch source — the
2880 /// reference-view is the narrowest borrow that supports every
2881 /// present + roadmapped consumer (per-axis accessor dispatch,
2882 /// serde composite-serialization on the programs.yaml overlay,
2883 /// presence-probe early return on the "author-omitted `:entrada`
2884 /// ⇒ cluster-internal Aplicacao" partition, `Aplicacao`-composition
2885 /// seed's forward arm) without cloning the composite through every
2886 /// consumer's fast path. The `Option` half of the return-type
2887 /// preserves the load-bearing "author-omitted `:entrada` ⇒
2888 /// cluster-internal Aplicacao" partition (not a default composite
2889 /// the downstream must reject on emptiness — a cluster-internal
2890 /// Aplicacao has no external gateway at all, not "a default gateway
2891 /// that emits nothing"); the accessor projects the raw
2892 /// `Option<Entrada>` slot's presence bit through the reference-
2893 /// return unchanged. Named `entrada()` to match the storage field's
2894 /// name verbatim and the tatara-lisp author-surface term
2895 /// (`:entrada`) the field's own docstring already carries.
2896 #[must_use]
2897 pub fn entrada(&self) -> Option<&crate::aplicacao::Entrada> {
2898 self.entrada.as_ref()
2899 }
2900
2901 /// Substrate-canonical per-`Caixa` `:ci` slot accessor — returns the
2902 /// author-declared typed CI run (`canteiro_types::CiRun`) verbatim as
2903 /// an `Option<&CiRun>`, borrowed from the typed slot's own
2904 /// `Option<CiRun>` storage. `None` when the slot is absent (every
2905 /// non-`Acao` kind, and an `Acao` caixa that hasn't declared `:ci`
2906 /// yet — the latter is caught by [`crate::LayoutError::MissingCi`],
2907 /// not silently accepted).
2908 ///
2909 /// Named `ci()` to match the storage field's name and the
2910 /// tatara-lisp author surface (`:ci`); mirrors the sibling
2911 /// `Option<&Composite>` accessors on this same `Caixa` altitude
2912 /// ([`Self::limits`], [`Self::behavior`], [`Self::politicas`],
2913 /// [`Self::placement`], [`Self::entrada`]) — one typed dispatch on
2914 /// the substrate primitive rather than an open-coded `self.ci.as_ref()`
2915 /// at every consumer.
2916 #[must_use]
2917 pub fn ci(&self) -> Option<&canteiro_types::CiRun> {
2918 self.ci.as_ref()
2919 }
2920
2921 /// Substrate-canonical per-`Caixa` `:estrategia` M2 supervisor-tree-
2922 /// slot flat-spread OTP-shaped sibling-restart-strategy discriminant
2923 /// accessor every consumer of the top-level manifest's per-Supervisor
2924 /// restart-strategy axis keys off — returns the author-declared
2925 /// `:estrategia` variant verbatim as an `Option<RestartStrategy>`,
2926 /// `Copy`-projected from the typed slot's own
2927 /// `Option<crate::supervisor::RestartStrategy>` storage. Optional
2928 /// (`:estrategia` is a flat-spread supervisor-only slot every
2929 /// non-`Supervisor`-kind `defcaixa` carries as `None` by
2930 /// `#[serde(default)]`, and every `Supervisor`-kind `defcaixa` may
2931 /// still omit to defer to [`RestartStrategy::default`] —
2932 /// [`RestartStrategy::OneForOne`] — through the [`Self::supervisor_view`]
2933 /// `unwrap_or_default()` fold; a returned `None` degenerates to the
2934 /// [`SupervisorSpec::default`]-inherited strategy without any silent
2935 /// promotion to a fresh explicit variant at the accessor boundary).
2936 ///
2937 /// The `:estrategia` slot carries the M2 typed OTP-shaped sibling-
2938 /// restart-strategy discriminant every substrate-side per-Supervisor
2939 /// dispatch fans on (INSPIRATIONS §II.2 — OTP `supervisor:strategy`
2940 /// closed-set `one_for_one | one_for_all | rest_for_one |
2941 /// simple_one_for_one` algebra translated onto pleme-io's typed
2942 /// [`RestartStrategy`] enum; CAIXA-SDLC §II — the M2 supervisor-tree
2943 /// slot algebra the operator's hierarchical reconciliation scheduler
2944 /// fans on). The slot is *flat-spread* on the outer top-level `Caixa`
2945 /// (per the field-shape docstring at caixa-core/src/manifest.rs — "The
2946 /// supervisor slots are flat on Caixa (vs nested under a
2947 /// `SupervisorSpec` sub-form) to keep tatara-lisp authoring at one
2948 /// level of nesting"), so the accessor's altitude is the outer
2949 /// [`Caixa`] surface rather than the composed [`SupervisorSpec`]
2950 /// altitude the sibling [`crate::supervisor::SupervisorSpec::estrategia`]
2951 /// (eafb619) accessor keys off. The two typed axes — the outer
2952 /// author-surface `Option<RestartStrategy>` on the [`Caixa`] altitude
2953 /// (author-omitted arm carried as `None`) and the inner post-
2954 /// composition `RestartStrategy` on the [`SupervisorSpec`] altitude
2955 /// (`Option` collapsed through the [`Self::supervisor_view`]
2956 /// `unwrap_or_default()` fold) — now share one accessor discipline for
2957 /// the shared substrate concept "the author-declared OTP-shaped
2958 /// sibling-restart-strategy variant that partitions the downstream
2959 /// per-Supervisor renderer's per-arm fan-out"; the outer-altitude
2960 /// `None` arm is the pre-composition presence bit every declared-slot
2961 /// enumerator ([`Self::declared_supervisor_slots`]) reads, and the
2962 /// inner-altitude non-`Option` `RestartStrategy` is the post-
2963 /// composition partition-dispatch input every strategy-arm consumer
2964 /// ([`SupervisorSpec::validate`], the future wasm-operator's per-
2965 /// Supervisor sibling-restart branch, the future M4
2966 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2967 /// webhook) fans on.
2968 ///
2969 /// Prior to this lift the `.estrategia` field was accessed inline at
2970 /// two production sites in `caixa-core/src/manifest.rs` — the
2971 /// [`Self::declared_supervisor_slots`] `SUPERVISOR_AUTHOR_KEY_ESTRATEGIA`
2972 /// presence-probe arm at `if self.estrategia.is_some()` (which drives
2973 /// the [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] kind-
2974 /// coherence gate's per-slot label push) and the [`Self::supervisor_view`]
2975 /// `SupervisorSpec` construction site at `estrategia:
2976 /// self.estrategia.unwrap_or_default()` (which composes the flat-
2977 /// spread outer author-surface `Option<RestartStrategy>` onto the
2978 /// inner post-composition [`SupervisorSpec`] `RestartStrategy` field
2979 /// the [`SupervisorSpec::estrategia`] accessor keys off) — two open-
2980 /// coded field-accesses that expressed no compile-time link back to
2981 /// the typed slot. A future extension of the outer `:estrategia` axis
2982 /// to a richer author surface (a per-cluster strategy override the
2983 /// operator pins through a future `:estrategia-overrides` overlay the
2984 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2985 /// a per-tenant strategy-alias table the M4 CR materializer resolves
2986 /// per-CR, a per-Supervisor dynamic strategy derivation the future
2987 /// adaptive-supervision engine computes from child-failure-history
2988 /// topology, a per-child-cohort strategy split the future
2989 /// `RestForCohort` extension the INSPIRATIONS.md §II.2 Erlang/OTP
2990 /// absorption roadmap acknowledges, a promotion of the plain
2991 /// `Option<RestartStrategy>` to a richer
2992 /// `AuthorDeclaredStrategy { declared, overlay }` newtype once the
2993 /// operator-resolved overlay lands) would have had to be threaded
2994 /// through both open-coded copies in lockstep or the enumerator's
2995 /// presence probe and the composition site's `unwrap_or_default()`
2996 /// fold would silently disagree on which strategy a given [`Caixa`]
2997 /// resolves to (an author's `:estrategia OneForAll` would satisfy
2998 /// the enumerator's presence probe while the composition site
2999 /// silently rendered a stale `OneForOne`, or vice versa). Lifting
3000 /// the resolution rule to a typed method on the substrate primitive
3001 /// means every downstream consumer of the caixa's per-`Caixa` outer-
3002 /// altitude sibling-restart-strategy surface reaches for exactly one
3003 /// typed dispatch — the resolver's accept-set migrates as a unit on
3004 /// any future axis addition.
3005 ///
3006 /// First outer top-level [`Caixa`] `Option<Copy>`-return supervisor-
3007 /// tree-slot flat-spread accessor for M2 supervisor-slot Copy-carry
3008 /// axes — opens the outer-`Caixa` `Option<Copy>` flat-spread
3009 /// projection pattern the sibling per-`Caixa` `:max-restarts`
3010 /// `Option<u32>` and (through the future duration-newtype landing)
3011 /// `:restart-window` `Option<Duration>` future outer-scalar lifts
3012 /// fold on. Peer of the inner-altitude [`crate::supervisor::SupervisorSpec::estrategia`]
3013 /// (eafb619) `Copy`-return sibling-restart-strategy scalar accessor on
3014 /// the post-composition [`SupervisorSpec`] altitude — same "one
3015 /// typed dispatch on the substrate primitive, thin projections at
3016 /// each consumer" discipline extended onto the pre-composition outer
3017 /// author-surface [`Caixa`] altitude for the same OTP-shaped
3018 /// sibling-restart-strategy axis. Peer of the closed outer-`Caixa`
3019 /// `Option<&Composite>` composite-reference family the sibling
3020 /// [`Self::limits`] (b2bd9d7) / [`Self::behavior`] (35d8b52) /
3021 /// [`Self::politicas`] (5d23d29) / [`Self::placement`] (4fb8074) /
3022 /// [`Self::entrada`] (e4128e4) accessor pins already carry on the
3023 /// outer `Option<&Composite>` altitude — extends the outer-`Caixa`
3024 /// typed-slot accessor discipline onto the flat-spread M2 supervisor-
3025 /// tree `Option<Copy>`-discriminant sub-family the sibling M3
3026 /// [`crate::aplicacao::Placement::estrategia`] (921fe1b)
3027 /// `PlacementStrategy` `Copy`-composite-enum scalar accessor already
3028 /// pins on the inner-altitude per-`:placement` composite. Named
3029 /// `estrategia()` to match the storage field's name and the
3030 /// per-[`SupervisorSpec`] peer [`crate::supervisor::SupervisorSpec::estrategia`]
3031 /// / per-[`crate::aplicacao::Placement`] peer
3032 /// [`crate::aplicacao::Placement::estrategia`] method-name discipline
3033 /// verbatim; the accessor's identity name maps onto the canonical
3034 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3035 /// docstring already carries.
3036 #[must_use]
3037 pub fn estrategia(&self) -> Option<crate::supervisor::RestartStrategy> {
3038 self.estrategia
3039 }
3040
3041 /// Substrate-canonical per-`Caixa` `:max-restarts` M2 supervisor-tree-
3042 /// slot flat-spread OTP-`MaxIntensity`-shaped restart-budget-count
3043 /// scalar accessor every consumer of the top-level manifest's per-
3044 /// Supervisor `:max-restarts` restart-budget-count axis keys off —
3045 /// returns the author-declared `:max-restarts` typed `Option<u32>`
3046 /// verbatim, `Copy`-projected from the typed slot's own `Option<u32>`
3047 /// storage (`u32` is `Copy`, so `Option<u32>` is `Copy` and the
3048 /// accessor returns by value; no borrow of `&self` past the call).
3049 /// Optional (`:max-restarts` is a flat-spread supervisor-only slot
3050 /// every non-`Supervisor`-kind `defcaixa` carries as `None` by
3051 /// `#[serde(default)]`, and every `Supervisor`-kind `defcaixa` may
3052 /// still omit to defer to the [`Self::supervisor_view`]
3053 /// `unwrap_or(5)` fold's OTP-canonical `{intensity, 5, 60}` default).
3054 ///
3055 /// The `:max-restarts` slot carries the M2 typed Erlang/OTP-shaped
3056 /// `MaxIntensity` restart-budget count that pairs with the sibling
3057 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3058 /// restart-intensity ratio the supervisor trips its own escalation on
3059 /// (INSPIRATIONS §II.2 — Erlang/OTP `supervisor` `{intensity, 5, 60}`
3060 /// worker-supervisor default; RUNTIME-PATTERNS §II.2; CAIXA-SDLC §II
3061 /// — the M2 supervisor-tree slot algebra the operator's hierarchical
3062 /// reconciliation scheduler fans on). The slot is *flat-spread* on
3063 /// the outer top-level `Caixa` (per the field-shape docstring at
3064 /// caixa-core/src/manifest.rs — "The supervisor slots are flat on
3065 /// Caixa (vs nested under a `SupervisorSpec` sub-form)"), so the
3066 /// accessor's altitude is the outer [`Caixa`] surface rather than the
3067 /// composed [`SupervisorSpec`] altitude the sibling
3068 /// [`crate::supervisor::SupervisorSpec::max_restarts`] accessor keys
3069 /// off. The two typed axes — the outer author-surface `Option<u32>`
3070 /// on the [`Caixa`] altitude (author-omitted arm carried as `None`)
3071 /// and the inner post-composition `u32` on the [`SupervisorSpec`]
3072 /// altitude (`Option` collapsed through the [`Self::supervisor_view`]
3073 /// `unwrap_or(5)` fold) — now share one accessor discipline for the
3074 /// shared substrate concept "the author-declared OTP-shaped
3075 /// restart-budget count every downstream per-Supervisor consumer's
3076 /// restart-intensity budget-vs-count comparator fans on".
3077 ///
3078 /// Prior to this lift the `.max_restarts` field was accessed inline
3079 /// at two production sites in `caixa-core/src/manifest.rs` — the
3080 /// [`Self::declared_supervisor_slots`] `SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS`
3081 /// presence-probe arm at `if self.max_restarts.is_some()` (which
3082 /// drives the [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`]
3083 /// kind-coherence gate's per-slot label push) and the
3084 /// [`Self::supervisor_view`] `SupervisorSpec` construction site at
3085 /// `max_restarts: self.max_restarts.unwrap_or(5)` (which composes the
3086 /// flat-spread outer author-surface `Option<u32>` onto the inner
3087 /// post-composition [`SupervisorSpec`] `u32` field the
3088 /// [`SupervisorSpec::max_restarts`] accessor keys off) — two open-
3089 /// coded field-accesses that expressed no compile-time link back to
3090 /// the typed slot. A future extension of the outer `:max-restarts`
3091 /// axis to a richer author surface (a per-cluster restart-budget
3092 /// override the operator pins through a future `:max-restarts-overrides`
3093 /// overlay the MESH-COMPOSITION §III.2 supervision-canary roadmap
3094 /// acknowledges, a per-tenant restart-budget-alias table the M4 CR
3095 /// materializer resolves per-CR, a per-Supervisor dynamic restart-
3096 /// budget derivation the future adaptive-supervision engine computes
3097 /// from child-failure-history topology, a promotion of the plain
3098 /// `Option<u32>` count to a richer `{MaxR, MaxT}` per-child-cohort
3099 /// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
3100 /// per-child-cohort roadmap lands) would have had to be threaded
3101 /// through both open-coded copies in lockstep or the enumerator's
3102 /// presence probe and the composition site's `unwrap_or(5)` fold
3103 /// would silently disagree on which restart-budget a given [`Caixa`]
3104 /// resolves to (an author's `:max-restarts 10` would satisfy the
3105 /// enumerator's presence probe while the composition site silently
3106 /// composed the OTP-canonical `5`, or vice versa). Lifting the
3107 /// resolution rule to a typed method on the substrate primitive means
3108 /// every downstream consumer of the caixa's per-`Caixa` outer-altitude
3109 /// restart-budget-count surface reaches for exactly one typed dispatch
3110 /// — the resolver's accept-set migrates as a unit on any future axis
3111 /// addition.
3112 ///
3113 /// Second outer top-level [`Caixa`] `Option<Copy>`-return supervisor-
3114 /// tree-slot flat-spread accessor for M2 supervisor-slot Copy-carry
3115 /// axes — folds on the outer-`Caixa` `Option<Copy>` flat-spread
3116 /// projection pattern the sibling per-`Caixa`
3117 /// [`Self::estrategia`] (ed04d3c) accessor opened, extends the
3118 /// sub-family onto the sibling `Option<u32>` restart-budget-count arm.
3119 /// Peer of the inner-altitude
3120 /// [`crate::supervisor::SupervisorSpec::max_restarts`] `u32` accessor
3121 /// on the post-composition [`SupervisorSpec`] altitude — same "one
3122 /// typed dispatch on the substrate primitive, thin projections at
3123 /// each consumer" discipline extended onto the pre-composition outer
3124 /// author-surface [`Caixa`] altitude for the same OTP-`MaxIntensity`-
3125 /// shaped restart-budget-count axis. Named `max_restarts()` to match
3126 /// the storage field's name and the per-[`SupervisorSpec`] peer
3127 /// [`crate::supervisor::SupervisorSpec::max_restarts`] method-name
3128 /// discipline verbatim; the accessor's identity maps onto the
3129 /// canonical OTP-shape supervision vocabulary the `:max-restarts`
3130 /// field's docstring already carries.
3131 #[must_use]
3132 pub const fn max_restarts(&self) -> Option<u32> {
3133 self.max_restarts
3134 }
3135
3136 /// Substrate-canonical per-`Caixa` `:restart-window` M2 supervisor-
3137 /// tree-slot flat-spread OTP-`Period`-shaped restart-intensity-
3138 /// denominator raw-duration-string scalar accessor every consumer of
3139 /// the top-level manifest's per-Supervisor `:restart-window` sliding-
3140 /// window axis keys off — returns the author-declared `:restart-window`
3141 /// typed `Option<String>` verbatim as an `Option<&str>`, borrowed
3142 /// from the typed slot's own `Option<String>` storage. `None` when
3143 /// the slot is absent (the canonical "never reset — every restart
3144 /// across the supervisor's lifetime counts against the sibling
3145 /// `:max-restarts` budget" sentinel every non-`Supervisor`-kind
3146 /// `defcaixa` carries by `#[serde(default)]` and every
3147 /// `Supervisor`-kind `defcaixa` may still omit to defer to the
3148 /// [`Self::supervisor_view`] `restart_window: None` composition
3149 /// through the [`crate::supervisor::duration_codec::parse`] soft-
3150 /// swallow `.and_then(|s| … .ok())` fold).
3151 ///
3152 /// The `:restart-window` slot carries the raw M2 typed Erlang/OTP-
3153 /// shaped `Period` sliding-observation-interval duration string that
3154 /// pairs with the sibling `:max-restarts` `MaxIntensity` restart-
3155 /// budget count to form the `MaxIntensity / Period` restart-intensity
3156 /// ratio the supervisor trips its own escalation on (INSPIRATIONS
3157 /// §II.2 — Erlang/OTP `supervisor` `{intensity, 5, 60}` worker-
3158 /// supervisor default; RUNTIME-PATTERNS §II.2). The outer-`Caixa`
3159 /// slot stores the raw duration string (`"60s"`, `"5m"`, `"500ms"`)
3160 /// authored under `:restart-window` — the typed [`SupervisorSpec`]
3161 /// holds an `Option<Duration>` routed through the shared
3162 /// [`crate::supervisor::duration_codec`] via `with = "duration_codec"`
3163 /// — so the outer altitude's accessor returns `Option<&str>` (raw
3164 /// authoring surface) while the inner altitude's
3165 /// [`crate::supervisor::SupervisorSpec::restart_window`] returns
3166 /// `Option<Duration>` (parsed typed surface). The parse-refusal arm
3167 /// is closed by the sibling [`Self::validate_restart_window`] gate
3168 /// that surfaces [`ManifestError::RestartWindowMalformed`] naming
3169 /// the offending value; the view-construction path
3170 /// [`Self::supervisor_view`] soft-swallows the same parse error to
3171 /// `None` to keep the view best-effort.
3172 ///
3173 /// Prior to this lift the `.restart_window` field was accessed inline
3174 /// at three production sites in `caixa-core/src/manifest.rs` — the
3175 /// [`Self::declared_supervisor_slots`]
3176 /// `SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW` presence-probe arm at
3177 /// `if self.restart_window.is_some()` (which drives the
3178 /// [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] kind-
3179 /// coherence gate's per-slot label push), the
3180 /// [`Self::validate_restart_window`] `let Some(s) =
3181 /// self.restart_window.as_deref()` empty-and-shape gate binding
3182 /// (which folds the raw string through the shared
3183 /// [`crate::supervisor::duration_codec::parse`] to surface
3184 /// [`ManifestError::RestartWindowMalformed`] naming the offending
3185 /// value), and the [`Self::supervisor_view`] `self.restart_window
3186 /// .as_deref().and_then(…)` view-construction fold (which composes
3187 /// the flat-spread outer author-surface `Option<String>` onto the
3188 /// inner post-composition [`SupervisorSpec`] `Option<Duration>`
3189 /// field the [`SupervisorSpec::restart_window`] accessor keys off) —
3190 /// three open-coded field-accesses that expressed no compile-time
3191 /// link back to the typed slot. A future extension of the outer
3192 /// `:restart-window` axis to a richer author surface (a per-cluster
3193 /// window override, a per-tenant window-alias table, a per-Supervisor
3194 /// dynamic window derivation the future adaptive-supervision engine
3195 /// computes from child-failure-history topology, a promotion of the
3196 /// plain `Option<String>` raw duration to a typed `Option<Duration>`
3197 /// once the future author-surface parser lands at the [`Caixa`]
3198 /// altitude and the raw-string form is retired) would have had to be
3199 /// threaded through every open-coded copy in lockstep or the three
3200 /// consumers would silently disagree on which raw string a given
3201 /// [`Caixa`] resolves to. Lifting the resolution rule to a typed
3202 /// method on the substrate primitive means every downstream consumer
3203 /// of the caixa's per-`Caixa` outer-altitude restart-window raw-
3204 /// string surface reaches for exactly one typed dispatch — the
3205 /// resolver's accept-set migrates as a unit on any future axis
3206 /// addition.
3207 ///
3208 /// Third outer top-level [`Caixa`] supervisor-tree-slot flat-spread
3209 /// accessor — folds on the outer-`Caixa` M2 supervisor-tree flat-
3210 /// spread projection pattern the sibling per-`Caixa`
3211 /// [`Self::estrategia`] (ed04d3c) `Option<Copy>` and
3212 /// [`Self::max_restarts`] `Option<Copy>` accessors opened, extends
3213 /// the sub-family onto the sibling `Option<&str>` raw-duration-
3214 /// string arm (the outer altitude's raw-string form; the inner
3215 /// altitude's parsed [`Duration`] form is the peer
3216 /// [`crate::supervisor::SupervisorSpec::restart_window`] accessor).
3217 /// Peer of the sibling per-`Caixa` `Option<&str>`-return scalar
3218 /// accessors ([`Self::licenca`] / [`Self::repositorio`] /
3219 /// [`Self::descricao`] / [`Self::edicao`]) on the universal-axis
3220 /// outer scalar-projection family the outer-`Caixa` `Option<&str>`
3221 /// sub-family already carries — same "one typed dispatch on the
3222 /// substrate primitive, thin projections at each consumer"
3223 /// discipline extended onto the M2 supervisor-tree flat-spread
3224 /// `Option<&str>` raw-duration-string arm. Named `restart_window()`
3225 /// to match the storage field's name and the per-[`SupervisorSpec`]
3226 /// peer [`crate::supervisor::SupervisorSpec::restart_window`]
3227 /// method-name discipline verbatim; the accessor's identity maps
3228 /// onto the canonical OTP-shape supervision vocabulary the
3229 /// `:restart-window` field's docstring already carries.
3230 #[must_use]
3231 pub fn restart_window(&self) -> Option<&str> {
3232 self.restart_window.as_deref()
3233 }
3234
3235 /// Substrate-canonical per-`Caixa` `:upgrade-from` M2 typed-slot
3236 /// outer-composite OTP-appup-shaped per-prior-version migration-
3237 /// entry-list slice accessor every consumer of the top-level
3238 /// manifest's per-Servico hot-upgrade-block `&[UpgradeFromEntry]`
3239 /// slice-view keys off — returns the author-declared `:upgrade-from`
3240 /// typed `Vec<UpgradeFromEntry>` verbatim as a
3241 /// `&[UpgradeFromEntry]` slice-view over the same backing buffer
3242 /// the raw `self.upgrade_from.as_slice()` field access borrows
3243 /// from. Empty-slice-carrying (the "no hot-upgrade path declared"
3244 /// arm every `defcaixa` without an `:upgrade-from` block carries;
3245 /// the [`Self::from_lisp`] derive folds an omitted `:upgrade-from`
3246 /// through `#[serde(default)]` to `Vec::new()`, so a `Caixa` past
3247 /// parse definitionally carries a `Vec<UpgradeFromEntry>` slot —
3248 /// possibly empty — and the returned `&[UpgradeFromEntry]`
3249 /// degenerates to an empty slice on that arm without any silent
3250 /// `None` collapse).
3251 ///
3252 /// The outer `:upgrade-from` slot carries the M2 typed OTP-appup
3253 /// migration block — the load-bearing container of every per-
3254 /// prior-`:versao` migration-instruction list the wasm-operator
3255 /// dispatches on at hot-upgrade time (INSPIRATIONS §II.4 — OTP
3256 /// `.appup` per-prior-version `LoadModule | StateChange |
3257 /// SoftPurge | Purge | Restart` instruction algebra translated
3258 /// onto pleme-io's typed `:upgrade-from :from` + `:instructions`
3259 /// entry list; CAIXA-SDLC §II — the typed-M2 slot algebra the
3260 /// operator's hot-upgrade dispatch fans on). Every per-entry axis
3261 /// threads through a lifted per-entry accessor on the
3262 /// [`UpgradeFromEntry`] type: the
3263 /// [`UpgradeFromEntry::prior_versao`] SemVer-shaped previous-
3264 /// version scalar accessor and the
3265 /// [`UpgradeFromEntry::instructions`] `&[UpgradeInstruction]`-
3266 /// return per-entry instruction-list accessor (0137e5a). Every
3267 /// downstream consumer of the hot-upgrade path first passes
3268 /// through this outer accessor onto the slice and then dispatches
3269 /// per-entry through the inner accessors — the two-level dispatch
3270 /// means every per-`:upgrade-from` reader now routes through a
3271 /// typed dispatch on the substrate primitive at both altitudes.
3272 ///
3273 /// Prior to this lift the `.upgrade_from` `Vec<UpgradeFromEntry>`
3274 /// slot was accessed inline at production sites across three
3275 /// files — the [`Self::declared_servico_slots`] M2 declared-slot
3276 /// enumerator's `self.upgrade_from.is_empty()` presence probe
3277 /// (caixa-core/src/manifest.rs, which drives the
3278 /// `M2_AUTHOR_KEY_UPGRADE_FROM` kebab-case author-label push every
3279 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] kind-coherence
3280 /// gate reads), the [`crate::StandardLayout::verify`] per-
3281 /// `:upgrade-from` three-stage validation pass (caixa-core/src/
3282 /// layout.rs, which fans onto the
3283 /// [`crate::upgrade::validate_upgrade_from`] per-entry shape +
3284 /// cross-entry duplicate gate, the
3285 /// [`crate::upgrade::validate_upgrade_from_against_versao`]
3286 /// SemVer-precedence cross-slot gate, the
3287 /// [`crate::upgrade::validate_upgrade_from_against_behavior`]
3288 /// `:state-change` ↔ `:on-state-change` cross-slot composition
3289 /// gate, and the per-instruction script-path existence-probe walk
3290 /// that reads each entry's [`UpgradeFromEntry::instructions`] to
3291 /// resolve every declared migration script against the layout
3292 /// root), and the [`crate::render::servico_m2_overlay`] per-
3293 /// Servico M2 overlay emitter's `!caixa.upgrade_from.is_empty()`
3294 /// presence gate + `serde_yaml::to_value(&caixa.upgrade_from)`
3295 /// projection (caixa-core/src/render.rs, which drives the
3296 /// `M2_KEY_UPGRADE_FROM`-keyed `serde_yaml` projection every
3297 /// `caixa-helm` / `caixa-flux` Servico values-block emitter fans
3298 /// on and lands as the ComputeUnit CR's `spec.upgradeFrom` field).
3299 /// A future extension of the outer `:upgrade-from` axis (a per-
3300 /// cluster `:upgrade-overrides` overlay the wasm-engine operator
3301 /// resolves at admission time so a cluster-specific migration
3302 /// policy can tighten a caixa-declared step without re-authoring
3303 /// the `caixa.lisp`, promotion of the plain
3304 /// `Vec<UpgradeFromEntry>` to a richer `{static, dynamic}`
3305 /// partition once runtime-resolved hot-upgrade instructions land,
3306 /// per-entry priority annotation once multi-strategy fan-out
3307 /// lands) would have had to be threaded through all six open-
3308 /// coded copies in lockstep or one consumer would silently
3309 /// disagree with the peers on which upgrade slice a given Caixa
3310 /// resolves to — a six-consumer split at the enumerator, the
3311 /// three-stage validate pass, the script-path probe walk, and the
3312 /// M2 overlay emitter, far from the source `caixa.lisp` with no
3313 /// field naming the upgrade-drift root cause. Lifting the
3314 /// resolution rule to a typed method on the substrate primitive
3315 /// means every downstream consumer of the caixa's per-`Caixa`
3316 /// OTP-appup outer-slice surface reaches for exactly one typed
3317 /// dispatch — the resolver's accept-set migrates as a unit on any
3318 /// future axis addition.
3319 ///
3320 /// First outer top-level [`Caixa`] `&[Composite]`-return slice
3321 /// accessor for M2 / M3 typed-slot vec-carry axes — opens the
3322 /// outer-`Caixa` `&[Composite]` composite-slice projection
3323 /// pattern the sibling `:children`
3324 /// [`crate::supervisor::ChildSpec`] / `:membros`
3325 /// [`crate::aplicacao::Membro`] / `:contratos`
3326 /// [`crate::aplicacao::WitContract`] future outer-composite-slice
3327 /// lifts fold on. Peer of the closed outer-`Caixa` scalar
3328 /// `Option<&Composite>` composite-reference family the sibling
3329 /// [`Self::limits`] (b2bd9d7) / [`Self::behavior`] (35d8b52) /
3330 /// [`Self::politicas`] (5d23d29) / [`Self::placement`] (4fb8074) /
3331 /// [`Self::entrada`] (e4128e4) accessors closed on the outer
3332 /// `Option<&Composite>` altitude, extended here to the outer-
3333 /// `Caixa` `&[Composite]` vec-carry altitude. Peer at the inner
3334 /// altitude of [`crate::upgrade::UpgradeFromEntry::instructions`]
3335 /// (0137e5a) — same "one typed dispatch on the substrate
3336 /// primitive, thin projections at each consumer" discipline
3337 /// folded onto the outer top-level [`Caixa`] altitude, opening the
3338 /// M2 vec-carry slot family's outer-composite-slice axis. Sibling
3339 /// in shape to the peer outer-`Caixa` `&[Dep]`-return
3340 /// [`Self::deps`] (ad34b4e) / [`Self::deps_dev`] (f7fd81e) and
3341 /// `&[String]`-return [`Self::autores`] (b5d813f) /
3342 /// [`Self::etiquetas`] (78c7d3c) / [`Self::bibliotecas`]
3343 /// (8a36c23) / [`Self::exe`] (65d9527) / [`Self::servicos`]
3344 /// (611f78b) slice-accessors on the sibling outer-`Caixa` scalar-
3345 /// element vec-carry axes — folds the "outer [`Caixa`] `&[T]`
3346 /// slice" projection pattern onto the sibling M2 typed-composite-
3347 /// element axis (`UpgradeFromEntry` composite, matching the
3348 /// per-inner [`UpgradeFromEntry::instructions`] element type at a
3349 /// different altitude).
3350 ///
3351 /// Returns `&[UpgradeFromEntry]` (not `&Vec<UpgradeFromEntry>`)
3352 /// because every downstream consumer of the hot-upgrade list
3353 /// treats it as a read-only sequence — the slice-view is the
3354 /// narrowest borrow that supports every present + roadmapped
3355 /// consumer (`.iter()`, `.len()`, `.is_empty()`, `serde` slice-
3356 /// serialization through
3357 /// `serde_yaml::to_value(&[UpgradeFromEntry])`) without leaking
3358 /// the backing `Vec`'s grow/push/reserve surface no consumer of
3359 /// the typed view reaches for (the storage-side `Vec` remains
3360 /// reachable through the `pub upgrade_from` field for the
3361 /// mutation-carrying serde round-trip and per-test fixture-
3362 /// mutation paths). Named `upgrade_from()` to match the storage
3363 /// field's `snake_case` name; the kebab-case author-surface tag
3364 /// `:upgrade-from` is the same axis after tatara-lisp's
3365 /// kebab↔snake fold and the accessor's identity maps onto the
3366 /// canonical CAIXA-SDLC §II vocabulary the slot's docstring
3367 /// already carries.
3368 #[must_use]
3369 pub fn upgrade_from(&self) -> &[UpgradeFromEntry] {
3370 self.upgrade_from.as_slice()
3371 }
3372
3373 /// Substrate-canonical per-`Caixa` `:children` M2 supervisor-tree-
3374 /// slot outer-composite OTP-shaped per-supervisor static-child-list
3375 /// slice accessor every consumer of the top-level manifest's per-
3376 /// Supervisor `&[ChildSpec]` slice-view keys off — returns the
3377 /// author-declared `:children` typed `Vec<crate::supervisor::ChildSpec>`
3378 /// verbatim as a `&[crate::supervisor::ChildSpec]` slice-view over
3379 /// the same backing buffer the raw `self.children.as_slice()` field
3380 /// access borrows from. Empty-slice-carrying (the "no static children
3381 /// declared" arm every non-`Supervisor`-kind `defcaixa` carries by
3382 /// #[serde(default)] and every `SimpleOneForOne` supervisor carries
3383 /// by [`crate::supervisor::SupervisorError::SimpleOneForOneWithStaticChildren`]
3384 /// gate; the returned `&[ChildSpec]` degenerates to an empty slice
3385 /// on those arms without any silent `None` collapse).
3386 ///
3387 /// The outer `:children` slot carries the M2 typed OTP-supervisor
3388 /// static-child list — the load-bearing container of every per-
3389 /// child `{caixa, versao, restart}` triple the wasm-operator's
3390 /// hierarchical reconciler dispatches on at supervisor-tree
3391 /// materialization time (INSPIRATIONS §II.2 — OTP `supervisor:init/1`
3392 /// static-child list translated onto pleme-io's typed
3393 /// [`crate::supervisor::ChildSpec`] entry list; CAIXA-SDLC §II —
3394 /// the typed-M2 slot algebra the operator's per-supervisor fan-out
3395 /// dispatch fans on). Every per-child axis threads through a lifted
3396 /// per-entry accessor on the [`crate::supervisor::ChildSpec`] type:
3397 /// the [`crate::supervisor::ChildSpec::nome`] DNS-1123-label
3398 /// child-caixa-identity scalar accessor, the peer versao SemVer-2
3399 /// version-requirement scalar accessor, and the
3400 /// [`crate::supervisor::ChildSpec::restart`] `Copy`-composite-enum
3401 /// per-child post-exit restart-decision-policy discriminant
3402 /// accessor (dfb4a81). Every downstream consumer of the supervisor-
3403 /// tree path first passes through this outer accessor onto the
3404 /// slice and then dispatches per-child through the inner accessors
3405 /// — the two-level dispatch means every per-`:children` reader now
3406 /// routes through a typed dispatch on the substrate primitive at
3407 /// both altitudes.
3408 ///
3409 /// Prior to this lift the `.children` `Vec<ChildSpec>` slot was
3410 /// accessed inline at three production sites across two files —
3411 /// the [`Self::declared_supervisor_slots`] supervisor-tree
3412 /// declared-slot enumerator's `!self.children.is_empty()` presence
3413 /// probe (caixa-core/src/manifest.rs, which drives the
3414 /// `SUPERVISOR_AUTHOR_KEY_CHILDREN` kebab-case author-label push
3415 /// every [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`]
3416 /// kind-coherence gate reads), the [`Self::supervisor_view`]
3417 /// per-supervisor typed-view composer's `self.children.clone()`
3418 /// per-child fold-in path (caixa-core/src/manifest.rs, which
3419 /// materializes the typed [`crate::supervisor::SupervisorSpec`]
3420 /// view every [`crate::StandardLayout::verify`] Supervisor-arm gate
3421 /// dispatches on), and the [`crate::StandardLayout::verify`] per-
3422 /// `:children :caixa` self-parent refusal probe's
3423 /// `&caixa.children`-borrowed
3424 /// [`crate::supervisor::validate_no_self_supervision`] input
3425 /// (caixa-core/src/layout.rs, which pins the "no child names the
3426 /// supervisor's own `:nome`" cross-slot coherence gate). A future
3427 /// extension of the outer `:children` axis (a per-cluster
3428 /// `:children-overrides` overlay the wasm-engine operator resolves
3429 /// at admission time so a cluster-specific child-set can tighten
3430 /// a caixa-declared list without re-authoring the `caixa.lisp`,
3431 /// promotion of the plain `Vec<ChildSpec>` to a richer
3432 /// `{static, dynamic}` partition once Erlang/OTP's
3433 /// `simple_one_for_one`-shaped dynamic-child slot lands as a typed
3434 /// axis, per-child priority annotation once multi-strategy fan-out
3435 /// lands) would have had to be threaded through all three open-
3436 /// coded copies in lockstep or one consumer would silently
3437 /// disagree with the peers on which child slice a given Caixa
3438 /// resolves to — the enumerator's presence probe reading the raw
3439 /// slot while the peer view-composer's fold-in path read an
3440 /// operator-resolved slot would silently split the paired
3441 /// declared-slot enumerator and typed-view composition, and the
3442 /// [`crate::supervisor::validate_no_self_supervision`] self-parent
3443 /// refusal probe reading a third borrow would silently drift the
3444 /// cross-slot coherence gate's traversal input from the two peers,
3445 /// a three-consumer split at the enumerator, the view composer,
3446 /// and the self-parent gate far from the source `caixa.lisp` with
3447 /// no field naming the child-set-drift root cause. Lifting the
3448 /// resolution rule to a typed method on the substrate primitive
3449 /// means every downstream consumer of the caixa's per-`Caixa`
3450 /// OTP-supervisor outer-slice surface reaches for exactly one
3451 /// typed dispatch — the resolver's accept-set migrates as a unit
3452 /// on any future axis addition.
3453 ///
3454 /// Second outer top-level [`Caixa`] `&[Composite]`-return slice
3455 /// accessor for M2 / M3 typed-slot vec-carry axes — folds on the
3456 /// outer-`Caixa` `&[Composite]` composite-slice sub-family the
3457 /// sibling [`Self::upgrade_from`] (2a1f907) accessor opened, peer
3458 /// at the outer altitude of the closed inner-`SupervisorSpec`
3459 /// [`crate::SupervisorSpec::children`] (bc92bce) accessor on the
3460 /// same OTP-supervisor static-child-list axis — same "byte-equal,
3461 /// borrow-shared" outer-accessor discipline extended onto the
3462 /// second outer-`Caixa` `&[Composite]` vec-carry axis. Sibling in
3463 /// shape to the peer outer-`Caixa` `&[Dep]`-return [`Self::deps`]
3464 /// (ad34b4e) / [`Self::deps_dev`] (f7fd81e) and `&[String]`-return
3465 /// [`Self::autores`] (b5d813f) / [`Self::etiquetas`] (78c7d3c) /
3466 /// [`Self::bibliotecas`] (8a36c23) / [`Self::exe`] (65d9527) /
3467 /// [`Self::servicos`] (611f78b) slice-accessors on the sibling
3468 /// outer-`Caixa` scalar-element vec-carry axes — folds the "outer
3469 /// [`Caixa`] `&[T]` slice" projection pattern onto the sibling
3470 /// M2 typed-composite-element axis
3471 /// ([`crate::supervisor::ChildSpec`] composite, matching the
3472 /// per-inner [`crate::SupervisorSpec::children`] element type at a
3473 /// different altitude).
3474 ///
3475 /// Returns `&[crate::supervisor::ChildSpec]` (not
3476 /// `&Vec<ChildSpec>`) because every downstream consumer of the
3477 /// child list treats it as a read-only sequence — the slice-view
3478 /// is the narrowest borrow that supports every present +
3479 /// roadmapped consumer (`.iter()`, `.len()`, `.is_empty()`, the
3480 /// [`crate::supervisor::validate_no_self_supervision`] `&[ChildSpec]`
3481 /// input, `serde` slice-serialization) without leaking the backing
3482 /// `Vec`'s grow/push/reserve surface no consumer of the typed view
3483 /// reaches for (the storage-side `Vec` remains reachable through
3484 /// the `pub children` field for the mutation-carrying serde round-
3485 /// trip and per-test fixture-mutation paths, including the
3486 /// [`Self::supervisor_view`] fold-in path that clones the slot
3487 /// into the typed view). Named `children()` to match the storage
3488 /// field's name verbatim and the tatara-lisp author-surface term
3489 /// (`:children`) the field's own docstring already carries; the
3490 /// accessor's identity maps onto the canonical OTP supervision
3491 /// vocabulary the [`Caixa::children`] field's docstring already
3492 /// reaches for ("Static children of a supervisor").
3493 #[must_use]
3494 pub fn children(&self) -> &[crate::supervisor::ChildSpec] {
3495 self.children.as_slice()
3496 }
3497
3498 /// Substrate-canonical per-`Caixa` `:membros` M3 mesh-slot outer-
3499 /// composite MESH-COMPOSITION-shaped per-Aplicacao member-list slice
3500 /// accessor every consumer of the top-level manifest's per-Aplicacao
3501 /// `&[crate::aplicacao::Membro]` slice-view keys off — returns the
3502 /// author-declared `:membros` typed `Vec<crate::aplicacao::Membro>`
3503 /// verbatim as a `&[crate::aplicacao::Membro]` slice-view over the
3504 /// same backing buffer the raw `self.membros.as_slice()` field access
3505 /// borrows from. Empty-slice-carrying (the "no members declared" arm
3506 /// every non-`Aplicacao`-kind `defcaixa` carries by `#[serde(default)]`
3507 /// and every partially-authored Aplicacao carries before the
3508 /// [`crate::AplicacaoError::MembrosEmpty`] gate fires; the returned
3509 /// `&[Membro]` degenerates to an empty slice on those arms without any
3510 /// silent `None` collapse).
3511 ///
3512 /// The outer `:membros` slot carries the M3 typed MESH-COMPOSITION
3513 /// per-Aplicacao member list — the load-bearing container of every
3514 /// per-member `{caixa, versao}` pair the caixa-mesh renderer's
3515 /// per-Aplicacao program-emission dispatch fans on at mesh-artifact
3516 /// materialization time (MESH-COMPOSITION §III.1 — the typed graph's
3517 /// vertex set the `:contratos` `:de`/`:para` edges resolve against and
3518 /// the `:entrada :para` external-gateway destination validates
3519 /// against; CAIXA-SDLC §II — the typed-M3 slot algebra the operator's
3520 /// per-Aplicacao fan-out dispatch fans on). Every per-member axis
3521 /// threads through a lifted per-entry accessor on the
3522 /// [`crate::aplicacao::Membro`] type: the
3523 /// [`crate::aplicacao::Membro::nome`] DNS-1123-label member-caixa-
3524 /// identity scalar accessor (4a32abf) and the peer
3525 /// [`crate::aplicacao::Membro::versao_requirement`] SemVer-2
3526 /// version-requirement scalar accessor (a40b0e3). Every downstream
3527 /// consumer of the mesh-graph path first passes through this outer
3528 /// accessor onto the slice and then dispatches per-member through
3529 /// the inner accessors — the two-level dispatch means every per-
3530 /// `:membros` reader now routes through a typed dispatch on the
3531 /// substrate primitive at both altitudes.
3532 ///
3533 /// Prior to this lift the `.membros` `Vec<Membro>` slot was accessed
3534 /// inline at three production sites across two files — the
3535 /// [`Self::declared_mesh_slots`] mesh-slot declared-slot
3536 /// enumerator's `!self.membros.is_empty()` presence probe
3537 /// (caixa-core/src/manifest.rs, which drives the
3538 /// `M3_AUTHOR_KEY_MEMBROS` kebab-case author-label push every
3539 /// [`crate::LayoutError::MeshSlotsOnNonAplicacao`] kind-coherence
3540 /// gate reads), the [`Self::aplicacao_view`] per-Aplicacao typed-view
3541 /// composer's `self.membros.clone()` per-member fold-in path
3542 /// (caixa-core/src/manifest.rs, which materializes the typed
3543 /// [`crate::aplicacao::AplicacaoSpec`] view every
3544 /// [`crate::StandardLayout::verify`] Aplicacao-arm gate dispatches
3545 /// on), and the [`crate::StandardLayout::verify`] per-`:membros
3546 /// :caixa` self-membership refusal probe's `&caixa.membros`-borrowed
3547 /// [`crate::aplicacao::validate_no_self_membership`] input
3548 /// (caixa-core/src/layout.rs, which pins the "no member names the
3549 /// Aplicacao's own `:nome`" cross-slot coherence gate). A future
3550 /// extension of the outer `:membros` axis (a per-cluster
3551 /// `:membros-overrides` overlay the wasm-engine operator resolves at
3552 /// admission time so a cluster-specific member-set can tighten a
3553 /// caixa-declared list without re-authoring the `caixa.lisp`,
3554 /// promotion of the plain `Vec<Membro>` to a richer
3555 /// `{static, dynamic}` partition once runtime-resolved Aplicacao
3556 /// members land as a typed axis, per-member priority annotation once
3557 /// multi-strategy fan-out lands) would have had to be threaded
3558 /// through all three open-coded copies in lockstep or one consumer
3559 /// would silently disagree with the peers on which member slice a
3560 /// given Caixa resolves to — the enumerator's presence probe reading
3561 /// the raw slot while the peer view-composer's fold-in path read an
3562 /// operator-resolved slot would silently split the paired
3563 /// declared-slot enumerator and typed-view composition, and the
3564 /// [`crate::aplicacao::validate_no_self_membership`] self-membership
3565 /// refusal probe reading a third borrow would silently drift the
3566 /// cross-slot coherence gate's traversal input from the two peers, a
3567 /// three-consumer split at the enumerator, the view composer, and
3568 /// the self-membership gate far from the source `caixa.lisp` with no
3569 /// field naming the member-set-drift root cause. Lifting the
3570 /// resolution rule to a typed method on the substrate primitive
3571 /// means every downstream consumer of the caixa's per-`Caixa`
3572 /// MESH-COMPOSITION outer-slice surface reaches for exactly one
3573 /// typed dispatch — the resolver's accept-set migrates as a unit on
3574 /// any future axis addition.
3575 ///
3576 /// Third outer top-level [`Caixa`] `&[Composite]`-return slice
3577 /// accessor for M2 / M3 typed-slot vec-carry axes — opens the outer-
3578 /// `Caixa` M3 mesh-slot arm of the `&[Composite]` composite-slice
3579 /// sub-family the sibling M2 [`Self::upgrade_from`] (2a1f907) /
3580 /// [`Self::children`] (c17b51e) accessors opened for the M2 vec-carry
3581 /// altitude. Peer at the outer altitude of the closed inner-
3582 /// [`crate::AplicacaoSpec::membros`] (6c77e36) accessor on the same
3583 /// MESH-COMPOSITION per-Aplicacao member-list axis — the two
3584 /// altitudes now share the same "byte-equal, borrow-shared" outer-
3585 /// accessor discipline. Sibling in shape to the peer outer-`Caixa`
3586 /// `&[Dep]`-return [`Self::deps`] (ad34b4e) / [`Self::deps_dev`]
3587 /// (f7fd81e) and `&[String]`-return [`Self::autores`] (b5d813f) /
3588 /// [`Self::etiquetas`] (78c7d3c) / [`Self::bibliotecas`] (8a36c23) /
3589 /// [`Self::exe`] (65d9527) / [`Self::servicos`] (611f78b) slice-
3590 /// accessors on the sibling outer-`Caixa` scalar-element vec-carry
3591 /// axes — folds the "outer [`Caixa`] `&[T]` slice" projection
3592 /// pattern onto the sibling M3 typed-composite-element axis
3593 /// ([`crate::aplicacao::Membro`] composite, matching the per-inner
3594 /// [`crate::AplicacaoSpec::membros`] element type at a different
3595 /// altitude).
3596 ///
3597 /// Returns `&[crate::aplicacao::Membro]` (not `&Vec<Membro>`)
3598 /// because every downstream consumer of the member list treats it
3599 /// as a read-only sequence — the slice-view is the narrowest borrow
3600 /// that supports every present + roadmapped consumer (`.iter()`,
3601 /// `.len()`, `.is_empty()`, the
3602 /// [`crate::aplicacao::validate_no_self_membership`] `&[Membro]`
3603 /// input, `serde` slice-serialization) without leaking the backing
3604 /// `Vec`'s grow/push/reserve surface no consumer of the typed view
3605 /// reaches for (the storage-side `Vec` remains reachable through the
3606 /// `pub membros` field for the mutation-carrying serde round-trip
3607 /// and per-test fixture-mutation paths, including the
3608 /// [`Self::aplicacao_view`] fold-in path that clones the slot into
3609 /// the typed view). Named `membros()` to match the storage field's
3610 /// name verbatim and the tatara-lisp author-surface term
3611 /// (`:membros`) the field's own docstring already carries; the
3612 /// accessor's identity maps onto the canonical MESH-COMPOSITION
3613 /// vocabulary the [`Caixa::membros`] field's docstring already
3614 /// reaches for ("Member Servicos that make up this Aplicacao").
3615 #[must_use]
3616 pub fn membros(&self) -> &[crate::aplicacao::Membro] {
3617 self.membros.as_slice()
3618 }
3619
3620 /// Substrate-canonical per-`Caixa` `:contratos` M3 mesh-slot outer-
3621 /// composite MESH-COMPOSITION-shaped per-Aplicacao WIT-typed
3622 /// inter-Servico contract-list slice accessor every consumer of the
3623 /// top-level manifest's per-Aplicacao `&[crate::aplicacao::WitContract]`
3624 /// slice-view keys off — returns the author-declared `:contratos`
3625 /// typed `Vec<crate::aplicacao::WitContract>` verbatim as a
3626 /// `&[crate::aplicacao::WitContract]` slice-view over the same
3627 /// backing buffer the raw `self.contratos.as_slice()` field access
3628 /// borrows from. Empty-slice-carrying (the "no contracts declared"
3629 /// arm every non-`Aplicacao`-kind `defcaixa` carries by
3630 /// `#[serde(default)]` and every leaf Aplicacao carrying only a
3631 /// single member with no inter-Servico edge carries; the returned
3632 /// `&[WitContract]` degenerates to an empty slice on those arms
3633 /// without any silent `None` collapse).
3634 ///
3635 /// The outer `:contratos` slot carries the M3 typed MESH-COMPOSITION
3636 /// per-Aplicacao WIT-typed inter-Servico edge list — the load-bearing
3637 /// container of every per-edge `{de, para, wit, endpoint | subject |
3638 /// slot}` quadruple the caixa-mesh renderer's per-Aplicacao
3639 /// `CiliumNetworkPolicy` fan-out (one L7 policy per edge —
3640 /// MESH-COMPOSITION §III.2 point 2) and per-`(:de, :para)`
3641 /// adjacency-list seed dispatch on at mesh-artifact materialization
3642 /// time (MESH-COMPOSITION §III.1 — the typed graph's edge set the
3643 /// `:membros` vertex set resolves against, closed by the
3644 /// [`crate::AplicacaoError::ContractoUnknownMember`] / cycle-refusal
3645 /// gates in §III.3; CAIXA-SDLC §II — the typed-M3 slot algebra the
3646 /// operator's per-Aplicacao fan-out dispatch fans on). Every
3647 /// per-edge axis threads through a lifted per-entry accessor on the
3648 /// [`crate::aplicacao::WitContract`] type: the peer `de` / `para`
3649 /// DNS-1123-label member-caixa-name endpoint scalar accessors, the
3650 /// [`crate::aplicacao::WitContract::endpoint`] (7020470) HTTP-shape
3651 /// / [`crate::aplicacao::WitContract::subject`] (90de675)
3652 /// NATS-pub-sub-shape / [`crate::aplicacao::WitContract::slot`]
3653 /// (ed22b66) `wasi:keyvalue/store`-shape payload-carrier accessors,
3654 /// and the WIT-world discriminant. Every downstream consumer of the
3655 /// mesh-graph edge path first passes through this outer accessor
3656 /// onto the slice and then dispatches per-contract through the
3657 /// inner accessors — the two-level dispatch means every
3658 /// per-`:contratos` reader now routes through a typed dispatch on
3659 /// the substrate primitive at both altitudes.
3660 ///
3661 /// Prior to this lift the `.contratos` `Vec<WitContract>` slot was
3662 /// accessed inline at two production sites in
3663 /// caixa-core/src/manifest.rs — the [`Self::declared_mesh_slots`]
3664 /// mesh-slot declared-slot enumerator's
3665 /// `!self.contratos.is_empty()` presence probe (which drives the
3666 /// `M3_AUTHOR_KEY_CONTRATOS` kebab-case author-label push every
3667 /// [`crate::LayoutError::MeshSlotsOnNonAplicacao`] kind-coherence
3668 /// gate reads) and the [`Self::aplicacao_view`] per-Aplicacao
3669 /// typed-view composer's `self.contratos.clone()` per-contract
3670 /// fold-in path (which materializes the typed
3671 /// [`crate::aplicacao::AplicacaoSpec`] view every
3672 /// [`crate::StandardLayout::verify`] Aplicacao-arm gate and every
3673 /// downstream `caixa-mesh` renderer dispatches on). A future
3674 /// extension of the outer `:contratos` axis (a per-cluster
3675 /// `:contratos-overrides` overlay the wasm-engine operator resolves
3676 /// at admission time so a cluster-specific edge-set can tighten a
3677 /// caixa-declared list without re-authoring the `caixa.lisp`,
3678 /// promotion of the plain `Vec<WitContract>` to a richer
3679 /// `{static, dynamic}` partition once runtime-resolved contract
3680 /// edges land, per-edge policy annotation once the M4 per-edge
3681 /// policy overlay axis lands) would have had to be threaded through
3682 /// both open-coded copies in lockstep or one consumer would
3683 /// silently disagree with the peer on which edge slice a given
3684 /// Caixa resolves to — the enumerator's presence probe reading the
3685 /// raw slot while the peer view-composer's fold-in path read an
3686 /// operator-resolved slot would silently split the paired
3687 /// declared-slot enumerator and typed-view composition, a
3688 /// two-consumer split at the enumerator and the view composer far
3689 /// from the source `caixa.lisp` with no field naming the edge-set-
3690 /// drift root cause. Lifting the resolution rule to a typed method
3691 /// on the substrate primitive means every downstream consumer of
3692 /// the caixa's per-`Caixa` MESH-COMPOSITION outer-slice surface
3693 /// reaches for exactly one typed dispatch — the resolver's
3694 /// accept-set migrates as a unit on any future axis addition.
3695 ///
3696 /// Fourth and final outer top-level [`Caixa`] `&[Composite]`-return
3697 /// slice accessor for M2 / M3 typed-slot vec-carry axes — closes
3698 /// the outer-`Caixa` `&[Composite]` composite-slice sub-family the
3699 /// sibling M2 [`Self::upgrade_from`] (2a1f907) / [`Self::children`]
3700 /// (c17b51e) accessors opened and the M3 [`Self::membros`]
3701 /// (0f26987) accessor folded on, and closes the outer-`Caixa` M3
3702 /// mesh-slot arm of the composite-slice sub-family the sibling
3703 /// [`Self::membros`] accessor opened for the M3 vec-carry altitude.
3704 /// Peer at the outer altitude of the closed inner-
3705 /// [`crate::AplicacaoSpec::contratos`] (0dcc926) accessor on the
3706 /// same MESH-COMPOSITION per-Aplicacao contract-list axis — the two
3707 /// altitudes now share the same "byte-equal, borrow-shared" outer-
3708 /// accessor discipline. Sibling in shape to the peer outer-`Caixa`
3709 /// `&[Dep]`-return [`Self::deps`] (ad34b4e) / [`Self::deps_dev`]
3710 /// (f7fd81e) and `&[String]`-return [`Self::autores`] (b5d813f) /
3711 /// [`Self::etiquetas`] (78c7d3c) / [`Self::bibliotecas`] (8a36c23) /
3712 /// [`Self::exe`] (65d9527) / [`Self::servicos`] (611f78b) slice-
3713 /// accessors on the sibling outer-`Caixa` scalar-element vec-carry
3714 /// axes — folds the "outer [`Caixa`] `&[T]` slice" projection
3715 /// pattern onto the sibling M3 typed-composite-element axis
3716 /// ([`crate::aplicacao::WitContract`] composite, matching the
3717 /// per-inner [`crate::AplicacaoSpec::contratos`] element type at a
3718 /// different altitude).
3719 ///
3720 /// Returns `&[crate::aplicacao::WitContract]` (not
3721 /// `&Vec<WitContract>`) because every downstream consumer of the
3722 /// contract list treats it as a read-only sequence — the slice-view
3723 /// is the narrowest borrow that supports every present + roadmapped
3724 /// consumer (`.iter()`, `.len()`, `.is_empty()`, per-edge WIT-world
3725 /// discriminant dispatch, `serde` slice-serialization) without
3726 /// leaking the backing `Vec`'s grow/push/reserve surface no
3727 /// consumer of the typed view reaches for (the storage-side `Vec`
3728 /// remains reachable through the `pub contratos` field for the
3729 /// mutation-carrying serde round-trip and per-test fixture-mutation
3730 /// paths, including the [`Self::aplicacao_view`] fold-in path that
3731 /// clones the slot into the typed view). Named `contratos()` to
3732 /// match the storage field's name verbatim and the tatara-lisp
3733 /// author-surface term (`:contratos`) the field's own docstring
3734 /// already carries; the accessor's identity maps onto the canonical
3735 /// MESH-COMPOSITION vocabulary the [`Caixa::contratos`] field's
3736 /// docstring already reaches for ("WIT-typed inter-Servico
3737 /// contracts").
3738 #[must_use]
3739 pub fn contratos(&self) -> &[crate::aplicacao::WitContract] {
3740 self.contratos.as_slice()
3741 }
3742
3743 /// Compose the Aplicacao-related flat slots into a single typed
3744 /// [`crate::aplicacao::AplicacaoSpec`] for validation +
3745 /// downstream renderer consumption. Returns `None` when the
3746 /// caixa isn't a `:kind Aplicacao`.
3747 #[must_use]
3748 pub fn aplicacao_view(&self) -> Option<crate::aplicacao::AplicacaoSpec> {
3749 if !self.kind().is_aplicacao() {
3750 return None;
3751 }
3752 Some(crate::aplicacao::AplicacaoSpec {
3753 membros: self.membros().to_vec(),
3754 contratos: self.contratos().to_vec(),
3755 politicas: self.politicas().cloned().unwrap_or_default(),
3756 placement: self.placement().cloned().unwrap_or_default(),
3757 entrada: self.entrada().cloned(),
3758 })
3759 }
3760
3761 /// The kebab-case `:slot` tags of every M3 mesh slot this caixa
3762 /// *declares* a value on, in canonical declaration order
3763 /// (`:membros` → `:contratos` → `:politicas` → `:placement` →
3764 /// `:entrada`). A slot counts as declared when its backing field
3765 /// carries a value — a non-empty `Vec`, or a `Some(...)`.
3766 ///
3767 /// The M3 mesh slots compose the typed graph of a `:kind Aplicacao`
3768 /// (MESH-COMPOSITION §III.1). [`Self::aplicacao_view`] only folds
3769 /// them into a validatable [`crate::aplicacao::AplicacaoSpec`] when
3770 /// the kind matches (returns `None` otherwise), and the caixa-mesh /
3771 /// caixa-flux / caixa-helm renderers only emit them for an
3772 /// Aplicacao. On any *other* kind a declared mesh slot is the
3773 /// manifest field's documented "ignored otherwise" (see the
3774 /// `:membros` … `:entrada` field docs): it silently passes
3775 /// [`Caixa::from_lisp`] and then vanishes — never validated, never
3776 /// rendered — far from the source caixa.lisp.
3777 /// [`crate::StandardLayout::verify`] consults this to reject that
3778 /// silent-drop at caixa-build time
3779 /// ([`crate::LayoutError::MeshSlotsOnNonAplicacao`]), mirroring the
3780 /// `SupervisorOwnsCode` / `AplicacaoOwnsCode` kind-coherence gates:
3781 /// a slot foreign to the kind is a build error, not a silent drop.
3782 ///
3783 /// Lifted as a typed method (rather than an inline disjunction at
3784 /// the verify call site) so the mesh-slot set lives in one place —
3785 /// a future M4 axis added to the Aplicacao surface (per-edge policy
3786 /// overlay, distributed-app takeover config) is one push here, and
3787 /// every consumer reaching for "which mesh slots are set" (the
3788 /// verify gate, a future `feira lint` kind-coherence advisory)
3789 /// inherits the canonical order without rolling its own.
3790 ///
3791 /// Each per-arm kebab-case label is routed through the peer
3792 /// [`crate::M3_AUTHOR_KEY_MEMBROS`] /
3793 /// [`crate::M3_AUTHOR_KEY_CONTRATOS`] /
3794 /// [`crate::M3_AUTHOR_KEY_POLITICAS`] /
3795 /// [`crate::M3_AUTHOR_KEY_PLACEMENT`] /
3796 /// [`crate::M3_AUTHOR_KEY_ENTRADA`] consts declared next to the
3797 /// [`crate::M3_KEY_PLACEMENT`] renderer-side wire-key peer, so both
3798 /// halves of every M3 top-level mesh slot's dual axis (author-facing
3799 /// kebab-case label + renderer-side artifact key) route through one
3800 /// canonical declaration per arm — same discipline the peer
3801 /// [`crate::M2_AUTHOR_KEY_LIMITS`] / [`crate::M2_AUTHOR_KEY_BEHAVIOR`]
3802 /// / [`crate::M2_AUTHOR_KEY_UPGRADE_FROM`] top-level M2 slot consts
3803 /// (f49c8b0) establish on the sibling per-Servico M2 top-level slot
3804 /// axis, extended here to close the M3 mesh-slot author-facing-label
3805 /// axis so both altitudes of the typed-slot algebra
3806 /// (per-Servico M2 + per-Aplicacao M3) share the same
3807 /// "one canonical byte-string per arm, next to the axis" discipline.
3808 #[must_use]
3809 pub fn declared_mesh_slots(&self) -> Vec<&'static str> {
3810 let mut slots = Vec::new();
3811 if !self.membros().is_empty() {
3812 slots.push(crate::render::M3_AUTHOR_KEY_MEMBROS);
3813 }
3814 if !self.contratos().is_empty() {
3815 slots.push(crate::render::M3_AUTHOR_KEY_CONTRATOS);
3816 }
3817 if self.politicas().is_some() {
3818 slots.push(crate::render::M3_AUTHOR_KEY_POLITICAS);
3819 }
3820 if self.placement().is_some() {
3821 slots.push(crate::render::M3_AUTHOR_KEY_PLACEMENT);
3822 }
3823 if self.entrada().is_some() {
3824 slots.push(crate::render::M3_AUTHOR_KEY_ENTRADA);
3825 }
3826 slots
3827 }
3828
3829 /// The kebab-case `:slot` tags of every supervisor-tree slot this
3830 /// caixa *declares* a value on, in canonical declaration order
3831 /// (`:estrategia` → `:max-restarts` → `:restart-window` →
3832 /// `:children`). A slot counts as declared when its backing field
3833 /// carries a value — a `Some(...)`, or a non-empty `Vec`.
3834 ///
3835 /// The supervisor-tree slots compose the typed OTP supervisor of a
3836 /// `:kind Supervisor` (INSPIRATIONS §II.2; the `:estrategia` +
3837 /// `:children` field docs above). [`Self::supervisor_view`] only
3838 /// folds them into a validatable [`SupervisorSpec`] when the kind
3839 /// matches (returns `None` otherwise), and the wasm-operator's
3840 /// hierarchical reconciler only consumes them for a Supervisor. On
3841 /// any *other* kind a declared supervisor slot is the manifest
3842 /// field's documented "ignored otherwise" (see the `:estrategia` …
3843 /// `:children` field docs): it silently passes [`Caixa::from_lisp`]
3844 /// and then vanishes — never validated, never reconciled — far from
3845 /// the source caixa.lisp. [`crate::StandardLayout::verify`] consults
3846 /// this to reject that silent-drop at caixa-build time
3847 /// ([`crate::LayoutError::SupervisorSlotsOnNonSupervisor`]), the
3848 /// exact mirror of the [`Self::declared_mesh_slots`] /
3849 /// [`crate::LayoutError::MeshSlotsOnNonAplicacao`] gate on the
3850 /// Aplicacao-only slot set: a slot foreign to the kind is a build
3851 /// error, not a silent drop.
3852 #[must_use]
3853 pub fn declared_supervisor_slots(&self) -> Vec<&'static str> {
3854 let mut slots = Vec::new();
3855 if self.estrategia().is_some() {
3856 slots.push(crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA);
3857 }
3858 if self.max_restarts().is_some() {
3859 slots.push(crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS);
3860 }
3861 if self.restart_window().is_some() {
3862 slots.push(crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW);
3863 }
3864 if !self.children().is_empty() {
3865 slots.push(crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN);
3866 }
3867 slots
3868 }
3869
3870 /// The kebab-case `:slot` tags of every M2 Servico-runtime slot this
3871 /// caixa *declares* a value on, in canonical declaration order
3872 /// (`:limits` → `:behavior` → `:upgrade-from`). A slot counts as
3873 /// declared when its backing field carries a value — a `Some(...)`,
3874 /// or a non-empty `Vec`.
3875 ///
3876 /// The M2 slots configure the runtime of a long-running wasm
3877 /// component, i.e. a `:kind Servico`: `:limits` is Lunatic
3878 /// per-process sandboxing (INSPIRATIONS §III.1), `:behavior` is the
3879 /// OTP `gen_server` callback set (§II.3), `:upgrade-from` is the OTP
3880 /// appup hot-code-reload table (§II.4). The caixa-helm / caixa-flux
3881 /// renderers gate on [`crate::require_kind`]`(_, Servico)` and only
3882 /// emit these slots for a Servico; on any *other* kind a declared M2
3883 /// slot is the manifest field's documented "ignored otherwise": its
3884 /// well-formedness is checked by [`crate::StandardLayout::verify`]
3885 /// but the value is never rendered into a chart / programs.yaml entry
3886 /// — it silently passes [`Caixa::from_lisp`] + `feira build` and then
3887 /// vanishes, far from the source caixa.lisp.
3888 /// [`crate::StandardLayout::verify`] consults this to reject that
3889 /// silent-drop at caixa-build time
3890 /// ([`crate::LayoutError::ServicoSlotsOnNonServico`]), the exact
3891 /// mirror of the [`Self::declared_mesh_slots`] /
3892 /// [`Self::declared_supervisor_slots`] gates on the peer
3893 /// kind-exclusive slot sets: a slot foreign to the kind is a build
3894 /// error, not a silent drop.
3895 ///
3896 /// Each per-arm kebab-case label is routed through the peer
3897 /// [`crate::M2_AUTHOR_KEY_LIMITS`] / [`crate::M2_AUTHOR_KEY_BEHAVIOR`] /
3898 /// [`crate::M2_AUTHOR_KEY_UPGRADE_FROM`] consts declared next to the
3899 /// [`crate::M2_KEY_LIMITS`] / [`crate::M2_KEY_BEHAVIOR`] /
3900 /// [`crate::M2_KEY_UPGRADE_FROM`] renderer-side wire-key peers, so
3901 /// both halves of the M2 top-level slot's dual axis (author-facing
3902 /// kebab-case label + renderer-side camelCase overlay-container wire
3903 /// key) route through one canonical declaration per arm — same
3904 /// discipline the peer [`crate::M2_BEHAVIOR_AUTHOR_KEY_ON_*`] sub-slot
3905 /// author-label consts (889dc18) establish on the sibling
3906 /// per-callback axis inside the `:behavior` overlay block.
3907 #[must_use]
3908 pub fn declared_servico_slots(&self) -> Vec<&'static str> {
3909 let mut slots = Vec::new();
3910 if self.limits().is_some() {
3911 slots.push(crate::render::M2_AUTHOR_KEY_LIMITS);
3912 }
3913 if self.behavior().is_some() {
3914 slots.push(crate::render::M2_AUTHOR_KEY_BEHAVIOR);
3915 }
3916 if !self.upgrade_from().is_empty() {
3917 slots.push(crate::render::M2_AUTHOR_KEY_UPGRADE_FROM);
3918 }
3919 slots
3920 }
3921
3922 /// The kebab-case `:slot` tags of every code-surface slot this caixa
3923 /// declares a value on that its [`CaixaKind`] doesn't natively own,
3924 /// in canonical declaration order (`:exe` → `:servicos`). A
3925 /// code-surface slot is owned by exactly one kind: `:exe` by
3926 /// [`CaixaKind::Binario`] (the nix-built executable surface), and
3927 /// `:servicos` by [`CaixaKind::Servico`] (the wasm component +
3928 /// `ComputeUnit` daemon surface).
3929 ///
3930 /// Each is silently ignored when declared on the wrong kind: the
3931 /// caixa-helm / caixa-flux / caixa-flake renderers gate on
3932 /// [`crate::require_kind`]`(_, <owning-kind>)`, so on any *other*
3933 /// code-running kind a declared `:exe` / `:servicos` is the manifest
3934 /// field's documented "ignored otherwise" — its path is checked for
3935 /// existence by the layout's `bibliotecas`/`exe`/`servicos` loops
3936 /// (which run after [`Caixa::from_lisp`]), but the value is never
3937 /// rendered into a build target or programs.yaml entry. It silently
3938 /// passes [`Caixa::from_lisp`] + `feira build`, far from the source
3939 /// caixa.lisp, with no field naming which slot is foreign.
3940 ///
3941 /// [`crate::StandardLayout::verify`] consults this to reject that
3942 /// silent-drop at caixa-build time
3943 /// ([`crate::LayoutError::ForeignCodeSlot`]), beside the M2
3944 /// servico-runtime, supervisor-tree, and M3 mesh kind-coherence
3945 /// gates ([`Self::declared_servico_slots`] /
3946 /// [`Self::declared_supervisor_slots`] /
3947 /// [`Self::declared_mesh_slots`]): the fourth kind ↔ slot algebra
3948 /// axis to be closed on the typed surface. The Supervisor /
3949 /// Aplicacao "no code at all" cases ([`crate::LayoutError::SupervisorOwnsCode`]
3950 /// / [`crate::LayoutError::AplicacaoOwnsCode`]) keep their dedicated
3951 /// diagnostics — they fire ahead of this gate on the same `verify`
3952 /// pass, so for Supervisor / Aplicacao the `OwnCode` arm always wins
3953 /// and this method is moot. For Biblioteca / Binario / Servico, this
3954 /// gate fires when a code-running kind declares another code-running
3955 /// kind's exclusive code surface.
3956 ///
3957 /// `:bibliotecas` is deliberately excluded — a Binario or Servico
3958 /// may legitimately ship a `lib/` helper that the underlying
3959 /// substrate (the nix flake for Binario, the wasm component build
3960 /// for Servico) bundles into its build, so the slot's
3961 /// declared-on-wrong-kind cardinality isn't a structural error on
3962 /// either code-running kind. A Biblioteca declaring `:bibliotecas`
3963 /// is the native case (the slot's owning kind). Supervisor /
3964 /// Aplicacao declaring `:bibliotecas` is gated upstream by
3965 /// [`crate::LayoutError::SupervisorOwnsCode`] /
3966 /// [`crate::LayoutError::AplicacaoOwnsCode`].
3967 ///
3968 /// Lifted as a typed method (rather than an inline disjunction at
3969 /// the verify call site) so the foreign-code-slot set lives in one
3970 /// place — a future kind that gains its own code-surface slot is
3971 /// one push here, and every consumer reaching for "which code
3972 /// surfaces are foreign to this kind" (the verify gate, a future
3973 /// `feira lint` kind-coherence advisory, the future `app-operator`'s
3974 /// per-caixa build-target classifier) inherits the canonical order
3975 /// without rolling its own.
3976 #[must_use]
3977 pub fn declared_foreign_code_slots(&self) -> Vec<&'static str> {
3978 let mut slots = Vec::new();
3979 if !self.exe().is_empty() && !self.kind().requires_exe() {
3980 slots.push(":exe");
3981 }
3982 if !self.servicos().is_empty() && !self.kind().requires_servicos() {
3983 slots.push(":servicos");
3984 }
3985 slots
3986 }
3987
3988 /// Validate every entry of `:deps` and `:deps-dev` through
3989 /// [`Dep::validate`] — closing the parity loop with the per-axis
3990 /// `:versao` gates already wired into the typed-graph
3991 /// ([`crate::AplicacaoSpec::validate_membros`] for `:membros`,
3992 /// 9888b13) and typed supervisor tree
3993 /// ([`crate::SupervisorSpec::validate`] for `:children`, b38ff3a).
3994 ///
3995 /// Until this gate landed `:deps :versao` and `:deps-dev :versao`
3996 /// were the only `:versao` axes still untyped past
3997 /// [`Caixa::from_lisp`]: the derive macro stored the requirement
3998 /// as a String without parsing it, so a malformed-but-non-empty
3999 /// requirement (`"^bad-version"`, `"^^0.1"`, `"v0.1"`, `"not-a-req"`)
4000 /// silently passed parse and the `semver::Error` surfaced at
4001 /// lacre-resolve time, far from the source caixa.lisp, with no
4002 /// field naming which `:deps` entry carried the typo. Lifting the
4003 /// gate here makes the four `:versao` typed surfaces (`:deps`,
4004 /// `:deps-dev`, `:membros`, `:children`) structurally equivalent —
4005 /// every requirement string past `validate_deps` is round-trippable
4006 /// through [`crate::parse_requirement`] without re-checking at the
4007 /// resolver layer.
4008 ///
4009 /// Both lists run through the same per-entry validator so a typo
4010 /// in `:deps-dev` surfaces with the same diagnostic as one in
4011 /// `:deps` — neither axis is a second-class citizen of the typed
4012 /// surface.
4013 ///
4014 /// Within each list, [`DepError::DuplicateNome`] closes the
4015 /// set-not-multiset discipline on the `:nome` axis: two entries
4016 /// naming the same caixa carry two `:versao` / `:fonte` / feature
4017 /// triples that the caixa-resolver's lacre pipeline collapses to one
4018 /// via its `HashMap`-keyed-by-`:nome` consumption — the second entry
4019 /// silently overwrites the first at `concrete_versao`-resolve time
4020 /// (the same "second wins / one silently overwrites the other"
4021 /// shape the peer typed-graph duplicate gates already close on every
4022 /// other Vec-shaped authoring surface that keys by name). The
4023 /// duplicate check fires per-list and runs *after* each per-entry
4024 /// [`Dep::validate`] call so a malformed-and-duplicated entry
4025 /// surfaces its narrower per-entry diagnostic
4026 /// ([`DepError::NomeInvalid`], [`DepError::VersaoInvalid`],
4027 /// [`DepError::FonteRepoEmpty`], …) before the cross-entry duplicate
4028 /// diagnostic — the canonical "per-entry shape before cross-entry
4029 /// uniqueness" precedence the peer `:children :caixa`
4030 /// ([`crate::SupervisorSpec::validate`]), `:membros :caixa`
4031 /// ([`crate::AplicacaoSpec::validate_membros`]), `:contratos`
4032 /// ([`crate::AplicacaoSpec::validate`]), `:placement :clusters`
4033 /// ([`crate::AplicacaoSpec::validate_placement`]),
4034 /// `:entrada :paths` ([`crate::AplicacaoSpec::validate`]),
4035 /// `:upgrade-from :from` ([`crate::upgrade::validate_upgrade_from`]),
4036 /// and the within-`:upgrade-from`-entry per-instruction-class
4037 /// singularity gates ([`crate::UpgradeError::DuplicateLoadModule`],
4038 /// [`crate::UpgradeError::DuplicateStateChange`],
4039 /// [`crate::UpgradeError::DuplicateCleanup`]) all establish.
4040 ///
4041 /// Cross-list (`:deps` ↔ `:deps-dev`) coincidence is *not* gated
4042 /// here: Cargo's `[dependencies]` + `[dev-dependencies]` accept the
4043 /// same name in both tables (the dev table's pin overrides the
4044 /// runtime table's pin in test/dev contexts), and caixa's surface
4045 /// mirrors that convention until a deliberate choice retires the
4046 /// override pattern. Only within-list duplicates are structurally
4047 /// incoherent — those are what this gate closes.
4048 pub fn validate_deps(&self) -> Result<(), DepError> {
4049 for &list in crate::dep::DepList::ALL {
4050 let mut seen = std::collections::HashSet::new();
4051 for dep in self.deps_of(list) {
4052 dep.validate()?;
4053 crate::render::insert_first_seen(&mut seen, dep.nome(), || {
4054 DepError::DuplicateNome {
4055 nome: dep.nome().to_string(),
4056 list: list.as_str(),
4057 }
4058 })?;
4059 }
4060 }
4061 Ok(())
4062 }
4063
4064 /// Reject `:nome` values the K8s apiserver would refuse at admission
4065 /// time. The top-level Caixa identity flows directly into every
4066 /// substrate-side artifact's `metadata.name` axis: the
4067 /// `lareira-<nome>` Helm chart name ([`caixa-helm::lib::chart_name`]),
4068 /// the programs.yaml `name:` entry the `lareira-fleet-programs`
4069 /// aggregator keys ComputeUnit derivation off
4070 /// ([`caixa-flux::lib::programs_yaml_entry`]), the
4071 /// `LABEL_APLICACAO` label value carried on every Aplicacao-owned
4072 /// pod and the per-`:contratos` CiliumNetworkPolicy `metadata.name`
4073 /// (`<aplicacao>-<de>-to-<para>`) and the per-`:entrada`
4074 /// `<aplicacao>-<para>` HTTPRoute `metadata.name`
4075 /// ([`caixa-mesh::lib::cilium_network_policies`],
4076 /// [`caixa-mesh::lib::gateway_routes`]), and the default
4077 /// `lib/<nome>.lisp` / `exe/<nome>` layout paths
4078 /// ([`crate::StandardLayout::verify`]). Each K8s apiserver-side
4079 /// schema enforces the DNS-1123 label rule on admission; a
4080 /// structurally invalid `:nome` (`"MyApp"` — the canonical
4081 /// "I copied the display name verbatim" footgun, `"my_app"` — the
4082 /// Python-/Postgres-leak, `"team.app"` — `:nome` is a single label
4083 /// not a subdomain, `"-app"` / `"app-"` — DNS-1123 boundary
4084 /// violations, `"my app"` — the paste-from-doc footgun, `"café"` —
4085 /// IDN must be pre-encoded as Punycode, the 64-byte UUID-shaped
4086 /// over-cap slug) silently passed [`Caixa::from_lisp`] and the
4087 /// failure surfaced at `kubectl apply` time as a `metadata.name:
4088 /// Invalid value` rejection on whichever derived artifact admitted
4089 /// first, far from the source `caixa.lisp` and without any field
4090 /// naming the offending `:nome`.
4091 ///
4092 /// Thin wrapper around [`crate::render::is_dns_1123_label`] (the
4093 /// substrate-side predicate the per-axis name gates already share:
4094 /// `:membros :caixa` 3f9d7a0, `:placement :clusters` 6cbb900,
4095 /// `:children :caixa` 31bfa43) that maps the shared parser-shaped
4096 /// reason into the [`ManifestError::NomeInvalid`] variant, so the
4097 /// diagnostic is self-locating (the offending `:nome` is named
4098 /// verbatim) and the author can grep their `caixa.lisp` for
4099 /// `:nome "<value>"` and fix it in one edit. Same diagnostic shape
4100 /// every per-axis sibling gate already exposes
4101 /// ([`crate::AplicacaoError::MembroCaixaInvalid`],
4102 /// [`crate::AplicacaoError::PlacementClusterInvalid`],
4103 /// [`crate::SupervisorError::ChildCaixaInvalid`]).
4104 ///
4105 /// Empty `:nome` (which [`Caixa::from_lisp`] does not reject — the
4106 /// derive macro stores the raw String) is gated by the narrower
4107 /// [`ManifestError::NomeEmpty`] arm before the predicate is
4108 /// consulted, mirroring the empty-first cascade every per-axis
4109 /// name gate already uses (e.g. `MembroCaixaEmpty` before
4110 /// `MembroCaixaInvalid`, `EmptyChildName` before `ChildCaixaInvalid`).
4111 pub fn validate_nome(&self) -> Result<(), ManifestError> {
4112 // Routes through the shared
4113 // [`crate::render::require_valid_dns_1123_label`] gate the peer
4114 // name axes each land on so drift between the eight axes'
4115 // accepted DNS-1123-label sets is structurally impossible.
4116 let nome = self.nome();
4117 crate::render::require_valid_dns_1123_label(
4118 nome,
4119 || ManifestError::NomeEmpty,
4120 |reason| ManifestError::NomeInvalid {
4121 nome: nome.to_string(),
4122 reason,
4123 },
4124 )
4125 }
4126
4127 /// Reject `:nome` values whose joint length with the canonical
4128 /// [`crate::LAREIRA_CHART_NAME_PREFIX`] (`"lareira-"`) overflows
4129 /// the K8s DNS-1123 label cap [`crate::DNS_1123_LABEL_MAX_LEN`]
4130 /// (63 bytes). Every per-Servico / per-Aplicacao renderer the
4131 /// substrate carries materializes the caixa's `:nome` through the
4132 /// canonical [`crate::lareira_chart_name`] helper (f7320d7) into a
4133 /// `lareira-<nome>` artifact that lands as a K8s `metadata.name` /
4134 /// Helm chart name / `HelmRelease` `release_name`: `caixa-helm`'s
4135 /// `ChartDir.name` + `Chart.yaml::name`
4136 /// (caixa-helm/src/lib.rs:207), `caixa-flux`'s `cluster_bundle`
4137 /// `HelmRelease` `chart:` slot (caixa-flux/src/lib.rs:329),
4138 /// `caixa-tatara`'s `process_for_aplicacao` `release_name` +
4139 /// `oci://<registry>/lareira-<nome>` chart ref
4140 /// (caixa-tatara/src/lib.rs:124,178). Helm's own `Chart.yaml::name`
4141 /// admission rule strict-parses against DNS-1123-label, the Helm
4142 /// operator's tracking-secret name is derived from `release_name`
4143 /// and is itself DNS-1123-label-bounded, and the rendered chart's
4144 /// K8s object `metadata.name` axes embed the chart name as a
4145 /// prefix — every one fails admission on a > 63-byte chart name.
4146 ///
4147 /// The per-axis [`Self::validate_nome`] gate (6c992f8) already
4148 /// caps `:nome` itself at 63 bytes via [`is_dns_1123_label`], so a
4149 /// `:nome` of 56–63 bytes silently passed validate (the inner
4150 /// DNS-1123 check accepts the bare `:nome`) but produced a
4151 /// `lareira-<nome>` of 64–71 bytes that the apiserver / `helm lint`
4152 /// rejected at admission — far from the source `caixa.lisp`, with
4153 /// no field naming the overflow root cause. The
4154 /// [`lareira_chart_name`] helper's own doc comment
4155 /// (caixa-core/src/render.rs:3198) explicitly deferred the fix:
4156 /// "the M4 admission webhook will pin the joint-length invariant
4157 /// when it lands". This gate lands the invariant at the
4158 /// manifest-validate layer rather than waiting for the apiserver
4159 /// — the same fail-at-the-source posture every peer per-axis
4160 /// value-shape gate (DNS-1123 on `:nome`, SemVer-2 on `:versao`,
4161 /// SPDX-expression-shape on `:licenca`, 4-digit decimal year on
4162 /// `:edicao`, etc.) takes.
4163 ///
4164 /// Thin wrapper around
4165 /// [`crate::render::is_lareira_chart_name_shape`] (the
4166 /// substrate-side predicate that composes [`lareira_chart_name`] +
4167 /// [`is_dns_1123_label`] via the lifted
4168 /// [`crate::LAREIRA_CHART_NAME_NOME_MAX_LEN`] budget); maps the
4169 /// shared parser-shaped reason into the
4170 /// [`ManifestError::NomeChartNameBudgetExceeded`] variant so the
4171 /// diagnostic is self-locating (the offending `:nome` is named
4172 /// verbatim alongside the rendered chart name and the budget) and
4173 /// the author can shorten in one edit. The gate runs across every
4174 /// `:kind` — `:nome` is the substrate-wide identity axis any
4175 /// future renderer the substrate adds can derive a
4176 /// `lareira-<nome>` artifact from, and uniform enforcement closes
4177 /// the drift footgun where a future kind grows a chart-emitting
4178 /// render path while the validate cascade doesn't catch it.
4179 ///
4180 /// Runs *after* [`Self::validate_nome`] so the narrower
4181 /// `NomeEmpty` / `NomeInvalid` shape diagnostics fire first — a
4182 /// structurally-malformed `:nome` (empty, uppercase, underscore,
4183 /// dot, leading/trailing hyphen, Unicode, > 63 bytes) surfaces its
4184 /// specific shape error rather than the chart-name-budget error,
4185 /// preserving the legitimate "well-shaped `:nome` that happens to
4186 /// overflow the joint cap" arm for this gate.
4187 pub fn validate_nome_chart_name_budget(&self) -> Result<(), ManifestError> {
4188 let nome = self.nome();
4189 crate::render::is_lareira_chart_name_shape(nome).map_err(|reason| {
4190 ManifestError::NomeChartNameBudgetExceeded {
4191 nome: nome.to_string(),
4192 reason,
4193 }
4194 })
4195 }
4196
4197 /// Reject `:versao` values that don't parse as [`semver::Version`].
4198 /// The top-level Caixa version flows directly into every
4199 /// substrate-side artifact that carries a "this is which version of
4200 /// the caixa" axis: the `lareira-<nome>` Helm chart's `Chart.yaml`
4201 /// `version:` + `appVersion:` axes ([`caixa-helm::lib`] —
4202 /// SemVer-2-strict at `helm template` / `helm install` time per
4203 /// https://helm.sh/docs/topics/charts/#charts-and-versioning), the
4204 /// `feira publish` Zig-style `v<versao>` git tag
4205 /// ([`caixa-flux::lib::programs_yaml_entry`] / the
4206 /// `caixa-publish.yml` reusable workflow), the programs.yaml entry's
4207 /// `versao:` value the `lareira-fleet-programs` aggregator carries
4208 /// onto each rendered ComputeUnit, the OCI image's `:v<versao>` /
4209 /// `:latest` tags the substrate's `wasi-service-flake` builds with
4210 /// `skopeo push`, the lacre closure's pinned versions
4211 /// ([`caixa-resolver`] keys `concrete_versao`), and the
4212 /// `:upgrade-from :from` references peers in this exact `versao`
4213 /// shape (`semver::Version`, not `VersionReq`). Each consumer
4214 /// expects a strict three-part `MAJOR.MINOR.PATCH` (optionally
4215 /// `-prerelease` and/or `+build`); a structurally invalid `:versao`
4216 /// (`"0.1"` — missing patch, the canonical "I shortened it" footgun;
4217 /// `"v0.1.0"` — the git-tag-shape-leaking-into-versao typo;
4218 /// `"latest"` / `"main"` — the "I confused it with a docker tag"
4219 /// footgun; `"^0.1"` / `"~0.1.2"` — the requirement-shape leaking
4220 /// into the version field a peer `:deps :versao` accepts;
4221 /// `"0.1.0.0"` — the four-part Java/Microsoft convention DNS
4222 /// SemVer-2 forbids) silently passed [`Caixa::from_lisp`] (the
4223 /// derive macro stores the raw String) and the failure surfaced at
4224 /// the *first* downstream consumer that strict-parses it: at
4225 /// `helm install` time as a chart-version rejection, at
4226 /// `feira publish` time as a malformed git tag, at lacre-resolve
4227 /// time as a `semver::Error` not naming the offending caixa, at
4228 /// `feira upgrade --to <versao>` time as an unresolvable
4229 /// `:upgrade-from :from` match — far from the source `caixa.lisp`
4230 /// and without any field naming the offending `:versao`.
4231 ///
4232 /// Thin wrapper around [`semver::Version::parse`] — the same parser
4233 /// [`crate::CaixaVersion::parse`] (the typed `:versao` accessor)
4234 /// and [`crate::UpgradeFromEntry::validate`] (the peer
4235 /// `:upgrade-from :from` axis, 26da2c7) consume. Maps the
4236 /// `semver::Error` reason into the [`ManifestError::VersaoInvalid`]
4237 /// variant, carrying the offending `:versao` verbatim + a
4238 /// parser-shaped reason naming the specific violation, so the
4239 /// diagnostic is self-locating (the author can grep their
4240 /// `caixa.lisp` for `:versao "<value>"` and fix it in one edit).
4241 /// Same diagnostic shape as [`ManifestError::NomeInvalid`]
4242 /// (6c992f8) and [`crate::UpgradeError::FromInvalid`]
4243 /// (b0c8389) on the peer axes. With this gate, the typed `:versao`
4244 /// surfaces — top-level `:versao`, `:upgrade-from :from` — are
4245 /// now structurally equivalent (every value past validate is
4246 /// round-trippable through [`semver::Version::parse`] without
4247 /// re-checking at the renderer, resolver, or operator hot-upgrade
4248 /// layer), peer with the four `:versao` requirement axes (`:deps`,
4249 /// `:deps-dev`, `:membros`, `:children`) the prior commits
4250 /// (2420c44, 9888b13, b38ff3a) wired through `parse_requirement`.
4251 ///
4252 /// Empty `:versao` (which [`Caixa::from_lisp`] does not reject —
4253 /// the derive macro stores the raw String) is gated by the
4254 /// narrower [`ManifestError::VersaoEmpty`] arm before the parser is
4255 /// consulted, mirroring the empty-first cascade every per-axis
4256 /// version gate already uses (e.g. `MembroVersaoEmpty` before
4257 /// `MembroVersaoInvalid`, `EmptyChildVersion` before
4258 /// `ChildVersaoInvalid`, `NomeEmpty` before `NomeInvalid`).
4259 pub fn validate_versao(&self) -> Result<(), ManifestError> {
4260 let versao = self.versao();
4261 if versao.is_empty() {
4262 return Err(ManifestError::VersaoEmpty);
4263 }
4264 semver::Version::parse(versao).map_err(|e| ManifestError::VersaoInvalid {
4265 versao: versao.to_string(),
4266 reason: e.to_string(),
4267 })?;
4268 Ok(())
4269 }
4270
4271 /// Reject `:restart-window` values the shared
4272 /// [`crate::supervisor::duration_codec::parse`] refuses. The flat
4273 /// `restart_window: Option<String>` slot on [`Caixa`] is stored
4274 /// raw by the derive macro (the typed [`SupervisorSpec`] holds an
4275 /// `Option<Duration>` routed through the shared codec via `with =
4276 /// "duration_codec"`); the inline `Caixa → SupervisorSpec`
4277 /// view-construction path ([`Self::supervisor_view`]) folds the
4278 /// raw string through the same shared codec and soft-swallows the
4279 /// parse error as `None` to keep the view best-effort. Without
4280 /// this gate a malformed `:restart-window` (`"1.5s"` — the
4281 /// fractional-seconds drift class; `"1.0s"` — the decimal-shaped
4282 /// integer drift; `"0.5m"` — the unit-fraction drift; `"+30s"` /
4283 /// `"-30s"` — the leading-sign drift; `"30x"` — the unknown-unit
4284 /// footgun; `"abc"` — pure garbage; `""` — the empty-after-trim
4285 /// edge case) silently produced a `SupervisorSpec` with
4286 /// `restart_window: None`, indistinguishable from the canonical
4287 /// "omit the slot to express no reset" authoring shape — Erlang/OTP's
4288 /// `MaxIntensity / Period` invariant turns into a never-reset
4289 /// supervisor far from the source `caixa.lisp`, with no field
4290 /// naming the offending `:restart-window`. Lifting the gate to a
4291 /// Caixa-level validator mirrors the trajectory of the peer
4292 /// per-axis identity gates ([`Self::validate_nome`] 6c992f8,
4293 /// [`Self::validate_versao`] 1fdaa02, [`Self::validate_deps`]
4294 /// a7f0d8c) and the ABSORPTION-ROADMAP.md M2.2 test pin
4295 /// (line 196: "reject invalid `:restart-window` (non-duration)").
4296 ///
4297 /// Thin wrapper around [`crate::supervisor::duration_codec::parse`]
4298 /// (the shared codec backing `:supervisor :restart-window` as
4299 /// serde-routed on [`SupervisorSpec`], `:politicas :timeout`, and
4300 /// `:politicas :circuit-breaker :window` — all three covered by
4301 /// the integer-magnitude gate 1c55a2a). Maps the codec's parse
4302 /// error verbatim into the [`ManifestError::RestartWindowMalformed`]
4303 /// variant, carrying the offending raw string + a parser-shaped
4304 /// reason naming the canonical authoring form, so the diagnostic
4305 /// is self-locating (the author can grep their `caixa.lisp` for
4306 /// `:restart-window "<value>"` and fix it in one edit) and
4307 /// uniform with every other manifest-level validate diagnostic.
4308 /// With this gate the four `:restart-window`-shaped surfaces (the
4309 /// flat raw string on [`Caixa`], the typed `Option<Duration>` on
4310 /// [`SupervisorSpec`], the two `MeshPolicy` peer durations) are
4311 /// now structurally equivalent — every value past the codec is in
4312 /// one accepted set, by construction.
4313 ///
4314 /// `None` (the canonical "omit the slot to express no reset"
4315 /// shape) is accepted trivially — the gate is a no-op when the
4316 /// author didn't author a window. The empty string is rejected by
4317 /// the shared codec (its digit-only gate refuses an empty
4318 /// magnitude), surfacing the same `RestartWindowMalformed`
4319 /// diagnostic as every other rejected non-canonical shape.
4320 pub fn validate_restart_window(&self) -> Result<(), ManifestError> {
4321 let Some(s) = self.restart_window() else {
4322 return Ok(());
4323 };
4324 crate::supervisor::duration_codec::parse(s)
4325 .map(|_| ())
4326 .map_err(|reason| ManifestError::RestartWindowMalformed {
4327 restart_window: s.to_string(),
4328 reason,
4329 })
4330 }
4331
4332 /// Reject per-entry values on the three Caixa-level code-surface
4333 /// path lists (`:bibliotecas`, `:exe`, `:servicos`) that the
4334 /// layout checker's `root.join(p)` sandbox would silently subvert.
4335 /// Same three structural footguns the peer
4336 /// [`BehaviorSpec::validate`] (b0c8389) and
4337 /// [`crate::UpgradeInstruction::validate`] `StateChange` arm
4338 /// (26da2c7) already close on the M2 `:behavior :on-*` and
4339 /// `:upgrade-from :state-change :script` axes, here lifted onto
4340 /// the three top-level code-path axes through the shared
4341 /// [`is_sandboxed_relative_path`] predicate:
4342 ///
4343 /// - empty entry (`(:bibliotecas (""))` / `(:exe (""))` /
4344 /// `(:servicos (""))`): `PathBuf::new()` round-trips through
4345 /// [`Path::join`] as the base itself — `root.join("")` ==
4346 /// `root`, so the existence check (`self.exists(&root)`)
4347 /// trivially passes (the project root exists), and the layout
4348 /// silently treats the project root as a biblioteca / exe /
4349 /// servico entry. The `:bibliotecas` loop then hands the root
4350 /// to `tatara_lisp::read` at `feira build` time as if the root
4351 /// directory itself were a Lisp source file — a parse error
4352 /// far from the source `caixa.lisp` with no field naming the
4353 /// offending entry.
4354 /// - absolute path (`(:bibliotecas ("/etc/passwd"))`):
4355 /// [`Path::join`] *replaces* the base when the right-hand side
4356 /// is absolute, so `root.join("/etc/passwd")` resolves to
4357 /// `"/etc/passwd"` and escapes the project sandbox entirely.
4358 /// The existence check then silently consults whatever the
4359 /// escaped path resolves to — for `:bibliotecas`, the layout
4360 /// has no `starts_with`-fence (only `:exe` is fenced under
4361 /// `exe/` and `:servicos` under `servicos/`), so an absolute
4362 /// `:bibliotecas` entry that happens to resolve on disk
4363 /// silently passes. For `:exe` / `:servicos` the fence catches
4364 /// the absolute case downstream as `ExeOutsideDir` /
4365 /// `ServicoOutsideDir` (or `MissingEntry` if the absolute path
4366 /// doesn't exist), but with a downstream-shaped diagnostic
4367 /// that names the resolved escape path rather than the
4368 /// authoring footgun at the source.
4369 /// - parent-escape (`(:bibliotecas ("../sibling/x.lisp"))` /
4370 /// `(:exe ("exe/../../escape.lisp"))`): a [`PathBuf`] with any
4371 /// [`std::path::Component::ParentDir`] anywhere round-trips
4372 /// through [`Path::join`] as a traversal above the caixa root.
4373 /// The `:exe` / `:servicos` `starts_with(<dir>)` fence is
4374 /// *component-aware* (not canonical-path-aware), so
4375 /// `root.join("exe/../../escape.lisp")` `starts_with(exe_dir)`
4376 /// is **true** even though the canonical resolution
4377 /// `{parent of root}/escape.lisp` lives outside the caixa root
4378 /// — the fence silently lets the parent-escape through, and
4379 /// the existence check passes if that escape-target happens
4380 /// to exist. Caught regardless of where the `..` sits
4381 /// (leading, mid-path, trailing) so the gate matches the peer
4382 /// predicate's full coverage.
4383 ///
4384 /// Same `Empty` → `Absolute` → `ParentEscape` arm-ordering every peer
4385 /// `is_sandboxed_relative_path` consumer follows (b0c8389 / 26da2c7);
4386 /// same per-slot diagnostic shape every peer per-axis path-gate
4387 /// exposes (`*Empty { slot }` / `*Absolute { slot, path }` /
4388 /// `*ParentEscape { slot, path }`). Cross-slot precedence is
4389 /// `:bibliotecas` → `:exe` → `:servicos` — the same declaration
4390 /// order [`Caixa::declared_foreign_code_slots`] uses for its
4391 /// canonical foreign-code-slot diagnostic, so a manifest with
4392 /// multiple malformed slots surfaces the lexicographically-earliest
4393 /// slot's diagnostic deterministically.
4394 ///
4395 /// Lifted to the typed surface as a Caixa-level validator (peer
4396 /// of [`Self::validate_nome`] / [`Self::validate_versao`] /
4397 /// [`Self::validate_deps`] / [`Self::validate_restart_window`])
4398 /// and wired into [`crate::StandardLayout::verify`] before the
4399 /// existence-check loops so the diagnostic names the offending
4400 /// slot at the source caixa.lisp rather than reporting a
4401 /// downstream `MissingEntry` / `ExeOutsideDir` /
4402 /// `ServicoOutsideDir` against the resolved sandbox-escape path.
4403 /// The fourth typed code-path surface — every author-supplied
4404 /// path on the manifest — is now structurally accept-shaped
4405 /// past validate, peer with `:behavior :on-*` and
4406 /// `:upgrade-from :state-change :script`.
4407 pub fn validate_code_paths(&self) -> Result<(), ManifestError> {
4408 /// Per-slot file-type contract for the three Caixa-level
4409 /// code-path surfaces (`:bibliotecas`, `:exe`, `:servicos`).
4410 /// Each variant names the predicate the per-entry file-type
4411 /// gate consults; [`Self::None`] opts the slot out of any
4412 /// file-type contract. Lifted as a typed local enum so the
4413 /// per-slot dispatch is exhaustive at the `match` — adding a
4414 /// future axis to the typed-substrate `:` slot set (the
4415 /// future `:assets` resource axis the M5 roadmap names, the
4416 /// future `:nix-flake` derivation axis the caixa-flake
4417 /// emitter consults) lands as one variant + one `match` arm,
4418 /// not a coordinated rewrite of every per-slot bool flag.
4419 ///
4420 /// Peer of the typed-substrate per-slot variant disciplines
4421 /// already established on this surface
4422 /// ([`crate::supervisor::RestartStrategy`] +
4423 /// [`crate::supervisor::RestartPolicy`] on the OTP-shape
4424 /// supervision-tree axis,
4425 /// [`crate::aplicacao::PlacementStrategy`] on the §III.1
4426 /// placement axis, [`crate::aplicacao::WitTarget`] on the
4427 /// `:contratos` payload-target axis): the typed `enum` is
4428 /// the substrate's single source of truth for the per-axis
4429 /// dispatch, and every consumer (the per-arm body here, the
4430 /// future feira-lint per-slot diagnostic renderer, the M4
4431 /// per-axis admission webhook) reaches for the same typed
4432 /// surface rather than re-deriving the partition from inline
4433 /// flag combinations.
4434 enum CodePathFileType {
4435 /// `:exe` — nix-build derivation output, no terminating-
4436 /// extension contract (the canonical `"exe/<name>"`
4437 /// fixtures the layout's `ExeOutsideDir` error message
4438 /// documents carry no extension by convention).
4439 None,
4440 /// `:bibliotecas` — tatara-lisp source files the
4441 /// `feira build` loop reads through `tatara_lisp::read`
4442 /// at parse time. Routes to [`is_lisp_extension`].
4443 LispSource,
4444 /// `:servicos` — ComputeUnit-CR YAML files the
4445 /// caixa-helm / caixa-flux renderers consume through
4446 /// `serde_yaml::from_str`. Routes to
4447 /// [`is_computeunit_yaml_extension`].
4448 ComputeUnitYaml,
4449 }
4450
4451 // The per-slot [`CodePathFileType`] selects which axes carry the
4452 // lifted file-type predicate. `:bibliotecas` is the tatara-lisp
4453 // source axis (the `feira build` loop at
4454 // `caixa-feira/src/cmd/build.rs:33` reads each entry through
4455 // `tatara_lisp::read` at parse time) — the lifted
4456 // [`is_lisp_extension`] predicate gates the `.lisp` extension.
4457 // `:exe` is the nix-built executable surface (per the canonical
4458 // `"exe/<name>"`-shaped fixtures the layout's `ExeOutsideDir`
4459 // error message documents and every in-tree
4460 // `caixa_with_code_paths` positive control uses) — its file-type
4461 // contract is "nix-build derivation output", not a typed source
4462 // file, so [`CodePathFileType::None`] opts the slot out of any
4463 // file-type gate. `:servicos` is the `.computeunit.yaml`
4464 // ComputeUnit-CR axis (the peer caixa-helm / caixa-flux
4465 // renderers consume each entry through `serde_yaml::from_str` as
4466 // a typed `ComputeUnit` CR) — the lifted
4467 // [`is_computeunit_yaml_extension`] predicate gates the compound
4468 // `.computeunit.yaml` suffix. All three axes are surfaced through
4469 // the same iteration so the sandbox-shape + duplicate gates
4470 // apply uniformly; the typed file-type dispatch fires per-slot
4471 // exactly where the downstream consumer's accepted set demands
4472 // it. The third file-type variant ([`ComputeUnitYaml`]) is the
4473 // compounding lift on the peer 64772a9 `:bibliotecas`
4474 // `.lisp`-gate trajectory — the second of the three code-path
4475 // axes to land on a typed compound-suffix gate, with the same
4476 // self-locating per-slot diagnostic shape every peer per-axis
4477 // file-type lift uses (`*NonLispExtension { slot, path }` /
4478 // `*NonComputeUnitYamlExtension { slot, path }`).
4479 for (slot, list, file_type) in [
4480 (
4481 ":bibliotecas",
4482 &self.bibliotecas,
4483 CodePathFileType::LispSource,
4484 ),
4485 (":exe", &self.exe, CodePathFileType::None),
4486 (
4487 ":servicos",
4488 &self.servicos,
4489 CodePathFileType::ComputeUnitYaml,
4490 ),
4491 ] {
4492 // Per-slot set-not-multiset gate on the typed code-path axis.
4493 // Every peer Vec-shaped author-supplied list past validate is
4494 // a set, not a multiset: `:membros :caixa`
4495 // ([`crate::AplicacaoError::MembroDuplicate`]), `:placement
4496 // :clusters` ([`crate::AplicacaoError::PlacementClusterDuplicate`]),
4497 // `:entrada :paths` ([`crate::AplicacaoError::EntradaPathDuplicate`]),
4498 // `:contratos` ([`crate::AplicacaoError::ContratoDuplicate`]),
4499 // `:children :caixa` ([`crate::SupervisorError::DuplicateChild`]),
4500 // `:deps` / `:deps-dev` `:nome` ([`crate::DepError::DuplicateNome`]
4501 // per 359fba5), `:upgrade-from :from` ([`crate::UpgradeError::DuplicateFrom`]),
4502 // `:etiquetas` ([`ManifestError::EtiquetaDuplicate`] per 360a499),
4503 // `:autores` ([`ManifestError::AutorDuplicate`] per 86c769b) —
4504 // the three code-path lists are the last Vec-shaped author-
4505 // supplied slots on the typed Caixa surface still admitting a
4506 // duplicate entry silently. Scope is per-list (`:bibliotecas`
4507 // duplicates are flagged within `:bibliotecas`, not across
4508 // `:bibliotecas` ↔ `:exe`) — the same per-list scope `:deps`
4509 // ↔ `:deps-dev` use (a `:nome` present in both lists is a
4510 // legitimate dev-vs-runtime shape on the dep axis, fenced
4511 // separately by [`crate::dep::validate_no_self_dep`]). On the
4512 // code-path axis a cross-slot collision is structurally
4513 // impossible by the layout's `starts_with(<exe|servicos>_dir)`
4514 // fence — `:exe` and `:servicos` entries are confined to their
4515 // own directory trees, so the only way a string could appear
4516 // on two code-path lists is the (rare, structurally invalid)
4517 // case where `:bibliotecas` carries an `"exe/<x>"` or
4518 // `"servicos/<x>.yaml"`-shaped path.
4519 //
4520 // Without the gate three authoring footguns silently passed:
4521 //
4522 // - `:bibliotecas ("lib/foo.lisp" "lib/foo.lisp")` — the
4523 // canonical copy-paste-the-wrong-file footgun. `feira
4524 // build` (`caixa-feira/src/cmd/build.rs:33`) walks the
4525 // list and re-parses the same file twice, wasting work
4526 // and silently masking the author's intent to declare a
4527 // *second* biblioteca.
4528 // - `:exe ("exe/cli" "exe/cli")` — the same footgun on the
4529 // Binario surface. The future `caixa-flake` `nix flake`
4530 // emitter that materializes each `:exe` entry as a flake
4531 // `packages.<exe-name>` derivation would collide on the
4532 // duplicate package name and surface a flake-eval error
4533 // far from the source `caixa.lisp`.
4534 // - `:servicos ("servicos/x.computeunit.yaml"
4535 // "servicos/x.computeunit.yaml")` — the same footgun on
4536 // the Servico surface. The peer `caixa-helm` / `caixa-flux`
4537 // renderers already refuse `:servicos.len() != 1` with
4538 // the narrower [`UnsupportedServicoCount`] diagnostic, but
4539 // that diagnostic surfaces "too many servicos" without
4540 // naming "duplicate entry" — the typed self-locating
4541 // "which entry is the duplicate" framing only lands at
4542 // this gate.
4543 //
4544 // Same `seen.insert(entry.as_str())` shape every peer per-list
4545 // duplicate gate uses (`:etiquetas` 360a499, `:autores`
4546 // 86c769b, `:deps` 359fba5) and the same "structural shape
4547 // checks fire before the duplicate check on the same entry"
4548 // ordering (a `(:bibliotecas ("" "lib/x.lisp" "lib/x.lisp"))`
4549 // shape surfaces the narrower [`Self::CodePathEmpty`] for the
4550 // empty entry first, not the duplicate on the later pair).
4551 let mut seen = std::collections::HashSet::new();
4552 for entry in list {
4553 let path = Path::new(entry);
4554 match is_sandboxed_relative_path(path) {
4555 Ok(()) => {}
4556 Err(PathShapeViolation::Empty) => {
4557 return Err(ManifestError::CodePathEmpty { slot });
4558 }
4559 Err(PathShapeViolation::Absolute) => {
4560 return Err(ManifestError::CodePathAbsolute {
4561 slot,
4562 path: path.to_path_buf(),
4563 });
4564 }
4565 Err(PathShapeViolation::ParentEscape) => {
4566 return Err(ManifestError::CodePathParentEscape {
4567 slot,
4568 path: path.to_path_buf(),
4569 });
4570 }
4571 }
4572 // The per-slot file-type gate dispatched through the
4573 // typed [`CodePathFileType`] selector above. Each variant
4574 // routes to the lifted predicate the downstream consumer
4575 // demands:
4576 //
4577 // - [`LispSource`] → [`is_lisp_extension`] for
4578 // `:bibliotecas` (the `feira build` loop's
4579 // `tatara_lisp::read` consumer);
4580 // - [`ComputeUnitYaml`] → [`is_computeunit_yaml_extension`]
4581 // for `:servicos` (the caixa-helm / caixa-flux
4582 // `serde_yaml::from_str` consumer's `ComputeUnit` CR
4583 // accepted set);
4584 // - [`None`] for `:exe` — the nix-build derivation-
4585 // output axis has no terminating-extension contract.
4586 //
4587 // Fires after the sandbox-shape arms so a path that is
4588 // *both* sandbox-escaping and wrong-extension surfaces
4589 // the more fundamental sandbox-shape diagnostic first
4590 // (mirrors the peer `EmptyPath` → `AbsolutePath` →
4591 // `ParentEscape` → `NonLispExtension` arm-ordering on
4592 // `:behavior :on-*` c97815a, and `EmptyScript` →
4593 // `AbsoluteScript` → `ParentEscapeScript` →
4594 // `NonLispExtensionScript` on
4595 // `:upgrade-from :state-change :script` 33cc830), and
4596 // before the duplicate gate so the narrower per-entry
4597 // file-type shape dominates the cross-entry uniqueness
4598 // diagnostic (a
4599 // `("servicos/x.yaml" "servicos/x.yaml")` shape on
4600 // `:servicos` surfaces
4601 // `CodePathNonComputeUnitYamlExtension` on the first
4602 // entry rather than `CodePathDuplicate` on the pair —
4603 // peer with the 64772a9 `:bibliotecas`
4604 // `("lib/x.txt" "lib/x.txt")` ordering).
4605 match file_type {
4606 CodePathFileType::None => {}
4607 CodePathFileType::LispSource => {
4608 if !is_lisp_extension(path) {
4609 return Err(ManifestError::CodePathNonLispExtension {
4610 slot,
4611 path: path.to_path_buf(),
4612 });
4613 }
4614 }
4615 CodePathFileType::ComputeUnitYaml => {
4616 if !is_computeunit_yaml_extension(path) {
4617 return Err(ManifestError::CodePathNonComputeUnitYamlExtension {
4618 slot,
4619 path: path.to_path_buf(),
4620 });
4621 }
4622 }
4623 }
4624 crate::render::insert_first_seen(&mut seen, entry.as_str(), || {
4625 ManifestError::CodePathDuplicate {
4626 slot,
4627 path: path.to_path_buf(),
4628 }
4629 })?;
4630 }
4631 }
4632 Ok(())
4633 }
4634
4635 /// Reject `:etiquetas` lists with an empty entry or with two entries
4636 /// agreeing on the same string. `:etiquetas` is the universal
4637 /// registry-search-tag axis on [`Caixa`] (every kind carries the
4638 /// `Vec<String>` slot) and lands verbatim as the Helm chart
4639 /// `Chart.yaml` `keywords:` array on every Servico (caixa-helm's
4640 /// `build_chart_yaml` at `caixa-helm/src/lib.rs:236` folds it through
4641 /// a [`std::collections::BTreeSet`] alongside the four substrate-
4642 /// fixed tags `lareira` / `wasm` / `tatara-lisp` / `caixa-servico`).
4643 /// Two authoring footguns silently passed validate without this gate:
4644 ///
4645 /// - Empty entry (`(:etiquetas (""))` — the canonical paste-from-
4646 /// blank-doc footgun) rendered as `keywords: ["", "caixa-servico",
4647 /// "lareira", "tatara-lisp", "wasm"]` in `Chart.yaml`. Helm's
4648 /// `chart.metadata.keywords` admits the value without a strict
4649 /// parser-side gate, but the empty keyword has no operational
4650 /// meaning — it indexes nothing in the future caixa-registry
4651 /// search axis and clutters the rendered chart with a no-op tag.
4652 /// - Duplicate entries (`(:etiquetas ("demo" "demo"))` — the
4653 /// copy-paste-the-wrong-tag footgun) silently passed validate
4654 /// and were silently dedup'd by caixa-helm's `BTreeSet` collect
4655 /// at chart render — a "second wins / one silently disappears"
4656 /// shape divergent from every peer typed-graph set gate
4657 /// ([`crate::AplicacaoError::MembroDuplicate`] on `:membros`,
4658 /// [`crate::AplicacaoError::PlacementClusterDuplicate`] on
4659 /// `:placement :clusters`, [`crate::AplicacaoError::EntradaPathDuplicate`]
4660 /// on `:entrada :paths`, [`crate::AplicacaoError::ContratoDuplicate`]
4661 /// on `:contratos`, [`crate::DepError::DuplicateNome`] on
4662 /// `:deps` / `:deps-dev` per 359fba5, [`crate::UpgradeError::DuplicateFrom`]
4663 /// on `:upgrade-from`, the per-instruction-class singularity
4664 /// gates [`crate::UpgradeError::DuplicateLoadModule`] /
4665 /// [`crate::UpgradeError::DuplicateStateChange`] /
4666 /// [`crate::UpgradeError::DuplicateCleanup`]). The typed-graph
4667 /// discipline is uniform: every Vec-shaped author-supplied list
4668 /// past validate is set-not-multiset, by construction.
4669 ///
4670 /// Past the empty arm the gate enforces the chart-keyword shape
4671 /// predicate via [`crate::render::is_chart_keyword_shape`]: Cargo's
4672 /// crates.io `[package] keywords` grammar — 1..=20 bytes, starts
4673 /// with an ASCII letter, ASCII alphanumeric / `_` / `-`
4674 /// continuation. Closes the canonical paste-from-doc footguns the
4675 /// bare empty + duplicate arms left open: paste-from-aligned-doc
4676 /// whitespace (`" mesh"`, `"mesh "`), paste-from-multiline-doc
4677 /// newline (`"mesh\nhttp"` — the author pasted a multi-tag block
4678 /// into one entry instead of splitting), paste-from-Windows-CRLF-doc
4679 /// carriage return, CSV-list-separator confusion (`"mesh,http,grpc"`
4680 /// — the author meant three separate list entries), path-separator
4681 /// confusion (`"caixa/servico"`), namespace-suffix (`"http.1"`),
4682 /// leading-digit (`"1foo"`), kebab-leak (`"-foo"`), snake-leak
4683 /// (`"_foo"`), non-ASCII (`"café"`), and paste-from-binary-blob
4684 /// control bytes that would silently land as malformed search tags
4685 /// in the rendered Chart.yaml `keywords:` array and break the
4686 /// Artifact Hub keyword index lookup far from the source caixa.lisp.
4687 /// Mirrors the [`Self::validate_autores`] shape-predicate cascade
4688 /// established on the sibling universal-axis `Vec<String>` surface
4689 /// — the second universal-axis Vec<String> surface to land the
4690 /// empty-first-then-shape-then-duplicate per-entry cascade.
4691 ///
4692 /// Same empty-first cascade discipline every peer per-axis gate
4693 /// uses: the per-entry empty arm fires before the per-entry shape
4694 /// arm fires before the cross-entry duplicate arm, so an
4695 /// `("" "mesh" "mesh")` authoring shape surfaces the narrower
4696 /// [`ManifestError::EtiquetaEmpty`] (the structural "this entry
4697 /// has no value" defect) before either the shape or the duplicate
4698 /// diagnostic. Walks the list in declaration order so the
4699 /// first-collision diagnostic surfaces the lexicographically-
4700 /// earliest offending position, peer with every other duplicate
4701 /// gate on this surface.
4702 ///
4703 /// Universal-axis (every kind carries `:etiquetas`), so wired at the
4704 /// caixa-build gate alongside the peer universal gates
4705 /// [`Self::validate_nome`] / [`Self::validate_versao`] /
4706 /// [`Self::validate_deps`] / [`Self::validate_code_paths`] — before
4707 /// the kind-coherence gates ([`crate::LayoutError::MeshSlotsOnNonAplicacao`]
4708 /// / [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] /
4709 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] /
4710 /// [`crate::LayoutError::ForeignCodeSlot`]) which fence kind-specific
4711 /// slot sets. The future caixa-registry search axis can reach for
4712 /// `caixa.etiquetas` knowing every entry is a non-empty distinct
4713 /// chart-keyword-shaped string without re-deriving the precondition.
4714 pub fn validate_etiquetas(&self) -> Result<(), ManifestError> {
4715 let mut seen = std::collections::HashSet::new();
4716 for etiqueta in self.etiquetas() {
4717 if etiqueta.is_empty() {
4718 return Err(ManifestError::EtiquetaEmpty);
4719 }
4720 crate::render::is_chart_keyword_shape(etiqueta).map_err(|reason| {
4721 ManifestError::EtiquetaInvalid {
4722 etiqueta: etiqueta.clone(),
4723 reason,
4724 }
4725 })?;
4726 crate::render::insert_first_seen(&mut seen, etiqueta.as_str(), || {
4727 ManifestError::EtiquetaDuplicate {
4728 etiqueta: etiqueta.clone(),
4729 }
4730 })?;
4731 }
4732 Ok(())
4733 }
4734
4735 /// Reject `:autores` lists with an empty entry or with two entries
4736 /// agreeing on the same string. `:autores` is the universal
4737 /// maintainer-axis on [`Caixa`] (every kind carries the
4738 /// `Vec<String>` slot) and lands verbatim as the Helm chart
4739 /// `Chart.yaml` `maintainers:` array on every Servico (caixa-helm's
4740 /// `build_chart_yaml` at `caixa-helm/src/lib.rs:251` maps each entry
4741 /// to a `Maintainer { name, email: None }` without dedup). Two
4742 /// authoring footguns silently passed validate without this gate:
4743 ///
4744 /// - Empty entry (`(:autores (""))` — the canonical paste-from-
4745 /// blank-doc footgun) rendered as
4746 /// `maintainers: [{name: "", email: null}]` in `Chart.yaml`. The
4747 /// empty maintainer name has no operational meaning — it
4748 /// identifies no one in the substrate's authorship index and
4749 /// clutters the rendered chart with a no-op maintainer.
4750 /// - Duplicate entries (`(:autores ("pleme-io" "pleme-io"))` —
4751 /// the copy-paste-the-wrong-author footgun) silently passed
4752 /// validate and rendered as two identical maintainer entries.
4753 /// Unlike the [`Self::validate_etiquetas`] peer (caixa-helm's
4754 /// `BTreeSet`-collect on `:etiquetas` silently dedups the
4755 /// rendered `keywords:` array at chart-render time), the
4756 /// `maintainers:` rendering has *no* dedup — duplicate `:autores`
4757 /// entries stack verbatim in the chart, divergent from every
4758 /// peer typed-graph set gate ([`crate::AplicacaoError::MembroDuplicate`]
4759 /// on `:membros`, [`crate::AplicacaoError::PlacementClusterDuplicate`]
4760 /// on `:placement :clusters`, [`crate::AplicacaoError::EntradaPathDuplicate`]
4761 /// on `:entrada :paths`, [`crate::AplicacaoError::ContratoDuplicate`]
4762 /// on `:contratos`, [`crate::DepError::DuplicateNome`] on
4763 /// `:deps` / `:deps-dev`, [`crate::UpgradeError::DuplicateFrom`]
4764 /// on `:upgrade-from`, [`ManifestError::EtiquetaDuplicate`] on
4765 /// `:etiquetas`).
4766 ///
4767 /// Past the empty arm the gate enforces the chart-maintainer-name
4768 /// shape predicate via [`crate::render::is_chart_maintainer_name_shape`]:
4769 /// the structural single-line printable-UTF-8 floor every realistic
4770 /// Helm chart maintainer name carries — 1..=128 bytes, no leading
4771 /// or trailing whitespace, no ASCII control characters anywhere,
4772 /// Unicode bytes accepted. Closes the canonical paste-from-doc
4773 /// footguns the bare empty + duplicate arms left open:
4774 /// paste-from-aligned-doc whitespace (`" pleme-io"`, `"pleme-io "`),
4775 /// paste-from-multiline-doc newline (`"alice\nbob"` — the author
4776 /// pasted a multi-line block of author records into one `:autores`
4777 /// entry instead of splitting into one entry per author),
4778 /// paste-from-Windows-CRLF-doc carriage return, tab-from-aligned-doc,
4779 /// and the paste-from-binary-blob control bytes that would silently
4780 /// land as YAML-illegal byte sequences in the rendered Chart.yaml
4781 /// `maintainers:` array. Mirrors the shape-predicate cascade
4782 /// [`Self::validate_descricao`] / [`Self::validate_licenca`] /
4783 /// [`Self::validate_edicao`] / [`Self::validate_repositorio`]
4784 /// establish past their own empty arms on the sibling universal-axis
4785 /// `Option<String>` surfaces — the first universal-axis Vec<String>
4786 /// surface to land the empty-first-then-shape-then-duplicate per-entry
4787 /// cascade.
4788 ///
4789 /// Same empty-first cascade discipline every peer per-axis gate
4790 /// uses: the per-entry empty arm fires before the per-entry shape
4791 /// arm before the cross-entry duplicate arm. Walks the list in
4792 /// declaration order so the first-collision diagnostic surfaces the
4793 /// lexicographically-earliest offending position, peer with every
4794 /// other duplicate gate on this surface.
4795 ///
4796 /// Universal-axis (every kind carries `:autores`), so wired at the
4797 /// caixa-build gate alongside the peer universal gates
4798 /// [`Self::validate_nome`] / [`Self::validate_versao`] /
4799 /// [`Self::validate_deps`] / [`Self::validate_etiquetas`] /
4800 /// [`Self::validate_code_paths`] — before the kind-coherence gates
4801 /// ([`crate::LayoutError::MeshSlotsOnNonAplicacao`] /
4802 /// [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] /
4803 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] /
4804 /// [`crate::LayoutError::ForeignCodeSlot`]) which fence kind-specific
4805 /// slot sets.
4806 pub fn validate_autores(&self) -> Result<(), ManifestError> {
4807 let mut seen = std::collections::HashSet::new();
4808 for autor in self.autores() {
4809 if autor.is_empty() {
4810 return Err(ManifestError::AutorEmpty);
4811 }
4812 crate::render::is_chart_maintainer_name_shape(autor).map_err(|reason| {
4813 ManifestError::AutorInvalid {
4814 autor: autor.clone(),
4815 reason,
4816 }
4817 })?;
4818 crate::render::insert_first_seen(&mut seen, autor.as_str(), || {
4819 ManifestError::AutorDuplicate {
4820 autor: autor.clone(),
4821 }
4822 })?;
4823 }
4824 Ok(())
4825 }
4826
4827 /// Reject `:repositorio` values whose shape the shared
4828 /// [`crate::render::is_git_repo_url`] predicate refuses. The flat
4829 /// `repositorio: Option<String>` slot on [`Caixa`] is the
4830 /// universal git-shaped homepage axis every kind carries — the
4831 /// substrate routes the same string through two load-bearing
4832 /// consumers:
4833 ///
4834 /// - [`caixa-helm`] folds it verbatim into the rendered
4835 /// `lareira-<nome>` Helm chart's `Chart.yaml` `home:` field
4836 /// (`build_chart_yaml` at `caixa-helm/src/lib.rs:268`) and into
4837 /// the chart `README.md` `repo = …` interpolation
4838 /// (`caixa-helm/src/lib.rs:359`).
4839 /// - [`caixa-flux`] folds it verbatim into the standalone
4840 /// `ClusterBundleOpts::for_caixa` `git_url:` field
4841 /// (`caixa-flux/src/lib.rs:293`), which becomes the `FluxCD`
4842 /// `GitRepository.spec.url` the cluster's source-controller
4843 /// polls — the load-bearing deploy-time axis.
4844 ///
4845 /// Both consumers use `Option::unwrap_or_else(|| <fallback>)` to
4846 /// substitute a placeholder when the slot is absent (`None` → the
4847 /// fallback fires); a `Some("")` *skips the fallback* and silently
4848 /// passes the empty string through to `Chart.yaml home: ""` /
4849 /// `GitRepository url: ""` — Helm's chart lint and `FluxCD`'s source
4850 /// controller both reject the empty URL far from the source
4851 /// `caixa.lisp`, with no field naming the offending `:repositorio`.
4852 /// Similarly a malformed `:repositorio` (whitespace, control char,
4853 /// missing `:` separator, leading `-`) silently lands in the
4854 /// rendered artifacts and breaks at `git clone` / `helm template`
4855 /// / `flux reconcile` time.
4856 ///
4857 /// Thin wrapper around [`crate::render::is_git_repo_url`] — the
4858 /// same shared predicate the peer [`crate::DepSource::validate`]
4859 /// routes the `:fonte (:tipo git :repo …)` axis through. With this
4860 /// gate the two `git URL`-shaped surfaces on the typed Caixa
4861 /// (`:repositorio` here, `:deps :fonte :repo` peer) are
4862 /// structurally equivalent: every value past validate is
4863 /// guaranteed-acceptable by the predicate's union of constraints
4864 /// (non-empty, length-bounded, no leading `-`, no whitespace, no
4865 /// control chars, ASCII only, no leading `:`, contains a `:`
4866 /// separator). The predicate accepts every documented authoring
4867 /// shape — `github:org/repo` shorthand, `https://host/path`,
4868 /// `ssh://[user@]host/path`, `git://host/path`, `git@host:path`
4869 /// scp-style SSH, `file:///path` — and refuses the canonical
4870 /// paste-from-blank-doc / paste-from-multiline-doc / CLI-arg-
4871 /// injection footguns at validate time. Maps the predicate's
4872 /// `String` reason verbatim into the
4873 /// [`ManifestError::RepositorioInvalid`] variant, carrying the
4874 /// offending value + parser-shaped reason so the diagnostic is
4875 /// self-locating (the author can grep their `caixa.lisp` for
4876 /// `:repositorio "<value>"` and fix it in one edit).
4877 ///
4878 /// `None` (the canonical "omit the slot to express no published
4879 /// homepage" shape) is accepted trivially — the gate is a no-op
4880 /// when the author didn't declare a value. `Some("")` is gated by
4881 /// the narrower [`ManifestError::RepositorioEmpty`] arm before the
4882 /// shape predicate is consulted, mirroring the empty-first cascade
4883 /// every peer per-axis identity gate uses
4884 /// ([`ManifestError::NomeEmpty`] → [`ManifestError::NomeInvalid`],
4885 /// [`ManifestError::VersaoEmpty`] → [`ManifestError::VersaoInvalid`],
4886 /// [`crate::DepError::FonteRepoEmpty`] →
4887 /// [`crate::DepError::FonteRepoInvalid`]).
4888 ///
4889 /// Universal-axis (every kind carries `:repositorio`), so wired at
4890 /// the caixa-build gate alongside the peer universal gates
4891 /// [`Self::validate_nome`] / [`Self::validate_versao`] /
4892 /// [`Self::validate_deps`] / [`Self::validate_etiquetas`] /
4893 /// [`Self::validate_autores`] / [`Self::validate_code_paths`] —
4894 /// before the kind-coherence gates
4895 /// ([`crate::LayoutError::MeshSlotsOnNonAplicacao`] /
4896 /// [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] /
4897 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] /
4898 /// [`crate::LayoutError::ForeignCodeSlot`]) which fence kind-
4899 /// specific slot sets.
4900 pub fn validate_repositorio(&self) -> Result<(), ManifestError> {
4901 let Some(s) = self.repositorio() else {
4902 return Ok(());
4903 };
4904 if s.is_empty() {
4905 return Err(ManifestError::RepositorioEmpty);
4906 }
4907 is_git_repo_url(s).map_err(|reason| ManifestError::RepositorioInvalid {
4908 repositorio: s.to_string(),
4909 reason,
4910 })
4911 }
4912
4913 /// Reject `:descricao` values that are the empty string. The flat
4914 /// `descricao: Option<String>` slot on [`Caixa`] is the universal
4915 /// free-form-prose homepage axis every kind carries — the
4916 /// substrate routes the same string through two load-bearing
4917 /// consumers in the [`caixa-helm`] renderer:
4918 ///
4919 /// - `build_chart_yaml` folds it verbatim into the rendered
4920 /// `lareira-<nome>` Helm chart's `Chart.yaml` `description:`
4921 /// field (`caixa-helm/src/lib.rs:232-235`).
4922 /// - `build_readme` folds it verbatim into the rendered chart
4923 /// `README.md` header (`caixa-helm/src/lib.rs:333-336`).
4924 ///
4925 /// Both consumers use `Option::unwrap_or_else(|| <fallback>)` to
4926 /// substitute a `caixa.nome`-derived placeholder when the slot is
4927 /// absent (`None` → the fallback fires); a `Some("")` *skips the
4928 /// fallback* and silently passes the empty string through to
4929 /// `Chart.yaml description: ""` / a blank chart `README.md`
4930 /// header. Helm's chart spec requires a non-empty `description:`
4931 /// field on `apiVersion: v2` charts (`helm lint` surfaces it as
4932 /// `WARNING [chart.metadata.description]: description is required`),
4933 /// so the empty `Some("")` silently lands in the rendered
4934 /// artifacts and breaks at `helm lint` / `helm install` time far
4935 /// from the source `caixa.lisp`, with no field naming the
4936 /// offending `:descricao`.
4937 ///
4938 /// `None` (the canonical "omit the slot to defer to the renderer's
4939 /// `caixa.nome`-derived fallback" shape) is accepted trivially —
4940 /// the gate is a no-op when the author didn't declare a value.
4941 /// `Some("")` is gated by the narrower
4942 /// [`ManifestError::DescricaoEmpty`] arm, mirroring the empty-arm
4943 /// shape every peer per-axis empty gate uses
4944 /// ([`ManifestError::NomeEmpty`], [`ManifestError::VersaoEmpty`],
4945 /// [`ManifestError::EtiquetaEmpty`], [`ManifestError::AutorEmpty`],
4946 /// [`ManifestError::RepositorioEmpty`]).
4947 ///
4948 /// Universal-axis (every kind carries `:descricao`), so wired at
4949 /// the caixa-build gate alongside the peer universal gates
4950 /// [`Self::validate_nome`] / [`Self::validate_versao`] /
4951 /// [`Self::validate_deps`] / [`Self::validate_etiquetas`] /
4952 /// [`Self::validate_autores`] / [`Self::validate_repositorio`] /
4953 /// [`Self::validate_code_paths`] — before the kind-coherence
4954 /// gates ([`crate::LayoutError::MeshSlotsOnNonAplicacao`] /
4955 /// [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] /
4956 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] /
4957 /// [`crate::LayoutError::ForeignCodeSlot`]) which fence kind-
4958 /// specific slot sets.
4959 ///
4960 /// Past the empty arm the gate enforces the chart-description
4961 /// shape predicate via [`crate::render::is_chart_description_shape`]:
4962 /// the structural single-line UTF-8 floor every realistic chart
4963 /// description in the wild matches — 1..=512 bytes, no leading
4964 /// or trailing whitespace, no ASCII control characters anywhere
4965 /// (`0x00..=0x1F` plus `0x7F` DEL — banning tab, newline,
4966 /// carriage return, and every other control byte), Unicode
4967 /// continuation bytes accepted (the canonical fixtures carry
4968 /// `→` and `—`). Closes the canonical paste-from-doc footguns
4969 /// the bare empty-arm gate left open: paste-from-aligned-doc
4970 /// leading / trailing whitespace (`" Checkout flow."`,
4971 /// `"Checkout flow. "`), paste-from-multiline-doc newline
4972 /// (`"Checkout\nflow."`), paste-from-Windows-CRLF-doc CR
4973 /// (`"Checkout\rflow."`), tab-from-aligned-doc
4974 /// (`"Checkout\tflow."`), and paste-from-binary-blob NUL / BEL /
4975 /// ESC / DEL bytes. Mirrors the shape-predicate cascade
4976 /// [`Self::validate_repositorio`] / [`Self::validate_licenca`] /
4977 /// [`Self::validate_edicao`] establish past their own empty arms
4978 /// on the sibling universal-axis `Option<String>` Caixa-level
4979 /// value-shape surfaces.
4980 ///
4981 /// The empty-first cascade discipline mirrors every peer per-axis
4982 /// identity gate: [`ManifestError::DescricaoEmpty`] runs before
4983 /// [`ManifestError::DescricaoInvalid`], so the narrower empty
4984 /// diagnostic surfaces on `Some("")` rather than the broader
4985 /// shape-predicate diagnostic — peer with how
4986 /// [`ManifestError::LicencaEmpty`] runs before
4987 /// [`ManifestError::LicencaInvalid`],
4988 /// [`ManifestError::EdicaoEmpty`] runs before
4989 /// [`ManifestError::EdicaoInvalid`],
4990 /// [`ManifestError::RepositorioEmpty`] runs before
4991 /// [`ManifestError::RepositorioInvalid`].
4992 pub fn validate_descricao(&self) -> Result<(), ManifestError> {
4993 let Some(s) = self.descricao() else {
4994 return Ok(());
4995 };
4996 if s.is_empty() {
4997 return Err(ManifestError::DescricaoEmpty);
4998 }
4999 crate::render::is_chart_description_shape(s).map_err(|reason| {
5000 ManifestError::DescricaoInvalid {
5001 descricao: s.to_string(),
5002 reason,
5003 }
5004 })?;
5005 Ok(())
5006 }
5007
5008 /// Reject `:licenca` values that are the empty string. The flat
5009 /// `licenca: Option<String>` slot on [`Caixa`] is the universal
5010 /// SPDX-shaped license-expression axis every kind carries — the
5011 /// substrate routes the same string through the [`caixa-helm`]
5012 /// renderer's `build_readme` which folds it verbatim into the
5013 /// rendered `lareira-<nome>` Helm chart's `README.md` `## License`
5014 /// section (`caixa-helm/src/lib.rs:361`) via
5015 /// `caixa.licenca.clone().unwrap_or_else(|| "MIT".into())`. The
5016 /// fallback only fires on `None`; a `Some("")` *skips the
5017 /// fallback* and silently passes the empty string through to a
5018 /// chart `README.md` whose `License` section renders as the bare
5019 /// trailing period (`.\n`) — peer footgun with the
5020 /// `Some("")`-skips-`unwrap_or_else` shape the
5021 /// [`Self::validate_descricao`] and [`Self::validate_repositorio`]
5022 /// gates close on the sibling free-form-prose and git-URL axes.
5023 ///
5024 /// `None` (the canonical "omit the slot to defer to the
5025 /// renderer's `MIT` fallback" shape every existing fixture
5026 /// carries) is accepted trivially — the gate is a no-op when the
5027 /// author didn't declare a value. `Some("")` is gated by the
5028 /// narrower [`ManifestError::LicencaEmpty`] arm, mirroring the
5029 /// empty-arm shape every peer per-axis empty gate uses
5030 /// ([`ManifestError::NomeEmpty`], [`ManifestError::VersaoEmpty`],
5031 /// [`ManifestError::EtiquetaEmpty`], [`ManifestError::AutorEmpty`],
5032 /// [`ManifestError::RepositorioEmpty`],
5033 /// [`ManifestError::DescricaoEmpty`]).
5034 ///
5035 /// Universal-axis (every kind carries `:licenca`), so wired at
5036 /// the caixa-build gate alongside the peer universal gates
5037 /// [`Self::validate_nome`] / [`Self::validate_versao`] /
5038 /// [`Self::validate_deps`] / [`Self::validate_etiquetas`] /
5039 /// [`Self::validate_autores`] / [`Self::validate_repositorio`] /
5040 /// [`Self::validate_descricao`] / [`Self::validate_code_paths`]
5041 /// — before the kind-coherence gates
5042 /// ([`crate::LayoutError::MeshSlotsOnNonAplicacao`] /
5043 /// [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] /
5044 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] /
5045 /// [`crate::LayoutError::ForeignCodeSlot`]) which fence kind-
5046 /// specific slot sets.
5047 ///
5048 /// Past the empty arm the gate enforces the SPDX-expression shape
5049 /// predicate via [`crate::render::is_spdx_expression_shape`]: the
5050 /// structural alphabet floor every realistic SPDX expression in
5051 /// the wild uses — ASCII alphanumeric plus `.`, `-`, `+`, `(`,
5052 /// `)`, `:` (the `DocumentRef-…:LicenseRef-…` separator), and a
5053 /// single ASCII space (token separator). Closes the canonical
5054 /// paste-from-doc footguns the bare empty-arm gate left open:
5055 /// paste-from-doc whitespace (`"MIT "`, `" MIT"`), paste-from-
5056 /// multiline-doc CRLF (`"MIT\n"`), tab-from-aligned-doc
5057 /// (`"MIT\tOR Apache-2.0"`), non-ASCII smart-quote paste,
5058 /// underscore-instead-of-hyphen typo (`"Apache_2.0"`),
5059 /// comma-instead-of-`OR`-keyword colloquial idiom (`"MIT,
5060 /// Apache-2.0"`), slash-dual-license colloquial idiom (`"MIT/
5061 /// Apache-2.0"`), and semicolon-list-separator confusion
5062 /// (`"MIT; Apache-2.0"`). Mirrors the shape-predicate cascade
5063 /// [`Self::validate_repositorio`] / [`Self::validate_edicao`]
5064 /// establish past their own empty arms.
5065 ///
5066 /// The empty-first cascade discipline mirrors every peer per-axis
5067 /// identity gate: [`ManifestError::LicencaEmpty`] runs before
5068 /// [`ManifestError::LicencaInvalid`], so the narrower empty
5069 /// diagnostic surfaces on `Some("")` rather than the broader
5070 /// shape-predicate diagnostic — peer with how
5071 /// [`ManifestError::EdicaoEmpty`] runs before
5072 /// [`ManifestError::EdicaoInvalid`],
5073 /// [`ManifestError::RepositorioEmpty`] runs before
5074 /// [`ManifestError::RepositorioInvalid`].
5075 ///
5076 /// A future tightening on this axis can extend the alphabet
5077 /// floor into a full SPDX expression parser + license-id
5078 /// allowlist (rejecting alphabet-valid values that don't name a
5079 /// real SPDX license identifier — e.g., `"NotAReal"` is
5080 /// alphabet-valid but no `NotAReal` license-id exists). That
5081 /// parser only becomes meaningful past a real SPDX-spec
5082 /// dependency; this gate establishes the structural floor by
5083 /// refusing every non-SPDX-alphabet value at validate time.
5084 pub fn validate_licenca(&self) -> Result<(), ManifestError> {
5085 let Some(s) = self.licenca() else {
5086 return Ok(());
5087 };
5088 if s.is_empty() {
5089 return Err(ManifestError::LicencaEmpty);
5090 }
5091 crate::render::is_spdx_expression_shape(s).map_err(|reason| {
5092 ManifestError::LicencaInvalid {
5093 licenca: s.to_string(),
5094 reason,
5095 }
5096 })?;
5097 Ok(())
5098 }
5099
5100 /// Reject `:edicao` values that are the empty string. The flat
5101 /// `edicao: Option<String>` slot on [`Caixa`] is the universal
5102 /// language-edition axis every kind carries — it determines the
5103 /// tatara-lisp macro surface + compatibility flags the substrate
5104 /// applies when building a caixa, and lands verbatim in the
5105 /// `Caixa::template` author-time scaffold (the canonical
5106 /// `:edicao "2026"` line every `feira init` emits via
5107 /// [`Caixa::template`] at `caixa-core/src/manifest.rs:1193`) and
5108 /// in every renderer-side fixture (`caixa-helm/src/lib.rs:375`,
5109 /// `caixa-flux/src/lib.rs:445`, `caixa-mesh/src/lib.rs:629`,
5110 /// `caixa-core/src/render.rs:2510`) via
5111 /// `edicao: Some("2026".into())`.
5112 ///
5113 /// `None` (the canonical "omit the slot to defer to the
5114 /// substrate's default edition" shape every existing
5115 /// [`caixa-resolver`] integration test fixture carries via
5116 /// `edicao: None` — see `caixa-resolver/tests/git_integration.rs`)
5117 /// is accepted trivially — the gate is a no-op when the author
5118 /// didn't declare a value. `Some("")` is gated by the narrower
5119 /// [`ManifestError::EdicaoEmpty`] arm, mirroring the empty-arm
5120 /// shape every peer per-axis empty gate uses
5121 /// ([`ManifestError::NomeEmpty`], [`ManifestError::VersaoEmpty`],
5122 /// [`ManifestError::EtiquetaEmpty`], [`ManifestError::AutorEmpty`],
5123 /// [`ManifestError::RepositorioEmpty`],
5124 /// [`ManifestError::DescricaoEmpty`], [`ManifestError::LicencaEmpty`]).
5125 ///
5126 /// Universal-axis (every kind carries `:edicao`), so wired at
5127 /// the caixa-build gate alongside the peer universal gates
5128 /// [`Self::validate_nome`] / [`Self::validate_versao`] /
5129 /// [`Self::validate_deps`] / [`Self::validate_etiquetas`] /
5130 /// [`Self::validate_autores`] / [`Self::validate_repositorio`] /
5131 /// [`Self::validate_descricao`] / [`Self::validate_licenca`] /
5132 /// [`Self::validate_code_paths`] — before the kind-coherence
5133 /// gates ([`crate::LayoutError::MeshSlotsOnNonAplicacao`] /
5134 /// [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] /
5135 /// [`crate::LayoutError::ServicoSlotsOnNonServico`] /
5136 /// [`crate::LayoutError::ForeignCodeSlot`]) which fence kind-
5137 /// specific slot sets.
5138 ///
5139 /// Past the empty arm the gate enforces the canonical year-shape
5140 /// predicate: every documented tatara-lisp edition is a 4-digit
5141 /// ASCII decimal year (`"2026"` is the only edition currently
5142 /// minted; future-introduced siblings will follow the same
5143 /// shape, peer with Cargo's `[package] edition` grammar which
5144 /// every value Cargo has ever accepted matches — `"2015"`,
5145 /// `"2018"`, `"2021"`, `"2024"`). Any value that's not exactly
5146 /// 4 ASCII decimal bytes is rejected with the narrower
5147 /// [`ManifestError::EdicaoInvalid`] arm, mirroring the
5148 /// shape-predicate cascade [`Self::validate_repositorio`]
5149 /// establishes past its own empty arm
5150 /// ([`ManifestError::RepositorioEmpty`] →
5151 /// [`ManifestError::RepositorioInvalid`]). Closes the canonical
5152 /// paste-from-doc footguns the bare empty-arm gate left open:
5153 ///
5154 /// - leading / trailing whitespace from a paste-from-doc
5155 /// (`"2026 "`, `" 2026"`)
5156 /// - control characters / CRLF from a paste-from-multiline-doc
5157 /// (`"2026\n"`)
5158 /// - non-ASCII look-alikes from a fullwidth keyboard
5159 /// (`"2026"`) which would silently land as a non-ASCII
5160 /// string in the rendered caixa.lisp
5161 /// - free-form non-year values (`"x"`, `"latest"`,
5162 /// `"nightly"`) that have no operational meaning on the
5163 /// substrate's build-time edition selector
5164 /// - leading non-digit prefixes (`"v2026"`, `"e2026"`,
5165 /// `"r2026"`) — common version-tag idioms that don't apply
5166 /// to the year-shaped edition axis
5167 /// - decimal-shaped values (`"2026.1"`, `"2026.0"`) — every
5168 /// edition is a year, not a fractional version
5169 /// - wrong-length numeric values (`"26"`, `"202"`, `"20260"`,
5170 /// `"00026"`) that don't name a year
5171 ///
5172 /// `None` (the canonical "omit the slot to defer to the
5173 /// substrate's default edition" shape every existing
5174 /// [`caixa-resolver`] integration test fixture carries via
5175 /// `edicao: None` — see `caixa-resolver/tests/git_integration.rs`)
5176 /// is accepted trivially — the gate is a no-op when the author
5177 /// didn't declare a value. The empty-first cascade discipline
5178 /// mirrors every peer per-axis identity gate:
5179 /// [`ManifestError::EdicaoEmpty`] runs before
5180 /// [`ManifestError::EdicaoInvalid`], so the narrower empty
5181 /// diagnostic surfaces on `Some("")` rather than the broader
5182 /// shape-predicate diagnostic — peer with how
5183 /// [`ManifestError::NomeEmpty`] runs before
5184 /// [`ManifestError::NomeInvalid`],
5185 /// [`ManifestError::VersaoEmpty`] runs before
5186 /// [`ManifestError::VersaoInvalid`],
5187 /// [`ManifestError::RepositorioEmpty`] runs before
5188 /// [`ManifestError::RepositorioInvalid`].
5189 ///
5190 /// A future tightening on this axis can extend the shape
5191 /// predicate into a known-edition allowlist (rejecting
5192 /// year-shaped values that don't name a tatara-lisp edition
5193 /// the substrate actually understands — e.g., `"1999"` is
5194 /// year-shaped but no `1999` edition exists). That allowlist
5195 /// only becomes meaningful past the introduction of a sibling
5196 /// edition to `"2026"`; this gate establishes the structural
5197 /// floor by refusing every non-year-shaped value at validate
5198 /// time.
5199 pub fn validate_edicao(&self) -> Result<(), ManifestError> {
5200 let Some(s) = self.edicao() else {
5201 return Ok(());
5202 };
5203 if s.is_empty() {
5204 return Err(ManifestError::EdicaoEmpty);
5205 }
5206 if s.len() != 4 || !s.bytes().all(|b| b.is_ascii_digit()) {
5207 return Err(ManifestError::EdicaoInvalid {
5208 edicao: s.to_string(),
5209 reason: "must be a 4-digit ASCII decimal year (canonical \"2026\")".to_string(),
5210 });
5211 }
5212 Ok(())
5213 }
5214
5215 /// Compose the supervisor-related flat slots into a single
5216 /// [`SupervisorSpec`] for validation. Returns `None` when the
5217 /// caixa isn't a `:kind Supervisor`.
5218 ///
5219 /// The flat representation in [`Caixa`] keeps tatara-lisp authoring
5220 /// simple (one form, no nested `:supervisor (…)` block); this view
5221 /// is the "typed shape" the operator + supervisor reconciler
5222 /// consume.
5223 #[must_use]
5224 pub fn supervisor_view(&self) -> Option<SupervisorSpec> {
5225 if !self.kind().is_supervisor() {
5226 return None;
5227 }
5228 // Fold through the shared `supervisor::duration_codec::parse`
5229 // — the same parser the serde-routed `with = "duration_codec"`
5230 // on `SupervisorSpec::restart_window`, the `:politicas
5231 // :timeout` codec, and the `:politicas :circuit-breaker
5232 // :window` codec all consume. The prior inline f64-shaped
5233 // duplicate (`parse_window_inline`) admitted every magnitude
5234 // the integer-magnitude gate (1c55a2a) rejects on the three
5235 // serde-routed siblings — `"1.5s"`, `"1.0s"`, `"0.5m"`,
5236 // `"+30s"`, `"-30s"` — and silently dropped malformed input as
5237 // `None` (i.e. "no reset"), divergent from the shared codec's
5238 // integer-magnitude discipline by construction. The fold
5239 // closes the divergence: every value the typed
5240 // `SupervisorSpec` carries past `supervisor_view` is in the
5241 // shared codec's accepted set. The `.ok()` here preserves the
5242 // existing soft-swallow shape on this view-construction path;
5243 // the new [`Caixa::validate_restart_window`] (sibling of
5244 // [`Self::validate_nome`] / [`Self::validate_versao`]) names
5245 // the offending raw string at build time so authoring tools
5246 // (`feira lint`, the future layout-side wire-up) surface a
5247 // self-locating diagnostic instead of a silently dropped
5248 // window.
5249 let restart_window = self
5250 .restart_window()
5251 .and_then(|s| crate::supervisor::duration_codec::parse(s).ok());
5252 Some(SupervisorSpec {
5253 estrategia: self.estrategia().unwrap_or_default(),
5254 max_restarts: self.max_restarts().unwrap_or(5),
5255 restart_window,
5256 children: self.children().to_vec(),
5257 })
5258 }
5259
5260 /// A minimal starter manifest emitted by `feira init`.
5261 #[must_use]
5262 pub fn template(nome: &str) -> String {
5263 format!(
5264 "(defcaixa\n \
5265 :nome {nome:?}\n \
5266 :versao \"0.1.0\"\n \
5267 :kind Biblioteca\n \
5268 :edicao \"2026\"\n \
5269 :descricao \"FIXME — describe this caixa\"\n \
5270 :autores ()\n \
5271 :etiquetas ()\n \
5272 :deps ()\n \
5273 :deps-dev ()\n \
5274 :bibliotecas (\"lib/{nome}.lisp\"))\n"
5275 )
5276 }
5277
5278 /// Serialize to a canonical `caixa.lisp` source — suitable for writing
5279 /// back after mutation (e.g. `feira add`).
5280 ///
5281 /// Goes through serde JSON → canonical Sexp → per-field pretty print.
5282 /// The derive-macro `compile_from_sexp` path is the inverse, so any
5283 /// `Caixa` round-trips through `to_lisp` + `from_lisp`.
5284 #[must_use]
5285 pub fn to_lisp(&self) -> String {
5286 let json = serde_json::to_value(self).expect("Caixa serialize");
5287 let sexp = tatara_lisp::domain::json_to_sexp(&json);
5288 let tatara_lisp::Sexp::List(items) = sexp else {
5289 return format!("(defcaixa {sexp})\n");
5290 };
5291 let mut out = String::from("(defcaixa");
5292 let mut i = 0;
5293 while i + 1 < items.len() {
5294 out.push_str("\n ");
5295 out.push_str(&items[i].to_string());
5296 out.push(' ');
5297 out.push_str(&items[i + 1].to_string());
5298 i += 2;
5299 }
5300 out.push_str(")\n");
5301 out
5302 }
5303}
5304
5305/// Errors raised by top-level [`Caixa`] validators that don't fit
5306/// the per-axis [`DepError`] / [`crate::AplicacaoError`] /
5307/// [`crate::SupervisorError`] / [`crate::LayoutError`] families —
5308/// the Caixa's own identity axes (`:nome`, `:versao`) that flow
5309/// through every substrate-side artifact's `metadata.name` /
5310/// version derivation.
5311///
5312/// A future top-level sum (the M4 `CaixaError` the [`DepError`]
5313/// doc-comment anticipates) can hold one of each per-axis error
5314/// family without reshaping individual diagnostics; this enum is
5315/// the first such per-Caixa-identity family.
5316#[derive(Debug, Error, PartialEq, Eq)]
5317pub enum ManifestError {
5318 #[error(
5319 ":nome is empty (every caixa must name itself; the value flows \
5320 into every K8s artifact's `metadata.name` derivation and into \
5321 the default `lib/<nome>.lisp` / `exe/<nome>` layout paths)"
5322 )]
5323 NomeEmpty,
5324 #[error(
5325 ":nome {nome:?} is not a valid DNS-1123 label: {reason} (the K8s \
5326 apiserver enforces this rule on every `metadata.name` the \
5327 caixa's substrate-side renderers derive from `:nome` — the \
5328 `lareira-<nome>` Helm chart name, the programs.yaml entry \
5329 name, the `LABEL_APLICACAO` label value, the `<aplicacao>-<de>-to-<para>` \
5330 CiliumNetworkPolicy name, the `<aplicacao>-<para>` HTTPRoute \
5331 name; use a lowercase alphanumeric + hyphen identifier like \
5332 `\"checkout\"` or `\"cart-v2\"`)"
5333 )]
5334 NomeInvalid { nome: String, reason: String },
5335 #[error(
5336 ":nome {nome:?} overflows the joint-length budget on the canonical \
5337 `lareira-<nome>` chart-name shape: {reason} (every per-Servico / \
5338 per-Aplicacao renderer the substrate carries — `caixa-helm`'s \
5339 `Chart.yaml::name`, `caixa-flux`'s `cluster_bundle` HelmRelease \
5340 `chart:` slot, `caixa-tatara`'s `release_name` + \
5341 `oci://<registry>/lareira-<nome>` chart ref — derives the same \
5342 joint name through the canonical `lareira_chart_name` helper, and \
5343 Helm's `Chart.yaml::name` admission rule + the K8s apiserver's \
5344 DNS-1123 label cap on every chart-name-derived `metadata.name` \
5345 reject any joint name exceeding 63 bytes; the narrower \
5346 `:nome` shape (`NomeInvalid`) gates the bare-`:nome` budget, this \
5347 arm gates the chart-name budget downstream renderers inherit)"
5348 )]
5349 NomeChartNameBudgetExceeded { nome: String, reason: String },
5350 #[error(
5351 ":versao is empty (every caixa must pin its own version; the value flows \
5352 into the `lareira-<nome>` Helm chart's `Chart.yaml` version + appVersion, \
5353 the `feira publish` `v<versao>` git tag, the OCI image's `:v<versao>` / \
5354 `:latest` tags, the lacre closure's `concrete_versao`, and the \
5355 `:upgrade-from :from` peers — use a SemVer-2 literal like `\"0.1.0\"`)"
5356 )]
5357 VersaoEmpty,
5358 #[error(
5359 ":versao {versao:?} is not a valid SemVer-2 version: {reason} (the substrate \
5360 consumes this string as `semver::Version` — three-part `MAJOR.MINOR.PATCH` \
5361 with optional `-prerelease` and `+build` — across every artifact derived \
5362 from `:versao`: the `lareira-<nome>` Helm chart's `Chart.yaml` version + \
5363 appVersion (Helm SemVer-2-strict), the `feira publish` `v<versao>` git tag, \
5364 the OCI image's `:v<versao>` tag, the lacre closure's `concrete_versao`, \
5365 and the `:upgrade-from :from` peers that match against this exact shape; \
5366 use a literal like `\"0.1.0\"`, `\"0.2.0-rc.1\"`, or `\"1.0.0+build.42\"` — \
5367 not a git-tag-shape like `\"v0.1.0\"`, a docker-tag-shape like `\"latest\"`, \
5368 a requirement-shape like `\"^0.1\"`, or a four-part `\"0.1.0.0\"`)"
5369 )]
5370 VersaoInvalid { versao: String, reason: String },
5371 #[error(
5372 ":restart-window {restart_window:?} is not a valid duration: {reason} (the \
5373 substrate consumes this string through the shared \
5374 `supervisor::duration_codec` — the same parser routed via `with = \
5375 \"duration_codec\"` onto the typed `SupervisorSpec::restart_window`, \
5376 `:politicas :timeout`, and `:politicas :circuit-breaker :window` slots; \
5377 the canonical authoring form is `<integer><unit>` where the unit is one \
5378 of `ms` / `s` / `m` / `h` and the magnitude has no decimal point and no \
5379 leading `+` / `-` sign — e.g. `\"60s\"`, `\"5m\"`, `\"1h\"`, `\"500ms\"`. \
5380 Without this gate a malformed `:restart-window` silently produced a \
5381 supervisor with `restart_window: None` (\"never reset\"), turning OTP's \
5382 `MaxIntensity / Period` invariant into a never-reset supervisor far from \
5383 the source `caixa.lisp`; the gate moves the diagnostic to the manifest \
5384 layer with the offending value named verbatim. Omit the slot entirely to \
5385 express \"no reset\"; carry a positive integer duration to express the \
5386 sliding window)"
5387 )]
5388 RestartWindowMalformed {
5389 restart_window: String,
5390 reason: String,
5391 },
5392 #[error(
5393 "{slot} entry is an empty path string — every {slot} entry must name \
5394 a file relative to the caixa root; omit the entry to omit the file \
5395 (the layout checker's `root.join(\"\")` resolves to the caixa root \
5396 itself, so an empty entry silently aliases the project root as a \
5397 declared {slot} file, then fails downstream at parse / existence \
5398 time with a diagnostic that names the root rather than the offending \
5399 entry)"
5400 )]
5401 CodePathEmpty { slot: &'static str },
5402 #[error(
5403 "{slot} entry {} is an absolute path — entries must be relative to \
5404 the caixa root, since `Path::join` replaces the base with an absolute \
5405 right-hand side and `root.join(\"/abs/...\")` resolves to \"/abs/...\" \
5406 outside the caixa root sandbox; rewrite the entry as a relative path \
5407 under the caixa root (e.g. `\"lib/<name>.lisp\"`, `\"exe/<name>\"`, \
5408 `\"servicos/<name>.computeunit.yaml\"`)",
5409 path.display()
5410 )]
5411 CodePathAbsolute { slot: &'static str, path: PathBuf },
5412 #[error(
5413 "{slot} entry {} contains a `..` component — entries must not traverse \
5414 above the caixa root (the layout's `starts_with(<dir>)` fence on \
5415 `:exe` / `:servicos` is component-aware, not canonical-path-aware, \
5416 so a mid-path `..` silently traverses the sandbox; `:bibliotecas` \
5417 has no such fence, so a leading `..` escapes unconditionally if the \
5418 resolved target happens to exist)",
5419 path.display()
5420 )]
5421 CodePathParentEscape { slot: &'static str, path: PathBuf },
5422 #[error(
5423 "{slot} entry {} does not terminate in the `.lisp` extension — every \
5424 `:bibliotecas` entry is a tatara-lisp source file the `feira build` \
5425 loop reads through `tatara_lisp::read` at parse time, so any other \
5426 extension (`.rs`, `.txt`, `.lisp.bak`) or no-extension shape is \
5427 structurally a parser error far from the source caixa.lisp, with \
5428 no field naming the offending `:bibliotecas` entry. Pin a relative \
5429 path under the caixa root whose terminating extension is \
5430 lowercase-`.lisp` (e.g. `\"lib/<name>.lisp\"`, \
5431 `\"lib/handlers.lisp\"`) — the same file-type contract the peer \
5432 `:behavior :on-*` (c97815a) and `:upgrade-from :state-change :script` \
5433 (33cc830) axes already carry through the same lifted \
5434 `is_lisp_extension` predicate",
5435 path.display()
5436 )]
5437 CodePathNonLispExtension { slot: &'static str, path: PathBuf },
5438 #[error(
5439 "{slot} entry {} does not terminate in the `.computeunit.yaml` \
5440 compound suffix — every `:servicos` entry is a typed `ComputeUnit` \
5441 CR YAML file the peer caixa-helm / caixa-flux renderers consume \
5442 through `serde_yaml::from_str` at chart / FluxCD bundle render \
5443 time, so any other extension (`.yaml`, `.yml`, `.json`, the \
5444 off-by-one-segment `.computeunit-yaml`, the editor-backup \
5445 `.computeunit.yaml.bak`) or no-extension shape is structurally a \
5446 YAML-parser error / `ComputeUnit` schema-mismatch far from the \
5447 source caixa.lisp, with no field naming the offending `:servicos` \
5448 entry. Pin a relative path under the caixa root whose terminating \
5449 compound suffix is lowercase-`.computeunit.yaml` (e.g. \
5450 `\"servicos/<name>.computeunit.yaml\"`, \
5451 `\"servicos/hello-rio.computeunit.yaml\"`) — the same file-type \
5452 contract the sibling `:bibliotecas` axis (64772a9) already carries \
5453 on the tatara-lisp-source axis through the peer lifted \
5454 `is_lisp_extension` predicate, here on the compound-suffix axis \
5455 `Path::extension` can't express on its own through the lifted \
5456 `is_computeunit_yaml_extension` predicate",
5457 path.display()
5458 )]
5459 CodePathNonComputeUnitYamlExtension { slot: &'static str, path: PathBuf },
5460 #[error(
5461 "{slot} entry {} appears more than once (the code-path list is \
5462 a set, not a multiset; every peer Vec-shaped author-supplied \
5463 list past validate is set-not-multiset — `:membros :caixa`, \
5464 `:placement :clusters`, `:entrada :paths`, `:contratos`, \
5465 `:children :caixa`, `:deps` / `:deps-dev` `:nome`, \
5466 `:upgrade-from :from`, `:etiquetas`, `:autores` — and the three \
5467 code-path lists are the last Vec-shaped author-supplied slots on \
5468 the typed Caixa surface still admitting a duplicate entry. \
5469 `:bibliotecas` duplicates re-parse the same file at \
5470 `feira build` time and silently mask the author's intent to \
5471 declare a *second* biblioteca; `:exe` duplicates collide on the \
5472 flake `packages.<name>` derivation key at the future \
5473 `caixa-flake` materializer; `:servicos` duplicates surface as the \
5474 narrower [`caixa-helm`] / [`caixa-flux`] `UnsupportedServicoCount` \
5475 rejection far from the source `caixa.lisp`. Drop the duplicate \
5476 or rename it to the actual second file intended)",
5477 path.display()
5478 )]
5479 CodePathDuplicate { slot: &'static str, path: PathBuf },
5480 #[error(
5481 ":etiquetas entry is empty (every tag must carry a non-empty \
5482 registry-search identifier; the empty entry has no operational \
5483 meaning — it indexes nothing in the future caixa-registry search \
5484 axis and clutters the rendered Helm `Chart.yaml` `keywords:` array \
5485 with a no-op tag; omit the entry to express \"no tag on this \
5486 position\")"
5487 )]
5488 EtiquetaEmpty,
5489 #[error(
5490 ":etiquetas entry {etiqueta:?} appears more than once (the \
5491 registry-search tag set is a set, not a multiset; duplicate \
5492 entries are silently dedup'd by caixa-helm's `BTreeSet` collect \
5493 at chart render — a \"second wins / one silently disappears\" \
5494 shape divergent from every peer typed-graph set gate \
5495 (`:membros :caixa`, `:placement :clusters`, `:entrada :paths`, \
5496 `:contratos`, `:deps :nome`, `:upgrade-from :from`); drop the \
5497 duplicate or rename it to the actual tag intended)"
5498 )]
5499 EtiquetaDuplicate { etiqueta: String },
5500 #[error(
5501 ":etiquetas entry {etiqueta:?} is not a valid chart-keyword shape: \
5502 {reason} (the substrate consumes this string through the shared \
5503 `crate::render::is_chart_keyword_shape` predicate — the same \
5504 Cargo crates.io `[package] keywords` grammar entry shape: 1..=20 \
5505 bytes, starts with an ASCII letter, ASCII alphanumeric / `_` / `-` \
5506 continuation. The canonical authoring shapes are short kebab-case \
5507 identifiers like `\"mesh\"`, `\"wasm\"`, `\"tatara-lisp\"`, \
5508 `\"hello-world\"`, `\"caixa-servico\"`, `\"infrastructure\"`. \
5509 Without this gate a malformed `:etiquetas` entry (paste-from-doc \
5510 leading / trailing whitespace `\" mesh\"` / `\"mesh \"`; \
5511 paste-from-multiline-doc newline `\"mesh\\nhttp\"`; \
5512 paste-from-Windows-CRLF-doc CR; CSV-list-separator confusion \
5513 `\"mesh,http,grpc\"` — the author meant to author three separate \
5514 list entries; path-separator confusion `\"caixa/servico\"`; \
5515 namespace-suffix `\"http.1\"`; leading-digit `\"1foo\"`; \
5516 kebab-leak `\"-foo\"`; snake-leak `\"_foo\"`; non-ASCII \
5517 `\"café\"` — every legitimate search tag is strict ASCII; \
5518 paste-from-binary-blob NUL / BEL / ESC / DEL byte) silently \
5519 passed `from_lisp` + `validate_etiquetas` + \
5520 `StandardLayout::verify` and landed in the rendered \
5521 `lareira-<nome>` Helm chart's `Chart.yaml keywords:` array as a \
5522 malformed search tag — Artifact Hub's keyword index + the future \
5523 caixa-registry's keyword index would either silently drop the \
5524 tag or fail to index it far from the source caixa.lisp; the gate \
5525 moves the diagnostic to the manifest layer with the offending \
5526 value named verbatim)"
5527 )]
5528 EtiquetaInvalid { etiqueta: String, reason: String },
5529 #[error(
5530 ":autores entry is empty (every maintainer must carry a non-empty \
5531 identifier; the empty entry has no operational meaning — it \
5532 identifies no one in the substrate's authorship index and renders \
5533 as `maintainers: [{{name: \"\", email: null}}]` in the Helm chart's \
5534 `Chart.yaml`, a no-op maintainer the substrate cannot route to; \
5535 omit the entry to express \"no maintainer on this position\")"
5536 )]
5537 AutorEmpty,
5538 #[error(
5539 ":autores entry {autor:?} appears more than once (the maintainer \
5540 set is a set, not a multiset; unlike `:etiquetas`, caixa-helm's \
5541 `maintainers:` rendering does *no* dedup — duplicate entries \
5542 stack verbatim in `Chart.yaml` as two identical \
5543 `Maintainer {{ name, email: None }}` records, divergent from every \
5544 peer typed-graph set gate (`:etiquetas`, `:membros :caixa`, \
5545 `:placement :clusters`, `:entrada :paths`, `:contratos`, \
5546 `:deps :nome`, `:upgrade-from :from`); drop the duplicate or \
5547 rename it to the actual author intended)"
5548 )]
5549 AutorDuplicate { autor: String },
5550 #[error(
5551 ":autores entry {autor:?} is not a valid chart-maintainer-name shape: \
5552 {reason} (the substrate consumes this string through the shared \
5553 `crate::render::is_chart_maintainer_name_shape` predicate — the same \
5554 single-line-UTF-8 floor every realistic chart maintainer name carries: \
5555 1..=128 bytes, no leading or trailing whitespace, no ASCII control \
5556 characters anywhere, Unicode bytes accepted. The canonical authoring \
5557 shapes are short single-line identifiers like `\"pleme-io\"`, \
5558 `\"Pleme Contributors\"`, `\"alice <alice@example.com>\"`, \
5559 `\"François Dupont\"`. Without this gate a malformed `:autores` entry \
5560 (paste-from-aligned-doc leading whitespace `\" pleme-io\"` / trailing \
5561 whitespace `\"pleme-io \"`; paste-from-multiline-doc newline \
5562 `\"alice\\nbob\"` — the author pasted a multi-line block of author \
5563 records into one entry instead of splitting into one entry per author; \
5564 paste-from-Windows-CRLF-doc carriage return `\"alice\\rbob\"`; \
5565 tab-from-aligned-doc `\"Pleme\\tContributors\"`; paste-from-binary-blob \
5566 NUL / BEL / ESC / DEL byte) silently passed `from_lisp` + \
5567 `validate_autores` + `StandardLayout::verify` and landed in the \
5568 rendered `lareira-<nome>` Helm chart's `Chart.yaml maintainers:` array \
5569 as a YAML-illegal multi-line scalar or a silently-trimmed whitespace \
5570 round-trip — every chart-aware UI (`helm list`, `helm search`, \
5571 Artifact Hub maintainer index) would render the maintainer name in a \
5572 single-line column far from the source caixa.lisp; the gate moves the \
5573 diagnostic to the manifest layer with the offending value named \
5574 verbatim)"
5575 )]
5576 AutorInvalid { autor: String, reason: String },
5577 #[error(
5578 ":repositorio is the empty string (every published caixa names its \
5579 git source via a non-empty `:repositorio` locator — the value \
5580 flows verbatim into the rendered `lareira-<nome>` Helm chart's \
5581 `Chart.yaml` `home:` field via `caixa-helm` and into the FluxCD \
5582 `GitRepository.spec.url` via `caixa-flux`'s \
5583 `ClusterBundleOpts::for_caixa`; both consumers' \
5584 `Option::unwrap_or_else` fallbacks only fire when the slot is \
5585 `None`, so an empty `Some(\"\")` silently lands as `home: \"\"` / \
5586 `url: \"\"` in the rendered artifacts and breaks at `helm \
5587 template` / FluxCD source-controller reconcile time far from the \
5588 source caixa.lisp; omit the slot entirely to defer to the \
5589 renderer's `https://github.com/pleme-io/<nome>` / \
5590 `caixa.nome`-derived fallback, or carry a canonical authoring \
5591 shape like `\"github:org/repo\"`, `\"https://host/path\"`, \
5592 `\"ssh://[user@]host/path\"`, `\"git@host:path\"`, or \
5593 `\"file:///path\"`)"
5594 )]
5595 RepositorioEmpty,
5596 #[error(
5597 ":repositorio {repositorio:?} is not a valid git repo URL: {reason} \
5598 (the substrate consumes this string through the shared \
5599 `crate::render::is_git_repo_url` predicate — the same parser the \
5600 peer `:deps :fonte (:tipo git :repo …)` axis routes its `:repo` \
5601 value through via `DepSource::validate`; the canonical authoring \
5602 shapes are `\"github:org/repo\"` shorthand, `\"https://host/path\"` \
5603 / `\"ssh://[user@]host/path\"` / `\"git://host/path\"` / \
5604 `\"file:///path\"` URL schemes, or the `\"git@host:path\"` \
5605 scp-style SSH form. Without this gate a malformed `:repositorio` \
5606 (whitespace from a paste-from-doc; control characters / CRLF \
5607 from a paste-from-multiline-doc; a leading `-` from a \
5608 CLI-argument-injection footgun; a missing `:` separator from a \
5609 bare `org/repo` shape git treats as a relative filesystem path) \
5610 silently landed in the rendered `Chart.yaml home:` and the \
5611 FluxCD `GitRepository.spec.url` and broke at `git clone` / \
5612 FluxCD reconcile time far from the source caixa.lisp; the gate \
5613 moves the diagnostic to the manifest layer with the offending \
5614 value named verbatim)"
5615 )]
5616 RepositorioInvalid { repositorio: String, reason: String },
5617 #[error(
5618 ":descricao is the empty string (every published caixa names \
5619 its purpose via a non-empty `:descricao` summary — the value \
5620 flows verbatim into the rendered `lareira-<nome>` Helm \
5621 chart's `Chart.yaml` `description:` field via `caixa-helm`'s \
5622 `build_chart_yaml` and into the chart `README.md` header via \
5623 `build_readme`; both consumers' `Option::unwrap_or_else` \
5624 `caixa.nome`-derived fallbacks only fire when the slot is \
5625 `None`, so an empty `Some(\"\")` silently lands as \
5626 `description: \"\"` / a blank `README.md` header in the \
5627 rendered artifacts and breaks at `helm lint` time \
5628 (`WARNING [chart.metadata.description]: description is \
5629 required` on `apiVersion: v2` charts) far from the source \
5630 caixa.lisp; omit the slot entirely to defer to the \
5631 renderer's `\"Generated chart for caixa Servico <nome>\"` / \
5632 `\"caixa Servico <nome>\"` fallbacks, or carry a non-empty \
5633 summary like `\"Canonical Rust→wasm32-wasip2 caixa \
5634 Servico.\"`)"
5635 )]
5636 DescricaoEmpty,
5637 #[error(
5638 ":descricao {descricao:?} is not a valid chart-description shape: \
5639 {reason} (the substrate consumes this string through the shared \
5640 `crate::render::is_chart_description_shape` predicate — the same \
5641 single-line-UTF-8 floor every realistic chart description carries: \
5642 1..=512 bytes, no leading or trailing whitespace, no ASCII control \
5643 characters anywhere, Unicode prose bytes accepted. The canonical \
5644 authoring shapes are short single-line summaries like `\"Canonical \
5645 Rust→wasm32-wasip2 caixa Servico.\"`, `\"Checkout flow.\"`, \
5646 `\"AWS provider caixa for tatara-lisp\"`. Without this gate a \
5647 malformed `:descricao` (paste-from-aligned-doc leading whitespace \
5648 `\" Checkout flow.\"` / trailing whitespace `\"Checkout flow. \"`; \
5649 paste-from-multiline-doc newline `\"Checkout\\nflow.\"`; \
5650 paste-from-Windows-CRLF-doc carriage return `\"Checkout\\rflow.\"`; \
5651 tab-from-aligned-doc `\"Checkout\\tflow.\"`; paste-from-binary-blob \
5652 NUL / BEL / ESC / DEL byte) silently passed `from_lisp` + \
5653 `validate_descricao` + `StandardLayout::verify` and landed in the \
5654 rendered `lareira-<nome>` Helm chart's `Chart.yaml description:` \
5655 field + `README.md` header paragraph as a YAML-illegal multi-line \
5656 scalar or a silently-trimmed whitespace round-trip — every \
5657 chart-aware UI (`helm list`, `helm search`, Artifact Hub) would \
5658 render the description in a single-line column far from the source \
5659 caixa.lisp; the gate moves the diagnostic to the manifest layer \
5660 with the offending value named verbatim)"
5661 )]
5662 DescricaoInvalid { descricao: String, reason: String },
5663 #[error(
5664 ":licenca is the empty string (every published caixa names \
5665 its license via a non-empty `:licenca` SPDX expression — the \
5666 value flows verbatim into the rendered `lareira-<nome>` Helm \
5667 chart's `README.md` `## License` section via `caixa-helm`'s \
5668 `build_readme` at `caixa-helm/src/lib.rs:361`; the consumer's \
5669 `Option::unwrap_or_else(|| \"MIT\".into())` `MIT` fallback \
5670 only fires when the slot is `None`, so an empty `Some(\"\")` \
5671 silently lands as a bare trailing period in the rendered \
5672 chart `README.md` `License` section far from the source \
5673 caixa.lisp; omit the slot entirely to defer to the \
5674 renderer's `MIT` fallback, or carry a canonical SPDX \
5675 expression like `\"MIT\"`, `\"Apache-2.0\"`, \
5676 `\"Apache-2.0 OR MIT\"`)"
5677 )]
5678 LicencaEmpty,
5679 #[error(
5680 ":licenca {licenca:?} is not a valid SPDX expression shape: {reason} \
5681 (the substrate consumes this string through the shared \
5682 `crate::render::is_spdx_expression_shape` predicate — the same \
5683 alphabet-floor parser every peer per-axis value-shape gate routes \
5684 its value through; the canonical authoring shapes are single \
5685 license identifiers like `\"MIT\"`, `\"Apache-2.0\"`, `\"BSD-3-Clause\"`, \
5686 compound expressions like `\"Apache-2.0 OR MIT\"`, \
5687 `\"MIT AND BSD-3-Clause\"`, `\"(MIT OR Apache-2.0) AND ISC\"`, \
5688 license-with-exception forms like `\"Apache-2.0 WITH LLVM-exception\"`, \
5689 `+`-suffix variants like `\"GPL-2.0+\"`, and user-defined references \
5690 like `\"LicenseRef-MyLicense\"` / \
5691 `\"DocumentRef-doc:LicenseRef-MyLicense\"`. Without this gate a \
5692 malformed `:licenca` (paste-from-doc whitespace `\"MIT \"` / \
5693 `\" MIT\"`; paste-from-multiline-doc CRLF `\"MIT\\n\"`; \
5694 tab-from-aligned-doc `\"MIT\\tOR Apache-2.0\"`; non-ASCII byte from \
5695 a smart-quote paste; underscore-instead-of-hyphen typo \
5696 `\"Apache_2.0\"`; comma-instead-of-`OR`-keyword colloquial idiom \
5697 `\"MIT, Apache-2.0\"`; slash-dual-license colloquial idiom \
5698 `\"MIT/Apache-2.0\"`; semicolon-list-separator confusion \
5699 `\"MIT; Apache-2.0\"`) silently landed in the rendered chart \
5700 `README.md` `## License` section + a future SPDX-aware \
5701 `Chart.yaml license:` emitter would refuse the value at \
5702 `helm lint` time far from the source caixa.lisp; the gate moves \
5703 the diagnostic to the manifest layer with the offending value \
5704 named verbatim)"
5705 )]
5706 LicencaInvalid { licenca: String, reason: String },
5707 #[error(
5708 ":edicao is the empty string (every published caixa names \
5709 its language edition via a non-empty `:edicao` value — the \
5710 edition determines the tatara-lisp macro surface + \
5711 compatibility flags the substrate applies when building \
5712 the caixa; the canonical `Caixa::template` scaffold every \
5713 `feira init` emits carries `:edicao \"2026\"` verbatim and \
5714 every renderer-side fixture (`caixa-helm`, `caixa-flux`, \
5715 `caixa-mesh`) carries `edicao: Some(\"2026\".into())` by \
5716 construction, so an empty `Some(\"\")` silently lands as a \
5717 bare `(:edicao \"\")` line in the rendered `caixa.lisp` and \
5718 a future renderer-side consumer that folds it through \
5719 `Option::unwrap_or_else` will skip the fallback and pass the \
5720 empty edition through to the substrate's build-time edition \
5721 selector far from the source caixa.lisp; omit the slot \
5722 entirely to defer to the substrate's default edition, or \
5723 carry a canonical edition like `\"2026\"`)"
5724 )]
5725 EdicaoEmpty,
5726 #[error(
5727 ":edicao {edicao:?} is not a valid edition: {reason} (every \
5728 documented tatara-lisp edition is a 4-digit ASCII decimal \
5729 year — `\"2026\"` is the only edition currently minted; \
5730 future-introduced siblings will follow the same shape, peer \
5731 with Cargo's `[package] edition` grammar which every value \
5732 Cargo has ever accepted matches: `\"2015\"`, `\"2018\"`, \
5733 `\"2021\"`, `\"2024\"`. Without this gate the canonical \
5734 paste-from-doc footguns silently passed: a trailing space \
5735 (`\"2026 \"`) from a paste-from-doc, a CRLF (`\"2026\\n\"`) \
5736 from a paste-from-multiline-doc, a fullwidth-keyboard \
5737 look-alike (`\"2026\"`), a free-form non-year value \
5738 (`\"x\"`, `\"latest\"`, `\"nightly\"`), a leading non-digit \
5739 version-tag prefix (`\"v2026\"`, `\"e2026\"`), a \
5740 decimal-shaped pseudo-version (`\"2026.1\"`), or a \
5741 wrong-length numeric value (`\"26\"`, `\"202\"`, \
5742 `\"20260\"`) all landed as `(:edicao \"<garbage>\")` in the \
5743 rendered caixa.lisp and broke at the substrate's \
5744 build-time edition selector far from the source caixa.lisp; \
5745 omit the slot entirely to defer to the substrate's default \
5746 edition, or carry a canonical 4-digit ASCII decimal year \
5747 like `\"2026\"`)"
5748 )]
5749 EdicaoInvalid { edicao: String, reason: String },
5750}
5751
5752#[cfg(test)]
5753mod tests {
5754 use super::*;
5755
5756 #[test]
5757 fn template_round_trips() {
5758 let src = Caixa::template("demo");
5759 let c = Caixa::from_lisp(&src).expect("template must parse");
5760 assert_eq!(c.nome, "demo");
5761 assert_eq!(c.versao, "0.1.0");
5762 assert_eq!(c.kind, CaixaKind::Biblioteca);
5763 assert_eq!(c.bibliotecas, vec!["lib/demo.lisp".to_string()]);
5764 assert!(c.deps.is_empty());
5765 assert!(c.deps_dev.is_empty());
5766 }
5767
5768 #[test]
5769 fn register_populates_registry() {
5770 Caixa::register().expect("first register call in this test process must succeed");
5771 let kws = tatara_lisp::domain::registered_keywords();
5772 assert!(kws.contains(&"defcaixa"));
5773 }
5774
5775 #[test]
5776 fn to_lisp_round_trips() {
5777 let src = Caixa::template("demo");
5778 let c1 = Caixa::from_lisp(&src).unwrap();
5779 let emitted = c1.to_lisp();
5780 let c2 = Caixa::from_lisp(&emitted).expect("emitted lisp parses back");
5781 assert_eq!(c1, c2);
5782 }
5783
5784 // ── DialetoEstrangeiro carries a single typed axis ────────────────────
5785 //
5786 // The compounding pin: the variant stores only the typed
5787 // [`crate::dialeto::CaixaDialeto`], and every user-facing byte-string
5788 // (canonical keyword, description, consumer) routes through the enum's
5789 // own accessors at Display time. Prior to that closure the variant
5790 // carried each accessor's return value as a stored `&'static str`
5791 // snapshot alongside `dialeto`; a caller could construct the variant
5792 // with a snapshot that drifted from what `dialeto`'s accessors would
5793 // return, and every downstream user-facing projection would silently
5794 // disagree with the classification. Storing only the axis makes the
5795 // drift structurally impossible.
5796
5797 #[test]
5798 fn dialeto_estrangeiro_variant_carries_only_the_typed_dialeto_axis() {
5799 // Single-field construction is the whole compounding shape — a
5800 // future re-introduction of a snapshot field (a `palavra_canonica:
5801 // &'static str`, a stored `descricao:`, a stored `consumidor:`)
5802 // would re-open the drift surface and this construction would fail
5803 // to compile with "missing field" until every snapshot was seeded
5804 // at the call site again. The compile-time guarantee is the
5805 // invariant; the assertion below only witnesses that the
5806 // construction is well-formed after the closure.
5807 let err = LeituraError::DialetoEstrangeiro {
5808 dialeto: crate::dialeto::CaixaDialeto::Molde,
5809 };
5810 assert!(matches!(
5811 err,
5812 LeituraError::DialetoEstrangeiro {
5813 dialeto: crate::dialeto::CaixaDialeto::Molde,
5814 }
5815 ));
5816 }
5817
5818 #[test]
5819 fn dialeto_estrangeiro_display_routes_through_typed_dialeto_accessors() {
5820 // For every foreign-dialect classification the variant surfaces —
5821 // [`crate::dialeto::CaixaDialeto::Molde`] and
5822 // [`crate::dialeto::CaixaDialeto::MoldePosicional`], the two
5823 // variants [`Caixa::from_lisp`] raises this error for — the
5824 // rendered [`std::fmt::Display`] byte-string must interpolate each
5825 // typed accessor's return verbatim. A future re-introduction of a
5826 // stored `&'static str` snapshot alongside `dialeto` that Display
5827 // read instead of the accessor would fail this pin as soon as the
5828 // two disagreed; a future accessor rebrand (a per-dialect
5829 // consumer rename, a canonical-keyword shift once the substrate
5830 // migration named in [`crate::dialeto`] completes) reaches every
5831 // consumer through one typed dispatch and this pin verifies the
5832 // display path is one of them.
5833 for d in [
5834 crate::dialeto::CaixaDialeto::Molde,
5835 crate::dialeto::CaixaDialeto::MoldePosicional,
5836 ] {
5837 let rendered = LeituraError::DialetoEstrangeiro { dialeto: d }.to_string();
5838 assert!(
5839 rendered.contains(d.palavra_canonica()),
5840 "Display must interpolate `dialeto.palavra_canonica()` \
5841 verbatim — a stored snapshot would silently drift from \
5842 the typed accessor. dialect: {d}, rendered: {rendered:?}"
5843 );
5844 assert!(
5845 rendered.contains(d.descricao()),
5846 "Display must interpolate `dialeto.descricao()` verbatim. \
5847 dialect: {d}, rendered: {rendered:?}"
5848 );
5849 assert!(
5850 rendered.contains(d.consumidor()),
5851 "Display must interpolate `dialeto.consumidor()` verbatim. \
5852 dialect: {d}, rendered: {rendered:?}"
5853 );
5854 }
5855 }
5856
5857 #[test]
5858 fn from_lisp_rejects_molde_dialect_via_typed_variant() {
5859 // The end-to-end pin the compounding closure defends: a
5860 // Molde-dialect source lands as [`LeituraError::DialetoEstrangeiro`]
5861 // carrying [`crate::dialeto::CaixaDialeto::Molde`], and the
5862 // rendered Display byte-string names the Molde accessors'
5863 // returns verbatim. Any future path that constructed the variant
5864 // with a mismatched snapshot (a stored `palavra_canonica:
5865 // "defcaixa"` on a `Molde` classification) would land Display
5866 // pointing at `defcaixa` while the typed axis said `Molde` — the
5867 // exact drift the closure removes.
5868 let src = r#"
5869 (defcaixa
5870 :name "x"
5871 :kind :Biblioteca
5872 :ecosystem :rust-single-crate
5873 :package {:name "x" :version "0.1.0"})
5874 "#;
5875 let err = Caixa::from_lisp(src).expect_err("Molde dialect must not parse as Pacote");
5876 match err {
5877 LeituraError::DialetoEstrangeiro { dialeto } => {
5878 assert_eq!(dialeto, crate::dialeto::CaixaDialeto::Molde);
5879 let rendered = LeituraError::DialetoEstrangeiro { dialeto }.to_string();
5880 assert!(rendered.contains(dialeto.palavra_canonica()));
5881 assert!(rendered.contains(dialeto.consumidor()));
5882 assert!(rendered.contains(dialeto.descricao()));
5883 }
5884 other => panic!("expected DialetoEstrangeiro, got {other:?}"),
5885 }
5886 }
5887
5888 #[test]
5889 fn from_lisp_rejects_molde_posicional_dialect_via_typed_variant() {
5890 // Coverage pin for the [`crate::dialeto::CaixaDialeto::MoldePosicional`]
5891 // arm of the [`Caixa::from_lisp`] foreign-dialect gate — the
5892 // positional-arity `defmolde` form written under a `(defcaixa …)`
5893 // head (`(defcaixa todoku-go :kind :Biblioteca :ecosystem :go
5894 // …)`). Pre-lift this arm rode the same `foreign =>` wildcard
5895 // the [`crate::dialeto::CaixaDialeto::Molde`] sibling arm rode,
5896 // so no test exercised the positional-arity path through
5897 // `Caixa::from_lisp` specifically; the sibling
5898 // [`from_lisp_rejects_molde_dialect_via_typed_variant`] only
5899 // covered [`crate::dialeto::CaixaDialeto::Molde`]. Post-lift the
5900 // two arms route through the lifted
5901 // [`crate::dialeto::CaixaDialeto::is_molde_family`] (e9d2315)
5902 // typed predicate — the same predicate the pre-lift `foreign =>`
5903 // wildcard resolved to today — and this pin makes the
5904 // positional-arity arm's byte-shape at the gate explicit rather
5905 // than implied by wildcard-absorption. A future regression that
5906 // silently reordered [`crate::dialeto::CaixaDialeto::is_molde_family`]'s
5907 // arm-set (dropped [`crate::dialeto::CaixaDialeto::MoldePosicional`]
5908 // from the two-arity closure) would fail this pin at caixa-core
5909 // test time rather than surfacing far from the change as a
5910 // `caixa.lisp` carrying a `(defcaixa todoku-go :ecosystem :go
5911 // …)` silently parsing past the derive.
5912 let src = r#"
5913 (defcaixa todoku-go
5914 :kind :Biblioteca
5915 :ecosystem :go
5916 :package {:name "todoku-go" :version "0.3.0"})
5917 "#;
5918 let err =
5919 Caixa::from_lisp(src).expect_err("MoldePosicional dialect must not parse as Pacote");
5920 match err {
5921 LeituraError::DialetoEstrangeiro { dialeto } => {
5922 assert_eq!(
5923 dialeto,
5924 crate::dialeto::CaixaDialeto::MoldePosicional,
5925 "DialetoEstrangeiro must carry the MoldePosicional \
5926 variant verbatim — the positional-arity `defmolde` \
5927 form under a `(defcaixa …)` head is the \
5928 `MoldePosicional` arm's canonical byte-shape"
5929 );
5930 let rendered = LeituraError::DialetoEstrangeiro { dialeto }.to_string();
5931 assert!(
5932 rendered.contains(dialeto.palavra_canonica()),
5933 "Display must interpolate `dialeto.palavra_canonica()` \
5934 verbatim on the MoldePosicional arm; rendered: \
5935 {rendered:?}"
5936 );
5937 assert!(
5938 rendered.contains(dialeto.consumidor()),
5939 "Display must interpolate `dialeto.consumidor()` \
5940 verbatim on the MoldePosicional arm; rendered: \
5941 {rendered:?}"
5942 );
5943 assert!(
5944 rendered.contains(dialeto.descricao()),
5945 "Display must interpolate `dialeto.descricao()` \
5946 verbatim on the MoldePosicional arm; rendered: \
5947 {rendered:?}"
5948 );
5949 }
5950 other => panic!("expected DialetoEstrangeiro, got {other:?}"),
5951 }
5952 }
5953
5954 #[test]
5955 fn from_lisp_dialect_gate_dispatches_through_caixa_dialeto_is_molde_family_predicate() {
5956 // Load-bearing byte-parity pin: for every arm in
5957 // [`crate::dialeto::CaixaDialeto::ALL`], the
5958 // [`Caixa::from_lisp`] foreign-dialect gate's DialetoEstrangeiro
5959 // partition must agree with the lifted
5960 // [`crate::dialeto::CaixaDialeto::is_molde_family`] (e9d2315)
5961 // typed predicate — i.e. from_lisp raises
5962 // [`LeituraError::DialetoEstrangeiro`] carrying `d` iff
5963 // `d.is_molde_family()` returns `true`, and does NOT raise
5964 // [`LeituraError::DialetoEstrangeiro`] on any arm where the
5965 // predicate returns `false` (the arm's source falls through to
5966 // the derive — parses cleanly on
5967 // [`crate::dialeto::CaixaDialeto::Pacote`], surfaces a
5968 // [`LeituraError::Leitura`] on
5969 // [`crate::dialeto::CaixaDialeto::Desconhecido`]).
5970 //
5971 // Pre-lift the gate hand-rolled a three-arm match
5972 // (`Pacote => {}`, `Desconhecido => {}`, `foreign => Err(…)`)
5973 // whose `foreign =>` wildcard expressed no compile-time link
5974 // back to the substrate primitive's arm-family; a future fifth
5975 // dialect the [`crate::dialeto`] module doc's "third dialect"
5976 // hazard actualises would fall silently onto the wildcard
5977 // regardless of whether it belonged to the `defmolde` family or
5978 // to a distinct `defcaixa`-family. Post-lift the partition
5979 // resolves through
5980 // [`crate::dialeto::CaixaDialeto::is_molde_family`]'s single
5981 // typed dispatch, and this pin refuses any future regression
5982 // that silently split the from_lisp partition from the typed
5983 // predicate — the two paths now migrate as one on any future
5984 // arm addition.
5985 //
5986 // Sibling in shape to the peer
5987 // [`crate::dialeto::tests::caixa_dialeto_is_molde_family_agrees_with_palavra_canonica_defmolde_projection`]
5988 // (e9d2315) that pins the same byte-parity between
5989 // [`crate::dialeto::CaixaDialeto::is_molde_family`] and the
5990 // sibling [`crate::dialeto::CaixaDialeto::palavra_canonica`]
5991 // `== "defmolde"` classifier — extends the discipline from the
5992 // two paths within the [`crate::dialeto`] primitive onto the
5993 // third external consumer of the `defmolde`-family partition
5994 // (the [`Caixa::from_lisp`] gate that raises
5995 // [`LeituraError::DialetoEstrangeiro`]).
5996 let fixtures: &[(crate::dialeto::CaixaDialeto, &str)] = &[
5997 (
5998 crate::dialeto::CaixaDialeto::Pacote,
5999 r#"
6000 (defcaixa
6001 :nome "checkout"
6002 :versao "0.1.0"
6003 :kind Biblioteca
6004 :edicao "2026"
6005 :descricao "canonical Pacote source"
6006 :autores ()
6007 :etiquetas ()
6008 :deps ()
6009 :deps-dev ()
6010 :bibliotecas ("lib/checkout.lisp"))
6011 "#,
6012 ),
6013 (
6014 crate::dialeto::CaixaDialeto::Molde,
6015 r#"
6016 (defcaixa
6017 :name "base64"
6018 :kind :Biblioteca
6019 :ecosystem :rust-single-crate
6020 :package {:name "base64" :version "0.22.1"}
6021 :workflows [:auto-release])
6022 "#,
6023 ),
6024 (
6025 crate::dialeto::CaixaDialeto::MoldePosicional,
6026 r#"
6027 (defcaixa todoku-go
6028 :kind :Biblioteca
6029 :ecosystem :go
6030 :package {:name "todoku-go" :version "0.3.0"})
6031 "#,
6032 ),
6033 (
6034 crate::dialeto::CaixaDialeto::Desconhecido,
6035 r#"(defcaixa :licenca "MIT")"#,
6036 ),
6037 ];
6038
6039 // Coverage: every arm in [`crate::dialeto::CaixaDialeto::ALL`]
6040 // must appear in the fixture table so the pin's arm-set stays
6041 // synchronised with the enum's arm-set. Fails at test time if a
6042 // future fifth arm added to [`crate::dialeto::CaixaDialeto`]
6043 // (with a corresponding `is_molde_family` return) forgot to
6044 // extend this fixture table with a canonical source for the new
6045 // arm — the pin cannot cover an arm it has no source for.
6046 for &expected in crate::dialeto::CaixaDialeto::ALL {
6047 assert!(
6048 fixtures.iter().any(|(d, _)| *d == expected),
6049 "fixture table must carry a canonical source for every \
6050 CaixaDialeto arm; missing: {expected:?}"
6051 );
6052 }
6053
6054 for &(expected_dialect, src) in fixtures {
6055 let classified = crate::dialeto::classify(src.trim()).unwrap_or_else(|err| {
6056 panic!(
6057 "fixture source for {expected_dialect:?} must classify \
6058 cleanly, got err: {err:?}"
6059 )
6060 });
6061 assert_eq!(
6062 classified, expected_dialect,
6063 "fixture source for {expected_dialect:?} must classify as \
6064 {expected_dialect:?} (drift here defeats the byte-parity \
6065 pin below — a source labelled for one arm but classifying \
6066 as another would silently satisfy or violate the pin for \
6067 the wrong reason)"
6068 );
6069
6070 let outcome = Caixa::from_lisp(src);
6071 match (expected_dialect.is_molde_family(), &outcome) {
6072 (true, Err(LeituraError::DialetoEstrangeiro { dialeto })) => {
6073 assert_eq!(
6074 *dialeto, expected_dialect,
6075 "DialetoEstrangeiro must carry the same typed arm \
6076 the classifier returned — a drift here would let \
6077 from_lisp raise the error while pointing at the \
6078 wrong dialect (e.g. rejecting a \
6079 MoldePosicional source as Molde). arm: \
6080 {expected_dialect:?}"
6081 );
6082 }
6083 (true, other) => panic!(
6084 "arm {expected_dialect:?} has is_molde_family() = true \
6085 so from_lisp must raise DialetoEstrangeiro carrying \
6086 {expected_dialect:?}; got: {other:?}"
6087 ),
6088 (false, Err(LeituraError::DialetoEstrangeiro { dialeto })) => panic!(
6089 "arm {expected_dialect:?} has is_molde_family() = false \
6090 so from_lisp must NOT raise DialetoEstrangeiro; got \
6091 one carrying: {dialeto:?}. This means the typed \
6092 predicate and the from_lisp partition disagree on \
6093 this arm — exactly the drift this pin refuses."
6094 ),
6095 (false, _) => {
6096 // A non-molde arm's source falls through to the
6097 // derive: Pacote sources parse to Ok(_); Desconhecido
6098 // sources surface as LeituraError::Leitura from the
6099 // derive's own unknown-keyword rejection. Either
6100 // shape is acceptable here — the pin's promise is
6101 // narrower: "no DialetoEstrangeiro on
6102 // is_molde_family() == false".
6103 }
6104 }
6105 }
6106 }
6107
6108 // ── M2 typed-substrate slot tests (limits, behavior, upgrade-from, supervisor) ──
6109
6110 #[test]
6111 fn limits_round_trip_via_json() {
6112 use crate::LimitsSpec;
6113 use std::time::Duration;
6114 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6115 c.limits = Some(LimitsSpec {
6116 memory: Some(64 * 1024 * 1024),
6117 fuel: Some(1_000_000),
6118 wall_clock: Some(Duration::from_secs(30)),
6119 cpu: Some(500),
6120 });
6121 let json = serde_json::to_string(&c).unwrap();
6122 assert!(json.contains("\"limits\""));
6123 assert!(json.contains("\"64MiB\""));
6124 assert!(json.contains("\"30s\""));
6125 assert!(json.contains("\"500m\""));
6126 let back: Caixa = serde_json::from_str(&json).unwrap();
6127 assert_eq!(c.limits, back.limits);
6128 }
6129
6130 #[test]
6131 fn behavior_round_trip_via_json() {
6132 use crate::BehaviorSpec;
6133 use std::path::PathBuf;
6134 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6135 c.behavior = Some(BehaviorSpec {
6136 on_init: Some(PathBuf::from("lib/init.lisp")),
6137 on_call: Some(PathBuf::from("lib/handlers.lisp")),
6138 ..Default::default()
6139 });
6140 let json = serde_json::to_string(&c).unwrap();
6141 let back: Caixa = serde_json::from_str(&json).unwrap();
6142 assert_eq!(c.behavior, back.behavior);
6143 }
6144
6145 #[test]
6146 fn upgrade_from_round_trip_via_json() {
6147 use crate::{UpgradeFromEntry, UpgradeInstruction};
6148 use std::path::PathBuf;
6149 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6150 c.upgrade_from = vec![UpgradeFromEntry {
6151 from: "0.1.0".into(),
6152 instructions: vec![
6153 UpgradeInstruction::LoadModule {
6154 module: "demo".into(),
6155 },
6156 UpgradeInstruction::StateChange {
6157 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6158 },
6159 UpgradeInstruction::SoftPurge {
6160 module: "demo-old".into(),
6161 },
6162 ],
6163 }];
6164 let json = serde_json::to_string(&c).unwrap();
6165 let back: Caixa = serde_json::from_str(&json).unwrap();
6166 assert_eq!(c.upgrade_from, back.upgrade_from);
6167 }
6168
6169 #[test]
6170 fn supervisor_view_returns_typed_shape() {
6171 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
6172 let mut c = Caixa::from_lisp(&Caixa::template("root")).unwrap();
6173 c.kind = CaixaKind::Supervisor;
6174 c.bibliotecas.clear();
6175 c.estrategia = Some(RestartStrategy::OneForOne);
6176 c.max_restarts = Some(5);
6177 c.restart_window = Some("60s".into());
6178 c.children = vec![ChildSpec {
6179 caixa: "worker".into(),
6180 versao: "^0.1".into(),
6181 restart: RestartPolicy::Permanent,
6182 }];
6183 let view = c.supervisor_view().expect("Supervisor kind has a view");
6184 assert_eq!(view.estrategia, RestartStrategy::OneForOne);
6185 assert_eq!(view.max_restarts, 5);
6186 assert_eq!(
6187 view.restart_window,
6188 Some(std::time::Duration::from_secs(60))
6189 );
6190 assert_eq!(view.children.len(), 1);
6191 view.validate().unwrap();
6192 }
6193
6194 #[test]
6195 fn supervisor_view_none_for_non_supervisor_kinds() {
6196 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6197 assert!(c.supervisor_view().is_none());
6198 }
6199
6200 #[test]
6201 fn declared_mesh_slots_empty_for_bare_caixa() {
6202 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6203 assert!(c.declared_mesh_slots().is_empty());
6204 }
6205
6206 #[test]
6207 fn declared_mesh_slots_reports_only_set_slots_in_canonical_order() {
6208 use crate::{Entrada, Membro};
6209 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6210 // Set a non-adjacent pair (:membros + :entrada) to pin that the
6211 // canonical declaration order is preserved regardless of which
6212 // subset is populated.
6213 c.membros = vec![Membro {
6214 caixa: "a".into(),
6215 versao: "^0.1".into(),
6216 }];
6217 c.entrada = Some(Entrada {
6218 host: "x.example.com".into(),
6219 para: "a".into(),
6220 paths: vec![],
6221 port: 8080,
6222 });
6223 assert_eq!(
6224 c.declared_mesh_slots(),
6225 vec![
6226 crate::render::M3_AUTHOR_KEY_MEMBROS,
6227 crate::render::M3_AUTHOR_KEY_ENTRADA,
6228 ]
6229 );
6230 }
6231
6232 #[test]
6233 fn m3_top_level_author_key_consts_pin_canonical_kebab_case_labels() {
6234 // Scalar-value pin: the five author-facing kebab-case labels the
6235 // `(defcaixa … :<slot> (…))` surface admits on the M3 top-level
6236 // mesh slot axis, one arm per typed slot. Mirrors the peer
6237 // scalar-value pin the sibling
6238 // [`crate::M2_AUTHOR_KEY_LIMITS`] /
6239 // [`crate::M2_AUTHOR_KEY_BEHAVIOR`] /
6240 // [`crate::M2_AUTHOR_KEY_UPGRADE_FROM`] M2 top-level slot consts
6241 // carry (f49c8b0), so both altitudes of the typed-slot algebra
6242 // (per-Servico M2 + per-Aplicacao M3) share the same
6243 // "one canonical byte-string per arm" discipline. A future
6244 // rebrand (`:membros` → `:members`, `:contratos` → `:contracts`,
6245 // `:politicas` → `:policies`, `:placement` → `:distribution`,
6246 // `:entrada` → `:ingress`) lands as an edit to exactly one const,
6247 // and every consumer that reaches for the label picks it up at
6248 // build time rather than at runtime as a downstream mismatch.
6249 assert_eq!(crate::render::M3_AUTHOR_KEY_MEMBROS, ":membros");
6250 assert_eq!(crate::render::M3_AUTHOR_KEY_CONTRATOS, ":contratos");
6251 assert_eq!(crate::render::M3_AUTHOR_KEY_POLITICAS, ":politicas");
6252 assert_eq!(crate::render::M3_AUTHOR_KEY_PLACEMENT, ":placement");
6253 assert_eq!(crate::render::M3_AUTHOR_KEY_ENTRADA, ":entrada");
6254 }
6255
6256 #[test]
6257 fn declared_mesh_slots_route_through_lifted_m3_author_key_consts() {
6258 // Production-through-const pin: the five per-arm labels the
6259 // [`Caixa::declared_mesh_slots`] tagger pushes onto its return
6260 // `Vec` route through the lifted
6261 // [`crate::M3_AUTHOR_KEY_MEMBROS`] /
6262 // [`crate::M3_AUTHOR_KEY_CONTRATOS`] /
6263 // [`crate::M3_AUTHOR_KEY_POLITICAS`] /
6264 // [`crate::M3_AUTHOR_KEY_PLACEMENT`] /
6265 // [`crate::M3_AUTHOR_KEY_ENTRADA`] consts, in canonical
6266 // declaration order. A future re-order or drift at the tagger
6267 // (a rename that reaches the tagger but not the const, or vice
6268 // versa) surfaces here at build time rather than at runtime as
6269 // a [`crate::LayoutError::MeshSlotsOnNonAplicacao`]
6270 // `slots: <stale-kebab-case>` diagnostic far from the rename's
6271 // commit. Mirror of the peer
6272 // [`declared_servico_slots_route_through_lifted_m2_author_key_consts`]
6273 // pin (f49c8b0) on the sibling per-Servico M2 top-level slot
6274 // axis.
6275 use crate::{Entrada, Membro, MeshPolicy, Placement, PlacementStrategy, WitContract};
6276 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6277 c.membros = vec![Membro {
6278 caixa: "a".into(),
6279 versao: "^0.1".into(),
6280 }];
6281 c.contratos = vec![WitContract {
6282 de: "a".into(),
6283 para: "a".into(),
6284 wit: "wasi:http/proxy".into(),
6285 endpoint: Some("/x".into()),
6286 subject: None,
6287 slot: None,
6288 }];
6289 c.politicas = Some(MeshPolicy::default());
6290 c.placement = Some(Placement {
6291 estrategia: PlacementStrategy::Replicated,
6292 clusters: vec!["rio".into()],
6293 affinity: None,
6294 shard_key: None,
6295 });
6296 c.entrada = Some(Entrada {
6297 host: "x.example.com".into(),
6298 para: "a".into(),
6299 paths: vec![],
6300 port: 8080,
6301 });
6302 assert_eq!(
6303 c.declared_mesh_slots(),
6304 vec![
6305 crate::render::M3_AUTHOR_KEY_MEMBROS,
6306 crate::render::M3_AUTHOR_KEY_CONTRATOS,
6307 crate::render::M3_AUTHOR_KEY_POLITICAS,
6308 crate::render::M3_AUTHOR_KEY_PLACEMENT,
6309 crate::render::M3_AUTHOR_KEY_ENTRADA,
6310 ]
6311 );
6312 }
6313
6314 #[test]
6315 fn declared_supervisor_slots_empty_for_bare_caixa() {
6316 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6317 assert!(c.declared_supervisor_slots().is_empty());
6318 }
6319
6320 #[test]
6321 fn declared_supervisor_slots_reports_only_set_slots_in_canonical_order() {
6322 use crate::RestartStrategy;
6323 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6324 // Set a non-adjacent pair (:estrategia + :restart-window) to pin
6325 // that the canonical declaration order is preserved regardless
6326 // of which subset is populated.
6327 c.estrategia = Some(RestartStrategy::OneForOne);
6328 c.restart_window = Some("60s".into());
6329 assert_eq!(
6330 c.declared_supervisor_slots(),
6331 vec![
6332 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6333 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6334 ]
6335 );
6336 }
6337
6338 #[test]
6339 fn supervisor_top_level_author_key_consts_pin_canonical_kebab_case_labels() {
6340 // Scalar-value pin: the four author-facing kebab-case labels the
6341 // `(defcaixa … :<slot> (…))` surface admits on the Supervisor
6342 // supervision-tree slot axis, one arm per typed slot. Mirrors the
6343 // peer scalar-value pins the sibling
6344 // [`crate::render::M2_AUTHOR_KEY_LIMITS`] /
6345 // [`crate::render::M2_AUTHOR_KEY_BEHAVIOR`] /
6346 // [`crate::render::M2_AUTHOR_KEY_UPGRADE_FROM`] top-level M2 slot
6347 // consts and [`crate::render::M3_AUTHOR_KEY_MEMBROS`] etc.
6348 // top-level M3 slot consts carry, so all three kind-scoped
6349 // typed-slot-family author-facing-label axes route through one
6350 // canonical per-arm declaration. A future rebrand
6351 // (`:estrategia` → `:strategy` for English uniformity,
6352 // `:max-restarts` → `:max-intensity` matching Erlang/OTP's
6353 // `MaxIntensity` name, `:restart-window` → `:period` matching
6354 // OTP's `Period` name, `:children` → `:workers` matching Elixir
6355 // idiom) lands as an edit to exactly one const, and every
6356 // consumer that reaches for the label picks it up at build time
6357 // rather than at runtime as a downstream mismatch.
6358 assert_eq!(
6359 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6360 ":estrategia"
6361 );
6362 assert_eq!(
6363 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6364 ":max-restarts"
6365 );
6366 assert_eq!(
6367 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6368 ":restart-window"
6369 );
6370 assert_eq!(crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN, ":children");
6371 }
6372
6373 #[test]
6374 fn declared_supervisor_slots_route_through_lifted_supervisor_author_key_consts() {
6375 // Production-through-const pin: the four per-arm labels the
6376 // [`Caixa::declared_supervisor_slots`] tagger pushes onto its
6377 // return `Vec` route through the lifted
6378 // [`crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA`] /
6379 // [`crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS`] /
6380 // [`crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW`] /
6381 // [`crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN`] consts, in
6382 // canonical declaration order. A future re-order or drift at the
6383 // tagger (a rename that reaches the tagger but not the const, or
6384 // vice versa) surfaces here at build time rather than at runtime
6385 // as a [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`]
6386 // `slots: <stale-kebab-case>` diagnostic far from the rename's
6387 // commit. Mirror of the peer
6388 // [`declared_servico_slots_route_through_lifted_m2_author_key_consts`]
6389 // (f49c8b0) and
6390 // [`declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
6391 // (882f498) pins on the sibling M2 / M3 top-level slot axes.
6392 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
6393 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6394 c.estrategia = Some(RestartStrategy::OneForOne);
6395 c.max_restarts = Some(5);
6396 c.restart_window = Some("60s".into());
6397 c.children = vec![ChildSpec {
6398 caixa: "worker".into(),
6399 versao: "^0.1".into(),
6400 restart: RestartPolicy::Permanent,
6401 }];
6402 assert_eq!(
6403 c.declared_supervisor_slots(),
6404 vec![
6405 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6406 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6407 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6408 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6409 ]
6410 );
6411 }
6412
6413 #[test]
6414 fn declared_servico_slots_empty_for_bare_caixa() {
6415 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6416 assert!(c.declared_servico_slots().is_empty());
6417 }
6418
6419 #[test]
6420 fn declared_servico_slots_reports_only_set_slots_in_canonical_order() {
6421 use crate::{UpgradeFromEntry, UpgradeInstruction};
6422 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6423 // Set a non-adjacent pair (:limits + :upgrade-from) to pin that
6424 // the canonical declaration order is preserved regardless of
6425 // which subset is populated.
6426 c.limits = Some(crate::LimitsSpec {
6427 fuel: Some(1_000_000),
6428 ..Default::default()
6429 });
6430 c.upgrade_from = vec![UpgradeFromEntry {
6431 from: "0.1.0".into(),
6432 instructions: vec![UpgradeInstruction::Restart],
6433 }];
6434 assert_eq!(
6435 c.declared_servico_slots(),
6436 vec![
6437 crate::render::M2_AUTHOR_KEY_LIMITS,
6438 crate::render::M2_AUTHOR_KEY_UPGRADE_FROM,
6439 ]
6440 );
6441 }
6442
6443 #[test]
6444 fn m2_top_level_author_key_consts_pin_canonical_kebab_case_labels() {
6445 // Scalar-value pin: the three author-facing kebab-case labels
6446 // the `(defcaixa … :<slot> (…))` surface admits on the M2
6447 // top-level slot axis, one arm per typed slot. Mirrors the peer
6448 // scalar-value pin the sibling renderer-side
6449 // [`crate::M2_KEY_LIMITS`] / [`crate::M2_KEY_BEHAVIOR`] /
6450 // [`crate::M2_KEY_UPGRADE_FROM`] camelCase overlay-container
6451 // consts carry, so both halves of the M2 top-level slot dual
6452 // axis (author-facing kebab-case label + renderer-side
6453 // camelCase overlay-container wire key) route through one
6454 // canonical per-arm declaration. A future rebrand
6455 // (`:limits` → `:sandbox` matching Lunatic per-process
6456 // terminology INSPIRATIONS §III.1, `:behavior` → `:gen-server`
6457 // matching Erlang's verbatim name, `:upgrade-from` → `:appup`
6458 // matching Erlang's verbatim appup name) lands as an edit to
6459 // exactly one const, and every consumer that reaches for the
6460 // label picks it up at build time rather than at runtime as a
6461 // downstream mismatch.
6462 assert_eq!(crate::render::M2_AUTHOR_KEY_LIMITS, ":limits");
6463 assert_eq!(crate::render::M2_AUTHOR_KEY_BEHAVIOR, ":behavior");
6464 assert_eq!(crate::render::M2_AUTHOR_KEY_UPGRADE_FROM, ":upgrade-from");
6465 }
6466
6467 #[test]
6468 fn declared_servico_slots_route_through_lifted_m2_author_key_consts() {
6469 // Production-through-const pin: the three per-arm labels the
6470 // [`Caixa::declared_servico_slots`] tagger pushes onto its
6471 // return `Vec` route through the lifted
6472 // [`crate::M2_AUTHOR_KEY_LIMITS`] /
6473 // [`crate::M2_AUTHOR_KEY_BEHAVIOR`] /
6474 // [`crate::M2_AUTHOR_KEY_UPGRADE_FROM`] consts, in canonical
6475 // declaration order. A future re-order or drift at the tagger
6476 // (a rename that reaches the tagger but not the const, or vice
6477 // versa) surfaces here at build time rather than at runtime as
6478 // a [`crate::LayoutError::ServicoSlotsOnNonServico`]
6479 // `slots: <stale-kebab-case>` diagnostic far from the rename's
6480 // commit. Mirror of the peer
6481 // [`crate::behavior::BehaviorSpec::declared_slots`] production
6482 // tagger pin (889dc18) on the sibling per-callback axis.
6483 use crate::{BehaviorSpec, UpgradeFromEntry, UpgradeInstruction};
6484 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6485 c.limits = Some(crate::LimitsSpec {
6486 fuel: Some(1_000_000),
6487 ..Default::default()
6488 });
6489 c.behavior = Some(BehaviorSpec {
6490 on_init: Some(PathBuf::from("lib/init.lisp")),
6491 ..Default::default()
6492 });
6493 c.upgrade_from = vec![UpgradeFromEntry {
6494 from: "0.1.0".into(),
6495 instructions: vec![UpgradeInstruction::Restart],
6496 }];
6497 assert_eq!(
6498 c.declared_servico_slots(),
6499 vec![
6500 crate::render::M2_AUTHOR_KEY_LIMITS,
6501 crate::render::M2_AUTHOR_KEY_BEHAVIOR,
6502 crate::render::M2_AUTHOR_KEY_UPGRADE_FROM,
6503 ]
6504 );
6505 }
6506
6507 #[test]
6508 fn existing_manifests_unaffected_by_new_optional_slots() {
6509 // Regression test: a caixa.lisp authored before M2 typed slots
6510 // should still parse + serialize cleanly. The bare `defcaixa`
6511 // emitted by `Caixa::template` has none of the new fields.
6512 let src = Caixa::template("legacy");
6513 let c = Caixa::from_lisp(&src).unwrap();
6514 assert!(c.limits.is_none());
6515 assert!(c.behavior.is_none());
6516 assert!(c.upgrade_from.is_empty());
6517 assert!(c.estrategia.is_none());
6518 assert!(c.children.is_empty());
6519
6520 // And to_lisp emits a manifest with the new slots in the
6521 // empty/default state — round-trippable.
6522 let emitted = c.to_lisp();
6523 let back = Caixa::from_lisp(&emitted).unwrap();
6524 assert_eq!(c, back);
6525 }
6526
6527 #[test]
6528 fn validate_deps_accepts_canonical_caixa() {
6529 // Positive control: the bare template — zero deps, zero
6530 // deps_dev — passes the gate trivially. A future axis added to
6531 // `Dep::validate` mustn't regress an empty-deps caixa to a
6532 // build error.
6533 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6534 c.validate_deps().unwrap();
6535 }
6536
6537 #[test]
6538 fn validate_deps_rejects_invalid_versao_in_deps() {
6539 // Fail-before-pass-after pin: a malformed `:deps :versao`
6540 // surfaces at validate_deps() time, not at lacre-resolve time.
6541 // Mirrors `rejects_invalid_membro_versao_requirement` and
6542 // `validate_rejects_invalid_child_versao_requirement` on the
6543 // other two `:versao` axes.
6544 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6545 c.deps = vec![Dep::simple("caixa-teia", "^bad-version")];
6546 let err = c.validate_deps().unwrap_err();
6547 assert!(
6548 matches!(
6549 err,
6550 crate::dep::DepError::VersaoInvalid { ref nome, ref versao, .. }
6551 if nome == "caixa-teia" && versao == "^bad-version"
6552 ),
6553 "got {err:?}"
6554 );
6555 }
6556
6557 #[test]
6558 fn validate_deps_rejects_invalid_versao_in_deps_dev() {
6559 // Parity pin: `:deps-dev` must run through the same per-entry
6560 // validator as `:deps` — a typo in either axis surfaces the
6561 // same diagnostic. Without this leg, `:deps-dev` would be a
6562 // second-class citizen of the typed surface and an author
6563 // could land a build that passes validate_deps but fails at
6564 // `feira lock`-time when the dev-dep is resolved for a test
6565 // build.
6566 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6567 c.deps_dev = vec![Dep::simple("tatara-check", "^^0.1")];
6568 let err = c.validate_deps().unwrap_err();
6569 assert!(
6570 matches!(
6571 err,
6572 crate::dep::DepError::VersaoInvalid { ref nome, ref versao, .. }
6573 if nome == "tatara-check" && versao == "^^0.1"
6574 ),
6575 "got {err:?}"
6576 );
6577 }
6578
6579 #[test]
6580 fn validate_deps_runs_deps_before_deps_dev() {
6581 // Order pin: when both lists carry typos, the `:deps`
6582 // diagnostic surfaces first. The author's mental model is
6583 // "runtime deps are load-bearing; dev deps are scaffolding";
6584 // surfacing the runtime axis first matches that hierarchy.
6585 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6586 c.deps = vec![Dep::simple("runtime-dep", "^bad-runtime")];
6587 c.deps_dev = vec![Dep::simple("dev-dep", "^bad-dev")];
6588 let err = c.validate_deps().unwrap_err();
6589 assert!(
6590 matches!(
6591 err,
6592 crate::dep::DepError::VersaoInvalid { ref nome, .. }
6593 if nome == "runtime-dep"
6594 ),
6595 "expected `:deps` typo to surface first, got {err:?}"
6596 );
6597 }
6598
6599 #[test]
6600 fn validate_deps_accepts_canonical_versao_forms_in_both_lists() {
6601 // Positive control sweep across both lists. Pin every
6602 // canonical Cargo-shaped form so a future tightening of the
6603 // accepted set surfaces here as a test failure (parity with
6604 // `accepts_canonical_membro_versao_forms` and
6605 // `validate_accepts_canonical_child_versao_forms`).
6606 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6607 c.deps = vec![
6608 Dep::simple("caret", "^0.1"),
6609 Dep::simple("tilde", "~0.1.2"),
6610 Dep::simple("exact", "0.1.0"),
6611 Dep::simple("wildcard", "*"),
6612 Dep::simple("multi-range", ">=0.1, <2"),
6613 ];
6614 c.deps_dev = vec![
6615 Dep::simple("dev-caret", "^0.1"),
6616 Dep::simple("dev-wildcard", "*"),
6617 ];
6618 c.validate_deps().unwrap();
6619 }
6620
6621 #[test]
6622 fn validate_deps_diagnostic_carries_offending_dep() {
6623 // Diagnostic-shape pin: the error names the offending entry's
6624 // `:nome` + `:versao` verbatim and carries a non-empty
6625 // `reason` from `semver::VersionReq::parse`, so a `feira lint`
6626 // run can render the diagnostic without re-parsing.
6627 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6628 c.deps = vec![Dep::simple("caixa-teia", "not-a-req")];
6629 let err = c.validate_deps().unwrap_err();
6630 let crate::dep::DepError::VersaoInvalid {
6631 nome,
6632 versao,
6633 reason,
6634 } = err
6635 else {
6636 panic!("expected VersaoInvalid, got other variant");
6637 };
6638 assert_eq!(nome, "caixa-teia");
6639 assert_eq!(versao, "not-a-req");
6640 assert!(
6641 !reason.is_empty(),
6642 "VersaoInvalid `reason` must carry the parser's wording verbatim"
6643 );
6644 }
6645
6646 #[test]
6647 fn validate_deps_rejects_ambiguous_fonte_in_deps_dev() {
6648 // Cross-axis pin: `validate_deps` walks both :deps and
6649 // :deps-dev through `Dep::validate`, and the new fonte gate
6650 // (`:tag` + `:branch` both set — the canonical "pin drift"
6651 // footgun) must surface from the :deps-dev arm with the
6652 // offending entry's :nome named. Pin the :deps-dev arm
6653 // explicitly so a future shortcut that only walks :deps
6654 // surfaces here as a regression.
6655 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6656 c.deps_dev = vec![Dep {
6657 nome: "dev-only".into(),
6658 versao: "^0.1".into(),
6659 fonte: Some(crate::DepSource::Git {
6660 repo: "github:p/x".into(),
6661 tag: Some("v1".into()),
6662 rev: None,
6663 branch: Some("main".into()),
6664 }),
6665 opcional: false,
6666 caracteristicas: vec![],
6667 }];
6668 let err = c.validate_deps().unwrap_err();
6669 let crate::dep::DepError::FontePinAmbiguous { nome, pins } = err else {
6670 panic!("expected FontePinAmbiguous from :deps-dev walk");
6671 };
6672 assert_eq!(nome, "dev-only");
6673 assert!(pins.contains(":tag") && pins.contains(":branch"));
6674 }
6675
6676 #[test]
6677 fn validate_deps_rejects_empty_repo_in_deps() {
6678 // Parity pin on the :deps arm: an empty :repo on the runtime
6679 // deps list surfaces the same FonteRepoEmpty diagnostic the
6680 // dep.rs per-entry tests pin, naming the offending entry.
6681 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6682 c.deps = vec![Dep {
6683 nome: "runtime".into(),
6684 versao: "^0.1".into(),
6685 fonte: Some(crate::DepSource::Git {
6686 repo: String::new(),
6687 tag: Some("v1".into()),
6688 rev: None,
6689 branch: None,
6690 }),
6691 opcional: false,
6692 caracteristicas: vec![],
6693 }];
6694 let err = c.validate_deps().unwrap_err();
6695 assert!(
6696 matches!(
6697 err,
6698 crate::dep::DepError::FonteRepoEmpty { ref nome }
6699 if nome == "runtime"
6700 ),
6701 "got {err:?}"
6702 );
6703 }
6704
6705 // ── validate_deps: within-list :nome set-not-multiset gate ─────────
6706
6707 #[test]
6708 fn validate_deps_rejects_duplicate_nome_in_deps() {
6709 // Fail-before-pass-after pin: two `:deps` entries naming the same
6710 // caixa carry two `:versao` / `:fonte` / feature triples that the
6711 // caixa-resolver's lacre pipeline collapses (the second silently
6712 // overwrites the first at `concrete_versao`-resolve time). The
6713 // gate surfaces the duplicate at validate-time, naming the
6714 // offending caixa + the list, before the resolver-side silent
6715 // drop. Mirrors the peer typed-graph duplicate gates
6716 // (`DuplicateChildCaixa`, `MembroDuplicate`, `DuplicateFrom`, …).
6717 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6718 c.deps = vec![
6719 Dep::simple("caixa-teia", "^0.1"),
6720 Dep::simple("caixa-teia", "^0.2"),
6721 ];
6722 let err = c.validate_deps().unwrap_err();
6723 assert!(
6724 matches!(
6725 err,
6726 crate::dep::DepError::DuplicateNome { ref nome, list }
6727 if nome == "caixa-teia" && list == crate::render::DEP_AUTHOR_KEY_DEPS
6728 ),
6729 "got {err:?}"
6730 );
6731 }
6732
6733 #[test]
6734 fn validate_deps_rejects_duplicate_nome_in_deps_dev() {
6735 // Parity pin: `:deps-dev` runs through the same per-list
6736 // duplicate check as `:deps` — neither axis is a second-class
6737 // citizen of the set-not-multiset discipline.
6738 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6739 c.deps_dev = vec![
6740 Dep::simple("tatara-check", "*"),
6741 Dep::simple("tatara-check", "^0.1"),
6742 ];
6743 let err = c.validate_deps().unwrap_err();
6744 assert!(
6745 matches!(
6746 err,
6747 crate::dep::DepError::DuplicateNome { ref nome, list }
6748 if nome == "tatara-check" && list == crate::render::DEP_AUTHOR_KEY_DEPS_DEV
6749 ),
6750 "got {err:?}"
6751 );
6752 }
6753
6754 #[test]
6755 fn validate_deps_accepts_cross_list_same_nome() {
6756 // The Cargo `[dependencies]` + `[dev-dependencies]` override
6757 // convention is preserved: a name appearing in *both* lists is
6758 // valid (the dev-pin overrides at test/dev time). Only
6759 // within-list duplicates are structurally incoherent — pin the
6760 // permissive cross-list semantics so a future shortcut that
6761 // collapses the two seen-sets into one surfaces here as a test
6762 // failure.
6763 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6764 c.deps = vec![Dep::simple("caixa-teia", "^0.1")];
6765 c.deps_dev = vec![Dep::simple("caixa-teia", "^0.2")];
6766 c.validate_deps().unwrap();
6767 }
6768
6769 #[test]
6770 fn validate_deps_accepts_distinct_nome_in_both_lists() {
6771 // Positive control: distinct names within each list pass — the
6772 // gate's identity element on the canonical authoring shape.
6773 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6774 c.deps = vec![
6775 Dep::simple("caixa-teia", "^0.1"),
6776 Dep::simple("pleme-mesh", "*"),
6777 ];
6778 c.deps_dev = vec![
6779 Dep::simple("tatara-check", "*"),
6780 Dep::simple("dev-shim", "^0.1"),
6781 ];
6782 c.validate_deps().unwrap();
6783 }
6784
6785 #[test]
6786 fn validate_deps_per_entry_validate_fires_before_duplicate_in_deps() {
6787 // Diagnostic-precedence pin: a malformed `:versao` on the
6788 // duplicating entry surfaces its narrower `VersaoInvalid`
6789 // diagnostic first, before the cross-entry duplicate gate fires
6790 // — the canonical "per-entry shape before cross-entry uniqueness"
6791 // precedence every peer set-not-multiset gate establishes
6792 // (`*_invalid_fires_before_duplicate_check` pins on
6793 // `SupervisorSpec::validate`, `AplicacaoSpec::validate_membros`,
6794 // `validate_upgrade_from`).
6795 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6796 c.deps = vec![
6797 Dep::simple("caixa-teia", "^0.1"),
6798 Dep::simple("caixa-teia", "^bad-version"),
6799 ];
6800 let err = c.validate_deps().unwrap_err();
6801 assert!(
6802 matches!(
6803 err,
6804 crate::dep::DepError::VersaoInvalid { ref nome, ref versao, .. }
6805 if nome == "caixa-teia" && versao == "^bad-version"
6806 ),
6807 "expected VersaoInvalid to surface before DuplicateNome, got {err:?}"
6808 );
6809 }
6810
6811 #[test]
6812 fn validate_deps_duplicate_diagnostic_names_first_collision() {
6813 // First-collision determinism pin: with three entries naming the
6814 // same caixa, the first colliding pair surfaces — not the last.
6815 // Mirrors the peer first-collision posture on every
6816 // duplicate-target gate
6817 // (`validate_upgrade_from_duplicate_diagnostic_names_second_collision`
6818 // — the second entry is the first collision; this gate uses the
6819 // same shape: the second entry's `:nome` lands in the diagnostic
6820 // because `seen.insert(first.nome)` already populated the set).
6821 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6822 c.deps = vec![
6823 Dep::simple("caixa-teia", "^0.1"),
6824 Dep::simple("caixa-teia", "^0.2"),
6825 Dep::simple("caixa-teia", "^0.3"),
6826 ];
6827 let err = c.validate_deps().unwrap_err();
6828 // The diagnostic carries the offending caixa name; the
6829 // implementation surfaces on the *second* entry (the first
6830 // collision), so the test pins the `:nome` value.
6831 assert!(
6832 matches!(
6833 err,
6834 crate::dep::DepError::DuplicateNome { ref nome, list }
6835 if nome == "caixa-teia" && list == crate::render::DEP_AUTHOR_KEY_DEPS
6836 ),
6837 "got {err:?}"
6838 );
6839 }
6840
6841 #[test]
6842 fn validate_deps_duplicate_in_deps_fires_before_duplicate_in_deps_dev() {
6843 // Cross-list precedence pin: when both lists carry duplicates,
6844 // the `:deps` diagnostic surfaces first — same author-mental-
6845 // model ordering the `validate_deps_runs_deps_before_deps_dev`
6846 // pin establishes for malformed `:versao` (runtime axis before
6847 // dev axis).
6848 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6849 c.deps = vec![
6850 Dep::simple("runtime-dep", "^0.1"),
6851 Dep::simple("runtime-dep", "^0.2"),
6852 ];
6853 c.deps_dev = vec![Dep::simple("dev-dep", "*"), Dep::simple("dev-dep", "^0.1")];
6854 let err = c.validate_deps().unwrap_err();
6855 assert!(
6856 matches!(
6857 err,
6858 crate::dep::DepError::DuplicateNome { ref nome, list }
6859 if nome == "runtime-dep" && list == crate::render::DEP_AUTHOR_KEY_DEPS
6860 ),
6861 "expected :deps duplicate to surface before :deps-dev duplicate, got {err:?}"
6862 );
6863 }
6864
6865 #[test]
6866 fn validate_deps_empty_lists_pass_duplicate_gate() {
6867 // Empty-set identity pin: the bare template (zero deps, zero
6868 // deps_dev) passes the duplicate gate as the gate's identity
6869 // element. A future tighten that conflates "empty" with
6870 // "missing" would regress this baseline.
6871 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6872 c.validate_deps().unwrap();
6873 }
6874
6875 #[test]
6876 fn validate_deps_duplicate_diagnostic_carries_list_tag() {
6877 // Diagnostic-shape pin: the `list:` field tags which list the
6878 // duplicate landed in (`:deps` vs `:deps-dev`) verbatim, so a
6879 // `feira lint` run can route the author to the right block in
6880 // their caixa.lisp without re-deriving the list from context.
6881 // Same self-locating shape every peer per-axis diagnostic
6882 // already exposes.
6883 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6884 c.deps_dev = vec![
6885 Dep::simple("dev-thing", "*"),
6886 Dep::simple("dev-thing", "^0.1"),
6887 ];
6888 let err = c.validate_deps().unwrap_err();
6889 let crate::dep::DepError::DuplicateNome { nome, list } = err else {
6890 panic!("expected DuplicateNome from :deps-dev walk");
6891 };
6892 assert_eq!(nome, "dev-thing");
6893 assert_eq!(list, crate::render::DEP_AUTHOR_KEY_DEPS_DEV);
6894 }
6895
6896 // ── validate_deps: per-entry :caracteristicas set-discipline gate ──
6897
6898 #[test]
6899 fn validate_deps_surfaces_caracteristicas_duplicate_in_deps_list() {
6900 // Thread-through pin on `:deps`: the per-entry
6901 // `Dep::validate_caracteristicas` gate fires inside
6902 // `Caixa::validate_deps`'s linear walk, so a malformed feature
6903 // list on any `:deps` entry surfaces as a `DepError` from
6904 // `validate_deps` — the same reachability shape every per-entry
6905 // `Dep::validate` arm threads through. Without this pin a future
6906 // shortcut that skips the per-entry `Dep::validate` call on the
6907 // cross-entry-uniqueness path would mask the within-entry
6908 // `:caracteristicas` gates.
6909 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6910 c.deps = vec![Dep {
6911 nome: "caixa-teia".into(),
6912 versao: "^0.1".into(),
6913 fonte: None,
6914 opcional: false,
6915 caracteristicas: vec!["http".into(), "http".into()],
6916 }];
6917 let err = c.validate_deps().unwrap_err();
6918 let crate::dep::DepError::CaracteristicaDuplicate {
6919 nome,
6920 caracteristica,
6921 } = err
6922 else {
6923 panic!("expected CaracteristicaDuplicate from :deps walk, got {err:?}");
6924 };
6925 assert_eq!(nome, "caixa-teia");
6926 assert_eq!(caracteristica, "http");
6927 }
6928
6929 #[test]
6930 fn validate_deps_surfaces_caracteristicas_empty_in_deps_dev_list() {
6931 // Peer thread-through pin on `:deps-dev`: same reachability as
6932 // the `:deps` arm above, on the dev-only authoring axis. Pins
6933 // that the `validate_deps` walk visits both lists' per-entry
6934 // gates uniformly. The empty-feature arm carries here so both
6935 // new `:caracteristicas` arms are surfaced via at least one
6936 // `validate_deps` thread-through.
6937 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6938 c.deps_dev = vec![Dep {
6939 nome: "caixa-teia".into(),
6940 versao: "^0.1".into(),
6941 fonte: None,
6942 opcional: false,
6943 caracteristicas: vec![String::new()],
6944 }];
6945 let err = c.validate_deps().unwrap_err();
6946 let crate::dep::DepError::CaracteristicaEmpty { nome } = err else {
6947 panic!("expected CaracteristicaEmpty from :deps-dev walk, got {err:?}");
6948 };
6949 assert_eq!(nome, "caixa-teia");
6950 }
6951
6952 #[test]
6953 fn validate_deps_surfaces_caracteristicas_invalid_in_deps_list() {
6954 // Thread-through pin on `:deps`: the per-entry
6955 // `Dep::validate_caracteristicas` value-shape gate (lifted via
6956 // `crate::render::is_cargo_feature_name`) fires inside
6957 // `Caixa::validate_deps`'s linear walk on the `:deps` list, so
6958 // a structurally invalid feature name on any `:deps` entry
6959 // surfaces as `DepError::CaracteristicaInvalid` from
6960 // `validate_deps` — the same reachability shape every per-entry
6961 // `Dep::validate` arm threads through. Without this pin a
6962 // future shortcut that skips the per-entry `Dep::validate` call
6963 // on the cross-entry-uniqueness path would mask the within-
6964 // entry `:caracteristicas` value-shape gate.
6965 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6966 c.deps = vec![Dep {
6967 nome: "caixa-teia".into(),
6968 versao: "^0.1".into(),
6969 fonte: None,
6970 opcional: false,
6971 caracteristicas: vec!["+http".into()],
6972 }];
6973 let err = c.validate_deps().unwrap_err();
6974 let crate::dep::DepError::CaracteristicaInvalid {
6975 nome,
6976 caracteristica,
6977 ..
6978 } = err
6979 else {
6980 panic!("expected CaracteristicaInvalid from :deps walk, got {err:?}");
6981 };
6982 assert_eq!(nome, "caixa-teia");
6983 assert_eq!(caracteristica, "+http");
6984 }
6985
6986 #[test]
6987 fn validate_deps_surfaces_caracteristicas_invalid_in_deps_dev_list() {
6988 // Peer thread-through pin on `:deps-dev`: same reachability as
6989 // the `:deps` arm above, on the dev-only authoring axis. The
6990 // `http/json` shape carries here so the segment-separator
6991 // diagnostic (the canonical Cargo `dep/feat` namespaced-dep
6992 // confusion footgun) is surfaced via the cross-entry walk too —
6993 // pinning that the `:deps-dev` list visits the same per-entry
6994 // value-shape gate as the `:deps` list.
6995 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
6996 c.deps_dev = vec![Dep {
6997 nome: "caixa-teia".into(),
6998 versao: "^0.1".into(),
6999 fonte: None,
7000 opcional: false,
7001 caracteristicas: vec!["http/json".into()],
7002 }];
7003 let err = c.validate_deps().unwrap_err();
7004 let crate::dep::DepError::CaracteristicaInvalid {
7005 nome,
7006 caracteristica,
7007 ..
7008 } = err
7009 else {
7010 panic!("expected CaracteristicaInvalid from :deps-dev walk, got {err:?}");
7011 };
7012 assert_eq!(nome, "caixa-teia");
7013 assert_eq!(caracteristica, "http/json");
7014 }
7015
7016 #[test]
7017 fn to_lisp_preserves_deps() {
7018 let src = r#"
7019(defcaixa
7020 :nome "x"
7021 :versao "0.1.0"
7022 :kind Biblioteca
7023 :deps ((:nome "a" :versao "^0.1")
7024 (:nome "b" :versao "*" :fonte (:tipo git :repo "github:o/b" :tag "v1"))))
7025"#;
7026 let c1 = Caixa::from_lisp(src).unwrap();
7027 let emitted = c1.to_lisp();
7028 let c2 = Caixa::from_lisp(&emitted).expect("round trip");
7029 assert_eq!(c1.deps, c2.deps);
7030 }
7031
7032 // ── Caixa::validate_nome — top-level :nome value-shape gate ─────────
7033
7034 fn caixa_with_nome(nome: &str) -> Caixa {
7035 let mut c = Caixa::from_lisp(&Caixa::template("placeholder")).unwrap();
7036 c.nome = nome.to_string();
7037 c
7038 }
7039
7040 #[test]
7041 fn validate_nome_accepts_canonical_template() {
7042 // Positive control: the bare `feira init`-style template's
7043 // `:nome` ("demo") is a canonical DNS-1123 label; the gate must
7044 // not regress this baseline shape. A future tightening of the
7045 // accepted set surfaces here as a test failure first.
7046 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
7047 c.validate_nome().unwrap();
7048 }
7049
7050 #[test]
7051 fn validate_nome_accepts_canonical_forms() {
7052 // Positive-set sweep: each realistic caixa-name shape the K8s
7053 // apiserver accepts as a `metadata.name` label must pass —
7054 // single-word, hyphen-joined, version-suffixed, single-char,
7055 // two-char, digit-start (DNS-1123 allows this; the stricter
7056 // DNS-1035 Service-name rule doesn't), version-suffix-bearing.
7057 // Mirrors `accepts_canonical_membro_caixa_forms` (3f9d7a0) on
7058 // the peer member-name axis.
7059 for nome in [
7060 "checkout",
7061 "cart-v2",
7062 "a",
7063 "db",
7064 "3rd-party-shim",
7065 "payment-retry",
7066 "0",
7067 ] {
7068 caixa_with_nome(nome)
7069 .validate_nome()
7070 .unwrap_or_else(|e| panic!("canonical :nome {nome:?} must validate, got {e:?}"));
7071 }
7072 }
7073
7074 #[test]
7075 fn validate_nome_rejects_empty() {
7076 // Fail-before-pass-after pin: `Caixa::from_lisp` does not refuse
7077 // an empty `:nome` (the derive macro stores the raw String);
7078 // the gate's empty arm names the offending axis with a narrower
7079 // diagnostic than the `NomeInvalid` parse arm would emit.
7080 let c = caixa_with_nome("");
7081 let err = c.validate_nome().unwrap_err();
7082 assert_eq!(err, ManifestError::NomeEmpty);
7083 }
7084
7085 #[test]
7086 fn validate_nome_rejects_uppercase() {
7087 // The canonical "I copied the TitleCase display name verbatim"
7088 // footgun. The K8s apiserver rejects `metadata.name: MyApp` at
7089 // admission on every derived artifact (Helm chart, ComputeUnit,
7090 // CNP, HTTPRoute, label values); the gate moves the diagnostic
7091 // to the source `caixa.lisp` and the reason suggests the
7092 // lowercased fix verbatim.
7093 let c = caixa_with_nome("MyApp");
7094 let err = c.validate_nome().unwrap_err();
7095 let ManifestError::NomeInvalid { nome, reason } = err else {
7096 panic!("expected NomeInvalid for uppercase :nome");
7097 };
7098 assert_eq!(nome, "MyApp");
7099 assert!(
7100 reason.contains("uppercase") && reason.contains("myapp"),
7101 "diagnostic must name the violation + the lowercased fix, got {reason:?}"
7102 );
7103 }
7104
7105 #[test]
7106 fn validate_nome_rejects_underscore() {
7107 // The Python-/Postgres-style `snake_case` leak. DNS-1123 forbids
7108 // `_`; the apiserver rejects on admission across every derived
7109 // artifact. Same fixture pinned for `:membros :caixa` (3f9d7a0)
7110 // and `:children :caixa` (31bfa43).
7111 let c = caixa_with_nome("my_app");
7112 let err = c.validate_nome().unwrap_err();
7113 assert!(
7114 matches!(
7115 err,
7116 ManifestError::NomeInvalid { ref nome, ref reason }
7117 if nome == "my_app" && reason.contains('_')
7118 ),
7119 "got {err:?}"
7120 );
7121 }
7122
7123 #[test]
7124 fn validate_nome_rejects_dot() {
7125 // A `:nome` is a single DNS-1123 label, not a subdomain. The
7126 // "I want to namespace with `.`" footgun the gate redirects to
7127 // `-` via the shared predicate's reason wording.
7128 let c = caixa_with_nome("team.app");
7129 let err = c.validate_nome().unwrap_err();
7130 assert!(
7131 matches!(
7132 err,
7133 ManifestError::NomeInvalid { ref nome, ref reason }
7134 if nome == "team.app" && reason.contains('.')
7135 ),
7136 "got {err:?}"
7137 );
7138 }
7139
7140 #[test]
7141 fn validate_nome_rejects_leading_hyphen() {
7142 // DNS-1123 boundary rule: the label must start with an ASCII
7143 // alphanumeric. Pin the leading-`-` arm explicitly.
7144 let c = caixa_with_nome("-app");
7145 let err = c.validate_nome().unwrap_err();
7146 assert!(
7147 matches!(
7148 err,
7149 ManifestError::NomeInvalid { ref nome, .. } if nome == "-app"
7150 ),
7151 "got {err:?}"
7152 );
7153 }
7154
7155 #[test]
7156 fn validate_nome_rejects_trailing_hyphen() {
7157 // Symmetric arm of the boundary rule, pinned separately so a
7158 // future relaxation that only checks the leading position
7159 // surfaces here. Mirrors `rejects_membro_caixa_with_trailing_hyphen`
7160 // and `_with_trailing_hyphen` on the supervisor / aplicacao
7161 // axes.
7162 let c = caixa_with_nome("app-");
7163 let err = c.validate_nome().unwrap_err();
7164 assert!(
7165 matches!(
7166 err,
7167 ManifestError::NomeInvalid { ref nome, .. } if nome == "app-"
7168 ),
7169 "got {err:?}"
7170 );
7171 }
7172
7173 #[test]
7174 fn validate_nome_rejects_unicode() {
7175 // IDN must be pre-encoded as Punycode (`xn--…`); raw Unicode
7176 // bytes are rejected by the K8s apiserver on every name axis.
7177 let c = caixa_with_nome("café");
7178 let err = c.validate_nome().unwrap_err();
7179 assert!(
7180 matches!(
7181 err,
7182 ManifestError::NomeInvalid { ref nome, .. } if nome == "café"
7183 ),
7184 "got {err:?}"
7185 );
7186 }
7187
7188 #[test]
7189 fn validate_nome_rejects_whitespace() {
7190 // The paste-from-sketch / paste-from-spec footgun. Internal
7191 // whitespace is rejected by every K8s name axis.
7192 let c = caixa_with_nome("my app");
7193 let err = c.validate_nome().unwrap_err();
7194 assert!(
7195 matches!(
7196 err,
7197 ManifestError::NomeInvalid { ref nome, .. } if nome == "my app"
7198 ),
7199 "got {err:?}"
7200 );
7201 }
7202
7203 #[test]
7204 fn validate_nome_rejects_too_long() {
7205 // 64-byte boundary pin: the K8s apiserver rejects any
7206 // `metadata.name` over 63 bytes at admission; the diagnostic
7207 // names both the 63-byte cap and the actual length so the
7208 // author can shorten in one edit. Mirrors `_too_long` on the
7209 // peer member-/cluster-/child-name axes.
7210 let over = "a".repeat(crate::DNS_1123_LABEL_MAX_LEN + 1);
7211 let c = caixa_with_nome(&over);
7212 let err = c.validate_nome().unwrap_err();
7213 let ManifestError::NomeInvalid { nome, reason } = err else {
7214 panic!("expected NomeInvalid for over-cap :nome");
7215 };
7216 assert_eq!(nome.len(), crate::DNS_1123_LABEL_MAX_LEN + 1);
7217 assert!(
7218 reason.contains("63") && reason.contains("64"),
7219 "diagnostic must name the cap + actual length, got {reason:?}"
7220 );
7221 }
7222
7223 #[test]
7224 fn nome_max_length_validates() {
7225 // The 63-byte cap exactly — the boundary-accepting case pinned
7226 // alongside `validate_nome_rejects_too_long` so a future cap
7227 // shift surfaces both arms simultaneously. Mirrors
7228 // `membro_caixa_max_length_validates`,
7229 // `placement_cluster_max_length_validates`,
7230 // `child_caixa_max_length_validates`.
7231 let at_cap = "a".repeat(crate::DNS_1123_LABEL_MAX_LEN);
7232 caixa_with_nome(&at_cap).validate_nome().unwrap();
7233 }
7234
7235 #[test]
7236 fn nome_empty_takes_precedence_over_invalid() {
7237 // Order pin: the empty arm fires before the predicate is
7238 // consulted. Empty < invalid in self-locating-ness — the
7239 // narrower `NomeEmpty` diagnostic doesn't carry a useless
7240 // `nome: ""` reference into the parser-shaped reason. Mirrors
7241 // `membro_caixa_empty_takes_precedence_over_invalid` on the
7242 // peer axis (3f9d7a0).
7243 let c = caixa_with_nome("");
7244 assert_eq!(c.validate_nome().unwrap_err(), ManifestError::NomeEmpty);
7245 }
7246
7247 #[test]
7248 fn nome_invalid_diagnostic_carries_offending_nome() {
7249 // Diagnostic-shape pin: the error names the offending `:nome`
7250 // verbatim with a non-empty parser-shaped reason, so a `feira
7251 // lint` run can render the diagnostic without re-parsing.
7252 // Mirrors `membro_caixa_invalid_diagnostic_carries_offending_caixa`.
7253 let c = caixa_with_nome("MyApp");
7254 let err = c.validate_nome().unwrap_err();
7255 let ManifestError::NomeInvalid { nome, reason } = err else {
7256 panic!("expected NomeInvalid variant");
7257 };
7258 assert_eq!(nome, "MyApp");
7259 assert!(
7260 !reason.is_empty(),
7261 "NomeInvalid `reason` must carry the predicate's wording verbatim"
7262 );
7263 }
7264
7265 // ── Caixa::validate_nome_chart_name_budget — joint-length on `:nome` ──
7266 //
7267 // The bare-`:nome` axis [`Caixa::validate_nome`] caps at 63 bytes
7268 // via DNS-1123; this second-axis gate caps the joint
7269 // `lareira-<nome>` chart name at the same 63-byte ceiling. The
7270 // canonical [`crate::lareira_chart_name`] helper's doc comment
7271 // (f7320d7, caixa-core/src/render.rs:3198) explicitly deferred:
7272 // "the M4 admission webhook will pin the joint-length invariant
7273 // when it lands". These tests pin it at the manifest-validate
7274 // layer instead, fail-before-pass-after on the 56-byte boundary.
7275
7276 #[test]
7277 fn validate_nome_chart_name_budget_accepts_canonical_template() {
7278 // Positive control: the bare `feira init`-style template's
7279 // `:nome` ("demo") sits far below the cap; the gate must not
7280 // regress this baseline. Same shape every peer
7281 // value-shape-gate baseline pin uses.
7282 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
7283 c.validate_nome_chart_name_budget().unwrap();
7284 }
7285
7286 #[test]
7287 fn validate_nome_chart_name_budget_accepts_canonical_fixtures() {
7288 // Positive-set sweep across the canonical author surface every
7289 // in-tree fixture uses (`hello-rio`, `cart`, `checkout`,
7290 // `worker`, the `checkout-aplicacao` example members, the
7291 // `akeyless-attest` caixa-tatara fixture). Every value sits
7292 // far below the 55-byte per-`:nome` budget. Same shape every
7293 // peer per-axis baseline pin uses.
7294 for nome in [
7295 "hello-rio",
7296 "cart",
7297 "checkout",
7298 "worker",
7299 "akeyless-attest",
7300 "demo",
7301 "a",
7302 ] {
7303 caixa_with_nome(nome)
7304 .validate_nome_chart_name_budget()
7305 .unwrap_or_else(|e| {
7306 panic!("canonical :nome {nome:?} must pass chart-name budget, got {e:?}")
7307 });
7308 }
7309 }
7310
7311 #[test]
7312 fn validate_nome_chart_name_budget_accepts_nome_at_cap() {
7313 // Boundary-accepting case at the 55-byte per-`:nome` budget —
7314 // the joint chart name is exactly 63 bytes, the DNS-1123 label
7315 // cap. Pinned alongside the rejecting-arm test so a future cap
7316 // shift surfaces both arms simultaneously. Mirrors
7317 // `nome_max_length_validates` on the peer bare-`:nome` axis.
7318 let at_cap = "a".repeat(crate::LAREIRA_CHART_NAME_NOME_MAX_LEN);
7319 caixa_with_nome(&at_cap)
7320 .validate_nome_chart_name_budget()
7321 .unwrap();
7322 }
7323
7324 #[test]
7325 fn validate_nome_chart_name_budget_rejects_nome_one_over_cap() {
7326 // Fail-before-pass-after pin on the 56-byte boundary: the
7327 // smallest `:nome` length that overflows the joint chart-name
7328 // cap. The inner [`is_dns_1123_label`] gate
7329 // (`Caixa::validate_nome`) accepts it (56 ≤ 63), so prior to
7330 // this gate it silently passed the manifest-validate cascade
7331 // and surfaced as a `helm lint` / apiserver rejection on the
7332 // rendered chart name far from the source `caixa.lisp`, with
7333 // no field naming the overflow. With this gate the diagnostic
7334 // names the offending `:nome` verbatim alongside the rendered
7335 // chart name and the budget, so the author can shorten in one
7336 // edit. Mirrors `validate_nome_rejects_too_long` on the peer
7337 // bare-`:nome` axis.
7338 let over = "a".repeat(crate::LAREIRA_CHART_NAME_NOME_MAX_LEN + 1);
7339 let c = caixa_with_nome(&over);
7340 let err = c.validate_nome_chart_name_budget().unwrap_err();
7341 let ManifestError::NomeChartNameBudgetExceeded { nome, reason } = err else {
7342 panic!("expected NomeChartNameBudgetExceeded for over-budget :nome");
7343 };
7344 assert_eq!(nome.len(), crate::LAREIRA_CHART_NAME_NOME_MAX_LEN + 1);
7345 assert_eq!(nome, over);
7346 assert!(
7347 reason.contains("63") && reason.contains("64") && reason.contains("55"),
7348 "diagnostic must name the DNS-1123 cap (63), the actual chart-name length (64), \
7349 and the per-`:nome` budget (55), got {reason:?}"
7350 );
7351 }
7352
7353 #[test]
7354 fn validate_nome_chart_name_budget_rejects_nome_at_bare_dns_cap() {
7355 // The 63-byte `:nome` boundary — passes the bare-`:nome`
7356 // [`is_dns_1123_label`] cap exactly, but produces a 71-byte
7357 // joint chart name that overflows the DNS-1123 label cap
7358 // structurally. The most stringent fail-before-pass-after
7359 // surface: every `:nome` in the 56..=63-byte range passed the
7360 // prior cascade and broke at admission.
7361 let bare_max = "a".repeat(crate::DNS_1123_LABEL_MAX_LEN);
7362 let c = caixa_with_nome(&bare_max);
7363 // The bare-`:nome` gate accepts the 63-byte length.
7364 c.validate_nome().unwrap();
7365 // The new joint-length gate rejects it.
7366 let err = c.validate_nome_chart_name_budget().unwrap_err();
7367 assert!(
7368 matches!(
7369 err,
7370 ManifestError::NomeChartNameBudgetExceeded { ref nome, .. }
7371 if nome.len() == crate::DNS_1123_LABEL_MAX_LEN
7372 ),
7373 "got {err:?}"
7374 );
7375 }
7376
7377 #[test]
7378 fn validate_nome_chart_name_budget_diagnostic_carries_offending_chart_name() {
7379 // Diagnostic-shape pin: the rendered `lareira-<nome>` chart
7380 // name appears verbatim in the diagnostic so the author sees
7381 // exactly the string the apiserver / `helm lint` would have
7382 // rejected — no re-derivation required to grep the source.
7383 // Peer with `nome_invalid_diagnostic_carries_offending_nome`
7384 // on the bare-`:nome` axis.
7385 let over = "x".repeat(crate::LAREIRA_CHART_NAME_NOME_MAX_LEN + 5);
7386 let c = caixa_with_nome(&over);
7387 let err = c.validate_nome_chart_name_budget().unwrap_err();
7388 let ManifestError::NomeChartNameBudgetExceeded { nome, reason } = err else {
7389 panic!("expected NomeChartNameBudgetExceeded variant");
7390 };
7391 assert_eq!(nome, over);
7392 let expected_chart = crate::lareira_chart_name(&over);
7393 assert!(
7394 reason.contains(&expected_chart),
7395 "diagnostic must carry the rendered chart name {expected_chart:?} verbatim, \
7396 got {reason:?}"
7397 );
7398 assert!(
7399 reason.contains("lareira-"),
7400 "diagnostic must name the canonical chart-name prefix verbatim, got {reason:?}"
7401 );
7402 }
7403
7404 #[test]
7405 fn validate_nome_chart_name_budget_runs_after_nome_shape_via_layout_verify() {
7406 // Order pin on the layout cascade: the narrower
7407 // `NomeInvalid` (bare-DNS-1123 shape) fires before the
7408 // joint-length budget. A structurally-malformed `:nome` (here:
7409 // uppercase) surfaces its specific shape error rather than
7410 // the chart-name-budget error, even when the joint length
7411 // would also overflow — the narrower diagnostic is more
7412 // self-locating. Mirrors the cascade-precedence pins peer
7413 // gates already use (e.g. `EntradaParaEmpty` before
7414 // `EntradaParaInvalid`).
7415 let over = "A".repeat(crate::LAREIRA_CHART_NAME_NOME_MAX_LEN + 1);
7416 let c = caixa_with_nome(&over);
7417 // The bare-shape gate fires first.
7418 let err = c.validate_nome().unwrap_err();
7419 assert!(
7420 matches!(err, ManifestError::NomeInvalid { .. }),
7421 "bare-shape gate must fire before chart-name-budget gate; got {err:?}"
7422 );
7423 // And the layout verify cascade surfaces that diagnostic, not
7424 // the budget arm. Inject a path-exists oracle so the cascade
7425 // gets past the manifest-presence check and into the
7426 // value-shape gates.
7427 let layout = crate::StandardLayout::new().with_path_exists(|_| true);
7428 let err = crate::LayoutInvariants::verify(
7429 &layout,
7430 &c,
7431 std::path::Path::new("/tmp/caixa-test-fake-root"),
7432 )
7433 .unwrap_err();
7434 let issue = err.to_string();
7435 assert!(
7436 issue.contains("DNS-1123") || issue.contains("uppercase"),
7437 "layout cascade must surface the bare-DNS-1123 diagnostic on a \
7438 structurally-malformed :nome, not the chart-name-budget diagnostic; got {issue:?}"
7439 );
7440 }
7441
7442 #[test]
7443 fn layout_verify_routes_chart_name_budget_through_nome_violation() {
7444 // Cross-axis envelope pin: the layout cascade wraps both
7445 // bare-`:nome` and joint-length-`:nome` failures through the
7446 // same [`LayoutError::NomeViolation`] envelope, since both
7447 // arms are on the `:nome` axis. The user's diagnostic stays
7448 // self-locating ("which axis"), and a future consumer that
7449 // dispatches on the layout-error variant (e.g. a `feira lint`
7450 // exit-code mapping) sees a single per-axis envelope. The
7451 // wrapped `issue:` carries the full inner diagnostic.
7452 let over = "a".repeat(crate::LAREIRA_CHART_NAME_NOME_MAX_LEN + 1);
7453 let c = caixa_with_nome(&over);
7454 // The bare-shape gate accepts.
7455 c.validate_nome().unwrap();
7456 let layout = crate::StandardLayout::new().with_path_exists(|_| true);
7457 let err = crate::LayoutInvariants::verify(
7458 &layout,
7459 &c,
7460 std::path::Path::new("/tmp/caixa-test-fake-root"),
7461 )
7462 .unwrap_err();
7463 let crate::LayoutError::NomeViolation { caixa, issue } = err else {
7464 panic!("expected LayoutError::NomeViolation, got {err:?}");
7465 };
7466 assert_eq!(caixa, over);
7467 assert!(
7468 issue.contains("lareira-") && issue.contains("63") && issue.contains("55"),
7469 "wrapped issue must carry the joint-length diagnostic verbatim, got {issue:?}"
7470 );
7471 }
7472
7473 // ── Caixa::validate_versao — top-level :versao value-shape gate ─────
7474
7475 fn caixa_with_versao(versao: &str) -> Caixa {
7476 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
7477 c.versao = versao.to_string();
7478 c
7479 }
7480
7481 #[test]
7482 fn validate_versao_accepts_canonical_template() {
7483 // Positive control: the bare `feira init`-style template's
7484 // `:versao` ("0.1.0") is a canonical SemVer-2 literal; the gate
7485 // must not regress this baseline shape. A future tightening of
7486 // the accepted set surfaces here as a test failure first.
7487 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
7488 c.validate_versao().unwrap();
7489 }
7490
7491 #[test]
7492 fn validate_versao_accepts_canonical_forms() {
7493 // Positive-set sweep: each realistic SemVer-2 shape the
7494 // substrate's downstream consumers accept must pass — bare
7495 // MAJOR.MINOR.PATCH, pre-release tags (`-rc.1`, `-alpha.0`),
7496 // build metadata (`+build.42`), the combined form, and the
7497 // `0.0.0` boundary case. Mirrors `accepts_canonical_forms` on
7498 // the peer `:nome` axis (6c992f8).
7499 for versao in [
7500 "0.1.0",
7501 "0.0.0",
7502 "1.0.0",
7503 "0.2.0-rc.1",
7504 "1.0.0-alpha.0",
7505 "1.0.0+build.42",
7506 "1.0.0-rc.1+build.42",
7507 "10.20.30",
7508 ] {
7509 caixa_with_versao(versao)
7510 .validate_versao()
7511 .unwrap_or_else(|e| {
7512 panic!("canonical :versao {versao:?} must validate, got {e:?}")
7513 });
7514 }
7515 }
7516
7517 #[test]
7518 fn validate_versao_rejects_empty() {
7519 // Fail-before-pass-after pin: `Caixa::from_lisp` does not refuse
7520 // an empty `:versao` (the derive macro stores the raw String);
7521 // the gate's empty arm names the offending axis with a narrower
7522 // diagnostic than the `VersaoInvalid` parse arm would emit.
7523 // Mirrors `validate_nome_rejects_empty` (6c992f8).
7524 let c = caixa_with_versao("");
7525 let err = c.validate_versao().unwrap_err();
7526 assert_eq!(err, ManifestError::VersaoEmpty);
7527 }
7528
7529 #[test]
7530 fn validate_versao_rejects_git_tag_shape() {
7531 // The canonical "I copied the git tag verbatim" footgun —
7532 // `feira publish` *emits* `v<versao>` git tags, so a leaked
7533 // `v0.1.0` in `:versao` would render as `vv0.1.0` and silently
7534 // shift every downstream consumer's version axis. `semver`
7535 // rejects the leading `v` at parse time; the gate moves the
7536 // diagnostic to the source `caixa.lisp`.
7537 let c = caixa_with_versao("v0.1.0");
7538 let err = c.validate_versao().unwrap_err();
7539 let ManifestError::VersaoInvalid { versao, reason } = err else {
7540 panic!("expected VersaoInvalid for git-tag-shape :versao");
7541 };
7542 assert_eq!(versao, "v0.1.0");
7543 assert!(
7544 !reason.is_empty(),
7545 "VersaoInvalid `reason` must carry the parser's wording, got {reason:?}"
7546 );
7547 }
7548
7549 #[test]
7550 fn validate_versao_rejects_missing_patch() {
7551 // The canonical "I shortened it" footgun — SemVer-2 requires
7552 // three parts. Cargo's `version =` field accepts the shortened
7553 // form as a requirement, conflating the two leaks across the
7554 // typed `:deps :versao` vs top-level `:versao` axes; the gate
7555 // pins the top-level axis to the strict three-part shape.
7556 let c = caixa_with_versao("0.1");
7557 let err = c.validate_versao().unwrap_err();
7558 assert!(
7559 matches!(
7560 err,
7561 ManifestError::VersaoInvalid { ref versao, .. } if versao == "0.1"
7562 ),
7563 "got {err:?}"
7564 );
7565 }
7566
7567 #[test]
7568 fn validate_versao_rejects_requirement_shape() {
7569 // The canonical "I leaked a requirement into a version" footgun —
7570 // the typed `:deps :versao` / `:membros :versao` axes accept
7571 // `^0.1` (a `VersionReq`); the top-level `:versao` requires a
7572 // concrete `Version`. Without this gate the two typed surfaces
7573 // would silently overlap, and a top-level `^0.1` would surface
7574 // at `helm install` time as a Chart.yaml version rejection far
7575 // from the source `caixa.lisp`.
7576 let c = caixa_with_versao("^0.1");
7577 let err = c.validate_versao().unwrap_err();
7578 assert!(
7579 matches!(
7580 err,
7581 ManifestError::VersaoInvalid { ref versao, .. } if versao == "^0.1"
7582 ),
7583 "got {err:?}"
7584 );
7585 }
7586
7587 #[test]
7588 fn validate_versao_rejects_docker_tag_shape() {
7589 // The "I confused it with a docker tag" footgun — `latest`,
7590 // `main`, `stable` parse as identifiers, not SemVer-2 versions.
7591 // SemVer rejects at parse time; the gate moves the diagnostic
7592 // to the source `caixa.lisp`.
7593 for bad in ["latest", "main", "stable"] {
7594 let c = caixa_with_versao(bad);
7595 let err = c.validate_versao().unwrap_err();
7596 assert!(
7597 matches!(
7598 err,
7599 ManifestError::VersaoInvalid { ref versao, .. } if versao == bad
7600 ),
7601 "got {err:?} for {bad:?}"
7602 );
7603 }
7604 }
7605
7606 #[test]
7607 fn validate_versao_rejects_four_part_form() {
7608 // The Java/Microsoft "MAJOR.MINOR.PATCH.BUILD" convention
7609 // SemVer-2 forbids. A leak from a non-SemVer ecosystem; the
7610 // semver crate rejects the extra `.0` at parse time.
7611 let c = caixa_with_versao("0.1.0.0");
7612 let err = c.validate_versao().unwrap_err();
7613 assert!(
7614 matches!(
7615 err,
7616 ManifestError::VersaoInvalid { ref versao, .. } if versao == "0.1.0.0"
7617 ),
7618 "got {err:?}"
7619 );
7620 }
7621
7622 #[test]
7623 fn versao_empty_takes_precedence_over_invalid() {
7624 // Order pin: the empty arm fires before the parser is consulted.
7625 // Empty < invalid in self-locating-ness — the narrower
7626 // `VersaoEmpty` diagnostic doesn't carry a useless `versao: ""`
7627 // reference into the parser-shaped reason. Mirrors
7628 // `nome_empty_takes_precedence_over_invalid` (6c992f8) on the
7629 // peer axis.
7630 let c = caixa_with_versao("");
7631 assert_eq!(c.validate_versao().unwrap_err(), ManifestError::VersaoEmpty);
7632 }
7633
7634 #[test]
7635 fn versao_invalid_diagnostic_carries_offending_versao() {
7636 // Diagnostic-shape pin: the error names the offending `:versao`
7637 // verbatim with a non-empty parser-shaped reason, so a `feira
7638 // lint` run can render the diagnostic without re-parsing.
7639 // Mirrors `nome_invalid_diagnostic_carries_offending_nome`.
7640 let c = caixa_with_versao("v0.1.0");
7641 let err = c.validate_versao().unwrap_err();
7642 let ManifestError::VersaoInvalid { versao, reason } = err else {
7643 panic!("expected VersaoInvalid variant");
7644 };
7645 assert_eq!(versao, "v0.1.0");
7646 assert!(
7647 !reason.is_empty(),
7648 "VersaoInvalid `reason` must carry the parser's wording verbatim"
7649 );
7650 }
7651
7652 #[test]
7653 fn validate_versao_accepts_what_upgrade_from_from_accepts() {
7654 // Parity pin: every shape `UpgradeFromEntry::validate` accepts
7655 // for `:upgrade-from :from` must also pass `validate_versao` —
7656 // the two `:versao`-typed surfaces (top-level `:versao`,
7657 // `:upgrade-from :from`) consume the *same* `semver::Version`
7658 // parser, so they must agree on the accepted set. Without this
7659 // pin, a future tightening of one axis could silently diverge
7660 // from the other. Mirrors the `:versao` requirement-axis
7661 // parity (`:deps`/`:deps-dev`/`:membros`/`:children`) the prior
7662 // commits established.
7663 for versao in ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42"] {
7664 // From the canonical UpgradeFromEntry round-trip fixture
7665 // (`upgrade::tests::round_trip_load_module` peers).
7666 let entry = crate::UpgradeFromEntry {
7667 from: versao.to_string(),
7668 instructions: Vec::new(),
7669 };
7670 entry
7671 .validate()
7672 .unwrap_or_else(|e| panic!(":from {versao:?} must validate, got {e:?}"));
7673 caixa_with_versao(versao)
7674 .validate_versao()
7675 .unwrap_or_else(|e| {
7676 panic!(":versao {versao:?} must validate, got {e:?} — peer axis diverges")
7677 });
7678 }
7679 }
7680
7681 // ── Caixa::validate_restart_window — supervisor restart-window
7682 // folds through the shared `supervisor::duration_codec` ────────
7683
7684 fn caixa_with_restart_window(window: Option<&str>) -> Caixa {
7685 let mut c = Caixa::from_lisp(&Caixa::template("root")).unwrap();
7686 c.kind = CaixaKind::Supervisor;
7687 c.restart_window = window.map(str::to_string);
7688 c
7689 }
7690
7691 #[test]
7692 fn validate_restart_window_accepts_none() {
7693 // The canonical "omit the slot to express no reset" shape — a
7694 // `None` raw string is the absence of the typed
7695 // `:restart-window` slot, which is exactly the SupervisorSpec
7696 // "never reset" semantics. The gate must be a no-op here; a
7697 // future tightening that rejected `None` would force every
7698 // supervisor caixa to authoring-time pin a window even when
7699 // the OTP semantics call for none.
7700 caixa_with_restart_window(None)
7701 .validate_restart_window()
7702 .unwrap();
7703 }
7704
7705 #[test]
7706 fn validate_restart_window_accepts_canonical_forms() {
7707 // Positive-set sweep across the canonical authoring units the
7708 // shared `supervisor::duration_codec::parse` accepts —
7709 // matches the codec-side `parse_accepts_integer_canonical_units`
7710 // pin in supervisor::tests so a future codec-side tightening
7711 // surfaces simultaneously on both axes.
7712 for window in ["60s", "5m", "1h", "500ms", "30", "0s"] {
7713 caixa_with_restart_window(Some(window))
7714 .validate_restart_window()
7715 .unwrap_or_else(|e| {
7716 panic!("canonical :restart-window {window:?} must validate, got {e:?}")
7717 });
7718 }
7719 }
7720
7721 #[test]
7722 fn validate_restart_window_rejects_fractional_seconds() {
7723 // Fail-before-pass-after pin: the `"1.5s"` drift class (parses
7724 // as f64 to 1.5 → renders back as `"1500ms"` on first
7725 // serialize). Prior to the fold + this gate, the inline
7726 // `parse_window_inline` accepted f64 magnitudes and silently
7727 // produced a `Duration::from_secs_f64(1.5)`, divergent from
7728 // the shared codec's integer-magnitude discipline on the
7729 // serde-routed siblings. The gate now surfaces a self-locating
7730 // diagnostic at the manifest layer.
7731 let err = caixa_with_restart_window(Some("1.5s"))
7732 .validate_restart_window()
7733 .unwrap_err();
7734 let ManifestError::RestartWindowMalformed {
7735 restart_window,
7736 reason,
7737 } = err
7738 else {
7739 panic!("expected RestartWindowMalformed for fractional seconds");
7740 };
7741 assert_eq!(restart_window, "1.5s");
7742 assert!(
7743 reason.contains("\"1.5\"") && reason.contains("not a non-negative integer"),
7744 "diagnostic must carry shared-codec wording, got {reason:?}"
7745 );
7746 }
7747
7748 #[test]
7749 fn validate_restart_window_rejects_decimal_shaped_integer() {
7750 // The `"1.0s"` class — numerically `1s` exactly, but the
7751 // canonical form is `"1s"` not `"1.0s"`. Decimal-shape leak
7752 // gets the same canonical-form diagnostic.
7753 let err = caixa_with_restart_window(Some("1.0s"))
7754 .validate_restart_window()
7755 .unwrap_err();
7756 assert!(
7757 matches!(
7758 err,
7759 ManifestError::RestartWindowMalformed { ref restart_window, .. }
7760 if restart_window == "1.0s"
7761 ),
7762 "got {err:?}"
7763 );
7764 }
7765
7766 #[test]
7767 fn validate_restart_window_rejects_half_unit_minute() {
7768 // `"0.5m"` is the unit-fraction footgun — author writes a
7769 // human-readable half-minute, the prior inline parser silently
7770 // produced `Duration::from_secs_f64(30.0)` and serde
7771 // re-emitted as `"30s"`, rewriting author intent. The gate
7772 // closes the loop at the manifest layer.
7773 let err = caixa_with_restart_window(Some("0.5m"))
7774 .validate_restart_window()
7775 .unwrap_err();
7776 let ManifestError::RestartWindowMalformed {
7777 restart_window,
7778 reason,
7779 } = err
7780 else {
7781 panic!("expected RestartWindowMalformed");
7782 };
7783 assert_eq!(restart_window, "0.5m");
7784 assert!(
7785 reason.contains("\"30s\""),
7786 "diagnostic must point at the canonical-form remediation, got {reason:?}"
7787 );
7788 }
7789
7790 #[test]
7791 fn validate_restart_window_rejects_leading_sign() {
7792 // `"+30s"` and `"-30s"` both round-tripped through f64 cleanly
7793 // on the prior parser (`+30` parses as `30.0`; `-30` parsed
7794 // and was caught by the `num < 0.0` arm which silently
7795 // returned `None`, dropping the author-supplied window). The
7796 // shared codec's digit-only gate rejects both with a unified
7797 // canonical-form diagnostic; the manifest-layer wrapper names
7798 // the offending value.
7799 for bad in ["+30s", "-30s"] {
7800 let err = caixa_with_restart_window(Some(bad))
7801 .validate_restart_window()
7802 .unwrap_err();
7803 assert!(
7804 matches!(
7805 err,
7806 ManifestError::RestartWindowMalformed { ref restart_window, .. }
7807 if restart_window == bad
7808 ),
7809 "got {err:?} for {bad:?}"
7810 );
7811 }
7812 }
7813
7814 #[test]
7815 fn validate_restart_window_rejects_unknown_unit() {
7816 // `"30x"` — the typo / wrong-unit footgun. The shared codec's
7817 // unit dispatch surfaces an `unknown duration unit` reason;
7818 // the manifest-layer wrapper names the offending value.
7819 let err = caixa_with_restart_window(Some("30x"))
7820 .validate_restart_window()
7821 .unwrap_err();
7822 let ManifestError::RestartWindowMalformed {
7823 restart_window,
7824 reason,
7825 } = err
7826 else {
7827 panic!("expected RestartWindowMalformed for unknown unit");
7828 };
7829 assert_eq!(restart_window, "30x");
7830 assert!(
7831 reason.contains("unknown duration unit"),
7832 "diagnostic must carry shared-codec unit-rejection wording, got {reason:?}"
7833 );
7834 }
7835
7836 #[test]
7837 fn validate_restart_window_rejects_garbage() {
7838 // Pure non-numeric magnitude (`"abc"`) falls through to the
7839 // shared codec's narrower `"bad duration magnitude"` arm. Same
7840 // diagnostic shape as the codec-side
7841 // `parse_garbage_still_falls_through_to_bad_magnitude` pin.
7842 let err = caixa_with_restart_window(Some("abc"))
7843 .validate_restart_window()
7844 .unwrap_err();
7845 let ManifestError::RestartWindowMalformed {
7846 restart_window,
7847 reason,
7848 } = err
7849 else {
7850 panic!("expected RestartWindowMalformed for garbage");
7851 };
7852 assert_eq!(restart_window, "abc");
7853 assert!(
7854 reason.contains("bad duration magnitude"),
7855 "diagnostic must carry shared-codec garbage-rejection wording, got {reason:?}"
7856 );
7857 }
7858
7859 #[test]
7860 fn validate_restart_window_rejects_empty_string() {
7861 // The empty-after-trim edge case — distinct from the `None`
7862 // canonical "omit the slot" shape. The shared codec's
7863 // digit-only gate refuses an empty magnitude; the manifest
7864 // layer names the offending `""` so the author can grep for
7865 // the literal empty value in their `caixa.lisp` and either
7866 // remove the slot (the canonical "no reset" shape) or pin a
7867 // positive duration.
7868 let err = caixa_with_restart_window(Some(""))
7869 .validate_restart_window()
7870 .unwrap_err();
7871 assert!(
7872 matches!(
7873 err,
7874 ManifestError::RestartWindowMalformed { ref restart_window, .. }
7875 if restart_window.is_empty()
7876 ),
7877 "got {err:?}"
7878 );
7879 }
7880
7881 #[test]
7882 fn validate_restart_window_diagnostic_carries_offending_value() {
7883 // Diagnostic-shape pin (peer with
7884 // `nome_invalid_diagnostic_carries_offending_nome` /
7885 // `versao_invalid_diagnostic_carries_offending_versao`): the
7886 // error names the offending raw `:restart-window` verbatim
7887 // with a non-empty shared-codec-shaped reason, so a `feira
7888 // lint` run can render the diagnostic without re-parsing.
7889 let err = caixa_with_restart_window(Some("1.5s"))
7890 .validate_restart_window()
7891 .unwrap_err();
7892 let ManifestError::RestartWindowMalformed {
7893 restart_window,
7894 reason,
7895 } = err
7896 else {
7897 panic!("expected RestartWindowMalformed variant");
7898 };
7899 assert_eq!(restart_window, "1.5s");
7900 assert!(
7901 !reason.is_empty(),
7902 "RestartWindowMalformed `reason` must carry the codec's wording verbatim"
7903 );
7904 }
7905
7906 #[test]
7907 fn supervisor_view_folds_through_shared_codec_on_canonical_form() {
7908 // Behavioral parity pin after the fold (`parse_window_inline`
7909 // deletion): the canonical `"60s"` still produces
7910 // `Duration::from_secs(60)` on the typed view — the fold is
7911 // semantically equivalent to the prior inline parser on the
7912 // accepted set. Mirrors the pre-fold `supervisor_view_returns_typed_shape`
7913 // pin, narrowed to the parser-side contract.
7914 let c = caixa_with_restart_window(Some("60s"));
7915 let view = c.supervisor_view().expect("Supervisor kind has a view");
7916 assert_eq!(
7917 view.restart_window,
7918 Some(std::time::Duration::from_secs(60))
7919 );
7920 }
7921
7922 #[test]
7923 fn supervisor_view_soft_swallows_what_validate_rejects() {
7924 // Parity pin between the view-construction path and the
7925 // manifest-level validator: the same `"1.5s"` that surfaces
7926 // `RestartWindowMalformed` at `validate_restart_window` time
7927 // becomes `restart_window: None` on the typed view (the fold
7928 // preserves the existing best-effort shape of `supervisor_view`).
7929 // The contract is: a layout-verifier / `feira lint` flow that
7930 // cares about the malformed-window axis MUST consult
7931 // `validate_restart_window` — relying solely on the view's
7932 // `None` swallows the diagnostic silently. This pin makes the
7933 // expectation a typed invariant.
7934 let c = caixa_with_restart_window(Some("1.5s"));
7935 let view = c.supervisor_view().expect("Supervisor kind has a view");
7936 assert_eq!(
7937 view.restart_window, None,
7938 "view-construction path soft-swallows the parse error to None"
7939 );
7940 // And the manifest-level validator does NOT soft-swallow:
7941 assert!(
7942 matches!(
7943 c.validate_restart_window().unwrap_err(),
7944 ManifestError::RestartWindowMalformed { ref restart_window, .. }
7945 if restart_window == "1.5s"
7946 ),
7947 "validator must surface the offending value",
7948 );
7949 }
7950
7951 // ── validate_code_paths — per-entry shape on :bibliotecas / :exe / :servicos ──
7952
7953 fn caixa_with_code_paths(bibliotecas: Vec<&str>, exe: Vec<&str>, servicos: Vec<&str>) -> Caixa {
7954 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
7955 c.bibliotecas = bibliotecas.into_iter().map(String::from).collect();
7956 c.exe = exe.into_iter().map(String::from).collect();
7957 c.servicos = servicos.into_iter().map(String::from).collect();
7958 c
7959 }
7960
7961 #[test]
7962 fn validate_code_paths_accepts_canonical_template() {
7963 // The bare `Caixa::template` shape is the gate's identity element
7964 // on the canonical authoring shape — `:bibliotecas
7965 // ("lib/demo.lisp")` + empty `:exe` + empty `:servicos`. Pins
7966 // that the gate is non-disruptive against every existing caixa.
7967 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
7968 c.validate_code_paths().unwrap();
7969 }
7970
7971 #[test]
7972 fn validate_code_paths_accepts_explicit_relative_paths_on_every_slot() {
7973 // Positive control sweep: a canonical-shaped path on every slot
7974 // passes. Mirrors the peer
7975 // `behavior::validate_every_slot_relative_is_ok` pin.
7976 let c = caixa_with_code_paths(
7977 vec!["lib/demo.lisp", "lib/helpers.lisp"],
7978 vec!["exe/demo", "exe/tool"],
7979 vec!["servicos/demo.computeunit.yaml"],
7980 );
7981 c.validate_code_paths().unwrap();
7982 }
7983
7984 #[test]
7985 fn validate_code_paths_accepts_all_empty_lists() {
7986 // The empty-list identity element: every Caixa with no declared
7987 // code paths trivially passes (Supervisor / Aplicacao kinds rely
7988 // on this — the OwnCode gate already rejected them before the
7989 // path-shape gate runs in the layout, but the validator itself
7990 // must accept the empty shape).
7991 let c = caixa_with_code_paths(vec![], vec![], vec![]);
7992 c.validate_code_paths().unwrap();
7993 }
7994
7995 #[test]
7996 fn validate_code_paths_rejects_empty_bibliotecas_entry() {
7997 let c = caixa_with_code_paths(vec![""], vec![], vec![]);
7998 let err = c.validate_code_paths().unwrap_err();
7999 assert!(
8000 matches!(
8001 err,
8002 ManifestError::CodePathEmpty {
8003 slot: ":bibliotecas"
8004 }
8005 ),
8006 "got {err:?}",
8007 );
8008 }
8009
8010 #[test]
8011 fn validate_code_paths_rejects_empty_exe_entry() {
8012 let c = caixa_with_code_paths(vec![], vec![""], vec![]);
8013 let err = c.validate_code_paths().unwrap_err();
8014 assert!(
8015 matches!(err, ManifestError::CodePathEmpty { slot: ":exe" }),
8016 "got {err:?}",
8017 );
8018 }
8019
8020 #[test]
8021 fn validate_code_paths_rejects_empty_servicos_entry() {
8022 let c = caixa_with_code_paths(vec![], vec![], vec![""]);
8023 let err = c.validate_code_paths().unwrap_err();
8024 assert!(
8025 matches!(err, ManifestError::CodePathEmpty { slot: ":servicos" }),
8026 "got {err:?}",
8027 );
8028 }
8029
8030 #[test]
8031 fn validate_code_paths_rejects_absolute_bibliotecas_entry() {
8032 // `:bibliotecas` has no `starts_with(<dir>)` fence downstream,
8033 // so an absolute path that resolves on disk silently passes the
8034 // layout's existence check — the canonical sandbox-escape on
8035 // the biblioteca axis.
8036 let c = caixa_with_code_paths(vec!["/etc/passwd"], vec![], vec![]);
8037 let err = c.validate_code_paths().unwrap_err();
8038 let ManifestError::CodePathAbsolute { slot, path } = err else {
8039 panic!("expected CodePathAbsolute, got {err:?}");
8040 };
8041 assert_eq!(slot, ":bibliotecas");
8042 assert_eq!(path, PathBuf::from("/etc/passwd"));
8043 }
8044
8045 #[test]
8046 fn validate_code_paths_rejects_absolute_exe_entry() {
8047 let c = caixa_with_code_paths(vec![], vec!["/usr/bin/env"], vec![]);
8048 let err = c.validate_code_paths().unwrap_err();
8049 let ManifestError::CodePathAbsolute { slot, path } = err else {
8050 panic!("expected CodePathAbsolute, got {err:?}");
8051 };
8052 assert_eq!(slot, ":exe");
8053 assert_eq!(path, PathBuf::from("/usr/bin/env"));
8054 }
8055
8056 #[test]
8057 fn validate_code_paths_rejects_absolute_servicos_entry() {
8058 let c = caixa_with_code_paths(vec![], vec![], vec!["/var/servicos/x.yaml"]);
8059 let err = c.validate_code_paths().unwrap_err();
8060 let ManifestError::CodePathAbsolute { slot, path } = err else {
8061 panic!("expected CodePathAbsolute, got {err:?}");
8062 };
8063 assert_eq!(slot, ":servicos");
8064 assert_eq!(path, PathBuf::from("/var/servicos/x.yaml"));
8065 }
8066
8067 #[test]
8068 fn validate_code_paths_rejects_parent_escape_bibliotecas_leading() {
8069 // Canonical "I want a lib from a sibling caixa" footgun on the
8070 // biblioteca axis. `:bibliotecas` has no `starts_with` fence
8071 // downstream, so a leading `..` traverses to the parent of the
8072 // caixa root with no diagnostic at layout time if the resolved
8073 // target exists.
8074 let c = caixa_with_code_paths(vec!["../sibling/x.lisp"], vec![], vec![]);
8075 let err = c.validate_code_paths().unwrap_err();
8076 let ManifestError::CodePathParentEscape { slot, path } = err else {
8077 panic!("expected CodePathParentEscape, got {err:?}");
8078 };
8079 assert_eq!(slot, ":bibliotecas");
8080 assert_eq!(path, PathBuf::from("../sibling/x.lisp"));
8081 }
8082
8083 #[test]
8084 fn validate_code_paths_rejects_parent_escape_exe_mid_path() {
8085 // Mid-path `..` defeats the layout's component-aware
8086 // `starts_with(exe_dir)` fence — `root.join("exe/../../escape")`
8087 // `starts_with(<root>/exe)` is true, but the canonical resolution
8088 // lives outside the caixa root. Caught regardless of where the
8089 // `..` sits — mirrors the peer
8090 // `behavior::validate_rejects_parent_escape_mid_path` pin.
8091 let c = caixa_with_code_paths(vec![], vec!["exe/../../escape"], vec![]);
8092 let err = c.validate_code_paths().unwrap_err();
8093 let ManifestError::CodePathParentEscape { slot, path } = err else {
8094 panic!("expected CodePathParentEscape, got {err:?}");
8095 };
8096 assert_eq!(slot, ":exe");
8097 assert_eq!(path, PathBuf::from("exe/../../escape"));
8098 }
8099
8100 #[test]
8101 fn validate_code_paths_rejects_parent_escape_servicos_trailing() {
8102 let c = caixa_with_code_paths(vec![], vec![], vec!["servicos/foo/../../escape.yaml"]);
8103 let err = c.validate_code_paths().unwrap_err();
8104 let ManifestError::CodePathParentEscape { slot, path } = err else {
8105 panic!("expected CodePathParentEscape, got {err:?}");
8106 };
8107 assert_eq!(slot, ":servicos");
8108 assert_eq!(path, PathBuf::from("servicos/foo/../../escape.yaml"));
8109 }
8110
8111 #[test]
8112 fn validate_code_paths_cross_slot_precedence_bibliotecas_before_exe_before_servicos() {
8113 // Cross-slot precedence pin: `:bibliotecas` → `:exe` →
8114 // `:servicos`. A manifest with malformed entries on all three
8115 // surfaces surfaces the `:bibliotecas` defect first, mirroring
8116 // the canonical declaration order
8117 // `Caixa::declared_foreign_code_slots` already establishes for
8118 // the foreign-code-slot diagnostic.
8119 let c = caixa_with_code_paths(vec![""], vec![""], vec![""]);
8120 let err = c.validate_code_paths().unwrap_err();
8121 assert!(
8122 matches!(
8123 err,
8124 ManifestError::CodePathEmpty {
8125 slot: ":bibliotecas"
8126 }
8127 ),
8128 "got {err:?}",
8129 );
8130 }
8131
8132 #[test]
8133 fn validate_code_paths_within_slot_precedence_empty_before_absolute_before_parent_escape() {
8134 // Within-slot precedence pin: empty → absolute → parent-escape,
8135 // matching the [`PathShapeViolation`] arm-ordering every peer
8136 // `is_sandboxed_relative_path` caller follows (b0c8389
8137 // BehaviorSpec, 26da2c7 UpgradeInstruction::StateChange). A
8138 // `:bibliotecas` list whose first entry is empty *and* whose
8139 // later entries are absolute/parent-escape surfaces the empty
8140 // arm first, on the lexicographically-earliest offending entry.
8141 let c = caixa_with_code_paths(vec!["", "/etc/passwd", "../escape.lisp"], vec![], vec![]);
8142 let err = c.validate_code_paths().unwrap_err();
8143 assert!(
8144 matches!(
8145 err,
8146 ManifestError::CodePathEmpty {
8147 slot: ":bibliotecas"
8148 }
8149 ),
8150 "got {err:?}",
8151 );
8152 }
8153
8154 #[test]
8155 fn validate_code_paths_first_offender_per_slot_wins() {
8156 // Within a single slot, the first declaration-order offender
8157 // surfaces — pins that the gate is left-to-right deterministic
8158 // (peer of every `*_first_collision_*` pin on duplicate gates).
8159 let c = caixa_with_code_paths(
8160 vec!["lib/ok.lisp", "/etc/escape", "../also-escape"],
8161 vec![],
8162 vec![],
8163 );
8164 let err = c.validate_code_paths().unwrap_err();
8165 let ManifestError::CodePathAbsolute { slot, path } = err else {
8166 panic!("expected CodePathAbsolute, got {err:?}");
8167 };
8168 assert_eq!(slot, ":bibliotecas");
8169 assert_eq!(path, PathBuf::from("/etc/escape"));
8170 }
8171
8172 #[test]
8173 fn validate_code_paths_diagnostic_carries_offending_slot_and_path() {
8174 // Diagnostic-shape pin (peer with
8175 // `nome_invalid_diagnostic_carries_offending_nome` /
8176 // `versao_invalid_diagnostic_carries_offending_versao`): the
8177 // error's Display surfaces both the offending `:slot` tag and
8178 // the offending path verbatim, so a `feira lint` run can render
8179 // the diagnostic without re-parsing.
8180 let c = caixa_with_code_paths(vec!["/etc/passwd"], vec![], vec![]);
8181 let rendered = c.validate_code_paths().unwrap_err().to_string();
8182 assert!(
8183 rendered.contains(":bibliotecas"),
8184 "diagnostic must name the offending slot: {rendered}",
8185 );
8186 assert!(
8187 rendered.contains("/etc/passwd"),
8188 "diagnostic must quote the offending path: {rendered}",
8189 );
8190 }
8191
8192 #[test]
8193 fn validate_code_paths_rejects_duplicate_bibliotecas_entry() {
8194 // Canonical copy-paste-the-wrong-file footgun on the biblioteca
8195 // axis. Without the gate `feira build` re-parses the same lib
8196 // twice, wasting work and silently masking the author's intent
8197 // to declare a *second* biblioteca.
8198 let c = caixa_with_code_paths(vec!["lib/demo.lisp", "lib/demo.lisp"], vec![], vec![]);
8199 let err = c.validate_code_paths().unwrap_err();
8200 let ManifestError::CodePathDuplicate { slot, path } = err else {
8201 panic!("expected CodePathDuplicate, got {err:?}");
8202 };
8203 assert_eq!(slot, ":bibliotecas");
8204 assert_eq!(path, PathBuf::from("lib/demo.lisp"));
8205 }
8206
8207 #[test]
8208 fn validate_code_paths_rejects_duplicate_exe_entry() {
8209 // Same footgun on the Binario surface. The future `caixa-flake`
8210 // emitter that materializes each `:exe` entry as a flake
8211 // `packages.<name>` derivation would collide on the duplicate
8212 // package key — surfaced here at the typed-validate layer with a
8213 // self-locating diagnostic instead.
8214 let c = caixa_with_code_paths(vec![], vec!["exe/cli", "exe/cli"], vec![]);
8215 let err = c.validate_code_paths().unwrap_err();
8216 let ManifestError::CodePathDuplicate { slot, path } = err else {
8217 panic!("expected CodePathDuplicate, got {err:?}");
8218 };
8219 assert_eq!(slot, ":exe");
8220 assert_eq!(path, PathBuf::from("exe/cli"));
8221 }
8222
8223 #[test]
8224 fn validate_code_paths_rejects_duplicate_servicos_entry() {
8225 // Same footgun on the Servico surface. The peer caixa-helm /
8226 // caixa-flux renderers refuse `:servicos.len() != 1` with the
8227 // narrower `UnsupportedServicoCount` diagnostic, but that
8228 // diagnostic surfaces "too many servicos" without naming
8229 // "duplicate entry" — the typed self-locating framing only lands
8230 // at this gate.
8231 let c = caixa_with_code_paths(
8232 vec![],
8233 vec![],
8234 vec![
8235 "servicos/demo.computeunit.yaml",
8236 "servicos/demo.computeunit.yaml",
8237 ],
8238 );
8239 let err = c.validate_code_paths().unwrap_err();
8240 let ManifestError::CodePathDuplicate { slot, path } = err else {
8241 panic!("expected CodePathDuplicate, got {err:?}");
8242 };
8243 assert_eq!(slot, ":servicos");
8244 assert_eq!(path, PathBuf::from("servicos/demo.computeunit.yaml"));
8245 }
8246
8247 #[test]
8248 fn validate_code_paths_accepts_same_path_across_slots() {
8249 // Per-list scope pin: a `:bibliotecas` entry that happens to
8250 // collide with an `:exe` or `:servicos` entry as a *string* is
8251 // not a duplicate by this gate (each list gets its own HashSet),
8252 // mirroring the peer `:deps` ↔ `:deps-dev` per-list scope
8253 // (a `:nome` present in both lists is a legitimate dev-vs-runtime
8254 // shape on the dep axis). The structural `starts_with(<exe |
8255 // servicos>_dir)` fence at layout time prevents the realistic
8256 // cross-slot collision case from existing on disk, but the gate's
8257 // per-list scope is correct independent of that downstream fence.
8258 let c = caixa_with_code_paths(
8259 vec!["lib/x.lisp"],
8260 vec!["exe/x"],
8261 vec!["servicos/x.computeunit.yaml"],
8262 );
8263 c.validate_code_paths().unwrap();
8264 }
8265
8266 #[test]
8267 fn validate_code_paths_duplicate_fires_after_structural_checks_on_same_slot() {
8268 // Within-slot ordering pin: structural defects (empty / absolute
8269 // / parent-escape) fire before the duplicate gate on the same
8270 // slot. A `:bibliotecas ("" "lib/x.lisp" "lib/x.lisp")` shape
8271 // surfaces the narrower `CodePathEmpty` for the empty entry
8272 // first, not the duplicate on the later pair — same arm-ordering
8273 // every peer per-list duplicate gate uses (`:etiquetas` 360a499,
8274 // `:autores` 86c769b, `:deps` 359fba5).
8275 let c = caixa_with_code_paths(vec!["", "lib/x.lisp", "lib/x.lisp"], vec![], vec![]);
8276 let err = c.validate_code_paths().unwrap_err();
8277 assert!(
8278 matches!(
8279 err,
8280 ManifestError::CodePathEmpty {
8281 slot: ":bibliotecas"
8282 }
8283 ),
8284 "got {err:?}",
8285 );
8286 }
8287
8288 #[test]
8289 fn validate_code_paths_duplicate_in_bibliotecas_fires_before_duplicate_in_exe() {
8290 // Cross-slot ordering pin on the duplicate arm: `:bibliotecas`
8291 // duplicates surface before `:exe` duplicates, matching the
8292 // canonical `:bibliotecas` → `:exe` → `:servicos` declaration
8293 // order every peer per-slot diagnostic on this surface follows.
8294 let c = caixa_with_code_paths(
8295 vec!["lib/x.lisp", "lib/x.lisp"],
8296 vec!["exe/y", "exe/y"],
8297 vec![],
8298 );
8299 let err = c.validate_code_paths().unwrap_err();
8300 let ManifestError::CodePathDuplicate { slot, path } = err else {
8301 panic!("expected CodePathDuplicate, got {err:?}");
8302 };
8303 assert_eq!(slot, ":bibliotecas");
8304 assert_eq!(path, PathBuf::from("lib/x.lisp"));
8305 }
8306
8307 #[test]
8308 fn validate_code_paths_duplicate_diagnostic_carries_offending_slot_and_path() {
8309 // Diagnostic-shape pin (peer with
8310 // `validate_code_paths_diagnostic_carries_offending_slot_and_path`
8311 // on the structural arm): the duplicate-arm Display surfaces both
8312 // the offending `:slot` tag and the offending path verbatim, so a
8313 // `feira lint` run can render the diagnostic without re-parsing.
8314 let c = caixa_with_code_paths(
8315 vec![],
8316 vec![],
8317 vec![
8318 "servicos/demo.computeunit.yaml",
8319 "servicos/demo.computeunit.yaml",
8320 ],
8321 );
8322 let rendered = c.validate_code_paths().unwrap_err().to_string();
8323 assert!(
8324 rendered.contains(":servicos"),
8325 "diagnostic must name the offending slot: {rendered}",
8326 );
8327 assert!(
8328 rendered.contains("servicos/demo.computeunit.yaml"),
8329 "diagnostic must quote the offending path: {rendered}",
8330 );
8331 }
8332
8333 // ── validate_code_paths — `.lisp` extension gate on :bibliotecas ──
8334 //
8335 // The lifted [`crate::render::is_lisp_extension`] predicate (33cc830)
8336 // now gates `:bibliotecas` entries on the tatara-lisp-source file-type
8337 // contract. The `feira build` loop (`caixa-feira/src/cmd/build.rs:33`)
8338 // reads every declared `:bibliotecas` entry through `tatara_lisp::read`
8339 // at parse time — the same downstream consumer the peer `:behavior
8340 // :on-*` (c97815a, [`crate::BehaviorError::NonLispExtension`]) and
8341 // `:upgrade-from :state-change :script` (33cc830,
8342 // [`crate::UpgradeError::NonLispExtensionScript`]) axes route through.
8343 // `:exe` and `:servicos` are deliberately excluded — `:exe` is the
8344 // nix-built executable surface (`"exe/<name>"` shape per the canonical
8345 // [`crate::LayoutError::ExeOutsideDir`] error message and every
8346 // in-tree `caixa_with_code_paths` positive control), and `:servicos`
8347 // is the `.computeunit.yaml` ComputeUnit-CR axis.
8348
8349 #[test]
8350 fn validate_code_paths_rejects_no_extension_bibliotecas_entry() {
8351 // Canonical "I dragged the wrong file from the workspace tree"
8352 // footgun on the biblioteca axis. Without the gate `feira build`
8353 // hands the extensionless path to `tatara_lisp::read` and fails
8354 // with a parser-shaped diagnostic far from the source caixa.lisp,
8355 // with no field naming the offending `:bibliotecas` entry.
8356 for relpath in ["lib/demo", "demo", "lib/handlers/inner"] {
8357 let c = caixa_with_code_paths(vec![relpath], vec![], vec![]);
8358 let err = c.validate_code_paths().unwrap_err();
8359 let ManifestError::CodePathNonLispExtension { slot, path } = err else {
8360 panic!("expected CodePathNonLispExtension for {relpath:?}, got {err:?}");
8361 };
8362 assert_eq!(slot, ":bibliotecas");
8363 assert_eq!(path, PathBuf::from(relpath));
8364 }
8365 }
8366
8367 #[test]
8368 fn validate_code_paths_rejects_wrong_extension_bibliotecas_entry() {
8369 // Wrong-extension sweep across common authoring footguns. Same
8370 // sweep posture as the peer
8371 // `behavior::validate_rejects_wrong_extension` (c97815a) and
8372 // `upgrade::tests::state_change_rejects_wrong_extension_script`
8373 // (33cc830) cases.
8374 for relpath in [
8375 "lib/demo.rs",
8376 "lib/demo.txt",
8377 "lib/demo.md",
8378 "lib/demo.json",
8379 "lib/demo.yaml",
8380 "lib/demo.toml",
8381 "lib/demo.lisp.bak",
8382 "lib/demo.lispx",
8383 "lib/demo.lis",
8384 ] {
8385 let c = caixa_with_code_paths(vec![relpath], vec![], vec![]);
8386 let err = c.validate_code_paths().unwrap_err();
8387 let ManifestError::CodePathNonLispExtension { slot, path } = err else {
8388 panic!("expected CodePathNonLispExtension for {relpath:?}, got {err:?}");
8389 };
8390 assert_eq!(slot, ":bibliotecas");
8391 assert_eq!(path, PathBuf::from(relpath));
8392 }
8393 }
8394
8395 #[test]
8396 fn validate_code_paths_rejects_case_folded_extension_bibliotecas_entry() {
8397 // Case-sensitivity sweep — pins the strict lowercase `.lisp`
8398 // contract. An uppercase `.LISP` shape that the layout's existence
8399 // check would (case-insensitively, on case-insensitive volumes)
8400 // match the on-disk file still mismatches the canonical form the
8401 // codec emits, breaking the THEORY.md §V.2.7 render-determinism
8402 // contract. Mirrors the peer
8403 // `behavior::validate_rejects_case_folded_extension` (c97815a) and
8404 // `upgrade::tests::state_change_rejects_case_folded_extension_script`
8405 // (33cc830) sweeps.
8406 for relpath in [
8407 "lib/demo.LISP",
8408 "lib/demo.Lisp",
8409 "lib/demo.LiSp",
8410 "lib/demo.lISP",
8411 ] {
8412 let c = caixa_with_code_paths(vec![relpath], vec![], vec![]);
8413 let err = c.validate_code_paths().unwrap_err();
8414 let ManifestError::CodePathNonLispExtension { slot, path } = err else {
8415 panic!("expected CodePathNonLispExtension for {relpath:?}, got {err:?}");
8416 };
8417 assert_eq!(slot, ":bibliotecas");
8418 assert_eq!(path, PathBuf::from(relpath));
8419 }
8420 }
8421
8422 #[test]
8423 fn validate_code_paths_accepts_canonical_lisp_shapes() {
8424 // Positive-control sweep through every canonical authoring shape
8425 // every in-tree fixture and the `Caixa::template` scaffold use.
8426 // Mirrors the peer `behavior::validate_accepts_canonical_lisp_paths`
8427 // (c97815a) and the lifted predicate's own
8428 // `is_lisp_extension_accepts_canonical_shapes` sweep in render.rs
8429 // (33cc830).
8430 for relpath in [
8431 "lib/demo.lisp",
8432 "lib/handlers.lisp",
8433 "lib/migrations/v01-to-v02.lisp",
8434 "demo.lisp",
8435 "a.lisp",
8436 "./lib/demo.lisp",
8437 "lib/./handlers.lisp",
8438 "lib/migrations/v.0.1.lisp",
8439 ] {
8440 let c = caixa_with_code_paths(vec![relpath], vec![], vec![]);
8441 c.validate_code_paths()
8442 .unwrap_or_else(|e| panic!("canonical shape {relpath:?} must pass, got {e:?}"));
8443 }
8444 }
8445
8446 #[test]
8447 fn validate_code_paths_non_lisp_extension_does_not_fire_on_exe_or_servicos() {
8448 // The file-type gate is per-slot — only `:bibliotecas` carries the
8449 // tatara-lisp-source contract. An extensionless `:exe` entry
8450 // (`exe/demo`) and a `.computeunit.yaml` `:servicos` entry are the
8451 // canonical shapes every in-tree fixture uses, and must continue
8452 // to pass validate. Pins that a future tightening that broadens
8453 // the `.lisp` gate to either axis surfaces as a test failure
8454 // rather than as a silent breaking change to existing valid
8455 // manifests.
8456 let c = caixa_with_code_paths(
8457 vec![],
8458 vec!["exe/demo", "exe/tool"],
8459 vec!["servicos/demo.computeunit.yaml"],
8460 );
8461 c.validate_code_paths().unwrap();
8462 }
8463
8464 #[test]
8465 fn validate_code_paths_sandbox_shape_arms_precede_non_lisp_extension() {
8466 // Cross-arm precedence pin: a `:bibliotecas` entry that is *both*
8467 // sandbox-escaping and non-`.lisp` surfaces the more fundamental
8468 // sandbox-shape diagnostic first (the `.lisp` remediation would
8469 // be misleading when the offending path can never resolve under
8470 // the caixa root anyway). Mirrors the peer
8471 // `EmptyPath` → `AbsolutePath` → `ParentEscape` → `NonLispExtension`
8472 // ordering on `:behavior :on-*` (c97815a) and `EmptyScript` →
8473 // `AbsoluteScript` → `ParentEscapeScript` → `NonLispExtensionScript`
8474 // on `:upgrade-from :state-change :script` (33cc830).
8475 //
8476 // Empty wins (the strictly-smaller-scope structural arm).
8477 let c = caixa_with_code_paths(vec![""], vec![], vec![]);
8478 assert!(
8479 matches!(
8480 c.validate_code_paths().unwrap_err(),
8481 ManifestError::CodePathEmpty {
8482 slot: ":bibliotecas"
8483 }
8484 ),
8485 "empty must win over non-lisp-extension",
8486 );
8487 // Absolute wins (the path can't resolve under the caixa root).
8488 let c = caixa_with_code_paths(vec!["/etc/passwd"], vec![], vec![]);
8489 let err = c.validate_code_paths().unwrap_err();
8490 let ManifestError::CodePathAbsolute { slot, .. } = err else {
8491 panic!("absolute must win over non-lisp-extension, got {err:?}");
8492 };
8493 assert_eq!(slot, ":bibliotecas");
8494 // ParentEscape wins (the path escapes the caixa root).
8495 let c = caixa_with_code_paths(vec!["../sibling/x.txt"], vec![], vec![]);
8496 let err = c.validate_code_paths().unwrap_err();
8497 let ManifestError::CodePathParentEscape { slot, .. } = err else {
8498 panic!("parent-escape must win over non-lisp-extension, got {err:?}");
8499 };
8500 assert_eq!(slot, ":bibliotecas");
8501 }
8502
8503 #[test]
8504 fn validate_code_paths_non_lisp_extension_precedes_duplicate() {
8505 // Within-slot precedence pin: the per-entry file-type shape gate
8506 // fires before the cross-entry duplicate gate, so the narrower
8507 // structural defect dominates the uniqueness diagnostic. A
8508 // `("lib/x.txt" "lib/x.txt")` shape surfaces
8509 // `CodePathNonLispExtension` on the first entry rather than
8510 // `CodePathDuplicate` on the pair — same posture every per-entry
8511 // shape-gate-precedes-duplicate cascade follows on this surface
8512 // (the empty / absolute / parent-escape arms already precede the
8513 // duplicate arm; the lifted file-type arm joins that set).
8514 let c = caixa_with_code_paths(vec!["lib/x.txt", "lib/x.txt"], vec![], vec![]);
8515 let err = c.validate_code_paths().unwrap_err();
8516 let ManifestError::CodePathNonLispExtension { slot, path } = err else {
8517 panic!("expected CodePathNonLispExtension, got {err:?}");
8518 };
8519 assert_eq!(slot, ":bibliotecas");
8520 assert_eq!(path, PathBuf::from("lib/x.txt"));
8521 }
8522
8523 #[test]
8524 fn validate_code_paths_non_lisp_extension_diagnostic_carries_offending_slot_and_path() {
8525 // Diagnostic-shape pin (peer with
8526 // `validate_code_paths_diagnostic_carries_offending_slot_and_path`
8527 // on the sandbox-shape arms and
8528 // `validate_code_paths_duplicate_diagnostic_carries_offending_slot_and_path`
8529 // on the duplicate arm): the file-type-arm Display surfaces both
8530 // the offending `:slot` tag, the offending path verbatim, and the
8531 // expected `.lisp` extension named in the remediation text, so a
8532 // `feira lint` run can render the diagnostic without re-parsing.
8533 let c = caixa_with_code_paths(vec!["lib/demo.rs"], vec![], vec![]);
8534 let rendered = c.validate_code_paths().unwrap_err().to_string();
8535 assert!(
8536 rendered.contains(":bibliotecas"),
8537 "diagnostic must name the offending slot: {rendered}",
8538 );
8539 assert!(
8540 rendered.contains("lib/demo.rs"),
8541 "diagnostic must quote the offending path: {rendered}",
8542 );
8543 assert!(
8544 rendered.contains(".lisp"),
8545 "diagnostic must name the expected extension: {rendered}",
8546 );
8547 }
8548
8549 // ── validate_code_paths — `.computeunit.yaml` compound-suffix gate on :servicos ──
8550 //
8551 // The lifted [`crate::render::is_computeunit_yaml_extension`] predicate
8552 // now gates `:servicos` entries on the ComputeUnit-CR YAML file-type
8553 // contract. The peer caixa-helm / caixa-flux renderers consume each
8554 // `:servicos` entry through `serde_yaml::from_str` as a typed
8555 // `ComputeUnit` CR — same downstream-consumer-shape lift as the peer
8556 // `:bibliotecas` `.lisp` gate (64772a9), here on the compound-suffix
8557 // axis `Path::extension` can't express on its own.
8558
8559 #[test]
8560 fn validate_code_paths_rejects_no_extension_servicos_entry() {
8561 // Canonical "I dragged the wrong file from the workspace tree"
8562 // footgun on the Servico axis. Without the gate the peer
8563 // caixa-helm / caixa-flux renderers hand the extensionless path
8564 // to `serde_yaml::from_str` and fail with a parser-shaped
8565 // diagnostic far from the source caixa.lisp, with no field
8566 // naming the offending `:servicos` entry.
8567 for relpath in ["servicos/demo", "demo", "servicos/sub/nested"] {
8568 let c = caixa_with_code_paths(vec![], vec![], vec![relpath]);
8569 let err = c.validate_code_paths().unwrap_err();
8570 let ManifestError::CodePathNonComputeUnitYamlExtension { slot, path } = err else {
8571 panic!(
8572 "expected CodePathNonComputeUnitYamlExtension for {relpath:?}, \
8573 got {err:?}"
8574 );
8575 };
8576 assert_eq!(slot, ":servicos");
8577 assert_eq!(path, PathBuf::from(relpath));
8578 }
8579 }
8580
8581 #[test]
8582 fn validate_code_paths_rejects_wrong_extension_servicos_entry() {
8583 // Wrong-extension sweep across common authoring footguns on the
8584 // Servico axis. Bare `.yaml` is the canonical "I forgot the
8585 // `.computeunit` segment" typo; the off-by-one-segment shapes
8586 // (`.computeunit-yaml` / `.computeunit_yaml`) silently pass the
8587 // bare `Path::extension` view but mismatch the typed compound
8588 // suffix the renderers' `serde_yaml::from_str` consumer demands.
8589 // Same sweep-posture as the peer
8590 // `validate_code_paths_rejects_wrong_extension_bibliotecas_entry`
8591 // (64772a9) on the sibling tatara-lisp-source axis.
8592 for relpath in [
8593 "servicos/demo.yaml",
8594 "servicos/demo.yml",
8595 "servicos/demo.json",
8596 "servicos/demo.toml",
8597 "servicos/demo.txt",
8598 "servicos/demo.computeunit.yaml.bak",
8599 "servicos/demo.computeunit.yam",
8600 "servicos/demo.computeunit",
8601 "servicos/demo-computeunit.yaml",
8602 "servicos/demo_computeunit.yaml",
8603 ] {
8604 let c = caixa_with_code_paths(vec![], vec![], vec![relpath]);
8605 let err = c.validate_code_paths().unwrap_err();
8606 let ManifestError::CodePathNonComputeUnitYamlExtension { slot, path } = err else {
8607 panic!(
8608 "expected CodePathNonComputeUnitYamlExtension for {relpath:?}, \
8609 got {err:?}"
8610 );
8611 };
8612 assert_eq!(slot, ":servicos");
8613 assert_eq!(path, PathBuf::from(relpath));
8614 }
8615 }
8616
8617 #[test]
8618 fn validate_code_paths_rejects_case_folded_extension_servicos_entry() {
8619 // Case-sensitivity sweep — pins the strict lowercase
8620 // `.computeunit.yaml` contract. A case-folded shape that the
8621 // layout's existence check would (case-insensitively, on
8622 // case-insensitive volumes) match the on-disk file still
8623 // mismatches the canonical form the codec emits, breaking the
8624 // THEORY.md §V.2.7 render-determinism contract. Mirrors the peer
8625 // `validate_code_paths_rejects_case_folded_extension_bibliotecas_entry`
8626 // (64772a9) sweep on the sibling tatara-lisp-source axis.
8627 for relpath in [
8628 "servicos/demo.ComputeUnit.yaml",
8629 "servicos/demo.COMPUTEUNIT.yaml",
8630 "servicos/demo.computeunit.YAML",
8631 "servicos/demo.computeunit.Yaml",
8632 "servicos/demo.COMPUTEUNIT.YAML",
8633 ] {
8634 let c = caixa_with_code_paths(vec![], vec![], vec![relpath]);
8635 let err = c.validate_code_paths().unwrap_err();
8636 let ManifestError::CodePathNonComputeUnitYamlExtension { slot, path } = err else {
8637 panic!(
8638 "expected CodePathNonComputeUnitYamlExtension for {relpath:?}, \
8639 got {err:?}"
8640 );
8641 };
8642 assert_eq!(slot, ":servicos");
8643 assert_eq!(path, PathBuf::from(relpath));
8644 }
8645 }
8646
8647 #[test]
8648 fn validate_code_paths_rejects_empty_stem_servicos_entry() {
8649 // Degenerate hidden-file shape: a file name exactly equal to the
8650 // suffix (`.computeunit.yaml` — no stem preceding the suffix) is
8651 // the structural "Servico declared with no identity" footgun.
8652 // The substrate identifies each ComputeUnit by the file-stem
8653 // segment that precedes `.computeunit.yaml` (the rendered
8654 // `lareira-<stem>` Helm chart, the per-Servico `metadata.name`,
8655 // the M3 `:contratos` membership lookup), so an empty stem
8656 // leaves the Servico unidentifiable. Pinned at the typed-axis
8657 // level so a future regression that drops the `name.len() >
8658 // SUFFIX.len()` bound at the predicate surfaces here, not
8659 // piecemeal as a `lareira-` chart-name collision at render time.
8660 for relpath in ["servicos/.computeunit.yaml"] {
8661 let c = caixa_with_code_paths(vec![], vec![], vec![relpath]);
8662 let err = c.validate_code_paths().unwrap_err();
8663 let ManifestError::CodePathNonComputeUnitYamlExtension { slot, path } = err else {
8664 panic!(
8665 "expected CodePathNonComputeUnitYamlExtension for {relpath:?}, \
8666 got {err:?}"
8667 );
8668 };
8669 assert_eq!(slot, ":servicos");
8670 assert_eq!(path, PathBuf::from(relpath));
8671 }
8672 }
8673
8674 #[test]
8675 fn validate_code_paths_accepts_canonical_computeunit_yaml_shapes() {
8676 // Positive-control sweep through every canonical authoring shape
8677 // every in-tree fixture and the `Caixa::template` scaffold use.
8678 // Mirrors the peer
8679 // `validate_code_paths_accepts_canonical_lisp_shapes` (64772a9)
8680 // and the lifted predicate's own
8681 // `computeunit_yaml_extension_accepts_canonical_shapes` sweep in
8682 // render.rs.
8683 for relpath in [
8684 "servicos/demo.computeunit.yaml",
8685 "servicos/hello-rio.computeunit.yaml",
8686 "servicos/my-service.computeunit.yaml",
8687 "servicos/a.computeunit.yaml",
8688 "./servicos/demo.computeunit.yaml",
8689 "servicos/./demo.computeunit.yaml",
8690 "servicos/sub/nested.computeunit.yaml",
8691 "servicos/v0.1.computeunit.yaml",
8692 ] {
8693 let c = caixa_with_code_paths(vec![], vec![], vec![relpath]);
8694 c.validate_code_paths()
8695 .unwrap_or_else(|e| panic!("canonical shape {relpath:?} must pass, got {e:?}"));
8696 }
8697 }
8698
8699 #[test]
8700 fn validate_code_paths_non_computeunit_yaml_extension_does_not_fire_on_bibliotecas_or_exe() {
8701 // The file-type gate is per-slot — only `:servicos` carries the
8702 // ComputeUnit-CR YAML contract. A canonical `.lisp` `:bibliotecas`
8703 // entry and an extensionless `:exe` entry are the canonical
8704 // shapes every in-tree fixture uses, and must continue to pass
8705 // validate. Peer of
8706 // `validate_code_paths_non_lisp_extension_does_not_fire_on_exe_or_servicos`
8707 // (64772a9) — together pin that the typed
8708 // [`CodePathFileType`] dispatch is exhaustively per-slot, with no
8709 // cross-axis leakage in either direction.
8710 let c = caixa_with_code_paths(
8711 vec!["lib/demo.lisp"],
8712 vec!["exe/demo", "exe/tool"],
8713 vec!["servicos/demo.computeunit.yaml"],
8714 );
8715 c.validate_code_paths().unwrap();
8716 }
8717
8718 #[test]
8719 fn validate_code_paths_sandbox_shape_arms_precede_non_computeunit_yaml_extension() {
8720 // Cross-arm precedence pin: a `:servicos` entry that is *both*
8721 // sandbox-escaping and wrong-extension surfaces the more
8722 // fundamental sandbox-shape diagnostic first (the
8723 // `.computeunit.yaml` remediation would be misleading when the
8724 // offending path can never resolve under the caixa root
8725 // anyway). Mirrors the peer
8726 // `validate_code_paths_sandbox_shape_arms_precede_non_lisp_extension`
8727 // (64772a9) ordering on the sibling `:bibliotecas` axis and the
8728 // peer `EmptyPath` → `AbsolutePath` → `ParentEscape` →
8729 // `NonComputeUnitYamlExtension` arm-ordering the dispatch
8730 // table establishes.
8731 //
8732 // Empty wins (the strictly-smaller-scope structural arm).
8733 let c = caixa_with_code_paths(vec![], vec![], vec![""]);
8734 assert!(
8735 matches!(
8736 c.validate_code_paths().unwrap_err(),
8737 ManifestError::CodePathEmpty { slot: ":servicos" }
8738 ),
8739 "empty must win over non-computeunit-yaml-extension",
8740 );
8741 // Absolute wins (the path can't resolve under the caixa root).
8742 let c = caixa_with_code_paths(vec![], vec![], vec!["/etc/foo.yaml"]);
8743 let err = c.validate_code_paths().unwrap_err();
8744 let ManifestError::CodePathAbsolute { slot, .. } = err else {
8745 panic!("absolute must win over non-computeunit-yaml-extension, got {err:?}");
8746 };
8747 assert_eq!(slot, ":servicos");
8748 // ParentEscape wins (the path escapes the caixa root).
8749 let c = caixa_with_code_paths(vec![], vec![], vec!["../sibling/x.yaml"]);
8750 let err = c.validate_code_paths().unwrap_err();
8751 let ManifestError::CodePathParentEscape { slot, .. } = err else {
8752 panic!("parent-escape must win over non-computeunit-yaml-extension, got {err:?}");
8753 };
8754 assert_eq!(slot, ":servicos");
8755 }
8756
8757 #[test]
8758 fn validate_code_paths_non_computeunit_yaml_extension_precedes_duplicate() {
8759 // Within-slot precedence pin: the per-entry file-type shape gate
8760 // fires before the cross-entry duplicate gate, so the narrower
8761 // structural defect dominates the uniqueness diagnostic. A
8762 // `("servicos/x.yaml" "servicos/x.yaml")` shape surfaces
8763 // `CodePathNonComputeUnitYamlExtension` on the first entry
8764 // rather than `CodePathDuplicate` on the pair — same posture
8765 // every per-entry shape-gate-precedes-duplicate cascade follows
8766 // on this surface, peer of the 64772a9 `:bibliotecas`
8767 // `("lib/x.txt" "lib/x.txt")` ordering.
8768 let c = caixa_with_code_paths(vec![], vec![], vec!["servicos/x.yaml", "servicos/x.yaml"]);
8769 let err = c.validate_code_paths().unwrap_err();
8770 let ManifestError::CodePathNonComputeUnitYamlExtension { slot, path } = err else {
8771 panic!("expected CodePathNonComputeUnitYamlExtension, got {err:?}");
8772 };
8773 assert_eq!(slot, ":servicos");
8774 assert_eq!(path, PathBuf::from("servicos/x.yaml"));
8775 }
8776
8777 #[test]
8778 fn validate_code_paths_non_computeunit_yaml_extension_diagnostic_carries_offending_slot_and_path()
8779 {
8780 // Diagnostic-shape pin (peer with
8781 // `validate_code_paths_non_lisp_extension_diagnostic_carries_offending_slot_and_path`
8782 // on the sibling tatara-lisp-source axis): the file-type-arm
8783 // Display surfaces both the offending `:slot` tag, the
8784 // offending path verbatim, and the expected
8785 // `.computeunit.yaml` compound suffix named in the remediation
8786 // text, so a `feira lint` run can render the diagnostic without
8787 // re-parsing.
8788 let c = caixa_with_code_paths(vec![], vec![], vec!["servicos/demo.yaml"]);
8789 let rendered = c.validate_code_paths().unwrap_err().to_string();
8790 assert!(
8791 rendered.contains(":servicos"),
8792 "diagnostic must name the offending slot: {rendered}",
8793 );
8794 assert!(
8795 rendered.contains("servicos/demo.yaml"),
8796 "diagnostic must quote the offending path: {rendered}",
8797 );
8798 assert!(
8799 rendered.contains(".computeunit.yaml"),
8800 "diagnostic must name the expected compound suffix: {rendered}",
8801 );
8802 }
8803
8804 // ── validate_etiquetas — universal-axis registry-search-tag shape ──
8805
8806 fn caixa_with_etiquetas(etiquetas: Vec<&str>) -> Caixa {
8807 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
8808 c.etiquetas = etiquetas.into_iter().map(String::from).collect();
8809 c
8810 }
8811
8812 #[test]
8813 fn validate_etiquetas_accepts_empty_list() {
8814 // The empty-list identity: every caixa with no declared tags
8815 // trivially passes — `Caixa::template` emits `:etiquetas ()`,
8816 // so the gate is non-disruptive against every existing manifest.
8817 let c = caixa_with_etiquetas(vec![]);
8818 c.validate_etiquetas().unwrap();
8819 }
8820
8821 #[test]
8822 fn validate_etiquetas_accepts_canonical_forms() {
8823 // Positive control sweep: a canonical-shaped non-empty distinct
8824 // tag list passes, mirroring the example checkout-aplicacao
8825 // (`:etiquetas ("example" "aplicacao" "mesh" "ecommerce" "demo")`)
8826 // and the hello-rio fixture (`("hello-world" "wasm" "rust")`).
8827 let c = caixa_with_etiquetas(vec!["example", "aplicacao", "mesh", "ecommerce", "demo"]);
8828 c.validate_etiquetas().unwrap();
8829 }
8830
8831 #[test]
8832 fn validate_etiquetas_rejects_empty_entry() {
8833 // Canonical paste-from-blank-doc footgun. Without the gate the
8834 // empty entry rendered as `keywords: [""]` in `Chart.yaml`, a
8835 // no-op tag indexing nothing in the future caixa-registry.
8836 let c = caixa_with_etiquetas(vec![""]);
8837 let err = c.validate_etiquetas().unwrap_err();
8838 assert!(matches!(err, ManifestError::EtiquetaEmpty), "got {err:?}",);
8839 }
8840
8841 #[test]
8842 fn validate_etiquetas_rejects_duplicate_entry() {
8843 // Canonical copy-paste-the-wrong-tag footgun. Without the gate
8844 // the duplicate was silently dedup'd by caixa-helm's BTreeSet
8845 // collect at chart render — a "second wins / one silently
8846 // disappears" shape divergent from every peer typed-graph set
8847 // gate. The duplicate-arm names the offending tag verbatim.
8848 let c = caixa_with_etiquetas(vec!["demo", "demo"]);
8849 let err = c.validate_etiquetas().unwrap_err();
8850 let ManifestError::EtiquetaDuplicate { etiqueta } = err else {
8851 panic!("expected EtiquetaDuplicate, got {err:?}");
8852 };
8853 assert_eq!(etiqueta, "demo");
8854 }
8855
8856 #[test]
8857 fn validate_etiquetas_empty_takes_precedence_over_duplicate() {
8858 // Empty-first cascade pin: `("" "demo" "demo")` surfaces
8859 // `EtiquetaEmpty` not `EtiquetaDuplicate` — the narrower
8860 // structural "this entry has no value" defect dominates the
8861 // cross-entry uniqueness diagnostic. Mirrors the peer
8862 // empty-before-duplicate cascades on `:caracteristicas`
8863 // (`CaracteristicaEmpty` before `CaracteristicaDuplicate`,
8864 // fc3b4d5) and `:membros :caixa` (`MembroCaixaEmpty` before
8865 // `MembroDuplicate`).
8866 let c = caixa_with_etiquetas(vec!["", "demo", "demo"]);
8867 let err = c.validate_etiquetas().unwrap_err();
8868 assert!(matches!(err, ManifestError::EtiquetaEmpty), "got {err:?}",);
8869 }
8870
8871 #[test]
8872 fn validate_etiquetas_duplicate_reports_first_collision() {
8873 // First-collision pin: `("a" "b" "a" "b")` surfaces the `"a"`
8874 // duplicate (the lexicographically-earliest offending position
8875 // — the second `"a"` at index 2 collides with the first `"a"`
8876 // at index 0), not the later `"b"` collision at index 3,
8877 // peer with every other first-collision diagnostic posture on
8878 // this surface (`validate_load_singularity_reports_first_collision`,
8879 // `validate_cleanup_singularity_reports_first_collision`).
8880 let c = caixa_with_etiquetas(vec!["a", "b", "a", "b"]);
8881 let err = c.validate_etiquetas().unwrap_err();
8882 let ManifestError::EtiquetaDuplicate { etiqueta } = err else {
8883 panic!("expected EtiquetaDuplicate, got {err:?}");
8884 };
8885 assert_eq!(etiqueta, "a");
8886 }
8887
8888 #[test]
8889 fn validate_etiquetas_case_sensitive() {
8890 // Case-sensitivity pin: `("Foo" "foo")` is two distinct entries,
8891 // mirroring the peer `:membros :caixa` / `:children :caixa`
8892 // exact-string-match discipline. The shape gate this routine
8893 // landed (`is_chart_keyword_shape`, Cargo crates.io keyword
8894 // grammar) accepts mixed case — crates.io's keyword rule is
8895 // "case-insensitive" at the index layer but admits mixed case
8896 // at the entry layer (the canonical Helm chart `keywords:`
8897 // shape is lowercase by convention, but the grammar admits
8898 // uppercase). Case-sensitivity at the duplicate-set layer
8899 // remains structural — two distinct strings are two distinct
8900 // entries.
8901 let c = caixa_with_etiquetas(vec!["Foo", "foo"]);
8902 c.validate_etiquetas().unwrap();
8903 }
8904
8905 #[test]
8906 fn validate_etiquetas_diagnostic_carries_offending_tag() {
8907 // Diagnostic-shape pin (peer with
8908 // `validate_code_paths_diagnostic_carries_offending_slot_and_path`):
8909 // the error's Display surfaces the offending tag verbatim, so a
8910 // `feira lint` run can render the diagnostic without re-parsing
8911 // and the author can grep their caixa.lisp for the offending
8912 // value.
8913 let c = caixa_with_etiquetas(vec!["demo", "demo"]);
8914 let rendered = c.validate_etiquetas().unwrap_err().to_string();
8915 assert!(
8916 rendered.contains(":etiquetas"),
8917 "diagnostic must name the offending slot: {rendered}",
8918 );
8919 assert!(
8920 rendered.contains("demo"),
8921 "diagnostic must quote the offending tag: {rendered}",
8922 );
8923 }
8924
8925 #[test]
8926 fn validate_etiquetas_rejects_leading_whitespace_entry() {
8927 // Canonical paste-from-aligned-doc footgun. Without the shape
8928 // gate `" mesh"` silently passed validate and landed as a
8929 // YAML plain-style scalar with leading whitespace in the
8930 // rendered Chart.yaml `keywords:` array — every YAML 1.2
8931 // dumper trims leading whitespace from plain-style scalars,
8932 // so the authored space round-tripped inconsistently back
8933 // through `caixa.lisp`. Mirrors the peer
8934 // `validate_autores_rejects_leading_whitespace_entry`.
8935 let c = caixa_with_etiquetas(vec![" mesh"]);
8936 let err = c.validate_etiquetas().unwrap_err();
8937 let ManifestError::EtiquetaInvalid { etiqueta, reason } = err else {
8938 panic!("expected EtiquetaInvalid, got {err:?}");
8939 };
8940 assert_eq!(etiqueta, " mesh");
8941 assert!(reason.contains("whitespace"), "got: {reason}");
8942 }
8943
8944 #[test]
8945 fn validate_etiquetas_rejects_embedded_newline_entry() {
8946 // Canonical paste-from-multiline-doc footgun — the author
8947 // pasted a multi-tag block into one `:etiquetas` entry
8948 // instead of splitting into one entry per tag. Without the
8949 // shape gate `"mesh\nhttp"` silently passed validate and
8950 // landed as a YAML-illegal multi-line scalar in the rendered
8951 // Chart.yaml `keywords:` array.
8952 let c = caixa_with_etiquetas(vec!["mesh\nhttp"]);
8953 let err = c.validate_etiquetas().unwrap_err();
8954 let ManifestError::EtiquetaInvalid { etiqueta, reason } = err else {
8955 panic!("expected EtiquetaInvalid, got {err:?}");
8956 };
8957 assert_eq!(etiqueta, "mesh\nhttp");
8958 assert!(reason.contains("newline"), "got: {reason}");
8959 }
8960
8961 #[test]
8962 fn validate_etiquetas_rejects_embedded_comma_entry() {
8963 // Canonical CSV-list-separator-confusion footgun: the author
8964 // confused the CSV-style separator convention with the
8965 // `:etiquetas` list grammar. Without the shape gate
8966 // `"mesh,http,grpc"` silently passed validate and landed as a
8967 // single malformed search tag in the rendered Chart.yaml
8968 // `keywords:` array — Artifact Hub's keyword index would
8969 // either silently drop the tag or index it as
8970 // `mesh,http,grpc` instead of three separate tags.
8971 let c = caixa_with_etiquetas(vec!["mesh,http,grpc"]);
8972 let err = c.validate_etiquetas().unwrap_err();
8973 let ManifestError::EtiquetaInvalid { etiqueta, reason } = err else {
8974 panic!("expected EtiquetaInvalid, got {err:?}");
8975 };
8976 assert_eq!(etiqueta, "mesh,http,grpc");
8977 assert!(reason.contains('`'), "got: {reason}");
8978 assert!(reason.contains(','), "got: {reason}");
8979 }
8980
8981 #[test]
8982 fn validate_etiquetas_rejects_embedded_slash_entry() {
8983 // Canonical path-separator-confusion footgun: the author
8984 // confused namespace-path notation with the keyword grammar.
8985 let c = caixa_with_etiquetas(vec!["caixa/servico"]);
8986 let err = c.validate_etiquetas().unwrap_err();
8987 let ManifestError::EtiquetaInvalid { etiqueta, reason } = err else {
8988 panic!("expected EtiquetaInvalid, got {err:?}");
8989 };
8990 assert_eq!(etiqueta, "caixa/servico");
8991 assert!(reason.contains('/'), "got: {reason}");
8992 }
8993
8994 #[test]
8995 fn validate_etiquetas_rejects_leading_digit_entry() {
8996 // Canonical paste-from-numbered-list footgun: the author
8997 // copied `1. mesh` from a numbered doc and the `1` leaked
8998 // into the tag.
8999 let c = caixa_with_etiquetas(vec!["1mesh"]);
9000 let err = c.validate_etiquetas().unwrap_err();
9001 let ManifestError::EtiquetaInvalid { etiqueta, reason } = err else {
9002 panic!("expected EtiquetaInvalid, got {err:?}");
9003 };
9004 assert_eq!(etiqueta, "1mesh");
9005 assert!(reason.contains("digit"), "got: {reason}");
9006 }
9007
9008 #[test]
9009 fn validate_etiquetas_rejects_leading_hyphen_entry() {
9010 // Canonical kebab-leak footgun.
9011 let c = caixa_with_etiquetas(vec!["-foo"]);
9012 let err = c.validate_etiquetas().unwrap_err();
9013 let ManifestError::EtiquetaInvalid { etiqueta, reason } = err else {
9014 panic!("expected EtiquetaInvalid, got {err:?}");
9015 };
9016 assert_eq!(etiqueta, "-foo");
9017 assert!(reason.contains('-'), "got: {reason}");
9018 }
9019
9020 #[test]
9021 fn validate_etiquetas_rejects_non_ascii_entry() {
9022 // Canonical paste-from-Unicode-doc footgun. Every legitimate
9023 // search tag is strict ASCII; raw non-ASCII silently
9024 // round-trips inconsistently across NFC/NFD normalization on
9025 // APFS / case-folding filesystems and breaks the Artifact Hub
9026 // keyword search index lookup.
9027 let c = caixa_with_etiquetas(vec!["café"]);
9028 let err = c.validate_etiquetas().unwrap_err();
9029 let ManifestError::EtiquetaInvalid { etiqueta, reason } = err else {
9030 panic!("expected EtiquetaInvalid, got {err:?}");
9031 };
9032 assert_eq!(etiqueta, "café");
9033 assert!(reason.contains("non-ASCII"), "got: {reason}");
9034 }
9035
9036 #[test]
9037 fn validate_etiquetas_rejects_period_entry() {
9038 // Canonical namespace-confusion / version-suffix footgun
9039 // (`"http.1"` / `"v1.0"`): Cargo's crates.io keyword grammar
9040 // excludes `.` from the continuation set even though the
9041 // sibling `:caracteristicas` axis (Cargo's feature-name
9042 // grammar) admits it. Tighter than the sibling axis, peer
9043 // with Cargo's own crates.io keyword shape.
9044 let c = caixa_with_etiquetas(vec!["http.1"]);
9045 let err = c.validate_etiquetas().unwrap_err();
9046 let ManifestError::EtiquetaInvalid { etiqueta, reason } = err else {
9047 panic!("expected EtiquetaInvalid, got {err:?}");
9048 };
9049 assert_eq!(etiqueta, "http.1");
9050 assert!(reason.contains('.'), "got: {reason}");
9051 }
9052
9053 #[test]
9054 fn validate_etiquetas_empty_takes_precedence_over_shape() {
9055 // Per-entry empty-first cascade pin: an entry that is both
9056 // empty *and* shape-invalid surfaces `EtiquetaEmpty` (the
9057 // narrower "this entry has no value" structural defect
9058 // dominates the broader shape-predicate diagnostic). The
9059 // empty arm fires before the shape predicate is consulted,
9060 // mirroring the peer `validate_autores_empty_takes_precedence_over_shape`
9061 // cascade established on the sibling universal-axis Vec<String>
9062 // surface.
9063 let c = caixa_with_etiquetas(vec![""]);
9064 let err = c.validate_etiquetas().unwrap_err();
9065 assert!(matches!(err, ManifestError::EtiquetaEmpty), "got {err:?}",);
9066 }
9067
9068 #[test]
9069 fn validate_etiquetas_shape_takes_precedence_over_duplicate() {
9070 // Per-entry shape-before-cross-entry-duplicate cascade pin: an
9071 // entry that is malformed surfaces `EtiquetaInvalid` even when
9072 // a later entry would have collided on duplicate. The
9073 // per-entry shape arm fires inside the same loop iteration as
9074 // the empty arm, before the seen-set insert at end-of-iteration
9075 // — structural per-entry defects dominate the cross-entry
9076 // uniqueness diagnostic. Mirrors the peer
9077 // `validate_autores_shape_takes_precedence_over_duplicate`.
9078 let c = caixa_with_etiquetas(vec!["mesh\nhttp", "mesh\nhttp"]);
9079 let err = c.validate_etiquetas().unwrap_err();
9080 assert!(
9081 matches!(err, ManifestError::EtiquetaInvalid { .. }),
9082 "got {err:?}",
9083 );
9084 }
9085
9086 #[test]
9087 fn validate_etiquetas_invalid_diagnostic_names_offending_slot_and_value() {
9088 // Diagnostic-shape pin on the new shape arm (peer with
9089 // `validate_autores_invalid_diagnostic_names_offending_slot_and_value`):
9090 // the rendered Display surfaces both the offending slot name
9091 // and the offending value verbatim, so a `feira lint` run
9092 // points the author at the exact `:etiquetas` entry to fix.
9093 let c = caixa_with_etiquetas(vec!["mesh\nhttp"]);
9094 let rendered = c.validate_etiquetas().unwrap_err().to_string();
9095 assert!(
9096 rendered.contains(":etiquetas"),
9097 "diagnostic must name the offending slot: {rendered}",
9098 );
9099 assert!(
9100 rendered.contains("mesh\\nhttp"),
9101 "diagnostic must quote the offending value (debug-escaped): {rendered}",
9102 );
9103 }
9104
9105 #[test]
9106 fn validate_etiquetas_rejects_at_21_byte_boundary() {
9107 // The 20-byte cap pin — boundary-exceeding case rejected,
9108 // boundary-accepting case passes. Mirrors the peer
9109 // `chart_keyword_shape_rejects_at_21_byte_boundary` substrate-
9110 // side pin, surfaced at the per-axis caller so the cap
9111 // propagates through validate end-to-end. Constructed as a
9112 // single all-`a` token so only the cap arm fires.
9113 let max_ok = "a".repeat(20);
9114 let c = caixa_with_etiquetas(vec![max_ok.as_str()]);
9115 c.validate_etiquetas().unwrap();
9116 let too_long = "a".repeat(21);
9117 let c = caixa_with_etiquetas(vec![too_long.as_str()]);
9118 let err = c.validate_etiquetas().unwrap_err();
9119 let ManifestError::EtiquetaInvalid { reason, .. } = err else {
9120 panic!("expected EtiquetaInvalid, got {err:?}");
9121 };
9122 assert!(reason.contains("20"), "got: {reason}");
9123 assert!(reason.contains("21"), "got: {reason}");
9124 }
9125
9126 #[test]
9127 fn validate_etiquetas_accepts_canonical_shaped_forms() {
9128 // Positive control sweep: every canonical-shaped tag from the
9129 // hello-rio / checkout-aplicacao / pangea-tatara-akeyless
9130 // example fixtures plus the substrate-fixed tags caixa-helm
9131 // unions in at chart render. Drift between this list and the
9132 // substrate-side `chart_keyword_shape_accepts_canonical_forms`
9133 // sweep surfaces here — one source of truth for the rule.
9134 let c = caixa_with_etiquetas(vec![
9135 "example",
9136 "aplicacao",
9137 "mesh",
9138 "ecommerce",
9139 "demo",
9140 "infrastructure",
9141 "aws",
9142 "akeyless",
9143 "pangea-native",
9144 "hello-world",
9145 "wasm",
9146 "rust",
9147 "tatara-lisp",
9148 "caixa-servico",
9149 "lareira",
9150 ]);
9151 c.validate_etiquetas().unwrap();
9152 }
9153
9154 // ── validate_autores — universal-axis maintainer shape ────────────
9155
9156 fn caixa_with_autores(autores: Vec<&str>) -> Caixa {
9157 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
9158 c.autores = autores.into_iter().map(String::from).collect();
9159 c
9160 }
9161
9162 #[test]
9163 fn validate_autores_accepts_empty_list() {
9164 // The empty-list identity: `Caixa::template` emits `:autores ()`,
9165 // so the gate is non-disruptive against every existing manifest.
9166 let c = caixa_with_autores(vec![]);
9167 c.validate_autores().unwrap();
9168 }
9169
9170 #[test]
9171 fn validate_autores_accepts_canonical_forms() {
9172 // Positive control sweep: every canonical-shaped non-empty
9173 // distinct maintainer list passes — the hello-rio / checkout-
9174 // aplicacao fixtures' `:autores ("pleme-io")` shape, plus the
9175 // multi-author shape downstream packaging surfaces emit.
9176 let c = caixa_with_autores(vec!["pleme-io"]);
9177 c.validate_autores().unwrap();
9178 let c = caixa_with_autores(vec!["alice <alice@example.com>", "bob <bob@example.com>"]);
9179 c.validate_autores().unwrap();
9180 }
9181
9182 #[test]
9183 fn validate_autores_rejects_empty_entry() {
9184 // Canonical paste-from-blank-doc footgun. Without the gate the
9185 // empty entry rendered as `maintainers: [{name: "", email: null}]`
9186 // in `Chart.yaml`, a no-op maintainer the substrate cannot route
9187 // to.
9188 let c = caixa_with_autores(vec![""]);
9189 let err = c.validate_autores().unwrap_err();
9190 assert!(matches!(err, ManifestError::AutorEmpty), "got {err:?}",);
9191 }
9192
9193 #[test]
9194 fn validate_autores_rejects_duplicate_entry() {
9195 // Canonical copy-paste-the-wrong-author footgun. Unlike the
9196 // `:etiquetas` peer (caixa-helm's `BTreeSet` collect silently
9197 // dedups the rendered `keywords:` array), the `maintainers:`
9198 // rendering has *no* dedup — duplicates stack verbatim. The
9199 // duplicate-arm names the offending author verbatim.
9200 let c = caixa_with_autores(vec!["pleme-io", "pleme-io"]);
9201 let err = c.validate_autores().unwrap_err();
9202 let ManifestError::AutorDuplicate { autor } = err else {
9203 panic!("expected AutorDuplicate, got {err:?}");
9204 };
9205 assert_eq!(autor, "pleme-io");
9206 }
9207
9208 #[test]
9209 fn validate_autores_empty_takes_precedence_over_duplicate() {
9210 // Empty-first cascade pin: `("" "pleme-io" "pleme-io")` surfaces
9211 // `AutorEmpty` not `AutorDuplicate` — the narrower structural
9212 // "this entry has no value" defect dominates the cross-entry
9213 // uniqueness diagnostic. Mirrors the peer empty-before-duplicate
9214 // cascades on `:etiquetas` (`EtiquetaEmpty` before
9215 // `EtiquetaDuplicate`, 360a499), `:caracteristicas`
9216 // (`CaracteristicaEmpty` before `CaracteristicaDuplicate`,
9217 // fc3b4d5), and `:membros :caixa` (`MembroCaixaEmpty` before
9218 // `MembroDuplicate`).
9219 let c = caixa_with_autores(vec!["", "pleme-io", "pleme-io"]);
9220 let err = c.validate_autores().unwrap_err();
9221 assert!(matches!(err, ManifestError::AutorEmpty), "got {err:?}",);
9222 }
9223
9224 #[test]
9225 fn validate_autores_duplicate_reports_first_collision() {
9226 // First-collision pin: `("a" "b" "a" "b")` surfaces the `"a"`
9227 // duplicate (the lexicographically-earliest offending position
9228 // — the second `"a"` at index 2 collides with the first `"a"`
9229 // at index 0), not the later `"b"` collision at index 3,
9230 // peer with every other first-collision diagnostic posture on
9231 // this surface.
9232 let c = caixa_with_autores(vec!["a", "b", "a", "b"]);
9233 let err = c.validate_autores().unwrap_err();
9234 let ManifestError::AutorDuplicate { autor } = err else {
9235 panic!("expected AutorDuplicate, got {err:?}");
9236 };
9237 assert_eq!(autor, "a");
9238 }
9239
9240 #[test]
9241 fn validate_autores_case_sensitive() {
9242 // Case-sensitivity pin: `("Pleme-io" "pleme-io")` is two distinct
9243 // entries, mirroring the peer `:etiquetas` / `:membros :caixa`
9244 // / `:children :caixa` exact-string-match discipline.
9245 let c = caixa_with_autores(vec!["Pleme-io", "pleme-io"]);
9246 c.validate_autores().unwrap();
9247 }
9248
9249 #[test]
9250 fn validate_autores_diagnostic_carries_offending_author() {
9251 // Diagnostic-shape pin (peer with
9252 // `validate_etiquetas_diagnostic_carries_offending_tag`): the
9253 // error's Display surfaces the offending author verbatim, so a
9254 // `feira lint` run can render the diagnostic without re-parsing
9255 // and the author can grep their caixa.lisp for the offending
9256 // value.
9257 let c = caixa_with_autores(vec!["pleme-io", "pleme-io"]);
9258 let rendered = c.validate_autores().unwrap_err().to_string();
9259 assert!(
9260 rendered.contains(":autores"),
9261 "diagnostic must name the offending slot: {rendered}",
9262 );
9263 assert!(
9264 rendered.contains("pleme-io"),
9265 "diagnostic must quote the offending author: {rendered}",
9266 );
9267 }
9268
9269 #[test]
9270 fn validate_autores_rejects_leading_whitespace_entry() {
9271 // Canonical paste-from-aligned-doc footgun. Without the shape
9272 // gate `" pleme-io"` silently passed validate and landed as a
9273 // YAML plain-style scalar with leading whitespace in the
9274 // rendered Chart.yaml `maintainers:` array — every YAML 1.2
9275 // dumper trims leading whitespace from plain-style scalars, so
9276 // the authored space round-tripped inconsistently back through
9277 // `caixa.lisp`. Mirrors the peer
9278 // `validate_descricao_rejects_leading_whitespace`.
9279 let c = caixa_with_autores(vec![" pleme-io"]);
9280 let err = c.validate_autores().unwrap_err();
9281 let ManifestError::AutorInvalid { autor, reason } = err else {
9282 panic!("expected AutorInvalid, got {err:?}");
9283 };
9284 assert_eq!(autor, " pleme-io");
9285 assert!(reason.contains("whitespace"), "got: {reason}");
9286 }
9287
9288 #[test]
9289 fn validate_autores_rejects_trailing_whitespace_entry() {
9290 // Canonical paste-from-doc footgun.
9291 let c = caixa_with_autores(vec!["pleme-io "]);
9292 let err = c.validate_autores().unwrap_err();
9293 let ManifestError::AutorInvalid { autor, reason } = err else {
9294 panic!("expected AutorInvalid, got {err:?}");
9295 };
9296 assert_eq!(autor, "pleme-io ");
9297 assert!(reason.contains("whitespace"), "got: {reason}");
9298 }
9299
9300 #[test]
9301 fn validate_autores_rejects_embedded_newline_entry() {
9302 // Canonical paste-from-multiline-doc footgun — the author
9303 // pasted a multi-line block of author records into one
9304 // `:autores` entry instead of splitting into one entry per
9305 // author. Without the shape gate `"alice\nbob"` silently
9306 // passed validate and landed as a YAML-illegal multi-line
9307 // scalar in the rendered Chart.yaml `maintainers:` array.
9308 let c = caixa_with_autores(vec!["alice\nbob"]);
9309 let err = c.validate_autores().unwrap_err();
9310 let ManifestError::AutorInvalid { autor, reason } = err else {
9311 panic!("expected AutorInvalid, got {err:?}");
9312 };
9313 assert_eq!(autor, "alice\nbob");
9314 assert!(reason.contains("newline"), "got: {reason}");
9315 }
9316
9317 #[test]
9318 fn validate_autores_rejects_embedded_carriage_return_entry() {
9319 // Canonical paste-from-Windows-CRLF-doc footgun.
9320 let c = caixa_with_autores(vec!["alice\rbob"]);
9321 let err = c.validate_autores().unwrap_err();
9322 let ManifestError::AutorInvalid { autor, reason } = err else {
9323 panic!("expected AutorInvalid, got {err:?}");
9324 };
9325 assert_eq!(autor, "alice\rbob");
9326 assert!(reason.contains("carriage return"), "got: {reason}");
9327 }
9328
9329 #[test]
9330 fn validate_autores_rejects_embedded_tab_entry() {
9331 // Canonical tab-from-aligned-doc footgun.
9332 let c = caixa_with_autores(vec!["Pleme\tContributors"]);
9333 let err = c.validate_autores().unwrap_err();
9334 let ManifestError::AutorInvalid { autor, reason } = err else {
9335 panic!("expected AutorInvalid, got {err:?}");
9336 };
9337 assert_eq!(autor, "Pleme\tContributors");
9338 assert!(reason.contains("tab"), "got: {reason}");
9339 }
9340
9341 #[test]
9342 fn validate_autores_rejects_embedded_control_bytes_entry() {
9343 // Paste-from-binary-blob footguns: NUL, BEL, ESC, DEL all
9344 // surface the same control-byte arm.
9345 for entry in [
9346 "alice\x00bob",
9347 "alice\x07bob",
9348 "alice\x1bbob",
9349 "alice\x7fbob",
9350 ] {
9351 let c = caixa_with_autores(vec![entry]);
9352 let err = c.validate_autores().unwrap_err();
9353 let ManifestError::AutorInvalid { autor, reason } = err else {
9354 panic!("expected AutorInvalid for {entry:?}, got {err:?}");
9355 };
9356 assert_eq!(autor, entry);
9357 assert!(
9358 reason.contains("control character"),
9359 "{entry:?} reason: {reason}",
9360 );
9361 }
9362 }
9363
9364 #[test]
9365 fn validate_autores_accepts_unicode_entry() {
9366 // Unicode positive control: realistic maintainer names carry
9367 // Unicode (`François`, `日本語`, `naïve`). The predicate must
9368 // round-trip Unicode losslessly, peer with the
9369 // `chart_maintainer_name_shape_accepts_unicode` substrate-side
9370 // sweep.
9371 let c = caixa_with_autores(vec![
9372 "François Dupont",
9373 "日本語の名前",
9374 "naïve <naive@example.com>",
9375 ]);
9376 c.validate_autores().unwrap();
9377 }
9378
9379 #[test]
9380 fn validate_autores_empty_takes_precedence_over_shape() {
9381 // Per-entry empty-first cascade pin: an entry that is both
9382 // empty *and* shape-invalid surfaces `AutorEmpty` (the narrower
9383 // "this entry has no value" structural defect dominates the
9384 // broader shape-predicate diagnostic). The empty arm fires
9385 // before the shape predicate is consulted, mirroring the peer
9386 // `validate_repositorio_empty_takes_precedence_over_shape`
9387 // cascade on the universal `Option<String>` siblings — and now
9388 // established on the Vec<String> per-entry surface.
9389 let c = caixa_with_autores(vec![""]);
9390 let err = c.validate_autores().unwrap_err();
9391 assert!(matches!(err, ManifestError::AutorEmpty), "got {err:?}",);
9392 }
9393
9394 #[test]
9395 fn validate_autores_shape_takes_precedence_over_duplicate() {
9396 // Per-entry shape-before-cross-entry-duplicate cascade pin: an
9397 // entry that is malformed surfaces `AutorInvalid` even when a
9398 // later entry would have collided on duplicate. The per-entry
9399 // shape arm fires inside the same loop iteration as the empty
9400 // arm, before the seen-set insert at end-of-iteration —
9401 // structural per-entry defects dominate the cross-entry
9402 // uniqueness diagnostic.
9403 let c = caixa_with_autores(vec!["alice\nbob", "alice\nbob"]);
9404 let err = c.validate_autores().unwrap_err();
9405 assert!(
9406 matches!(err, ManifestError::AutorInvalid { .. }),
9407 "got {err:?}",
9408 );
9409 }
9410
9411 #[test]
9412 fn validate_autores_invalid_diagnostic_names_offending_slot_and_value() {
9413 // Diagnostic-shape pin on the new shape arm (peer with
9414 // `validate_descricao_invalid_diagnostic_carries_offending_value`):
9415 // the rendered Display surfaces both the offending slot name
9416 // and the offending value verbatim, so a `feira lint` run
9417 // points the author at the exact `:autores` entry to fix.
9418 let c = caixa_with_autores(vec!["alice\nbob"]);
9419 let rendered = c.validate_autores().unwrap_err().to_string();
9420 assert!(
9421 rendered.contains(":autores"),
9422 "diagnostic must name the offending slot: {rendered}",
9423 );
9424 assert!(
9425 rendered.contains("alice\\nbob"),
9426 "diagnostic must quote the offending value (debug-escaped): {rendered}",
9427 );
9428 }
9429
9430 #[test]
9431 fn validate_autores_rejects_at_129_byte_boundary() {
9432 // The 128-byte cap pin — boundary-exceeding case rejected,
9433 // boundary-accepting case passes. Mirrors the peer
9434 // `chart_maintainer_name_shape_rejects_at_129_byte_boundary`
9435 // substrate-side pin, surfaced at the per-axis caller so the
9436 // cap propagates through validate end-to-end. Constructed as
9437 // a single all-`a` token so only the cap arm fires.
9438 let max_ok = "a".repeat(128);
9439 let c = caixa_with_autores(vec![max_ok.as_str()]);
9440 c.validate_autores().unwrap();
9441 let too_long = "a".repeat(129);
9442 let c = caixa_with_autores(vec![too_long.as_str()]);
9443 let err = c.validate_autores().unwrap_err();
9444 let ManifestError::AutorInvalid { reason, .. } = err else {
9445 panic!("expected AutorInvalid, got {err:?}");
9446 };
9447 assert!(reason.contains("128"), "got: {reason}");
9448 assert!(reason.contains("129"), "got: {reason}");
9449 }
9450
9451 // ── validate_repositorio — universal-axis git-repo-URL shape ──────
9452
9453 fn caixa_with_repositorio(repositorio: Option<&str>) -> Caixa {
9454 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
9455 c.repositorio = repositorio.map(String::from);
9456 c
9457 }
9458
9459 #[test]
9460 fn validate_repositorio_accepts_none() {
9461 // The omit-the-slot identity: `:repositorio` is optional. The
9462 // gate is a no-op when the author didn't declare a value —
9463 // every caixa without a `:repositorio` line trivially passes,
9464 // and the substrate-side renderers fall back to their
9465 // documented placeholder (`caixa-helm`'s `home: None`,
9466 // `caixa-flux`'s `https://github.com/pleme-io/<nome>` derived
9467 // URL). Mirrors the peer `validate_restart_window_accepts_none`
9468 // posture on the other `Option<String>` Caixa slot.
9469 let c = caixa_with_repositorio(None);
9470 c.validate_repositorio().unwrap();
9471 }
9472
9473 #[test]
9474 fn validate_repositorio_accepts_canonical_forms() {
9475 // Positive control sweep across every documented `:repositorio`
9476 // authoring shape — the same union the shared
9477 // `crate::render::is_git_repo_url` predicate accepts and the
9478 // peer `:deps :fonte :repo` axis already routes through.
9479 // Covers the `github:` shorthand (the canonical pleme-io
9480 // convention used in the `:repositorio` field of every
9481 // manifest fixture across `caixa-helm` / `caixa-mesh` and the
9482 // `examples/`), the `https://…` URL the README quickstart uses,
9483 // the `ssh://`, `git://`, `git@host:path` scp-style SSH, and
9484 // `file://` URL schemes the shared predicate documents.
9485 for repo in [
9486 "github:pleme-io/hello-rio",
9487 "github:pleme-io/checkout",
9488 "https://github.com/pleme-io/hello-rio",
9489 "ssh://git@github.com/pleme-io/hello-rio.git",
9490 "git://github.com/pleme-io/hello-rio.git",
9491 "git@github.com:pleme-io/hello-rio.git",
9492 "file:///srv/pleme/hello-rio",
9493 ] {
9494 let c = caixa_with_repositorio(Some(repo));
9495 c.validate_repositorio()
9496 .unwrap_or_else(|err| panic!("canonical {repo:?} must pass: {err:?}"));
9497 }
9498 }
9499
9500 #[test]
9501 fn validate_repositorio_rejects_empty_some() {
9502 // Canonical paste-from-blank-doc footgun. The narrower
9503 // [`ManifestError::RepositorioEmpty`] arm fires before the
9504 // shape predicate is consulted, mirroring the empty-first
9505 // cascade every peer per-axis identity gate uses
9506 // (`NomeEmpty` → `NomeInvalid`, `VersaoEmpty` → `VersaoInvalid`,
9507 // `FonteRepoEmpty` → `FonteRepoInvalid`). Without this gate
9508 // the empty `Some("")` silently passed the renderer's
9509 // `Option::unwrap_or_else(|| <fallback>)` (which only fires
9510 // on `None`) and landed as `home: ""` in `Chart.yaml` /
9511 // `url: ""` in the FluxCD `GitRepository`.
9512 let c = caixa_with_repositorio(Some(""));
9513 let err = c.validate_repositorio().unwrap_err();
9514 assert!(
9515 matches!(err, ManifestError::RepositorioEmpty),
9516 "got {err:?}",
9517 );
9518 }
9519
9520 #[test]
9521 fn validate_repositorio_rejects_whitespace() {
9522 // Paste-from-doc whitespace footgun. The shared
9523 // `is_git_repo_url` predicate refuses any whitespace byte; a
9524 // trailing space in a `:repositorio` value silently broke
9525 // `git clone '<value> '` at clone time. The diagnostic names
9526 // the offending value verbatim.
9527 let c = caixa_with_repositorio(Some("github:pleme-io/hello-rio "));
9528 let err = c.validate_repositorio().unwrap_err();
9529 let ManifestError::RepositorioInvalid { repositorio, .. } = err else {
9530 panic!("expected RepositorioInvalid, got {err:?}");
9531 };
9532 assert_eq!(repositorio, "github:pleme-io/hello-rio ");
9533 }
9534
9535 #[test]
9536 fn validate_repositorio_rejects_control_char() {
9537 // Paste-from-multiline-doc CRLF footgun — control characters
9538 // at the URL boundary are a class of subprocess-arg injection
9539 // and break git's URL parser at every porcelain entry point.
9540 let c = caixa_with_repositorio(Some("https://example.com/repo\n"));
9541 let err = c.validate_repositorio().unwrap_err();
9542 assert!(
9543 matches!(err, ManifestError::RepositorioInvalid { .. }),
9544 "got {err:?}",
9545 );
9546 }
9547
9548 #[test]
9549 fn validate_repositorio_rejects_leading_dash() {
9550 // Canonical CLI-argument-injection footgun: `git clone <repo>`
9551 // interprets a leading `-` as a CLI flag, so a
9552 // `-upload-pack=…` value escapes the subprocess argument
9553 // boundary. The shared predicate refuses every leading-`-`
9554 // shape at validate time.
9555 let c = caixa_with_repositorio(Some("-upload-pack=evil"));
9556 let err = c.validate_repositorio().unwrap_err();
9557 assert!(
9558 matches!(err, ManifestError::RepositorioInvalid { .. }),
9559 "got {err:?}",
9560 );
9561 }
9562
9563 #[test]
9564 fn validate_repositorio_rejects_missing_colon_separator() {
9565 // The bare `org/repo` ambiguity footgun — `git clone` reads
9566 // a no-`:` form as a relative filesystem path rather than the
9567 // GitHub-shorthand expansion the author probably intended.
9568 // The shared predicate refuses every shape without a `:`
9569 // separator.
9570 let c = caixa_with_repositorio(Some("pleme-io/hello-rio"));
9571 let err = c.validate_repositorio().unwrap_err();
9572 assert!(
9573 matches!(err, ManifestError::RepositorioInvalid { .. }),
9574 "got {err:?}",
9575 );
9576 }
9577
9578 #[test]
9579 fn validate_repositorio_rejects_fragment_anchor() {
9580 // Paste-from-browser-address-bar footgun on the
9581 // `:repositorio` axis — an author copies a GitHub permalink
9582 // to a README section / line-permalink and forgets to trim
9583 // the `#fragment` tail. The shared `is_git_repo_url`
9584 // predicate refuses the byte at the URL-grammar layer
9585 // (libcurl strips the fragment before opening the
9586 // transport, so the byte rides verbatim into the rendered
9587 // `Chart.yaml` `home:` and FluxCD `GitRepository` `url:`
9588 // fields but is silently dropped on the wire — two
9589 // manifest variants whose values differ only in their
9590 // fragment anchor lock to two distinct rendered artifacts
9591 // for the byte-identical clone, defeating the THEORY.md
9592 // §V.2 render-determinism contract on the `:repositorio`
9593 // axis the peer `:fonte :repo` axis already closes).
9594 let c = caixa_with_repositorio(Some("https://github.com/pleme-io/hello-rio#readme"));
9595 let err = c.validate_repositorio().unwrap_err();
9596 let ManifestError::RepositorioInvalid {
9597 repositorio,
9598 reason,
9599 } = err
9600 else {
9601 panic!("expected RepositorioInvalid, got {err:?}");
9602 };
9603 assert_eq!(repositorio, "https://github.com/pleme-io/hello-rio#readme");
9604 assert!(
9605 reason.contains("must not contain `#`"),
9606 "reason must surface the fragment-`#` arm, got {reason:?}"
9607 );
9608 }
9609
9610 #[test]
9611 fn validate_repositorio_rejects_query_string() {
9612 // Paste-from-browser-address-bar footgun on the
9613 // `:repositorio` axis (peer with the a68f818 fragment-`#`
9614 // arm on the same axis). An author copies a GitHub tab
9615 // deep-link out of the address bar and forgets to trim
9616 // the `?tab=…` query tail. The shared `is_git_repo_url`
9617 // predicate refuses the byte at the URL-grammar layer
9618 // (GitHub / GitLab / Bitbucket silently ignore the
9619 // `?query` tail and serve the same repo regardless, so
9620 // the byte rides verbatim into the rendered `Chart.yaml`
9621 // `home:` and FluxCD `GitRepository` `url:` fields but
9622 // is silently masked at the wire — two manifest variants
9623 // whose values differ only in their query tail lock to
9624 // two distinct rendered artifacts for the byte-identical
9625 // clone, defeating the THEORY.md §V.2 render-determinism
9626 // contract on the `:repositorio` axis the peer `:fonte
9627 // :repo` axis already closes).
9628 let c = caixa_with_repositorio(Some(
9629 "https://github.com/pleme-io/hello-rio?tab=readme-ov-file",
9630 ));
9631 let err = c.validate_repositorio().unwrap_err();
9632 let ManifestError::RepositorioInvalid {
9633 repositorio,
9634 reason,
9635 } = err
9636 else {
9637 panic!("expected RepositorioInvalid, got {err:?}");
9638 };
9639 assert_eq!(
9640 repositorio,
9641 "https://github.com/pleme-io/hello-rio?tab=readme-ov-file"
9642 );
9643 assert!(
9644 reason.contains("must not contain `?`"),
9645 "reason must surface the query-`?` arm, got {reason:?}"
9646 );
9647 }
9648
9649 #[test]
9650 fn validate_repositorio_rejects_embedded_backslash() {
9651 // Windows-file-path-confusion footgun on the `:repositorio`
9652 // axis (peer with the prior fragment-`#` / query-`?` arms on
9653 // the same axis, and peer with the new dep-level `:fonte :repo`
9654 // backslash arm on the URL-grammar trajectory). An author
9655 // pastes a Windows Explorer address-bar `file:///C:\Users\me\
9656 // hello-rio` into the `:repositorio` slot, expecting the
9657 // `lareira-<nome>` chart's `home:` field and the FluxCD
9658 // `GitRepository` `url:` field to render the canonical local
9659 // file-URI. The shared `is_git_repo_url` predicate refuses
9660 // the byte at the URL-grammar layer (libcurl silently
9661 // translates `\` → `/` on some platforms and refuses it on
9662 // others, so the byte rides verbatim into the rendered
9663 // artifacts but is silently rewritten or rejected at the wire
9664 // — two manifest variants whose values differ only in
9665 // backslash-vs-forward-slash lock to two distinct rendered
9666 // artifacts for the byte-identical clone, defeating the
9667 // THEORY.md §V.2 render-determinism contract on the
9668 // `:repositorio` axis the peer `:fonte :repo` axis already
9669 // closes).
9670 let c = caixa_with_repositorio(Some("file:///C:\\Users\\me\\hello-rio"));
9671 let err = c.validate_repositorio().unwrap_err();
9672 let ManifestError::RepositorioInvalid {
9673 repositorio,
9674 reason,
9675 } = err
9676 else {
9677 panic!("expected RepositorioInvalid, got {err:?}");
9678 };
9679 assert_eq!(repositorio, "file:///C:\\Users\\me\\hello-rio");
9680 assert!(
9681 reason.contains("must not contain `\\`"),
9682 "reason must surface the backslash-`\\` arm, got {reason:?}"
9683 );
9684 }
9685
9686 #[test]
9687 fn validate_repositorio_rejects_uri_template_placeholder() {
9688 // URI Template (RFC 6570) placeholder footgun on the
9689 // `:repositorio` axis (peer with the prior fragment-`#` /
9690 // query-`?` / backslash-`\` arms on the same axis, and peer
9691 // with the new dep-level `:fonte :repo` `{` / `}` arm on the
9692 // URL-grammar trajectory). An author pastes a quick-start
9693 // README snippet / OpenAPI `servers:` URL / Helm chart
9694 // `home:` template carrying unresolved `{org}` / `{repo}`
9695 // placeholders into the `:repositorio` slot, expecting the
9696 // substrate to resolve the placeholder downstream. The
9697 // shared `is_git_repo_url` predicate refuses the byte at the
9698 // URL-grammar layer (libcurl percent-encodes `{` / `}` to
9699 // `%7B` / `%7D` on the wire, so the byte round-trips
9700 // inconsistently between the rendered `Chart.yaml home:` /
9701 // FluxCD `GitRepository url:` and the resolver's `git clone`
9702 // invocation, defeating the THEORY.md §V.2 render-
9703 // determinism contract on the `:repositorio` axis the peer
9704 // `:fonte :repo` axis already closes; every git porcelain
9705 // entry-point additionally fetches a nonexistent literal-
9706 // `{placeholder}`-named path far from the source caixa.lisp).
9707 let c = caixa_with_repositorio(Some("https://github.com/{org}/hello-rio"));
9708 let err = c.validate_repositorio().unwrap_err();
9709 let ManifestError::RepositorioInvalid {
9710 repositorio,
9711 reason,
9712 } = err
9713 else {
9714 panic!("expected RepositorioInvalid, got {err:?}");
9715 };
9716 assert_eq!(repositorio, "https://github.com/{org}/hello-rio");
9717 assert!(
9718 reason.contains("must not contain `{`"),
9719 "reason must surface the open-brace `{{` arm, got {reason:?}"
9720 );
9721 assert!(
9722 reason.contains("URI Template") || reason.contains("RFC 6570"),
9723 "reason must name the RFC 6570 URI Template grammar, got {reason:?}"
9724 );
9725 }
9726
9727 #[test]
9728 fn validate_repositorio_empty_takes_precedence_over_shape() {
9729 // Empty-first cascade pin: the empty `Some("")` surfaces the
9730 // narrower `RepositorioEmpty` not the shape-predicate-wrapped
9731 // `RepositorioInvalid`, mirroring the peer
9732 // `NomeEmpty` → `NomeInvalid`, `VersaoEmpty` → `VersaoInvalid`,
9733 // `FonteRepoEmpty` → `FonteRepoInvalid` cascades. The shared
9734 // `is_git_repo_url` predicate also rejects the empty input
9735 // (defensively, with its own `"must not be empty"` reason),
9736 // but the manifest-layer empty arm runs first to surface the
9737 // narrower diagnostic verbatim.
9738 let c = caixa_with_repositorio(Some(""));
9739 let err = c.validate_repositorio().unwrap_err();
9740 assert!(
9741 matches!(err, ManifestError::RepositorioEmpty),
9742 "got {err:?}",
9743 );
9744 }
9745
9746 #[test]
9747 fn validate_repositorio_diagnostic_carries_offending_value() {
9748 // Diagnostic-shape pin (peer with
9749 // `validate_autores_diagnostic_carries_offending_author`): the
9750 // error's Display surfaces the offending value + slot name
9751 // verbatim, so a `feira lint` run can render the diagnostic
9752 // without re-parsing and the author can grep their caixa.lisp
9753 // for the offending `:repositorio` value.
9754 let c = caixa_with_repositorio(Some("pleme-io/hello-rio"));
9755 let rendered = c.validate_repositorio().unwrap_err().to_string();
9756 assert!(
9757 rendered.contains(":repositorio"),
9758 "diagnostic must name the offending slot: {rendered}",
9759 );
9760 assert!(
9761 rendered.contains("pleme-io/hello-rio"),
9762 "diagnostic must quote the offending value: {rendered}",
9763 );
9764 }
9765
9766 // ── validate_descricao — universal-axis Chart.yaml description shape ──
9767
9768 fn caixa_with_descricao(descricao: Option<&str>) -> Caixa {
9769 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
9770 c.descricao = descricao.map(String::from);
9771 c
9772 }
9773
9774 #[test]
9775 fn validate_descricao_accepts_none() {
9776 // The omit-the-slot identity: `:descricao` is optional. The
9777 // gate is a no-op when the author didn't declare a value —
9778 // every caixa without a `:descricao` line trivially passes,
9779 // and the substrate-side renderers fall back to their
9780 // documented `caixa.nome`-derived placeholder. Mirrors the
9781 // peer `validate_repositorio_accepts_none` posture on the
9782 // sibling `Option<String>` Caixa slot.
9783 let c = caixa_with_descricao(None);
9784 c.validate_descricao().unwrap();
9785 }
9786
9787 #[test]
9788 fn validate_descricao_accepts_canonical_summary() {
9789 // Positive control: the canonical pleme-io descricao shape —
9790 // a short free-form prose summary — passes the gate. Covers
9791 // the fixture shapes the `caixa-helm` / `caixa-flux` /
9792 // `caixa-mesh` test fixtures use (`"Canonical Rust→wasm32-
9793 // wasip2 caixa Servico."`, `"Checkout flow."`).
9794 for desc in [
9795 "Canonical Rust→wasm32-wasip2 caixa Servico.",
9796 "Checkout flow.",
9797 "AWS provider caixa for tatara-lisp",
9798 "FIXME — describe this caixa",
9799 "x",
9800 ] {
9801 let c = caixa_with_descricao(Some(desc));
9802 c.validate_descricao()
9803 .unwrap_or_else(|err| panic!("canonical {desc:?} must pass: {err:?}"));
9804 }
9805 }
9806
9807 #[test]
9808 fn validate_descricao_rejects_empty_some() {
9809 // Canonical paste-from-blank-doc footgun. Without this gate
9810 // the empty `Some("")` silently passed the renderer's
9811 // `Option::unwrap_or_else(|| <fallback>)` (which only fires
9812 // on `None`) and landed as `description: ""` in `Chart.yaml`
9813 // and a blank `README.md` header. Mirrors the peer
9814 // [`ManifestError::RepositorioEmpty`] empty-arm on the
9815 // sibling `Option<String>` Caixa slot.
9816 let c = caixa_with_descricao(Some(""));
9817 let err = c.validate_descricao().unwrap_err();
9818 assert!(matches!(err, ManifestError::DescricaoEmpty), "got {err:?}",);
9819 }
9820
9821 #[test]
9822 fn validate_descricao_rejects_leading_whitespace() {
9823 // Paste-from-aligned-doc footgun: a leading ASCII space the
9824 // bare empty-arm gate accepted, the shape predicate now
9825 // refuses. The diagnostic carries the offending value
9826 // verbatim (with the leading space preserved) so the author
9827 // can grep their caixa.lisp for the exact `:descricao` line
9828 // and fix the round-trip-inconsistent leading whitespace.
9829 // Mirrors the peer
9830 // `validate_licenca_rejects_leading_whitespace` arm on the
9831 // sibling `:licenca` axis.
9832 let c = caixa_with_descricao(Some(" Checkout flow."));
9833 let err = c.validate_descricao().unwrap_err();
9834 let ManifestError::DescricaoInvalid { descricao, reason } = err else {
9835 panic!("expected DescricaoInvalid, got {err:?}");
9836 };
9837 assert_eq!(descricao, " Checkout flow.");
9838 assert!(reason.contains("whitespace"), "got: {reason:?}");
9839 }
9840
9841 #[test]
9842 fn validate_descricao_rejects_trailing_whitespace() {
9843 // Paste-from-doc footgun: a trailing ASCII space the bare
9844 // empty-arm gate accepted, the shape predicate now refuses.
9845 let c = caixa_with_descricao(Some("Checkout flow. "));
9846 let err = c.validate_descricao().unwrap_err();
9847 let ManifestError::DescricaoInvalid { descricao, reason } = err else {
9848 panic!("expected DescricaoInvalid, got {err:?}");
9849 };
9850 assert_eq!(descricao, "Checkout flow. ");
9851 assert!(reason.contains("whitespace"), "got: {reason:?}");
9852 }
9853
9854 #[test]
9855 fn validate_descricao_rejects_embedded_newline() {
9856 // Paste-from-multiline-doc footgun: an embedded LF the bare
9857 // empty-arm gate accepted, the shape predicate now refuses.
9858 // Without this gate the embedded newline silently landed in
9859 // the rendered Chart.yaml as a multi-line YAML block scalar,
9860 // and every chart-aware UI (`helm list`, `helm search`,
9861 // Artifact Hub) renders the description in a single-line
9862 // column so the embedded newline is silently dropped at
9863 // every downstream consumer.
9864 let c = caixa_with_descricao(Some("Checkout\nflow."));
9865 let err = c.validate_descricao().unwrap_err();
9866 assert!(
9867 matches!(err, ManifestError::DescricaoInvalid { .. }),
9868 "got {err:?}",
9869 );
9870 assert!(err.to_string().contains("newline"), "got {err}");
9871 }
9872
9873 #[test]
9874 fn validate_descricao_rejects_embedded_carriage_return() {
9875 // Paste-from-Windows-CRLF-doc footgun.
9876 let c = caixa_with_descricao(Some("Checkout\rflow."));
9877 let err = c.validate_descricao().unwrap_err();
9878 assert!(
9879 matches!(err, ManifestError::DescricaoInvalid { .. }),
9880 "got {err:?}",
9881 );
9882 assert!(err.to_string().contains("carriage return"), "got {err}");
9883 }
9884
9885 #[test]
9886 fn validate_descricao_rejects_embedded_tab() {
9887 // Tab-from-aligned-doc footgun.
9888 let c = caixa_with_descricao(Some("Checkout\tflow."));
9889 let err = c.validate_descricao().unwrap_err();
9890 assert!(
9891 matches!(err, ManifestError::DescricaoInvalid { .. }),
9892 "got {err:?}",
9893 );
9894 assert!(err.to_string().contains("tab"), "got {err}");
9895 }
9896
9897 #[test]
9898 fn validate_descricao_rejects_embedded_control_bytes() {
9899 // Paste-from-binary-blob footgun: every other control byte
9900 // (NUL, BEL, ESC, DEL) is refused at validate time. Mirrors
9901 // the peer SPDX-expression control-byte arm.
9902 for s in [
9903 "Checkout\x00flow.",
9904 "Checkout\x07flow.",
9905 "Checkout\x1bflow.",
9906 "Checkout\x7fflow.",
9907 ] {
9908 let c = caixa_with_descricao(Some(s));
9909 let err = c.validate_descricao().unwrap_err();
9910 assert!(
9911 matches!(err, ManifestError::DescricaoInvalid { .. }),
9912 "{s:?} got {err:?}",
9913 );
9914 assert!(
9915 err.to_string().contains("control character"),
9916 "{s:?} got {err}",
9917 );
9918 }
9919 }
9920
9921 #[test]
9922 fn validate_descricao_accepts_unicode_prose() {
9923 // Positive control: Unicode prose is accepted — the
9924 // canonical fixtures carry `→` (U+2192) and `—` (U+2014),
9925 // and `Caixa::template`'s `"FIXME — describe this caixa"`
9926 // scaffold every `feira init` emits must continue to pass.
9927 for s in [
9928 "Canonical Rust→wasm32-wasip2 caixa Servico.",
9929 "FIXME — describe this caixa",
9930 "Caixa pour le projet tâche",
9931 "日本語の説明",
9932 ] {
9933 let c = caixa_with_descricao(Some(s));
9934 c.validate_descricao()
9935 .unwrap_or_else(|err| panic!("Unicode {s:?} must pass: {err:?}"));
9936 }
9937 }
9938
9939 #[test]
9940 fn validate_descricao_empty_takes_precedence_over_shape() {
9941 // Cascade pin: a `Some("")` surfaces the narrower
9942 // `DescricaoEmpty` arm, not the broader `DescricaoInvalid`
9943 // shape-predicate arm. Mirrors the peer
9944 // `validate_licenca_empty_takes_precedence_over_shape` pin
9945 // on the sibling `:licenca` axis.
9946 let c = caixa_with_descricao(Some(""));
9947 let err = c.validate_descricao().unwrap_err();
9948 assert!(matches!(err, ManifestError::DescricaoEmpty), "got {err:?}",);
9949 }
9950
9951 #[test]
9952 fn validate_descricao_invalid_diagnostic_carries_offending_value_and_slot() {
9953 // Diagnostic-shape pin: the error's Display surfaces both
9954 // the `:descricao` slot name and the offending value
9955 // verbatim, so a `feira lint` run can render the diagnostic
9956 // without re-parsing and the author can grep their caixa.lisp
9957 // for the offending `:descricao` line. Mirrors the peer
9958 // `validate_licenca_invalid_diagnostic_carries_offending_value_and_slot`
9959 // pin (ee2e888) on the sibling `:licenca` axis.
9960 // The `{descricao:?}` Debug format escapes embedded control
9961 // bytes; the quoted offending value surfaces as
9962 // `"Checkout\nflow."` (literal backslash-n) in the rendered
9963 // diagnostic. The author can grep their caixa.lisp for the
9964 // literal `Checkout` summary prefix.
9965 let c = caixa_with_descricao(Some("Checkout\nflow."));
9966 let rendered = c.validate_descricao().unwrap_err().to_string();
9967 assert!(
9968 rendered.contains(":descricao"),
9969 "diagnostic must name the offending slot: {rendered}",
9970 );
9971 assert!(
9972 rendered.contains("Checkout\\nflow."),
9973 "diagnostic must quote the offending value (debug-escaped): {rendered}",
9974 );
9975 }
9976
9977 #[test]
9978 fn validate_descricao_template_passes() {
9979 // Round-trip pin: the bare `Caixa::template` shape carries
9980 // `:descricao "FIXME — describe this caixa"` (a non-empty
9981 // sentinel), so the template-derived Caixa passes the gate by
9982 // construction. A future template-shape change that omits or
9983 // empties `:descricao` would surface here as a regression.
9984 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
9985 c.validate_descricao().unwrap();
9986 }
9987
9988 #[test]
9989 fn validate_descricao_diagnostic_names_offending_slot() {
9990 // Diagnostic-shape pin (peer with
9991 // `validate_repositorio_diagnostic_carries_offending_value`):
9992 // the error's Display surfaces the `:descricao` slot name
9993 // verbatim, so a `feira lint` run can render the diagnostic
9994 // without re-parsing and the author can grep their caixa.lisp
9995 // for the offending `:descricao` line.
9996 let c = caixa_with_descricao(Some(""));
9997 let rendered = c.validate_descricao().unwrap_err().to_string();
9998 assert!(
9999 rendered.contains(":descricao"),
10000 "diagnostic must name the offending slot: {rendered}",
10001 );
10002 }
10003
10004 // ── validate_licenca — universal-axis chart README license shape ──
10005
10006 fn caixa_with_licenca(licenca: Option<&str>) -> Caixa {
10007 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
10008 c.licenca = licenca.map(String::from);
10009 c
10010 }
10011
10012 #[test]
10013 fn validate_licenca_accepts_none() {
10014 // The omit-the-slot identity: `:licenca` is optional. The
10015 // gate is a no-op when the author didn't declare a value —
10016 // every caixa without a `:licenca` line trivially passes,
10017 // and the substrate-side `caixa-helm` renderer falls back to
10018 // the documented `"MIT"` placeholder. Mirrors the peer
10019 // `validate_descricao_accepts_none` posture on the sibling
10020 // `Option<String>` Caixa slot.
10021 let c = caixa_with_licenca(None);
10022 c.validate_licenca().unwrap();
10023 }
10024
10025 #[test]
10026 fn validate_licenca_accepts_canonical_expressions() {
10027 // Positive control: every canonical SPDX expression shape
10028 // pleme-io carries in its existing fixtures + the canonical
10029 // SPDX dual-license / with-exception / `+`-suffix / grouped /
10030 // user-defined-reference shapes all pass the gate. Covers
10031 // the single-license, `OR`-compound, `AND`-compound,
10032 // `WITH`-exception, parenthesis-grouped, `+`-suffix, and
10033 // `LicenseRef-` / `DocumentRef-:LicenseRef-` shapes — every
10034 // production the SPDX 2.1 expression grammar admits that
10035 // sits within the alphabet floor the
10036 // `is_spdx_expression_shape` predicate enforces.
10037 for lic in [
10038 "MIT",
10039 "Apache-2.0",
10040 "Apache-2.0 OR MIT",
10041 "Apache-2.0 AND MIT",
10042 "BSD-3-Clause",
10043 "MPL-2.0",
10044 "GPL-3.0-or-later",
10045 "GPL-2.0+",
10046 "Apache-2.0 WITH LLVM-exception",
10047 "(MIT OR Apache-2.0) AND BSD-3-Clause",
10048 "(MIT OR Apache-2.0) AND BSD-3-Clause AND ISC",
10049 "LicenseRef-MyLicense",
10050 "DocumentRef-spdx-tool:LicenseRef-MIT-Style",
10051 "x",
10052 ] {
10053 let c = caixa_with_licenca(Some(lic));
10054 c.validate_licenca()
10055 .unwrap_or_else(|err| panic!("canonical {lic:?} must pass: {err:?}"));
10056 }
10057 }
10058
10059 #[test]
10060 fn validate_licenca_rejects_trailing_whitespace() {
10061 // Paste-from-doc whitespace footgun. A trailing space in the
10062 // `:licenca` value would silently break a downstream SPDX
10063 // parser that splits on exact `AND` / `OR` / `WITH` keyword
10064 // boundaries. The shape predicate refuses every trailing
10065 // whitespace byte by construction. Peer with
10066 // `validate_repositorio_rejects_whitespace` and
10067 // `validate_edicao_rejects_trailing_whitespace`.
10068 let c = caixa_with_licenca(Some("MIT "));
10069 let err = c.validate_licenca().unwrap_err();
10070 let ManifestError::LicencaInvalid { licenca, .. } = err else {
10071 panic!("expected LicencaInvalid, got {err:?}");
10072 };
10073 assert_eq!(licenca, "MIT ");
10074 }
10075
10076 #[test]
10077 fn validate_licenca_rejects_leading_whitespace() {
10078 // Symmetric paste-from-doc whitespace footgun on the leading
10079 // boundary — the gate refuses every shape that starts with a
10080 // space byte by construction. Peer with
10081 // `validate_edicao_rejects_leading_whitespace`.
10082 let c = caixa_with_licenca(Some(" MIT"));
10083 let err = c.validate_licenca().unwrap_err();
10084 assert!(
10085 matches!(err, ManifestError::LicencaInvalid { .. }),
10086 "got {err:?}",
10087 );
10088 }
10089
10090 #[test]
10091 fn validate_licenca_rejects_control_char() {
10092 // Paste-from-multiline-doc CRLF footgun — control characters
10093 // at the value boundary land as a malformed line in the
10094 // rendered chart `README.md` `## License` section. Peer with
10095 // `validate_repositorio_rejects_control_char` and
10096 // `validate_edicao_rejects_control_char`.
10097 for lic in ["MIT\n", "MIT\r\n", "MIT\rApache-2.0"] {
10098 let c = caixa_with_licenca(Some(lic));
10099 let err = c.validate_licenca().unwrap_err();
10100 assert!(
10101 matches!(err, ManifestError::LicencaInvalid { .. }),
10102 "expected LicencaInvalid on {lic:?}, got {err:?}",
10103 );
10104 }
10105 }
10106
10107 #[test]
10108 fn validate_licenca_rejects_tab() {
10109 // Tab-from-aligned-doc footgun — SPDX expressions use a
10110 // single ASCII space between tokens; a tab breaks every
10111 // downstream SPDX parser that splits on exact `" "`
10112 // boundaries.
10113 let c = caixa_with_licenca(Some("MIT\tOR Apache-2.0"));
10114 let err = c.validate_licenca().unwrap_err();
10115 assert!(
10116 matches!(err, ManifestError::LicencaInvalid { .. }),
10117 "got {err:?}",
10118 );
10119 }
10120
10121 #[test]
10122 fn validate_licenca_rejects_non_ascii() {
10123 // Smart-quote / non-ASCII paste footgun — SPDX identifiers
10124 // are ASCII per the `idstring = 1*(ALPHA / DIGIT / "-" /
10125 // ".")` production. The shape predicate refuses every
10126 // non-ASCII byte by construction; peer with
10127 // `validate_edicao_rejects_non_ascii_lookalike`.
10128 for lic in ["MIT\u{a0}OR Apache-2.0", "MIT\u{2013}1.0", "Café-1.0"] {
10129 let c = caixa_with_licenca(Some(lic));
10130 let err = c.validate_licenca().unwrap_err();
10131 assert!(
10132 matches!(err, ManifestError::LicencaInvalid { .. }),
10133 "expected LicencaInvalid on {lic:?}, got {err:?}",
10134 );
10135 }
10136 }
10137
10138 #[test]
10139 fn validate_licenca_rejects_underscore() {
10140 // Underscore-instead-of-hyphen typo footgun — `Apache_2.0` /
10141 // `MIT_Style` / `BSD_3_Clause` are familiar shapes from
10142 // snake-case identifier conventions that don't apply to the
10143 // SPDX `idstring` grammar (which admits only `ALPHA / DIGIT /
10144 // "-" / "."`). The shape predicate refuses every underscore
10145 // byte by construction.
10146 for lic in ["Apache_2.0", "MIT_Style", "BSD_3_Clause"] {
10147 let c = caixa_with_licenca(Some(lic));
10148 let err = c.validate_licenca().unwrap_err();
10149 assert!(
10150 matches!(err, ManifestError::LicencaInvalid { .. }),
10151 "expected LicencaInvalid on {lic:?}, got {err:?}",
10152 );
10153 }
10154 }
10155
10156 #[test]
10157 fn validate_licenca_rejects_comma_separator() {
10158 // Comma-instead-of-`OR`-keyword colloquial idiom footgun —
10159 // SPDX expressions compose multiple licenses via `AND` / `OR`
10160 // keywords, not the comma separator. The shape predicate
10161 // refuses every comma byte by construction.
10162 for lic in ["MIT, Apache-2.0", "MIT,Apache-2.0"] {
10163 let c = caixa_with_licenca(Some(lic));
10164 let err = c.validate_licenca().unwrap_err();
10165 assert!(
10166 matches!(err, ManifestError::LicencaInvalid { .. }),
10167 "expected LicencaInvalid on {lic:?}, got {err:?}",
10168 );
10169 }
10170 }
10171
10172 #[test]
10173 fn validate_licenca_rejects_slash_dual_license() {
10174 // Slash-dual-license colloquial idiom footgun — the
10175 // `MIT/Apache-2.0` shape is common in Cargo's pre-SPDX
10176 // `package.license` field but non-SPDX; the SPDX equivalent
10177 // is `MIT OR Apache-2.0`. The shape predicate refuses every
10178 // forward-slash byte by construction.
10179 for lic in ["MIT/Apache-2.0", "MIT/BSD-3-Clause"] {
10180 let c = caixa_with_licenca(Some(lic));
10181 let err = c.validate_licenca().unwrap_err();
10182 assert!(
10183 matches!(err, ManifestError::LicencaInvalid { .. }),
10184 "expected LicencaInvalid on {lic:?}, got {err:?}",
10185 );
10186 }
10187 }
10188
10189 #[test]
10190 fn validate_licenca_rejects_semicolon_separator() {
10191 // Semicolon-list-separator confusion footgun — adjacent to
10192 // the comma-separator idiom, every list-separator-belongs-
10193 // to-list-grammar confusion lands here.
10194 let c = caixa_with_licenca(Some("MIT; Apache-2.0"));
10195 let err = c.validate_licenca().unwrap_err();
10196 assert!(
10197 matches!(err, ManifestError::LicencaInvalid { .. }),
10198 "got {err:?}",
10199 );
10200 }
10201
10202 #[test]
10203 fn validate_licenca_empty_takes_precedence_over_shape() {
10204 // Empty-first cascade pin: the empty `Some("")` surfaces the
10205 // narrower `LicencaEmpty` not the shape-predicate-wrapped
10206 // `LicencaInvalid`, mirroring the peer
10207 // `validate_edicao_empty_takes_precedence_over_shape` and
10208 // `validate_repositorio_empty_takes_precedence_over_shape`
10209 // (`RepositorioEmpty` → `RepositorioInvalid`), `NomeEmpty` →
10210 // `NomeInvalid`, `VersaoEmpty` → `VersaoInvalid` cascades.
10211 // The shape predicate also refuses the empty input
10212 // (defensively — `"must not be empty"`), but the manifest-
10213 // layer empty arm runs first to surface the narrower
10214 // diagnostic verbatim.
10215 let c = caixa_with_licenca(Some(""));
10216 let err = c.validate_licenca().unwrap_err();
10217 assert!(matches!(err, ManifestError::LicencaEmpty), "got {err:?}",);
10218 }
10219
10220 #[test]
10221 fn validate_licenca_invalid_diagnostic_carries_offending_value() {
10222 // Diagnostic-shape pin on the shape-predicate arm (peer with
10223 // `validate_edicao_invalid_diagnostic_carries_offending_value`
10224 // and `validate_repositorio_diagnostic_carries_offending_value`):
10225 // the error's Display surfaces the offending value + slot
10226 // name verbatim, so a `feira lint` run can render the
10227 // diagnostic without re-parsing and the author can grep
10228 // their caixa.lisp for the offending `:licenca` value.
10229 let c = caixa_with_licenca(Some("Apache_2.0"));
10230 let rendered = c.validate_licenca().unwrap_err().to_string();
10231 assert!(
10232 rendered.contains(":licenca"),
10233 "diagnostic must name the offending slot: {rendered}",
10234 );
10235 assert!(
10236 rendered.contains("Apache_2.0"),
10237 "diagnostic must quote the offending value: {rendered}",
10238 );
10239 }
10240
10241 #[test]
10242 fn validate_licenca_rejects_empty_some() {
10243 // Canonical paste-from-blank-doc footgun. Without this gate
10244 // the empty `Some("")` silently passed the renderer's
10245 // `Option::unwrap_or_else(|| "MIT".into())` (which only
10246 // fires on `None`) and landed as a bare trailing period in
10247 // the rendered chart `README.md` `## License` section.
10248 // Mirrors the peer [`ManifestError::DescricaoEmpty`] empty-
10249 // arm on the sibling `Option<String>` Caixa slot.
10250 let c = caixa_with_licenca(Some(""));
10251 let err = c.validate_licenca().unwrap_err();
10252 assert!(matches!(err, ManifestError::LicencaEmpty), "got {err:?}",);
10253 }
10254
10255 #[test]
10256 fn validate_licenca_template_passes() {
10257 // Round-trip pin: the bare `Caixa::template` shape (whether
10258 // it carries `:licenca` or omits it) passes the gate by
10259 // construction. A future template-shape change that
10260 // introduced `(:licenca "")` would surface here as a
10261 // regression. Mirrors the peer
10262 // `validate_descricao_template_passes` pin.
10263 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
10264 c.validate_licenca().unwrap();
10265 }
10266
10267 #[test]
10268 fn validate_licenca_diagnostic_names_offending_slot() {
10269 // Diagnostic-shape pin (peer with
10270 // `validate_descricao_diagnostic_names_offending_slot`):
10271 // the error's Display surfaces the `:licenca` slot name
10272 // verbatim, so a `feira lint` run can render the diagnostic
10273 // without re-parsing and the author can grep their caixa.lisp
10274 // for the offending `:licenca` line.
10275 let c = caixa_with_licenca(Some(""));
10276 let rendered = c.validate_licenca().unwrap_err().to_string();
10277 assert!(
10278 rendered.contains(":licenca"),
10279 "diagnostic must name the offending slot: {rendered}",
10280 );
10281 }
10282
10283 // ── Caixa::licenca — outer top-level Option<&str> scalar accessor ──
10284
10285 #[test]
10286 fn licenca_returns_licenca_byte_string_verbatim_across_permutations() {
10287 // The canonical per-`Caixa` `:licenca` SPDX-expression scalar
10288 // pin: [`Caixa::licenca`] must return the `:licenca` typed
10289 // byte-string verbatim as an `Option<&str>`, byte-equal to the
10290 // raw `self.licenca.as_deref()` access across every
10291 // representative value in the accept-set — `None` (the "omit
10292 // the slot to defer to the caixa-helm renderer's `MIT`
10293 // fallback" arm every existing fixture without a `:licenca`
10294 // line carries), `Some("")` (a past-the-guard sentinel that
10295 // pins the accessor doesn't perform a silent
10296 // `Some("") → None` collapse on the empty arm — validate
10297 // rejects `Some("")` through `LicencaEmpty` but the accessor
10298 // must ship the raw slot verbatim so a validate-time gate
10299 // regression surfaces at the caixa-helm emit boundary rather
10300 // than being silently absorbed into the fallback), `Some("MIT")`
10301 // (the canonical single-license shape every `feira init`
10302 // template scaffolds), `Some("Apache-2.0 OR MIT")` (the
10303 // canonical `OR`-compound shape the peer
10304 // `validate_licenca_accepts_canonical_expressions` positive
10305 // sweep exercises), `Some("(MIT OR Apache-2.0) AND
10306 // BSD-3-Clause")` (the canonical parenthesis-grouped shape),
10307 // `Some("MIT ")` / `Some(" MIT")` / `Some("MIT\n")` /
10308 // `Some("Apache_2.0")` / `Some("MIT,Apache-2.0")` (past-the-
10309 // guard sentinels — validate rejects each through
10310 // `LicencaInvalid` but the accessor must ship the raw slot
10311 // verbatim).
10312 //
10313 // First outer top-level [`Caixa`] `Option<&str>`-return scalar
10314 // accessor pin on the substrate primitive — opens the "outer
10315 // [`Caixa`] `Option<&str>` scalar" projection pattern the
10316 // sibling per-`Caixa` `:descricao` / `:repositorio` / `:edicao`
10317 // future lifts fold on. Sibling in shape to the peer per-`:placement`
10318 // [`crate::aplicacao::Placement::shard_key`] (7cd2a28) /
10319 // [`crate::aplicacao::Placement::affinity`] (74ec2d3) accessor
10320 // pins on the sibling per-M3-mesh-slot `Option<&str>`-return
10321 // axes, extended onto the outer top-level [`Caixa`] universal-
10322 // axis surface. Pins against a future silent detour that
10323 // returned an owned `Option<String>` (which would type-check
10324 // but silently allocate on every accessor call, breaking the
10325 // zero-cost projection every peer sibling accessor carries), a
10326 // `Some("") → None` collapse (which would silently absorb the
10327 // `LicencaEmpty` refusal case at the accessor boundary and the
10328 // caixa-helm emit path would silently fall back to `"MIT"` on
10329 // a struct-literal `Caixa { licenca: Some(""), .. }`), or a
10330 // `None → Some("MIT")` collapse (which would silently reify
10331 // the caixa-helm renderer's `"MIT"` fallback at the accessor
10332 // boundary and every downstream consumer keying off the
10333 // `Option::is_none()` discriminator would lose the "author
10334 // omitted the slot" signal).
10335 for licenca in [
10336 None,
10337 Some(""),
10338 Some("MIT"),
10339 Some("Apache-2.0 OR MIT"),
10340 Some("(MIT OR Apache-2.0) AND BSD-3-Clause"),
10341 Some("MIT "),
10342 Some(" MIT"),
10343 Some("MIT\n"),
10344 Some("Apache_2.0"),
10345 Some("MIT,Apache-2.0"),
10346 ] {
10347 let c = caixa_with_licenca(licenca);
10348 assert_eq!(
10349 c.licenca(),
10350 licenca,
10351 "Caixa::licenca must return :licenca verbatim (got {:?}, \
10352 expected {licenca:?})",
10353 c.licenca(),
10354 );
10355 assert_eq!(
10356 c.licenca(),
10357 c.licenca.as_deref(),
10358 "Caixa::licenca must byte-equal the raw \
10359 `self.licenca.as_deref()` field access across every \
10360 value in the Option<&str> accept-set",
10361 );
10362 }
10363 }
10364
10365 #[test]
10366 fn validate_licenca_empty_arm_routes_through_accessor() {
10367 // Composition pin: [`Caixa::validate_licenca`]'s empty-arm gate
10368 // must key off [`Caixa::licenca`], not the raw
10369 // `self.licenca.as_deref()` field access. Structurally: a
10370 // `Caixa { licenca: Some(""), .. }` must surface the
10371 // `LicencaEmpty` refusal exactly, and a
10372 // `Caixa { licenca: Some("MIT"), .. }` (the canonical
10373 // single-license form) must pass validate. The pair jointly
10374 // pins the accessor + validate-gate composition: any future
10375 // silent detour that had the accessor return `None` on the
10376 // empty arm (a `.filter(|s| !s.is_empty())` collapse) would
10377 // silently absorb the `LicencaEmpty` refusal at the accessor
10378 // boundary and the validate gate would accept a struct-literal
10379 // `Caixa { licenca: Some(""), .. }` — the composition pin
10380 // catches that at caixa-core build time.
10381 //
10382 // Peer of the per-`:politicas :circuit-breaker`
10383 // [`crate::aplicacao::CircuitBreaker::max_failures`] (3a74062)
10384 // accessor-composition pin
10385 // (`validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`)
10386 // on the sibling per-M3-mesh-slot required-`u32` axis — same
10387 // "the validate / shape-gate predicate must route through the
10388 // substrate-primitive typed dispatch" discipline extended onto
10389 // the outer top-level [`Caixa`] universal-axis
10390 // `Option<&str>`-composition surface.
10391 let c = caixa_with_licenca(Some(""));
10392 assert!(
10393 matches!(c.validate_licenca(), Err(ManifestError::LicencaEmpty)),
10394 "validate_licenca must reject licenca == Some(\"\") with \
10395 LicencaEmpty — the accessor and the validate gate must \
10396 route through the same substrate-primitive typed dispatch \
10397 on the :licenca empty arm",
10398 );
10399 let c = caixa_with_licenca(Some("MIT"));
10400 assert!(
10401 c.validate_licenca().is_ok(),
10402 "validate_licenca must accept licenca == Some(\"MIT\") \
10403 (the canonical single-license SPDX shape)",
10404 );
10405 }
10406
10407 #[test]
10408 fn licenca_projects_option_str_by_borrow() {
10409 // The by-borrow pin: [`Caixa::licenca`] returns
10410 // `Option<&str>` by borrow — the `&str` borrows the underlying
10411 // `String` storage of the `Option<String>` slot and the
10412 // accessor must not allocate a fresh `String` on every call.
10413 // Peer of the per-`:placement`
10414 // [`crate::aplicacao::Placement::shard_key`] (7cd2a28) by-
10415 // borrow pin on the peer per-M3-mesh-slot
10416 // `Option<&str>`-return axis, extended onto the outer top-
10417 // level [`Caixa`] universal-axis `Option<&str>` shape — the
10418 // accessor's returned `&str` must borrow from `&self` (the
10419 // returned reference's lifetime is tied to `&self`), and
10420 // calling the accessor twice on the same [`Caixa`] must yield
10421 // the same `Option<&str>` verbatim (idempotent, no side
10422 // effects on `&self`).
10423 //
10424 // Pins against a future silent detour that returned an owned
10425 // `Option<String>` (which would type-check but silently
10426 // allocate on every call, breaking the zero-cost projection
10427 // every peer sibling accessor carries), or a one-arm-only
10428 // accessor that returned a saturating value on some sentinel
10429 // input (breaking the pass-through invariant the sibling
10430 // required-scalar accessors carry).
10431 for licenca in [None, Some(""), Some("MIT"), Some("Apache-2.0 OR MIT")] {
10432 let c = caixa_with_licenca(licenca);
10433 let first = c.licenca();
10434 let second = c.licenca();
10435 assert_eq!(
10436 first, second,
10437 "Caixa::licenca must be idempotent — two successive \
10438 calls on the same &self must return the same \
10439 Option<&str>",
10440 );
10441 assert_eq!(
10442 first, licenca,
10443 "Caixa::licenca must return :licenca verbatim by \
10444 borrow — got {first:?}, expected {licenca:?}",
10445 );
10446 }
10447 }
10448
10449 // ── Caixa::repositorio — outer top-level Option<&str> scalar accessor ──
10450
10451 #[test]
10452 fn repositorio_returns_repositorio_byte_string_verbatim_across_permutations() {
10453 // The canonical per-`Caixa` `:repositorio` git-repo-URL scalar
10454 // pin: [`Caixa::repositorio`] must return the `:repositorio`
10455 // typed byte-string verbatim as an `Option<&str>`, byte-equal
10456 // to the raw `self.repositorio.as_deref()` access across every
10457 // representative value in the accept-set — `None` (the "omit
10458 // the slot to defer to the per-renderer placeholder" arm every
10459 // existing fixture without a `:repositorio` line carries),
10460 // `Some("")` (a past-the-guard sentinel that pins the accessor
10461 // doesn't perform a silent `Some("") → None` collapse on the
10462 // empty arm — validate rejects `Some("")` through
10463 // `RepositorioEmpty` but the accessor must ship the raw slot
10464 // verbatim so a validate-time gate regression surfaces at the
10465 // caixa-helm / caixa-flux emit boundary rather than being
10466 // silently absorbed into the per-renderer fallback),
10467 // `Some("github:pleme-io/hello-rio")` (the canonical `github:`
10468 // shorthand every existing manifest fixture across
10469 // `caixa-helm` / `caixa-mesh` and the `examples/` uses),
10470 // `Some("https://github.com/pleme-io/checkout")` (the canonical
10471 // `https://` URL the README quickstart uses),
10472 // `Some("ssh://git@github.com/pleme-io/checkout.git")` /
10473 // `Some("git://github.com/pleme-io/checkout.git")` /
10474 // `Some("git@github.com:pleme-io/checkout.git")` /
10475 // `Some("file:///opt/mirrors/pleme-io/checkout")` (every non-
10476 // github scheme the shared `is_git_repo_url` predicate
10477 // documents), and five past-the-guard sentinels for the
10478 // `RepositorioInvalid` refusal cases (`Some("pleme-io/checkout")`
10479 // missing-colon, `Some("-upload-pack=evil")` leading-dash, /
10480 // `Some("github:pleme-io/checkout?ref=main")` query-string, /
10481 // `Some("github:pleme-io/checkout#main")` fragment-anchor, /
10482 // `Some("github:pleme-io/{tpl}")` URI-template-placeholder — the
10483 // sentinels pin the accessor doesn't silently absorb the
10484 // refusal cases into a fallback).
10485 //
10486 // Second outer top-level [`Caixa`] `Option<&str>`-return scalar
10487 // accessor pin on the substrate primitive — sibling of the peer
10488 // [`Caixa::licenca`] (6d5bc28) pin
10489 // (`licenca_returns_licenca_byte_string_verbatim_across_permutations`)
10490 // that opened the "outer [`Caixa`] `Option<&str>` scalar"
10491 // projection pin pattern this pin folds on. Sibling in shape to
10492 // the peer per-`:placement`
10493 // [`crate::aplicacao::Placement::shard_key`] (7cd2a28) /
10494 // [`crate::aplicacao::Placement::affinity`] (74ec2d3) accessor
10495 // pins on the sibling per-M3-mesh-slot `Option<&str>`-return
10496 // axes, extended onto the outer top-level [`Caixa`] universal-
10497 // axis surface. Pins against a future silent detour that
10498 // returned an owned `Option<String>` (which would type-check
10499 // but silently allocate on every accessor call, breaking the
10500 // zero-cost projection every peer sibling accessor carries), a
10501 // `Some("") → None` collapse (which would silently absorb the
10502 // `RepositorioEmpty` refusal case at the accessor boundary and
10503 // the caixa-helm `Chart.yaml` `home:` fold would silently
10504 // render a `home: null` / omitted field on a struct-literal
10505 // `Caixa { repositorio: Some(""), .. }`), or a
10506 // `None → Some(<default>)` collapse (which would silently reify
10507 // the per-renderer fallback at the accessor boundary and every
10508 // downstream consumer keying off the `Option::is_none()`
10509 // discriminator would lose the "author omitted the slot"
10510 // signal).
10511 for repositorio in [
10512 None,
10513 Some(""),
10514 Some("github:pleme-io/hello-rio"),
10515 Some("https://github.com/pleme-io/checkout"),
10516 Some("ssh://git@github.com/pleme-io/checkout.git"),
10517 Some("git://github.com/pleme-io/checkout.git"),
10518 Some("git@github.com:pleme-io/checkout.git"),
10519 Some("file:///opt/mirrors/pleme-io/checkout"),
10520 Some("pleme-io/checkout"),
10521 Some("-upload-pack=evil"),
10522 Some("github:pleme-io/checkout?ref=main"),
10523 Some("github:pleme-io/checkout#main"),
10524 Some("github:pleme-io/{tpl}"),
10525 ] {
10526 let c = caixa_with_repositorio(repositorio);
10527 assert_eq!(
10528 c.repositorio(),
10529 repositorio,
10530 "Caixa::repositorio must return :repositorio verbatim \
10531 (got {:?}, expected {repositorio:?})",
10532 c.repositorio(),
10533 );
10534 assert_eq!(
10535 c.repositorio(),
10536 c.repositorio.as_deref(),
10537 "Caixa::repositorio must byte-equal the raw \
10538 `self.repositorio.as_deref()` field access across every \
10539 value in the Option<&str> accept-set",
10540 );
10541 }
10542 }
10543
10544 #[test]
10545 fn validate_repositorio_empty_arm_routes_through_accessor() {
10546 // Composition pin: [`Caixa::validate_repositorio`]'s empty-arm
10547 // gate must key off [`Caixa::repositorio`], not the raw
10548 // `self.repositorio.as_deref()` field access. Structurally: a
10549 // `Caixa { repositorio: Some(""), .. }` must surface the
10550 // `RepositorioEmpty` refusal exactly, and a
10551 // `Caixa { repositorio: Some("github:pleme-io/hello-rio"), .. }`
10552 // (the canonical `github:` shorthand form) must pass validate.
10553 // The pair jointly pins the accessor + validate-gate
10554 // composition: any future silent detour that had the accessor
10555 // return `None` on the empty arm (a `.filter(|s| !s.is_empty())`
10556 // collapse) would silently absorb the `RepositorioEmpty` refusal
10557 // at the accessor boundary and the validate gate would accept a
10558 // struct-literal `Caixa { repositorio: Some(""), .. }` — the
10559 // composition pin catches that at caixa-core build time.
10560 //
10561 // Peer of the [`Caixa::licenca`] (6d5bc28)
10562 // `validate_licenca_empty_arm_routes_through_accessor`
10563 // composition pin on the sibling outer top-level [`Caixa`]
10564 // `Option<&str>` universal-axis surface — same "the validate /
10565 // shape-gate predicate must route through the substrate-
10566 // primitive typed dispatch" discipline extended onto the second
10567 // outer top-level [`Caixa`] universal-axis `Option<&str>`-
10568 // composition surface.
10569 let c = caixa_with_repositorio(Some(""));
10570 assert!(
10571 matches!(
10572 c.validate_repositorio(),
10573 Err(ManifestError::RepositorioEmpty),
10574 ),
10575 "validate_repositorio must reject repositorio == Some(\"\") \
10576 with RepositorioEmpty — the accessor and the validate gate \
10577 must route through the same substrate-primitive typed \
10578 dispatch on the :repositorio empty arm",
10579 );
10580 let c = caixa_with_repositorio(Some("github:pleme-io/hello-rio"));
10581 assert!(
10582 c.validate_repositorio().is_ok(),
10583 "validate_repositorio must accept repositorio == \
10584 Some(\"github:pleme-io/hello-rio\") (the canonical \
10585 `github:` shorthand git-repo-URL shape)",
10586 );
10587 }
10588
10589 #[test]
10590 fn repositorio_projects_option_str_by_borrow() {
10591 // The by-borrow pin: [`Caixa::repositorio`] returns
10592 // `Option<&str>` by borrow — the `&str` borrows the underlying
10593 // `String` storage of the `Option<String>` slot and the
10594 // accessor must not allocate a fresh `String` on every call.
10595 // Peer of the per-`:placement`
10596 // [`crate::aplicacao::Placement::shard_key`] (7cd2a28) and the
10597 // [`Caixa::licenca`] (6d5bc28) by-borrow pins on the peer
10598 // `Option<&str>`-return axes, extended onto the second outer
10599 // top-level [`Caixa`] universal-axis `Option<&str>` shape —
10600 // the accessor's returned `&str` must borrow from `&self` (the
10601 // returned reference's lifetime is tied to `&self`), and
10602 // calling the accessor twice on the same [`Caixa`] must yield
10603 // the same `Option<&str>` verbatim (idempotent, no side effects
10604 // on `&self`).
10605 //
10606 // Pins against a future silent detour that returned an owned
10607 // `Option<String>` (which would type-check but silently
10608 // allocate on every call, breaking the zero-cost projection
10609 // every peer sibling accessor carries), or a one-arm-only
10610 // accessor that returned a saturating value on some sentinel
10611 // input (breaking the pass-through invariant the sibling
10612 // required-scalar accessors carry).
10613 for repositorio in [
10614 None,
10615 Some(""),
10616 Some("github:pleme-io/hello-rio"),
10617 Some("https://github.com/pleme-io/checkout"),
10618 ] {
10619 let c = caixa_with_repositorio(repositorio);
10620 let first = c.repositorio();
10621 let second = c.repositorio();
10622 assert_eq!(
10623 first, second,
10624 "Caixa::repositorio must be idempotent — two successive \
10625 calls on the same &self must return the same \
10626 Option<&str>",
10627 );
10628 assert_eq!(
10629 first, repositorio,
10630 "Caixa::repositorio must return :repositorio verbatim by \
10631 borrow — got {first:?}, expected {repositorio:?}",
10632 );
10633 }
10634 }
10635
10636 // ── Caixa::canonical_git_url — resolved-git-URL composer ──────────
10637
10638 #[test]
10639 fn canonical_git_url_returns_repositorio_verbatim_on_some_arm() {
10640 // Fail-before-pass-after pin: [`Caixa::canonical_git_url`] must
10641 // return the author-declared `:repositorio` byte-string verbatim
10642 // on the `Some` arm — no scheme rewrite, no trailing-slash
10643 // canonicalization, no `github:` → `https://github.com/`
10644 // desugaring. The resolved-URL composer is the projection of
10645 // the raw [`Caixa::repositorio`] `Option<&str>` accessor onto
10646 // the `String`-return arity every substrate-side field-fill
10647 // consumer keys off; on the `Some` arm the projection is
10648 // `str::to_owned` verbatim, so every accept-set value the
10649 // sibling `repositorio_returns_repositorio_byte_string_verbatim_
10650 // across_permutations` pin covers (`https://…`, `github:…`,
10651 // `ssh://…`, `git://…`, `git@…`, `file://…`, and the past-the-
10652 // guard sentinel `pleme-io/…`) must survive the accessor
10653 // byte-equal. Pins against a future silent detour that rewrote
10654 // the `github:` shorthand to the `https://github.com/` full URL
10655 // at the accessor boundary (which would silently split the
10656 // resolved-URL surface from the raw [`Caixa::repositorio`]
10657 // accessor's documented pass-through invariant), or a trailing-
10658 // slash normalization (which would silently break the
10659 // FluxCD `GitRepository` `spec.url` byte-exact match every
10660 // downstream consumer keys the source-controller reconcile off).
10661 for repositorio in [
10662 "github:pleme-io/hello-rio",
10663 "https://github.com/pleme-io/checkout",
10664 "ssh://git@github.com/pleme-io/checkout.git",
10665 "git://github.com/pleme-io/checkout.git",
10666 "git@github.com:pleme-io/checkout.git",
10667 "file:///opt/mirrors/pleme-io/checkout",
10668 ] {
10669 let c = caixa_with_repositorio(Some(repositorio));
10670 assert_eq!(
10671 c.canonical_git_url(),
10672 repositorio,
10673 "Caixa::canonical_git_url on the Some arm must return \
10674 :repositorio verbatim (got {:?}, expected {repositorio:?})",
10675 c.canonical_git_url(),
10676 );
10677 }
10678 }
10679
10680 #[test]
10681 fn canonical_git_url_falls_back_to_pleme_org_url_on_none_arm() {
10682 // Fail-before-pass-after pin: [`Caixa::canonical_git_url`] on the
10683 // `None` arm must emit the substrate's canonical pleme-org github
10684 // URL derived from `caixa.nome()` — `https://github.com/<org>/
10685 // <nome>` with `<org>` bound to [`crate::DEFAULT_PLEME_GIT_ORG`]
10686 // and `<nome>` bound to the typed [`Caixa::nome`] accessor. This
10687 // is the exact byte-image of the prior inline
10688 // [`caixa-flux::ClusterBundleOpts::for_caixa`] `git_url`
10689 // composer at caixa-flux/src/lib.rs:2080 that every prior caller
10690 // re-derived open-coded. Pins against a future silent detour
10691 // that migrated the `<org>` segment to a different constant (a
10692 // fork rebranding that split off a new
10693 // `DEFAULT_PLEME_GIT_ORG_MIRROR` const the accessor would need
10694 // to migrate onto), a scheme change (`https://` → `git://` or
10695 // `ssh://`), or a per-`Caixa` `.canonical_git_url_prefix`
10696 // override (which would break the substrate-wide single-source-
10697 // of-truth guarantee this method encodes).
10698 let c = caixa_with_repositorio(None);
10699 let expected = format!(
10700 "https://github.com/{org}/{nome}",
10701 org = crate::DEFAULT_PLEME_GIT_ORG,
10702 nome = c.nome(),
10703 );
10704 assert_eq!(
10705 c.canonical_git_url(),
10706 expected,
10707 "Caixa::canonical_git_url on the None arm must fold through \
10708 the substrate's canonical pleme-org github URL fallback \
10709 `https://github.com/<DEFAULT_PLEME_GIT_ORG>/<nome>` — got \
10710 {:?}, expected {expected:?}",
10711 c.canonical_git_url(),
10712 );
10713 }
10714
10715 #[test]
10716 fn canonical_git_url_byte_matches_manual_composition() {
10717 // Byte-parity pin: [`Caixa::canonical_git_url`] must render
10718 // byte-identically to the manual open-coded
10719 // `caixa.repositorio().map(str::to_owned).unwrap_or_else(||
10720 // format!("https://github.com/{org}/{nome}", ...))` composition
10721 // every prior substrate-side caller re-derived. Guards the
10722 // paired-site convergence just applied at caixa-flux's
10723 // [`ClusterBundleOpts::for_caixa`] `git_url` composer (which
10724 // now routes through this accessor): a future implementation of
10725 // this method that reordered the format arguments, swapped the
10726 // `<org>` constant for a different one, or interposed a
10727 // canonicalization pass on the `Some` arm surfaces here as a
10728 // caixa-core build-time test failure rather than as a downstream
10729 // FluxCD `GitRepository` reconcile mismatch far from this
10730 // method's source.
10731 for repositorio in [
10732 None,
10733 Some("github:pleme-io/hello-rio"),
10734 Some("https://github.com/pleme-io/checkout"),
10735 Some("ssh://git@github.com/pleme-io/checkout.git"),
10736 ] {
10737 let c = caixa_with_repositorio(repositorio);
10738 let manual = c.repositorio().map_or_else(
10739 || {
10740 format!(
10741 "https://github.com/{org}/{nome}",
10742 org = crate::DEFAULT_PLEME_GIT_ORG,
10743 nome = c.nome(),
10744 )
10745 },
10746 str::to_owned,
10747 );
10748 assert_eq!(
10749 c.canonical_git_url(),
10750 manual,
10751 "Caixa::canonical_git_url must byte-equal the manual \
10752 open-coded `repositorio().map(str::to_owned)\
10753 .unwrap_or_else(|| format!(...))` composition across \
10754 every representative :repositorio input — got {:?}, \
10755 expected {manual:?}",
10756 c.canonical_git_url(),
10757 );
10758 }
10759 }
10760
10761 // ── Caixa::publish_tag — resolved-publish-tag composer ───────────
10762
10763 #[test]
10764 fn publish_tag_composes_prefix_and_versao_on_all_shapes() {
10765 // Fail-before-pass-after pin: [`Caixa::publish_tag`] must compose
10766 // [`crate::DEFAULT_PUBLISH_TAG_PREFIX`] against the caixa's typed
10767 // [`Caixa::versao`] byte-string across every SemVer-2 shape the
10768 // sibling [`validate_versao_accepts_canonical_forms`] positive-set
10769 // sweep documents — bare MAJOR.MINOR.PATCH, pre-release tags
10770 // (`-rc.1`), build metadata (`+build.42`), the combined form, and
10771 // the `0.0.0` boundary case. Every accept-set value the peer
10772 // validate gate lets through must survive the resolved-tag
10773 // projection byte-equal.
10774 for versao in [
10775 "0.1.0",
10776 "0.0.0",
10777 "1.0.0",
10778 "1.2.3-rc.1",
10779 "1.2.3+build.42",
10780 "1.2.3-rc.1+build.42",
10781 ] {
10782 let c = caixa_with_versao(versao);
10783 let expected = format!(
10784 "{prefix}{versao}",
10785 prefix = crate::DEFAULT_PUBLISH_TAG_PREFIX,
10786 );
10787 assert_eq!(
10788 c.publish_tag(),
10789 expected,
10790 "Caixa::publish_tag must compose \
10791 DEFAULT_PUBLISH_TAG_PREFIX ({prefix:?}) against \
10792 :versao ({versao:?}) verbatim — got {got:?}, \
10793 expected {expected:?}",
10794 prefix = crate::DEFAULT_PUBLISH_TAG_PREFIX,
10795 got = c.publish_tag(),
10796 );
10797 }
10798 }
10799
10800 #[test]
10801 fn publish_tag_starts_with_default_publish_tag_prefix() {
10802 // Prefix-shape pin: every [`Caixa::publish_tag`] emission must
10803 // begin with the canonical [`crate::DEFAULT_PUBLISH_TAG_PREFIX`]
10804 // byte-string on every input, guarding a hypothetical future
10805 // implementation that migrated the prefix segment to an inline
10806 // literal (`"v"`) that would silently drift from any rebrand of
10807 // the lifted constant. Peer to the sibling caixa-flux
10808 // `cluster_bundle_default_git_tag_uses_lifted_caixa_core_prefix`
10809 // test which pins the same prefix invariant at the reader-side
10810 // `GitRefSpec::Tag` emit site.
10811 for versao in ["0.0.0", "0.1.0", "1.2.3-rc.1", "9.9.9+build.1"] {
10812 let c = caixa_with_versao(versao);
10813 let tag = c.publish_tag();
10814 assert!(
10815 tag.starts_with(crate::DEFAULT_PUBLISH_TAG_PREFIX),
10816 "Caixa::publish_tag emission {tag:?} must start with \
10817 the lifted crate::DEFAULT_PUBLISH_TAG_PREFIX \
10818 ({prefix:?})",
10819 prefix = crate::DEFAULT_PUBLISH_TAG_PREFIX,
10820 );
10821 }
10822 }
10823
10824 #[test]
10825 fn publish_tag_byte_matches_manual_composition() {
10826 // Byte-parity pin: [`Caixa::publish_tag`] must render byte-
10827 // identically to the manual open-coded
10828 // `format!("{prefix}{versao}", prefix =
10829 // caixa_core::DEFAULT_PUBLISH_TAG_PREFIX, versao =
10830 // caixa.versao())` composition every prior substrate-side
10831 // caller re-derived. Guards the paired-site convergence just
10832 // applied at caixa-flux's [`ClusterBundleOpts::for_caixa`]
10833 // `git_ref` composer (which now routes through this accessor):
10834 // a future implementation of this method that reordered the
10835 // format arguments, swapped the `<prefix>` constant for a
10836 // different one, or interposed a canonicalization pass on the
10837 // `:versao` axis surfaces here as a caixa-core build-time test
10838 // failure rather than as a downstream FluxCD `GitRepository`
10839 // reconcile mismatch far from this method's source.
10840 for versao in [
10841 "0.1.0",
10842 "0.0.0",
10843 "1.2.3-rc.1",
10844 "1.2.3+build.42",
10845 "1.2.3-rc.1+build.42",
10846 ] {
10847 let c = caixa_with_versao(versao);
10848 let manual = format!(
10849 "{prefix}{versao}",
10850 prefix = crate::DEFAULT_PUBLISH_TAG_PREFIX,
10851 versao = c.versao(),
10852 );
10853 assert_eq!(
10854 c.publish_tag(),
10855 manual,
10856 "Caixa::publish_tag must byte-equal the manual \
10857 open-coded `format!(\"{{prefix}}{{versao}}\", ...)` \
10858 composition across every representative :versao input \
10859 — got {got:?}, expected {manual:?}",
10860 got = c.publish_tag(),
10861 );
10862 }
10863 }
10864
10865 // ── Caixa::lareira_chart_name — resolved-chart-name composer ─────
10866
10867 #[test]
10868 fn lareira_chart_name_composes_prefix_and_nome_on_all_shapes() {
10869 // Fail-before-pass-after pin: [`Caixa::lareira_chart_name`] must
10870 // compose [`crate::LAREIRA_CHART_NAME_PREFIX`] against the caixa's
10871 // typed [`Caixa::nome`] byte-string across every DNS-1123 shape
10872 // the sibling [`validate_nome_accepts_canonical_forms`] positive-
10873 // set sweep documents — single-word, hyphen-joined, version-
10874 // suffixed, single-char, two-char, digit-start, retry-suffixed.
10875 // Every accept-set value the peer validate gate lets through must
10876 // survive the resolved-chart-name projection byte-equal.
10877 for nome in [
10878 "checkout",
10879 "cart-v2",
10880 "a",
10881 "db",
10882 "3rd-party-shim",
10883 "payment-retry",
10884 "0",
10885 ] {
10886 let c = caixa_with_nome(nome);
10887 let expected = format!("{prefix}{nome}", prefix = crate::LAREIRA_CHART_NAME_PREFIX);
10888 assert_eq!(
10889 c.lareira_chart_name(),
10890 expected,
10891 "Caixa::lareira_chart_name must compose \
10892 LAREIRA_CHART_NAME_PREFIX ({prefix:?}) against \
10893 :nome ({nome:?}) verbatim — got {got:?}, \
10894 expected {expected:?}",
10895 prefix = crate::LAREIRA_CHART_NAME_PREFIX,
10896 got = c.lareira_chart_name(),
10897 );
10898 }
10899 }
10900
10901 #[test]
10902 fn lareira_chart_name_starts_with_lifted_prefix() {
10903 // Prefix-shape pin: every [`Caixa::lareira_chart_name`] emission
10904 // must begin with the canonical
10905 // [`crate::LAREIRA_CHART_NAME_PREFIX`] byte-string on every
10906 // input, guarding a hypothetical future implementation that
10907 // migrated the prefix segment to an inline literal (`"lareira-"`)
10908 // that would silently drift from any rebrand of the lifted
10909 // constant. Peer to the sibling
10910 // [`publish_tag_starts_with_default_publish_tag_prefix`] pin on
10911 // the co-resident resolved-publish-tag composer's prefix axis.
10912 for nome in ["checkout", "cart", "a", "payment-retry", "0"] {
10913 let c = caixa_with_nome(nome);
10914 let chart = c.lareira_chart_name();
10915 assert!(
10916 chart.starts_with(crate::LAREIRA_CHART_NAME_PREFIX),
10917 "Caixa::lareira_chart_name emission {chart:?} must start \
10918 with the lifted crate::LAREIRA_CHART_NAME_PREFIX \
10919 ({prefix:?})",
10920 prefix = crate::LAREIRA_CHART_NAME_PREFIX,
10921 );
10922 }
10923 }
10924
10925 #[test]
10926 fn lareira_chart_name_byte_matches_canonical_helper_composition() {
10927 // Byte-parity pin: [`Caixa::lareira_chart_name`] must render
10928 // byte-identically to the manual open-coded
10929 // `caixa_core::lareira_chart_name(caixa.nome())` two-step
10930 // composition every prior substrate-side caller re-derived.
10931 // Guards the paired-site convergence just applied at caixa-helm's
10932 // [`render_chart_for_servico_with`] `ChartDir.name` composer,
10933 // caixa-flux's [`cluster_bundle`] per-CR `chart_name` binding,
10934 // and caixa-tatara's [`process_for_aplicacao`] `release_name`
10935 // composer (all of which now route through this accessor): a
10936 // future implementation of this method that reordered the
10937 // composition arguments, swapped the `<prefix>` constant for a
10938 // different one, or interposed a canonicalization pass on the
10939 // `:nome` axis surfaces here as a caixa-core build-time test
10940 // failure rather than as a downstream Helm chart-render / FluxCD
10941 // reconcile / tatara Process-CR mismatch far from this method's
10942 // source.
10943 for nome in [
10944 "checkout",
10945 "cart-v2",
10946 "a",
10947 "db",
10948 "3rd-party-shim",
10949 "payment-retry",
10950 ] {
10951 let c = caixa_with_nome(nome);
10952 let manual = crate::lareira_chart_name(c.nome());
10953 assert_eq!(
10954 c.lareira_chart_name(),
10955 manual,
10956 "Caixa::lareira_chart_name must byte-equal the manual \
10957 open-coded `caixa_core::lareira_chart_name(caixa.nome())` \
10958 composition across every representative :nome input — \
10959 got {got:?}, expected {manual:?}",
10960 got = c.lareira_chart_name(),
10961 );
10962 }
10963 }
10964
10965 // ── Caixa::oci_chart_ref — resolved-OCI-chart-ref composer ────────
10966
10967 #[test]
10968 fn oci_chart_ref_composes_scheme_and_lareira_chart_name_on_all_shapes() {
10969 // Fail-before-pass-after pin: [`Caixa::oci_chart_ref`] must
10970 // compose [`crate::OCI_SCHEME_PREFIX`] + the caller-supplied
10971 // `registry` + [`crate::lareira_chart_name`]-of-[`Caixa::nome`]
10972 // across the full paired `(registry, :nome)` accept-set — every
10973 // representative registry the substrate-side emitters carry
10974 // (`ghcr.io/pleme-io/charts`, the canonical CAIXA-SDLC §II
10975 // ArtifactHub-tier registry; `ghcr.io/pleme-io`, the bare-org
10976 // arm the sibling `oci_chart_ref_pins_byte_shape_against_prior_
10977 // inline_format` render-side pin exercises; `registry.example.
10978 // com`, an off-org shape; `localhost:5000`, the local-dev shape
10979 // every `feira chart` iteration path lands under) × every DNS-
10980 // 1123 `:nome` shape the peer `validate_nome_accepts_canonical_
10981 // forms` positive-set sweep documents (single-word, hyphen-
10982 // joined, single-char, two-char, digit-start, retry-suffixed).
10983 // Every accept-set pair the peer validate gates let through must
10984 // survive the resolved-OCI-ref projection byte-equal.
10985 for registry in [
10986 "ghcr.io/pleme-io/charts",
10987 "ghcr.io/pleme-io",
10988 "registry.example.com",
10989 "localhost:5000",
10990 ] {
10991 for nome in [
10992 "checkout",
10993 "cart-v2",
10994 "a",
10995 "db",
10996 "3rd-party-shim",
10997 "payment-retry",
10998 "0",
10999 ] {
11000 let c = caixa_with_nome(nome);
11001 let expected = format!(
11002 "{scheme}{registry}/{chart}",
11003 scheme = crate::OCI_SCHEME_PREFIX,
11004 chart = crate::lareira_chart_name(nome),
11005 );
11006 assert_eq!(
11007 c.oci_chart_ref(registry),
11008 expected,
11009 "Caixa::oci_chart_ref must compose \
11010 OCI_SCHEME_PREFIX ({scheme:?}) + registry ({registry:?}) + \
11011 lareira_chart_name(:nome ({nome:?})) verbatim — got {got:?}, \
11012 expected {expected:?}",
11013 scheme = crate::OCI_SCHEME_PREFIX,
11014 got = c.oci_chart_ref(registry),
11015 );
11016 }
11017 }
11018 }
11019
11020 #[test]
11021 fn oci_chart_ref_starts_with_lifted_scheme_prefix() {
11022 // Scheme-prefix-shape pin: every [`Caixa::oci_chart_ref`]
11023 // emission must begin with the canonical
11024 // [`crate::OCI_SCHEME_PREFIX`] byte-string on every input, guarding
11025 // a hypothetical future implementation that migrated the scheme
11026 // segment to an inline literal (`"oci://"`) that would silently
11027 // drift from any rebrand of the lifted constant. Peer to the
11028 // sibling [`publish_tag_starts_with_default_publish_tag_prefix`]
11029 // + [`lareira_chart_name_starts_with_lifted_prefix`] pins on the
11030 // co-resident resolved-publish-tag / resolved-chart-name
11031 // composers' prefix axes.
11032 for registry in [
11033 "ghcr.io/pleme-io/charts",
11034 "ghcr.io/pleme-io",
11035 "localhost:5000",
11036 ] {
11037 for nome in ["checkout", "cart", "a", "payment-retry", "0"] {
11038 let c = caixa_with_nome(nome);
11039 let ref_ = c.oci_chart_ref(registry);
11040 assert!(
11041 ref_.starts_with(crate::OCI_SCHEME_PREFIX),
11042 "Caixa::oci_chart_ref emission {ref_:?} must start \
11043 with the lifted crate::OCI_SCHEME_PREFIX ({scheme:?}) \
11044 — registry ({registry:?}), :nome ({nome:?})",
11045 scheme = crate::OCI_SCHEME_PREFIX,
11046 );
11047 }
11048 }
11049 }
11050
11051 #[test]
11052 fn oci_chart_ref_byte_matches_canonical_helper_composition() {
11053 // Byte-parity pin: [`Caixa::oci_chart_ref`] must render byte-
11054 // identically to the manual open-coded
11055 // `caixa_core::oci_chart_ref(registry, caixa.nome())` two-step
11056 // composition every prior substrate-side caller re-derived.
11057 // Guards the paired-site convergence just applied at caixa-
11058 // tatara's [`derive_chart_ref`] helper (which now routes through
11059 // this accessor): a future implementation of this method that
11060 // reordered the composition arguments, swapped the `<scheme>`
11061 // constant for a different one, migrated the `<chart>` segment
11062 // off the paired [`crate::lareira_chart_name`] composer, or
11063 // interposed a canonicalization pass on either input axis
11064 // surfaces here as a caixa-core build-time test failure rather
11065 // than as a downstream `helm install` / FluxCD OCI-source
11066 // reconcile / tatara `Process`-CR mismatch far from this
11067 // method's source. Sibling to the peer
11068 // [`lareira_chart_name_byte_matches_canonical_helper_composition`]
11069 // / [`publish_tag_byte_matches_manual_composition`] /
11070 // [`canonical_git_url_byte_matches_manual_composition`] byte-
11071 // parity pins that carry the same discipline on the co-resident
11072 // resolved-chart-name / resolved-publish-tag / resolved-git-URL
11073 // composers.
11074 for registry in [
11075 "ghcr.io/pleme-io/charts",
11076 "ghcr.io/pleme-io",
11077 "registry.example.com",
11078 "localhost:5000",
11079 ] {
11080 for nome in [
11081 "checkout",
11082 "cart-v2",
11083 "a",
11084 "db",
11085 "3rd-party-shim",
11086 "payment-retry",
11087 ] {
11088 let c = caixa_with_nome(nome);
11089 let manual = crate::oci_chart_ref(registry, c.nome());
11090 assert_eq!(
11091 c.oci_chart_ref(registry),
11092 manual,
11093 "Caixa::oci_chart_ref must byte-equal the manual \
11094 open-coded `caixa_core::oci_chart_ref(registry, \
11095 caixa.nome())` composition across every representative \
11096 (registry, :nome) pair — registry ({registry:?}), \
11097 :nome ({nome:?}), got {got:?}, expected {manual:?}",
11098 got = c.oci_chart_ref(registry),
11099 );
11100 }
11101 }
11102 }
11103
11104 // ── Caixa::descricao — outer top-level Option<&str> scalar accessor ──
11105
11106 #[test]
11107 fn descricao_returns_descricao_byte_string_verbatim_across_permutations() {
11108 // The canonical per-`Caixa` `:descricao` free-form-prose scalar
11109 // pin: [`Caixa::descricao`] must return the `:descricao` typed
11110 // byte-string verbatim as an `Option<&str>`, byte-equal to the
11111 // raw `self.descricao.as_deref()` access across every
11112 // representative value in the accept-set — `None` (the "omit
11113 // the slot to defer to the per-renderer `caixa.nome`-derived
11114 // fallback" arm every existing fixture without a `:descricao`
11115 // line carries), `Some("")` (a past-the-guard sentinel that
11116 // pins the accessor doesn't perform a silent `Some("") → None`
11117 // collapse on the empty arm — validate rejects `Some("")`
11118 // through `DescricaoEmpty` but the accessor must ship the raw
11119 // slot verbatim so a validate-time gate regression surfaces at
11120 // the caixa-helm / caixa-feira emit boundary rather than being
11121 // silently absorbed into the per-renderer `caixa.nome`-derived
11122 // fallback), `Some("Checkout flow.")` (the canonical one-line
11123 // prose descriptor the peer
11124 // `validate_descricao_accepts_canonical_value` positive sweep
11125 // exercises), `Some("Canonical Rust→wasm32-wasip2 caixa
11126 // Servico.")` (the multi-byte Unicode continuation-byte shape
11127 // the `hello-rio` fixture carries), `Some("→ — · ✓")` (a
11128 // multi-glyph Unicode shape the peer
11129 // `is_chart_description_shape` predicate accepts), and five
11130 // past-the-guard sentinels for the `DescricaoInvalid` refusal
11131 // cases (`Some(" Checkout flow.")` leading-whitespace,
11132 // `Some("Checkout flow. ")` trailing-whitespace,
11133 // `Some("Checkout\nflow.")` embedded-LF,
11134 // `Some("Checkout\tflow.")` embedded-TAB, and
11135 // `Some("Checkout\x00flow.")` embedded-NUL — the sentinels pin
11136 // the accessor doesn't silently absorb the refusal cases into
11137 // a fallback).
11138 //
11139 // Third outer top-level [`Caixa`] `Option<&str>`-return scalar
11140 // accessor pin on the substrate primitive — sibling of the peer
11141 // [`Caixa::licenca`] (6d5bc28) and [`Caixa::repositorio`]
11142 // (cc7332d) pins that opened the "outer [`Caixa`]
11143 // `Option<&str>` scalar" projection pin pattern this pin folds
11144 // on. Sibling in shape to the peer per-`:placement`
11145 // [`crate::aplicacao::Placement::shard_key`] (7cd2a28) /
11146 // [`crate::aplicacao::Placement::affinity`] (74ec2d3) accessor
11147 // pins on the sibling per-M3-mesh-slot `Option<&str>`-return
11148 // axes, extended onto the outer top-level [`Caixa`] universal-
11149 // axis surface. Pins against a future silent detour that
11150 // returned an owned `Option<String>` (which would type-check
11151 // but silently allocate on every accessor call, breaking the
11152 // zero-cost projection every peer sibling accessor carries), a
11153 // `Some("") → None` collapse (which would silently absorb the
11154 // `DescricaoEmpty` refusal case at the accessor boundary and
11155 // the caixa-helm `Chart.yaml` `description:` fold would
11156 // silently render a `caixa.nome`-derived fallback on a
11157 // struct-literal `Caixa { descricao: Some(""), .. }`), or a
11158 // `None → Some(<default>)` collapse (which would silently
11159 // reify the per-renderer `caixa.nome`-derived fallback at the
11160 // accessor boundary and every downstream consumer keying off
11161 // the `Option::is_none()` discriminator would lose the "author
11162 // omitted the slot" signal).
11163 for descricao in [
11164 None,
11165 Some(""),
11166 Some("Checkout flow."),
11167 Some("Canonical Rust→wasm32-wasip2 caixa Servico."),
11168 Some("→ — · ✓"),
11169 Some(" Checkout flow."),
11170 Some("Checkout flow. "),
11171 Some("Checkout\nflow."),
11172 Some("Checkout\tflow."),
11173 Some("Checkout\x00flow."),
11174 ] {
11175 let c = caixa_with_descricao(descricao);
11176 assert_eq!(
11177 c.descricao(),
11178 descricao,
11179 "Caixa::descricao must return :descricao verbatim (got \
11180 {:?}, expected {descricao:?})",
11181 c.descricao(),
11182 );
11183 assert_eq!(
11184 c.descricao(),
11185 c.descricao.as_deref(),
11186 "Caixa::descricao must byte-equal the raw \
11187 `self.descricao.as_deref()` field access across every \
11188 value in the Option<&str> accept-set",
11189 );
11190 }
11191 }
11192
11193 #[test]
11194 fn validate_descricao_empty_arm_routes_through_accessor() {
11195 // Composition pin: [`Caixa::validate_descricao`]'s empty-arm
11196 // gate must key off [`Caixa::descricao`], not the raw
11197 // `self.descricao.as_deref()` field access. Structurally: a
11198 // `Caixa { descricao: Some(""), .. }` must surface the
11199 // `DescricaoEmpty` refusal exactly, and a
11200 // `Caixa { descricao: Some("Checkout flow."), .. }` (the
11201 // canonical one-line-prose form) must pass validate. The pair
11202 // jointly pins the accessor + validate-gate composition: any
11203 // future silent detour that had the accessor return `None` on
11204 // the empty arm (a `.filter(|s| !s.is_empty())` collapse) would
11205 // silently absorb the `DescricaoEmpty` refusal at the accessor
11206 // boundary and the validate gate would accept a struct-literal
11207 // `Caixa { descricao: Some(""), .. }` — the composition pin
11208 // catches that at caixa-core build time.
11209 //
11210 // Peer of the [`Caixa::licenca`] (6d5bc28)
11211 // `validate_licenca_empty_arm_routes_through_accessor` and
11212 // [`Caixa::repositorio`] (cc7332d)
11213 // `validate_repositorio_empty_arm_routes_through_accessor`
11214 // composition pins on the sibling outer top-level [`Caixa`]
11215 // `Option<&str>` universal-axis surface — same "the validate /
11216 // shape-gate predicate must route through the substrate-
11217 // primitive typed dispatch" discipline extended onto the third
11218 // outer top-level [`Caixa`] universal-axis `Option<&str>`-
11219 // composition surface.
11220 let c = caixa_with_descricao(Some(""));
11221 assert!(
11222 matches!(c.validate_descricao(), Err(ManifestError::DescricaoEmpty),),
11223 "validate_descricao must reject descricao == Some(\"\") \
11224 with DescricaoEmpty — the accessor and the validate gate \
11225 must route through the same substrate-primitive typed \
11226 dispatch on the :descricao empty arm",
11227 );
11228 let c = caixa_with_descricao(Some("Checkout flow."));
11229 assert!(
11230 c.validate_descricao().is_ok(),
11231 "validate_descricao must accept descricao == \
11232 Some(\"Checkout flow.\") (the canonical one-line-prose \
11233 chart-description shape)",
11234 );
11235 }
11236
11237 #[test]
11238 fn descricao_projects_option_str_by_borrow() {
11239 // The by-borrow pin: [`Caixa::descricao`] returns
11240 // `Option<&str>` by borrow — the `&str` borrows the underlying
11241 // `String` storage of the `Option<String>` slot and the
11242 // accessor must not allocate a fresh `String` on every call.
11243 // Peer of the [`Caixa::licenca`] (6d5bc28) and
11244 // [`Caixa::repositorio`] (cc7332d) by-borrow pins on the peer
11245 // outer top-level [`Caixa`] `Option<&str>`-return axes, and of
11246 // the per-`:placement`
11247 // [`crate::aplicacao::Placement::shard_key`] (7cd2a28) by-
11248 // borrow pin on the peer per-M3-mesh-slot `Option<&str>`-
11249 // return axis, extended onto the third outer top-level
11250 // [`Caixa`] universal-axis `Option<&str>` shape — the
11251 // accessor's returned `&str` must borrow from `&self` (the
11252 // returned reference's lifetime is tied to `&self`), and
11253 // calling the accessor twice on the same [`Caixa`] must yield
11254 // the same `Option<&str>` verbatim (idempotent, no side
11255 // effects on `&self`).
11256 //
11257 // Pins against a future silent detour that returned an owned
11258 // `Option<String>` (which would type-check but silently
11259 // allocate on every call, breaking the zero-cost projection
11260 // every peer sibling accessor carries), or a one-arm-only
11261 // accessor that returned a saturating value on some sentinel
11262 // input (breaking the pass-through invariant the sibling
11263 // required-scalar accessors carry).
11264 for descricao in [
11265 None,
11266 Some(""),
11267 Some("Checkout flow."),
11268 Some("Canonical Rust→wasm32-wasip2 caixa Servico."),
11269 ] {
11270 let c = caixa_with_descricao(descricao);
11271 let first = c.descricao();
11272 let second = c.descricao();
11273 assert_eq!(
11274 first, second,
11275 "Caixa::descricao must be idempotent — two successive \
11276 calls on the same &self must return the same \
11277 Option<&str>",
11278 );
11279 assert_eq!(
11280 first, descricao,
11281 "Caixa::descricao must return :descricao verbatim by \
11282 borrow — got {first:?}, expected {descricao:?}",
11283 );
11284 }
11285 }
11286
11287 // ── validate_edicao — universal-axis language-edition shape ──
11288
11289 fn caixa_with_edicao(edicao: Option<&str>) -> Caixa {
11290 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
11291 c.edicao = edicao.map(String::from);
11292 c
11293 }
11294
11295 #[test]
11296 fn validate_edicao_accepts_none() {
11297 // The omit-the-slot identity: `:edicao` is optional. The
11298 // gate is a no-op when the author didn't declare a value —
11299 // every caixa without an `:edicao` line trivially passes,
11300 // and the substrate-side build pipeline falls back to the
11301 // documented default edition. Mirrors the peer
11302 // `validate_licenca_accepts_none` posture on the sibling
11303 // `Option<String>` Caixa slot.
11304 let c = caixa_with_edicao(None);
11305 c.validate_edicao().unwrap();
11306 }
11307
11308 #[test]
11309 fn validate_edicao_accepts_canonical_value() {
11310 // Positive control: the canonical `"2026"` edition every
11311 // existing renderer-side fixture (`caixa-helm`, `caixa-flux`,
11312 // `caixa-mesh`) carries by construction passes the gate.
11313 // Future-introduced sibling editions (`"2027"`, `"2030"`,
11314 // `"2049"`) that match the same 4-digit ASCII decimal year
11315 // shape must also trivially pass — the structural shape
11316 // predicate accepts every well-formed year regardless of
11317 // whether the substrate yet understands the specific value
11318 // (a future known-edition allowlist tightens that).
11319 for ed in ["2026", "2027", "2030", "2049"] {
11320 let c = caixa_with_edicao(Some(ed));
11321 c.validate_edicao()
11322 .unwrap_or_else(|err| panic!("canonical {ed:?} must pass: {err:?}"));
11323 }
11324 }
11325
11326 #[test]
11327 fn validate_edicao_rejects_empty_some() {
11328 // Canonical paste-from-blank-doc footgun. Without this gate
11329 // the empty `Some("")` silently lands as `(:edicao "")` in
11330 // the rendered caixa.lisp and a future renderer-side
11331 // consumer's `Option::unwrap_or_else` (which only fires on
11332 // `None`) skips its fallback. Mirrors the peer
11333 // [`ManifestError::LicencaEmpty`] empty-arm on the sibling
11334 // `Option<String>` Caixa slot.
11335 let c = caixa_with_edicao(Some(""));
11336 let err = c.validate_edicao().unwrap_err();
11337 assert!(matches!(err, ManifestError::EdicaoEmpty), "got {err:?}",);
11338 }
11339
11340 #[test]
11341 fn validate_edicao_rejects_free_form_non_year() {
11342 // Free-form non-year footgun: the bare `"x"` / `"latest"` /
11343 // `"nightly"` shapes carry no operational meaning on the
11344 // substrate's build-time edition selector. Until this gate
11345 // landed the bare empty-arm check let every such value
11346 // through and broke far from the source caixa.lisp. Peer
11347 // with the shape-predicate cascade
11348 // `validate_repositorio_rejects_missing_colon_separator`
11349 // establishes past its own empty arm.
11350 for ed in ["x", "latest", "nightly", "stable"] {
11351 let c = caixa_with_edicao(Some(ed));
11352 let err = c.validate_edicao().unwrap_err();
11353 assert!(
11354 matches!(err, ManifestError::EdicaoInvalid { .. }),
11355 "expected EdicaoInvalid on {ed:?}, got {err:?}",
11356 );
11357 }
11358 }
11359
11360 #[test]
11361 fn validate_edicao_rejects_trailing_whitespace() {
11362 // Paste-from-doc whitespace footgun. A trailing space in
11363 // the `:edicao` value would silently break the substrate's
11364 // build-time edition match-table lookup at the rendered
11365 // artifact's edition-selector consumer. The shape predicate
11366 // refuses every whitespace byte by construction (any byte
11367 // outside `0-9` fails `is_ascii_digit`). Peer with
11368 // `validate_repositorio_rejects_whitespace`.
11369 let c = caixa_with_edicao(Some("2026 "));
11370 let err = c.validate_edicao().unwrap_err();
11371 let ManifestError::EdicaoInvalid { edicao, .. } = err else {
11372 panic!("expected EdicaoInvalid, got {err:?}");
11373 };
11374 assert_eq!(edicao, "2026 ");
11375 }
11376
11377 #[test]
11378 fn validate_edicao_rejects_leading_whitespace() {
11379 // Symmetric paste-from-doc whitespace footgun on the leading
11380 // boundary — the gate refuses every shape with a non-digit
11381 // byte by construction.
11382 let c = caixa_with_edicao(Some(" 2026"));
11383 let err = c.validate_edicao().unwrap_err();
11384 assert!(
11385 matches!(err, ManifestError::EdicaoInvalid { .. }),
11386 "got {err:?}",
11387 );
11388 }
11389
11390 #[test]
11391 fn validate_edicao_rejects_control_char() {
11392 // Paste-from-multiline-doc CRLF footgun — control characters
11393 // at the value boundary break the substrate's build-time
11394 // edition-selector parser. Peer with
11395 // `validate_repositorio_rejects_control_char`.
11396 let c = caixa_with_edicao(Some("2026\n"));
11397 let err = c.validate_edicao().unwrap_err();
11398 assert!(
11399 matches!(err, ManifestError::EdicaoInvalid { .. }),
11400 "got {err:?}",
11401 );
11402 }
11403
11404 #[test]
11405 fn validate_edicao_rejects_non_ascii_lookalike() {
11406 // Fullwidth-keyboard look-alike footgun — `"2026"` is
11407 // the U+FF12 U+FF10 U+FF12 U+FF16 sequence (CJK fullwidth
11408 // digits), 4 codepoints but 12 UTF-8 bytes; the substrate's
11409 // edition selector wants an ASCII year, and the gate
11410 // refuses every non-ASCII shape by construction (length in
11411 // bytes is 12 ≠ 4, *and* every byte falls outside
11412 // `is_ascii_digit`'s `0-9` range).
11413 let c = caixa_with_edicao(Some("2026"));
11414 let err = c.validate_edicao().unwrap_err();
11415 assert!(
11416 matches!(err, ManifestError::EdicaoInvalid { .. }),
11417 "got {err:?}",
11418 );
11419 }
11420
11421 #[test]
11422 fn validate_edicao_rejects_version_tag_prefix() {
11423 // Common version-tag idiom footgun — `"v2026"` / `"e2026"`
11424 // / `"r2026"` are familiar shapes from git-tag / Rust
11425 // edition / release-tag conventions that don't apply to
11426 // the year-shaped edition axis. The shape predicate refuses
11427 // every leading non-digit prefix.
11428 for ed in ["v2026", "e2026", "r2026"] {
11429 let c = caixa_with_edicao(Some(ed));
11430 let err = c.validate_edicao().unwrap_err();
11431 assert!(
11432 matches!(err, ManifestError::EdicaoInvalid { .. }),
11433 "expected EdicaoInvalid on {ed:?}, got {err:?}",
11434 );
11435 }
11436 }
11437
11438 #[test]
11439 fn validate_edicao_rejects_decimal_shape() {
11440 // Decimal-shaped pseudo-version footgun — `"2026.1"` /
11441 // `"2026.0"` are familiar shapes from semver / float
11442 // conventions that don't apply to the year-shaped edition
11443 // axis. The shape predicate refuses every non-digit byte
11444 // (`.` falls outside `is_ascii_digit`).
11445 for ed in ["2026.1", "2026.0", "2026.0.1"] {
11446 let c = caixa_with_edicao(Some(ed));
11447 let err = c.validate_edicao().unwrap_err();
11448 assert!(
11449 matches!(err, ManifestError::EdicaoInvalid { .. }),
11450 "expected EdicaoInvalid on {ed:?}, got {err:?}",
11451 );
11452 }
11453 }
11454
11455 #[test]
11456 fn validate_edicao_rejects_wrong_length_numeric() {
11457 // Wrong-length numeric footgun — `"26"` (truncated) /
11458 // `"202"` (truncated) / `"20260"` (extra digit) / `"00026"`
11459 // (zero-padded too wide) all parse as integers but don't
11460 // name a 4-digit year. The shape predicate refuses every
11461 // value whose length isn't exactly 4 bytes.
11462 for ed in ["26", "202", "20260", "00026", "9"] {
11463 let c = caixa_with_edicao(Some(ed));
11464 let err = c.validate_edicao().unwrap_err();
11465 assert!(
11466 matches!(err, ManifestError::EdicaoInvalid { .. }),
11467 "expected EdicaoInvalid on {ed:?}, got {err:?}",
11468 );
11469 }
11470 }
11471
11472 #[test]
11473 fn validate_edicao_empty_takes_precedence_over_shape() {
11474 // Empty-first cascade pin: the empty `Some("")` surfaces
11475 // the narrower `EdicaoEmpty` not the shape-predicate-
11476 // wrapped `EdicaoInvalid`, mirroring the peer
11477 // `validate_repositorio_empty_takes_precedence_over_shape`
11478 // (`RepositorioEmpty` → `RepositorioInvalid`),
11479 // `NomeEmpty` → `NomeInvalid`, `VersaoEmpty` →
11480 // `VersaoInvalid`, `FonteRepoEmpty` → `FonteRepoInvalid`
11481 // cascades. The shape predicate also refuses the empty
11482 // input (defensively — `s.len() != 4`), but the
11483 // manifest-layer empty arm runs first to surface the
11484 // narrower diagnostic verbatim.
11485 let c = caixa_with_edicao(Some(""));
11486 let err = c.validate_edicao().unwrap_err();
11487 assert!(matches!(err, ManifestError::EdicaoEmpty), "got {err:?}",);
11488 }
11489
11490 #[test]
11491 fn validate_edicao_template_passes() {
11492 // Round-trip pin: the bare `Caixa::template` shape (which
11493 // carries `:edicao "2026"` verbatim) passes the gate by
11494 // construction. A future template-shape change that
11495 // introduced `(:edicao "")` or a non-year value would
11496 // surface here as a regression. Mirrors the peer
11497 // `validate_licenca_template_passes` pin.
11498 let c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
11499 c.validate_edicao().unwrap();
11500 }
11501
11502 #[test]
11503 fn validate_edicao_diagnostic_names_offending_slot() {
11504 // Diagnostic-shape pin (peer with
11505 // `validate_licenca_diagnostic_names_offending_slot`): the
11506 // error's Display surfaces the `:edicao` slot name verbatim,
11507 // so a `feira lint` run can render the diagnostic without
11508 // re-parsing and the author can grep their caixa.lisp for
11509 // the offending `:edicao` line.
11510 let c = caixa_with_edicao(Some(""));
11511 let rendered = c.validate_edicao().unwrap_err().to_string();
11512 assert!(
11513 rendered.contains(":edicao"),
11514 "diagnostic must name the offending slot: {rendered}",
11515 );
11516 }
11517
11518 #[test]
11519 fn validate_edicao_invalid_diagnostic_carries_offending_value() {
11520 // Diagnostic-shape pin on the shape-predicate arm (peer
11521 // with `validate_repositorio_diagnostic_carries_offending_value`):
11522 // the error's Display surfaces the offending value + slot
11523 // name verbatim, so a `feira lint` run can render the
11524 // diagnostic without re-parsing and the author can grep
11525 // their caixa.lisp for the offending `:edicao` value.
11526 let c = caixa_with_edicao(Some("v2026"));
11527 let rendered = c.validate_edicao().unwrap_err().to_string();
11528 assert!(
11529 rendered.contains(":edicao"),
11530 "diagnostic must name the offending slot: {rendered}",
11531 );
11532 assert!(
11533 rendered.contains("v2026"),
11534 "diagnostic must quote the offending value: {rendered}",
11535 );
11536 }
11537
11538 // ── Caixa::edicao — outer top-level Option<&str> scalar accessor ──
11539
11540 #[test]
11541 fn edicao_returns_edicao_byte_string_verbatim_across_permutations() {
11542 // The canonical per-`Caixa` `:edicao` language-edition scalar
11543 // pin: [`Caixa::edicao`] must return the `:edicao` typed
11544 // byte-string verbatim as an `Option<&str>`, byte-equal to the
11545 // raw `self.edicao.as_deref()` access across every representative
11546 // value in the accept-set — `None` (the "omit the slot to defer
11547 // to the substrate's default edition" arm every existing
11548 // [`caixa-resolver`] fixture without an `:edicao` line carries),
11549 // `Some("")` (a past-the-guard sentinel that pins the accessor
11550 // doesn't perform a silent `Some("") → None` collapse on the
11551 // empty arm — validate rejects `Some("")` through `EdicaoEmpty`
11552 // but the accessor must ship the raw slot verbatim so a
11553 // validate-time gate regression surfaces at any future edition-
11554 // aware consumer's boundary rather than being silently absorbed
11555 // into the substrate's default edition), `Some("2026")` (the
11556 // canonical 4-digit-ASCII-decimal-year shape every `feira init`
11557 // template scaffolds via [`Caixa::template`] and every
11558 // renderer-side fixture at `caixa-helm/src/lib.rs:978` /
11559 // `caixa-flux/src/lib.rs:2319` / `caixa-mesh/src/lib.rs:3208`
11560 // carries by construction), `Some("2018")` / `Some("2021")` /
11561 // `Some("2024")` (canonical 4-digit-ASCII-decimal-year shapes
11562 // peer with Cargo's `[package] edition` grammar every future-
11563 // introduced sibling to `"2026"` will follow), and eight
11564 // past-the-guard sentinels for the `EdicaoInvalid` refusal cases
11565 // (`Some("2026 ")` trailing-whitespace, `Some(" 2026")` leading-
11566 // whitespace, `Some("2026\n")` embedded-LF, `Some("2026")`
11567 // fullwidth-non-ASCII-lookalike, `Some("v2026")` version-tag-
11568 // prefix, `Some("2026.1")` decimal-shape, `Some("26")` wrong-
11569 // length-numeric, `Some("latest")` free-form-non-year — the
11570 // sentinels pin the accessor doesn't silently absorb the
11571 // refusal cases into a substrate-default-edition fallback).
11572 //
11573 // Fourth and final outer top-level [`Caixa`] `Option<&str>`-
11574 // return scalar accessor pin on the substrate primitive —
11575 // sibling of the peer [`Caixa::licenca`] (6d5bc28),
11576 // [`Caixa::repositorio`] (cc7332d), and [`Caixa::descricao`]
11577 // (3f16e2f) pins that opened the "outer [`Caixa`]
11578 // `Option<&str>` scalar" projection pin pattern this pin folds
11579 // on. Sibling in shape to the peer per-`:placement`
11580 // [`crate::aplicacao::Placement::shard_key`] (7cd2a28) /
11581 // [`crate::aplicacao::Placement::affinity`] (74ec2d3) accessor
11582 // pins on the sibling per-M3-mesh-slot `Option<&str>`-return
11583 // axes, extended onto the outer top-level [`Caixa`] universal-
11584 // axis surface's last unlifted `Option<String>` slot. Pins
11585 // against a future silent detour that returned an owned
11586 // `Option<String>` (which would type-check but silently
11587 // allocate on every accessor call, breaking the zero-cost
11588 // projection every peer sibling accessor carries), a
11589 // `Some("") → None` collapse (which would silently absorb the
11590 // `EdicaoEmpty` refusal case at the accessor boundary and any
11591 // future edition-aware consumer would silently fall back to
11592 // the substrate's default edition on a struct-literal
11593 // `Caixa { edicao: Some(""), .. }`), or a
11594 // `None → Some("2026")` collapse (which would silently reify
11595 // the substrate's default edition at the accessor boundary
11596 // and every downstream consumer keying off the
11597 // `Option::is_none()` discriminator would lose the "author
11598 // omitted the slot" signal).
11599 for edicao in [
11600 None,
11601 Some(""),
11602 Some("2026"),
11603 Some("2018"),
11604 Some("2021"),
11605 Some("2024"),
11606 Some("2026 "),
11607 Some(" 2026"),
11608 Some("2026\n"),
11609 Some("2026"),
11610 Some("v2026"),
11611 Some("2026.1"),
11612 Some("26"),
11613 Some("latest"),
11614 ] {
11615 let c = caixa_with_edicao(edicao);
11616 assert_eq!(
11617 c.edicao(),
11618 edicao,
11619 "Caixa::edicao must return :edicao verbatim (got {:?}, \
11620 expected {edicao:?})",
11621 c.edicao(),
11622 );
11623 assert_eq!(
11624 c.edicao(),
11625 c.edicao.as_deref(),
11626 "Caixa::edicao must byte-equal the raw \
11627 `self.edicao.as_deref()` field access across every \
11628 value in the Option<&str> accept-set",
11629 );
11630 }
11631 }
11632
11633 #[test]
11634 fn validate_edicao_empty_arm_routes_through_accessor() {
11635 // Composition pin: [`Caixa::validate_edicao`]'s empty-arm gate
11636 // must key off [`Caixa::edicao`], not the raw
11637 // `self.edicao.as_deref()` field access. Structurally: a
11638 // `Caixa { edicao: Some(""), .. }` must surface the
11639 // `EdicaoEmpty` refusal exactly, and a
11640 // `Caixa { edicao: Some("2026"), .. }` (the canonical
11641 // 4-digit-ASCII-decimal-year form) must pass validate. The
11642 // pair jointly pins the accessor + validate-gate composition:
11643 // any future silent detour that had the accessor return `None`
11644 // on the empty arm (a `.filter(|s| !s.is_empty())` collapse)
11645 // would silently absorb the `EdicaoEmpty` refusal at the
11646 // accessor boundary and the validate gate would accept a
11647 // struct-literal `Caixa { edicao: Some(""), .. }` — the
11648 // composition pin catches that at caixa-core build time.
11649 //
11650 // Peer of the [`Caixa::licenca`] (6d5bc28)
11651 // `validate_licenca_empty_arm_routes_through_accessor`,
11652 // [`Caixa::repositorio`] (cc7332d)
11653 // `validate_repositorio_empty_arm_routes_through_accessor`,
11654 // and [`Caixa::descricao`] (3f16e2f)
11655 // `validate_descricao_empty_arm_routes_through_accessor`
11656 // composition pins on the sibling outer top-level [`Caixa`]
11657 // `Option<&str>` universal-axis surface — same "the validate /
11658 // shape-gate predicate must route through the substrate-
11659 // primitive typed dispatch" discipline extended onto the
11660 // fourth and final outer top-level [`Caixa`] universal-axis
11661 // `Option<&str>`-composition surface, closing the accessor-
11662 // composition family.
11663 let c = caixa_with_edicao(Some(""));
11664 assert!(
11665 matches!(c.validate_edicao(), Err(ManifestError::EdicaoEmpty)),
11666 "validate_edicao must reject edicao == Some(\"\") with \
11667 EdicaoEmpty — the accessor and the validate gate must \
11668 route through the same substrate-primitive typed dispatch \
11669 on the :edicao empty arm",
11670 );
11671 let c = caixa_with_edicao(Some("2026"));
11672 assert!(
11673 c.validate_edicao().is_ok(),
11674 "validate_edicao must accept edicao == Some(\"2026\") \
11675 (the canonical 4-digit-ASCII-decimal-year shape)",
11676 );
11677 }
11678
11679 #[test]
11680 fn edicao_projects_option_str_by_borrow() {
11681 // The by-borrow pin: [`Caixa::edicao`] returns
11682 // `Option<&str>` by borrow — the `&str` borrows the underlying
11683 // `String` storage of the `Option<String>` slot and the
11684 // accessor must not allocate a fresh `String` on every call.
11685 // Peer of the [`Caixa::licenca`] (6d5bc28),
11686 // [`Caixa::repositorio`] (cc7332d), and [`Caixa::descricao`]
11687 // (3f16e2f) by-borrow pins on the peer outer top-level
11688 // [`Caixa`] `Option<&str>`-return axes, and of the
11689 // per-`:placement`
11690 // [`crate::aplicacao::Placement::shard_key`] (7cd2a28) by-
11691 // borrow pin on the peer per-M3-mesh-slot `Option<&str>`-
11692 // return axis, extended onto the fourth and final outer top-
11693 // level [`Caixa`] universal-axis `Option<&str>` shape — the
11694 // accessor's returned `&str` must borrow from `&self` (the
11695 // returned reference's lifetime is tied to `&self`), and
11696 // calling the accessor twice on the same [`Caixa`] must yield
11697 // the same `Option<&str>` verbatim (idempotent, no side
11698 // effects on `&self`).
11699 //
11700 // Pins against a future silent detour that returned an owned
11701 // `Option<String>` (which would type-check but silently
11702 // allocate on every call, breaking the zero-cost projection
11703 // every peer sibling accessor carries), or a one-arm-only
11704 // accessor that returned a saturating value on some sentinel
11705 // input (breaking the pass-through invariant the sibling
11706 // required-scalar accessors carry).
11707 for edicao in [None, Some(""), Some("2026"), Some("2018")] {
11708 let c = caixa_with_edicao(edicao);
11709 let first = c.edicao();
11710 let second = c.edicao();
11711 assert_eq!(
11712 first, second,
11713 "Caixa::edicao must be idempotent — two successive \
11714 calls on the same &self must return the same \
11715 Option<&str>",
11716 );
11717 assert_eq!(
11718 first, edicao,
11719 "Caixa::edicao must return :edicao verbatim by \
11720 borrow — got {first:?}, expected {edicao:?}",
11721 );
11722 }
11723 }
11724
11725 #[test]
11726 fn nome_returns_nome_byte_string_verbatim_across_permutations() {
11727 // The canonical per-`Caixa` `:nome` universal-axis DNS-1123-
11728 // label caixa-identity scalar pin: [`Caixa::nome`] must return
11729 // the `:nome` typed `String` verbatim as `&str`, byte-equal to
11730 // the raw field access across every representative value in
11731 // the accept-set — the canonical `"demo"` template baseline
11732 // (the same `feira init`-scaffolded default the sibling
11733 // `validate_nome_accepts_canonical_template` positive-control
11734 // gate pins), plus every sibling per-typed-slot atom accessor's
11735 // canonical positive-arm byte-string (`"catalog"` per
11736 // [`crate::aplicacao::Membro::nome`], `"cart"` per the peer
11737 // per-`:contratos` `:de`, `"hello-rio"` per the canonical
11738 // `caixa-helm`/`caixa-flux` cross-crate integration-test
11739 // fixture, `"checkout"` per the M3 mesh-slot Aplicacao
11740 // canonical example), plus every past-the-guard sentinel for
11741 // the `NomeEmpty` / `NomeInvalid` / `NomeChartNameBudgetExceeded`
11742 // refusal cases (`""`, `"Bad_Name"`, `"a"` × 56 — 56 bytes fits
11743 // the bare DNS-1123 63-byte cap but overflows the joint
11744 // `lareira-<nome>` chart-name budget the sibling
11745 // [`Caixa::validate_nome_chart_name_budget`] gate closes on).
11746 //
11747 // The past-the-guard sentinels pin the accessor doesn't
11748 // silently absorb the refusal cases into a template-derived
11749 // fallback (a future `.nome().is_empty().then(|| "demo")`
11750 // collapse would silently absorb the `NomeEmpty` refusal at
11751 // the accessor boundary and the validate gate would accept a
11752 // struct-literal `Caixa { nome: "".into(), .. }` — the pin
11753 // catches that at caixa-core build time).
11754 //
11755 // First outer top-level [`Caixa`] `&str`-return required-
11756 // scalar accessor pin — opens the "outer [`Caixa`] `&str`
11757 // required-scalar" projection pattern the sibling per-`Caixa`
11758 // `:versao` future lift folds on. Sibling in shape to the peer
11759 // per-`:membros` [`crate::aplicacao::Membro::nome`] (4a32abf)
11760 // required-`String`-carry accessor pin on the sibling per-
11761 // sub-struct required-axis, extended onto the outer top-level
11762 // [`Caixa`] universal-axis required-`String`-carry axis.
11763 for nome in [
11764 "demo",
11765 "catalog",
11766 "cart",
11767 "hello-rio",
11768 "checkout",
11769 "",
11770 "Bad_Name",
11771 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
11772 ] {
11773 let c = caixa_with_nome(nome);
11774 assert_eq!(
11775 c.nome(),
11776 nome,
11777 "Caixa::nome must return :nome verbatim (got {}, \
11778 expected {nome})",
11779 c.nome(),
11780 );
11781 assert_eq!(
11782 c.nome(),
11783 c.nome.as_str(),
11784 "Caixa::nome must byte-equal the raw .nome field \
11785 access across every value in the String accept-set",
11786 );
11787 }
11788 }
11789
11790 #[test]
11791 fn validate_nome_empty_arm_routes_through_accessor() {
11792 // Composition pin: [`Caixa::validate_nome`]'s empty-arm must
11793 // key off [`Caixa::nome`], not the raw `.nome` field access.
11794 // Structurally: a `Caixa { nome: "".into(), .. }` must surface
11795 // the `NomeEmpty` refusal exactly, and the canonical `"demo"`
11796 // template baseline (the peer positive-arm the sibling
11797 // `validate_nome_accepts_canonical_template` gate carves out)
11798 // must pass validate. The pair jointly pins the accessor +
11799 // validate-gate composition: any future silent detour that
11800 // had the accessor return a fresh `"demo"` on the empty arm
11801 // (a `.nome().is_empty().then(|| "demo")` fallback collapse)
11802 // would silently absorb the `NomeEmpty` refusal at the
11803 // accessor boundary and the validate gate would accept a
11804 // struct-literal `Caixa { nome: "".into(), .. }` — the
11805 // composition pin catches that at caixa-core build time.
11806 //
11807 // Peer of the sibling per-`Caixa`
11808 // `validate_licenca_empty_arm_routes_through_accessor` (6d5bc28)
11809 // / `validate_repositorio_empty_arm_routes_through_accessor`
11810 // (cc7332d) / `validate_descricao_empty_arm_routes_through_accessor`
11811 // (3f16e2f) / `validate_edicao_empty_arm_routes_through_accessor`
11812 // (2641cbd) composition pins on the sibling outer top-level
11813 // [`Caixa`] `Option<&str>` axes — same "the validate /
11814 // shape-gate predicate must route through the substrate-
11815 // primitive typed dispatch" discipline extended onto the peer
11816 // outer top-level [`Caixa`] required-`&str` composition axis.
11817 let c = caixa_with_nome("");
11818 assert!(
11819 matches!(c.validate_nome(), Err(ManifestError::NomeEmpty)),
11820 "validate_nome must reject nome == \"\" with NomeEmpty — \
11821 the accessor and the validate gate must route through the \
11822 same substrate-primitive typed dispatch on the :nome \
11823 empty-arm",
11824 );
11825 let c = caixa_with_nome("demo");
11826 assert!(
11827 c.validate_nome().is_ok(),
11828 "validate_nome must accept nome == \"demo\" (the canonical \
11829 DNS-1123-label template baseline)",
11830 );
11831 }
11832
11833 #[test]
11834 fn nome_projects_str_by_borrow() {
11835 // The by-borrow pin: [`Caixa::nome`] returns `&str` by borrow
11836 // — the `&str` borrows the underlying `String` storage of the
11837 // required `nome` slot and the accessor must not allocate a
11838 // fresh `String` on every call. Peer of the [`Caixa::licenca`]
11839 // (6d5bc28) / [`Caixa::repositorio`] (cc7332d) /
11840 // [`Caixa::descricao`] (3f16e2f) / [`Caixa::edicao`] (2641cbd)
11841 // by-borrow pins on the peer outer top-level [`Caixa`]
11842 // `Option<&str>`-return axes, extended onto the first outer
11843 // top-level [`Caixa`] required-`&str`-return axis — the
11844 // accessor's returned `&str` must borrow from `&self` (the
11845 // returned reference's lifetime is tied to `&self`), and
11846 // calling the accessor twice on the same [`Caixa`] must yield
11847 // the same `&str` verbatim (idempotent, no side effects on
11848 // `&self`).
11849 //
11850 // Pins against a future silent detour that returned an owned
11851 // `String` (which would type-check but silently allocate on
11852 // every call, breaking the zero-cost projection every peer
11853 // sibling accessor carries), an accidental
11854 // `.nome.to_lowercase()` detour that returned a fresh
11855 // allocation through an already-DNS-1123-lowercase-only
11856 // string (breaking a future `const fn` regression), or a
11857 // one-arm-only accessor that returned a canonicalized value
11858 // on some sentinel input (breaking the pass-through invariant
11859 // the sibling required-scalar accessors carry).
11860 for nome in ["demo", "catalog", "hello-rio", "checkout"] {
11861 let c = caixa_with_nome(nome);
11862 let first = c.nome();
11863 let second = c.nome();
11864 assert_eq!(
11865 first, second,
11866 "Caixa::nome must be idempotent — two successive calls \
11867 on the same &self must return the same &str",
11868 );
11869 assert_eq!(
11870 first, nome,
11871 "Caixa::nome must return :nome verbatim by borrow — \
11872 got {first}, expected {nome}",
11873 );
11874 }
11875 }
11876
11877 #[test]
11878 fn versao_returns_versao_byte_string_verbatim_across_permutations() {
11879 // The canonical per-`Caixa` `:versao` universal-axis SemVer-2
11880 // pinned-version scalar pin: [`Caixa::versao`] must return the
11881 // `:versao` typed `String` verbatim as `&str`, byte-equal to the
11882 // raw `.versao` field access across every representative value
11883 // in the accept-set — the canonical `"0.1.0"` template baseline
11884 // (the same `feira init`-scaffolded default the sibling
11885 // `validate_versao_accepts_canonical_template` positive-control
11886 // gate pins), plus every canonical SemVer-2 shape the sibling
11887 // `validate_versao_accepts_canonical_forms` positive-arm sweep
11888 // covers (`"0.0.0"`, `"1.0.0"`, `"0.2.0-rc.1"`,
11889 // `"1.0.0-alpha.0"`, `"1.0.0+build.42"`, `"1.0.0-rc.1+build.42"`,
11890 // `"10.20.30"`), plus every past-the-guard sentinel for the
11891 // `VersaoEmpty` / `VersaoInvalid` refusal cases (`""` the empty
11892 // arm, `"v0.1.0"` the git-tag-shape-leak footgun, `"0.1"` the
11893 // missing-patch footgun, `"^0.1"` the requirement-shape-leak
11894 // footgun, `"0.1.0.0"` the four-part-Java-convention footgun,
11895 // `"latest"` the docker-tag-shape footgun — the sentinels pin
11896 // the accessor doesn't silently absorb the refusal cases into a
11897 // template-derived fallback like `"0.1.0"`).
11898 //
11899 // The past-the-guard sentinels pin the accessor doesn't silently
11900 // absorb the refusal cases into a template-derived fallback (a
11901 // future `.versao().is_empty().then(|| "0.1.0")` collapse would
11902 // silently absorb the `VersaoEmpty` refusal at the accessor
11903 // boundary and the validate gate would accept a struct-literal
11904 // `Caixa { versao: "".into(), .. }` — the pin catches that at
11905 // caixa-core build time).
11906 //
11907 // Second outer top-level [`Caixa`] `&str`-return required-scalar
11908 // accessor pin — folds on the "outer [`Caixa`] `&str` required-
11909 // scalar" projection pattern the sibling per-`Caixa`
11910 // [`Caixa::nome`] (e6b7d97) opened. Sibling in shape to the peer
11911 // per-`:membros` [`crate::aplicacao::Membro::versao_requirement`]
11912 // (4127bb6) / per-`:children`
11913 // [`crate::supervisor::ChildSpec::versao_requirement`] (2c053c8)
11914 // / per-`:upgrade-from`
11915 // [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) per-sub-
11916 // struct `:versao`-shaped `&str`-return accessor pins on the
11917 // sibling per-typed-slot version-carrier axes, extended onto the
11918 // second outer top-level [`Caixa`] universal-axis required-
11919 // `String`-carry axis so the two universal-axis identity-
11920 // carrying scalars every `defcaixa` form supplies (`:nome` +
11921 // `:versao`) share the same "one typed dispatch per axis" pin
11922 // discipline.
11923 for versao in [
11924 "0.1.0",
11925 "0.0.0",
11926 "1.0.0",
11927 "0.2.0-rc.1",
11928 "1.0.0-alpha.0",
11929 "1.0.0+build.42",
11930 "1.0.0-rc.1+build.42",
11931 "10.20.30",
11932 "",
11933 "v0.1.0",
11934 "0.1",
11935 "^0.1",
11936 "0.1.0.0",
11937 "latest",
11938 ] {
11939 let c = caixa_with_versao(versao);
11940 assert_eq!(
11941 c.versao(),
11942 versao,
11943 "Caixa::versao must return :versao verbatim (got {}, \
11944 expected {versao})",
11945 c.versao(),
11946 );
11947 assert_eq!(
11948 c.versao(),
11949 c.versao.as_str(),
11950 "Caixa::versao must byte-equal the raw .versao field \
11951 access across every value in the String accept-set",
11952 );
11953 }
11954 }
11955
11956 #[test]
11957 fn validate_versao_empty_arm_routes_through_accessor() {
11958 // Composition pin: [`Caixa::validate_versao`]'s empty-arm gate
11959 // must key off [`Caixa::versao`], not the raw `.versao` field
11960 // access. Structurally: a `Caixa { versao: "".into(), .. }` must
11961 // surface the `VersaoEmpty` refusal exactly, and the canonical
11962 // `"0.1.0"` template baseline (the peer positive-arm the sibling
11963 // `validate_versao_accepts_canonical_template` gate carves out)
11964 // must pass validate. The pair jointly pins the accessor +
11965 // validate-gate composition: any future silent detour that had
11966 // the accessor return a fresh `"0.1.0"` on the empty arm
11967 // (a `.versao().is_empty().then(|| "0.1.0")` fallback collapse)
11968 // would silently absorb the `VersaoEmpty` refusal at the
11969 // accessor boundary and the validate gate would accept a
11970 // struct-literal `Caixa { versao: "".into(), .. }` — the
11971 // composition pin catches that at caixa-core build time.
11972 //
11973 // Peer of the sibling per-`Caixa`
11974 // `validate_nome_empty_arm_routes_through_accessor` (e6b7d97)
11975 // composition pin on the sibling outer top-level [`Caixa`]
11976 // required-`&str` universal-axis surface — same "the validate /
11977 // shape-gate predicate must route through the substrate-
11978 // primitive typed dispatch" discipline extended onto the peer
11979 // outer top-level [`Caixa`] required-`&str` universal-axis
11980 // pinned-version composition axis, closing the second
11981 // coordinate of the "one canonical typed dispatch per per-Caixa
11982 // required-`&str` universal-axis" discipline.
11983 let c = caixa_with_versao("");
11984 assert!(
11985 matches!(c.validate_versao(), Err(ManifestError::VersaoEmpty)),
11986 "validate_versao must reject versao == \"\" with VersaoEmpty — \
11987 the accessor and the validate gate must route through the \
11988 same substrate-primitive typed dispatch on the :versao \
11989 empty-arm",
11990 );
11991 let c = caixa_with_versao("0.1.0");
11992 assert!(
11993 c.validate_versao().is_ok(),
11994 "validate_versao must accept versao == \"0.1.0\" (the \
11995 canonical SemVer-2 template baseline)",
11996 );
11997 }
11998
11999 #[test]
12000 fn versao_projects_str_by_borrow() {
12001 // The by-borrow pin: [`Caixa::versao`] returns `&str` by borrow
12002 // — the `&str` borrows the underlying `String` storage of the
12003 // required `versao` slot and the accessor must not allocate a
12004 // fresh `String` on every call. Peer of the [`Caixa::nome`]
12005 // (e6b7d97) by-borrow pin on the sibling outer top-level
12006 // [`Caixa`] required-`&str`-return axis, extended onto the
12007 // second outer top-level [`Caixa`] required-`&str`-return
12008 // universal-axis pinned-version surface — the accessor's
12009 // returned `&str` must borrow from `&self` (the returned
12010 // reference's lifetime is tied to `&self`), and calling the
12011 // accessor twice on the same [`Caixa`] must yield the same
12012 // `&str` verbatim (idempotent, no side effects on `&self`).
12013 //
12014 // Pins against a future silent detour that returned an owned
12015 // `String` (which would type-check but silently allocate on
12016 // every call, breaking the zero-cost projection every peer
12017 // sibling accessor carries), an accidental
12018 // `semver::Version::parse(&self.versao).unwrap().to_string()`
12019 // detour that returned a canonicalized fresh allocation through
12020 // an already-canonical byte-string (breaking a future `const fn`
12021 // regression and silently absorbing the `VersaoInvalid` refusal
12022 // at the accessor boundary), or a one-arm-only accessor that
12023 // returned a canonicalized value on some sentinel input
12024 // (breaking the pass-through invariant the sibling required-
12025 // scalar accessors carry).
12026 for versao in ["0.1.0", "1.0.0", "0.2.0-rc.1", "1.0.0+build.42"] {
12027 let c = caixa_with_versao(versao);
12028 let first = c.versao();
12029 let second = c.versao();
12030 assert_eq!(
12031 first, second,
12032 "Caixa::versao must be idempotent — two successive \
12033 calls on the same &self must return the same &str",
12034 );
12035 assert_eq!(
12036 first, versao,
12037 "Caixa::versao must return :versao verbatim by borrow \
12038 — got {first}, expected {versao}",
12039 );
12040 }
12041 }
12042
12043 fn caixa_with_kind(kind: CaixaKind) -> Caixa {
12044 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
12045 c.kind = kind;
12046 c
12047 }
12048
12049 #[test]
12050 fn kind_returns_kind_variant_verbatim_across_permutations() {
12051 // The canonical per-`Caixa` `:kind` universal-axis closed-set-
12052 // enum discriminant pin: [`Caixa::kind`] must return the `:kind`
12053 // typed [`CaixaKind`] variant verbatim by `Copy`, byte-equal to
12054 // the raw `.kind` field access across every variant in the
12055 // closed accept-set (`Biblioteca` — the library kind that
12056 // exports lisp forms; `Binario` — the nix-built executable kind
12057 // under `exe/`; `Servico` — the wasm-component daemon kind
12058 // under `servicos/`; `Supervisor` — the OTP-shaped hierarchical
12059 // reconciliation kind; `Aplicacao` — the M3 typed-mesh
12060 // composition kind).
12061 //
12062 // Pins against a future silent detour that re-derived the kind
12063 // from a peer axis (an accidental fallback to
12064 // `if !servicos.is_empty() { Servico } else if
12065 // !membros.is_empty() { Aplicacao } else { Biblioteca }`
12066 // collapse that read the code-surface / mesh-slot columns into
12067 // the kind discriminator), a variant remap the operator
12068 // authors on one consumer without the other, or a stale-derive
12069 // detour that substituted [`CaixaKind::Biblioteca`] as the
12070 // default when the field held any other variant (which would
12071 // silently collapse the distinction between "author explicitly
12072 // declared `:kind Servico`" and "author declared any other
12073 // kind" every downstream renderer-dispatch site depends on).
12074 //
12075 // First outer top-level [`Caixa`] `Copy`-return required-enum-
12076 // discriminant accessor pin — opens the "outer [`Caixa`]
12077 // `Copy`-return required-discriminant" projection pattern.
12078 // Sibling in shape to the peer per-`:supervisor`
12079 // [`crate::supervisor::SupervisorSpec::estrategia`] (eafb619),
12080 // per-`:placement` [`crate::aplicacao::Placement::estrategia`]
12081 // (921fe1b), and per-`:children`
12082 // [`crate::supervisor::ChildSpec::restart`] (dfb4a81)
12083 // `Copy`-return closed-set-enum discriminant accessor pins on
12084 // the sibling nested-spec typed-slot discriminator axes,
12085 // extended here to the outer top-level [`Caixa`] universal-
12086 // axis surface.
12087 for kind in [
12088 CaixaKind::Biblioteca,
12089 CaixaKind::Binario,
12090 CaixaKind::Servico,
12091 CaixaKind::Supervisor,
12092 CaixaKind::Aplicacao,
12093 ] {
12094 let c = caixa_with_kind(kind);
12095 assert_eq!(
12096 c.kind(),
12097 kind,
12098 "Caixa::kind must return :kind verbatim (got {:?}, \
12099 expected {kind:?})",
12100 c.kind(),
12101 );
12102 assert_eq!(
12103 c.kind(),
12104 c.kind,
12105 "Caixa::kind accessor and .kind field access must \
12106 byte-equal — the accessor is the substrate-primitive \
12107 typed dispatch every downstream kind-gate consumer \
12108 must route through",
12109 );
12110 }
12111 }
12112
12113 #[test]
12114 fn require_kind_reads_through_lifted_kind_accessor() {
12115 // Two-consumer coherence pin: the [`crate::render::require_kind`]
12116 // entry-gate predicate (the canonical two-line
12117 // `require_kind(caixa, Servico)?` prelude every per-Servico /
12118 // per-Aplicacao renderer runs at its entry-point) and the
12119 // sibling [`crate::render::KindMismatch`] error carrier's
12120 // `actual:` field (which names the offending caixa's variant
12121 // in the diagnostic) must both key off the lifted accessor, so
12122 // any future rebrand on the typed slot's reader shape lands at
12123 // exactly one place. Pins the two-site coherence by exercising
12124 // every off-diagonal `(actual, expected)` pair across the
12125 // closed accept-set — the `KindMismatch { actual, expected }`
12126 // surfaced on the mismatch arm must byte-equal the pair the
12127 // accessor returns for each side.
12128 //
12129 // Peer of the sibling per-`:placement`
12130 // `validate_placement_reads_through_lifted_estrategia_accessor`
12131 // (921fe1b) two-arm consumer-coherence pin on the M3 mesh-slot
12132 // `Copy`-return discriminant axis — same "the entry-gate
12133 // predicate and the error carrier's `actual:` field must route
12134 // through the substrate-primitive typed dispatch" discipline
12135 // extended onto the outer top-level [`Caixa`] universal-axis
12136 // discriminant surface.
12137 for expected in [
12138 CaixaKind::Biblioteca,
12139 CaixaKind::Binario,
12140 CaixaKind::Servico,
12141 CaixaKind::Supervisor,
12142 CaixaKind::Aplicacao,
12143 ] {
12144 for actual in [
12145 CaixaKind::Biblioteca,
12146 CaixaKind::Binario,
12147 CaixaKind::Servico,
12148 CaixaKind::Supervisor,
12149 CaixaKind::Aplicacao,
12150 ] {
12151 let c = caixa_with_kind(actual);
12152 let result = crate::render::require_kind(&c, expected);
12153 if expected == actual {
12154 assert!(
12155 result.is_ok(),
12156 "require_kind must accept when actual == expected \
12157 (actual={actual:?}, expected={expected:?})",
12158 );
12159 } else {
12160 let err = result.expect_err("require_kind must reject when actual != expected");
12161 assert_eq!(
12162 err.actual,
12163 c.kind(),
12164 "KindMismatch.actual must byte-equal Caixa::kind() \
12165 — the error carrier's `actual:` field reads \
12166 through the lifted accessor",
12167 );
12168 assert_eq!(
12169 err.expected, expected,
12170 "KindMismatch.expected must byte-equal the \
12171 expected variant passed to require_kind",
12172 );
12173 }
12174 }
12175 }
12176 }
12177
12178 #[test]
12179 fn aplicacao_view_kind_gate_routes_through_accessor() {
12180 // Composition pin: [`Caixa::aplicacao_view`]'s kind-gate arm
12181 // must key off [`Caixa::kind`], not the raw `.kind` field
12182 // access. Structurally: a `Caixa { kind: X, .. }` for any
12183 // non-`Aplicacao` variant must fold to `None` on the
12184 // `aplicacao_view` composer (the "kind mismatch → no typed
12185 // view" contract every downstream Aplicacao consumer keys off
12186 // via `?`), and a `Caixa { kind: Aplicacao, .. }` must fold to
12187 // `Some(_)`. The pair jointly pins the accessor + view-gate
12188 // composition: any future silent detour that had the accessor
12189 // return a fresh [`CaixaKind::Aplicacao`] on some sentinel
12190 // input would silently absorb the kind-mismatch case at the
12191 // accessor boundary and every per-Aplicacao renderer would
12192 // silently render a non-Aplicacao caixa's mesh slots — the
12193 // composition pin catches that at caixa-core build time.
12194 //
12195 // Peer of the sibling per-`Caixa`
12196 // `validate_nome_empty_arm_routes_through_accessor` (e6b7d97) /
12197 // `validate_versao_empty_arm_routes_through_accessor` (20c0539)
12198 // composition pins on the sibling outer top-level [`Caixa`]
12199 // required-`&str` universal-axis surfaces — same "the
12200 // composer / validate gate must route through the substrate-
12201 // primitive typed dispatch" discipline extended onto the
12202 // outer top-level [`Caixa`] `Copy`-return required-
12203 // discriminant composition axis.
12204 for kind in [
12205 CaixaKind::Biblioteca,
12206 CaixaKind::Binario,
12207 CaixaKind::Servico,
12208 CaixaKind::Supervisor,
12209 ] {
12210 let c = caixa_with_kind(kind);
12211 assert!(
12212 c.aplicacao_view().is_none(),
12213 "aplicacao_view must return None on non-Aplicacao \
12214 kind {kind:?} — the composer's kind-gate must route \
12215 through Caixa::kind()",
12216 );
12217 }
12218 let c = caixa_with_kind(CaixaKind::Aplicacao);
12219 assert!(
12220 c.aplicacao_view().is_some(),
12221 "aplicacao_view must return Some on kind Aplicacao — \
12222 the composer's kind-gate must accept the matching arm \
12223 through Caixa::kind()",
12224 );
12225 }
12226
12227 #[test]
12228 fn supervisor_view_kind_gate_routes_through_accessor() {
12229 // Composition pin (mirror of the sibling
12230 // `aplicacao_view_kind_gate_routes_through_accessor` on the
12231 // second `_view` composer): [`Caixa::supervisor_view`]'s kind-
12232 // gate arm must key off [`Caixa::kind`], not the raw `.kind`
12233 // field access. A `Caixa { kind: X, .. }` for any non-
12234 // `Supervisor` variant must fold to `None` on the
12235 // `supervisor_view` composer, and a `Caixa { kind:
12236 // Supervisor, .. }` must fold to `Some(_)`. Same peer
12237 // composition pin discipline on the second `_view` composer
12238 // axis.
12239 for kind in [
12240 CaixaKind::Biblioteca,
12241 CaixaKind::Binario,
12242 CaixaKind::Servico,
12243 CaixaKind::Aplicacao,
12244 ] {
12245 let c = caixa_with_kind(kind);
12246 assert!(
12247 c.supervisor_view().is_none(),
12248 "supervisor_view must return None on non-Supervisor \
12249 kind {kind:?} — the composer's kind-gate must route \
12250 through Caixa::kind()",
12251 );
12252 }
12253 let mut c = caixa_with_kind(CaixaKind::Supervisor);
12254 // A Supervisor caixa needs a strategy + at least one child to
12255 // fold to a Some(_) that also validates; the composer itself
12256 // requires only the kind arm, so bare kind flip is enough to
12257 // pin the `Some(_)` return, but we populate the minimum
12258 // supervisor shape so a future strengthening of the composer
12259 // to reject an empty spec doesn't false-positive this pin.
12260 c.estrategia = Some(crate::supervisor::RestartStrategy::OneForOne);
12261 c.children = vec![crate::supervisor::ChildSpec {
12262 caixa: "child".into(),
12263 versao: "^0.1".into(),
12264 restart: crate::supervisor::RestartPolicy::Permanent,
12265 }];
12266 assert!(
12267 c.supervisor_view().is_some(),
12268 "supervisor_view must return Some on kind Supervisor — \
12269 the composer's kind-gate must accept the matching arm \
12270 through Caixa::kind()",
12271 );
12272 }
12273
12274 #[test]
12275 fn kind_projects_by_copy() {
12276 // The by-`Copy` pin: [`Caixa::kind`] returns a fresh
12277 // [`CaixaKind`] by `Copy` — the accessor must not borrow from
12278 // `&self` (the returned value is owned, `Copy`-projected from
12279 // the underlying [`CaixaKind`] storage; two calls on the same
12280 // [`Caixa`] must yield byte-equal values). Peer of the peer
12281 // per-`:placement` `Placement::estrategia` / per-`:supervisor`
12282 // `SupervisorSpec::estrategia` / per-`:children`
12283 // `ChildSpec::restart` `Copy`-return discriminant accessor
12284 // pins on the sibling nested-spec typed-slot discriminator
12285 // axes, extended onto the first outer top-level [`Caixa`]
12286 // required-`Copy`-return axis — pins against a future silent
12287 // detour that returned `&CaixaKind` (which would type-check
12288 // but silently constrain every consumer's callsite to a
12289 // borrow-shaped dispatch, breaking the zero-cost `Copy`
12290 // projection every peer sibling accessor carries).
12291 for kind in [
12292 CaixaKind::Biblioteca,
12293 CaixaKind::Binario,
12294 CaixaKind::Servico,
12295 CaixaKind::Supervisor,
12296 CaixaKind::Aplicacao,
12297 ] {
12298 let c = caixa_with_kind(kind);
12299 let first: CaixaKind = c.kind();
12300 let second: CaixaKind = c.kind();
12301 assert_eq!(
12302 first, second,
12303 "Caixa::kind must be idempotent — two successive \
12304 calls on the same &self must return the same \
12305 CaixaKind variant",
12306 );
12307 assert_eq!(
12308 first, kind,
12309 "Caixa::kind must return :kind verbatim by Copy — \
12310 got {first:?}, expected {kind:?}",
12311 );
12312 }
12313 }
12314
12315 // ── Caixa::autores — outer top-level &[T] slice accessor ──────────
12316
12317 #[test]
12318 fn autores_returns_autores_slice_verbatim_across_permutations() {
12319 // The canonical per-`Caixa` `:autores` universal-axis maintainer-
12320 // name-list slice pin: [`Caixa::autores`] must return the
12321 // `:autores` typed [`Vec<String>`] list verbatim as a
12322 // `&[String]`, byte-equal to the raw `self.autores.as_slice()`
12323 // access across every representative value in the accept-set —
12324 // `[]` (the "no maintainers declared" arm every existing
12325 // fixture without an `:autores` line carries), `[""]` (a past-
12326 // the-guard sentinel that pins the accessor doesn't perform a
12327 // silent `[""] → []` collapse on the empty-entry arm — validate
12328 // rejects `[""]` through `AutorEmpty` but the accessor must
12329 // ship the raw slot verbatim so a validate-time gate regression
12330 // surfaces at the caixa-helm emit boundary rather than being
12331 // silently absorbed into a maintainer-drop), `["pleme-io"]` (the
12332 // canonical single-maintainer form every `feira init` template
12333 // scaffolds), `["alice", "bob"]` (a canonical multi-maintainer
12334 // form), `["alice <alice@example.com>", "bob <bob@example.com>"]`
12335 // (the canonical RFC-5322 `<name> <email>` form the
12336 // `is_chart_maintainer_name_shape` predicate accepts), and
12337 // `["pleme-io", "pleme-io"]` (a past-the-guard duplicate
12338 // sentinel — validate rejects through `AutorDuplicate` but the
12339 // accessor must ship the raw slot verbatim).
12340 //
12341 // First outer top-level [`Caixa`] `&[T]`-return slice accessor
12342 // pin on the substrate primitive — opens the "outer [`Caixa`]
12343 // `&[T]` slice" projection pattern the sibling per-`Caixa`
12344 // `:etiquetas` / `:deps` / `:deps-dev` / `:exe` / `:bibliotecas`
12345 // / `:servicos` / `:upgrade-from` / `:children` future lifts
12346 // fold on. Sibling in shape to the peer per-`:supervisor`
12347 // [`crate::supervisor::SupervisorSpec::children`] (bc92bce),
12348 // per-`:placement` [`crate::aplicacao::Placement::clusters`]
12349 // (a6e18d7), per-`:membros`
12350 // [`crate::aplicacao::AplicacaoSpec::membros`] (6c77e36),
12351 // per-`:contratos` [`crate::aplicacao::AplicacaoSpec::contratos`]
12352 // (0dcc926), and per-`:upgrade-from :instructions`
12353 // [`crate::upgrade::UpgradeFromEntry::instructions`] (0137e5a)
12354 // `&[T]`-return slice accessor pins on the sibling per-M2 /
12355 // per-M3 typed-slot list axes, extended onto the outer top-
12356 // level [`Caixa`] universal-axis surface. Pins against a future
12357 // silent detour that returned an owned `Vec<String>` (which
12358 // would type-check but silently clone on every accessor call,
12359 // breaking the zero-cost projection every peer sibling slice
12360 // accessor carries), a `[""] → []` collapse (which would
12361 // silently absorb the `AutorEmpty` refusal case at the accessor
12362 // boundary), or a `["a", "a"] → ["a"]` dedup collapse (which
12363 // would silently absorb the `AutorDuplicate` refusal case at
12364 // the accessor boundary and the caixa-helm `maintainers:` fold
12365 // would silently render a dedupped list on a struct-literal
12366 // `Caixa { autores: vec!["a".into(), "a".into()], .. }`).
12367 for autores in [
12368 vec![],
12369 vec![""],
12370 vec!["pleme-io"],
12371 vec!["alice", "bob"],
12372 vec!["alice <alice@example.com>", "bob <bob@example.com>"],
12373 vec!["pleme-io", "pleme-io"],
12374 ] {
12375 let c = caixa_with_autores(autores.clone());
12376 let expected: Vec<String> = autores.iter().map(|s| (*s).to_string()).collect();
12377 assert_eq!(
12378 c.autores(),
12379 expected.as_slice(),
12380 "Caixa::autores must return :autores verbatim (got {:?}, \
12381 expected {expected:?})",
12382 c.autores(),
12383 );
12384 assert_eq!(
12385 c.autores(),
12386 c.autores.as_slice(),
12387 "Caixa::autores must byte-equal the raw \
12388 `self.autores.as_slice()` field access across every \
12389 value in the Vec<String> accept-set",
12390 );
12391 }
12392 }
12393
12394 #[test]
12395 fn validate_autores_empty_entry_arm_routes_through_accessor() {
12396 // Composition pin: [`Caixa::validate_autores`]'s per-entry
12397 // empty-arm gate must key off [`Caixa::autores`], not the raw
12398 // `&self.autores` field-borrow walk. Structurally: a
12399 // `Caixa { autores: vec!["".into()], .. }` must surface the
12400 // `AutorEmpty` refusal exactly, and a
12401 // `Caixa { autores: vec!["pleme-io".into()], .. }` (the
12402 // canonical single-maintainer form) must pass validate. The
12403 // pair jointly pins the accessor + validate-gate composition:
12404 // any future silent detour that had the accessor return an
12405 // empty slice on the `[""]` arm (a
12406 // `.iter().filter(|s| !s.is_empty()).collect()` collapse)
12407 // would silently absorb the `AutorEmpty` refusal at the
12408 // accessor boundary and the validate gate would accept a
12409 // struct-literal `Caixa { autores: vec!["".into()], .. }` —
12410 // the composition pin catches that at caixa-core build time.
12411 //
12412 // Peer of the per-`Caixa` [`Caixa::validate_licenca`] (6d5bc28)
12413 // accessor-composition pin
12414 // (`validate_licenca_empty_arm_routes_through_accessor`) on the
12415 // sibling `Option<&str>`-composition axis and the
12416 // per-`:politicas :circuit-breaker`
12417 // [`crate::aplicacao::CircuitBreaker::max_failures`] (3a74062)
12418 // accessor-composition pin
12419 // (`validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`)
12420 // on the sibling required-`u32`-composition axis — same "the
12421 // validate / shape-gate predicate must route through the
12422 // substrate-primitive typed dispatch" discipline extended onto
12423 // the outer top-level [`Caixa`] universal-axis `&[T]`-
12424 // composition surface.
12425 let c = caixa_with_autores(vec![""]);
12426 assert!(
12427 matches!(c.validate_autores(), Err(ManifestError::AutorEmpty)),
12428 "validate_autores must reject autores == vec![\"\"] with \
12429 AutorEmpty — the accessor and the validate gate must \
12430 route through the same substrate-primitive typed dispatch \
12431 on the :autores per-entry empty arm",
12432 );
12433 let c = caixa_with_autores(vec!["pleme-io"]);
12434 assert!(
12435 c.validate_autores().is_ok(),
12436 "validate_autores must accept autores == vec![\"pleme-io\"] \
12437 (the canonical single-maintainer shape every `feira init` \
12438 template scaffolds)",
12439 );
12440 }
12441
12442 #[test]
12443 fn autores_projects_slice_by_borrow() {
12444 // The by-borrow pin: [`Caixa::autores`] returns `&[String]` by
12445 // borrow — the returned slice borrows the underlying
12446 // `Vec<String>` storage of the `:autores` slot and the
12447 // accessor must not clone the backing `Vec` on every call.
12448 // Peer of the per-`:membros`
12449 // [`crate::aplicacao::AplicacaoSpec::membros`] (6c77e36) /
12450 // per-`:contratos` [`crate::aplicacao::AplicacaoSpec::contratos`]
12451 // (0dcc926) / per-`:placement`
12452 // [`crate::aplicacao::Placement::clusters`] (a6e18d7) /
12453 // per-`:supervisor` [`crate::supervisor::SupervisorSpec::children`]
12454 // (bc92bce) by-borrow pins on the sibling per-M2 / per-M3
12455 // typed-slot `&[T]`-return axes, extended onto the outer top-
12456 // level [`Caixa`] universal-axis `&[String]` shape — the
12457 // accessor's returned slice must borrow from `&self` (the
12458 // returned reference's lifetime is tied to `&self`), and
12459 // calling the accessor twice on the same [`Caixa`] must yield
12460 // slices that are pointer-equal (the underlying byte-buffer is
12461 // the storage `Vec`'s allocation, not a fresh copy) as well as
12462 // value-equal (idempotent, no side effects on `&self`).
12463 //
12464 // Pins against a future silent detour that returned an owned
12465 // `Vec<String>` (which would type-check but silently clone on
12466 // every call, breaking the zero-cost projection every peer
12467 // sibling slice accessor carries), a `&Vec<String>` return
12468 // (which would leak the backing `Vec`'s grow/push/reserve
12469 // surface no downstream consumer reaches for), or a one-arm-
12470 // only accessor that returned a saturating value on some
12471 // sentinel input (breaking the pass-through invariant the
12472 // sibling slice accessors carry).
12473 for autores in [
12474 vec![],
12475 vec!["pleme-io"],
12476 vec!["alice", "bob"],
12477 vec!["pleme-io", "pleme-io"],
12478 ] {
12479 let c = caixa_with_autores(autores.clone());
12480 let expected: Vec<String> = autores.iter().map(|s| (*s).to_string()).collect();
12481 let first = c.autores();
12482 let second = c.autores();
12483 assert_eq!(
12484 first, second,
12485 "Caixa::autores must be idempotent — two successive \
12486 calls on the same &self must return the same \
12487 &[String]",
12488 );
12489 assert_eq!(
12490 first.as_ptr(),
12491 second.as_ptr(),
12492 "Caixa::autores must borrow the underlying Vec<String> \
12493 storage — two successive calls must return slices \
12494 with the same backing pointer (a fresh Vec<String> \
12495 clone would change the pointer on every call)",
12496 );
12497 assert_eq!(
12498 first,
12499 expected.as_slice(),
12500 "Caixa::autores must return :autores verbatim by \
12501 borrow — got {first:?}, expected {expected:?}",
12502 );
12503 }
12504 }
12505
12506 // ── Caixa::etiquetas — outer top-level &[T] slice accessor ────────
12507
12508 #[test]
12509 fn etiquetas_returns_etiquetas_slice_verbatim_across_permutations() {
12510 // The canonical per-`Caixa` `:etiquetas` universal-axis
12511 // registry-search-tag-list slice pin: [`Caixa::etiquetas`] must
12512 // return the `:etiquetas` typed [`Vec<String>`] list verbatim
12513 // as a `&[String]`, byte-equal to the raw
12514 // `self.etiquetas.as_slice()` access across every representative
12515 // value in the accept-set — `[]` (the "no tags declared" arm
12516 // every existing fixture without an `:etiquetas` line carries),
12517 // `[""]` (a past-the-guard sentinel that pins the accessor
12518 // doesn't perform a silent `[""] → []` collapse on the empty-
12519 // entry arm — validate rejects `[""]` through `EtiquetaEmpty`
12520 // but the accessor must ship the raw slot verbatim so a
12521 // validate-time gate regression surfaces at the caixa-helm emit
12522 // boundary rather than being silently absorbed into a keyword-
12523 // drop), `["demo"]` (the canonical single-tag form every
12524 // `feira init` template scaffolds), `["example", "aplicacao",
12525 // "mesh", "ecommerce", "demo"]` (the canonical multi-tag form
12526 // the checkout-aplicacao fixture emits), and `["demo", "demo"]`
12527 // (a past-the-guard duplicate sentinel — validate rejects
12528 // through `EtiquetaDuplicate` but the accessor must ship the
12529 // raw slot verbatim so the caixa-helm `BTreeSet::collect` dedup
12530 // at chart-render time isn't silently promoted into the
12531 // accessor boundary and struct-literal
12532 // `Caixa { etiquetas: vec!["demo".into(), "demo".into()], .. }`
12533 // fixtures continue to expose the duplicate at the accessor).
12534 //
12535 // Second outer top-level [`Caixa`] `&[T]`-return slice accessor
12536 // pin on the substrate primitive — folds on the "outer
12537 // [`Caixa`] `&[T]` slice" projection pattern
12538 // `autores_returns_autores_slice_verbatim_across_permutations`
12539 // (b5d813f) opened, sibling in shape and idiom. Pins against a
12540 // future silent detour that returned an owned `Vec<String>`
12541 // (which would type-check but silently clone on every accessor
12542 // call, breaking the zero-cost projection every peer sibling
12543 // slice accessor carries), a `[""] → []` collapse (which would
12544 // silently absorb the `EtiquetaEmpty` refusal case at the
12545 // accessor boundary), or a `["a", "a"] → ["a"]` dedup collapse
12546 // (which would silently absorb the `EtiquetaDuplicate` refusal
12547 // case at the accessor boundary — the caixa-helm chart-render
12548 // `BTreeSet::collect` dedup is downstream of the accessor and
12549 // must not be silently promoted into it).
12550 for etiquetas in [
12551 vec![],
12552 vec![""],
12553 vec!["demo"],
12554 vec!["example", "aplicacao", "mesh", "ecommerce", "demo"],
12555 vec!["demo", "demo"],
12556 ] {
12557 let c = caixa_with_etiquetas(etiquetas.clone());
12558 let expected: Vec<String> = etiquetas.iter().map(|s| (*s).to_string()).collect();
12559 assert_eq!(
12560 c.etiquetas(),
12561 expected.as_slice(),
12562 "Caixa::etiquetas must return :etiquetas verbatim (got \
12563 {:?}, expected {expected:?})",
12564 c.etiquetas(),
12565 );
12566 assert_eq!(
12567 c.etiquetas(),
12568 c.etiquetas.as_slice(),
12569 "Caixa::etiquetas must byte-equal the raw \
12570 `self.etiquetas.as_slice()` field access across every \
12571 value in the Vec<String> accept-set",
12572 );
12573 }
12574 }
12575
12576 #[test]
12577 fn validate_etiquetas_empty_entry_arm_routes_through_accessor() {
12578 // Composition pin: [`Caixa::validate_etiquetas`]'s per-entry
12579 // empty-arm gate must key off [`Caixa::etiquetas`], not the raw
12580 // `&self.etiquetas` field-borrow walk. Structurally: a
12581 // `Caixa { etiquetas: vec!["".into()], .. }` must surface the
12582 // `EtiquetaEmpty` refusal exactly, and a
12583 // `Caixa { etiquetas: vec!["demo".into()], .. }` (the canonical
12584 // single-tag form) must pass validate. The pair jointly pins
12585 // the accessor + validate-gate composition: any future silent
12586 // detour that had the accessor return an empty slice on the
12587 // `[""]` arm (a
12588 // `.iter().filter(|s| !s.is_empty()).collect()` collapse) would
12589 // silently absorb the `EtiquetaEmpty` refusal at the accessor
12590 // boundary and the validate gate would accept a struct-literal
12591 // `Caixa { etiquetas: vec!["".into()], .. }` — the composition
12592 // pin catches that at caixa-core build time.
12593 //
12594 // Peer of the per-`Caixa` `validate_autores_empty_arm_routes_
12595 // through_accessor` (b5d813f) accessor-composition pin on the
12596 // sibling `&[T]`-composition axis — same "the validate / shape-
12597 // gate predicate must route through the substrate-primitive
12598 // typed dispatch" discipline extended onto the sibling outer
12599 // top-level [`Caixa`] `&[T]`-composition surface.
12600 let c = caixa_with_etiquetas(vec![""]);
12601 assert!(
12602 matches!(c.validate_etiquetas(), Err(ManifestError::EtiquetaEmpty)),
12603 "validate_etiquetas must reject etiquetas == vec![\"\"] \
12604 with EtiquetaEmpty — the accessor and the validate gate \
12605 must route through the same substrate-primitive typed \
12606 dispatch on the :etiquetas per-entry empty arm",
12607 );
12608 let c = caixa_with_etiquetas(vec!["demo"]);
12609 assert!(
12610 c.validate_etiquetas().is_ok(),
12611 "validate_etiquetas must accept etiquetas == vec![\"demo\"] \
12612 (the canonical single-tag shape every `feira init` \
12613 template scaffolds)",
12614 );
12615 }
12616
12617 #[test]
12618 fn etiquetas_projects_slice_by_borrow() {
12619 // The by-borrow pin: [`Caixa::etiquetas`] returns `&[String]`
12620 // by borrow — the returned slice borrows the underlying
12621 // `Vec<String>` storage of the `:etiquetas` slot and the
12622 // accessor must not clone the backing `Vec` on every call.
12623 // Peer of the per-`Caixa` `autores_projects_slice_by_borrow`
12624 // (b5d813f) by-borrow pin on the sibling outer top-level
12625 // [`Caixa`] `&[String]`-return axis — the accessor's returned
12626 // slice must borrow from `&self` (the returned reference's
12627 // lifetime is tied to `&self`), and calling the accessor twice
12628 // on the same [`Caixa`] must yield slices that are pointer-
12629 // equal (the underlying byte-buffer is the storage `Vec`'s
12630 // allocation, not a fresh copy) as well as value-equal
12631 // (idempotent, no side effects on `&self`).
12632 //
12633 // Pins against a future silent detour that returned an owned
12634 // `Vec<String>` (which would type-check but silently clone on
12635 // every call, breaking the zero-cost projection every peer
12636 // sibling slice accessor carries), a `&Vec<String>` return
12637 // (which would leak the backing `Vec`'s grow/push/reserve
12638 // surface no downstream consumer reaches for), or a one-arm-
12639 // only accessor that returned a saturating value on some
12640 // sentinel input (breaking the pass-through invariant the
12641 // sibling slice accessors carry).
12642 for etiquetas in [
12643 vec![],
12644 vec!["demo"],
12645 vec!["example", "aplicacao", "mesh"],
12646 vec!["demo", "demo"],
12647 ] {
12648 let c = caixa_with_etiquetas(etiquetas.clone());
12649 let expected: Vec<String> = etiquetas.iter().map(|s| (*s).to_string()).collect();
12650 let first = c.etiquetas();
12651 let second = c.etiquetas();
12652 assert_eq!(
12653 first, second,
12654 "Caixa::etiquetas must be idempotent — two successive \
12655 calls on the same &self must return the same \
12656 &[String]",
12657 );
12658 assert_eq!(
12659 first.as_ptr(),
12660 second.as_ptr(),
12661 "Caixa::etiquetas must borrow the underlying \
12662 Vec<String> storage — two successive calls must \
12663 return slices with the same backing pointer (a fresh \
12664 Vec<String> clone would change the pointer on every \
12665 call)",
12666 );
12667 assert_eq!(
12668 first,
12669 expected.as_slice(),
12670 "Caixa::etiquetas must return :etiquetas verbatim by \
12671 borrow — got {first:?}, expected {expected:?}",
12672 );
12673 }
12674 }
12675
12676 // ── Caixa::bibliotecas — outer top-level &[T] slice accessor ──────
12677
12678 #[test]
12679 fn bibliotecas_returns_bibliotecas_slice_verbatim_across_permutations() {
12680 // The canonical per-`Caixa` `:bibliotecas` universal-axis
12681 // library-source-path-list slice pin: [`Caixa::bibliotecas`]
12682 // must return the `:bibliotecas` typed [`Vec<String>`] list
12683 // verbatim as a `&[String]`, byte-equal to the raw
12684 // `self.bibliotecas.as_slice()` access across every
12685 // representative value in the accept-set — `[]` (the "no
12686 // libraries declared" arm every `:kind` other than `Biblioteca`
12687 // + every `Biblioteca` relying on the canonical
12688 // `lib/<nome>.lisp` implicit-default path carries; the
12689 // layout's [`crate::LayoutInvariants`] `MissingLib` arm-gate
12690 // fires exactly on this empty-slot + `Biblioteca`-kind
12691 // combination), `[""]` (a past-the-guard sentinel that pins
12692 // the accessor doesn't perform a silent `[""] → []` collapse
12693 // on the empty-entry arm — validate rejects `[""]` through
12694 // `CodePathEmpty { slot: ":bibliotecas" }` but the accessor
12695 // must ship the raw slot verbatim so a validate-time gate
12696 // regression surfaces at the `feira build` phase-1 parse
12697 // boundary rather than being silently absorbed into a
12698 // library-drop), `["lib/demo.lisp"]` (the canonical single-
12699 // entry form `Caixa::template` scaffolds and every `feira init`
12700 // template emits), `["lib/demo.lisp", "lib/helpers.lisp"]`
12701 // (the canonical multi-library form the
12702 // `validate_code_paths_accepts_explicit_relative_paths_on_
12703 // every_slot` fixture emits), and `["lib/foo.lisp",
12704 // "lib/foo.lisp"]` (a past-the-guard duplicate sentinel —
12705 // validate rejects through `CodePathDuplicate { slot:
12706 // ":bibliotecas" }` per the per-slot set-not-multiset gate,
12707 // but the accessor must ship the raw slot verbatim so the
12708 // `feira build` `for entry in caixa.bibliotecas()` parse walk
12709 // sees the duplicate at the accessor boundary and struct-
12710 // literal `Caixa { bibliotecas: vec!["lib/foo.lisp".into(),
12711 // "lib/foo.lisp".into()], .. }` fixtures continue to expose
12712 // the duplicate at the accessor).
12713 //
12714 // Third outer top-level [`Caixa`] `&[T]`-return slice accessor
12715 // pin on the substrate primitive — folds on the "outer
12716 // [`Caixa`] `&[T]` slice" projection pattern
12717 // `autores_returns_autores_slice_verbatim_across_permutations`
12718 // (b5d813f) opened and
12719 // `etiquetas_returns_etiquetas_slice_verbatim_across_permutations`
12720 // (78c7d3c) folded on, sibling in shape and idiom. Pins
12721 // against a future silent detour that returned an owned
12722 // `Vec<String>` (which would type-check but silently clone on
12723 // every accessor call, breaking the zero-cost projection
12724 // every peer sibling slice accessor carries), a `[""] → []`
12725 // collapse (which would silently absorb the `CodePathEmpty`
12726 // refusal case at the accessor boundary), or a `["lib/foo.lisp",
12727 // "lib/foo.lisp"] → ["lib/foo.lisp"]` dedup collapse (which
12728 // would silently absorb the `CodePathDuplicate` refusal case
12729 // at the accessor boundary — the per-slot set-not-multiset
12730 // gate is downstream of the accessor and must not be silently
12731 // promoted into it).
12732 for bibliotecas in [
12733 vec![],
12734 vec![""],
12735 vec!["lib/demo.lisp"],
12736 vec!["lib/demo.lisp", "lib/helpers.lisp"],
12737 vec!["lib/foo.lisp", "lib/foo.lisp"],
12738 ] {
12739 let c = caixa_with_code_paths(bibliotecas.clone(), vec![], vec![]);
12740 let expected: Vec<String> = bibliotecas.iter().map(|s| (*s).to_string()).collect();
12741 assert_eq!(
12742 c.bibliotecas(),
12743 expected.as_slice(),
12744 "Caixa::bibliotecas must return :bibliotecas verbatim \
12745 (got {:?}, expected {expected:?})",
12746 c.bibliotecas(),
12747 );
12748 assert_eq!(
12749 c.bibliotecas(),
12750 c.bibliotecas.as_slice(),
12751 "Caixa::bibliotecas must byte-equal the raw \
12752 `self.bibliotecas.as_slice()` field access across \
12753 every value in the Vec<String> accept-set",
12754 );
12755 }
12756 }
12757
12758 #[test]
12759 fn validate_code_paths_bibliotecas_empty_arm_routes_through_accessor() {
12760 // Composition pin: [`Caixa::validate_code_paths`]'s per-entry
12761 // empty-arm gate on the `:bibliotecas` slot must key off
12762 // [`Caixa::bibliotecas`], not a divergent raw
12763 // `&self.bibliotecas` field-borrow walk. Structurally: a
12764 // `Caixa { bibliotecas: vec!["".into()], .. }` must surface
12765 // the `CodePathEmpty { slot: ":bibliotecas" }` refusal
12766 // exactly, and a `Caixa { bibliotecas: vec!["lib/demo.lisp".
12767 // into()], .. }` (the canonical single-library form
12768 // `Caixa::template` scaffolds) must pass validate. The pair
12769 // jointly pins the accessor + validate-gate composition: any
12770 // future silent detour that had the accessor return an empty
12771 // slice on the `[""]` arm (a `.iter().filter(|s|
12772 // !s.is_empty()).collect()` collapse) would silently absorb
12773 // the `CodePathEmpty` refusal at the accessor boundary and
12774 // the validate gate would accept a struct-literal
12775 // `Caixa { bibliotecas: vec!["".into()], .. }` — the
12776 // composition pin catches that at caixa-core build time.
12777 //
12778 // Peer of the per-`Caixa` `validate_autores_empty_arm_routes_
12779 // through_accessor` (b5d813f) and
12780 // `validate_etiquetas_empty_entry_arm_routes_through_accessor`
12781 // (78c7d3c) accessor-composition pins on the sibling `&[T]`-
12782 // composition axes — same "the validate / shape-gate
12783 // predicate must route through the substrate-primitive typed
12784 // dispatch" discipline extended onto the sibling outer top-
12785 // level [`Caixa`] `&[T]`-composition surface. Nominally the
12786 // in-tree `validate_code_paths` production body still keys
12787 // off the internal `[(":bibliotecas", &self.bibliotecas,
12788 // CodePathFileType::LispSource), (":exe", &self.exe, ..),
12789 // (":servicos", &self.servicos, ..)]` per-slot dispatch tuple
12790 // (the tuple's homogeneous slice-typed shape blocks a per-
12791 // element accessor swap in isolation — a future companion
12792 // lift for `:exe` and `:servicos` on the same outer-`Caixa`
12793 // `&[T]` slice-accessor axis closes that tuple onto the
12794 // triple of typed dispatches as a unit); the composition pin
12795 // catches any future accessor-side silent filter drop against
12796 // that eventual tuple-closure regardless of whether the
12797 // `:bibliotecas` slot is threaded through the accessor or the
12798 // raw field access at the tuple's construction site.
12799 let c = caixa_with_code_paths(vec![""], vec![], vec![]);
12800 assert!(
12801 matches!(
12802 c.validate_code_paths(),
12803 Err(ManifestError::CodePathEmpty {
12804 slot: ":bibliotecas"
12805 })
12806 ),
12807 "validate_code_paths must reject bibliotecas == vec![\"\"] \
12808 with CodePathEmpty {{ slot: \":bibliotecas\" }} — the \
12809 accessor and the validate gate must route through the \
12810 same substrate-primitive typed dispatch on the \
12811 :bibliotecas per-entry empty arm",
12812 );
12813 let c = caixa_with_code_paths(vec!["lib/demo.lisp"], vec![], vec![]);
12814 assert!(
12815 c.validate_code_paths().is_ok(),
12816 "validate_code_paths must accept bibliotecas == \
12817 vec![\"lib/demo.lisp\"] (the canonical single-library \
12818 shape every `feira init` template scaffolds)",
12819 );
12820 }
12821
12822 #[test]
12823 fn bibliotecas_projects_slice_by_borrow() {
12824 // The by-borrow pin: [`Caixa::bibliotecas`] returns
12825 // `&[String]` by borrow — the returned slice borrows the
12826 // underlying `Vec<String>` storage of the `:bibliotecas` slot
12827 // and the accessor must not clone the backing `Vec` on every
12828 // call. Peer of the per-`Caixa` `autores_projects_slice_by_borrow`
12829 // (b5d813f) and `etiquetas_projects_slice_by_borrow` (78c7d3c)
12830 // by-borrow pins on the sibling outer top-level [`Caixa`]
12831 // `&[String]`-return axes — the accessor's returned slice
12832 // must borrow from `&self` (the returned reference's lifetime
12833 // is tied to `&self`), and calling the accessor twice on the
12834 // same [`Caixa`] must yield slices that are pointer-equal
12835 // (the underlying byte-buffer is the storage `Vec`'s
12836 // allocation, not a fresh copy) as well as value-equal
12837 // (idempotent, no side effects on `&self`).
12838 //
12839 // Pins against a future silent detour that returned an owned
12840 // `Vec<String>` (which would type-check but silently clone on
12841 // every call, breaking the zero-cost projection every peer
12842 // sibling slice accessor carries), a `&Vec<String>` return
12843 // (which would leak the backing `Vec`'s grow/push/reserve
12844 // surface no downstream consumer reaches for), or a one-arm-
12845 // only accessor that returned a saturating value on some
12846 // sentinel input (breaking the pass-through invariant the
12847 // sibling slice accessors carry).
12848 for bibliotecas in [
12849 vec![],
12850 vec!["lib/demo.lisp"],
12851 vec!["lib/demo.lisp", "lib/helpers.lisp"],
12852 vec!["lib/foo.lisp", "lib/foo.lisp"],
12853 ] {
12854 let c = caixa_with_code_paths(bibliotecas.clone(), vec![], vec![]);
12855 let expected: Vec<String> = bibliotecas.iter().map(|s| (*s).to_string()).collect();
12856 let first = c.bibliotecas();
12857 let second = c.bibliotecas();
12858 assert_eq!(
12859 first, second,
12860 "Caixa::bibliotecas must be idempotent — two \
12861 successive calls on the same &self must return the \
12862 same &[String]",
12863 );
12864 assert_eq!(
12865 first.as_ptr(),
12866 second.as_ptr(),
12867 "Caixa::bibliotecas must borrow the underlying \
12868 Vec<String> storage — two successive calls must \
12869 return slices with the same backing pointer (a \
12870 fresh Vec<String> clone would change the pointer on \
12871 every call)",
12872 );
12873 assert_eq!(
12874 first,
12875 expected.as_slice(),
12876 "Caixa::bibliotecas must return :bibliotecas verbatim \
12877 by borrow — got {first:?}, expected {expected:?}",
12878 );
12879 }
12880 }
12881
12882 // ── Caixa::exe — outer top-level &[T] slice accessor ──────────────
12883
12884 #[test]
12885 fn exe_returns_exe_slice_verbatim_across_permutations() {
12886 // The canonical per-`Caixa` `:exe` universal-axis
12887 // nix-built-executable-entry-path-list slice pin: [`Caixa::exe`]
12888 // must return the `:exe` typed [`Vec<String>`] list verbatim as
12889 // a `&[String]`, byte-equal to the raw `self.exe.as_slice()`
12890 // access across every representative value in the accept-set —
12891 // `[]` (the "no executable declared" arm every `:kind` other
12892 // than `Binario` carries; the layout's [`crate::LayoutInvariants`]
12893 // `BinarioWithoutExe` arm-gate fires exactly on this empty-slot
12894 // + `Binario`-kind combination), `[""]` (a past-the-guard
12895 // sentinel that pins the accessor doesn't perform a silent
12896 // `[""] → []` collapse on the empty-entry arm — validate rejects
12897 // `[""]` through `CodePathEmpty { slot: ":exe" }` but the
12898 // accessor must ship the raw slot verbatim so a validate-time
12899 // gate regression surfaces at the layout / `feira nix` boundary
12900 // rather than being silently absorbed into an executable-drop),
12901 // `["exe/cli"]` (the canonical single-entry Binario form every
12902 // in-tree `caixa_with_code_paths` positive control uses),
12903 // `["exe/cli", "exe/serve"]` (the canonical multi-executable
12904 // form the `validate_code_paths_accepts_explicit_relative_paths_
12905 // on_every_slot` fixture emits), and `["exe/cli", "exe/cli"]`
12906 // (a past-the-guard duplicate sentinel — validate rejects
12907 // through `CodePathDuplicate { slot: ":exe" }` per the per-slot
12908 // set-not-multiset gate, but the accessor must ship the raw
12909 // slot verbatim so struct-literal `Caixa { exe: vec!["exe/cli".
12910 // into(), "exe/cli".into()], .. }` fixtures continue to expose
12911 // the duplicate at the accessor).
12912 //
12913 // Fourth outer top-level [`Caixa`] `&[T]`-return slice accessor
12914 // pin on the substrate primitive — folds on the "outer
12915 // [`Caixa`] `&[T]` slice" projection pattern
12916 // `autores_returns_autores_slice_verbatim_across_permutations`
12917 // (b5d813f) opened,
12918 // `etiquetas_returns_etiquetas_slice_verbatim_across_permutations`
12919 // (78c7d3c) folded on, and
12920 // `bibliotecas_returns_bibliotecas_slice_verbatim_across_permutations`
12921 // (8a36c23) closed the universal-axis text-tag family of.
12922 // Opens the outer-`Caixa` foreign-code-slot `&[T]` sub-family
12923 // the sibling `:servicos` future lift closes onto. Pins against
12924 // a future silent detour that returned an owned `Vec<String>`
12925 // (which would type-check but silently clone on every accessor
12926 // call, breaking the zero-cost projection every peer sibling
12927 // slice accessor carries), a `[""] → []` collapse (which would
12928 // silently absorb the `CodePathEmpty` refusal case at the
12929 // accessor boundary), or an `["exe/cli", "exe/cli"] →
12930 // ["exe/cli"]` dedup collapse (which would silently absorb the
12931 // `CodePathDuplicate` refusal case at the accessor boundary —
12932 // the per-slot set-not-multiset gate is downstream of the
12933 // accessor and must not be silently promoted into it).
12934 for exe in [
12935 vec![],
12936 vec![""],
12937 vec!["exe/cli"],
12938 vec!["exe/cli", "exe/serve"],
12939 vec!["exe/cli", "exe/cli"],
12940 ] {
12941 let c = caixa_with_code_paths(vec![], exe.clone(), vec![]);
12942 let expected: Vec<String> = exe.iter().map(|s| (*s).to_string()).collect();
12943 assert_eq!(
12944 c.exe(),
12945 expected.as_slice(),
12946 "Caixa::exe must return :exe verbatim (got {:?}, \
12947 expected {expected:?})",
12948 c.exe(),
12949 );
12950 assert_eq!(
12951 c.exe(),
12952 c.exe.as_slice(),
12953 "Caixa::exe must byte-equal the raw \
12954 `self.exe.as_slice()` field access across every value \
12955 in the Vec<String> accept-set",
12956 );
12957 }
12958 }
12959
12960 #[test]
12961 fn validate_code_paths_exe_empty_arm_routes_through_accessor() {
12962 // Composition pin: [`Caixa::validate_code_paths`]'s per-entry
12963 // empty-arm gate on the `:exe` slot must key off
12964 // [`Caixa::exe`], not a divergent raw `&self.exe` field-borrow
12965 // walk. Structurally: a `Caixa { exe: vec!["".into()], .. }`
12966 // must surface the `CodePathEmpty { slot: ":exe" }` refusal
12967 // exactly, and a `Caixa { exe: vec!["exe/cli".into()], .. }`
12968 // (the canonical single-executable form every in-tree
12969 // `caixa_with_code_paths` positive control uses) must pass
12970 // validate. The pair jointly pins the accessor + validate-gate
12971 // composition: any future silent detour that had the accessor
12972 // return an empty slice on the `[""]` arm (a
12973 // `.iter().filter(|s| !s.is_empty()).collect()` collapse) would
12974 // silently absorb the `CodePathEmpty` refusal at the accessor
12975 // boundary and the validate gate would accept a struct-literal
12976 // `Caixa { exe: vec!["".into()], .. }` — the composition pin
12977 // catches that at caixa-core build time.
12978 //
12979 // Peer of the per-`Caixa`
12980 // `validate_code_paths_bibliotecas_empty_arm_routes_through_accessor`
12981 // (8a36c23), `validate_autores_empty_arm_routes_through_accessor`
12982 // (b5d813f), and
12983 // `validate_etiquetas_empty_entry_arm_routes_through_accessor`
12984 // (78c7d3c) accessor-composition pins on the sibling `&[T]`-
12985 // composition axes — same "the validate / shape-gate predicate
12986 // must route through the substrate-primitive typed dispatch"
12987 // discipline extended onto the sibling outer top-level [`Caixa`]
12988 // `&[T]`-composition surface. Nominally the in-tree
12989 // `validate_code_paths` production body still keys off the
12990 // internal `[(":bibliotecas", &self.bibliotecas,
12991 // CodePathFileType::LispSource), (":exe", &self.exe, ..),
12992 // (":servicos", &self.servicos, ..)]` per-slot dispatch tuple
12993 // (the tuple's homogeneous slice-typed shape blocks a per-
12994 // element accessor swap in isolation — a future companion lift
12995 // for `:servicos` on the same outer-`Caixa` `&[T]` slice-
12996 // accessor axis closes that tuple onto the triple of typed
12997 // dispatches as a unit); the composition pin catches any future
12998 // accessor-side silent filter drop against that eventual tuple-
12999 // closure regardless of whether the `:exe` slot is threaded
13000 // through the accessor or the raw field access at the tuple's
13001 // construction site.
13002 let c = caixa_with_code_paths(vec![], vec![""], vec![]);
13003 assert!(
13004 matches!(
13005 c.validate_code_paths(),
13006 Err(ManifestError::CodePathEmpty { slot: ":exe" })
13007 ),
13008 "validate_code_paths must reject exe == vec![\"\"] \
13009 with CodePathEmpty {{ slot: \":exe\" }} — the \
13010 accessor and the validate gate must route through the \
13011 same substrate-primitive typed dispatch on the \
13012 :exe per-entry empty arm",
13013 );
13014 let c = caixa_with_code_paths(vec![], vec!["exe/cli"], vec![]);
13015 assert!(
13016 c.validate_code_paths().is_ok(),
13017 "validate_code_paths must accept exe == vec![\"exe/cli\"] \
13018 (the canonical single-executable shape every in-tree \
13019 `caixa_with_code_paths` positive control uses)",
13020 );
13021 }
13022
13023 #[test]
13024 fn exe_projects_slice_by_borrow() {
13025 // The by-borrow pin: [`Caixa::exe`] returns `&[String]` by
13026 // borrow — the returned slice borrows the underlying
13027 // `Vec<String>` storage of the `:exe` slot and the accessor
13028 // must not clone the backing `Vec` on every call. Peer of the
13029 // per-`Caixa` `autores_projects_slice_by_borrow` (b5d813f),
13030 // `etiquetas_projects_slice_by_borrow` (78c7d3c), and
13031 // `bibliotecas_projects_slice_by_borrow` (8a36c23) by-borrow
13032 // pins on the sibling outer top-level [`Caixa`] `&[String]`-
13033 // return axes — the accessor's returned slice must borrow from
13034 // `&self` (the returned reference's lifetime is tied to
13035 // `&self`), and calling the accessor twice on the same
13036 // [`Caixa`] must yield slices that are pointer-equal (the
13037 // underlying byte-buffer is the storage `Vec`'s allocation,
13038 // not a fresh copy) as well as value-equal (idempotent, no
13039 // side effects on `&self`).
13040 //
13041 // Pins against a future silent detour that returned an owned
13042 // `Vec<String>` (which would type-check but silently clone on
13043 // every call, breaking the zero-cost projection every peer
13044 // sibling slice accessor carries), a `&Vec<String>` return
13045 // (which would leak the backing `Vec`'s grow/push/reserve
13046 // surface no downstream consumer reaches for), or a one-arm-
13047 // only accessor that returned a saturating value on some
13048 // sentinel input (breaking the pass-through invariant the
13049 // sibling slice accessors carry).
13050 for exe in [
13051 vec![],
13052 vec!["exe/cli"],
13053 vec!["exe/cli", "exe/serve"],
13054 vec!["exe/cli", "exe/cli"],
13055 ] {
13056 let c = caixa_with_code_paths(vec![], exe.clone(), vec![]);
13057 let expected: Vec<String> = exe.iter().map(|s| (*s).to_string()).collect();
13058 let first = c.exe();
13059 let second = c.exe();
13060 assert_eq!(
13061 first, second,
13062 "Caixa::exe must be idempotent — two successive calls \
13063 on the same &self must return the same &[String]",
13064 );
13065 assert_eq!(
13066 first.as_ptr(),
13067 second.as_ptr(),
13068 "Caixa::exe must borrow the underlying Vec<String> \
13069 storage — two successive calls must return slices \
13070 with the same backing pointer (a fresh Vec<String> \
13071 clone would change the pointer on every call)",
13072 );
13073 assert_eq!(
13074 first,
13075 expected.as_slice(),
13076 "Caixa::exe must return :exe verbatim by borrow — \
13077 got {first:?}, expected {expected:?}",
13078 );
13079 }
13080 }
13081
13082 // ── Caixa::servicos — outer top-level &[T] slice accessor ─────────
13083
13084 #[test]
13085 fn servicos_returns_servicos_slice_verbatim_across_permutations() {
13086 // The canonical per-`Caixa` `:servicos` universal-axis
13087 // ComputeUnit-CR-YAML-entry-path-list slice pin:
13088 // [`Caixa::servicos`] must return the `:servicos` typed
13089 // [`Vec<String>`] list verbatim as a `&[String]`, byte-equal to
13090 // the raw `self.servicos.as_slice()` access across every
13091 // representative value in the accept-set — `[]` (the "no
13092 // ComputeUnit-CR declared" arm every `:kind` other than
13093 // `Servico` carries; the layout's [`crate::LayoutInvariants`]
13094 // `ServicoWithoutServicos` arm-gate fires exactly on this
13095 // empty-slot + `Servico`-kind combination), `[""]` (a past-the-
13096 // guard sentinel that pins the accessor doesn't perform a
13097 // silent `[""] → []` collapse on the empty-entry arm — validate
13098 // rejects `[""]` through `CodePathEmpty { slot: ":servicos" }`
13099 // but the accessor must ship the raw slot verbatim so a
13100 // validate-time gate regression surfaces at the layout /
13101 // per-Servico renderer boundary rather than being silently
13102 // absorbed into a component-drop),
13103 // `["servicos/demo.computeunit.yaml"]` (the canonical
13104 // singleton V0-shape every in-tree `caixa_with_code_paths`
13105 // positive control uses; the same shape
13106 // [`crate::require_single_servico`] admits),
13107 // `["servicos/a.computeunit.yaml", "servicos/b.computeunit.
13108 // yaml"]` (a past-the-guard `len != 1` sentinel — the V0
13109 // singularity gate rejects through `ServicoCountMismatch
13110 // { count: 2 }` but the accessor must ship the raw slot
13111 // verbatim so struct-literal `Caixa { servicos: vec![...,
13112 // ...], .. }` fixtures continue to expose the count at the
13113 // accessor), and `["servicos/a.computeunit.yaml",
13114 // "servicos/a.computeunit.yaml"]` (a past-the-guard duplicate
13115 // sentinel — validate rejects through
13116 // `CodePathDuplicate { slot: ":servicos" }` per the per-slot
13117 // set-not-multiset gate, but the accessor must ship the raw
13118 // slot verbatim so struct-literal fixtures continue to expose
13119 // the duplicate at the accessor).
13120 //
13121 // Fifth and final outer top-level [`Caixa`] `&[T]`-return
13122 // slice accessor pin on the substrate primitive — folds on the
13123 // "outer [`Caixa`] `&[T]` slice" projection pattern
13124 // `autores_returns_autores_slice_verbatim_across_permutations`
13125 // (b5d813f) opened,
13126 // `etiquetas_returns_etiquetas_slice_verbatim_across_permutations`
13127 // (78c7d3c) folded on,
13128 // `bibliotecas_returns_bibliotecas_slice_verbatim_across_permutations`
13129 // (8a36c23) closed the universal-axis text-tag family of, and
13130 // `exe_returns_exe_slice_verbatim_across_permutations`
13131 // (65d9527) opened the foreign-code-slot sub-family of. Closes
13132 // the outer-`Caixa` foreign-code-slot `&[T]` sub-family — the
13133 // trio of code-surface list slots (`:bibliotecas` + `:exe` +
13134 // `:servicos`) now each carries a substrate-canonical slice
13135 // accessor. Pins against a future silent detour that returned
13136 // an owned `Vec<String>` (which would type-check but silently
13137 // clone on every accessor call, breaking the zero-cost
13138 // projection every peer sibling slice accessor carries), a
13139 // `[""] → []` collapse (which would silently absorb the
13140 // `CodePathEmpty` refusal case at the accessor boundary), an
13141 // `[a, a] → [a]` dedup collapse (which would silently absorb
13142 // the `CodePathDuplicate` refusal case at the accessor
13143 // boundary — the per-slot set-not-multiset gate is downstream
13144 // of the accessor and must not be silently promoted into it),
13145 // or a `[a, b] → [a]` singleton collapse (which would silently
13146 // absorb the V0 `ServicoCountMismatch` refusal case at the
13147 // accessor boundary — the V0 singularity gate is downstream of
13148 // the accessor and must not be silently promoted into it).
13149 for servicos in [
13150 vec![],
13151 vec![""],
13152 vec!["servicos/demo.computeunit.yaml"],
13153 vec!["servicos/a.computeunit.yaml", "servicos/b.computeunit.yaml"],
13154 vec!["servicos/a.computeunit.yaml", "servicos/a.computeunit.yaml"],
13155 ] {
13156 let c = caixa_with_code_paths(vec![], vec![], servicos.clone());
13157 let expected: Vec<String> = servicos.iter().map(|s| (*s).to_string()).collect();
13158 assert_eq!(
13159 c.servicos(),
13160 expected.as_slice(),
13161 "Caixa::servicos must return :servicos verbatim (got \
13162 {:?}, expected {expected:?})",
13163 c.servicos(),
13164 );
13165 assert_eq!(
13166 c.servicos(),
13167 c.servicos.as_slice(),
13168 "Caixa::servicos must byte-equal the raw \
13169 `self.servicos.as_slice()` field access across every \
13170 value in the Vec<String> accept-set",
13171 );
13172 }
13173 }
13174
13175 #[test]
13176 fn validate_code_paths_servicos_empty_arm_routes_through_accessor() {
13177 // Composition pin: [`Caixa::validate_code_paths`]'s per-entry
13178 // empty-arm gate on the `:servicos` slot must key off
13179 // [`Caixa::servicos`], not a divergent raw `&self.servicos`
13180 // field-borrow walk. Structurally: a `Caixa { servicos:
13181 // vec!["".into()], .. }` must surface the `CodePathEmpty
13182 // { slot: ":servicos" }` refusal exactly, and a `Caixa
13183 // { servicos: vec!["servicos/demo.computeunit.yaml".into()],
13184 // .. }` (the canonical singleton V0-shape every in-tree
13185 // `caixa_with_code_paths` positive control uses) must pass
13186 // validate. The pair jointly pins the accessor + validate-gate
13187 // composition: any future silent detour that had the accessor
13188 // return an empty slice on the `[""]` arm (a `.iter().filter
13189 // (|s| !s.is_empty()).collect()` collapse) would silently
13190 // absorb the `CodePathEmpty` refusal at the accessor boundary
13191 // and the validate gate would accept a struct-literal
13192 // `Caixa { servicos: vec!["".into()], .. }` — the composition
13193 // pin catches that at caixa-core build time.
13194 //
13195 // Peer of the per-`Caixa`
13196 // `validate_code_paths_bibliotecas_empty_arm_routes_through_accessor`
13197 // (8a36c23), `validate_code_paths_exe_empty_arm_routes_through_accessor`
13198 // (65d9527), `validate_autores_empty_arm_routes_through_accessor`
13199 // (b5d813f), and
13200 // `validate_etiquetas_empty_entry_arm_routes_through_accessor`
13201 // (78c7d3c) accessor-composition pins on the sibling `&[T]`-
13202 // composition axes — same "the validate / shape-gate predicate
13203 // must route through the substrate-primitive typed dispatch"
13204 // discipline extended onto the sibling outer top-level
13205 // [`Caixa`] `&[T]`-composition surface, closing the trio of
13206 // code-surface accessor-composition pins on the same axis.
13207 // Nominally the in-tree `validate_code_paths` production body
13208 // still keys off the internal
13209 // `[(":bibliotecas", &self.bibliotecas,
13210 // CodePathFileType::LispSource), (":exe", &self.exe, ..),
13211 // (":servicos", &self.servicos, ..)]` per-slot dispatch tuple
13212 // (the tuple's homogeneous `&Vec<String>`-typed shape blocks a
13213 // per-element accessor swap in isolation — a future companion
13214 // lift promotes the tuple's element type to `&[String]` and
13215 // threads the triple of typed dispatches through as a unit);
13216 // the composition pin catches any future accessor-side silent
13217 // filter drop against that eventual tuple-closure regardless
13218 // of whether the `:servicos` slot is threaded through the
13219 // accessor or the raw field access at the tuple's construction
13220 // site.
13221 let c = caixa_with_code_paths(vec![], vec![], vec![""]);
13222 assert!(
13223 matches!(
13224 c.validate_code_paths(),
13225 Err(ManifestError::CodePathEmpty { slot: ":servicos" })
13226 ),
13227 "validate_code_paths must reject servicos == vec![\"\"] \
13228 with CodePathEmpty {{ slot: \":servicos\" }} — the \
13229 accessor and the validate gate must route through the \
13230 same substrate-primitive typed dispatch on the \
13231 :servicos per-entry empty arm",
13232 );
13233 let c = caixa_with_code_paths(vec![], vec![], vec!["servicos/demo.computeunit.yaml"]);
13234 assert!(
13235 c.validate_code_paths().is_ok(),
13236 "validate_code_paths must accept servicos == \
13237 vec![\"servicos/demo.computeunit.yaml\"] (the canonical \
13238 singleton V0-shape every in-tree `caixa_with_code_paths` \
13239 positive control uses)",
13240 );
13241 }
13242
13243 #[test]
13244 fn servicos_projects_slice_by_borrow() {
13245 // The by-borrow pin: [`Caixa::servicos`] returns `&[String]` by
13246 // borrow — the returned slice borrows the underlying
13247 // `Vec<String>` storage of the `:servicos` slot and the
13248 // accessor must not clone the backing `Vec` on every call.
13249 // Peer of the per-`Caixa` `autores_projects_slice_by_borrow`
13250 // (b5d813f), `etiquetas_projects_slice_by_borrow` (78c7d3c),
13251 // `bibliotecas_projects_slice_by_borrow` (8a36c23), and
13252 // `exe_projects_slice_by_borrow` (65d9527) by-borrow pins on
13253 // the sibling outer top-level [`Caixa`] `&[String]`-return
13254 // axes — the accessor's returned slice must borrow from
13255 // `&self` (the returned reference's lifetime is tied to
13256 // `&self`), and calling the accessor twice on the same
13257 // [`Caixa`] must yield slices that are pointer-equal (the
13258 // underlying byte-buffer is the storage `Vec`'s allocation,
13259 // not a fresh copy) as well as value-equal (idempotent, no
13260 // side effects on `&self`).
13261 //
13262 // Pins against a future silent detour that returned an owned
13263 // `Vec<String>` (which would type-check but silently clone on
13264 // every call, breaking the zero-cost projection every peer
13265 // sibling slice accessor carries), a `&Vec<String>` return
13266 // (which would leak the backing `Vec`'s grow/push/reserve
13267 // surface no downstream consumer reaches for), or a one-arm-
13268 // only accessor that returned a saturating value on some
13269 // sentinel input (breaking the pass-through invariant the
13270 // sibling slice accessors carry).
13271 for servicos in [
13272 vec![],
13273 vec!["servicos/demo.computeunit.yaml"],
13274 vec!["servicos/a.computeunit.yaml", "servicos/b.computeunit.yaml"],
13275 vec!["servicos/a.computeunit.yaml", "servicos/a.computeunit.yaml"],
13276 ] {
13277 let c = caixa_with_code_paths(vec![], vec![], servicos.clone());
13278 let expected: Vec<String> = servicos.iter().map(|s| (*s).to_string()).collect();
13279 let first = c.servicos();
13280 let second = c.servicos();
13281 assert_eq!(
13282 first, second,
13283 "Caixa::servicos must be idempotent — two successive \
13284 calls on the same &self must return the same &[String]",
13285 );
13286 assert_eq!(
13287 first.as_ptr(),
13288 second.as_ptr(),
13289 "Caixa::servicos must borrow the underlying \
13290 Vec<String> storage — two successive calls must \
13291 return slices with the same backing pointer (a fresh \
13292 Vec<String> clone would change the pointer on every \
13293 call)",
13294 );
13295 assert_eq!(
13296 first,
13297 expected.as_slice(),
13298 "Caixa::servicos must return :servicos verbatim by \
13299 borrow — got {first:?}, expected {expected:?}",
13300 );
13301 }
13302 }
13303
13304 // ── Caixa::deps — outer top-level &[Dep] slice accessor ───────────
13305
13306 fn caixa_with_deps(deps: Vec<Dep>) -> Caixa {
13307 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
13308 c.deps = deps;
13309 c
13310 }
13311
13312 #[test]
13313 fn deps_returns_deps_slice_verbatim_across_permutations() {
13314 // The canonical per-`Caixa` `:deps` universal-axis runtime-
13315 // dependency-declaration-list slice pin: [`Caixa::deps`] must
13316 // return the `:deps` typed [`Vec<Dep>`] list verbatim as a
13317 // `&[Dep]`, element-equal to the raw `self.deps.as_slice()`
13318 // access across every representative value in the accept-set —
13319 // `[]` (the "no runtime deps declared" arm every existing
13320 // fixture without a `:deps` line carries; the
13321 // [`Caixa::template`] scaffold emits `:deps ()`), a canonical
13322 // single-entry list (the shape most consumer caixas carry), a
13323 // canonical two-entry list (the multi-dep runtime closure), and
13324 // two past-the-guard sentinels — a `[""]`-`:nome` entry
13325 // ([`Self::validate_deps`] rejects through `NomeEmpty` /
13326 // `NomeInvalid` but the accessor must ship the raw slot
13327 // verbatim) and a `[a, a]` duplicate (validate rejects through
13328 // `DuplicateNome { list: ":deps" }` but the accessor must ship
13329 // the raw slot verbatim so struct-literal fixtures continue to
13330 // expose the duplicate at the accessor).
13331 //
13332 // First outer top-level [`Caixa`] `&[Dep]`-return slice accessor
13333 // pin on the substrate primitive — opens the outer-`Caixa`
13334 // dependency-slot `&[Dep]` sub-family the sibling `:deps-dev`
13335 // future lift closes on. Peer of the closed outer-`Caixa`
13336 // foreign-code-slot `&[String]` sub-family
13337 // (`bibliotecas_returns_bibliotecas_slice_verbatim_across_permutations`
13338 // 8a36c23, `exe_returns_exe_slice_verbatim_across_permutations`
13339 // 65d9527, `servicos_returns_servicos_slice_verbatim_across_permutations`
13340 // 611f78b) and the outer-`Caixa` universal-axis text-tag family
13341 // (`autores_returns_autores_slice_verbatim_across_permutations`
13342 // b5d813f, `etiquetas_returns_etiquetas_slice_verbatim_across_permutations`
13343 // 78c7d3c) — extends the "outer [`Caixa`] `&[T]` slice"
13344 // projection pattern onto a novel element-type axis (`Dep`
13345 // composite vs the prior sibling family's `String` scalar).
13346 // Pins against a future silent detour that returned an owned
13347 // `Vec<Dep>` (which would type-check but silently clone on every
13348 // accessor call, breaking the zero-cost projection every peer
13349 // sibling slice accessor carries), a `[""] → []` collapse (which
13350 // would silently absorb the `NomeEmpty` refusal case at the
13351 // accessor boundary), or a `[a, a] → [a]` dedup collapse (which
13352 // would silently absorb the `DuplicateNome` refusal case at the
13353 // accessor boundary).
13354 for deps in [
13355 vec![],
13356 vec![Dep::simple("", "^0.1")],
13357 vec![Dep::simple("caixa-teia", "^0.1")],
13358 vec![
13359 Dep::simple("caixa-teia", "^0.1"),
13360 Dep::simple("caixa-core", "^0.1"),
13361 ],
13362 vec![
13363 Dep::simple("caixa-teia", "^0.1"),
13364 Dep::simple("caixa-teia", "^0.2"),
13365 ],
13366 ] {
13367 let c = caixa_with_deps(deps.clone());
13368 assert_eq!(
13369 c.deps(),
13370 deps.as_slice(),
13371 "Caixa::deps must return :deps verbatim (got {:?}, \
13372 expected {deps:?})",
13373 c.deps(),
13374 );
13375 assert_eq!(
13376 c.deps(),
13377 c.deps.as_slice(),
13378 "Caixa::deps must element-equal the raw \
13379 `self.deps.as_slice()` field access across every \
13380 value in the Vec<Dep> accept-set",
13381 );
13382 }
13383 }
13384
13385 #[test]
13386 fn validate_deps_duplicate_arm_routes_through_accessor() {
13387 // Composition pin: [`Caixa::validate_deps`]'s within-`:deps`
13388 // duplicate-`:nome` gate must key off [`Caixa::deps`], not the
13389 // raw `&self.deps` field-borrow walk. Structurally: a `Caixa
13390 // { deps: vec![Dep::simple("d", "^0.1"), Dep::simple("d",
13391 // "^0.2")], .. }` must surface the `DuplicateNome { list:
13392 // ":deps" }` refusal exactly, and a `Caixa { deps: vec![
13393 // Dep::simple("d", "^0.1")], .. }` (the canonical single-entry
13394 // form) must pass validate. The pair jointly pins the accessor +
13395 // validate-gate composition: any future silent detour that had
13396 // the accessor return a dedupped slice on the `[a, a]` arm (a
13397 // `.iter().unique_by(|d| d.nome.as_str()).collect()` collapse)
13398 // would silently absorb the `DuplicateNome` refusal at the
13399 // accessor boundary and the validate gate would accept a
13400 // struct-literal `Caixa` carrying the drift — the composition
13401 // pin catches that at caixa-core build time.
13402 //
13403 // Peer of the per-`Caixa`
13404 // `validate_autores_empty_entry_arm_routes_through_accessor`
13405 // (b5d813f), `validate_etiquetas_empty_entry_arm_routes_through_accessor`
13406 // (78c7d3c), `validate_code_paths_bibliotecas_empty_arm_routes_through_accessor`
13407 // (8a36c23), `validate_code_paths_exe_empty_arm_routes_through_accessor`
13408 // (65d9527), and `validate_code_paths_servicos_empty_arm_routes_through_accessor`
13409 // (611f78b) accessor-composition pins on the sibling `&[T]`-
13410 // composition axes — same "the validate gate must route through
13411 // the substrate-primitive typed dispatch" discipline extended
13412 // onto the sibling outer top-level [`Caixa`] `&[Dep]`-
13413 // composition surface, opening the outer-`Caixa` dependency-slot
13414 // arm of the composition-pin family.
13415 let c = caixa_with_deps(vec![Dep::simple("d", "^0.1"), Dep::simple("d", "^0.2")]);
13416 let err = c.validate_deps().unwrap_err();
13417 assert!(
13418 matches!(
13419 err,
13420 DepError::DuplicateNome { ref nome, list } if nome == "d"
13421 && list == crate::render::DEP_AUTHOR_KEY_DEPS
13422 ),
13423 "validate_deps must reject deps == \
13424 vec![Dep(\"d\",\"^0.1\"), Dep(\"d\",\"^0.2\")] with \
13425 DuplicateNome {{ nome: \"d\", list: \":deps\" }} — the \
13426 accessor and the validate gate must route through the \
13427 same substrate-primitive typed dispatch on the :deps \
13428 within-list duplicate arm (got {err:?})",
13429 );
13430 let c = caixa_with_deps(vec![Dep::simple("d", "^0.1")]);
13431 assert!(
13432 c.validate_deps().is_ok(),
13433 "validate_deps must accept deps == vec![Dep(\"d\",\"^0.1\")] \
13434 (the canonical single-entry form)",
13435 );
13436 }
13437
13438 #[test]
13439 fn deps_projects_slice_by_borrow() {
13440 // The by-borrow pin: [`Caixa::deps`] returns `&[Dep]` by borrow
13441 // — the returned slice borrows the underlying `Vec<Dep>` storage
13442 // of the `:deps` slot and the accessor must not clone the
13443 // backing `Vec` on every call. Peer of the per-`Caixa`
13444 // `autores_projects_slice_by_borrow` (b5d813f),
13445 // `etiquetas_projects_slice_by_borrow` (78c7d3c),
13446 // `bibliotecas_projects_slice_by_borrow` (8a36c23),
13447 // `exe_projects_slice_by_borrow` (65d9527), and
13448 // `servicos_projects_slice_by_borrow` (611f78b) by-borrow pins
13449 // on the sibling outer top-level [`Caixa`] `&[String]`-return
13450 // axes — the accessor's returned slice must borrow from `&self`
13451 // (the returned reference's lifetime is tied to `&self`), and
13452 // calling the accessor twice on the same [`Caixa`] must yield
13453 // slices that are pointer-equal (the underlying byte-buffer is
13454 // the storage `Vec`'s allocation, not a fresh copy) as well as
13455 // value-equal (idempotent, no side effects on `&self`).
13456 //
13457 // Pins against a future silent detour that returned an owned
13458 // `Vec<Dep>` (which would type-check but silently clone on
13459 // every call), a `&Vec<Dep>` return (which would leak the
13460 // backing `Vec`'s grow/push/reserve surface no downstream
13461 // consumer reaches for), or a one-arm-only accessor that
13462 // returned a saturating value on some sentinel input.
13463 for deps in [
13464 vec![],
13465 vec![Dep::simple("caixa-teia", "^0.1")],
13466 vec![
13467 Dep::simple("caixa-teia", "^0.1"),
13468 Dep::simple("caixa-core", "^0.1"),
13469 ],
13470 ] {
13471 let c = caixa_with_deps(deps.clone());
13472 let first = c.deps();
13473 let second = c.deps();
13474 assert_eq!(
13475 first, second,
13476 "Caixa::deps must be idempotent — two successive calls \
13477 on the same &self must return the same &[Dep]",
13478 );
13479 assert_eq!(
13480 first.as_ptr(),
13481 second.as_ptr(),
13482 "Caixa::deps must borrow the underlying Vec<Dep> \
13483 storage — two successive calls must return slices \
13484 with the same backing pointer (a fresh Vec<Dep> clone \
13485 would change the pointer on every call)",
13486 );
13487 assert_eq!(
13488 first,
13489 deps.as_slice(),
13490 "Caixa::deps must return :deps verbatim by borrow — \
13491 got {first:?}, expected {deps:?}",
13492 );
13493 }
13494 }
13495
13496 // ── Caixa::deps_dev — outer top-level &[Dep] slice accessor ──────
13497
13498 fn caixa_with_deps_dev(deps_dev: Vec<Dep>) -> Caixa {
13499 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
13500 c.deps_dev = deps_dev;
13501 c
13502 }
13503
13504 #[test]
13505 fn deps_dev_returns_deps_dev_slice_verbatim_across_permutations() {
13506 // The canonical per-`Caixa` `:deps-dev` universal-axis dev-only-
13507 // dependency-declaration-list slice pin: [`Caixa::deps_dev`]
13508 // must return the `:deps-dev` typed [`Vec<Dep>`] list verbatim as
13509 // a `&[Dep]`, element-equal to the raw `self.deps_dev.as_slice()`
13510 // access across every representative value in the accept-set —
13511 // `[]` (the "no dev deps declared" arm every existing fixture
13512 // without a `:deps-dev` line carries; the [`Caixa::template`]
13513 // scaffold emits `:deps-dev ()`), a canonical single-entry list
13514 // (the shape most consumer caixas carry — a `tatara-check` dev
13515 // pin), a canonical two-entry list (the multi-dev-dep closure),
13516 // and two past-the-guard sentinels — a `[""]`-`:nome` entry
13517 // ([`Self::validate_deps`] rejects through `NomeEmpty` /
13518 // `NomeInvalid` but the accessor must ship the raw slot
13519 // verbatim) and a `[a, a]` duplicate (validate rejects through
13520 // `DuplicateNome { list: ":deps-dev" }` but the accessor must
13521 // ship the raw slot verbatim so struct-literal fixtures continue
13522 // to expose the duplicate at the accessor).
13523 //
13524 // Second outer top-level [`Caixa`] `&[Dep]`-return slice-accessor
13525 // pin on the substrate primitive — closes the outer-`Caixa`
13526 // dependency-slot `&[Dep]` sub-family the sibling
13527 // `deps_returns_deps_slice_verbatim_across_permutations`
13528 // (ad34b4e) opened on. Folds the "outer [`Caixa`] `&[Dep]`
13529 // slice" projection pattern onto the sibling dev-dep axis —
13530 // pins against a future silent detour that returned an owned
13531 // `Vec<Dep>` (which would type-check but silently clone on every
13532 // accessor call, breaking the zero-cost projection every peer
13533 // sibling slice accessor carries), a `[""] → []` collapse (which
13534 // would silently absorb the `NomeEmpty` refusal case at the
13535 // accessor boundary), or a `[a, a] → [a]` dedup collapse (which
13536 // would silently absorb the `DuplicateNome` refusal case at the
13537 // accessor boundary).
13538 for deps_dev in [
13539 vec![],
13540 vec![Dep::simple("", "^0.1")],
13541 vec![Dep::simple("tatara-check", "^0.1")],
13542 vec![
13543 Dep::simple("tatara-check", "^0.1"),
13544 Dep::simple("caixa-lint", "^0.1"),
13545 ],
13546 vec![
13547 Dep::simple("tatara-check", "^0.1"),
13548 Dep::simple("tatara-check", "^0.2"),
13549 ],
13550 ] {
13551 let c = caixa_with_deps_dev(deps_dev.clone());
13552 assert_eq!(
13553 c.deps_dev(),
13554 deps_dev.as_slice(),
13555 "Caixa::deps_dev must return :deps-dev verbatim (got \
13556 {:?}, expected {deps_dev:?})",
13557 c.deps_dev(),
13558 );
13559 assert_eq!(
13560 c.deps_dev(),
13561 c.deps_dev.as_slice(),
13562 "Caixa::deps_dev must element-equal the raw \
13563 `self.deps_dev.as_slice()` field access across every \
13564 value in the Vec<Dep> accept-set",
13565 );
13566 }
13567 }
13568
13569 #[test]
13570 fn validate_deps_duplicate_deps_dev_arm_routes_through_accessor() {
13571 // Composition pin: [`Caixa::validate_deps`]'s within-`:deps-dev`
13572 // duplicate-`:nome` gate must key off [`Caixa::deps_dev`], not
13573 // the raw `&self.deps_dev` field-borrow walk. Structurally: a
13574 // `Caixa { deps_dev: vec![Dep::simple("d", "^0.1"),
13575 // Dep::simple("d", "^0.2")], .. }` must surface the
13576 // `DuplicateNome { list: ":deps-dev" }` refusal exactly, and a
13577 // `Caixa { deps_dev: vec![Dep::simple("d", "^0.1")], .. }` (the
13578 // canonical single-entry form) must pass validate. The pair
13579 // jointly pins the accessor + validate-gate composition: any
13580 // future silent detour that had the accessor return a dedupped
13581 // slice on the `[a, a]` arm (a
13582 // `.iter().unique_by(|d| d.nome.as_str()).collect()` collapse)
13583 // would silently absorb the `DuplicateNome` refusal at the
13584 // accessor boundary and the validate gate would accept a
13585 // struct-literal `Caixa` carrying the drift — the composition
13586 // pin catches that at caixa-core build time.
13587 //
13588 // Peer of `validate_deps_duplicate_arm_routes_through_accessor`
13589 // (ad34b4e) on the sibling `:deps` axis — same "the validate
13590 // gate must route through the substrate-primitive typed
13591 // dispatch" discipline folded onto the sibling `:deps-dev`
13592 // axis, closing the two-list dep-graph composition-pin family.
13593 // The `:deps-dev` diagnostic must carry the
13594 // `DEP_AUTHOR_KEY_DEPS_DEV` list-tag (not
13595 // `DEP_AUTHOR_KEY_DEPS`) so the emitted error names the
13596 // offending list unambiguously.
13597 let c = caixa_with_deps_dev(vec![Dep::simple("d", "^0.1"), Dep::simple("d", "^0.2")]);
13598 let err = c.validate_deps().unwrap_err();
13599 assert!(
13600 matches!(
13601 err,
13602 DepError::DuplicateNome { ref nome, list } if nome == "d"
13603 && list == crate::render::DEP_AUTHOR_KEY_DEPS_DEV
13604 ),
13605 "validate_deps must reject deps_dev == \
13606 vec![Dep(\"d\",\"^0.1\"), Dep(\"d\",\"^0.2\")] with \
13607 DuplicateNome {{ nome: \"d\", list: \":deps-dev\" }} — the \
13608 accessor and the validate gate must route through the \
13609 same substrate-primitive typed dispatch on the :deps-dev \
13610 within-list duplicate arm (got {err:?})",
13611 );
13612 let c = caixa_with_deps_dev(vec![Dep::simple("d", "^0.1")]);
13613 assert!(
13614 c.validate_deps().is_ok(),
13615 "validate_deps must accept deps_dev == \
13616 vec![Dep(\"d\",\"^0.1\")] (the canonical single-entry form)",
13617 );
13618 }
13619
13620 #[test]
13621 fn deps_dev_projects_slice_by_borrow() {
13622 // The by-borrow pin: [`Caixa::deps_dev`] returns `&[Dep]` by
13623 // borrow — the returned slice borrows the underlying `Vec<Dep>`
13624 // storage of the `:deps-dev` slot and the accessor must not
13625 // clone the backing `Vec` on every call. Peer of
13626 // `deps_projects_slice_by_borrow` (ad34b4e) on the sibling
13627 // `:deps` axis, and of the per-`Caixa`
13628 // `autores_projects_slice_by_borrow` (b5d813f),
13629 // `etiquetas_projects_slice_by_borrow` (78c7d3c),
13630 // `bibliotecas_projects_slice_by_borrow` (8a36c23),
13631 // `exe_projects_slice_by_borrow` (65d9527), and
13632 // `servicos_projects_slice_by_borrow` (611f78b) by-borrow pins
13633 // on the sibling outer top-level [`Caixa`] `&[String]`-return
13634 // axes — the accessor's returned slice must borrow from `&self`
13635 // (the returned reference's lifetime is tied to `&self`), and
13636 // calling the accessor twice on the same [`Caixa`] must yield
13637 // slices that are pointer-equal (the underlying byte-buffer is
13638 // the storage `Vec`'s allocation, not a fresh copy) as well as
13639 // value-equal (idempotent, no side effects on `&self`).
13640 //
13641 // Pins against a future silent detour that returned an owned
13642 // `Vec<Dep>` (which would type-check but silently clone on
13643 // every call), a `&Vec<Dep>` return (which would leak the
13644 // backing `Vec`'s grow/push/reserve surface no downstream
13645 // consumer reaches for), or a one-arm-only accessor that
13646 // returned a saturating value on some sentinel input.
13647 for deps_dev in [
13648 vec![],
13649 vec![Dep::simple("tatara-check", "^0.1")],
13650 vec![
13651 Dep::simple("tatara-check", "^0.1"),
13652 Dep::simple("caixa-lint", "^0.1"),
13653 ],
13654 ] {
13655 let c = caixa_with_deps_dev(deps_dev.clone());
13656 let first = c.deps_dev();
13657 let second = c.deps_dev();
13658 assert_eq!(
13659 first, second,
13660 "Caixa::deps_dev must be idempotent — two successive \
13661 calls on the same &self must return the same &[Dep]",
13662 );
13663 assert_eq!(
13664 first.as_ptr(),
13665 second.as_ptr(),
13666 "Caixa::deps_dev must borrow the underlying Vec<Dep> \
13667 storage — two successive calls must return slices \
13668 with the same backing pointer (a fresh Vec<Dep> clone \
13669 would change the pointer on every call)",
13670 );
13671 assert_eq!(
13672 first,
13673 deps_dev.as_slice(),
13674 "Caixa::deps_dev must return :deps-dev verbatim by \
13675 borrow — got {first:?}, expected {deps_dev:?}",
13676 );
13677 }
13678 }
13679
13680 // ── Caixa::limits — outer top-level Option<&LimitsSpec> composite-reference accessor ──
13681
13682 fn caixa_with_limits(limits: Option<crate::LimitsSpec>) -> Caixa {
13683 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
13684 c.limits = limits;
13685 c
13686 }
13687
13688 #[test]
13689 fn limits_returns_limits_option_ref_verbatim_across_permutations() {
13690 // The canonical per-`Caixa` `:limits` M2 typed-slot outer-
13691 // composite optional-composite-reference-shape pin:
13692 // [`Caixa::limits`] must return the `:limits` typed
13693 // `Option<LimitsSpec>` verbatim as an `Option<&LimitsSpec>`
13694 // reference over the same backing storage the raw
13695 // `self.limits.as_ref()` field access borrows from, byte-equal
13696 // across every representative fixture in the accept-set — the
13697 // author-omitted `None` shape (the "engine-default applies"
13698 // partition every downstream Servico M2 overlay emitter treats
13699 // as "emit nothing"), the empty-composite `Some(LimitsSpec {
13700 // .. default })` shape ([`LimitsSpec::is_empty`] holds — every
13701 // per-axis cap is `None`, so the peer M2 overlay emitter's
13702 // `.is_empty()`-gated projection still emits nothing but the
13703 // outer presence-bit is `Some`, so [`Caixa::declared_servico_slots`]
13704 // still pushes the `M2_AUTHOR_KEY_LIMITS` label), a single-axis
13705 // fixture (only `:memory` set — the canonical shape most
13706 // memory-heavy Servicos carry), and a fully-populated composite
13707 // (every per-axis cap set — the canonical shape a
13708 // sandboxed-by-default Servico carries).
13709 //
13710 // Pins against a future silent detour that returned a fresh-
13711 // cloned [`LimitsSpec`] copy (which would type-check via the
13712 // `Clone` impl but silently break every downstream caller that
13713 // relied on the reference sharing the composite's backing
13714 // identity), a reference to an operator-resolved overlay (the
13715 // future per-cluster `:limits-overrides` slot — its resolution
13716 // must land at exactly this accessor body, not silently divert
13717 // the raw slot away from a second consumer), a
13718 // `None` → `Some(LimitsSpec::default)` cluster-default
13719 // projection (which would collapse the load-bearing
13720 // "author-omitted `:limits` ⇒ engine-default applies" partition
13721 // the peer [`crate::render::servico_m2_overlay`] emitter and
13722 // the peer [`Caixa::declared_servico_slots`] enumerator both
13723 // read), or an axis-shuffled projection (a future detour that
13724 // swapped `memory` and `fuel` through the accessor would
13725 // silently split the paired [`crate::StandardLayout::verify`]
13726 // per-`:limits` shape gate's traversal input from the peer
13727 // `servico_m2_overlay` emitter's projection input).
13728 //
13729 // First outer top-level [`Caixa`] `Option<&Composite>`-return
13730 // composite-reference accessor pin on the substrate primitive
13731 // — opens the outer-`Caixa` `Option<&Composite>` composite-
13732 // reference projection pattern the sibling `:behavior`
13733 // [`crate::BehaviorSpec`] / `:politicas`
13734 // [`crate::aplicacao::MeshPolicy`] / `:placement`
13735 // [`crate::aplicacao::Placement`] / `:entrada`
13736 // [`crate::aplicacao::Entrada`] future outer-composite lifts
13737 // fold on. Peer of the closed M3 outer-composite family the
13738 // sibling [`crate::AplicacaoSpec::politicas`] (534dc21) /
13739 // [`crate::AplicacaoSpec::placement`] (9abb8f0) /
13740 // [`crate::AplicacaoSpec::entrada`] (d32111c) composite-
13741 // reference accessor pins already carry on the outer
13742 // [`crate::AplicacaoSpec`] altitude — extends the outer-
13743 // accessor byte-equal-projection discipline onto the outer
13744 // top-level [`Caixa`] M2 Servico-runtime slot altitude.
13745 use crate::LimitsSpec;
13746 use std::time::Duration;
13747 let fixtures: Vec<Option<LimitsSpec>> = vec![
13748 None,
13749 Some(LimitsSpec::default()),
13750 Some(LimitsSpec {
13751 memory: Some(64 * 1024 * 1024),
13752 ..Default::default()
13753 }),
13754 Some(LimitsSpec {
13755 memory: Some(64 * 1024 * 1024),
13756 fuel: Some(1_000_000),
13757 wall_clock: Some(Duration::from_secs(30)),
13758 cpu: Some(500),
13759 }),
13760 ];
13761 for limits in fixtures {
13762 let c = caixa_with_limits(limits.clone());
13763 assert_eq!(
13764 c.limits(),
13765 limits.as_ref(),
13766 "Caixa::limits must return :limits verbatim (got {:?}, \
13767 expected {:?})",
13768 c.limits(),
13769 limits.as_ref(),
13770 );
13771 match (c.limits(), c.limits.as_ref()) {
13772 (Some(a), Some(b)) => assert!(
13773 std::ptr::eq(a, b),
13774 "Caixa::limits accessor and self.limits.as_ref() \
13775 field access must borrow the same backing storage \
13776 — the accessor is the substrate-primitive typed \
13777 dispatch every downstream Servico-M2-overlay \
13778 composite consumer must route through, and a \
13779 reference-identity split would silently break \
13780 every consumer that relied on the borrow sharing \
13781 the composite's storage",
13782 ),
13783 (None, None) => {}
13784 _ => panic!(
13785 "Caixa::limits presence bit must byte-equal \
13786 self.limits.is_some() — a presence-bit drift would \
13787 silently split the paired StandardLayout::verify \
13788 per-`:limits` shape gate's traversal head from \
13789 the peer render::servico_m2_overlay M2 overlay \
13790 emitter's traversal head from the peer \
13791 Caixa::declared_servico_slots M2 declared-slot \
13792 enumerator's presence probe",
13793 ),
13794 }
13795 assert_eq!(
13796 c.limits().is_some(),
13797 c.limits.is_some(),
13798 "Caixa::limits().is_some() must byte-equal \
13799 self.limits.is_some() — a presence-bit drift would \
13800 silently split every downstream Option<&LimitsSpec> \
13801 consumer's partition on the engine-default arm",
13802 );
13803 }
13804 }
13805
13806 #[test]
13807 fn declared_servico_slots_limits_arm_routes_through_accessor() {
13808 // Composition pin: [`Caixa::declared_servico_slots`]'s
13809 // `:limits` presence-probe arm must key off [`Caixa::limits`],
13810 // not the raw `self.limits.is_some()` field-probe. Structurally:
13811 // a `Caixa { limits: Some(LimitsSpec::default()), .. }` must
13812 // still push `M2_AUTHOR_KEY_LIMITS` onto the declared-slot list
13813 // (the presence bit is `Some`, so the M2 kind-coherence gate
13814 // must surface the slot as "declared" even when every per-axis
13815 // cap is unset), and a `Caixa { limits: None, .. }` must NOT
13816 // push the label (the "author omitted the slot entirely"
13817 // partition). The pair jointly pins the accessor + declared-
13818 // slot enumerator composition: any future silent detour that
13819 // had the accessor collapse `Some(LimitsSpec::default())` to
13820 // `None` (a `.filter(|l| !l.is_empty())` projection) would
13821 // silently absorb the "declared but empty" arm at the
13822 // accessor boundary and the [`crate::LayoutError::ServicoSlotsOnNonServico`]
13823 // kind-coherence gate would silently accept a
13824 // struct-literal `Caixa` carrying the drift.
13825 //
13826 // Peer of the sibling per-`Caixa`
13827 // `validate_deps_duplicate_arm_routes_through_accessor` (ad34b4e)
13828 // and `validate_deps_duplicate_deps_dev_arm_routes_through_accessor`
13829 // (f7fd81e) accessor-composition pins on the sibling `:deps` /
13830 // `:deps-dev` outer-`&[Dep]`-composition axes — same "the
13831 // enumerator gate must route through the substrate-primitive
13832 // typed dispatch" discipline extended onto the outer top-level
13833 // [`Caixa`] `Option<&LimitsSpec>`-composition surface, opening
13834 // the outer-`Caixa` M2 Servico-runtime-slot arm of the
13835 // composition-pin family.
13836 use crate::LimitsSpec;
13837 let c = caixa_with_limits(Some(LimitsSpec::default()));
13838 let slots = c.declared_servico_slots();
13839 assert!(
13840 slots.contains(&crate::render::M2_AUTHOR_KEY_LIMITS),
13841 "declared_servico_slots must push M2_AUTHOR_KEY_LIMITS \
13842 when `:limits` is Some (even for LimitsSpec::default()) \
13843 — the accessor and the enumerator gate must route through \
13844 the same substrate-primitive typed dispatch on the outer \
13845 :limits presence bit (got slots={slots:?})",
13846 );
13847 let c = caixa_with_limits(None);
13848 let slots = c.declared_servico_slots();
13849 assert!(
13850 !slots.contains(&crate::render::M2_AUTHOR_KEY_LIMITS),
13851 "declared_servico_slots must NOT push M2_AUTHOR_KEY_LIMITS \
13852 when `:limits` is None — the author-omitted arm must \
13853 route through the accessor's None-return unchanged (got \
13854 slots={slots:?})",
13855 );
13856 }
13857
13858 #[test]
13859 fn servico_m2_overlay_limits_arm_routes_through_accessor() {
13860 // Composition pin: [`crate::render::servico_m2_overlay`]'s
13861 // per-`:limits` M2 overlay emit arm must key off
13862 // [`Caixa::limits`], not the raw `&caixa.limits` field-borrow.
13863 // Structurally: a `Caixa { limits: Some(LimitsSpec { memory:
13864 // Some(64 MiB), .. default }), .. }` must surface the
13865 // `M2_KEY_LIMITS` key with the per-axis
13866 // `memory: "64MiB"` sub-mapping in the overlay, a `Caixa {
13867 // limits: Some(LimitsSpec::default()), .. }` must omit the
13868 // key entirely (the `.is_empty()`-gated inner arm elides an
13869 // empty composite even when the outer presence bit is `Some`),
13870 // and a `Caixa { limits: None, .. }` must also omit the key
13871 // (the "author omitted the slot entirely" partition). The
13872 // three-fixture family jointly pins the accessor + M2 overlay
13873 // emitter composition: any future silent detour that had the
13874 // accessor return a fresh-cloned copy on the `Some` arm (a
13875 // `LimitsSpec::clone()` projection) would silently break the
13876 // reference-identity pin the peer per-axis
13877 // `serde_yaml::to_value(limits)` projection reads from.
13878 use crate::LimitsSpec;
13879 use crate::render::{M2_KEY_LIMITS, servico_m2_overlay};
13880 let c = caixa_with_limits(Some(LimitsSpec {
13881 memory: Some(64 * 1024 * 1024),
13882 ..Default::default()
13883 }));
13884 let overlay = servico_m2_overlay(&c).unwrap();
13885 assert!(
13886 overlay.contains_key(M2_KEY_LIMITS),
13887 "servico_m2_overlay must surface M2_KEY_LIMITS when \
13888 `:limits` carries a non-empty composite — the accessor \
13889 and the M2 overlay emitter must route through the same \
13890 substrate-primitive typed dispatch on the outer :limits \
13891 composite (got overlay={overlay:?})",
13892 );
13893 let c = caixa_with_limits(Some(LimitsSpec::default()));
13894 let overlay = servico_m2_overlay(&c).unwrap();
13895 assert!(
13896 !overlay.contains_key(M2_KEY_LIMITS),
13897 "servico_m2_overlay must omit M2_KEY_LIMITS when \
13898 `:limits` is Some(LimitsSpec::default()) — the empty \
13899 composite's `.is_empty()`-gated inner arm must elide \
13900 the key regardless of the outer presence bit (got \
13901 overlay={overlay:?})",
13902 );
13903 let c = caixa_with_limits(None);
13904 let overlay = servico_m2_overlay(&c).unwrap();
13905 assert!(
13906 !overlay.contains_key(M2_KEY_LIMITS),
13907 "servico_m2_overlay must omit M2_KEY_LIMITS when \
13908 `:limits` is None — the author-omitted arm must route \
13909 through the accessor's None-return unchanged (got \
13910 overlay={overlay:?})",
13911 );
13912 }
13913
13914 #[test]
13915 fn limits_projects_option_ref_by_borrow() {
13916 // The by-borrow pin: [`Caixa::limits`] returns
13917 // `Option<&LimitsSpec>` by borrow — the returned reference
13918 // borrows the underlying `Option<LimitsSpec>` storage of the
13919 // `:limits` slot and the accessor must not clone the backing
13920 // composite on every call. Peer of the sibling
13921 // `deps_projects_slice_by_borrow` (ad34b4e) /
13922 // `deps_dev_projects_slice_by_borrow` (f7fd81e) by-borrow pins
13923 // on the outer top-level [`Caixa`] `&[Dep]`-return axes —
13924 // extended here to the outer [`Caixa`] `Option<&Composite>`-
13925 // return axis: the accessor's returned reference must borrow
13926 // from `&self` (the returned reference's lifetime is tied to
13927 // `&self`), and calling the accessor twice on the same
13928 // [`Caixa`] must yield references that are pointer-equal (the
13929 // underlying byte-buffer is the storage `LimitsSpec`'s
13930 // allocation, not a fresh copy) as well as value-equal
13931 // (idempotent, no side effects on `&self`).
13932 //
13933 // Pins against a future silent detour that returned an owned
13934 // `LimitsSpec` (which would type-check via the `Clone` impl
13935 // but silently clone on every call), a `&LimitsSpec` panic-
13936 // return on the `None` arm (which would collapse the load-
13937 // bearing `Option` presence-bit into a runtime panic), or a
13938 // one-arm-only accessor that returned a saturating composite
13939 // on some sentinel input.
13940 use crate::LimitsSpec;
13941 use std::time::Duration;
13942 for limits in [
13943 Some(LimitsSpec::default()),
13944 Some(LimitsSpec {
13945 memory: Some(64 * 1024 * 1024),
13946 fuel: Some(1_000_000),
13947 wall_clock: Some(Duration::from_secs(30)),
13948 cpu: Some(500),
13949 }),
13950 ] {
13951 let c = caixa_with_limits(limits.clone());
13952 let first = c.limits().unwrap();
13953 let second = c.limits().unwrap();
13954 assert_eq!(
13955 first, second,
13956 "Caixa::limits must be idempotent — two successive \
13957 calls on the same &self must return the same \
13958 &LimitsSpec",
13959 );
13960 assert!(
13961 std::ptr::eq(first, second),
13962 "Caixa::limits must borrow the underlying \
13963 Option<LimitsSpec> storage — two successive calls \
13964 must return references with the same backing pointer \
13965 (a fresh LimitsSpec clone would change the pointer \
13966 on every call)",
13967 );
13968 assert_eq!(
13969 Some(first),
13970 limits.as_ref(),
13971 "Caixa::limits must return :limits verbatim by borrow \
13972 — got {first:?}, expected {:?}",
13973 limits.as_ref(),
13974 );
13975 }
13976 let c = caixa_with_limits(None);
13977 assert!(
13978 c.limits().is_none(),
13979 "Caixa::limits must return None when :limits is absent — \
13980 the author-omitted arm must project through the \
13981 accessor's Option::None unchanged",
13982 );
13983 }
13984
13985 // ── Caixa::behavior — outer top-level Option<&BehaviorSpec> composite-reference accessor ──
13986
13987 fn caixa_with_behavior(behavior: Option<crate::BehaviorSpec>) -> Caixa {
13988 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
13989 c.behavior = behavior;
13990 c
13991 }
13992
13993 #[test]
13994 fn behavior_returns_behavior_option_ref_verbatim_across_permutations() {
13995 // The canonical per-`Caixa` `:behavior` M2 typed-slot outer-
13996 // composite optional-composite-reference-shape pin:
13997 // [`Caixa::behavior`] must return the `:behavior` typed
13998 // `Option<BehaviorSpec>` verbatim as an `Option<&BehaviorSpec>`
13999 // reference over the same backing storage the raw
14000 // `self.behavior.as_ref()` field access borrows from, byte-equal
14001 // across every representative fixture in the accept-set — the
14002 // author-omitted `None` shape (the "runtime-default applies"
14003 // partition every downstream Servico M2 overlay emitter treats
14004 // as "emit nothing"), the empty-composite `Some(BehaviorSpec {
14005 // .. default })` shape ([`BehaviorSpec::is_empty`] holds —
14006 // every per-callback path is `None`, so the peer M2 overlay
14007 // emitter's `.is_empty()`-gated projection still emits nothing
14008 // but the outer presence-bit is `Some`, so
14009 // [`Caixa::declared_servico_slots`] still pushes the
14010 // `M2_AUTHOR_KEY_BEHAVIOR` label), a single-callback fixture
14011 // (only `:on-state-change` set — the canonical shape a caixa
14012 // that only wires the hot-upgrade migration path carries), and
14013 // a fully-populated composite (every per-callback path set —
14014 // the canonical shape a fully-instrumented gen_server-shaped
14015 // Servico carries).
14016 //
14017 // Peer of the sibling
14018 // `limits_returns_limits_option_ref_verbatim_across_permutations`
14019 // (b2bd9d7) opening fixture-family + reference-identity +
14020 // presence-bit tetrad pin on the outer top-level [`Caixa`]
14021 // `Option<&Composite>`-return sub-family — extended here to the
14022 // second axis of that sub-family so both of the currently-lifted
14023 // M2 Servico-runtime `Option<&Composite>` slots (`:limits` /
14024 // `:behavior`) carry the same "byte-equal, borrow-shared,
14025 // presence-bit-preserved" outer-accessor discipline.
14026 //
14027 // Pins against a future silent detour that returned a fresh-
14028 // cloned [`crate::BehaviorSpec`] copy (which would type-check
14029 // via the `Clone` impl but silently break every downstream
14030 // caller that relied on the reference sharing the composite's
14031 // backing identity), a reference to an operator-resolved
14032 // overlay (a future per-cluster `:behavior-overrides` slot —
14033 // its resolution must land at exactly this accessor body, not
14034 // silently divert the raw slot away from a second consumer), a
14035 // `None` → `Some(BehaviorSpec::default)` cluster-default
14036 // projection (which would collapse the load-bearing
14037 // "author-omitted `:behavior` ⇒ runtime-default applies"
14038 // partition the peer [`crate::render::servico_m2_overlay`]
14039 // emitter, the peer [`Caixa::declared_servico_slots`]
14040 // enumerator, and the cross-slot
14041 // [`crate::upgrade::validate_upgrade_from_against_behavior`]
14042 // gate all read), or a callback-shuffled projection (a future
14043 // detour that swapped `on_init` and `on_terminate` through the
14044 // accessor would silently split the paired
14045 // [`crate::StandardLayout::verify`] per-`:behavior` shape gate's
14046 // traversal input from the peer `servico_m2_overlay` emitter's
14047 // projection input from the cross-slot `:state-change`
14048 // composition gate's traversal input).
14049 use crate::BehaviorSpec;
14050 use std::path::PathBuf;
14051 let fixtures: Vec<Option<BehaviorSpec>> = vec![
14052 None,
14053 Some(BehaviorSpec::default()),
14054 Some(BehaviorSpec {
14055 on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
14056 ..Default::default()
14057 }),
14058 Some(BehaviorSpec {
14059 on_init: Some(PathBuf::from("lib/init.lisp")),
14060 on_call: Some(PathBuf::from("lib/handlers.lisp")),
14061 on_cast: Some(PathBuf::from("lib/handlers.lisp")),
14062 on_info: Some(PathBuf::from("lib/handlers.lisp")),
14063 on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
14064 on_terminate: Some(PathBuf::from("lib/cleanup.lisp")),
14065 }),
14066 ];
14067 for behavior in fixtures {
14068 let c = caixa_with_behavior(behavior.clone());
14069 assert_eq!(
14070 c.behavior(),
14071 behavior.as_ref(),
14072 "Caixa::behavior must return :behavior verbatim (got \
14073 {:?}, expected {:?})",
14074 c.behavior(),
14075 behavior.as_ref(),
14076 );
14077 match (c.behavior(), c.behavior.as_ref()) {
14078 (Some(a), Some(b)) => assert!(
14079 std::ptr::eq(a, b),
14080 "Caixa::behavior accessor and self.behavior.as_ref() \
14081 field access must borrow the same backing storage \
14082 — the accessor is the substrate-primitive typed \
14083 dispatch every downstream Servico-M2-overlay \
14084 composite consumer must route through, and a \
14085 reference-identity split would silently break \
14086 every consumer that relied on the borrow sharing \
14087 the composite's storage",
14088 ),
14089 (None, None) => {}
14090 _ => panic!(
14091 "Caixa::behavior presence bit must byte-equal \
14092 self.behavior.is_some() — a presence-bit drift \
14093 would silently split the paired \
14094 StandardLayout::verify per-`:behavior` shape \
14095 gate's traversal head from the peer \
14096 render::servico_m2_overlay M2 overlay emitter's \
14097 traversal head from the cross-slot \
14098 validate_upgrade_from_against_behavior \
14099 composition gate's traversal head from the peer \
14100 Caixa::declared_servico_slots M2 declared-slot \
14101 enumerator's presence probe",
14102 ),
14103 }
14104 assert_eq!(
14105 c.behavior().is_some(),
14106 c.behavior.is_some(),
14107 "Caixa::behavior().is_some() must byte-equal \
14108 self.behavior.is_some() — a presence-bit drift would \
14109 silently split every downstream Option<&BehaviorSpec> \
14110 consumer's partition on the runtime-default arm",
14111 );
14112 }
14113 }
14114
14115 #[test]
14116 fn declared_servico_slots_behavior_arm_routes_through_accessor() {
14117 // Composition pin: [`Caixa::declared_servico_slots`]'s
14118 // `:behavior` presence-probe arm must key off
14119 // [`Caixa::behavior`], not the raw `self.behavior.is_some()`
14120 // field-probe. Structurally: a `Caixa { behavior:
14121 // Some(BehaviorSpec::default()), .. }` must still push
14122 // `M2_AUTHOR_KEY_BEHAVIOR` onto the declared-slot list (the
14123 // presence bit is `Some`, so the M2 kind-coherence gate must
14124 // surface the slot as "declared" even when every per-callback
14125 // path is unset), and a `Caixa { behavior: None, .. }` must
14126 // NOT push the label (the "author omitted the slot entirely"
14127 // partition). The pair jointly pins the accessor + declared-
14128 // slot enumerator composition: any future silent detour that
14129 // had the accessor collapse `Some(BehaviorSpec::default())`
14130 // to `None` (a `.filter(|b| !b.is_empty())` projection) would
14131 // silently absorb the "declared but empty" arm at the
14132 // accessor boundary and the
14133 // [`crate::LayoutError::ServicoSlotsOnNonServico`]
14134 // kind-coherence gate would silently accept a struct-literal
14135 // `Caixa` carrying the drift.
14136 //
14137 // Peer of the sibling
14138 // `declared_servico_slots_limits_arm_routes_through_accessor`
14139 // (b2bd9d7) composition pin on the sibling `:limits` outer-
14140 // `Option<&LimitsSpec>` arm of the same
14141 // [`Caixa::declared_servico_slots`] M2 declared-slot
14142 // enumerator's traversal — same "the enumerator gate must
14143 // route through the substrate-primitive typed dispatch"
14144 // discipline extended onto the outer top-level [`Caixa`]
14145 // `Option<&BehaviorSpec>`-composition surface.
14146 use crate::BehaviorSpec;
14147 let c = caixa_with_behavior(Some(BehaviorSpec::default()));
14148 let slots = c.declared_servico_slots();
14149 assert!(
14150 slots.contains(&crate::render::M2_AUTHOR_KEY_BEHAVIOR),
14151 "declared_servico_slots must push M2_AUTHOR_KEY_BEHAVIOR \
14152 when `:behavior` is Some (even for BehaviorSpec::default()) \
14153 — the accessor and the enumerator gate must route through \
14154 the same substrate-primitive typed dispatch on the outer \
14155 :behavior presence bit (got slots={slots:?})",
14156 );
14157 let c = caixa_with_behavior(None);
14158 let slots = c.declared_servico_slots();
14159 assert!(
14160 !slots.contains(&crate::render::M2_AUTHOR_KEY_BEHAVIOR),
14161 "declared_servico_slots must NOT push M2_AUTHOR_KEY_BEHAVIOR \
14162 when `:behavior` is None — the author-omitted arm must \
14163 route through the accessor's None-return unchanged (got \
14164 slots={slots:?})",
14165 );
14166 }
14167
14168 #[test]
14169 fn servico_m2_overlay_behavior_arm_routes_through_accessor() {
14170 // Composition pin: [`crate::render::servico_m2_overlay`]'s
14171 // per-`:behavior` M2 overlay emit arm must key off
14172 // [`Caixa::behavior`], not the raw `&caixa.behavior`
14173 // field-borrow. Structurally: a `Caixa { behavior:
14174 // Some(BehaviorSpec { on_state_change: Some(...), .. default
14175 // }), .. }` must surface the `M2_KEY_BEHAVIOR` key with the
14176 // per-callback `onStateChange` sub-mapping in the overlay, a
14177 // `Caixa { behavior: Some(BehaviorSpec::default()), .. }`
14178 // must omit the key entirely (the `.is_empty()`-gated inner
14179 // arm elides an empty composite even when the outer presence
14180 // bit is `Some`), and a `Caixa { behavior: None, .. }` must
14181 // also omit the key (the "author omitted the slot entirely"
14182 // partition). The three-fixture family jointly pins the
14183 // accessor + M2 overlay emitter composition: any future
14184 // silent detour that had the accessor return a fresh-cloned
14185 // copy on the `Some` arm (a `BehaviorSpec::clone()`
14186 // projection) would silently break the reference-identity
14187 // pin the peer per-callback `serde_yaml::to_value(behavior)`
14188 // projection reads from.
14189 //
14190 // Peer of the sibling
14191 // `servico_m2_overlay_limits_arm_routes_through_accessor`
14192 // (b2bd9d7) composition pin on the sibling `:limits` outer-
14193 // `Option<&LimitsSpec>` arm of the same
14194 // [`crate::render::servico_m2_overlay`] M2 overlay emitter's
14195 // traversal — same "the emitter must route through the
14196 // substrate-primitive typed dispatch on the outer composite"
14197 // discipline extended onto the outer top-level [`Caixa`]
14198 // `Option<&BehaviorSpec>`-composition surface.
14199 use crate::BehaviorSpec;
14200 use crate::render::{M2_KEY_BEHAVIOR, servico_m2_overlay};
14201 use std::path::PathBuf;
14202 let c = caixa_with_behavior(Some(BehaviorSpec {
14203 on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
14204 ..Default::default()
14205 }));
14206 let overlay = servico_m2_overlay(&c).unwrap();
14207 assert!(
14208 overlay.contains_key(M2_KEY_BEHAVIOR),
14209 "servico_m2_overlay must surface M2_KEY_BEHAVIOR when \
14210 `:behavior` carries a non-empty composite — the accessor \
14211 and the M2 overlay emitter must route through the same \
14212 substrate-primitive typed dispatch on the outer :behavior \
14213 composite (got overlay={overlay:?})",
14214 );
14215 let c = caixa_with_behavior(Some(BehaviorSpec::default()));
14216 let overlay = servico_m2_overlay(&c).unwrap();
14217 assert!(
14218 !overlay.contains_key(M2_KEY_BEHAVIOR),
14219 "servico_m2_overlay must omit M2_KEY_BEHAVIOR when \
14220 `:behavior` is Some(BehaviorSpec::default()) — the empty \
14221 composite's `.is_empty()`-gated inner arm must elide the \
14222 key regardless of the outer presence bit (got \
14223 overlay={overlay:?})",
14224 );
14225 let c = caixa_with_behavior(None);
14226 let overlay = servico_m2_overlay(&c).unwrap();
14227 assert!(
14228 !overlay.contains_key(M2_KEY_BEHAVIOR),
14229 "servico_m2_overlay must omit M2_KEY_BEHAVIOR when \
14230 `:behavior` is None — the author-omitted arm must route \
14231 through the accessor's None-return unchanged (got \
14232 overlay={overlay:?})",
14233 );
14234 }
14235
14236 #[test]
14237 fn behavior_projects_option_ref_by_borrow() {
14238 // The by-borrow pin: [`Caixa::behavior`] returns
14239 // `Option<&BehaviorSpec>` by borrow — the returned reference
14240 // borrows the underlying `Option<BehaviorSpec>` storage of the
14241 // `:behavior` slot and the accessor must not clone the backing
14242 // composite on every call. Peer of the sibling
14243 // `limits_projects_option_ref_by_borrow` (b2bd9d7) by-borrow
14244 // pin on the outer top-level [`Caixa`] `Option<&Composite>`-
14245 // return sub-family — extended here to the second axis of the
14246 // same sub-family: the accessor's returned reference must
14247 // borrow from `&self` (the returned reference's lifetime is
14248 // tied to `&self`), and calling the accessor twice on the same
14249 // [`Caixa`] must yield references that are pointer-equal (the
14250 // underlying byte-buffer is the storage `BehaviorSpec`'s
14251 // allocation, not a fresh copy) as well as value-equal
14252 // (idempotent, no side effects on `&self`).
14253 //
14254 // Pins against a future silent detour that returned an owned
14255 // `BehaviorSpec` (which would type-check via the `Clone` impl
14256 // but silently clone on every call), a `&BehaviorSpec` panic-
14257 // return on the `None` arm (which would collapse the load-
14258 // bearing `Option` presence-bit into a runtime panic), or a
14259 // one-arm-only accessor that returned a saturating composite
14260 // on some sentinel input.
14261 use crate::BehaviorSpec;
14262 use std::path::PathBuf;
14263 for behavior in [
14264 Some(BehaviorSpec::default()),
14265 Some(BehaviorSpec {
14266 on_init: Some(PathBuf::from("lib/init.lisp")),
14267 on_call: Some(PathBuf::from("lib/handlers.lisp")),
14268 on_cast: Some(PathBuf::from("lib/handlers.lisp")),
14269 on_info: Some(PathBuf::from("lib/handlers.lisp")),
14270 on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
14271 on_terminate: Some(PathBuf::from("lib/cleanup.lisp")),
14272 }),
14273 ] {
14274 let c = caixa_with_behavior(behavior.clone());
14275 let first = c.behavior().unwrap();
14276 let second = c.behavior().unwrap();
14277 assert_eq!(
14278 first, second,
14279 "Caixa::behavior must be idempotent — two successive \
14280 calls on the same &self must return the same \
14281 &BehaviorSpec",
14282 );
14283 assert!(
14284 std::ptr::eq(first, second),
14285 "Caixa::behavior must borrow the underlying \
14286 Option<BehaviorSpec> storage — two successive calls \
14287 must return references with the same backing pointer \
14288 (a fresh BehaviorSpec clone would change the pointer \
14289 on every call)",
14290 );
14291 assert_eq!(
14292 Some(first),
14293 behavior.as_ref(),
14294 "Caixa::behavior must return :behavior verbatim by \
14295 borrow — got {first:?}, expected {:?}",
14296 behavior.as_ref(),
14297 );
14298 }
14299 let c = caixa_with_behavior(None);
14300 assert!(
14301 c.behavior().is_none(),
14302 "Caixa::behavior must return None when :behavior is absent \
14303 — the author-omitted arm must project through the \
14304 accessor's Option::None unchanged",
14305 );
14306 }
14307
14308 // ── Caixa::politicas — outer top-level Option<&MeshPolicy> composite-reference accessor ──
14309
14310 fn caixa_aplicacao_with_politicas(politicas: Option<crate::aplicacao::MeshPolicy>) -> Caixa {
14311 use crate::aplicacao::{Membro, WitContract};
14312 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
14313 c.kind = CaixaKind::Aplicacao;
14314 c.membros = vec![Membro {
14315 caixa: "a".into(),
14316 versao: "^0.1".into(),
14317 }];
14318 c.contratos = vec![WitContract {
14319 de: "a".into(),
14320 para: "a".into(),
14321 wit: "wasi:http/proxy".into(),
14322 endpoint: Some("/x".into()),
14323 subject: None,
14324 slot: None,
14325 }];
14326 c.politicas = politicas;
14327 c
14328 }
14329
14330 #[test]
14331 fn politicas_returns_politicas_option_ref_verbatim_across_permutations() {
14332 // The canonical per-`Caixa` `:politicas` M3 mesh-slot outer-
14333 // composite optional-composite-reference-shape pin:
14334 // [`Caixa::politicas`] must return the `:politicas` typed
14335 // `Option<MeshPolicy>` verbatim as an `Option<&MeshPolicy>`
14336 // reference over the same backing storage the raw
14337 // `self.politicas.as_ref()` field access borrows from,
14338 // byte-equal across every representative fixture in the
14339 // accept-set — the author-omitted `None` shape (the "cluster-
14340 // default applies" partition every downstream mesh-artifact
14341 // emitter treats as "emit no `:politicas` overlay"), the
14342 // empty-composite `Some(MeshPolicy { .. default })` shape
14343 // ([`crate::aplicacao::MeshPolicy::is_empty`] holds — every
14344 // per-axis mesh-policy scalar is `None`, so the peer inner
14345 // [`crate::AplicacaoSpec::politicas`] `.is_empty()`-gated
14346 // caixa-mesh overlay elides every per-axis emit but the outer
14347 // presence-bit is `Some`, so [`Caixa::declared_mesh_slots`]
14348 // still pushes the `M3_AUTHOR_KEY_POLITICAS` label), a
14349 // single-axis fixture (only `:timeout` set — the canonical
14350 // shape a latency-sensitive Aplicacao carries), and a
14351 // fully-populated composite (every per-axis mesh-policy
14352 // scalar set — the canonical shape a fully-governed
14353 // Aplicacao carries).
14354 //
14355 // Pins against a future silent detour that returned a fresh-
14356 // cloned [`crate::aplicacao::MeshPolicy`] copy (which would
14357 // type-check via the `Clone` impl but silently break every
14358 // downstream caller that relied on the reference sharing the
14359 // composite's backing identity), a reference to an operator-
14360 // resolved overlay (the future per-cluster
14361 // `:politicas-overrides` slot — its resolution must land at
14362 // exactly this accessor body, not silently divert the raw
14363 // slot away from the peer [`Caixa::declared_mesh_slots`]
14364 // enumerator's presence probe), a
14365 // `None` → `Some(MeshPolicy::default)` cluster-default
14366 // projection (which would collapse the load-bearing
14367 // "author-omitted `:politicas` ⇒ cluster-default applies"
14368 // partition the peer [`Caixa::declared_mesh_slots`]
14369 // enumerator and the peer [`Caixa::aplicacao_view`]
14370 // Aplicacao-composition seed both read), or an axis-shuffled
14371 // projection (a future detour that swapped `timeout` and
14372 // `retries` through the accessor would silently split the
14373 // paired [`Caixa::aplicacao_view`] seed's fold input from the
14374 // sibling M3 mesh-artifact emitter's projection input).
14375 //
14376 // Third outer top-level [`Caixa`] `Option<&Composite>`-return
14377 // composite-reference accessor pin on the substrate primitive
14378 // — peer of the sibling
14379 // `limits_returns_limits_option_ref_verbatim_across_permutations`
14380 // (b2bd9d7) and
14381 // `behavior_returns_behavior_option_ref_verbatim_across_permutations`
14382 // (35d8b52) opening tetrad pins on the outer top-level
14383 // [`Caixa`] `Option<&Composite>`-return sub-family — extended
14384 // here to the first of the three M3 mesh-slot axes so the
14385 // opening third of the outer `Option<&Composite>` sub-family
14386 // carries the same "byte-equal, borrow-shared, presence-bit-
14387 // preserved" outer-accessor discipline.
14388 use crate::aplicacao::{CircuitBreaker, MeshPolicy, RateLimit};
14389 use std::time::Duration;
14390 let fixtures: Vec<Option<MeshPolicy>> = vec![
14391 None,
14392 Some(MeshPolicy::default()),
14393 Some(MeshPolicy {
14394 timeout: Some(Duration::from_secs(30)),
14395 ..Default::default()
14396 }),
14397 Some(MeshPolicy {
14398 timeout: Some(Duration::from_secs(30)),
14399 retries: Some(3),
14400 circuit_breaker: Some(CircuitBreaker {
14401 max_failures: 5,
14402 window: Duration::from_secs(60),
14403 }),
14404 mtls_required: Some(true),
14405 rate_limit: Some(RateLimit {
14406 rate: 100,
14407 window: Duration::from_secs(1),
14408 }),
14409 }),
14410 ];
14411 for politicas in fixtures {
14412 let c = caixa_aplicacao_with_politicas(politicas.clone());
14413 assert_eq!(
14414 c.politicas(),
14415 politicas.as_ref(),
14416 "Caixa::politicas must return :politicas verbatim (got \
14417 {:?}, expected {:?})",
14418 c.politicas(),
14419 politicas.as_ref(),
14420 );
14421 match (c.politicas(), c.politicas.as_ref()) {
14422 (Some(a), Some(b)) => assert!(
14423 std::ptr::eq(a, b),
14424 "Caixa::politicas accessor and self.politicas.as_ref() \
14425 field access must borrow the same backing storage \
14426 — the accessor is the substrate-primitive typed \
14427 dispatch every downstream Aplicacao-mesh-overlay \
14428 composite consumer must route through, and a \
14429 reference-identity split would silently break \
14430 every consumer that relied on the borrow sharing \
14431 the composite's storage",
14432 ),
14433 (None, None) => {}
14434 _ => panic!(
14435 "Caixa::politicas presence bit must byte-equal \
14436 self.politicas.is_some() — a presence-bit drift \
14437 would silently split the paired \
14438 Caixa::aplicacao_view Aplicacao-composition seed's \
14439 traversal head from the peer \
14440 Caixa::declared_mesh_slots M3 declared-slot \
14441 enumerator's presence probe",
14442 ),
14443 }
14444 assert_eq!(
14445 c.politicas().is_some(),
14446 c.politicas.is_some(),
14447 "Caixa::politicas().is_some() must byte-equal \
14448 self.politicas.is_some() — a presence-bit drift would \
14449 silently split every downstream Option<&MeshPolicy> \
14450 consumer's partition on the cluster-default arm",
14451 );
14452 }
14453 }
14454
14455 #[test]
14456 fn declared_mesh_slots_politicas_arm_routes_through_accessor() {
14457 // Composition pin: [`Caixa::declared_mesh_slots`]'s
14458 // `:politicas` presence-probe arm must key off
14459 // [`Caixa::politicas`], not the raw `self.politicas.is_some()`
14460 // field-probe. Structurally: a `Caixa { politicas:
14461 // Some(MeshPolicy::default()), .. }` must still push
14462 // `M3_AUTHOR_KEY_POLITICAS` onto the declared-slot list (the
14463 // presence bit is `Some`, so the M3 kind-coherence gate must
14464 // surface the slot as "declared" even when every per-axis
14465 // scalar is unset), and a `Caixa { politicas: None, .. }` must
14466 // NOT push the label (the "author omitted the slot entirely"
14467 // partition). The pair jointly pins the accessor + declared-
14468 // slot enumerator composition: any future silent detour that
14469 // had the accessor collapse `Some(MeshPolicy::default())` to
14470 // `None` (a `.filter(|p| !p.is_empty())` projection) would
14471 // silently absorb the "declared but empty" arm at the
14472 // accessor boundary and the
14473 // [`crate::LayoutError::MeshSlotsOnNonAplicacao`] kind-
14474 // coherence gate would silently accept a struct-literal
14475 // `Caixa` carrying the drift.
14476 //
14477 // Peer of the sibling
14478 // `declared_servico_slots_limits_arm_routes_through_accessor`
14479 // (b2bd9d7) and
14480 // `declared_servico_slots_behavior_arm_routes_through_accessor`
14481 // (35d8b52) composition pins on the sibling `:limits` /
14482 // `:behavior` outer-`Option<&Composite>` arms of the peer
14483 // [`Caixa::declared_servico_slots`] M2 declared-slot
14484 // enumerator's traversal — same "the enumerator gate must
14485 // route through the substrate-primitive typed dispatch"
14486 // discipline extended onto the outer top-level [`Caixa`] M3
14487 // mesh-slot family so the [`Caixa::declared_mesh_slots`]
14488 // enumerator carries the same routing invariant as its M2
14489 // sibling.
14490 use crate::aplicacao::MeshPolicy;
14491 let c = caixa_aplicacao_with_politicas(Some(MeshPolicy::default()));
14492 let slots = c.declared_mesh_slots();
14493 assert!(
14494 slots.contains(&crate::render::M3_AUTHOR_KEY_POLITICAS),
14495 "declared_mesh_slots must push M3_AUTHOR_KEY_POLITICAS \
14496 when `:politicas` is Some (even for MeshPolicy::default()) \
14497 — the accessor and the enumerator gate must route through \
14498 the same substrate-primitive typed dispatch on the outer \
14499 :politicas presence bit (got slots={slots:?})",
14500 );
14501 let c = caixa_aplicacao_with_politicas(None);
14502 let slots = c.declared_mesh_slots();
14503 assert!(
14504 !slots.contains(&crate::render::M3_AUTHOR_KEY_POLITICAS),
14505 "declared_mesh_slots must NOT push M3_AUTHOR_KEY_POLITICAS \
14506 when `:politicas` is None — the author-omitted arm must \
14507 route through the accessor's None-return unchanged (got \
14508 slots={slots:?})",
14509 );
14510 }
14511
14512 #[test]
14513 fn aplicacao_view_politicas_arm_folds_through_accessor() {
14514 // Composition pin: [`Caixa::aplicacao_view`]'s per-`:politicas`
14515 // Aplicacao-composition seed must fold through
14516 // [`Caixa::politicas`], not the raw
14517 // `self.politicas.clone().unwrap_or_default()` field-borrow.
14518 // Structurally: a `Caixa { politicas: Some(MeshPolicy {
14519 // timeout: Some(30s), .. default }), kind: Aplicacao, .. }`
14520 // must surface a projected [`crate::AplicacaoSpec`] whose
14521 // `politicas().timeout()` field byte-equals the outer
14522 // composite's `timeout` scalar (the fold must project the
14523 // authored composite verbatim), a `Caixa { politicas:
14524 // Some(MeshPolicy::default()), kind: Aplicacao, .. }` must
14525 // surface an [`crate::AplicacaoSpec`] whose `politicas()`
14526 // byte-equals [`crate::aplicacao::MeshPolicy::default`] (the
14527 // fold's empty-composite arm collapses to the same default the
14528 // author-omitted arm does), and a `Caixa { politicas: None,
14529 // kind: Aplicacao, .. }` must surface an
14530 // [`crate::AplicacaoSpec`] whose `politicas()` byte-equals
14531 // [`crate::aplicacao::MeshPolicy::default`] (the "author
14532 // omitted the slot entirely" arm folds through the
14533 // `unwrap_or_default` onto the cluster-default). The triad
14534 // jointly pins the accessor + Aplicacao-composition seed
14535 // composition: any future silent detour that had the accessor
14536 // divert the raw slot away from the seed's fold (an operator-
14537 // resolved overlay's default-fold arm silently differing from
14538 // the raw slot's default-fold arm) would silently split the
14539 // build-time mesh-artifact emission gate from the caixa-mesh
14540 // renderer's Aplicacao-view input at the composition boundary.
14541 use crate::aplicacao::MeshPolicy;
14542 use std::time::Duration;
14543 let c = caixa_aplicacao_with_politicas(Some(MeshPolicy {
14544 timeout: Some(Duration::from_secs(30)),
14545 ..Default::default()
14546 }));
14547 let view = c.aplicacao_view().unwrap();
14548 assert_eq!(
14549 view.politicas().timeout(),
14550 Some(Duration::from_secs(30)),
14551 "Caixa::aplicacao_view must fold the authored :politicas \
14552 :timeout scalar through the accessor verbatim onto the \
14553 projected AplicacaoSpec — a future silent detour at the \
14554 seed's fold arm would surface here as a projected-scalar \
14555 drift (got {:?})",
14556 view.politicas().timeout(),
14557 );
14558 let c = caixa_aplicacao_with_politicas(Some(MeshPolicy::default()));
14559 let view = c.aplicacao_view().unwrap();
14560 assert_eq!(
14561 view.politicas(),
14562 &MeshPolicy::default(),
14563 "Caixa::aplicacao_view must fold Some(MeshPolicy::default()) \
14564 through the accessor onto MeshPolicy::default — the empty- \
14565 composite arm collapses to the same default the author- \
14566 omitted arm does (got {:?})",
14567 view.politicas(),
14568 );
14569 let c = caixa_aplicacao_with_politicas(None);
14570 let view = c.aplicacao_view().unwrap();
14571 assert_eq!(
14572 view.politicas(),
14573 &MeshPolicy::default(),
14574 "Caixa::aplicacao_view must fold None through the accessor's \
14575 unwrap_or_default onto MeshPolicy::default — the author- \
14576 omitted arm must route through the accessor's None-return \
14577 unchanged (got {:?})",
14578 view.politicas(),
14579 );
14580 }
14581
14582 #[test]
14583 fn politicas_projects_option_ref_by_borrow() {
14584 // The by-borrow pin: [`Caixa::politicas`] returns
14585 // `Option<&MeshPolicy>` by borrow — the returned reference
14586 // borrows the underlying `Option<MeshPolicy>` storage of the
14587 // `:politicas` slot and the accessor must not clone the
14588 // backing composite on every call. Peer of the sibling
14589 // `limits_projects_option_ref_by_borrow` (b2bd9d7) and
14590 // `behavior_projects_option_ref_by_borrow` (35d8b52) by-borrow
14591 // pins on the outer top-level [`Caixa`]
14592 // `Option<&Composite>`-return sub-family — extended here to
14593 // the third axis of the same sub-family: the accessor's
14594 // returned reference must borrow from `&self` (the returned
14595 // reference's lifetime is tied to `&self`), and calling the
14596 // accessor twice on the same [`Caixa`] must yield references
14597 // that are pointer-equal (the underlying byte-buffer is the
14598 // storage `MeshPolicy`'s allocation, not a fresh copy) as
14599 // well as value-equal (idempotent, no side effects on
14600 // `&self`).
14601 //
14602 // Pins against a future silent detour that returned an owned
14603 // `MeshPolicy` (which would type-check via the `Clone` impl
14604 // but silently clone on every call), a `&MeshPolicy` panic-
14605 // return on the `None` arm (which would collapse the load-
14606 // bearing `Option` presence-bit into a runtime panic), or a
14607 // one-arm-only accessor that returned a saturating composite
14608 // on some sentinel input.
14609 use crate::aplicacao::{CircuitBreaker, MeshPolicy, RateLimit};
14610 use std::time::Duration;
14611 for politicas in [
14612 Some(MeshPolicy::default()),
14613 Some(MeshPolicy {
14614 timeout: Some(Duration::from_secs(30)),
14615 retries: Some(3),
14616 circuit_breaker: Some(CircuitBreaker {
14617 max_failures: 5,
14618 window: Duration::from_secs(60),
14619 }),
14620 mtls_required: Some(true),
14621 rate_limit: Some(RateLimit {
14622 rate: 100,
14623 window: Duration::from_secs(1),
14624 }),
14625 }),
14626 ] {
14627 let c = caixa_aplicacao_with_politicas(politicas.clone());
14628 let first = c.politicas().unwrap();
14629 let second = c.politicas().unwrap();
14630 assert_eq!(
14631 first, second,
14632 "Caixa::politicas must be idempotent — two successive \
14633 calls on the same &self must return the same \
14634 &MeshPolicy",
14635 );
14636 assert!(
14637 std::ptr::eq(first, second),
14638 "Caixa::politicas must borrow the underlying \
14639 Option<MeshPolicy> storage — two successive calls \
14640 must return references with the same backing pointer \
14641 (a fresh MeshPolicy clone would change the pointer on \
14642 every call)",
14643 );
14644 assert_eq!(
14645 Some(first),
14646 politicas.as_ref(),
14647 "Caixa::politicas must return :politicas verbatim by \
14648 borrow — got {first:?}, expected {:?}",
14649 politicas.as_ref(),
14650 );
14651 }
14652 let c = caixa_aplicacao_with_politicas(None);
14653 assert!(
14654 c.politicas().is_none(),
14655 "Caixa::politicas must return None when :politicas is \
14656 absent — the author-omitted arm must project through the \
14657 accessor's Option::None unchanged",
14658 );
14659 }
14660
14661 // ── Caixa::placement — outer top-level Option<&Placement> composite-reference accessor ──
14662
14663 fn caixa_aplicacao_with_placement(placement: Option<crate::aplicacao::Placement>) -> Caixa {
14664 use crate::aplicacao::{Membro, WitContract};
14665 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
14666 c.kind = CaixaKind::Aplicacao;
14667 c.membros = vec![Membro {
14668 caixa: "a".into(),
14669 versao: "^0.1".into(),
14670 }];
14671 c.contratos = vec![WitContract {
14672 de: "a".into(),
14673 para: "a".into(),
14674 wit: "wasi:http/proxy".into(),
14675 endpoint: Some("/x".into()),
14676 subject: None,
14677 slot: None,
14678 }];
14679 c.placement = placement;
14680 c
14681 }
14682
14683 #[test]
14684 fn placement_returns_placement_option_ref_verbatim_across_permutations() {
14685 // The canonical per-`Caixa` `:placement` M3 mesh-slot outer-
14686 // composite optional-composite-reference-shape pin:
14687 // [`Caixa::placement`] must return the `:placement` typed
14688 // `Option<Placement>` verbatim as an `Option<&Placement>`
14689 // reference over the same backing storage the raw
14690 // `self.placement.as_ref()` field access borrows from,
14691 // byte-equal across every representative fixture in the
14692 // accept-set — the author-omitted `None` shape (the
14693 // "cluster-default applies" partition every downstream mesh-
14694 // artifact emitter treats as "emit no `:placement` overlay"),
14695 // the empty-composite `Some(Placement { .. default })` shape
14696 // (`estrategia: SingleNode`, empty clusters, no shard-key /
14697 // affinity — the outer presence-bit is `Some` so
14698 // [`Caixa::declared_mesh_slots`] still pushes the
14699 // `M3_AUTHOR_KEY_PLACEMENT` label), a single-axis
14700 // `Replicated`-on-two-clusters fixture (the canonical shape a
14701 // stateless HTTP Aplicacao carries), and a fully-populated
14702 // `Sharded`-with-shard-key-and-affinity fixture (the canonical
14703 // shape a stateful Akka-style cluster-sharding Aplicacao
14704 // carries).
14705 //
14706 // Pins against a future silent detour that returned a fresh-
14707 // cloned [`crate::aplicacao::Placement`] copy (which would
14708 // type-check via the `Clone` impl but silently break every
14709 // downstream caller that relied on the reference sharing the
14710 // composite's backing identity), a reference to an operator-
14711 // resolved overlay (the future per-cluster
14712 // `:placement-overrides` slot — its resolution must land at
14713 // exactly this accessor body, not silently divert the raw
14714 // slot away from the peer [`Caixa::declared_mesh_slots`]
14715 // enumerator's presence probe), a `None` →
14716 // `Some(Placement::default)` cluster-default projection (which
14717 // would collapse the load-bearing "author-omitted `:placement`
14718 // ⇒ cluster-default applies" partition the peer
14719 // [`Caixa::declared_mesh_slots`] enumerator and the peer
14720 // [`Caixa::aplicacao_view`] Aplicacao-composition seed both
14721 // read), or an axis-shuffled projection (a future detour that
14722 // swapped `clusters` and `affinity` through the accessor would
14723 // silently split the paired [`Caixa::aplicacao_view`] seed's
14724 // fold input from the sibling M3 mesh-artifact emitter's
14725 // projection input).
14726 //
14727 // Fourth outer top-level [`Caixa`] `Option<&Composite>`-return
14728 // composite-reference accessor pin on the substrate primitive
14729 // — peer of the sibling
14730 // `limits_returns_limits_option_ref_verbatim_across_permutations`
14731 // (b2bd9d7),
14732 // `behavior_returns_behavior_option_ref_verbatim_across_permutations`
14733 // (35d8b52), and
14734 // `politicas_returns_politicas_option_ref_verbatim_across_permutations`
14735 // (5d23d29) opening triad pins on the outer top-level
14736 // [`Caixa`] `Option<&Composite>`-return sub-family — extended
14737 // here to the second of the three M3 mesh-slot axes so the
14738 // opening four-fifths of the outer `Option<&Composite>` sub-
14739 // family carries the same "byte-equal, borrow-shared,
14740 // presence-bit-preserved" outer-accessor discipline.
14741 use crate::aplicacao::{Placement, PlacementStrategy};
14742 let fixtures: Vec<Option<Placement>> = vec![
14743 None,
14744 Some(Placement::default()),
14745 Some(Placement {
14746 estrategia: PlacementStrategy::Replicated,
14747 clusters: vec!["rio".into(), "sao-paulo".into()],
14748 affinity: None,
14749 shard_key: None,
14750 }),
14751 Some(Placement {
14752 estrategia: PlacementStrategy::Sharded,
14753 clusters: vec!["rio".into(), "sao-paulo".into(), "brasilia".into()],
14754 affinity: Some("data-locality".into()),
14755 shard_key: Some("$tenantId".into()),
14756 }),
14757 ];
14758 for placement in fixtures {
14759 let c = caixa_aplicacao_with_placement(placement.clone());
14760 assert_eq!(
14761 c.placement(),
14762 placement.as_ref(),
14763 "Caixa::placement must return :placement verbatim (got \
14764 {:?}, expected {:?})",
14765 c.placement(),
14766 placement.as_ref(),
14767 );
14768 match (c.placement(), c.placement.as_ref()) {
14769 (Some(a), Some(b)) => assert!(
14770 std::ptr::eq(a, b),
14771 "Caixa::placement accessor and self.placement.as_ref() \
14772 field access must borrow the same backing storage \
14773 — the accessor is the substrate-primitive typed \
14774 dispatch every downstream Aplicacao-distribution- \
14775 overlay composite consumer must route through, and \
14776 a reference-identity split would silently break \
14777 every consumer that relied on the borrow sharing \
14778 the composite's storage",
14779 ),
14780 (None, None) => {}
14781 _ => panic!(
14782 "Caixa::placement presence bit must byte-equal \
14783 self.placement.is_some() — a presence-bit drift \
14784 would silently split the paired \
14785 Caixa::aplicacao_view Aplicacao-composition seed's \
14786 traversal head from the peer \
14787 Caixa::declared_mesh_slots M3 declared-slot \
14788 enumerator's presence probe",
14789 ),
14790 }
14791 assert_eq!(
14792 c.placement().is_some(),
14793 c.placement.is_some(),
14794 "Caixa::placement().is_some() must byte-equal \
14795 self.placement.is_some() — a presence-bit drift would \
14796 silently split every downstream Option<&Placement> \
14797 consumer's partition on the cluster-default arm",
14798 );
14799 }
14800 }
14801
14802 #[test]
14803 fn declared_mesh_slots_placement_arm_routes_through_accessor() {
14804 // Composition pin: [`Caixa::declared_mesh_slots`]'s
14805 // `:placement` presence-probe arm must key off
14806 // [`Caixa::placement`], not the raw `self.placement.is_some()`
14807 // field-probe. Structurally: a `Caixa { placement:
14808 // Some(Placement::default()), .. }` must still push
14809 // `M3_AUTHOR_KEY_PLACEMENT` onto the declared-slot list (the
14810 // presence bit is `Some`, so the M3 kind-coherence gate must
14811 // surface the slot as "declared" even when every per-axis
14812 // scalar defers to the cluster-default arm), and a `Caixa {
14813 // placement: None, .. }` must NOT push the label (the "author
14814 // omitted the slot entirely" partition). The pair jointly pins
14815 // the accessor + declared-slot enumerator composition: any
14816 // future silent detour that had the accessor collapse
14817 // `Some(Placement::default())` to `None` (a `.filter(|p|
14818 // p.clusters().is_empty().not())` projection) would silently
14819 // absorb the "declared but empty" arm at the accessor boundary
14820 // and the [`crate::LayoutError::MeshSlotsOnNonAplicacao`]
14821 // kind-coherence gate would silently accept a struct-literal
14822 // `Caixa` carrying the drift.
14823 //
14824 // Peer of the sibling
14825 // `declared_servico_slots_limits_arm_routes_through_accessor`
14826 // (b2bd9d7),
14827 // `declared_servico_slots_behavior_arm_routes_through_accessor`
14828 // (35d8b52), and
14829 // `declared_mesh_slots_politicas_arm_routes_through_accessor`
14830 // (5d23d29) composition pins on the sibling `:limits` /
14831 // `:behavior` / `:politicas` outer-`Option<&Composite>` arms
14832 // — same "the enumerator gate must route through the
14833 // substrate-primitive typed dispatch" discipline extended onto
14834 // the second of the three M3 mesh-slot axes so the
14835 // [`Caixa::declared_mesh_slots`] enumerator carries the same
14836 // routing invariant on the `:placement` arm as the peer
14837 // `:politicas` arm.
14838 use crate::aplicacao::Placement;
14839 let c = caixa_aplicacao_with_placement(Some(Placement::default()));
14840 let slots = c.declared_mesh_slots();
14841 assert!(
14842 slots.contains(&crate::render::M3_AUTHOR_KEY_PLACEMENT),
14843 "declared_mesh_slots must push M3_AUTHOR_KEY_PLACEMENT \
14844 when `:placement` is Some (even for Placement::default()) \
14845 — the accessor and the enumerator gate must route through \
14846 the same substrate-primitive typed dispatch on the outer \
14847 :placement presence bit (got slots={slots:?})",
14848 );
14849 let c = caixa_aplicacao_with_placement(None);
14850 let slots = c.declared_mesh_slots();
14851 assert!(
14852 !slots.contains(&crate::render::M3_AUTHOR_KEY_PLACEMENT),
14853 "declared_mesh_slots must NOT push M3_AUTHOR_KEY_PLACEMENT \
14854 when `:placement` is None — the author-omitted arm must \
14855 route through the accessor's None-return unchanged (got \
14856 slots={slots:?})",
14857 );
14858 }
14859
14860 #[test]
14861 fn aplicacao_view_placement_arm_folds_through_accessor() {
14862 // Composition pin: [`Caixa::aplicacao_view`]'s per-`:placement`
14863 // Aplicacao-composition seed must fold through
14864 // [`Caixa::placement`], not the raw
14865 // `self.placement.clone().unwrap_or_default()` field-borrow.
14866 // Structurally: a `Caixa { placement: Some(Placement {
14867 // estrategia: Replicated, clusters: ["rio"], .. default }),
14868 // kind: Aplicacao, .. }` must surface a projected
14869 // [`crate::AplicacaoSpec`] whose `placement().estrategia()` +
14870 // `placement().clusters()` byte-equal the outer composite's
14871 // authored values (the fold must project the authored
14872 // composite verbatim), a `Caixa { placement:
14873 // Some(Placement::default()), kind: Aplicacao, .. }` must
14874 // surface an [`crate::AplicacaoSpec`] whose `placement()`
14875 // byte-equals [`crate::aplicacao::Placement::default`] (the
14876 // fold's empty-composite arm collapses to the same default
14877 // the author-omitted arm does), and a `Caixa { placement:
14878 // None, kind: Aplicacao, .. }` must surface an
14879 // [`crate::AplicacaoSpec`] whose `placement()` byte-equals
14880 // [`crate::aplicacao::Placement::default`] (the "author
14881 // omitted the slot entirely" arm folds through the
14882 // `unwrap_or_default` onto the cluster-default). The triad
14883 // jointly pins the accessor + Aplicacao-composition seed
14884 // composition: any future silent detour that had the accessor
14885 // divert the raw slot away from the seed's fold (an operator-
14886 // resolved overlay's default-fold arm silently differing from
14887 // the raw slot's default-fold arm) would silently split the
14888 // build-time distribution-artifact emission gate from the
14889 // caixa-mesh renderer's Aplicacao-view input at the
14890 // composition boundary.
14891 use crate::aplicacao::{Placement, PlacementStrategy};
14892 let c = caixa_aplicacao_with_placement(Some(Placement {
14893 estrategia: PlacementStrategy::Replicated,
14894 clusters: vec!["rio".into()],
14895 affinity: None,
14896 shard_key: None,
14897 }));
14898 let view = c.aplicacao_view().unwrap();
14899 assert_eq!(
14900 view.placement().estrategia(),
14901 PlacementStrategy::Replicated,
14902 "Caixa::aplicacao_view must fold the authored :placement \
14903 :estrategia scalar through the accessor verbatim onto the \
14904 projected AplicacaoSpec — a future silent detour at the \
14905 seed's fold arm would surface here as a projected-scalar \
14906 drift (got {:?})",
14907 view.placement().estrategia(),
14908 );
14909 assert_eq!(
14910 view.placement().clusters(),
14911 &["rio"],
14912 "Caixa::aplicacao_view must fold the authored :placement \
14913 :clusters list through the accessor verbatim onto the \
14914 projected AplicacaoSpec — a future silent detour at the \
14915 seed's fold arm would surface here as a projected-list \
14916 drift (got {:?})",
14917 view.placement().clusters(),
14918 );
14919 let c = caixa_aplicacao_with_placement(Some(Placement::default()));
14920 let view = c.aplicacao_view().unwrap();
14921 assert_eq!(
14922 view.placement(),
14923 &Placement::default(),
14924 "Caixa::aplicacao_view must fold Some(Placement::default()) \
14925 through the accessor onto Placement::default — the empty- \
14926 composite arm collapses to the same default the author- \
14927 omitted arm does (got {:?})",
14928 view.placement(),
14929 );
14930 let c = caixa_aplicacao_with_placement(None);
14931 let view = c.aplicacao_view().unwrap();
14932 assert_eq!(
14933 view.placement(),
14934 &Placement::default(),
14935 "Caixa::aplicacao_view must fold None through the accessor's \
14936 unwrap_or_default onto Placement::default — the author- \
14937 omitted arm must route through the accessor's None-return \
14938 unchanged (got {:?})",
14939 view.placement(),
14940 );
14941 }
14942
14943 #[test]
14944 fn placement_projects_option_ref_by_borrow() {
14945 // The by-borrow pin: [`Caixa::placement`] returns
14946 // `Option<&Placement>` by borrow — the returned reference
14947 // borrows the underlying `Option<Placement>` storage of the
14948 // `:placement` slot and the accessor must not clone the
14949 // backing composite on every call. Peer of the sibling
14950 // `limits_projects_option_ref_by_borrow` (b2bd9d7),
14951 // `behavior_projects_option_ref_by_borrow` (35d8b52), and
14952 // `politicas_projects_option_ref_by_borrow` (5d23d29) by-borrow
14953 // pins on the outer top-level [`Caixa`]
14954 // `Option<&Composite>`-return sub-family — extended here to
14955 // the fourth axis of the same sub-family: the accessor's
14956 // returned reference must borrow from `&self` (the returned
14957 // reference's lifetime is tied to `&self`), and calling the
14958 // accessor twice on the same [`Caixa`] must yield references
14959 // that are pointer-equal (the underlying byte-buffer is the
14960 // storage `Placement`'s allocation, not a fresh copy) as well
14961 // as value-equal (idempotent, no side effects on `&self`).
14962 //
14963 // Pins against a future silent detour that returned an owned
14964 // `Placement` (which would type-check via the `Clone` impl
14965 // but silently clone on every call), a `&Placement` panic-
14966 // return on the `None` arm (which would collapse the load-
14967 // bearing `Option` presence-bit into a runtime panic), or a
14968 // one-arm-only accessor that returned a saturating composite
14969 // on some sentinel input.
14970 use crate::aplicacao::{Placement, PlacementStrategy};
14971 for placement in [
14972 Some(Placement::default()),
14973 Some(Placement {
14974 estrategia: PlacementStrategy::Sharded,
14975 clusters: vec!["rio".into(), "sao-paulo".into()],
14976 affinity: Some("data-locality".into()),
14977 shard_key: Some("$tenantId".into()),
14978 }),
14979 ] {
14980 let c = caixa_aplicacao_with_placement(placement.clone());
14981 let first = c.placement().unwrap();
14982 let second = c.placement().unwrap();
14983 assert_eq!(
14984 first, second,
14985 "Caixa::placement must be idempotent — two successive \
14986 calls on the same &self must return the same \
14987 &Placement",
14988 );
14989 assert!(
14990 std::ptr::eq(first, second),
14991 "Caixa::placement must borrow the underlying \
14992 Option<Placement> storage — two successive calls \
14993 must return references with the same backing pointer \
14994 (a fresh Placement clone would change the pointer on \
14995 every call)",
14996 );
14997 assert_eq!(
14998 Some(first),
14999 placement.as_ref(),
15000 "Caixa::placement must return :placement verbatim by \
15001 borrow — got {first:?}, expected {:?}",
15002 placement.as_ref(),
15003 );
15004 }
15005 let c = caixa_aplicacao_with_placement(None);
15006 assert!(
15007 c.placement().is_none(),
15008 "Caixa::placement must return None when :placement is \
15009 absent — the author-omitted arm must project through the \
15010 accessor's Option::None unchanged",
15011 );
15012 }
15013
15014 // ── Caixa::entrada — outer top-level Option<&Entrada> composite-reference accessor ──
15015
15016 fn caixa_aplicacao_with_entrada(entrada: Option<crate::aplicacao::Entrada>) -> Caixa {
15017 use crate::aplicacao::{Membro, WitContract};
15018 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
15019 c.kind = CaixaKind::Aplicacao;
15020 c.membros = vec![Membro {
15021 caixa: "a".into(),
15022 versao: "^0.1".into(),
15023 }];
15024 c.contratos = vec![WitContract {
15025 de: "a".into(),
15026 para: "a".into(),
15027 wit: "wasi:http/proxy".into(),
15028 endpoint: Some("/x".into()),
15029 subject: None,
15030 slot: None,
15031 }];
15032 c.entrada = entrada;
15033 c
15034 }
15035
15036 #[test]
15037 fn entrada_returns_entrada_option_ref_verbatim_across_permutations() {
15038 // The canonical per-`Caixa` `:entrada` M3 mesh-slot outer-
15039 // composite optional-composite-reference-shape pin:
15040 // [`Caixa::entrada`] must return the `:entrada` typed
15041 // `Option<Entrada>` verbatim as an `Option<&Entrada>`
15042 // reference over the same backing storage the raw
15043 // `self.entrada.as_ref()` field access borrows from,
15044 // byte-equal across every representative fixture in the
15045 // accept-set — the author-omitted `None` shape (the
15046 // "cluster-internal Aplicacao" partition every downstream
15047 // Gateway-API emitter treats as "emit no listener + no
15048 // HTTPRoute"), a bare-`host`/`para` minimum-composite fixture
15049 // (empty `paths` — the resolved-paths fallback the peer
15050 // [`crate::aplicacao::Entrada::resolved_paths`] cascade folds
15051 // onto the substrate catch-all), and a fully-populated
15052 // multi-path-with-non-default-port fixture (the canonical
15053 // shape a public HTTP Aplicacao carries).
15054 //
15055 // Pins against a future silent detour that returned a fresh-
15056 // cloned [`crate::aplicacao::Entrada`] copy (which would
15057 // type-check via the `Clone` impl but silently break every
15058 // downstream caller that relied on the reference sharing the
15059 // composite's backing identity), a reference to an operator-
15060 // resolved overlay (the future per-cluster
15061 // `:entrada-overrides` slot — its resolution must land at
15062 // exactly this accessor body, not silently divert the raw
15063 // slot away from the peer [`Caixa::declared_mesh_slots`]
15064 // enumerator's presence probe), or an axis-shuffled projection
15065 // (a future detour that swapped `host` and `para` through the
15066 // accessor would silently split the paired
15067 // [`Caixa::aplicacao_view`] seed's forward input from the
15068 // sibling M3 gateway-artifact emitter's projection input).
15069 //
15070 // Fifth and final outer top-level [`Caixa`]
15071 // `Option<&Composite>`-return composite-reference accessor pin
15072 // on the substrate primitive — peer of the sibling
15073 // `limits_returns_limits_option_ref_verbatim_across_permutations`
15074 // (b2bd9d7),
15075 // `behavior_returns_behavior_option_ref_verbatim_across_permutations`
15076 // (35d8b52),
15077 // `politicas_returns_politicas_option_ref_verbatim_across_permutations`
15078 // (5d23d29), and
15079 // `placement_returns_placement_option_ref_verbatim_across_permutations`
15080 // (4fb8074) opening tetrad pins on the outer top-level
15081 // [`Caixa`] `Option<&Composite>`-return sub-family — extended
15082 // here to the third and final M3 mesh-slot axis so the closed
15083 // outer `Option<&Composite>` sub-family carries the same
15084 // "byte-equal, borrow-shared, presence-bit-preserved" outer-
15085 // accessor discipline across all five arms.
15086 use crate::aplicacao::Entrada;
15087 let fixtures: Vec<Option<Entrada>> = vec![
15088 None,
15089 Some(Entrada {
15090 host: "checkout.quero.cloud".into(),
15091 para: "gateway".into(),
15092 paths: Vec::new(),
15093 port: crate::DEFAULT_SERVICO_PORT,
15094 }),
15095 Some(Entrada {
15096 host: "api.pleme.io".into(),
15097 para: "public-api".into(),
15098 paths: vec!["/v1".into(), "/v2".into()],
15099 port: 8080,
15100 }),
15101 ];
15102 for entrada in fixtures {
15103 let c = caixa_aplicacao_with_entrada(entrada.clone());
15104 assert_eq!(
15105 c.entrada(),
15106 entrada.as_ref(),
15107 "Caixa::entrada must return :entrada verbatim (got \
15108 {:?}, expected {:?})",
15109 c.entrada(),
15110 entrada.as_ref(),
15111 );
15112 match (c.entrada(), c.entrada.as_ref()) {
15113 (Some(a), Some(b)) => assert!(
15114 std::ptr::eq(a, b),
15115 "Caixa::entrada accessor and self.entrada.as_ref() \
15116 field access must borrow the same backing storage \
15117 — the accessor is the substrate-primitive typed \
15118 dispatch every downstream Aplicacao-external- \
15119 gateway composite consumer must route through, and \
15120 a reference-identity split would silently break \
15121 every consumer that relied on the borrow sharing \
15122 the composite's storage",
15123 ),
15124 (None, None) => {}
15125 _ => panic!(
15126 "Caixa::entrada presence bit must byte-equal \
15127 self.entrada.is_some() — a presence-bit drift \
15128 would silently split the paired \
15129 Caixa::aplicacao_view Aplicacao-composition seed's \
15130 traversal head from the peer \
15131 Caixa::declared_mesh_slots M3 declared-slot \
15132 enumerator's presence probe",
15133 ),
15134 }
15135 assert_eq!(
15136 c.entrada().is_some(),
15137 c.entrada.is_some(),
15138 "Caixa::entrada().is_some() must byte-equal \
15139 self.entrada.is_some() — a presence-bit drift would \
15140 silently split every downstream Option<&Entrada> \
15141 consumer's partition on the cluster-internal arm",
15142 );
15143 }
15144 }
15145
15146 #[test]
15147 fn declared_mesh_slots_entrada_arm_routes_through_accessor() {
15148 // Composition pin: [`Caixa::declared_mesh_slots`]'s `:entrada`
15149 // presence-probe arm must key off [`Caixa::entrada`], not the
15150 // raw `self.entrada.is_some()` field-probe. Structurally: a
15151 // `Caixa { entrada: Some(Entrada { host: "...", para: "...",
15152 // paths: [], port: DEFAULT_SERVICO_PORT }), .. }` must push
15153 // `M3_AUTHOR_KEY_ENTRADA` onto the declared-slot list (the
15154 // presence bit is `Some`, so the M3 kind-coherence gate must
15155 // surface the slot as "declared" even when every per-axis
15156 // scalar defers to the substrate catch-all / default port),
15157 // and a `Caixa { entrada: None, .. }` must NOT push the label
15158 // (the "author omitted the slot entirely" partition). The pair
15159 // jointly pins the accessor + declared-slot enumerator
15160 // composition: any future silent detour that had the accessor
15161 // collapse `Some(Entrada { paths: [], .. })` to `None` (a
15162 // `.filter(|e| !e.paths.is_empty())` projection) would silently
15163 // absorb the "declared but empty-paths" arm at the accessor
15164 // boundary and the
15165 // [`crate::LayoutError::MeshSlotsOnNonAplicacao`] kind-
15166 // coherence gate would silently accept a struct-literal
15167 // `Caixa` carrying the drift.
15168 //
15169 // Peer of the sibling
15170 // `declared_servico_slots_limits_arm_routes_through_accessor`
15171 // (b2bd9d7),
15172 // `declared_servico_slots_behavior_arm_routes_through_accessor`
15173 // (35d8b52),
15174 // `declared_mesh_slots_politicas_arm_routes_through_accessor`
15175 // (5d23d29), and
15176 // `declared_mesh_slots_placement_arm_routes_through_accessor`
15177 // (4fb8074) composition pins on the sibling `:limits` /
15178 // `:behavior` / `:politicas` / `:placement` outer-
15179 // `Option<&Composite>` arms — same "the enumerator gate must
15180 // route through the substrate-primitive typed dispatch"
15181 // discipline extended onto the third and final M3 mesh-slot
15182 // axis so the [`Caixa::declared_mesh_slots`] enumerator now
15183 // carries the routing invariant on every M3 mesh-slot arm.
15184 use crate::aplicacao::Entrada;
15185 let c = caixa_aplicacao_with_entrada(Some(Entrada {
15186 host: "checkout.quero.cloud".into(),
15187 para: "gateway".into(),
15188 paths: Vec::new(),
15189 port: crate::DEFAULT_SERVICO_PORT,
15190 }));
15191 let slots = c.declared_mesh_slots();
15192 assert!(
15193 slots.contains(&crate::render::M3_AUTHOR_KEY_ENTRADA),
15194 "declared_mesh_slots must push M3_AUTHOR_KEY_ENTRADA when \
15195 `:entrada` is Some (even for empty-paths / default-port) \
15196 — the accessor and the enumerator gate must route through \
15197 the same substrate-primitive typed dispatch on the outer \
15198 :entrada presence bit (got slots={slots:?})",
15199 );
15200 let c = caixa_aplicacao_with_entrada(None);
15201 let slots = c.declared_mesh_slots();
15202 assert!(
15203 !slots.contains(&crate::render::M3_AUTHOR_KEY_ENTRADA),
15204 "declared_mesh_slots must NOT push M3_AUTHOR_KEY_ENTRADA \
15205 when `:entrada` is None — the author-omitted arm must \
15206 route through the accessor's None-return unchanged (got \
15207 slots={slots:?})",
15208 );
15209 }
15210
15211 #[test]
15212 fn aplicacao_view_entrada_arm_folds_through_accessor() {
15213 // Composition pin: [`Caixa::aplicacao_view`]'s per-`:entrada`
15214 // Aplicacao-composition seed must fold through
15215 // [`Caixa::entrada`], not the raw `self.entrada.clone()` field-
15216 // borrow. Structurally: a `Caixa { entrada: Some(Entrada {
15217 // host: "api.pleme.io", para: "public-api", paths: ["/v1"],
15218 // port: 8080 }), kind: Aplicacao, .. }` must surface a projected
15219 // [`crate::AplicacaoSpec`] whose `entrada().unwrap()` byte-
15220 // equals the outer composite's authored value (the fold must
15221 // project the authored composite verbatim), and a `Caixa {
15222 // entrada: None, kind: Aplicacao, .. }` must surface an
15223 // [`crate::AplicacaoSpec`] whose `entrada()` is `None` (the
15224 // "author omitted the slot entirely" arm folds through the
15225 // accessor's `Option::cloned` onto the same `None` presence
15226 // bit — unlike the peer `:politicas` / `:placement` arms
15227 // `:entrada` has no cluster-default fold, the omitted arm
15228 // stays omitted). The pair jointly pins the accessor +
15229 // Aplicacao-composition seed composition: any future silent
15230 // detour that had the accessor divert the raw slot away from
15231 // the seed's fold (an operator-resolved overlay's forward arm
15232 // silently differing from the raw slot's forward arm) would
15233 // silently split the build-time gateway-artifact emission gate
15234 // from the caixa-mesh renderer's Aplicacao-view input at the
15235 // composition boundary.
15236 use crate::aplicacao::Entrada;
15237 let authored = Entrada {
15238 host: "api.pleme.io".into(),
15239 para: "public-api".into(),
15240 paths: vec!["/v1".into()],
15241 port: 8080,
15242 };
15243 let c = caixa_aplicacao_with_entrada(Some(authored.clone()));
15244 let view = c.aplicacao_view().unwrap();
15245 assert_eq!(
15246 view.entrada(),
15247 Some(&authored),
15248 "Caixa::aplicacao_view must fold the authored :entrada \
15249 composite through the accessor verbatim onto the \
15250 projected AplicacaoSpec — a future silent detour at the \
15251 seed's fold arm would surface here as a projected- \
15252 composite drift (got {:?})",
15253 view.entrada(),
15254 );
15255 let c = caixa_aplicacao_with_entrada(None);
15256 let view = c.aplicacao_view().unwrap();
15257 assert!(
15258 view.entrada().is_none(),
15259 "Caixa::aplicacao_view must fold None through the \
15260 accessor's Option::cloned onto None — the author- \
15261 omitted arm must route through the accessor's None-return \
15262 unchanged (got {:?})",
15263 view.entrada(),
15264 );
15265 }
15266
15267 #[test]
15268 fn entrada_projects_option_ref_by_borrow() {
15269 // The by-borrow pin: [`Caixa::entrada`] returns
15270 // `Option<&Entrada>` by borrow — the returned reference
15271 // borrows the underlying `Option<Entrada>` storage of the
15272 // `:entrada` slot and the accessor must not clone the backing
15273 // composite on every call. Peer of the sibling
15274 // `limits_projects_option_ref_by_borrow` (b2bd9d7),
15275 // `behavior_projects_option_ref_by_borrow` (35d8b52),
15276 // `politicas_projects_option_ref_by_borrow` (5d23d29), and
15277 // `placement_projects_option_ref_by_borrow` (4fb8074) by-
15278 // borrow pins on the outer top-level [`Caixa`]
15279 // `Option<&Composite>`-return sub-family — extended here to
15280 // the fifth and final axis of the same sub-family, closing
15281 // the discipline: the accessor's returned reference must
15282 // borrow from `&self` (the returned reference's lifetime is
15283 // tied to `&self`), and calling the accessor twice on the
15284 // same [`Caixa`] must yield references that are pointer-equal
15285 // (the underlying byte-buffer is the storage `Entrada`'s
15286 // allocation, not a fresh copy) as well as value-equal
15287 // (idempotent, no side effects on `&self`).
15288 //
15289 // Pins against a future silent detour that returned an owned
15290 // `Entrada` (which would type-check via the `Clone` impl but
15291 // silently clone on every call), a `&Entrada` panic-return on
15292 // the `None` arm (which would collapse the load-bearing
15293 // `Option` presence-bit into a runtime panic), or a one-arm-
15294 // only accessor that returned a saturating composite on some
15295 // sentinel input.
15296 use crate::aplicacao::Entrada;
15297 for entrada in [
15298 Some(Entrada {
15299 host: "checkout.quero.cloud".into(),
15300 para: "gateway".into(),
15301 paths: Vec::new(),
15302 port: crate::DEFAULT_SERVICO_PORT,
15303 }),
15304 Some(Entrada {
15305 host: "api.pleme.io".into(),
15306 para: "public-api".into(),
15307 paths: vec!["/v1".into(), "/v2".into()],
15308 port: 8080,
15309 }),
15310 ] {
15311 let c = caixa_aplicacao_with_entrada(entrada.clone());
15312 let first = c.entrada().unwrap();
15313 let second = c.entrada().unwrap();
15314 assert_eq!(
15315 first, second,
15316 "Caixa::entrada must be idempotent — two successive \
15317 calls on the same &self must return the same &Entrada",
15318 );
15319 assert!(
15320 std::ptr::eq(first, second),
15321 "Caixa::entrada must borrow the underlying \
15322 Option<Entrada> storage — two successive calls must \
15323 return references with the same backing pointer (a \
15324 fresh Entrada clone would change the pointer on every \
15325 call)",
15326 );
15327 assert_eq!(
15328 Some(first),
15329 entrada.as_ref(),
15330 "Caixa::entrada must return :entrada verbatim by \
15331 borrow — got {first:?}, expected {:?}",
15332 entrada.as_ref(),
15333 );
15334 }
15335 let c = caixa_aplicacao_with_entrada(None);
15336 assert!(
15337 c.entrada().is_none(),
15338 "Caixa::entrada must return None when :entrada is absent \
15339 — the author-omitted arm must project through the \
15340 accessor's Option::None unchanged",
15341 );
15342 }
15343
15344 // ── Caixa::estrategia — outer top-level Option<RestartStrategy> flat-spread supervisor-tree accessor ──
15345
15346 fn caixa_with_estrategia(estrategia: Option<crate::supervisor::RestartStrategy>) -> Caixa {
15347 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
15348 c.estrategia = estrategia;
15349 c
15350 }
15351
15352 #[test]
15353 fn estrategia_returns_estrategia_option_verbatim_across_permutations() {
15354 // The canonical per-`Caixa` `:estrategia` M2 supervisor-tree-slot
15355 // flat-spread `Option<RestartStrategy>`-return `Copy`-composite-
15356 // enum-arm scalar shape pin: [`Caixa::estrategia`] must return
15357 // the `:estrategia` typed `Option<crate::supervisor::RestartStrategy>`
15358 // verbatim as an `Option<RestartStrategy>` `Copy`-projected value
15359 // over the same discriminant the raw `self.estrategia` field
15360 // access carries, byte-equal across every representative fixture
15361 // in the accept-set — the author-omitted `None` shape (the
15362 // "defer to [`RestartStrategy::default`] through the
15363 // [`Self::supervisor_view`] `unwrap_or_default()` fold" partition
15364 // every non-`Supervisor`-kind `defcaixa` carries by
15365 // `#[serde(default)]`), and each of the four closed-set variants
15366 // [`RestartStrategy::OneForOne`] / [`RestartStrategy::OneForAll`]
15367 // / [`RestartStrategy::RestForOne`] /
15368 // [`RestartStrategy::SimpleOneForOne`] the author-declared arm
15369 // partitions on.
15370 //
15371 // Pins against a future silent detour that re-derived the
15372 // strategy from a peer axis (an accidental fallback to
15373 // `if children.is_empty() { SimpleOneForOne } else { OneForOne }`
15374 // collapse that read the outer `:children` list-length axis into
15375 // the strategy discriminator at the accessor boundary), a
15376 // stale-derive detour that substituted [`RestartStrategy::default`]
15377 // when the outer `Option` held `None` (which would silently
15378 // collapse the load-bearing "author explicitly declared
15379 // `:estrategia OneForOne`" vs "author omitted the slot and
15380 // inherited the default" partition the [`Self::declared_supervisor_slots`]
15381 // presence-probe reads — the enumerator gate would still push
15382 // `SUPERVISOR_AUTHOR_KEY_ESTRATEGIA` on the omitted arm, silently
15383 // splitting the paired [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`]
15384 // kind-coherence gate's traversal head from the
15385 // [`Self::supervisor_view`] `unwrap_or_default()` fold's
15386 // composition head), a reference to an operator-resolved overlay
15387 // (the future per-cluster `:estrategia-overrides` slot — its
15388 // resolution must land at exactly this accessor body, not
15389 // silently divert the raw slot away from a second consumer), or
15390 // an axis-remap projection (a future detour that mapped
15391 // `OneForAll` through the accessor onto `OneForOne` would
15392 // silently split every downstream sibling-restart-strategy
15393 // consumer's per-arm fan-out).
15394 //
15395 // First outer top-level [`Caixa`] `Option<Copy>`-return
15396 // supervisor-tree-slot flat-spread accessor pin on the substrate
15397 // primitive — opens the outer-`Caixa` `Option<Copy>` flat-spread
15398 // projection pattern the sibling per-`Caixa` `:max-restarts` /
15399 // `:restart-window` future outer-scalar pins fold on. Peer of
15400 // the inner-altitude
15401 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
15402 // (eafb619) pin on the post-composition [`SupervisorSpec`]
15403 // altitude — same "the substrate-primitive accessor must byte-
15404 // equal the raw field access verbatim across every author-
15405 // declared value" discipline extended onto the pre-composition
15406 // outer author-surface [`Caixa`] altitude. Peer of the closed
15407 // outer-`Caixa` `Option<&Composite>` composite-reference family
15408 // the sibling `limits` / `behavior` / `politicas` / `placement` /
15409 // `entrada`
15410 // `..._returns_..._option_ref_verbatim_across_permutations` pins
15411 // already carry on the outer `Option<&Composite>` altitude.
15412 use crate::supervisor::RestartStrategy;
15413 let fixtures: Vec<Option<RestartStrategy>> = vec![
15414 None,
15415 Some(RestartStrategy::OneForOne),
15416 Some(RestartStrategy::OneForAll),
15417 Some(RestartStrategy::RestForOne),
15418 Some(RestartStrategy::SimpleOneForOne),
15419 ];
15420 for estrategia in fixtures {
15421 let c = caixa_with_estrategia(estrategia);
15422 assert_eq!(
15423 c.estrategia(),
15424 estrategia,
15425 "Caixa::estrategia must return :estrategia verbatim (got \
15426 {:?}, expected {:?})",
15427 c.estrategia(),
15428 estrategia,
15429 );
15430 assert_eq!(
15431 c.estrategia(),
15432 c.estrategia,
15433 "Caixa::estrategia accessor and self.estrategia field \
15434 access must byte-equal — the accessor is the substrate-\
15435 primitive typed dispatch every downstream supervisor-\
15436 tree flat-spread consumer must route through, and a \
15437 discriminant split would silently break every consumer \
15438 that relied on the accessor sharing the field's own \
15439 Option<Copy> shape",
15440 );
15441 assert_eq!(
15442 c.estrategia().is_some(),
15443 c.estrategia.is_some(),
15444 "Caixa::estrategia().is_some() must byte-equal \
15445 self.estrategia.is_some() — a presence-bit drift would \
15446 silently split the paired Caixa::declared_supervisor_slots \
15447 presence-probe arm from the Caixa::supervisor_view \
15448 unwrap_or_default() fold's composition input",
15449 );
15450 }
15451 }
15452
15453 #[test]
15454 fn declared_supervisor_slots_estrategia_arm_routes_through_accessor() {
15455 // Composition pin: [`Caixa::declared_supervisor_slots`]'s
15456 // `:estrategia` presence-probe arm must key off
15457 // [`Caixa::estrategia`], not the raw `self.estrategia.is_some()`
15458 // field-probe. Structurally: every `Caixa { estrategia:
15459 // Some(RestartStrategy::_), .. }` variant must push
15460 // `SUPERVISOR_AUTHOR_KEY_ESTRATEGIA` onto the declared-slot list
15461 // (the presence bit is `Some` for every closed-set variant, so
15462 // the M2 supervisor-tree kind-coherence gate must surface the
15463 // slot as "declared" regardless of which variant the author
15464 // picked), and a `Caixa { estrategia: None, .. }` must NOT push
15465 // the label (the "author omitted the slot entirely, deferring
15466 // to [`RestartStrategy::default`] through the supervisor_view
15467 // fold" partition). The pair jointly pins the accessor +
15468 // declared-slot enumerator composition: any future silent detour
15469 // that had the accessor collapse `Some(RestartStrategy::default())`
15470 // to `None` (a `.filter(|e| *e != RestartStrategy::default())`
15471 // projection) would silently absorb the "declared but default-
15472 // valued" arm at the accessor boundary and the
15473 // [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`] kind-
15474 // coherence gate would silently accept a struct-literal `Caixa`
15475 // carrying the drift.
15476 //
15477 // Peer of the sibling per-`Caixa`
15478 // `declared_servico_slots_limits_arm_routes_through_accessor`
15479 // (b2bd9d7) accessor-composition pin on the sibling outer-`Caixa`
15480 // `Option<&LimitsSpec>` composition axis — same "the enumerator
15481 // gate must route through the substrate-primitive typed
15482 // dispatch" discipline extended onto the flat-spread M2
15483 // supervisor-tree `Option<RestartStrategy>`-composition surface,
15484 // opening the outer-`Caixa` supervisor-tree-slot arm of the
15485 // composition-pin family.
15486 use crate::supervisor::RestartStrategy;
15487 for estrategia in [
15488 RestartStrategy::OneForOne,
15489 RestartStrategy::OneForAll,
15490 RestartStrategy::RestForOne,
15491 RestartStrategy::SimpleOneForOne,
15492 ] {
15493 let c = caixa_with_estrategia(Some(estrategia));
15494 let slots = c.declared_supervisor_slots();
15495 assert!(
15496 slots.contains(&crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA),
15497 "declared_supervisor_slots must push \
15498 SUPERVISOR_AUTHOR_KEY_ESTRATEGIA when `:estrategia` is \
15499 Some({estrategia:?}) — the accessor and the enumerator \
15500 gate must route through the same substrate-primitive \
15501 typed dispatch on the outer :estrategia presence bit \
15502 (got slots={slots:?})",
15503 );
15504 }
15505 let c = caixa_with_estrategia(None);
15506 let slots = c.declared_supervisor_slots();
15507 assert!(
15508 !slots.contains(&crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA),
15509 "declared_supervisor_slots must NOT push \
15510 SUPERVISOR_AUTHOR_KEY_ESTRATEGIA when `:estrategia` is None \
15511 — the author-omitted arm must route through the accessor's \
15512 None-return unchanged (got slots={slots:?})",
15513 );
15514 }
15515
15516 #[test]
15517 fn supervisor_view_estrategia_arm_routes_through_accessor() {
15518 // Composition pin: [`Caixa::supervisor_view`]'s per-`:estrategia`
15519 // [`SupervisorSpec`] construction arm must key off
15520 // [`Caixa::estrategia`]'s `unwrap_or_default()` fold, not the raw
15521 // `self.estrategia.unwrap_or_default()` field-fold. Structurally:
15522 // for every `:kind Supervisor` `Caixa` carrying an author-
15523 // declared `Some(RestartStrategy::_)` variant, the composed
15524 // [`SupervisorSpec`]'s `.estrategia` field must byte-equal the
15525 // outer accessor's declared variant unchanged; and for a
15526 // `:kind Supervisor` `Caixa` carrying `None`, the composed
15527 // [`SupervisorSpec`]'s `.estrategia` field must byte-equal
15528 // [`RestartStrategy::default`] (the [`RestartStrategy::OneForOne`]
15529 // arm the flat-spread `unwrap_or_default()` fold projects to on
15530 // the author-omitted arm — this is the *composition* between the
15531 // outer `Option<RestartStrategy>` accessor's presence-bit
15532 // surface and the inner post-composition non-`Option`
15533 // [`SupervisorSpec::estrategia`] altitude). The pair jointly
15534 // pins the accessor + supervisor_view composition: any future
15535 // silent detour that had the accessor promote `None` to
15536 // `Some(RestartStrategy::default())` (a `.or_else(|| Some(RestartStrategy::default()))`
15537 // projection) would silently collapse the two arms into one at
15538 // the accessor boundary and the [`Self::declared_supervisor_slots`]
15539 // presence probe would silently drift from the composition site.
15540 //
15541 // Peer of the sibling M2 supervisor-slot post-composition
15542 // `validate_reads_through_lifted_estrategia_accessor` (eafb619)
15543 // pin on the [`SupervisorSpec::validate`] altitude — this pin
15544 // extends that inner-altitude accessor-routing discipline onto
15545 // the pre-composition outer author-surface [`Caixa`] altitude,
15546 // pinning the composition edge between the flat-spread outer
15547 // `Option<RestartStrategy>` and the composed [`SupervisorSpec`]
15548 // `RestartStrategy` axes.
15549 use crate::CaixaKind;
15550 use crate::supervisor::{ChildSpec, RestartPolicy, RestartStrategy};
15551 for estrategia in [
15552 RestartStrategy::OneForOne,
15553 RestartStrategy::OneForAll,
15554 RestartStrategy::RestForOne,
15555 RestartStrategy::SimpleOneForOne,
15556 ] {
15557 let mut c = caixa_with_estrategia(Some(estrategia));
15558 c.kind = CaixaKind::Supervisor;
15559 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
15560 // shape partition through the [`gen_platform::IsVariant`]
15561 // derive-generated
15562 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
15563 // than the raw `matches!(estrategia, RestartStrategy::
15564 // SimpleOneForOne)` open-coded pattern-match — same closed-
15565 // set-typed-enum arm-discriminator dispatch discipline the
15566 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
15567 // convergence (915a934) extended onto its two paired positive
15568 // / negated `matches!` sites and the peer
15569 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
15570 // predicate convergence (766ec63) extended onto the M3 mesh-
15571 // slot per-`:placement` distribution-strategy discriminator
15572 // axis. See the sibling `supervisor::tests::
15573 // round_trip_all_strategies` and
15574 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
15575 // fixtures — the three sites (all test-only,
15576 // acknowledged in 915a934's Prior-commits footnote as the
15577 // outstanding follow-up) now consult one typed dispatch on
15578 // the substrate primitive.
15579 c.children = if estrategia.is_simple_one_for_one() {
15580 Vec::new()
15581 } else {
15582 vec![ChildSpec {
15583 caixa: "worker".into(),
15584 versao: "^0.1".into(),
15585 restart: RestartPolicy::Permanent,
15586 }]
15587 };
15588 let view = c.supervisor_view().expect(
15589 "supervisor_view must materialize a SupervisorSpec for a \
15590 :kind Supervisor Caixa carrying a Some(:estrategia) slot",
15591 );
15592 assert_eq!(
15593 view.estrategia(),
15594 c.estrategia().unwrap(),
15595 "supervisor_view must carry the outer Caixa::estrategia() \
15596 declared variant onto the composed SupervisorSpec.estrategia \
15597 field verbatim on the Some arm (got {:?}, expected {:?})",
15598 view.estrategia(),
15599 c.estrategia().unwrap(),
15600 );
15601 }
15602 // The author-omitted arm: outer `None` → composed
15603 // `RestartStrategy::default()` through the flat-spread
15604 // `unwrap_or_default()` fold.
15605 let mut c = caixa_with_estrategia(None);
15606 c.kind = CaixaKind::Supervisor;
15607 // Populate children so the sibling supervisor slots are coherent
15608 // for the [`Self::supervisor_view`] projection; the `:estrategia`
15609 // arm still defers to [`RestartStrategy::default`] on the
15610 // author-omitted arm even when the sibling slots carry values.
15611 c.children = vec![ChildSpec {
15612 caixa: "worker".into(),
15613 versao: "^0.1".into(),
15614 restart: RestartPolicy::Permanent,
15615 }];
15616 let view = c.supervisor_view().expect(
15617 "supervisor_view must materialize a SupervisorSpec for a \
15618 :kind Supervisor Caixa carrying a None `:estrategia` slot",
15619 );
15620 assert_eq!(
15621 view.estrategia(),
15622 RestartStrategy::default(),
15623 "supervisor_view must project the outer Caixa::estrategia() \
15624 None arm onto RestartStrategy::default() through the flat-\
15625 spread unwrap_or_default() fold (got {:?}, expected {:?})",
15626 view.estrategia(),
15627 RestartStrategy::default(),
15628 );
15629 assert!(
15630 c.estrategia().is_none(),
15631 "Caixa::estrategia() must remain None on the author-omitted \
15632 arm — the supervisor_view fold must not mutate the outer \
15633 flat-spread presence bit",
15634 );
15635 }
15636
15637 #[test]
15638 fn estrategia_projects_option_by_copy() {
15639 // The by-`Copy` pin: [`Caixa::estrategia`] returns
15640 // `Option<RestartStrategy>` by value (`RestartStrategy: Copy`) —
15641 // the accessor does not borrow `&self` past the call (no
15642 // lifetime on the return type), and calling the accessor twice
15643 // on the same [`Caixa`] must yield discriminant-equal values
15644 // (idempotent, no side effects on `&self`). Peer of the sibling
15645 // outer-`Caixa` `Option<&Composite>` by-borrow
15646 // `limits_projects_option_ref_by_borrow` (b2bd9d7) /
15647 // `behavior_projects_option_ref_by_borrow` (35d8b52) /
15648 // `politicas_projects_option_ref_by_borrow` (5d23d29) /
15649 // `placement_projects_option_ref_by_borrow` (4fb8074) /
15650 // `entrada_projects_option_ref_by_borrow` (e4128e4) by-borrow
15651 // pins on the outer-`Caixa` `Option<&Composite>`-return axes —
15652 // extended here to the outer-`Caixa` `Option<Copy>`-return
15653 // flat-spread axis. The `Copy` discipline replaces the pointer-
15654 // equality claim the by-borrow siblings pin (a fresh `Copy` of a
15655 // `Copy` discriminant is definitionally the same discriminant, so
15656 // the axis reduces to discriminant equality).
15657 //
15658 // Pins against a future silent detour that returned a fresh
15659 // `Option<&RestartStrategy>` (which would type-check but silently
15660 // introduce a borrow of `&self` past the call, collapsing the
15661 // load-bearing "no lifetime on the return type" `Copy` projection
15662 // the flat-spread axis's `Option<Copy>` shape carries), a stale-
15663 // read side effect that flipped the outer discriminant on
15664 // successive calls, or an axis-remap projection that returned a
15665 // different variant than the field storage.
15666 use crate::supervisor::RestartStrategy;
15667 for estrategia in [
15668 Some(RestartStrategy::OneForOne),
15669 Some(RestartStrategy::OneForAll),
15670 Some(RestartStrategy::RestForOne),
15671 Some(RestartStrategy::SimpleOneForOne),
15672 ] {
15673 let c = caixa_with_estrategia(estrategia);
15674 let first = c.estrategia();
15675 let second = c.estrategia();
15676 assert_eq!(
15677 first, second,
15678 "Caixa::estrategia must be idempotent — two successive \
15679 calls on the same &self must return the same \
15680 Option<RestartStrategy>",
15681 );
15682 assert_eq!(
15683 first, estrategia,
15684 "Caixa::estrategia must return :estrategia verbatim by \
15685 Copy — got {first:?}, expected {estrategia:?}",
15686 );
15687 }
15688 let c = caixa_with_estrategia(None);
15689 assert!(
15690 c.estrategia().is_none(),
15691 "Caixa::estrategia must return None when :estrategia is \
15692 absent — the author-omitted arm must project through the \
15693 accessor's Option::None unchanged",
15694 );
15695 }
15696
15697 // ── Caixa::max_restarts / Caixa::restart_window —
15698 // outer top-level M2 supervisor-tree-slot flat-spread accessors
15699 // (Option<u32> / Option<&str>) folding on the ed04d3c
15700 // Caixa::estrategia Option<Copy> sub-family ─────────────────────
15701
15702 fn caixa_with_max_restarts(max_restarts: Option<u32>) -> Caixa {
15703 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
15704 c.max_restarts = max_restarts;
15705 c
15706 }
15707
15708 fn caixa_supervisor_with_max_restarts_and_window(
15709 max_restarts: Option<u32>,
15710 restart_window: Option<&str>,
15711 ) -> Caixa {
15712 use crate::CaixaKind;
15713 use crate::supervisor::{ChildSpec, RestartPolicy};
15714 let mut c = Caixa::from_lisp(&Caixa::template("root")).unwrap();
15715 c.kind = CaixaKind::Supervisor;
15716 c.max_restarts = max_restarts;
15717 c.restart_window = restart_window.map(str::to_string);
15718 c.children = vec![ChildSpec {
15719 caixa: "worker".into(),
15720 versao: "^0.1".into(),
15721 restart: RestartPolicy::Permanent,
15722 }];
15723 c
15724 }
15725
15726 #[test]
15727 fn max_restarts_returns_max_restarts_option_verbatim_across_permutations() {
15728 // Value-shape pin: [`Caixa::max_restarts`] returns the
15729 // `:max-restarts` typed `Option<u32>` verbatim, `Copy`-projected
15730 // from the typed slot's own storage, byte-equal across the
15731 // author-omitted `None` arm (the "defer to the
15732 // [`Self::supervisor_view`] `unwrap_or(5)` OTP-canonical
15733 // `{intensity, 5, 60}` default" partition every
15734 // non-`Supervisor`-kind caixa carries by `#[serde(default)]`)
15735 // and each of the representative fixtures in the accept-set —
15736 // `0` (the zero-floor arm the peer
15737 // [`crate::supervisor::SupervisorSpec::validate`]
15738 // [`crate::SupervisorError::ZeroMaxRestarts`] gate refuses on
15739 // the post-composition altitude — the accessor must ship the
15740 // raw slot verbatim so struct-literal fixtures continue to
15741 // expose the zero at the accessor boundary), the OTP-canonical
15742 // `5` default (`{intensity, 5, 60}` worker-supervisor from
15743 // Learn You Some Erlang), `1000` (the
15744 // [`SUPERVISOR_MAX_RESTARTS_MAX`] cap the peer post-composition
15745 // upper-bound gate accepts on the boundary), `u32::MAX` (a
15746 // past-the-cap sentinel that the substrate-primitive accessor
15747 // must still ship verbatim). Second outer top-level
15748 // [`Caixa`] `Option<Copy>`-return supervisor-tree flat-spread
15749 // pin — folds on the sibling
15750 // `estrategia_returns_estrategia_option_verbatim_across_permutations`
15751 // (ed04d3c) pin's `Option<Copy>` shape, extending the sub-family
15752 // onto the sibling `Option<u32>` restart-budget-count arm.
15753 let fixtures: Vec<Option<u32>> = vec![None, Some(0), Some(5), Some(1000), Some(u32::MAX)];
15754 for max_restarts in fixtures {
15755 let c = caixa_with_max_restarts(max_restarts);
15756 assert_eq!(
15757 c.max_restarts(),
15758 max_restarts,
15759 "Caixa::max_restarts must return :max-restarts verbatim \
15760 (got {:?}, expected {max_restarts:?})",
15761 c.max_restarts(),
15762 );
15763 assert_eq!(
15764 c.max_restarts(),
15765 c.max_restarts,
15766 "Caixa::max_restarts accessor and self.max_restarts \
15767 field access must byte-equal — a presence-bit or count \
15768 drift would silently split the paired \
15769 Caixa::declared_supervisor_slots presence-probe arm \
15770 from the Caixa::supervisor_view unwrap_or(5) fold's \
15771 composition input",
15772 );
15773 }
15774 }
15775
15776 #[test]
15777 fn max_restarts_projects_option_by_copy() {
15778 // The by-`Copy` pin: [`Caixa::max_restarts`] returns
15779 // `Option<u32>` by value (`u32: Copy`) — the accessor does not
15780 // borrow `&self` past the call (no lifetime on the return type),
15781 // and calling the accessor twice on the same [`Caixa`] must
15782 // yield equal values (idempotent, no side effects). Peer of the
15783 // sibling `estrategia_projects_option_by_copy` (ed04d3c) pin on
15784 // the outer-`Caixa` `Option<Copy>`-return flat-spread axis.
15785 for max_restarts in [Some(0u32), Some(5), Some(1000), Some(u32::MAX), None] {
15786 let c = caixa_with_max_restarts(max_restarts);
15787 let first = c.max_restarts();
15788 let second = c.max_restarts();
15789 assert_eq!(
15790 first, second,
15791 "Caixa::max_restarts must be idempotent — two successive \
15792 calls on the same &self must return the same Option<u32>",
15793 );
15794 assert_eq!(
15795 first, max_restarts,
15796 "Caixa::max_restarts must return :max-restarts verbatim \
15797 by Copy — got {first:?}, expected {max_restarts:?}",
15798 );
15799 }
15800 }
15801
15802 #[test]
15803 fn declared_supervisor_slots_max_restarts_arm_routes_through_accessor() {
15804 // Composition pin: [`Caixa::declared_supervisor_slots`]'s
15805 // `:max-restarts` presence-probe arm must key off
15806 // [`Caixa::max_restarts`], not the raw
15807 // `self.max_restarts.is_some()` field-probe. Structurally: every
15808 // `Caixa { max_restarts: Some(_), .. }` variant must push
15809 // `SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS` onto the declared-slot
15810 // list (the presence bit is `Some` for every representative
15811 // count, so the M2 kind-coherence gate must surface the slot as
15812 // "declared"), and a `Caixa { max_restarts: None, .. }` must
15813 // NOT push the label. Peer of the sibling
15814 // `declared_supervisor_slots_estrategia_arm_routes_through_accessor`
15815 // (ed04d3c) composition pin — same routing-through-accessor
15816 // discipline extended onto the sibling flat-spread `Option<u32>`
15817 // arm.
15818 for max_restarts in [0u32, 5, 1000, u32::MAX] {
15819 let c = caixa_with_max_restarts(Some(max_restarts));
15820 let slots = c.declared_supervisor_slots();
15821 assert!(
15822 slots.contains(&crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS),
15823 "declared_supervisor_slots must push \
15824 SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS when `:max-restarts` \
15825 is Some({max_restarts}) — the accessor and the \
15826 enumerator gate must route through the same \
15827 substrate-primitive typed dispatch on the outer \
15828 :max-restarts presence bit (got slots={slots:?})",
15829 );
15830 }
15831 let c = caixa_with_max_restarts(None);
15832 let slots = c.declared_supervisor_slots();
15833 assert!(
15834 !slots.contains(&crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS),
15835 "declared_supervisor_slots must NOT push \
15836 SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS when `:max-restarts` is \
15837 None — the author-omitted arm must route through the \
15838 accessor's None-return unchanged (got slots={slots:?})",
15839 );
15840 }
15841
15842 #[test]
15843 fn supervisor_view_max_restarts_arm_routes_through_accessor() {
15844 // Composition pin: [`Caixa::supervisor_view`]'s per-`:max-restarts`
15845 // [`SupervisorSpec`] construction arm must key off
15846 // [`Caixa::max_restarts`]'s `unwrap_or(5)` fold, not the raw
15847 // `self.max_restarts.unwrap_or(5)` field-fold. Structurally: for
15848 // every `:kind Supervisor` `Caixa` carrying an author-declared
15849 // `Some(n)`, the composed [`SupervisorSpec`]'s `.max_restarts()`
15850 // must byte-equal `n`; and for a `:kind Supervisor` `Caixa`
15851 // carrying `None`, the composed [`SupervisorSpec`]'s
15852 // `.max_restarts()` must byte-equal the OTP-canonical `5`. Peer
15853 // of the sibling
15854 // `supervisor_view_estrategia_arm_routes_through_accessor`
15855 // (ed04d3c) composition pin.
15856 for max_restarts in [1u32, 5, 1000] {
15857 let c = caixa_supervisor_with_max_restarts_and_window(Some(max_restarts), None);
15858 let view = c.supervisor_view().expect(
15859 "supervisor_view must materialize a SupervisorSpec for a \
15860 :kind Supervisor Caixa carrying a Some(:max-restarts)",
15861 );
15862 assert_eq!(
15863 view.max_restarts(),
15864 max_restarts,
15865 "supervisor_view must carry the outer \
15866 Caixa::max_restarts() Some arm onto the composed \
15867 SupervisorSpec.max_restarts field verbatim (got {}, \
15868 expected {max_restarts})",
15869 view.max_restarts(),
15870 );
15871 }
15872 let c = caixa_supervisor_with_max_restarts_and_window(None, None);
15873 let view = c.supervisor_view().expect(
15874 "supervisor_view must materialize a SupervisorSpec for a \
15875 :kind Supervisor Caixa carrying a None :max-restarts",
15876 );
15877 assert_eq!(
15878 view.max_restarts(),
15879 5,
15880 "supervisor_view must project the outer \
15881 Caixa::max_restarts() None arm onto the OTP-canonical \
15882 {{intensity, 5, 60}} default (5) through the flat-spread \
15883 unwrap_or(5) fold (got {})",
15884 view.max_restarts(),
15885 );
15886 assert!(
15887 c.max_restarts().is_none(),
15888 "Caixa::max_restarts() must remain None on the author-\
15889 omitted arm — the supervisor_view fold must not mutate \
15890 the outer flat-spread presence bit",
15891 );
15892 }
15893
15894 #[test]
15895 fn restart_window_returns_restart_window_option_verbatim_across_permutations() {
15896 // Value-shape pin: [`Caixa::restart_window`] returns the
15897 // `:restart-window` typed `Option<String>` verbatim as an
15898 // `Option<&str>`, borrowed from the typed slot's own storage,
15899 // byte-equal across the author-omitted `None` arm and each of
15900 // the representative fixtures in the accept-set — the canonical
15901 // `"60s"` from `{intensity, 5, 60}`, the sibling
15902 // canonical-magnitude forms (`"5m"` / `"1h"` / `"500ms"` / `"30"`
15903 // / `"0s"`) the shared codec's positive-set sweep pin covers,
15904 // plus a past-the-guard sentinel (`"1.5s"` — the fractional-
15905 // seconds drift the sibling [`Self::validate_restart_window`]
15906 // gate refuses; the accessor must ship the raw slot verbatim
15907 // so struct-literal fixtures continue to expose the drift at
15908 // the accessor boundary). Third outer top-level [`Caixa`]
15909 // supervisor-tree flat-spread pin — extends the sub-family onto
15910 // the sibling `Option<&str>` raw-duration-string arm.
15911 for window in [
15912 None,
15913 Some("60s"),
15914 Some("5m"),
15915 Some("1h"),
15916 Some("500ms"),
15917 Some("1.5s"),
15918 Some(""),
15919 ] {
15920 let c = caixa_with_restart_window(window);
15921 assert_eq!(
15922 c.restart_window(),
15923 window,
15924 "Caixa::restart_window must return :restart-window \
15925 verbatim as Option<&str> (got {:?}, expected {window:?})",
15926 c.restart_window(),
15927 );
15928 assert_eq!(
15929 c.restart_window(),
15930 c.restart_window.as_deref(),
15931 "Caixa::restart_window accessor and \
15932 self.restart_window.as_deref() field access must \
15933 byte-equal — a byte-level drift would silently split \
15934 the paired Caixa::declared_supervisor_slots \
15935 presence-probe arm from the \
15936 Caixa::validate_restart_window shared-codec gate and \
15937 the Caixa::supervisor_view soft-swallowing fold",
15938 );
15939 }
15940 }
15941
15942 #[test]
15943 fn restart_window_projects_slice_by_borrow() {
15944 // The by-borrow pin: [`Caixa::restart_window`] returns
15945 // `Option<&str>` by borrow — the returned string slice borrows
15946 // the underlying `Option<String>` storage of the `:restart-window`
15947 // slot and the accessor must not clone on every call. Peer of
15948 // the sibling outer top-level [`Caixa`] `Option<&str>`-return
15949 // by-borrow pins on the universal-axis scalar family
15950 // (`licenca_projects_option_ref_by_borrow` /
15951 // `descricao_projects_option_ref_by_borrow` and siblings) —
15952 // extended onto the M2 supervisor-tree flat-spread
15953 // `Option<&str>` raw-duration-string axis.
15954 for window in [None, Some("60s"), Some("5m"), Some("")] {
15955 let c = caixa_with_restart_window(window);
15956 let first = c.restart_window();
15957 let second = c.restart_window();
15958 assert_eq!(
15959 first, second,
15960 "Caixa::restart_window must be idempotent — two \
15961 successive calls on the same &self must return the \
15962 same Option<&str>",
15963 );
15964 if let (Some(a), Some(b)) = (first, second) {
15965 assert_eq!(
15966 a.as_ptr(),
15967 b.as_ptr(),
15968 "Caixa::restart_window must borrow the underlying \
15969 String storage — two successive Some-arm calls must \
15970 return slices with the same backing pointer (a fresh \
15971 String clone would change the pointer on every call)",
15972 );
15973 }
15974 assert_eq!(
15975 first, window,
15976 "Caixa::restart_window must return :restart-window \
15977 verbatim by borrow — got {first:?}, expected {window:?}",
15978 );
15979 }
15980 }
15981
15982 #[test]
15983 fn declared_supervisor_slots_restart_window_arm_routes_through_accessor() {
15984 // Composition pin: [`Caixa::declared_supervisor_slots`]'s
15985 // `:restart-window` presence-probe arm must key off
15986 // [`Caixa::restart_window`], not the raw
15987 // `self.restart_window.is_some()` field-probe. Structurally:
15988 // every `Caixa { restart_window: Some(_), .. }` must push
15989 // `SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW` onto the declared-slot
15990 // list, and a `Caixa { restart_window: None, .. }` must NOT
15991 // push the label. Peer of the sibling
15992 // `declared_supervisor_slots_max_restarts_arm_routes_through_accessor`
15993 // routing pin.
15994 for window in ["60s", "5m", "1h", "500ms", "1.5s", ""] {
15995 let c = caixa_with_restart_window(Some(window));
15996 let slots = c.declared_supervisor_slots();
15997 assert!(
15998 slots.contains(&crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW),
15999 "declared_supervisor_slots must push \
16000 SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW when \
16001 `:restart-window` is Some({window:?}) — the accessor \
16002 and the enumerator gate must route through the same \
16003 substrate-primitive typed dispatch on the outer \
16004 :restart-window presence bit (got slots={slots:?})",
16005 );
16006 }
16007 let c = caixa_with_restart_window(None);
16008 let slots = c.declared_supervisor_slots();
16009 assert!(
16010 !slots.contains(&crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW),
16011 "declared_supervisor_slots must NOT push \
16012 SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW when `:restart-window` \
16013 is None — the author-omitted arm must route through the \
16014 accessor's None-return unchanged (got slots={slots:?})",
16015 );
16016 }
16017
16018 #[test]
16019 fn validate_restart_window_arm_routes_through_accessor() {
16020 // Composition pin: [`Caixa::validate_restart_window`]'s
16021 // shared-codec fold arm must key off [`Caixa::restart_window`],
16022 // not the raw `self.restart_window.as_deref()` field-projection.
16023 // Structurally: (1) `None` → `Ok(())` (the "omit the slot to
16024 // express no reset" canonical shape); (2) a canonical `Some`
16025 // arm (`"60s"`) → `Ok(())`; (3) a codec-rejected `Some` arm
16026 // (`"1.5s"`) → `Err(RestartWindowMalformed { restart_window,
16027 // .. })` carrying the offending raw string verbatim. The three
16028 // arms jointly pin that the validator's raw-string binding is
16029 // the accessor's return, not a peer projection — any future
16030 // silent detour that had the accessor collapse `Some("")` to
16031 // `None` would silently absorb the empty-after-trim refusal
16032 // case at the accessor boundary.
16033 caixa_with_restart_window(None)
16034 .validate_restart_window()
16035 .expect("None :restart-window must validate through the accessor");
16036 caixa_with_restart_window(Some("60s"))
16037 .validate_restart_window()
16038 .expect("canonical :restart-window \"60s\" must validate through the accessor");
16039 let err = caixa_with_restart_window(Some("1.5s"))
16040 .validate_restart_window()
16041 .expect_err("fractional-seconds :restart-window must fail through the accessor");
16042 assert!(
16043 matches!(
16044 err,
16045 ManifestError::RestartWindowMalformed { ref restart_window, .. }
16046 if restart_window == "1.5s"
16047 ),
16048 "validator must carry the offending raw string verbatim \
16049 from the accessor's borrowed &str (got {err:?})",
16050 );
16051 }
16052
16053 #[test]
16054 fn supervisor_view_restart_window_arm_routes_through_accessor() {
16055 // Composition pin: [`Caixa::supervisor_view`]'s
16056 // per-`:restart-window` [`SupervisorSpec`] construction arm
16057 // must key off [`Caixa::restart_window`]'s soft-swallowing
16058 // `.and_then(|s| duration_codec::parse(s).ok())` fold, not the
16059 // raw `self.restart_window.as_deref().and_then(…)` field-fold.
16060 // Structurally: (1) `None` → `SupervisorSpec.restart_window ==
16061 // None` (the "never reset" sentinel); (2) canonical `Some("60s")`
16062 // → `SupervisorSpec.restart_window == Some(Duration::from_secs(60))`
16063 // (the shared codec's canonical parse); (3) codec-rejected
16064 // `Some("1.5s")` → `SupervisorSpec.restart_window == None`
16065 // (the soft-swallow preserving the view's best-effort shape).
16066 let c = caixa_supervisor_with_max_restarts_and_window(None, None);
16067 let view = c.supervisor_view().expect("Supervisor kind has a view");
16068 assert_eq!(
16069 view.restart_window(),
16070 None,
16071 "supervisor_view must project outer None :restart-window \
16072 onto None on the composed SupervisorSpec (never-reset \
16073 sentinel) through the accessor's None-return unchanged",
16074 );
16075
16076 let c = caixa_supervisor_with_max_restarts_and_window(None, Some("60s"));
16077 let view = c.supervisor_view().expect("Supervisor kind has a view");
16078 assert_eq!(
16079 view.restart_window(),
16080 Some(std::time::Duration::from_secs(60)),
16081 "supervisor_view must fold outer Some(\"60s\") through the \
16082 shared duration_codec into Duration::from_secs(60) on the \
16083 composed SupervisorSpec (accessor's Some(&str) → codec \
16084 parse → Some(Duration))",
16085 );
16086
16087 let c = caixa_supervisor_with_max_restarts_and_window(None, Some("1.5s"));
16088 let view = c.supervisor_view().expect("Supervisor kind has a view");
16089 assert_eq!(
16090 view.restart_window(),
16091 None,
16092 "supervisor_view must soft-swallow the shared-codec parse \
16093 failure to None (the view's best-effort shape the sibling \
16094 manifest-level validate_restart_window surfaces as \
16095 RestartWindowMalformed); the accessor's raw-string return \
16096 is the single input every downstream consumer keys off",
16097 );
16098 }
16099
16100 // ── Caixa::upgrade_from — outer top-level &[UpgradeFromEntry] composite-slice accessor ──
16101
16102 fn caixa_with_upgrade_from(upgrade_from: Vec<crate::upgrade::UpgradeFromEntry>) -> Caixa {
16103 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
16104 c.upgrade_from = upgrade_from;
16105 c
16106 }
16107
16108 #[test]
16109 fn upgrade_from_returns_upgrade_from_slice_verbatim_across_permutations() {
16110 // The canonical per-`Caixa` `:upgrade-from` M2 typed-slot
16111 // outer-composite `&[UpgradeFromEntry]`-return slice-shape
16112 // pin: [`Caixa::upgrade_from`] must return the `:upgrade-from`
16113 // typed `Vec<UpgradeFromEntry>` verbatim as a
16114 // `&[UpgradeFromEntry]` slice-view over the same backing
16115 // buffer the raw `self.upgrade_from.as_slice()` field access
16116 // borrows from, element-equal across every representative
16117 // fixture in the accept-set — `[]` (the "no hot-upgrade path
16118 // declared" arm every `defcaixa` without an `:upgrade-from`
16119 // block carries; `#[serde(default)]` folds an omitted slot
16120 // onto `Vec::new()`), a canonical single-entry `Restart`
16121 // fixture (the shape most Servicos carry — a single prior
16122 // version with the fallback strategy), a canonical multi-
16123 // entry list carrying every typed instruction variant
16124 // (`LoadModule` / `StateChange` / `SoftPurge` / `Purge` /
16125 // `Restart`), and a past-the-guard sentinel — a duplicate-
16126 // `:from` `[(0.1.0, Restart), (0.1.0, Restart)]` entry pair
16127 // ([`crate::upgrade::validate_upgrade_from`] rejects through
16128 // `DuplicateFrom { from: "0.1.0" }` but the accessor must
16129 // ship the raw slot verbatim so struct-literal fixtures
16130 // continue to expose the duplicate at the accessor boundary).
16131 //
16132 // Pins against a future silent detour that returned an owned
16133 // `Vec<UpgradeFromEntry>` (which would type-check but silently
16134 // clone on every accessor call, breaking the zero-cost
16135 // projection every peer sibling slice accessor carries), a
16136 // `[dup, dup] → [dup]` dedup collapse (which would silently
16137 // absorb the `DuplicateFrom` refusal case at the accessor
16138 // boundary and the [`crate::StandardLayout::verify`] cross-
16139 // entry gate would silently accept a struct-literal `Caixa`
16140 // carrying the drift), a reference to an operator-resolved
16141 // overlay (the future per-cluster `:upgrade-overrides` slot
16142 // — its resolution must land at exactly this accessor body,
16143 // not silently divert the raw slot away from a second
16144 // consumer), or an axis-shuffled projection (a future detour
16145 // that reordered entries through the accessor would silently
16146 // split the paired [`crate::StandardLayout::verify`] per-
16147 // `:upgrade-from` shape gate's traversal input from the peer
16148 // [`crate::render::servico_m2_overlay`] emitter's projection
16149 // input, since the operator's hot-upgrade dispatch matches
16150 // per-`:from` and axis reordering would silently split the
16151 // per-entry script-path existence probe's iteration order
16152 // from the M2 overlay emitter's serialized-entry order).
16153 //
16154 // First outer top-level [`Caixa`] `&[Composite]`-return
16155 // slice accessor pin on the substrate primitive for M2 / M3
16156 // typed-slot vec-carry axes — opens the outer-`Caixa`
16157 // `&[Composite]` composite-slice projection pattern the
16158 // sibling `:children` [`crate::supervisor::ChildSpec`] /
16159 // `:membros` [`crate::aplicacao::Membro`] / `:contratos`
16160 // [`crate::aplicacao::WitContract`] future outer-composite-
16161 // slice pins fold on. Peer of the closed outer-`Caixa`
16162 // scalar `Option<&Composite>` composite-reference family the
16163 // sibling `limits` / `behavior` / `politicas` / `placement`
16164 // / `entrada` `..._returns_..._option_ref_verbatim_across_
16165 // permutations` pins closed (b2bd9d7 → e4128e4) — extends
16166 // the "byte-equal, borrow-shared" outer-accessor discipline
16167 // onto the outer-`Caixa` `&[Composite]` vec-carry altitude.
16168 use crate::upgrade::{UpgradeFromEntry, UpgradeInstruction};
16169 let fixtures: Vec<Vec<UpgradeFromEntry>> = vec![
16170 vec![],
16171 vec![UpgradeFromEntry {
16172 from: "0.0.1".into(),
16173 instructions: vec![UpgradeInstruction::Restart],
16174 }],
16175 vec![
16176 UpgradeFromEntry {
16177 from: "0.0.1".into(),
16178 instructions: vec![
16179 UpgradeInstruction::LoadModule {
16180 module: "demo".into(),
16181 },
16182 UpgradeInstruction::SoftPurge {
16183 module: "demo".into(),
16184 },
16185 ],
16186 },
16187 UpgradeFromEntry {
16188 from: "0.0.2".into(),
16189 instructions: vec![
16190 UpgradeInstruction::StateChange {
16191 script: "servicos/upgrade.lisp".into(),
16192 },
16193 UpgradeInstruction::Purge {
16194 module: "demo".into(),
16195 },
16196 UpgradeInstruction::Restart,
16197 ],
16198 },
16199 ],
16200 vec![
16201 UpgradeFromEntry {
16202 from: "0.1.0".into(),
16203 instructions: vec![UpgradeInstruction::Restart],
16204 },
16205 UpgradeFromEntry {
16206 from: "0.1.0".into(),
16207 instructions: vec![UpgradeInstruction::Restart],
16208 },
16209 ],
16210 ];
16211 for upgrade_from in fixtures {
16212 let c = caixa_with_upgrade_from(upgrade_from.clone());
16213 assert_eq!(
16214 c.upgrade_from(),
16215 upgrade_from.as_slice(),
16216 "Caixa::upgrade_from must return :upgrade-from \
16217 verbatim (got {:?}, expected {upgrade_from:?})",
16218 c.upgrade_from(),
16219 );
16220 assert_eq!(
16221 c.upgrade_from(),
16222 c.upgrade_from.as_slice(),
16223 "Caixa::upgrade_from must element-equal the raw \
16224 `self.upgrade_from.as_slice()` field access across \
16225 every value in the Vec<UpgradeFromEntry> accept-set",
16226 );
16227 assert_eq!(
16228 c.upgrade_from().is_empty(),
16229 c.upgrade_from.is_empty(),
16230 "Caixa::upgrade_from().is_empty() must byte-equal \
16231 self.upgrade_from.is_empty() — a presence-bit drift \
16232 would silently split the paired \
16233 Caixa::declared_servico_slots M2 declared-slot \
16234 enumerator's presence probe from the peer \
16235 crate::render::servico_m2_overlay M2 overlay \
16236 emitter's presence gate",
16237 );
16238 }
16239 }
16240
16241 #[test]
16242 fn declared_servico_slots_upgrade_from_arm_routes_through_accessor() {
16243 // Composition pin: [`Caixa::declared_servico_slots`]'s
16244 // `:upgrade-from` presence-probe arm must key off
16245 // [`Caixa::upgrade_from`], not the raw
16246 // `self.upgrade_from.is_empty()` field-probe. Structurally: a
16247 // `Caixa { upgrade_from: vec![UpgradeFromEntry { from: "0.0.1",
16248 // instructions: vec![Restart] }], .. }` must push
16249 // `M2_AUTHOR_KEY_UPGRADE_FROM` onto the declared-slot list
16250 // (the presence bit is non-empty, so the M2 kind-coherence
16251 // gate must surface the slot as "declared"), and a `Caixa {
16252 // upgrade_from: vec![], .. }` must NOT push the label (the
16253 // "author omitted the slot entirely" arm — the empty-slice
16254 // partition the serde-default folds onto). The pair jointly
16255 // pins the accessor + declared-slot enumerator composition:
16256 // any future silent detour that had the accessor collapse
16257 // `[Restart]` to `[]` (a `.filter(|e| !e.instructions.
16258 // is_empty())` projection) would silently absorb the
16259 // "declared but degenerate" arm at the accessor boundary and
16260 // the [`crate::LayoutError::ServicoSlotsOnNonServico`] kind-
16261 // coherence gate would silently accept a struct-literal
16262 // `Caixa` carrying the drift.
16263 //
16264 // Peer of the sibling
16265 // `declared_servico_slots_limits_arm_routes_through_accessor`
16266 // (b2bd9d7) and
16267 // `declared_servico_slots_behavior_arm_routes_through_accessor`
16268 // (35d8b52) composition pins on the sibling `:limits` /
16269 // `:behavior` outer-`Option<&Composite>` arms — same "the
16270 // enumerator gate must route through the substrate-primitive
16271 // typed dispatch" discipline extended onto the third M2
16272 // Servico-runtime slot axis, closing the enumerator's routing
16273 // invariant on every M2 arm.
16274 use crate::upgrade::{UpgradeFromEntry, UpgradeInstruction};
16275 let c = caixa_with_upgrade_from(vec![UpgradeFromEntry {
16276 from: "0.0.1".into(),
16277 instructions: vec![UpgradeInstruction::Restart],
16278 }]);
16279 let slots = c.declared_servico_slots();
16280 assert!(
16281 slots.contains(&crate::render::M2_AUTHOR_KEY_UPGRADE_FROM),
16282 "declared_servico_slots must push \
16283 M2_AUTHOR_KEY_UPGRADE_FROM when `:upgrade-from` is \
16284 non-empty — the accessor and the enumerator gate must \
16285 route through the same substrate-primitive typed \
16286 dispatch on the outer :upgrade-from presence bit (got \
16287 slots={slots:?})",
16288 );
16289 let c = caixa_with_upgrade_from(vec![]);
16290 let slots = c.declared_servico_slots();
16291 assert!(
16292 !slots.contains(&crate::render::M2_AUTHOR_KEY_UPGRADE_FROM),
16293 "declared_servico_slots must NOT push \
16294 M2_AUTHOR_KEY_UPGRADE_FROM when `:upgrade-from` is \
16295 empty — the author-omitted arm must route through the \
16296 accessor's empty-slice return unchanged (got \
16297 slots={slots:?})",
16298 );
16299 }
16300
16301 #[test]
16302 fn servico_m2_overlay_upgrade_from_arm_routes_through_accessor() {
16303 // Composition pin: [`crate::render::servico_m2_overlay`]'s
16304 // per-`:upgrade-from` M2 overlay emit arm must key off
16305 // [`Caixa::upgrade_from`], not the raw
16306 // `!caixa.upgrade_from.is_empty()` presence gate + the
16307 // `serde_yaml::to_value(&caixa.upgrade_from)` projection.
16308 // Structurally: a `Caixa { upgrade_from: vec![UpgradeFromEntry
16309 // { from: "0.0.1", instructions: vec![Restart] }], .. }` must
16310 // surface the `M2_KEY_UPGRADE_FROM` key with a per-entry
16311 // sequence in the overlay (the emitter fans onto the serde
16312 // slice-serialization), and a `Caixa { upgrade_from: vec![],
16313 // .. }` must omit the key entirely (the empty-slice
16314 // partition — the `!.is_empty()` outer gate elides the key
16315 // when the author omitted the slot). The pair jointly pins
16316 // the accessor + M2 overlay emitter composition: any future
16317 // silent detour that had the accessor return a fresh-cloned
16318 // `Vec<UpgradeFromEntry>` copy would silently break the
16319 // reference-identity pin the peer per-entry
16320 // `serde_yaml::to_value(caixa.upgrade_from())` projection
16321 // reads from — the projection would clone once per accessor
16322 // call instead of borrowing the storage buffer verbatim.
16323 //
16324 // Peer of the sibling
16325 // `servico_m2_overlay_limits_arm_routes_through_accessor`
16326 // (b2bd9d7) and
16327 // `servico_m2_overlay_behavior_arm_routes_through_accessor`
16328 // (35d8b52) composition pins on the sibling `:limits` /
16329 // `:behavior` outer-`Option<&Composite>` arms — same "the
16330 // M2 overlay emitter must route through the substrate-
16331 // primitive typed dispatch" discipline extended onto the
16332 // third M2 Servico-runtime slot axis, closing the overlay
16333 // emitter's routing invariant on every M2 arm.
16334 use crate::render::{M2_KEY_UPGRADE_FROM, servico_m2_overlay};
16335 use crate::upgrade::{UpgradeFromEntry, UpgradeInstruction};
16336 let c = caixa_with_upgrade_from(vec![UpgradeFromEntry {
16337 from: "0.0.1".into(),
16338 instructions: vec![UpgradeInstruction::Restart],
16339 }]);
16340 let overlay = servico_m2_overlay(&c).unwrap();
16341 assert!(
16342 overlay.contains_key(M2_KEY_UPGRADE_FROM),
16343 "servico_m2_overlay must surface M2_KEY_UPGRADE_FROM when \
16344 `:upgrade-from` is non-empty — the accessor and the M2 \
16345 overlay emitter must route through the same substrate- \
16346 primitive typed dispatch on the outer :upgrade-from \
16347 slice (got overlay={overlay:?})",
16348 );
16349 let c = caixa_with_upgrade_from(vec![]);
16350 let overlay = servico_m2_overlay(&c).unwrap();
16351 assert!(
16352 !overlay.contains_key(M2_KEY_UPGRADE_FROM),
16353 "servico_m2_overlay must omit M2_KEY_UPGRADE_FROM when \
16354 `:upgrade-from` is empty — the empty-slice partition \
16355 must route through the accessor's empty-slice return \
16356 unchanged (got overlay={overlay:?})",
16357 );
16358 }
16359
16360 #[test]
16361 fn upgrade_from_projects_slice_by_borrow() {
16362 // The by-borrow pin: [`Caixa::upgrade_from`] returns
16363 // `&[UpgradeFromEntry]` by borrow — the returned slice
16364 // borrows the underlying `Vec<UpgradeFromEntry>` storage of
16365 // the `:upgrade-from` slot and the accessor must not clone
16366 // the backing `Vec` on every call. Peer of the sibling
16367 // outer top-level [`Caixa`] `&[T]`-return by-borrow pins
16368 // (`autores_projects_slice_by_borrow` b5d813f,
16369 // `etiquetas_projects_slice_by_borrow` 78c7d3c,
16370 // `bibliotecas_projects_slice_by_borrow` 8a36c23,
16371 // `exe_projects_slice_by_borrow` 65d9527,
16372 // `servicos_projects_slice_by_borrow` 611f78b,
16373 // `deps_projects_slice_by_borrow` ad34b4e,
16374 // `deps_dev_projects_slice_by_borrow` f7fd81e) on the
16375 // sibling outer top-level [`Caixa`] scalar-element `&[T]`
16376 // axes — extended here to the first outer-`Caixa`
16377 // composite-element `&[Composite]` axis: the accessor's
16378 // returned slice must borrow from `&self` (the returned
16379 // reference's lifetime is tied to `&self`), and calling the
16380 // accessor twice on the same [`Caixa`] must yield slices
16381 // that are pointer-equal (the underlying byte-buffer is the
16382 // storage `Vec`'s allocation, not a fresh copy) as well as
16383 // value-equal (idempotent, no side effects on `&self`).
16384 //
16385 // Pins against a future silent detour that returned an owned
16386 // `Vec<UpgradeFromEntry>` (which would type-check but
16387 // silently clone on every call), a `&Vec<UpgradeFromEntry>`
16388 // return (which would leak the backing `Vec`'s
16389 // grow/push/reserve surface no downstream consumer reaches
16390 // for), or a one-arm-only accessor that returned a
16391 // saturating value on some sentinel input.
16392 use crate::upgrade::{UpgradeFromEntry, UpgradeInstruction};
16393 for upgrade_from in [
16394 vec![],
16395 vec![UpgradeFromEntry {
16396 from: "0.0.1".into(),
16397 instructions: vec![UpgradeInstruction::Restart],
16398 }],
16399 vec![
16400 UpgradeFromEntry {
16401 from: "0.0.1".into(),
16402 instructions: vec![UpgradeInstruction::Restart],
16403 },
16404 UpgradeFromEntry {
16405 from: "0.0.2".into(),
16406 instructions: vec![UpgradeInstruction::SoftPurge {
16407 module: "demo".into(),
16408 }],
16409 },
16410 ],
16411 ] {
16412 let c = caixa_with_upgrade_from(upgrade_from.clone());
16413 let first = c.upgrade_from();
16414 let second = c.upgrade_from();
16415 assert_eq!(
16416 first, second,
16417 "Caixa::upgrade_from must be idempotent — two \
16418 successive calls on the same &self must return the \
16419 same &[UpgradeFromEntry]",
16420 );
16421 assert_eq!(
16422 first.as_ptr(),
16423 second.as_ptr(),
16424 "Caixa::upgrade_from must borrow the underlying \
16425 Vec<UpgradeFromEntry> storage — two successive calls \
16426 must return slices with the same backing pointer (a \
16427 fresh Vec<UpgradeFromEntry> clone would change the \
16428 pointer on every call)",
16429 );
16430 assert_eq!(
16431 first,
16432 upgrade_from.as_slice(),
16433 "Caixa::upgrade_from must return :upgrade-from \
16434 verbatim by borrow — got {first:?}, expected \
16435 {upgrade_from:?}",
16436 );
16437 }
16438 }
16439
16440 // ── Caixa::children — outer top-level &[ChildSpec] composite-slice accessor ──
16441
16442 fn caixa_with_children(children: Vec<crate::supervisor::ChildSpec>) -> Caixa {
16443 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
16444 c.children = children;
16445 c
16446 }
16447
16448 #[test]
16449 fn children_returns_children_slice_verbatim_across_permutations() {
16450 // The canonical per-`Caixa` `:children` M2 supervisor-tree-slot
16451 // outer-composite `&[ChildSpec]`-return slice-shape pin:
16452 // [`Caixa::children`] must return the `:children` typed
16453 // `Vec<ChildSpec>` verbatim as a `&[ChildSpec]` slice-view over
16454 // the same backing buffer the raw `self.children.as_slice()`
16455 // field access borrows from, element-equal across every
16456 // representative fixture in the accept-set — `[]` (the "no
16457 // static children declared" arm every non-`Supervisor`-kind
16458 // `defcaixa` carries by `#[serde(default)]` and every
16459 // `SimpleOneForOne` supervisor carries by cross-slot refusal),
16460 // a canonical single-child `Permanent` fixture (the shape
16461 // most `OneForOne` supervisors carry — a single long-running
16462 // worker child), a canonical multi-child list carrying every
16463 // typed restart-policy variant (`Permanent` / `Transient` /
16464 // `Temporary`), and a past-the-guard sentinel — a duplicate
16465 // `:caixa` `[("w", ...), ("w", ...)]` entry pair
16466 // ([`crate::SupervisorSpec::validate`] rejects through
16467 // `DuplicateChildNome { nome: "w" }` but the accessor must
16468 // ship the raw slot verbatim so struct-literal fixtures
16469 // continue to expose the duplicate at the accessor boundary).
16470 //
16471 // Pins against a future silent detour that returned an owned
16472 // `Vec<ChildSpec>` (which would type-check but silently clone
16473 // on every accessor call, breaking the zero-cost projection
16474 // every peer sibling slice accessor carries), a `[dup, dup] →
16475 // [dup]` dedup collapse (which would silently absorb the
16476 // `DuplicateChildNome` refusal case at the accessor boundary
16477 // and the [`crate::StandardLayout::verify`] cross-child gate
16478 // would silently accept a struct-literal `Caixa` carrying the
16479 // drift), a reference to an operator-resolved overlay (the
16480 // future per-cluster `:children-overrides` slot — its
16481 // resolution must land at exactly this accessor body, not
16482 // silently divert the raw slot away from a second consumer),
16483 // or an axis-shuffled projection (a future detour that
16484 // reordered children through the accessor would silently
16485 // split the paired [`crate::StandardLayout::verify`] per-
16486 // supervisor gate's traversal input from the peer
16487 // [`Self::supervisor_view`] fold-in path's clone-order input,
16488 // since the OTP `RestForOne` restart strategy dispatches on
16489 // declared child order and axis reordering would silently
16490 // split the operator's per-cluster restart-fan-out order
16491 // from the caixa.lisp source-order).
16492 //
16493 // Second outer top-level [`Caixa`] `&[Composite]`-return slice
16494 // accessor pin on the substrate primitive for M2 / M3 typed-
16495 // slot vec-carry axes — folds on the outer-`Caixa`
16496 // `&[Composite]` composite-slice sub-family the sibling
16497 // `upgrade_from_returns_upgrade_from_slice_verbatim_across_permutations`
16498 // (2a1f907) pin opened, peer at the outer altitude of the
16499 // closed inner-`SupervisorSpec` `SupervisorSpec::children`
16500 // (bc92bce) accessor on the same OTP-supervisor static-child-
16501 // list axis.
16502 use crate::supervisor::{ChildSpec, RestartPolicy};
16503 let fixtures: Vec<Vec<ChildSpec>> = vec![
16504 vec![],
16505 vec![ChildSpec {
16506 caixa: "worker".into(),
16507 versao: "^0.1".into(),
16508 restart: RestartPolicy::Permanent,
16509 }],
16510 vec![
16511 ChildSpec {
16512 caixa: "worker-a".into(),
16513 versao: "^0.1".into(),
16514 restart: RestartPolicy::Permanent,
16515 },
16516 ChildSpec {
16517 caixa: "worker-b".into(),
16518 versao: "^0.1".into(),
16519 restart: RestartPolicy::Transient,
16520 },
16521 ChildSpec {
16522 caixa: "worker-c".into(),
16523 versao: "^0.1".into(),
16524 restart: RestartPolicy::Temporary,
16525 },
16526 ],
16527 vec![
16528 ChildSpec {
16529 caixa: "w".into(),
16530 versao: "^0.1".into(),
16531 restart: RestartPolicy::Permanent,
16532 },
16533 ChildSpec {
16534 caixa: "w".into(),
16535 versao: "^0.1".into(),
16536 restart: RestartPolicy::Permanent,
16537 },
16538 ],
16539 ];
16540 for children in fixtures {
16541 let c = caixa_with_children(children.clone());
16542 assert_eq!(
16543 c.children(),
16544 children.as_slice(),
16545 "Caixa::children must return :children verbatim \
16546 (got {:?}, expected {children:?})",
16547 c.children(),
16548 );
16549 assert_eq!(
16550 c.children(),
16551 c.children.as_slice(),
16552 "Caixa::children must element-equal the raw \
16553 `self.children.as_slice()` field access across \
16554 every value in the Vec<ChildSpec> accept-set",
16555 );
16556 assert_eq!(
16557 c.children().is_empty(),
16558 c.children.is_empty(),
16559 "Caixa::children().is_empty() must byte-equal \
16560 self.children.is_empty() — a presence-bit drift \
16561 would silently split the paired \
16562 Caixa::declared_supervisor_slots supervisor-tree \
16563 declared-slot enumerator's presence probe from the \
16564 peer Caixa::supervisor_view typed-view composer's \
16565 fold-in path",
16566 );
16567 }
16568 }
16569
16570 #[test]
16571 fn declared_supervisor_slots_children_arm_routes_through_accessor() {
16572 // Composition pin: [`Caixa::declared_supervisor_slots`]'s
16573 // `:children` presence-probe arm must key off
16574 // [`Caixa::children`], not the raw
16575 // `!self.children.is_empty()` field-probe. Structurally: a
16576 // `Caixa { children: vec![ChildSpec { caixa: "w", versao:
16577 // "^0.1", restart: Permanent }], .. }` must push
16578 // `SUPERVISOR_AUTHOR_KEY_CHILDREN` onto the declared-slot list
16579 // (the presence bit is non-empty, so the supervisor-tree
16580 // kind-coherence gate must surface the slot as "declared"),
16581 // and a `Caixa { children: vec![], .. }` must NOT push the
16582 // label (the "author omitted the slot entirely" arm — the
16583 // empty-slice partition the serde-default folds onto). The
16584 // pair jointly pins the accessor + declared-slot enumerator
16585 // composition: any future silent detour that had the accessor
16586 // collapse `[Permanent]` to `[]` (a `.filter(|c| c.nome() !=
16587 // "__reserved__")` projection) would silently absorb the
16588 // "declared but degenerate" arm at the accessor boundary and
16589 // the [`crate::LayoutError::SupervisorSlotsOnNonSupervisor`]
16590 // kind-coherence gate would silently accept a struct-literal
16591 // `Caixa` carrying the drift.
16592 //
16593 // Peer of the sibling
16594 // `declared_servico_slots_upgrade_from_arm_routes_through_accessor`
16595 // (2a1f907) on the M2 `:upgrade-from` composite-slice arm —
16596 // same "the enumerator gate must route through the substrate-
16597 // primitive typed dispatch" discipline extended onto the
16598 // supervisor-tree `:children` composite-slice arm.
16599 use crate::supervisor::{ChildSpec, RestartPolicy};
16600 let c = caixa_with_children(vec![ChildSpec {
16601 caixa: "w".into(),
16602 versao: "^0.1".into(),
16603 restart: RestartPolicy::Permanent,
16604 }]);
16605 let slots = c.declared_supervisor_slots();
16606 assert!(
16607 slots.contains(&crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN),
16608 "declared_supervisor_slots must push \
16609 SUPERVISOR_AUTHOR_KEY_CHILDREN when `:children` is \
16610 non-empty — the accessor and the enumerator gate must \
16611 route through the same substrate-primitive typed \
16612 dispatch on the outer :children presence bit (got \
16613 slots={slots:?})",
16614 );
16615 let c = caixa_with_children(vec![]);
16616 let slots = c.declared_supervisor_slots();
16617 assert!(
16618 !slots.contains(&crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN),
16619 "declared_supervisor_slots must NOT push \
16620 SUPERVISOR_AUTHOR_KEY_CHILDREN when `:children` is \
16621 empty — the author-omitted arm must route through the \
16622 accessor's empty-slice return unchanged (got \
16623 slots={slots:?})",
16624 );
16625 }
16626
16627 #[test]
16628 fn supervisor_view_children_arm_routes_through_accessor() {
16629 // Composition pin: [`Caixa::supervisor_view`]'s per-`:children`
16630 // fold-in arm must key off [`Caixa::children`], not the raw
16631 // `self.children.clone()` field-clone. Structurally: a `Caixa {
16632 // kind: Supervisor, estrategia: Some(OneForOne), children:
16633 // vec![ChildSpec { caixa: "w", .. }], .. }` must fold the
16634 // per-child list through the accessor into the typed
16635 // [`SupervisorSpec`] view's `children` field verbatim — every
16636 // entry the accessor surfaces must land in the view's
16637 // `children` slot in the same order. The pair jointly pins the
16638 // accessor + view-composer composition: any future silent
16639 // detour that had the accessor return a fresh-cloned
16640 // `Vec<ChildSpec>` copy would silently break the reference-
16641 // identity pin the peer `supervisor_view` fold-in path reads
16642 // from — the fold would clone once more per accessor call
16643 // instead of borrowing the storage buffer verbatim once.
16644 //
16645 // Peer of the sibling
16646 // `supervisor_view_kind_gate_routes_through_accessor` (35d8b52-
16647 // family) composition pin on the peer kind-gate arm — same
16648 // "the view composer must route through the substrate-
16649 // primitive typed dispatch" discipline extended onto the
16650 // per-`:children` fold-in arm, closing the supervisor-view
16651 // composer's routing invariant on the composite-slice input.
16652 use crate::supervisor::{ChildSpec, RestartPolicy, RestartStrategy};
16653 let mut c = caixa_with_children(vec![
16654 ChildSpec {
16655 caixa: "worker-a".into(),
16656 versao: "^0.1".into(),
16657 restart: RestartPolicy::Permanent,
16658 },
16659 ChildSpec {
16660 caixa: "worker-b".into(),
16661 versao: "^0.1".into(),
16662 restart: RestartPolicy::Transient,
16663 },
16664 ]);
16665 c.kind = crate::CaixaKind::Supervisor;
16666 c.estrategia = Some(RestartStrategy::OneForOne);
16667 let view = c
16668 .supervisor_view()
16669 .expect("Supervisor kind must produce a supervisor_view");
16670 assert_eq!(
16671 view.children(),
16672 c.children(),
16673 "supervisor_view must fold Caixa::children verbatim into \
16674 SupervisorSpec::children — the accessor and the view \
16675 composer must route through the same substrate-primitive \
16676 typed dispatch on the outer :children slice (got view \
16677 children={:?}, expected {:?})",
16678 view.children(),
16679 c.children(),
16680 );
16681 }
16682
16683 #[test]
16684 fn children_projects_slice_by_borrow() {
16685 // The by-borrow pin: [`Caixa::children`] returns
16686 // `&[ChildSpec]` by borrow — the returned slice borrows the
16687 // underlying `Vec<ChildSpec>` storage of the `:children` slot
16688 // and the accessor must not clone the backing `Vec` on every
16689 // call. Peer of the sibling outer top-level [`Caixa`]
16690 // `&[T]`-return by-borrow pins (`autores_projects_slice_by_borrow`
16691 // b5d813f, `etiquetas_projects_slice_by_borrow` 78c7d3c,
16692 // `bibliotecas_projects_slice_by_borrow` 8a36c23,
16693 // `exe_projects_slice_by_borrow` 65d9527,
16694 // `servicos_projects_slice_by_borrow` 611f78b,
16695 // `deps_projects_slice_by_borrow` ad34b4e,
16696 // `deps_dev_projects_slice_by_borrow` f7fd81e,
16697 // `upgrade_from_projects_slice_by_borrow` 2a1f907) on the
16698 // sibling outer top-level [`Caixa`] scalar-element and
16699 // composite-element `&[T]` axes — folds on the outer-`Caixa`
16700 // composite-element `&[Composite]` axis: the accessor's
16701 // returned slice must borrow from `&self` (the returned
16702 // reference's lifetime is tied to `&self`), and calling the
16703 // accessor twice on the same [`Caixa`] must yield slices
16704 // that are pointer-equal (the underlying byte-buffer is the
16705 // storage `Vec`'s allocation, not a fresh copy) as well as
16706 // value-equal (idempotent, no side effects on `&self`).
16707 //
16708 // Pins against a future silent detour that returned an owned
16709 // `Vec<ChildSpec>` (which would type-check but silently clone
16710 // on every call), a `&Vec<ChildSpec>` return (which would leak
16711 // the backing `Vec`'s grow/push/reserve surface no downstream
16712 // consumer reaches for), or a one-arm-only accessor that
16713 // returned a saturating value on some sentinel input.
16714 use crate::supervisor::{ChildSpec, RestartPolicy};
16715 for children in [
16716 vec![],
16717 vec![ChildSpec {
16718 caixa: "w".into(),
16719 versao: "^0.1".into(),
16720 restart: RestartPolicy::Permanent,
16721 }],
16722 vec![
16723 ChildSpec {
16724 caixa: "worker-a".into(),
16725 versao: "^0.1".into(),
16726 restart: RestartPolicy::Permanent,
16727 },
16728 ChildSpec {
16729 caixa: "worker-b".into(),
16730 versao: "^0.1".into(),
16731 restart: RestartPolicy::Transient,
16732 },
16733 ],
16734 ] {
16735 let c = caixa_with_children(children.clone());
16736 let first = c.children();
16737 let second = c.children();
16738 assert_eq!(
16739 first, second,
16740 "Caixa::children must be idempotent — two successive \
16741 calls on the same &self must return the same \
16742 &[ChildSpec]",
16743 );
16744 assert_eq!(
16745 first.as_ptr(),
16746 second.as_ptr(),
16747 "Caixa::children must borrow the underlying \
16748 Vec<ChildSpec> storage — two successive calls must \
16749 return slices with the same backing pointer (a fresh \
16750 Vec<ChildSpec> clone would change the pointer on \
16751 every call)",
16752 );
16753 assert_eq!(
16754 first,
16755 children.as_slice(),
16756 "Caixa::children must return :children verbatim by \
16757 borrow — got {first:?}, expected {children:?}",
16758 );
16759 }
16760 }
16761
16762 // ── Caixa::membros — outer top-level &[Membro] composite-slice accessor ──
16763
16764 fn caixa_aplicacao_with_membros(membros: Vec<crate::aplicacao::Membro>) -> Caixa {
16765 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
16766 c.kind = CaixaKind::Aplicacao;
16767 c.membros = membros;
16768 c
16769 }
16770
16771 #[test]
16772 fn membros_returns_membros_slice_verbatim_across_permutations() {
16773 // The canonical per-`Caixa` `:membros` M3 mesh-slot outer-
16774 // composite `&[Membro]`-return slice-shape pin:
16775 // [`Caixa::membros`] must return the `:membros` typed
16776 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
16777 // same backing buffer the raw `self.membros.as_slice()` field
16778 // access borrows from, element-equal across every
16779 // representative fixture in the accept-set — `[]` (the "no
16780 // members declared" arm every non-`Aplicacao`-kind `defcaixa`
16781 // carries by `#[serde(default)]` and every partially-authored
16782 // Aplicacao carries before the
16783 // [`crate::AplicacaoError::MembrosEmpty`] gate fires), a
16784 // canonical single-member fixture (the shape a minimal
16785 // Aplicacao carries — one Servico wrapping one contained
16786 // computation), a canonical multi-member list carrying three
16787 // distinct entries (the canonical checkout-shape Aplicacao —
16788 // cart / pricing / auth — every canonical example carries), and
16789 // a past-the-guard sentinel — a duplicate `:caixa`
16790 // `[("cart", ...), ("cart", ...)]` entry pair
16791 // ([`crate::AplicacaoSpec::validate`] rejects through
16792 // `DuplicateMembro { nome: "cart" }` but the accessor must ship
16793 // the raw slot verbatim so struct-literal fixtures continue to
16794 // expose the duplicate at the accessor boundary).
16795 //
16796 // Pins against a future silent detour that returned an owned
16797 // `Vec<Membro>` (which would type-check but silently clone on
16798 // every accessor call, breaking the zero-cost projection every
16799 // peer sibling slice accessor carries), a `[dup, dup] → [dup]`
16800 // dedup collapse (which would silently absorb the
16801 // `DuplicateMembro` refusal case at the accessor boundary and
16802 // the [`crate::StandardLayout::verify`] cross-member gate would
16803 // silently accept a struct-literal `Caixa` carrying the drift),
16804 // a reference to an operator-resolved overlay (the future per-
16805 // cluster `:membros-overrides` slot — its resolution must land
16806 // at exactly this accessor body, not silently divert the raw
16807 // slot away from a second consumer), or an axis-shuffled
16808 // projection (a future detour that reordered members through
16809 // the accessor would silently split the paired
16810 // [`crate::StandardLayout::verify`] per-Aplicacao gate's
16811 // traversal input from the peer [`Self::aplicacao_view`] fold-
16812 // in path's clone-order input, since the canonical `:contratos`
16813 // `:de`/`:para` and `:entrada :para` cross-slot refusal probes
16814 // read the member set through the same slice).
16815 //
16816 // Third outer top-level [`Caixa`] `&[Composite]`-return slice
16817 // accessor pin on the substrate primitive for M2 / M3 typed-
16818 // slot vec-carry axes — opens the outer-`Caixa` M3 mesh-slot
16819 // arm of the `&[Composite]` composite-slice sub-family the
16820 // sibling M2 `upgrade_from_returns_upgrade_from_slice_verbatim_across_permutations`
16821 // (2a1f907) and
16822 // `children_returns_children_slice_verbatim_across_permutations`
16823 // (c17b51e) pins opened, peer at the outer altitude of the
16824 // closed inner-[`crate::AplicacaoSpec::membros`] (6c77e36)
16825 // accessor on the same MESH-COMPOSITION per-Aplicacao member-
16826 // list axis.
16827 use crate::aplicacao::Membro;
16828 let fixtures: Vec<Vec<Membro>> = vec![
16829 vec![],
16830 vec![Membro {
16831 caixa: "cart".into(),
16832 versao: "^0.1".into(),
16833 }],
16834 vec![
16835 Membro {
16836 caixa: "cart".into(),
16837 versao: "^0.1".into(),
16838 },
16839 Membro {
16840 caixa: "pricing".into(),
16841 versao: "^0.2".into(),
16842 },
16843 Membro {
16844 caixa: "auth".into(),
16845 versao: "^1.0".into(),
16846 },
16847 ],
16848 vec![
16849 Membro {
16850 caixa: "cart".into(),
16851 versao: "^0.1".into(),
16852 },
16853 Membro {
16854 caixa: "cart".into(),
16855 versao: "^0.1".into(),
16856 },
16857 ],
16858 ];
16859 for membros in fixtures {
16860 let c = caixa_aplicacao_with_membros(membros.clone());
16861 assert_eq!(
16862 c.membros(),
16863 membros.as_slice(),
16864 "Caixa::membros must return :membros verbatim \
16865 (got {:?}, expected {membros:?})",
16866 c.membros(),
16867 );
16868 assert_eq!(
16869 c.membros(),
16870 c.membros.as_slice(),
16871 "Caixa::membros must element-equal the raw \
16872 `self.membros.as_slice()` field access across every \
16873 value in the Vec<Membro> accept-set",
16874 );
16875 assert_eq!(
16876 c.membros().is_empty(),
16877 c.membros.is_empty(),
16878 "Caixa::membros().is_empty() must byte-equal \
16879 self.membros.is_empty() — a presence-bit drift would \
16880 silently split the paired Caixa::declared_mesh_slots \
16881 mesh declared-slot enumerator's presence probe from \
16882 the peer Caixa::aplicacao_view typed-view composer's \
16883 fold-in path",
16884 );
16885 }
16886 }
16887
16888 #[test]
16889 fn declared_mesh_slots_membros_arm_routes_through_accessor() {
16890 // Composition pin: [`Caixa::declared_mesh_slots`]'s `:membros`
16891 // presence-probe arm must key off [`Caixa::membros`], not the
16892 // raw `!self.membros.is_empty()` field-probe. Structurally: a
16893 // `Caixa { membros: vec![Membro { caixa: "cart", versao:
16894 // "^0.1" }], .. }` must push `M3_AUTHOR_KEY_MEMBROS` onto the
16895 // declared-slot list (the presence bit is non-empty, so the
16896 // mesh kind-coherence gate must surface the slot as
16897 // "declared"), and a `Caixa { membros: vec![], .. }` must NOT
16898 // push the label (the "author omitted the slot entirely" arm
16899 // — the empty-slice partition the serde-default folds onto).
16900 // The pair jointly pins the accessor + declared-slot
16901 // enumerator composition: any future silent detour that had
16902 // the accessor collapse `[Membro { .. }]` to `[]` (a
16903 // `.filter(|m| m.nome() != "__reserved__")` projection) would
16904 // silently absorb the "declared but degenerate" arm at the
16905 // accessor boundary and the
16906 // [`crate::LayoutError::MeshSlotsOnNonAplicacao`] kind-
16907 // coherence gate would silently accept a struct-literal
16908 // `Caixa` carrying the drift.
16909 //
16910 // Peer of the sibling
16911 // `declared_servico_slots_upgrade_from_arm_routes_through_accessor`
16912 // (2a1f907) and
16913 // `declared_supervisor_slots_children_arm_routes_through_accessor`
16914 // (c17b51e) composition pins on the M2 `:upgrade-from` /
16915 // `:children` composite-slice arms — same "the enumerator gate
16916 // must route through the substrate-primitive typed dispatch"
16917 // discipline extended onto the M3 `:membros` composite-slice
16918 // arm, opening the M3 arm of the declared-slot enumerator's
16919 // routing invariant.
16920 use crate::aplicacao::Membro;
16921 let c = caixa_aplicacao_with_membros(vec![Membro {
16922 caixa: "cart".into(),
16923 versao: "^0.1".into(),
16924 }]);
16925 let slots = c.declared_mesh_slots();
16926 assert!(
16927 slots.contains(&crate::render::M3_AUTHOR_KEY_MEMBROS),
16928 "declared_mesh_slots must push M3_AUTHOR_KEY_MEMBROS when \
16929 `:membros` is non-empty — the accessor and the enumerator \
16930 gate must route through the same substrate-primitive \
16931 typed dispatch on the outer :membros presence bit (got \
16932 slots={slots:?})",
16933 );
16934 let c = caixa_aplicacao_with_membros(vec![]);
16935 let slots = c.declared_mesh_slots();
16936 assert!(
16937 !slots.contains(&crate::render::M3_AUTHOR_KEY_MEMBROS),
16938 "declared_mesh_slots must NOT push M3_AUTHOR_KEY_MEMBROS \
16939 when `:membros` is empty — the author-omitted arm must \
16940 route through the accessor's empty-slice return unchanged \
16941 (got slots={slots:?})",
16942 );
16943 }
16944
16945 #[test]
16946 fn aplicacao_view_membros_arm_routes_through_accessor() {
16947 // Composition pin: [`Caixa::aplicacao_view`]'s per-`:membros`
16948 // fold-in arm must key off [`Caixa::membros`], not the raw
16949 // `self.membros.clone()` field-clone. Structurally: a `Caixa {
16950 // kind: Aplicacao, membros: vec![Membro { caixa: "cart", .. },
16951 // Membro { caixa: "pricing", .. }], .. }` must fold the per-
16952 // member list through the accessor into the typed
16953 // [`crate::AplicacaoSpec`] view's `membros` slot verbatim —
16954 // every entry the accessor surfaces must land in the view's
16955 // `membros` slot in the same order. The pair jointly pins the
16956 // accessor + view-composer composition: any future silent
16957 // detour that had the accessor return a fresh-cloned
16958 // `Vec<Membro>` copy would silently break the reference-
16959 // identity pin the peer `aplicacao_view` fold-in path reads
16960 // from — the fold would clone once more per accessor call
16961 // instead of borrowing the storage buffer verbatim once.
16962 //
16963 // Peer of the sibling
16964 // `aplicacao_view_politicas_arm_folds_through_accessor`
16965 // (5d23d29) /
16966 // `aplicacao_view_placement_arm_folds_through_accessor`
16967 // (4fb8074) /
16968 // `aplicacao_view_entrada_arm_folds_through_accessor` (e4128e4)
16969 // composition pins on the M3 `:politicas` / `:placement` /
16970 // `:entrada` outer-`Option<&Composite>` arms — extended here to
16971 // the M3 `:membros` outer-`&[Composite]` composite-slice arm,
16972 // closing the aplicacao-view composer's routing invariant on
16973 // the composite-slice input.
16974 use crate::aplicacao::Membro;
16975 let c = caixa_aplicacao_with_membros(vec![
16976 Membro {
16977 caixa: "cart".into(),
16978 versao: "^0.1".into(),
16979 },
16980 Membro {
16981 caixa: "pricing".into(),
16982 versao: "^0.2".into(),
16983 },
16984 ]);
16985 let view = c
16986 .aplicacao_view()
16987 .expect("Aplicacao kind must produce an aplicacao_view");
16988 assert_eq!(
16989 view.membros(),
16990 c.membros(),
16991 "aplicacao_view must fold Caixa::membros verbatim into \
16992 AplicacaoSpec::membros — the accessor and the view \
16993 composer must route through the same substrate-primitive \
16994 typed dispatch on the outer :membros slice (got view \
16995 membros={:?}, expected {:?})",
16996 view.membros(),
16997 c.membros(),
16998 );
16999 }
17000
17001 #[test]
17002 fn membros_projects_slice_by_borrow() {
17003 // The by-borrow pin: [`Caixa::membros`] returns `&[Membro]` by
17004 // borrow — the returned slice borrows the underlying
17005 // `Vec<Membro>` storage of the `:membros` slot and the
17006 // accessor must not clone the backing `Vec` on every call.
17007 // Peer of the sibling outer top-level [`Caixa`] `&[T]`-return
17008 // by-borrow pins (`autores_projects_slice_by_borrow` b5d813f,
17009 // `etiquetas_projects_slice_by_borrow` 78c7d3c,
17010 // `bibliotecas_projects_slice_by_borrow` 8a36c23,
17011 // `exe_projects_slice_by_borrow` 65d9527,
17012 // `servicos_projects_slice_by_borrow` 611f78b,
17013 // `deps_projects_slice_by_borrow` ad34b4e,
17014 // `deps_dev_projects_slice_by_borrow` f7fd81e,
17015 // `upgrade_from_projects_slice_by_borrow` 2a1f907,
17016 // `children_projects_slice_by_borrow` c17b51e) on the sibling
17017 // outer top-level [`Caixa`] scalar-element and composite-
17018 // element `&[T]` axes — folds on the outer-`Caixa` M3 mesh-
17019 // slot composite-element `&[Composite]` axis: the accessor's
17020 // returned slice must borrow from `&self` (the returned
17021 // reference's lifetime is tied to `&self`), and calling the
17022 // accessor twice on the same [`Caixa`] must yield slices that
17023 // are pointer-equal (the underlying byte-buffer is the storage
17024 // `Vec`'s allocation, not a fresh copy) as well as value-equal
17025 // (idempotent, no side effects on `&self`).
17026 //
17027 // Pins against a future silent detour that returned an owned
17028 // `Vec<Membro>` (which would type-check but silently clone on
17029 // every call), a `&Vec<Membro>` return (which would leak the
17030 // backing `Vec`'s grow/push/reserve surface no downstream
17031 // consumer reaches for), or a one-arm-only accessor that
17032 // returned a saturating value on some sentinel input.
17033 use crate::aplicacao::Membro;
17034 for membros in [
17035 vec![],
17036 vec![Membro {
17037 caixa: "cart".into(),
17038 versao: "^0.1".into(),
17039 }],
17040 vec![
17041 Membro {
17042 caixa: "cart".into(),
17043 versao: "^0.1".into(),
17044 },
17045 Membro {
17046 caixa: "pricing".into(),
17047 versao: "^0.2".into(),
17048 },
17049 ],
17050 ] {
17051 let c = caixa_aplicacao_with_membros(membros.clone());
17052 let first = c.membros();
17053 let second = c.membros();
17054 assert_eq!(
17055 first, second,
17056 "Caixa::membros must be idempotent — two successive \
17057 calls on the same &self must return the same &[Membro]",
17058 );
17059 assert_eq!(
17060 first.as_ptr(),
17061 second.as_ptr(),
17062 "Caixa::membros must borrow the underlying Vec<Membro> \
17063 storage — two successive calls must return slices with \
17064 the same backing pointer (a fresh Vec<Membro> clone \
17065 would change the pointer on every call)",
17066 );
17067 assert_eq!(
17068 first,
17069 membros.as_slice(),
17070 "Caixa::membros must return :membros verbatim by borrow \
17071 — got {first:?}, expected {membros:?}",
17072 );
17073 }
17074 }
17075
17076 // ── Caixa::contratos — outer top-level &[WitContract] composite-slice accessor ──
17077
17078 fn caixa_aplicacao_with_contratos(contratos: Vec<crate::aplicacao::WitContract>) -> Caixa {
17079 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
17080 c.kind = CaixaKind::Aplicacao;
17081 c.contratos = contratos;
17082 c
17083 }
17084
17085 fn contrato_http_for_test(
17086 de: &str,
17087 para: &str,
17088 endpoint: &str,
17089 ) -> crate::aplicacao::WitContract {
17090 crate::aplicacao::WitContract {
17091 de: de.into(),
17092 para: para.into(),
17093 wit: "wasi:http/proxy".into(),
17094 endpoint: Some(endpoint.into()),
17095 subject: None,
17096 slot: None,
17097 }
17098 }
17099
17100 #[test]
17101 fn contratos_returns_contratos_slice_verbatim_across_permutations() {
17102 // The canonical per-`Caixa` `:contratos` M3 mesh-slot outer-
17103 // composite `&[WitContract]`-return slice-shape pin:
17104 // [`Caixa::contratos`] must return the `:contratos` typed
17105 // `Vec<WitContract>` verbatim as a `&[WitContract]` slice-view
17106 // over the same backing buffer the raw
17107 // `self.contratos.as_slice()` field access borrows from,
17108 // element-equal across every representative fixture in the
17109 // accept-set — `[]` (the "no contracts declared" arm every
17110 // non-`Aplicacao`-kind `defcaixa` carries by
17111 // `#[serde(default)]` and every leaf-Aplicacao with a single
17112 // member carries), a canonical single-edge fixture (the
17113 // minimal directed-graph shape: one HTTP-shape `(cart → catalog)`
17114 // edge), and a canonical multi-edge fixture with three distinct
17115 // edges (the checkout-shape Aplicacao's HTTP-fan pattern:
17116 // `(cart → catalog)`, `(cart → pricing)`, `(cart → auth)`).
17117 //
17118 // Pins against a future silent detour that returned an owned
17119 // `Vec<WitContract>` (which would type-check but silently clone
17120 // on every accessor call, breaking the zero-cost projection
17121 // every peer sibling slice accessor carries), an axis-shuffled
17122 // projection (a future detour that reordered edges through the
17123 // accessor would silently split the paired
17124 // [`crate::StandardLayout::verify`] per-Aplicacao gate's
17125 // traversal input from the peer [`Self::aplicacao_view`] fold-
17126 // in path's clone-order input, since every canonical
17127 // `caixa-mesh` renderer's per-`(:de, :para)` adjacency-list
17128 // seed dispatch reads the edge set through the same slice),
17129 // or a reference to an operator-resolved overlay (the future
17130 // per-cluster `:contratos-overrides` slot — its resolution
17131 // must land at exactly this accessor body, not silently divert
17132 // the raw slot away from a second consumer).
17133 //
17134 // Fourth outer top-level [`Caixa`] `&[Composite]`-return slice
17135 // accessor pin on the substrate primitive for M2 / M3 typed-
17136 // slot vec-carry axes — closes the outer-`Caixa`
17137 // `&[Composite]` composite-slice sub-family the sibling M2
17138 // `upgrade_from_returns_upgrade_from_slice_verbatim_across_permutations`
17139 // (2a1f907) and
17140 // `children_returns_children_slice_verbatim_across_permutations`
17141 // (c17b51e) pins opened and the M3
17142 // `membros_returns_membros_slice_verbatim_across_permutations`
17143 // (0f26987) pin folded on, closing the outer-`Caixa` M3 mesh-
17144 // slot arm of the composite-slice sub-family. Peer at the outer
17145 // altitude of the closed inner-
17146 // [`crate::AplicacaoSpec::contratos`] (0dcc926) accessor on the
17147 // same MESH-COMPOSITION per-Aplicacao contract-list axis.
17148 let fixtures: Vec<Vec<crate::aplicacao::WitContract>> = vec![
17149 vec![],
17150 vec![contrato_http_for_test("cart", "catalog", "/items")],
17151 vec![
17152 contrato_http_for_test("cart", "catalog", "/items"),
17153 contrato_http_for_test("cart", "pricing", "/price"),
17154 contrato_http_for_test("cart", "auth", "/whoami"),
17155 ],
17156 ];
17157 for contratos in fixtures {
17158 let c = caixa_aplicacao_with_contratos(contratos.clone());
17159 assert_eq!(
17160 c.contratos(),
17161 contratos.as_slice(),
17162 "Caixa::contratos must return :contratos verbatim \
17163 (got {:?}, expected {contratos:?})",
17164 c.contratos(),
17165 );
17166 assert_eq!(
17167 c.contratos(),
17168 c.contratos.as_slice(),
17169 "Caixa::contratos must element-equal the raw \
17170 `self.contratos.as_slice()` field access across every \
17171 value in the Vec<WitContract> accept-set",
17172 );
17173 assert_eq!(
17174 c.contratos().is_empty(),
17175 c.contratos.is_empty(),
17176 "Caixa::contratos().is_empty() must byte-equal \
17177 self.contratos.is_empty() — a presence-bit drift would \
17178 silently split the paired Caixa::declared_mesh_slots \
17179 mesh declared-slot enumerator's presence probe from \
17180 the peer Caixa::aplicacao_view typed-view composer's \
17181 fold-in path",
17182 );
17183 }
17184 }
17185
17186 #[test]
17187 fn declared_mesh_slots_contratos_arm_routes_through_accessor() {
17188 // Composition pin: [`Caixa::declared_mesh_slots`]'s `:contratos`
17189 // presence-probe arm must key off [`Caixa::contratos`], not the
17190 // raw `!self.contratos.is_empty()` field-probe. Structurally: a
17191 // `Caixa { contratos: vec![WitContract { .. }], .. }` must push
17192 // `M3_AUTHOR_KEY_CONTRATOS` onto the declared-slot list (the
17193 // presence bit is non-empty, so the mesh kind-coherence gate
17194 // must surface the slot as "declared"), and a `Caixa {
17195 // contratos: vec![], .. }` must NOT push the label (the "author
17196 // omitted the slot entirely" arm — the empty-slice partition
17197 // the serde-default folds onto). The pair jointly pins the
17198 // accessor + declared-slot enumerator composition: any future
17199 // silent detour that had the accessor collapse
17200 // `[WitContract { .. }]` to `[]` (a `.filter(|c| c.de() !=
17201 // "__reserved__")` projection) would silently absorb the
17202 // "declared but degenerate" arm at the accessor boundary and
17203 // the [`crate::LayoutError::MeshSlotsOnNonAplicacao`] kind-
17204 // coherence gate would silently accept a struct-literal
17205 // `Caixa` carrying the drift.
17206 //
17207 // Peer of the sibling
17208 // `declared_servico_slots_upgrade_from_arm_routes_through_accessor`
17209 // (2a1f907),
17210 // `declared_supervisor_slots_children_arm_routes_through_accessor`
17211 // (c17b51e), and
17212 // `declared_mesh_slots_membros_arm_routes_through_accessor`
17213 // (0f26987) composition pins on the M2 `:upgrade-from` /
17214 // `:children` / M3 `:membros` composite-slice arms — same "the
17215 // enumerator gate must route through the substrate-primitive
17216 // typed dispatch" discipline extended onto the M3 `:contratos`
17217 // composite-slice arm, closing the M3 mesh-slot arm of the
17218 // declared-slot enumerator's routing invariant on the
17219 // composite-slice inputs.
17220 let c = caixa_aplicacao_with_contratos(vec![contrato_http_for_test(
17221 "cart", "catalog", "/items",
17222 )]);
17223 let slots = c.declared_mesh_slots();
17224 assert!(
17225 slots.contains(&crate::render::M3_AUTHOR_KEY_CONTRATOS),
17226 "declared_mesh_slots must push M3_AUTHOR_KEY_CONTRATOS when \
17227 `:contratos` is non-empty — the accessor and the enumerator \
17228 gate must route through the same substrate-primitive \
17229 typed dispatch on the outer :contratos presence bit (got \
17230 slots={slots:?})",
17231 );
17232 let c = caixa_aplicacao_with_contratos(vec![]);
17233 let slots = c.declared_mesh_slots();
17234 assert!(
17235 !slots.contains(&crate::render::M3_AUTHOR_KEY_CONTRATOS),
17236 "declared_mesh_slots must NOT push M3_AUTHOR_KEY_CONTRATOS \
17237 when `:contratos` is empty — the author-omitted arm must \
17238 route through the accessor's empty-slice return unchanged \
17239 (got slots={slots:?})",
17240 );
17241 }
17242
17243 #[test]
17244 fn aplicacao_view_contratos_arm_routes_through_accessor() {
17245 // Composition pin: [`Caixa::aplicacao_view`]'s per-`:contratos`
17246 // fold-in arm must key off [`Caixa::contratos`], not the raw
17247 // `self.contratos.clone()` field-clone. Structurally: a `Caixa
17248 // { kind: Aplicacao, contratos: vec![WitContract { de: "cart",
17249 // .. }, WitContract { de: "pricing", .. }], .. }` must fold the
17250 // per-edge list through the accessor into the typed
17251 // [`crate::AplicacaoSpec`] view's `contratos` slot verbatim —
17252 // every entry the accessor surfaces must land in the view's
17253 // `contratos` slot in the same order. The pair jointly pins
17254 // the accessor + view-composer composition: a future silent
17255 // detour that had the accessor shuffle or drop an edge would
17256 // silently split the paired declared-slot enumerator's
17257 // presence bit from the typed-view composer's edge-list, a
17258 // two-consumer split at the enumerator and the view composer
17259 // far from the source `caixa.lisp`.
17260 //
17261 // Peer of the sibling
17262 // `aplicacao_view_membros_arm_routes_through_accessor`
17263 // (0f26987) composition pin on the M3 `:membros` outer-
17264 // `&[Composite]` composite-slice arm, closing the aplicacao-
17265 // view composer's routing invariant on the composite-slice
17266 // inputs at the outer altitude.
17267 let c = caixa_aplicacao_with_contratos(vec![
17268 contrato_http_for_test("cart", "catalog", "/items"),
17269 contrato_http_for_test("cart", "pricing", "/price"),
17270 ]);
17271 let view = c
17272 .aplicacao_view()
17273 .expect("Aplicacao kind must produce an aplicacao_view");
17274 assert_eq!(
17275 view.contratos(),
17276 c.contratos(),
17277 "aplicacao_view must fold Caixa::contratos verbatim into \
17278 AplicacaoSpec::contratos — the accessor and the view \
17279 composer must route through the same substrate-primitive \
17280 typed dispatch on the outer :contratos slice (got view \
17281 contratos={:?}, expected {:?})",
17282 view.contratos(),
17283 c.contratos(),
17284 );
17285 }
17286
17287 #[test]
17288 fn contratos_projects_slice_by_borrow() {
17289 // The by-borrow pin: [`Caixa::contratos`] returns `&[WitContract]`
17290 // by borrow — the returned slice borrows the underlying
17291 // `Vec<WitContract>` storage of the `:contratos` slot and the
17292 // accessor must not clone the backing `Vec` on every call.
17293 // Peer of the sibling outer top-level [`Caixa`] `&[T]`-return
17294 // by-borrow pins (`autores_projects_slice_by_borrow` b5d813f,
17295 // `etiquetas_projects_slice_by_borrow` 78c7d3c,
17296 // `bibliotecas_projects_slice_by_borrow` 8a36c23,
17297 // `exe_projects_slice_by_borrow` 65d9527,
17298 // `servicos_projects_slice_by_borrow` 611f78b,
17299 // `deps_projects_slice_by_borrow` ad34b4e,
17300 // `deps_dev_projects_slice_by_borrow` f7fd81e,
17301 // `upgrade_from_projects_slice_by_borrow` 2a1f907,
17302 // `children_projects_slice_by_borrow` c17b51e,
17303 // `membros_projects_slice_by_borrow` 0f26987) on the sibling
17304 // outer top-level [`Caixa`] scalar-element and composite-
17305 // element `&[T]` axes — closes the outer-`Caixa` M3 mesh-slot
17306 // composite-element `&[Composite]` axis on the by-borrow pin:
17307 // the accessor's returned slice must borrow from `&self` (the
17308 // returned reference's lifetime is tied to `&self`), and
17309 // calling the accessor twice on the same [`Caixa`] must yield
17310 // slices that are pointer-equal (the underlying byte-buffer is
17311 // the storage `Vec`'s allocation, not a fresh copy) as well as
17312 // value-equal (idempotent, no side effects on `&self`).
17313 //
17314 // Pins against a future silent detour that returned an owned
17315 // `Vec<WitContract>` (which would type-check but silently clone
17316 // on every call), a `&Vec<WitContract>` return (which would
17317 // leak the backing `Vec`'s grow/push/reserve surface no
17318 // downstream consumer reaches for), or a one-arm-only accessor
17319 // that returned a saturating value on some sentinel input.
17320 for contratos in [
17321 vec![],
17322 vec![contrato_http_for_test("cart", "catalog", "/items")],
17323 vec![
17324 contrato_http_for_test("cart", "catalog", "/items"),
17325 contrato_http_for_test("cart", "pricing", "/price"),
17326 ],
17327 ] {
17328 let c = caixa_aplicacao_with_contratos(contratos.clone());
17329 let first = c.contratos();
17330 let second = c.contratos();
17331 assert_eq!(
17332 first, second,
17333 "Caixa::contratos must be idempotent — two successive \
17334 calls on the same &self must return the same \
17335 &[WitContract]",
17336 );
17337 assert_eq!(
17338 first.as_ptr(),
17339 second.as_ptr(),
17340 "Caixa::contratos must borrow the underlying \
17341 Vec<WitContract> storage — two successive calls must \
17342 return slices with the same backing pointer (a fresh \
17343 Vec<WitContract> clone would change the pointer on \
17344 every call)",
17345 );
17346 assert_eq!(
17347 first,
17348 contratos.as_slice(),
17349 "Caixa::contratos must return :contratos verbatim by \
17350 borrow — got {first:?}, expected {contratos:?}",
17351 );
17352 }
17353 }
17354
17355 // ── drift-detection: Caixa top-level multi-word serde-derive-to-const identity ──
17356
17357 #[test]
17358 fn caixa_multi_word_serde_keys_match_lifted_top_level_key_consts() {
17359 // Load-bearing invariant: every multi-word top-level [`Caixa`]
17360 // serde-derived JSON key routes through a lifted `&'static str`
17361 // const. The Rust field names are `snake_case`
17362 // (`deps_dev` / `upgrade_from` / `max_restarts` /
17363 // `restart_window`); [`Caixa`]'s `#[serde(rename_all =
17364 // "camelCase")]` derive attribute maps each to the camelCase
17365 // byte-string the [`Caixa::to_lisp`] round-trip's
17366 // `serde_json::to_value(self)` step lands under before
17367 // `tatara_lisp::domain::json_to_sexp` re-projects the JSON keys
17368 // to the kebab-case `:deps-dev` / `:upgrade-from` /
17369 // `:max-restarts` / `:restart-window` author surface. Serialize
17370 // a fully-populated [`Caixa`] and pin that each canonical
17371 // byte-sequence appears verbatim in the JSON — a future
17372 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
17373 // verbatim-field-name flip at the derive attribute (any of
17374 // which would silently break every [`Caixa::to_lisp`]
17375 // round-trip and the future M4 operator-side manifest ingest's
17376 // `Value::get(<key>)` navigation) surfaces here as a build-time
17377 // test failure at `manifest.rs`, not as an apply-time
17378 // `.get(<stale-canonical-const>)` returning `None` far from the
17379 // derive-attr drift's commit. Same discipline the sibling
17380 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
17381 // (40cc4e5), `membro_serde_keys_match_lifted_membro_key_consts`
17382 // (ce80ca0), and `upgrade_from_entry_serde_keys_match_lifted_
17383 // m2_upgrade_from_key_consts` (36ffe65) pins established on the
17384 // sibling M2 supervision-tree, M3 [`Membro`] per-entry, and M2
17385 // [`UpgradeFromEntry`] per-entry axes — extended here to the
17386 // enclosing M0 [`Caixa`] top-level axis so the last of the four
17387 // multi-word top-level [`Caixa`] serde-derived JSON keys
17388 // (`depsDev`) joins the substrate's "one canonical byte-string
17389 // per typed serialized-key axis" discipline.
17390 use crate::supervisor::{ChildSpec, RestartPolicy, RestartStrategy};
17391 use crate::upgrade::{UpgradeFromEntry, UpgradeInstruction};
17392 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
17393 c.deps_dev = vec![Dep::simple("tatara-check", "^0.1")];
17394 c.upgrade_from = vec![UpgradeFromEntry {
17395 from: "0.0.1".into(),
17396 instructions: vec![UpgradeInstruction::Restart],
17397 }];
17398 c.estrategia = Some(RestartStrategy::OneForOne);
17399 c.max_restarts = Some(3);
17400 c.restart_window = Some("60s".into());
17401 c.children = vec![ChildSpec {
17402 caixa: "child".into(),
17403 versao: "^0.1".into(),
17404 restart: RestartPolicy::Permanent,
17405 }];
17406 let json = serde_json::to_string(&c).unwrap();
17407 for key in [
17408 crate::render::CAIXA_KEY_DEPS_DEV,
17409 crate::render::M2_KEY_UPGRADE_FROM,
17410 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
17411 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
17412 ] {
17413 let quoted = format!("\"{key}\"");
17414 assert!(
17415 json.contains("ed),
17416 "serialized Caixa must carry the lifted top-level \
17417 multi-word byte-sequence {quoted} verbatim in the JSON \
17418 emission (got: {json})",
17419 );
17420 }
17421 }
17422
17423 #[test]
17424 fn caixa_top_level_multi_word_key_consts_are_pairwise_distinct() {
17425 // Cross-axis drift-detection pin: a future collapse of the four
17426 // canonical [`Caixa`] top-level multi-word byte-strings onto the
17427 // same value (e.g. an accidental copy-paste flip of
17428 // [`crate::render::CAIXA_KEY_DEPS_DEV`] to also read
17429 // `"upgradeFrom"`) would silently reroute every downstream
17430 // `Value::get(<key>)` probe on one axis onto the sibling axis's
17431 // top-level entry and pass every propagation-probe test that
17432 // expected only the stale axis's value. Peer of the sibling
17433 // four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
17434 // (40cc4e5) and the two-way pin on `MEMBRO_KEY_*` (ce80ca0).
17435 let all = [
17436 crate::render::CAIXA_KEY_DEPS_DEV,
17437 crate::render::M2_KEY_UPGRADE_FROM,
17438 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
17439 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
17440 ];
17441 for (i, a) in all.iter().enumerate() {
17442 for b in all.iter().skip(i + 1) {
17443 assert_ne!(
17444 a, b,
17445 "Caixa top-level multi-word key consts must be \
17446 pairwise-distinct canonical byte-sequences — got \
17447 `{a}` == `{b}`",
17448 );
17449 }
17450 }
17451 }
17452
17453 #[test]
17454 fn caixa_top_level_multi_word_key_consts_are_lower_camel_case_shape() {
17455 // Shape-pin: every [`Caixa`] top-level multi-word key const must
17456 // be a lowerCamelCase byte-sequence (no `snake_case`
17457 // underscores, no `kebab-case` hyphens, no leading colon, no
17458 // `PascalCase` leading capital, no whitespace / dots) — the
17459 // canonical shape the `#[serde(rename_all = "camelCase")]`
17460 // derive produces on [`Caixa`]. A future flip to a
17461 // non-camelCase attribute at the derive surfaces both here
17462 // (this test fails on the stale-constant shape) and at
17463 // `caixa_multi_word_serde_keys_match_lifted_top_level_key_consts`
17464 // (that test fails on the mismatch between const and derive).
17465 // Peer with `membro_key_consts_are_lower_camel_case_shape`
17466 // (ce80ca0) and `supervisor_key_consts_are_lower_camel_case_shape`
17467 // (40cc4e5) on the sibling per-entry / supervisor-tree axes.
17468 for key in [
17469 crate::render::CAIXA_KEY_DEPS_DEV,
17470 crate::render::M2_KEY_UPGRADE_FROM,
17471 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
17472 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
17473 ] {
17474 assert!(
17475 !key.is_empty(),
17476 "Caixa top-level multi-word key const must be non-empty \
17477 (got {key:?})"
17478 );
17479 let first = key.chars().next().unwrap();
17480 assert!(
17481 first.is_ascii_lowercase(),
17482 "Caixa top-level multi-word key const must lead with an \
17483 ASCII-lowercase byte (got {key:?}, leads with {first:?})",
17484 );
17485 assert!(
17486 key.chars().all(|c| c.is_ascii_alphanumeric()),
17487 "Caixa top-level multi-word key const must be \
17488 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
17489 whitespace (got {key:?})",
17490 );
17491 }
17492 }
17493
17494 #[test]
17495 fn caixa_key_deps_dev_pins_canonical_camel_case_byte_string() {
17496 // Scalar-value pin: the byte-string the
17497 // [`crate::render::CAIXA_KEY_DEPS_DEV`] const resolves to,
17498 // asserted verbatim. A future rebrand (`depsDev` → `devDeps`
17499 // matching Cargo's verbatim `dev-dependencies` axis, `depsDev`
17500 // → `depsTest` matching a hypothetical per-test-target
17501 // vocabulary flip) lands as an edit to exactly one const AND
17502 // one derive attribute — the sibling
17503 // `caixa_multi_word_serde_keys_match_lifted_top_level_key_consts`
17504 // pin already ties the const to the derive attribute, so a
17505 // rebrand that touches only one side of the pair fails at
17506 // caixa-core build time. Same "scalar-value pin per const"
17507 // discipline the sibling
17508 // `m2_top_level_author_key_consts_pin_canonical_kebab_case_labels`
17509 // (f49c8b0) and `contrato_key_consts_pin_canonical_camel_case_labels`
17510 // (ca463a4) pins carry on the peer M2 / M3 top-level slot axes.
17511 assert_eq!(crate::render::CAIXA_KEY_DEPS_DEV, "depsDev");
17512 }
17513
17514 #[test]
17515 fn caixa_key_deps_pins_canonical_byte_string() {
17516 // Scalar-value pin: the byte-string the
17517 // [`crate::render::CAIXA_KEY_DEPS`] const resolves to, asserted
17518 // verbatim. Peer of `caixa_key_deps_dev_pins_canonical_camel_case_byte_string`
17519 // on the two-list dep-graph serialized-key axis — the sibling
17520 // pin covers the multi-word `deps_dev → depsDev` camelCase
17521 // arm, this pin covers the single-word `deps → deps` no-op arm
17522 // (the [`crate::Caixa::deps`] field name carries no `_`, so the
17523 // `#[serde(rename_all = "camelCase")]` derive is a no-op on this
17524 // axis and the emitted JSON key equals the source-side field
17525 // name byte-for-byte). A future [`crate::Caixa::deps`] field
17526 // rename (`deps` → `dependencies` matching Cargo's verbatim
17527 // `[dependencies]` axis, `deps` → `runtime_deps` matching a
17528 // hypothetical per-runtime-target vocabulary flip) OR an added
17529 // `#[serde(rename = "…")]` explicit override lands as an edit
17530 // to exactly one const AND one derive-attr / field name — the
17531 // sibling `caixa_deps_serde_key_matches_lifted_caixa_key_deps`
17532 // pin ties the const to the emitted JSON key, so a rebrand
17533 // that touches only one side of the pair fails at caixa-core
17534 // build time.
17535 assert_eq!(crate::render::CAIXA_KEY_DEPS, "deps");
17536 }
17537
17538 #[test]
17539 fn caixa_deps_serde_key_matches_lifted_caixa_key_deps() {
17540 // Load-bearing invariant on the single-word `deps` top-level
17541 // axis: the byte-string [`crate::render::CAIXA_KEY_DEPS`] pins
17542 // must appear verbatim in the JSON [`Caixa::to_lisp`]'s
17543 // `serde_json::to_value(self)` step emits. Serialize a
17544 // populated [`Caixa`] whose `:deps` slot carries at least one
17545 // entry (the `#[serde(default)]` attribute on the field emits
17546 // an empty `[]` even without members, but a non-empty vec
17547 // additionally covers the codec's per-`Dep`-entry emission
17548 // path) and pin that `"deps"` appears verbatim in the JSON
17549 // emission — a future accidental `rename_all = "snake_case"` /
17550 // `"kebab-case"` flip at the derive attribute (or an added
17551 // `#[serde(rename = "…")]` explicit override on the field, or
17552 // a Rust field rename) would break every [`Caixa::to_lisp`]
17553 // round-trip and the future M4 operator-side manifest ingest's
17554 // `Value::get(CAIXA_KEY_DEPS)` navigation — surfaces here as a
17555 // build-time test failure at `manifest.rs`, not as an
17556 // apply-time `.get(<stale-canonical-const>)` returning `None`
17557 // far from the drift's commit. Peer of the sibling
17558 // `caixa_multi_word_serde_keys_match_lifted_top_level_key_consts`
17559 // multi-word pin on the same M0 [`Caixa`] top-level
17560 // serialized-key axis, extended here to the single-word arm
17561 // the multi-word test's `rename_all = "camelCase"` sweep can't
17562 // reach (single-word `deps → deps` is a no-op the multi-word
17563 // pin's `\"depsDev\"` / `\"upgradeFrom\"` / `\"maxRestarts\"` /
17564 // `\"restartWindow\"` byte-scan can never observe).
17565 let mut c = Caixa::from_lisp(&Caixa::template("demo")).unwrap();
17566 c.deps = vec![Dep::simple("caixa-core", "^0.1")];
17567 let json = serde_json::to_string(&c).unwrap();
17568 let quoted = format!("\"{}\"", crate::render::CAIXA_KEY_DEPS);
17569 assert!(
17570 json.contains("ed),
17571 "serialized Caixa must carry the lifted top-level `deps` \
17572 byte-sequence {quoted} verbatim in the JSON emission (got: \
17573 {json})",
17574 );
17575 }
17576
17577 #[test]
17578 fn caixa_dep_graph_two_list_key_consts_are_pairwise_distinct() {
17579 // Cross-axis drift-detection pin on the two-list dep-graph
17580 // renderer-side wire-key axis: a future collapse of the
17581 // canonical [`crate::render::CAIXA_KEY_DEPS`] /
17582 // [`crate::render::CAIXA_KEY_DEPS_DEV`] byte-strings onto the
17583 // same value (e.g. an accidental copy-paste flip of
17584 // `CAIXA_KEY_DEPS_DEV` to also read `"deps"`) would silently
17585 // reroute every downstream `Value::get(<key>)` probe on one
17586 // axis onto the sibling axis's dep-list and pass every
17587 // propagation-probe test that expected only the stale axis's
17588 // value — a dev-only dep would land in the runtime closure at
17589 // publish time, or a runtime dep would be excluded from the
17590 // published lacre. Peer of the sibling four-way distinct pin
17591 // on the top-level multi-word tetrad
17592 // (`caixa_top_level_multi_word_key_consts_are_pairwise_distinct`)
17593 // and the two-way pin on the sibling
17594 // [`DEP_AUTHOR_KEY_DEPS`] / [`DEP_AUTHOR_KEY_DEPS_DEV`]
17595 // author-facing arm (4da6fba's test), extended here to the
17596 // renderer-side wire-key arm of the same two-list dep-graph
17597 // axis so both halves of the "one canonical byte-string per
17598 // typed axis per (author, wire)" grid carry the same
17599 // distinct-ness discipline.
17600 assert_ne!(
17601 crate::render::CAIXA_KEY_DEPS,
17602 crate::render::CAIXA_KEY_DEPS_DEV,
17603 "CAIXA_KEY_DEPS and CAIXA_KEY_DEPS_DEV must be distinct \
17604 canonical byte-sequences on the two-list dep-graph \
17605 renderer-side wire-key axis"
17606 );
17607 }
17608
17609 // ── DepList / Caixa::push_dep pin ────────────────────────────────
17610 //
17611 // The compounding pin: the two-arm closed-set typed enum
17612 // [`crate::dep::DepList`] carries the runtime-closure `:deps`
17613 // (`Prod`) vs dev-only-closure `:deps-dev` (`Dev`) dispatch every
17614 // consumer of the top-level manifest's dep-mutation surface reads
17615 // through, and the typed dispatch [`Caixa::push_dep`] on the
17616 // substrate primitive folds the "select list → check within-list
17617 // dup → push" cascade onto one method call. Prior to this landing
17618 // the two axes lived across two `&'static str` constants
17619 // (`DEP_AUTHOR_KEY_DEPS`, `DEP_AUTHOR_KEY_DEPS_DEV`) with no closed-
17620 // set type carrying the pair; the `feira add` mutation site's
17621 // inline `if self.dev { &mut caixa.deps_dev } else { &mut
17622 // caixa.deps }` dispatch expressed no compile-time link back to
17623 // the substrate primitive, and a future third dep-list axis would
17624 // have silently split at every open-coded mutation site.
17625
17626 #[test]
17627 fn dep_list_as_str_routes_through_lifted_author_key_constants() {
17628 // Every arm returns the same `&'static str` the substrate's
17629 // canonical `DEP_AUTHOR_KEY_DEPS` / `DEP_AUTHOR_KEY_DEPS_DEV`
17630 // constants carry. A future rebrand on either constant reaches
17631 // the enum through one edit; a regression to inline literals
17632 // (e.g. `Prod => ":deps"`) would silently split the diagnostic
17633 // quotes from the wire-format constants every consumer routes
17634 // through and this pin flags it at build time.
17635 assert_eq!(
17636 crate::dep::DepList::Prod.as_str(),
17637 crate::render::DEP_AUTHOR_KEY_DEPS
17638 );
17639 assert_eq!(
17640 crate::dep::DepList::Dev.as_str(),
17641 crate::render::DEP_AUTHOR_KEY_DEPS_DEV
17642 );
17643 }
17644
17645 #[test]
17646 fn dep_list_display_routes_through_as_str() {
17647 // Same as-str-through-Display convergence discipline the
17648 // sibling closed-set typed enums carry — a `format!("{list}")`
17649 // call must land byte-for-byte on the accessor's return so a
17650 // future consumer that formats the enum for a diagnostic line
17651 // reaches the same wire-format constant the wire-format
17652 // producers do.
17653 assert_eq!(
17654 format!("{}", crate::dep::DepList::Prod),
17655 crate::dep::DepList::Prod.as_str()
17656 );
17657 assert_eq!(
17658 format!("{}", crate::dep::DepList::Dev),
17659 crate::dep::DepList::Dev.as_str()
17660 );
17661 }
17662
17663 #[test]
17664 fn dep_list_all_enumerates_every_variant_once() {
17665 // Exhaustive-iteration pin — every arm appears exactly once in
17666 // `ALL`, matching the closed set the compiler enforces on the
17667 // sibling `match self` arms. A future variant addition that
17668 // extends only one method's match without extending `ALL`
17669 // would silently drop the new arm from every consumer that
17670 // iterates the slice.
17671 let variants: &[crate::dep::DepList] = crate::dep::DepList::ALL;
17672 assert!(variants.contains(&crate::dep::DepList::Prod));
17673 assert!(variants.contains(&crate::dep::DepList::Dev));
17674 assert_eq!(variants.len(), 2);
17675 }
17676
17677 #[test]
17678 fn dep_list_from_wire_returns_prod_on_deps_wire_scalar() {
17679 // Reverse projection on the two-list dep-graph axis: the
17680 // author-surface wire tag the sibling `as_str` emitter walks
17681 // for `Prod` (`:deps` via `DEP_AUTHOR_KEY_DEPS`) parses back to
17682 // `Some(DepList::Prod)`. A regression that hand-rolled the
17683 // per-arm match without routing through the lifted
17684 // `DEP_AUTHOR_KEY_DEPS` const would silently disagree on any
17685 // future wire-tag rebrand and this pin flags it at build time.
17686 assert_eq!(
17687 crate::dep::DepList::from_wire(crate::render::DEP_AUTHOR_KEY_DEPS),
17688 Some(crate::dep::DepList::Prod)
17689 );
17690 }
17691
17692 #[test]
17693 fn dep_list_from_wire_returns_dev_on_deps_dev_wire_scalar() {
17694 // Peer of the `Prod`-arm pin on the dev-only axis: the
17695 // author-surface wire tag the sibling `as_str` emitter walks
17696 // for `Dev` (`:deps-dev` via `DEP_AUTHOR_KEY_DEPS_DEV`) parses
17697 // back to `Some(DepList::Dev)`. Same drift-detection posture
17698 // as the peer arm — the sibling method `match` arms are
17699 // compiler-checked exhaustive so a future variant addition
17700 // trips at build time.
17701 assert_eq!(
17702 crate::dep::DepList::from_wire(crate::render::DEP_AUTHOR_KEY_DEPS_DEV),
17703 Some(crate::dep::DepList::Dev)
17704 );
17705 }
17706
17707 #[test]
17708 fn dep_list_from_wire_returns_none_on_unknown_wire_scalar() {
17709 // Every input outside the closed-set arm-string set the
17710 // sibling `as_str` emitter walks lands on the terminal `None`
17711 // fallback — no silent-accept surface. Sweeps a set of
17712 // plausibly-adjacent scalars (unprefixed wire form, PascalCase
17713 // rebrand candidates, foreign wire tags, empty string) so a
17714 // future variant addition that widened one wire form without
17715 // extending the emitter's arm-set would trip the sibling
17716 // round-trip pin below rather than silently accepting the new
17717 // form here.
17718 for candidate in [
17719 "",
17720 "deps",
17721 "deps-dev",
17722 ":deps ",
17723 ":Deps",
17724 ":DEPS",
17725 ":build-dep",
17726 ":tool-dep",
17727 "prod",
17728 "dev",
17729 ] {
17730 assert_eq!(
17731 crate::dep::DepList::from_wire(candidate),
17732 None,
17733 "from_wire({candidate:?}) must return None; every input outside \
17734 the {{DEP_AUTHOR_KEY_DEPS, DEP_AUTHOR_KEY_DEPS_DEV}} accept-set \
17735 the sibling as_str emitter walks lands on the terminal fallback",
17736 );
17737 }
17738 }
17739
17740 #[test]
17741 fn dep_list_round_trips_through_as_str_and_from_wire() {
17742 // Load-bearing round-trip pin: every arm the `ALL` iteration
17743 // exposes survives the `as_str` → `from_wire` composition
17744 // byte-for-byte. Same discipline the sibling closed-set enums
17745 // carry — `CaixaKind` /
17746 // `RestartStrategy` / `RestartPolicy` /
17747 // `PlacementStrategy` — extended onto the two-list dep-graph
17748 // axis. A future variant addition that extends `ALL` +
17749 // `as_str` without extending `from_wire` (or vice versa)
17750 // trips at build time on this iteration because the compiler
17751 // enforces exhaustiveness on the sibling `match self` arms.
17752 for &list in crate::dep::DepList::ALL {
17753 assert_eq!(
17754 crate::dep::DepList::from_wire(list.as_str()),
17755 Some(list),
17756 "DepList::from_wire(as_str({list:?})) must round-trip to Some({list:?}) — \
17757 a silent split between the forward emitter and the reverse parser \
17758 would drift the two halves of the two-list dep-graph axis's typed dispatch",
17759 );
17760 }
17761 }
17762
17763 #[test]
17764 fn push_dep_routes_to_deps_slot_on_prod_arm() {
17765 // The `Prod` arm dispatches to the runtime-closure `:deps`
17766 // slot every downstream lacre-pipeline consumer resolves at
17767 // build time. A future arm that regressed to inline `&mut
17768 // self.deps_dev` on the `Prod` path would silently reroute
17769 // every runtime dep into the dev-only closure at publish time
17770 // — this pin refuses that regression.
17771 let src = Caixa::template("host");
17772 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
17773 let before_deps = caixa.deps().len();
17774 let before_deps_dev = caixa.deps_dev().len();
17775 let dep = Dep {
17776 nome: "caixa-teia".to_string(),
17777 versao: "^0.1".to_string(),
17778 fonte: None,
17779 opcional: false,
17780 caracteristicas: Vec::new(),
17781 };
17782 caixa
17783 .push_dep(crate::dep::DepList::Prod, dep)
17784 .expect("first push into :deps succeeds");
17785 assert_eq!(caixa.deps().len(), before_deps + 1);
17786 assert_eq!(caixa.deps_dev().len(), before_deps_dev);
17787 assert_eq!(caixa.deps().last().unwrap().nome(), "caixa-teia");
17788 }
17789
17790 #[test]
17791 fn push_dep_routes_to_deps_dev_slot_on_dev_arm() {
17792 // Peer of the sibling `Prod`-arm dispatch pin — the `Dev` arm
17793 // must dispatch to the dev-only-closure `:deps-dev` slot every
17794 // downstream test-facing artifact resolver reads. A future
17795 // regression that inverted the two arms would silently route
17796 // every dev-only dep into the runtime closure at publish time
17797 // and this pin catches it before the drift ships.
17798 let src = Caixa::template("host");
17799 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
17800 let dep = Dep {
17801 nome: "tatara-check".to_string(),
17802 versao: "*".to_string(),
17803 fonte: None,
17804 opcional: false,
17805 caracteristicas: Vec::new(),
17806 };
17807 caixa
17808 .push_dep(crate::dep::DepList::Dev, dep)
17809 .expect("first push into :deps-dev succeeds");
17810 assert!(caixa.deps().is_empty());
17811 assert_eq!(caixa.deps_dev().len(), 1);
17812 assert_eq!(caixa.deps_dev().last().unwrap().nome(), "tatara-check");
17813 }
17814
17815 #[test]
17816 fn push_dep_refuses_within_list_duplicate_nome_with_typed_error() {
17817 // Within-list dup check routes through the canonical
17818 // [`DepError::DuplicateNome`] carrier — the substrate's typed
17819 // diagnostic for the same axis [`Caixa::validate_deps`]'s
17820 // parse-time [`crate::render::insert_first_seen`] walk raises
17821 // on. Prior to the lift the mutation site's inline
17822 // `bail!("dep '{}' already declared", …)` string-diagnostic
17823 // path expressed no through-line back to the typed error;
17824 // routing every dep-list refusal through one carrier means an
17825 // author reading a `feira add` refusal and a `feira build`
17826 // refusal reaches for the same corrective surface without
17827 // switching diagnostic idioms.
17828 let src = Caixa::template("host");
17829 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
17830 let dep = Dep {
17831 nome: "caixa-teia".to_string(),
17832 versao: "^0.1".to_string(),
17833 fonte: None,
17834 opcional: false,
17835 caracteristicas: Vec::new(),
17836 };
17837 caixa
17838 .push_dep(crate::dep::DepList::Prod, dep.clone())
17839 .expect("first push succeeds");
17840 let dup = Dep {
17841 nome: "caixa-teia".to_string(),
17842 versao: "^0.2".to_string(),
17843 fonte: None,
17844 opcional: false,
17845 caracteristicas: Vec::new(),
17846 };
17847 let err = caixa
17848 .push_dep(crate::dep::DepList::Prod, dup)
17849 .expect_err("second push with same :nome refuses");
17850 assert_eq!(
17851 err,
17852 DepError::DuplicateNome {
17853 nome: "caixa-teia".to_string(),
17854 list: crate::render::DEP_AUTHOR_KEY_DEPS,
17855 }
17856 );
17857 // The refused mutation must not corrupt the target list —
17858 // exactly one entry lives past the refusal, matching the
17859 // canonical single-source-of-truth invariant `Caixa::deps()`
17860 // carries.
17861 assert_eq!(caixa.deps().len(), 1);
17862 }
17863
17864 #[test]
17865 fn push_dep_refuses_dup_on_dev_list_arm_names_deps_dev_key() {
17866 // Peer of the sibling `Prod`-arm dup-refusal pin — the `Dev`
17867 // arm's refusal must carry `DEP_AUTHOR_KEY_DEPS_DEV` in the
17868 // `list` payload so a future author reading the refusal grep's
17869 // for the correct `:deps-dev` block in their `caixa.lisp`,
17870 // not the sibling `:deps` block the runtime closure resolves.
17871 let src = Caixa::template("host");
17872 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
17873 let dep = Dep {
17874 nome: "tatara-check".to_string(),
17875 versao: "*".to_string(),
17876 fonte: None,
17877 opcional: false,
17878 caracteristicas: Vec::new(),
17879 };
17880 caixa
17881 .push_dep(crate::dep::DepList::Dev, dep.clone())
17882 .expect("first push succeeds");
17883 let err = caixa
17884 .push_dep(crate::dep::DepList::Dev, dep)
17885 .expect_err("second push with same :nome refuses");
17886 assert!(matches!(
17887 err,
17888 DepError::DuplicateNome {
17889 ref nome,
17890 list,
17891 } if nome == "tatara-check"
17892 && list == crate::render::DEP_AUTHOR_KEY_DEPS_DEV
17893 ));
17894 }
17895
17896 #[test]
17897 fn push_dep_allows_same_nome_across_prod_and_dev_lists() {
17898 // The within-list dup check is scoped to the target arm — a
17899 // caixa may legitimately carry the same `:nome` under both
17900 // `:deps` and `:deps-dev` (though the substrate's peer
17901 // [`crate::Caixa::validate_deps`] walk still refuses the
17902 // shape at parse time; the mutation-site refusal is scoped to
17903 // the mutation-site's list to match the peer parse-time
17904 // per-list [`crate::render::insert_first_seen`] discipline).
17905 // The two arms hold independent seen-sets.
17906 let src = Caixa::template("host");
17907 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
17908 let dep_prod = Dep {
17909 nome: "shared".to_string(),
17910 versao: "^0.1".to_string(),
17911 fonte: None,
17912 opcional: false,
17913 caracteristicas: Vec::new(),
17914 };
17915 let dep_dev = Dep {
17916 nome: "shared".to_string(),
17917 versao: "*".to_string(),
17918 fonte: None,
17919 opcional: false,
17920 caracteristicas: Vec::new(),
17921 };
17922 caixa
17923 .push_dep(crate::dep::DepList::Prod, dep_prod)
17924 .expect("push into :deps succeeds");
17925 caixa
17926 .push_dep(crate::dep::DepList::Dev, dep_dev)
17927 .expect("push same :nome into :deps-dev succeeds");
17928 assert_eq!(caixa.deps().len(), 1);
17929 assert_eq!(caixa.deps_dev().len(), 1);
17930 }
17931
17932 #[test]
17933 fn deps_of_prod_returns_the_deps_slot_verbatim() {
17934 // The `Prod` arm of the typed-dispatch [`Caixa::deps_of`] read
17935 // accessor must project onto the runtime-closure `:deps` slot —
17936 // element-equal and length-equal to the sibling per-slot
17937 // [`Caixa::deps`] accessor's return over every per-caixa fixture.
17938 // A future arm that regressed to `self.deps_dev()` on the `Prod`
17939 // path would silently reroute every downstream typed-dispatch
17940 // walker (the [`Caixa::validate_deps`] per-list
17941 // [`crate::render::insert_first_seen`] dedup walk, any future
17942 // per-axis-parametrised consumer) into the sibling dev-only
17943 // closure and this pin refuses that regression.
17944 let src = Caixa::template("host");
17945 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
17946 assert_eq!(caixa.deps_of(crate::dep::DepList::Prod), caixa.deps());
17947 assert_eq!(caixa.deps_of(crate::dep::DepList::Prod).len(), 0);
17948 let dep = Dep {
17949 nome: "caixa-teia".to_string(),
17950 versao: "^0.1".to_string(),
17951 fonte: None,
17952 opcional: false,
17953 caracteristicas: Vec::new(),
17954 };
17955 caixa
17956 .push_dep(crate::dep::DepList::Prod, dep.clone())
17957 .expect("push into :deps succeeds");
17958 assert_eq!(caixa.deps_of(crate::dep::DepList::Prod), caixa.deps());
17959 assert_eq!(caixa.deps_of(crate::dep::DepList::Prod).len(), 1);
17960 assert_eq!(
17961 caixa.deps_of(crate::dep::DepList::Prod)[0].nome(),
17962 "caixa-teia"
17963 );
17964 }
17965
17966 #[test]
17967 fn deps_of_dev_returns_the_deps_dev_slot_verbatim() {
17968 // Peer of the sibling `Prod`-arm pin — the `Dev` arm of
17969 // [`Caixa::deps_of`] must project onto the dev-only-closure
17970 // `:deps-dev` slot, element-equal and length-equal to the
17971 // sibling per-slot [`Caixa::deps_dev`] accessor's return. A
17972 // future regression that inverted the two arms would silently
17973 // route every dev-list walker onto the runtime closure and this
17974 // pin catches it before the drift ships.
17975 let src = Caixa::template("host");
17976 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
17977 assert_eq!(caixa.deps_of(crate::dep::DepList::Dev), caixa.deps_dev());
17978 assert_eq!(caixa.deps_of(crate::dep::DepList::Dev).len(), 0);
17979 let dep = Dep {
17980 nome: "tatara-check".to_string(),
17981 versao: "*".to_string(),
17982 fonte: None,
17983 opcional: false,
17984 caracteristicas: Vec::new(),
17985 };
17986 caixa
17987 .push_dep(crate::dep::DepList::Dev, dep)
17988 .expect("push into :deps-dev succeeds");
17989 assert_eq!(caixa.deps_of(crate::dep::DepList::Dev), caixa.deps_dev());
17990 assert_eq!(caixa.deps_of(crate::dep::DepList::Dev).len(), 1);
17991 assert_eq!(
17992 caixa.deps_of(crate::dep::DepList::Dev)[0].nome(),
17993 "tatara-check"
17994 );
17995 }
17996
17997 #[test]
17998 fn deps_of_exhaustive_over_dep_list_all_covers_the_two_slots() {
17999 // Composition pin: iterating [`crate::dep::DepList::ALL`] through
18000 // [`Caixa::deps_of`] must land on the same two-slot partition the
18001 // per-slot [`Caixa::deps`] / [`Caixa::deps_dev`] accessors
18002 // expose — the canonical dispatch a future per-axis-parametrised
18003 // walker (a future `feira app graph` per-list dep summary, a
18004 // future M4 per-cluster dev-closure-audit overlay the CR
18005 // materializer resolves per-CR) reads through. Prior to the
18006 // lift the two-block iteration lived open-coded at every walker,
18007 // so a future third dep-list axis (`:deps-build`, per CAIXA-SDLC
18008 // §I) would have had to grow a third block at every consumer.
18009 // A regression that dropped the `Dev` arm from `ALL` would flip
18010 // the collected pairs to `[(":deps", &[])]` alone and this pin
18011 // refuses that shape.
18012 let src = Caixa::template("host");
18013 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
18014 let prod_dep = Dep {
18015 nome: "caixa-teia".to_string(),
18016 versao: "^0.1".to_string(),
18017 fonte: None,
18018 opcional: false,
18019 caracteristicas: Vec::new(),
18020 };
18021 let dev_dep = Dep {
18022 nome: "tatara-check".to_string(),
18023 versao: "*".to_string(),
18024 fonte: None,
18025 opcional: false,
18026 caracteristicas: Vec::new(),
18027 };
18028 caixa
18029 .push_dep(crate::dep::DepList::Prod, prod_dep)
18030 .expect("push into :deps succeeds");
18031 caixa
18032 .push_dep(crate::dep::DepList::Dev, dev_dep)
18033 .expect("push into :deps-dev succeeds");
18034 let collected: Vec<(&'static str, usize, &str)> = crate::dep::DepList::ALL
18035 .iter()
18036 .map(|&list| {
18037 let slice = caixa.deps_of(list);
18038 (list.as_str(), slice.len(), slice[0].nome())
18039 })
18040 .collect();
18041 assert_eq!(
18042 collected,
18043 vec![
18044 (crate::render::DEP_AUTHOR_KEY_DEPS, 1, "caixa-teia"),
18045 (crate::render::DEP_AUTHOR_KEY_DEPS_DEV, 1, "tatara-check"),
18046 ]
18047 );
18048 }
18049
18050 #[test]
18051 fn validate_deps_iterates_through_dep_list_all_via_deps_of() {
18052 // Composition pin: the [`Caixa::validate_deps`] parse-time gate
18053 // must route its per-list [`crate::render::insert_first_seen`]
18054 // dedup walk through [`Caixa::deps_of`] + [`crate::dep::DepList::ALL`]
18055 // rather than the pre-lift open-coded two-block iteration over
18056 // `self.deps()` + `self.deps_dev()`. A regression that dropped
18057 // one arm (e.g. hand-inlining `self.deps()` alone) would silently
18058 // stop refusing within-list dups on the sibling arm; a
18059 // regression that flipped the arm-to-list-key mapping
18060 // (`Dev => DEP_AUTHOR_KEY_DEPS`) would silently mislabel the
18061 // diagnostic surface. Both drifts surface here through a paired
18062 // duplicate-name refusal per arm plus an offending-list-key
18063 // check on the emitted [`DepError::DuplicateNome`] carrier.
18064 for &list in crate::dep::DepList::ALL {
18065 let src = Caixa::template("host");
18066 let mut caixa = Caixa::from_lisp(&src).expect("template parses");
18067 let dup = Dep {
18068 nome: "twin".to_string(),
18069 versao: "^0.1".to_string(),
18070 fonte: None,
18071 opcional: false,
18072 caracteristicas: Vec::new(),
18073 };
18074 match list {
18075 crate::dep::DepList::Prod => {
18076 caixa.deps.push(dup.clone());
18077 caixa.deps.push(dup);
18078 }
18079 crate::dep::DepList::Dev => {
18080 caixa.deps_dev.push(dup.clone());
18081 caixa.deps_dev.push(dup);
18082 }
18083 }
18084 let err = caixa
18085 .validate_deps()
18086 .expect_err("within-list duplicate :nome must refuse");
18087 assert_eq!(
18088 err,
18089 DepError::DuplicateNome {
18090 nome: "twin".to_string(),
18091 list: list.as_str(),
18092 },
18093 "validate_deps on {list} arm must emit \
18094 DepError::DuplicateNome carrying the arm's own \
18095 as_str() diagnostic — the arm-to-list-key mapping \
18096 flowed through DepList::ALL + Caixa::deps_of"
18097 );
18098 }
18099 }
18100}