caixa_core/layout.rs
1//! Layout invariants — the Rust-enforced package structure.
2//!
3//! This is the caixa analog of Cargo's implicit `src/lib.rs` vs `src/main.rs`
4//! rule: the Rust type system dictates the package shape, and the invariant
5//! checker runs before any build step. [`StandardLayout`] encodes the
6//! canonical layout:
7//!
8//! - `caixa.lisp` — always required
9//! - `lib/<nome>.lisp` — required when `:kind Biblioteca` and
10//! `:bibliotecas` is empty
11//! - each `:bibliotecas` — must resolve on disk
12//! - each `:exe` — must resolve on disk, under `exe/`
13//! - each `:servicos` — must resolve on disk, under `servicos/`
14//!
15//! Filesystem I/O is injected through [`StandardLayout::with_path_exists`]
16//! so tests can run without touching disk.
17
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21use thiserror::Error;
22
23use crate::{Caixa, CaixaKind};
24
25/// Contract — a caixa layout checker.
26pub trait LayoutInvariants {
27 /// Verify every declared path resolves + kind-specific invariants hold.
28 fn verify(&self, caixa: &Caixa, root: &Path) -> Result<(), LayoutError>;
29}
30
31type ExistsFn = Arc<dyn Fn(&Path) -> bool + Send + Sync>;
32
33/// The default layout contract.
34#[derive(Default, Clone)]
35pub struct StandardLayout {
36 path_exists: Option<ExistsFn>,
37}
38
39impl StandardLayout {
40 #[must_use]
41 pub fn new() -> Self {
42 Self::default()
43 }
44
45 /// Override how file existence is tested. Useful for in-memory tests.
46 #[must_use]
47 pub fn with_path_exists<F>(mut self, f: F) -> Self
48 where
49 F: Fn(&Path) -> bool + Send + Sync + 'static,
50 {
51 self.path_exists = Some(Arc::new(f));
52 self
53 }
54
55 fn exists(&self, p: &Path) -> bool {
56 self.path_exists
57 .as_ref()
58 .map_or_else(|| p.exists(), |f| f(p))
59 }
60
61 /// Probe an authored path's resolved on-disk location under `root`
62 /// and, on absence, return the paired [`LayoutError::MissingEntry`]
63 /// naming the missing entry at that resolved location with the
64 /// caller-provided canonical `kind` label (from the
65 /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] const family).
66 /// Returns the resolved [`PathBuf`] on hit so callers that need to
67 /// run a follow-up per-path gate (the `:exe` /
68 /// `:servicos` sandbox-directory-containment check the peer
69 /// wire-up sites carry) reach it without re-computing
70 /// `root.join(path)`.
71 ///
72 /// Folds the five self-similar
73 /// `let full = root.join(p); if !self.exists(&full) { return
74 /// Err(LayoutError::missing_entry(<kind>, full)); }` existence-probe
75 /// blocks at [`Self::verify`] (`:bibliotecas` iteration, `:exe`
76 /// iteration, `:servicos` iteration, `:behavior` on-disk callback-
77 /// path iteration, `:upgrade-from` per-instruction script-path
78 /// iteration) onto one substrate primitive on [`StandardLayout`].
79 /// Every future consumer that wants to probe a declared path
80 /// against an out-of-band filesystem oracle (a per-slot admission
81 /// webhook, a `feira validate --paths` per-caixa admission verb,
82 /// the deferred `caixa.pleme.io/v1alpha1/Caixa` CR materializer's
83 /// admission-webhook floor, a per-cluster overlay resolver
84 /// re-probing a declared path against a cluster-local filesystem
85 /// snapshot) reaches the two-step `root.join` + `exists` + wrap
86 /// dispatch through one call rather than re-inlining the three-
87 /// line block in lockstep with the five wire-up sites.
88 fn probe_declared_entry<P: AsRef<Path>>(
89 &self,
90 path: P,
91 root: &Path,
92 kind: &'static str,
93 ) -> Result<PathBuf, LayoutError> {
94 let full = root.join(path.as_ref());
95 if !self.exists(&full) {
96 return Err(LayoutError::missing_entry(kind, full));
97 }
98 Ok(full)
99 }
100
101 /// Probe an authored path's resolved on-disk location under `root`
102 /// and, on presence, verify the resolved [`PathBuf`] lives inside
103 /// the paired `sandbox_dir` sub-tree; on absence return the paired
104 /// [`LayoutError::MissingEntry`] (via [`Self::probe_declared_entry`])
105 /// and on sandbox escape return `outside_ctor(full)` naming the
106 /// offending resolved path.
107 ///
108 /// Folds the two self-similar `let full = self.probe_declared_entry(
109 /// p, root, <kind>)?; if !full.starts_with(&<slot>_dir) { return
110 /// Err(LayoutError::<Slot>OutsideDir(full)); }` blocks at
111 /// [`Self::verify`] (`:exe` iteration, `:servicos` iteration) onto
112 /// one substrate primitive on [`StandardLayout`]. The two wire-ups
113 /// used the identical two-arm cascade around the peer
114 /// [`Self::probe_declared_entry`] hit-arm hand-off, differing only
115 /// in the three names bound at each site — the `kind` label, the
116 /// resolved `sandbox_dir`, and the paired outside-dir
117 /// tuple-variant constructor (`LayoutError::ExeOutsideDir` /
118 /// `LayoutError::ServicoOutsideDir`) — exactly the shape the PRIME
119 /// DIRECTIVE names as a bug.
120 ///
121 /// Diagnostic order preserved: [`LayoutError::MissingEntry`] fires
122 /// before `outside_ctor` on the same iteration (the pre-lift order
123 /// this primitive's sibling [`Self::probe_declared_entry`]
124 /// docstring documents). Every future consumer that wants to probe
125 /// a declared path against an out-of-band filesystem oracle *and*
126 /// gate the resolved path on a sandbox sub-tree — a per-slot
127 /// admission webhook probing a declared `:exe` / `:servicos` entry
128 /// against a mounted cluster-local filesystem snapshot, a
129 /// per-cluster overlay resolver rejecting a sandbox-escape patch,
130 /// the deferred `caixa.pleme.io/v1alpha1/Caixa` CR materializer's
131 /// admission-webhook floor — reaches the two-arm probe + sandbox
132 /// dispatch through one call rather than re-inlining the three-
133 /// line block in lockstep with the two `verify` wire-up sites.
134 fn probe_sandboxed_declared_entry<P: AsRef<Path>>(
135 &self,
136 path: P,
137 root: &Path,
138 kind: &'static str,
139 sandbox_dir: &Path,
140 outside_ctor: fn(PathBuf) -> LayoutError,
141 ) -> Result<PathBuf, LayoutError> {
142 let full = self.probe_declared_entry(path, root, kind)?;
143 if !full.starts_with(sandbox_dir) {
144 return Err(outside_ctor(full));
145 }
146 Ok(full)
147 }
148
149 /// Probe every path yielded by `paths` against the injected oracle
150 /// under `root`; on the first miss return the paired
151 /// [`LayoutError::MissingEntry`] naming the offending entry with the
152 /// caller-provided canonical `kind` label (via the sibling
153 /// [`Self::probe_declared_entry`] primitive), and on empty / all-hit
154 /// arms return `Ok(())`.
155 ///
156 /// Folds the three self-similar per-slot existence-probe *loop*
157 /// blocks at [`Self::verify`] onto one substrate primitive on
158 /// [`StandardLayout`]:
159 ///
160 /// - `:bibliotecas` iteration — `for p in caixa.bibliotecas() { self.
161 /// probe_declared_entry(p, root, LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA)?; }`,
162 /// - `:behavior` on-disk callback-path iteration — `for p in
163 /// b.declared_paths() { self.probe_declared_entry(p, root,
164 /// LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK)?; }`,
165 /// - `:upgrade-from` per-instruction script-path iteration — the
166 /// `for entry in caixa.upgrade_from() { for instr in entry.
167 /// instructions() { if let Some(p) = instr.declared_path() { self.
168 /// probe_declared_entry(p, root, LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT)?;
169 /// } } }` nested cascade, flattened at the wire-up site through
170 /// `.iter().flat_map(_::instructions).filter_map(_::declared_path)`.
171 ///
172 /// Three consumers, three identical `for … { self.probe_declared_entry
173 /// (…, kind)?; }` loop shapes, one substrate primitive on
174 /// [`StandardLayout`] closing the duplication the PRIME DIRECTIVE
175 /// names as a bug — sibling to the peer per-arm-probe
176 /// [`Self::probe_declared_entry`] (fda1e35) and the two-arm-sandboxed
177 /// [`Self::probe_sandboxed_declared_entry`] (4940d55) primitives on
178 /// the same layout-pipeline existence-probe axis. Diagnostic order
179 /// preserved: iteration proceeds in the caller-supplied iterator
180 /// order and short-circuits on the first miss, byte-equal to the
181 /// pre-lift `for … { … ? }` loop's first-error return semantics.
182 /// Every future consumer that wants to sweep a per-slot declared-
183 /// path list against an out-of-band filesystem oracle (a per-slot
184 /// admission webhook probing an entire `:bibliotecas` / `:behavior`
185 /// / `:upgrade-from` slot as a unit against a mounted cluster-local
186 /// filesystem snapshot, a `feira validate --exists` per-caixa
187 /// admission verb, the deferred `caixa.pleme.io/v1alpha1/Caixa` CR
188 /// materializer's admission-webhook floor, a per-cluster overlay
189 /// resolver re-probing a slot-of-paths after a patch) reaches the
190 /// per-slot batch through one call rather than re-inlining the
191 /// three-line loop body in lockstep with the three `verify` wire-up
192 /// sites.
193 fn probe_declared_entries<I, P>(
194 &self,
195 paths: I,
196 root: &Path,
197 kind: &'static str,
198 ) -> Result<(), LayoutError>
199 where
200 I: IntoIterator<Item = P>,
201 P: AsRef<Path>,
202 {
203 for p in paths {
204 self.probe_declared_entry(p, root, kind)?;
205 }
206 Ok(())
207 }
208
209 /// Probe every path yielded by `paths` against the injected oracle
210 /// under `root` and, on presence, verify the resolved path lives
211 /// inside `sandbox_dir` (via the sibling
212 /// [`Self::probe_sandboxed_declared_entry`] primitive); on the first
213 /// miss return the paired [`LayoutError::MissingEntry`] naming the
214 /// offending entry with the caller-provided canonical `kind` label,
215 /// on the first sandbox-escape return `outside_ctor(full)` naming
216 /// the offending resolved path, and on empty / all-hit arms return
217 /// `Ok(())`.
218 ///
219 /// Folds the two self-similar per-slot sandboxed-existence-probe
220 /// *loop* blocks at [`Self::verify`] onto one substrate primitive on
221 /// [`StandardLayout`]:
222 ///
223 /// - `:exe` iteration — `let exe_dir = root.join(LAYOUT_DIR_EXE); for
224 /// p in caixa.exe() { self.probe_sandboxed_declared_entry(p, root,
225 /// LAYOUT_MISSING_ENTRY_KIND_EXE, &exe_dir, LayoutError::ExeOutsideDir)?; }`,
226 /// - `:servicos` iteration — `let servicos_dir = root.join(
227 /// LAYOUT_DIR_SERVICOS); for p in caixa.servicos() {
228 /// self.probe_sandboxed_declared_entry(p, root,
229 /// LAYOUT_MISSING_ENTRY_KIND_SERVICO, &servicos_dir,
230 /// LayoutError::ServicoOutsideDir)?; }`.
231 ///
232 /// Two consumers, two identical `for … { self.probe_sandboxed_declared_entry
233 /// (…, kind, &sandbox_dir, outside_ctor)?; }` loop shapes, one
234 /// substrate primitive on [`StandardLayout`] closing the duplication
235 /// the PRIME DIRECTIVE names as a bug — sibling to the peer per-slot
236 /// batch [`Self::probe_declared_entries`] (d1ccb0b) primitive on the
237 /// non-sandboxed axis and the per-arm [`Self::probe_declared_entry`]
238 /// (fda1e35) / [`Self::probe_sandboxed_declared_entry`] (4940d55)
239 /// primitives on the per-path axis. The four together close the
240 /// layout-pipeline existence-probe algebra: every wire-up on the
241 /// (per-arm | per-slot batch) × (bare | sandboxed) product now
242 /// routes through one substrate primitive rather than N open-coded
243 /// blocks.
244 ///
245 /// Diagnostic order preserved: iteration proceeds in the caller-
246 /// supplied iterator order and short-circuits on the first miss or
247 /// sandbox-escape, byte-equal to the pre-lift `for … { … ? }` loop's
248 /// first-error return semantics. Within each iteration
249 /// [`LayoutError::MissingEntry`] fires before `outside_ctor` (the
250 /// order the peer [`Self::probe_sandboxed_declared_entry`] primitive
251 /// docstring documents). Every future consumer that wants to sweep a
252 /// per-slot declared-path list against an out-of-band filesystem
253 /// oracle *and* gate each resolved path on a sandbox sub-tree (a
254 /// per-slot admission webhook probing an entire `:exe` / `:servicos`
255 /// slot as a unit against a mounted cluster-local filesystem
256 /// snapshot, a `feira validate --exists --sandbox` per-caixa
257 /// admission verb, the deferred `caixa.pleme.io/v1alpha1/Caixa` CR
258 /// materializer's admission-webhook floor, a per-cluster overlay
259 /// resolver re-probing a slot-of-sandboxed-paths after a patch)
260 /// reaches the per-slot batch through one call rather than
261 /// re-inlining the three-line loop body in lockstep with the two
262 /// `verify` wire-up sites.
263 fn probe_sandboxed_declared_entries<I, P>(
264 &self,
265 paths: I,
266 root: &Path,
267 kind: &'static str,
268 sandbox_dir: &Path,
269 outside_ctor: fn(PathBuf) -> LayoutError,
270 ) -> Result<(), LayoutError>
271 where
272 I: IntoIterator<Item = P>,
273 P: AsRef<Path>,
274 {
275 for p in paths {
276 self.probe_sandboxed_declared_entry(p, root, kind, sandbox_dir, outside_ctor)?;
277 }
278 Ok(())
279 }
280}
281
282impl std::fmt::Debug for StandardLayout {
283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 f.debug_struct("StandardLayout")
285 .field("custom_exists", &self.path_exists.is_some())
286 .finish()
287 }
288}
289
290impl LayoutInvariants for StandardLayout {
291 fn verify(&self, caixa: &Caixa, root: &Path) -> Result<(), LayoutError> {
292 let manifest = root.join("caixa.lisp");
293 if !self.exists(&manifest) {
294 return Err(LayoutError::missing_manifest(manifest));
295 }
296
297 // Caixa-identity value-shape gates on the two universal axes
298 // (`:nome`, `:versao`) every substrate-side artifact's
299 // `metadata.name` / version derivation flows through. The
300 // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] doc-
301 // comments name the canonical authoring footguns verbatim —
302 // `:nome` "MyApp" / "my_app" / "team.app" / "-app" / "café"
303 // (DNS-1123 violations the K8s apiserver refuses at admission
304 // time on every derived `metadata.name`: `lareira-<nome>`,
305 // programs.yaml entry, CiliumNetworkPolicy / HTTPRoute names,
306 // `LABEL_APLICACAO` value); `:versao` "0.1" / "v0.1.0" / "latest"
307 // / "^0.1" / "0.1.0.0" (SemVer-2 violations Helm / OCI tag /
308 // `feira publish` git tag / lacre `concrete_versao` /
309 // `:upgrade-from :from` peer matching each refuse downstream).
310 // Until this wire-up landed both validators existed as `pub fn`
311 // on [`Caixa`] (with full per-arm test coverage in
312 // `manifest::tests`) but no production code path called them —
313 // `feira build` (the canonical author-time gate) silently
314 // accepted a malformed `:nome` / `:versao` and the failure
315 // surfaced at `helm install` / `kubectl apply` / `feira publish`
316 // time on the *first* downstream consumer to strict-parse the
317 // value, far from the source `caixa.lisp` and without any field
318 // naming the offending Caixa identity axis. The gate runs
319 // *after* [`LayoutError::MissingManifest`] (no caixa to check
320 // when the manifest is missing) and *before* every kind-coherence
321 // gate (each of which carries `caixa.nome` verbatim in its
322 // diagnostic — running them first on a structurally-invalid
323 // identity would surface a "this kind has slot X" diagnostic
324 // against an unrecoverable name). Cross-axis precedence is
325 // `:nome` → `:versao` — the canonical declaration order on
326 // [`Caixa`] and the same author-grep ordering the
327 // [`ManifestError`] family uses. Same per-axis `*Violation
328 // { caixa, issue }` envelope every peer per-axis wrap exposes
329 // ([`LayoutError::CodePathViolation`] b868442,
330 // [`LayoutError::LimitsViolation`] / [`LayoutError::BehaviorViolation`]
331 // / [`LayoutError::UpgradeViolation`] / [`LayoutError::SupervisorViolation`]
332 // / [`LayoutError::AplicacaoViolation`]).
333 caixa.run_layout_gate(Caixa::validate_nome, LayoutError::nome_violation)?;
334 // `:nome`-side joint-length budget on the canonical
335 // `lareira-<nome>` chart-name shape — the second arm on the
336 // shared `:nome` axis after the bare-DNS-1123 gate above. Runs
337 // through the same [`LayoutError::NomeViolation`] envelope so
338 // every per-axis diagnostic on `:nome` carries one wrap shape,
339 // peer with the [`Caixa::validate_nome`] → `NomeInvalid`
340 // routing already at this site. The chart-name budget is the
341 // second-axis ceiling [`Caixa::validate_nome`] cannot see — a
342 // 56-byte DNS-1123-valid `:nome` passes the bare-`:nome` shape
343 // but produces a 64-byte `lareira-<nome>` chart name the
344 // apiserver / `helm lint` rejects at admission, far from the
345 // source `caixa.lisp` and naming none of the joint-length
346 // overflow's three carriers (DNS-1123 cap, prefix, `:nome`
347 // length). Closing it at this wire-up turns the
348 // [`lareira_chart_name`] doc-comment's explicit M4-admission
349 // deferral (caixa-core/src/render.rs:3198) into a build-time
350 // structural property of every emitted artifact.
351 caixa.run_layout_gate(
352 Caixa::validate_nome_chart_name_budget,
353 LayoutError::nome_violation,
354 )?;
355 caixa.run_layout_gate(Caixa::validate_versao, LayoutError::versao_violation)?;
356
357 // `:deps` / `:deps-dev` per-entry shape gate. The third Caixa-
358 // level orphan validator on the universal authoring surface (peer
359 // of [`Caixa::validate_nome`] / [`Caixa::validate_versao`] wired
360 // immediately above): [`Caixa::validate_deps`] walks every
361 // [`Dep::validate`] arm — empty / non-DNS-1123 `:nome`, empty /
362 // unparseable `:versao` requirement, malformed `:fonte` repo /
363 // pin / `:caminho`, malformed `:caracteristicas` Cargo-feature
364 // name (de68c0c) — and then closes the per-list set-not-multiset
365 // duplicate-`:nome` invariant on each of `:deps` and `:deps-dev`
366 // (359fba5). Until this wire-up landed `validate_deps` existed as
367 // `pub fn` on [`Caixa`] with full per-arm unit coverage in
368 // `manifest::tests` + `dep::tests` (validate_deps_rejects_*,
369 // 53 dep-axis tests) but no production code path called it —
370 // `feira build` (the canonical author-time gate;
371 // `caixa-feira/src/cmd/build.rs:29` routes through
372 // `StandardLayout::verify`) silently accepted a malformed `:deps`
373 // entry and the failure surfaced at the *first* downstream
374 // consumer to strict-parse it: at lacre-resolve time as a
375 // `semver::Error` not naming the offending dep (`:versao` per-
376 // entry); at `git clone` time as a fetch failure quoting the
377 // shell-escape `repo` (`:fonte :repo`); at the resolver's
378 // `HashMap<:nome>` collapse as a silent "second-wins" overwrite
379 // (within-list `:nome` duplicate); at `cargo metadata` time as a
380 // feature-name rejection on the *target* caixa rather than the
381 // dep entry referencing it (`:caracteristicas`); at `helm
382 // install` / `kubectl apply` time as an apiserver `metadata.name`
383 // rejection on the rendered `lareira-<nome>` chart's per-dep
384 // derivation (DNS-1123-violating `:deps :nome`) — each far from
385 // the source `caixa.lisp`, none naming the offending `:deps` /
386 // `:deps-dev` axis. Runs *after* the Caixa-identity gates (the
387 // diagnostic carries `caixa.nome().to_string()` verbatim, which the
388 // peer [`Caixa::validate_nome`] gate above has just guaranteed is
389 // a valid DNS-1123 label) and *before* every kind-coherence gate
390 // (the dep surface is universal — every kind has `:deps` /
391 // `:deps-dev` — so its shape diagnostic is more fundamental than
392 // the kind-coherence partitions on `:bibliotecas` / `:exe` /
393 // `:servicos` / `:membros` / `:children` / M2 slots that follow).
394 // Same per-axis `*Violation { caixa, issue }` envelope every peer
395 // per-axis wrap exposes ([`LayoutError::NomeViolation`] /
396 // [`LayoutError::VersaoViolation`] (1f74a5f),
397 // [`LayoutError::CodePathViolation`] (b868442),
398 // [`LayoutError::LimitsViolation`] / [`LayoutError::BehaviorViolation`]
399 // / [`LayoutError::UpgradeViolation`] / [`LayoutError::SupervisorViolation`]
400 // / [`LayoutError::AplicacaoViolation`]). Threads [`DepError`]
401 // Display through verbatim — every per-arm reason already names
402 // the offending dep's `:nome` (e.g. `":deps entry "caixa-teia"
403 // :versao "^bad" is not a valid semver requirement: …"`), so the
404 // wrap envelope's `issue` carries a self-locating "which dep,
405 // which axis, why" without re-shaping the per-arm parser-side
406 // reason. With this wire-up the canonical author-time gate
407 // refuses every ill-formed `:deps` / `:deps-dev` value-shape by
408 // construction — closing the second-to-last orphan-validator gap
409 // on the typed Caixa surface (`validate_restart_window` is the
410 // remaining orphan, Supervisor-axis specific and wired into the
411 // Supervisor branch below alongside `view.validate()`).
412 // Compound per-Caixa entry gate on the dep-graph axis: the
413 // layout pipeline's two-dispatch `:deps` / `:deps-dev` cascade
414 // — the per-entry + within-list duplicate-`:nome` gate (the
415 // [`crate::Dep::validate`] + [`crate::render::insert_first_seen`]
416 // cascade `Caixa::validate_deps` opened on, 359fba5) and the
417 // cross-slot self-edge gate
418 // ([`crate::dep::validate_no_self_dep`], ad4abf1) — folded
419 // onto the [`crate::Caixa::validate_deps`] substrate primitive.
420 // The two arms run in the same canonical order at the primitive
421 // (per-entry + cross-entry duplicate → cross-slot self-edge) so
422 // the fold is byte-for-byte equivalent to the pre-fold
423 // two-block cascade this call site formerly carried, pinned by
424 // the paired
425 // `validate_deps_folds_{per_entry,self_edge}_arm_matches_gate`
426 // equivalence pins and the
427 // `validate_deps_per_entry_arm_fires_before_self_edge_arm`
428 // ordering pin in the [`crate::Caixa::validate_deps`] pin
429 // family (`manifest.rs`).
430 //
431 // Same lift discipline the peer per-slot compound gates
432 // ([`crate::AplicacaoSpec::validate_contratos`] and its
433 // `:membros` / `:entrada` / `:placement` / `:politicas` peers,
434 // [`crate::MeshPolicy::validate`],
435 // [`crate::SupervisorSpec::validate_children`],
436 // [`crate::Caixa::validate_upgrade_from`] d6801df) each carry —
437 // one named substrate-primitive gate per typed slot folds every
438 // structural + cross-slot axis on that slot onto one call, so
439 // every future consumer that wants to re-check the dep-graph
440 // after a per-entry patch (the deferred
441 // `caixa.pleme.io/v1alpha1/Caixa` CR materializer's admission
442 // webhook, a future `feira validate --deps` per-caixa admission
443 // verb, a per-`:deps` overlay resolver) reaches the two-arm
444 // compound gate through one dispatch rather than re-inlining
445 // the two-dispatch cascade in lockstep with this wire-up.
446 caixa.run_layout_gate(Caixa::validate_deps, LayoutError::deps_violation)?;
447
448 // `:etiquetas` per-entry empty + cross-entry duplicate gate. The
449 // fourth universal-axis Caixa-level value-shape gate (peer of
450 // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] /
451 // [`Caixa::validate_deps`] wired immediately above and
452 // [`Caixa::validate_code_paths`] wired below the kind-coherence
453 // gates) on the typed Caixa surface. `:etiquetas` is the
454 // registry-search-tag axis every kind carries (universal
455 // `Vec<String>` slot on [`Caixa`]) and lands verbatim as the
456 // Helm chart `Chart.yaml` `keywords:` array on every Servico
457 // (`caixa-helm/src/lib.rs:236` folds it through a
458 // [`std::collections::BTreeSet`]). Until this wire-up landed
459 // `:etiquetas` had no shape gate at any layer — an empty entry
460 // (`(:etiquetas (""))` — the canonical paste-from-blank-doc
461 // footgun) silently rendered as `keywords: [""]` in `Chart.yaml`,
462 // and duplicate entries (`(:etiquetas ("demo" "demo"))` — the
463 // copy-paste-the-wrong-tag footgun) were silently dedup'd by
464 // the renderer's `BTreeSet` collect — a "second wins / one
465 // silently disappears" shape divergent from every peer typed-
466 // graph set gate (`:membros :caixa`, `:placement :clusters`,
467 // `:entrada :paths`, `:contratos`, `:deps :nome`,
468 // `:upgrade-from :from`, the per-instruction-class singularity
469 // gates on `:upgrade-from :instructions`). Runs *after* the
470 // peer universal `:nome` / `:versao` / `:deps` gates (declaration
471 // order on [`Caixa`] is `:nome` → `:versao` → `:edicao` →
472 // `:descricao` → `:repositorio` → `:licenca` → `:autores` →
473 // `:etiquetas` → `:deps` → `:deps-dev`, but the gate order
474 // follows the same identity-axis-first cascade the peer gates
475 // establish: `:nome` → `:versao` are the load-bearing identity
476 // axes that flow into every diagnostic's caixa prefix, and
477 // `:deps` is the universal dep surface that dominates every
478 // kind-coherence gate; `:etiquetas` runs after this trio so the
479 // diagnostic carries an already-validated `:nome` and the
480 // peer universal axes' narrower diagnostics surface first when
481 // multiple axes are malformed) and *before* the kind-coherence
482 // gates ([`Self::MeshSlotsOnNonAplicacao`] /
483 // [`Self::SupervisorSlotsOnNonSupervisor`] /
484 // [`Self::ServicoSlotsOnNonServico`] / [`Self::ForeignCodeSlot`])
485 // — `:etiquetas` is universal so its shape diagnostic is more
486 // fundamental than the kind-coherence partitions on kind-
487 // exclusive slot sets.
488 //
489 // Same per-axis `*Violation { caixa, issue }` envelope every peer
490 // per-axis wrap exposes ([`Self::NomeViolation`] /
491 // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
492 // aa77d0f, [`Self::CodePathViolation`] b868442,
493 // [`Self::RestartWindowViolation`] 10e321a). Threads
494 // [`ManifestError::EtiquetaEmpty`] / [`ManifestError::EtiquetaDuplicate`]
495 // Display through verbatim — each per-arm reason already names
496 // the offending tag (for the duplicate arm) or the structural
497 // "empty entry" defect (for the empty arm), so the wrap
498 // envelope's `issue` carries a self-locating "which axis, which
499 // entry, why" without re-shaping the per-arm reason.
500 caixa.run_layout_gate(Caixa::validate_etiquetas, LayoutError::etiquetas_violation)?;
501
502 // `:autores` per-entry empty + cross-entry duplicate gate. The
503 // fifth universal-axis Caixa-level value-shape gate (peer of
504 // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] /
505 // [`Caixa::validate_deps`] / [`Caixa::validate_etiquetas`] wired
506 // immediately above and [`Caixa::validate_code_paths`] wired
507 // below the kind-coherence gates) on the typed Caixa surface.
508 // `:autores` is the maintainer-axis every kind carries
509 // (universal `Vec<String>` slot on [`Caixa`]) and lands verbatim
510 // as the Helm chart `Chart.yaml` `maintainers:` array on every
511 // Servico (`caixa-helm/src/lib.rs:251` maps each entry to a
512 // `Maintainer { name, email: None }` without dedup). Until this
513 // wire-up landed `:autores` had no shape gate at any layer — an
514 // empty entry (`(:autores (""))` — the canonical paste-from-
515 // blank-doc footgun) silently rendered as
516 // `maintainers: [{name: "", email: null}]` in `Chart.yaml`, and
517 // duplicate entries (`(:autores ("pleme-io" "pleme-io"))` —
518 // the copy-paste-the-wrong-author footgun) stacked verbatim in
519 // the chart. Unlike the peer `:etiquetas` axis (where the
520 // renderer's `BTreeSet` collect silently dedups the `keywords:`
521 // array at chart render — a "second wins / one silently
522 // disappears" shape), `maintainers:` has *no* renderer-side
523 // dedup, so duplicate `:autores` entries render as two identical
524 // maintainer records by construction — a strictly worse footgun
525 // than the peer `:etiquetas` shape. Runs *after* the peer
526 // universal `:nome` / `:versao` / `:deps` / `:etiquetas` gates
527 // (the gate order follows the canonical identity-axis-first
528 // cascade the peer gates establish; `:autores` and `:etiquetas`
529 // are the two Vec-shaped universal metadata axes — they sit
530 // adjacent in the cascade after the load-bearing identity +
531 // dep trio) and *before* the kind-coherence gates
532 // ([`Self::MeshSlotsOnNonAplicacao`] /
533 // [`Self::SupervisorSlotsOnNonSupervisor`] /
534 // [`Self::ServicoSlotsOnNonServico`] / [`Self::ForeignCodeSlot`])
535 // — `:autores` is universal so its shape diagnostic is more
536 // fundamental than the kind-coherence partitions on kind-
537 // exclusive slot sets.
538 //
539 // Same per-axis `*Violation { caixa, issue }` envelope every peer
540 // per-axis wrap exposes ([`Self::NomeViolation`] /
541 // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
542 // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
543 // [`Self::CodePathViolation`] b868442,
544 // [`Self::RestartWindowViolation`] 10e321a). Threads
545 // [`ManifestError::AutorEmpty`] / [`ManifestError::AutorDuplicate`]
546 // Display through verbatim — each per-arm reason already names
547 // the offending author (for the duplicate arm) or the structural
548 // "empty entry" defect (for the empty arm), so the wrap
549 // envelope's `issue` carries a self-locating "which axis, which
550 // entry, why" without re-shaping the per-arm reason.
551 caixa.run_layout_gate(Caixa::validate_autores, LayoutError::autores_violation)?;
552
553 // `:repositorio` git-repo-URL shape gate. The sixth
554 // universal-axis Caixa-level value-shape gate (peer of
555 // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] /
556 // [`Caixa::validate_deps`] / [`Caixa::validate_etiquetas`] /
557 // [`Caixa::validate_autores`] wired immediately above and
558 // [`Caixa::validate_code_paths`] wired below the kind-coherence
559 // gates) on the typed Caixa surface. `:repositorio` is the
560 // universal git-shaped homepage axis every kind carries
561 // (universal `Option<String>` slot on [`Caixa`]) and routes
562 // through two load-bearing substrate consumers:
563 // [`caixa-helm`] folds it verbatim into the rendered
564 // `lareira-<nome>` Helm chart's `Chart.yaml` `home:` field
565 // (`build_chart_yaml` at `caixa-helm/src/lib.rs:268`) and into
566 // the chart `README.md` `repo = …` interpolation
567 // (`caixa-helm/src/lib.rs:359`); [`caixa-flux`] folds it
568 // verbatim into the standalone `ClusterBundleOpts::for_caixa`
569 // `git_url:` field (`caixa-flux/src/lib.rs:293`), which
570 // becomes the FluxCD `GitRepository.spec.url` the cluster's
571 // source-controller polls — the load-bearing deploy-time axis.
572 // Both consumers use `Option::unwrap_or_else(|| <fallback>)`
573 // to substitute a placeholder when the slot is absent (`None`
574 // → the fallback fires); a `Some("")` *skips the fallback*
575 // and silently passes the empty string through to
576 // `Chart.yaml home: ""` / `GitRepository url: ""`. Until this
577 // wire-up landed `:repositorio` had no shape gate at any
578 // layer — empty (`(:repositorio "")` — the canonical
579 // paste-from-blank-doc footgun) and malformed (whitespace,
580 // control char / CRLF, leading `-` CLI-arg-injection,
581 // missing `:` separator) values silently landed in the
582 // rendered artifacts and broke at `helm template` / FluxCD
583 // reconcile time far from the source `caixa.lisp`.
584 //
585 // Runs *after* the peer universal `:nome` / `:versao` /
586 // `:deps` / `:etiquetas` / `:autores` gates (the gate order
587 // follows the canonical identity-axis-first cascade the peer
588 // gates establish; `:repositorio` is the universal git-URL
589 // axis — it sits adjacent to `:autores` in the cascade after
590 // the load-bearing identity + dep trio + the two Vec-shaped
591 // universal metadata axes) and *before* the kind-coherence
592 // gates ([`Self::MeshSlotsOnNonAplicacao`] /
593 // [`Self::SupervisorSlotsOnNonSupervisor`] /
594 // [`Self::ServicoSlotsOnNonServico`] / [`Self::ForeignCodeSlot`])
595 // — `:repositorio` is universal so its shape diagnostic is
596 // more fundamental than the kind-coherence partitions on
597 // kind-exclusive slot sets.
598 //
599 // Same per-axis `*Violation { caixa, issue }` envelope every
600 // peer per-axis wrap exposes ([`Self::NomeViolation`] /
601 // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
602 // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
603 // [`Self::AutoresViolation`] 86c769b, [`Self::CodePathViolation`]
604 // b868442, [`Self::RestartWindowViolation`] 10e321a). Threads
605 // [`ManifestError::RepositorioEmpty`] /
606 // [`ManifestError::RepositorioInvalid`] Display through
607 // verbatim — each per-arm reason already names the offending
608 // `:repositorio` value (for the invalid arm) or the
609 // structural "empty entry" defect (for the empty arm), so
610 // the wrap envelope's `issue` carries a self-locating "which
611 // axis, which value, why" without re-shaping the per-arm
612 // reason. With this gate the two `git URL`-shaped surfaces on
613 // the typed Caixa (`:repositorio` here, `:deps :fonte :repo`
614 // peer routed through the same shared
615 // [`crate::render::is_git_repo_url`] predicate via
616 // [`crate::DepSource::validate`]) are now structurally
617 // equivalent — every value past validate is
618 // guaranteed-acceptable by the shared predicate's constraint
619 // union, by construction.
620 caixa.run_layout_gate(
621 Caixa::validate_repositorio,
622 LayoutError::repositorio_violation,
623 )?;
624
625 // `:descricao` non-empty shape gate. The seventh universal-
626 // axis Caixa-level value-shape gate (peer of
627 // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] /
628 // [`Caixa::validate_deps`] / [`Caixa::validate_etiquetas`] /
629 // [`Caixa::validate_autores`] / [`Caixa::validate_repositorio`]
630 // wired immediately above and [`Caixa::validate_code_paths`]
631 // wired below the kind-coherence gates) on the typed Caixa
632 // surface. `:descricao` is the universal free-form-prose
633 // summary axis every kind carries (universal `Option<String>`
634 // slot on [`Caixa`]) and routes through two load-bearing
635 // [`caixa-helm`] consumers: `build_chart_yaml` folds it
636 // verbatim into the rendered `lareira-<nome>` Helm chart's
637 // `Chart.yaml` `description:` field
638 // (`caixa-helm/src/lib.rs:232-235`), and `build_readme` folds
639 // it verbatim into the chart `README.md` header
640 // (`caixa-helm/src/lib.rs:333-336`). Both consumers use
641 // `Option::unwrap_or_else(|| <fallback>)` to substitute a
642 // `caixa.nome`-derived placeholder when the slot is absent
643 // (`None` → the fallback fires); a `Some("")` *skips the
644 // fallback* and silently passes the empty string through to
645 // `Chart.yaml description: ""` / a blank `README.md` header
646 // — exact same footgun shape as the peer `:repositorio`
647 // surface above. Until this wire-up landed `:descricao` had
648 // no shape gate at any layer — the empty
649 // (`(:descricao "")` — the canonical paste-from-blank-doc
650 // footgun) silently landed in the rendered artifacts and
651 // broke at `helm lint` time (`WARNING [chart.metadata.description]:
652 // description is required` on `apiVersion: v2` charts) far
653 // from the source `caixa.lisp`.
654 //
655 // Runs *after* the peer universal `:nome` / `:versao` /
656 // `:deps` / `:etiquetas` / `:autores` / `:repositorio` gates
657 // (the gate order follows the canonical identity-axis-first
658 // cascade the peer gates establish; `:descricao` is the
659 // universal free-form-prose axis — it sits adjacent to
660 // `:repositorio` in the cascade after the load-bearing
661 // identity + dep trio + the two Vec-shaped universal
662 // metadata axes + the universal git-URL axis) and *before*
663 // the kind-coherence gates ([`Self::MeshSlotsOnNonAplicacao`]
664 // / [`Self::SupervisorSlotsOnNonSupervisor`] /
665 // [`Self::ServicoSlotsOnNonServico`] /
666 // [`Self::ForeignCodeSlot`]) — `:descricao` is universal so
667 // its shape diagnostic is more fundamental than the kind-
668 // coherence partitions on kind-exclusive slot sets.
669 //
670 // Same per-axis `*Violation { caixa, issue }` envelope every
671 // peer per-axis wrap exposes ([`Self::NomeViolation`] /
672 // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
673 // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
674 // [`Self::AutoresViolation`] 86c769b,
675 // [`Self::RepositorioViolation`] 577b0a9,
676 // [`Self::CodePathViolation`] b868442,
677 // [`Self::RestartWindowViolation`] 10e321a). Threads
678 // [`ManifestError::DescricaoEmpty`] Display through verbatim
679 // — the per-arm reason already names the offending
680 // `:descricao` slot + cites the renderer-side footgun, so
681 // the wrap envelope's `issue` carries a self-locating
682 // "which axis, why" without re-shaping the per-arm reason.
683 caixa.run_layout_gate(Caixa::validate_descricao, LayoutError::descricao_violation)?;
684
685 // `:licenca` non-empty shape gate. The eighth universal-axis
686 // Caixa-level value-shape gate (peer of [`Caixa::validate_nome`]
687 // / [`Caixa::validate_versao`] / [`Caixa::validate_deps`] /
688 // [`Caixa::validate_etiquetas`] / [`Caixa::validate_autores`] /
689 // [`Caixa::validate_repositorio`] / [`Caixa::validate_descricao`]
690 // wired immediately above and [`Caixa::validate_code_paths`]
691 // wired below the kind-coherence gates) on the typed Caixa
692 // surface. `:licenca` is the universal SPDX-shaped license-
693 // expression axis every kind carries (universal `Option<String>`
694 // slot on [`Caixa`]) and routes through one load-bearing
695 // [`caixa-helm`] consumer: `build_readme` folds it verbatim into
696 // the rendered `lareira-<nome>` Helm chart's `README.md` `##
697 // License` section (`caixa-helm/src/lib.rs:361`) via
698 // `caixa.licenca.clone().unwrap_or_else(|| "MIT".into())`. The
699 // consumer's fallback only fires when the slot is absent (`None`
700 // → the `MIT` fallback fires); a `Some("")` *skips the
701 // fallback* and silently passes the empty string through to a
702 // chart `README.md` whose `License` section renders as a bare
703 // trailing period — exact same footgun shape as the peer
704 // `:repositorio` (577b0a9) and `:descricao` (4e6db38) surfaces
705 // above. Until this wire-up landed `:licenca` had no shape
706 // gate at any layer — the empty (`(:licenca "")` — the
707 // canonical paste-from-blank-doc footgun) silently landed in
708 // the rendered chart `README.md` far from the source
709 // `caixa.lisp`.
710 //
711 // Runs *after* the peer universal `:nome` / `:versao` /
712 // `:deps` / `:etiquetas` / `:autores` / `:repositorio` /
713 // `:descricao` gates (the gate order follows the canonical
714 // identity-axis-first cascade the peer gates establish;
715 // `:licenca` sits adjacent to `:descricao` in the cascade
716 // after the load-bearing identity + dep trio + the two
717 // Vec-shaped universal metadata axes + the universal
718 // git-URL + free-form-prose axes) and *before* the kind-
719 // coherence gates ([`Self::MeshSlotsOnNonAplicacao`] /
720 // [`Self::SupervisorSlotsOnNonSupervisor`] /
721 // [`Self::ServicoSlotsOnNonServico`] /
722 // [`Self::ForeignCodeSlot`]) — `:licenca` is universal so
723 // its shape diagnostic is more fundamental than the kind-
724 // coherence partitions on kind-exclusive slot sets.
725 //
726 // Same per-axis `*Violation { caixa, issue }` envelope every
727 // peer per-axis wrap exposes ([`Self::NomeViolation`] /
728 // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
729 // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
730 // [`Self::AutoresViolation`] 86c769b,
731 // [`Self::RepositorioViolation`] 577b0a9,
732 // [`Self::DescricaoViolation`] 4e6db38,
733 // [`Self::CodePathViolation`] b868442,
734 // [`Self::RestartWindowViolation`] 10e321a). Threads
735 // [`ManifestError::LicencaEmpty`] Display through verbatim
736 // — the per-arm reason already names the offending
737 // `:licenca` slot + cites the renderer-side footgun, so
738 // the wrap envelope's `issue` carries a self-locating
739 // "which axis, why" without re-shaping the per-arm reason.
740 caixa.run_layout_gate(Caixa::validate_licenca, LayoutError::licenca_violation)?;
741
742 // `:edicao` non-empty shape gate. The ninth (and last
743 // un-gated) universal-axis Caixa-level value-shape gate
744 // (peer of [`Caixa::validate_nome`] / [`Caixa::validate_versao`]
745 // / [`Caixa::validate_deps`] / [`Caixa::validate_etiquetas`] /
746 // [`Caixa::validate_autores`] / [`Caixa::validate_repositorio`]
747 // / [`Caixa::validate_descricao`] / [`Caixa::validate_licenca`]
748 // wired immediately above and [`Caixa::validate_code_paths`]
749 // wired below the kind-coherence gates) on the typed Caixa
750 // surface. `:edicao` is the universal language-edition axis
751 // every kind carries (universal `Option<String>` slot on
752 // [`Caixa`]) that selects the tatara-lisp macro surface +
753 // compatibility flags the substrate applies when building
754 // the caixa. The canonical [`Caixa::template`] scaffold every
755 // `feira init` emits carries `:edicao "2026"` verbatim
756 // (`caixa-core/src/manifest.rs:1193`) and every renderer-side
757 // fixture carries `edicao: Some("2026".into())` by
758 // construction (`caixa-helm/src/lib.rs:375`,
759 // `caixa-flux/src/lib.rs:445`, `caixa-mesh/src/lib.rs:629`,
760 // `caixa-core/src/render.rs:2510`). Until this wire-up landed
761 // `:edicao` had no shape gate at any layer — the empty
762 // (`(:edicao "")` — the canonical paste-from-blank-doc
763 // footgun) silently landed as a bare `(:edicao "")` line
764 // in the rendered caixa.lisp and a future renderer-side
765 // consumer that folds the value through
766 // `Option::unwrap_or_else` would skip its fallback (which
767 // only fires on `None`) and pass the empty edition through
768 // to the substrate's build-time edition selector far from
769 // the source `caixa.lisp` — exact same
770 // `Some("")`-skips-`unwrap_or_else` footgun shape as the
771 // peer `:repositorio` (577b0a9), `:descricao` (4e6db38),
772 // and `:licenca` (3d1e535) surfaces above.
773 //
774 // Runs *after* the peer universal `:nome` / `:versao` /
775 // `:deps` / `:etiquetas` / `:autores` / `:repositorio` /
776 // `:descricao` / `:licenca` gates (the gate order follows
777 // the canonical identity-axis-first cascade the peer gates
778 // establish; `:edicao` sits at the tail of the cascade
779 // after the load-bearing identity + dep trio + the two
780 // Vec-shaped universal metadata axes + the three universal
781 // `Option<String>` chart-metadata axes) and *before* the
782 // kind-coherence gates ([`Self::MeshSlotsOnNonAplicacao`] /
783 // [`Self::SupervisorSlotsOnNonSupervisor`] /
784 // [`Self::ServicoSlotsOnNonServico`] /
785 // [`Self::ForeignCodeSlot`]) — `:edicao` is universal so
786 // its shape diagnostic is more fundamental than the kind-
787 // coherence partitions on kind-exclusive slot sets.
788 //
789 // Same per-axis `*Violation { caixa, issue }` envelope every
790 // peer per-axis wrap exposes ([`Self::NomeViolation`] /
791 // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
792 // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
793 // [`Self::AutoresViolation`] 86c769b,
794 // [`Self::RepositorioViolation`] 577b0a9,
795 // [`Self::DescricaoViolation`] 4e6db38,
796 // [`Self::LicencaViolation`] 3d1e535,
797 // [`Self::CodePathViolation`] b868442,
798 // [`Self::RestartWindowViolation`] 10e321a). Threads
799 // [`ManifestError::EdicaoEmpty`] Display through verbatim
800 // — the per-arm reason already names the offending
801 // `:edicao` slot + cites the renderer-side footgun, so
802 // the wrap envelope's `issue` carries a self-locating
803 // "which axis, why" without re-shaping the per-arm reason.
804 // With this gate every universal-axis `Option<String>`
805 // surface on the typed Caixa (`:repositorio` 577b0a9,
806 // `:descricao` 4e6db38, `:licenca` 3d1e535, `:edicao` here)
807 // now carries the same structural empty-arm gate by
808 // construction.
809 caixa.run_layout_gate(Caixa::validate_edicao, LayoutError::edicao_violation)?;
810
811 // Kind ↔ code-surface coherence on the three no-code kinds
812 // (Supervisor / Aplicacao / Acao) — folded onto one substrate
813 // primitive at [`crate::Caixa::validate_no_code_kind_coherence`].
814 // Pre-lift each of the three arms lived as a self-similar
815 // `if caixa.kind().is_<no-code-kind>() && has_code { return
816 // Err(LayoutError::<kind>_owns_code(caixa)); }` block at this
817 // call site — three consumers, three identical shapes, one
818 // substrate primitive on [`Caixa`] closing the duplication the
819 // PRIME DIRECTIVE names as a bug. Mirror of the sibling
820 // [`crate::Caixa::validate_kind_slot_coherence`] fold f0d286e
821 // on the author-time typed-slot coherence axis: this wire-up
822 // closes the same three-arm cascade on the reciprocal
823 // code-surface axis, so the layout pipeline now routes both
824 // "no-code kind declares typed slots" and "no-code kind
825 // declares code" author-time footgun families through one
826 // substrate primitive per axis rather than six open-coded
827 // blocks. Each of the three inner ctors
828 // ([`crate::LayoutError::supervisor_owns_code`] /
829 // [`crate::LayoutError::aplicacao_owns_code`] /
830 // [`crate::LayoutError::acao_owns_code`]) was already lifted
831 // onto the substrate by the peer [`layout_nome_only_ctors!`]
832 // macro, so the primitive routes through the same
833 // `Self::<variant>(caixa.nome().to_string())` tuple-literal
834 // wrap per arm as the pre-lift open-coded blocks. Runs
835 // BEFORE the path-existence loops below so a no-code kind
836 // that declares code surfaces the self-locating OwnsCode
837 // diagnostic naming the offending kind rather than a
838 // downstream `MissingEntry` / `ExeOutsideDir` /
839 // `ServicoOutsideDir` against the resolved path far from the
840 // source `caixa.lisp`.
841 caixa.validate_no_code_kind_coherence()?;
842
843 // Kind ↔ typed-slot coherence on the M3 mesh / supervisor-tree /
844 // M2 Servico-runtime slot families — folded onto one substrate
845 // primitive at [`crate::Caixa::validate_kind_slot_coherence`].
846 // Pre-lift each of the three arms lived as a self-similar
847 // five-line `if !caixa.kind().is_<owner>() { let slots =
848 // caixa.declared_<family>_slots(); if !slots.is_empty() { return
849 // Err(LayoutError::<family>_on_non_<owner>(caixa, slots)); } }`
850 // block at this call site — three consumers, three identical
851 // shapes, one substrate primitive on [`Caixa`] closing the
852 // duplication the PRIME DIRECTIVE names as a bug. The primitive
853 // preserves the pre-fold canonical diagnostic order — mesh →
854 // supervisor → servico — pinned by the load-bearing
855 // `validate_kind_slot_coherence_mesh_arm_fires_before_supervisor_arm`
856 // / `_supervisor_arm_fires_before_servico_arm` ordering pins at
857 // caixa-core/src/manifest.rs, so this wire-up is byte-for-byte
858 // equivalent to the pre-fold three-block cascade on every fixture
859 // exercising any of the three arms. Peer with the per-slot
860 // compound entry gates the substrate already carries
861 // ([`crate::Caixa::validate_deps`] b5dd55e,
862 // [`crate::Caixa::validate_limits`] baa4688,
863 // [`crate::Caixa::validate_behavior`] 0d2877a,
864 // [`crate::Caixa::validate_upgrade_from`] d6801df,
865 // [`crate::Caixa::validate_aplicacao_shape`] 949a7a0,
866 // [`crate::Caixa::validate_supervisor_shape`] 4c70105,
867 // [`crate::Caixa::validate_acao_shape`] 5d6df54) — the
868 // author-time gate axis on the per-slot algebra now shares one
869 // substrate primitive per compound gate, and this lift closes
870 // the symmetric axis on the cross-family kind ↔ slot coherence
871 // algebra so the layout pipeline routes the three self-similar
872 // gates through one substrate primitive rather than three
873 // open-coded blocks. The sibling
874 // [`LayoutError::ForeignCodeSlot`] (code-surface family) and
875 // [`LayoutError::CiOnNonAcao`] (`:ci` axis) gates stay
876 // open-coded downstream: the former bakes the kind-check into
877 // its declared_*_slots helper by design (so it carries no outer
878 // `if !kind().is_<owner>()` guard), the latter carries a
879 // distinct `{ caixa, kind }` wrap shape (no `slots` field —
880 // `:ci` is a single `Option`, not a `Vec`-of-named-slots) whose
881 // reshape onto the uniform `{ caixa, kind, slots }` envelope a
882 // future symmetry lift can join here.
883 caixa.validate_kind_slot_coherence()?;
884
885 // Kind ↔ `:ci` coherence (mirror of the three arms above on
886 // the M3 mesh / supervisor-tree / M2 Servico-runtime slot
887 // families, CANTEIRO §7.1-C, folded onto one substrate
888 // primitive at [`crate::Caixa::validate_ci_kind_coherence`]):
889 // `:ci` carries a typed CI run — a
890 // [`canteiro_types::CiRun`] — that only the caixa-actions
891 // renderer decomposes + validates, and only for a `:kind
892 // Acao`. On any *other* kind a declared `:ci` is the
893 // manifest field's documented "ignored otherwise": it
894 // silently passes verify and then vanishes (never
895 // decomposed, never rendered), far from the source
896 // `caixa.lisp`. Pre-lift the arm lived as a self-similar
897 // `if caixa.ci().is_some() && !caixa.kind().is_acao() { …
898 // return Err(LayoutError::CiOnNonAcao { … }); }` block at
899 // this call site — one consumer today but every future
900 // consumer that wanted to gate this coherence axis as a
901 // unit was structurally forced to re-inline the two-
902 // condition guard in lockstep with this wire-up (the
903 // duplication the PRIME DIRECTIVE names as a bug).
904 // Post-fold the arm reads through one call, and the
905 // [`crate::LayoutError::CiOnNonAcao`] envelope (with its
906 // distinct `{ caixa, kind }` wrap shape — no `slots`
907 // field, because `:ci` is a single `Option` not a `Vec`-
908 // of-named-slots) surfaces byte-for-byte equivalent to the
909 // pre-fold open-coded block, pinned by the paired
910 // `validate_ci_kind_coherence_folds_arm_matches_gate`
911 // per-arm equivalence pin and the
912 // `validate_ci_kind_coherence_accepts_acao_on_every_ci_shape`
913 // /
914 // `validate_ci_kind_coherence_accepts_absent_ci_on_every_kind`
915 // identity-element pins in the
916 // [`crate::Caixa::validate_ci_kind_coherence`] pin family
917 // (`manifest.rs`). Peer to the sibling three-arm
918 // [`crate::Caixa::validate_kind_slot_coherence`] fold
919 // f0d286e: that primitive carries the M3 / supervisor-tree
920 // / M2 axes under a uniform `{ caixa, kind, slots }`
921 // envelope, this primitive carries the `:ci` axis under
922 // its distinct `{ caixa, kind }` envelope, and every
923 // author-time kind ↔ slot coherence diagnostic at the
924 // layout altitude now routes through one substrate
925 // primitive per envelope shape rather than an open-coded
926 // block.
927 caixa.validate_ci_kind_coherence()?;
928
929 // Kind ↔ slot coherence on the fourth and final axis — the
930 // code-surface slot set (the trio M2/Supervisor/Aplicacao gates
931 // above close on the M2 runtime, supervisor-tree, and M3 mesh
932 // axes; this gate closes the symmetric "kind owns this code
933 // shape" relation on `:exe` + `:servicos`). `:exe` is the nix-
934 // built executable surface owned only by Binario; `:servicos`
935 // is the wasm-component daemon surface owned only by Servico.
936 // The caixa-helm / caixa-flux / caixa-flake renderers gate on
937 // `require_kind(_, <owning-kind>)` and only emit the slot for
938 // its owning kind — so on any *other* code-running kind a
939 // declared `:exe` / `:servicos` is the manifest field's
940 // documented "ignored otherwise" (see the field docs on
941 // `Caixa::exe` + `Caixa::servicos`): the path is validated by
942 // the per-kind path-existence loops below, but the value is
943 // never rendered into a build target or programs.yaml entry —
944 // it silently passes `feira build` and then vanishes, far from
945 // the source caixa.lisp.
946 //
947 // Reject it here — beside the M2/Supervisor/Aplicacao slot
948 // gates, after the `SupervisorOwnsCode` / `AplicacaoOwnsCode`
949 // OwnCode gates which dominate on those two no-code kinds (a
950 // Supervisor / Aplicacao with any of `:bibliotecas` / `:exe` /
951 // `:servicos` surfaces the OwnCode diagnostic first), and
952 // before the path-existence loops which would otherwise spend
953 // a less-helpful `MissingEntry` diagnostic on the foreign
954 // slot's path. `declared_foreign_code_slots` is the single
955 // typed source of the foreign-code-slot set + its canonical
956 // diagnostic order (`:exe` → `:servicos`).
957 //
958 // Mirrors the 9d37f98 / 510c00a / 760a430 kind ↔ slot
959 // coherence trio's "declared-but-inert" footgun closure on the
960 // M2 / supervisor-tree / M3 axes, now extended onto the code-
961 // surface axis — every code-running kind's exclusive code
962 // surface is structurally fenced from every other code-running
963 // kind. `:bibliotecas` is deliberately excluded from the foreign
964 // set on Binario / Servico (a `lib/` helper bundled into the
965 // nix flake's build or the wasm-component's source tree is a
966 // legitimate cross-kind authoring shape); on Biblioteca it is
967 // the native slot, and on Supervisor / Aplicacao the OwnCode
968 // gates above already close it.
969 //
970 // Folded onto [`crate::Caixa::validate_foreign_code_kind_coherence`]
971 // — the fourth and last kind ↔ slot coherence primitive on the
972 // typed [`Caixa`] surface, peer of
973 // [`crate::Caixa::validate_kind_slot_coherence`] (f0d286e,
974 // the cross-family M3/supervisor/M2 fold on the sibling
975 // `{ caixa, kind, slots }` envelope),
976 // [`crate::Caixa::validate_no_code_kind_coherence`] (3bbf6a2,
977 // the reciprocal no-code-kind fold on `SupervisorOwnsCode` /
978 // `AplicacaoOwnsCode` / `AcaoOwnsCode`), and
979 // [`crate::Caixa::validate_ci_kind_coherence`] (9b55beb, the
980 // `:ci` axis fold on the `{ caixa, kind }` envelope). With
981 // this lift every kind-coherence axis at the layout altitude
982 // routes through one substrate primitive per axis rather than
983 // an open-coded block, closing the last open-coded gap the
984 // sibling [`crate::Caixa::validate_kind_slot_coherence`]
985 // doc-comment's "ForeignCodeSlot … stays open-coded downstream"
986 // note flagged.
987 caixa.validate_foreign_code_kind_coherence()?;
988
989 // Per-entry path-shape gate on the three Caixa-level code-surface
990 // path lists (`:bibliotecas`, `:exe`, `:servicos`): each entry must
991 // be non-empty, relative, and free of `..` components — the same
992 // [`crate::render::is_sandboxed_relative_path`] discipline the
993 // peer `:behavior :on-*` (b0c8389) and
994 // `:upgrade-from :state-change :script` (26da2c7) axes already
995 // route through. Runs *after* the kind-coherence gates above (so
996 // a `:exe` on a Servico surfaces ForeignCodeSlot rather than a
997 // per-entry shape diagnostic, and a Supervisor/Aplicacao with any
998 // code surface surfaces OwnCode first) and *before* the existence
999 // loops below (so an empty / absolute / parent-escaping entry
1000 // surfaces its self-locating per-slot diagnostic rather than a
1001 // downstream `MissingEntry` / `ExeOutsideDir` /
1002 // `ServicoOutsideDir` against the resolved sandbox-escape path).
1003 caixa.run_layout_gate(Caixa::validate_code_paths, LayoutError::code_path_violation)?;
1004
1005 if caixa.kind().requires_lib() && caixa.bibliotecas().is_empty() {
1006 let expected = root
1007 .join(crate::render::LAYOUT_DIR_LIB)
1008 .join(format!("{}.lisp", caixa.nome()));
1009 if !self.exists(&expected) {
1010 return Err(LayoutError::missing_lib(caixa, expected));
1011 }
1012 }
1013
1014 // Required-slot gate on the three [`CaixaKind`] arms whose
1015 // sole payload is a canonical typed slot — folded onto one
1016 // substrate primitive at
1017 // [`crate::Caixa::validate_required_kind_slot`]. Pre-lift each
1018 // of the three arms lived as a self-similar
1019 // `if caixa.kind().requires_<slot>() && caixa.<slot>().is_<empty>() {
1020 // return Err(LayoutError::<kind>_without_<slot>(caixa)); }` block
1021 // at this call site — three consumers, three identical shapes,
1022 // one substrate primitive on [`Caixa`] closing the duplication
1023 // the PRIME DIRECTIVE names as a bug. Diagnostic order at the
1024 // primitive matches the pre-fold canonical sequence — `:exe` →
1025 // `:servicos` → `:ci` — the same three-arm sweep the peer
1026 // [`CaixaKind`] discriminator carries at its `requires_*`
1027 // accessors; the three arms are mutually exclusive by
1028 // construction (`:kind` is a single-valued discriminator so at
1029 // most one arm can fire per caixa) so no cross-arm ordering
1030 // pin is meaningful.
1031 //
1032 // The paired `Biblioteca`-arm required-slot check
1033 // ([`LayoutError::MissingLib`], immediately above) stays
1034 // open-coded at this altitude by design: it needs the
1035 // [`LayoutInvariants::exists`] filesystem oracle to check the
1036 // default `lib/<nome>.lisp` fallback path, which the pure
1037 // per-`Caixa` typed-shape surface the fold rides on has no
1038 // reference to. Same posture the peer
1039 // [`crate::Caixa::validate_no_code_kind_coherence`] fold
1040 // (3bbf6a2) takes on the on-disk existence loops.
1041 //
1042 // Peer with the per-slot and per-kind compound entry gates
1043 // every substrate primitive on the M2/M3 typed-slot family
1044 // already carries ([`crate::Caixa::validate_deps`] b5dd55e,
1045 // [`crate::Caixa::validate_limits`] baa4688,
1046 // [`crate::Caixa::validate_behavior`] 0d2877a,
1047 // [`crate::Caixa::validate_upgrade_from`] d6801df,
1048 // [`crate::Caixa::validate_aplicacao_shape`] 949a7a0,
1049 // [`crate::Caixa::validate_supervisor_shape`] 4c70105,
1050 // [`crate::Caixa::validate_acao_shape`] 5d6df54,
1051 // [`crate::Caixa::validate_kind_slot_coherence`] f0d286e,
1052 // [`crate::Caixa::validate_no_code_kind_coherence`] 3bbf6a2,
1053 // [`crate::Caixa::validate_ci_kind_coherence`] 9b55beb): the
1054 // layout pipeline routes the three self-similar required-slot
1055 // gates through one substrate primitive rather than three
1056 // open-coded blocks, and every future required-slot arm (a
1057 // per-Aplicacao required-`:membros` gate, a per-Supervisor
1058 // required-`:children` gate — both already carried at
1059 // [`CaixaKind::requires_membros`] / [`CaixaKind::requires_children`]
1060 // without a paired layout-side wire-up) folds onto this
1061 // compound gate as one arm addition rather than a fourth
1062 // open-coded block at the wire-up site.
1063 caixa.validate_required_kind_slot()?;
1064
1065 // On-disk existence probe on the three Caixa-level code-surface
1066 // path lists (`:bibliotecas`, `:exe`, `:servicos`): every declared
1067 // entry must resolve on disk. The `:bibliotecas` sweep folds onto
1068 // the [`Self::probe_declared_entries`] per-slot batch primitive
1069 // so the iteration + per-iteration `probe_declared_entry`
1070 // dispatch reads through one call rather than a three-line
1071 // `for … { self.probe_declared_entry(…)?; }` loop kept in
1072 // lockstep with the peer `:behavior` / `:upgrade-from` batch
1073 // wire-ups below. The `:exe` / `:servicos` peers fold onto the
1074 // sibling [`Self::probe_sandboxed_declared_entries`] per-slot
1075 // batch primitive on the sandboxed axis so the iteration +
1076 // per-iteration `probe_sandboxed_declared_entry` dispatch reads
1077 // through one call rather than a three-line `for … { self.
1078 // probe_sandboxed_declared_entry(…)?; }` loop kept in lockstep
1079 // with each other and with the peer `:bibliotecas` bare-batch
1080 // wire-up above. All three preserve the pre-lift diagnostic
1081 // order: `MissingEntry` fires before `ExeOutsideDir` /
1082 // `ServicoOutsideDir` on the same iteration, and iteration
1083 // proceeds in the caller-supplied iterator order (short-
1084 // circuiting on the first miss).
1085 self.probe_declared_entries(
1086 caixa.bibliotecas(),
1087 root,
1088 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
1089 )?;
1090
1091 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
1092 self.probe_sandboxed_declared_entries(
1093 caixa.exe(),
1094 root,
1095 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
1096 &exe_dir,
1097 LayoutError::ExeOutsideDir,
1098 )?;
1099
1100 let servicos_dir = root.join(crate::render::LAYOUT_DIR_SERVICOS);
1101 self.probe_sandboxed_declared_entries(
1102 caixa.servicos(),
1103 root,
1104 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
1105 &servicos_dir,
1106 LayoutError::ServicoOutsideDir,
1107 )?;
1108
1109 // ── M2 typed-substrate invariants ────────────────────────────────
1110
1111 // Compound per-Caixa entry gate on the M2 `:limits` slot: the
1112 // layout pipeline's `if let Some(l) = caixa.limits() { l.validate() }`
1113 // `Option::None → Ok(()) | Some(_) → dispatch` unwrap-and-
1114 // dispatch pattern — the four-axis cascade on the present-slot
1115 // arm ([`crate::LimitsSpec::validate`]'s `:memory` wasm32
1116 // zero-floor / below-page / above-cap / non-page-multiple;
1117 // `:fuel` zero-floor / cap; `:wall-clock` zero-floor / cap;
1118 // `:cpu` zero-floor / cap) folded onto the
1119 // [`crate::Caixa::validate_limits`] substrate primitive. The
1120 // absent-slot arm (`limits: None`, the canonical "no bound
1121 // declared — engine-default applies" author shape) is the
1122 // fold's identity element and passes trivially through the
1123 // primitive, byte-equal to the pre-lift `if let Some(l) = …`
1124 // guard this call site formerly carried. Pinned by the paired
1125 // `validate_limits_folds_arm_matches_gate` equivalence pin and
1126 // the `validate_limits_accepts_none` / `_accepts_clean_fixture`
1127 // positive-control pins in the [`crate::Caixa::validate_limits`]
1128 // pin family (`manifest.rs`).
1129 //
1130 // Same lift discipline the peer per-Caixa compound gates
1131 // ([`crate::Caixa::validate_upgrade_from`] d6801df,
1132 // [`crate::Caixa::validate_deps`] b5dd55e) each carry — one
1133 // named substrate-primitive gate per typed slot folds every
1134 // structural axis on that slot (plus the `Option::None`
1135 // identity element for the `Option`-shaped slots) onto one
1136 // call, so every future consumer that wants to re-check
1137 // `:limits` after a per-`{:memory, :fuel, :wall-clock, :cpu}`
1138 // patch (the deferred `caixa.pleme.io/v1alpha1/Caixa` CR
1139 // materializer's admission webhook, a future `feira validate
1140 // --limits` per-caixa admission verb, a per-`:limits` overlay
1141 // resolver) reaches the four-axis cascade through one dispatch
1142 // rather than re-inlining the `if let Some(l) = …` unwrap-and-
1143 // dispatch pattern in lockstep with this wire-up.
1144 caixa.run_layout_gate(Caixa::validate_limits, LayoutError::limits_violation)?;
1145
1146 // Compound per-Caixa entry gate on the M2 `:behavior` slot's
1147 // pure value-shape surface: the layout pipeline's
1148 // `if let Some(b) = caixa.behavior() { b.validate() }`
1149 // `Option::None → Ok(()) | Some(_) → dispatch` unwrap-and-
1150 // dispatch pattern — the six-slot value-shape cascade on the
1151 // present-slot arm ([`crate::BehaviorSpec::validate`]'s per-
1152 // `:on-init` / `:on-call` / `:on-cast` / `:on-info` /
1153 // `:on-state-change` / `:on-terminate` non-empty / relative /
1154 // no-`..`-parent-escape / terminating-`.lisp`-extension
1155 // arm-set routed through the shared
1156 // [`crate::render::require_sandboxed_lisp_path`] helper) —
1157 // folded onto the [`crate::Caixa::validate_behavior`] substrate
1158 // primitive. The absent-slot arm (`behavior: None`, the
1159 // canonical "no callback declared — the runtime falls back to
1160 // the wasm-engine's default per arm" author shape) is the
1161 // fold's identity element and passes trivially through the
1162 // primitive, byte-equal to the pre-lift `if let Some(b) = …`
1163 // guard this call site formerly carried. Pinned by the paired
1164 // `validate_behavior_folds_arm_matches_gate` equivalence pin
1165 // and the `validate_behavior_accepts_none` /
1166 // `_accepts_clean_fixture` positive-control pins in the
1167 // [`crate::Caixa::validate_behavior`] pin family
1168 // (`manifest.rs`).
1169 //
1170 // The value-shape gate runs BEFORE the on-disk callback-path
1171 // existence walk below so a malformed `:behavior` slot
1172 // surfaces its self-locating per-slot diagnostic (naming the
1173 // offending `:on-*` slot) rather than the less-helpful
1174 // "missing behavior-callback" the existence probe would raise
1175 // against the resolved sandbox-escape path.
1176 //
1177 // Same lift discipline the peer per-Caixa compound gates
1178 // ([`crate::Caixa::validate_limits`] baa4688,
1179 // [`crate::Caixa::validate_upgrade_from`] d6801df,
1180 // [`crate::Caixa::validate_deps`] b5dd55e) each carry — one
1181 // named substrate-primitive gate per typed slot folds every
1182 // structural axis on that slot (plus the `Option::None`
1183 // identity element for the `Option`-shaped slots) onto one
1184 // call, so every future consumer that wants to re-check
1185 // `:behavior` after a per-`{:on-init, …, :on-terminate}`
1186 // patch (the deferred `caixa.pleme.io/v1alpha1/Caixa` CR
1187 // materializer's admission webhook, a future `feira validate
1188 // --behavior` per-caixa admission verb, a per-`:behavior`
1189 // overlay resolver) reaches the six-slot cascade through one
1190 // dispatch rather than re-inlining the `if let Some(b) = …`
1191 // unwrap-and-dispatch pattern in lockstep with this wire-up.
1192 // The paired on-disk existence walk stays open-coded at this
1193 // altitude because it needs the [`LayoutInvariants::exists`]
1194 // filesystem oracle the pure typed-shape surface has no
1195 // reference to — mirror of the peer M2 `:upgrade-from` per-
1196 // instruction script-path existence probe that stayed at this
1197 // altitude after the [`crate::Caixa::validate_upgrade_from`]
1198 // lift for the same reason.
1199 caixa.run_layout_gate(Caixa::validate_behavior, LayoutError::behavior_violation)?;
1200 if let Some(b) = caixa.behavior() {
1201 self.probe_declared_entries(
1202 b.declared_paths(),
1203 root,
1204 crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
1205 )?;
1206 }
1207
1208 // Compound per-Caixa entry gate on `:upgrade-from`: the layout
1209 // pipeline's three-dispatch M2 `:upgrade-from` cascade — the
1210 // per-entry shape + cross-entry duplicate-`:from` gate
1211 // ([`crate::upgrade::validate_upgrade_from`]), the cross-slot
1212 // `:from < :versao` SemVer-2 precedence gate
1213 // ([`crate::upgrade::validate_upgrade_from_against_versao`]), and
1214 // the cross-slot `:state-change` ↔ `:on-state-change` composition
1215 // gate ([`crate::upgrade::validate_upgrade_from_against_behavior`])
1216 // — folded onto the [`crate::Caixa::validate_upgrade_from`]
1217 // substrate primitive. The three dispatches run in the same
1218 // canonical order at the primitive (per-entry → versao → behavior)
1219 // so the fold is byte-for-byte equivalent to the pre-fold
1220 // three-block cascade this call site formerly carried, pinned by
1221 // the paired
1222 // `validate_upgrade_from_folds_{per_entry,versao,behavior}_arm_matches_gate`
1223 // equivalence pins and the
1224 // `validate_upgrade_from_{per_entry_arm_fires_before_versao_arm,
1225 // versao_arm_fires_before_behavior_arm}` ordering pins in the
1226 // [`crate::Caixa::validate_upgrade_from`] pin family
1227 // (`manifest.rs`).
1228 //
1229 // Runs BEFORE the existing per-instruction script-path existence
1230 // pass below so a malformed typed slot surfaces its own
1231 // self-locating diagnostic rather than the less-helpful "missing
1232 // upgrade-script" (which doesn't fire for non-script axes at all).
1233 // Same lift discipline the peer per-slot compound gates
1234 // ([`crate::AplicacaoSpec::validate_contratos`] and its
1235 // `:membros` / `:entrada` / `:placement` / `:politicas` peers,
1236 // [`crate::MeshPolicy::validate`],
1237 // [`crate::SupervisorSpec::validate_children`]) each carry — one
1238 // named substrate-primitive gate per typed slot folds every
1239 // structural axis on that slot onto one call, so every future
1240 // consumer that wants to re-check `:upgrade-from` after a
1241 // per-entry patch (the deferred `caixa.pleme.io/v1alpha1/Caixa`
1242 // CR materializer's admission webhook, a future `feira validate
1243 // --upgrade` per-caixa admission verb, a per-`:upgrade-from`
1244 // overlay resolver) reaches the three-arm compound gate through
1245 // one dispatch rather than re-inlining the three-dispatch
1246 // cascade in lockstep with this wire-up.
1247 //
1248 // The per-instruction on-disk existence-probe walk below stays
1249 // open-coded at the layout wire-up site — that arm needs the
1250 // filesystem oracle on the [`LayoutInvariants`] trait, not on
1251 // the pure per-Caixa typed-shape surface the compound gate
1252 // folds. Same posture [`crate::Caixa::validate_code_paths`] takes
1253 // on the sibling code-path axes: the typed-shape gate fires on
1254 // the per-Caixa surface, the on-disk existence check fires on
1255 // the [`StandardLayout`] surface.
1256 caixa.run_layout_gate(Caixa::validate_upgrade_from, LayoutError::upgrade_violation)?;
1257 self.probe_declared_entries(
1258 caixa
1259 .upgrade_from()
1260 .iter()
1261 .flat_map(crate::UpgradeFromEntry::instructions)
1262 .filter_map(crate::upgrade::UpgradeInstruction::declared_path),
1263 root,
1264 crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
1265 )?;
1266
1267 // Supervisor invariants (typed shape — children, restart strategy).
1268 // The "supervisor doesn't own code" check is at the top of verify()
1269 // so it fires before the existence-check loops.
1270 if caixa.kind().is_supervisor() {
1271 // Raw `:restart-window` parse gate on the flat
1272 // `Caixa::restart_window: Option<String>` axis — the last
1273 // orphan-validator on the typed Caixa surface flagged by the
1274 // [`Self::validate_deps`] wire-up's closing comment (the
1275 // "Supervisor-axis specific" remainder) and the
1276 // [`Caixa::supervisor_view`] doc-comment's "the future
1277 // layout-side wire-up" pin. Until this gate landed
1278 // [`Caixa::validate_restart_window`] existed as `pub fn` on
1279 // [`Caixa`] with full per-arm unit coverage in `manifest::tests`
1280 // (`validate_restart_window_rejects_*` — fractional seconds,
1281 // decimal-shaped integer, half-unit minute, leading sign,
1282 // unknown unit, garbage, empty-after-trim; eight rejection
1283 // arms total), but no production code path called it —
1284 // `feira build` (the canonical author-time gate; routes
1285 // through [`StandardLayout::verify`]) silently accepted a
1286 // malformed `:restart-window` and [`Caixa::supervisor_view`]
1287 // soft-swallowed the parse failure as `restart_window: None`
1288 // (i.e. the canonical "omit the slot to express no reset"
1289 // sentinel), turning every malformed window into a never-reset
1290 // supervisor far from the source `caixa.lisp`, with no field
1291 // naming the offending `:restart-window`. The Erlang/OTP
1292 // `MaxIntensity / Period` invariant the typed [`SupervisorSpec`]
1293 // gate (`view.validate()` immediately below) enforces on the
1294 // `Option<Duration>` value never reached the gate at all on
1295 // these inputs: the parse error was already laundered to
1296 // `None`, and `None` is the canonical "never reset" shape
1297 // that always validates cleanly. Lifting the parse gate to
1298 // the layout-pipeline wire-up closes the laundering — every
1299 // value past this gate either parses through the shared
1300 // `crate::supervisor::duration_codec::parse` (and therefore
1301 // round-trips canonically) or fires the new
1302 // [`Self::RestartWindowViolation`] envelope at the source.
1303 //
1304 // Runs *inside* the `kind == Supervisor` branch (rather than
1305 // alongside the peer flat-Caixa gates `validate_nome` /
1306 // `validate_versao` / `validate_deps` / `validate_code_paths`
1307 // above the kind dispatch) because `:restart-window` is in
1308 // the Supervisor slot set per [`Caixa::declared_supervisor_slots`]
1309 // — every non-Supervisor caixa with `:restart-window` set
1310 // already errors upstream via the
1311 // [`Self::SupervisorSlotsOnNonSupervisor`] kind-coherence gate
1312 // (line 243-252), so reaching this gate on a non-Supervisor
1313 // kind would be a no-op (the field is `None` by construction).
1314 // Runs *before* `view.validate()` so the parse-side diagnostic
1315 // surfaces first on the raw-string axis — a `:restart-window
1316 // "1.5s"` lands on the more self-locating
1317 // `RestartWindowViolation` (which names the offending raw
1318 // string verbatim) rather than the laundered-to-`None`
1319 // soft-pass that the typed view would silently let through.
1320 //
1321 // Same per-axis `*Violation { caixa, issue }` envelope every
1322 // peer flat-Caixa wrap exposes ([`Self::NomeViolation`] /
1323 // [`Self::VersaoViolation`] 1f74a5f,
1324 // [`Self::DepsViolation`] aa77d0f, [`Self::CodePathViolation`]
1325 // b868442). Threads [`ManifestError::RestartWindowMalformed`]
1326 // Display through verbatim — the per-arm reason already names
1327 // the offending raw value (e.g. `":restart-window \"1.5s\" is
1328 // not a canonical duration: …"`), so the wrap's `issue`
1329 // carries a self-locating "which axis, which value, why"
1330 // without re-shaping the parser-side reason.
1331 caixa.run_layout_gate(
1332 Caixa::validate_restart_window,
1333 LayoutError::restart_window_violation,
1334 )?;
1335 // Compound per-Caixa entry gate on the Supervisor-kind
1336 // supervision-tree slot family: the layout pipeline's paired
1337 // `let view = caixa.supervisor_view().expect(...);
1338 // view.validate() … validate_no_self_supervision(...) …`
1339 // cascade — the typed-shape cascade
1340 // ([`crate::SupervisorSpec::validate`]'s per-slot gates on
1341 // `:estrategia` ↔ `:children` invariants, `:max-restarts` /
1342 // `:restart-window` bounds, per-child DNS-1123 `:caixa`
1343 // names, semver-valid `:versao` constraints, the
1344 // set-not-multiset duplicate-child gate) and the cross-slot
1345 // self-edge gate
1346 // ([`crate::supervisor::validate_no_self_supervision`], the
1347 // `:children :caixa` ≠ `:nome` invariant the typed view
1348 // cannot enforce on its own because it carries the children
1349 // but not the parent `:nome`) — folded onto the
1350 // [`crate::Caixa::validate_supervisor_shape`] substrate
1351 // primitive. The two arms run in the same canonical order at
1352 // the primitive (typed-shape cascade → cross-slot self-edge)
1353 // so the fold is byte-for-byte equivalent to the pre-fold
1354 // two-block cascade this call site formerly carried, pinned
1355 // by the paired
1356 // `validate_supervisor_shape_folds_{view,self_supervision}_arm_matches_gate`
1357 // equivalence pins and the
1358 // `validate_supervisor_shape_view_arm_fires_before_self_supervision_arm`
1359 // ordering pin in the
1360 // [`crate::Caixa::validate_supervisor_shape`] pin family
1361 // (`manifest.rs`).
1362 //
1363 // Same lift discipline the peer per-Caixa compound gates
1364 // ([`crate::Caixa::validate_aplicacao_shape`] 949a7a0,
1365 // [`crate::Caixa::validate_upgrade_from`] d6801df,
1366 // [`crate::Caixa::validate_deps`] b5dd55e,
1367 // [`crate::Caixa::validate_limits`] baa4688,
1368 // [`crate::Caixa::validate_behavior`] 0d2877a) each carry —
1369 // one named substrate-primitive gate folds every structural +
1370 // cross-slot axis on that slot family onto one call, so every
1371 // future consumer that wants to re-check the Supervisor shape
1372 // after a per-slot patch (the wasm-operator's hierarchical
1373 // reconciliation scheduler, the M4
1374 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1375 // admission webhook, a future `feira validate --supervisor`
1376 // per-caixa admission verb, a per-Supervisor overlay
1377 // resolver) reaches the two-arm compound gate through one
1378 // dispatch rather than re-inlining the two-dispatch cascade
1379 // in lockstep with this wire-up. Peer with the
1380 // [`crate::render::require_supervisor_view`] compound entry
1381 // gate every per-Supervisor renderer would route through
1382 // (which already folds the same `spec.validate()` +
1383 // `validate_no_self_supervision` two-arm cascade behind its
1384 // `require_kind` + `validate_restart_window` prelude): the
1385 // two consumers of the Supervisor-shape cascade now share
1386 // one substrate primitive on each side of the
1387 // author-time-vs-renderer split, rather than two open-coded
1388 // cascades kept in lockstep.
1389 //
1390 // `:restart-window` stays wired above through its own
1391 // per-axis `LayoutError::RestartWindowViolation` envelope
1392 // (the raw-string parse gate on the flat
1393 // `Caixa::restart_window: Option<String>` axis, distinct
1394 // from the typed view's `Duration`-shape gate) — the fold
1395 // covers the two arms that share the
1396 // `LayoutError::SupervisorViolation` envelope; the
1397 // parse-gate arm keeps its self-locating envelope so a
1398 // malformed `:restart-window` surfaces the raw-value
1399 // diagnostic rather than the laundered-to-`None` soft-pass.
1400 caixa.run_layout_gate(
1401 Caixa::validate_supervisor_shape,
1402 LayoutError::supervisor_violation,
1403 )?;
1404 }
1405
1406 // Aplicacao invariants — typed graph composition. Like
1407 // Supervisor, an Aplicacao runs no code itself.
1408 //
1409 // Compound per-Caixa entry gate on the Aplicacao-kind mesh-slot
1410 // family: the layout pipeline's paired `let view =
1411 // caixa.aplicacao_view().expect(...); view.validate() …
1412 // validate_no_self_membership(...) …` cascade — the typed-shape
1413 // cascade ([`crate::AplicacaoSpec::validate`]'s per-slot gates
1414 // on `:membros`, `:contratos`, `:entrada`, `:placement`,
1415 // `:politicas`, in that declared order) and the cross-slot
1416 // self-edge gate ([`crate::aplicacao::validate_no_self_membership`],
1417 // the `:membros :caixa` ≠ `:nome` invariant the typed view
1418 // cannot enforce on its own because it carries the membros but
1419 // not the parent `:nome`) — folded onto the
1420 // [`crate::Caixa::validate_aplicacao_shape`] substrate primitive.
1421 // The two arms run in the same canonical order at the primitive
1422 // (typed-shape cascade → cross-slot self-edge) so the fold is
1423 // byte-for-byte equivalent to the pre-fold two-block cascade
1424 // this call site formerly carried, pinned by the paired
1425 // `validate_aplicacao_shape_folds_{view,self_membership}_arm_matches_gate`
1426 // equivalence pins and the
1427 // `validate_aplicacao_shape_view_arm_fires_before_self_membership_arm`
1428 // ordering pin in the [`crate::Caixa::validate_aplicacao_shape`]
1429 // pin family (`manifest.rs`).
1430 //
1431 // Same lift discipline the peer per-slot compound gates
1432 // ([`crate::Caixa::validate_upgrade_from`] d6801df,
1433 // [`crate::Caixa::validate_deps`] b5dd55e,
1434 // [`crate::Caixa::validate_limits`] baa4688,
1435 // [`crate::Caixa::validate_behavior`] 0d2877a) each carry — one
1436 // named substrate-primitive gate folds every structural +
1437 // cross-slot axis on that slot family onto one call, so every
1438 // future consumer that wants to re-check the Aplicacao shape
1439 // after a per-slot patch (the deferred
1440 // `caixa.pleme.io/v1alpha1/Caixa` CR materializer's admission
1441 // webhook, a future `feira validate --aplicacao` per-caixa
1442 // admission verb, a per-Aplicacao overlay resolver) reaches the
1443 // two-arm compound gate through one dispatch rather than
1444 // re-inlining the two-dispatch cascade in lockstep with this
1445 // wire-up. Peer with the [`crate::render::require_aplicacao_view`]
1446 // compound entry gate every per-Aplicacao renderer routes
1447 // through (3aefefb): the two consumers of the Aplicacao-shape
1448 // cascade now share one substrate primitive on each side of the
1449 // author-time-vs-renderer split, rather than two open-coded
1450 // cascades kept in lockstep.
1451 //
1452 // The outer `if caixa.kind().is_aplicacao()` guard stays because
1453 // [`crate::Caixa::validate_aplicacao_shape`] is the fold's
1454 // identity element on non-Aplicacao kinds (returns `Ok(())`
1455 // without touching the mesh slots — same posture as
1456 // [`crate::Caixa::validate_limits`] / [`Self`]::
1457 // [`crate::Caixa::validate_behavior`] on their `Option`-shaped
1458 // slots); the guard is a redundant but zero-cost fast-path that
1459 // preserves the peer supervisor branch's `if
1460 // caixa.kind().is_supervisor()` parallel structure at this
1461 // altitude.
1462 if caixa.kind().is_aplicacao() {
1463 caixa.run_layout_gate(
1464 Caixa::validate_aplicacao_shape,
1465 LayoutError::aplicacao_violation,
1466 )?;
1467 }
1468
1469 // Acao invariants — typed CI-run decompose. Like Supervisor and
1470 // Aplicacao, an Acao runs no code itself; unlike them, its sole
1471 // payload is a [`canteiro_types::CiRun`] whose declared-node
1472 // shape can carry three structural violations
1473 // ([`canteiro_types::DecomposeError`]: `DuplicateNode`,
1474 // `UnknownDep`, `Cycle`) the layout pipeline formerly deferred
1475 // to [`caixa_actions::validate`] — layout only checked `:ci`
1476 // *presence* via [`Self::MissingCi`] above, so a `:kind Acao`
1477 // carrying a structurally illegal `:ci` (a duplicate node
1478 // name, a dependency on an undeclared node, a dependency
1479 // cycle) passed `feira build` cleanly and surfaced the
1480 // diagnostic only when [`caixa_actions::validate`] later
1481 // refused it — far from the source `caixa.lisp` on the
1482 // author-time gate side.
1483 //
1484 // Compound per-Caixa entry gate on the Acao-kind `:ci` slot
1485 // family: the [`crate::render::decompose_ci`] typed decompose
1486 // gate — the sibling axis owned by the substrate-canonical
1487 // [`crate::render::require_acao_view`] compound helper every
1488 // per-`Acao` renderer routes through — folded onto the
1489 // [`crate::Caixa::validate_acao_shape`] substrate primitive.
1490 // The single-arm fold is byte-for-byte equivalent to the
1491 // pre-fold `decompose_ci(caixa, ci).map(|_| ())?` call this
1492 // wire-up sees, pinned by the paired
1493 // `validate_acao_shape_folds_decompose_arm_matches_gate`
1494 // equivalence pin and the
1495 // `validate_acao_shape_accepts_non_acao_kind` /
1496 // `validate_acao_shape_accepts_absent_ci_slot` identity-
1497 // element pins in the
1498 // [`crate::Caixa::validate_acao_shape`] pin family
1499 // (`manifest.rs`).
1500 //
1501 // Same lift discipline the peer per-kind compound gates
1502 // ([`crate::Caixa::validate_supervisor_shape`] 4c70105,
1503 // [`crate::Caixa::validate_aplicacao_shape`] 949a7a0,
1504 // [`crate::Caixa::validate_upgrade_from`] d6801df,
1505 // [`crate::Caixa::validate_deps`] b5dd55e,
1506 // [`crate::Caixa::validate_limits`] baa4688,
1507 // [`crate::Caixa::validate_behavior`] 0d2877a) each carry —
1508 // one named substrate-primitive gate folds every structural
1509 // axis on that kind onto one call, so every future consumer
1510 // that wants to re-check the Acao shape after a per-node
1511 // patch (a per-`Acao` CR materializer's admission webhook, a
1512 // future `feira validate --acao` per-caixa admission verb, a
1513 // per-`Acao` overlay resolver) reaches the compound gate
1514 // through one dispatch rather than re-inlining the decompose
1515 // cascade in lockstep with this wire-up. Peer with the
1516 // [`crate::render::require_acao_view`] compound entry gate
1517 // every per-`Acao` renderer routes through: the two consumers
1518 // of the Acao-shape cascade now share one substrate primitive
1519 // on each side of the author-time-vs-renderer split, rather
1520 // than two open-coded cascades kept in lockstep. Closes the
1521 // last per-kind asymmetry — with this wire-up the four typed
1522 // named-caixa kinds (`Servico` / `Aplicacao` / `Supervisor` /
1523 // `Acao`) each route through one compound per-Caixa shape
1524 // gate at the layout altitude.
1525 //
1526 // Runs *after* the [`Self::MissingCi`] presence gate above
1527 // (so a `:kind Acao` caixa with `ci = None` surfaces the
1528 // presence diagnostic first — the fold's identity-element arm
1529 // passes cleanly on absent `:ci`) and *after* the sibling
1530 // Supervisor / Aplicacao shape gates so the per-kind
1531 // diagnostic ordering at the layout altitude reads as the
1532 // canonical `Supervisor → Aplicacao → Acao` sweep.
1533 //
1534 // The outer `if caixa.kind().is_acao()` guard stays because
1535 // [`crate::Caixa::validate_acao_shape`] is the fold's
1536 // identity element on non-Acao kinds (returns `Ok(())`
1537 // without touching the `:ci` slot — same posture as
1538 // [`crate::Caixa::validate_supervisor_shape`] /
1539 // [`crate::Caixa::validate_aplicacao_shape`] on the sibling
1540 // typed-view-carrying arms); the guard is a redundant but
1541 // zero-cost fast-path that preserves the peer supervisor /
1542 // aplicacao branches' `if caixa.kind().is_<kind>()` parallel
1543 // structure at this altitude.
1544 if caixa.kind().is_acao() {
1545 caixa.run_layout_gate(Caixa::validate_acao_shape, LayoutError::acao_violation)?;
1546 }
1547
1548 Ok(())
1549 }
1550}
1551
1552#[derive(Debug, Error, PartialEq, Eq)]
1553pub enum LayoutError {
1554 #[error("manifest missing: {}", .0.display())]
1555 MissingManifest(PathBuf),
1556 #[error("caixa '{caixa}' is a Biblioteca but has no lib entry — expected {}", expected.display())]
1557 MissingLib { caixa: String, expected: PathBuf },
1558 #[error("caixa '{0}' is a Binario but has no :exe entries")]
1559 BinarioWithoutExe(String),
1560 #[error("caixa '{0}' is a Servico but has no :servicos entries")]
1561 ServicoWithoutServicos(String),
1562 #[error("declared {kind} entry missing: {}", path.display())]
1563 MissingEntry { kind: &'static str, path: PathBuf },
1564 #[error("exe entry outside exe/ directory: {}", .0.display())]
1565 ExeOutsideDir(PathBuf),
1566 #[error("servico entry outside servicos/ directory: {}", .0.display())]
1567 ServicoOutsideDir(PathBuf),
1568 #[error("caixa '{caixa}' has invalid :nome: {issue}")]
1569 NomeViolation { caixa: String, issue: String },
1570 #[error("caixa '{caixa}' has invalid :versao: {issue}")]
1571 VersaoViolation { caixa: String, issue: String },
1572 #[error("caixa '{caixa}' has invalid :deps / :deps-dev entry: {issue}")]
1573 DepsViolation { caixa: String, issue: String },
1574 #[error("caixa '{caixa}' has invalid :etiquetas entry: {issue}")]
1575 EtiquetasViolation { caixa: String, issue: String },
1576 #[error("caixa '{caixa}' has invalid :autores entry: {issue}")]
1577 AutoresViolation { caixa: String, issue: String },
1578 #[error("caixa '{caixa}' has invalid :repositorio: {issue}")]
1579 RepositorioViolation { caixa: String, issue: String },
1580 #[error("caixa '{caixa}' has invalid :descricao: {issue}")]
1581 DescricaoViolation { caixa: String, issue: String },
1582 #[error("caixa '{caixa}' has invalid :licenca: {issue}")]
1583 LicencaViolation { caixa: String, issue: String },
1584 #[error("caixa '{caixa}' has invalid :edicao: {issue}")]
1585 EdicaoViolation { caixa: String, issue: String },
1586 #[error("caixa '{caixa}' has invalid code-path entry: {issue}")]
1587 CodePathViolation { caixa: String, issue: String },
1588 #[error("caixa '{caixa}' has invalid :limits: {issue}")]
1589 LimitsViolation { caixa: String, issue: String },
1590 #[error("caixa '{caixa}' has invalid :behavior callback: {issue}")]
1591 BehaviorViolation { caixa: String, issue: String },
1592 #[error("caixa '{caixa}' has invalid :upgrade-from entry: {issue}")]
1593 UpgradeViolation { caixa: String, issue: String },
1594 #[error("supervisor caixa '{caixa}' violates typed shape: {issue}")]
1595 SupervisorViolation { caixa: String, issue: String },
1596 #[error("supervisor caixa '{caixa}' has invalid :restart-window: {issue}")]
1597 RestartWindowViolation { caixa: String, issue: String },
1598 #[error(
1599 "supervisor caixa '{0}' must not declare :bibliotecas, :exe, or :servicos — supervisors don't run code, they orchestrate other caixas"
1600 )]
1601 SupervisorOwnsCode(String),
1602 #[error("aplicacao caixa '{caixa}' violates typed shape: {issue}")]
1603 AplicacaoViolation { caixa: String, issue: String },
1604 #[error("acao caixa '{caixa}' violates typed shape: {issue}")]
1605 AcaoViolation { caixa: String, issue: String },
1606 #[error(
1607 "aplicacao caixa '{0}' must not declare :bibliotecas, :exe, or :servicos — aplicacaos compose Servicos, they don't run code themselves"
1608 )]
1609 AplicacaoOwnsCode(String),
1610 #[error(
1611 "acao caixa '{0}' must not declare :bibliotecas, :exe, or :servicos — acaos carry a typed CI run (:ci), they don't run code themselves"
1612 )]
1613 AcaoOwnsCode(String),
1614 #[error(
1615 "caixa '{caixa}' is :kind {kind:?} but declares Aplicacao-only mesh slot(s): {slots} — \
1616 :membros / :contratos / :politicas / :placement / :entrada compose a :kind Aplicacao's \
1617 typed graph (MESH-COMPOSITION §III.1) and are silently ignored on every other kind \
1618 (never validated, never rendered); move them to a :kind Aplicacao caixa or remove them"
1619 )]
1620 MeshSlotsOnNonAplicacao {
1621 caixa: String,
1622 kind: CaixaKind,
1623 slots: String,
1624 },
1625 #[error(
1626 "caixa '{caixa}' is :kind {kind:?} but declares Supervisor-only slot(s): {slots} — \
1627 :estrategia / :max-restarts / :restart-window / :children compose a :kind Supervisor's \
1628 typed OTP supervisor (INSPIRATIONS §II.2) and are silently ignored on every other kind \
1629 (never validated, never reconciled); move them to a :kind Supervisor caixa or remove them"
1630 )]
1631 SupervisorSlotsOnNonSupervisor {
1632 caixa: String,
1633 kind: CaixaKind,
1634 slots: String,
1635 },
1636 #[error(
1637 "caixa '{caixa}' is :kind {kind:?} but declares Servico-only slot(s): {slots} — \
1638 :limits / :behavior / :upgrade-from configure the runtime of a long-running :kind Servico \
1639 wasm component (INSPIRATIONS §III.1 / §II.3 / §II.4) and are silently ignored on every \
1640 other kind (never rendered into a chart or programs.yaml entry); move them to a :kind \
1641 Servico caixa or remove them"
1642 )]
1643 ServicoSlotsOnNonServico {
1644 caixa: String,
1645 kind: CaixaKind,
1646 slots: String,
1647 },
1648 #[error(
1649 "caixa '{caixa}' is :kind {kind:?} but declares foreign code-surface slot(s): {slots} — \
1650 :exe is the nix-built executable surface owned only by :kind Binario, :servicos is the \
1651 wasm-component + ComputeUnit daemon surface owned only by :kind Servico; \
1652 caixa-helm / caixa-flux / caixa-flake gate emission on `require_kind(_, <owning-kind>)`, \
1653 so a declared :exe / :servicos on the wrong code-running kind is silently ignored — the \
1654 path is validated by the layout's path-existence loops but never rendered into a build \
1655 target or programs.yaml entry. Move the slot to its owning kind, change :kind to match \
1656 (Binario for :exe, Servico for :servicos), or drop the slot entirely"
1657 )]
1658 ForeignCodeSlot {
1659 caixa: String,
1660 kind: CaixaKind,
1661 slots: String,
1662 },
1663 #[error("caixa '{0}' is an Acao but has no :ci slot")]
1664 MissingCi(String),
1665 #[error(
1666 "caixa '{caixa}' is :kind {kind:?} but declares the Acao-only :ci slot — \
1667 :ci carries a typed CI run (canteiro_types::CiRun, CANTEIRO §7.1-C) that only the \
1668 caixa-actions renderer validates for :kind Acao, and is silently ignored on every \
1669 other kind (never decomposed, never rendered); move it to a :kind Acao caixa or \
1670 remove it"
1671 )]
1672 CiOnNonAcao { caixa: String, kind: CaixaKind },
1673}
1674
1675// Fold the layout-pipeline per-Caixa violation wrap onto one substrate
1676// primitive per typed slot. Every `LayoutError::*Violation { caixa, issue }`
1677// variant follows the same uniform shape — `caixa = layout-Caixa's :nome`,
1678// `issue = the gate's per-arm Display` — and every wire-up in
1679// [`StandardLayout::verify`] used to open-code the identical five-line
1680// `.map_err(|err| LayoutError::XxxViolation { caixa: caixa.nome().to_string(),
1681// issue: err.to_string() })` block, once per typed slot. Sixteen distinct
1682// wrap-variants × eighteen wire-up sites is exactly the duplication the
1683// PRIME DIRECTIVE names as a bug: every future consumer that wants to add a
1684// new per-slot gate (the deferred `caixa.pleme.io/v1alpha1/Caixa` CR
1685// materializer's admission webhook, a future per-slot `feira validate`
1686// verb, a per-slot overlay resolver) had to re-inline the five-line block
1687// in lockstep with the pre-existing wire-ups.
1688//
1689// The macro below generates one static constructor per variant of shape
1690// `fn <slot>_violation(caixa: &Caixa, err: impl Display) -> LayoutError`,
1691// so every wire-up site collapses onto one dispatch:
1692// `caixa.validate_<slot>().map_err(|err| LayoutError::<slot>_violation(caixa,
1693// err))?;`. The uniform two-slot construction (`caixa: caixa.nome()
1694// .to_string()`, `issue: err.to_string()`) is spelled once — inside the
1695// macro — rather than at every wire-up site. Every constructor is
1696// `#[must_use]` so a caller who mistakenly discards the wrapped error
1697// (rather than routing it through `?`) trips a compile warning at the
1698// wire-up site.
1699//
1700// Peer with the per-slot compound entry gates every substrate primitive
1701// on the M2/M3 typed-slot family already carries
1702// ([`crate::Caixa::validate_deps`] b5dd55e, [`crate::Caixa::validate_limits`]
1703// baa4688, [`crate::Caixa::validate_behavior`] 0d2877a,
1704// [`crate::Caixa::validate_upgrade_from`] d6801df,
1705// [`crate::Caixa::validate_aplicacao_shape`] 949a7a0,
1706// [`crate::AplicacaoSpec::validate_contratos`],
1707// [`crate::MeshPolicy::validate`],
1708// [`crate::SupervisorSpec::validate_children`]): the author-time gates
1709// fold onto one substrate primitive per typed slot; here the layout-side
1710// error-wrap folds onto one substrate primitive per typed variant, so the
1711// two sides of the layout pipeline's per-slot cascade (the gate, the
1712// wrap) each route through one call rather than N open-coded block
1713// repetitions.
1714macro_rules! layout_violation_ctors {
1715 ($($ctor:ident => $variant:ident),* $(,)?) => {
1716 impl LayoutError {
1717 $(
1718 #[doc = concat!(
1719 "Construct a [`LayoutError::",
1720 stringify!($variant),
1721 "`] wrapping `err` under `caixa.nome()`. Folds the ",
1722 "uniform `{ caixa: caixa.nome().to_string(), issue: ",
1723 "err.to_string() }` two-slot construction onto one ",
1724 "substrate primitive so every ",
1725 "[`StandardLayout::verify`] wire-up on this variant ",
1726 "reads through one dispatch rather than the pre-lift ",
1727 "five-line open-coded block."
1728 )]
1729 #[must_use]
1730 pub fn $ctor<E: std::fmt::Display>(caixa: &crate::Caixa, err: E) -> Self {
1731 Self::$variant {
1732 caixa: caixa.nome().to_string(),
1733 issue: err.to_string(),
1734 }
1735 }
1736 )*
1737 }
1738 };
1739}
1740
1741layout_violation_ctors! {
1742 nome_violation => NomeViolation,
1743 versao_violation => VersaoViolation,
1744 deps_violation => DepsViolation,
1745 etiquetas_violation => EtiquetasViolation,
1746 autores_violation => AutoresViolation,
1747 repositorio_violation => RepositorioViolation,
1748 descricao_violation => DescricaoViolation,
1749 licenca_violation => LicencaViolation,
1750 edicao_violation => EdicaoViolation,
1751 code_path_violation => CodePathViolation,
1752 limits_violation => LimitsViolation,
1753 behavior_violation => BehaviorViolation,
1754 upgrade_violation => UpgradeViolation,
1755 restart_window_violation => RestartWindowViolation,
1756 supervisor_violation => SupervisorViolation,
1757 aplicacao_violation => AplicacaoViolation,
1758 acao_violation => AcaoViolation,
1759}
1760
1761// Fold the four `LayoutError::*SlotsOn*` / `LayoutError::ForeignCodeSlot`
1762// kind-coherence wrap sites onto one substrate primitive per typed variant —
1763// the sibling of [`layout_violation_ctors!`] above on the second uniform
1764// error-envelope shape `LayoutError` carries: `{ caixa: caixa.nome(),
1765// kind: caixa.kind(), slots: <declared_*_slots()>.join(" ") }`. Every
1766// wire-up in [`StandardLayout::verify`] on this shape (four sites: the
1767// M3-mesh gate on non-Aplicacao, the supervisor-tree gate on
1768// non-Supervisor, the M2-runtime gate on non-Servico, the code-surface
1769// `ForeignCodeSlot` gate) used to open-code the identical four-field
1770// `.{ caixa: caixa.nome().to_string(), kind: caixa.kind(), slots:
1771// <declared_*_slots>.join(" ") }` block — the exact "same block re-inlined
1772// at every consumer" shape the PRIME DIRECTIVE names as a bug on the same
1773// altitude the peer [`layout_violation_ctors!`] macro just closed on the
1774// `{ caixa, issue }` sibling shape.
1775//
1776// The macro below generates one static constructor per variant of shape
1777// `fn <slot>_on_non_<owner>(caixa: &Caixa, slots: Vec<&'static str>) ->
1778// LayoutError`, so every wire-up site collapses onto one dispatch:
1779// `return Err(LayoutError::<slot>_on_non_<owner>(caixa, <declared_slots>));`.
1780// The uniform four-field construction is spelled once — inside the macro —
1781// rather than at every wire-up site. Every constructor is `#[must_use]` so
1782// a caller who mistakenly discards the constructed error (rather than
1783// routing it through `return Err(…)`) trips a compile warning at the
1784// wire-up site.
1785//
1786// Peer with the `_violation` constructor family above on the same
1787// `LayoutError` — the two together now fold every uniform-shape
1788// `LayoutError` variant carried by [`StandardLayout::verify`] onto one
1789// substrate primitive per typed variant, so the layout-side error-wrap
1790// surface reads through one dispatch per variant rather than N open-coded
1791// blocks. Every future consumer that wants to construct one of these
1792// variants outside the layout pipeline (a per-slot admission webhook, a
1793// `feira validate --kind X` verb, an overlay resolver rejecting a
1794// kind-foreign patch) reaches its variant through one call, matching the
1795// `_violation` family's substrate-primitive discipline.
1796macro_rules! layout_slot_kind_ctors {
1797 ($($ctor:ident => $variant:ident),* $(,)?) => {
1798 impl LayoutError {
1799 $(
1800 #[doc = concat!(
1801 "Construct a [`LayoutError::",
1802 stringify!($variant),
1803 "`] naming the offending slot list under `caixa.nome()` ",
1804 "at `caixa.kind()`. Folds the uniform `{ caixa: caixa.",
1805 "nome().to_string(), kind: caixa.kind(), slots: slots.",
1806 "join(\" \") }` four-field construction onto one substrate ",
1807 "primitive so every [`StandardLayout::verify`] wire-up on ",
1808 "this variant reads through one dispatch rather than the ",
1809 "pre-lift open-coded block."
1810 )]
1811 #[must_use]
1812 pub fn $ctor(caixa: &crate::Caixa, slots: Vec<&'static str>) -> Self {
1813 Self::$variant {
1814 caixa: caixa.nome().to_string(),
1815 kind: caixa.kind(),
1816 slots: slots.join(" "),
1817 }
1818 }
1819 )*
1820 }
1821 };
1822}
1823
1824layout_slot_kind_ctors! {
1825 mesh_slots_on_non_aplicacao => MeshSlotsOnNonAplicacao,
1826 supervisor_slots_on_non_supervisor => SupervisorSlotsOnNonSupervisor,
1827 servico_slots_on_non_servico => ServicoSlotsOnNonServico,
1828 foreign_code_slot => ForeignCodeSlot,
1829}
1830
1831// Fold the five [`LayoutError::MissingEntry`] wire-up sites at
1832// [`StandardLayout::verify`] onto one substrate primitive on `LayoutError` —
1833// the third and last uniform-shape envelope on `LayoutError` after the
1834// `{ caixa, issue }` family the [`layout_violation_ctors!`] macro closed
1835// (131ca0d) and the `{ caixa, kind, slots }` family the peer
1836// [`layout_slot_kind_ctors!`] macro closed (0419438). Each of the five
1837// wire-up sites on `MissingEntry` (`:bibliotecas` iteration line 823,
1838// `:exe` iteration line 834, `:servicos` iteration line 848, `:behavior`
1839// on-disk callback-path iteration line 957, `:upgrade-from` per-
1840// instruction script-path iteration line 1021) opened the same four-line
1841// `LayoutError::MissingEntry { kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_<slot>,
1842// path: full }` struct-literal block — the exact "same block re-inlined
1843// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
1844// same altitude the peer `_violation` / `_slots_on_non_*` families each
1845// closed on the sibling `LayoutError` envelopes.
1846//
1847// One `#[must_use]` inherent constructor on `LayoutError` collapses the
1848// five sites onto one dispatch:
1849// `return Err(LayoutError::missing_entry(<kind-label>, full));`, byte-
1850// equal to the pre-lift struct-literal block. A macro is not warranted
1851// on the one-variant envelope shape `{ kind: &'static str, path: PathBuf }`
1852// (unlike the sibling 16-variant `_violation` / 4-variant
1853// `_slots_on_non_*` shapes), but the same substrate-primitive discipline
1854// applies: every future consumer that wants to construct a `MissingEntry`
1855// outside the layout pipeline (a per-slot admission webhook probing a
1856// declared path against an out-of-band filesystem oracle, a `feira
1857// validate --lib` / `--exe` / `--servico` / `--behavior` / `--upgrade`
1858// per-caixa admission verb, the deferred `caixa.pleme.io/v1alpha1/Caixa`
1859// CR materializer's admission-webhook floor, a per-cluster overlay
1860// resolver rejecting a missing entry against a cluster-local filesystem
1861// snapshot) reaches the variant through one call rather than re-inlining
1862// the four-line struct-literal block in lockstep with the five
1863// layout-pipeline wire-up sites.
1864impl LayoutError {
1865 /// Construct a [`LayoutError::MissingManifest`] naming the resolved
1866 /// `caixa.lisp` path the layout gate probed for at
1867 /// [`StandardLayout::verify`]'s top-of-body manifest-existence
1868 /// check.
1869 ///
1870 /// Folds the uniform `Self::MissingManifest(path)` one-slot
1871 /// tuple-literal onto one substrate primitive so the sole
1872 /// [`StandardLayout::verify`] wire-up on this variant reads through
1873 /// one dispatch rather than the pre-lift open-coded tuple-literal
1874 /// block. Peer of the sibling [`Self::missing_entry`] `{ kind, path }`
1875 /// ctor on the same envelope's declared-entry-existence axis, and
1876 /// mirror-symmetric sibling of the sibling [`Self::missing_lib`]
1877 /// `{ caixa, expected }` ctor on the enclosing envelope's per-caixa
1878 /// required-fallback-path axis: the top-level manifest-existence
1879 /// gate now routes its emit-site through the same substrate-
1880 /// primitive discipline every sibling variant on the same
1881 /// [`LayoutError`] envelope carries, closing the last un-lifted
1882 /// `<Variant>(PathBuf)` tuple-newtype variant on the envelope
1883 /// carried through a direct open-coded construction (the peer
1884 /// [`Self::ExeOutsideDir`] / [`Self::ServicoOutsideDir`]
1885 /// `<Variant>(PathBuf)` variants stay on their pre-lift
1886 /// tuple-variant-constructor coercion inside
1887 /// [`StandardLayout::probe_sandboxed_declared_entry`]'s
1888 /// `outside_ctor: fn(PathBuf) -> LayoutError` function-pointer
1889 /// parameter — the substrate primitive on that axis is the
1890 /// sandbox-probe helper itself, so the paired variant ctors are
1891 /// already substrate-canonical at their wire-up site by
1892 /// construction).
1893 ///
1894 /// The `PathBuf` parameter takes ownership of the resolved
1895 /// `root.join("caixa.lisp")` path from the wire-up site's
1896 /// [`Path::join`] product — byte-equal to the pre-lift
1897 /// `Self::MissingManifest(manifest)` tuple-literal on the same
1898 /// owned `PathBuf` fixture. `#[must_use]` fires a compile warning
1899 /// at any wire-up that mistakenly discards the constructed error
1900 /// rather than routing it through `return Err(…)`.
1901 ///
1902 /// Every future consumer that wants to construct this variant
1903 /// outside [`StandardLayout::verify`] — a deferred
1904 /// `caixa.pleme.io/v1alpha1/Caixa` CR materializer's admission-
1905 /// webhook re-check probing the resolved manifest path against a
1906 /// mounted cluster-local filesystem snapshot, a future
1907 /// `feira validate --manifest-exists` per-caixa admission verb
1908 /// re-running the manifest-existence gate on demand, a per-cluster
1909 /// overlay resolver rejecting a `:placement`-scoped manifest
1910 /// omission against a cluster-local snapshot — now reaches the
1911 /// variant through one call rather than re-inlining the two-line
1912 /// tuple-literal in lockstep with the in-crate wire-up site.
1913 #[must_use]
1914 pub const fn missing_manifest(path: PathBuf) -> Self {
1915 Self::MissingManifest(path)
1916 }
1917
1918 /// Construct a [`LayoutError::MissingEntry`] naming the missing
1919 /// declared entry at `path` under the canonical `kind` label from
1920 /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`] /
1921 /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] /
1922 /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] /
1923 /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`] /
1924 /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT`].
1925 /// Folds the uniform `{ kind, path }` two-slot construction onto one
1926 /// substrate primitive so every [`StandardLayout::verify`] wire-up
1927 /// on this variant reads through one dispatch rather than the
1928 /// pre-lift open-coded struct-literal block.
1929 #[must_use]
1930 pub fn missing_entry(kind: &'static str, path: PathBuf) -> Self {
1931 Self::MissingEntry { kind, path }
1932 }
1933
1934 /// Construct a [`LayoutError::MissingLib`] naming the offending
1935 /// `caixa.nome()` and the resolved fallback `expected` path.
1936 ///
1937 /// Folds the uniform `Self::MissingLib { caixa: caixa.nome()
1938 /// .to_string(), expected }` two-slot struct-literal onto one
1939 /// substrate primitive so every [`StandardLayout::verify`] wire-up
1940 /// on this variant reads through one dispatch rather than the
1941 /// pre-lift open-coded struct-literal block, projecting the caixa
1942 /// slot through the paired [`crate::Caixa::nome`] accessor — the
1943 /// same discipline the sibling [`Self::missing_entry`]
1944 /// `{ kind, path }` ctor and the [`layout_nome_only_ctors!`]
1945 /// `{ caixa }`-only tuple-variant ctor family already take on the
1946 /// same envelope.
1947 #[must_use]
1948 pub fn missing_lib(caixa: &crate::Caixa, expected: PathBuf) -> Self {
1949 Self::MissingLib {
1950 caixa: caixa.nome().to_string(),
1951 expected,
1952 }
1953 }
1954
1955 /// Construct a [`LayoutError::CiOnNonAcao`] naming the offending
1956 /// `caixa.nome()` and its declared `:kind`.
1957 ///
1958 /// Folds the uniform `Self::CiOnNonAcao { caixa: caixa.nome()
1959 /// .to_string(), kind: caixa.kind() }` two-slot struct-literal
1960 /// onto one substrate primitive so every wire-up on this variant
1961 /// (today the sole [`crate::Caixa::validate_ci_kind_coherence`]
1962 /// call site at `caixa-core/src/manifest.rs:5586` — the deferred
1963 /// `caixa.pleme.io/v1alpha1/Caixa` CR admission webhook and a
1964 /// future `feira validate --ci-kind` per-caixa verb sit at the
1965 /// same axis) reads through one dispatch rather than the pre-lift
1966 /// open-coded struct-literal block. Both slots project through
1967 /// the paired [`crate::Caixa::nome`] / [`crate::Caixa::kind`]
1968 /// accessors — the same discipline every sibling ctor on this
1969 /// envelope ([`Self::missing_lib`] on `{ caixa, expected }`, the
1970 /// [`layout_nome_only_ctors!`] family on `{ caixa }`-only
1971 /// tuple-variants, the [`layout_slot_kind_ctors!`] family on
1972 /// `{ caixa, kind, slots }`) already takes.
1973 #[must_use]
1974 pub fn ci_on_non_acao(caixa: &crate::Caixa) -> Self {
1975 Self::CiOnNonAcao {
1976 caixa: caixa.nome().to_string(),
1977 kind: caixa.kind(),
1978 }
1979 }
1980}
1981
1982// Fold the six `LayoutError::<Variant>(caixa.nome().to_string())` nome-
1983// only tuple-variant wire-up sites at [`StandardLayout::verify`] onto one
1984// substrate primitive per typed variant — the fourth uniform-shape
1985// envelope on `LayoutError` after the `{ caixa, issue }` family the
1986// [`layout_violation_ctors!`] macro closed (131ca0d), the
1987// `{ caixa, kind, slots }` family the peer [`layout_slot_kind_ctors!`]
1988// macro closed (0419438), and the `{ kind, path }`
1989// [`LayoutError::missing_entry`] one-variant ctor (1b09f9d). Each of the
1990// six wire-up sites on this shape (`SupervisorOwnsCode` /
1991// `AplicacaoOwnsCode` / `AcaoOwnsCode` at the no-code kind-coherence gate;
1992// `BinarioWithoutExe` / `ServicoWithoutServicos` / `MissingCi` at the
1993// required-slot gate) opened the identical one-line
1994// `LayoutError::<Variant>(caixa.nome().to_string())` tuple-literal — the
1995// exact "same block re-inlined at every consumer" shape the PRIME
1996// DIRECTIVE names as a bug, on the same altitude the peer `_violation` /
1997// `_slots_on_non_*` / `missing_entry` families each closed on the
1998// sibling `LayoutError` envelopes.
1999//
2000// The macro below generates one static constructor per variant of shape
2001// `fn <slot>(caixa: &Caixa) -> LayoutError`, so every wire-up site
2002// collapses onto one dispatch:
2003// `return Err(LayoutError::<slot>(caixa));`, byte-equal to the pre-lift
2004// tuple-literal. The uniform one-field construction (`caixa: caixa.nome()
2005// .to_string()`) is spelled once — inside the macro — rather than at
2006// every wire-up site. Every constructor is `#[must_use]` so a caller who
2007// mistakenly discards the constructed error (rather than routing it
2008// through `return Err(…)`) trips a compile warning at the wire-up site.
2009//
2010// Peer with the three prior `LayoutError`-envelope constructor families
2011// — the four together now fold every uniform-shape `LayoutError` variant
2012// carried by [`StandardLayout::verify`] onto one substrate primitive per
2013// typed variant, so every layout-side error-wrap on `LayoutError` reads
2014// through one dispatch per variant rather than N open-coded blocks.
2015// Every future consumer that wants to construct one of these variants
2016// outside the layout pipeline (a per-slot admission webhook probing an
2017// Acao's `:ci` slot, a `feira validate --kind <X>` verb refusing a
2018// no-code kind that declares `:bibliotecas` / `:exe` / `:servicos`, an
2019// overlay resolver rejecting a required-slot omission against a
2020// cluster-local snapshot) reaches its variant through one call, matching
2021// the `_violation` / `_slots_on_non_*` / `missing_entry` families'
2022// substrate-primitive discipline.
2023macro_rules! layout_nome_only_ctors {
2024 ($($ctor:ident => $variant:ident),* $(,)?) => {
2025 impl LayoutError {
2026 $(
2027 #[doc = concat!(
2028 "Construct a [`LayoutError::",
2029 stringify!($variant),
2030 "`] naming the offending `caixa.nome()`. Folds the ",
2031 "uniform `Self::",
2032 stringify!($variant),
2033 "(caixa.nome().to_string())` one-field tuple-",
2034 "literal onto one substrate primitive so every ",
2035 "[`StandardLayout::verify`] wire-up on this variant ",
2036 "reads through one dispatch rather than the pre-lift ",
2037 "open-coded block."
2038 )]
2039 #[must_use]
2040 pub fn $ctor(caixa: &crate::Caixa) -> Self {
2041 Self::$variant(caixa.nome().to_string())
2042 }
2043 )*
2044 }
2045 };
2046}
2047
2048layout_nome_only_ctors! {
2049 binario_without_exe => BinarioWithoutExe,
2050 servico_without_servicos => ServicoWithoutServicos,
2051 missing_ci => MissingCi,
2052 supervisor_owns_code => SupervisorOwnsCode,
2053 aplicacao_owns_code => AplicacaoOwnsCode,
2054 acao_owns_code => AcaoOwnsCode,
2055}
2056
2057#[cfg(test)]
2058mod tests {
2059 use super::*;
2060 use crate::{Caixa, CaixaKind};
2061 use std::path::PathBuf;
2062
2063 fn caixa(kind: CaixaKind) -> Caixa {
2064 Caixa {
2065 nome: "demo".into(),
2066 versao: "0.1.0".into(),
2067 kind,
2068 edicao: None,
2069 descricao: None,
2070 repositorio: None,
2071 licenca: None,
2072 autores: vec![],
2073 etiquetas: vec![],
2074 deps: vec![],
2075 deps_dev: vec![],
2076 exe: vec![],
2077 bibliotecas: vec![],
2078 servicos: vec![],
2079 // M2 typed-substrate slots default to absent.
2080 limits: None,
2081 behavior: None,
2082 upgrade_from: vec![],
2083 estrategia: None,
2084 max_restarts: None,
2085 restart_window: None,
2086 children: vec![],
2087 // M3 Aplicacao slots default to absent.
2088 membros: vec![],
2089 contratos: vec![],
2090 politicas: None,
2091 placement: None,
2092 entrada: None,
2093 ci: None,
2094 }
2095 }
2096
2097 #[test]
2098 fn missing_manifest_errors() {
2099 let layout = StandardLayout::new().with_path_exists(|_| false);
2100 let err = layout
2101 .verify(&caixa(CaixaKind::Biblioteca), Path::new("/tmp/x"))
2102 .unwrap_err();
2103 assert!(matches!(err, LayoutError::MissingManifest(_)));
2104 }
2105
2106 #[test]
2107 fn missing_manifest_ctor_matches_tuple_literal_wrap() {
2108 // Equivalence pin locking [`LayoutError::missing_manifest`] to
2109 // its tuple-literal peer under PartialEq. The pre-lift wire-up
2110 // at [`StandardLayout::verify`]'s top-of-body manifest-existence
2111 // gate read `LayoutError::MissingManifest(manifest)` — a two-
2112 // line open-coded tuple-literal against the resolved
2113 // `root.join("caixa.lisp")` `PathBuf`. The post-lift dispatch
2114 // reads `LayoutError::missing_manifest(manifest)`. Both must
2115 // produce byte-equal variants — a silent divergence (a
2116 // `.canonicalize()` slip on the ctor body, a stray `.clone()`
2117 // that duplicates the payload's underlying buffer, an
2118 // accidental `.into()` that reshapes the `PathBuf` bytes on
2119 // one side and not the other) surfaces here rather than at a
2120 // downstream diagnostic-shape drift far from the ctor
2121 // definition.
2122 //
2123 // Peer of the sibling
2124 // [`missing_entry_ctor_matches_struct_literal_wrap`] /
2125 // [`missing_lib_ctor_matches_struct_literal_wrap`] /
2126 // [`ci_on_non_acao_ctor_matches_struct_literal_wrap`] pins on
2127 // the same [`LayoutError`] envelope — closes the last
2128 // un-pinned inherent-ctor equivalence-against-open-coded-
2129 // literal pin on the envelope.
2130 let path = PathBuf::from("/tmp/x/caixa.lisp");
2131 assert_eq!(
2132 LayoutError::missing_manifest(path.clone()),
2133 LayoutError::MissingManifest(path),
2134 "missing_manifest ctor must byte-equal the pre-lift tuple-literal",
2135 );
2136 }
2137
2138 #[test]
2139 fn verify_missing_manifest_gate_routes_through_missing_manifest_ctor() {
2140 // Fail-before-pass-after routing pin: the pre-lift
2141 // [`StandardLayout::verify`] wire-up hand-rolled
2142 // `LayoutError::MissingManifest(manifest)` at its top-of-body
2143 // manifest-existence arm; the post-lift dispatch routes the
2144 // same arm through
2145 // [`LayoutError::missing_manifest`]. This pin sweeps a fixture
2146 // whose oracle refuses every path (`with_path_exists(|_| false)`
2147 // — the same shape [`missing_manifest_errors`] uses to prove
2148 // the gate fires at all) and asserts that the emitted
2149 // [`LayoutError`] equals the ctor-built error verbatim under
2150 // [`PartialEq`]. A future de-lift of this wire-up (a
2151 // hand-rolled `Self::MissingManifest(_)` reintroduced at the
2152 // gate, an intercept that unwraps the ctor's payload before
2153 // re-emitting) trips this pin at layout.rs build time rather
2154 // than surfacing as a drift-detection failure at a downstream
2155 // diagnostic-shape consumer far from the wire-up site.
2156 //
2157 // Same discipline the peer
2158 // [`ci_on_non_acao_ctor_matches_struct_literal_wrap`] /
2159 // [`missing_entry_ctor_routes_kind_through_arg_verbatim`] /
2160 // [`missing_lib_ctor_projects_nome_through_accessor`] pins on
2161 // the sibling [`LayoutError`] envelope's per-variant substrate-
2162 // primitive ctor family already carry — extended here onto
2163 // the last un-pinned wire-up-routing gate on the envelope.
2164 let root = Path::new("/tmp/routing-pin");
2165 let layout = StandardLayout::new().with_path_exists(|_| false);
2166 let err = layout
2167 .verify(&caixa(CaixaKind::Biblioteca), root)
2168 .unwrap_err();
2169 assert_eq!(
2170 err,
2171 LayoutError::missing_manifest(root.join("caixa.lisp")),
2172 "StandardLayout::verify's manifest-existence gate must route through \
2173 LayoutError::missing_manifest with the resolved `root.join(\"caixa.lisp\")` \
2174 payload verbatim",
2175 );
2176 }
2177
2178 // ── LayoutError::*_violation constructor family ──────────────────────
2179 //
2180 // The [`layout_violation_ctors!`] macro (below the `LayoutError` enum
2181 // definition) generates one static constructor per `*Violation { caixa,
2182 // issue }` variant that folds the uniform `{ caixa: caixa.nome()
2183 // .to_string(), issue: err.to_string() }` two-slot construction onto
2184 // one substrate primitive. The per-variant equivalence pins below
2185 // (fail-before-pass-after by construction — a byte-mismatched macro
2186 // arm would trip its equivalence pin first) lock each generated
2187 // constructor to its struct-literal peer under `PartialEq`, so every
2188 // wire-up in [`StandardLayout::verify`] on that variant produces a
2189 // byte-equal `LayoutError` to the pre-lift open-coded block. The
2190 // fixture caixa fires under `caixa("demo")` so the `caixa: "demo"`
2191 // half is pinned; the fixture error fires under a fixed `&str` so the
2192 // `issue: <literal>` half is pinned; the two together pin every field
2193 // of every generated variant.
2194
2195 fn layout_violation_ctor_fixture() -> (Caixa, &'static str) {
2196 (caixa(CaixaKind::Biblioteca), "sample issue text")
2197 }
2198
2199 // `assert_eq!` uses `PartialEq::eq(&self, &other)` under the hood, so
2200 // `actual`/`expected` are only ever read, never moved into anything —
2201 // the ergonomic tradeoff (owned + move-in vs. reference + &-borrow at
2202 // every call site) favors the owned form for a test-only assertion
2203 // helper called from 17 wire-up pins. The lint targets the general
2204 // API-shape case where callers still have downstream uses for the
2205 // moved value; the assertion helper terminates on the equality check.
2206 #[allow(clippy::needless_pass_by_value)]
2207 fn assert_violation_ctor_matches(actual: LayoutError, expected: LayoutError) {
2208 assert_eq!(
2209 actual, expected,
2210 "generated constructor must produce byte-equal LayoutError to open-coded struct-literal wrap",
2211 );
2212 }
2213
2214 #[test]
2215 fn nome_violation_ctor_matches_struct_literal_wrap() {
2216 let (c, issue) = layout_violation_ctor_fixture();
2217 assert_violation_ctor_matches(
2218 LayoutError::nome_violation(&c, issue),
2219 LayoutError::NomeViolation {
2220 caixa: c.nome().to_string(),
2221 issue: issue.to_string(),
2222 },
2223 );
2224 }
2225
2226 #[test]
2227 fn versao_violation_ctor_matches_struct_literal_wrap() {
2228 let (c, issue) = layout_violation_ctor_fixture();
2229 assert_violation_ctor_matches(
2230 LayoutError::versao_violation(&c, issue),
2231 LayoutError::VersaoViolation {
2232 caixa: c.nome().to_string(),
2233 issue: issue.to_string(),
2234 },
2235 );
2236 }
2237
2238 #[test]
2239 fn deps_violation_ctor_matches_struct_literal_wrap() {
2240 let (c, issue) = layout_violation_ctor_fixture();
2241 assert_violation_ctor_matches(
2242 LayoutError::deps_violation(&c, issue),
2243 LayoutError::DepsViolation {
2244 caixa: c.nome().to_string(),
2245 issue: issue.to_string(),
2246 },
2247 );
2248 }
2249
2250 #[test]
2251 fn etiquetas_violation_ctor_matches_struct_literal_wrap() {
2252 let (c, issue) = layout_violation_ctor_fixture();
2253 assert_violation_ctor_matches(
2254 LayoutError::etiquetas_violation(&c, issue),
2255 LayoutError::EtiquetasViolation {
2256 caixa: c.nome().to_string(),
2257 issue: issue.to_string(),
2258 },
2259 );
2260 }
2261
2262 #[test]
2263 fn autores_violation_ctor_matches_struct_literal_wrap() {
2264 let (c, issue) = layout_violation_ctor_fixture();
2265 assert_violation_ctor_matches(
2266 LayoutError::autores_violation(&c, issue),
2267 LayoutError::AutoresViolation {
2268 caixa: c.nome().to_string(),
2269 issue: issue.to_string(),
2270 },
2271 );
2272 }
2273
2274 #[test]
2275 fn repositorio_violation_ctor_matches_struct_literal_wrap() {
2276 let (c, issue) = layout_violation_ctor_fixture();
2277 assert_violation_ctor_matches(
2278 LayoutError::repositorio_violation(&c, issue),
2279 LayoutError::RepositorioViolation {
2280 caixa: c.nome().to_string(),
2281 issue: issue.to_string(),
2282 },
2283 );
2284 }
2285
2286 #[test]
2287 fn descricao_violation_ctor_matches_struct_literal_wrap() {
2288 let (c, issue) = layout_violation_ctor_fixture();
2289 assert_violation_ctor_matches(
2290 LayoutError::descricao_violation(&c, issue),
2291 LayoutError::DescricaoViolation {
2292 caixa: c.nome().to_string(),
2293 issue: issue.to_string(),
2294 },
2295 );
2296 }
2297
2298 #[test]
2299 fn licenca_violation_ctor_matches_struct_literal_wrap() {
2300 let (c, issue) = layout_violation_ctor_fixture();
2301 assert_violation_ctor_matches(
2302 LayoutError::licenca_violation(&c, issue),
2303 LayoutError::LicencaViolation {
2304 caixa: c.nome().to_string(),
2305 issue: issue.to_string(),
2306 },
2307 );
2308 }
2309
2310 #[test]
2311 fn edicao_violation_ctor_matches_struct_literal_wrap() {
2312 let (c, issue) = layout_violation_ctor_fixture();
2313 assert_violation_ctor_matches(
2314 LayoutError::edicao_violation(&c, issue),
2315 LayoutError::EdicaoViolation {
2316 caixa: c.nome().to_string(),
2317 issue: issue.to_string(),
2318 },
2319 );
2320 }
2321
2322 #[test]
2323 fn code_path_violation_ctor_matches_struct_literal_wrap() {
2324 let (c, issue) = layout_violation_ctor_fixture();
2325 assert_violation_ctor_matches(
2326 LayoutError::code_path_violation(&c, issue),
2327 LayoutError::CodePathViolation {
2328 caixa: c.nome().to_string(),
2329 issue: issue.to_string(),
2330 },
2331 );
2332 }
2333
2334 #[test]
2335 fn limits_violation_ctor_matches_struct_literal_wrap() {
2336 let (c, issue) = layout_violation_ctor_fixture();
2337 assert_violation_ctor_matches(
2338 LayoutError::limits_violation(&c, issue),
2339 LayoutError::LimitsViolation {
2340 caixa: c.nome().to_string(),
2341 issue: issue.to_string(),
2342 },
2343 );
2344 }
2345
2346 #[test]
2347 fn behavior_violation_ctor_matches_struct_literal_wrap() {
2348 let (c, issue) = layout_violation_ctor_fixture();
2349 assert_violation_ctor_matches(
2350 LayoutError::behavior_violation(&c, issue),
2351 LayoutError::BehaviorViolation {
2352 caixa: c.nome().to_string(),
2353 issue: issue.to_string(),
2354 },
2355 );
2356 }
2357
2358 #[test]
2359 fn upgrade_violation_ctor_matches_struct_literal_wrap() {
2360 let (c, issue) = layout_violation_ctor_fixture();
2361 assert_violation_ctor_matches(
2362 LayoutError::upgrade_violation(&c, issue),
2363 LayoutError::UpgradeViolation {
2364 caixa: c.nome().to_string(),
2365 issue: issue.to_string(),
2366 },
2367 );
2368 }
2369
2370 #[test]
2371 fn restart_window_violation_ctor_matches_struct_literal_wrap() {
2372 let (c, issue) = layout_violation_ctor_fixture();
2373 assert_violation_ctor_matches(
2374 LayoutError::restart_window_violation(&c, issue),
2375 LayoutError::RestartWindowViolation {
2376 caixa: c.nome().to_string(),
2377 issue: issue.to_string(),
2378 },
2379 );
2380 }
2381
2382 #[test]
2383 fn supervisor_violation_ctor_matches_struct_literal_wrap() {
2384 let (c, issue) = layout_violation_ctor_fixture();
2385 assert_violation_ctor_matches(
2386 LayoutError::supervisor_violation(&c, issue),
2387 LayoutError::SupervisorViolation {
2388 caixa: c.nome().to_string(),
2389 issue: issue.to_string(),
2390 },
2391 );
2392 }
2393
2394 #[test]
2395 fn aplicacao_violation_ctor_matches_struct_literal_wrap() {
2396 let (c, issue) = layout_violation_ctor_fixture();
2397 assert_violation_ctor_matches(
2398 LayoutError::aplicacao_violation(&c, issue),
2399 LayoutError::AplicacaoViolation {
2400 caixa: c.nome().to_string(),
2401 issue: issue.to_string(),
2402 },
2403 );
2404 }
2405
2406 #[test]
2407 fn acao_violation_ctor_matches_struct_literal_wrap() {
2408 // Sibling of [`aplicacao_violation_ctor_matches_struct_literal_wrap`]
2409 // / [`supervisor_violation_ctor_matches_struct_literal_wrap`] on
2410 // the third per-kind compound-shape wrap envelope on
2411 // `LayoutError`. Pins the macro-generated `acao_violation`
2412 // constructor to its struct-literal peer under `PartialEq`, so
2413 // every wire-up in [`StandardLayout::verify`] on the
2414 // [`LayoutError::AcaoViolation`] variant produces a byte-equal
2415 // `LayoutError` to the pre-lift open-coded block. Closes the
2416 // pin family the peer per-kind shape wraps already carry.
2417 let (c, issue) = layout_violation_ctor_fixture();
2418 assert_violation_ctor_matches(
2419 LayoutError::acao_violation(&c, issue),
2420 LayoutError::AcaoViolation {
2421 caixa: c.nome().to_string(),
2422 issue: issue.to_string(),
2423 },
2424 );
2425 }
2426
2427 #[test]
2428 fn violation_ctor_routes_issue_through_display_impl() {
2429 // Pin the fold's `issue = err.to_string()` half against any type
2430 // implementing `Display` — a per-arm error type from a foreign
2431 // module (here, `std::io::Error`) threads through byte-equal to
2432 // the struct-literal `.to_string()` construction, so the fold
2433 // does not silently collapse onto `&str`-only inputs.
2434 let c = caixa(CaixaKind::Biblioteca);
2435 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "sample io display source");
2436 let expected_issue = io_err.to_string();
2437 let actual = LayoutError::deps_violation(&c, &io_err);
2438 assert_eq!(
2439 actual,
2440 LayoutError::DepsViolation {
2441 caixa: c.nome().to_string(),
2442 issue: expected_issue,
2443 },
2444 );
2445 }
2446
2447 #[test]
2448 fn violation_ctor_routes_caixa_prefix_through_nome_accessor() {
2449 // Pin the fold's `caixa = caixa.nome().to_string()` half against
2450 // a non-default `:nome` — the accessor threads the caller's
2451 // `:nome` verbatim into the wrap envelope, so the fold does not
2452 // silently collapse onto the default `"demo"` fixture nome.
2453 let mut c = caixa(CaixaKind::Biblioteca);
2454 c.nome = "alt-nome".into();
2455 let actual = LayoutError::behavior_violation(&c, "sample issue");
2456 assert_eq!(
2457 actual,
2458 LayoutError::BehaviorViolation {
2459 caixa: "alt-nome".to_string(),
2460 issue: "sample issue".to_string(),
2461 },
2462 );
2463 }
2464
2465 // ── Caixa::run_layout_gate — per-slot gate + LayoutError wrap fold ───
2466 //
2467 // The [`Caixa::run_layout_gate`] substrate primitive folds the 18
2468 // self-similar `caixa.validate_<slot>().map_err(|err| LayoutError::
2469 // <slot>_violation(caixa, err))?;` wire-up sites at
2470 // [`StandardLayout::verify`] onto one dispatch. The pins below
2471 // (fail-before-pass-after by construction — a silent regression that
2472 // de-folded either arm would trip its own pin first) lock the two
2473 // arms of the fold under `PartialEq`:
2474 //
2475 // - The `Ok(())` identity-element arm passes through verbatim (no
2476 // wrap runs, no `caixa` closure capture).
2477 // - The `Err(E)` arm routes through the caller-supplied `wrap`
2478 // ctor with `self` bound as the caixa slot, byte-equal to the
2479 // pre-lift `.map_err(|err| CTOR(caixa, err))` closure.
2480 //
2481 // The third pin (per-arm equivalence) runs the primitive with the
2482 // canonical `Caixa::validate_nome` validator and the paired
2483 // `LayoutError::nome_violation` ctor on a fixture whose `:nome`
2484 // fails `validate_nome`'s DNS-1123 gate ("Bad_Nome" — the uppercase
2485 // + underscore double footgun) and asserts the primitive's
2486 // `Result<(), LayoutError>` matches the open-coded pre-lift cascade
2487 // on the same fixture. A silent regression that de-folded the wrap
2488 // (dropped the `self` binding, threaded a stale caixa nome, swapped
2489 // the wrap ctor) would surface here as a mismatch between the two
2490 // dispatches.
2491
2492 #[test]
2493 fn run_layout_gate_ok_arm_passes_through() {
2494 // Positive control on the identity-element arm: a gate returning
2495 // `Ok(())` short-circuits before the wrap runs, so the caller
2496 // receives `Ok(())` verbatim regardless of what the paired ctor
2497 // would have produced. Pins the fold's `Result::map_err`
2498 // short-circuit semantics — a regression that unconditionally
2499 // wrapped (e.g. always called the ctor) would trip here.
2500 let c = caixa(CaixaKind::Biblioteca);
2501 let result: Result<(), LayoutError> = c.run_layout_gate(
2502 |_c: &Caixa| Ok::<(), &'static str>(()),
2503 |_c: &Caixa, _err: &'static str| {
2504 panic!("wrap must not run on the Ok(()) arm of the fold")
2505 },
2506 );
2507 assert!(
2508 result.is_ok(),
2509 "run_layout_gate must pass Ok(()) through verbatim, got {result:?}"
2510 );
2511 }
2512
2513 #[test]
2514 fn run_layout_gate_err_arm_wraps_via_ctor() {
2515 // Positive control on the err arm: a gate returning `Err(E)`
2516 // threads `E` into the caller-supplied `wrap` ctor with `self`
2517 // bound as the caixa argument. Uses a synthetic `&'static str`
2518 // error and the canonical `LayoutError::deps_violation` ctor so
2519 // the pin covers the fold's two-callable dispatch shape without
2520 // depending on any per-slot validator's specific arm sweep.
2521 let c = caixa(CaixaKind::Biblioteca);
2522 let sample_reason = "sample gate reason";
2523 let result = c.run_layout_gate(
2524 |_c: &Caixa| Err::<(), &'static str>(sample_reason),
2525 LayoutError::deps_violation,
2526 );
2527 let err = result.expect_err("Err arm must reach the caller");
2528 assert_eq!(
2529 err,
2530 LayoutError::DepsViolation {
2531 caixa: c.nome().to_string(),
2532 issue: sample_reason.to_string(),
2533 },
2534 "run_layout_gate must wrap the gate's Err via the caller-supplied \
2535 ctor with `self` bound as the caixa slot"
2536 );
2537 }
2538
2539 #[test]
2540 fn run_layout_gate_folds_arm_matches_gate() {
2541 // Fail-before-pass-after per-arm equivalence pin on the err arm:
2542 // a fixture whose `:nome` fails `validate_nome`'s DNS-1123 gate
2543 // (`"Bad_Nome"` — uppercase + underscore double footgun the
2544 // [`crate::ManifestError::NomeInvalid`] arm rejects) surfaces
2545 // the same `LayoutError::NomeViolation` byte-equal through both
2546 // the primitive `Caixa::run_layout_gate(Caixa::validate_nome,
2547 // LayoutError::nome_violation)` and the open-coded pre-lift
2548 // cascade `Caixa::validate_nome().map_err(|err|
2549 // LayoutError::nome_violation(&c, err))` on the same Caixa
2550 // fixture. Pins the fold — a silent regression that de-folded
2551 // either arm (dropped the `self` binding, threaded a stale
2552 // caixa nome, swapped the wrap ctor) would surface here as a
2553 // mismatch between the two dispatches.
2554 let mut c = caixa(CaixaKind::Biblioteca);
2555 c.nome = "Bad_Nome".into();
2556 let via_primitive = c
2557 .run_layout_gate(Caixa::validate_nome, LayoutError::nome_violation)
2558 .expect_err("Bad_Nome must fail validate_nome");
2559 let via_open_coded = c
2560 .validate_nome()
2561 .map_err(|err| LayoutError::nome_violation(&c, err))
2562 .expect_err("Bad_Nome must fail validate_nome");
2563 assert_eq!(
2564 via_primitive, via_open_coded,
2565 "Caixa::run_layout_gate must surface the err-arm diagnostic \
2566 byte-equal to the open-coded `.map_err(|err| CTOR(caixa, err))` \
2567 cascade on the same Caixa fixture"
2568 );
2569 assert!(
2570 matches!(via_primitive, LayoutError::NomeViolation { .. }),
2571 "expected NomeViolation on Bad_Nome, got {via_primitive:?}"
2572 );
2573 }
2574
2575 // ── LayoutError kind-coherence constructor family ────────────────────
2576 //
2577 // The [`layout_slot_kind_ctors!`] macro (sibling of
2578 // [`layout_violation_ctors!`] beside the `LayoutError` enum definition)
2579 // generates one static constructor per `*SlotsOn*` / `ForeignCodeSlot`
2580 // variant that folds the uniform `{ caixa: caixa.nome().to_string(),
2581 // kind: caixa.kind(), slots: slots.join(" ") }` four-field construction
2582 // onto one substrate primitive. The per-variant equivalence pins below
2583 // (fail-before-pass-after by construction — a byte-mismatched macro arm
2584 // would trip its equivalence pin first) lock each generated constructor
2585 // to its struct-literal peer under `PartialEq`, so every wire-up in
2586 // [`StandardLayout::verify`] on that variant produces a byte-equal
2587 // `LayoutError` to the pre-lift open-coded block. The three cross-axis
2588 // pins that follow (non-default `:nome`, non-default kind, non-trivial
2589 // slots list) route each of the three constructor input axes through
2590 // its declared accessor / arg, so the fold does not silently collapse
2591 // onto a fixture default on any axis.
2592
2593 fn layout_slot_kind_ctor_fixture() -> (Caixa, Vec<&'static str>) {
2594 (caixa(CaixaKind::Biblioteca), vec![":membros", ":contratos"])
2595 }
2596
2597 // Same rationale as `assert_violation_ctor_matches` above: the helper
2598 // terminates on the equality check, so the owned-arg lint's general
2599 // API-shape target does not apply.
2600 #[allow(clippy::needless_pass_by_value)]
2601 fn assert_slot_kind_ctor_matches(actual: LayoutError, expected: LayoutError) {
2602 assert_eq!(
2603 actual, expected,
2604 "generated constructor must produce byte-equal LayoutError to open-coded struct-literal wrap",
2605 );
2606 }
2607
2608 #[test]
2609 fn mesh_slots_on_non_aplicacao_ctor_matches_struct_literal_wrap() {
2610 let (c, slots) = layout_slot_kind_ctor_fixture();
2611 assert_slot_kind_ctor_matches(
2612 LayoutError::mesh_slots_on_non_aplicacao(&c, slots.clone()),
2613 LayoutError::MeshSlotsOnNonAplicacao {
2614 caixa: c.nome().to_string(),
2615 kind: c.kind(),
2616 slots: slots.join(" "),
2617 },
2618 );
2619 }
2620
2621 #[test]
2622 fn supervisor_slots_on_non_supervisor_ctor_matches_struct_literal_wrap() {
2623 let (c, slots) = layout_slot_kind_ctor_fixture();
2624 assert_slot_kind_ctor_matches(
2625 LayoutError::supervisor_slots_on_non_supervisor(&c, slots.clone()),
2626 LayoutError::SupervisorSlotsOnNonSupervisor {
2627 caixa: c.nome().to_string(),
2628 kind: c.kind(),
2629 slots: slots.join(" "),
2630 },
2631 );
2632 }
2633
2634 #[test]
2635 fn servico_slots_on_non_servico_ctor_matches_struct_literal_wrap() {
2636 let (c, slots) = layout_slot_kind_ctor_fixture();
2637 assert_slot_kind_ctor_matches(
2638 LayoutError::servico_slots_on_non_servico(&c, slots.clone()),
2639 LayoutError::ServicoSlotsOnNonServico {
2640 caixa: c.nome().to_string(),
2641 kind: c.kind(),
2642 slots: slots.join(" "),
2643 },
2644 );
2645 }
2646
2647 #[test]
2648 fn foreign_code_slot_ctor_matches_struct_literal_wrap() {
2649 let (c, slots) = layout_slot_kind_ctor_fixture();
2650 assert_slot_kind_ctor_matches(
2651 LayoutError::foreign_code_slot(&c, slots.clone()),
2652 LayoutError::ForeignCodeSlot {
2653 caixa: c.nome().to_string(),
2654 kind: c.kind(),
2655 slots: slots.join(" "),
2656 },
2657 );
2658 }
2659
2660 #[test]
2661 fn slot_kind_ctor_routes_caixa_prefix_through_nome_accessor() {
2662 // Pin the fold's `caixa = caixa.nome().to_string()` half against a
2663 // non-default `:nome` — the accessor threads the caller's `:nome`
2664 // verbatim into the wrap envelope, so the fold does not silently
2665 // collapse onto the default `"demo"` fixture nome. Peer of the
2666 // sibling `violation_ctor_routes_caixa_prefix_through_nome_accessor`
2667 // pin on the `{ caixa, issue }` envelope; extended here onto the
2668 // `{ caixa, kind, slots }` envelope so both `LayoutError`-shape
2669 // constructor families guarantee the `:nome`-derived-caixa slot
2670 // routes through [`Caixa::nome`] rather than a hard-coded string.
2671 let mut c = caixa(CaixaKind::Biblioteca);
2672 c.nome = "alt-nome".into();
2673 let actual = LayoutError::mesh_slots_on_non_aplicacao(&c, vec![":membros"]);
2674 assert_eq!(
2675 actual,
2676 LayoutError::MeshSlotsOnNonAplicacao {
2677 caixa: "alt-nome".to_string(),
2678 kind: CaixaKind::Biblioteca,
2679 slots: ":membros".to_string(),
2680 },
2681 );
2682 }
2683
2684 #[test]
2685 fn slot_kind_ctor_routes_kind_through_caixa_kind_accessor() {
2686 // Pin the fold's `kind = caixa.kind()` half against a non-default
2687 // kind — the accessor threads the caller's `:kind` verbatim into
2688 // the wrap envelope, so the fold does not silently collapse onto
2689 // one hard-coded kind. Sweeps every non-Aplicacao / non-Supervisor
2690 // / non-Servico kind the corresponding gate can fire on so the
2691 // pin covers the kind-derivation axis on every downstream variant.
2692 for kind in [
2693 CaixaKind::Biblioteca,
2694 CaixaKind::Binario,
2695 CaixaKind::Servico,
2696 CaixaKind::Supervisor,
2697 CaixaKind::Aplicacao,
2698 CaixaKind::Acao,
2699 ] {
2700 let c = caixa(kind);
2701 let actual = LayoutError::foreign_code_slot(&c, vec![":exe"]);
2702 assert_eq!(
2703 actual,
2704 LayoutError::ForeignCodeSlot {
2705 caixa: c.nome().to_string(),
2706 kind,
2707 slots: ":exe".to_string(),
2708 },
2709 "foreign_code_slot ctor must thread `caixa.kind()` verbatim on every kind",
2710 );
2711 }
2712 }
2713
2714 #[test]
2715 fn slot_kind_ctor_routes_slots_through_join_separator() {
2716 // Pin the fold's `slots = slots.join(" ")` half against a
2717 // multi-entry slots list — the join threads exactly one ASCII
2718 // space between entries, in caller-supplied order, so the fold
2719 // does not silently collapse onto a fixed separator (`", "`, `";
2720 // "`, `"\n"`), a sorted order, or a single-entry pass-through.
2721 // Uses the M2 servico-slot vocabulary since these are what the
2722 // corresponding `servico_slots_on_non_servico` gate reports.
2723 let c = caixa(CaixaKind::Biblioteca);
2724 let actual = LayoutError::servico_slots_on_non_servico(
2725 &c,
2726 vec![":limits", ":behavior", ":upgrade-from"],
2727 );
2728 assert_eq!(
2729 actual,
2730 LayoutError::ServicoSlotsOnNonServico {
2731 caixa: c.nome().to_string(),
2732 kind: c.kind(),
2733 slots: ":limits :behavior :upgrade-from".to_string(),
2734 },
2735 );
2736 }
2737
2738 // ── LayoutError::missing_entry substrate-primitive constructor ───────
2739 //
2740 // The [`LayoutError::missing_entry`] constructor beside the enum
2741 // definition folds the `{ kind: &'static str, path: PathBuf }`
2742 // uniform-shape envelope onto one substrate primitive — the third
2743 // and last uniform-shape envelope on `LayoutError` after the
2744 // `{ caixa, issue }` family the [`layout_violation_ctors!`] macro
2745 // closed (131ca0d) and the `{ caixa, kind, slots }` family the peer
2746 // [`layout_slot_kind_ctors!`] macro closed (0419438). The pins below
2747 // (fail-before-pass-after by construction — a byte-mismatched
2748 // constructor arm would trip its equivalence pin first) lock the
2749 // constructor to its struct-literal peer under `PartialEq`, so every
2750 // wire-up in [`StandardLayout::verify`] on this variant produces a
2751 // byte-equal `LayoutError` to the pre-lift open-coded block. The two
2752 // cross-axis pins that follow (canonical-kind-label sweep, non-
2753 // default path) route each of the two constructor input axes through
2754 // its arg verbatim, so the fold does not silently collapse onto a
2755 // fixture default on either axis.
2756
2757 #[test]
2758 fn missing_entry_ctor_matches_struct_literal_wrap() {
2759 // Per-envelope equivalence pin — the `missing_entry` constructor
2760 // produces a `LayoutError::MissingEntry` byte-equal under
2761 // `PartialEq` to the open-coded four-line struct-literal wrap on
2762 // the same `(kind, path)` fixture. Peer of the sibling
2763 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
2764 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap`
2765 // pins on the two prior uniform-shape envelopes on the same
2766 // `LayoutError`.
2767 let path = PathBuf::from("/tmp/x/lib/demo.lisp");
2768 assert_eq!(
2769 LayoutError::missing_entry(
2770 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2771 path.clone(),
2772 ),
2773 LayoutError::MissingEntry {
2774 kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2775 path,
2776 },
2777 );
2778 }
2779
2780 #[test]
2781 fn missing_entry_ctor_routes_kind_through_arg_verbatim() {
2782 // Pin the fold's `kind: &'static str` arg through every canonical
2783 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] label the five
2784 // wire-up sites in [`StandardLayout::verify`] pass — so the fold
2785 // does not silently collapse onto one hard-coded label. Sweep
2786 // matches the arm set the peer
2787 // `layout_missing_entry_kind_m2_consts_pin_canonical_kebab_case_labels`
2788 // pin (below) covers on the const-label declarations.
2789 let path = PathBuf::from("/tmp/x/entry");
2790 for kind in [
2791 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2792 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
2793 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2794 crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
2795 crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
2796 ] {
2797 assert_eq!(
2798 LayoutError::missing_entry(kind, path.clone()),
2799 LayoutError::MissingEntry {
2800 kind,
2801 path: path.clone(),
2802 },
2803 "missing_entry ctor must thread `kind` verbatim on every canonical label",
2804 );
2805 }
2806 }
2807
2808 #[test]
2809 fn missing_entry_ctor_routes_path_through_arg_verbatim() {
2810 // Pin the fold's `path: PathBuf` arg against a non-default,
2811 // multi-component `PathBuf` — the ctor threads the caller's
2812 // `PathBuf` verbatim into the wrap envelope, so the fold does
2813 // not silently collapse onto a fixed component prefix, a
2814 // canonicalized form, or a single-component pass-through.
2815 let path = PathBuf::from("/alt/root")
2816 .join("servicos")
2817 .join("hello-rio.computeunit.yaml");
2818 assert_eq!(
2819 LayoutError::missing_entry(
2820 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2821 path.clone(),
2822 ),
2823 LayoutError::MissingEntry {
2824 kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2825 path,
2826 },
2827 );
2828 }
2829
2830 // ── StandardLayout::probe_declared_entry substrate primitive ─────────
2831 //
2832 // The [`StandardLayout::probe_declared_entry`] method
2833 // (`layout.rs`) folds the five self-similar
2834 // `let full = root.join(p); if !self.exists(&full) { return
2835 // Err(LayoutError::missing_entry(<kind>, full)); }` existence-probe
2836 // blocks at [`StandardLayout::verify`] (`:bibliotecas` iteration,
2837 // `:exe` iteration, `:servicos` iteration, `:behavior` on-disk
2838 // callback-path iteration, `:upgrade-from` per-instruction script-
2839 // path iteration) onto one substrate primitive. The pins below
2840 // (fail-before-pass-after by construction — a byte-mismatched
2841 // primitive body would trip its equivalence pin first) lock the
2842 // fold to its pre-lift open-coded shape under `PartialEq`, so every
2843 // wire-up in [`StandardLayout::verify`] on this primitive produces
2844 // a byte-equal `LayoutError` on miss and a byte-equal `PathBuf` on
2845 // hit.
2846
2847 #[test]
2848 fn probe_declared_entry_folds_miss_returns_missing_entry() {
2849 // Per-primitive equivalence pin on the miss arm — a
2850 // [`StandardLayout`] whose oracle returns `false` for every
2851 // path yields a `MissingEntry` byte-equal under `PartialEq` to
2852 // the open-coded `LayoutError::missing_entry(<kind>,
2853 // root.join(path))` wrap the pre-lift block carried at each of
2854 // the five wire-up sites. Peer of the sibling
2855 // `missing_entry_ctor_matches_struct_literal_wrap` pin on the
2856 // constructor's own byte-equal shape.
2857 let layout = StandardLayout::new().with_path_exists(|_| false);
2858 let root = PathBuf::from("/tmp/x");
2859 let path = Path::new("lib/demo.lisp");
2860 let err = layout
2861 .probe_declared_entry(
2862 path,
2863 &root,
2864 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2865 )
2866 .unwrap_err();
2867 assert_eq!(
2868 err,
2869 LayoutError::missing_entry(
2870 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2871 root.join(path),
2872 ),
2873 "probe_declared_entry miss arm must produce byte-equal LayoutError to \
2874 open-coded `missing_entry(<kind>, root.join(path))` wrap",
2875 );
2876 }
2877
2878 #[test]
2879 fn probe_declared_entry_folds_hit_returns_resolved_full() {
2880 // Per-primitive equivalence pin on the hit arm — a
2881 // [`StandardLayout`] whose oracle returns `true` for the probed
2882 // resolved path yields `Ok(root.join(path))` byte-equal under
2883 // `PartialEq`. The pre-lift `:exe` / `:servicos` wire-up sites
2884 // needed the resolved `full` for the follow-up sandbox-directory-
2885 // containment check; the fold preserves that hand-off through
2886 // the primitive's `Ok(PathBuf)` return arm rather than
2887 // re-computing `root.join(path)` at the follow-up gate.
2888 let root = PathBuf::from("/tmp/x");
2889 let path = Path::new("exe/tool.lisp");
2890 let full = root.join(path);
2891 let full_probe = full.clone();
2892 let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
2893 let resolved = layout
2894 .probe_declared_entry(path, &root, crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE)
2895 .expect("probe_declared_entry must return Ok(root.join(path)) when the oracle hits");
2896 assert_eq!(
2897 resolved, full,
2898 "probe_declared_entry hit arm must return the resolved `root.join(path)` \
2899 byte-equal so the `:exe` / `:servicos` sandbox-containment follow-up \
2900 reads it verbatim without re-computing",
2901 );
2902 }
2903
2904 #[test]
2905 fn probe_declared_entry_threads_kind_through_arg_verbatim() {
2906 // Cross-axis pin — sweep every canonical
2907 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] label the five
2908 // wire-up sites in [`StandardLayout::verify`] pass. Each miss
2909 // must return a `MissingEntry` whose `kind:` field byte-equals
2910 // the caller-provided arg, so the fold does not silently
2911 // collapse onto one hard-coded label. Sweep matches the arm
2912 // set the peer
2913 // `missing_entry_ctor_routes_kind_through_arg_verbatim` pin
2914 // covers on the constructor arg.
2915 let layout = StandardLayout::new().with_path_exists(|_| false);
2916 let root = PathBuf::from("/tmp/x");
2917 let path = Path::new("some/entry");
2918 for kind in [
2919 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2920 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
2921 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2922 crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
2923 crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
2924 ] {
2925 let err = layout.probe_declared_entry(path, &root, kind).unwrap_err();
2926 assert_eq!(
2927 err,
2928 LayoutError::missing_entry(kind, root.join(path)),
2929 "probe_declared_entry must thread `kind` verbatim on every canonical label",
2930 );
2931 }
2932 }
2933
2934 #[test]
2935 fn probe_declared_entry_threads_path_through_arg_verbatim() {
2936 // Cross-axis pin — the primitive must compose the `path` arg
2937 // through `root.join` verbatim on the miss arm's `MissingEntry
2938 // { path: … }` field, so the fold does not silently collapse
2939 // onto a fixed component prefix, a canonicalized form, or a
2940 // hand-authored `root.join(<literal>)`. Sweep two multi-
2941 // component `Path` fixtures (one under `servicos/`, one under
2942 // `lib/`) so a byte-drifted composition on either axis would
2943 // trip.
2944 let layout = StandardLayout::new().with_path_exists(|_| false);
2945 let root = PathBuf::from("/alt/root");
2946 for path in [
2947 Path::new("servicos/hello-rio.computeunit.yaml"),
2948 Path::new("lib/demo.lisp"),
2949 ] {
2950 let err = layout
2951 .probe_declared_entry(
2952 path,
2953 &root,
2954 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2955 )
2956 .unwrap_err();
2957 assert_eq!(
2958 err,
2959 LayoutError::missing_entry(
2960 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2961 root.join(path),
2962 ),
2963 "probe_declared_entry must compose `path` through `root.join` verbatim",
2964 );
2965 }
2966 }
2967
2968 #[test]
2969 fn probe_declared_entry_routes_through_configurable_exists_oracle() {
2970 // Cross-axis pin — the primitive must consult the injected
2971 // [`StandardLayout::with_path_exists`] oracle, not the ambient
2972 // `Path::exists` filesystem probe. Configure a per-path
2973 // discriminator that returns `true` only for one canonical
2974 // resolved path and assert both arms:
2975 // - the "hit" path resolves to `Ok(full)` byte-equal
2976 // - every other path resolves to `MissingEntry` on the same
2977 // [`StandardLayout`] instance
2978 // The pin traps a regression that reroutes the primitive off
2979 // the injected oracle onto the ambient `Path::exists` (which
2980 // would silently return `false` for every path in `/tmp/x/…`
2981 // and mask the miss-arm hand-off on the hit fixture, or
2982 // silently return `true` for a real system path and mask the
2983 // hit-arm hand-off on the miss fixture).
2984 let root = PathBuf::from("/tmp/x");
2985 let hit_path = Path::new("servicos/keep.computeunit.yaml");
2986 let miss_path = Path::new("servicos/drop.computeunit.yaml");
2987 let hit_full = root.join(hit_path);
2988 let hit_full_probe = hit_full.clone();
2989 let layout = StandardLayout::new().with_path_exists(move |p| p == hit_full_probe);
2990
2991 let resolved = layout
2992 .probe_declared_entry(
2993 hit_path,
2994 &root,
2995 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2996 )
2997 .expect("probe_declared_entry must consult the injected oracle on the hit arm");
2998 assert_eq!(
2999 resolved, hit_full,
3000 "probe_declared_entry hit arm must return the oracle-approved resolved path",
3001 );
3002
3003 let err = layout
3004 .probe_declared_entry(
3005 miss_path,
3006 &root,
3007 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3008 )
3009 .unwrap_err();
3010 assert_eq!(
3011 err,
3012 LayoutError::missing_entry(
3013 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3014 root.join(miss_path),
3015 ),
3016 "probe_declared_entry miss arm must fire when the injected oracle rejects the path",
3017 );
3018 }
3019
3020 // ── StandardLayout::probe_sandboxed_declared_entry substrate primitive ─
3021 //
3022 // The [`StandardLayout::probe_sandboxed_declared_entry`] method
3023 // (`layout.rs`) folds the two self-similar `let full = self.
3024 // probe_declared_entry(p, root, <kind>)?; if !full.starts_with(&<slot>_dir)
3025 // { return Err(LayoutError::<Slot>OutsideDir(full)); }` blocks at
3026 // [`StandardLayout::verify`] (`:exe` iteration, `:servicos` iteration)
3027 // onto one substrate primitive. The pins below (fail-before-pass-after
3028 // by construction — a byte-mismatched primitive body would trip its
3029 // equivalence pin first) lock the fold to its pre-lift open-coded
3030 // shape under `PartialEq`, so every wire-up in
3031 // [`StandardLayout::verify`] on this primitive produces a byte-equal
3032 // `LayoutError` on miss / sandbox-escape and a byte-equal `PathBuf`
3033 // on hit.
3034
3035 #[test]
3036 fn probe_sandboxed_declared_entry_folds_miss_returns_missing_entry() {
3037 // Per-primitive equivalence pin on the miss arm — a
3038 // [`StandardLayout`] whose oracle returns `false` for every
3039 // path yields a `MissingEntry` byte-equal under `PartialEq` to
3040 // the open-coded `LayoutError::missing_entry(<kind>,
3041 // root.join(path))` wrap the sibling
3042 // [`StandardLayout::probe_declared_entry`] primitive routes
3043 // through. Diagnostic-order pin: `MissingEntry` outranks the
3044 // `outside_ctor` sandbox-escape arm on the same iteration, so
3045 // an entry that is both absent *and* outside the sandbox fires
3046 // the `MissingEntry` diagnostic (the pre-lift order the two
3047 // wire-up sites carried).
3048 let layout = StandardLayout::new().with_path_exists(|_| false);
3049 let root = PathBuf::from("/tmp/x");
3050 let path = Path::new("lib/tool");
3051 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3052 let err = layout
3053 .probe_sandboxed_declared_entry(
3054 path,
3055 &root,
3056 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3057 &exe_dir,
3058 LayoutError::ExeOutsideDir,
3059 )
3060 .unwrap_err();
3061 assert_eq!(
3062 err,
3063 LayoutError::missing_entry(
3064 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3065 root.join(path),
3066 ),
3067 "probe_sandboxed_declared_entry miss arm must produce byte-equal \
3068 LayoutError to the sibling probe_declared_entry primitive's miss wrap, \
3069 preserving the pre-lift MissingEntry-before-<Slot>OutsideDir diagnostic order",
3070 );
3071 }
3072
3073 #[test]
3074 fn probe_sandboxed_declared_entry_folds_sandbox_escape_via_outside_ctor() {
3075 // Per-primitive equivalence pin on the sandbox-escape arm — a
3076 // [`StandardLayout`] whose oracle admits the probed resolved
3077 // path (so the miss arm passes) but whose resolved path lies
3078 // outside the caller-provided `sandbox_dir` yields the paired
3079 // `outside_ctor(full)` byte-equal under `PartialEq`. The
3080 // primitive threads the resolved `full` through the caller-
3081 // supplied `fn(PathBuf) -> LayoutError` constructor rather
3082 // than a hard-coded variant, so the fold does not silently
3083 // collapse onto one of the two `:exe` / `:servicos` outside-
3084 // dir variants.
3085 let root = PathBuf::from("/tmp/x");
3086 let path = Path::new("lib/tool");
3087 let full = root.join(path);
3088 let full_probe = full.clone();
3089 let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3090 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3091 let err = layout
3092 .probe_sandboxed_declared_entry(
3093 path,
3094 &root,
3095 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3096 &exe_dir,
3097 LayoutError::ExeOutsideDir,
3098 )
3099 .unwrap_err();
3100 assert_eq!(
3101 err,
3102 LayoutError::ExeOutsideDir(full),
3103 "probe_sandboxed_declared_entry sandbox-escape arm must route the \
3104 resolved `full` through the caller-supplied outside_ctor byte-equal to \
3105 the pre-lift `LayoutError::ExeOutsideDir(full)` tuple-literal",
3106 );
3107 }
3108
3109 #[test]
3110 fn probe_sandboxed_declared_entry_folds_hit_returns_resolved_full() {
3111 // Per-primitive equivalence pin on the hit arm — a
3112 // [`StandardLayout`] whose oracle admits the probed path *and*
3113 // whose resolved path lives inside `sandbox_dir` yields
3114 // `Ok(root.join(path))` byte-equal under `PartialEq`. The
3115 // pre-lift wire-ups discarded the resolved `Ok(PathBuf)` since
3116 // no follow-up per-path gate consumes it after the sandbox
3117 // check; the fold preserves the same hit-arm hand-off through
3118 // the primitive's `Ok(PathBuf)` return so a future consumer
3119 // that wants to run a per-path successor gate reaches the
3120 // resolved path without re-computing `root.join(path)`.
3121 let root = PathBuf::from("/tmp/x");
3122 let path = Path::new("exe/tool");
3123 let full = root.join(path);
3124 let full_probe = full.clone();
3125 let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3126 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3127 let resolved = layout
3128 .probe_sandboxed_declared_entry(
3129 path,
3130 &root,
3131 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3132 &exe_dir,
3133 LayoutError::ExeOutsideDir,
3134 )
3135 .expect(
3136 "probe_sandboxed_declared_entry must return Ok(root.join(path)) \
3137 when the oracle admits the path and it lives inside sandbox_dir",
3138 );
3139 assert_eq!(
3140 resolved, full,
3141 "probe_sandboxed_declared_entry hit arm must return the resolved \
3142 `root.join(path)` byte-equal so a future per-path successor gate \
3143 reaches it without re-computing",
3144 );
3145 }
3146
3147 #[test]
3148 fn probe_sandboxed_declared_entry_threads_outside_ctor_through_arg_verbatim() {
3149 // Cross-axis pin — the primitive must thread the caller-
3150 // supplied `outside_ctor` verbatim into the sandbox-escape
3151 // arm's `LayoutError` return, so the fold does not silently
3152 // collapse onto one hard-coded variant. Sweep both
3153 // [`LayoutError`] tuple-variants the two wire-up sites in
3154 // [`StandardLayout::verify`] pass — [`LayoutError::ExeOutsideDir`]
3155 // and [`LayoutError::ServicoOutsideDir`] — so a byte-drifted
3156 // ctor-routing on either axis would trip.
3157 let root = PathBuf::from("/tmp/x");
3158 let outside_dir = root.join(crate::render::LAYOUT_DIR_LIB);
3159 for (kind, sandbox_component, ctor, expected_variant) in [
3160 (
3161 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3162 crate::render::LAYOUT_DIR_EXE,
3163 LayoutError::ExeOutsideDir as fn(PathBuf) -> LayoutError,
3164 LayoutError::ExeOutsideDir as fn(PathBuf) -> LayoutError,
3165 ),
3166 (
3167 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3168 crate::render::LAYOUT_DIR_SERVICOS,
3169 LayoutError::ServicoOutsideDir as fn(PathBuf) -> LayoutError,
3170 LayoutError::ServicoOutsideDir as fn(PathBuf) -> LayoutError,
3171 ),
3172 ] {
3173 let path = outside_dir.strip_prefix(&root).unwrap().join("tool");
3174 let full = root.join(&path);
3175 let full_probe = full.clone();
3176 let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3177 let sandbox_dir = root.join(sandbox_component);
3178 let err = layout
3179 .probe_sandboxed_declared_entry(&path, &root, kind, &sandbox_dir, ctor)
3180 .unwrap_err();
3181 assert_eq!(
3182 err,
3183 expected_variant(full),
3184 "probe_sandboxed_declared_entry must thread `outside_ctor` verbatim \
3185 on every canonical `<Slot>OutsideDir` variant the two wire-up sites pass",
3186 );
3187 }
3188 }
3189
3190 #[test]
3191 fn probe_sandboxed_declared_entry_routes_miss_arm_through_probe_declared_entry() {
3192 // Cross-primitive pin — the sandboxed probe must route its
3193 // miss arm through the sibling [`StandardLayout::
3194 // probe_declared_entry`] primitive rather than re-inlining the
3195 // `root.join` + `exists` + `missing_entry` cascade, so a
3196 // future edit to the miss-arm shape on either primitive lands
3197 // in exactly one place. Byte-parity assertion: on a fixture
3198 // that misses the oracle, the sandboxed primitive's `Err`
3199 // arm must equal the peer [`StandardLayout::
3200 // probe_declared_entry`] primitive's `Err` arm on the same
3201 // fixture — otherwise the fold has drifted from the substrate
3202 // primitive.
3203 let layout = StandardLayout::new().with_path_exists(|_| false);
3204 let root = PathBuf::from("/tmp/x");
3205 let path = Path::new("servicos/hello-rio.computeunit.yaml");
3206 let sandbox_dir = root.join(crate::render::LAYOUT_DIR_SERVICOS);
3207 let via_sandboxed = layout
3208 .probe_sandboxed_declared_entry(
3209 path,
3210 &root,
3211 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3212 &sandbox_dir,
3213 LayoutError::ServicoOutsideDir,
3214 )
3215 .unwrap_err();
3216 let via_probe = layout
3217 .probe_declared_entry(
3218 path,
3219 &root,
3220 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3221 )
3222 .unwrap_err();
3223 assert_eq!(
3224 via_sandboxed, via_probe,
3225 "probe_sandboxed_declared_entry's miss arm must equal the sibling \
3226 probe_declared_entry primitive's miss arm byte-equal — pins that the \
3227 sandboxed primitive routes through the substrate primitive rather than \
3228 re-inlining the `root.join` + `exists` + `missing_entry` cascade",
3229 );
3230 }
3231
3232 // ── StandardLayout::probe_declared_entries substrate primitive ───────
3233 //
3234 // The [`StandardLayout::probe_declared_entries`] method (`layout.rs`)
3235 // folds the three self-similar per-slot existence-probe *loop* blocks
3236 // at [`StandardLayout::verify`] (`:bibliotecas` iteration,
3237 // `:behavior` on-disk callback-path iteration, `:upgrade-from` per-
3238 // instruction script-path iteration) onto one substrate primitive.
3239 // The pins below (fail-before-pass-after by construction — a byte-
3240 // mismatched primitive body would trip its equivalence pin first)
3241 // lock the fold to its pre-lift open-coded shape under `PartialEq`,
3242 // so every wire-up in [`StandardLayout::verify`] on this primitive
3243 // produces a byte-equal `LayoutError` on miss (via the sibling
3244 // [`StandardLayout::probe_declared_entry`] miss arm) and a byte-
3245 // equal `Ok(())` on the empty / all-hit arms (the fold's identity
3246 // element on an empty slot list; the pre-lift `for … { … }` loop's
3247 // vacuous pass-through).
3248 //
3249 // Sibling of the peer per-arm-probe [`StandardLayout::probe_declared_entry`]
3250 // (fda1e35) and two-arm-sandboxed [`StandardLayout::
3251 // probe_sandboxed_declared_entry`] (4940d55) primitive test blocks
3252 // — same substrate-primitive discipline extended onto the per-slot
3253 // batch axis these two per-path primitives compose under.
3254
3255 #[test]
3256 fn probe_declared_entries_folds_empty_iterator_returns_ok() {
3257 // Per-primitive identity-element pin on the empty-iterator arm —
3258 // the fold's `Ok(())` return on an empty `IntoIterator` is byte-
3259 // equal to the pre-lift `for _ in <empty> { … }` loop's vacuous
3260 // pass-through. Peer of the peer-primitive `Option::None →
3261 // Ok(())` identity elements the sibling per-Caixa compound
3262 // gates ([`crate::Caixa::validate_limits`] baa4688,
3263 // [`crate::Caixa::validate_behavior`] 0d2877a) each carry on
3264 // the sibling per-slot compound-gate axis.
3265 let layout = StandardLayout::new().with_path_exists(|_| false);
3266 let root = PathBuf::from("/tmp/x");
3267 let empty: [&Path; 0] = [];
3268 layout
3269 .probe_declared_entries(
3270 empty,
3271 &root,
3272 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3273 )
3274 .expect(
3275 "probe_declared_entries must return Ok(()) on an empty iterator \
3276 — the fold's identity element on an empty per-slot batch",
3277 );
3278 }
3279
3280 #[test]
3281 fn probe_declared_entries_folds_all_hits_returns_ok() {
3282 // Per-primitive equivalence pin on the all-hit arm — a
3283 // [`StandardLayout`] whose oracle admits every path in the batch
3284 // yields `Ok(())` byte-equal to the pre-lift `for p in … {
3285 // self.probe_declared_entry(p, root, kind)?; }` loop's full-
3286 // consumption pass-through.
3287 let root = PathBuf::from("/tmp/x");
3288 let a = root.join("lib/a.lisp");
3289 let b = root.join("lib/b.lisp");
3290 let a_probe = a.clone();
3291 let b_probe = b.clone();
3292 let layout = StandardLayout::new().with_path_exists(move |p| p == a_probe || p == b_probe);
3293 layout
3294 .probe_declared_entries(
3295 [Path::new("lib/a.lisp"), Path::new("lib/b.lisp")],
3296 &root,
3297 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3298 )
3299 .expect(
3300 "probe_declared_entries must return Ok(()) when every path in the \
3301 batch is admitted by the oracle",
3302 );
3303 }
3304
3305 #[test]
3306 fn probe_declared_entries_folds_first_miss_short_circuits_via_probe_declared_entry() {
3307 // Per-primitive equivalence pin on the first-miss arm — a
3308 // [`StandardLayout`] whose oracle admits the first path and
3309 // rejects the second yields a `MissingEntry` byte-equal under
3310 // `PartialEq` to the sibling [`StandardLayout::
3311 // probe_declared_entry`] primitive's miss wrap on the *second*
3312 // path (the pre-lift `for … { … ? }` loop's first-error return
3313 // semantics), *not* on the first (admitted) path.
3314 let root = PathBuf::from("/tmp/x");
3315 let hit = root.join("lib/a.lisp");
3316 let hit_probe = hit.clone();
3317 let layout = StandardLayout::new().with_path_exists(move |p| p == hit_probe);
3318 let miss = Path::new("lib/b.lisp");
3319 let err = layout
3320 .probe_declared_entries(
3321 [Path::new("lib/a.lisp"), miss],
3322 &root,
3323 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3324 )
3325 .unwrap_err();
3326 assert_eq!(
3327 err,
3328 LayoutError::missing_entry(
3329 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3330 root.join(miss),
3331 ),
3332 "probe_declared_entries must short-circuit on the first missing entry \
3333 with a `MissingEntry` byte-equal to the sibling probe_declared_entry \
3334 primitive's miss wrap on that entry — the pre-lift `for … {{ … ? }}` \
3335 loop's first-error return semantics",
3336 );
3337 }
3338
3339 #[test]
3340 fn probe_declared_entries_folds_first_miss_short_circuits_before_later_paths() {
3341 // Diagnostic-order pin — the primitive must return on the *first*
3342 // miss in iterator order rather than probing every path and
3343 // returning the last miss (which would silently drop the pre-
3344 // lift `for … { … ? }` loop's first-error contract). Fixture:
3345 // the oracle rejects both paths, so a byte-equal `MissingEntry`
3346 // on the *first* path in the iterator distinguishes the two
3347 // return-order shapes.
3348 let layout = StandardLayout::new().with_path_exists(|_| false);
3349 let root = PathBuf::from("/tmp/x");
3350 let first = Path::new("lib/first.lisp");
3351 let second = Path::new("lib/second.lisp");
3352 let err = layout
3353 .probe_declared_entries(
3354 [first, second],
3355 &root,
3356 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3357 )
3358 .unwrap_err();
3359 assert_eq!(
3360 err,
3361 LayoutError::missing_entry(
3362 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3363 root.join(first),
3364 ),
3365 "probe_declared_entries must return on the *first* miss in iterator order \
3366 — a `MissingEntry` on the second path would silently drop the pre-lift \
3367 `for … {{ … ? }}` loop's first-error contract",
3368 );
3369 }
3370
3371 #[test]
3372 fn probe_declared_entries_threads_kind_through_arg_verbatim() {
3373 // Cross-axis pin — sweep every canonical
3374 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] label the three
3375 // batch wire-up sites in [`StandardLayout::verify`] pass through
3376 // this primitive (`:bibliotecas`, `:behavior` callback,
3377 // `:upgrade-from` script). Each miss must return a `MissingEntry`
3378 // whose `kind:` field byte-equals the caller-provided arg, so
3379 // the fold does not silently collapse onto one hard-coded label.
3380 // Sibling of the peer `probe_declared_entry_threads_kind_through_arg_verbatim`
3381 // pin's five-label sweep on the per-arm primitive.
3382 let layout = StandardLayout::new().with_path_exists(|_| false);
3383 let root = PathBuf::from("/tmp/x");
3384 let path = Path::new("some/entry");
3385 for kind in [
3386 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3387 crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
3388 crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
3389 ] {
3390 let err = layout
3391 .probe_declared_entries([path], &root, kind)
3392 .unwrap_err();
3393 assert_eq!(
3394 err,
3395 LayoutError::missing_entry(kind, root.join(path)),
3396 "probe_declared_entries must thread `kind` verbatim on every canonical \
3397 batch label",
3398 );
3399 }
3400 }
3401
3402 #[test]
3403 fn probe_declared_entries_accepts_asref_path_shape_wire_up_sites_pass() {
3404 // Cross-axis pin — the primitive's `P: AsRef<Path>` bound must
3405 // admit every concrete iterator element type the three
3406 // [`StandardLayout::verify`] wire-up sites pass:
3407 // - `&String` (from `caixa.bibliotecas(): &[String]`),
3408 // - `&Path` (from `b.declared_paths(): impl Iterator<Item = &Path>`),
3409 // - `&PathBuf` (from the flattened `.filter_map(_::declared_path)`
3410 // on `:upgrade-from` instructions, whose `declared_path`
3411 // returns `Option<&PathBuf>`).
3412 //
3413 // Byte-parity assertion: on a shared `/tmp/x/lib/demo.lisp`
3414 // fixture the miss-arm return must be byte-equal across all
3415 // three element-type flavors, so a future re-shape of the
3416 // bound (a narrower `P: Into<PathBuf>` collapse, a stricter
3417 // `&Path`-only signature) would surface here rather than at
3418 // the caller wire-up site.
3419 let layout = StandardLayout::new().with_path_exists(|_| false);
3420 let root = PathBuf::from("/tmp/x");
3421 let literal = "lib/demo.lisp";
3422 let expected = LayoutError::missing_entry(
3423 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3424 root.join(Path::new(literal)),
3425 );
3426
3427 let via_string_slice: Vec<String> = vec![literal.to_string()];
3428 let via_string_err = layout
3429 .probe_declared_entries(
3430 via_string_slice.iter(),
3431 &root,
3432 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3433 )
3434 .unwrap_err();
3435 assert_eq!(
3436 via_string_err, expected,
3437 "probe_declared_entries must accept `&String` items (the `caixa.bibliotecas() \
3438 : &[String]` wire-up shape)",
3439 );
3440
3441 let via_path_slice: [&Path; 1] = [Path::new(literal)];
3442 let via_path_err = layout
3443 .probe_declared_entries(
3444 via_path_slice,
3445 &root,
3446 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3447 )
3448 .unwrap_err();
3449 assert_eq!(
3450 via_path_err, expected,
3451 "probe_declared_entries must accept `&Path` items (the `b.declared_paths() \
3452 : impl Iterator<Item = &Path>` wire-up shape)",
3453 );
3454
3455 let via_pathbuf_slice: Vec<PathBuf> = vec![PathBuf::from(literal)];
3456 let via_pathbuf_err = layout
3457 .probe_declared_entries(
3458 via_pathbuf_slice.iter(),
3459 &root,
3460 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3461 )
3462 .unwrap_err();
3463 assert_eq!(
3464 via_pathbuf_err, expected,
3465 "probe_declared_entries must accept `&PathBuf` items (the `.filter_map( \
3466 _::declared_path)` on `:upgrade-from` instructions wire-up shape)",
3467 );
3468 }
3469
3470 #[test]
3471 fn probe_declared_entries_routes_miss_arm_through_probe_declared_entry() {
3472 // Cross-primitive pin — the batch primitive must route its miss
3473 // arm through the sibling [`StandardLayout::probe_declared_entry`]
3474 // primitive rather than re-inlining the `root.join` + `exists`
3475 // + `missing_entry` cascade, so a future edit to the miss-arm
3476 // shape on either primitive lands in exactly one place. Byte-
3477 // parity assertion: on a fixture that misses the oracle, the
3478 // batch primitive's `Err` arm must equal the peer per-arm
3479 // [`StandardLayout::probe_declared_entry`] primitive's `Err` arm
3480 // on the same fixture — otherwise the batch fold has drifted
3481 // from the substrate primitive. Same discipline the peer
3482 // `probe_sandboxed_declared_entry_routes_miss_arm_through_probe_declared_entry`
3483 // pin establishes on the sibling sandboxed-primitive axis.
3484 let layout = StandardLayout::new().with_path_exists(|_| false);
3485 let root = PathBuf::from("/tmp/x");
3486 let path = Path::new("lib/demo.lisp");
3487 let via_batch = layout
3488 .probe_declared_entries(
3489 [path],
3490 &root,
3491 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3492 )
3493 .unwrap_err();
3494 let via_probe = layout
3495 .probe_declared_entry(
3496 path,
3497 &root,
3498 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3499 )
3500 .unwrap_err();
3501 assert_eq!(
3502 via_batch, via_probe,
3503 "probe_declared_entries's miss arm must equal the sibling probe_declared_entry \
3504 primitive's miss arm byte-equal — pins that the batch primitive routes \
3505 through the substrate primitive rather than re-inlining the `root.join` + \
3506 `exists` + `missing_entry` cascade",
3507 );
3508 }
3509
3510 // ── StandardLayout::probe_sandboxed_declared_entries substrate primitive ─
3511 //
3512 // The [`StandardLayout::probe_sandboxed_declared_entries`] method
3513 // (`layout.rs`) folds the two self-similar per-slot sandboxed-
3514 // existence-probe *loop* blocks at [`StandardLayout::verify`]
3515 // (`:exe` iteration, `:servicos` iteration) onto one substrate
3516 // primitive. The pins below (fail-before-pass-after by construction
3517 // — a byte-mismatched primitive body would trip its equivalence pin
3518 // first) lock the fold to its pre-lift open-coded shape under
3519 // `PartialEq`, so every wire-up in [`StandardLayout::verify`] on
3520 // this primitive produces a byte-equal `LayoutError` on miss / on
3521 // sandbox-escape (via the sibling
3522 // [`StandardLayout::probe_sandboxed_declared_entry`] arms) and a
3523 // byte-equal `Ok(())` on the empty / all-hit arms (the fold's
3524 // identity element on an empty slot list; the pre-lift `for … {
3525 // … }` loop's vacuous pass-through).
3526 //
3527 // Sibling of the peer per-slot batch bare-probe
3528 // [`StandardLayout::probe_declared_entries`] (d1ccb0b), per-arm
3529 // bare-probe [`StandardLayout::probe_declared_entry`] (fda1e35), and
3530 // per-arm sandboxed-probe
3531 // [`StandardLayout::probe_sandboxed_declared_entry`] (4940d55)
3532 // primitive test blocks — same substrate-primitive discipline
3533 // extended onto the fourth and last quadrant of the
3534 // (per-arm | per-slot batch) × (bare | sandboxed) existence-probe
3535 // algebra.
3536
3537 #[test]
3538 fn probe_sandboxed_declared_entries_folds_empty_iterator_returns_ok() {
3539 // Per-primitive identity-element pin on the empty-iterator arm —
3540 // the fold's `Ok(())` return on an empty `IntoIterator` is byte-
3541 // equal to the pre-lift `for _ in <empty> { … }` loop's vacuous
3542 // pass-through. Peer of the sibling
3543 // `probe_declared_entries_folds_empty_iterator_returns_ok` pin
3544 // on the bare-batch axis and the `Option::None → Ok(())`
3545 // identity elements the per-Caixa compound gates
3546 // ([`crate::Caixa::validate_limits`] baa4688,
3547 // [`crate::Caixa::validate_behavior`] 0d2877a) each carry on the
3548 // per-slot compound-gate axis.
3549 let layout = StandardLayout::new().with_path_exists(|_| false);
3550 let root = PathBuf::from("/tmp/x");
3551 let empty: [&Path; 0] = [];
3552 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3553 layout
3554 .probe_sandboxed_declared_entries(
3555 empty,
3556 &root,
3557 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3558 &exe_dir,
3559 LayoutError::ExeOutsideDir,
3560 )
3561 .expect(
3562 "probe_sandboxed_declared_entries must return Ok(()) on an empty iterator \
3563 — the fold's identity element on an empty per-slot sandboxed batch",
3564 );
3565 }
3566
3567 #[test]
3568 fn probe_sandboxed_declared_entries_folds_all_hits_returns_ok() {
3569 // Per-primitive equivalence pin on the all-hit arm — a
3570 // [`StandardLayout`] whose oracle admits every path in the batch
3571 // *and* whose resolved paths live inside `sandbox_dir` yields
3572 // `Ok(())` byte-equal to the pre-lift `for p in … {
3573 // self.probe_sandboxed_declared_entry(p, root, kind,
3574 // &sandbox_dir, outside_ctor)?; }` loop's full-consumption
3575 // pass-through.
3576 let root = PathBuf::from("/tmp/x");
3577 let a = root.join("exe/a");
3578 let b = root.join("exe/b");
3579 let a_probe = a.clone();
3580 let b_probe = b.clone();
3581 let layout = StandardLayout::new().with_path_exists(move |p| p == a_probe || p == b_probe);
3582 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3583 layout
3584 .probe_sandboxed_declared_entries(
3585 [Path::new("exe/a"), Path::new("exe/b")],
3586 &root,
3587 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3588 &exe_dir,
3589 LayoutError::ExeOutsideDir,
3590 )
3591 .expect(
3592 "probe_sandboxed_declared_entries must return Ok(()) when every path in \
3593 the batch is admitted by the oracle and lives inside sandbox_dir",
3594 );
3595 }
3596
3597 #[test]
3598 fn probe_sandboxed_declared_entries_folds_first_miss_short_circuits_via_probe_sandboxed_declared_entry()
3599 {
3600 // Per-primitive equivalence pin on the first-miss arm — a
3601 // [`StandardLayout`] whose oracle admits the first path (inside
3602 // sandbox_dir) and rejects the second yields a `MissingEntry`
3603 // byte-equal under `PartialEq` to the sibling
3604 // [`StandardLayout::probe_sandboxed_declared_entry`] primitive's
3605 // miss wrap on the *second* path (the pre-lift `for … { … ? }`
3606 // loop's first-error return semantics), *not* on the first
3607 // (admitted) path.
3608 let root = PathBuf::from("/tmp/x");
3609 let hit = root.join("exe/a");
3610 let hit_probe = hit.clone();
3611 let layout = StandardLayout::new().with_path_exists(move |p| p == hit_probe);
3612 let miss = Path::new("exe/b");
3613 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3614 let err = layout
3615 .probe_sandboxed_declared_entries(
3616 [Path::new("exe/a"), miss],
3617 &root,
3618 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3619 &exe_dir,
3620 LayoutError::ExeOutsideDir,
3621 )
3622 .unwrap_err();
3623 assert_eq!(
3624 err,
3625 LayoutError::missing_entry(
3626 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3627 root.join(miss),
3628 ),
3629 "probe_sandboxed_declared_entries must short-circuit on the first missing \
3630 entry with a `MissingEntry` byte-equal to the sibling \
3631 probe_sandboxed_declared_entry primitive's miss wrap on that entry — the \
3632 pre-lift `for … {{ … ? }}` loop's first-error return semantics",
3633 );
3634 }
3635
3636 #[test]
3637 fn probe_sandboxed_declared_entries_folds_first_miss_short_circuits_before_later_paths() {
3638 // Diagnostic-order pin — the primitive must return on the *first*
3639 // miss in iterator order rather than probing every path and
3640 // returning the last miss (which would silently drop the pre-
3641 // lift `for … { … ? }` loop's first-error contract). Fixture:
3642 // the oracle rejects both paths, so a byte-equal `MissingEntry`
3643 // on the *first* path in the iterator distinguishes the two
3644 // return-order shapes. Sibling of the peer
3645 // `probe_declared_entries_folds_first_miss_short_circuits_before_later_paths`
3646 // pin on the bare-batch axis.
3647 let layout = StandardLayout::new().with_path_exists(|_| false);
3648 let root = PathBuf::from("/tmp/x");
3649 let first = Path::new("exe/first");
3650 let second = Path::new("exe/second");
3651 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3652 let err = layout
3653 .probe_sandboxed_declared_entries(
3654 [first, second],
3655 &root,
3656 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3657 &exe_dir,
3658 LayoutError::ExeOutsideDir,
3659 )
3660 .unwrap_err();
3661 assert_eq!(
3662 err,
3663 LayoutError::missing_entry(
3664 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3665 root.join(first),
3666 ),
3667 "probe_sandboxed_declared_entries must return on the *first* miss in iterator \
3668 order — a `MissingEntry` on the second path would silently drop the pre-lift \
3669 `for … {{ … ? }}` loop's first-error contract",
3670 );
3671 }
3672
3673 #[test]
3674 fn probe_sandboxed_declared_entries_folds_sandbox_escape_via_outside_ctor() {
3675 // Per-primitive equivalence pin on the sandbox-escape arm — a
3676 // [`StandardLayout`] whose oracle admits the probed resolved
3677 // path (so the miss arm passes) but whose resolved path lies
3678 // outside the caller-provided `sandbox_dir` yields the paired
3679 // `outside_ctor(full)` byte-equal under `PartialEq`. The
3680 // primitive threads the resolved `full` through the caller-
3681 // supplied `fn(PathBuf) -> LayoutError` constructor rather than
3682 // a hard-coded variant, so the fold does not silently collapse
3683 // onto one of the two `:exe` / `:servicos` outside-dir variants.
3684 let root = PathBuf::from("/tmp/x");
3685 let path = Path::new("lib/tool");
3686 let full = root.join(path);
3687 let full_probe = full.clone();
3688 let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3689 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3690 let err = layout
3691 .probe_sandboxed_declared_entries(
3692 [path],
3693 &root,
3694 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3695 &exe_dir,
3696 LayoutError::ExeOutsideDir,
3697 )
3698 .unwrap_err();
3699 assert_eq!(
3700 err,
3701 LayoutError::ExeOutsideDir(full),
3702 "probe_sandboxed_declared_entries sandbox-escape arm must route the resolved \
3703 `full` through the caller-supplied outside_ctor byte-equal to the pre-lift \
3704 `LayoutError::ExeOutsideDir(full)` tuple-literal",
3705 );
3706 }
3707
3708 #[test]
3709 fn probe_sandboxed_declared_entries_threads_outside_ctor_through_arg_verbatim() {
3710 // Cross-axis pin — the primitive must thread the caller-supplied
3711 // `outside_ctor` verbatim into the sandbox-escape arm's
3712 // `LayoutError` return, so the fold does not silently collapse
3713 // onto one hard-coded variant. Sweep both [`LayoutError`]
3714 // tuple-variants the two wire-up sites in
3715 // [`StandardLayout::verify`] pass — [`LayoutError::ExeOutsideDir`]
3716 // and [`LayoutError::ServicoOutsideDir`] — so a byte-drifted
3717 // ctor-routing on either axis would trip. Sibling of the peer
3718 // `probe_sandboxed_declared_entry_threads_outside_ctor_through_arg_verbatim`
3719 // pin on the per-arm sandboxed-primitive axis.
3720 let root = PathBuf::from("/tmp/x");
3721 let outside_dir = root.join(crate::render::LAYOUT_DIR_LIB);
3722 for (kind, sandbox_component, ctor) in [
3723 (
3724 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3725 crate::render::LAYOUT_DIR_EXE,
3726 LayoutError::ExeOutsideDir as fn(PathBuf) -> LayoutError,
3727 ),
3728 (
3729 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3730 crate::render::LAYOUT_DIR_SERVICOS,
3731 LayoutError::ServicoOutsideDir as fn(PathBuf) -> LayoutError,
3732 ),
3733 ] {
3734 let path = outside_dir.strip_prefix(&root).unwrap().join("tool");
3735 let full = root.join(&path);
3736 let full_probe = full.clone();
3737 let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3738 let sandbox_dir = root.join(sandbox_component);
3739 let err = layout
3740 .probe_sandboxed_declared_entries([&path], &root, kind, &sandbox_dir, ctor)
3741 .unwrap_err();
3742 assert_eq!(
3743 err,
3744 ctor(full),
3745 "probe_sandboxed_declared_entries must thread `outside_ctor` verbatim on \
3746 every canonical `<Slot>OutsideDir` variant the two wire-up sites pass",
3747 );
3748 }
3749 }
3750
3751 #[test]
3752 fn probe_sandboxed_declared_entries_threads_kind_through_arg_verbatim() {
3753 // Cross-axis pin — sweep every canonical
3754 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] label the two
3755 // sandboxed-batch wire-up sites in [`StandardLayout::verify`]
3756 // pass through this primitive (`:exe`, `:servicos`). Each miss
3757 // must return a `MissingEntry` whose `kind:` field byte-equals
3758 // the caller-provided arg, so the fold does not silently
3759 // collapse onto one hard-coded label. Sibling of the peer
3760 // `probe_declared_entries_threads_kind_through_arg_verbatim`
3761 // pin's label sweep on the bare-batch axis.
3762 let layout = StandardLayout::new().with_path_exists(|_| false);
3763 let root = PathBuf::from("/tmp/x");
3764 let path = Path::new("some/entry");
3765 for (kind, sandbox_component, ctor) in [
3766 (
3767 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3768 crate::render::LAYOUT_DIR_EXE,
3769 LayoutError::ExeOutsideDir as fn(PathBuf) -> LayoutError,
3770 ),
3771 (
3772 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3773 crate::render::LAYOUT_DIR_SERVICOS,
3774 LayoutError::ServicoOutsideDir as fn(PathBuf) -> LayoutError,
3775 ),
3776 ] {
3777 let sandbox_dir = root.join(sandbox_component);
3778 let err = layout
3779 .probe_sandboxed_declared_entries([path], &root, kind, &sandbox_dir, ctor)
3780 .unwrap_err();
3781 assert_eq!(
3782 err,
3783 LayoutError::missing_entry(kind, root.join(path)),
3784 "probe_sandboxed_declared_entries must thread `kind` verbatim on every \
3785 canonical sandboxed-batch label",
3786 );
3787 }
3788 }
3789
3790 #[test]
3791 fn probe_sandboxed_declared_entries_accepts_asref_path_shape_wire_up_sites_pass() {
3792 // Cross-axis pin — the primitive's `P: AsRef<Path>` bound must
3793 // admit every concrete iterator element type the two
3794 // [`StandardLayout::verify`] wire-up sites pass:
3795 // - `&String` (from `caixa.exe(): &[String]`),
3796 // - `&String` (from `caixa.servicos(): &[String]`).
3797 //
3798 // Byte-parity assertion: on a shared `/tmp/x/lib/demo`
3799 // fixture the miss-arm return must be byte-equal across
3800 // `&String` and the ergonomic `&Path` / `&PathBuf` element-type
3801 // flavors, so a future re-shape of the bound (a narrower `P:
3802 // Into<PathBuf>` collapse, a stricter `&Path`-only signature)
3803 // would surface here rather than at the caller wire-up site.
3804 // Sibling of the peer
3805 // `probe_declared_entries_accepts_asref_path_shape_wire_up_sites_pass`
3806 // pin on the bare-batch axis.
3807 let layout = StandardLayout::new().with_path_exists(|_| false);
3808 let root = PathBuf::from("/tmp/x");
3809 let literal = "exe/demo";
3810 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3811 let expected = LayoutError::missing_entry(
3812 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3813 root.join(Path::new(literal)),
3814 );
3815
3816 let via_string_slice: Vec<String> = vec![literal.to_string()];
3817 let via_string_err = layout
3818 .probe_sandboxed_declared_entries(
3819 via_string_slice.iter(),
3820 &root,
3821 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3822 &exe_dir,
3823 LayoutError::ExeOutsideDir,
3824 )
3825 .unwrap_err();
3826 assert_eq!(
3827 via_string_err, expected,
3828 "probe_sandboxed_declared_entries must accept `&String` items (the `caixa.exe() \
3829 : &[String]` / `caixa.servicos(): &[String]` wire-up shape)",
3830 );
3831
3832 let via_path_slice: [&Path; 1] = [Path::new(literal)];
3833 let via_path_err = layout
3834 .probe_sandboxed_declared_entries(
3835 via_path_slice,
3836 &root,
3837 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3838 &exe_dir,
3839 LayoutError::ExeOutsideDir,
3840 )
3841 .unwrap_err();
3842 assert_eq!(
3843 via_path_err, expected,
3844 "probe_sandboxed_declared_entries must accept `&Path` items",
3845 );
3846
3847 let via_pathbuf_slice: Vec<PathBuf> = vec![PathBuf::from(literal)];
3848 let via_pathbuf_err = layout
3849 .probe_sandboxed_declared_entries(
3850 via_pathbuf_slice.iter(),
3851 &root,
3852 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3853 &exe_dir,
3854 LayoutError::ExeOutsideDir,
3855 )
3856 .unwrap_err();
3857 assert_eq!(
3858 via_pathbuf_err, expected,
3859 "probe_sandboxed_declared_entries must accept `&PathBuf` items",
3860 );
3861 }
3862
3863 #[test]
3864 fn probe_sandboxed_declared_entries_routes_miss_arm_through_probe_sandboxed_declared_entry() {
3865 // Cross-primitive pin — the batch primitive must route its miss
3866 // arm through the sibling
3867 // [`StandardLayout::probe_sandboxed_declared_entry`] primitive
3868 // rather than re-inlining the `probe_declared_entry` +
3869 // `starts_with` cascade, so a future edit to the miss-arm shape
3870 // on either primitive lands in exactly one place. Byte-parity
3871 // assertion: on a fixture that misses the oracle, the batch
3872 // primitive's `Err` arm must equal the peer per-arm
3873 // [`StandardLayout::probe_sandboxed_declared_entry`] primitive's
3874 // `Err` arm on the same fixture — otherwise the batch fold has
3875 // drifted from the substrate primitive. Same discipline the peer
3876 // `probe_declared_entries_routes_miss_arm_through_probe_declared_entry`
3877 // pin establishes on the sibling bare-batch axis.
3878 let layout = StandardLayout::new().with_path_exists(|_| false);
3879 let root = PathBuf::from("/tmp/x");
3880 let path = Path::new("servicos/hello-rio.computeunit.yaml");
3881 let sandbox_dir = root.join(crate::render::LAYOUT_DIR_SERVICOS);
3882 let via_batch = layout
3883 .probe_sandboxed_declared_entries(
3884 [path],
3885 &root,
3886 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3887 &sandbox_dir,
3888 LayoutError::ServicoOutsideDir,
3889 )
3890 .unwrap_err();
3891 let via_probe = layout
3892 .probe_sandboxed_declared_entry(
3893 path,
3894 &root,
3895 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3896 &sandbox_dir,
3897 LayoutError::ServicoOutsideDir,
3898 )
3899 .unwrap_err();
3900 assert_eq!(
3901 via_batch, via_probe,
3902 "probe_sandboxed_declared_entries's miss arm must equal the sibling \
3903 probe_sandboxed_declared_entry primitive's miss arm byte-equal — pins that \
3904 the batch primitive routes through the substrate primitive rather than \
3905 re-inlining the `probe_declared_entry` + `starts_with` cascade",
3906 );
3907 }
3908
3909 #[test]
3910 fn probe_sandboxed_declared_entries_routes_sandbox_escape_arm_through_probe_sandboxed_declared_entry()
3911 {
3912 // Cross-primitive pin — the batch primitive's sandbox-escape arm
3913 // must equal the sibling
3914 // [`StandardLayout::probe_sandboxed_declared_entry`] primitive's
3915 // sandbox-escape arm on the same fixture. Byte-parity assertion:
3916 // on a fixture where the oracle admits the probed path but the
3917 // resolved path lies outside sandbox_dir, both primitives must
3918 // return the same `outside_ctor(full)` byte-equal under
3919 // `PartialEq` — otherwise the batch fold has drifted from the
3920 // per-arm primitive on the second-arm dispatch.
3921 let root = PathBuf::from("/tmp/x");
3922 let path = Path::new("lib/escape");
3923 let full = root.join(path);
3924 let full_probe = full.clone();
3925 let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3926 let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3927 let via_batch = layout
3928 .probe_sandboxed_declared_entries(
3929 [path],
3930 &root,
3931 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3932 &exe_dir,
3933 LayoutError::ExeOutsideDir,
3934 )
3935 .unwrap_err();
3936 let via_probe = layout
3937 .probe_sandboxed_declared_entry(
3938 path,
3939 &root,
3940 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3941 &exe_dir,
3942 LayoutError::ExeOutsideDir,
3943 )
3944 .unwrap_err();
3945 assert_eq!(
3946 via_batch, via_probe,
3947 "probe_sandboxed_declared_entries's sandbox-escape arm must equal the sibling \
3948 probe_sandboxed_declared_entry primitive's sandbox-escape arm byte-equal — \
3949 pins that the batch primitive routes through the substrate primitive on both \
3950 the miss and sandbox-escape arms rather than re-inlining either cascade",
3951 );
3952 }
3953
3954 // ── LayoutError::<nome-only> constructor family ──────────────────────
3955 //
3956 // The [`layout_nome_only_ctors!`] macro (below the `LayoutError` enum
3957 // definition) generates one static constructor per `<Variant>(String)`
3958 // tuple-variant that folds the uniform `Self::<Variant>(caixa.nome()
3959 // .to_string())` one-field construction onto one substrate primitive.
3960 // The per-variant equivalence pins below (fail-before-pass-after by
3961 // construction — a byte-mismatched macro arm would trip its
3962 // equivalence pin first) lock each generated constructor to its
3963 // tuple-literal peer under `PartialEq`, so every wire-up in
3964 // [`StandardLayout::verify`] on that variant produces a byte-equal
3965 // `LayoutError` to the pre-lift open-coded tuple-literal. The
3966 // cross-axis pin that follows (non-default `:nome`) routes the sole
3967 // constructor input axis through its declared accessor, so the fold
3968 // does not silently collapse onto the fixture default `:nome`.
3969
3970 fn layout_nome_only_ctor_fixture() -> Caixa {
3971 caixa(CaixaKind::Biblioteca)
3972 }
3973
3974 // Same rationale as `assert_violation_ctor_matches` / `assert_slot_
3975 // kind_ctor_matches` above: the helper terminates on the equality
3976 // check, so the owned-arg lint's general API-shape target does not
3977 // apply.
3978 #[allow(clippy::needless_pass_by_value)]
3979 fn assert_nome_only_ctor_matches(actual: LayoutError, expected: LayoutError) {
3980 assert_eq!(
3981 actual, expected,
3982 "generated constructor must produce byte-equal LayoutError to open-coded tuple-literal wrap",
3983 );
3984 }
3985
3986 #[test]
3987 fn binario_without_exe_ctor_matches_tuple_literal_wrap() {
3988 let c = layout_nome_only_ctor_fixture();
3989 assert_nome_only_ctor_matches(
3990 LayoutError::binario_without_exe(&c),
3991 LayoutError::BinarioWithoutExe(c.nome().to_string()),
3992 );
3993 }
3994
3995 #[test]
3996 fn servico_without_servicos_ctor_matches_tuple_literal_wrap() {
3997 let c = layout_nome_only_ctor_fixture();
3998 assert_nome_only_ctor_matches(
3999 LayoutError::servico_without_servicos(&c),
4000 LayoutError::ServicoWithoutServicos(c.nome().to_string()),
4001 );
4002 }
4003
4004 #[test]
4005 fn missing_ci_ctor_matches_tuple_literal_wrap() {
4006 let c = layout_nome_only_ctor_fixture();
4007 assert_nome_only_ctor_matches(
4008 LayoutError::missing_ci(&c),
4009 LayoutError::MissingCi(c.nome().to_string()),
4010 );
4011 }
4012
4013 #[test]
4014 fn supervisor_owns_code_ctor_matches_tuple_literal_wrap() {
4015 let c = layout_nome_only_ctor_fixture();
4016 assert_nome_only_ctor_matches(
4017 LayoutError::supervisor_owns_code(&c),
4018 LayoutError::SupervisorOwnsCode(c.nome().to_string()),
4019 );
4020 }
4021
4022 #[test]
4023 fn aplicacao_owns_code_ctor_matches_tuple_literal_wrap() {
4024 let c = layout_nome_only_ctor_fixture();
4025 assert_nome_only_ctor_matches(
4026 LayoutError::aplicacao_owns_code(&c),
4027 LayoutError::AplicacaoOwnsCode(c.nome().to_string()),
4028 );
4029 }
4030
4031 #[test]
4032 fn acao_owns_code_ctor_matches_tuple_literal_wrap() {
4033 let c = layout_nome_only_ctor_fixture();
4034 assert_nome_only_ctor_matches(
4035 LayoutError::acao_owns_code(&c),
4036 LayoutError::AcaoOwnsCode(c.nome().to_string()),
4037 );
4038 }
4039
4040 #[test]
4041 fn nome_only_ctor_routes_caixa_through_nome_accessor() {
4042 // Pin the fold's `caixa.nome().to_string()` sole-field construction
4043 // against a non-default `:nome` — the accessor threads the caller's
4044 // `:nome` verbatim into the tuple-variant, so the fold does not
4045 // silently collapse onto the default `"demo"` fixture nome. Peer of
4046 // the sibling `violation_ctor_routes_caixa_prefix_through_nome_
4047 // accessor` / `slot_kind_ctor_routes_caixa_prefix_through_nome_
4048 // accessor` pins on the `{ caixa, issue }` / `{ caixa, kind,
4049 // slots }` envelopes; extended here onto the sixth
4050 // `<Variant>(String)` envelope so every LayoutError-shape ctor
4051 // family guarantees the `:nome`-derived-caixa slot routes through
4052 // [`Caixa::nome`] rather than a hard-coded string. Sweeps the six
4053 // ctors in the [`layout_nome_only_ctors!`] macro so the pin covers
4054 // every generated arm.
4055 let mut c = caixa(CaixaKind::Biblioteca);
4056 c.nome = "alt-nome".into();
4057 assert_eq!(
4058 LayoutError::binario_without_exe(&c),
4059 LayoutError::BinarioWithoutExe("alt-nome".to_string()),
4060 );
4061 assert_eq!(
4062 LayoutError::servico_without_servicos(&c),
4063 LayoutError::ServicoWithoutServicos("alt-nome".to_string()),
4064 );
4065 assert_eq!(
4066 LayoutError::missing_ci(&c),
4067 LayoutError::MissingCi("alt-nome".to_string()),
4068 );
4069 assert_eq!(
4070 LayoutError::supervisor_owns_code(&c),
4071 LayoutError::SupervisorOwnsCode("alt-nome".to_string()),
4072 );
4073 assert_eq!(
4074 LayoutError::aplicacao_owns_code(&c),
4075 LayoutError::AplicacaoOwnsCode("alt-nome".to_string()),
4076 );
4077 assert_eq!(
4078 LayoutError::acao_owns_code(&c),
4079 LayoutError::AcaoOwnsCode("alt-nome".to_string()),
4080 );
4081 }
4082
4083 #[test]
4084 fn biblioteca_needs_default_lib_path() {
4085 let root = PathBuf::from("/tmp/x");
4086 let expect_manifest = root.join("caixa.lisp");
4087 let layout = StandardLayout::new().with_path_exists(move |p| p == expect_manifest);
4088 let err = layout
4089 .verify(&caixa(CaixaKind::Biblioteca), &root)
4090 .unwrap_err();
4091 assert!(matches!(err, LayoutError::MissingLib { .. }));
4092 }
4093
4094 #[test]
4095 fn biblioteca_passes_when_default_lib_exists() {
4096 let root = PathBuf::from("/tmp/x");
4097 let manifest = root.join("caixa.lisp");
4098 let default_lib = root.join("lib").join("demo.lisp");
4099 let layout =
4100 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4101 layout
4102 .verify(&caixa(CaixaKind::Biblioteca), &root)
4103 .expect("should pass");
4104 }
4105
4106 #[test]
4107 fn binario_without_exe_errors() {
4108 let root = PathBuf::from("/tmp/x");
4109 let manifest = root.join("caixa.lisp");
4110 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
4111 let err = layout
4112 .verify(&caixa(CaixaKind::Binario), &root)
4113 .unwrap_err();
4114 assert!(matches!(err, LayoutError::BinarioWithoutExe(_)));
4115 }
4116
4117 #[test]
4118 fn exe_outside_dir_errors() {
4119 // A relative entry that lives under the caixa root but *not*
4120 // under `exe/` — the canonical case the `starts_with(exe_dir)`
4121 // fence catches. The prior parent-escape shape this test used
4122 // (`"../sibling/tool"`) is now caught at validate time by
4123 // [`Caixa::validate_code_paths`] with the narrower
4124 // [`crate::ManifestError::CodePathParentEscape`] diagnostic
4125 // (see the layout-level integration pin
4126 // `code_path_violation_on_parent_escape_fires_before_existence_check`),
4127 // so this fence pin uses a non-`..` non-absolute shape outside
4128 // `exe/` to preserve coverage of the ExeOutsideDir surface.
4129 let root = PathBuf::from("/tmp/x");
4130 let manifest = root.join("caixa.lisp");
4131 let outside = root.join("lib/tool");
4132 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == outside);
4133 let mut c = caixa(CaixaKind::Binario);
4134 c.exe = vec!["lib/tool".into()];
4135 let err = layout.verify(&c, &root).unwrap_err();
4136 assert!(matches!(err, LayoutError::ExeOutsideDir(_)));
4137 }
4138
4139 // ── code-path shape gate (lifted to layout-level verify) ─────────────
4140
4141 #[test]
4142 fn code_path_violation_on_empty_bibliotecas_entry() {
4143 let root = PathBuf::from("/tmp/x");
4144 let manifest = root.join("caixa.lisp");
4145 let default_lib = root.join("lib").join("demo.lisp");
4146 let layout =
4147 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4148 let mut c = caixa(CaixaKind::Biblioteca);
4149 c.bibliotecas = vec![String::new()];
4150 let err = layout.verify(&c, &root).unwrap_err();
4151 // The wire-up wraps `ManifestError` Display into the
4152 // CodePathViolation envelope (peer of LimitsViolation /
4153 // BehaviorViolation / UpgradeViolation), so the issue string
4154 // names the offending slot at the source.
4155 let LayoutError::CodePathViolation { caixa, issue } = err else {
4156 panic!("expected LayoutError::CodePathViolation, got {err:?}");
4157 };
4158 assert_eq!(caixa, "demo");
4159 assert!(
4160 issue.contains(":bibliotecas"),
4161 "issue must name the offending slot: {issue}",
4162 );
4163 }
4164
4165 #[test]
4166 fn code_path_violation_on_absolute_servicos_entry() {
4167 let root = PathBuf::from("/tmp/x");
4168 let manifest = root.join("caixa.lisp");
4169 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
4170 let mut c = caixa(CaixaKind::Servico);
4171 c.servicos = vec!["/etc/servicos/escape.yaml".into()];
4172 let err = layout.verify(&c, &root).unwrap_err();
4173 let LayoutError::CodePathViolation { caixa, issue } = err else {
4174 panic!("expected LayoutError::CodePathViolation, got {err:?}");
4175 };
4176 assert_eq!(caixa, "demo");
4177 assert!(
4178 issue.contains(":servicos"),
4179 "issue must name the offending slot: {issue}",
4180 );
4181 assert!(
4182 issue.contains("/etc/servicos/escape.yaml"),
4183 "issue must quote the offending path: {issue}",
4184 );
4185 }
4186
4187 #[test]
4188 fn code_path_violation_on_parent_escape_fires_before_existence_check() {
4189 // The new gate runs BEFORE the existence loops, so a
4190 // parent-escaping `:exe` entry surfaces CodePathViolation
4191 // (naming `:exe` at the source) rather than the downstream
4192 // ExeOutsideDir / MissingEntry against the resolved sandbox-
4193 // escape path. Even if the resolved escape target exists
4194 // on disk (which we simulate here by claiming it does), the
4195 // shape diagnostic wins.
4196 let root = PathBuf::from("/tmp/x");
4197 let manifest = root.join("caixa.lisp");
4198 let resolved_escape = root.join("exe/../../escape.lisp");
4199 let layout =
4200 StandardLayout::new().with_path_exists(move |p| p == manifest || p == resolved_escape);
4201 let mut c = caixa(CaixaKind::Binario);
4202 c.exe = vec!["exe/../../escape.lisp".into()];
4203 let err = layout.verify(&c, &root).unwrap_err();
4204 let LayoutError::CodePathViolation { caixa, issue } = err else {
4205 panic!("expected LayoutError::CodePathViolation, got {err:?}");
4206 };
4207 assert_eq!(caixa, "demo");
4208 assert!(
4209 issue.contains(":exe"),
4210 "issue must name the offending slot: {issue}",
4211 );
4212 }
4213
4214 // ── etiquetas universal-axis gate wired into verify ─────────────────
4215 //
4216 // Pins the layout-pipeline wire-up of [`Caixa::validate_etiquetas`]:
4217 // the fourth universal-axis Caixa-level value-shape gate (peer of
4218 // `validate_nome` / `validate_versao` / `validate_deps` /
4219 // `validate_code_paths`), wired before the kind-coherence gates so
4220 // a structurally-invalid `:etiquetas` entry on any kind surfaces
4221 // the per-axis `EtiquetasViolation { caixa, issue }` envelope at
4222 // the source rather than silently rendering as `keywords: [""]`
4223 // in `Chart.yaml` (Servico kind, via caixa-helm's `BTreeSet`
4224 // collect) or silently dedup'ing at chart render (every kind).
4225 // Until this wire-up landed `:etiquetas` had no shape gate at any
4226 // layer — the registry-search-tag axis was the largest universal
4227 // authoring surface on the typed Caixa surface with no validate
4228 // discipline.
4229 //
4230 // Same per-axis `*Violation { caixa, issue }` envelope every peer
4231 // per-axis wrap exposes; the wire-up runs after `validate_deps`
4232 // (universal axis ordering: `:nome` → `:versao` → `:deps` →
4233 // `:etiquetas`) and before every kind-coherence gate
4234 // (`:etiquetas` is universal so its shape diagnostic is more
4235 // fundamental than the partition-on-kind diagnostics).
4236
4237 #[test]
4238 fn etiquetas_violation_on_empty_entry() {
4239 // Canonical paste-from-blank-doc footgun on every kind. The
4240 // wrap envelope wraps [`ManifestError::EtiquetaEmpty`]'s
4241 // Display through verbatim, so the issue string names the
4242 // offending `:etiquetas` axis at the source — the author can
4243 // grep their caixa.lisp for `:etiquetas` and fix the empty
4244 // entry in one edit. Mirrors the peer
4245 // `code_path_violation_on_empty_bibliotecas_entry` shape
4246 // (b868442) on the `:bibliotecas` axis.
4247 let root = PathBuf::from("/tmp/x");
4248 let manifest = root.join("caixa.lisp");
4249 let default_lib = root.join("lib").join("demo.lisp");
4250 let layout =
4251 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4252 let mut c = caixa(CaixaKind::Biblioteca);
4253 c.etiquetas = vec![String::new()];
4254 let err = layout.verify(&c, &root).unwrap_err();
4255 let LayoutError::EtiquetasViolation { caixa, issue } = err else {
4256 panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
4257 };
4258 assert_eq!(caixa, "demo");
4259 assert!(
4260 issue.contains(":etiquetas"),
4261 "issue must name the offending slot: {issue}",
4262 );
4263 }
4264
4265 #[test]
4266 fn etiquetas_violation_on_duplicate_entry() {
4267 // Canonical copy-paste-the-wrong-tag footgun. Without the wire-
4268 // up the duplicate was silently dedup'd by caixa-helm's
4269 // `BTreeSet` collect at chart render — a "second wins / one
4270 // silently disappears" shape. The wrap envelope names the
4271 // offending tag verbatim through the inner
4272 // [`ManifestError::EtiquetaDuplicate`]'s Display.
4273 let root = PathBuf::from("/tmp/x");
4274 let manifest = root.join("caixa.lisp");
4275 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
4276 let mut c = caixa(CaixaKind::Servico);
4277 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
4278 c.etiquetas = vec!["demo".into(), "demo".into()];
4279 // The servicos path doesn't exist in this fixture, but the
4280 // `:etiquetas` gate fires before the existence loop (universal
4281 // axis dominates kind-specific existence checks). Wire is
4282 // intact iff the wrap envelope surfaces first.
4283 let err = layout.verify(&c, &root).unwrap_err();
4284 let LayoutError::EtiquetasViolation { caixa, issue } = err else {
4285 panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
4286 };
4287 assert_eq!(caixa, "demo");
4288 assert!(
4289 issue.contains("demo"),
4290 "issue must quote the offending tag: {issue}",
4291 );
4292 }
4293
4294 #[test]
4295 fn etiquetas_violation_fires_before_kind_coherence_mesh_slot() {
4296 // Cross-axis precedence pin: a Biblioteca with malformed
4297 // `:etiquetas` *and* declared mesh slots (`:membros`) surfaces
4298 // the universal `:etiquetas` diagnostic first, not the
4299 // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4300 // `:etiquetas` is universal (every kind owns the slot), so its
4301 // shape diagnostic is more fundamental than the partition-on-
4302 // kind diagnostic. Mirrors the peer
4303 // `deps_violation_fires_before_*` precedence pins (aa77d0f) on
4304 // the universal `:deps` axis vs the same kind-coherence gates.
4305 let root = PathBuf::from("/tmp/x");
4306 let manifest = root.join("caixa.lisp");
4307 let default_lib = root.join("lib").join("demo.lisp");
4308 let layout =
4309 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4310 let mut c = caixa(CaixaKind::Biblioteca);
4311 c.etiquetas = vec![String::new()];
4312 c.membros = vec![crate::aplicacao::Membro {
4313 caixa: "x".into(),
4314 versao: "^0.1".into(),
4315 }];
4316 let err = layout.verify(&c, &root).unwrap_err();
4317 assert!(
4318 matches!(err, LayoutError::EtiquetasViolation { .. }),
4319 "got {err:?}",
4320 );
4321 }
4322
4323 #[test]
4324 fn etiquetas_violation_fires_after_deps_violation() {
4325 // Cross-axis precedence pin (inside the universal-axis trio):
4326 // a caixa with both a malformed `:deps` entry *and* a malformed
4327 // `:etiquetas` entry surfaces `DepsViolation` first — `:deps`
4328 // is the third universal axis in declaration order
4329 // (`:nome` → `:versao` → `:deps` → `:etiquetas`) and runs first
4330 // in `verify`. Mirrors the peer
4331 // `nome_violation_fires_before_versao_violation` shape on the
4332 // identity-axis pair.
4333 let root = PathBuf::from("/tmp/x");
4334 let manifest = root.join("caixa.lisp");
4335 let default_lib = root.join("lib").join("demo.lisp");
4336 let layout =
4337 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4338 let mut c = caixa(CaixaKind::Biblioteca);
4339 c.deps = vec![crate::Dep::simple("Caixa-Teia", "^0.1")]; // uppercase :nome
4340 c.etiquetas = vec![String::new()];
4341 let err = layout.verify(&c, &root).unwrap_err();
4342 assert!(
4343 matches!(err, LayoutError::DepsViolation { .. }),
4344 "got {err:?}",
4345 );
4346 }
4347
4348 #[test]
4349 fn etiquetas_violation_accepts_canonical_template() {
4350 // Positive control sanity pin: the canonical `Caixa::template`
4351 // shape (`:etiquetas ()` — empty list) passes the gate
4352 // trivially. Mirrors the peer
4353 // `validate_code_paths_accepts_canonical_template` pin.
4354 let root = PathBuf::from("/tmp/x");
4355 let manifest = root.join("caixa.lisp");
4356 let default_lib = root.join("lib").join("demo.lisp");
4357 let layout =
4358 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4359 let c = caixa(CaixaKind::Biblioteca);
4360 layout.verify(&c, &root).expect("template must pass");
4361 }
4362
4363 #[test]
4364 fn etiquetas_violation_on_non_chart_keyword_shape() {
4365 // Canonical CSV-list-separator-confusion footgun: the author
4366 // confused the CSV-style separator with the `:etiquetas` list
4367 // grammar. The shape gate fires past the empty + duplicate
4368 // arms via [`Caixa::validate_etiquetas`]'s new
4369 // `is_chart_keyword_shape` cascade, and the layout envelope
4370 // wraps [`ManifestError::EtiquetaInvalid`]'s Display through
4371 // verbatim — the issue string names both the offending slot
4372 // and the offending value (debug-escaped). Peer with the
4373 // `autores_violation_on_non_chart_maintainer_shape` pin on
4374 // the sibling universal-axis `Vec<String>` surface — the
4375 // second layout pin on the Vec<String> per-entry shape
4376 // cascade.
4377 let root = PathBuf::from("/tmp/x");
4378 let manifest = root.join("caixa.lisp");
4379 let default_lib = root.join("lib").join("demo.lisp");
4380 let layout =
4381 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4382 let mut c = caixa(CaixaKind::Biblioteca);
4383 c.etiquetas = vec!["mesh,http,grpc".into()];
4384 let err = layout.verify(&c, &root).unwrap_err();
4385 let LayoutError::EtiquetasViolation { caixa, issue } = err else {
4386 panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
4387 };
4388 assert_eq!(caixa, "demo");
4389 assert!(
4390 issue.contains(":etiquetas"),
4391 "issue must name the offending slot: {issue}",
4392 );
4393 assert!(
4394 issue.contains("mesh,http,grpc"),
4395 "issue must quote the offending value: {issue}",
4396 );
4397 }
4398
4399 // ── autores universal-axis gate wired into verify ───────────────────
4400 //
4401 // Pins the layout-pipeline wire-up of [`Caixa::validate_autores`]:
4402 // the fifth universal-axis Caixa-level value-shape gate (peer of
4403 // `validate_nome` / `validate_versao` / `validate_deps` /
4404 // `validate_etiquetas` / `validate_code_paths`), wired immediately
4405 // after `validate_etiquetas` so the two Vec-shaped universal
4406 // metadata axes sit adjacent in the cascade. Until this wire-up
4407 // landed `:autores` had no shape gate at any layer — the
4408 // maintainer-axis was the second largest universal authoring
4409 // surface on the typed Caixa surface with no validate discipline,
4410 // and unlike `:etiquetas` (caixa-helm dedups the rendered
4411 // `keywords:` array via `BTreeSet` collect at chart render),
4412 // `maintainers:` has *no* renderer-side dedup, so duplicate
4413 // `:autores` entries render verbatim as two identical
4414 // `Maintainer { name, email: None }` records — a strictly worse
4415 // footgun than the peer `:etiquetas` shape.
4416
4417 #[test]
4418 fn autores_violation_on_empty_entry() {
4419 // Canonical paste-from-blank-doc footgun on every kind. The
4420 // wrap envelope wraps [`ManifestError::AutorEmpty`]'s Display
4421 // through verbatim, so the issue string names the offending
4422 // `:autores` axis at the source — the author can grep their
4423 // caixa.lisp for `:autores` and fix the empty entry in one
4424 // edit. Mirrors the peer `etiquetas_violation_on_empty_entry`
4425 // shape (360a499) on the `:etiquetas` axis.
4426 let root = PathBuf::from("/tmp/x");
4427 let manifest = root.join("caixa.lisp");
4428 let default_lib = root.join("lib").join("demo.lisp");
4429 let layout =
4430 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4431 let mut c = caixa(CaixaKind::Biblioteca);
4432 c.autores = vec![String::new()];
4433 let err = layout.verify(&c, &root).unwrap_err();
4434 let LayoutError::AutoresViolation { caixa, issue } = err else {
4435 panic!("expected LayoutError::AutoresViolation, got {err:?}");
4436 };
4437 assert_eq!(caixa, "demo");
4438 assert!(
4439 issue.contains(":autores"),
4440 "issue must name the offending slot: {issue}",
4441 );
4442 }
4443
4444 #[test]
4445 fn autores_violation_on_duplicate_entry() {
4446 // Canonical copy-paste-the-wrong-author footgun. Unlike the
4447 // peer `:etiquetas` axis (silently dedup'd by caixa-helm's
4448 // `BTreeSet` collect at chart render), `:autores` duplicates
4449 // stack verbatim in the rendered `maintainers:` — the gate
4450 // closes the footgun at validate time before any renderer
4451 // sees it. The wrap envelope names the offending author
4452 // verbatim through the inner [`ManifestError::AutorDuplicate`]'s
4453 // Display.
4454 let root = PathBuf::from("/tmp/x");
4455 let manifest = root.join("caixa.lisp");
4456 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
4457 let mut c = caixa(CaixaKind::Servico);
4458 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
4459 c.autores = vec!["pleme-io".into(), "pleme-io".into()];
4460 // The servicos path doesn't exist in this fixture, but the
4461 // `:autores` gate fires before the existence loop (universal
4462 // axis dominates kind-specific existence checks). Wire is
4463 // intact iff the wrap envelope surfaces first.
4464 let err = layout.verify(&c, &root).unwrap_err();
4465 let LayoutError::AutoresViolation { caixa, issue } = err else {
4466 panic!("expected LayoutError::AutoresViolation, got {err:?}");
4467 };
4468 assert_eq!(caixa, "demo");
4469 assert!(
4470 issue.contains("pleme-io"),
4471 "issue must quote the offending author: {issue}",
4472 );
4473 }
4474
4475 #[test]
4476 fn autores_violation_fires_before_kind_coherence_mesh_slot() {
4477 // Cross-axis precedence pin: a Biblioteca with malformed
4478 // `:autores` *and* declared mesh slots (`:membros`) surfaces
4479 // the universal `:autores` diagnostic first, not the
4480 // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4481 // `:autores` is universal (every kind owns the slot), so its
4482 // shape diagnostic is more fundamental than the partition-on-
4483 // kind diagnostic. Mirrors the peer
4484 // `etiquetas_violation_fires_before_kind_coherence_mesh_slot`
4485 // pin (360a499) on the `:etiquetas` axis vs the same kind-
4486 // coherence gates.
4487 let root = PathBuf::from("/tmp/x");
4488 let manifest = root.join("caixa.lisp");
4489 let default_lib = root.join("lib").join("demo.lisp");
4490 let layout =
4491 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4492 let mut c = caixa(CaixaKind::Biblioteca);
4493 c.autores = vec![String::new()];
4494 c.membros = vec![crate::aplicacao::Membro {
4495 caixa: "x".into(),
4496 versao: "^0.1".into(),
4497 }];
4498 let err = layout.verify(&c, &root).unwrap_err();
4499 assert!(
4500 matches!(err, LayoutError::AutoresViolation { .. }),
4501 "got {err:?}",
4502 );
4503 }
4504
4505 #[test]
4506 fn autores_violation_fires_after_etiquetas_violation() {
4507 // Cross-axis precedence pin (inside the Vec-shaped universal
4508 // metadata pair): a caixa with both a malformed `:etiquetas`
4509 // entry *and* a malformed `:autores` entry surfaces
4510 // `EtiquetasViolation` first — `:etiquetas` is the fourth
4511 // universal axis in the cascade and runs before `:autores`,
4512 // peer with the canonical identity-axis-first cascade the
4513 // peer gates establish. Mirrors the peer
4514 // `etiquetas_violation_fires_after_deps_violation` precedence
4515 // pin (360a499) on the dep-axis-before-tag-axis pair.
4516 let root = PathBuf::from("/tmp/x");
4517 let manifest = root.join("caixa.lisp");
4518 let default_lib = root.join("lib").join("demo.lisp");
4519 let layout =
4520 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4521 let mut c = caixa(CaixaKind::Biblioteca);
4522 c.etiquetas = vec![String::new()];
4523 c.autores = vec![String::new()];
4524 let err = layout.verify(&c, &root).unwrap_err();
4525 assert!(
4526 matches!(err, LayoutError::EtiquetasViolation { .. }),
4527 "got {err:?}",
4528 );
4529 }
4530
4531 #[test]
4532 fn autores_violation_accepts_canonical_template() {
4533 // Positive control sanity pin: the canonical `Caixa::template`
4534 // shape (`:autores ()` — empty list) passes the gate trivially.
4535 // Mirrors the peer `etiquetas_violation_accepts_canonical_template`
4536 // pin (360a499).
4537 let root = PathBuf::from("/tmp/x");
4538 let manifest = root.join("caixa.lisp");
4539 let default_lib = root.join("lib").join("demo.lisp");
4540 let layout =
4541 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4542 let c = caixa(CaixaKind::Biblioteca);
4543 layout.verify(&c, &root).expect("template must pass");
4544 }
4545
4546 #[test]
4547 fn autores_violation_on_non_chart_maintainer_shape() {
4548 // Canonical paste-from-multiline-doc footgun: the author
4549 // pasted a multi-line block of author records into one
4550 // `:autores` entry instead of splitting into one entry per
4551 // author. The shape gate fires past the empty + duplicate arms
4552 // via [`Caixa::validate_autores`]'s new
4553 // `is_chart_maintainer_name_shape` cascade, and the layout
4554 // envelope wraps [`ManifestError::AutorInvalid`]'s Display
4555 // through verbatim — the issue string names both the offending
4556 // slot and the offending value (debug-escaped). Peer with the
4557 // `descricao_violation_on_non_chart_shape` pin on the sibling
4558 // universal-axis `Option<String>` surface and the
4559 // `licenca_violation_on_non_spdx_shape` /
4560 // `edicao_violation_on_non_year_shape` peers — and the first
4561 // layout pin on the Vec<String> per-entry shape cascade.
4562 let root = PathBuf::from("/tmp/x");
4563 let manifest = root.join("caixa.lisp");
4564 let default_lib = root.join("lib").join("demo.lisp");
4565 let layout =
4566 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4567 let mut c = caixa(CaixaKind::Biblioteca);
4568 c.autores = vec!["alice\nbob".into()];
4569 let err = layout.verify(&c, &root).unwrap_err();
4570 let LayoutError::AutoresViolation { caixa, issue } = err else {
4571 panic!("expected LayoutError::AutoresViolation, got {err:?}");
4572 };
4573 assert_eq!(caixa, "demo");
4574 assert!(
4575 issue.contains(":autores"),
4576 "issue must name the offending slot: {issue}",
4577 );
4578 assert!(
4579 issue.contains("alice\\nbob"),
4580 "issue must quote the offending value (debug-escaped): {issue}",
4581 );
4582 }
4583
4584 // ── repositorio universal-axis gate wired into verify ────────────────
4585 //
4586 // Pins the layout-pipeline wire-up of [`Caixa::validate_repositorio`]:
4587 // the sixth universal-axis Caixa-level value-shape gate (peer of
4588 // `validate_nome` / `validate_versao` / `validate_deps` /
4589 // `validate_etiquetas` / `validate_autores` / `validate_code_paths`),
4590 // wired immediately after `validate_autores` so the universal
4591 // git-URL axis sits adjacent to the two Vec-shaped universal
4592 // metadata axes (`:etiquetas`, `:autores`) in the cascade. Until
4593 // this wire-up landed `:repositorio` had no shape gate at any
4594 // layer — the universal git-shaped homepage axis was the third
4595 // largest universal authoring surface on the typed Caixa with no
4596 // validate discipline, routing the same string through two
4597 // load-bearing substrate consumers (`caixa-helm`'s `Chart.yaml
4598 // home:` field and `caixa-flux`'s FluxCD `GitRepository.spec.url`)
4599 // via `Option::unwrap_or_else` fallbacks that only fire on `None` —
4600 // a `Some("")` silently passed every fallback and rendered as an
4601 // empty URL in both consumers, breaking at `helm template` /
4602 // FluxCD reconcile time far from the source `caixa.lisp`. The
4603 // gate closes the divergence and makes the two `git URL`-shaped
4604 // surfaces on the typed Caixa (`:repositorio` here, `:deps :fonte
4605 // :repo` peer routed through the same shared
4606 // `crate::render::is_git_repo_url` predicate) structurally
4607 // equivalent by construction.
4608
4609 #[test]
4610 fn repositorio_violation_on_empty_some() {
4611 // Canonical paste-from-blank-doc footgun on every kind. The
4612 // wrap envelope wraps [`ManifestError::RepositorioEmpty`]'s
4613 // Display through verbatim, so the issue string names the
4614 // offending `:repositorio` axis at the source — the author
4615 // can grep their caixa.lisp for `:repositorio ""` and fix the
4616 // empty value in one edit. Mirrors the peer
4617 // `autores_violation_on_empty_entry` shape (86c769b) on the
4618 // `:autores` axis.
4619 let root = PathBuf::from("/tmp/x");
4620 let manifest = root.join("caixa.lisp");
4621 let default_lib = root.join("lib").join("demo.lisp");
4622 let layout =
4623 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4624 let mut c = caixa(CaixaKind::Biblioteca);
4625 c.repositorio = Some(String::new());
4626 let err = layout.verify(&c, &root).unwrap_err();
4627 let LayoutError::RepositorioViolation { caixa, issue } = err else {
4628 panic!("expected LayoutError::RepositorioViolation, got {err:?}");
4629 };
4630 assert_eq!(caixa, "demo");
4631 assert!(
4632 issue.contains(":repositorio"),
4633 "issue must name the offending slot: {issue}",
4634 );
4635 }
4636
4637 #[test]
4638 fn repositorio_violation_on_malformed_shape() {
4639 // Canonical CLI-argument-injection footgun: a leading `-`
4640 // value (`-upload-pack=evil`) escapes the `git clone <repo>`
4641 // subprocess argument boundary at clone time. The shared
4642 // `is_git_repo_url` predicate — the same parser the peer
4643 // `:deps :fonte :repo` axis routes through via
4644 // `DepSource::validate` — refuses every leading-`-` shape at
4645 // validate time. The wrap envelope names the offending value
4646 // verbatim through the inner [`ManifestError::RepositorioInvalid`]'s
4647 // Display.
4648 let root = PathBuf::from("/tmp/x");
4649 let manifest = root.join("caixa.lisp");
4650 let default_lib = root.join("lib").join("demo.lisp");
4651 let layout =
4652 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4653 let mut c = caixa(CaixaKind::Biblioteca);
4654 c.repositorio = Some("-upload-pack=evil".into());
4655 let err = layout.verify(&c, &root).unwrap_err();
4656 let LayoutError::RepositorioViolation { caixa, issue } = err else {
4657 panic!("expected LayoutError::RepositorioViolation, got {err:?}");
4658 };
4659 assert_eq!(caixa, "demo");
4660 assert!(
4661 issue.contains("-upload-pack=evil"),
4662 "issue must quote the offending value: {issue}",
4663 );
4664 }
4665
4666 #[test]
4667 fn repositorio_violation_fires_before_kind_coherence_mesh_slot() {
4668 // Cross-axis precedence pin: a Biblioteca with malformed
4669 // `:repositorio` *and* declared mesh slots (`:membros`)
4670 // surfaces the universal `:repositorio` diagnostic first, not
4671 // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4672 // `:repositorio` is universal (every kind owns the slot), so
4673 // its shape diagnostic is more fundamental than the
4674 // partition-on-kind diagnostic. Mirrors the peer
4675 // `autores_violation_fires_before_kind_coherence_mesh_slot`
4676 // pin (86c769b) on the `:autores` axis vs the same
4677 // kind-coherence gates.
4678 let root = PathBuf::from("/tmp/x");
4679 let manifest = root.join("caixa.lisp");
4680 let default_lib = root.join("lib").join("demo.lisp");
4681 let layout =
4682 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4683 let mut c = caixa(CaixaKind::Biblioteca);
4684 c.repositorio = Some(String::new());
4685 c.membros = vec![crate::aplicacao::Membro {
4686 caixa: "x".into(),
4687 versao: "^0.1".into(),
4688 }];
4689 let err = layout.verify(&c, &root).unwrap_err();
4690 assert!(
4691 matches!(err, LayoutError::RepositorioViolation { .. }),
4692 "got {err:?}",
4693 );
4694 }
4695
4696 #[test]
4697 fn repositorio_violation_fires_after_autores_violation() {
4698 // Cross-axis precedence pin (inside the universal metadata
4699 // trio): a caixa with both a malformed `:autores` entry *and*
4700 // a malformed `:repositorio` value surfaces `AutoresViolation`
4701 // first — `:autores` is the fifth universal axis in the
4702 // cascade and runs before `:repositorio`, peer with the
4703 // canonical identity-axis-first cascade the peer gates
4704 // establish. Mirrors the peer
4705 // `autores_violation_fires_after_etiquetas_violation`
4706 // precedence pin (86c769b) on the tag-axis-before-author-axis
4707 // pair.
4708 let root = PathBuf::from("/tmp/x");
4709 let manifest = root.join("caixa.lisp");
4710 let default_lib = root.join("lib").join("demo.lisp");
4711 let layout =
4712 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4713 let mut c = caixa(CaixaKind::Biblioteca);
4714 c.autores = vec![String::new()];
4715 c.repositorio = Some(String::new());
4716 let err = layout.verify(&c, &root).unwrap_err();
4717 assert!(
4718 matches!(err, LayoutError::AutoresViolation { .. }),
4719 "got {err:?}",
4720 );
4721 }
4722
4723 #[test]
4724 fn repositorio_violation_accepts_canonical_template() {
4725 // Positive control sanity pin: the canonical `Caixa::template`
4726 // shape (omits `:repositorio` entirely → `None` on the typed
4727 // surface) passes the gate trivially — the gate is a no-op
4728 // when the author didn't author a value. Mirrors the peer
4729 // `autores_violation_accepts_canonical_template` pin (86c769b).
4730 let root = PathBuf::from("/tmp/x");
4731 let manifest = root.join("caixa.lisp");
4732 let default_lib = root.join("lib").join("demo.lisp");
4733 let layout =
4734 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4735 let c = caixa(CaixaKind::Biblioteca);
4736 layout.verify(&c, &root).expect("template must pass");
4737 }
4738
4739 #[test]
4740 fn repositorio_violation_accepts_canonical_github_shorthand() {
4741 // Positive control pin on the canonical pleme-io `:repositorio`
4742 // shape: the `github:org/repo` shorthand the README quickstart
4743 // and the `caixa-helm` / `caixa-mesh` / `caixa-flux` fixtures
4744 // all use passes the gate end-to-end. Closes the structural
4745 // equivalence between this surface and the peer `:deps :fonte
4746 // :repo` axis — both consume `crate::render::is_git_repo_url`
4747 // and both must agree on the same accepted shape set.
4748 let root = PathBuf::from("/tmp/x");
4749 let manifest = root.join("caixa.lisp");
4750 let default_lib = root.join("lib").join("demo.lisp");
4751 let layout =
4752 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4753 let mut c = caixa(CaixaKind::Biblioteca);
4754 c.repositorio = Some("github:pleme-io/hello-rio".into());
4755 layout.verify(&c, &root).expect("canonical shape must pass");
4756 }
4757
4758 // ── descricao universal-axis gate wired into verify ──────────────────
4759 //
4760 // Pins the layout-pipeline wire-up of [`Caixa::validate_descricao`]:
4761 // the seventh universal-axis Caixa-level value-shape gate (peer of
4762 // `validate_nome` / `validate_versao` / `validate_deps` /
4763 // `validate_etiquetas` / `validate_autores` / `validate_repositorio` /
4764 // `validate_code_paths`), wired immediately after `validate_repositorio`
4765 // so the universal free-form-prose axis sits adjacent to the
4766 // universal git-URL axis in the cascade. Until this wire-up landed
4767 // `:descricao` had no shape gate at any layer — the empty
4768 // `Some("")` silently passed both `caixa-helm` consumers'
4769 // `Option::unwrap_or_else(|| <fallback>)` (which only fire on
4770 // `None`) and rendered as `Chart.yaml description: ""` plus a
4771 // blank `README.md` header, breaking at `helm lint` time
4772 // (`WARNING [chart.metadata.description]: description is required`
4773 // on `apiVersion: v2` charts) far from the source `caixa.lisp`.
4774 // Closes the same `Some("")` skips-`unwrap_or_else` footgun the
4775 // peer `:repositorio` gate (577b0a9) closed, on the universal
4776 // free-form-prose summary axis.
4777
4778 #[test]
4779 fn descricao_violation_on_empty_some() {
4780 // Canonical paste-from-blank-doc footgun on every kind. The
4781 // wrap envelope wraps [`ManifestError::DescricaoEmpty`]'s
4782 // Display through verbatim, so the issue string names the
4783 // offending `:descricao` axis at the source — the author can
4784 // grep their caixa.lisp for `:descricao ""` and fix the empty
4785 // value in one edit. Mirrors the peer
4786 // `repositorio_violation_on_empty_some` shape (577b0a9) on
4787 // the sibling `Option<String>` `:repositorio` axis.
4788 let root = PathBuf::from("/tmp/x");
4789 let manifest = root.join("caixa.lisp");
4790 let default_lib = root.join("lib").join("demo.lisp");
4791 let layout =
4792 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4793 let mut c = caixa(CaixaKind::Biblioteca);
4794 c.descricao = Some(String::new());
4795 let err = layout.verify(&c, &root).unwrap_err();
4796 let LayoutError::DescricaoViolation { caixa, issue } = err else {
4797 panic!("expected LayoutError::DescricaoViolation, got {err:?}");
4798 };
4799 assert_eq!(caixa, "demo");
4800 assert!(
4801 issue.contains(":descricao"),
4802 "issue must name the offending slot: {issue}",
4803 );
4804 }
4805
4806 #[test]
4807 fn descricao_violation_fires_before_kind_coherence_mesh_slot() {
4808 // Cross-axis precedence pin: a Biblioteca with empty
4809 // `:descricao` *and* declared mesh slots (`:membros`)
4810 // surfaces the universal `:descricao` diagnostic first, not
4811 // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4812 // `:descricao` is universal (every kind owns the slot), so
4813 // its shape diagnostic is more fundamental than the
4814 // partition-on-kind diagnostic. Mirrors the peer
4815 // `repositorio_violation_fires_before_kind_coherence_mesh_slot`
4816 // pin (577b0a9) on the `:repositorio` axis vs the same
4817 // kind-coherence gates.
4818 let root = PathBuf::from("/tmp/x");
4819 let manifest = root.join("caixa.lisp");
4820 let default_lib = root.join("lib").join("demo.lisp");
4821 let layout =
4822 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4823 let mut c = caixa(CaixaKind::Biblioteca);
4824 c.descricao = Some(String::new());
4825 c.membros = vec![crate::aplicacao::Membro {
4826 caixa: "x".into(),
4827 versao: "^0.1".into(),
4828 }];
4829 let err = layout.verify(&c, &root).unwrap_err();
4830 assert!(
4831 matches!(err, LayoutError::DescricaoViolation { .. }),
4832 "got {err:?}",
4833 );
4834 }
4835
4836 #[test]
4837 fn descricao_violation_fires_after_repositorio_violation() {
4838 // Cross-axis precedence pin (inside the universal metadata
4839 // cascade): a caixa with both a malformed `:repositorio` *and*
4840 // an empty `:descricao` surfaces `RepositorioViolation`
4841 // first — `:repositorio` is the sixth universal axis in the
4842 // cascade and runs before `:descricao`, peer with the
4843 // canonical identity-axis-first cascade the peer gates
4844 // establish. Mirrors the peer
4845 // `repositorio_violation_fires_after_autores_violation`
4846 // precedence pin (577b0a9) on the autores-axis-before-
4847 // repositorio-axis pair.
4848 let root = PathBuf::from("/tmp/x");
4849 let manifest = root.join("caixa.lisp");
4850 let default_lib = root.join("lib").join("demo.lisp");
4851 let layout =
4852 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4853 let mut c = caixa(CaixaKind::Biblioteca);
4854 c.repositorio = Some(String::new());
4855 c.descricao = Some(String::new());
4856 let err = layout.verify(&c, &root).unwrap_err();
4857 assert!(
4858 matches!(err, LayoutError::RepositorioViolation { .. }),
4859 "got {err:?}",
4860 );
4861 }
4862
4863 #[test]
4864 fn descricao_violation_accepts_none() {
4865 // Positive control sanity pin: a caixa that omits
4866 // `:descricao` entirely (the canonical `Caixa::template` shape
4867 // carries `Some("FIXME — describe this caixa")`, but the
4868 // layout-test fixture defaults to `None`) passes the gate
4869 // trivially — the gate is a no-op when the author didn't
4870 // author a value. Mirrors the peer
4871 // `repositorio_violation_accepts_canonical_template` pin
4872 // (577b0a9).
4873 let root = PathBuf::from("/tmp/x");
4874 let manifest = root.join("caixa.lisp");
4875 let default_lib = root.join("lib").join("demo.lisp");
4876 let layout =
4877 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4878 let c = caixa(CaixaKind::Biblioteca);
4879 layout.verify(&c, &root).expect("None must pass");
4880 }
4881
4882 #[test]
4883 fn descricao_violation_accepts_canonical_summary() {
4884 // Positive control pin on the canonical pleme-io `:descricao`
4885 // shape: a short free-form prose summary the `caixa-helm` /
4886 // `caixa-flux` / `caixa-mesh` fixtures all carry passes the
4887 // gate end-to-end.
4888 let root = PathBuf::from("/tmp/x");
4889 let manifest = root.join("caixa.lisp");
4890 let default_lib = root.join("lib").join("demo.lisp");
4891 let layout =
4892 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4893 let mut c = caixa(CaixaKind::Biblioteca);
4894 c.descricao = Some("Canonical Rust→wasm32-wasip2 caixa Servico.".into());
4895 layout
4896 .verify(&c, &root)
4897 .expect("canonical summary must pass");
4898 }
4899
4900 #[test]
4901 fn descricao_violation_on_non_chart_shape() {
4902 // Shape-predicate wire-up pin: a malformed `:descricao` value
4903 // that's a non-empty `Some(s)` but carries a paste-from-
4904 // multiline-doc embedded newline surfaces the
4905 // `DescricaoViolation` envelope via the manifest-layer
4906 // `ManifestError::DescricaoInvalid` arm. Mirrors the peer
4907 // `descricao_violation_on_empty_some` shape on the empty arm
4908 // of the same axis and the peer
4909 // `licenca_violation_on_non_spdx_shape` shape on the sibling
4910 // `:licenca` axis. Until this gate landed a value like
4911 // `"Checkout\nflow."` (an embedded newline) or `"Checkout
4912 // flow. "` (a trailing whitespace) silently passed
4913 // `StandardLayout::verify` and landed in the rendered
4914 // Chart.yaml `description:` field as a YAML-illegal
4915 // multi-line scalar or a silently-trimmed whitespace
4916 // round-trip far from the source caixa.lisp.
4917 let root = PathBuf::from("/tmp/x");
4918 let manifest = root.join("caixa.lisp");
4919 let default_lib = root.join("lib").join("demo.lisp");
4920 let layout =
4921 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4922 let mut c = caixa(CaixaKind::Biblioteca);
4923 c.descricao = Some("Checkout\nflow.".into());
4924 let err = layout.verify(&c, &root).unwrap_err();
4925 let LayoutError::DescricaoViolation { caixa, issue } = err else {
4926 panic!("expected LayoutError::DescricaoViolation, got {err:?}");
4927 };
4928 assert_eq!(caixa, "demo");
4929 assert!(
4930 issue.contains(":descricao"),
4931 "issue must name the offending slot: {issue}",
4932 );
4933 // The wrapped `ManifestError::DescricaoInvalid` Display uses
4934 // `{descricao:?}` (Debug) so the embedded newline surfaces
4935 // debug-escaped as `\n` in the issue string.
4936 assert!(
4937 issue.contains("Checkout\\nflow."),
4938 "issue must quote the offending value (debug-escaped): {issue}",
4939 );
4940 }
4941
4942 // ── :licenca empty-Some shape wired into verify (universal axis) ──
4943 //
4944 // Until this wire-up landed `Caixa::validate_licenca` did not
4945 // exist — the universal SPDX-shaped license-expression axis had
4946 // no shape gate at any layer, so an empty `Some("")` silently
4947 // passed `Caixa::from_lisp` and `StandardLayout::verify` and
4948 // landed as a bare trailing period in the rendered
4949 // `lareira-<nome>` chart's `README.md` `## License` section via
4950 // the `caixa-helm` consumer's `caixa.licenca.clone().unwrap_or_else(||
4951 // "MIT".into())` (which only fires on `None`) at
4952 // `caixa-helm/src/lib.rs:361`. Closes the same `Some("")`
4953 // skips-`unwrap_or_else` footgun the peer `:repositorio`
4954 // (577b0a9) and `:descricao` (4e6db38) gates closed, on the
4955 // universal license-expression axis.
4956
4957 #[test]
4958 fn licenca_violation_on_empty_some() {
4959 // Canonical paste-from-blank-doc footgun on every kind. The
4960 // wrap envelope wraps [`ManifestError::LicencaEmpty`]'s
4961 // Display through verbatim, so the issue string names the
4962 // offending `:licenca` axis at the source — the author can
4963 // grep their caixa.lisp for `:licenca ""` and fix the empty
4964 // value in one edit. Mirrors the peer
4965 // `descricao_violation_on_empty_some` shape (4e6db38) on
4966 // the sibling `Option<String>` `:licenca` axis.
4967 let root = PathBuf::from("/tmp/x");
4968 let manifest = root.join("caixa.lisp");
4969 let default_lib = root.join("lib").join("demo.lisp");
4970 let layout =
4971 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4972 let mut c = caixa(CaixaKind::Biblioteca);
4973 c.licenca = Some(String::new());
4974 let err = layout.verify(&c, &root).unwrap_err();
4975 let LayoutError::LicencaViolation { caixa, issue } = err else {
4976 panic!("expected LayoutError::LicencaViolation, got {err:?}");
4977 };
4978 assert_eq!(caixa, "demo");
4979 assert!(
4980 issue.contains(":licenca"),
4981 "issue must name the offending slot: {issue}",
4982 );
4983 }
4984
4985 #[test]
4986 fn licenca_violation_fires_before_kind_coherence_mesh_slot() {
4987 // Cross-axis precedence pin: a Biblioteca with empty
4988 // `:licenca` *and* declared mesh slots (`:membros`)
4989 // surfaces the universal `:licenca` diagnostic first, not
4990 // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4991 // `:licenca` is universal (every kind owns the slot), so
4992 // its shape diagnostic is more fundamental than the
4993 // partition-on-kind diagnostic. Mirrors the peer
4994 // `descricao_violation_fires_before_kind_coherence_mesh_slot`
4995 // pin (4e6db38) on the `:descricao` axis vs the same
4996 // kind-coherence gates.
4997 let root = PathBuf::from("/tmp/x");
4998 let manifest = root.join("caixa.lisp");
4999 let default_lib = root.join("lib").join("demo.lisp");
5000 let layout =
5001 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5002 let mut c = caixa(CaixaKind::Biblioteca);
5003 c.licenca = Some(String::new());
5004 c.membros = vec![crate::aplicacao::Membro {
5005 caixa: "x".into(),
5006 versao: "^0.1".into(),
5007 }];
5008 let err = layout.verify(&c, &root).unwrap_err();
5009 assert!(
5010 matches!(err, LayoutError::LicencaViolation { .. }),
5011 "got {err:?}",
5012 );
5013 }
5014
5015 #[test]
5016 fn licenca_violation_fires_after_descricao_violation() {
5017 // Cross-axis precedence pin (inside the universal metadata
5018 // cascade): a caixa with both an empty `:descricao` *and*
5019 // an empty `:licenca` surfaces `DescricaoViolation`
5020 // first — `:descricao` is the seventh universal axis in the
5021 // cascade and runs before `:licenca`, peer with the
5022 // canonical identity-axis-first cascade the peer gates
5023 // establish. Mirrors the peer
5024 // `descricao_violation_fires_after_repositorio_violation`
5025 // precedence pin (4e6db38) on the repositorio-axis-before-
5026 // descricao-axis pair.
5027 let root = PathBuf::from("/tmp/x");
5028 let manifest = root.join("caixa.lisp");
5029 let default_lib = root.join("lib").join("demo.lisp");
5030 let layout =
5031 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5032 let mut c = caixa(CaixaKind::Biblioteca);
5033 c.descricao = Some(String::new());
5034 c.licenca = Some(String::new());
5035 let err = layout.verify(&c, &root).unwrap_err();
5036 assert!(
5037 matches!(err, LayoutError::DescricaoViolation { .. }),
5038 "got {err:?}",
5039 );
5040 }
5041
5042 #[test]
5043 fn licenca_violation_accepts_none() {
5044 // Positive control sanity pin: a caixa that omits `:licenca`
5045 // entirely (the layout-test fixture defaults to `None`)
5046 // passes the gate trivially — the gate is a no-op when the
5047 // author didn't author a value. Mirrors the peer
5048 // `descricao_violation_accepts_none` pin (4e6db38).
5049 let root = PathBuf::from("/tmp/x");
5050 let manifest = root.join("caixa.lisp");
5051 let default_lib = root.join("lib").join("demo.lisp");
5052 let layout =
5053 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5054 let c = caixa(CaixaKind::Biblioteca);
5055 layout.verify(&c, &root).expect("None must pass");
5056 }
5057
5058 #[test]
5059 fn licenca_violation_accepts_canonical_expression() {
5060 // Positive control pin on the canonical pleme-io `:licenca`
5061 // shape: a non-empty SPDX expression the `caixa-helm` /
5062 // `caixa-flux` / `caixa-mesh` fixtures all carry (`"MIT"`)
5063 // passes the gate end-to-end.
5064 let root = PathBuf::from("/tmp/x");
5065 let manifest = root.join("caixa.lisp");
5066 let default_lib = root.join("lib").join("demo.lisp");
5067 let layout =
5068 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5069 let mut c = caixa(CaixaKind::Biblioteca);
5070 c.licenca = Some("Apache-2.0 OR MIT".into());
5071 layout
5072 .verify(&c, &root)
5073 .expect("canonical SPDX expression must pass");
5074 }
5075
5076 #[test]
5077 fn licenca_violation_on_non_spdx_shape() {
5078 // Shape-predicate wire-up pin: a malformed `:licenca` value
5079 // that's a non-empty `Some(s)` but falls outside the SPDX
5080 // expression alphabet floor surfaces the `LicencaViolation`
5081 // envelope via the manifest-layer `ManifestError::LicencaInvalid`
5082 // arm. Mirrors the peer `licenca_violation_on_empty_some`
5083 // shape on the empty arm of the same axis and the peer
5084 // `edicao_violation_on_non_year_shape` shape on the sibling
5085 // `:edicao` axis. Until this gate landed a value like
5086 // `"Apache_2.0"` (an underscore-instead-of-hyphen typo) or
5087 // `"MIT, Apache-2.0"` (a comma-instead-of-`OR`-keyword
5088 // colloquial idiom) silently passed `StandardLayout::verify`
5089 // and landed in the rendered chart `README.md` `## License`
5090 // section + a future SPDX-aware Chart.yaml `license:`
5091 // emitter would refuse the value at `helm lint` time far
5092 // from the source caixa.lisp.
5093 let root = PathBuf::from("/tmp/x");
5094 let manifest = root.join("caixa.lisp");
5095 let default_lib = root.join("lib").join("demo.lisp");
5096 let layout =
5097 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5098 let mut c = caixa(CaixaKind::Biblioteca);
5099 c.licenca = Some("Apache_2.0".into());
5100 let err = layout.verify(&c, &root).unwrap_err();
5101 let LayoutError::LicencaViolation { caixa, issue } = err else {
5102 panic!("expected LayoutError::LicencaViolation, got {err:?}");
5103 };
5104 assert_eq!(caixa, "demo");
5105 assert!(
5106 issue.contains(":licenca"),
5107 "issue must name the offending slot: {issue}",
5108 );
5109 assert!(
5110 issue.contains("Apache_2.0"),
5111 "issue must quote the offending value: {issue}",
5112 );
5113 }
5114
5115 // ── :edicao empty-Some shape wired into verify (universal axis) ──
5116 //
5117 // Until this wire-up landed `Caixa::validate_edicao` did not
5118 // exist — the universal language-edition axis had no shape gate
5119 // at any layer, so an empty `Some("")` silently passed
5120 // `Caixa::from_lisp` and `StandardLayout::verify` and landed as a
5121 // bare `(:edicao "")` line in the rendered caixa.lisp, ready for
5122 // a future renderer-side consumer's `Option::unwrap_or_else`
5123 // (which only fires on `None`) to skip its fallback. Closes the
5124 // same `Some("")`-skips-`unwrap_or_else` footgun the peer
5125 // `:repositorio` (577b0a9), `:descricao` (4e6db38), and
5126 // `:licenca` (3d1e535) gates closed, on the universal language-
5127 // edition axis — the last un-gated universal-axis
5128 // `Option<String>` Caixa-level value-shape surface.
5129
5130 #[test]
5131 fn edicao_violation_on_empty_some() {
5132 // Canonical paste-from-blank-doc footgun on every kind. The
5133 // wrap envelope wraps [`ManifestError::EdicaoEmpty`]'s
5134 // Display through verbatim, so the issue string names the
5135 // offending `:edicao` axis at the source — the author can
5136 // grep their caixa.lisp for `:edicao ""` and fix the empty
5137 // value in one edit. Mirrors the peer
5138 // `licenca_violation_on_empty_some` shape (3d1e535) on the
5139 // sibling `Option<String>` `:edicao` axis.
5140 let root = PathBuf::from("/tmp/x");
5141 let manifest = root.join("caixa.lisp");
5142 let default_lib = root.join("lib").join("demo.lisp");
5143 let layout =
5144 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5145 let mut c = caixa(CaixaKind::Biblioteca);
5146 c.edicao = Some(String::new());
5147 let err = layout.verify(&c, &root).unwrap_err();
5148 let LayoutError::EdicaoViolation { caixa, issue } = err else {
5149 panic!("expected LayoutError::EdicaoViolation, got {err:?}");
5150 };
5151 assert_eq!(caixa, "demo");
5152 assert!(
5153 issue.contains(":edicao"),
5154 "issue must name the offending slot: {issue}",
5155 );
5156 }
5157
5158 #[test]
5159 fn edicao_violation_fires_before_kind_coherence_mesh_slot() {
5160 // Cross-axis precedence pin: a Biblioteca with empty
5161 // `:edicao` *and* declared mesh slots (`:membros`) surfaces
5162 // the universal `:edicao` diagnostic first, not the
5163 // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
5164 // `:edicao` is universal (every kind owns the slot), so
5165 // its shape diagnostic is more fundamental than the
5166 // partition-on-kind diagnostic. Mirrors the peer
5167 // `licenca_violation_fires_before_kind_coherence_mesh_slot`
5168 // pin (3d1e535) on the `:licenca` axis vs the same
5169 // kind-coherence gates.
5170 let root = PathBuf::from("/tmp/x");
5171 let manifest = root.join("caixa.lisp");
5172 let default_lib = root.join("lib").join("demo.lisp");
5173 let layout =
5174 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5175 let mut c = caixa(CaixaKind::Biblioteca);
5176 c.edicao = Some(String::new());
5177 c.membros = vec![crate::aplicacao::Membro {
5178 caixa: "x".into(),
5179 versao: "^0.1".into(),
5180 }];
5181 let err = layout.verify(&c, &root).unwrap_err();
5182 assert!(
5183 matches!(err, LayoutError::EdicaoViolation { .. }),
5184 "got {err:?}",
5185 );
5186 }
5187
5188 #[test]
5189 fn edicao_violation_fires_after_licenca_violation() {
5190 // Cross-axis precedence pin (inside the universal metadata
5191 // cascade): a caixa with both an empty `:licenca` *and* an
5192 // empty `:edicao` surfaces `LicencaViolation` first —
5193 // `:licenca` is the eighth universal axis in the cascade
5194 // and runs before `:edicao`, peer with the canonical
5195 // identity-axis-first cascade the peer gates establish.
5196 // Mirrors the peer
5197 // `licenca_violation_fires_after_descricao_violation`
5198 // precedence pin (3d1e535) on the descricao-axis-before-
5199 // licenca-axis pair.
5200 let root = PathBuf::from("/tmp/x");
5201 let manifest = root.join("caixa.lisp");
5202 let default_lib = root.join("lib").join("demo.lisp");
5203 let layout =
5204 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5205 let mut c = caixa(CaixaKind::Biblioteca);
5206 c.licenca = Some(String::new());
5207 c.edicao = Some(String::new());
5208 let err = layout.verify(&c, &root).unwrap_err();
5209 assert!(
5210 matches!(err, LayoutError::LicencaViolation { .. }),
5211 "got {err:?}",
5212 );
5213 }
5214
5215 #[test]
5216 fn edicao_violation_accepts_none() {
5217 // Positive control sanity pin: a caixa that omits `:edicao`
5218 // entirely (the layout-test fixture defaults to `None`)
5219 // passes the gate trivially — the gate is a no-op when the
5220 // author didn't author a value. Mirrors the peer
5221 // `licenca_violation_accepts_none` pin (3d1e535).
5222 let root = PathBuf::from("/tmp/x");
5223 let manifest = root.join("caixa.lisp");
5224 let default_lib = root.join("lib").join("demo.lisp");
5225 let layout =
5226 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5227 let c = caixa(CaixaKind::Biblioteca);
5228 layout.verify(&c, &root).expect("None must pass");
5229 }
5230
5231 #[test]
5232 fn edicao_violation_accepts_canonical_value() {
5233 // Positive control pin on the canonical pleme-io `:edicao`
5234 // shape: the `"2026"` edition every `caixa-helm` /
5235 // `caixa-flux` / `caixa-mesh` / `caixa-core/src/render.rs`
5236 // fixture carries by construction passes the gate end-to-end.
5237 let root = PathBuf::from("/tmp/x");
5238 let manifest = root.join("caixa.lisp");
5239 let default_lib = root.join("lib").join("demo.lisp");
5240 let layout =
5241 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5242 let mut c = caixa(CaixaKind::Biblioteca);
5243 c.edicao = Some("2026".into());
5244 layout
5245 .verify(&c, &root)
5246 .expect("canonical edition must pass");
5247 }
5248
5249 #[test]
5250 fn edicao_violation_on_non_year_shape() {
5251 // Shape-predicate wire-up pin: a malformed `:edicao` value
5252 // that's a non-empty `Some(s)` but not a 4-digit ASCII
5253 // decimal year surfaces the `EdicaoViolation` envelope via
5254 // the manifest-layer `ManifestError::EdicaoInvalid` arm.
5255 // Mirrors the peer `edicao_violation_on_empty_some` shape
5256 // on the empty arm of the same axis. Until this gate landed
5257 // a value like `"v2026"` (a familiar git-tag idiom that
5258 // doesn't apply to the year-shaped edition axis) silently
5259 // passed `StandardLayout::verify` and broke at the
5260 // substrate's build-time edition selector far from the
5261 // source caixa.lisp.
5262 let root = PathBuf::from("/tmp/x");
5263 let manifest = root.join("caixa.lisp");
5264 let default_lib = root.join("lib").join("demo.lisp");
5265 let layout =
5266 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5267 let mut c = caixa(CaixaKind::Biblioteca);
5268 c.edicao = Some("v2026".into());
5269 let err = layout.verify(&c, &root).unwrap_err();
5270 let LayoutError::EdicaoViolation { caixa, issue } = err else {
5271 panic!("expected LayoutError::EdicaoViolation, got {err:?}");
5272 };
5273 assert_eq!(caixa, "demo");
5274 assert!(
5275 issue.contains(":edicao"),
5276 "issue must name the offending slot: {issue}",
5277 );
5278 assert!(
5279 issue.contains("v2026"),
5280 "issue must quote the offending value: {issue}",
5281 );
5282 }
5283
5284 // ── Caixa-identity gates (`:nome`, `:versao`) wired into verify ────
5285 //
5286 // Until this wire-up landed `Caixa::validate_nome` and
5287 // `Caixa::validate_versao` lived as `pub fn` on `Caixa` with full
5288 // per-arm unit coverage in `manifest::tests`, but no production
5289 // path called them — `feira build` silently accepted malformed
5290 // `:nome` / `:versao` and the failure surfaced at `helm install` /
5291 // `kubectl apply` / `feira publish` / lacre-resolve / `:upgrade-from
5292 // :from` matching time, far from the source `caixa.lisp`. The
5293 // following pins fence the layout-pipeline wire-up: every layout
5294 // verify on a structurally-invalid Caixa identity axis surfaces
5295 // the per-axis `*Violation { caixa, issue }` envelope before any
5296 // kind-coherence, code-path, or downstream gate sees it.
5297
5298 #[test]
5299 fn nome_violation_on_uppercase() {
5300 let root = PathBuf::from("/tmp/x");
5301 let manifest = root.join("caixa.lisp");
5302 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5303 let mut c = caixa(CaixaKind::Biblioteca);
5304 c.nome = "MyApp".into();
5305 let err = layout.verify(&c, &root).unwrap_err();
5306 let LayoutError::NomeViolation { caixa, issue } = err else {
5307 panic!("expected LayoutError::NomeViolation, got {err:?}");
5308 };
5309 assert_eq!(caixa, "MyApp");
5310 assert!(
5311 issue.contains("MyApp"),
5312 "issue must quote the offending nome: {issue}",
5313 );
5314 }
5315
5316 #[test]
5317 fn nome_violation_on_underscore() {
5318 let root = PathBuf::from("/tmp/x");
5319 let manifest = root.join("caixa.lisp");
5320 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5321 let mut c = caixa(CaixaKind::Biblioteca);
5322 c.nome = "my_app".into();
5323 let err = layout.verify(&c, &root).unwrap_err();
5324 assert!(
5325 matches!(err, LayoutError::NomeViolation { ref caixa, .. } if caixa == "my_app"),
5326 "got {err:?}",
5327 );
5328 }
5329
5330 #[test]
5331 fn nome_violation_on_empty() {
5332 // Empty `:nome` surfaces NomeViolation wrapping the narrower
5333 // `ManifestError::NomeEmpty` arm — the empty-first cascade the
5334 // peer per-axis name gates already use.
5335 let root = PathBuf::from("/tmp/x");
5336 let manifest = root.join("caixa.lisp");
5337 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5338 let mut c = caixa(CaixaKind::Biblioteca);
5339 c.nome = String::new();
5340 let err = layout.verify(&c, &root).unwrap_err();
5341 let LayoutError::NomeViolation { caixa, issue } = err else {
5342 panic!("expected LayoutError::NomeViolation, got {err:?}");
5343 };
5344 assert!(caixa.is_empty());
5345 assert!(
5346 issue.contains(":nome is empty"),
5347 "issue must surface the empty-arm diagnostic: {issue}",
5348 );
5349 }
5350
5351 #[test]
5352 fn versao_violation_on_missing_patch() {
5353 // `"0.1"` — the canonical "I shortened it" footgun. Helm /
5354 // OCI / lacre-resolve / `:upgrade-from :from` all strict-parse
5355 // through `semver::Version::parse`, which refuses a two-part
5356 // shape.
5357 let root = PathBuf::from("/tmp/x");
5358 let manifest = root.join("caixa.lisp");
5359 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5360 let mut c = caixa(CaixaKind::Biblioteca);
5361 c.versao = "0.1".into();
5362 let err = layout.verify(&c, &root).unwrap_err();
5363 let LayoutError::VersaoViolation { caixa, issue } = err else {
5364 panic!("expected LayoutError::VersaoViolation, got {err:?}");
5365 };
5366 assert_eq!(caixa, "demo");
5367 assert!(
5368 issue.contains("0.1"),
5369 "issue must quote the offending versao: {issue}",
5370 );
5371 }
5372
5373 #[test]
5374 fn versao_violation_on_git_tag_shape() {
5375 // `"v0.1.0"` — the git-tag-shape-leaking-into-versao typo.
5376 let root = PathBuf::from("/tmp/x");
5377 let manifest = root.join("caixa.lisp");
5378 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5379 let mut c = caixa(CaixaKind::Biblioteca);
5380 c.versao = "v0.1.0".into();
5381 let err = layout.verify(&c, &root).unwrap_err();
5382 assert!(
5383 matches!(err, LayoutError::VersaoViolation { ref issue, .. }
5384 if issue.contains("v0.1.0")),
5385 "got {err:?}",
5386 );
5387 }
5388
5389 #[test]
5390 fn versao_violation_on_empty() {
5391 let root = PathBuf::from("/tmp/x");
5392 let manifest = root.join("caixa.lisp");
5393 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5394 let mut c = caixa(CaixaKind::Biblioteca);
5395 c.versao = String::new();
5396 let err = layout.verify(&c, &root).unwrap_err();
5397 let LayoutError::VersaoViolation { caixa, issue } = err else {
5398 panic!("expected LayoutError::VersaoViolation, got {err:?}");
5399 };
5400 assert_eq!(caixa, "demo");
5401 assert!(
5402 issue.contains(":versao is empty"),
5403 "issue must surface the empty-arm diagnostic: {issue}",
5404 );
5405 }
5406
5407 #[test]
5408 fn nome_violation_fires_before_versao_violation() {
5409 // Precedence pin: when both `:nome` and `:versao` are malformed,
5410 // `:nome` surfaces first — the canonical declaration-order
5411 // precedence the `ManifestError` family establishes, the same
5412 // grep-order the author follows when fixing in `caixa.lisp`.
5413 let root = PathBuf::from("/tmp/x");
5414 let manifest = root.join("caixa.lisp");
5415 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5416 let mut c = caixa(CaixaKind::Biblioteca);
5417 c.nome = "MyApp".into();
5418 c.versao = "0.1".into();
5419 let err = layout.verify(&c, &root).unwrap_err();
5420 assert!(
5421 matches!(err, LayoutError::NomeViolation { .. }),
5422 "got {err:?} — nome must fire before versao",
5423 );
5424 }
5425
5426 #[test]
5427 fn nome_violation_fires_before_kind_coherence() {
5428 // Precedence pin: a Biblioteca caixa with a malformed `:nome`
5429 // AND a declared mesh slot surfaces NomeViolation, not
5430 // MeshSlotsOnNonAplicacao — the identity-axis gate is more
5431 // fundamental than the kind-coherence gate (which carries
5432 // `caixa.nome` verbatim in its diagnostic, and so depends on the
5433 // name being structurally valid to render a useful message).
5434 let root = PathBuf::from("/tmp/x");
5435 let manifest = root.join("caixa.lisp");
5436 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5437 let mut c = caixa(CaixaKind::Biblioteca);
5438 c.nome = "MyApp".into();
5439 c.membros = vec![crate::aplicacao::Membro {
5440 caixa: "x".into(),
5441 versao: "^0.1".into(),
5442 }];
5443 let err = layout.verify(&c, &root).unwrap_err();
5444 assert!(
5445 matches!(err, LayoutError::NomeViolation { .. }),
5446 "got {err:?} — nome must fire before MeshSlotsOnNonAplicacao",
5447 );
5448 }
5449
5450 #[test]
5451 fn nome_violation_fires_before_owncode() {
5452 // Precedence pin: a Supervisor with a malformed `:nome` AND
5453 // declared `:bibliotecas` surfaces NomeViolation, not
5454 // SupervisorOwnsCode — same rationale as above.
5455 let root = PathBuf::from("/tmp/x");
5456 let manifest = root.join("caixa.lisp");
5457 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5458 let mut c = caixa(CaixaKind::Supervisor);
5459 c.nome = "MyApp".into();
5460 c.bibliotecas = vec!["lib/x.lisp".into()];
5461 let err = layout.verify(&c, &root).unwrap_err();
5462 assert!(
5463 matches!(err, LayoutError::NomeViolation { .. }),
5464 "got {err:?} — nome must fire before SupervisorOwnsCode",
5465 );
5466 }
5467
5468 #[test]
5469 fn versao_violation_fires_before_kind_coherence() {
5470 // Precedence pin: a Biblioteca with a valid `:nome` but a
5471 // malformed `:versao` AND a declared servico slot surfaces
5472 // VersaoViolation before ServicoSlotsOnNonServico.
5473 let root = PathBuf::from("/tmp/x");
5474 let manifest = root.join("caixa.lisp");
5475 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5476 let mut c = caixa(CaixaKind::Biblioteca);
5477 c.versao = "v0.1.0".into();
5478 c.limits = Some(crate::LimitsSpec {
5479 memory: Some(64 * 1024 * 1024),
5480 ..Default::default()
5481 });
5482 let err = layout.verify(&c, &root).unwrap_err();
5483 assert!(
5484 matches!(err, LayoutError::VersaoViolation { .. }),
5485 "got {err:?} — versao must fire before ServicoSlotsOnNonServico",
5486 );
5487 }
5488
5489 #[test]
5490 fn nome_violation_fires_before_missing_lib() {
5491 // Precedence pin: a Biblioteca with a malformed `:nome` and no
5492 // lib entry surfaces NomeViolation, not MissingLib — the
5493 // identity-axis gate is more fundamental than the layout's
5494 // `lib/<nome>.lisp` default-path check (which derives the
5495 // expected path from `:nome` itself, so would surface a
5496 // misleading "expected lib/MyApp.lisp" diagnostic against an
5497 // unrecoverable name).
5498 let root = PathBuf::from("/tmp/x");
5499 let manifest = root.join("caixa.lisp");
5500 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5501 let mut c = caixa(CaixaKind::Biblioteca);
5502 c.nome = "MyApp".into();
5503 let err = layout.verify(&c, &root).unwrap_err();
5504 assert!(
5505 matches!(err, LayoutError::NomeViolation { .. }),
5506 "got {err:?} — nome must fire before MissingLib",
5507 );
5508 }
5509
5510 #[test]
5511 fn nome_versao_violations_fire_after_missing_manifest() {
5512 // Precedence pin: `MissingManifest` still dominates — there's
5513 // no caixa to identity-check when the manifest is missing.
5514 let root = PathBuf::from("/tmp/x");
5515 let layout = StandardLayout::new().with_path_exists(|_| false);
5516 let mut c = caixa(CaixaKind::Biblioteca);
5517 c.nome = "MyApp".into();
5518 c.versao = "0.1".into();
5519 let err = layout.verify(&c, &root).unwrap_err();
5520 assert!(
5521 matches!(err, LayoutError::MissingManifest(_)),
5522 "got {err:?} — MissingManifest must dominate identity gates",
5523 );
5524 }
5525
5526 #[test]
5527 fn valid_nome_versao_passes_to_downstream_gates() {
5528 // Sanity pin: the canonical "demo" / "0.1.0" identity passes
5529 // both axes; downstream gates (MissingLib here) take over.
5530 let root = PathBuf::from("/tmp/x");
5531 let manifest = root.join("caixa.lisp");
5532 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5533 let err = layout
5534 .verify(&caixa(CaixaKind::Biblioteca), &root)
5535 .unwrap_err();
5536 assert!(
5537 matches!(err, LayoutError::MissingLib { .. }),
5538 "got {err:?} — valid identity must pass to MissingLib",
5539 );
5540 }
5541
5542 // ── :deps / :deps-dev shape gate (lifted to layout-level verify) ─────
5543 //
5544 // Until this wire-up landed `Caixa::validate_deps` lived as `pub fn`
5545 // on `Caixa` with full per-arm unit coverage in `manifest::tests` +
5546 // `dep::tests` but no production path called it — `feira build`
5547 // silently accepted a malformed `:deps` / `:deps-dev` entry and the
5548 // failure surfaced at lacre-resolve / `git clone` / `cargo metadata`
5549 // / `helm install` time on the *first* downstream consumer to
5550 // strict-parse the value, far from the source `caixa.lisp` and
5551 // without any field naming the offending `:deps` axis. The following
5552 // pins fence the layout-pipeline wire-up: every layout verify on a
5553 // structurally-invalid `:deps` value-shape surfaces the per-axis
5554 // `DepsViolation { caixa, issue }` envelope (peer of
5555 // `NomeViolation` / `VersaoViolation` / `CodePathViolation` /
5556 // `LimitsViolation` / `BehaviorViolation` / `UpgradeViolation` /
5557 // `SupervisorViolation` / `AplicacaoViolation`) before any kind-
5558 // coherence, code-path, or downstream gate sees it.
5559
5560 #[test]
5561 fn deps_violation_on_empty_dep_nome() {
5562 // Empty `:nome` on a `:deps` entry surfaces the narrower
5563 // `DepError::NomeEmpty` arm through the wrap envelope.
5564 use crate::Dep;
5565 let root = PathBuf::from("/tmp/x");
5566 let manifest = root.join("caixa.lisp");
5567 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5568 let mut c = caixa(CaixaKind::Biblioteca);
5569 c.deps = vec![Dep::simple("", "^0.1")];
5570 let err = layout.verify(&c, &root).unwrap_err();
5571 let LayoutError::DepsViolation { caixa, issue } = err else {
5572 panic!("expected LayoutError::DepsViolation, got {err:?}");
5573 };
5574 assert_eq!(caixa, "demo");
5575 assert!(
5576 issue.contains(":deps") && issue.contains(":nome"),
5577 "issue must name the offending slot + axis: {issue}",
5578 );
5579 }
5580
5581 #[test]
5582 fn deps_violation_on_uppercase_dep_nome() {
5583 // Uppercase `:nome` on a `:deps` entry surfaces
5584 // `DepError::NomeInvalid` (DNS-1123 violation) through the wrap.
5585 use crate::Dep;
5586 let root = PathBuf::from("/tmp/x");
5587 let manifest = root.join("caixa.lisp");
5588 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5589 let mut c = caixa(CaixaKind::Biblioteca);
5590 c.deps = vec![Dep::simple("Caixa-Teia", "^0.1")];
5591 let err = layout.verify(&c, &root).unwrap_err();
5592 let LayoutError::DepsViolation { caixa, issue } = err else {
5593 panic!("expected LayoutError::DepsViolation, got {err:?}");
5594 };
5595 assert_eq!(caixa, "demo");
5596 assert!(
5597 issue.contains("Caixa-Teia"),
5598 "issue must quote the offending dep nome verbatim: {issue}",
5599 );
5600 }
5601
5602 #[test]
5603 fn deps_violation_on_unparseable_dep_versao() {
5604 // Unparseable `:versao` requirement on a `:deps` entry surfaces
5605 // `DepError::VersaoInvalid` through the wrap — the canonical
5606 // "the semver::Error reached the resolver, far from the source"
5607 // footgun closed at author time.
5608 use crate::Dep;
5609 let root = PathBuf::from("/tmp/x");
5610 let manifest = root.join("caixa.lisp");
5611 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5612 let mut c = caixa(CaixaKind::Biblioteca);
5613 c.deps = vec![Dep::simple("caixa-teia", "not-a-req")];
5614 let err = layout.verify(&c, &root).unwrap_err();
5615 let LayoutError::DepsViolation { caixa, issue } = err else {
5616 panic!("expected LayoutError::DepsViolation, got {err:?}");
5617 };
5618 assert_eq!(caixa, "demo");
5619 assert!(
5620 issue.contains("caixa-teia") && issue.contains("not-a-req"),
5621 "issue must quote the dep nome + offending versao: {issue}",
5622 );
5623 }
5624
5625 #[test]
5626 fn deps_violation_on_duplicate_nome_in_deps() {
5627 // Within-list `:deps :nome` duplicate surfaces
5628 // `DepError::DuplicateNome { list: ":deps" }` through the wrap.
5629 use crate::Dep;
5630 let root = PathBuf::from("/tmp/x");
5631 let manifest = root.join("caixa.lisp");
5632 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5633 let mut c = caixa(CaixaKind::Biblioteca);
5634 c.deps = vec![
5635 Dep::simple("caixa-teia", "^0.1"),
5636 Dep::simple("caixa-teia", "^0.2"),
5637 ];
5638 let err = layout.verify(&c, &root).unwrap_err();
5639 let LayoutError::DepsViolation { caixa, issue } = err else {
5640 panic!("expected LayoutError::DepsViolation, got {err:?}");
5641 };
5642 assert_eq!(caixa, "demo");
5643 assert!(
5644 issue.contains("caixa-teia") && issue.contains(":deps"),
5645 "issue must quote the duplicated nome + list: {issue}",
5646 );
5647 }
5648
5649 #[test]
5650 fn deps_violation_on_duplicate_nome_in_deps_dev() {
5651 // Within-list `:deps-dev :nome` duplicate surfaces the same
5652 // diagnostic on the dev-only axis — neither list is a
5653 // second-class citizen of the typed surface.
5654 use crate::Dep;
5655 let root = PathBuf::from("/tmp/x");
5656 let manifest = root.join("caixa.lisp");
5657 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5658 let mut c = caixa(CaixaKind::Biblioteca);
5659 c.deps_dev = vec![
5660 Dep::simple("caixa-teia", "^0.1"),
5661 Dep::simple("caixa-teia", "^0.2"),
5662 ];
5663 let err = layout.verify(&c, &root).unwrap_err();
5664 let LayoutError::DepsViolation { caixa, issue } = err else {
5665 panic!("expected LayoutError::DepsViolation, got {err:?}");
5666 };
5667 assert_eq!(caixa, "demo");
5668 assert!(
5669 issue.contains(":deps-dev"),
5670 "issue must name the offending list: {issue}",
5671 );
5672 }
5673
5674 #[test]
5675 fn deps_violation_in_deps_fires_before_deps_dev() {
5676 // Precedence pin: when *both* `:deps` and `:deps-dev` carry a
5677 // malformed entry, the `:deps` walk fires first — the canonical
5678 // declaration-order precedence `Caixa::validate_deps` establishes
5679 // (the same author-grep ordering the typed-graph peers use on
5680 // every other Vec-shaped surface).
5681 use crate::Dep;
5682 let root = PathBuf::from("/tmp/x");
5683 let manifest = root.join("caixa.lisp");
5684 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5685 let mut c = caixa(CaixaKind::Biblioteca);
5686 c.deps = vec![Dep::simple("Bad-In-Deps", "^0.1")];
5687 c.deps_dev = vec![Dep::simple("Bad-In-Deps-Dev", "^0.1")];
5688 let err = layout.verify(&c, &root).unwrap_err();
5689 let LayoutError::DepsViolation { caixa: _, issue } = err else {
5690 panic!("expected LayoutError::DepsViolation, got {err:?}");
5691 };
5692 assert!(
5693 issue.contains("Bad-In-Deps") && !issue.contains("Bad-In-Deps-Dev"),
5694 "issue must name the :deps offender, not :deps-dev: {issue}",
5695 );
5696 }
5697
5698 #[test]
5699 fn deps_violation_fires_after_versao_violation() {
5700 // Precedence pin: when both the top-level `:versao` and a `:deps`
5701 // entry are malformed, the Caixa-identity gate fires first — the
5702 // canonical declaration order on `Caixa` (`:nome` → `:versao` →
5703 // ... → `:deps`) and the same identity-axis-dominates-content-
5704 // axis discipline the peer `validate_nome` / `validate_versao`
5705 // wire-up established (1f74a5f). A malformed `:versao` would
5706 // otherwise quote `caixa.nome` against a downstream-shaped
5707 // diagnostic.
5708 use crate::Dep;
5709 let root = PathBuf::from("/tmp/x");
5710 let manifest = root.join("caixa.lisp");
5711 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5712 let mut c = caixa(CaixaKind::Biblioteca);
5713 c.versao = "v0.1.0".into();
5714 c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
5715 let err = layout.verify(&c, &root).unwrap_err();
5716 assert!(
5717 matches!(err, LayoutError::VersaoViolation { .. }),
5718 "got {err:?} — versao must fire before DepsViolation",
5719 );
5720 }
5721
5722 #[test]
5723 fn deps_violation_fires_before_kind_coherence() {
5724 // Precedence pin: a Supervisor with a malformed `:deps` entry
5725 // AND declared `:bibliotecas` (the canonical SupervisorOwnsCode
5726 // shape) surfaces DepsViolation, not SupervisorOwnsCode — the
5727 // dep surface is universal across all kinds and its shape gate
5728 // is more fundamental than the kind-coherence partitions on
5729 // `:bibliotecas` / `:exe` / `:servicos`. The author can fix the
5730 // dep typo without first being told to move their `:bibliotecas`
5731 // off a Supervisor.
5732 use crate::Dep;
5733 let root = PathBuf::from("/tmp/x");
5734 let manifest = root.join("caixa.lisp");
5735 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5736 let mut c = caixa(CaixaKind::Supervisor);
5737 c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
5738 c.bibliotecas = vec!["lib/x.lisp".into()];
5739 let err = layout.verify(&c, &root).unwrap_err();
5740 assert!(
5741 matches!(err, LayoutError::DepsViolation { .. }),
5742 "got {err:?} — DepsViolation must fire before SupervisorOwnsCode",
5743 );
5744 }
5745
5746 #[test]
5747 fn deps_violation_fires_after_missing_manifest() {
5748 // Precedence pin: `MissingManifest` still dominates — there's no
5749 // caixa to deps-check when the manifest is missing.
5750 use crate::Dep;
5751 let root = PathBuf::from("/tmp/x");
5752 let layout = StandardLayout::new().with_path_exists(|_| false);
5753 let mut c = caixa(CaixaKind::Biblioteca);
5754 c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
5755 let err = layout.verify(&c, &root).unwrap_err();
5756 assert!(
5757 matches!(err, LayoutError::MissingManifest(_)),
5758 "got {err:?} — MissingManifest must dominate the deps gate",
5759 );
5760 }
5761
5762 #[test]
5763 fn deps_violation_on_self_dep_in_deps() {
5764 // Cross-slot self-edge: a caixa whose `:deps` lists its own
5765 // `:nome` is rejected at the layout wire-up, the diagnostic
5766 // surfaces through the `DepsViolation` envelope with both the
5767 // offending list tag (`":deps"`) and the parent's `:nome`
5768 // verbatim. Until this wire-up landed the self-dep silently
5769 // passed `feira build` and the resolver's lacre-pipeline
5770 // closure walk either rejected mid-traversal (infinite
5771 // recursion detected far from the source caixa.lisp) or, on
5772 // the unbounded path, recursed until it exhausted its stack.
5773 // Mirrors the supervision-tree
5774 // [`supervisor_violation_on_self_supervision`] and the
5775 // Aplicacao-membership self-edge wire-up tests on the peer
5776 // typed-name-graph axes.
5777 use crate::Dep;
5778 let root = PathBuf::from("/tmp/x");
5779 let manifest = root.join("caixa.lisp");
5780 let default_lib = root.join("lib").join("demo.lisp");
5781 let layout =
5782 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5783 let mut c = caixa(CaixaKind::Biblioteca);
5784 c.deps = vec![Dep::simple("demo", "^0.1")];
5785 let err = layout.verify(&c, &root).unwrap_err();
5786 let LayoutError::DepsViolation { caixa, issue } = err else {
5787 panic!("expected LayoutError::DepsViolation, got {err:?}");
5788 };
5789 assert_eq!(caixa, "demo");
5790 assert!(
5791 issue.contains(":deps") && issue.contains("demo"),
5792 "issue must name the offending list + parent :nome: {issue}",
5793 );
5794 }
5795
5796 #[test]
5797 fn deps_violation_on_self_dep_in_deps_dev() {
5798 // Same cross-slot self-edge gate on the `:deps-dev` axis —
5799 // neither dep list is a second-class citizen of the typed
5800 // surface. The diagnostic names `:deps-dev` so the author can
5801 // grep their caixa.lisp for the offending block directly.
5802 use crate::Dep;
5803 let root = PathBuf::from("/tmp/x");
5804 let manifest = root.join("caixa.lisp");
5805 let default_lib = root.join("lib").join("demo.lisp");
5806 let layout =
5807 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5808 let mut c = caixa(CaixaKind::Biblioteca);
5809 c.deps_dev = vec![Dep::simple("demo", "^0.1")];
5810 let err = layout.verify(&c, &root).unwrap_err();
5811 let LayoutError::DepsViolation { caixa, issue } = err else {
5812 panic!("expected LayoutError::DepsViolation, got {err:?}");
5813 };
5814 assert_eq!(caixa, "demo");
5815 assert!(
5816 issue.contains(":deps-dev"),
5817 "issue must name the offending list: {issue}",
5818 );
5819 }
5820
5821 #[test]
5822 fn self_dep_fires_after_per_entry_dep_shape() {
5823 // Precedence pin: the per-entry shape gates of
5824 // [`Caixa::validate_deps`] (DNS-1123 / SemVer / fonte / etc.)
5825 // fire first on a self-dep entry whose `:nome` is malformed.
5826 // Same ordering posture every peer cross-slot gate uses
5827 // (`validate_no_self_supervision` after `SupervisorSpec::validate`,
5828 // `validate_no_self_membership` after `AplicacaoSpec::validate`).
5829 // A malformed self-dep `:nome` surfaces the narrower
5830 // per-entry diagnostic (which already names the parser-side
5831 // reason) before the self-edge gate sees the entry.
5832 use crate::Dep;
5833 let root = PathBuf::from("/tmp/x");
5834 let manifest = root.join("caixa.lisp");
5835 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5836 let mut c = caixa(CaixaKind::Biblioteca);
5837 // The parent is "demo" (DNS-1123 valid); the dep is "DEMO"
5838 // (DNS-1123 invalid). The per-entry shape gate fires on the
5839 // upper-case nome, masking the self-edge gate (and that's the
5840 // canonical precedence — fix the dep shape first, then the
5841 // structural self-edge becomes the next live diagnostic).
5842 c.deps = vec![Dep::simple("DEMO", "^0.1")];
5843 let err = layout.verify(&c, &root).unwrap_err();
5844 let LayoutError::DepsViolation { caixa: _, issue } = err else {
5845 panic!("expected LayoutError::DepsViolation, got {err:?}");
5846 };
5847 assert!(
5848 issue.contains("DNS-1123"),
5849 "issue must be the per-entry shape diagnostic, not the self-edge gate: {issue}",
5850 );
5851 }
5852
5853 #[test]
5854 fn valid_deps_pass_to_downstream_gates() {
5855 // Positive control pin: the canonical authoring shape (one
5856 // `:deps` entry naming a DNS-1123 nome + Cargo-shaped requirement,
5857 // one `:deps-dev` entry on a distinct nome) passes the dep gate;
5858 // downstream gates (MissingLib here) take over. Drift here =
5859 // a future tighten that rejects any canonical shape surfaces as
5860 // a regression at this layout-level pin.
5861 use crate::Dep;
5862 let root = PathBuf::from("/tmp/x");
5863 let manifest = root.join("caixa.lisp");
5864 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5865 let mut c = caixa(CaixaKind::Biblioteca);
5866 c.deps = vec![Dep::simple("caixa-teia", "^0.1")];
5867 c.deps_dev = vec![Dep::simple("caixa-lint", "^0.2")];
5868 let err = layout.verify(&c, &root).unwrap_err();
5869 assert!(
5870 matches!(err, LayoutError::MissingLib { .. }),
5871 "got {err:?} — valid deps must pass to MissingLib",
5872 );
5873 }
5874
5875 #[test]
5876 fn code_path_gate_runs_after_foreign_code_slot_gate() {
5877 // Precedence pin: a Servico that declares `:exe` (foreign code
5878 // surface) surfaces ForeignCodeSlot, *not* a per-entry path
5879 // shape diagnostic, even when the `:exe` entry is itself
5880 // malformed. The kind-coherence gate is the load-bearing
5881 // diagnostic at this site — once the slot is moved off the
5882 // wrong kind, the per-entry shape gate becomes the next live
5883 // diagnostic.
5884 let root = PathBuf::from("/tmp/x");
5885 let manifest = root.join("caixa.lisp");
5886 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5887 let mut c = caixa(CaixaKind::Servico);
5888 c.servicos = vec!["servicos/ok.yaml".into()];
5889 c.exe = vec!["/etc/foreign".into()];
5890 let err = layout.verify(&c, &root).unwrap_err();
5891 assert!(
5892 matches!(err, LayoutError::ForeignCodeSlot { .. }),
5893 "expected ForeignCodeSlot (kind-coherence wins over per-entry shape), got {err:?}",
5894 );
5895 }
5896
5897 // ── M2 typed-substrate invariants ────────────────────────────────────
5898
5899 #[test]
5900 fn behavior_callback_path_must_exist() {
5901 use crate::BehaviorSpec;
5902 use std::path::PathBuf;
5903 let root = PathBuf::from("/tmp/x");
5904 let manifest = root.join("caixa.lisp");
5905 let mut c = caixa(CaixaKind::Servico);
5906 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5907 let svc = root.join("servicos/demo.computeunit.yaml");
5908 c.behavior = Some(BehaviorSpec {
5909 on_init: Some(PathBuf::from("lib/init.lisp")),
5910 ..Default::default()
5911 });
5912 let manifest_clone = manifest.clone();
5913 let svc_clone = svc.clone();
5914 let layout =
5915 StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
5916 let err = layout.verify(&c, &root).unwrap_err();
5917 assert!(matches!(
5918 err,
5919 LayoutError::MissingEntry { kind, .. }
5920 if kind == crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK
5921 ));
5922
5923 // Now declare the path exists — passes.
5924 let init = root.join("lib/init.lisp");
5925 let layout =
5926 StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc || p == init);
5927 layout.verify(&c, &root).unwrap();
5928 }
5929
5930 #[test]
5931 fn behavior_absolute_callback_is_violation_not_missing() {
5932 // An absolute path silently subverts `root.join(p)` (Path::join
5933 // replaces the base when the right side is absolute). Before
5934 // BehaviorSpec::validate ran, an `:on-init "/etc/passwd"` would
5935 // surface as a confusing "missing behavior-callback /etc/passwd"
5936 // — or, worse, pass when /etc/passwd happens to exist. Now it's
5937 // a value-shape error naming the slot.
5938 use crate::BehaviorSpec;
5939 let root = PathBuf::from("/tmp/x");
5940 let manifest = root.join("caixa.lisp");
5941 let svc = root.join("servicos/demo.computeunit.yaml");
5942 let mut c = caixa(CaixaKind::Servico);
5943 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5944 c.behavior = Some(BehaviorSpec {
5945 on_init: Some(PathBuf::from("/etc/passwd")),
5946 ..Default::default()
5947 });
5948 // Path exists check would *succeed* on /etc/passwd (proving the
5949 // sandbox bypass) — value-shape pass must fire first.
5950 let layout = StandardLayout::new()
5951 .with_path_exists(move |p| p == manifest || p == svc || p == Path::new("/etc/passwd"));
5952 let err = layout.verify(&c, &root).unwrap_err();
5953 assert!(
5954 matches!(err, LayoutError::BehaviorViolation { ref caixa, .. } if caixa == "demo"),
5955 "got {err:?}",
5956 );
5957 }
5958
5959 #[test]
5960 fn behavior_empty_callback_is_violation() {
5961 use crate::BehaviorSpec;
5962 let root = PathBuf::from("/tmp/x");
5963 let manifest = root.join("caixa.lisp");
5964 let svc = root.join("servicos/demo.computeunit.yaml");
5965 let mut c = caixa(CaixaKind::Servico);
5966 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5967 c.behavior = Some(BehaviorSpec {
5968 on_call: Some(PathBuf::new()),
5969 ..Default::default()
5970 });
5971 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
5972 let err = layout.verify(&c, &root).unwrap_err();
5973 assert!(matches!(err, LayoutError::BehaviorViolation { .. }));
5974 }
5975
5976 #[test]
5977 fn upgrade_from_duplicate_surfaces_as_upgrade_violation() {
5978 // Wiring pin: the cross-entry duplicate-`:from` gate in
5979 // `validate_upgrade_from` lands on the same
5980 // `LayoutError::UpgradeViolation` axis the per-entry
5981 // `UpgradeFromEntry::validate` already does (26da2c7), so a
5982 // caixa.lisp with two `(:from "0.1.0" …)` blocks surfaces at
5983 // `feira build` time naming the offending caixa rather than
5984 // silently passing into the wasm-operator's non-deterministic
5985 // dispatch. Mirrors `behavior_empty_callback_is_violation` on
5986 // the peer M2 typed slot.
5987 use crate::{UpgradeFromEntry, UpgradeInstruction};
5988 let root = PathBuf::from("/tmp/x");
5989 let manifest = root.join("caixa.lisp");
5990 let svc = root.join("servicos/demo.computeunit.yaml");
5991 let mut c = caixa(CaixaKind::Servico);
5992 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5993 c.upgrade_from = vec![
5994 UpgradeFromEntry {
5995 from: "0.1.0".into(),
5996 instructions: vec![UpgradeInstruction::Restart],
5997 },
5998 UpgradeFromEntry {
5999 from: "0.1.0".into(),
6000 instructions: vec![UpgradeInstruction::Restart],
6001 },
6002 ];
6003 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
6004 let err = layout.verify(&c, &root).unwrap_err();
6005 let LayoutError::UpgradeViolation { caixa, issue } = err else {
6006 panic!("expected LayoutError::UpgradeViolation for duplicate `:from`, got {err:?}");
6007 };
6008 assert_eq!(caixa, "demo");
6009 assert!(
6010 issue.contains("0.1.0"),
6011 "UpgradeViolation issue must name the offending `:from` verbatim, got {issue:?}"
6012 );
6013 }
6014
6015 #[test]
6016 fn upgrade_from_downgrade_surfaces_as_upgrade_violation() {
6017 // Wiring pin: the cross-slot precedence gate in
6018 // `validate_upgrade_from_against_versao` lands on the same
6019 // `LayoutError::UpgradeViolation` axis the per-entry and
6020 // cross-entry gates already do (26da2c7, 7c6aef2), so a
6021 // caixa.lisp whose `:upgrade-from :from` is greater than the
6022 // caixa's own `:versao` surfaces at `feira build` time
6023 // naming the offending caixa rather than silently passing
6024 // into the wasm-operator's `:from`-match dispatch where the
6025 // entry would sit dormant forever. Mirrors
6026 // `upgrade_from_duplicate_surfaces_as_upgrade_violation` on
6027 // the peer cross-entry gate.
6028 use crate::{UpgradeFromEntry, UpgradeInstruction};
6029 let root = PathBuf::from("/tmp/x");
6030 let manifest = root.join("caixa.lisp");
6031 let svc = root.join("servicos/demo.computeunit.yaml");
6032 let mut c = caixa(CaixaKind::Servico);
6033 c.versao = "0.1.5".into();
6034 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
6035 c.upgrade_from = vec![UpgradeFromEntry {
6036 from: "0.2.0".into(),
6037 instructions: vec![UpgradeInstruction::Restart],
6038 }];
6039 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
6040 let err = layout.verify(&c, &root).unwrap_err();
6041 let LayoutError::UpgradeViolation { caixa, issue } = err else {
6042 panic!(
6043 "expected LayoutError::UpgradeViolation for downgrade-shaped `:from`, got {err:?}"
6044 );
6045 };
6046 assert_eq!(caixa, "demo");
6047 assert!(
6048 issue.contains("0.2.0") && issue.contains("0.1.5"),
6049 "UpgradeViolation issue must name both `:from` and `:versao` verbatim, got {issue:?}"
6050 );
6051 }
6052
6053 #[test]
6054 fn upgrade_from_equal_to_versao_surfaces_as_upgrade_violation() {
6055 // Self-upgrade no-op arm: `:from "0.1.0"` while
6056 // `:versao "0.1.0"` declares "upgrade from myself to
6057 // myself", which the operator's dispatch either skips
6058 // silently or trivially "succeeds" with no observable
6059 // transition. Surfaces at validate time naming both values
6060 // so the author can fix in one edit.
6061 use crate::{UpgradeFromEntry, UpgradeInstruction};
6062 let root = PathBuf::from("/tmp/x");
6063 let manifest = root.join("caixa.lisp");
6064 let svc = root.join("servicos/demo.computeunit.yaml");
6065 let mut c = caixa(CaixaKind::Servico);
6066 c.versao = "0.1.0".into();
6067 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
6068 c.upgrade_from = vec![UpgradeFromEntry {
6069 from: "0.1.0".into(),
6070 instructions: vec![UpgradeInstruction::Restart],
6071 }];
6072 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
6073 let err = layout.verify(&c, &root).unwrap_err();
6074 let LayoutError::UpgradeViolation { caixa, issue } = err else {
6075 panic!(
6076 "expected LayoutError::UpgradeViolation for self-upgrade `:from == :versao`, got \
6077 {err:?}"
6078 );
6079 };
6080 assert_eq!(caixa, "demo");
6081 assert!(
6082 issue.contains("0.1.0"),
6083 "UpgradeViolation issue must name the equal `:from`/`:versao` verbatim, got {issue:?}"
6084 );
6085 }
6086
6087 #[test]
6088 fn upgrade_from_strict_upgrade_passes_layout() {
6089 // Positive control for the precedence gate at the
6090 // LayoutInvariants level: a valid `:from < :versao` chain
6091 // (`0.1.0 → 0.2.0`) must not regress into a false-positive
6092 // `UpgradeViolation`. Mirrors `behavior_callback_path_must_exist`'s
6093 // positive-control arm.
6094 use crate::{UpgradeFromEntry, UpgradeInstruction};
6095 let root = PathBuf::from("/tmp/x");
6096 let manifest = root.join("caixa.lisp");
6097 let svc = root.join("servicos/demo.computeunit.yaml");
6098 let mut c = caixa(CaixaKind::Servico);
6099 c.versao = "0.2.0".into();
6100 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
6101 c.upgrade_from = vec![UpgradeFromEntry {
6102 from: "0.1.0".into(),
6103 instructions: vec![UpgradeInstruction::Restart],
6104 }];
6105 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
6106 layout.verify(&c, &root).unwrap();
6107 }
6108
6109 #[test]
6110 fn upgrade_script_path_must_exist() {
6111 use crate::{BehaviorSpec, UpgradeFromEntry, UpgradeInstruction};
6112 use std::path::PathBuf;
6113 let root = PathBuf::from("/tmp/x");
6114 let manifest = root.join("caixa.lisp");
6115 let svc = root.join("servicos/demo.computeunit.yaml");
6116 let on_state_change = root.join("lib/migrations.lisp");
6117 let mut c = caixa(CaixaKind::Servico);
6118 // `:versao` past the entry's `:from` so the cross-slot
6119 // precedence gate (`FromNotBeforeVersao`) lets this case
6120 // through to the path-existence pass under test.
6121 c.versao = "0.2.0".into();
6122 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
6123 // `:on-state-change` declared so the cross-slot composition
6124 // gate (`validate_upgrade_from_against_behavior`) lets the
6125 // `:state-change` entry through to the path-existence pass
6126 // under test. Without the callback the missing-callback gate
6127 // would surface first and the path-existence pass wouldn't be
6128 // exercised.
6129 c.behavior = Some(BehaviorSpec {
6130 on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
6131 ..Default::default()
6132 });
6133 // A `:load-module` precedes the `:state-change` so the entry
6134 // satisfies the within-entry state-change-ordering gate
6135 // (`StateChangeWithoutPriorLoad`) and the path-existence pass
6136 // under test is the gate actually exercised. `:load-module`
6137 // carries no on-disk path, so it adds no existence requirement.
6138 c.upgrade_from = vec![UpgradeFromEntry {
6139 from: "0.1.0".into(),
6140 instructions: vec![
6141 UpgradeInstruction::LoadModule {
6142 module: "demo".into(),
6143 },
6144 UpgradeInstruction::StateChange {
6145 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6146 },
6147 ],
6148 }];
6149 let manifest_clone = manifest.clone();
6150 let svc_clone = svc.clone();
6151 let on_state_change_clone = on_state_change.clone();
6152 let layout = StandardLayout::new().with_path_exists(move |p| {
6153 p == manifest_clone || p == svc_clone || p == on_state_change_clone
6154 });
6155 let err = layout.verify(&c, &root).unwrap_err();
6156 assert!(matches!(
6157 err,
6158 LayoutError::MissingEntry { kind, .. }
6159 if kind == crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT
6160 ));
6161 }
6162
6163 #[test]
6164 fn layout_missing_entry_kind_m2_consts_pin_canonical_kebab_case_labels() {
6165 // Byte-identity pin: the two per-M2-slot leaf-kind labels the
6166 // [`LayoutError::MissingEntry`] `kind: &'static str`
6167 // discriminator surfaces under (the M2 `:behavior` per-callback
6168 // on-disk-leaf axis, the M2 `:upgrade-from :instructions`
6169 // per-`:state-change` script-path on-disk-leaf axis) route
6170 // through the lifted [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`]
6171 // / [`crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT`]
6172 // consts, so a future rebrand that reaches the const but not
6173 // the production emit / test probe (or vice versa) surfaces
6174 // here at build time rather than at runtime as a downstream
6175 // [`LayoutError::MissingEntry`] `kind: <stale-label>`
6176 // diagnostic mismatch far from the rename's commit. Mirror of
6177 // the peer
6178 // [`crate::aplicacao::tests::contrato_author_key_consts_pin_canonical_kebab_case_labels`]
6179 // (f50c875) and
6180 // [`crate::upgrade::tests::upgrade_instruction_kind_consts_pin_canonical_kebab_case_tags`]
6181 // (56120ef) byte-identity pins on the sibling M3 `:contratos`
6182 // per-entry endpoint-label + M2 `:upgrade-from :instructions`
6183 // per-variant kind-tag axes.
6184 assert_eq!(
6185 crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
6186 "behavior-callback"
6187 );
6188 assert_eq!(
6189 crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
6190 "upgrade-script"
6191 );
6192 }
6193
6194 #[test]
6195 fn layout_missing_entry_kind_m0_consts_pin_canonical_code_slot_labels() {
6196 // Byte-identity pin: the three per-M0-code-slot leaf-kind
6197 // labels the [`LayoutError::MissingEntry`] `kind: &'static
6198 // str` discriminator surfaces under (the `:bibliotecas`
6199 // per-entry axis, the `:exe` per-entry axis, the `:servicos`
6200 // per-entry axis) route through the lifted
6201 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`] /
6202 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] /
6203 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] consts,
6204 // so a future rebrand that reaches the const but not the
6205 // production emit (or vice versa) surfaces here at build time
6206 // rather than at runtime as a downstream
6207 // [`LayoutError::MissingEntry`] `kind: <stale-label>`
6208 // diagnostic mismatch far from the rename's commit. Mirror of
6209 // the peer M2-tier pin
6210 // [`layout_missing_entry_kind_m2_consts_pin_canonical_kebab_case_labels`]
6211 // (95c9c4c) on the sibling `:behavior` / `:upgrade-from`
6212 // per-slot leaf-kind axes.
6213 assert_eq!(
6214 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
6215 "biblioteca"
6216 );
6217 assert_eq!(crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE, "exe");
6218 assert_eq!(crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO, "servico");
6219 }
6220
6221 #[test]
6222 fn layout_missing_entry_kind_m0_consts_align_with_caixa_kind_as_str() {
6223 // Cross-axis byte-identity pin: the two `:kind`-namesake M0
6224 // leaf-kind labels ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`]
6225 // = `"biblioteca"`,
6226 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] =
6227 // `"servico"`) must equal [`crate::CaixaKind::Biblioteca`] /
6228 // [`crate::CaixaKind::Servico`]'s
6229 // [`crate::CaixaKind::as_str`] outputs verbatim — the
6230 // substrate's canonical human-readable-kind axis and the
6231 // layout diagnostic's per-slot leaf-kind axis share one
6232 // vocabulary for these two arms by design (both label the
6233 // caixa's code-producing shape by its Portuguese-native
6234 // idiom), so drift between the two lands as a build-time
6235 // pattern-arm miss here rather than as a runtime diagnostic
6236 // that reads inconsistently across `feira build`'s
6237 // per-invocation output.
6238 //
6239 // The third M0 arm ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`]
6240 // = `"exe"`) is deliberately *distinct* from
6241 // [`crate::CaixaKind::Binario`]'s [`crate::CaixaKind::as_str`]
6242 // output (`"binario"`) — the `:exe` code slot names the
6243 // per-directory leaf-kind at the `exe/` subtree, whereas
6244 // [`crate::CaixaKind::Binario`] names the caixa's own runtime
6245 // kind. Two axes, two labels — the inequality assertion here
6246 // pins the split so a future accidental collapse of the two
6247 // onto one scalar (a rebrand that reroutes either axis to
6248 // match the other) trips at build time.
6249 assert_eq!(
6250 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
6251 CaixaKind::Biblioteca.as_str()
6252 );
6253 assert_eq!(
6254 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
6255 CaixaKind::Servico.as_str()
6256 );
6257 assert_ne!(
6258 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
6259 CaixaKind::Binario.as_str(),
6260 "`exe` leaf-kind label names the per-directory code-slot \
6261 axis; `binario` names the caixa-kind axis — the two must \
6262 not silently collapse onto one scalar"
6263 );
6264 }
6265
6266 #[test]
6267 fn layout_missing_entry_kind_consts_are_pairwise_distinct() {
6268 // Distinctness pin: the five [`LayoutError::MissingEntry`]
6269 // `kind: &'static str` accept-set members
6270 // ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`] /
6271 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] /
6272 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] on the
6273 // M0 code-slot arms plus
6274 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`]
6275 // / [`crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT`]
6276 // on the M2 slot arms) must be pairwise distinct — an
6277 // accidental copy-paste flip that reroutes one label's byte-
6278 // string to also match another silently collapses two
6279 // per-slot diagnostics onto one, so an operator running
6280 // `feira build` reads `kind: "biblioteca"` for what should
6281 // have surfaced as a `:behavior :on-init` script-not-found
6282 // diagnostic (or vice versa). This pin catches any such
6283 // flip at build time. Mirror of the peer
6284 // [`crate::render::tests::m2_limits_key_consts_are_pairwise_distinct`]
6285 // / peer distinctness pins on other closed-set typed axes.
6286 let entries: &[(&str, &str)] = &[
6287 (
6288 "LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA",
6289 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
6290 ),
6291 (
6292 "LAYOUT_MISSING_ENTRY_KIND_EXE",
6293 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
6294 ),
6295 (
6296 "LAYOUT_MISSING_ENTRY_KIND_SERVICO",
6297 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
6298 ),
6299 (
6300 "LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK",
6301 crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
6302 ),
6303 (
6304 "LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT",
6305 crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
6306 ),
6307 ];
6308 for (i, (name_a, value_a)) in entries.iter().enumerate() {
6309 for (name_b, value_b) in entries.iter().skip(i + 1) {
6310 assert_ne!(
6311 value_a, value_b,
6312 "LAYOUT_MISSING_ENTRY_KIND_* consts must be \
6313 pairwise-distinct byte-strings — {name_a} and \
6314 {name_b} both resolve to {value_a:?}"
6315 );
6316 }
6317 }
6318 }
6319
6320 #[test]
6321 fn layout_dir_consts_pin_canonical_directory_names() {
6322 // Scalar-value pin for the three [`crate::render::LAYOUT_DIR_*`]
6323 // consts naming the CSE-invariant per-[`CaixaKind`]
6324 // on-disk-directory-name axes the substrate's layout invariants
6325 // pin (`lib/` for [`CaixaKind::Biblioteca`], `exe/` for
6326 // [`CaixaKind::Binario`], `servicos/` for [`CaixaKind::Servico`]).
6327 // A future rebrand of any of the three on-disk directory landing
6328 // conventions must reach this pin — the const-edit lands on one
6329 // arm, the assertion here re-pins the new byte-string, and every
6330 // downstream consumer (the caixa-feira `init` / `fmt` / `lint` /
6331 // `tofu` scaffolders, the [`crate::LayoutInvariants::verify`]
6332 // sandbox reconstruction, the future
6333 // `feira app deploy`-cluster scaffolder) picks up the new
6334 // directory name at build time. Mirror of the peer
6335 // [`layout_missing_entry_kind_m0_consts_pin_canonical_code_slot_labels`]
6336 // (fe2a898) on the sibling
6337 // [`crate::LayoutError::MissingEntry`] `kind:` discriminator
6338 // axis this on-disk-directory axis composes with.
6339 assert_eq!(crate::render::LAYOUT_DIR_LIB, "lib");
6340 assert_eq!(crate::render::LAYOUT_DIR_EXE, "exe");
6341 assert_eq!(crate::render::LAYOUT_DIR_SERVICOS, "servicos");
6342 }
6343
6344 #[test]
6345 fn layout_dir_consts_are_pairwise_distinct() {
6346 // Distinctness pin: the three per-[`CaixaKind`]
6347 // on-disk-directory-name arms must resolve to pairwise-distinct
6348 // byte-strings — a future accidental copy-paste flip that
6349 // reroutes any one of the three onto another's value silently
6350 // collapses two per-kind on-disk sandboxes onto one, so
6351 // [`crate::LayoutInvariants::verify`] would gate a
6352 // [`CaixaKind::Binario`] caixa's `:exe` entries against the
6353 // wrong sub-tree (or a `:kind Servico` caixa's `:servicos`
6354 // entries against `lib/` and pass every entry `feira build`
6355 // should have rejected as [`crate::LayoutError::ServicoOutsideDir`]).
6356 // Mirror of the peer
6357 // [`layout_missing_entry_kind_consts_are_pairwise_distinct`]
6358 // (fe2a898) on the sibling leaf-kind label accept-set.
6359 let entries: &[(&str, &str)] = &[
6360 ("LAYOUT_DIR_LIB", crate::render::LAYOUT_DIR_LIB),
6361 ("LAYOUT_DIR_EXE", crate::render::LAYOUT_DIR_EXE),
6362 ("LAYOUT_DIR_SERVICOS", crate::render::LAYOUT_DIR_SERVICOS),
6363 ];
6364 for (i, (name_a, value_a)) in entries.iter().enumerate() {
6365 for (name_b, value_b) in entries.iter().skip(i + 1) {
6366 assert_ne!(
6367 value_a, value_b,
6368 "LAYOUT_DIR_* consts must be pairwise-distinct \
6369 byte-strings — {name_a} and {name_b} both resolve \
6370 to {value_a:?}"
6371 );
6372 }
6373 }
6374 }
6375
6376 #[test]
6377 fn layout_dir_exe_matches_layout_missing_entry_kind_exe() {
6378 // Cross-axis byte-identity pin: [`crate::render::LAYOUT_DIR_EXE`]
6379 // (the on-disk-directory-name arm) equals
6380 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] (the
6381 // [`LayoutError::MissingEntry`] `kind:` leaf-kind categorization
6382 // arm) verbatim — the M0 `:kind Binario` on-disk-directory axis
6383 // and the [`crate::LayoutError::MissingEntry`] `kind:` leaf-kind
6384 // discriminator name the same three-byte sub-tree (`exe/`), a
6385 // coincidence [`crate::LayoutInvariants::verify`] itself relies
6386 // on: it joins `root` with [`crate::render::LAYOUT_DIR_EXE`] to
6387 // reconstruct `exe_dir` and emits [`crate::LayoutError::MissingEntry
6388 // { kind: LAYOUT_MISSING_ENTRY_KIND_EXE, path: <under exe_dir> }`]
6389 // for every non-resolving entry. Making the coincidence
6390 // load-bearing means a future rebrand touching either axis
6391 // without the other (a per-consumer disambiguation collapsing
6392 // the leaf-kind label onto `"binary"` while the directory stays
6393 // `"exe"`, or vice versa) trips at caixa-core build time rather
6394 // than surfacing at runtime as a mismatched
6395 // [`crate::LayoutInvariants::verify`] diagnostic whose `kind:`
6396 // reads one label while the `path:` sits under a differently-named
6397 // sub-tree.
6398 assert_eq!(
6399 crate::render::LAYOUT_DIR_EXE,
6400 crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
6401 "LAYOUT_DIR_EXE must equal LAYOUT_MISSING_ENTRY_KIND_EXE — \
6402 both name the M0 `:kind Binario` sub-tree by the same \
6403 three-byte scalar"
6404 );
6405 }
6406
6407 #[test]
6408 fn layout_dir_bib_is_distinct_from_layout_missing_entry_kind_bib() {
6409 // Cross-axis distinctness pin: [`crate::render::LAYOUT_DIR_LIB`]
6410 // (`"lib"`, the Cargo-style abbreviated on-disk directory name)
6411 // is *deliberately* distinct from
6412 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`]
6413 // (`"biblioteca"`, the full-form Portuguese-native leaf-kind
6414 // label) — the substrate splits the on-disk convention terse
6415 // (`lib/`) from the diagnostic vocabulary full (`biblioteca`),
6416 // matching Cargo's `src/lib.rs` abbreviation of the `library`
6417 // crate-type discriminator. A future accidental collapse of the
6418 // two axes onto one scalar (a rebrand aligning either arm with
6419 // the other for schema-clarity, an English-uniformity pass that
6420 // renames `LAYOUT_DIR_LIB` to `LAYOUT_DIR_BIBLIOTECA` or the
6421 // diagnostic label to `"lib"`) would silently reroute either
6422 // consumer onto the other's byte-string. This pin catches the
6423 // collapse at build time. Peer of the sibling
6424 // [`layout_missing_entry_kind_m0_consts_align_with_caixa_kind_as_str`]
6425 // (fe2a898) that pins the analogous *equality* between the M0
6426 // `:kind Biblioteca` diagnostic-label arm and
6427 // [`crate::CaixaKind::Biblioteca`]'s [`crate::CaixaKind::as_str`]
6428 // output — the two pins jointly encode the "which of the three
6429 // Biblioteca-related scalars are load-bearing-equal, which are
6430 // load-bearing-distinct" invariant across the substrate's
6431 // per-kind vocabulary.
6432 assert_ne!(
6433 crate::render::LAYOUT_DIR_LIB,
6434 crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
6435 "LAYOUT_DIR_LIB (`\"lib\"`) and LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA \
6436 (`\"biblioteca\"`) name two distinct axes — the on-disk \
6437 directory convention (Cargo-style abbreviated) and the \
6438 layout-diagnostic leaf-kind label (full-form Portuguese) — \
6439 and must not silently collapse onto one scalar"
6440 );
6441 }
6442
6443 #[test]
6444 fn layout_dir_servicos_is_distinct_from_layout_missing_entry_kind_servico() {
6445 // Cross-axis distinctness pin: [`crate::render::LAYOUT_DIR_SERVICOS`]
6446 // (`"servicos"`, the Portuguese-*plural* on-disk directory
6447 // name) is *deliberately* distinct from
6448 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`]
6449 // (`"servico"`, the singular leaf-kind label) — the on-disk
6450 // sub-tree houses one-or-more ComputeUnit YAML descriptors per
6451 // caixa (hence the plural), the diagnostic label names the
6452 // caixa's own kind (singular). A future accidental collapse
6453 // onto one scalar (a per-consumer disambiguation aligning the
6454 // two, a hypothetical English-uniformity pass renaming
6455 // `"servicos"` → `"services"` while retaining `"servico"` on
6456 // the diagnostic arm — or vice versa) would silently reroute
6457 // either consumer onto the other's byte-string. Peer of the
6458 // sibling [`layout_dir_bib_is_distinct_from_layout_missing_entry_kind_bib`]
6459 // pin on the M0 `:kind Biblioteca` split axis; two of the three
6460 // per-kind on-disk / leaf-kind splits carry a distinctness
6461 // pin here, the third ([`crate::render::LAYOUT_DIR_EXE`] vs
6462 // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`]) carries an
6463 // equality pin under
6464 // [`layout_dir_exe_matches_layout_missing_entry_kind_exe`].
6465 assert_ne!(
6466 crate::render::LAYOUT_DIR_SERVICOS,
6467 crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
6468 "LAYOUT_DIR_SERVICOS (`\"servicos\"`, plural on-disk sub-tree) \
6469 and LAYOUT_MISSING_ENTRY_KIND_SERVICO (`\"servico\"`, singular \
6470 leaf-kind label) name two distinct axes and must not silently \
6471 collapse onto one scalar"
6472 );
6473 }
6474
6475 #[test]
6476 fn layout_invariants_reconstruct_sandbox_roots_through_lifted_layout_dir_consts() {
6477 // Production-through-const pin: [`LayoutInvariants::verify`]
6478 // routes its three per-kind sandbox-root joins
6479 // (`root.join(LAYOUT_DIR_LIB)` for the `:kind Biblioteca`
6480 // default `lib/<nome>.lisp` reconstruction, `root.join(LAYOUT_DIR_EXE)`
6481 // for the [`LayoutError::ExeOutsideDir`] gate,
6482 // `root.join(LAYOUT_DIR_SERVICOS)` for the
6483 // [`LayoutError::ServicoOutsideDir`] gate) through the three
6484 // lifted consts, not through inline `"lib"` / `"exe"` /
6485 // `"servicos"` `&str` literals. This test drives the
6486 // [`LayoutError::ExeOutsideDir`] arm through a `:kind Binario`
6487 // caixa whose declared `:exe` entry deliberately escapes
6488 // `root.join(LAYOUT_DIR_EXE)` (a sibling `bin/tool` path) —
6489 // if the production emit reads the wrong const (or reverts to
6490 // an inline literal that drifts from the const) the diagnostic
6491 // arm surfaces the wrong variant, catching the drift at build
6492 // time rather than as a per-invocation runtime mismatch.
6493 //
6494 // Mirror of the peer production-through-const pin
6495 // [`crate::dep::tests::validate_no_self_dep_deps_field_routes_through_dep_author_key`]
6496 // (4da6fba) on the sibling M0 `:deps` `list:` diagnostic axis.
6497 use std::path::PathBuf;
6498 let root = PathBuf::from("/tmp/x");
6499 let manifest = root.join("caixa.lisp");
6500 let bin_entry_outside = root.join("bin/tool");
6501 let mut c = caixa(CaixaKind::Binario);
6502 c.exe = vec!["bin/tool".into()];
6503 let manifest_clone = manifest.clone();
6504 let outside_clone = bin_entry_outside.clone();
6505 let layout = StandardLayout::new()
6506 .with_path_exists(move |p| p == manifest_clone || p == outside_clone);
6507 let err = layout.verify(&c, &root).unwrap_err();
6508 match err {
6509 LayoutError::ExeOutsideDir(path) => {
6510 assert_eq!(
6511 path, bin_entry_outside,
6512 "ExeOutsideDir must carry the resolved `:exe` entry that \
6513 escapes `root.join(LAYOUT_DIR_EXE)`"
6514 );
6515 // Byte-identity check: the escape must be against the
6516 // lifted `LAYOUT_DIR_EXE` sub-tree, not a stale inline
6517 // literal — a future const-edit that drifts from `"exe"`
6518 // reroutes `exe_dir` off the sandbox `bin/tool` escapes
6519 // from, and this pattern-arm miss re-surfaces here.
6520 assert!(
6521 !path.starts_with(root.join(crate::render::LAYOUT_DIR_EXE)),
6522 "resolved `:exe` entry {path:?} must escape the \
6523 `root.join(LAYOUT_DIR_EXE)` sub-tree the production \
6524 emit uses to gate the [`LayoutError::ExeOutsideDir`] arm"
6525 );
6526 }
6527 other => panic!("expected ExeOutsideDir, got {other:?}"),
6528 }
6529 }
6530
6531 #[test]
6532 fn upgrade_state_change_without_behavior_callback_surfaces_as_upgrade_violation() {
6533 // Wiring pin for the cross-slot composition gate
6534 // (`validate_upgrade_from_against_behavior`): a caixa whose
6535 // `:upgrade-from` declares a `(:state-change "lib/m.lisp")`
6536 // instruction but does not declare `:behavior :on-state-change`
6537 // surfaces at `feira build` time as a `LayoutError::UpgradeViolation`
6538 // naming the offending caixa + the entry's `:from` + the
6539 // offending script — not at hot-upgrade dispatch when the
6540 // operator reaches for the missing callback. Mirrors
6541 // `upgrade_from_downgrade_surfaces_as_upgrade_violation` on the
6542 // peer `:from` ↔ `:versao` cross-slot precedence gate.
6543 use crate::{UpgradeFromEntry, UpgradeInstruction};
6544 use std::path::PathBuf;
6545 let root = PathBuf::from("/tmp/x");
6546 let manifest = root.join("caixa.lisp");
6547 let svc = root.join("servicos/demo.computeunit.yaml");
6548 let mut c = caixa(CaixaKind::Servico);
6549 c.versao = "0.2.0".into();
6550 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
6551 // `:behavior` is None (the canonical "I added the upgrade path
6552 // but never declared :behavior" footgun the gate closes); a
6553 // peer arm covers the BehaviorSpec-Some-but-on-state-change-
6554 // None shape in `upgrade::tests::behavior_gate_rejects_state_
6555 // change_when_on_state_change_is_none`.
6556 c.upgrade_from = vec![UpgradeFromEntry {
6557 from: "0.1.0".into(),
6558 instructions: vec![
6559 UpgradeInstruction::LoadModule {
6560 module: "demo".into(),
6561 },
6562 UpgradeInstruction::StateChange {
6563 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6564 },
6565 ],
6566 }];
6567 let manifest_clone = manifest.clone();
6568 let svc_clone = svc.clone();
6569 let layout =
6570 StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
6571 let err = layout.verify(&c, &root).unwrap_err();
6572 match err {
6573 LayoutError::UpgradeViolation { caixa, issue } => {
6574 assert_eq!(caixa, "demo", "diagnostic must name the offending caixa");
6575 assert!(
6576 issue.contains(crate::render::M2_BEHAVIOR_AUTHOR_KEY_ON_STATE_CHANGE),
6577 "diagnostic must name the missing callback slot for self-locating fix, \
6578 got {issue:?}"
6579 );
6580 assert!(
6581 issue.contains("0.1.0"),
6582 "diagnostic must name the offending entry's :from, got {issue:?}"
6583 );
6584 assert!(
6585 issue.contains("v01-to-v02.lisp"),
6586 "diagnostic must name the offending :script for self-locating fix, \
6587 got {issue:?}"
6588 );
6589 }
6590 other => panic!("expected UpgradeViolation, got {other:?}"),
6591 }
6592 }
6593
6594 #[test]
6595 fn supervisor_must_have_children() {
6596 use crate::RestartStrategy;
6597 let root = PathBuf::from("/tmp/x");
6598 let manifest = root.join("caixa.lisp");
6599 let manifest_clone = manifest.clone();
6600 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6601 let mut c = caixa(CaixaKind::Supervisor);
6602 c.estrategia = Some(RestartStrategy::OneForOne);
6603 c.max_restarts = Some(5);
6604 // No children → should fail
6605 let err = layout.verify(&c, &root).unwrap_err();
6606 assert!(matches!(err, LayoutError::SupervisorViolation { .. }));
6607 }
6608
6609 #[test]
6610 fn supervisor_self_referential_child_is_violation() {
6611 // A Supervisor whose `:children` names its own `:nome` is a
6612 // one-node supervision cycle. The cross-slot gate fires at
6613 // verify time, surfacing as a SupervisorViolation that names the
6614 // offending supervisor — not at the cluster apply far from
6615 // source. The `caixa()` helper's `:nome` is "demo".
6616 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
6617 let root = PathBuf::from("/tmp/x");
6618 let manifest = root.join("caixa.lisp");
6619 let manifest_clone = manifest.clone();
6620 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6621 let mut c = caixa(CaixaKind::Supervisor);
6622 c.estrategia = Some(RestartStrategy::OneForOne);
6623 c.max_restarts = Some(5);
6624 c.children = vec![
6625 ChildSpec {
6626 caixa: "worker".into(),
6627 versao: "^0.1".into(),
6628 restart: RestartPolicy::Permanent,
6629 },
6630 ChildSpec {
6631 caixa: "demo".into(),
6632 versao: "^0.1".into(),
6633 restart: RestartPolicy::Permanent,
6634 },
6635 ];
6636 let err = layout.verify(&c, &root).unwrap_err();
6637 let LayoutError::SupervisorViolation { caixa, issue } = err else {
6638 panic!("expected SupervisorViolation for self-referential child, got {err:?}");
6639 };
6640 assert_eq!(caixa, "demo");
6641 assert!(
6642 issue.contains("demo") && issue.contains("itself"),
6643 "issue must name the self-supervising caixa, got {issue:?}"
6644 );
6645 }
6646
6647 #[test]
6648 fn supervisor_distinct_children_pass_self_supervision_gate() {
6649 // Positive control: a Supervisor whose children are all distinct
6650 // from its own `:nome` verifies cleanly.
6651 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
6652 let root = PathBuf::from("/tmp/x");
6653 let manifest = root.join("caixa.lisp");
6654 let manifest_clone = manifest.clone();
6655 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6656 let mut c = caixa(CaixaKind::Supervisor);
6657 c.estrategia = Some(RestartStrategy::OneForOne);
6658 c.max_restarts = Some(5);
6659 c.children = vec![ChildSpec {
6660 caixa: "worker".into(),
6661 versao: "^0.1".into(),
6662 restart: RestartPolicy::Permanent,
6663 }];
6664 layout.verify(&c, &root).unwrap();
6665 }
6666
6667 #[test]
6668 fn cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor() {
6669 // Composition pin: every cross-slot self-edge gate fired from
6670 // `LayoutInvariants::verify` — the supervision-tree arm's
6671 // `crate::supervisor::validate_no_self_supervision` call, the
6672 // Aplicacao arm's `crate::aplicacao::validate_no_self_membership`
6673 // call, and the dep-graph arm's
6674 // `crate::dep::validate_no_self_dep` call — must key its
6675 // `parent_nome` arg off the typed [`Caixa::nome`] accessor, not
6676 // the raw `&caixa.nome` `&String`-borrow of the underlying
6677 // field.
6678 //
6679 // Structurally: a rename of the storage field or a hypothetical
6680 // accessor rebrand (a per-cluster alias table pinned through a
6681 // future `:placement`-scoped slot, the M4 CR materializer's
6682 // per-CR namespace-qualified rewrite, a `:nome-suffix` overlay
6683 // the MESH-COMPOSITION §III.2 roadmap acknowledges) would land
6684 // through the accessor by construction; a raw-borrow bypass
6685 // would silently disagree with every peer consumer that already
6686 // routes through `caixa.nome()` (the caixa-mesh 980c059,
6687 // caixa-helm 22461ef, caixa-flux 162e2e2, caixa-crd 61d3429,
6688 // caixa-feira ef83332 raw-borrow converges), reintroducing the
6689 // drift surface the sibling converges closed. Each arm fires
6690 // its per-kind `LayoutError` variant (`SupervisorViolation` /
6691 // `AplicacaoViolation` / `DepsViolation`) whose `caixa` field
6692 // carries the offending parent name verbatim through
6693 // `caixa.nome().clone()`; asserting the field equals
6694 // `caixa.nome()` on the mutated fixture pins the accessor-
6695 // routed parent-nome projection at every call site — a future
6696 // silent detour that had the gate observe a stale / aliased
6697 // name at the arg boundary would surface here as a
6698 // `caixa != "demo"` inequality.
6699 //
6700 // Peer of the sibling per-caixa-crate `nome`-arg raw-borrow
6701 // convergence pin discipline (54bf2f3 / 22461ef / 162e2e2 on the
6702 // renderer crates; ef83332 on the CLI) — extends the "one typed
6703 // dispatch per `:nome` consumer" discipline onto the substrate's
6704 // own [`LayoutInvariants::verify`] cross-slot self-edge gate
6705 // wire-up on all three typed-name-graph kinds.
6706 use crate::{
6707 ChildSpec, Dep, Membro, Placement, PlacementStrategy, RestartPolicy, RestartStrategy,
6708 };
6709 let root = PathBuf::from("/tmp/x");
6710 let manifest = root.join("caixa.lisp");
6711 let manifest_clone = manifest.clone();
6712 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6713
6714 // Supervisor arm — the `caixa()` helper's `:nome` is "demo",
6715 // and the accessor's return `caixa.nome()` must equal the
6716 // parent-nome that the self-supervision gate observes.
6717 let mut sup = caixa(CaixaKind::Supervisor);
6718 sup.estrategia = Some(RestartStrategy::OneForOne);
6719 sup.max_restarts = Some(5);
6720 sup.children = vec![ChildSpec {
6721 caixa: "demo".into(),
6722 versao: "^0.1".into(),
6723 restart: RestartPolicy::Permanent,
6724 }];
6725 let parent_nome_via_accessor = sup.nome();
6726 assert_eq!(
6727 parent_nome_via_accessor, "demo",
6728 "the caixa() fixture helper's `:nome` must be \"demo\" — \
6729 the accessor's return is the pin's ground truth for the \
6730 cross-slot gate's parent-nome arg",
6731 );
6732 let err = layout.verify(&sup, &root).unwrap_err();
6733 let LayoutError::SupervisorViolation { caixa: c_nome, .. } = err else {
6734 panic!("expected SupervisorViolation for self-referential child, got {err:?}");
6735 };
6736 assert_eq!(
6737 c_nome, parent_nome_via_accessor,
6738 "the SupervisorViolation's `caixa` field must equal \
6739 `sup.nome()` — the cross-slot self-supervision gate's \
6740 `parent_nome` arg must route through the lifted \
6741 [`Caixa::nome`] accessor, not the raw `&caixa.nome` \
6742 `&String`-borrow of the underlying field",
6743 );
6744
6745 // Aplicacao arm — same discipline on the peer typed-name-graph
6746 // kind. Constructed alongside the supervisor arm so any future
6747 // accessor drift lands on both arms in the same pin.
6748 let mut app = caixa(CaixaKind::Aplicacao);
6749 app.placement = Some(Placement {
6750 estrategia: PlacementStrategy::Replicated,
6751 clusters: vec!["rio".into()],
6752 affinity: None,
6753 shard_key: None,
6754 });
6755 app.membros = vec![Membro {
6756 caixa: "demo".into(),
6757 versao: "^0.1".into(),
6758 }];
6759 let parent_nome_via_accessor = app.nome();
6760 assert_eq!(
6761 parent_nome_via_accessor, "demo",
6762 "the caixa() fixture helper's `:nome` must be \"demo\" on \
6763 the Aplicacao arm too — same accessor-ground-truth as the \
6764 sibling supervisor arm above",
6765 );
6766 let err = layout.verify(&app, &root).unwrap_err();
6767 let LayoutError::AplicacaoViolation { caixa: c_nome, .. } = err else {
6768 panic!("expected AplicacaoViolation for self-referential membro, got {err:?}");
6769 };
6770 assert_eq!(
6771 c_nome, parent_nome_via_accessor,
6772 "the AplicacaoViolation's `caixa` field must equal \
6773 `app.nome()` — the cross-slot self-membership gate's \
6774 `parent_nome` arg must route through the lifted \
6775 [`Caixa::nome`] accessor, not the raw `&caixa.nome` \
6776 `&String`-borrow of the underlying field",
6777 );
6778
6779 // Dep-graph arm — third typed-name-graph kind on the
6780 // `parent_nome` arg boundary. Same discipline as the peer
6781 // supervision-tree and Aplicacao-membership arms above.
6782 // Constructed alongside so any future accessor drift lands on
6783 // all three arms in the same pin. Needs a distinct layout
6784 // fixture from the supervisor / aplicacao arms above because
6785 // the `Biblioteca` kind's code-path existence gate demands the
6786 // canonical `lib/<nome>.lisp` path also `exists`, so the shim
6787 // covers both `caixa.lisp` and `lib/demo.lisp`.
6788 let default_lib = root.join("lib").join("demo.lisp");
6789 let manifest_dep = manifest.clone();
6790 let default_lib_clone = default_lib.clone();
6791 let layout_dep = StandardLayout::new()
6792 .with_path_exists(move |p| p == manifest_dep || p == default_lib_clone);
6793 let mut lib = caixa(CaixaKind::Biblioteca);
6794 lib.deps = vec![Dep::simple("demo", "^0.1")];
6795 let parent_nome_via_accessor = lib.nome();
6796 assert_eq!(
6797 parent_nome_via_accessor, "demo",
6798 "the caixa() fixture helper's `:nome` must be \"demo\" on \
6799 the Biblioteca arm too — same accessor-ground-truth as the \
6800 sibling supervisor + Aplicacao arms above",
6801 );
6802 let err = layout_dep.verify(&lib, &root).unwrap_err();
6803 let LayoutError::DepsViolation { caixa: c_nome, .. } = err else {
6804 panic!("expected DepsViolation for self-referential :deps entry, got {err:?}");
6805 };
6806 assert_eq!(
6807 c_nome, parent_nome_via_accessor,
6808 "the DepsViolation's `caixa` field must equal \
6809 `lib.nome()` — the cross-slot self-dep gate's `parent_nome` \
6810 arg must route through the lifted [`Caixa::nome`] accessor, \
6811 not the raw `&caixa.nome` `&String`-borrow of the underlying \
6812 field",
6813 );
6814 }
6815
6816 #[test]
6817 fn upgrade_against_versao_gate_routes_current_versao_through_lifted_accessor() {
6818 // Composition pin: the cross-slot `:upgrade-from :from` ↔
6819 // `:versao` precedence gate fired from
6820 // `LayoutInvariants::verify` — the
6821 // `crate::upgrade::validate_upgrade_from_against_versao` call —
6822 // must key its `versao` arg off the typed [`Caixa::versao`]
6823 // accessor, not the raw `&caixa.versao` `&String`-borrow of
6824 // the underlying field.
6825 //
6826 // Same "arg-boundary reads through the lifted accessor"
6827 // discipline as the sibling
6828 // [`cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor`]
6829 // pin above on the `:nome`-arg axis of the three typed-name-
6830 // graph self-edge gates — extended here onto the `:versao`-arg
6831 // axis of the substrate's remaining `LayoutInvariants::verify`
6832 // cross-slot arg-carrying call site. Structurally byte-equal
6833 // today (the accessor is `pub fn versao(&self) -> &str { &self.versao }`,
6834 // so both paths coerce to the same `&str`); the pin catches a
6835 // future silent detour (an accessor rebrand that no longer
6836 // shipped the raw slot verbatim — a per-`:edicao` overlay,
6837 // a promotion of `:versao` to a `CaixaVersion` newtype with a
6838 // canonicalizing accessor, an M4 CR-materializer-side pinning
6839 // through a resolver-annotated `:versao-resolved` slot) that
6840 // would silently split the substrate's own precedence gate
6841 // from every peer consumer already routing `:versao` reads
6842 // through the lifted accessor.
6843 //
6844 // The gate fires an `UpgradeViolation { caixa, issue }` when a
6845 // `:upgrade-from` entry's `:from` is not strictly less than
6846 // the top-level `:versao` — the `issue` string names both the
6847 // offending prior version and the current version verbatim,
6848 // so asserting the substring `caixa.versao()` appears in the
6849 // fired diagnostic pins the accessor-routed current-versao
6850 // projection at the arg boundary. A raw-borrow bypass would
6851 // still surface the same bytes today, but the presence of
6852 // this pin makes any future divergence between the accessor's
6853 // return and the raw slot's contents a build-time failure at
6854 // this call site.
6855 use crate::{UpgradeFromEntry, UpgradeInstruction};
6856 let root = PathBuf::from("/tmp/x");
6857 let manifest = root.join("caixa.lisp");
6858 let servico_path = root.join("servicos").join("demo.computeunit.yaml");
6859 let manifest_clone = manifest.clone();
6860 let servico_clone = servico_path.clone();
6861 let layout = StandardLayout::new()
6862 .with_path_exists(move |p| p == manifest_clone || p == servico_clone);
6863 let mut svc = caixa(CaixaKind::Servico);
6864 svc.versao = "0.1.0".into();
6865 svc.servicos = vec!["servicos/demo.computeunit.yaml".into()];
6866 // `:from` >= current `:versao` — trips the precedence gate the
6867 // `validate_upgrade_from_against_versao` cross-slot call
6868 // enforces. `:load-module` carries no on-disk path so the
6869 // path-existence gate downstream stays inert; the precedence
6870 // gate is what fires. No `:on-state-change` needed because the
6871 // instruction list carries no `:state-change` entry, so the
6872 // sibling `validate_upgrade_from_against_behavior` gate is
6873 // inert too.
6874 svc.upgrade_from = vec![UpgradeFromEntry {
6875 from: "0.2.0".into(),
6876 instructions: vec![UpgradeInstruction::LoadModule {
6877 module: "demo".into(),
6878 }],
6879 }];
6880 let current_versao_via_accessor = svc.versao().to_string();
6881 assert_eq!(
6882 current_versao_via_accessor, "0.1.0",
6883 "the mutated fixture's `:versao` must be observable through \
6884 the accessor before layout verification fires — a drift on \
6885 `Caixa::versao` would surface here as a `!= \"0.1.0\"` \
6886 inequality",
6887 );
6888 let err = layout.verify(&svc, &root).unwrap_err();
6889 let LayoutError::UpgradeViolation {
6890 caixa: c_nome,
6891 issue,
6892 } = err
6893 else {
6894 panic!("expected UpgradeViolation for :from >= :versao, got {err:?}");
6895 };
6896 assert_eq!(c_nome, svc.nome(), "wrap envelope names the caixa");
6897 assert!(
6898 issue.contains(¤t_versao_via_accessor),
6899 "the UpgradeViolation's `issue` must quote the current \
6900 `:versao` byte-string verbatim — the cross-slot precedence \
6901 gate's `versao` arg must route through the lifted \
6902 [`Caixa::versao`] accessor, not the raw `&caixa.versao` \
6903 `&String`-borrow of the underlying field. issue: {issue}",
6904 );
6905 }
6906
6907 #[test]
6908 fn layout_violation_envelopes_carry_caixa_nome_through_lifted_accessor() {
6909 // Wrap-envelope drift-detection pin: every per-axis
6910 // `LayoutError::*Violation { caixa, issue }` envelope fired
6911 // from `LayoutInvariants::verify` must key its offending-caixa
6912 // field off the typed [`Caixa::nome`] accessor's
6913 // `.to_string()` extension, not the raw
6914 // `caixa.nome.clone()` `String::clone()` of the underlying
6915 // field. Structurally byte-equal today (each accessor is
6916 // `pub fn nome(&self) -> &str { &self.nome }`, so
6917 // `caixa.nome().to_string()` and `caixa.nome.clone()` produce
6918 // the same bytes); the pin catches a future silent detour
6919 // (an accessor rebrand that no longer shipped the raw slot
6920 // verbatim — a per-cluster alias table pinned through a
6921 // future `:placement`-scoped slot, the M4 CR materializer's
6922 // per-CR namespace-qualified rewrite, a `:nome-suffix`
6923 // overlay the MESH-COMPOSITION §III.2 roadmap acknowledges)
6924 // that would silently split the substrate's own layout
6925 // invariant verifier's diagnostic surface from every peer
6926 // caixa-crate consumer that already routes `:nome` reads
6927 // through the lifted accessor (the caixa-mesh 980c059,
6928 // caixa-helm 22461ef, caixa-flux 162e2e2, caixa-crd 61d3429,
6929 // caixa-feira ef83332 raw-borrow converges).
6930 //
6931 // Exercises a representative variant on each of the three
6932 // wrap-envelope arm shapes the substrate's per-axis fan-out
6933 // carries: (1) `LayoutError::NomeViolation` (the leading arm
6934 // in the `verify` order — the `:nome` axis's DNS-1123 shape
6935 // gate fires immediately after the manifest-existence gate),
6936 // (2) `LayoutError::BinarioWithoutExe` (a tuple-variant on
6937 // the kind-coherence family — different envelope shape than
6938 // the struct-variant `*Violation { caixa, issue }` family
6939 // but the same converge target on the `caixa.nome().to_string()`
6940 // arg), and (3) `LayoutError::ServicoWithoutServicos` (the
6941 // sibling tuple-variant on the same kind-coherence family).
6942 // Together they cover the two `LayoutError` envelope shapes
6943 // (struct-variant + tuple-variant) the layout invariants file
6944 // emits on `:nome`-carrying arms.
6945 //
6946 // Peer of the sibling
6947 // [`cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor`]
6948 // pin above — extends the "wrap-envelope `caixa:` field
6949 // reads through the lifted accessor" discipline from the
6950 // cross-slot self-edge gates' `parent_nome` arg boundary
6951 // onto the per-axis `LayoutError::*Violation` envelope's
6952 // `caixa:` field boundary.
6953
6954 let root = PathBuf::from("/tmp/x");
6955 let manifest = root.join("caixa.lisp");
6956 let manifest_clone = manifest.clone();
6957 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6958
6959 // (1) `NomeViolation` on the struct-variant envelope: force a
6960 // DNS-1123-invalid `:nome` (uppercase byte — `is_dns_1123_label`
6961 // rejects) and assert the fired envelope's `caixa:` field
6962 // byte-equals `c.nome().to_string()`.
6963 let mut c = caixa(CaixaKind::Biblioteca);
6964 c.nome = "BAD_NAME".into();
6965 c.bibliotecas = vec!["lib/demo.lisp".into()];
6966 let expected_nome_via_accessor = c.nome().to_string();
6967 assert_eq!(
6968 expected_nome_via_accessor, "BAD_NAME",
6969 "the mutated fixture's `:nome` must be observable through \
6970 the accessor before layout verification fires — a drift \
6971 on `Caixa::nome` would surface here as a `!= \"BAD_NAME\"` \
6972 inequality",
6973 );
6974 let err = layout.verify(&c, &root).unwrap_err();
6975 let LayoutError::NomeViolation { caixa: c_nome, .. } = err else {
6976 panic!("expected NomeViolation for DNS-1123-invalid :nome, got {err:?}");
6977 };
6978 assert_eq!(
6979 c_nome, expected_nome_via_accessor,
6980 "the NomeViolation's `caixa` field must equal \
6981 `c.nome().to_string()` — the wrap envelope's per-axis \
6982 projection must route through the lifted [`Caixa::nome`] \
6983 accessor's `.to_string()` extension, not the raw \
6984 `caixa.nome.clone()` `String::clone()` of the underlying \
6985 field",
6986 );
6987
6988 // (2) `BinarioWithoutExe` on the tuple-variant envelope: a
6989 // Binario-kind caixa with an empty `:exe` list fires the
6990 // kind-coherence gate whose payload is a bare `String`, so the
6991 // pattern is `LayoutError::BinarioWithoutExe(String)` rather
6992 // than the struct-variant `{ caixa, issue }` family. The
6993 // converge target is the same — `caixa.nome().to_string()` — but
6994 // the envelope shape is different, so the pin exercises both.
6995 let mut c = caixa(CaixaKind::Binario);
6996 // `:exe` empty is the trigger — the fixture helper defaults
6997 // it to `vec![]`, so no mutation is needed.
6998 c.nome = "binario-demo".into();
6999 let expected_nome_via_accessor = c.nome().to_string();
7000 assert_eq!(
7001 expected_nome_via_accessor, "binario-demo",
7002 "the mutated fixture's `:nome` must be observable through \
7003 the accessor before layout verification fires",
7004 );
7005 let err = layout.verify(&c, &root).unwrap_err();
7006 let LayoutError::BinarioWithoutExe(c_nome) = err else {
7007 panic!("expected BinarioWithoutExe for empty :exe list on Binario kind, got {err:?}");
7008 };
7009 assert_eq!(
7010 c_nome, expected_nome_via_accessor,
7011 "the BinarioWithoutExe's payload must equal \
7012 `c.nome().to_string()` — the tuple-variant envelope's \
7013 per-axis projection must route through the lifted \
7014 [`Caixa::nome`] accessor's `.to_string()` extension, not \
7015 the raw `caixa.nome.clone()` `String::clone()` of the \
7016 underlying field",
7017 );
7018
7019 // (3) `ServicoWithoutServicos` on the sibling tuple-variant
7020 // envelope: same discipline on the peer kind-coherence
7021 // partition arm. Constructed alongside the Binario arm so any
7022 // future accessor drift lands on both arms in the same pin.
7023 let mut c = caixa(CaixaKind::Servico);
7024 // `:servicos` empty is the trigger — the fixture helper
7025 // defaults it to `vec![]`, so no mutation is needed.
7026 c.nome = "servico-demo".into();
7027 let expected_nome_via_accessor = c.nome().to_string();
7028 assert_eq!(
7029 expected_nome_via_accessor, "servico-demo",
7030 "the mutated fixture's `:nome` must be observable through \
7031 the accessor before layout verification fires",
7032 );
7033 let err = layout.verify(&c, &root).unwrap_err();
7034 let LayoutError::ServicoWithoutServicos(c_nome) = err else {
7035 panic!(
7036 "expected ServicoWithoutServicos for empty :servicos list on Servico kind, \
7037 got {err:?}"
7038 );
7039 };
7040 assert_eq!(
7041 c_nome, expected_nome_via_accessor,
7042 "the ServicoWithoutServicos's payload must equal \
7043 `c.nome().to_string()` — same converge discipline as the \
7044 sibling `BinarioWithoutExe` tuple-variant arm above",
7045 );
7046 }
7047
7048 #[test]
7049 fn supervisor_must_not_have_bibliotecas() {
7050 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
7051 let root = PathBuf::from("/tmp/x");
7052 let manifest = root.join("caixa.lisp");
7053 let manifest_clone = manifest.clone();
7054 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7055 let mut c = caixa(CaixaKind::Supervisor);
7056 c.estrategia = Some(RestartStrategy::OneForOne);
7057 c.max_restarts = Some(5);
7058 c.bibliotecas = vec!["lib/code.lisp".into()];
7059 c.children = vec![ChildSpec {
7060 caixa: "worker".into(),
7061 versao: "^0.1".into(),
7062 restart: RestartPolicy::Permanent,
7063 }];
7064 let err = layout.verify(&c, &root).unwrap_err();
7065 assert!(matches!(err, LayoutError::SupervisorOwnsCode(_)));
7066 }
7067
7068 // ── Caixa::validate_restart_window wired into Supervisor verify ─────
7069 //
7070 // Until this wire-up landed `Caixa::validate_restart_window` lived as
7071 // `pub fn` on `Caixa` with full per-arm unit coverage in
7072 // `manifest::tests` (`validate_restart_window_rejects_*` — fractional,
7073 // decimal-shaped integer, half-unit minute, leading sign, unknown
7074 // unit, garbage, empty-after-trim) but no production path called it;
7075 // `feira build` silently accepted malformed `:restart-window` and
7076 // `Caixa::supervisor_view` soft-swallowed the parse failure as
7077 // `restart_window: None` (the canonical "no reset" sentinel), turning
7078 // every authoring footgun into a never-reset supervisor far from the
7079 // source caixa.lisp. The following pins fence the layout-pipeline
7080 // wire-up: every layout verify on a structurally-invalid `:restart-
7081 // window` axis surfaces the per-axis `RestartWindowViolation { caixa,
7082 // issue }` envelope before the typed `SupervisorSpec::validate` gate
7083 // sees the laundered `None`.
7084
7085 fn supervisor_with_window(window: Option<&str>) -> Caixa {
7086 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
7087 let mut c = caixa(CaixaKind::Supervisor);
7088 c.estrategia = Some(RestartStrategy::OneForOne);
7089 c.max_restarts = Some(5);
7090 c.restart_window = window.map(str::to_string);
7091 c.children = vec![ChildSpec {
7092 caixa: "worker".into(),
7093 versao: "^0.1".into(),
7094 restart: RestartPolicy::Permanent,
7095 }];
7096 c
7097 }
7098
7099 #[test]
7100 fn restart_window_violation_on_fractional_seconds() {
7101 // `"1.5s"` is the canonical fractional-seconds drift footgun the
7102 // shared integer-magnitude codec (1c55a2a) rejects: round-trips
7103 // through `render` as `"1500ms"` on first serialize, breaking
7104 // THEORY.md §V.2.7 render-determinism. Before this wire-up
7105 // `supervisor_view` soft-swallowed the parse error as
7106 // `restart_window: None`, masking the drift as a never-reset
7107 // supervisor.
7108 let root = PathBuf::from("/tmp/x");
7109 let manifest = root.join("caixa.lisp");
7110 let manifest_clone = manifest.clone();
7111 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7112 let c = supervisor_with_window(Some("1.5s"));
7113 let err = layout.verify(&c, &root).unwrap_err();
7114 let LayoutError::RestartWindowViolation { caixa, issue } = err else {
7115 panic!("expected LayoutError::RestartWindowViolation, got {err:?}");
7116 };
7117 assert_eq!(caixa, "demo");
7118 assert!(
7119 issue.contains("1.5s"),
7120 "issue must quote the offending raw value: {issue}",
7121 );
7122 }
7123
7124 #[test]
7125 fn restart_window_violation_on_decimal_shaped_integer() {
7126 // `"1.0s"` — decimal-shaped integer the codec also rejects (a
7127 // canonical authoring form is `"1s"`). Sibling of the fractional
7128 // case; same codec arm.
7129 let root = PathBuf::from("/tmp/x");
7130 let manifest = root.join("caixa.lisp");
7131 let manifest_clone = manifest.clone();
7132 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7133 let c = supervisor_with_window(Some("1.0s"));
7134 let err = layout.verify(&c, &root).unwrap_err();
7135 assert!(
7136 matches!(
7137 err,
7138 LayoutError::RestartWindowViolation { ref caixa, ref issue }
7139 if caixa == "demo" && issue.contains("1.0s")
7140 ),
7141 "got {err:?}",
7142 );
7143 }
7144
7145 #[test]
7146 fn restart_window_violation_on_leading_sign() {
7147 // `"+30s"` / `"-30s"` — leading-sign drift the codec rejects.
7148 // Canonical form is `"30s"`. Pin both signs separately because
7149 // a future relaxation might accept one but not the other.
7150 for raw in ["+30s", "-30s"] {
7151 let root = PathBuf::from("/tmp/x");
7152 let manifest = root.join("caixa.lisp");
7153 let manifest_clone = manifest.clone();
7154 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7155 let c = supervisor_with_window(Some(raw));
7156 let err = layout.verify(&c, &root).unwrap_err();
7157 assert!(
7158 matches!(
7159 err,
7160 LayoutError::RestartWindowViolation { ref caixa, ref issue }
7161 if caixa == "demo" && issue.contains(raw)
7162 ),
7163 "leading-sign {raw:?} got {err:?}",
7164 );
7165 }
7166 }
7167
7168 #[test]
7169 fn restart_window_violation_on_unknown_unit() {
7170 // `"30x"` — unknown duration unit. The codec admits only
7171 // `ms`/`s`/`m`/`h`.
7172 let root = PathBuf::from("/tmp/x");
7173 let manifest = root.join("caixa.lisp");
7174 let manifest_clone = manifest.clone();
7175 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7176 let c = supervisor_with_window(Some("30x"));
7177 let err = layout.verify(&c, &root).unwrap_err();
7178 assert!(
7179 matches!(
7180 err,
7181 LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"
7182 ),
7183 "got {err:?}",
7184 );
7185 }
7186
7187 #[test]
7188 fn restart_window_violation_on_garbage() {
7189 // `"abc"` — pure garbage. The codec's parse fails before the
7190 // unit dispatch; the wrap envelope still surfaces the
7191 // self-locating diagnostic at the source.
7192 let root = PathBuf::from("/tmp/x");
7193 let manifest = root.join("caixa.lisp");
7194 let manifest_clone = manifest.clone();
7195 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7196 let c = supervisor_with_window(Some("abc"));
7197 let err = layout.verify(&c, &root).unwrap_err();
7198 assert!(
7199 matches!(err, LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"),
7200 "got {err:?}",
7201 );
7202 }
7203
7204 #[test]
7205 fn restart_window_violation_on_empty_string() {
7206 // `""` — empty after trim. The shared codec's digit-only gate
7207 // refuses an empty magnitude. Distinguished here from the
7208 // `None` ("omit the slot") canonical authoring shape: an empty
7209 // string is an authored-but-empty slot, never the author's
7210 // intent.
7211 let root = PathBuf::from("/tmp/x");
7212 let manifest = root.join("caixa.lisp");
7213 let manifest_clone = manifest.clone();
7214 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7215 let c = supervisor_with_window(Some(""));
7216 let err = layout.verify(&c, &root).unwrap_err();
7217 assert!(
7218 matches!(err, LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"),
7219 "got {err:?}",
7220 );
7221 }
7222
7223 #[test]
7224 fn verify_accepts_supervisor_without_restart_window() {
7225 // `None` is the canonical "omit the slot to express no reset"
7226 // shape — never reaches the codec, validates cleanly.
7227 let root = PathBuf::from("/tmp/x");
7228 let manifest = root.join("caixa.lisp");
7229 let manifest_clone = manifest.clone();
7230 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7231 let c = supervisor_with_window(None);
7232 layout.verify(&c, &root).unwrap();
7233 }
7234
7235 #[test]
7236 fn verify_accepts_supervisor_with_canonical_restart_window() {
7237 // Every canonical form the shared codec round-trips losslessly
7238 // must pass — `"500ms"`, `"30s"`, `"60s"`, `"1m"`, `"2m"`,
7239 // `"1h"`. Pin every form so a future tightening of the codec's
7240 // accepted set surfaces here as a test failure.
7241 for form in ["500ms", "30s", "60s", "1m", "2m", "1h"] {
7242 let root = PathBuf::from("/tmp/x");
7243 let manifest = root.join("caixa.lisp");
7244 let manifest_clone = manifest.clone();
7245 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7246 let c = supervisor_with_window(Some(form));
7247 layout
7248 .verify(&c, &root)
7249 .unwrap_or_else(|e| panic!("canonical {form:?} must validate, got {e:?}"));
7250 }
7251 }
7252
7253 #[test]
7254 fn restart_window_violation_fires_before_supervisor_view_validate() {
7255 // Diagnostic-precedence pin: a Supervisor with a malformed
7256 // `:restart-window` AND a typed-shape defect on the typed view
7257 // (zero `:max-restarts`, which `SupervisorSpec::validate`'s
7258 // `ZeroMaxRestarts` arm rejects) surfaces the raw-string
7259 // diagnostic first — the narrower self-locating gate wins. Until
7260 // this wire-up landed `supervisor_view` would silently launder
7261 // the malformed `:restart-window` to `None` and then the typed
7262 // view's `ZeroMaxRestarts` gate would surface, masking the
7263 // raw-string footgun.
7264 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
7265 let root = PathBuf::from("/tmp/x");
7266 let manifest = root.join("caixa.lisp");
7267 let manifest_clone = manifest.clone();
7268 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7269 let mut c = caixa(CaixaKind::Supervisor);
7270 c.estrategia = Some(RestartStrategy::OneForOne);
7271 c.max_restarts = Some(0);
7272 c.restart_window = Some("1.5s".into());
7273 c.children = vec![ChildSpec {
7274 caixa: "worker".into(),
7275 versao: "^0.1".into(),
7276 restart: RestartPolicy::Permanent,
7277 }];
7278 let err = layout.verify(&c, &root).unwrap_err();
7279 assert!(
7280 matches!(err, LayoutError::RestartWindowViolation { .. }),
7281 "got {err:?} — RestartWindowViolation must fire before SupervisorViolation",
7282 );
7283 }
7284
7285 #[test]
7286 fn supervisor_slots_on_non_supervisor_fires_before_restart_window_violation() {
7287 // Order pin: a non-Supervisor caixa with a malformed
7288 // `:restart-window` surfaces `SupervisorSlotsOnNonSupervisor`
7289 // (the kind-coherence gate at the top of verify) before the
7290 // raw-string parse gate inside the Supervisor branch — because
7291 // `:restart-window` is foreign to non-Supervisor kinds, the
7292 // kind-coherence diagnostic is the load-bearing one. Mirrors
7293 // the existing `nome_violation_on_*` ordering tests that fence
7294 // the precedence between universal and kind-specific gates.
7295 let root = PathBuf::from("/tmp/x");
7296 let manifest = root.join("caixa.lisp");
7297 let default_lib = root.join("lib").join("demo.lisp");
7298 let layout =
7299 StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
7300 let mut c = caixa(CaixaKind::Biblioteca);
7301 c.restart_window = Some("1.5s".into());
7302 let err = layout.verify(&c, &root).unwrap_err();
7303 assert!(
7304 matches!(err, LayoutError::SupervisorSlotsOnNonSupervisor { .. }),
7305 "got {err:?} — kind-coherence must fire before RestartWindowViolation",
7306 );
7307 }
7308
7309 #[test]
7310 fn restart_window_violation_diagnostic_carries_offending_value() {
7311 // Diagnostic-shape pin: the wrap envelope's `issue` carries the
7312 // codec's parser-shaped reason verbatim (which names the
7313 // offending raw value), so the author can grep their caixa.lisp
7314 // for `:restart-window "<value>"` and fix in one edit. Mirrors
7315 // `nome_violation_*_carries_offending_*` shape pins.
7316 let root = PathBuf::from("/tmp/x");
7317 let manifest = root.join("caixa.lisp");
7318 let manifest_clone = manifest.clone();
7319 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7320 let c = supervisor_with_window(Some("0.5m"));
7321 let err = layout.verify(&c, &root).unwrap_err();
7322 let LayoutError::RestartWindowViolation { caixa, issue } = err else {
7323 panic!("expected LayoutError::RestartWindowViolation, got {err:?}");
7324 };
7325 assert_eq!(caixa, "demo");
7326 assert!(
7327 issue.contains("0.5m"),
7328 "issue must quote the offending raw value verbatim: {issue}",
7329 );
7330 assert!(
7331 !issue.is_empty(),
7332 "issue must carry the codec's parser-shaped reason",
7333 );
7334 }
7335
7336 // ── Aplicacao layout tests ──────────────────────────────────────────
7337
7338 #[test]
7339 fn aplicacao_must_have_membros() {
7340 use crate::{Membro, Placement, PlacementStrategy};
7341 let root = PathBuf::from("/tmp/x");
7342 let manifest = root.join("caixa.lisp");
7343 let manifest_clone = manifest.clone();
7344 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7345 let mut c = caixa(CaixaKind::Aplicacao);
7346 c.placement = Some(Placement {
7347 estrategia: PlacementStrategy::Replicated,
7348 clusters: vec!["rio".into()],
7349 affinity: None,
7350 shard_key: None,
7351 });
7352 // No membros → fails
7353 let err = layout.verify(&c, &root).unwrap_err();
7354 assert!(matches!(err, LayoutError::AplicacaoViolation { .. }));
7355
7356 // With membros → passes
7357 c.membros = vec![Membro {
7358 caixa: "service-a".into(),
7359 versao: "^0.1".into(),
7360 }];
7361 layout.verify(&c, &root).unwrap();
7362 }
7363
7364 #[test]
7365 fn aplicacao_self_referential_membro_is_violation() {
7366 // An Aplicacao whose `:membros` names its own `:nome` is a
7367 // one-node lacre-closure recursion. The cross-slot gate fires
7368 // at verify time, surfacing as an AplicacaoViolation that
7369 // names the offending aplicacao — not at lacre-resolve time
7370 // far from source. The `caixa()` helper's `:nome` is "demo".
7371 // Peer of `supervisor_self_referential_child_is_violation`
7372 // on the supervision-tree axis.
7373 use crate::{Membro, Placement, PlacementStrategy};
7374 let root = PathBuf::from("/tmp/x");
7375 let manifest = root.join("caixa.lisp");
7376 let manifest_clone = manifest.clone();
7377 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7378 let mut c = caixa(CaixaKind::Aplicacao);
7379 c.placement = Some(Placement {
7380 estrategia: PlacementStrategy::Replicated,
7381 clusters: vec!["rio".into()],
7382 affinity: None,
7383 shard_key: None,
7384 });
7385 c.membros = vec![
7386 Membro {
7387 caixa: "service-a".into(),
7388 versao: "^0.1".into(),
7389 },
7390 Membro {
7391 caixa: "demo".into(),
7392 versao: "^0.1".into(),
7393 },
7394 ];
7395 let err = layout.verify(&c, &root).unwrap_err();
7396 let LayoutError::AplicacaoViolation { caixa, issue } = err else {
7397 panic!("expected AplicacaoViolation for self-referential membro, got {err:?}");
7398 };
7399 assert_eq!(caixa, "demo");
7400 assert!(
7401 issue.contains("demo") && issue.contains("lists itself"),
7402 "issue must name the self-membering aplicacao, got {issue:?}"
7403 );
7404 }
7405
7406 #[test]
7407 fn aplicacao_distinct_membros_pass_self_membership_gate() {
7408 // Positive control: an Aplicacao whose membros are all distinct
7409 // from its own `:nome` verifies cleanly.
7410 use crate::{Membro, Placement, PlacementStrategy};
7411 let root = PathBuf::from("/tmp/x");
7412 let manifest = root.join("caixa.lisp");
7413 let manifest_clone = manifest.clone();
7414 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7415 let mut c = caixa(CaixaKind::Aplicacao);
7416 c.placement = Some(Placement {
7417 estrategia: PlacementStrategy::Replicated,
7418 clusters: vec!["rio".into()],
7419 affinity: None,
7420 shard_key: None,
7421 });
7422 c.membros = vec![
7423 Membro {
7424 caixa: "service-a".into(),
7425 versao: "^0.1".into(),
7426 },
7427 Membro {
7428 caixa: "service-b".into(),
7429 versao: "^0.1".into(),
7430 },
7431 ];
7432 layout.verify(&c, &root).unwrap();
7433 }
7434
7435 #[test]
7436 fn aplicacao_self_membership_fires_after_view_validate() {
7437 // Diagnostic-precedence pin: a self-referential membro alongside
7438 // a duplicate-:caixa shape surfaces the more-fundamental
7439 // `MembroDuplicate` (from `view.validate()`) first; only when the
7440 // per-membros shape diagnostics pass does the cross-slot
7441 // self-membership gate fire. Mirrors the ordering pin
7442 // `supervisor_self_referential_child_is_violation` carries on
7443 // the peer supervision-tree axis (`view.validate()` runs first,
7444 // then the cross-slot gate). Without this ordering a future
7445 // refactor that swaps the two calls would silently mask the
7446 // narrower per-membro defect.
7447 use crate::{Membro, Placement, PlacementStrategy};
7448 let root = PathBuf::from("/tmp/x");
7449 let manifest = root.join("caixa.lisp");
7450 let manifest_clone = manifest.clone();
7451 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7452 let mut c = caixa(CaixaKind::Aplicacao);
7453 c.placement = Some(Placement {
7454 estrategia: PlacementStrategy::Replicated,
7455 clusters: vec!["rio".into()],
7456 affinity: None,
7457 shard_key: None,
7458 });
7459 c.membros = vec![
7460 Membro {
7461 caixa: "service-a".into(),
7462 versao: "^0.1".into(),
7463 },
7464 Membro {
7465 caixa: "service-a".into(),
7466 versao: "^0.2".into(),
7467 },
7468 Membro {
7469 caixa: "demo".into(),
7470 versao: "^0.1".into(),
7471 },
7472 ];
7473 let err = layout.verify(&c, &root).unwrap_err();
7474 let LayoutError::AplicacaoViolation { issue, .. } = err else {
7475 panic!("expected AplicacaoViolation, got {err:?}");
7476 };
7477 // The per-membros duplicate diagnostic (from view.validate())
7478 // surfaces ahead of the cross-slot self-membership gate, so the
7479 // `service-a` duplicate is named — not the `demo` self-reference.
7480 assert!(
7481 issue.contains("service-a") && issue.contains("more than once"),
7482 "duplicate-:caixa diagnostic must surface before self-membership gate, \
7483 got {issue:?}"
7484 );
7485 }
7486
7487 #[test]
7488 fn mesh_slots_on_servico_rejected() {
7489 // The canonical real-world footgun: an author adds :entrada to a
7490 // :kind Servico expecting it to expose ingress. aplicacao_view
7491 // returns None for Servico, so the slot is the manifest's
7492 // "ignored otherwise" — never validated, never rendered. The
7493 // kind-coherence gate rejects it at build time (before the
7494 // :servicos existence loop), naming the offending slot + kind.
7495 use crate::Entrada;
7496 let root = PathBuf::from("/tmp/x");
7497 let manifest = root.join("caixa.lisp");
7498 let manifest_clone = manifest.clone();
7499 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7500 let mut c = caixa(CaixaKind::Servico);
7501 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7502 c.entrada = Some(Entrada {
7503 host: "demo.example.com".into(),
7504 para: "demo".into(),
7505 paths: vec![],
7506 port: 8080,
7507 });
7508 let err = layout.verify(&c, &root).unwrap_err();
7509 match err {
7510 LayoutError::MeshSlotsOnNonAplicacao { caixa, kind, slots } => {
7511 assert_eq!(caixa, "demo");
7512 assert_eq!(kind, CaixaKind::Servico);
7513 assert_eq!(slots, crate::render::M3_AUTHOR_KEY_ENTRADA);
7514 }
7515 other => panic!("expected MeshSlotsOnNonAplicacao, got {other:?}"),
7516 }
7517 }
7518
7519 #[test]
7520 fn mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order() {
7521 // All five mesh slots declared on a Biblioteca → the diagnostic
7522 // enumerates them in canonical declaration order, deterministic
7523 // across runs. The gate fires on declared-ness only (the values
7524 // need not be a *valid* AplicacaoSpec — aplicacao_view is never
7525 // called for a non-Aplicacao kind).
7526 use crate::{Entrada, Membro, MeshPolicy, Placement, PlacementStrategy, WitContract};
7527 let root = PathBuf::from("/tmp/x");
7528 let manifest = root.join("caixa.lisp");
7529 let manifest_clone = manifest.clone();
7530 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7531 let mut c = caixa(CaixaKind::Biblioteca);
7532 c.membros = vec![Membro {
7533 caixa: "a".into(),
7534 versao: "^0.1".into(),
7535 }];
7536 c.contratos = vec![WitContract {
7537 de: "a".into(),
7538 para: "a".into(),
7539 wit: "wasi:http/proxy".into(),
7540 endpoint: Some("/x".into()),
7541 subject: None,
7542 slot: None,
7543 }];
7544 c.politicas = Some(MeshPolicy::default());
7545 c.placement = Some(Placement {
7546 estrategia: PlacementStrategy::Replicated,
7547 clusters: vec!["rio".into()],
7548 affinity: None,
7549 shard_key: None,
7550 });
7551 c.entrada = Some(Entrada {
7552 host: "x.example.com".into(),
7553 para: "a".into(),
7554 paths: vec![],
7555 port: 8080,
7556 });
7557 let err = layout.verify(&c, &root).unwrap_err();
7558 match err {
7559 LayoutError::MeshSlotsOnNonAplicacao { slots, .. } => {
7560 assert_eq!(
7561 slots,
7562 format!(
7563 "{} {} {} {} {}",
7564 crate::render::M3_AUTHOR_KEY_MEMBROS,
7565 crate::render::M3_AUTHOR_KEY_CONTRATOS,
7566 crate::render::M3_AUTHOR_KEY_POLITICAS,
7567 crate::render::M3_AUTHOR_KEY_PLACEMENT,
7568 crate::render::M3_AUTHOR_KEY_ENTRADA,
7569 )
7570 );
7571 }
7572 other => panic!("expected MeshSlotsOnNonAplicacao, got {other:?}"),
7573 }
7574 }
7575
7576 #[test]
7577 fn servico_without_mesh_slots_still_verifies() {
7578 // Pass-after control: a well-formed Servico carrying no mesh
7579 // slots must remain accepted — the gate keys off declared-ness,
7580 // so it must not over-fire on the common case.
7581 let root = PathBuf::from("/tmp/x");
7582 let servico = root.join("servicos/demo.computeunit.yaml");
7583 let manifest = root.join("caixa.lisp");
7584 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == servico);
7585 let mut c = caixa(CaixaKind::Servico);
7586 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7587 layout.verify(&c, &root).unwrap();
7588 }
7589
7590 #[test]
7591 fn supervisor_slots_on_servico_rejected() {
7592 // Mirror of `mesh_slots_on_servico_rejected` on the
7593 // supervisor-tree slot set: an author adds `:children` to a
7594 // `:kind Servico` expecting it to spawn workers. supervisor_view
7595 // returns None for Servico, so the slot is the manifest's
7596 // "ignored otherwise" — never validated, never reconciled. The
7597 // kind-coherence gate rejects it at build time (before the
7598 // :servicos existence loop), naming the offending slot + kind.
7599 use crate::{ChildSpec, RestartPolicy};
7600 let root = PathBuf::from("/tmp/x");
7601 let manifest = root.join("caixa.lisp");
7602 let manifest_clone = manifest.clone();
7603 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7604 let mut c = caixa(CaixaKind::Servico);
7605 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7606 c.children = vec![ChildSpec {
7607 caixa: "worker".into(),
7608 versao: "^0.1".into(),
7609 restart: RestartPolicy::Permanent,
7610 }];
7611 let err = layout.verify(&c, &root).unwrap_err();
7612 match err {
7613 LayoutError::SupervisorSlotsOnNonSupervisor { caixa, kind, slots } => {
7614 assert_eq!(caixa, "demo");
7615 assert_eq!(kind, CaixaKind::Servico);
7616 assert_eq!(slots, crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN);
7617 }
7618 other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
7619 }
7620 }
7621
7622 #[test]
7623 fn supervisor_slots_on_non_supervisor_lists_slots_in_canonical_order() {
7624 // All four supervisor slots declared on a Biblioteca → the
7625 // diagnostic enumerates them in canonical declaration order
7626 // (`:estrategia` → `:max-restarts` → `:restart-window` →
7627 // `:children`), deterministic across runs. The gate fires on
7628 // declared-ness only (the values need not be a *valid*
7629 // SupervisorSpec — supervisor_view is never called for a
7630 // non-Supervisor kind). Mirror of
7631 // `mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order`.
7632 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
7633 let root = PathBuf::from("/tmp/x");
7634 let manifest = root.join("caixa.lisp");
7635 let manifest_clone = manifest.clone();
7636 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7637 let mut c = caixa(CaixaKind::Biblioteca);
7638 c.estrategia = Some(RestartStrategy::OneForOne);
7639 c.max_restarts = Some(5);
7640 c.restart_window = Some("60s".into());
7641 c.children = vec![ChildSpec {
7642 caixa: "worker".into(),
7643 versao: "^0.1".into(),
7644 restart: RestartPolicy::Permanent,
7645 }];
7646 let err = layout.verify(&c, &root).unwrap_err();
7647 match err {
7648 LayoutError::SupervisorSlotsOnNonSupervisor { slots, .. } => {
7649 assert_eq!(slots, ":estrategia :max-restarts :restart-window :children");
7650 }
7651 other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
7652 }
7653 }
7654
7655 #[test]
7656 fn aplicacao_with_supervisor_slots_rejected() {
7657 // Cross-kind pin: an Aplicacao (the other no-code orchestrator
7658 // kind) that declares a supervisor slot is rejected by the
7659 // supervisor-slot gate, just as a Supervisor declaring a mesh
7660 // slot is rejected by the mesh-slot gate — the two kind ↔ slot
7661 // coherence gates are symmetric and mutually exclusive. The
7662 // gate fires before the Aplicacao typed-graph validation, so
7663 // the diagnostic names the foreign supervisor slot rather than
7664 // a downstream AplicacaoViolation.
7665 use crate::{Membro, Placement, PlacementStrategy, RestartStrategy};
7666 let root = PathBuf::from("/tmp/x");
7667 let manifest = root.join("caixa.lisp");
7668 let manifest_clone = manifest.clone();
7669 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7670 let mut c = caixa(CaixaKind::Aplicacao);
7671 c.membros = vec![Membro {
7672 caixa: "service-a".into(),
7673 versao: "^0.1".into(),
7674 }];
7675 c.placement = Some(Placement {
7676 estrategia: PlacementStrategy::Replicated,
7677 clusters: vec!["rio".into()],
7678 affinity: None,
7679 shard_key: None,
7680 });
7681 c.estrategia = Some(RestartStrategy::OneForAll);
7682 let err = layout.verify(&c, &root).unwrap_err();
7683 match err {
7684 LayoutError::SupervisorSlotsOnNonSupervisor { caixa, kind, slots } => {
7685 assert_eq!(caixa, "demo");
7686 assert_eq!(kind, CaixaKind::Aplicacao);
7687 assert_eq!(slots, crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA);
7688 }
7689 other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
7690 }
7691 }
7692
7693 #[test]
7694 fn servico_without_supervisor_slots_still_verifies() {
7695 // Pass-after control: a well-formed Servico carrying no
7696 // supervisor slots must remain accepted — the gate keys off
7697 // declared-ness, so it must not over-fire on the common case.
7698 let root = PathBuf::from("/tmp/x");
7699 let servico = root.join("servicos/demo.computeunit.yaml");
7700 let manifest = root.join("caixa.lisp");
7701 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == servico);
7702 let mut c = caixa(CaixaKind::Servico);
7703 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7704 layout.verify(&c, &root).unwrap();
7705 }
7706
7707 #[test]
7708 fn servico_slots_on_biblioteca_rejected() {
7709 // Mirror of `mesh_slots_on_servico_rejected` /
7710 // `supervisor_slots_on_servico_rejected` on the M2
7711 // Servico-runtime slot set: an author adds `:limits` to a
7712 // `:kind Biblioteca` expecting per-process sandboxing. The
7713 // caixa-helm / caixa-flux renderers gate on `require_kind(_,
7714 // Servico)`, so the slot is the manifest's "ignored otherwise" —
7715 // never rendered into any artifact. The kind-coherence gate
7716 // rejects it at build time (before the M2 validate blocks),
7717 // naming the offending slot + kind.
7718 use crate::LimitsSpec;
7719 let root = PathBuf::from("/tmp/x");
7720 let manifest = root.join("caixa.lisp");
7721 let lib = root.join("lib").join("demo.lisp");
7722 let manifest_clone = manifest.clone();
7723 let layout =
7724 StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == lib);
7725 let mut c = caixa(CaixaKind::Biblioteca);
7726 c.limits = Some(LimitsSpec {
7727 fuel: Some(1_000_000),
7728 ..Default::default()
7729 });
7730 let err = layout.verify(&c, &root).unwrap_err();
7731 match err {
7732 LayoutError::ServicoSlotsOnNonServico { caixa, kind, slots } => {
7733 assert_eq!(caixa, "demo");
7734 assert_eq!(kind, CaixaKind::Biblioteca);
7735 assert_eq!(slots, crate::render::M2_AUTHOR_KEY_LIMITS);
7736 }
7737 other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
7738 }
7739 }
7740
7741 #[test]
7742 fn servico_slots_on_non_servico_lists_slots_in_canonical_order() {
7743 // All three M2 slots declared on a Biblioteca → the diagnostic
7744 // enumerates them in canonical declaration order (`:limits` →
7745 // `:behavior` → `:upgrade-from`), deterministic across runs. The
7746 // gate fires on declared-ness only (the values need not pass the
7747 // M2 validate blocks — those run only after the kind-coherence
7748 // gate, and never for a non-Servico declared-slot caixa). Mirror
7749 // of the mesh/supervisor `*_lists_slots_in_canonical_order` pins.
7750 use crate::{BehaviorSpec, LimitsSpec, UpgradeFromEntry, UpgradeInstruction};
7751 let root = PathBuf::from("/tmp/x");
7752 let manifest = root.join("caixa.lisp");
7753 let manifest_clone = manifest.clone();
7754 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7755 let mut c = caixa(CaixaKind::Biblioteca);
7756 c.limits = Some(LimitsSpec {
7757 fuel: Some(1_000_000),
7758 ..Default::default()
7759 });
7760 c.behavior = Some(BehaviorSpec {
7761 on_init: Some(PathBuf::from("lib/init.lisp")),
7762 ..Default::default()
7763 });
7764 c.upgrade_from = vec![UpgradeFromEntry {
7765 from: "0.1.0".into(),
7766 instructions: vec![UpgradeInstruction::Restart],
7767 }];
7768 let err = layout.verify(&c, &root).unwrap_err();
7769 match err {
7770 LayoutError::ServicoSlotsOnNonServico { slots, .. } => {
7771 assert_eq!(
7772 slots,
7773 format!(
7774 "{} {} {}",
7775 crate::render::M2_AUTHOR_KEY_LIMITS,
7776 crate::render::M2_AUTHOR_KEY_BEHAVIOR,
7777 crate::render::M2_AUTHOR_KEY_UPGRADE_FROM,
7778 )
7779 );
7780 }
7781 other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
7782 }
7783 }
7784
7785 #[test]
7786 fn aplicacao_with_servico_slots_rejected() {
7787 // Cross-kind pin (mirror of `aplicacao_with_supervisor_slots_rejected`):
7788 // an Aplicacao that declares an M2 Servico-runtime slot is
7789 // rejected by the Servico-slot gate, just as a Supervisor
7790 // declaring a mesh slot is rejected by the mesh-slot gate — the
7791 // three kind ↔ slot coherence gates are symmetric and mutually
7792 // exclusive. The gate fires before the Aplicacao typed-graph
7793 // validation, so the diagnostic names the foreign M2 slot rather
7794 // than a downstream AplicacaoViolation about missing :membros.
7795 use crate::{Membro, Placement, PlacementStrategy, UpgradeFromEntry, UpgradeInstruction};
7796 let root = PathBuf::from("/tmp/x");
7797 let manifest = root.join("caixa.lisp");
7798 let manifest_clone = manifest.clone();
7799 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7800 let mut c = caixa(CaixaKind::Aplicacao);
7801 c.membros = vec![Membro {
7802 caixa: "service-a".into(),
7803 versao: "^0.1".into(),
7804 }];
7805 c.placement = Some(Placement {
7806 estrategia: PlacementStrategy::Replicated,
7807 clusters: vec!["rio".into()],
7808 affinity: None,
7809 shard_key: None,
7810 });
7811 c.upgrade_from = vec![UpgradeFromEntry {
7812 from: "0.1.0".into(),
7813 instructions: vec![UpgradeInstruction::Restart],
7814 }];
7815 let err = layout.verify(&c, &root).unwrap_err();
7816 match err {
7817 LayoutError::ServicoSlotsOnNonServico { caixa, kind, slots } => {
7818 assert_eq!(caixa, "demo");
7819 assert_eq!(kind, CaixaKind::Aplicacao);
7820 assert_eq!(slots, crate::render::M2_AUTHOR_KEY_UPGRADE_FROM);
7821 }
7822 other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
7823 }
7824 }
7825
7826 #[test]
7827 fn servico_with_servico_slots_still_verifies() {
7828 // Pass-after control: a well-formed Servico carrying all three M2
7829 // slots must remain accepted — the gate is guarded by `kind !=
7830 // Servico`, so it must not over-fire on the kind these slots
7831 // exist for. Mirror of `servico_without_{mesh,supervisor}_slots_
7832 // still_verifies` on the legitimate-declaration axis.
7833 use crate::{BehaviorSpec, LimitsSpec, UpgradeFromEntry, UpgradeInstruction};
7834 let root = PathBuf::from("/tmp/x");
7835 let manifest = root.join("caixa.lisp");
7836 let svc = root.join("servicos/demo.computeunit.yaml");
7837 let init = root.join("lib/init.lisp");
7838 let layout =
7839 StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc || p == init);
7840 let mut c = caixa(CaixaKind::Servico);
7841 c.versao = "0.2.0".into();
7842 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7843 c.limits = Some(LimitsSpec {
7844 fuel: Some(1_000_000),
7845 ..Default::default()
7846 });
7847 c.behavior = Some(BehaviorSpec {
7848 on_init: Some(PathBuf::from("lib/init.lisp")),
7849 ..Default::default()
7850 });
7851 c.upgrade_from = vec![UpgradeFromEntry {
7852 from: "0.1.0".into(),
7853 instructions: vec![UpgradeInstruction::Restart],
7854 }];
7855 layout.verify(&c, &root).unwrap();
7856 }
7857
7858 #[test]
7859 fn aplicacao_must_not_have_bibliotecas() {
7860 use crate::{Membro, Placement, PlacementStrategy};
7861 let root = PathBuf::from("/tmp/x");
7862 let manifest = root.join("caixa.lisp");
7863 let manifest_clone = manifest.clone();
7864 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7865 let mut c = caixa(CaixaKind::Aplicacao);
7866 c.bibliotecas = vec!["lib/code.lisp".into()];
7867 c.membros = vec![Membro {
7868 caixa: "x".into(),
7869 versao: "^0.1".into(),
7870 }];
7871 c.placement = Some(Placement {
7872 estrategia: PlacementStrategy::Replicated,
7873 clusters: vec!["rio".into()],
7874 affinity: None,
7875 shard_key: None,
7876 });
7877 let err = layout.verify(&c, &root).unwrap_err();
7878 assert!(matches!(err, LayoutError::AplicacaoOwnsCode(_)));
7879 }
7880
7881 #[test]
7882 fn acao_must_not_have_bibliotecas() {
7883 // Mirror of `supervisor_must_not_have_bibliotecas` /
7884 // `aplicacao_must_not_have_bibliotecas` on the third no-code
7885 // kind. `has_code` fires before the `:ci`-presence gates below
7886 // it, so this must surface `AcaoOwnsCode` even though the
7887 // caixa also lacks a `:ci` slot (which would otherwise surface
7888 // as `MissingCi`) — the more-fundamental "this kind runs no
7889 // code at all" diagnostic wins.
7890 let root = PathBuf::from("/tmp/x");
7891 let manifest = root.join("caixa.lisp");
7892 let manifest_clone = manifest.clone();
7893 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7894 let mut c = caixa(CaixaKind::Acao);
7895 c.bibliotecas = vec!["lib/code.lisp".into()];
7896 let err = layout.verify(&c, &root).unwrap_err();
7897 assert!(matches!(err, LayoutError::AcaoOwnsCode(_)));
7898 }
7899
7900 #[test]
7901 fn acao_without_ci_errors() {
7902 // Mirror of `binario_without_exe_errors` on the fifth required-
7903 // slot axis.
7904 let root = PathBuf::from("/tmp/x");
7905 let manifest = root.join("caixa.lisp");
7906 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
7907 let err = layout.verify(&caixa(CaixaKind::Acao), &root).unwrap_err();
7908 assert!(matches!(err, LayoutError::MissingCi(_)));
7909 }
7910
7911 #[test]
7912 fn acao_with_ci_passes() {
7913 let root = PathBuf::from("/tmp/x");
7914 let manifest = root.join("caixa.lisp");
7915 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
7916 let mut c = caixa(CaixaKind::Acao);
7917 c.ci = Some(canteiro_types::CiRun {
7918 workspace: "pleme-io".into(),
7919 repo: "caixa".into(),
7920 nodes: vec![],
7921 });
7922 layout
7923 .verify(&c, &root)
7924 .expect("an Acao caixa with a declared :ci slot passes layout verify");
7925 }
7926
7927 #[test]
7928 fn acao_with_cyclic_ci_rejected_at_layout() {
7929 // Layout-side wire-up pin on the compound
7930 // [`crate::Caixa::validate_acao_shape`] gate: a `:kind Acao`
7931 // caixa declaring a structurally illegal `:ci` (here — a
7932 // minimal two-node cycle `a → b → a`, one of the three
7933 // `canteiro_types::DecomposeError` arms
7934 // [`crate::decompose_ci`] refuses) surfaces
7935 // [`LayoutError::AcaoViolation`] at `feira build` time rather
7936 // than passing the layout gate silently and deferring the
7937 // diagnostic to [`caixa_actions::validate`] at renderer time.
7938 //
7939 // Pre-lift the layout pipeline only checked `:ci` *presence*
7940 // via [`LayoutError::MissingCi`]; the decompose gate lived
7941 // only wired open-coded at
7942 // [`caixa_actions::validate`] via the substrate-canonical
7943 // [`crate::require_acao_view`] compound helper. This wire-up
7944 // pin locks the new layout-side compound-shape gate in place
7945 // — a future regression that dropped the `if
7946 // caixa.kind().is_acao() { validate_acao_shape() }` block or
7947 // relaxed the diagnostic surface trips here at caixa-core
7948 // build time. Sibling in shape to the peer
7949 // [`aplicacao_must_not_have_bibliotecas`] /
7950 // [`supervisor_must_not_have_bibliotecas`] /
7951 // [`acao_must_not_have_bibliotecas`] layout wire-up pins on
7952 // the sibling per-kind shape gates.
7953 let root = PathBuf::from("/tmp/x");
7954 let manifest = root.join("caixa.lisp");
7955 let manifest_clone = manifest.clone();
7956 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7957 let mut c = caixa(CaixaKind::Acao);
7958 c.ci = Some(canteiro_types::CiRun {
7959 workspace: "pleme-io".into(),
7960 repo: "caixa".into(),
7961 nodes: vec![
7962 canteiro_types::CiNode::new(
7963 "a",
7964 canteiro_types::EnvClass::None,
7965 canteiro_types::ActionRef {
7966 name: "a".into(),
7967 command: "true".into(),
7968 args: vec![],
7969 },
7970 vec!["b".into()],
7971 ),
7972 canteiro_types::CiNode::new(
7973 "b",
7974 canteiro_types::EnvClass::None,
7975 canteiro_types::ActionRef {
7976 name: "b".into(),
7977 command: "true".into(),
7978 args: vec![],
7979 },
7980 vec!["a".into()],
7981 ),
7982 ],
7983 });
7984 let err = layout.verify(&c, &root).unwrap_err();
7985 match err {
7986 LayoutError::AcaoViolation { caixa, issue } => {
7987 assert_eq!(caixa, "demo");
7988 assert!(
7989 issue.contains("decompose"),
7990 "AcaoViolation issue must name the decompose axis (got: {issue:?})",
7991 );
7992 assert!(
7993 issue.contains("demo"),
7994 "AcaoViolation issue must name the offending caixa nome via the folded \
7995 CiDecomposeFailure Display (got: {issue:?})",
7996 );
7997 }
7998 other => panic!("expected AcaoViolation on a cyclic :ci, got {other:?}"),
7999 }
8000 }
8001
8002 #[test]
8003 fn ci_on_non_acao_errors() {
8004 // Mirror of `mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order`
8005 // on the Acao-only `:ci` axis — declaring `:ci` on any other
8006 // kind is the same "silently ignored" footgun the sibling
8007 // mesh-/supervisor-/servico-slot gates already close.
8008 let root = PathBuf::from("/tmp/x");
8009 let manifest = root.join("caixa.lisp");
8010 let manifest_clone = manifest.clone();
8011 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
8012 let mut c = caixa(CaixaKind::Biblioteca);
8013 c.ci = Some(canteiro_types::CiRun {
8014 workspace: "pleme-io".into(),
8015 repo: "caixa".into(),
8016 nodes: vec![],
8017 });
8018 let err = layout.verify(&c, &root).unwrap_err();
8019 match err {
8020 LayoutError::CiOnNonAcao { caixa, kind } => {
8021 assert_eq!(caixa, "demo");
8022 assert_eq!(kind, CaixaKind::Biblioteca);
8023 }
8024 other => panic!("expected CiOnNonAcao, got {other:?}"),
8025 }
8026 }
8027
8028 // ── ForeignCodeSlot — kind ↔ code-surface coherence ────────────────
8029
8030 #[test]
8031 fn biblioteca_with_exe_rejected() {
8032 // Fail-before-pass-after pin: a `:kind Biblioteca` declaring
8033 // `:exe` is the "I added a CLI to my library" footgun — the nix
8034 // flake renderer for Binario gates on `require_kind(_, Binario)`,
8035 // so on a Biblioteca the `:exe` path is silently dropped past
8036 // the layout's path-existence check (no executable target is
8037 // ever generated). The diagnostic names the offending kind +
8038 // slot verbatim so the author can grep their caixa.lisp for
8039 // `:exe` and fix in one edit (drop the slot or change
8040 // `:kind Biblioteca` → `:kind Binario`).
8041 let root = PathBuf::from("/tmp/x");
8042 let manifest = root.join("caixa.lisp");
8043 let lib = root.join("lib").join("demo.lisp");
8044 let exe_path = root.join("exe").join("tool");
8045 let layout = StandardLayout::new()
8046 .with_path_exists(move |p| p == manifest || p == lib || p == exe_path);
8047 let mut c = caixa(CaixaKind::Biblioteca);
8048 c.exe = vec!["exe/tool".into()];
8049 let err = layout.verify(&c, &root).unwrap_err();
8050 match err {
8051 LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
8052 assert_eq!(caixa, "demo");
8053 assert_eq!(kind, CaixaKind::Biblioteca);
8054 assert_eq!(slots, ":exe");
8055 }
8056 other => panic!("expected ForeignCodeSlot, got {other:?}"),
8057 }
8058 }
8059
8060 #[test]
8061 fn biblioteca_with_servicos_rejected() {
8062 // Symmetric to `biblioteca_with_exe_rejected` on the
8063 // `:servicos` axis: a `:kind Biblioteca` declaring a Servico
8064 // computeunit silently passed validate and the daemon's
8065 // ComputeUnit / lareira chart never materialized (caixa-helm /
8066 // caixa-flux gate emission on `require_kind(_, Servico)`).
8067 let root = PathBuf::from("/tmp/x");
8068 let manifest = root.join("caixa.lisp");
8069 let lib = root.join("lib").join("demo.lisp");
8070 let svc = root.join("servicos").join("demo.computeunit.yaml");
8071 let layout =
8072 StandardLayout::new().with_path_exists(move |p| p == manifest || p == lib || p == svc);
8073 let mut c = caixa(CaixaKind::Biblioteca);
8074 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8075 let err = layout.verify(&c, &root).unwrap_err();
8076 match err {
8077 LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
8078 assert_eq!(caixa, "demo");
8079 assert_eq!(kind, CaixaKind::Biblioteca);
8080 assert_eq!(slots, ":servicos");
8081 }
8082 other => panic!("expected ForeignCodeSlot, got {other:?}"),
8083 }
8084 }
8085
8086 #[test]
8087 fn biblioteca_with_exe_and_servicos_lists_slots_in_canonical_order() {
8088 // Both foreign code slots declared on a Biblioteca → the
8089 // diagnostic enumerates them in canonical declaration order
8090 // (`:exe` → `:servicos`), deterministic across runs. Mirrors the
8091 // mesh/supervisor/servico-slot `*_lists_slots_in_canonical_order`
8092 // pins on the peer kind ↔ slot algebra axes; drift in the
8093 // [`Caixa::declared_foreign_code_slots`] iteration order surfaces
8094 // here.
8095 let root = PathBuf::from("/tmp/x");
8096 let manifest = root.join("caixa.lisp");
8097 let manifest_clone = manifest.clone();
8098 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
8099 let mut c = caixa(CaixaKind::Biblioteca);
8100 c.exe = vec!["exe/tool".into()];
8101 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8102 let err = layout.verify(&c, &root).unwrap_err();
8103 match err {
8104 LayoutError::ForeignCodeSlot { slots, .. } => {
8105 assert_eq!(slots, ":exe :servicos");
8106 }
8107 other => panic!("expected ForeignCodeSlot, got {other:?}"),
8108 }
8109 }
8110
8111 #[test]
8112 fn binario_with_servicos_rejected() {
8113 // The peer footgun on the Binario kind: declaring a Servico
8114 // computeunit on a `:kind Binario` caixa. The caixa-helm /
8115 // caixa-flux renderers gate on `require_kind(_, Servico)`, so
8116 // the `:servicos` slot vanishes past the layout's path-
8117 // existence check — no ComputeUnit, no Helm chart. `:exe` stays
8118 // valid (Binario's native code surface), so the kind-coherence
8119 // diagnostic targets only `:servicos`.
8120 let root = PathBuf::from("/tmp/x");
8121 let manifest = root.join("caixa.lisp");
8122 let exe_path = root.join("exe").join("tool");
8123 let svc = root.join("servicos").join("demo.computeunit.yaml");
8124 let layout = StandardLayout::new()
8125 .with_path_exists(move |p| p == manifest || p == exe_path || p == svc);
8126 let mut c = caixa(CaixaKind::Binario);
8127 c.exe = vec!["exe/tool".into()];
8128 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8129 let err = layout.verify(&c, &root).unwrap_err();
8130 match err {
8131 LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
8132 assert_eq!(caixa, "demo");
8133 assert_eq!(kind, CaixaKind::Binario);
8134 assert_eq!(slots, ":servicos");
8135 }
8136 other => panic!("expected ForeignCodeSlot, got {other:?}"),
8137 }
8138 }
8139
8140 #[test]
8141 fn servico_with_exe_rejected() {
8142 // Symmetric to `binario_with_servicos_rejected` on the other
8143 // code-running peer: a `:kind Servico` declaring an `:exe` is
8144 // the "I added a host-side CLI to my wasm component" footgun —
8145 // the nix flake's Binario target gates on `require_kind(_,
8146 // Binario)`, so the `:exe` path vanishes past the layout's
8147 // path-existence check.
8148 let root = PathBuf::from("/tmp/x");
8149 let manifest = root.join("caixa.lisp");
8150 let svc = root.join("servicos").join("demo.computeunit.yaml");
8151 let exe_path = root.join("exe").join("tool");
8152 let layout = StandardLayout::new()
8153 .with_path_exists(move |p| p == manifest || p == svc || p == exe_path);
8154 let mut c = caixa(CaixaKind::Servico);
8155 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8156 c.exe = vec!["exe/tool".into()];
8157 let err = layout.verify(&c, &root).unwrap_err();
8158 match err {
8159 LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
8160 assert_eq!(caixa, "demo");
8161 assert_eq!(kind, CaixaKind::Servico);
8162 assert_eq!(slots, ":exe");
8163 }
8164 other => panic!("expected ForeignCodeSlot, got {other:?}"),
8165 }
8166 }
8167
8168 #[test]
8169 fn binario_without_servicos_still_verifies() {
8170 // Pass-after control: a well-formed Binario carrying only its
8171 // native `:exe` surface must remain accepted — the gate keys off
8172 // declared-ness of the *foreign* slots, so it must not over-fire
8173 // on the legitimate same-kind case. Mirror of
8174 // `servico_with_servico_slots_still_verifies` on the peer axis.
8175 let root = PathBuf::from("/tmp/x");
8176 let manifest = root.join("caixa.lisp");
8177 let exe_path = root.join("exe").join("tool");
8178 let layout =
8179 StandardLayout::new().with_path_exists(move |p| p == manifest || p == exe_path);
8180 let mut c = caixa(CaixaKind::Binario);
8181 c.exe = vec!["exe/tool".into()];
8182 layout.verify(&c, &root).unwrap();
8183 }
8184
8185 #[test]
8186 fn biblioteca_with_only_bibliotecas_still_verifies() {
8187 // Pass-after control: a well-formed Biblioteca carrying only
8188 // its native `:bibliotecas` surface (or the default
8189 // `lib/<nome>.lisp`) must remain accepted. The gate keys off
8190 // declared-ness of `:exe` + `:servicos` only — `:bibliotecas`
8191 // is deliberately excluded from the foreign-set on every
8192 // code-running kind (`declared_foreign_code_slots` doc), so a
8193 // Biblioteca with the canonical lib surface alone passes.
8194 let root = PathBuf::from("/tmp/x");
8195 let manifest = root.join("caixa.lisp");
8196 let lib = root.join("lib").join("demo.lisp");
8197 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == lib);
8198 layout
8199 .verify(&caixa(CaixaKind::Biblioteca), &root)
8200 .expect("Biblioteca with default lib must verify");
8201 }
8202
8203 #[test]
8204 fn binario_with_bibliotecas_helper_still_verifies() {
8205 // Pass-after control on the deliberate `:bibliotecas`-as-helper
8206 // shape: a `:kind Binario` may legitimately bundle a `lib/`
8207 // helper its nix flake build consumes (the same shape a
8208 // `:kind Servico` may bundle for its wasm-component source).
8209 // The foreign-code-slot gate must NOT fire on `:bibliotecas` for
8210 // either code-running kind; pinned here so a future tightening
8211 // that adds `:bibliotecas` to the foreign set on Binario /
8212 // Servico surfaces as a test failure rather than as a silent
8213 // over-reach.
8214 let root = PathBuf::from("/tmp/x");
8215 let manifest = root.join("caixa.lisp");
8216 let exe_path = root.join("exe").join("tool");
8217 let lib = root.join("lib").join("helper.lisp");
8218 let layout = StandardLayout::new()
8219 .with_path_exists(move |p| p == manifest || p == exe_path || p == lib);
8220 let mut c = caixa(CaixaKind::Binario);
8221 c.exe = vec!["exe/tool".into()];
8222 c.bibliotecas = vec!["lib/helper.lisp".into()];
8223 layout.verify(&c, &root).unwrap();
8224 }
8225
8226 #[test]
8227 fn supervisor_with_exe_still_surfaces_owns_code() {
8228 // Diagnostic-precedence pin: a `:kind Supervisor` declaring
8229 // `:exe` is *both* "Supervisor with code" and "foreign code
8230 // slot". The more-fundamental `SupervisorOwnsCode` must win
8231 // (Supervisor doesn't run code at all — the foreign-slot
8232 // diagnostic would mislead the author toward changing `:kind`
8233 // when the underlying defect is that supervisors orchestrate
8234 // children, not code). Guards the call order in `verify`
8235 // against silent reordering.
8236 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
8237 let root = PathBuf::from("/tmp/x");
8238 let manifest = root.join("caixa.lisp");
8239 let manifest_clone = manifest.clone();
8240 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
8241 let mut c = caixa(CaixaKind::Supervisor);
8242 c.estrategia = Some(RestartStrategy::OneForOne);
8243 c.max_restarts = Some(5);
8244 c.exe = vec!["exe/tool".into()];
8245 c.children = vec![ChildSpec {
8246 caixa: "worker".into(),
8247 versao: "^0.1".into(),
8248 restart: RestartPolicy::Permanent,
8249 }];
8250 let err = layout.verify(&c, &root).unwrap_err();
8251 assert!(
8252 matches!(err, LayoutError::SupervisorOwnsCode(_)),
8253 "Supervisor-with-:exe must surface as SupervisorOwnsCode (the more-fundamental \
8254 no-code-at-all diagnostic), got {err:?}"
8255 );
8256 }
8257
8258 #[test]
8259 fn declared_foreign_code_slots_returns_canonical_order() {
8260 // Unit-level pin for the lifted method: the canonical iteration
8261 // order is `:exe` → `:servicos`, independent of which subset is
8262 // populated. Empty input + each single-slot subset + the full
8263 // pair are all checked so a future axis added to the method
8264 // (a hypothetical fifth code-surface slot) is one extension
8265 // point + one assertion update here, not a coordinated rewrite
8266 // across the layout-test sites that reach for the canonical
8267 // order.
8268 let mut c = caixa(CaixaKind::Biblioteca);
8269 assert!(c.declared_foreign_code_slots().is_empty());
8270 c.exe = vec!["exe/tool".into()];
8271 assert_eq!(c.declared_foreign_code_slots(), vec![":exe"]);
8272 c.exe.clear();
8273 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8274 assert_eq!(c.declared_foreign_code_slots(), vec![":servicos"]);
8275 c.exe = vec!["exe/tool".into()];
8276 assert_eq!(c.declared_foreign_code_slots(), vec![":exe", ":servicos"]);
8277 }
8278
8279 #[test]
8280 fn aplicacao_with_unknown_contrato_member_fails() {
8281 use crate::{Membro, Placement, PlacementStrategy, WitContract};
8282 let root = PathBuf::from("/tmp/x");
8283 let manifest = root.join("caixa.lisp");
8284 let manifest_clone = manifest.clone();
8285 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
8286 let mut c = caixa(CaixaKind::Aplicacao);
8287 c.membros = vec![Membro {
8288 caixa: "service-a".into(),
8289 versao: "^0.1".into(),
8290 }];
8291 c.contratos = vec![WitContract {
8292 de: "service-a".into(),
8293 para: "phantom".into(),
8294 wit: "wasi:http/proxy".into(),
8295 endpoint: Some("/x".into()),
8296 subject: None,
8297 slot: None,
8298 }];
8299 c.placement = Some(Placement {
8300 estrategia: PlacementStrategy::Replicated,
8301 clusters: vec!["rio".into()],
8302 affinity: None,
8303 shard_key: None,
8304 });
8305 let err = layout.verify(&c, &root).unwrap_err();
8306 assert!(matches!(err, LayoutError::AplicacaoViolation { .. }));
8307 }
8308
8309 #[test]
8310 fn limits_zero_axis_surfaces_as_layout_violation() {
8311 use crate::LimitsSpec;
8312 let root = PathBuf::from("/tmp/x");
8313 let manifest = root.join("caixa.lisp");
8314 let svc = root.join("servicos/demo.computeunit.yaml");
8315 let mut c = caixa(CaixaKind::Servico);
8316 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8317 c.limits = Some(LimitsSpec {
8318 fuel: Some(0),
8319 ..Default::default()
8320 });
8321 let manifest_clone = manifest.clone();
8322 let svc_clone = svc.clone();
8323 let layout =
8324 StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8325 let err = layout.verify(&c, &root).unwrap_err();
8326 let LayoutError::LimitsViolation { caixa, issue } = err else {
8327 panic!("expected LimitsViolation, got {err:?}");
8328 };
8329 assert_eq!(caixa, "demo");
8330 assert!(issue.contains(":fuel"), "issue must name the axis: {issue}");
8331 }
8332
8333 #[test]
8334 fn limits_well_formed_passes_layout() {
8335 use crate::LimitsSpec;
8336 use std::time::Duration;
8337 let root = PathBuf::from("/tmp/x");
8338 let manifest = root.join("caixa.lisp");
8339 let svc = root.join("servicos/demo.computeunit.yaml");
8340 let mut c = caixa(CaixaKind::Servico);
8341 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8342 c.limits = Some(LimitsSpec {
8343 memory: Some(64 * 1024 * 1024),
8344 fuel: Some(1_000_000),
8345 wall_clock: Some(Duration::from_secs(30)),
8346 cpu: Some(500),
8347 });
8348 let manifest_clone = manifest.clone();
8349 let svc_clone = svc.clone();
8350 let layout =
8351 StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8352 layout.verify(&c, &root).unwrap();
8353 }
8354
8355 #[test]
8356 fn supervisor_with_valid_children_passes() {
8357 use crate::{ChildSpec, RestartPolicy, RestartStrategy};
8358 let root = PathBuf::from("/tmp/x");
8359 let manifest = root.join("caixa.lisp");
8360 let manifest_clone = manifest.clone();
8361 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
8362 let mut c = caixa(CaixaKind::Supervisor);
8363 c.estrategia = Some(RestartStrategy::OneForOne);
8364 c.max_restarts = Some(5);
8365 c.children = vec![
8366 ChildSpec {
8367 caixa: "worker".into(),
8368 versao: "^0.1".into(),
8369 restart: RestartPolicy::Permanent,
8370 },
8371 ChildSpec {
8372 caixa: "cache".into(),
8373 versao: "^0.1".into(),
8374 restart: RestartPolicy::Transient,
8375 },
8376 ];
8377 layout.verify(&c, &root).unwrap();
8378 }
8379
8380 // ── :upgrade-from entry validation pipes through layout ─────────────
8381
8382 #[test]
8383 fn upgrade_invalid_module_surfaces_as_layout_violation() {
8384 // End-to-end pin that
8385 // [`crate::UpgradeFromEntry::validate`] runs *inside*
8386 // `LayoutInvariants::verify` and surfaces value-shape
8387 // violations through the new `UpgradeViolation` arm
8388 // (parallel to `BehaviorViolation`, `LimitsViolation`,
8389 // `SupervisorViolation`, `AplicacaoViolation`). Until this
8390 // wiring landed the entry validator was unreachable from any
8391 // build-pipeline caller — an `:upgrade-from
8392 // ((:from "0.1.0" :instructions ((:load-module "Hello")))` (uppercase
8393 // module name the K8s apiserver would reject on the per-
8394 // ComputeUnit `metadata.name` axis) silently passed
8395 // `feira lint` / `feira build` and surfaced only at wasm-engine
8396 // hot-upgrade time as a per-backend "module not found" /
8397 // `code:load_module/1` `badarg` runtime error, far from the
8398 // source caixa.lisp. Pinning the wiring here so a future
8399 // refactor that drops the `entry.validate()` call surfaces as
8400 // a build-pipeline regression at this test, not as a runtime
8401 // surprise per consumer.
8402 use crate::{UpgradeFromEntry, UpgradeInstruction};
8403 use std::path::PathBuf;
8404 let root = PathBuf::from("/tmp/x");
8405 let manifest = root.join("caixa.lisp");
8406 let svc = root.join("servicos/demo.computeunit.yaml");
8407 let mut c = caixa(CaixaKind::Servico);
8408 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8409 c.upgrade_from = vec![UpgradeFromEntry {
8410 from: "0.1.0".into(),
8411 instructions: vec![UpgradeInstruction::LoadModule {
8412 module: "Hello".into(), // uppercase — not DNS-1123
8413 }],
8414 }];
8415 let manifest_clone = manifest.clone();
8416 let svc_clone = svc.clone();
8417 let layout =
8418 StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8419 let err = layout.verify(&c, &root).unwrap_err();
8420 let LayoutError::UpgradeViolation { caixa, issue } = err else {
8421 panic!("expected UpgradeViolation, got {err:?}");
8422 };
8423 assert_eq!(caixa, "demo");
8424 assert!(
8425 issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE),
8426 "issue must name the lisp-form of the offending instruction: {issue}"
8427 );
8428 assert!(
8429 issue.contains("Hello"),
8430 "issue must name the offending :module verbatim: {issue}"
8431 );
8432 }
8433
8434 #[test]
8435 fn upgrade_empty_module_surfaces_as_layout_violation() {
8436 // Companion to the DNS-1123 footgun above on the narrower
8437 // empty arm. Every Module-bearing variant's empty value
8438 // reaches the layout pipeline through the kind-tagged
8439 // `ModuleEmpty` diagnostic naming its lisp-form.
8440 use crate::{UpgradeFromEntry, UpgradeInstruction};
8441 use std::path::PathBuf;
8442 let root = PathBuf::from("/tmp/x");
8443 let manifest = root.join("caixa.lisp");
8444 let svc = root.join("servicos/demo.computeunit.yaml");
8445 let mut c = caixa(CaixaKind::Servico);
8446 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8447 c.upgrade_from = vec![UpgradeFromEntry {
8448 from: "0.1.0".into(),
8449 instructions: vec![UpgradeInstruction::SoftPurge {
8450 module: String::new(),
8451 }],
8452 }];
8453 let manifest_clone = manifest.clone();
8454 let svc_clone = svc.clone();
8455 let layout =
8456 StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8457 let err = layout.verify(&c, &root).unwrap_err();
8458 let LayoutError::UpgradeViolation { caixa, issue } = err else {
8459 panic!("expected UpgradeViolation, got {err:?}");
8460 };
8461 assert_eq!(caixa, "demo");
8462 assert!(
8463 issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE),
8464 "issue must name the lisp-form of the empty instruction: {issue}"
8465 );
8466 }
8467
8468 #[test]
8469 fn upgrade_invalid_state_change_script_surfaces_as_layout_violation() {
8470 // Pins that the b0c8389 script value-shape gates
8471 // (AbsoluteScript / ParentEscapeScript) — previously
8472 // unreachable from any build-pipeline caller — now fire
8473 // through the same `UpgradeViolation` arm before the path-
8474 // existence pass would otherwise emit the less-helpful
8475 // "missing upgrade-script" (or, worse, *succeed* against
8476 // /etc/passwd, proving the sandbox bypass — same defect
8477 // the b0c8389 BehaviorSpec wiring closed on the peer M2
8478 // slot).
8479 use crate::{UpgradeFromEntry, UpgradeInstruction};
8480 use std::path::PathBuf;
8481 let root = PathBuf::from("/tmp/x");
8482 let manifest = root.join("caixa.lisp");
8483 let svc = root.join("servicos/demo.computeunit.yaml");
8484 let etc_passwd = PathBuf::from("/etc/passwd");
8485 let mut c = caixa(CaixaKind::Servico);
8486 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8487 c.upgrade_from = vec![UpgradeFromEntry {
8488 from: "0.1.0".into(),
8489 instructions: vec![UpgradeInstruction::StateChange {
8490 script: PathBuf::from("/etc/passwd"),
8491 }],
8492 }];
8493 let manifest_clone = manifest.clone();
8494 let svc_clone = svc.clone();
8495 let etc_passwd_clone = etc_passwd.clone();
8496 // Critically: /etc/passwd "exists" in our mock — without the
8497 // value-shape pre-check, the existence loop would *succeed*
8498 // and the path-traversal exit from the project sandbox would
8499 // pass `feira build` silently.
8500 let layout = StandardLayout::new().with_path_exists(move |p| {
8501 p == manifest_clone || p == svc_clone || p == etc_passwd_clone
8502 });
8503 let err = layout.verify(&c, &root).unwrap_err();
8504 let LayoutError::UpgradeViolation { caixa, issue } = err else {
8505 panic!("expected UpgradeViolation, got {err:?}");
8506 };
8507 assert_eq!(caixa, "demo");
8508 assert!(
8509 issue.contains("absolute") || issue.contains("Absolute"),
8510 "issue must name the violation kind (absolute): {issue}"
8511 );
8512 }
8513
8514 #[test]
8515 fn upgrade_well_formed_passes_layout() {
8516 // Positive control — every documented authoring shape
8517 // (`:load-module`, `:state-change` with a relative path,
8518 // `:soft-purge`, `:purge`, sole `:restart`) passes the wired
8519 // gate. The typed sequence (`:load-module` → `:state-change`
8520 // → `:soft-purge` → `:purge`) lives in one entry; the sole
8521 // `:restart` fallback lives in a *separate* entry on a
8522 // different `:from` (the within-entry restart-exclusivity
8523 // gate added in this commit rejects mixing the fallback with
8524 // the typed sequence — per the UpgradeInstruction::Restart
8525 // doc, `:restart` is terminal and any other instructions in
8526 // the same entry are dead code). Drift here = a future
8527 // tighten that rejects any canonical shape surfaces as a
8528 // regression at this layout-level pin, not piecemeal across
8529 // per-renderer call sites.
8530 //
8531 // `:soft-purge` and `:purge` target *distinct* old-version
8532 // modules (`hello-rio-old` and `hello-rio-oldest`) so the
8533 // within-entry cleanup-singularity gate
8534 // (`UpgradeError::DuplicateCleanup`) passes — that gate
8535 // rejects more than one cleanup per module per entry (one
8536 // semantic per old version; mixing drain + discard on one
8537 // module is the soft-then-hard fallback footgun the author
8538 // shouldn't write because the operator handles cleanup
8539 // failure escalation itself). The two distinct names cover
8540 // the legitimate "drain a recent old, hard-discard an
8541 // older-still" shape — both authoring forms remain load-
8542 // bearing in this positive-control enumeration.
8543 use crate::{BehaviorSpec, UpgradeFromEntry, UpgradeInstruction};
8544 use std::path::PathBuf;
8545 let root = PathBuf::from("/tmp/x");
8546 let manifest = root.join("caixa.lisp");
8547 let svc = root.join("servicos/demo.computeunit.yaml");
8548 let migration = root.join("lib/migrations/v01-to-v02.lisp");
8549 let on_state_change = root.join("lib/migrations.lisp");
8550 let mut c = caixa(CaixaKind::Servico);
8551 // `:versao` past both entries' `:from` so the cross-slot
8552 // precedence gate (`FromNotBeforeVersao`) lets this canonical
8553 // authoring shape through to the positive-control assertion.
8554 c.versao = "0.2.0".into();
8555 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8556 // `:on-state-change` declared alongside the `(:state-change …)`
8557 // instruction below — the cross-slot composition gate
8558 // (`validate_upgrade_from_against_behavior`) rejects a
8559 // `:state-change` without the callback, so the canonical
8560 // authoring shape this positive control pins now includes the
8561 // runtime delivery hook (the `gen_server:code_change/3` analog
8562 // that the per-version script is invoked through during hot
8563 // upgrade per the upgrade.rs module doc "Composes with"
8564 // promise).
8565 c.behavior = Some(BehaviorSpec {
8566 on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
8567 ..Default::default()
8568 });
8569 c.upgrade_from = vec![
8570 UpgradeFromEntry {
8571 from: "0.1.0".into(),
8572 instructions: vec![
8573 UpgradeInstruction::LoadModule {
8574 module: "hello-rio".into(),
8575 },
8576 UpgradeInstruction::StateChange {
8577 script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
8578 },
8579 UpgradeInstruction::SoftPurge {
8580 module: "hello-rio-old".into(),
8581 },
8582 UpgradeInstruction::Purge {
8583 module: "hello-rio-oldest".into(),
8584 },
8585 ],
8586 },
8587 UpgradeFromEntry {
8588 from: "0.0.9".into(),
8589 instructions: vec![UpgradeInstruction::Restart],
8590 },
8591 ];
8592 let manifest_clone = manifest.clone();
8593 let svc_clone = svc.clone();
8594 let migration_clone = migration.clone();
8595 let on_state_change_clone = on_state_change.clone();
8596 let layout = StandardLayout::new().with_path_exists(move |p| {
8597 p == manifest_clone
8598 || p == svc_clone
8599 || p == migration_clone
8600 || p == on_state_change_clone
8601 });
8602 layout.verify(&c, &root).unwrap();
8603 }
8604
8605 #[test]
8606 fn upgrade_from_restart_mixed_surfaces_as_upgrade_violation() {
8607 // Wiring pin: the within-entry `(:restart)`-exclusivity gate
8608 // (`UpgradeFromEntry::validate_restart_exclusive`) lands on
8609 // the same `LayoutError::UpgradeViolation` axis the per-entry
8610 // shape gate (26da2c7), the cross-entry duplicate-`:from`
8611 // gate (7c6aef2), and the cross-slot `:from < :versao`
8612 // precedence gate (de7ab1a) already do. A caixa.lisp whose
8613 // `:upgrade-from` entry mixes `(:restart)` with a typed
8614 // instruction surfaces at `feira build` time naming the
8615 // offending caixa + the entry's `:from` rather than silently
8616 // passing into the wasm-operator with semantically dead code
8617 // in the operator's dispatch table. Mirrors
8618 // `upgrade_from_duplicate_surfaces_as_upgrade_violation` on
8619 // the peer cross-entry gate.
8620 use crate::{UpgradeFromEntry, UpgradeInstruction};
8621 let root = PathBuf::from("/tmp/x");
8622 let manifest = root.join("caixa.lisp");
8623 let svc = root.join("servicos/demo.computeunit.yaml");
8624 let mut c = caixa(CaixaKind::Servico);
8625 c.versao = "0.2.0".into();
8626 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8627 c.upgrade_from = vec![UpgradeFromEntry {
8628 from: "0.1.0".into(),
8629 instructions: vec![
8630 UpgradeInstruction::LoadModule {
8631 module: "hello-rio".into(),
8632 },
8633 UpgradeInstruction::Restart,
8634 ],
8635 }];
8636 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
8637 let err = layout.verify(&c, &root).unwrap_err();
8638 let LayoutError::UpgradeViolation { caixa, issue } = err else {
8639 panic!("expected LayoutError::UpgradeViolation for restart-mixed entry, got {err:?}");
8640 };
8641 assert_eq!(caixa, "demo");
8642 assert!(
8643 issue.contains("0.1.0"),
8644 "UpgradeViolation issue must name the offending entry's `:from` verbatim, got \
8645 {issue:?}"
8646 );
8647 assert!(
8648 issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART),
8649 "UpgradeViolation issue must name the `:restart` axis verbatim, got {issue:?}"
8650 );
8651 assert!(
8652 issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE),
8653 "UpgradeViolation issue must name the non-:restart peer instruction's lisp-form \
8654 verbatim, got {issue:?}"
8655 );
8656 }
8657
8658 #[test]
8659 fn upgrade_from_restart_duplicated_surfaces_as_upgrade_violation() {
8660 // Companion arm: the duplicate-`(:restart)` mode of
8661 // `RestartNotExclusive` (no typed peers, just multiple
8662 // `Restart` variants) surfaces through the same wiring as the
8663 // mixed-with-typed mode above. The diagnostic still names the
8664 // offending entry's `:from` verbatim even when `other_kinds`
8665 // is empty.
8666 use crate::{UpgradeFromEntry, UpgradeInstruction};
8667 let root = PathBuf::from("/tmp/x");
8668 let manifest = root.join("caixa.lisp");
8669 let svc = root.join("servicos/demo.computeunit.yaml");
8670 let mut c = caixa(CaixaKind::Servico);
8671 c.versao = "0.2.0".into();
8672 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8673 c.upgrade_from = vec![UpgradeFromEntry {
8674 from: "0.1.0".into(),
8675 instructions: vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
8676 }];
8677 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
8678 let err = layout.verify(&c, &root).unwrap_err();
8679 let LayoutError::UpgradeViolation { caixa, issue } = err else {
8680 panic!(
8681 "expected LayoutError::UpgradeViolation for duplicate-restart entry, got \
8682 {err:?}"
8683 );
8684 };
8685 assert_eq!(caixa, "demo");
8686 assert!(
8687 issue.contains("0.1.0"),
8688 "UpgradeViolation issue must name the offending entry's `:from` verbatim, got \
8689 {issue:?}"
8690 );
8691 assert!(
8692 issue.contains("(:restart)")
8693 || issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART),
8694 "UpgradeViolation issue must name the `:restart` axis verbatim, got {issue:?}"
8695 );
8696 }
8697
8698 #[test]
8699 fn upgrade_from_invalid_surfaces_as_layout_violation() {
8700 // The `:from` semver gate (`UpgradeError::FromInvalid`)
8701 // was likewise unreachable before this wiring landed — a
8702 // typo-shaped `:from "v0.1.0"` (git-tag-shape leaking into
8703 // the semver slot) silently passed `feira build` and
8704 // surfaced only when the operator's hot-upgrade decision
8705 // engine tried to match against the version key it couldn't
8706 // parse. Now wired through `UpgradeViolation` with the
8707 // peer-shaped `{ from, reason }` payload — the
8708 // parser-shaped `reason` flows through `Display` so the
8709 // wrapped issue string carries both the offending value
8710 // *and* the SemVer-2 parser's wording (peer with the
8711 // `VersaoInvalid` / `MembroVersaoInvalid` envelopes on the
8712 // sibling SemVer-2 axes).
8713 use crate::{UpgradeFromEntry, UpgradeInstruction};
8714 use std::path::PathBuf;
8715 let root = PathBuf::from("/tmp/x");
8716 let manifest = root.join("caixa.lisp");
8717 let svc = root.join("servicos/demo.computeunit.yaml");
8718 let mut c = caixa(CaixaKind::Servico);
8719 c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8720 c.upgrade_from = vec![UpgradeFromEntry {
8721 from: "v0.1.0".into(), // git-tag-shape, not semver
8722 instructions: vec![UpgradeInstruction::Restart],
8723 }];
8724 let manifest_clone = manifest.clone();
8725 let svc_clone = svc.clone();
8726 let layout =
8727 StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8728 let err = layout.verify(&c, &root).unwrap_err();
8729 let LayoutError::UpgradeViolation { caixa, issue } = err else {
8730 panic!("expected UpgradeViolation, got {err:?}");
8731 };
8732 assert_eq!(caixa, "demo");
8733 assert!(
8734 issue.contains("v0.1.0"),
8735 "UpgradeViolation issue must name the offending :from value verbatim, got {issue:?}"
8736 );
8737 assert!(
8738 issue.contains(":from"),
8739 "UpgradeViolation issue must name the :from slot verbatim, got {issue:?}"
8740 );
8741 // Pin the parser-shaped reason flow-through: the renamed
8742 // `FromInvalid { from, reason }` carries the SemVer-2 parser's
8743 // wording verbatim, and the [`UpgradeError`] Display routes it
8744 // into the wrapped `issue` string so the layout envelope
8745 // surfaces both the offending value *and* the parser's
8746 // diagnosis. Mirrors the peer flow-through on
8747 // `ManifestError::VersaoInvalid` (top-level `:versao`) and
8748 // `AplicacaoError::MembroVersaoInvalid` (`:membros :versao`).
8749 assert!(
8750 issue.contains("SemVer-2"),
8751 "UpgradeViolation issue must carry the parser-shaped reason (\"SemVer-2\"), got {issue:?}"
8752 );
8753 }
8754
8755 #[test]
8756 fn missing_lib_gate_routes_through_kind_requires_lib_and_caixa_nome() {
8757 // Fail-before-pass-after pin on the two-part converge landed
8758 // at layout.rs:844-847:
8759 // (a) `caixa.kind().is_biblioteca()` →
8760 // `caixa.kind().requires_lib()` — routes the biblioteca
8761 // required-slot gate onto the same `requires_*()`
8762 // predicate family the three sibling required-slot
8763 // gates (`requires_exe()` at :856, `requires_servicos()`
8764 // at :860, `requires_ci()` at :874) already key off.
8765 // All four gates in the block now share one convention;
8766 // a future kind that gains its own required-slot gate
8767 // (an M4/M5 typed arm the CAIXA-SDLC §I six-kind roster
8768 // may grow) reaches for the same predicate family and
8769 // inherits the accessor discipline for free.
8770 // (b) raw `caixa.nome` → `caixa.nome()` — routes the
8771 // `expected` path composition through the typed
8772 // [`crate::Caixa::nome`] accessor, closing the last
8773 // unlifted raw `caixa.nome` production field-access
8774 // site in `caixa-core/src/layout.rs` (every peer
8775 // diagnostic in the file already routes through
8776 // `caixa.nome().to_string()`).
8777 //
8778 // The behavioral pin: for a Biblioteca kind with no fallback
8779 // `lib/<nome>.lisp` file, MissingLib fires and its `expected`
8780 // path composes through `Caixa::nome()`; for every other
8781 // kind, MissingLib does NOT fire (the gate short-circuits on
8782 // kinds where `requires_lib()` returns false), even when the
8783 // fallback file is likewise absent. A future regression that
8784 // reroutes the gate off `requires_lib()` (e.g. onto
8785 // `is_biblioteca()` again, or onto a hand-authored
8786 // `matches!(caixa.kind(), CaixaKind::Biblioteca)`) that
8787 // *happens* to agree byte-for-byte on today's arm-set trips
8788 // this test the moment a future kind's `requires_lib()`
8789 // returns true for a non-`Biblioteca` arm (or the sibling
8790 // required-slot gates diverge from the same convention).
8791 let root = PathBuf::from("/tmp/x");
8792 let manifest = root.join("caixa.lisp");
8793 let manifest_only = manifest.clone();
8794 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_only);
8795
8796 // Biblioteca kind + no lib fallback → MissingLib fires with
8797 // the expected path composed through `Caixa::nome()`.
8798 let bib = caixa(CaixaKind::Biblioteca);
8799 assert!(
8800 bib.kind().requires_lib(),
8801 "requires_lib() must return true for Biblioteca — the four-required-\
8802 slot-gate family's routing depends on this arm's assignment"
8803 );
8804 let err = layout.verify(&bib, &root).unwrap_err();
8805 let LayoutError::MissingLib {
8806 caixa: cname,
8807 expected,
8808 } = err
8809 else {
8810 panic!("expected MissingLib for Biblioteca kind with no lib fallback, got {err:?}");
8811 };
8812 assert_eq!(
8813 cname,
8814 bib.nome(),
8815 "MissingLib `caixa:` carrier must byte-equal Caixa::nome()"
8816 );
8817 assert_eq!(
8818 expected,
8819 root.join(crate::render::LAYOUT_DIR_LIB)
8820 .join(format!("{}.lisp", bib.nome())),
8821 "MissingLib `expected:` path must compose through Caixa::nome() \
8822 verbatim — a raw-field-access regression would silently drift \
8823 the composed path on any future `:nome` axis extension \
8824 (namespace-qualified rewrite, per-cluster alias overlay)"
8825 );
8826
8827 // Non-Biblioteca kinds → the MissingLib gate short-circuits.
8828 // Different kinds fail on their own required-slot gate
8829 // (BinarioWithoutExe, ServicoWithoutServicos, MissingCi) or
8830 // on downstream M2/M3 invariants; none of them may surface as
8831 // MissingLib, because `requires_lib()` returns false for each.
8832 for kind in [
8833 CaixaKind::Binario,
8834 CaixaKind::Servico,
8835 CaixaKind::Supervisor,
8836 CaixaKind::Aplicacao,
8837 CaixaKind::Acao,
8838 ] {
8839 assert!(
8840 !kind.requires_lib(),
8841 "requires_lib() must return false for {kind:?} — the \
8842 four-required-slot-gate family's arm assignment pins \
8843 exactly one kind (Biblioteca) as the arm that requires \
8844 a `lib/` entry"
8845 );
8846 let c = caixa(kind);
8847 let result = layout.verify(&c, &root);
8848 assert!(
8849 !matches!(result, Err(LayoutError::MissingLib { .. })),
8850 "MissingLib gate at layout.rs:844 must short-circuit for \
8851 kinds where requires_lib() returns false; unexpectedly \
8852 fired for {kind:?}: {result:?}"
8853 );
8854 }
8855 }
8856
8857 #[test]
8858 fn missing_lib_ctor_matches_struct_literal_wrap() {
8859 // Equivalence pin locking [`LayoutError::missing_lib`] to its
8860 // struct-literal peer under PartialEq. The pre-lift wire-up at
8861 // layout.rs:1010 read `LayoutError::MissingLib { caixa:
8862 // caixa.nome().to_string(), expected }`; the post-lift
8863 // dispatch reads `LayoutError::missing_lib(caixa, expected)`.
8864 // Both must produce byte-equal variants — a silent divergence
8865 // (a `to_lowercase()`, a `trim()`, a lost `.to_string()` copy,
8866 // an accidental `.clone()` of the wrong side of the `expected`
8867 // path) surfaces here rather than at a downstream diagnostic-
8868 // shape drift.
8869 let bib = caixa(CaixaKind::Biblioteca);
8870 let expected = PathBuf::from("/tmp/x")
8871 .join(crate::render::LAYOUT_DIR_LIB)
8872 .join(format!("{}.lisp", bib.nome()));
8873 let struct_lit = LayoutError::MissingLib {
8874 caixa: bib.nome().to_string(),
8875 expected: expected.clone(),
8876 };
8877 let ctor = LayoutError::missing_lib(&bib, expected);
8878 assert_eq!(
8879 struct_lit, ctor,
8880 "missing_lib ctor must byte-equal the pre-lift struct-literal"
8881 );
8882 }
8883
8884 #[test]
8885 fn missing_lib_ctor_projects_nome_through_accessor() {
8886 // Accessor-fidelity pin: any future `:nome` axis extension
8887 // (namespace-qualified rewrite `pleme-io/<nome>`, per-cluster
8888 // alias overlay, case-normalization pass) that lands on
8889 // [`crate::Caixa::nome`] must reach the `caixa:` carrier
8890 // through this projection rather than a raw field access.
8891 // The neighbour required-slot ctor family
8892 // ([`layout_nome_only_ctors!`]) projects the same way; this
8893 // pin locks `missing_lib` onto the same discipline so the
8894 // whole `LayoutError` family stays coherent under any future
8895 // `:nome` rewrite.
8896 //
8897 // Deliberately uses a byte-distinctive nome ("named-lib") so
8898 // a regression that hard-codes a fixture literal at the ctor
8899 // body (rather than projecting through the accessor) drops
8900 // the bytes and trips the assertion.
8901 let mut bib = caixa(CaixaKind::Biblioteca);
8902 bib.nome = "named-lib".into();
8903 let expected = PathBuf::from("/srv")
8904 .join(crate::render::LAYOUT_DIR_LIB)
8905 .join(format!("{}.lisp", bib.nome()));
8906 let err = LayoutError::missing_lib(&bib, expected.clone());
8907 let LayoutError::MissingLib {
8908 caixa: cname,
8909 expected: got,
8910 } = err
8911 else {
8912 panic!("missing_lib ctor must construct the MissingLib variant, got a foreign arm");
8913 };
8914 assert_eq!(
8915 cname,
8916 bib.nome(),
8917 "missing_lib `caixa:` carrier must project through Caixa::nome()"
8918 );
8919 assert_eq!(
8920 got, expected,
8921 "missing_lib `expected:` path must pass through verbatim"
8922 );
8923 }
8924
8925 #[test]
8926 fn missing_lib_verify_wire_up_routes_through_ctor() {
8927 // Behavioural pin: [`StandardLayout::verify`] must reach the
8928 // `MissingLib` variant through the newly lifted ctor rather
8929 // than a residual struct-literal block. The end-to-end
8930 // observable — a Biblioteca with no lib fallback — must
8931 // surface a `MissingLib` whose `caixa:` and `expected:`
8932 // carriers are byte-equal to what the ctor would produce
8933 // when called directly.
8934 let root = PathBuf::from("/opt/pkg");
8935 let manifest = root.join("caixa.lisp");
8936 let manifest_only = manifest.clone();
8937 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_only);
8938 let bib = caixa(CaixaKind::Biblioteca);
8939 let expected = root
8940 .join(crate::render::LAYOUT_DIR_LIB)
8941 .join(format!("{}.lisp", bib.nome()));
8942
8943 let observed = layout.verify(&bib, &root).unwrap_err();
8944 let synthesized = LayoutError::missing_lib(&bib, expected);
8945 assert_eq!(
8946 observed, synthesized,
8947 "StandardLayout::verify must reach MissingLib through the missing_lib ctor \
8948 — a residual struct-literal block would silently diverge on any future \
8949 accessor projection change"
8950 );
8951 }
8952
8953 #[test]
8954 fn ci_on_non_acao_ctor_matches_struct_literal_wrap() {
8955 // Equivalence pin locking [`LayoutError::ci_on_non_acao`] to
8956 // its struct-literal peer under `PartialEq`. The pre-lift
8957 // wire-up at `caixa-core/src/manifest.rs:5586` read
8958 // `LayoutError::CiOnNonAcao { caixa: self.nome().to_string(),
8959 // kind: self.kind() }`; the post-lift dispatch reads
8960 // `LayoutError::ci_on_non_acao(self)`. Both must produce
8961 // byte-equal variants — a silent divergence (a `to_lowercase()`,
8962 // a lost `.to_string()` copy, a swapped kind-copy) surfaces
8963 // here rather than at a downstream diagnostic-shape drift.
8964 let bib = caixa(CaixaKind::Biblioteca);
8965 let struct_lit = LayoutError::CiOnNonAcao {
8966 caixa: bib.nome().to_string(),
8967 kind: bib.kind(),
8968 };
8969 let ctor = LayoutError::ci_on_non_acao(&bib);
8970 assert_eq!(
8971 struct_lit, ctor,
8972 "ci_on_non_acao ctor must byte-equal the pre-lift struct-literal"
8973 );
8974 }
8975
8976 #[test]
8977 fn ci_on_non_acao_ctor_projects_nome_and_kind_through_accessors() {
8978 // Accessor-fidelity pin: any future `:nome` axis extension
8979 // (namespace-qualified rewrite `pleme-io/<nome>`, per-cluster
8980 // alias overlay, case-normalization pass) that lands on
8981 // [`crate::Caixa::nome`] and any future `:kind` re-projection
8982 // (an overlay pass returning a different `CaixaKind` copy)
8983 // that lands on [`crate::Caixa::kind`] must reach the
8984 // `caixa:` / `kind:` carriers through these projections
8985 // rather than raw field accesses. The neighbour
8986 // [`LayoutError::missing_lib`] ctor (b4d5a49) projects nome
8987 // the same way; this pin locks the `:ci` axis onto the same
8988 // discipline so the whole `LayoutError` family stays coherent
8989 // under any future rewrite.
8990 //
8991 // Deliberately uses a byte-distinctive nome ("ci-on-binario")
8992 // and a non-Acao kind (`Binario`) so a regression that
8993 // hard-codes a fixture literal at the ctor body (rather than
8994 // projecting through the accessors) drops the bytes or the
8995 // kind and trips the assertion.
8996 let mut bin = caixa(CaixaKind::Binario);
8997 bin.nome = "ci-on-binario".into();
8998 let err = LayoutError::ci_on_non_acao(&bin);
8999 let LayoutError::CiOnNonAcao {
9000 caixa: cname,
9001 kind: cknd,
9002 } = err
9003 else {
9004 panic!("ci_on_non_acao ctor must construct the CiOnNonAcao variant, got a foreign arm");
9005 };
9006 assert_eq!(
9007 cname,
9008 bin.nome(),
9009 "ci_on_non_acao `caixa:` carrier must project through Caixa::nome()"
9010 );
9011 assert_eq!(
9012 cknd,
9013 bin.kind(),
9014 "ci_on_non_acao `kind:` carrier must project through Caixa::kind()"
9015 );
9016 }
9017
9018 #[test]
9019 fn ci_on_non_acao_verify_wire_up_routes_through_ctor() {
9020 // Behavioural pin: [`StandardLayout::verify`] must reach the
9021 // `CiOnNonAcao` variant through the newly lifted ctor rather
9022 // than a residual struct-literal block. The end-to-end
9023 // observable — a non-Acao caixa with `:ci` declared — must
9024 // surface a `CiOnNonAcao` whose `caixa:` and `kind:` carriers
9025 // are byte-equal to what the ctor would produce when called
9026 // directly.
9027 let root = PathBuf::from("/tmp/x");
9028 let manifest = root.join("caixa.lisp");
9029 let manifest_only = manifest.clone();
9030 let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_only);
9031 let mut bib = caixa(CaixaKind::Biblioteca);
9032 bib.ci = Some(canteiro_types::CiRun {
9033 workspace: "pleme-io".into(),
9034 repo: "caixa".into(),
9035 nodes: vec![],
9036 });
9037
9038 let observed = layout.verify(&bib, &root).unwrap_err();
9039 let synthesized = LayoutError::ci_on_non_acao(&bib);
9040 assert_eq!(
9041 observed, synthesized,
9042 "Caixa::validate_ci_kind_coherence must reach CiOnNonAcao through the \
9043 ci_on_non_acao ctor — a residual struct-literal block would silently \
9044 diverge on any future accessor projection change"
9045 );
9046 }
9047}