Skip to main content

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::MissingManifest(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::MissingEntry`] naming the missing
1866    /// declared entry at `path` under the canonical `kind` label from
1867    /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`] /
1868    /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] /
1869    /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] /
1870    /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`] /
1871    /// [`crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT`].
1872    /// Folds the uniform `{ kind, path }` two-slot construction onto one
1873    /// substrate primitive so every [`StandardLayout::verify`] wire-up
1874    /// on this variant reads through one dispatch rather than the
1875    /// pre-lift open-coded struct-literal block.
1876    #[must_use]
1877    pub fn missing_entry(kind: &'static str, path: PathBuf) -> Self {
1878        Self::MissingEntry { kind, path }
1879    }
1880
1881    /// Construct a [`LayoutError::MissingLib`] naming the offending
1882    /// `caixa.nome()` and the resolved fallback `expected` path.
1883    ///
1884    /// Folds the uniform `Self::MissingLib { caixa: caixa.nome()
1885    /// .to_string(), expected }` two-slot struct-literal onto one
1886    /// substrate primitive so every [`StandardLayout::verify`] wire-up
1887    /// on this variant reads through one dispatch rather than the
1888    /// pre-lift open-coded struct-literal block, projecting the caixa
1889    /// slot through the paired [`crate::Caixa::nome`] accessor — the
1890    /// same discipline the sibling [`Self::missing_entry`]
1891    /// `{ kind, path }` ctor and the [`layout_nome_only_ctors!`]
1892    /// `{ caixa }`-only tuple-variant ctor family already take on the
1893    /// same envelope.
1894    #[must_use]
1895    pub fn missing_lib(caixa: &crate::Caixa, expected: PathBuf) -> Self {
1896        Self::MissingLib {
1897            caixa: caixa.nome().to_string(),
1898            expected,
1899        }
1900    }
1901}
1902
1903// Fold the six `LayoutError::<Variant>(caixa.nome().to_string())` nome-
1904// only tuple-variant wire-up sites at [`StandardLayout::verify`] onto one
1905// substrate primitive per typed variant — the fourth uniform-shape
1906// envelope on `LayoutError` after the `{ caixa, issue }` family the
1907// [`layout_violation_ctors!`] macro closed (131ca0d), the
1908// `{ caixa, kind, slots }` family the peer [`layout_slot_kind_ctors!`]
1909// macro closed (0419438), and the `{ kind, path }`
1910// [`LayoutError::missing_entry`] one-variant ctor (1b09f9d). Each of the
1911// six wire-up sites on this shape (`SupervisorOwnsCode` /
1912// `AplicacaoOwnsCode` / `AcaoOwnsCode` at the no-code kind-coherence gate;
1913// `BinarioWithoutExe` / `ServicoWithoutServicos` / `MissingCi` at the
1914// required-slot gate) opened the identical one-line
1915// `LayoutError::<Variant>(caixa.nome().to_string())` tuple-literal — the
1916// exact "same block re-inlined at every consumer" shape the PRIME
1917// DIRECTIVE names as a bug, on the same altitude the peer `_violation` /
1918// `_slots_on_non_*` / `missing_entry` families each closed on the
1919// sibling `LayoutError` envelopes.
1920//
1921// The macro below generates one static constructor per variant of shape
1922// `fn <slot>(caixa: &Caixa) -> LayoutError`, so every wire-up site
1923// collapses onto one dispatch:
1924// `return Err(LayoutError::<slot>(caixa));`, byte-equal to the pre-lift
1925// tuple-literal. The uniform one-field construction (`caixa: caixa.nome()
1926// .to_string()`) is spelled once — inside the macro — rather than at
1927// every wire-up site. Every constructor is `#[must_use]` so a caller who
1928// mistakenly discards the constructed error (rather than routing it
1929// through `return Err(…)`) trips a compile warning at the wire-up site.
1930//
1931// Peer with the three prior `LayoutError`-envelope constructor families
1932// — the four together now fold every uniform-shape `LayoutError` variant
1933// carried by [`StandardLayout::verify`] onto one substrate primitive per
1934// typed variant, so every layout-side error-wrap on `LayoutError` reads
1935// through one dispatch per variant rather than N open-coded blocks.
1936// Every future consumer that wants to construct one of these variants
1937// outside the layout pipeline (a per-slot admission webhook probing an
1938// Acao's `:ci` slot, a `feira validate --kind <X>` verb refusing a
1939// no-code kind that declares `:bibliotecas` / `:exe` / `:servicos`, an
1940// overlay resolver rejecting a required-slot omission against a
1941// cluster-local snapshot) reaches its variant through one call, matching
1942// the `_violation` / `_slots_on_non_*` / `missing_entry` families'
1943// substrate-primitive discipline.
1944macro_rules! layout_nome_only_ctors {
1945    ($($ctor:ident => $variant:ident),* $(,)?) => {
1946        impl LayoutError {
1947            $(
1948                #[doc = concat!(
1949                    "Construct a [`LayoutError::",
1950                    stringify!($variant),
1951                    "`] naming the offending `caixa.nome()`. Folds the ",
1952                    "uniform `Self::",
1953                    stringify!($variant),
1954                    "(caixa.nome().to_string())` one-field tuple-",
1955                    "literal onto one substrate primitive so every ",
1956                    "[`StandardLayout::verify`] wire-up on this variant ",
1957                    "reads through one dispatch rather than the pre-lift ",
1958                    "open-coded block."
1959                )]
1960                #[must_use]
1961                pub fn $ctor(caixa: &crate::Caixa) -> Self {
1962                    Self::$variant(caixa.nome().to_string())
1963                }
1964            )*
1965        }
1966    };
1967}
1968
1969layout_nome_only_ctors! {
1970    binario_without_exe => BinarioWithoutExe,
1971    servico_without_servicos => ServicoWithoutServicos,
1972    missing_ci => MissingCi,
1973    supervisor_owns_code => SupervisorOwnsCode,
1974    aplicacao_owns_code => AplicacaoOwnsCode,
1975    acao_owns_code => AcaoOwnsCode,
1976}
1977
1978#[cfg(test)]
1979mod tests {
1980    use super::*;
1981    use crate::{Caixa, CaixaKind};
1982    use std::path::PathBuf;
1983
1984    fn caixa(kind: CaixaKind) -> Caixa {
1985        Caixa {
1986            nome: "demo".into(),
1987            versao: "0.1.0".into(),
1988            kind,
1989            edicao: None,
1990            descricao: None,
1991            repositorio: None,
1992            licenca: None,
1993            autores: vec![],
1994            etiquetas: vec![],
1995            deps: vec![],
1996            deps_dev: vec![],
1997            exe: vec![],
1998            bibliotecas: vec![],
1999            servicos: vec![],
2000            // M2 typed-substrate slots default to absent.
2001            limits: None,
2002            behavior: None,
2003            upgrade_from: vec![],
2004            estrategia: None,
2005            max_restarts: None,
2006            restart_window: None,
2007            children: vec![],
2008            // M3 Aplicacao slots default to absent.
2009            membros: vec![],
2010            contratos: vec![],
2011            politicas: None,
2012            placement: None,
2013            entrada: None,
2014            ci: None,
2015        }
2016    }
2017
2018    #[test]
2019    fn missing_manifest_errors() {
2020        let layout = StandardLayout::new().with_path_exists(|_| false);
2021        let err = layout
2022            .verify(&caixa(CaixaKind::Biblioteca), Path::new("/tmp/x"))
2023            .unwrap_err();
2024        assert!(matches!(err, LayoutError::MissingManifest(_)));
2025    }
2026
2027    // ── LayoutError::*_violation constructor family ──────────────────────
2028    //
2029    // The [`layout_violation_ctors!`] macro (below the `LayoutError` enum
2030    // definition) generates one static constructor per `*Violation { caixa,
2031    // issue }` variant that folds the uniform `{ caixa: caixa.nome()
2032    // .to_string(), issue: err.to_string() }` two-slot construction onto
2033    // one substrate primitive. The per-variant equivalence pins below
2034    // (fail-before-pass-after by construction — a byte-mismatched macro
2035    // arm would trip its equivalence pin first) lock each generated
2036    // constructor to its struct-literal peer under `PartialEq`, so every
2037    // wire-up in [`StandardLayout::verify`] on that variant produces a
2038    // byte-equal `LayoutError` to the pre-lift open-coded block. The
2039    // fixture caixa fires under `caixa("demo")` so the `caixa: "demo"`
2040    // half is pinned; the fixture error fires under a fixed `&str` so the
2041    // `issue: <literal>` half is pinned; the two together pin every field
2042    // of every generated variant.
2043
2044    fn layout_violation_ctor_fixture() -> (Caixa, &'static str) {
2045        (caixa(CaixaKind::Biblioteca), "sample issue text")
2046    }
2047
2048    // `assert_eq!` uses `PartialEq::eq(&self, &other)` under the hood, so
2049    // `actual`/`expected` are only ever read, never moved into anything —
2050    // the ergonomic tradeoff (owned + move-in vs. reference + &-borrow at
2051    // every call site) favors the owned form for a test-only assertion
2052    // helper called from 17 wire-up pins. The lint targets the general
2053    // API-shape case where callers still have downstream uses for the
2054    // moved value; the assertion helper terminates on the equality check.
2055    #[allow(clippy::needless_pass_by_value)]
2056    fn assert_violation_ctor_matches(actual: LayoutError, expected: LayoutError) {
2057        assert_eq!(
2058            actual, expected,
2059            "generated constructor must produce byte-equal LayoutError to open-coded struct-literal wrap",
2060        );
2061    }
2062
2063    #[test]
2064    fn nome_violation_ctor_matches_struct_literal_wrap() {
2065        let (c, issue) = layout_violation_ctor_fixture();
2066        assert_violation_ctor_matches(
2067            LayoutError::nome_violation(&c, issue),
2068            LayoutError::NomeViolation {
2069                caixa: c.nome().to_string(),
2070                issue: issue.to_string(),
2071            },
2072        );
2073    }
2074
2075    #[test]
2076    fn versao_violation_ctor_matches_struct_literal_wrap() {
2077        let (c, issue) = layout_violation_ctor_fixture();
2078        assert_violation_ctor_matches(
2079            LayoutError::versao_violation(&c, issue),
2080            LayoutError::VersaoViolation {
2081                caixa: c.nome().to_string(),
2082                issue: issue.to_string(),
2083            },
2084        );
2085    }
2086
2087    #[test]
2088    fn deps_violation_ctor_matches_struct_literal_wrap() {
2089        let (c, issue) = layout_violation_ctor_fixture();
2090        assert_violation_ctor_matches(
2091            LayoutError::deps_violation(&c, issue),
2092            LayoutError::DepsViolation {
2093                caixa: c.nome().to_string(),
2094                issue: issue.to_string(),
2095            },
2096        );
2097    }
2098
2099    #[test]
2100    fn etiquetas_violation_ctor_matches_struct_literal_wrap() {
2101        let (c, issue) = layout_violation_ctor_fixture();
2102        assert_violation_ctor_matches(
2103            LayoutError::etiquetas_violation(&c, issue),
2104            LayoutError::EtiquetasViolation {
2105                caixa: c.nome().to_string(),
2106                issue: issue.to_string(),
2107            },
2108        );
2109    }
2110
2111    #[test]
2112    fn autores_violation_ctor_matches_struct_literal_wrap() {
2113        let (c, issue) = layout_violation_ctor_fixture();
2114        assert_violation_ctor_matches(
2115            LayoutError::autores_violation(&c, issue),
2116            LayoutError::AutoresViolation {
2117                caixa: c.nome().to_string(),
2118                issue: issue.to_string(),
2119            },
2120        );
2121    }
2122
2123    #[test]
2124    fn repositorio_violation_ctor_matches_struct_literal_wrap() {
2125        let (c, issue) = layout_violation_ctor_fixture();
2126        assert_violation_ctor_matches(
2127            LayoutError::repositorio_violation(&c, issue),
2128            LayoutError::RepositorioViolation {
2129                caixa: c.nome().to_string(),
2130                issue: issue.to_string(),
2131            },
2132        );
2133    }
2134
2135    #[test]
2136    fn descricao_violation_ctor_matches_struct_literal_wrap() {
2137        let (c, issue) = layout_violation_ctor_fixture();
2138        assert_violation_ctor_matches(
2139            LayoutError::descricao_violation(&c, issue),
2140            LayoutError::DescricaoViolation {
2141                caixa: c.nome().to_string(),
2142                issue: issue.to_string(),
2143            },
2144        );
2145    }
2146
2147    #[test]
2148    fn licenca_violation_ctor_matches_struct_literal_wrap() {
2149        let (c, issue) = layout_violation_ctor_fixture();
2150        assert_violation_ctor_matches(
2151            LayoutError::licenca_violation(&c, issue),
2152            LayoutError::LicencaViolation {
2153                caixa: c.nome().to_string(),
2154                issue: issue.to_string(),
2155            },
2156        );
2157    }
2158
2159    #[test]
2160    fn edicao_violation_ctor_matches_struct_literal_wrap() {
2161        let (c, issue) = layout_violation_ctor_fixture();
2162        assert_violation_ctor_matches(
2163            LayoutError::edicao_violation(&c, issue),
2164            LayoutError::EdicaoViolation {
2165                caixa: c.nome().to_string(),
2166                issue: issue.to_string(),
2167            },
2168        );
2169    }
2170
2171    #[test]
2172    fn code_path_violation_ctor_matches_struct_literal_wrap() {
2173        let (c, issue) = layout_violation_ctor_fixture();
2174        assert_violation_ctor_matches(
2175            LayoutError::code_path_violation(&c, issue),
2176            LayoutError::CodePathViolation {
2177                caixa: c.nome().to_string(),
2178                issue: issue.to_string(),
2179            },
2180        );
2181    }
2182
2183    #[test]
2184    fn limits_violation_ctor_matches_struct_literal_wrap() {
2185        let (c, issue) = layout_violation_ctor_fixture();
2186        assert_violation_ctor_matches(
2187            LayoutError::limits_violation(&c, issue),
2188            LayoutError::LimitsViolation {
2189                caixa: c.nome().to_string(),
2190                issue: issue.to_string(),
2191            },
2192        );
2193    }
2194
2195    #[test]
2196    fn behavior_violation_ctor_matches_struct_literal_wrap() {
2197        let (c, issue) = layout_violation_ctor_fixture();
2198        assert_violation_ctor_matches(
2199            LayoutError::behavior_violation(&c, issue),
2200            LayoutError::BehaviorViolation {
2201                caixa: c.nome().to_string(),
2202                issue: issue.to_string(),
2203            },
2204        );
2205    }
2206
2207    #[test]
2208    fn upgrade_violation_ctor_matches_struct_literal_wrap() {
2209        let (c, issue) = layout_violation_ctor_fixture();
2210        assert_violation_ctor_matches(
2211            LayoutError::upgrade_violation(&c, issue),
2212            LayoutError::UpgradeViolation {
2213                caixa: c.nome().to_string(),
2214                issue: issue.to_string(),
2215            },
2216        );
2217    }
2218
2219    #[test]
2220    fn restart_window_violation_ctor_matches_struct_literal_wrap() {
2221        let (c, issue) = layout_violation_ctor_fixture();
2222        assert_violation_ctor_matches(
2223            LayoutError::restart_window_violation(&c, issue),
2224            LayoutError::RestartWindowViolation {
2225                caixa: c.nome().to_string(),
2226                issue: issue.to_string(),
2227            },
2228        );
2229    }
2230
2231    #[test]
2232    fn supervisor_violation_ctor_matches_struct_literal_wrap() {
2233        let (c, issue) = layout_violation_ctor_fixture();
2234        assert_violation_ctor_matches(
2235            LayoutError::supervisor_violation(&c, issue),
2236            LayoutError::SupervisorViolation {
2237                caixa: c.nome().to_string(),
2238                issue: issue.to_string(),
2239            },
2240        );
2241    }
2242
2243    #[test]
2244    fn aplicacao_violation_ctor_matches_struct_literal_wrap() {
2245        let (c, issue) = layout_violation_ctor_fixture();
2246        assert_violation_ctor_matches(
2247            LayoutError::aplicacao_violation(&c, issue),
2248            LayoutError::AplicacaoViolation {
2249                caixa: c.nome().to_string(),
2250                issue: issue.to_string(),
2251            },
2252        );
2253    }
2254
2255    #[test]
2256    fn acao_violation_ctor_matches_struct_literal_wrap() {
2257        // Sibling of [`aplicacao_violation_ctor_matches_struct_literal_wrap`]
2258        // / [`supervisor_violation_ctor_matches_struct_literal_wrap`] on
2259        // the third per-kind compound-shape wrap envelope on
2260        // `LayoutError`. Pins the macro-generated `acao_violation`
2261        // constructor to its struct-literal peer under `PartialEq`, so
2262        // every wire-up in [`StandardLayout::verify`] on the
2263        // [`LayoutError::AcaoViolation`] variant produces a byte-equal
2264        // `LayoutError` to the pre-lift open-coded block. Closes the
2265        // pin family the peer per-kind shape wraps already carry.
2266        let (c, issue) = layout_violation_ctor_fixture();
2267        assert_violation_ctor_matches(
2268            LayoutError::acao_violation(&c, issue),
2269            LayoutError::AcaoViolation {
2270                caixa: c.nome().to_string(),
2271                issue: issue.to_string(),
2272            },
2273        );
2274    }
2275
2276    #[test]
2277    fn violation_ctor_routes_issue_through_display_impl() {
2278        // Pin the fold's `issue = err.to_string()` half against any type
2279        // implementing `Display` — a per-arm error type from a foreign
2280        // module (here, `std::io::Error`) threads through byte-equal to
2281        // the struct-literal `.to_string()` construction, so the fold
2282        // does not silently collapse onto `&str`-only inputs.
2283        let c = caixa(CaixaKind::Biblioteca);
2284        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "sample io display source");
2285        let expected_issue = io_err.to_string();
2286        let actual = LayoutError::deps_violation(&c, &io_err);
2287        assert_eq!(
2288            actual,
2289            LayoutError::DepsViolation {
2290                caixa: c.nome().to_string(),
2291                issue: expected_issue,
2292            },
2293        );
2294    }
2295
2296    #[test]
2297    fn violation_ctor_routes_caixa_prefix_through_nome_accessor() {
2298        // Pin the fold's `caixa = caixa.nome().to_string()` half against
2299        // a non-default `:nome` — the accessor threads the caller's
2300        // `:nome` verbatim into the wrap envelope, so the fold does not
2301        // silently collapse onto the default `"demo"` fixture nome.
2302        let mut c = caixa(CaixaKind::Biblioteca);
2303        c.nome = "alt-nome".into();
2304        let actual = LayoutError::behavior_violation(&c, "sample issue");
2305        assert_eq!(
2306            actual,
2307            LayoutError::BehaviorViolation {
2308                caixa: "alt-nome".to_string(),
2309                issue: "sample issue".to_string(),
2310            },
2311        );
2312    }
2313
2314    // ── Caixa::run_layout_gate — per-slot gate + LayoutError wrap fold ───
2315    //
2316    // The [`Caixa::run_layout_gate`] substrate primitive folds the 18
2317    // self-similar `caixa.validate_<slot>().map_err(|err| LayoutError::
2318    // <slot>_violation(caixa, err))?;` wire-up sites at
2319    // [`StandardLayout::verify`] onto one dispatch. The pins below
2320    // (fail-before-pass-after by construction — a silent regression that
2321    // de-folded either arm would trip its own pin first) lock the two
2322    // arms of the fold under `PartialEq`:
2323    //
2324    //   - The `Ok(())` identity-element arm passes through verbatim (no
2325    //     wrap runs, no `caixa` closure capture).
2326    //   - The `Err(E)` arm routes through the caller-supplied `wrap`
2327    //     ctor with `self` bound as the caixa slot, byte-equal to the
2328    //     pre-lift `.map_err(|err| CTOR(caixa, err))` closure.
2329    //
2330    // The third pin (per-arm equivalence) runs the primitive with the
2331    // canonical `Caixa::validate_nome` validator and the paired
2332    // `LayoutError::nome_violation` ctor on a fixture whose `:nome`
2333    // fails `validate_nome`'s DNS-1123 gate ("Bad_Nome" — the uppercase
2334    // + underscore double footgun) and asserts the primitive's
2335    // `Result<(), LayoutError>` matches the open-coded pre-lift cascade
2336    // on the same fixture. A silent regression that de-folded the wrap
2337    // (dropped the `self` binding, threaded a stale caixa nome, swapped
2338    // the wrap ctor) would surface here as a mismatch between the two
2339    // dispatches.
2340
2341    #[test]
2342    fn run_layout_gate_ok_arm_passes_through() {
2343        // Positive control on the identity-element arm: a gate returning
2344        // `Ok(())` short-circuits before the wrap runs, so the caller
2345        // receives `Ok(())` verbatim regardless of what the paired ctor
2346        // would have produced. Pins the fold's `Result::map_err`
2347        // short-circuit semantics — a regression that unconditionally
2348        // wrapped (e.g. always called the ctor) would trip here.
2349        let c = caixa(CaixaKind::Biblioteca);
2350        let result: Result<(), LayoutError> = c.run_layout_gate(
2351            |_c: &Caixa| Ok::<(), &'static str>(()),
2352            |_c: &Caixa, _err: &'static str| {
2353                panic!("wrap must not run on the Ok(()) arm of the fold")
2354            },
2355        );
2356        assert!(
2357            result.is_ok(),
2358            "run_layout_gate must pass Ok(()) through verbatim, got {result:?}"
2359        );
2360    }
2361
2362    #[test]
2363    fn run_layout_gate_err_arm_wraps_via_ctor() {
2364        // Positive control on the err arm: a gate returning `Err(E)`
2365        // threads `E` into the caller-supplied `wrap` ctor with `self`
2366        // bound as the caixa argument. Uses a synthetic `&'static str`
2367        // error and the canonical `LayoutError::deps_violation` ctor so
2368        // the pin covers the fold's two-callable dispatch shape without
2369        // depending on any per-slot validator's specific arm sweep.
2370        let c = caixa(CaixaKind::Biblioteca);
2371        let sample_reason = "sample gate reason";
2372        let result = c.run_layout_gate(
2373            |_c: &Caixa| Err::<(), &'static str>(sample_reason),
2374            LayoutError::deps_violation,
2375        );
2376        let err = result.expect_err("Err arm must reach the caller");
2377        assert_eq!(
2378            err,
2379            LayoutError::DepsViolation {
2380                caixa: c.nome().to_string(),
2381                issue: sample_reason.to_string(),
2382            },
2383            "run_layout_gate must wrap the gate's Err via the caller-supplied \
2384             ctor with `self` bound as the caixa slot"
2385        );
2386    }
2387
2388    #[test]
2389    fn run_layout_gate_folds_arm_matches_gate() {
2390        // Fail-before-pass-after per-arm equivalence pin on the err arm:
2391        // a fixture whose `:nome` fails `validate_nome`'s DNS-1123 gate
2392        // (`"Bad_Nome"` — uppercase + underscore double footgun the
2393        // [`crate::ManifestError::NomeInvalid`] arm rejects) surfaces
2394        // the same `LayoutError::NomeViolation` byte-equal through both
2395        // the primitive `Caixa::run_layout_gate(Caixa::validate_nome,
2396        // LayoutError::nome_violation)` and the open-coded pre-lift
2397        // cascade `Caixa::validate_nome().map_err(|err|
2398        // LayoutError::nome_violation(&c, err))` on the same Caixa
2399        // fixture. Pins the fold — a silent regression that de-folded
2400        // either arm (dropped the `self` binding, threaded a stale
2401        // caixa nome, swapped the wrap ctor) would surface here as a
2402        // mismatch between the two dispatches.
2403        let mut c = caixa(CaixaKind::Biblioteca);
2404        c.nome = "Bad_Nome".into();
2405        let via_primitive = c
2406            .run_layout_gate(Caixa::validate_nome, LayoutError::nome_violation)
2407            .expect_err("Bad_Nome must fail validate_nome");
2408        let via_open_coded = c
2409            .validate_nome()
2410            .map_err(|err| LayoutError::nome_violation(&c, err))
2411            .expect_err("Bad_Nome must fail validate_nome");
2412        assert_eq!(
2413            via_primitive, via_open_coded,
2414            "Caixa::run_layout_gate must surface the err-arm diagnostic \
2415             byte-equal to the open-coded `.map_err(|err| CTOR(caixa, err))` \
2416             cascade on the same Caixa fixture"
2417        );
2418        assert!(
2419            matches!(via_primitive, LayoutError::NomeViolation { .. }),
2420            "expected NomeViolation on Bad_Nome, got {via_primitive:?}"
2421        );
2422    }
2423
2424    // ── LayoutError kind-coherence constructor family ────────────────────
2425    //
2426    // The [`layout_slot_kind_ctors!`] macro (sibling of
2427    // [`layout_violation_ctors!`] beside the `LayoutError` enum definition)
2428    // generates one static constructor per `*SlotsOn*` / `ForeignCodeSlot`
2429    // variant that folds the uniform `{ caixa: caixa.nome().to_string(),
2430    // kind: caixa.kind(), slots: slots.join(" ") }` four-field construction
2431    // onto one substrate primitive. The per-variant equivalence pins below
2432    // (fail-before-pass-after by construction — a byte-mismatched macro arm
2433    // would trip its equivalence pin first) lock each generated constructor
2434    // to its struct-literal peer under `PartialEq`, so every wire-up in
2435    // [`StandardLayout::verify`] on that variant produces a byte-equal
2436    // `LayoutError` to the pre-lift open-coded block. The three cross-axis
2437    // pins that follow (non-default `:nome`, non-default kind, non-trivial
2438    // slots list) route each of the three constructor input axes through
2439    // its declared accessor / arg, so the fold does not silently collapse
2440    // onto a fixture default on any axis.
2441
2442    fn layout_slot_kind_ctor_fixture() -> (Caixa, Vec<&'static str>) {
2443        (caixa(CaixaKind::Biblioteca), vec![":membros", ":contratos"])
2444    }
2445
2446    // Same rationale as `assert_violation_ctor_matches` above: the helper
2447    // terminates on the equality check, so the owned-arg lint's general
2448    // API-shape target does not apply.
2449    #[allow(clippy::needless_pass_by_value)]
2450    fn assert_slot_kind_ctor_matches(actual: LayoutError, expected: LayoutError) {
2451        assert_eq!(
2452            actual, expected,
2453            "generated constructor must produce byte-equal LayoutError to open-coded struct-literal wrap",
2454        );
2455    }
2456
2457    #[test]
2458    fn mesh_slots_on_non_aplicacao_ctor_matches_struct_literal_wrap() {
2459        let (c, slots) = layout_slot_kind_ctor_fixture();
2460        assert_slot_kind_ctor_matches(
2461            LayoutError::mesh_slots_on_non_aplicacao(&c, slots.clone()),
2462            LayoutError::MeshSlotsOnNonAplicacao {
2463                caixa: c.nome().to_string(),
2464                kind: c.kind(),
2465                slots: slots.join(" "),
2466            },
2467        );
2468    }
2469
2470    #[test]
2471    fn supervisor_slots_on_non_supervisor_ctor_matches_struct_literal_wrap() {
2472        let (c, slots) = layout_slot_kind_ctor_fixture();
2473        assert_slot_kind_ctor_matches(
2474            LayoutError::supervisor_slots_on_non_supervisor(&c, slots.clone()),
2475            LayoutError::SupervisorSlotsOnNonSupervisor {
2476                caixa: c.nome().to_string(),
2477                kind: c.kind(),
2478                slots: slots.join(" "),
2479            },
2480        );
2481    }
2482
2483    #[test]
2484    fn servico_slots_on_non_servico_ctor_matches_struct_literal_wrap() {
2485        let (c, slots) = layout_slot_kind_ctor_fixture();
2486        assert_slot_kind_ctor_matches(
2487            LayoutError::servico_slots_on_non_servico(&c, slots.clone()),
2488            LayoutError::ServicoSlotsOnNonServico {
2489                caixa: c.nome().to_string(),
2490                kind: c.kind(),
2491                slots: slots.join(" "),
2492            },
2493        );
2494    }
2495
2496    #[test]
2497    fn foreign_code_slot_ctor_matches_struct_literal_wrap() {
2498        let (c, slots) = layout_slot_kind_ctor_fixture();
2499        assert_slot_kind_ctor_matches(
2500            LayoutError::foreign_code_slot(&c, slots.clone()),
2501            LayoutError::ForeignCodeSlot {
2502                caixa: c.nome().to_string(),
2503                kind: c.kind(),
2504                slots: slots.join(" "),
2505            },
2506        );
2507    }
2508
2509    #[test]
2510    fn slot_kind_ctor_routes_caixa_prefix_through_nome_accessor() {
2511        // Pin the fold's `caixa = caixa.nome().to_string()` half against a
2512        // non-default `:nome` — the accessor threads the caller's `:nome`
2513        // verbatim into the wrap envelope, so the fold does not silently
2514        // collapse onto the default `"demo"` fixture nome. Peer of the
2515        // sibling `violation_ctor_routes_caixa_prefix_through_nome_accessor`
2516        // pin on the `{ caixa, issue }` envelope; extended here onto the
2517        // `{ caixa, kind, slots }` envelope so both `LayoutError`-shape
2518        // constructor families guarantee the `:nome`-derived-caixa slot
2519        // routes through [`Caixa::nome`] rather than a hard-coded string.
2520        let mut c = caixa(CaixaKind::Biblioteca);
2521        c.nome = "alt-nome".into();
2522        let actual = LayoutError::mesh_slots_on_non_aplicacao(&c, vec![":membros"]);
2523        assert_eq!(
2524            actual,
2525            LayoutError::MeshSlotsOnNonAplicacao {
2526                caixa: "alt-nome".to_string(),
2527                kind: CaixaKind::Biblioteca,
2528                slots: ":membros".to_string(),
2529            },
2530        );
2531    }
2532
2533    #[test]
2534    fn slot_kind_ctor_routes_kind_through_caixa_kind_accessor() {
2535        // Pin the fold's `kind = caixa.kind()` half against a non-default
2536        // kind — the accessor threads the caller's `:kind` verbatim into
2537        // the wrap envelope, so the fold does not silently collapse onto
2538        // one hard-coded kind. Sweeps every non-Aplicacao / non-Supervisor
2539        // / non-Servico kind the corresponding gate can fire on so the
2540        // pin covers the kind-derivation axis on every downstream variant.
2541        for kind in [
2542            CaixaKind::Biblioteca,
2543            CaixaKind::Binario,
2544            CaixaKind::Servico,
2545            CaixaKind::Supervisor,
2546            CaixaKind::Aplicacao,
2547            CaixaKind::Acao,
2548        ] {
2549            let c = caixa(kind);
2550            let actual = LayoutError::foreign_code_slot(&c, vec![":exe"]);
2551            assert_eq!(
2552                actual,
2553                LayoutError::ForeignCodeSlot {
2554                    caixa: c.nome().to_string(),
2555                    kind,
2556                    slots: ":exe".to_string(),
2557                },
2558                "foreign_code_slot ctor must thread `caixa.kind()` verbatim on every kind",
2559            );
2560        }
2561    }
2562
2563    #[test]
2564    fn slot_kind_ctor_routes_slots_through_join_separator() {
2565        // Pin the fold's `slots = slots.join(" ")` half against a
2566        // multi-entry slots list — the join threads exactly one ASCII
2567        // space between entries, in caller-supplied order, so the fold
2568        // does not silently collapse onto a fixed separator (`", "`, `";
2569        // "`, `"\n"`), a sorted order, or a single-entry pass-through.
2570        // Uses the M2 servico-slot vocabulary since these are what the
2571        // corresponding `servico_slots_on_non_servico` gate reports.
2572        let c = caixa(CaixaKind::Biblioteca);
2573        let actual = LayoutError::servico_slots_on_non_servico(
2574            &c,
2575            vec![":limits", ":behavior", ":upgrade-from"],
2576        );
2577        assert_eq!(
2578            actual,
2579            LayoutError::ServicoSlotsOnNonServico {
2580                caixa: c.nome().to_string(),
2581                kind: c.kind(),
2582                slots: ":limits :behavior :upgrade-from".to_string(),
2583            },
2584        );
2585    }
2586
2587    // ── LayoutError::missing_entry substrate-primitive constructor ───────
2588    //
2589    // The [`LayoutError::missing_entry`] constructor beside the enum
2590    // definition folds the `{ kind: &'static str, path: PathBuf }`
2591    // uniform-shape envelope onto one substrate primitive — the third
2592    // and last uniform-shape envelope on `LayoutError` after the
2593    // `{ caixa, issue }` family the [`layout_violation_ctors!`] macro
2594    // closed (131ca0d) and the `{ caixa, kind, slots }` family the peer
2595    // [`layout_slot_kind_ctors!`] macro closed (0419438). The pins below
2596    // (fail-before-pass-after by construction — a byte-mismatched
2597    // constructor arm would trip its equivalence pin first) lock the
2598    // constructor to its struct-literal peer under `PartialEq`, so every
2599    // wire-up in [`StandardLayout::verify`] on this variant produces a
2600    // byte-equal `LayoutError` to the pre-lift open-coded block. The two
2601    // cross-axis pins that follow (canonical-kind-label sweep, non-
2602    // default path) route each of the two constructor input axes through
2603    // its arg verbatim, so the fold does not silently collapse onto a
2604    // fixture default on either axis.
2605
2606    #[test]
2607    fn missing_entry_ctor_matches_struct_literal_wrap() {
2608        // Per-envelope equivalence pin — the `missing_entry` constructor
2609        // produces a `LayoutError::MissingEntry` byte-equal under
2610        // `PartialEq` to the open-coded four-line struct-literal wrap on
2611        // the same `(kind, path)` fixture. Peer of the sibling
2612        // `<slot>_violation_ctor_matches_struct_literal_wrap` /
2613        // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap`
2614        // pins on the two prior uniform-shape envelopes on the same
2615        // `LayoutError`.
2616        let path = PathBuf::from("/tmp/x/lib/demo.lisp");
2617        assert_eq!(
2618            LayoutError::missing_entry(
2619                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2620                path.clone(),
2621            ),
2622            LayoutError::MissingEntry {
2623                kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2624                path,
2625            },
2626        );
2627    }
2628
2629    #[test]
2630    fn missing_entry_ctor_routes_kind_through_arg_verbatim() {
2631        // Pin the fold's `kind: &'static str` arg through every canonical
2632        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] label the five
2633        // wire-up sites in [`StandardLayout::verify`] pass — so the fold
2634        // does not silently collapse onto one hard-coded label. Sweep
2635        // matches the arm set the peer
2636        // `layout_missing_entry_kind_m2_consts_pin_canonical_kebab_case_labels`
2637        // pin (below) covers on the const-label declarations.
2638        let path = PathBuf::from("/tmp/x/entry");
2639        for kind in [
2640            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2641            crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
2642            crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2643            crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
2644            crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
2645        ] {
2646            assert_eq!(
2647                LayoutError::missing_entry(kind, path.clone()),
2648                LayoutError::MissingEntry {
2649                    kind,
2650                    path: path.clone(),
2651                },
2652                "missing_entry ctor must thread `kind` verbatim on every canonical label",
2653            );
2654        }
2655    }
2656
2657    #[test]
2658    fn missing_entry_ctor_routes_path_through_arg_verbatim() {
2659        // Pin the fold's `path: PathBuf` arg against a non-default,
2660        // multi-component `PathBuf` — the ctor threads the caller's
2661        // `PathBuf` verbatim into the wrap envelope, so the fold does
2662        // not silently collapse onto a fixed component prefix, a
2663        // canonicalized form, or a single-component pass-through.
2664        let path = PathBuf::from("/alt/root")
2665            .join("servicos")
2666            .join("hello-rio.computeunit.yaml");
2667        assert_eq!(
2668            LayoutError::missing_entry(
2669                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2670                path.clone(),
2671            ),
2672            LayoutError::MissingEntry {
2673                kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2674                path,
2675            },
2676        );
2677    }
2678
2679    // ── StandardLayout::probe_declared_entry substrate primitive ─────────
2680    //
2681    // The [`StandardLayout::probe_declared_entry`] method
2682    // (`layout.rs`) folds the five self-similar
2683    // `let full = root.join(p); if !self.exists(&full) { return
2684    // Err(LayoutError::missing_entry(<kind>, full)); }` existence-probe
2685    // blocks at [`StandardLayout::verify`] (`:bibliotecas` iteration,
2686    // `:exe` iteration, `:servicos` iteration, `:behavior` on-disk
2687    // callback-path iteration, `:upgrade-from` per-instruction script-
2688    // path iteration) onto one substrate primitive. The pins below
2689    // (fail-before-pass-after by construction — a byte-mismatched
2690    // primitive body would trip its equivalence pin first) lock the
2691    // fold to its pre-lift open-coded shape under `PartialEq`, so every
2692    // wire-up in [`StandardLayout::verify`] on this primitive produces
2693    // a byte-equal `LayoutError` on miss and a byte-equal `PathBuf` on
2694    // hit.
2695
2696    #[test]
2697    fn probe_declared_entry_folds_miss_returns_missing_entry() {
2698        // Per-primitive equivalence pin on the miss arm — a
2699        // [`StandardLayout`] whose oracle returns `false` for every
2700        // path yields a `MissingEntry` byte-equal under `PartialEq` to
2701        // the open-coded `LayoutError::missing_entry(<kind>,
2702        // root.join(path))` wrap the pre-lift block carried at each of
2703        // the five wire-up sites. Peer of the sibling
2704        // `missing_entry_ctor_matches_struct_literal_wrap` pin on the
2705        // constructor's own byte-equal shape.
2706        let layout = StandardLayout::new().with_path_exists(|_| false);
2707        let root = PathBuf::from("/tmp/x");
2708        let path = Path::new("lib/demo.lisp");
2709        let err = layout
2710            .probe_declared_entry(
2711                path,
2712                &root,
2713                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2714            )
2715            .unwrap_err();
2716        assert_eq!(
2717            err,
2718            LayoutError::missing_entry(
2719                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2720                root.join(path),
2721            ),
2722            "probe_declared_entry miss arm must produce byte-equal LayoutError to \
2723             open-coded `missing_entry(<kind>, root.join(path))` wrap",
2724        );
2725    }
2726
2727    #[test]
2728    fn probe_declared_entry_folds_hit_returns_resolved_full() {
2729        // Per-primitive equivalence pin on the hit arm — a
2730        // [`StandardLayout`] whose oracle returns `true` for the probed
2731        // resolved path yields `Ok(root.join(path))` byte-equal under
2732        // `PartialEq`. The pre-lift `:exe` / `:servicos` wire-up sites
2733        // needed the resolved `full` for the follow-up sandbox-directory-
2734        // containment check; the fold preserves that hand-off through
2735        // the primitive's `Ok(PathBuf)` return arm rather than
2736        // re-computing `root.join(path)` at the follow-up gate.
2737        let root = PathBuf::from("/tmp/x");
2738        let path = Path::new("exe/tool.lisp");
2739        let full = root.join(path);
2740        let full_probe = full.clone();
2741        let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
2742        let resolved = layout
2743            .probe_declared_entry(path, &root, crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE)
2744            .expect("probe_declared_entry must return Ok(root.join(path)) when the oracle hits");
2745        assert_eq!(
2746            resolved, full,
2747            "probe_declared_entry hit arm must return the resolved `root.join(path)` \
2748             byte-equal so the `:exe` / `:servicos` sandbox-containment follow-up \
2749             reads it verbatim without re-computing",
2750        );
2751    }
2752
2753    #[test]
2754    fn probe_declared_entry_threads_kind_through_arg_verbatim() {
2755        // Cross-axis pin — sweep every canonical
2756        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] label the five
2757        // wire-up sites in [`StandardLayout::verify`] pass. Each miss
2758        // must return a `MissingEntry` whose `kind:` field byte-equals
2759        // the caller-provided arg, so the fold does not silently
2760        // collapse onto one hard-coded label. Sweep matches the arm
2761        // set the peer
2762        // `missing_entry_ctor_routes_kind_through_arg_verbatim` pin
2763        // covers on the constructor arg.
2764        let layout = StandardLayout::new().with_path_exists(|_| false);
2765        let root = PathBuf::from("/tmp/x");
2766        let path = Path::new("some/entry");
2767        for kind in [
2768            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2769            crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
2770            crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2771            crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
2772            crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
2773        ] {
2774            let err = layout.probe_declared_entry(path, &root, kind).unwrap_err();
2775            assert_eq!(
2776                err,
2777                LayoutError::missing_entry(kind, root.join(path)),
2778                "probe_declared_entry must thread `kind` verbatim on every canonical label",
2779            );
2780        }
2781    }
2782
2783    #[test]
2784    fn probe_declared_entry_threads_path_through_arg_verbatim() {
2785        // Cross-axis pin — the primitive must compose the `path` arg
2786        // through `root.join` verbatim on the miss arm's `MissingEntry
2787        // { path: … }` field, so the fold does not silently collapse
2788        // onto a fixed component prefix, a canonicalized form, or a
2789        // hand-authored `root.join(<literal>)`. Sweep two multi-
2790        // component `Path` fixtures (one under `servicos/`, one under
2791        // `lib/`) so a byte-drifted composition on either axis would
2792        // trip.
2793        let layout = StandardLayout::new().with_path_exists(|_| false);
2794        let root = PathBuf::from("/alt/root");
2795        for path in [
2796            Path::new("servicos/hello-rio.computeunit.yaml"),
2797            Path::new("lib/demo.lisp"),
2798        ] {
2799            let err = layout
2800                .probe_declared_entry(
2801                    path,
2802                    &root,
2803                    crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2804                )
2805                .unwrap_err();
2806            assert_eq!(
2807                err,
2808                LayoutError::missing_entry(
2809                    crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
2810                    root.join(path),
2811                ),
2812                "probe_declared_entry must compose `path` through `root.join` verbatim",
2813            );
2814        }
2815    }
2816
2817    #[test]
2818    fn probe_declared_entry_routes_through_configurable_exists_oracle() {
2819        // Cross-axis pin — the primitive must consult the injected
2820        // [`StandardLayout::with_path_exists`] oracle, not the ambient
2821        // `Path::exists` filesystem probe. Configure a per-path
2822        // discriminator that returns `true` only for one canonical
2823        // resolved path and assert both arms:
2824        // - the "hit" path resolves to `Ok(full)` byte-equal
2825        // - every other path resolves to `MissingEntry` on the same
2826        //   [`StandardLayout`] instance
2827        // The pin traps a regression that reroutes the primitive off
2828        // the injected oracle onto the ambient `Path::exists` (which
2829        // would silently return `false` for every path in `/tmp/x/…`
2830        // and mask the miss-arm hand-off on the hit fixture, or
2831        // silently return `true` for a real system path and mask the
2832        // hit-arm hand-off on the miss fixture).
2833        let root = PathBuf::from("/tmp/x");
2834        let hit_path = Path::new("servicos/keep.computeunit.yaml");
2835        let miss_path = Path::new("servicos/drop.computeunit.yaml");
2836        let hit_full = root.join(hit_path);
2837        let hit_full_probe = hit_full.clone();
2838        let layout = StandardLayout::new().with_path_exists(move |p| p == hit_full_probe);
2839
2840        let resolved = layout
2841            .probe_declared_entry(
2842                hit_path,
2843                &root,
2844                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2845            )
2846            .expect("probe_declared_entry must consult the injected oracle on the hit arm");
2847        assert_eq!(
2848            resolved, hit_full,
2849            "probe_declared_entry hit arm must return the oracle-approved resolved path",
2850        );
2851
2852        let err = layout
2853            .probe_declared_entry(
2854                miss_path,
2855                &root,
2856                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2857            )
2858            .unwrap_err();
2859        assert_eq!(
2860            err,
2861            LayoutError::missing_entry(
2862                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
2863                root.join(miss_path),
2864            ),
2865            "probe_declared_entry miss arm must fire when the injected oracle rejects the path",
2866        );
2867    }
2868
2869    // ── StandardLayout::probe_sandboxed_declared_entry substrate primitive ─
2870    //
2871    // The [`StandardLayout::probe_sandboxed_declared_entry`] method
2872    // (`layout.rs`) folds the two self-similar `let full = self.
2873    // probe_declared_entry(p, root, <kind>)?; if !full.starts_with(&<slot>_dir)
2874    // { return Err(LayoutError::<Slot>OutsideDir(full)); }` blocks at
2875    // [`StandardLayout::verify`] (`:exe` iteration, `:servicos` iteration)
2876    // onto one substrate primitive. The pins below (fail-before-pass-after
2877    // by construction — a byte-mismatched primitive body would trip its
2878    // equivalence pin first) lock the fold to its pre-lift open-coded
2879    // shape under `PartialEq`, so every wire-up in
2880    // [`StandardLayout::verify`] on this primitive produces a byte-equal
2881    // `LayoutError` on miss / sandbox-escape and a byte-equal `PathBuf`
2882    // on hit.
2883
2884    #[test]
2885    fn probe_sandboxed_declared_entry_folds_miss_returns_missing_entry() {
2886        // Per-primitive equivalence pin on the miss arm — a
2887        // [`StandardLayout`] whose oracle returns `false` for every
2888        // path yields a `MissingEntry` byte-equal under `PartialEq` to
2889        // the open-coded `LayoutError::missing_entry(<kind>,
2890        // root.join(path))` wrap the sibling
2891        // [`StandardLayout::probe_declared_entry`] primitive routes
2892        // through. Diagnostic-order pin: `MissingEntry` outranks the
2893        // `outside_ctor` sandbox-escape arm on the same iteration, so
2894        // an entry that is both absent *and* outside the sandbox fires
2895        // the `MissingEntry` diagnostic (the pre-lift order the two
2896        // wire-up sites carried).
2897        let layout = StandardLayout::new().with_path_exists(|_| false);
2898        let root = PathBuf::from("/tmp/x");
2899        let path = Path::new("lib/tool");
2900        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
2901        let err = layout
2902            .probe_sandboxed_declared_entry(
2903                path,
2904                &root,
2905                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
2906                &exe_dir,
2907                LayoutError::ExeOutsideDir,
2908            )
2909            .unwrap_err();
2910        assert_eq!(
2911            err,
2912            LayoutError::missing_entry(
2913                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
2914                root.join(path),
2915            ),
2916            "probe_sandboxed_declared_entry miss arm must produce byte-equal \
2917             LayoutError to the sibling probe_declared_entry primitive's miss wrap, \
2918             preserving the pre-lift MissingEntry-before-<Slot>OutsideDir diagnostic order",
2919        );
2920    }
2921
2922    #[test]
2923    fn probe_sandboxed_declared_entry_folds_sandbox_escape_via_outside_ctor() {
2924        // Per-primitive equivalence pin on the sandbox-escape arm — a
2925        // [`StandardLayout`] whose oracle admits the probed resolved
2926        // path (so the miss arm passes) but whose resolved path lies
2927        // outside the caller-provided `sandbox_dir` yields the paired
2928        // `outside_ctor(full)` byte-equal under `PartialEq`. The
2929        // primitive threads the resolved `full` through the caller-
2930        // supplied `fn(PathBuf) -> LayoutError` constructor rather
2931        // than a hard-coded variant, so the fold does not silently
2932        // collapse onto one of the two `:exe` / `:servicos` outside-
2933        // dir variants.
2934        let root = PathBuf::from("/tmp/x");
2935        let path = Path::new("lib/tool");
2936        let full = root.join(path);
2937        let full_probe = full.clone();
2938        let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
2939        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
2940        let err = layout
2941            .probe_sandboxed_declared_entry(
2942                path,
2943                &root,
2944                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
2945                &exe_dir,
2946                LayoutError::ExeOutsideDir,
2947            )
2948            .unwrap_err();
2949        assert_eq!(
2950            err,
2951            LayoutError::ExeOutsideDir(full),
2952            "probe_sandboxed_declared_entry sandbox-escape arm must route the \
2953             resolved `full` through the caller-supplied outside_ctor byte-equal to \
2954             the pre-lift `LayoutError::ExeOutsideDir(full)` tuple-literal",
2955        );
2956    }
2957
2958    #[test]
2959    fn probe_sandboxed_declared_entry_folds_hit_returns_resolved_full() {
2960        // Per-primitive equivalence pin on the hit arm — a
2961        // [`StandardLayout`] whose oracle admits the probed path *and*
2962        // whose resolved path lives inside `sandbox_dir` yields
2963        // `Ok(root.join(path))` byte-equal under `PartialEq`. The
2964        // pre-lift wire-ups discarded the resolved `Ok(PathBuf)` since
2965        // no follow-up per-path gate consumes it after the sandbox
2966        // check; the fold preserves the same hit-arm hand-off through
2967        // the primitive's `Ok(PathBuf)` return so a future consumer
2968        // that wants to run a per-path successor gate reaches the
2969        // resolved path without re-computing `root.join(path)`.
2970        let root = PathBuf::from("/tmp/x");
2971        let path = Path::new("exe/tool");
2972        let full = root.join(path);
2973        let full_probe = full.clone();
2974        let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
2975        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
2976        let resolved = layout
2977            .probe_sandboxed_declared_entry(
2978                path,
2979                &root,
2980                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
2981                &exe_dir,
2982                LayoutError::ExeOutsideDir,
2983            )
2984            .expect(
2985                "probe_sandboxed_declared_entry must return Ok(root.join(path)) \
2986                 when the oracle admits the path and it lives inside sandbox_dir",
2987            );
2988        assert_eq!(
2989            resolved, full,
2990            "probe_sandboxed_declared_entry hit arm must return the resolved \
2991             `root.join(path)` byte-equal so a future per-path successor gate \
2992             reaches it without re-computing",
2993        );
2994    }
2995
2996    #[test]
2997    fn probe_sandboxed_declared_entry_threads_outside_ctor_through_arg_verbatim() {
2998        // Cross-axis pin — the primitive must thread the caller-
2999        // supplied `outside_ctor` verbatim into the sandbox-escape
3000        // arm's `LayoutError` return, so the fold does not silently
3001        // collapse onto one hard-coded variant. Sweep both
3002        // [`LayoutError`] tuple-variants the two wire-up sites in
3003        // [`StandardLayout::verify`] pass — [`LayoutError::ExeOutsideDir`]
3004        // and [`LayoutError::ServicoOutsideDir`] — so a byte-drifted
3005        // ctor-routing on either axis would trip.
3006        let root = PathBuf::from("/tmp/x");
3007        let outside_dir = root.join(crate::render::LAYOUT_DIR_LIB);
3008        for (kind, sandbox_component, ctor, expected_variant) in [
3009            (
3010                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3011                crate::render::LAYOUT_DIR_EXE,
3012                LayoutError::ExeOutsideDir as fn(PathBuf) -> LayoutError,
3013                LayoutError::ExeOutsideDir as fn(PathBuf) -> LayoutError,
3014            ),
3015            (
3016                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3017                crate::render::LAYOUT_DIR_SERVICOS,
3018                LayoutError::ServicoOutsideDir as fn(PathBuf) -> LayoutError,
3019                LayoutError::ServicoOutsideDir as fn(PathBuf) -> LayoutError,
3020            ),
3021        ] {
3022            let path = outside_dir.strip_prefix(&root).unwrap().join("tool");
3023            let full = root.join(&path);
3024            let full_probe = full.clone();
3025            let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3026            let sandbox_dir = root.join(sandbox_component);
3027            let err = layout
3028                .probe_sandboxed_declared_entry(&path, &root, kind, &sandbox_dir, ctor)
3029                .unwrap_err();
3030            assert_eq!(
3031                err,
3032                expected_variant(full),
3033                "probe_sandboxed_declared_entry must thread `outside_ctor` verbatim \
3034                 on every canonical `<Slot>OutsideDir` variant the two wire-up sites pass",
3035            );
3036        }
3037    }
3038
3039    #[test]
3040    fn probe_sandboxed_declared_entry_routes_miss_arm_through_probe_declared_entry() {
3041        // Cross-primitive pin — the sandboxed probe must route its
3042        // miss arm through the sibling [`StandardLayout::
3043        // probe_declared_entry`] primitive rather than re-inlining the
3044        // `root.join` + `exists` + `missing_entry` cascade, so a
3045        // future edit to the miss-arm shape on either primitive lands
3046        // in exactly one place. Byte-parity assertion: on a fixture
3047        // that misses the oracle, the sandboxed primitive's `Err`
3048        // arm must equal the peer [`StandardLayout::
3049        // probe_declared_entry`] primitive's `Err` arm on the same
3050        // fixture — otherwise the fold has drifted from the substrate
3051        // primitive.
3052        let layout = StandardLayout::new().with_path_exists(|_| false);
3053        let root = PathBuf::from("/tmp/x");
3054        let path = Path::new("servicos/hello-rio.computeunit.yaml");
3055        let sandbox_dir = root.join(crate::render::LAYOUT_DIR_SERVICOS);
3056        let via_sandboxed = layout
3057            .probe_sandboxed_declared_entry(
3058                path,
3059                &root,
3060                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3061                &sandbox_dir,
3062                LayoutError::ServicoOutsideDir,
3063            )
3064            .unwrap_err();
3065        let via_probe = layout
3066            .probe_declared_entry(
3067                path,
3068                &root,
3069                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3070            )
3071            .unwrap_err();
3072        assert_eq!(
3073            via_sandboxed, via_probe,
3074            "probe_sandboxed_declared_entry's miss arm must equal the sibling \
3075             probe_declared_entry primitive's miss arm byte-equal — pins that the \
3076             sandboxed primitive routes through the substrate primitive rather than \
3077             re-inlining the `root.join` + `exists` + `missing_entry` cascade",
3078        );
3079    }
3080
3081    // ── StandardLayout::probe_declared_entries substrate primitive ───────
3082    //
3083    // The [`StandardLayout::probe_declared_entries`] method (`layout.rs`)
3084    // folds the three self-similar per-slot existence-probe *loop* blocks
3085    // at [`StandardLayout::verify`] (`:bibliotecas` iteration,
3086    // `:behavior` on-disk callback-path iteration, `:upgrade-from` per-
3087    // instruction script-path iteration) onto one substrate primitive.
3088    // The pins below (fail-before-pass-after by construction — a byte-
3089    // mismatched primitive body would trip its equivalence pin first)
3090    // lock the fold to its pre-lift open-coded shape under `PartialEq`,
3091    // so every wire-up in [`StandardLayout::verify`] on this primitive
3092    // produces a byte-equal `LayoutError` on miss (via the sibling
3093    // [`StandardLayout::probe_declared_entry`] miss arm) and a byte-
3094    // equal `Ok(())` on the empty / all-hit arms (the fold's identity
3095    // element on an empty slot list; the pre-lift `for … { … }` loop's
3096    // vacuous pass-through).
3097    //
3098    // Sibling of the peer per-arm-probe [`StandardLayout::probe_declared_entry`]
3099    // (fda1e35) and two-arm-sandboxed [`StandardLayout::
3100    // probe_sandboxed_declared_entry`] (4940d55) primitive test blocks
3101    // — same substrate-primitive discipline extended onto the per-slot
3102    // batch axis these two per-path primitives compose under.
3103
3104    #[test]
3105    fn probe_declared_entries_folds_empty_iterator_returns_ok() {
3106        // Per-primitive identity-element pin on the empty-iterator arm —
3107        // the fold's `Ok(())` return on an empty `IntoIterator` is byte-
3108        // equal to the pre-lift `for _ in <empty> { … }` loop's vacuous
3109        // pass-through. Peer of the peer-primitive `Option::None →
3110        // Ok(())` identity elements the sibling per-Caixa compound
3111        // gates ([`crate::Caixa::validate_limits`] baa4688,
3112        // [`crate::Caixa::validate_behavior`] 0d2877a) each carry on
3113        // the sibling per-slot compound-gate axis.
3114        let layout = StandardLayout::new().with_path_exists(|_| false);
3115        let root = PathBuf::from("/tmp/x");
3116        let empty: [&Path; 0] = [];
3117        layout
3118            .probe_declared_entries(
3119                empty,
3120                &root,
3121                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3122            )
3123            .expect(
3124                "probe_declared_entries must return Ok(()) on an empty iterator \
3125                 — the fold's identity element on an empty per-slot batch",
3126            );
3127    }
3128
3129    #[test]
3130    fn probe_declared_entries_folds_all_hits_returns_ok() {
3131        // Per-primitive equivalence pin on the all-hit arm — a
3132        // [`StandardLayout`] whose oracle admits every path in the batch
3133        // yields `Ok(())` byte-equal to the pre-lift `for p in … {
3134        // self.probe_declared_entry(p, root, kind)?; }` loop's full-
3135        // consumption pass-through.
3136        let root = PathBuf::from("/tmp/x");
3137        let a = root.join("lib/a.lisp");
3138        let b = root.join("lib/b.lisp");
3139        let a_probe = a.clone();
3140        let b_probe = b.clone();
3141        let layout = StandardLayout::new().with_path_exists(move |p| p == a_probe || p == b_probe);
3142        layout
3143            .probe_declared_entries(
3144                [Path::new("lib/a.lisp"), Path::new("lib/b.lisp")],
3145                &root,
3146                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3147            )
3148            .expect(
3149                "probe_declared_entries must return Ok(()) when every path in the \
3150                 batch is admitted by the oracle",
3151            );
3152    }
3153
3154    #[test]
3155    fn probe_declared_entries_folds_first_miss_short_circuits_via_probe_declared_entry() {
3156        // Per-primitive equivalence pin on the first-miss arm — a
3157        // [`StandardLayout`] whose oracle admits the first path and
3158        // rejects the second yields a `MissingEntry` byte-equal under
3159        // `PartialEq` to the sibling [`StandardLayout::
3160        // probe_declared_entry`] primitive's miss wrap on the *second*
3161        // path (the pre-lift `for … { … ? }` loop's first-error return
3162        // semantics), *not* on the first (admitted) path.
3163        let root = PathBuf::from("/tmp/x");
3164        let hit = root.join("lib/a.lisp");
3165        let hit_probe = hit.clone();
3166        let layout = StandardLayout::new().with_path_exists(move |p| p == hit_probe);
3167        let miss = Path::new("lib/b.lisp");
3168        let err = layout
3169            .probe_declared_entries(
3170                [Path::new("lib/a.lisp"), miss],
3171                &root,
3172                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3173            )
3174            .unwrap_err();
3175        assert_eq!(
3176            err,
3177            LayoutError::missing_entry(
3178                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3179                root.join(miss),
3180            ),
3181            "probe_declared_entries must short-circuit on the first missing entry \
3182             with a `MissingEntry` byte-equal to the sibling probe_declared_entry \
3183             primitive's miss wrap on that entry — the pre-lift `for … {{ … ? }}` \
3184             loop's first-error return semantics",
3185        );
3186    }
3187
3188    #[test]
3189    fn probe_declared_entries_folds_first_miss_short_circuits_before_later_paths() {
3190        // Diagnostic-order pin — the primitive must return on the *first*
3191        // miss in iterator order rather than probing every path and
3192        // returning the last miss (which would silently drop the pre-
3193        // lift `for … { … ? }` loop's first-error contract). Fixture:
3194        // the oracle rejects both paths, so a byte-equal `MissingEntry`
3195        // on the *first* path in the iterator distinguishes the two
3196        // return-order shapes.
3197        let layout = StandardLayout::new().with_path_exists(|_| false);
3198        let root = PathBuf::from("/tmp/x");
3199        let first = Path::new("lib/first.lisp");
3200        let second = Path::new("lib/second.lisp");
3201        let err = layout
3202            .probe_declared_entries(
3203                [first, second],
3204                &root,
3205                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3206            )
3207            .unwrap_err();
3208        assert_eq!(
3209            err,
3210            LayoutError::missing_entry(
3211                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3212                root.join(first),
3213            ),
3214            "probe_declared_entries must return on the *first* miss in iterator order \
3215             — a `MissingEntry` on the second path would silently drop the pre-lift \
3216             `for … {{ … ? }}` loop's first-error contract",
3217        );
3218    }
3219
3220    #[test]
3221    fn probe_declared_entries_threads_kind_through_arg_verbatim() {
3222        // Cross-axis pin — sweep every canonical
3223        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] label the three
3224        // batch wire-up sites in [`StandardLayout::verify`] pass through
3225        // this primitive (`:bibliotecas`, `:behavior` callback,
3226        // `:upgrade-from` script). Each miss must return a `MissingEntry`
3227        // whose `kind:` field byte-equals the caller-provided arg, so
3228        // the fold does not silently collapse onto one hard-coded label.
3229        // Sibling of the peer `probe_declared_entry_threads_kind_through_arg_verbatim`
3230        // pin's five-label sweep on the per-arm primitive.
3231        let layout = StandardLayout::new().with_path_exists(|_| false);
3232        let root = PathBuf::from("/tmp/x");
3233        let path = Path::new("some/entry");
3234        for kind in [
3235            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3236            crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
3237            crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
3238        ] {
3239            let err = layout
3240                .probe_declared_entries([path], &root, kind)
3241                .unwrap_err();
3242            assert_eq!(
3243                err,
3244                LayoutError::missing_entry(kind, root.join(path)),
3245                "probe_declared_entries must thread `kind` verbatim on every canonical \
3246                 batch label",
3247            );
3248        }
3249    }
3250
3251    #[test]
3252    fn probe_declared_entries_accepts_asref_path_shape_wire_up_sites_pass() {
3253        // Cross-axis pin — the primitive's `P: AsRef<Path>` bound must
3254        // admit every concrete iterator element type the three
3255        // [`StandardLayout::verify`] wire-up sites pass:
3256        // - `&String` (from `caixa.bibliotecas(): &[String]`),
3257        // - `&Path` (from `b.declared_paths(): impl Iterator<Item = &Path>`),
3258        // - `&PathBuf` (from the flattened `.filter_map(_::declared_path)`
3259        //   on `:upgrade-from` instructions, whose `declared_path`
3260        //   returns `Option<&PathBuf>`).
3261        //
3262        // Byte-parity assertion: on a shared `/tmp/x/lib/demo.lisp`
3263        // fixture the miss-arm return must be byte-equal across all
3264        // three element-type flavors, so a future re-shape of the
3265        // bound (a narrower `P: Into<PathBuf>` collapse, a stricter
3266        // `&Path`-only signature) would surface here rather than at
3267        // the caller wire-up site.
3268        let layout = StandardLayout::new().with_path_exists(|_| false);
3269        let root = PathBuf::from("/tmp/x");
3270        let literal = "lib/demo.lisp";
3271        let expected = LayoutError::missing_entry(
3272            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3273            root.join(Path::new(literal)),
3274        );
3275
3276        let via_string_slice: Vec<String> = vec![literal.to_string()];
3277        let via_string_err = layout
3278            .probe_declared_entries(
3279                via_string_slice.iter(),
3280                &root,
3281                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3282            )
3283            .unwrap_err();
3284        assert_eq!(
3285            via_string_err, expected,
3286            "probe_declared_entries must accept `&String` items (the `caixa.bibliotecas() \
3287             : &[String]` wire-up shape)",
3288        );
3289
3290        let via_path_slice: [&Path; 1] = [Path::new(literal)];
3291        let via_path_err = layout
3292            .probe_declared_entries(
3293                via_path_slice,
3294                &root,
3295                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3296            )
3297            .unwrap_err();
3298        assert_eq!(
3299            via_path_err, expected,
3300            "probe_declared_entries must accept `&Path` items (the `b.declared_paths() \
3301             : impl Iterator<Item = &Path>` wire-up shape)",
3302        );
3303
3304        let via_pathbuf_slice: Vec<PathBuf> = vec![PathBuf::from(literal)];
3305        let via_pathbuf_err = layout
3306            .probe_declared_entries(
3307                via_pathbuf_slice.iter(),
3308                &root,
3309                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3310            )
3311            .unwrap_err();
3312        assert_eq!(
3313            via_pathbuf_err, expected,
3314            "probe_declared_entries must accept `&PathBuf` items (the `.filter_map( \
3315             _::declared_path)` on `:upgrade-from` instructions wire-up shape)",
3316        );
3317    }
3318
3319    #[test]
3320    fn probe_declared_entries_routes_miss_arm_through_probe_declared_entry() {
3321        // Cross-primitive pin — the batch primitive must route its miss
3322        // arm through the sibling [`StandardLayout::probe_declared_entry`]
3323        // primitive rather than re-inlining the `root.join` + `exists`
3324        // + `missing_entry` cascade, so a future edit to the miss-arm
3325        // shape on either primitive lands in exactly one place. Byte-
3326        // parity assertion: on a fixture that misses the oracle, the
3327        // batch primitive's `Err` arm must equal the peer per-arm
3328        // [`StandardLayout::probe_declared_entry`] primitive's `Err` arm
3329        // on the same fixture — otherwise the batch fold has drifted
3330        // from the substrate primitive. Same discipline the peer
3331        // `probe_sandboxed_declared_entry_routes_miss_arm_through_probe_declared_entry`
3332        // pin establishes on the sibling sandboxed-primitive axis.
3333        let layout = StandardLayout::new().with_path_exists(|_| false);
3334        let root = PathBuf::from("/tmp/x");
3335        let path = Path::new("lib/demo.lisp");
3336        let via_batch = layout
3337            .probe_declared_entries(
3338                [path],
3339                &root,
3340                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3341            )
3342            .unwrap_err();
3343        let via_probe = layout
3344            .probe_declared_entry(
3345                path,
3346                &root,
3347                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
3348            )
3349            .unwrap_err();
3350        assert_eq!(
3351            via_batch, via_probe,
3352            "probe_declared_entries's miss arm must equal the sibling probe_declared_entry \
3353             primitive's miss arm byte-equal — pins that the batch primitive routes \
3354             through the substrate primitive rather than re-inlining the `root.join` + \
3355             `exists` + `missing_entry` cascade",
3356        );
3357    }
3358
3359    // ── StandardLayout::probe_sandboxed_declared_entries substrate primitive ─
3360    //
3361    // The [`StandardLayout::probe_sandboxed_declared_entries`] method
3362    // (`layout.rs`) folds the two self-similar per-slot sandboxed-
3363    // existence-probe *loop* blocks at [`StandardLayout::verify`]
3364    // (`:exe` iteration, `:servicos` iteration) onto one substrate
3365    // primitive. The pins below (fail-before-pass-after by construction
3366    // — a byte-mismatched primitive body would trip its equivalence pin
3367    // first) lock the fold to its pre-lift open-coded shape under
3368    // `PartialEq`, so every wire-up in [`StandardLayout::verify`] on
3369    // this primitive produces a byte-equal `LayoutError` on miss / on
3370    // sandbox-escape (via the sibling
3371    // [`StandardLayout::probe_sandboxed_declared_entry`] arms) and a
3372    // byte-equal `Ok(())` on the empty / all-hit arms (the fold's
3373    // identity element on an empty slot list; the pre-lift `for … {
3374    // … }` loop's vacuous pass-through).
3375    //
3376    // Sibling of the peer per-slot batch bare-probe
3377    // [`StandardLayout::probe_declared_entries`] (d1ccb0b), per-arm
3378    // bare-probe [`StandardLayout::probe_declared_entry`] (fda1e35), and
3379    // per-arm sandboxed-probe
3380    // [`StandardLayout::probe_sandboxed_declared_entry`] (4940d55)
3381    // primitive test blocks — same substrate-primitive discipline
3382    // extended onto the fourth and last quadrant of the
3383    // (per-arm | per-slot batch) × (bare | sandboxed) existence-probe
3384    // algebra.
3385
3386    #[test]
3387    fn probe_sandboxed_declared_entries_folds_empty_iterator_returns_ok() {
3388        // Per-primitive identity-element pin on the empty-iterator arm —
3389        // the fold's `Ok(())` return on an empty `IntoIterator` is byte-
3390        // equal to the pre-lift `for _ in <empty> { … }` loop's vacuous
3391        // pass-through. Peer of the sibling
3392        // `probe_declared_entries_folds_empty_iterator_returns_ok` pin
3393        // on the bare-batch axis and the `Option::None → Ok(())`
3394        // identity elements the per-Caixa compound gates
3395        // ([`crate::Caixa::validate_limits`] baa4688,
3396        // [`crate::Caixa::validate_behavior`] 0d2877a) each carry on the
3397        // per-slot compound-gate axis.
3398        let layout = StandardLayout::new().with_path_exists(|_| false);
3399        let root = PathBuf::from("/tmp/x");
3400        let empty: [&Path; 0] = [];
3401        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3402        layout
3403            .probe_sandboxed_declared_entries(
3404                empty,
3405                &root,
3406                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3407                &exe_dir,
3408                LayoutError::ExeOutsideDir,
3409            )
3410            .expect(
3411                "probe_sandboxed_declared_entries must return Ok(()) on an empty iterator \
3412                 — the fold's identity element on an empty per-slot sandboxed batch",
3413            );
3414    }
3415
3416    #[test]
3417    fn probe_sandboxed_declared_entries_folds_all_hits_returns_ok() {
3418        // Per-primitive equivalence pin on the all-hit arm — a
3419        // [`StandardLayout`] whose oracle admits every path in the batch
3420        // *and* whose resolved paths live inside `sandbox_dir` yields
3421        // `Ok(())` byte-equal to the pre-lift `for p in … {
3422        // self.probe_sandboxed_declared_entry(p, root, kind,
3423        // &sandbox_dir, outside_ctor)?; }` loop's full-consumption
3424        // pass-through.
3425        let root = PathBuf::from("/tmp/x");
3426        let a = root.join("exe/a");
3427        let b = root.join("exe/b");
3428        let a_probe = a.clone();
3429        let b_probe = b.clone();
3430        let layout = StandardLayout::new().with_path_exists(move |p| p == a_probe || p == b_probe);
3431        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3432        layout
3433            .probe_sandboxed_declared_entries(
3434                [Path::new("exe/a"), Path::new("exe/b")],
3435                &root,
3436                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3437                &exe_dir,
3438                LayoutError::ExeOutsideDir,
3439            )
3440            .expect(
3441                "probe_sandboxed_declared_entries must return Ok(()) when every path in \
3442                 the batch is admitted by the oracle and lives inside sandbox_dir",
3443            );
3444    }
3445
3446    #[test]
3447    fn probe_sandboxed_declared_entries_folds_first_miss_short_circuits_via_probe_sandboxed_declared_entry()
3448     {
3449        // Per-primitive equivalence pin on the first-miss arm — a
3450        // [`StandardLayout`] whose oracle admits the first path (inside
3451        // sandbox_dir) and rejects the second yields a `MissingEntry`
3452        // byte-equal under `PartialEq` to the sibling
3453        // [`StandardLayout::probe_sandboxed_declared_entry`] primitive's
3454        // miss wrap on the *second* path (the pre-lift `for … { … ? }`
3455        // loop's first-error return semantics), *not* on the first
3456        // (admitted) path.
3457        let root = PathBuf::from("/tmp/x");
3458        let hit = root.join("exe/a");
3459        let hit_probe = hit.clone();
3460        let layout = StandardLayout::new().with_path_exists(move |p| p == hit_probe);
3461        let miss = Path::new("exe/b");
3462        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3463        let err = layout
3464            .probe_sandboxed_declared_entries(
3465                [Path::new("exe/a"), miss],
3466                &root,
3467                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3468                &exe_dir,
3469                LayoutError::ExeOutsideDir,
3470            )
3471            .unwrap_err();
3472        assert_eq!(
3473            err,
3474            LayoutError::missing_entry(
3475                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3476                root.join(miss),
3477            ),
3478            "probe_sandboxed_declared_entries must short-circuit on the first missing \
3479             entry with a `MissingEntry` byte-equal to the sibling \
3480             probe_sandboxed_declared_entry primitive's miss wrap on that entry — the \
3481             pre-lift `for … {{ … ? }}` loop's first-error return semantics",
3482        );
3483    }
3484
3485    #[test]
3486    fn probe_sandboxed_declared_entries_folds_first_miss_short_circuits_before_later_paths() {
3487        // Diagnostic-order pin — the primitive must return on the *first*
3488        // miss in iterator order rather than probing every path and
3489        // returning the last miss (which would silently drop the pre-
3490        // lift `for … { … ? }` loop's first-error contract). Fixture:
3491        // the oracle rejects both paths, so a byte-equal `MissingEntry`
3492        // on the *first* path in the iterator distinguishes the two
3493        // return-order shapes. Sibling of the peer
3494        // `probe_declared_entries_folds_first_miss_short_circuits_before_later_paths`
3495        // pin on the bare-batch axis.
3496        let layout = StandardLayout::new().with_path_exists(|_| false);
3497        let root = PathBuf::from("/tmp/x");
3498        let first = Path::new("exe/first");
3499        let second = Path::new("exe/second");
3500        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3501        let err = layout
3502            .probe_sandboxed_declared_entries(
3503                [first, second],
3504                &root,
3505                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3506                &exe_dir,
3507                LayoutError::ExeOutsideDir,
3508            )
3509            .unwrap_err();
3510        assert_eq!(
3511            err,
3512            LayoutError::missing_entry(
3513                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3514                root.join(first),
3515            ),
3516            "probe_sandboxed_declared_entries must return on the *first* miss in iterator \
3517             order — a `MissingEntry` on the second path would silently drop the pre-lift \
3518             `for … {{ … ? }}` loop's first-error contract",
3519        );
3520    }
3521
3522    #[test]
3523    fn probe_sandboxed_declared_entries_folds_sandbox_escape_via_outside_ctor() {
3524        // Per-primitive equivalence pin on the sandbox-escape arm — a
3525        // [`StandardLayout`] whose oracle admits the probed resolved
3526        // path (so the miss arm passes) but whose resolved path lies
3527        // outside the caller-provided `sandbox_dir` yields the paired
3528        // `outside_ctor(full)` byte-equal under `PartialEq`. The
3529        // primitive threads the resolved `full` through the caller-
3530        // supplied `fn(PathBuf) -> LayoutError` constructor rather than
3531        // a hard-coded variant, so the fold does not silently collapse
3532        // onto one of the two `:exe` / `:servicos` outside-dir variants.
3533        let root = PathBuf::from("/tmp/x");
3534        let path = Path::new("lib/tool");
3535        let full = root.join(path);
3536        let full_probe = full.clone();
3537        let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3538        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3539        let err = layout
3540            .probe_sandboxed_declared_entries(
3541                [path],
3542                &root,
3543                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3544                &exe_dir,
3545                LayoutError::ExeOutsideDir,
3546            )
3547            .unwrap_err();
3548        assert_eq!(
3549            err,
3550            LayoutError::ExeOutsideDir(full),
3551            "probe_sandboxed_declared_entries sandbox-escape arm must route the resolved \
3552             `full` through the caller-supplied outside_ctor byte-equal to the pre-lift \
3553             `LayoutError::ExeOutsideDir(full)` tuple-literal",
3554        );
3555    }
3556
3557    #[test]
3558    fn probe_sandboxed_declared_entries_threads_outside_ctor_through_arg_verbatim() {
3559        // Cross-axis pin — the primitive must thread the caller-supplied
3560        // `outside_ctor` verbatim into the sandbox-escape arm's
3561        // `LayoutError` return, so the fold does not silently collapse
3562        // onto one hard-coded variant. Sweep both [`LayoutError`]
3563        // tuple-variants the two wire-up sites in
3564        // [`StandardLayout::verify`] pass — [`LayoutError::ExeOutsideDir`]
3565        // and [`LayoutError::ServicoOutsideDir`] — so a byte-drifted
3566        // ctor-routing on either axis would trip. Sibling of the peer
3567        // `probe_sandboxed_declared_entry_threads_outside_ctor_through_arg_verbatim`
3568        // pin on the per-arm sandboxed-primitive axis.
3569        let root = PathBuf::from("/tmp/x");
3570        let outside_dir = root.join(crate::render::LAYOUT_DIR_LIB);
3571        for (kind, sandbox_component, ctor) in [
3572            (
3573                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3574                crate::render::LAYOUT_DIR_EXE,
3575                LayoutError::ExeOutsideDir as fn(PathBuf) -> LayoutError,
3576            ),
3577            (
3578                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3579                crate::render::LAYOUT_DIR_SERVICOS,
3580                LayoutError::ServicoOutsideDir as fn(PathBuf) -> LayoutError,
3581            ),
3582        ] {
3583            let path = outside_dir.strip_prefix(&root).unwrap().join("tool");
3584            let full = root.join(&path);
3585            let full_probe = full.clone();
3586            let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3587            let sandbox_dir = root.join(sandbox_component);
3588            let err = layout
3589                .probe_sandboxed_declared_entries([&path], &root, kind, &sandbox_dir, ctor)
3590                .unwrap_err();
3591            assert_eq!(
3592                err,
3593                ctor(full),
3594                "probe_sandboxed_declared_entries must thread `outside_ctor` verbatim on \
3595                 every canonical `<Slot>OutsideDir` variant the two wire-up sites pass",
3596            );
3597        }
3598    }
3599
3600    #[test]
3601    fn probe_sandboxed_declared_entries_threads_kind_through_arg_verbatim() {
3602        // Cross-axis pin — sweep every canonical
3603        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_*`] label the two
3604        // sandboxed-batch wire-up sites in [`StandardLayout::verify`]
3605        // pass through this primitive (`:exe`, `:servicos`). Each miss
3606        // must return a `MissingEntry` whose `kind:` field byte-equals
3607        // the caller-provided arg, so the fold does not silently
3608        // collapse onto one hard-coded label. Sibling of the peer
3609        // `probe_declared_entries_threads_kind_through_arg_verbatim`
3610        // pin's label sweep on the bare-batch axis.
3611        let layout = StandardLayout::new().with_path_exists(|_| false);
3612        let root = PathBuf::from("/tmp/x");
3613        let path = Path::new("some/entry");
3614        for (kind, sandbox_component, ctor) in [
3615            (
3616                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3617                crate::render::LAYOUT_DIR_EXE,
3618                LayoutError::ExeOutsideDir as fn(PathBuf) -> LayoutError,
3619            ),
3620            (
3621                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3622                crate::render::LAYOUT_DIR_SERVICOS,
3623                LayoutError::ServicoOutsideDir as fn(PathBuf) -> LayoutError,
3624            ),
3625        ] {
3626            let sandbox_dir = root.join(sandbox_component);
3627            let err = layout
3628                .probe_sandboxed_declared_entries([path], &root, kind, &sandbox_dir, ctor)
3629                .unwrap_err();
3630            assert_eq!(
3631                err,
3632                LayoutError::missing_entry(kind, root.join(path)),
3633                "probe_sandboxed_declared_entries must thread `kind` verbatim on every \
3634                 canonical sandboxed-batch label",
3635            );
3636        }
3637    }
3638
3639    #[test]
3640    fn probe_sandboxed_declared_entries_accepts_asref_path_shape_wire_up_sites_pass() {
3641        // Cross-axis pin — the primitive's `P: AsRef<Path>` bound must
3642        // admit every concrete iterator element type the two
3643        // [`StandardLayout::verify`] wire-up sites pass:
3644        // - `&String` (from `caixa.exe(): &[String]`),
3645        // - `&String` (from `caixa.servicos(): &[String]`).
3646        //
3647        // Byte-parity assertion: on a shared `/tmp/x/lib/demo`
3648        // fixture the miss-arm return must be byte-equal across
3649        // `&String` and the ergonomic `&Path` / `&PathBuf` element-type
3650        // flavors, so a future re-shape of the bound (a narrower `P:
3651        // Into<PathBuf>` collapse, a stricter `&Path`-only signature)
3652        // would surface here rather than at the caller wire-up site.
3653        // Sibling of the peer
3654        // `probe_declared_entries_accepts_asref_path_shape_wire_up_sites_pass`
3655        // pin on the bare-batch axis.
3656        let layout = StandardLayout::new().with_path_exists(|_| false);
3657        let root = PathBuf::from("/tmp/x");
3658        let literal = "exe/demo";
3659        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3660        let expected = LayoutError::missing_entry(
3661            crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3662            root.join(Path::new(literal)),
3663        );
3664
3665        let via_string_slice: Vec<String> = vec![literal.to_string()];
3666        let via_string_err = layout
3667            .probe_sandboxed_declared_entries(
3668                via_string_slice.iter(),
3669                &root,
3670                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3671                &exe_dir,
3672                LayoutError::ExeOutsideDir,
3673            )
3674            .unwrap_err();
3675        assert_eq!(
3676            via_string_err, expected,
3677            "probe_sandboxed_declared_entries must accept `&String` items (the `caixa.exe() \
3678             : &[String]` / `caixa.servicos(): &[String]` wire-up shape)",
3679        );
3680
3681        let via_path_slice: [&Path; 1] = [Path::new(literal)];
3682        let via_path_err = layout
3683            .probe_sandboxed_declared_entries(
3684                via_path_slice,
3685                &root,
3686                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3687                &exe_dir,
3688                LayoutError::ExeOutsideDir,
3689            )
3690            .unwrap_err();
3691        assert_eq!(
3692            via_path_err, expected,
3693            "probe_sandboxed_declared_entries must accept `&Path` items",
3694        );
3695
3696        let via_pathbuf_slice: Vec<PathBuf> = vec![PathBuf::from(literal)];
3697        let via_pathbuf_err = layout
3698            .probe_sandboxed_declared_entries(
3699                via_pathbuf_slice.iter(),
3700                &root,
3701                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3702                &exe_dir,
3703                LayoutError::ExeOutsideDir,
3704            )
3705            .unwrap_err();
3706        assert_eq!(
3707            via_pathbuf_err, expected,
3708            "probe_sandboxed_declared_entries must accept `&PathBuf` items",
3709        );
3710    }
3711
3712    #[test]
3713    fn probe_sandboxed_declared_entries_routes_miss_arm_through_probe_sandboxed_declared_entry() {
3714        // Cross-primitive pin — the batch primitive must route its miss
3715        // arm through the sibling
3716        // [`StandardLayout::probe_sandboxed_declared_entry`] primitive
3717        // rather than re-inlining the `probe_declared_entry` +
3718        // `starts_with` cascade, so a future edit to the miss-arm shape
3719        // on either primitive lands in exactly one place. Byte-parity
3720        // assertion: on a fixture that misses the oracle, the batch
3721        // primitive's `Err` arm must equal the peer per-arm
3722        // [`StandardLayout::probe_sandboxed_declared_entry`] primitive's
3723        // `Err` arm on the same fixture — otherwise the batch fold has
3724        // drifted from the substrate primitive. Same discipline the peer
3725        // `probe_declared_entries_routes_miss_arm_through_probe_declared_entry`
3726        // pin establishes on the sibling bare-batch axis.
3727        let layout = StandardLayout::new().with_path_exists(|_| false);
3728        let root = PathBuf::from("/tmp/x");
3729        let path = Path::new("servicos/hello-rio.computeunit.yaml");
3730        let sandbox_dir = root.join(crate::render::LAYOUT_DIR_SERVICOS);
3731        let via_batch = layout
3732            .probe_sandboxed_declared_entries(
3733                [path],
3734                &root,
3735                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3736                &sandbox_dir,
3737                LayoutError::ServicoOutsideDir,
3738            )
3739            .unwrap_err();
3740        let via_probe = layout
3741            .probe_sandboxed_declared_entry(
3742                path,
3743                &root,
3744                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
3745                &sandbox_dir,
3746                LayoutError::ServicoOutsideDir,
3747            )
3748            .unwrap_err();
3749        assert_eq!(
3750            via_batch, via_probe,
3751            "probe_sandboxed_declared_entries's miss arm must equal the sibling \
3752             probe_sandboxed_declared_entry primitive's miss arm byte-equal — pins that \
3753             the batch primitive routes through the substrate primitive rather than \
3754             re-inlining the `probe_declared_entry` + `starts_with` cascade",
3755        );
3756    }
3757
3758    #[test]
3759    fn probe_sandboxed_declared_entries_routes_sandbox_escape_arm_through_probe_sandboxed_declared_entry()
3760     {
3761        // Cross-primitive pin — the batch primitive's sandbox-escape arm
3762        // must equal the sibling
3763        // [`StandardLayout::probe_sandboxed_declared_entry`] primitive's
3764        // sandbox-escape arm on the same fixture. Byte-parity assertion:
3765        // on a fixture where the oracle admits the probed path but the
3766        // resolved path lies outside sandbox_dir, both primitives must
3767        // return the same `outside_ctor(full)` byte-equal under
3768        // `PartialEq` — otherwise the batch fold has drifted from the
3769        // per-arm primitive on the second-arm dispatch.
3770        let root = PathBuf::from("/tmp/x");
3771        let path = Path::new("lib/escape");
3772        let full = root.join(path);
3773        let full_probe = full.clone();
3774        let layout = StandardLayout::new().with_path_exists(move |p| p == full_probe);
3775        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
3776        let via_batch = layout
3777            .probe_sandboxed_declared_entries(
3778                [path],
3779                &root,
3780                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3781                &exe_dir,
3782                LayoutError::ExeOutsideDir,
3783            )
3784            .unwrap_err();
3785        let via_probe = layout
3786            .probe_sandboxed_declared_entry(
3787                path,
3788                &root,
3789                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
3790                &exe_dir,
3791                LayoutError::ExeOutsideDir,
3792            )
3793            .unwrap_err();
3794        assert_eq!(
3795            via_batch, via_probe,
3796            "probe_sandboxed_declared_entries's sandbox-escape arm must equal the sibling \
3797             probe_sandboxed_declared_entry primitive's sandbox-escape arm byte-equal — \
3798             pins that the batch primitive routes through the substrate primitive on both \
3799             the miss and sandbox-escape arms rather than re-inlining either cascade",
3800        );
3801    }
3802
3803    // ── LayoutError::<nome-only> constructor family ──────────────────────
3804    //
3805    // The [`layout_nome_only_ctors!`] macro (below the `LayoutError` enum
3806    // definition) generates one static constructor per `<Variant>(String)`
3807    // tuple-variant that folds the uniform `Self::<Variant>(caixa.nome()
3808    // .to_string())` one-field construction onto one substrate primitive.
3809    // The per-variant equivalence pins below (fail-before-pass-after by
3810    // construction — a byte-mismatched macro arm would trip its
3811    // equivalence pin first) lock each generated constructor to its
3812    // tuple-literal peer under `PartialEq`, so every wire-up in
3813    // [`StandardLayout::verify`] on that variant produces a byte-equal
3814    // `LayoutError` to the pre-lift open-coded tuple-literal. The
3815    // cross-axis pin that follows (non-default `:nome`) routes the sole
3816    // constructor input axis through its declared accessor, so the fold
3817    // does not silently collapse onto the fixture default `:nome`.
3818
3819    fn layout_nome_only_ctor_fixture() -> Caixa {
3820        caixa(CaixaKind::Biblioteca)
3821    }
3822
3823    // Same rationale as `assert_violation_ctor_matches` / `assert_slot_
3824    // kind_ctor_matches` above: the helper terminates on the equality
3825    // check, so the owned-arg lint's general API-shape target does not
3826    // apply.
3827    #[allow(clippy::needless_pass_by_value)]
3828    fn assert_nome_only_ctor_matches(actual: LayoutError, expected: LayoutError) {
3829        assert_eq!(
3830            actual, expected,
3831            "generated constructor must produce byte-equal LayoutError to open-coded tuple-literal wrap",
3832        );
3833    }
3834
3835    #[test]
3836    fn binario_without_exe_ctor_matches_tuple_literal_wrap() {
3837        let c = layout_nome_only_ctor_fixture();
3838        assert_nome_only_ctor_matches(
3839            LayoutError::binario_without_exe(&c),
3840            LayoutError::BinarioWithoutExe(c.nome().to_string()),
3841        );
3842    }
3843
3844    #[test]
3845    fn servico_without_servicos_ctor_matches_tuple_literal_wrap() {
3846        let c = layout_nome_only_ctor_fixture();
3847        assert_nome_only_ctor_matches(
3848            LayoutError::servico_without_servicos(&c),
3849            LayoutError::ServicoWithoutServicos(c.nome().to_string()),
3850        );
3851    }
3852
3853    #[test]
3854    fn missing_ci_ctor_matches_tuple_literal_wrap() {
3855        let c = layout_nome_only_ctor_fixture();
3856        assert_nome_only_ctor_matches(
3857            LayoutError::missing_ci(&c),
3858            LayoutError::MissingCi(c.nome().to_string()),
3859        );
3860    }
3861
3862    #[test]
3863    fn supervisor_owns_code_ctor_matches_tuple_literal_wrap() {
3864        let c = layout_nome_only_ctor_fixture();
3865        assert_nome_only_ctor_matches(
3866            LayoutError::supervisor_owns_code(&c),
3867            LayoutError::SupervisorOwnsCode(c.nome().to_string()),
3868        );
3869    }
3870
3871    #[test]
3872    fn aplicacao_owns_code_ctor_matches_tuple_literal_wrap() {
3873        let c = layout_nome_only_ctor_fixture();
3874        assert_nome_only_ctor_matches(
3875            LayoutError::aplicacao_owns_code(&c),
3876            LayoutError::AplicacaoOwnsCode(c.nome().to_string()),
3877        );
3878    }
3879
3880    #[test]
3881    fn acao_owns_code_ctor_matches_tuple_literal_wrap() {
3882        let c = layout_nome_only_ctor_fixture();
3883        assert_nome_only_ctor_matches(
3884            LayoutError::acao_owns_code(&c),
3885            LayoutError::AcaoOwnsCode(c.nome().to_string()),
3886        );
3887    }
3888
3889    #[test]
3890    fn nome_only_ctor_routes_caixa_through_nome_accessor() {
3891        // Pin the fold's `caixa.nome().to_string()` sole-field construction
3892        // against a non-default `:nome` — the accessor threads the caller's
3893        // `:nome` verbatim into the tuple-variant, so the fold does not
3894        // silently collapse onto the default `"demo"` fixture nome. Peer of
3895        // the sibling `violation_ctor_routes_caixa_prefix_through_nome_
3896        // accessor` / `slot_kind_ctor_routes_caixa_prefix_through_nome_
3897        // accessor` pins on the `{ caixa, issue }` / `{ caixa, kind,
3898        // slots }` envelopes; extended here onto the sixth
3899        // `<Variant>(String)` envelope so every LayoutError-shape ctor
3900        // family guarantees the `:nome`-derived-caixa slot routes through
3901        // [`Caixa::nome`] rather than a hard-coded string. Sweeps the six
3902        // ctors in the [`layout_nome_only_ctors!`] macro so the pin covers
3903        // every generated arm.
3904        let mut c = caixa(CaixaKind::Biblioteca);
3905        c.nome = "alt-nome".into();
3906        assert_eq!(
3907            LayoutError::binario_without_exe(&c),
3908            LayoutError::BinarioWithoutExe("alt-nome".to_string()),
3909        );
3910        assert_eq!(
3911            LayoutError::servico_without_servicos(&c),
3912            LayoutError::ServicoWithoutServicos("alt-nome".to_string()),
3913        );
3914        assert_eq!(
3915            LayoutError::missing_ci(&c),
3916            LayoutError::MissingCi("alt-nome".to_string()),
3917        );
3918        assert_eq!(
3919            LayoutError::supervisor_owns_code(&c),
3920            LayoutError::SupervisorOwnsCode("alt-nome".to_string()),
3921        );
3922        assert_eq!(
3923            LayoutError::aplicacao_owns_code(&c),
3924            LayoutError::AplicacaoOwnsCode("alt-nome".to_string()),
3925        );
3926        assert_eq!(
3927            LayoutError::acao_owns_code(&c),
3928            LayoutError::AcaoOwnsCode("alt-nome".to_string()),
3929        );
3930    }
3931
3932    #[test]
3933    fn biblioteca_needs_default_lib_path() {
3934        let root = PathBuf::from("/tmp/x");
3935        let expect_manifest = root.join("caixa.lisp");
3936        let layout = StandardLayout::new().with_path_exists(move |p| p == expect_manifest);
3937        let err = layout
3938            .verify(&caixa(CaixaKind::Biblioteca), &root)
3939            .unwrap_err();
3940        assert!(matches!(err, LayoutError::MissingLib { .. }));
3941    }
3942
3943    #[test]
3944    fn biblioteca_passes_when_default_lib_exists() {
3945        let root = PathBuf::from("/tmp/x");
3946        let manifest = root.join("caixa.lisp");
3947        let default_lib = root.join("lib").join("demo.lisp");
3948        let layout =
3949            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
3950        layout
3951            .verify(&caixa(CaixaKind::Biblioteca), &root)
3952            .expect("should pass");
3953    }
3954
3955    #[test]
3956    fn binario_without_exe_errors() {
3957        let root = PathBuf::from("/tmp/x");
3958        let manifest = root.join("caixa.lisp");
3959        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
3960        let err = layout
3961            .verify(&caixa(CaixaKind::Binario), &root)
3962            .unwrap_err();
3963        assert!(matches!(err, LayoutError::BinarioWithoutExe(_)));
3964    }
3965
3966    #[test]
3967    fn exe_outside_dir_errors() {
3968        // A relative entry that lives under the caixa root but *not*
3969        // under `exe/` — the canonical case the `starts_with(exe_dir)`
3970        // fence catches. The prior parent-escape shape this test used
3971        // (`"../sibling/tool"`) is now caught at validate time by
3972        // [`Caixa::validate_code_paths`] with the narrower
3973        // [`crate::ManifestError::CodePathParentEscape`] diagnostic
3974        // (see the layout-level integration pin
3975        // `code_path_violation_on_parent_escape_fires_before_existence_check`),
3976        // so this fence pin uses a non-`..` non-absolute shape outside
3977        // `exe/` to preserve coverage of the ExeOutsideDir surface.
3978        let root = PathBuf::from("/tmp/x");
3979        let manifest = root.join("caixa.lisp");
3980        let outside = root.join("lib/tool");
3981        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == outside);
3982        let mut c = caixa(CaixaKind::Binario);
3983        c.exe = vec!["lib/tool".into()];
3984        let err = layout.verify(&c, &root).unwrap_err();
3985        assert!(matches!(err, LayoutError::ExeOutsideDir(_)));
3986    }
3987
3988    // ── code-path shape gate (lifted to layout-level verify) ─────────────
3989
3990    #[test]
3991    fn code_path_violation_on_empty_bibliotecas_entry() {
3992        let root = PathBuf::from("/tmp/x");
3993        let manifest = root.join("caixa.lisp");
3994        let default_lib = root.join("lib").join("demo.lisp");
3995        let layout =
3996            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
3997        let mut c = caixa(CaixaKind::Biblioteca);
3998        c.bibliotecas = vec![String::new()];
3999        let err = layout.verify(&c, &root).unwrap_err();
4000        // The wire-up wraps `ManifestError` Display into the
4001        // CodePathViolation envelope (peer of LimitsViolation /
4002        // BehaviorViolation / UpgradeViolation), so the issue string
4003        // names the offending slot at the source.
4004        let LayoutError::CodePathViolation { caixa, issue } = err else {
4005            panic!("expected LayoutError::CodePathViolation, got {err:?}");
4006        };
4007        assert_eq!(caixa, "demo");
4008        assert!(
4009            issue.contains(":bibliotecas"),
4010            "issue must name the offending slot: {issue}",
4011        );
4012    }
4013
4014    #[test]
4015    fn code_path_violation_on_absolute_servicos_entry() {
4016        let root = PathBuf::from("/tmp/x");
4017        let manifest = root.join("caixa.lisp");
4018        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
4019        let mut c = caixa(CaixaKind::Servico);
4020        c.servicos = vec!["/etc/servicos/escape.yaml".into()];
4021        let err = layout.verify(&c, &root).unwrap_err();
4022        let LayoutError::CodePathViolation { caixa, issue } = err else {
4023            panic!("expected LayoutError::CodePathViolation, got {err:?}");
4024        };
4025        assert_eq!(caixa, "demo");
4026        assert!(
4027            issue.contains(":servicos"),
4028            "issue must name the offending slot: {issue}",
4029        );
4030        assert!(
4031            issue.contains("/etc/servicos/escape.yaml"),
4032            "issue must quote the offending path: {issue}",
4033        );
4034    }
4035
4036    #[test]
4037    fn code_path_violation_on_parent_escape_fires_before_existence_check() {
4038        // The new gate runs BEFORE the existence loops, so a
4039        // parent-escaping `:exe` entry surfaces CodePathViolation
4040        // (naming `:exe` at the source) rather than the downstream
4041        // ExeOutsideDir / MissingEntry against the resolved sandbox-
4042        // escape path. Even if the resolved escape target exists
4043        // on disk (which we simulate here by claiming it does), the
4044        // shape diagnostic wins.
4045        let root = PathBuf::from("/tmp/x");
4046        let manifest = root.join("caixa.lisp");
4047        let resolved_escape = root.join("exe/../../escape.lisp");
4048        let layout =
4049            StandardLayout::new().with_path_exists(move |p| p == manifest || p == resolved_escape);
4050        let mut c = caixa(CaixaKind::Binario);
4051        c.exe = vec!["exe/../../escape.lisp".into()];
4052        let err = layout.verify(&c, &root).unwrap_err();
4053        let LayoutError::CodePathViolation { caixa, issue } = err else {
4054            panic!("expected LayoutError::CodePathViolation, got {err:?}");
4055        };
4056        assert_eq!(caixa, "demo");
4057        assert!(
4058            issue.contains(":exe"),
4059            "issue must name the offending slot: {issue}",
4060        );
4061    }
4062
4063    // ── etiquetas universal-axis gate wired into verify ─────────────────
4064    //
4065    // Pins the layout-pipeline wire-up of [`Caixa::validate_etiquetas`]:
4066    // the fourth universal-axis Caixa-level value-shape gate (peer of
4067    // `validate_nome` / `validate_versao` / `validate_deps` /
4068    // `validate_code_paths`), wired before the kind-coherence gates so
4069    // a structurally-invalid `:etiquetas` entry on any kind surfaces
4070    // the per-axis `EtiquetasViolation { caixa, issue }` envelope at
4071    // the source rather than silently rendering as `keywords: [""]`
4072    // in `Chart.yaml` (Servico kind, via caixa-helm's `BTreeSet`
4073    // collect) or silently dedup'ing at chart render (every kind).
4074    // Until this wire-up landed `:etiquetas` had no shape gate at any
4075    // layer — the registry-search-tag axis was the largest universal
4076    // authoring surface on the typed Caixa surface with no validate
4077    // discipline.
4078    //
4079    // Same per-axis `*Violation { caixa, issue }` envelope every peer
4080    // per-axis wrap exposes; the wire-up runs after `validate_deps`
4081    // (universal axis ordering: `:nome` → `:versao` → `:deps` →
4082    // `:etiquetas`) and before every kind-coherence gate
4083    // (`:etiquetas` is universal so its shape diagnostic is more
4084    // fundamental than the partition-on-kind diagnostics).
4085
4086    #[test]
4087    fn etiquetas_violation_on_empty_entry() {
4088        // Canonical paste-from-blank-doc footgun on every kind. The
4089        // wrap envelope wraps [`ManifestError::EtiquetaEmpty`]'s
4090        // Display through verbatim, so the issue string names the
4091        // offending `:etiquetas` axis at the source — the author can
4092        // grep their caixa.lisp for `:etiquetas` and fix the empty
4093        // entry in one edit. Mirrors the peer
4094        // `code_path_violation_on_empty_bibliotecas_entry` shape
4095        // (b868442) on the `:bibliotecas` axis.
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        let mut c = caixa(CaixaKind::Biblioteca);
4102        c.etiquetas = vec![String::new()];
4103        let err = layout.verify(&c, &root).unwrap_err();
4104        let LayoutError::EtiquetasViolation { caixa, issue } = err else {
4105            panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
4106        };
4107        assert_eq!(caixa, "demo");
4108        assert!(
4109            issue.contains(":etiquetas"),
4110            "issue must name the offending slot: {issue}",
4111        );
4112    }
4113
4114    #[test]
4115    fn etiquetas_violation_on_duplicate_entry() {
4116        // Canonical copy-paste-the-wrong-tag footgun. Without the wire-
4117        // up the duplicate was silently dedup'd by caixa-helm's
4118        // `BTreeSet` collect at chart render — a "second wins / one
4119        // silently disappears" shape. The wrap envelope names the
4120        // offending tag verbatim through the inner
4121        // [`ManifestError::EtiquetaDuplicate`]'s Display.
4122        let root = PathBuf::from("/tmp/x");
4123        let manifest = root.join("caixa.lisp");
4124        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
4125        let mut c = caixa(CaixaKind::Servico);
4126        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
4127        c.etiquetas = vec!["demo".into(), "demo".into()];
4128        // The servicos path doesn't exist in this fixture, but the
4129        // `:etiquetas` gate fires before the existence loop (universal
4130        // axis dominates kind-specific existence checks). Wire is
4131        // intact iff the wrap envelope surfaces first.
4132        let err = layout.verify(&c, &root).unwrap_err();
4133        let LayoutError::EtiquetasViolation { caixa, issue } = err else {
4134            panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
4135        };
4136        assert_eq!(caixa, "demo");
4137        assert!(
4138            issue.contains("demo"),
4139            "issue must quote the offending tag: {issue}",
4140        );
4141    }
4142
4143    #[test]
4144    fn etiquetas_violation_fires_before_kind_coherence_mesh_slot() {
4145        // Cross-axis precedence pin: a Biblioteca with malformed
4146        // `:etiquetas` *and* declared mesh slots (`:membros`) surfaces
4147        // the universal `:etiquetas` diagnostic first, not the
4148        // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4149        // `:etiquetas` is universal (every kind owns the slot), so its
4150        // shape diagnostic is more fundamental than the partition-on-
4151        // kind diagnostic. Mirrors the peer
4152        // `deps_violation_fires_before_*` precedence pins (aa77d0f) on
4153        // the universal `:deps` axis vs the same kind-coherence gates.
4154        let root = PathBuf::from("/tmp/x");
4155        let manifest = root.join("caixa.lisp");
4156        let default_lib = root.join("lib").join("demo.lisp");
4157        let layout =
4158            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4159        let mut c = caixa(CaixaKind::Biblioteca);
4160        c.etiquetas = vec![String::new()];
4161        c.membros = vec![crate::aplicacao::Membro {
4162            caixa: "x".into(),
4163            versao: "^0.1".into(),
4164        }];
4165        let err = layout.verify(&c, &root).unwrap_err();
4166        assert!(
4167            matches!(err, LayoutError::EtiquetasViolation { .. }),
4168            "got {err:?}",
4169        );
4170    }
4171
4172    #[test]
4173    fn etiquetas_violation_fires_after_deps_violation() {
4174        // Cross-axis precedence pin (inside the universal-axis trio):
4175        // a caixa with both a malformed `:deps` entry *and* a malformed
4176        // `:etiquetas` entry surfaces `DepsViolation` first — `:deps`
4177        // is the third universal axis in declaration order
4178        // (`:nome` → `:versao` → `:deps` → `:etiquetas`) and runs first
4179        // in `verify`. Mirrors the peer
4180        // `nome_violation_fires_before_versao_violation` shape on the
4181        // identity-axis pair.
4182        let root = PathBuf::from("/tmp/x");
4183        let manifest = root.join("caixa.lisp");
4184        let default_lib = root.join("lib").join("demo.lisp");
4185        let layout =
4186            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4187        let mut c = caixa(CaixaKind::Biblioteca);
4188        c.deps = vec![crate::Dep::simple("Caixa-Teia", "^0.1")]; // uppercase :nome
4189        c.etiquetas = vec![String::new()];
4190        let err = layout.verify(&c, &root).unwrap_err();
4191        assert!(
4192            matches!(err, LayoutError::DepsViolation { .. }),
4193            "got {err:?}",
4194        );
4195    }
4196
4197    #[test]
4198    fn etiquetas_violation_accepts_canonical_template() {
4199        // Positive control sanity pin: the canonical `Caixa::template`
4200        // shape (`:etiquetas ()` — empty list) passes the gate
4201        // trivially. Mirrors the peer
4202        // `validate_code_paths_accepts_canonical_template` pin.
4203        let root = PathBuf::from("/tmp/x");
4204        let manifest = root.join("caixa.lisp");
4205        let default_lib = root.join("lib").join("demo.lisp");
4206        let layout =
4207            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4208        let c = caixa(CaixaKind::Biblioteca);
4209        layout.verify(&c, &root).expect("template must pass");
4210    }
4211
4212    #[test]
4213    fn etiquetas_violation_on_non_chart_keyword_shape() {
4214        // Canonical CSV-list-separator-confusion footgun: the author
4215        // confused the CSV-style separator with the `:etiquetas` list
4216        // grammar. The shape gate fires past the empty + duplicate
4217        // arms via [`Caixa::validate_etiquetas`]'s new
4218        // `is_chart_keyword_shape` cascade, and the layout envelope
4219        // wraps [`ManifestError::EtiquetaInvalid`]'s Display through
4220        // verbatim — the issue string names both the offending slot
4221        // and the offending value (debug-escaped). Peer with the
4222        // `autores_violation_on_non_chart_maintainer_shape` pin on
4223        // the sibling universal-axis `Vec<String>` surface — the
4224        // second layout pin on the Vec<String> per-entry shape
4225        // cascade.
4226        let root = PathBuf::from("/tmp/x");
4227        let manifest = root.join("caixa.lisp");
4228        let default_lib = root.join("lib").join("demo.lisp");
4229        let layout =
4230            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4231        let mut c = caixa(CaixaKind::Biblioteca);
4232        c.etiquetas = vec!["mesh,http,grpc".into()];
4233        let err = layout.verify(&c, &root).unwrap_err();
4234        let LayoutError::EtiquetasViolation { caixa, issue } = err else {
4235            panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
4236        };
4237        assert_eq!(caixa, "demo");
4238        assert!(
4239            issue.contains(":etiquetas"),
4240            "issue must name the offending slot: {issue}",
4241        );
4242        assert!(
4243            issue.contains("mesh,http,grpc"),
4244            "issue must quote the offending value: {issue}",
4245        );
4246    }
4247
4248    // ── autores universal-axis gate wired into verify ───────────────────
4249    //
4250    // Pins the layout-pipeline wire-up of [`Caixa::validate_autores`]:
4251    // the fifth universal-axis Caixa-level value-shape gate (peer of
4252    // `validate_nome` / `validate_versao` / `validate_deps` /
4253    // `validate_etiquetas` / `validate_code_paths`), wired immediately
4254    // after `validate_etiquetas` so the two Vec-shaped universal
4255    // metadata axes sit adjacent in the cascade. Until this wire-up
4256    // landed `:autores` had no shape gate at any layer — the
4257    // maintainer-axis was the second largest universal authoring
4258    // surface on the typed Caixa surface with no validate discipline,
4259    // and unlike `:etiquetas` (caixa-helm dedups the rendered
4260    // `keywords:` array via `BTreeSet` collect at chart render),
4261    // `maintainers:` has *no* renderer-side dedup, so duplicate
4262    // `:autores` entries render verbatim as two identical
4263    // `Maintainer { name, email: None }` records — a strictly worse
4264    // footgun than the peer `:etiquetas` shape.
4265
4266    #[test]
4267    fn autores_violation_on_empty_entry() {
4268        // Canonical paste-from-blank-doc footgun on every kind. The
4269        // wrap envelope wraps [`ManifestError::AutorEmpty`]'s Display
4270        // through verbatim, so the issue string names the offending
4271        // `:autores` axis at the source — the author can grep their
4272        // caixa.lisp for `:autores` and fix the empty entry in one
4273        // edit. Mirrors the peer `etiquetas_violation_on_empty_entry`
4274        // shape (360a499) on the `:etiquetas` axis.
4275        let root = PathBuf::from("/tmp/x");
4276        let manifest = root.join("caixa.lisp");
4277        let default_lib = root.join("lib").join("demo.lisp");
4278        let layout =
4279            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4280        let mut c = caixa(CaixaKind::Biblioteca);
4281        c.autores = vec![String::new()];
4282        let err = layout.verify(&c, &root).unwrap_err();
4283        let LayoutError::AutoresViolation { caixa, issue } = err else {
4284            panic!("expected LayoutError::AutoresViolation, got {err:?}");
4285        };
4286        assert_eq!(caixa, "demo");
4287        assert!(
4288            issue.contains(":autores"),
4289            "issue must name the offending slot: {issue}",
4290        );
4291    }
4292
4293    #[test]
4294    fn autores_violation_on_duplicate_entry() {
4295        // Canonical copy-paste-the-wrong-author footgun. Unlike the
4296        // peer `:etiquetas` axis (silently dedup'd by caixa-helm's
4297        // `BTreeSet` collect at chart render), `:autores` duplicates
4298        // stack verbatim in the rendered `maintainers:` — the gate
4299        // closes the footgun at validate time before any renderer
4300        // sees it. The wrap envelope names the offending author
4301        // verbatim through the inner [`ManifestError::AutorDuplicate`]'s
4302        // Display.
4303        let root = PathBuf::from("/tmp/x");
4304        let manifest = root.join("caixa.lisp");
4305        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
4306        let mut c = caixa(CaixaKind::Servico);
4307        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
4308        c.autores = vec!["pleme-io".into(), "pleme-io".into()];
4309        // The servicos path doesn't exist in this fixture, but the
4310        // `:autores` gate fires before the existence loop (universal
4311        // axis dominates kind-specific existence checks). Wire is
4312        // intact iff the wrap envelope surfaces first.
4313        let err = layout.verify(&c, &root).unwrap_err();
4314        let LayoutError::AutoresViolation { caixa, issue } = err else {
4315            panic!("expected LayoutError::AutoresViolation, got {err:?}");
4316        };
4317        assert_eq!(caixa, "demo");
4318        assert!(
4319            issue.contains("pleme-io"),
4320            "issue must quote the offending author: {issue}",
4321        );
4322    }
4323
4324    #[test]
4325    fn autores_violation_fires_before_kind_coherence_mesh_slot() {
4326        // Cross-axis precedence pin: a Biblioteca with malformed
4327        // `:autores` *and* declared mesh slots (`:membros`) surfaces
4328        // the universal `:autores` diagnostic first, not the
4329        // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4330        // `:autores` is universal (every kind owns the slot), so its
4331        // shape diagnostic is more fundamental than the partition-on-
4332        // kind diagnostic. Mirrors the peer
4333        // `etiquetas_violation_fires_before_kind_coherence_mesh_slot`
4334        // pin (360a499) on the `:etiquetas` axis vs the same kind-
4335        // coherence gates.
4336        let root = PathBuf::from("/tmp/x");
4337        let manifest = root.join("caixa.lisp");
4338        let default_lib = root.join("lib").join("demo.lisp");
4339        let layout =
4340            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4341        let mut c = caixa(CaixaKind::Biblioteca);
4342        c.autores = vec![String::new()];
4343        c.membros = vec![crate::aplicacao::Membro {
4344            caixa: "x".into(),
4345            versao: "^0.1".into(),
4346        }];
4347        let err = layout.verify(&c, &root).unwrap_err();
4348        assert!(
4349            matches!(err, LayoutError::AutoresViolation { .. }),
4350            "got {err:?}",
4351        );
4352    }
4353
4354    #[test]
4355    fn autores_violation_fires_after_etiquetas_violation() {
4356        // Cross-axis precedence pin (inside the Vec-shaped universal
4357        // metadata pair): a caixa with both a malformed `:etiquetas`
4358        // entry *and* a malformed `:autores` entry surfaces
4359        // `EtiquetasViolation` first — `:etiquetas` is the fourth
4360        // universal axis in the cascade and runs before `:autores`,
4361        // peer with the canonical identity-axis-first cascade the
4362        // peer gates establish. Mirrors the peer
4363        // `etiquetas_violation_fires_after_deps_violation` precedence
4364        // pin (360a499) on the dep-axis-before-tag-axis pair.
4365        let root = PathBuf::from("/tmp/x");
4366        let manifest = root.join("caixa.lisp");
4367        let default_lib = root.join("lib").join("demo.lisp");
4368        let layout =
4369            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4370        let mut c = caixa(CaixaKind::Biblioteca);
4371        c.etiquetas = vec![String::new()];
4372        c.autores = vec![String::new()];
4373        let err = layout.verify(&c, &root).unwrap_err();
4374        assert!(
4375            matches!(err, LayoutError::EtiquetasViolation { .. }),
4376            "got {err:?}",
4377        );
4378    }
4379
4380    #[test]
4381    fn autores_violation_accepts_canonical_template() {
4382        // Positive control sanity pin: the canonical `Caixa::template`
4383        // shape (`:autores ()` — empty list) passes the gate trivially.
4384        // Mirrors the peer `etiquetas_violation_accepts_canonical_template`
4385        // pin (360a499).
4386        let root = PathBuf::from("/tmp/x");
4387        let manifest = root.join("caixa.lisp");
4388        let default_lib = root.join("lib").join("demo.lisp");
4389        let layout =
4390            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4391        let c = caixa(CaixaKind::Biblioteca);
4392        layout.verify(&c, &root).expect("template must pass");
4393    }
4394
4395    #[test]
4396    fn autores_violation_on_non_chart_maintainer_shape() {
4397        // Canonical paste-from-multiline-doc footgun: the author
4398        // pasted a multi-line block of author records into one
4399        // `:autores` entry instead of splitting into one entry per
4400        // author. The shape gate fires past the empty + duplicate arms
4401        // via [`Caixa::validate_autores`]'s new
4402        // `is_chart_maintainer_name_shape` cascade, and the layout
4403        // envelope wraps [`ManifestError::AutorInvalid`]'s Display
4404        // through verbatim — the issue string names both the offending
4405        // slot and the offending value (debug-escaped). Peer with the
4406        // `descricao_violation_on_non_chart_shape` pin on the sibling
4407        // universal-axis `Option<String>` surface and the
4408        // `licenca_violation_on_non_spdx_shape` /
4409        // `edicao_violation_on_non_year_shape` peers — and the first
4410        // layout pin on the Vec<String> per-entry shape cascade.
4411        let root = PathBuf::from("/tmp/x");
4412        let manifest = root.join("caixa.lisp");
4413        let default_lib = root.join("lib").join("demo.lisp");
4414        let layout =
4415            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4416        let mut c = caixa(CaixaKind::Biblioteca);
4417        c.autores = vec!["alice\nbob".into()];
4418        let err = layout.verify(&c, &root).unwrap_err();
4419        let LayoutError::AutoresViolation { caixa, issue } = err else {
4420            panic!("expected LayoutError::AutoresViolation, got {err:?}");
4421        };
4422        assert_eq!(caixa, "demo");
4423        assert!(
4424            issue.contains(":autores"),
4425            "issue must name the offending slot: {issue}",
4426        );
4427        assert!(
4428            issue.contains("alice\\nbob"),
4429            "issue must quote the offending value (debug-escaped): {issue}",
4430        );
4431    }
4432
4433    // ── repositorio universal-axis gate wired into verify ────────────────
4434    //
4435    // Pins the layout-pipeline wire-up of [`Caixa::validate_repositorio`]:
4436    // the sixth universal-axis Caixa-level value-shape gate (peer of
4437    // `validate_nome` / `validate_versao` / `validate_deps` /
4438    // `validate_etiquetas` / `validate_autores` / `validate_code_paths`),
4439    // wired immediately after `validate_autores` so the universal
4440    // git-URL axis sits adjacent to the two Vec-shaped universal
4441    // metadata axes (`:etiquetas`, `:autores`) in the cascade. Until
4442    // this wire-up landed `:repositorio` had no shape gate at any
4443    // layer — the universal git-shaped homepage axis was the third
4444    // largest universal authoring surface on the typed Caixa with no
4445    // validate discipline, routing the same string through two
4446    // load-bearing substrate consumers (`caixa-helm`'s `Chart.yaml
4447    // home:` field and `caixa-flux`'s FluxCD `GitRepository.spec.url`)
4448    // via `Option::unwrap_or_else` fallbacks that only fire on `None` —
4449    // a `Some("")` silently passed every fallback and rendered as an
4450    // empty URL in both consumers, breaking at `helm template` /
4451    // FluxCD reconcile time far from the source `caixa.lisp`. The
4452    // gate closes the divergence and makes the two `git URL`-shaped
4453    // surfaces on the typed Caixa (`:repositorio` here, `:deps :fonte
4454    // :repo` peer routed through the same shared
4455    // `crate::render::is_git_repo_url` predicate) structurally
4456    // equivalent by construction.
4457
4458    #[test]
4459    fn repositorio_violation_on_empty_some() {
4460        // Canonical paste-from-blank-doc footgun on every kind. The
4461        // wrap envelope wraps [`ManifestError::RepositorioEmpty`]'s
4462        // Display through verbatim, so the issue string names the
4463        // offending `:repositorio` axis at the source — the author
4464        // can grep their caixa.lisp for `:repositorio ""` and fix the
4465        // empty value in one edit. Mirrors the peer
4466        // `autores_violation_on_empty_entry` shape (86c769b) on the
4467        // `:autores` axis.
4468        let root = PathBuf::from("/tmp/x");
4469        let manifest = root.join("caixa.lisp");
4470        let default_lib = root.join("lib").join("demo.lisp");
4471        let layout =
4472            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4473        let mut c = caixa(CaixaKind::Biblioteca);
4474        c.repositorio = Some(String::new());
4475        let err = layout.verify(&c, &root).unwrap_err();
4476        let LayoutError::RepositorioViolation { caixa, issue } = err else {
4477            panic!("expected LayoutError::RepositorioViolation, got {err:?}");
4478        };
4479        assert_eq!(caixa, "demo");
4480        assert!(
4481            issue.contains(":repositorio"),
4482            "issue must name the offending slot: {issue}",
4483        );
4484    }
4485
4486    #[test]
4487    fn repositorio_violation_on_malformed_shape() {
4488        // Canonical CLI-argument-injection footgun: a leading `-`
4489        // value (`-upload-pack=evil`) escapes the `git clone <repo>`
4490        // subprocess argument boundary at clone time. The shared
4491        // `is_git_repo_url` predicate — the same parser the peer
4492        // `:deps :fonte :repo` axis routes through via
4493        // `DepSource::validate` — refuses every leading-`-` shape at
4494        // validate time. The wrap envelope names the offending value
4495        // verbatim through the inner [`ManifestError::RepositorioInvalid`]'s
4496        // Display.
4497        let root = PathBuf::from("/tmp/x");
4498        let manifest = root.join("caixa.lisp");
4499        let default_lib = root.join("lib").join("demo.lisp");
4500        let layout =
4501            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4502        let mut c = caixa(CaixaKind::Biblioteca);
4503        c.repositorio = Some("-upload-pack=evil".into());
4504        let err = layout.verify(&c, &root).unwrap_err();
4505        let LayoutError::RepositorioViolation { caixa, issue } = err else {
4506            panic!("expected LayoutError::RepositorioViolation, got {err:?}");
4507        };
4508        assert_eq!(caixa, "demo");
4509        assert!(
4510            issue.contains("-upload-pack=evil"),
4511            "issue must quote the offending value: {issue}",
4512        );
4513    }
4514
4515    #[test]
4516    fn repositorio_violation_fires_before_kind_coherence_mesh_slot() {
4517        // Cross-axis precedence pin: a Biblioteca with malformed
4518        // `:repositorio` *and* declared mesh slots (`:membros`)
4519        // surfaces the universal `:repositorio` diagnostic first, not
4520        // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4521        // `:repositorio` is universal (every kind owns the slot), so
4522        // its shape diagnostic is more fundamental than the
4523        // partition-on-kind diagnostic. Mirrors the peer
4524        // `autores_violation_fires_before_kind_coherence_mesh_slot`
4525        // pin (86c769b) on the `:autores` axis vs the same
4526        // kind-coherence gates.
4527        let root = PathBuf::from("/tmp/x");
4528        let manifest = root.join("caixa.lisp");
4529        let default_lib = root.join("lib").join("demo.lisp");
4530        let layout =
4531            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4532        let mut c = caixa(CaixaKind::Biblioteca);
4533        c.repositorio = Some(String::new());
4534        c.membros = vec![crate::aplicacao::Membro {
4535            caixa: "x".into(),
4536            versao: "^0.1".into(),
4537        }];
4538        let err = layout.verify(&c, &root).unwrap_err();
4539        assert!(
4540            matches!(err, LayoutError::RepositorioViolation { .. }),
4541            "got {err:?}",
4542        );
4543    }
4544
4545    #[test]
4546    fn repositorio_violation_fires_after_autores_violation() {
4547        // Cross-axis precedence pin (inside the universal metadata
4548        // trio): a caixa with both a malformed `:autores` entry *and*
4549        // a malformed `:repositorio` value surfaces `AutoresViolation`
4550        // first — `:autores` is the fifth universal axis in the
4551        // cascade and runs before `:repositorio`, peer with the
4552        // canonical identity-axis-first cascade the peer gates
4553        // establish. Mirrors the peer
4554        // `autores_violation_fires_after_etiquetas_violation`
4555        // precedence pin (86c769b) on the tag-axis-before-author-axis
4556        // pair.
4557        let root = PathBuf::from("/tmp/x");
4558        let manifest = root.join("caixa.lisp");
4559        let default_lib = root.join("lib").join("demo.lisp");
4560        let layout =
4561            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4562        let mut c = caixa(CaixaKind::Biblioteca);
4563        c.autores = vec![String::new()];
4564        c.repositorio = Some(String::new());
4565        let err = layout.verify(&c, &root).unwrap_err();
4566        assert!(
4567            matches!(err, LayoutError::AutoresViolation { .. }),
4568            "got {err:?}",
4569        );
4570    }
4571
4572    #[test]
4573    fn repositorio_violation_accepts_canonical_template() {
4574        // Positive control sanity pin: the canonical `Caixa::template`
4575        // shape (omits `:repositorio` entirely → `None` on the typed
4576        // surface) passes the gate trivially — the gate is a no-op
4577        // when the author didn't author a value. Mirrors the peer
4578        // `autores_violation_accepts_canonical_template` pin (86c769b).
4579        let root = PathBuf::from("/tmp/x");
4580        let manifest = root.join("caixa.lisp");
4581        let default_lib = root.join("lib").join("demo.lisp");
4582        let layout =
4583            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4584        let c = caixa(CaixaKind::Biblioteca);
4585        layout.verify(&c, &root).expect("template must pass");
4586    }
4587
4588    #[test]
4589    fn repositorio_violation_accepts_canonical_github_shorthand() {
4590        // Positive control pin on the canonical pleme-io `:repositorio`
4591        // shape: the `github:org/repo` shorthand the README quickstart
4592        // and the `caixa-helm` / `caixa-mesh` / `caixa-flux` fixtures
4593        // all use passes the gate end-to-end. Closes the structural
4594        // equivalence between this surface and the peer `:deps :fonte
4595        // :repo` axis — both consume `crate::render::is_git_repo_url`
4596        // and both must agree on the same accepted shape set.
4597        let root = PathBuf::from("/tmp/x");
4598        let manifest = root.join("caixa.lisp");
4599        let default_lib = root.join("lib").join("demo.lisp");
4600        let layout =
4601            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4602        let mut c = caixa(CaixaKind::Biblioteca);
4603        c.repositorio = Some("github:pleme-io/hello-rio".into());
4604        layout.verify(&c, &root).expect("canonical shape must pass");
4605    }
4606
4607    // ── descricao universal-axis gate wired into verify ──────────────────
4608    //
4609    // Pins the layout-pipeline wire-up of [`Caixa::validate_descricao`]:
4610    // the seventh universal-axis Caixa-level value-shape gate (peer of
4611    // `validate_nome` / `validate_versao` / `validate_deps` /
4612    // `validate_etiquetas` / `validate_autores` / `validate_repositorio` /
4613    // `validate_code_paths`), wired immediately after `validate_repositorio`
4614    // so the universal free-form-prose axis sits adjacent to the
4615    // universal git-URL axis in the cascade. Until this wire-up landed
4616    // `:descricao` had no shape gate at any layer — the empty
4617    // `Some("")` silently passed both `caixa-helm` consumers'
4618    // `Option::unwrap_or_else(|| <fallback>)` (which only fire on
4619    // `None`) and rendered as `Chart.yaml description: ""` plus a
4620    // blank `README.md` header, breaking at `helm lint` time
4621    // (`WARNING [chart.metadata.description]: description is required`
4622    // on `apiVersion: v2` charts) far from the source `caixa.lisp`.
4623    // Closes the same `Some("")` skips-`unwrap_or_else` footgun the
4624    // peer `:repositorio` gate (577b0a9) closed, on the universal
4625    // free-form-prose summary axis.
4626
4627    #[test]
4628    fn descricao_violation_on_empty_some() {
4629        // Canonical paste-from-blank-doc footgun on every kind. The
4630        // wrap envelope wraps [`ManifestError::DescricaoEmpty`]'s
4631        // Display through verbatim, so the issue string names the
4632        // offending `:descricao` axis at the source — the author can
4633        // grep their caixa.lisp for `:descricao ""` and fix the empty
4634        // value in one edit. Mirrors the peer
4635        // `repositorio_violation_on_empty_some` shape (577b0a9) on
4636        // the sibling `Option<String>` `:repositorio` axis.
4637        let root = PathBuf::from("/tmp/x");
4638        let manifest = root.join("caixa.lisp");
4639        let default_lib = root.join("lib").join("demo.lisp");
4640        let layout =
4641            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4642        let mut c = caixa(CaixaKind::Biblioteca);
4643        c.descricao = Some(String::new());
4644        let err = layout.verify(&c, &root).unwrap_err();
4645        let LayoutError::DescricaoViolation { caixa, issue } = err else {
4646            panic!("expected LayoutError::DescricaoViolation, got {err:?}");
4647        };
4648        assert_eq!(caixa, "demo");
4649        assert!(
4650            issue.contains(":descricao"),
4651            "issue must name the offending slot: {issue}",
4652        );
4653    }
4654
4655    #[test]
4656    fn descricao_violation_fires_before_kind_coherence_mesh_slot() {
4657        // Cross-axis precedence pin: a Biblioteca with empty
4658        // `:descricao` *and* declared mesh slots (`:membros`)
4659        // surfaces the universal `:descricao` diagnostic first, not
4660        // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4661        // `:descricao` is universal (every kind owns the slot), so
4662        // its shape diagnostic is more fundamental than the
4663        // partition-on-kind diagnostic. Mirrors the peer
4664        // `repositorio_violation_fires_before_kind_coherence_mesh_slot`
4665        // pin (577b0a9) on the `:repositorio` axis vs the same
4666        // kind-coherence gates.
4667        let root = PathBuf::from("/tmp/x");
4668        let manifest = root.join("caixa.lisp");
4669        let default_lib = root.join("lib").join("demo.lisp");
4670        let layout =
4671            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4672        let mut c = caixa(CaixaKind::Biblioteca);
4673        c.descricao = Some(String::new());
4674        c.membros = vec![crate::aplicacao::Membro {
4675            caixa: "x".into(),
4676            versao: "^0.1".into(),
4677        }];
4678        let err = layout.verify(&c, &root).unwrap_err();
4679        assert!(
4680            matches!(err, LayoutError::DescricaoViolation { .. }),
4681            "got {err:?}",
4682        );
4683    }
4684
4685    #[test]
4686    fn descricao_violation_fires_after_repositorio_violation() {
4687        // Cross-axis precedence pin (inside the universal metadata
4688        // cascade): a caixa with both a malformed `:repositorio` *and*
4689        // an empty `:descricao` surfaces `RepositorioViolation`
4690        // first — `:repositorio` is the sixth universal axis in the
4691        // cascade and runs before `:descricao`, peer with the
4692        // canonical identity-axis-first cascade the peer gates
4693        // establish. Mirrors the peer
4694        // `repositorio_violation_fires_after_autores_violation`
4695        // precedence pin (577b0a9) on the autores-axis-before-
4696        // repositorio-axis pair.
4697        let root = PathBuf::from("/tmp/x");
4698        let manifest = root.join("caixa.lisp");
4699        let default_lib = root.join("lib").join("demo.lisp");
4700        let layout =
4701            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4702        let mut c = caixa(CaixaKind::Biblioteca);
4703        c.repositorio = Some(String::new());
4704        c.descricao = Some(String::new());
4705        let err = layout.verify(&c, &root).unwrap_err();
4706        assert!(
4707            matches!(err, LayoutError::RepositorioViolation { .. }),
4708            "got {err:?}",
4709        );
4710    }
4711
4712    #[test]
4713    fn descricao_violation_accepts_none() {
4714        // Positive control sanity pin: a caixa that omits
4715        // `:descricao` entirely (the canonical `Caixa::template` shape
4716        // carries `Some("FIXME — describe this caixa")`, but the
4717        // layout-test fixture defaults to `None`) passes the gate
4718        // trivially — the gate is a no-op when the author didn't
4719        // author a value. Mirrors the peer
4720        // `repositorio_violation_accepts_canonical_template` pin
4721        // (577b0a9).
4722        let root = PathBuf::from("/tmp/x");
4723        let manifest = root.join("caixa.lisp");
4724        let default_lib = root.join("lib").join("demo.lisp");
4725        let layout =
4726            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4727        let c = caixa(CaixaKind::Biblioteca);
4728        layout.verify(&c, &root).expect("None must pass");
4729    }
4730
4731    #[test]
4732    fn descricao_violation_accepts_canonical_summary() {
4733        // Positive control pin on the canonical pleme-io `:descricao`
4734        // shape: a short free-form prose summary the `caixa-helm` /
4735        // `caixa-flux` / `caixa-mesh` fixtures all carry passes the
4736        // gate end-to-end.
4737        let root = PathBuf::from("/tmp/x");
4738        let manifest = root.join("caixa.lisp");
4739        let default_lib = root.join("lib").join("demo.lisp");
4740        let layout =
4741            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4742        let mut c = caixa(CaixaKind::Biblioteca);
4743        c.descricao = Some("Canonical Rust→wasm32-wasip2 caixa Servico.".into());
4744        layout
4745            .verify(&c, &root)
4746            .expect("canonical summary must pass");
4747    }
4748
4749    #[test]
4750    fn descricao_violation_on_non_chart_shape() {
4751        // Shape-predicate wire-up pin: a malformed `:descricao` value
4752        // that's a non-empty `Some(s)` but carries a paste-from-
4753        // multiline-doc embedded newline surfaces the
4754        // `DescricaoViolation` envelope via the manifest-layer
4755        // `ManifestError::DescricaoInvalid` arm. Mirrors the peer
4756        // `descricao_violation_on_empty_some` shape on the empty arm
4757        // of the same axis and the peer
4758        // `licenca_violation_on_non_spdx_shape` shape on the sibling
4759        // `:licenca` axis. Until this gate landed a value like
4760        // `"Checkout\nflow."` (an embedded newline) or `"Checkout
4761        // flow. "` (a trailing whitespace) silently passed
4762        // `StandardLayout::verify` and landed in the rendered
4763        // Chart.yaml `description:` field as a YAML-illegal
4764        // multi-line scalar or a silently-trimmed whitespace
4765        // round-trip far from the source caixa.lisp.
4766        let root = PathBuf::from("/tmp/x");
4767        let manifest = root.join("caixa.lisp");
4768        let default_lib = root.join("lib").join("demo.lisp");
4769        let layout =
4770            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4771        let mut c = caixa(CaixaKind::Biblioteca);
4772        c.descricao = Some("Checkout\nflow.".into());
4773        let err = layout.verify(&c, &root).unwrap_err();
4774        let LayoutError::DescricaoViolation { caixa, issue } = err else {
4775            panic!("expected LayoutError::DescricaoViolation, got {err:?}");
4776        };
4777        assert_eq!(caixa, "demo");
4778        assert!(
4779            issue.contains(":descricao"),
4780            "issue must name the offending slot: {issue}",
4781        );
4782        // The wrapped `ManifestError::DescricaoInvalid` Display uses
4783        // `{descricao:?}` (Debug) so the embedded newline surfaces
4784        // debug-escaped as `\n` in the issue string.
4785        assert!(
4786            issue.contains("Checkout\\nflow."),
4787            "issue must quote the offending value (debug-escaped): {issue}",
4788        );
4789    }
4790
4791    // ── :licenca empty-Some shape wired into verify (universal axis) ──
4792    //
4793    // Until this wire-up landed `Caixa::validate_licenca` did not
4794    // exist — the universal SPDX-shaped license-expression axis had
4795    // no shape gate at any layer, so an empty `Some("")` silently
4796    // passed `Caixa::from_lisp` and `StandardLayout::verify` and
4797    // landed as a bare trailing period in the rendered
4798    // `lareira-<nome>` chart's `README.md` `## License` section via
4799    // the `caixa-helm` consumer's `caixa.licenca.clone().unwrap_or_else(||
4800    // "MIT".into())` (which only fires on `None`) at
4801    // `caixa-helm/src/lib.rs:361`. Closes the same `Some("")`
4802    // skips-`unwrap_or_else` footgun the peer `:repositorio`
4803    // (577b0a9) and `:descricao` (4e6db38) gates closed, on the
4804    // universal license-expression axis.
4805
4806    #[test]
4807    fn licenca_violation_on_empty_some() {
4808        // Canonical paste-from-blank-doc footgun on every kind. The
4809        // wrap envelope wraps [`ManifestError::LicencaEmpty`]'s
4810        // Display through verbatim, so the issue string names the
4811        // offending `:licenca` axis at the source — the author can
4812        // grep their caixa.lisp for `:licenca ""` and fix the empty
4813        // value in one edit. Mirrors the peer
4814        // `descricao_violation_on_empty_some` shape (4e6db38) on
4815        // the sibling `Option<String>` `:licenca` axis.
4816        let root = PathBuf::from("/tmp/x");
4817        let manifest = root.join("caixa.lisp");
4818        let default_lib = root.join("lib").join("demo.lisp");
4819        let layout =
4820            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4821        let mut c = caixa(CaixaKind::Biblioteca);
4822        c.licenca = Some(String::new());
4823        let err = layout.verify(&c, &root).unwrap_err();
4824        let LayoutError::LicencaViolation { caixa, issue } = err else {
4825            panic!("expected LayoutError::LicencaViolation, got {err:?}");
4826        };
4827        assert_eq!(caixa, "demo");
4828        assert!(
4829            issue.contains(":licenca"),
4830            "issue must name the offending slot: {issue}",
4831        );
4832    }
4833
4834    #[test]
4835    fn licenca_violation_fires_before_kind_coherence_mesh_slot() {
4836        // Cross-axis precedence pin: a Biblioteca with empty
4837        // `:licenca` *and* declared mesh slots (`:membros`)
4838        // surfaces the universal `:licenca` diagnostic first, not
4839        // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
4840        // `:licenca` is universal (every kind owns the slot), so
4841        // its shape diagnostic is more fundamental than the
4842        // partition-on-kind diagnostic. Mirrors the peer
4843        // `descricao_violation_fires_before_kind_coherence_mesh_slot`
4844        // pin (4e6db38) on the `:descricao` axis vs the same
4845        // kind-coherence gates.
4846        let root = PathBuf::from("/tmp/x");
4847        let manifest = root.join("caixa.lisp");
4848        let default_lib = root.join("lib").join("demo.lisp");
4849        let layout =
4850            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4851        let mut c = caixa(CaixaKind::Biblioteca);
4852        c.licenca = Some(String::new());
4853        c.membros = vec![crate::aplicacao::Membro {
4854            caixa: "x".into(),
4855            versao: "^0.1".into(),
4856        }];
4857        let err = layout.verify(&c, &root).unwrap_err();
4858        assert!(
4859            matches!(err, LayoutError::LicencaViolation { .. }),
4860            "got {err:?}",
4861        );
4862    }
4863
4864    #[test]
4865    fn licenca_violation_fires_after_descricao_violation() {
4866        // Cross-axis precedence pin (inside the universal metadata
4867        // cascade): a caixa with both an empty `:descricao` *and*
4868        // an empty `:licenca` surfaces `DescricaoViolation`
4869        // first — `:descricao` is the seventh universal axis in the
4870        // cascade and runs before `:licenca`, peer with the
4871        // canonical identity-axis-first cascade the peer gates
4872        // establish. Mirrors the peer
4873        // `descricao_violation_fires_after_repositorio_violation`
4874        // precedence pin (4e6db38) on the repositorio-axis-before-
4875        // descricao-axis pair.
4876        let root = PathBuf::from("/tmp/x");
4877        let manifest = root.join("caixa.lisp");
4878        let default_lib = root.join("lib").join("demo.lisp");
4879        let layout =
4880            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4881        let mut c = caixa(CaixaKind::Biblioteca);
4882        c.descricao = Some(String::new());
4883        c.licenca = Some(String::new());
4884        let err = layout.verify(&c, &root).unwrap_err();
4885        assert!(
4886            matches!(err, LayoutError::DescricaoViolation { .. }),
4887            "got {err:?}",
4888        );
4889    }
4890
4891    #[test]
4892    fn licenca_violation_accepts_none() {
4893        // Positive control sanity pin: a caixa that omits `:licenca`
4894        // entirely (the layout-test fixture defaults to `None`)
4895        // passes the gate trivially — the gate is a no-op when the
4896        // author didn't author a value. Mirrors the peer
4897        // `descricao_violation_accepts_none` pin (4e6db38).
4898        let root = PathBuf::from("/tmp/x");
4899        let manifest = root.join("caixa.lisp");
4900        let default_lib = root.join("lib").join("demo.lisp");
4901        let layout =
4902            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4903        let c = caixa(CaixaKind::Biblioteca);
4904        layout.verify(&c, &root).expect("None must pass");
4905    }
4906
4907    #[test]
4908    fn licenca_violation_accepts_canonical_expression() {
4909        // Positive control pin on the canonical pleme-io `:licenca`
4910        // shape: a non-empty SPDX expression the `caixa-helm` /
4911        // `caixa-flux` / `caixa-mesh` fixtures all carry (`"MIT"`)
4912        // passes the gate end-to-end.
4913        let root = PathBuf::from("/tmp/x");
4914        let manifest = root.join("caixa.lisp");
4915        let default_lib = root.join("lib").join("demo.lisp");
4916        let layout =
4917            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4918        let mut c = caixa(CaixaKind::Biblioteca);
4919        c.licenca = Some("Apache-2.0 OR MIT".into());
4920        layout
4921            .verify(&c, &root)
4922            .expect("canonical SPDX expression must pass");
4923    }
4924
4925    #[test]
4926    fn licenca_violation_on_non_spdx_shape() {
4927        // Shape-predicate wire-up pin: a malformed `:licenca` value
4928        // that's a non-empty `Some(s)` but falls outside the SPDX
4929        // expression alphabet floor surfaces the `LicencaViolation`
4930        // envelope via the manifest-layer `ManifestError::LicencaInvalid`
4931        // arm. Mirrors the peer `licenca_violation_on_empty_some`
4932        // shape on the empty arm of the same axis and the peer
4933        // `edicao_violation_on_non_year_shape` shape on the sibling
4934        // `:edicao` axis. Until this gate landed a value like
4935        // `"Apache_2.0"` (an underscore-instead-of-hyphen typo) or
4936        // `"MIT, Apache-2.0"` (a comma-instead-of-`OR`-keyword
4937        // colloquial idiom) silently passed `StandardLayout::verify`
4938        // and landed in the rendered chart `README.md` `## License`
4939        // section + a future SPDX-aware Chart.yaml `license:`
4940        // emitter would refuse the value at `helm lint` time far
4941        // from the source caixa.lisp.
4942        let root = PathBuf::from("/tmp/x");
4943        let manifest = root.join("caixa.lisp");
4944        let default_lib = root.join("lib").join("demo.lisp");
4945        let layout =
4946            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4947        let mut c = caixa(CaixaKind::Biblioteca);
4948        c.licenca = Some("Apache_2.0".into());
4949        let err = layout.verify(&c, &root).unwrap_err();
4950        let LayoutError::LicencaViolation { caixa, issue } = err else {
4951            panic!("expected LayoutError::LicencaViolation, got {err:?}");
4952        };
4953        assert_eq!(caixa, "demo");
4954        assert!(
4955            issue.contains(":licenca"),
4956            "issue must name the offending slot: {issue}",
4957        );
4958        assert!(
4959            issue.contains("Apache_2.0"),
4960            "issue must quote the offending value: {issue}",
4961        );
4962    }
4963
4964    // ── :edicao empty-Some shape wired into verify (universal axis) ──
4965    //
4966    // Until this wire-up landed `Caixa::validate_edicao` did not
4967    // exist — the universal language-edition axis had no shape gate
4968    // at any layer, so an empty `Some("")` silently passed
4969    // `Caixa::from_lisp` and `StandardLayout::verify` and landed as a
4970    // bare `(:edicao "")` line in the rendered caixa.lisp, ready for
4971    // a future renderer-side consumer's `Option::unwrap_or_else`
4972    // (which only fires on `None`) to skip its fallback. Closes the
4973    // same `Some("")`-skips-`unwrap_or_else` footgun the peer
4974    // `:repositorio` (577b0a9), `:descricao` (4e6db38), and
4975    // `:licenca` (3d1e535) gates closed, on the universal language-
4976    // edition axis — the last un-gated universal-axis
4977    // `Option<String>` Caixa-level value-shape surface.
4978
4979    #[test]
4980    fn edicao_violation_on_empty_some() {
4981        // Canonical paste-from-blank-doc footgun on every kind. The
4982        // wrap envelope wraps [`ManifestError::EdicaoEmpty`]'s
4983        // Display through verbatim, so the issue string names the
4984        // offending `:edicao` axis at the source — the author can
4985        // grep their caixa.lisp for `:edicao ""` and fix the empty
4986        // value in one edit. Mirrors the peer
4987        // `licenca_violation_on_empty_some` shape (3d1e535) on the
4988        // sibling `Option<String>` `:edicao` axis.
4989        let root = PathBuf::from("/tmp/x");
4990        let manifest = root.join("caixa.lisp");
4991        let default_lib = root.join("lib").join("demo.lisp");
4992        let layout =
4993            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
4994        let mut c = caixa(CaixaKind::Biblioteca);
4995        c.edicao = Some(String::new());
4996        let err = layout.verify(&c, &root).unwrap_err();
4997        let LayoutError::EdicaoViolation { caixa, issue } = err else {
4998            panic!("expected LayoutError::EdicaoViolation, got {err:?}");
4999        };
5000        assert_eq!(caixa, "demo");
5001        assert!(
5002            issue.contains(":edicao"),
5003            "issue must name the offending slot: {issue}",
5004        );
5005    }
5006
5007    #[test]
5008    fn edicao_violation_fires_before_kind_coherence_mesh_slot() {
5009        // Cross-axis precedence pin: a Biblioteca with empty
5010        // `:edicao` *and* declared mesh slots (`:membros`) surfaces
5011        // the universal `:edicao` diagnostic first, not the
5012        // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
5013        // `:edicao` is universal (every kind owns the slot), so
5014        // its shape diagnostic is more fundamental than the
5015        // partition-on-kind diagnostic. Mirrors the peer
5016        // `licenca_violation_fires_before_kind_coherence_mesh_slot`
5017        // pin (3d1e535) on the `:licenca` axis vs the same
5018        // kind-coherence gates.
5019        let root = PathBuf::from("/tmp/x");
5020        let manifest = root.join("caixa.lisp");
5021        let default_lib = root.join("lib").join("demo.lisp");
5022        let layout =
5023            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5024        let mut c = caixa(CaixaKind::Biblioteca);
5025        c.edicao = Some(String::new());
5026        c.membros = vec![crate::aplicacao::Membro {
5027            caixa: "x".into(),
5028            versao: "^0.1".into(),
5029        }];
5030        let err = layout.verify(&c, &root).unwrap_err();
5031        assert!(
5032            matches!(err, LayoutError::EdicaoViolation { .. }),
5033            "got {err:?}",
5034        );
5035    }
5036
5037    #[test]
5038    fn edicao_violation_fires_after_licenca_violation() {
5039        // Cross-axis precedence pin (inside the universal metadata
5040        // cascade): a caixa with both an empty `:licenca` *and* an
5041        // empty `:edicao` surfaces `LicencaViolation` first —
5042        // `:licenca` is the eighth universal axis in the cascade
5043        // and runs before `:edicao`, peer with the canonical
5044        // identity-axis-first cascade the peer gates establish.
5045        // Mirrors the peer
5046        // `licenca_violation_fires_after_descricao_violation`
5047        // precedence pin (3d1e535) on the descricao-axis-before-
5048        // licenca-axis pair.
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 mut c = caixa(CaixaKind::Biblioteca);
5055        c.licenca = Some(String::new());
5056        c.edicao = Some(String::new());
5057        let err = layout.verify(&c, &root).unwrap_err();
5058        assert!(
5059            matches!(err, LayoutError::LicencaViolation { .. }),
5060            "got {err:?}",
5061        );
5062    }
5063
5064    #[test]
5065    fn edicao_violation_accepts_none() {
5066        // Positive control sanity pin: a caixa that omits `:edicao`
5067        // entirely (the layout-test fixture defaults to `None`)
5068        // passes the gate trivially — the gate is a no-op when the
5069        // author didn't author a value. Mirrors the peer
5070        // `licenca_violation_accepts_none` pin (3d1e535).
5071        let root = PathBuf::from("/tmp/x");
5072        let manifest = root.join("caixa.lisp");
5073        let default_lib = root.join("lib").join("demo.lisp");
5074        let layout =
5075            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5076        let c = caixa(CaixaKind::Biblioteca);
5077        layout.verify(&c, &root).expect("None must pass");
5078    }
5079
5080    #[test]
5081    fn edicao_violation_accepts_canonical_value() {
5082        // Positive control pin on the canonical pleme-io `:edicao`
5083        // shape: the `"2026"` edition every `caixa-helm` /
5084        // `caixa-flux` / `caixa-mesh` / `caixa-core/src/render.rs`
5085        // fixture carries by construction passes the gate end-to-end.
5086        let root = PathBuf::from("/tmp/x");
5087        let manifest = root.join("caixa.lisp");
5088        let default_lib = root.join("lib").join("demo.lisp");
5089        let layout =
5090            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5091        let mut c = caixa(CaixaKind::Biblioteca);
5092        c.edicao = Some("2026".into());
5093        layout
5094            .verify(&c, &root)
5095            .expect("canonical edition must pass");
5096    }
5097
5098    #[test]
5099    fn edicao_violation_on_non_year_shape() {
5100        // Shape-predicate wire-up pin: a malformed `:edicao` value
5101        // that's a non-empty `Some(s)` but not a 4-digit ASCII
5102        // decimal year surfaces the `EdicaoViolation` envelope via
5103        // the manifest-layer `ManifestError::EdicaoInvalid` arm.
5104        // Mirrors the peer `edicao_violation_on_empty_some` shape
5105        // on the empty arm of the same axis. Until this gate landed
5106        // a value like `"v2026"` (a familiar git-tag idiom that
5107        // doesn't apply to the year-shaped edition axis) silently
5108        // passed `StandardLayout::verify` and broke at the
5109        // substrate's build-time edition selector far from the
5110        // source caixa.lisp.
5111        let root = PathBuf::from("/tmp/x");
5112        let manifest = root.join("caixa.lisp");
5113        let default_lib = root.join("lib").join("demo.lisp");
5114        let layout =
5115            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5116        let mut c = caixa(CaixaKind::Biblioteca);
5117        c.edicao = Some("v2026".into());
5118        let err = layout.verify(&c, &root).unwrap_err();
5119        let LayoutError::EdicaoViolation { caixa, issue } = err else {
5120            panic!("expected LayoutError::EdicaoViolation, got {err:?}");
5121        };
5122        assert_eq!(caixa, "demo");
5123        assert!(
5124            issue.contains(":edicao"),
5125            "issue must name the offending slot: {issue}",
5126        );
5127        assert!(
5128            issue.contains("v2026"),
5129            "issue must quote the offending value: {issue}",
5130        );
5131    }
5132
5133    // ── Caixa-identity gates (`:nome`, `:versao`) wired into verify ────
5134    //
5135    // Until this wire-up landed `Caixa::validate_nome` and
5136    // `Caixa::validate_versao` lived as `pub fn` on `Caixa` with full
5137    // per-arm unit coverage in `manifest::tests`, but no production
5138    // path called them — `feira build` silently accepted malformed
5139    // `:nome` / `:versao` and the failure surfaced at `helm install` /
5140    // `kubectl apply` / `feira publish` / lacre-resolve / `:upgrade-from
5141    // :from` matching time, far from the source `caixa.lisp`. The
5142    // following pins fence the layout-pipeline wire-up: every layout
5143    // verify on a structurally-invalid Caixa identity axis surfaces
5144    // the per-axis `*Violation { caixa, issue }` envelope before any
5145    // kind-coherence, code-path, or downstream gate sees it.
5146
5147    #[test]
5148    fn nome_violation_on_uppercase() {
5149        let root = PathBuf::from("/tmp/x");
5150        let manifest = root.join("caixa.lisp");
5151        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5152        let mut c = caixa(CaixaKind::Biblioteca);
5153        c.nome = "MyApp".into();
5154        let err = layout.verify(&c, &root).unwrap_err();
5155        let LayoutError::NomeViolation { caixa, issue } = err else {
5156            panic!("expected LayoutError::NomeViolation, got {err:?}");
5157        };
5158        assert_eq!(caixa, "MyApp");
5159        assert!(
5160            issue.contains("MyApp"),
5161            "issue must quote the offending nome: {issue}",
5162        );
5163    }
5164
5165    #[test]
5166    fn nome_violation_on_underscore() {
5167        let root = PathBuf::from("/tmp/x");
5168        let manifest = root.join("caixa.lisp");
5169        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5170        let mut c = caixa(CaixaKind::Biblioteca);
5171        c.nome = "my_app".into();
5172        let err = layout.verify(&c, &root).unwrap_err();
5173        assert!(
5174            matches!(err, LayoutError::NomeViolation { ref caixa, .. } if caixa == "my_app"),
5175            "got {err:?}",
5176        );
5177    }
5178
5179    #[test]
5180    fn nome_violation_on_empty() {
5181        // Empty `:nome` surfaces NomeViolation wrapping the narrower
5182        // `ManifestError::NomeEmpty` arm — the empty-first cascade the
5183        // peer per-axis name gates already use.
5184        let root = PathBuf::from("/tmp/x");
5185        let manifest = root.join("caixa.lisp");
5186        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5187        let mut c = caixa(CaixaKind::Biblioteca);
5188        c.nome = String::new();
5189        let err = layout.verify(&c, &root).unwrap_err();
5190        let LayoutError::NomeViolation { caixa, issue } = err else {
5191            panic!("expected LayoutError::NomeViolation, got {err:?}");
5192        };
5193        assert!(caixa.is_empty());
5194        assert!(
5195            issue.contains(":nome is empty"),
5196            "issue must surface the empty-arm diagnostic: {issue}",
5197        );
5198    }
5199
5200    #[test]
5201    fn versao_violation_on_missing_patch() {
5202        // `"0.1"` — the canonical "I shortened it" footgun. Helm /
5203        // OCI / lacre-resolve / `:upgrade-from :from` all strict-parse
5204        // through `semver::Version::parse`, which refuses a two-part
5205        // shape.
5206        let root = PathBuf::from("/tmp/x");
5207        let manifest = root.join("caixa.lisp");
5208        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5209        let mut c = caixa(CaixaKind::Biblioteca);
5210        c.versao = "0.1".into();
5211        let err = layout.verify(&c, &root).unwrap_err();
5212        let LayoutError::VersaoViolation { caixa, issue } = err else {
5213            panic!("expected LayoutError::VersaoViolation, got {err:?}");
5214        };
5215        assert_eq!(caixa, "demo");
5216        assert!(
5217            issue.contains("0.1"),
5218            "issue must quote the offending versao: {issue}",
5219        );
5220    }
5221
5222    #[test]
5223    fn versao_violation_on_git_tag_shape() {
5224        // `"v0.1.0"` — the git-tag-shape-leaking-into-versao typo.
5225        let root = PathBuf::from("/tmp/x");
5226        let manifest = root.join("caixa.lisp");
5227        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5228        let mut c = caixa(CaixaKind::Biblioteca);
5229        c.versao = "v0.1.0".into();
5230        let err = layout.verify(&c, &root).unwrap_err();
5231        assert!(
5232            matches!(err, LayoutError::VersaoViolation { ref issue, .. }
5233                if issue.contains("v0.1.0")),
5234            "got {err:?}",
5235        );
5236    }
5237
5238    #[test]
5239    fn versao_violation_on_empty() {
5240        let root = PathBuf::from("/tmp/x");
5241        let manifest = root.join("caixa.lisp");
5242        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5243        let mut c = caixa(CaixaKind::Biblioteca);
5244        c.versao = String::new();
5245        let err = layout.verify(&c, &root).unwrap_err();
5246        let LayoutError::VersaoViolation { caixa, issue } = err else {
5247            panic!("expected LayoutError::VersaoViolation, got {err:?}");
5248        };
5249        assert_eq!(caixa, "demo");
5250        assert!(
5251            issue.contains(":versao is empty"),
5252            "issue must surface the empty-arm diagnostic: {issue}",
5253        );
5254    }
5255
5256    #[test]
5257    fn nome_violation_fires_before_versao_violation() {
5258        // Precedence pin: when both `:nome` and `:versao` are malformed,
5259        // `:nome` surfaces first — the canonical declaration-order
5260        // precedence the `ManifestError` family establishes, the same
5261        // grep-order the author follows when fixing in `caixa.lisp`.
5262        let root = PathBuf::from("/tmp/x");
5263        let manifest = root.join("caixa.lisp");
5264        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5265        let mut c = caixa(CaixaKind::Biblioteca);
5266        c.nome = "MyApp".into();
5267        c.versao = "0.1".into();
5268        let err = layout.verify(&c, &root).unwrap_err();
5269        assert!(
5270            matches!(err, LayoutError::NomeViolation { .. }),
5271            "got {err:?} — nome must fire before versao",
5272        );
5273    }
5274
5275    #[test]
5276    fn nome_violation_fires_before_kind_coherence() {
5277        // Precedence pin: a Biblioteca caixa with a malformed `:nome`
5278        // AND a declared mesh slot surfaces NomeViolation, not
5279        // MeshSlotsOnNonAplicacao — the identity-axis gate is more
5280        // fundamental than the kind-coherence gate (which carries
5281        // `caixa.nome` verbatim in its diagnostic, and so depends on the
5282        // name being structurally valid to render a useful message).
5283        let root = PathBuf::from("/tmp/x");
5284        let manifest = root.join("caixa.lisp");
5285        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5286        let mut c = caixa(CaixaKind::Biblioteca);
5287        c.nome = "MyApp".into();
5288        c.membros = vec![crate::aplicacao::Membro {
5289            caixa: "x".into(),
5290            versao: "^0.1".into(),
5291        }];
5292        let err = layout.verify(&c, &root).unwrap_err();
5293        assert!(
5294            matches!(err, LayoutError::NomeViolation { .. }),
5295            "got {err:?} — nome must fire before MeshSlotsOnNonAplicacao",
5296        );
5297    }
5298
5299    #[test]
5300    fn nome_violation_fires_before_owncode() {
5301        // Precedence pin: a Supervisor with a malformed `:nome` AND
5302        // declared `:bibliotecas` surfaces NomeViolation, not
5303        // SupervisorOwnsCode — same rationale as above.
5304        let root = PathBuf::from("/tmp/x");
5305        let manifest = root.join("caixa.lisp");
5306        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5307        let mut c = caixa(CaixaKind::Supervisor);
5308        c.nome = "MyApp".into();
5309        c.bibliotecas = vec!["lib/x.lisp".into()];
5310        let err = layout.verify(&c, &root).unwrap_err();
5311        assert!(
5312            matches!(err, LayoutError::NomeViolation { .. }),
5313            "got {err:?} — nome must fire before SupervisorOwnsCode",
5314        );
5315    }
5316
5317    #[test]
5318    fn versao_violation_fires_before_kind_coherence() {
5319        // Precedence pin: a Biblioteca with a valid `:nome` but a
5320        // malformed `:versao` AND a declared servico slot surfaces
5321        // VersaoViolation before ServicoSlotsOnNonServico.
5322        let root = PathBuf::from("/tmp/x");
5323        let manifest = root.join("caixa.lisp");
5324        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5325        let mut c = caixa(CaixaKind::Biblioteca);
5326        c.versao = "v0.1.0".into();
5327        c.limits = Some(crate::LimitsSpec {
5328            memory: Some(64 * 1024 * 1024),
5329            ..Default::default()
5330        });
5331        let err = layout.verify(&c, &root).unwrap_err();
5332        assert!(
5333            matches!(err, LayoutError::VersaoViolation { .. }),
5334            "got {err:?} — versao must fire before ServicoSlotsOnNonServico",
5335        );
5336    }
5337
5338    #[test]
5339    fn nome_violation_fires_before_missing_lib() {
5340        // Precedence pin: a Biblioteca with a malformed `:nome` and no
5341        // lib entry surfaces NomeViolation, not MissingLib — the
5342        // identity-axis gate is more fundamental than the layout's
5343        // `lib/<nome>.lisp` default-path check (which derives the
5344        // expected path from `:nome` itself, so would surface a
5345        // misleading "expected lib/MyApp.lisp" diagnostic against an
5346        // unrecoverable name).
5347        let root = PathBuf::from("/tmp/x");
5348        let manifest = root.join("caixa.lisp");
5349        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5350        let mut c = caixa(CaixaKind::Biblioteca);
5351        c.nome = "MyApp".into();
5352        let err = layout.verify(&c, &root).unwrap_err();
5353        assert!(
5354            matches!(err, LayoutError::NomeViolation { .. }),
5355            "got {err:?} — nome must fire before MissingLib",
5356        );
5357    }
5358
5359    #[test]
5360    fn nome_versao_violations_fire_after_missing_manifest() {
5361        // Precedence pin: `MissingManifest` still dominates — there's
5362        // no caixa to identity-check when the manifest is missing.
5363        let root = PathBuf::from("/tmp/x");
5364        let layout = StandardLayout::new().with_path_exists(|_| false);
5365        let mut c = caixa(CaixaKind::Biblioteca);
5366        c.nome = "MyApp".into();
5367        c.versao = "0.1".into();
5368        let err = layout.verify(&c, &root).unwrap_err();
5369        assert!(
5370            matches!(err, LayoutError::MissingManifest(_)),
5371            "got {err:?} — MissingManifest must dominate identity gates",
5372        );
5373    }
5374
5375    #[test]
5376    fn valid_nome_versao_passes_to_downstream_gates() {
5377        // Sanity pin: the canonical "demo" / "0.1.0" identity passes
5378        // both axes; downstream gates (MissingLib here) take over.
5379        let root = PathBuf::from("/tmp/x");
5380        let manifest = root.join("caixa.lisp");
5381        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5382        let err = layout
5383            .verify(&caixa(CaixaKind::Biblioteca), &root)
5384            .unwrap_err();
5385        assert!(
5386            matches!(err, LayoutError::MissingLib { .. }),
5387            "got {err:?} — valid identity must pass to MissingLib",
5388        );
5389    }
5390
5391    // ── :deps / :deps-dev shape gate (lifted to layout-level verify) ─────
5392    //
5393    // Until this wire-up landed `Caixa::validate_deps` lived as `pub fn`
5394    // on `Caixa` with full per-arm unit coverage in `manifest::tests` +
5395    // `dep::tests` but no production path called it — `feira build`
5396    // silently accepted a malformed `:deps` / `:deps-dev` entry and the
5397    // failure surfaced at lacre-resolve / `git clone` / `cargo metadata`
5398    // / `helm install` time on the *first* downstream consumer to
5399    // strict-parse the value, far from the source `caixa.lisp` and
5400    // without any field naming the offending `:deps` axis. The following
5401    // pins fence the layout-pipeline wire-up: every layout verify on a
5402    // structurally-invalid `:deps` value-shape surfaces the per-axis
5403    // `DepsViolation { caixa, issue }` envelope (peer of
5404    // `NomeViolation` / `VersaoViolation` / `CodePathViolation` /
5405    // `LimitsViolation` / `BehaviorViolation` / `UpgradeViolation` /
5406    // `SupervisorViolation` / `AplicacaoViolation`) before any kind-
5407    // coherence, code-path, or downstream gate sees it.
5408
5409    #[test]
5410    fn deps_violation_on_empty_dep_nome() {
5411        // Empty `:nome` on a `:deps` entry surfaces the narrower
5412        // `DepError::NomeEmpty` arm through the wrap envelope.
5413        use crate::Dep;
5414        let root = PathBuf::from("/tmp/x");
5415        let manifest = root.join("caixa.lisp");
5416        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5417        let mut c = caixa(CaixaKind::Biblioteca);
5418        c.deps = vec![Dep::simple("", "^0.1")];
5419        let err = layout.verify(&c, &root).unwrap_err();
5420        let LayoutError::DepsViolation { caixa, issue } = err else {
5421            panic!("expected LayoutError::DepsViolation, got {err:?}");
5422        };
5423        assert_eq!(caixa, "demo");
5424        assert!(
5425            issue.contains(":deps") && issue.contains(":nome"),
5426            "issue must name the offending slot + axis: {issue}",
5427        );
5428    }
5429
5430    #[test]
5431    fn deps_violation_on_uppercase_dep_nome() {
5432        // Uppercase `:nome` on a `:deps` entry surfaces
5433        // `DepError::NomeInvalid` (DNS-1123 violation) through the wrap.
5434        use crate::Dep;
5435        let root = PathBuf::from("/tmp/x");
5436        let manifest = root.join("caixa.lisp");
5437        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5438        let mut c = caixa(CaixaKind::Biblioteca);
5439        c.deps = vec![Dep::simple("Caixa-Teia", "^0.1")];
5440        let err = layout.verify(&c, &root).unwrap_err();
5441        let LayoutError::DepsViolation { caixa, issue } = err else {
5442            panic!("expected LayoutError::DepsViolation, got {err:?}");
5443        };
5444        assert_eq!(caixa, "demo");
5445        assert!(
5446            issue.contains("Caixa-Teia"),
5447            "issue must quote the offending dep nome verbatim: {issue}",
5448        );
5449    }
5450
5451    #[test]
5452    fn deps_violation_on_unparseable_dep_versao() {
5453        // Unparseable `:versao` requirement on a `:deps` entry surfaces
5454        // `DepError::VersaoInvalid` through the wrap — the canonical
5455        // "the semver::Error reached the resolver, far from the source"
5456        // footgun closed at author time.
5457        use crate::Dep;
5458        let root = PathBuf::from("/tmp/x");
5459        let manifest = root.join("caixa.lisp");
5460        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5461        let mut c = caixa(CaixaKind::Biblioteca);
5462        c.deps = vec![Dep::simple("caixa-teia", "not-a-req")];
5463        let err = layout.verify(&c, &root).unwrap_err();
5464        let LayoutError::DepsViolation { caixa, issue } = err else {
5465            panic!("expected LayoutError::DepsViolation, got {err:?}");
5466        };
5467        assert_eq!(caixa, "demo");
5468        assert!(
5469            issue.contains("caixa-teia") && issue.contains("not-a-req"),
5470            "issue must quote the dep nome + offending versao: {issue}",
5471        );
5472    }
5473
5474    #[test]
5475    fn deps_violation_on_duplicate_nome_in_deps() {
5476        // Within-list `:deps :nome` duplicate surfaces
5477        // `DepError::DuplicateNome { list: ":deps" }` through the wrap.
5478        use crate::Dep;
5479        let root = PathBuf::from("/tmp/x");
5480        let manifest = root.join("caixa.lisp");
5481        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5482        let mut c = caixa(CaixaKind::Biblioteca);
5483        c.deps = vec![
5484            Dep::simple("caixa-teia", "^0.1"),
5485            Dep::simple("caixa-teia", "^0.2"),
5486        ];
5487        let err = layout.verify(&c, &root).unwrap_err();
5488        let LayoutError::DepsViolation { caixa, issue } = err else {
5489            panic!("expected LayoutError::DepsViolation, got {err:?}");
5490        };
5491        assert_eq!(caixa, "demo");
5492        assert!(
5493            issue.contains("caixa-teia") && issue.contains(":deps"),
5494            "issue must quote the duplicated nome + list: {issue}",
5495        );
5496    }
5497
5498    #[test]
5499    fn deps_violation_on_duplicate_nome_in_deps_dev() {
5500        // Within-list `:deps-dev :nome` duplicate surfaces the same
5501        // diagnostic on the dev-only axis — neither list is a
5502        // second-class citizen of the typed surface.
5503        use crate::Dep;
5504        let root = PathBuf::from("/tmp/x");
5505        let manifest = root.join("caixa.lisp");
5506        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5507        let mut c = caixa(CaixaKind::Biblioteca);
5508        c.deps_dev = vec![
5509            Dep::simple("caixa-teia", "^0.1"),
5510            Dep::simple("caixa-teia", "^0.2"),
5511        ];
5512        let err = layout.verify(&c, &root).unwrap_err();
5513        let LayoutError::DepsViolation { caixa, issue } = err else {
5514            panic!("expected LayoutError::DepsViolation, got {err:?}");
5515        };
5516        assert_eq!(caixa, "demo");
5517        assert!(
5518            issue.contains(":deps-dev"),
5519            "issue must name the offending list: {issue}",
5520        );
5521    }
5522
5523    #[test]
5524    fn deps_violation_in_deps_fires_before_deps_dev() {
5525        // Precedence pin: when *both* `:deps` and `:deps-dev` carry a
5526        // malformed entry, the `:deps` walk fires first — the canonical
5527        // declaration-order precedence `Caixa::validate_deps` establishes
5528        // (the same author-grep ordering the typed-graph peers use on
5529        // every other Vec-shaped surface).
5530        use crate::Dep;
5531        let root = PathBuf::from("/tmp/x");
5532        let manifest = root.join("caixa.lisp");
5533        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5534        let mut c = caixa(CaixaKind::Biblioteca);
5535        c.deps = vec![Dep::simple("Bad-In-Deps", "^0.1")];
5536        c.deps_dev = vec![Dep::simple("Bad-In-Deps-Dev", "^0.1")];
5537        let err = layout.verify(&c, &root).unwrap_err();
5538        let LayoutError::DepsViolation { caixa: _, issue } = err else {
5539            panic!("expected LayoutError::DepsViolation, got {err:?}");
5540        };
5541        assert!(
5542            issue.contains("Bad-In-Deps") && !issue.contains("Bad-In-Deps-Dev"),
5543            "issue must name the :deps offender, not :deps-dev: {issue}",
5544        );
5545    }
5546
5547    #[test]
5548    fn deps_violation_fires_after_versao_violation() {
5549        // Precedence pin: when both the top-level `:versao` and a `:deps`
5550        // entry are malformed, the Caixa-identity gate fires first — the
5551        // canonical declaration order on `Caixa` (`:nome` → `:versao` →
5552        // ... → `:deps`) and the same identity-axis-dominates-content-
5553        // axis discipline the peer `validate_nome` / `validate_versao`
5554        // wire-up established (1f74a5f). A malformed `:versao` would
5555        // otherwise quote `caixa.nome` against a downstream-shaped
5556        // diagnostic.
5557        use crate::Dep;
5558        let root = PathBuf::from("/tmp/x");
5559        let manifest = root.join("caixa.lisp");
5560        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5561        let mut c = caixa(CaixaKind::Biblioteca);
5562        c.versao = "v0.1.0".into();
5563        c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
5564        let err = layout.verify(&c, &root).unwrap_err();
5565        assert!(
5566            matches!(err, LayoutError::VersaoViolation { .. }),
5567            "got {err:?} — versao must fire before DepsViolation",
5568        );
5569    }
5570
5571    #[test]
5572    fn deps_violation_fires_before_kind_coherence() {
5573        // Precedence pin: a Supervisor with a malformed `:deps` entry
5574        // AND declared `:bibliotecas` (the canonical SupervisorOwnsCode
5575        // shape) surfaces DepsViolation, not SupervisorOwnsCode — the
5576        // dep surface is universal across all kinds and its shape gate
5577        // is more fundamental than the kind-coherence partitions on
5578        // `:bibliotecas` / `:exe` / `:servicos`. The author can fix the
5579        // dep typo without first being told to move their `:bibliotecas`
5580        // off a Supervisor.
5581        use crate::Dep;
5582        let root = PathBuf::from("/tmp/x");
5583        let manifest = root.join("caixa.lisp");
5584        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5585        let mut c = caixa(CaixaKind::Supervisor);
5586        c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
5587        c.bibliotecas = vec!["lib/x.lisp".into()];
5588        let err = layout.verify(&c, &root).unwrap_err();
5589        assert!(
5590            matches!(err, LayoutError::DepsViolation { .. }),
5591            "got {err:?} — DepsViolation must fire before SupervisorOwnsCode",
5592        );
5593    }
5594
5595    #[test]
5596    fn deps_violation_fires_after_missing_manifest() {
5597        // Precedence pin: `MissingManifest` still dominates — there's no
5598        // caixa to deps-check when the manifest is missing.
5599        use crate::Dep;
5600        let root = PathBuf::from("/tmp/x");
5601        let layout = StandardLayout::new().with_path_exists(|_| false);
5602        let mut c = caixa(CaixaKind::Biblioteca);
5603        c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
5604        let err = layout.verify(&c, &root).unwrap_err();
5605        assert!(
5606            matches!(err, LayoutError::MissingManifest(_)),
5607            "got {err:?} — MissingManifest must dominate the deps gate",
5608        );
5609    }
5610
5611    #[test]
5612    fn deps_violation_on_self_dep_in_deps() {
5613        // Cross-slot self-edge: a caixa whose `:deps` lists its own
5614        // `:nome` is rejected at the layout wire-up, the diagnostic
5615        // surfaces through the `DepsViolation` envelope with both the
5616        // offending list tag (`":deps"`) and the parent's `:nome`
5617        // verbatim. Until this wire-up landed the self-dep silently
5618        // passed `feira build` and the resolver's lacre-pipeline
5619        // closure walk either rejected mid-traversal (infinite
5620        // recursion detected far from the source caixa.lisp) or, on
5621        // the unbounded path, recursed until it exhausted its stack.
5622        // Mirrors the supervision-tree
5623        // [`supervisor_violation_on_self_supervision`] and the
5624        // Aplicacao-membership self-edge wire-up tests on the peer
5625        // typed-name-graph axes.
5626        use crate::Dep;
5627        let root = PathBuf::from("/tmp/x");
5628        let manifest = root.join("caixa.lisp");
5629        let default_lib = root.join("lib").join("demo.lisp");
5630        let layout =
5631            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5632        let mut c = caixa(CaixaKind::Biblioteca);
5633        c.deps = vec![Dep::simple("demo", "^0.1")];
5634        let err = layout.verify(&c, &root).unwrap_err();
5635        let LayoutError::DepsViolation { caixa, issue } = err else {
5636            panic!("expected LayoutError::DepsViolation, got {err:?}");
5637        };
5638        assert_eq!(caixa, "demo");
5639        assert!(
5640            issue.contains(":deps") && issue.contains("demo"),
5641            "issue must name the offending list + parent :nome: {issue}",
5642        );
5643    }
5644
5645    #[test]
5646    fn deps_violation_on_self_dep_in_deps_dev() {
5647        // Same cross-slot self-edge gate on the `:deps-dev` axis —
5648        // neither dep list is a second-class citizen of the typed
5649        // surface. The diagnostic names `:deps-dev` so the author can
5650        // grep their caixa.lisp for the offending block directly.
5651        use crate::Dep;
5652        let root = PathBuf::from("/tmp/x");
5653        let manifest = root.join("caixa.lisp");
5654        let default_lib = root.join("lib").join("demo.lisp");
5655        let layout =
5656            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
5657        let mut c = caixa(CaixaKind::Biblioteca);
5658        c.deps_dev = vec![Dep::simple("demo", "^0.1")];
5659        let err = layout.verify(&c, &root).unwrap_err();
5660        let LayoutError::DepsViolation { caixa, issue } = err else {
5661            panic!("expected LayoutError::DepsViolation, got {err:?}");
5662        };
5663        assert_eq!(caixa, "demo");
5664        assert!(
5665            issue.contains(":deps-dev"),
5666            "issue must name the offending list: {issue}",
5667        );
5668    }
5669
5670    #[test]
5671    fn self_dep_fires_after_per_entry_dep_shape() {
5672        // Precedence pin: the per-entry shape gates of
5673        // [`Caixa::validate_deps`] (DNS-1123 / SemVer / fonte / etc.)
5674        // fire first on a self-dep entry whose `:nome` is malformed.
5675        // Same ordering posture every peer cross-slot gate uses
5676        // (`validate_no_self_supervision` after `SupervisorSpec::validate`,
5677        // `validate_no_self_membership` after `AplicacaoSpec::validate`).
5678        // A malformed self-dep `:nome` surfaces the narrower
5679        // per-entry diagnostic (which already names the parser-side
5680        // reason) before the self-edge gate sees the entry.
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        // The parent is "demo" (DNS-1123 valid); the dep is "DEMO"
5687        // (DNS-1123 invalid). The per-entry shape gate fires on the
5688        // upper-case nome, masking the self-edge gate (and that's the
5689        // canonical precedence — fix the dep shape first, then the
5690        // structural self-edge becomes the next live diagnostic).
5691        c.deps = vec![Dep::simple("DEMO", "^0.1")];
5692        let err = layout.verify(&c, &root).unwrap_err();
5693        let LayoutError::DepsViolation { caixa: _, issue } = err else {
5694            panic!("expected LayoutError::DepsViolation, got {err:?}");
5695        };
5696        assert!(
5697            issue.contains("DNS-1123"),
5698            "issue must be the per-entry shape diagnostic, not the self-edge gate: {issue}",
5699        );
5700    }
5701
5702    #[test]
5703    fn valid_deps_pass_to_downstream_gates() {
5704        // Positive control pin: the canonical authoring shape (one
5705        // `:deps` entry naming a DNS-1123 nome + Cargo-shaped requirement,
5706        // one `:deps-dev` entry on a distinct nome) passes the dep gate;
5707        // downstream gates (MissingLib here) take over. Drift here =
5708        // a future tighten that rejects any canonical shape surfaces as
5709        // a regression at this layout-level pin.
5710        use crate::Dep;
5711        let root = PathBuf::from("/tmp/x");
5712        let manifest = root.join("caixa.lisp");
5713        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
5714        let mut c = caixa(CaixaKind::Biblioteca);
5715        c.deps = vec![Dep::simple("caixa-teia", "^0.1")];
5716        c.deps_dev = vec![Dep::simple("caixa-lint", "^0.2")];
5717        let err = layout.verify(&c, &root).unwrap_err();
5718        assert!(
5719            matches!(err, LayoutError::MissingLib { .. }),
5720            "got {err:?} — valid deps must pass to MissingLib",
5721        );
5722    }
5723
5724    #[test]
5725    fn code_path_gate_runs_after_foreign_code_slot_gate() {
5726        // Precedence pin: a Servico that declares `:exe` (foreign code
5727        // surface) surfaces ForeignCodeSlot, *not* a per-entry path
5728        // shape diagnostic, even when the `:exe` entry is itself
5729        // malformed. The kind-coherence gate is the load-bearing
5730        // diagnostic at this site — once the slot is moved off the
5731        // wrong kind, the per-entry shape gate becomes the next live
5732        // diagnostic.
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::Servico);
5737        c.servicos = vec!["servicos/ok.yaml".into()];
5738        c.exe = vec!["/etc/foreign".into()];
5739        let err = layout.verify(&c, &root).unwrap_err();
5740        assert!(
5741            matches!(err, LayoutError::ForeignCodeSlot { .. }),
5742            "expected ForeignCodeSlot (kind-coherence wins over per-entry shape), got {err:?}",
5743        );
5744    }
5745
5746    // ── M2 typed-substrate invariants ────────────────────────────────────
5747
5748    #[test]
5749    fn behavior_callback_path_must_exist() {
5750        use crate::BehaviorSpec;
5751        use std::path::PathBuf;
5752        let root = PathBuf::from("/tmp/x");
5753        let manifest = root.join("caixa.lisp");
5754        let mut c = caixa(CaixaKind::Servico);
5755        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5756        let svc = root.join("servicos/demo.computeunit.yaml");
5757        c.behavior = Some(BehaviorSpec {
5758            on_init: Some(PathBuf::from("lib/init.lisp")),
5759            ..Default::default()
5760        });
5761        let manifest_clone = manifest.clone();
5762        let svc_clone = svc.clone();
5763        let layout =
5764            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
5765        let err = layout.verify(&c, &root).unwrap_err();
5766        assert!(matches!(
5767            err,
5768            LayoutError::MissingEntry { kind, .. }
5769                if kind == crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK
5770        ));
5771
5772        // Now declare the path exists — passes.
5773        let init = root.join("lib/init.lisp");
5774        let layout =
5775            StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc || p == init);
5776        layout.verify(&c, &root).unwrap();
5777    }
5778
5779    #[test]
5780    fn behavior_absolute_callback_is_violation_not_missing() {
5781        // An absolute path silently subverts `root.join(p)` (Path::join
5782        // replaces the base when the right side is absolute). Before
5783        // BehaviorSpec::validate ran, an `:on-init "/etc/passwd"` would
5784        // surface as a confusing "missing behavior-callback /etc/passwd"
5785        // — or, worse, pass when /etc/passwd happens to exist. Now it's
5786        // a value-shape error naming the slot.
5787        use crate::BehaviorSpec;
5788        let root = PathBuf::from("/tmp/x");
5789        let manifest = root.join("caixa.lisp");
5790        let svc = root.join("servicos/demo.computeunit.yaml");
5791        let mut c = caixa(CaixaKind::Servico);
5792        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5793        c.behavior = Some(BehaviorSpec {
5794            on_init: Some(PathBuf::from("/etc/passwd")),
5795            ..Default::default()
5796        });
5797        // Path exists check would *succeed* on /etc/passwd (proving the
5798        // sandbox bypass) — value-shape pass must fire first.
5799        let layout = StandardLayout::new()
5800            .with_path_exists(move |p| p == manifest || p == svc || p == Path::new("/etc/passwd"));
5801        let err = layout.verify(&c, &root).unwrap_err();
5802        assert!(
5803            matches!(err, LayoutError::BehaviorViolation { ref caixa, .. } if caixa == "demo"),
5804            "got {err:?}",
5805        );
5806    }
5807
5808    #[test]
5809    fn behavior_empty_callback_is_violation() {
5810        use crate::BehaviorSpec;
5811        let root = PathBuf::from("/tmp/x");
5812        let manifest = root.join("caixa.lisp");
5813        let svc = root.join("servicos/demo.computeunit.yaml");
5814        let mut c = caixa(CaixaKind::Servico);
5815        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5816        c.behavior = Some(BehaviorSpec {
5817            on_call: Some(PathBuf::new()),
5818            ..Default::default()
5819        });
5820        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
5821        let err = layout.verify(&c, &root).unwrap_err();
5822        assert!(matches!(err, LayoutError::BehaviorViolation { .. }));
5823    }
5824
5825    #[test]
5826    fn upgrade_from_duplicate_surfaces_as_upgrade_violation() {
5827        // Wiring pin: the cross-entry duplicate-`:from` gate in
5828        // `validate_upgrade_from` lands on the same
5829        // `LayoutError::UpgradeViolation` axis the per-entry
5830        // `UpgradeFromEntry::validate` already does (26da2c7), so a
5831        // caixa.lisp with two `(:from "0.1.0" …)` blocks surfaces at
5832        // `feira build` time naming the offending caixa rather than
5833        // silently passing into the wasm-operator's non-deterministic
5834        // dispatch. Mirrors `behavior_empty_callback_is_violation` on
5835        // the peer M2 typed slot.
5836        use crate::{UpgradeFromEntry, UpgradeInstruction};
5837        let root = PathBuf::from("/tmp/x");
5838        let manifest = root.join("caixa.lisp");
5839        let svc = root.join("servicos/demo.computeunit.yaml");
5840        let mut c = caixa(CaixaKind::Servico);
5841        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5842        c.upgrade_from = vec![
5843            UpgradeFromEntry {
5844                from: "0.1.0".into(),
5845                instructions: vec![UpgradeInstruction::Restart],
5846            },
5847            UpgradeFromEntry {
5848                from: "0.1.0".into(),
5849                instructions: vec![UpgradeInstruction::Restart],
5850            },
5851        ];
5852        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
5853        let err = layout.verify(&c, &root).unwrap_err();
5854        let LayoutError::UpgradeViolation { caixa, issue } = err else {
5855            panic!("expected LayoutError::UpgradeViolation for duplicate `:from`, got {err:?}");
5856        };
5857        assert_eq!(caixa, "demo");
5858        assert!(
5859            issue.contains("0.1.0"),
5860            "UpgradeViolation issue must name the offending `:from` verbatim, got {issue:?}"
5861        );
5862    }
5863
5864    #[test]
5865    fn upgrade_from_downgrade_surfaces_as_upgrade_violation() {
5866        // Wiring pin: the cross-slot precedence gate in
5867        // `validate_upgrade_from_against_versao` lands on the same
5868        // `LayoutError::UpgradeViolation` axis the per-entry and
5869        // cross-entry gates already do (26da2c7, 7c6aef2), so a
5870        // caixa.lisp whose `:upgrade-from :from` is greater than the
5871        // caixa's own `:versao` surfaces at `feira build` time
5872        // naming the offending caixa rather than silently passing
5873        // into the wasm-operator's `:from`-match dispatch where the
5874        // entry would sit dormant forever. Mirrors
5875        // `upgrade_from_duplicate_surfaces_as_upgrade_violation` on
5876        // the peer cross-entry gate.
5877        use crate::{UpgradeFromEntry, UpgradeInstruction};
5878        let root = PathBuf::from("/tmp/x");
5879        let manifest = root.join("caixa.lisp");
5880        let svc = root.join("servicos/demo.computeunit.yaml");
5881        let mut c = caixa(CaixaKind::Servico);
5882        c.versao = "0.1.5".into();
5883        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5884        c.upgrade_from = vec![UpgradeFromEntry {
5885            from: "0.2.0".into(),
5886            instructions: vec![UpgradeInstruction::Restart],
5887        }];
5888        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
5889        let err = layout.verify(&c, &root).unwrap_err();
5890        let LayoutError::UpgradeViolation { caixa, issue } = err else {
5891            panic!(
5892                "expected LayoutError::UpgradeViolation for downgrade-shaped `:from`, got {err:?}"
5893            );
5894        };
5895        assert_eq!(caixa, "demo");
5896        assert!(
5897            issue.contains("0.2.0") && issue.contains("0.1.5"),
5898            "UpgradeViolation issue must name both `:from` and `:versao` verbatim, got {issue:?}"
5899        );
5900    }
5901
5902    #[test]
5903    fn upgrade_from_equal_to_versao_surfaces_as_upgrade_violation() {
5904        // Self-upgrade no-op arm: `:from "0.1.0"` while
5905        // `:versao "0.1.0"` declares "upgrade from myself to
5906        // myself", which the operator's dispatch either skips
5907        // silently or trivially "succeeds" with no observable
5908        // transition. Surfaces at validate time naming both values
5909        // so the author can fix in one edit.
5910        use crate::{UpgradeFromEntry, UpgradeInstruction};
5911        let root = PathBuf::from("/tmp/x");
5912        let manifest = root.join("caixa.lisp");
5913        let svc = root.join("servicos/demo.computeunit.yaml");
5914        let mut c = caixa(CaixaKind::Servico);
5915        c.versao = "0.1.0".into();
5916        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5917        c.upgrade_from = vec![UpgradeFromEntry {
5918            from: "0.1.0".into(),
5919            instructions: vec![UpgradeInstruction::Restart],
5920        }];
5921        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
5922        let err = layout.verify(&c, &root).unwrap_err();
5923        let LayoutError::UpgradeViolation { caixa, issue } = err else {
5924            panic!(
5925                "expected LayoutError::UpgradeViolation for self-upgrade `:from == :versao`, got \
5926                 {err:?}"
5927            );
5928        };
5929        assert_eq!(caixa, "demo");
5930        assert!(
5931            issue.contains("0.1.0"),
5932            "UpgradeViolation issue must name the equal `:from`/`:versao` verbatim, got {issue:?}"
5933        );
5934    }
5935
5936    #[test]
5937    fn upgrade_from_strict_upgrade_passes_layout() {
5938        // Positive control for the precedence gate at the
5939        // LayoutInvariants level: a valid `:from < :versao` chain
5940        // (`0.1.0 → 0.2.0`) must not regress into a false-positive
5941        // `UpgradeViolation`. Mirrors `behavior_callback_path_must_exist`'s
5942        // positive-control arm.
5943        use crate::{UpgradeFromEntry, UpgradeInstruction};
5944        let root = PathBuf::from("/tmp/x");
5945        let manifest = root.join("caixa.lisp");
5946        let svc = root.join("servicos/demo.computeunit.yaml");
5947        let mut c = caixa(CaixaKind::Servico);
5948        c.versao = "0.2.0".into();
5949        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5950        c.upgrade_from = vec![UpgradeFromEntry {
5951            from: "0.1.0".into(),
5952            instructions: vec![UpgradeInstruction::Restart],
5953        }];
5954        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
5955        layout.verify(&c, &root).unwrap();
5956    }
5957
5958    #[test]
5959    fn upgrade_script_path_must_exist() {
5960        use crate::{BehaviorSpec, UpgradeFromEntry, UpgradeInstruction};
5961        use std::path::PathBuf;
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 on_state_change = root.join("lib/migrations.lisp");
5966        let mut c = caixa(CaixaKind::Servico);
5967        // `:versao` past the entry's `:from` so the cross-slot
5968        // precedence gate (`FromNotBeforeVersao`) lets this case
5969        // through to the path-existence pass under test.
5970        c.versao = "0.2.0".into();
5971        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
5972        // `:on-state-change` declared so the cross-slot composition
5973        // gate (`validate_upgrade_from_against_behavior`) lets the
5974        // `:state-change` entry through to the path-existence pass
5975        // under test. Without the callback the missing-callback gate
5976        // would surface first and the path-existence pass wouldn't be
5977        // exercised.
5978        c.behavior = Some(BehaviorSpec {
5979            on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
5980            ..Default::default()
5981        });
5982        // A `:load-module` precedes the `:state-change` so the entry
5983        // satisfies the within-entry state-change-ordering gate
5984        // (`StateChangeWithoutPriorLoad`) and the path-existence pass
5985        // under test is the gate actually exercised. `:load-module`
5986        // carries no on-disk path, so it adds no existence requirement.
5987        c.upgrade_from = vec![UpgradeFromEntry {
5988            from: "0.1.0".into(),
5989            instructions: vec![
5990                UpgradeInstruction::LoadModule {
5991                    module: "demo".into(),
5992                },
5993                UpgradeInstruction::StateChange {
5994                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5995                },
5996            ],
5997        }];
5998        let manifest_clone = manifest.clone();
5999        let svc_clone = svc.clone();
6000        let on_state_change_clone = on_state_change.clone();
6001        let layout = StandardLayout::new().with_path_exists(move |p| {
6002            p == manifest_clone || p == svc_clone || p == on_state_change_clone
6003        });
6004        let err = layout.verify(&c, &root).unwrap_err();
6005        assert!(matches!(
6006            err,
6007            LayoutError::MissingEntry { kind, .. }
6008                if kind == crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT
6009        ));
6010    }
6011
6012    #[test]
6013    fn layout_missing_entry_kind_m2_consts_pin_canonical_kebab_case_labels() {
6014        // Byte-identity pin: the two per-M2-slot leaf-kind labels the
6015        // [`LayoutError::MissingEntry`] `kind: &'static str`
6016        // discriminator surfaces under (the M2 `:behavior` per-callback
6017        // on-disk-leaf axis, the M2 `:upgrade-from :instructions`
6018        // per-`:state-change` script-path on-disk-leaf axis) route
6019        // through the lifted [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`]
6020        // / [`crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT`]
6021        // consts, so a future rebrand that reaches the const but not
6022        // the production emit / test probe (or vice versa) surfaces
6023        // here at build time rather than at runtime as a downstream
6024        // [`LayoutError::MissingEntry`] `kind: <stale-label>`
6025        // diagnostic mismatch far from the rename's commit. Mirror of
6026        // the peer
6027        // [`crate::aplicacao::tests::contrato_author_key_consts_pin_canonical_kebab_case_labels`]
6028        // (f50c875) and
6029        // [`crate::upgrade::tests::upgrade_instruction_kind_consts_pin_canonical_kebab_case_tags`]
6030        // (56120ef) byte-identity pins on the sibling M3 `:contratos`
6031        // per-entry endpoint-label + M2 `:upgrade-from :instructions`
6032        // per-variant kind-tag axes.
6033        assert_eq!(
6034            crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
6035            "behavior-callback"
6036        );
6037        assert_eq!(
6038            crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
6039            "upgrade-script"
6040        );
6041    }
6042
6043    #[test]
6044    fn layout_missing_entry_kind_m0_consts_pin_canonical_code_slot_labels() {
6045        // Byte-identity pin: the three per-M0-code-slot leaf-kind
6046        // labels the [`LayoutError::MissingEntry`] `kind: &'static
6047        // str` discriminator surfaces under (the `:bibliotecas`
6048        // per-entry axis, the `:exe` per-entry axis, the `:servicos`
6049        // per-entry axis) route through the lifted
6050        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`] /
6051        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] /
6052        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] consts,
6053        // so a future rebrand that reaches the const but not the
6054        // production emit (or vice versa) surfaces here at build time
6055        // rather than at runtime as a downstream
6056        // [`LayoutError::MissingEntry`] `kind: <stale-label>`
6057        // diagnostic mismatch far from the rename's commit. Mirror of
6058        // the peer M2-tier pin
6059        // [`layout_missing_entry_kind_m2_consts_pin_canonical_kebab_case_labels`]
6060        // (95c9c4c) on the sibling `:behavior` / `:upgrade-from`
6061        // per-slot leaf-kind axes.
6062        assert_eq!(
6063            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
6064            "biblioteca"
6065        );
6066        assert_eq!(crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE, "exe");
6067        assert_eq!(crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO, "servico");
6068    }
6069
6070    #[test]
6071    fn layout_missing_entry_kind_m0_consts_align_with_caixa_kind_as_str() {
6072        // Cross-axis byte-identity pin: the two `:kind`-namesake M0
6073        // leaf-kind labels ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`]
6074        // = `"biblioteca"`,
6075        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] =
6076        // `"servico"`) must equal [`crate::CaixaKind::Biblioteca`] /
6077        // [`crate::CaixaKind::Servico`]'s
6078        // [`crate::CaixaKind::as_str`] outputs verbatim — the
6079        // substrate's canonical human-readable-kind axis and the
6080        // layout diagnostic's per-slot leaf-kind axis share one
6081        // vocabulary for these two arms by design (both label the
6082        // caixa's code-producing shape by its Portuguese-native
6083        // idiom), so drift between the two lands as a build-time
6084        // pattern-arm miss here rather than as a runtime diagnostic
6085        // that reads inconsistently across `feira build`'s
6086        // per-invocation output.
6087        //
6088        // The third M0 arm ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`]
6089        // = `"exe"`) is deliberately *distinct* from
6090        // [`crate::CaixaKind::Binario`]'s [`crate::CaixaKind::as_str`]
6091        // output (`"binario"`) — the `:exe` code slot names the
6092        // per-directory leaf-kind at the `exe/` subtree, whereas
6093        // [`crate::CaixaKind::Binario`] names the caixa's own runtime
6094        // kind. Two axes, two labels — the inequality assertion here
6095        // pins the split so a future accidental collapse of the two
6096        // onto one scalar (a rebrand that reroutes either axis to
6097        // match the other) trips at build time.
6098        assert_eq!(
6099            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
6100            CaixaKind::Biblioteca.as_str()
6101        );
6102        assert_eq!(
6103            crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
6104            CaixaKind::Servico.as_str()
6105        );
6106        assert_ne!(
6107            crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
6108            CaixaKind::Binario.as_str(),
6109            "`exe` leaf-kind label names the per-directory code-slot \
6110             axis; `binario` names the caixa-kind axis — the two must \
6111             not silently collapse onto one scalar"
6112        );
6113    }
6114
6115    #[test]
6116    fn layout_missing_entry_kind_consts_are_pairwise_distinct() {
6117        // Distinctness pin: the five [`LayoutError::MissingEntry`]
6118        // `kind: &'static str` accept-set members
6119        // ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`] /
6120        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] /
6121        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] on the
6122        // M0 code-slot arms plus
6123        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`]
6124        // / [`crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT`]
6125        // on the M2 slot arms) must be pairwise distinct — an
6126        // accidental copy-paste flip that reroutes one label's byte-
6127        // string to also match another silently collapses two
6128        // per-slot diagnostics onto one, so an operator running
6129        // `feira build` reads `kind: "biblioteca"` for what should
6130        // have surfaced as a `:behavior :on-init` script-not-found
6131        // diagnostic (or vice versa). This pin catches any such
6132        // flip at build time. Mirror of the peer
6133        // [`crate::render::tests::m2_limits_key_consts_are_pairwise_distinct`]
6134        // / peer distinctness pins on other closed-set typed axes.
6135        let entries: &[(&str, &str)] = &[
6136            (
6137                "LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA",
6138                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
6139            ),
6140            (
6141                "LAYOUT_MISSING_ENTRY_KIND_EXE",
6142                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
6143            ),
6144            (
6145                "LAYOUT_MISSING_ENTRY_KIND_SERVICO",
6146                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
6147            ),
6148            (
6149                "LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK",
6150                crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
6151            ),
6152            (
6153                "LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT",
6154                crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
6155            ),
6156        ];
6157        for (i, (name_a, value_a)) in entries.iter().enumerate() {
6158            for (name_b, value_b) in entries.iter().skip(i + 1) {
6159                assert_ne!(
6160                    value_a, value_b,
6161                    "LAYOUT_MISSING_ENTRY_KIND_* consts must be \
6162                     pairwise-distinct byte-strings — {name_a} and \
6163                     {name_b} both resolve to {value_a:?}"
6164                );
6165            }
6166        }
6167    }
6168
6169    #[test]
6170    fn layout_dir_consts_pin_canonical_directory_names() {
6171        // Scalar-value pin for the three [`crate::render::LAYOUT_DIR_*`]
6172        // consts naming the CSE-invariant per-[`CaixaKind`]
6173        // on-disk-directory-name axes the substrate's layout invariants
6174        // pin (`lib/` for [`CaixaKind::Biblioteca`], `exe/` for
6175        // [`CaixaKind::Binario`], `servicos/` for [`CaixaKind::Servico`]).
6176        // A future rebrand of any of the three on-disk directory landing
6177        // conventions must reach this pin — the const-edit lands on one
6178        // arm, the assertion here re-pins the new byte-string, and every
6179        // downstream consumer (the caixa-feira `init` / `fmt` / `lint` /
6180        // `tofu` scaffolders, the [`crate::LayoutInvariants::verify`]
6181        // sandbox reconstruction, the future
6182        // `feira app deploy`-cluster scaffolder) picks up the new
6183        // directory name at build time. Mirror of the peer
6184        // [`layout_missing_entry_kind_m0_consts_pin_canonical_code_slot_labels`]
6185        // (fe2a898) on the sibling
6186        // [`crate::LayoutError::MissingEntry`] `kind:` discriminator
6187        // axis this on-disk-directory axis composes with.
6188        assert_eq!(crate::render::LAYOUT_DIR_LIB, "lib");
6189        assert_eq!(crate::render::LAYOUT_DIR_EXE, "exe");
6190        assert_eq!(crate::render::LAYOUT_DIR_SERVICOS, "servicos");
6191    }
6192
6193    #[test]
6194    fn layout_dir_consts_are_pairwise_distinct() {
6195        // Distinctness pin: the three per-[`CaixaKind`]
6196        // on-disk-directory-name arms must resolve to pairwise-distinct
6197        // byte-strings — a future accidental copy-paste flip that
6198        // reroutes any one of the three onto another's value silently
6199        // collapses two per-kind on-disk sandboxes onto one, so
6200        // [`crate::LayoutInvariants::verify`] would gate a
6201        // [`CaixaKind::Binario`] caixa's `:exe` entries against the
6202        // wrong sub-tree (or a `:kind Servico` caixa's `:servicos`
6203        // entries against `lib/` and pass every entry `feira build`
6204        // should have rejected as [`crate::LayoutError::ServicoOutsideDir`]).
6205        // Mirror of the peer
6206        // [`layout_missing_entry_kind_consts_are_pairwise_distinct`]
6207        // (fe2a898) on the sibling leaf-kind label accept-set.
6208        let entries: &[(&str, &str)] = &[
6209            ("LAYOUT_DIR_LIB", crate::render::LAYOUT_DIR_LIB),
6210            ("LAYOUT_DIR_EXE", crate::render::LAYOUT_DIR_EXE),
6211            ("LAYOUT_DIR_SERVICOS", crate::render::LAYOUT_DIR_SERVICOS),
6212        ];
6213        for (i, (name_a, value_a)) in entries.iter().enumerate() {
6214            for (name_b, value_b) in entries.iter().skip(i + 1) {
6215                assert_ne!(
6216                    value_a, value_b,
6217                    "LAYOUT_DIR_* consts must be pairwise-distinct \
6218                     byte-strings — {name_a} and {name_b} both resolve \
6219                     to {value_a:?}"
6220                );
6221            }
6222        }
6223    }
6224
6225    #[test]
6226    fn layout_dir_exe_matches_layout_missing_entry_kind_exe() {
6227        // Cross-axis byte-identity pin: [`crate::render::LAYOUT_DIR_EXE`]
6228        // (the on-disk-directory-name arm) equals
6229        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] (the
6230        // [`LayoutError::MissingEntry`] `kind:` leaf-kind categorization
6231        // arm) verbatim — the M0 `:kind Binario` on-disk-directory axis
6232        // and the [`crate::LayoutError::MissingEntry`] `kind:` leaf-kind
6233        // discriminator name the same three-byte sub-tree (`exe/`), a
6234        // coincidence [`crate::LayoutInvariants::verify`] itself relies
6235        // on: it joins `root` with [`crate::render::LAYOUT_DIR_EXE`] to
6236        // reconstruct `exe_dir` and emits [`crate::LayoutError::MissingEntry
6237        // { kind: LAYOUT_MISSING_ENTRY_KIND_EXE, path: <under exe_dir> }`]
6238        // for every non-resolving entry. Making the coincidence
6239        // load-bearing means a future rebrand touching either axis
6240        // without the other (a per-consumer disambiguation collapsing
6241        // the leaf-kind label onto `"binary"` while the directory stays
6242        // `"exe"`, or vice versa) trips at caixa-core build time rather
6243        // than surfacing at runtime as a mismatched
6244        // [`crate::LayoutInvariants::verify`] diagnostic whose `kind:`
6245        // reads one label while the `path:` sits under a differently-named
6246        // sub-tree.
6247        assert_eq!(
6248            crate::render::LAYOUT_DIR_EXE,
6249            crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
6250            "LAYOUT_DIR_EXE must equal LAYOUT_MISSING_ENTRY_KIND_EXE — \
6251             both name the M0 `:kind Binario` sub-tree by the same \
6252             three-byte scalar"
6253        );
6254    }
6255
6256    #[test]
6257    fn layout_dir_bib_is_distinct_from_layout_missing_entry_kind_bib() {
6258        // Cross-axis distinctness pin: [`crate::render::LAYOUT_DIR_LIB`]
6259        // (`"lib"`, the Cargo-style abbreviated on-disk directory name)
6260        // is *deliberately* distinct from
6261        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`]
6262        // (`"biblioteca"`, the full-form Portuguese-native leaf-kind
6263        // label) — the substrate splits the on-disk convention terse
6264        // (`lib/`) from the diagnostic vocabulary full (`biblioteca`),
6265        // matching Cargo's `src/lib.rs` abbreviation of the `library`
6266        // crate-type discriminator. A future accidental collapse of the
6267        // two axes onto one scalar (a rebrand aligning either arm with
6268        // the other for schema-clarity, an English-uniformity pass that
6269        // renames `LAYOUT_DIR_LIB` to `LAYOUT_DIR_BIBLIOTECA` or the
6270        // diagnostic label to `"lib"`) would silently reroute either
6271        // consumer onto the other's byte-string. This pin catches the
6272        // collapse at build time. Peer of the sibling
6273        // [`layout_missing_entry_kind_m0_consts_align_with_caixa_kind_as_str`]
6274        // (fe2a898) that pins the analogous *equality* between the M0
6275        // `:kind Biblioteca` diagnostic-label arm and
6276        // [`crate::CaixaKind::Biblioteca`]'s [`crate::CaixaKind::as_str`]
6277        // output — the two pins jointly encode the "which of the three
6278        // Biblioteca-related scalars are load-bearing-equal, which are
6279        // load-bearing-distinct" invariant across the substrate's
6280        // per-kind vocabulary.
6281        assert_ne!(
6282            crate::render::LAYOUT_DIR_LIB,
6283            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
6284            "LAYOUT_DIR_LIB (`\"lib\"`) and LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA \
6285             (`\"biblioteca\"`) name two distinct axes — the on-disk \
6286             directory convention (Cargo-style abbreviated) and the \
6287             layout-diagnostic leaf-kind label (full-form Portuguese) — \
6288             and must not silently collapse onto one scalar"
6289        );
6290    }
6291
6292    #[test]
6293    fn layout_dir_servicos_is_distinct_from_layout_missing_entry_kind_servico() {
6294        // Cross-axis distinctness pin: [`crate::render::LAYOUT_DIR_SERVICOS`]
6295        // (`"servicos"`, the Portuguese-*plural* on-disk directory
6296        // name) is *deliberately* distinct from
6297        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`]
6298        // (`"servico"`, the singular leaf-kind label) — the on-disk
6299        // sub-tree houses one-or-more ComputeUnit YAML descriptors per
6300        // caixa (hence the plural), the diagnostic label names the
6301        // caixa's own kind (singular). A future accidental collapse
6302        // onto one scalar (a per-consumer disambiguation aligning the
6303        // two, a hypothetical English-uniformity pass renaming
6304        // `"servicos"` → `"services"` while retaining `"servico"` on
6305        // the diagnostic arm — or vice versa) would silently reroute
6306        // either consumer onto the other's byte-string. Peer of the
6307        // sibling [`layout_dir_bib_is_distinct_from_layout_missing_entry_kind_bib`]
6308        // pin on the M0 `:kind Biblioteca` split axis; two of the three
6309        // per-kind on-disk / leaf-kind splits carry a distinctness
6310        // pin here, the third ([`crate::render::LAYOUT_DIR_EXE`] vs
6311        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`]) carries an
6312        // equality pin under
6313        // [`layout_dir_exe_matches_layout_missing_entry_kind_exe`].
6314        assert_ne!(
6315            crate::render::LAYOUT_DIR_SERVICOS,
6316            crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
6317            "LAYOUT_DIR_SERVICOS (`\"servicos\"`, plural on-disk sub-tree) \
6318             and LAYOUT_MISSING_ENTRY_KIND_SERVICO (`\"servico\"`, singular \
6319             leaf-kind label) name two distinct axes and must not silently \
6320             collapse onto one scalar"
6321        );
6322    }
6323
6324    #[test]
6325    fn layout_invariants_reconstruct_sandbox_roots_through_lifted_layout_dir_consts() {
6326        // Production-through-const pin: [`LayoutInvariants::verify`]
6327        // routes its three per-kind sandbox-root joins
6328        // (`root.join(LAYOUT_DIR_LIB)` for the `:kind Biblioteca`
6329        // default `lib/<nome>.lisp` reconstruction, `root.join(LAYOUT_DIR_EXE)`
6330        // for the [`LayoutError::ExeOutsideDir`] gate,
6331        // `root.join(LAYOUT_DIR_SERVICOS)` for the
6332        // [`LayoutError::ServicoOutsideDir`] gate) through the three
6333        // lifted consts, not through inline `"lib"` / `"exe"` /
6334        // `"servicos"` `&str` literals. This test drives the
6335        // [`LayoutError::ExeOutsideDir`] arm through a `:kind Binario`
6336        // caixa whose declared `:exe` entry deliberately escapes
6337        // `root.join(LAYOUT_DIR_EXE)` (a sibling `bin/tool` path) —
6338        // if the production emit reads the wrong const (or reverts to
6339        // an inline literal that drifts from the const) the diagnostic
6340        // arm surfaces the wrong variant, catching the drift at build
6341        // time rather than as a per-invocation runtime mismatch.
6342        //
6343        // Mirror of the peer production-through-const pin
6344        // [`crate::dep::tests::validate_no_self_dep_deps_field_routes_through_dep_author_key`]
6345        // (4da6fba) on the sibling M0 `:deps` `list:` diagnostic axis.
6346        use std::path::PathBuf;
6347        let root = PathBuf::from("/tmp/x");
6348        let manifest = root.join("caixa.lisp");
6349        let bin_entry_outside = root.join("bin/tool");
6350        let mut c = caixa(CaixaKind::Binario);
6351        c.exe = vec!["bin/tool".into()];
6352        let manifest_clone = manifest.clone();
6353        let outside_clone = bin_entry_outside.clone();
6354        let layout = StandardLayout::new()
6355            .with_path_exists(move |p| p == manifest_clone || p == outside_clone);
6356        let err = layout.verify(&c, &root).unwrap_err();
6357        match err {
6358            LayoutError::ExeOutsideDir(path) => {
6359                assert_eq!(
6360                    path, bin_entry_outside,
6361                    "ExeOutsideDir must carry the resolved `:exe` entry that \
6362                     escapes `root.join(LAYOUT_DIR_EXE)`"
6363                );
6364                // Byte-identity check: the escape must be against the
6365                // lifted `LAYOUT_DIR_EXE` sub-tree, not a stale inline
6366                // literal — a future const-edit that drifts from `"exe"`
6367                // reroutes `exe_dir` off the sandbox `bin/tool` escapes
6368                // from, and this pattern-arm miss re-surfaces here.
6369                assert!(
6370                    !path.starts_with(root.join(crate::render::LAYOUT_DIR_EXE)),
6371                    "resolved `:exe` entry {path:?} must escape the \
6372                     `root.join(LAYOUT_DIR_EXE)` sub-tree the production \
6373                     emit uses to gate the [`LayoutError::ExeOutsideDir`] arm"
6374                );
6375            }
6376            other => panic!("expected ExeOutsideDir, got {other:?}"),
6377        }
6378    }
6379
6380    #[test]
6381    fn upgrade_state_change_without_behavior_callback_surfaces_as_upgrade_violation() {
6382        // Wiring pin for the cross-slot composition gate
6383        // (`validate_upgrade_from_against_behavior`): a caixa whose
6384        // `:upgrade-from` declares a `(:state-change "lib/m.lisp")`
6385        // instruction but does not declare `:behavior :on-state-change`
6386        // surfaces at `feira build` time as a `LayoutError::UpgradeViolation`
6387        // naming the offending caixa + the entry's `:from` + the
6388        // offending script — not at hot-upgrade dispatch when the
6389        // operator reaches for the missing callback. Mirrors
6390        // `upgrade_from_downgrade_surfaces_as_upgrade_violation` on the
6391        // peer `:from` ↔ `:versao` cross-slot precedence gate.
6392        use crate::{UpgradeFromEntry, UpgradeInstruction};
6393        use std::path::PathBuf;
6394        let root = PathBuf::from("/tmp/x");
6395        let manifest = root.join("caixa.lisp");
6396        let svc = root.join("servicos/demo.computeunit.yaml");
6397        let mut c = caixa(CaixaKind::Servico);
6398        c.versao = "0.2.0".into();
6399        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
6400        // `:behavior` is None (the canonical "I added the upgrade path
6401        // but never declared :behavior" footgun the gate closes); a
6402        // peer arm covers the BehaviorSpec-Some-but-on-state-change-
6403        // None shape in `upgrade::tests::behavior_gate_rejects_state_
6404        // change_when_on_state_change_is_none`.
6405        c.upgrade_from = vec![UpgradeFromEntry {
6406            from: "0.1.0".into(),
6407            instructions: vec![
6408                UpgradeInstruction::LoadModule {
6409                    module: "demo".into(),
6410                },
6411                UpgradeInstruction::StateChange {
6412                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6413                },
6414            ],
6415        }];
6416        let manifest_clone = manifest.clone();
6417        let svc_clone = svc.clone();
6418        let layout =
6419            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
6420        let err = layout.verify(&c, &root).unwrap_err();
6421        match err {
6422            LayoutError::UpgradeViolation { caixa, issue } => {
6423                assert_eq!(caixa, "demo", "diagnostic must name the offending caixa");
6424                assert!(
6425                    issue.contains(crate::render::M2_BEHAVIOR_AUTHOR_KEY_ON_STATE_CHANGE),
6426                    "diagnostic must name the missing callback slot for self-locating fix, \
6427                     got {issue:?}"
6428                );
6429                assert!(
6430                    issue.contains("0.1.0"),
6431                    "diagnostic must name the offending entry's :from, got {issue:?}"
6432                );
6433                assert!(
6434                    issue.contains("v01-to-v02.lisp"),
6435                    "diagnostic must name the offending :script for self-locating fix, \
6436                     got {issue:?}"
6437                );
6438            }
6439            other => panic!("expected UpgradeViolation, got {other:?}"),
6440        }
6441    }
6442
6443    #[test]
6444    fn supervisor_must_have_children() {
6445        use crate::RestartStrategy;
6446        let root = PathBuf::from("/tmp/x");
6447        let manifest = root.join("caixa.lisp");
6448        let manifest_clone = manifest.clone();
6449        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6450        let mut c = caixa(CaixaKind::Supervisor);
6451        c.estrategia = Some(RestartStrategy::OneForOne);
6452        c.max_restarts = Some(5);
6453        // No children → should fail
6454        let err = layout.verify(&c, &root).unwrap_err();
6455        assert!(matches!(err, LayoutError::SupervisorViolation { .. }));
6456    }
6457
6458    #[test]
6459    fn supervisor_self_referential_child_is_violation() {
6460        // A Supervisor whose `:children` names its own `:nome` is a
6461        // one-node supervision cycle. The cross-slot gate fires at
6462        // verify time, surfacing as a SupervisorViolation that names the
6463        // offending supervisor — not at the cluster apply far from
6464        // source. The `caixa()` helper's `:nome` is "demo".
6465        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
6466        let root = PathBuf::from("/tmp/x");
6467        let manifest = root.join("caixa.lisp");
6468        let manifest_clone = manifest.clone();
6469        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6470        let mut c = caixa(CaixaKind::Supervisor);
6471        c.estrategia = Some(RestartStrategy::OneForOne);
6472        c.max_restarts = Some(5);
6473        c.children = vec![
6474            ChildSpec {
6475                caixa: "worker".into(),
6476                versao: "^0.1".into(),
6477                restart: RestartPolicy::Permanent,
6478            },
6479            ChildSpec {
6480                caixa: "demo".into(),
6481                versao: "^0.1".into(),
6482                restart: RestartPolicy::Permanent,
6483            },
6484        ];
6485        let err = layout.verify(&c, &root).unwrap_err();
6486        let LayoutError::SupervisorViolation { caixa, issue } = err else {
6487            panic!("expected SupervisorViolation for self-referential child, got {err:?}");
6488        };
6489        assert_eq!(caixa, "demo");
6490        assert!(
6491            issue.contains("demo") && issue.contains("itself"),
6492            "issue must name the self-supervising caixa, got {issue:?}"
6493        );
6494    }
6495
6496    #[test]
6497    fn supervisor_distinct_children_pass_self_supervision_gate() {
6498        // Positive control: a Supervisor whose children are all distinct
6499        // from its own `:nome` verifies cleanly.
6500        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
6501        let root = PathBuf::from("/tmp/x");
6502        let manifest = root.join("caixa.lisp");
6503        let manifest_clone = manifest.clone();
6504        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6505        let mut c = caixa(CaixaKind::Supervisor);
6506        c.estrategia = Some(RestartStrategy::OneForOne);
6507        c.max_restarts = Some(5);
6508        c.children = vec![ChildSpec {
6509            caixa: "worker".into(),
6510            versao: "^0.1".into(),
6511            restart: RestartPolicy::Permanent,
6512        }];
6513        layout.verify(&c, &root).unwrap();
6514    }
6515
6516    #[test]
6517    fn cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor() {
6518        // Composition pin: every cross-slot self-edge gate fired from
6519        // `LayoutInvariants::verify` — the supervision-tree arm's
6520        // `crate::supervisor::validate_no_self_supervision` call, the
6521        // Aplicacao arm's `crate::aplicacao::validate_no_self_membership`
6522        // call, and the dep-graph arm's
6523        // `crate::dep::validate_no_self_dep` call — must key its
6524        // `parent_nome` arg off the typed [`Caixa::nome`] accessor, not
6525        // the raw `&caixa.nome` `&String`-borrow of the underlying
6526        // field.
6527        //
6528        // Structurally: a rename of the storage field or a hypothetical
6529        // accessor rebrand (a per-cluster alias table pinned through a
6530        // future `:placement`-scoped slot, the M4 CR materializer's
6531        // per-CR namespace-qualified rewrite, a `:nome-suffix` overlay
6532        // the MESH-COMPOSITION §III.2 roadmap acknowledges) would land
6533        // through the accessor by construction; a raw-borrow bypass
6534        // would silently disagree with every peer consumer that already
6535        // routes through `caixa.nome()` (the caixa-mesh 980c059,
6536        // caixa-helm 22461ef, caixa-flux 162e2e2, caixa-crd 61d3429,
6537        // caixa-feira ef83332 raw-borrow converges), reintroducing the
6538        // drift surface the sibling converges closed. Each arm fires
6539        // its per-kind `LayoutError` variant (`SupervisorViolation` /
6540        // `AplicacaoViolation` / `DepsViolation`) whose `caixa` field
6541        // carries the offending parent name verbatim through
6542        // `caixa.nome().clone()`; asserting the field equals
6543        // `caixa.nome()` on the mutated fixture pins the accessor-
6544        // routed parent-nome projection at every call site — a future
6545        // silent detour that had the gate observe a stale / aliased
6546        // name at the arg boundary would surface here as a
6547        // `caixa != "demo"` inequality.
6548        //
6549        // Peer of the sibling per-caixa-crate `nome`-arg raw-borrow
6550        // convergence pin discipline (54bf2f3 / 22461ef / 162e2e2 on the
6551        // renderer crates; ef83332 on the CLI) — extends the "one typed
6552        // dispatch per `:nome` consumer" discipline onto the substrate's
6553        // own [`LayoutInvariants::verify`] cross-slot self-edge gate
6554        // wire-up on all three typed-name-graph kinds.
6555        use crate::{
6556            ChildSpec, Dep, Membro, Placement, PlacementStrategy, RestartPolicy, RestartStrategy,
6557        };
6558        let root = PathBuf::from("/tmp/x");
6559        let manifest = root.join("caixa.lisp");
6560        let manifest_clone = manifest.clone();
6561        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6562
6563        // Supervisor arm — the `caixa()` helper's `:nome` is "demo",
6564        // and the accessor's return `caixa.nome()` must equal the
6565        // parent-nome that the self-supervision gate observes.
6566        let mut sup = caixa(CaixaKind::Supervisor);
6567        sup.estrategia = Some(RestartStrategy::OneForOne);
6568        sup.max_restarts = Some(5);
6569        sup.children = vec![ChildSpec {
6570            caixa: "demo".into(),
6571            versao: "^0.1".into(),
6572            restart: RestartPolicy::Permanent,
6573        }];
6574        let parent_nome_via_accessor = sup.nome();
6575        assert_eq!(
6576            parent_nome_via_accessor, "demo",
6577            "the caixa() fixture helper's `:nome` must be \"demo\" — \
6578             the accessor's return is the pin's ground truth for the \
6579             cross-slot gate's parent-nome arg",
6580        );
6581        let err = layout.verify(&sup, &root).unwrap_err();
6582        let LayoutError::SupervisorViolation { caixa: c_nome, .. } = err else {
6583            panic!("expected SupervisorViolation for self-referential child, got {err:?}");
6584        };
6585        assert_eq!(
6586            c_nome, parent_nome_via_accessor,
6587            "the SupervisorViolation's `caixa` field must equal \
6588             `sup.nome()` — the cross-slot self-supervision gate's \
6589             `parent_nome` arg must route through the lifted \
6590             [`Caixa::nome`] accessor, not the raw `&caixa.nome` \
6591             `&String`-borrow of the underlying field",
6592        );
6593
6594        // Aplicacao arm — same discipline on the peer typed-name-graph
6595        // kind. Constructed alongside the supervisor arm so any future
6596        // accessor drift lands on both arms in the same pin.
6597        let mut app = caixa(CaixaKind::Aplicacao);
6598        app.placement = Some(Placement {
6599            estrategia: PlacementStrategy::Replicated,
6600            clusters: vec!["rio".into()],
6601            affinity: None,
6602            shard_key: None,
6603        });
6604        app.membros = vec![Membro {
6605            caixa: "demo".into(),
6606            versao: "^0.1".into(),
6607        }];
6608        let parent_nome_via_accessor = app.nome();
6609        assert_eq!(
6610            parent_nome_via_accessor, "demo",
6611            "the caixa() fixture helper's `:nome` must be \"demo\" on \
6612             the Aplicacao arm too — same accessor-ground-truth as the \
6613             sibling supervisor arm above",
6614        );
6615        let err = layout.verify(&app, &root).unwrap_err();
6616        let LayoutError::AplicacaoViolation { caixa: c_nome, .. } = err else {
6617            panic!("expected AplicacaoViolation for self-referential membro, got {err:?}");
6618        };
6619        assert_eq!(
6620            c_nome, parent_nome_via_accessor,
6621            "the AplicacaoViolation's `caixa` field must equal \
6622             `app.nome()` — the cross-slot self-membership gate's \
6623             `parent_nome` arg must route through the lifted \
6624             [`Caixa::nome`] accessor, not the raw `&caixa.nome` \
6625             `&String`-borrow of the underlying field",
6626        );
6627
6628        // Dep-graph arm — third typed-name-graph kind on the
6629        // `parent_nome` arg boundary. Same discipline as the peer
6630        // supervision-tree and Aplicacao-membership arms above.
6631        // Constructed alongside so any future accessor drift lands on
6632        // all three arms in the same pin. Needs a distinct layout
6633        // fixture from the supervisor / aplicacao arms above because
6634        // the `Biblioteca` kind's code-path existence gate demands the
6635        // canonical `lib/<nome>.lisp` path also `exists`, so the shim
6636        // covers both `caixa.lisp` and `lib/demo.lisp`.
6637        let default_lib = root.join("lib").join("demo.lisp");
6638        let manifest_dep = manifest.clone();
6639        let default_lib_clone = default_lib.clone();
6640        let layout_dep = StandardLayout::new()
6641            .with_path_exists(move |p| p == manifest_dep || p == default_lib_clone);
6642        let mut lib = caixa(CaixaKind::Biblioteca);
6643        lib.deps = vec![Dep::simple("demo", "^0.1")];
6644        let parent_nome_via_accessor = lib.nome();
6645        assert_eq!(
6646            parent_nome_via_accessor, "demo",
6647            "the caixa() fixture helper's `:nome` must be \"demo\" on \
6648             the Biblioteca arm too — same accessor-ground-truth as the \
6649             sibling supervisor + Aplicacao arms above",
6650        );
6651        let err = layout_dep.verify(&lib, &root).unwrap_err();
6652        let LayoutError::DepsViolation { caixa: c_nome, .. } = err else {
6653            panic!("expected DepsViolation for self-referential :deps entry, got {err:?}");
6654        };
6655        assert_eq!(
6656            c_nome, parent_nome_via_accessor,
6657            "the DepsViolation's `caixa` field must equal \
6658             `lib.nome()` — the cross-slot self-dep gate's `parent_nome` \
6659             arg must route through the lifted [`Caixa::nome`] accessor, \
6660             not the raw `&caixa.nome` `&String`-borrow of the underlying \
6661             field",
6662        );
6663    }
6664
6665    #[test]
6666    fn upgrade_against_versao_gate_routes_current_versao_through_lifted_accessor() {
6667        // Composition pin: the cross-slot `:upgrade-from :from` ↔
6668        // `:versao` precedence gate fired from
6669        // `LayoutInvariants::verify` — the
6670        // `crate::upgrade::validate_upgrade_from_against_versao` call —
6671        // must key its `versao` arg off the typed [`Caixa::versao`]
6672        // accessor, not the raw `&caixa.versao` `&String`-borrow of
6673        // the underlying field.
6674        //
6675        // Same "arg-boundary reads through the lifted accessor"
6676        // discipline as the sibling
6677        // [`cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor`]
6678        // pin above on the `:nome`-arg axis of the three typed-name-
6679        // graph self-edge gates — extended here onto the `:versao`-arg
6680        // axis of the substrate's remaining `LayoutInvariants::verify`
6681        // cross-slot arg-carrying call site. Structurally byte-equal
6682        // today (the accessor is `pub fn versao(&self) -> &str { &self.versao }`,
6683        // so both paths coerce to the same `&str`); the pin catches a
6684        // future silent detour (an accessor rebrand that no longer
6685        // shipped the raw slot verbatim — a per-`:edicao` overlay,
6686        // a promotion of `:versao` to a `CaixaVersion` newtype with a
6687        // canonicalizing accessor, an M4 CR-materializer-side pinning
6688        // through a resolver-annotated `:versao-resolved` slot) that
6689        // would silently split the substrate's own precedence gate
6690        // from every peer consumer already routing `:versao` reads
6691        // through the lifted accessor.
6692        //
6693        // The gate fires an `UpgradeViolation { caixa, issue }` when a
6694        // `:upgrade-from` entry's `:from` is not strictly less than
6695        // the top-level `:versao` — the `issue` string names both the
6696        // offending prior version and the current version verbatim,
6697        // so asserting the substring `caixa.versao()` appears in the
6698        // fired diagnostic pins the accessor-routed current-versao
6699        // projection at the arg boundary. A raw-borrow bypass would
6700        // still surface the same bytes today, but the presence of
6701        // this pin makes any future divergence between the accessor's
6702        // return and the raw slot's contents a build-time failure at
6703        // this call site.
6704        use crate::{UpgradeFromEntry, UpgradeInstruction};
6705        let root = PathBuf::from("/tmp/x");
6706        let manifest = root.join("caixa.lisp");
6707        let servico_path = root.join("servicos").join("demo.computeunit.yaml");
6708        let manifest_clone = manifest.clone();
6709        let servico_clone = servico_path.clone();
6710        let layout = StandardLayout::new()
6711            .with_path_exists(move |p| p == manifest_clone || p == servico_clone);
6712        let mut svc = caixa(CaixaKind::Servico);
6713        svc.versao = "0.1.0".into();
6714        svc.servicos = vec!["servicos/demo.computeunit.yaml".into()];
6715        // `:from` >= current `:versao` — trips the precedence gate the
6716        // `validate_upgrade_from_against_versao` cross-slot call
6717        // enforces. `:load-module` carries no on-disk path so the
6718        // path-existence gate downstream stays inert; the precedence
6719        // gate is what fires. No `:on-state-change` needed because the
6720        // instruction list carries no `:state-change` entry, so the
6721        // sibling `validate_upgrade_from_against_behavior` gate is
6722        // inert too.
6723        svc.upgrade_from = vec![UpgradeFromEntry {
6724            from: "0.2.0".into(),
6725            instructions: vec![UpgradeInstruction::LoadModule {
6726                module: "demo".into(),
6727            }],
6728        }];
6729        let current_versao_via_accessor = svc.versao().to_string();
6730        assert_eq!(
6731            current_versao_via_accessor, "0.1.0",
6732            "the mutated fixture's `:versao` must be observable through \
6733             the accessor before layout verification fires — a drift on \
6734             `Caixa::versao` would surface here as a `!= \"0.1.0\"` \
6735             inequality",
6736        );
6737        let err = layout.verify(&svc, &root).unwrap_err();
6738        let LayoutError::UpgradeViolation {
6739            caixa: c_nome,
6740            issue,
6741        } = err
6742        else {
6743            panic!("expected UpgradeViolation for :from >= :versao, got {err:?}");
6744        };
6745        assert_eq!(c_nome, svc.nome(), "wrap envelope names the caixa");
6746        assert!(
6747            issue.contains(&current_versao_via_accessor),
6748            "the UpgradeViolation's `issue` must quote the current \
6749             `:versao` byte-string verbatim — the cross-slot precedence \
6750             gate's `versao` arg must route through the lifted \
6751             [`Caixa::versao`] accessor, not the raw `&caixa.versao` \
6752             `&String`-borrow of the underlying field. issue: {issue}",
6753        );
6754    }
6755
6756    #[test]
6757    fn layout_violation_envelopes_carry_caixa_nome_through_lifted_accessor() {
6758        // Wrap-envelope drift-detection pin: every per-axis
6759        // `LayoutError::*Violation { caixa, issue }` envelope fired
6760        // from `LayoutInvariants::verify` must key its offending-caixa
6761        // field off the typed [`Caixa::nome`] accessor's
6762        // `.to_string()` extension, not the raw
6763        // `caixa.nome.clone()` `String::clone()` of the underlying
6764        // field. Structurally byte-equal today (each accessor is
6765        // `pub fn nome(&self) -> &str { &self.nome }`, so
6766        // `caixa.nome().to_string()` and `caixa.nome.clone()` produce
6767        // the same bytes); the pin catches a future silent detour
6768        // (an accessor rebrand that no longer shipped the raw slot
6769        // verbatim — a per-cluster alias table pinned through a
6770        // future `:placement`-scoped slot, the M4 CR materializer's
6771        // per-CR namespace-qualified rewrite, a `:nome-suffix`
6772        // overlay the MESH-COMPOSITION §III.2 roadmap acknowledges)
6773        // that would silently split the substrate's own layout
6774        // invariant verifier's diagnostic surface from every peer
6775        // caixa-crate consumer that already routes `:nome` reads
6776        // through the lifted accessor (the caixa-mesh 980c059,
6777        // caixa-helm 22461ef, caixa-flux 162e2e2, caixa-crd 61d3429,
6778        // caixa-feira ef83332 raw-borrow converges).
6779        //
6780        // Exercises a representative variant on each of the three
6781        // wrap-envelope arm shapes the substrate's per-axis fan-out
6782        // carries: (1) `LayoutError::NomeViolation` (the leading arm
6783        // in the `verify` order — the `:nome` axis's DNS-1123 shape
6784        // gate fires immediately after the manifest-existence gate),
6785        // (2) `LayoutError::BinarioWithoutExe` (a tuple-variant on
6786        // the kind-coherence family — different envelope shape than
6787        // the struct-variant `*Violation { caixa, issue }` family
6788        // but the same converge target on the `caixa.nome().to_string()`
6789        // arg), and (3) `LayoutError::ServicoWithoutServicos` (the
6790        // sibling tuple-variant on the same kind-coherence family).
6791        // Together they cover the two `LayoutError` envelope shapes
6792        // (struct-variant + tuple-variant) the layout invariants file
6793        // emits on `:nome`-carrying arms.
6794        //
6795        // Peer of the sibling
6796        // [`cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor`]
6797        // pin above — extends the "wrap-envelope `caixa:` field
6798        // reads through the lifted accessor" discipline from the
6799        // cross-slot self-edge gates' `parent_nome` arg boundary
6800        // onto the per-axis `LayoutError::*Violation` envelope's
6801        // `caixa:` field boundary.
6802
6803        let root = PathBuf::from("/tmp/x");
6804        let manifest = root.join("caixa.lisp");
6805        let manifest_clone = manifest.clone();
6806        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6807
6808        // (1) `NomeViolation` on the struct-variant envelope: force a
6809        // DNS-1123-invalid `:nome` (uppercase byte — `is_dns_1123_label`
6810        // rejects) and assert the fired envelope's `caixa:` field
6811        // byte-equals `c.nome().to_string()`.
6812        let mut c = caixa(CaixaKind::Biblioteca);
6813        c.nome = "BAD_NAME".into();
6814        c.bibliotecas = vec!["lib/demo.lisp".into()];
6815        let expected_nome_via_accessor = c.nome().to_string();
6816        assert_eq!(
6817            expected_nome_via_accessor, "BAD_NAME",
6818            "the mutated fixture's `:nome` must be observable through \
6819             the accessor before layout verification fires — a drift \
6820             on `Caixa::nome` would surface here as a `!= \"BAD_NAME\"` \
6821             inequality",
6822        );
6823        let err = layout.verify(&c, &root).unwrap_err();
6824        let LayoutError::NomeViolation { caixa: c_nome, .. } = err else {
6825            panic!("expected NomeViolation for DNS-1123-invalid :nome, got {err:?}");
6826        };
6827        assert_eq!(
6828            c_nome, expected_nome_via_accessor,
6829            "the NomeViolation's `caixa` field must equal \
6830             `c.nome().to_string()` — the wrap envelope's per-axis \
6831             projection must route through the lifted [`Caixa::nome`] \
6832             accessor's `.to_string()` extension, not the raw \
6833             `caixa.nome.clone()` `String::clone()` of the underlying \
6834             field",
6835        );
6836
6837        // (2) `BinarioWithoutExe` on the tuple-variant envelope: a
6838        // Binario-kind caixa with an empty `:exe` list fires the
6839        // kind-coherence gate whose payload is a bare `String`, so the
6840        // pattern is `LayoutError::BinarioWithoutExe(String)` rather
6841        // than the struct-variant `{ caixa, issue }` family. The
6842        // converge target is the same — `caixa.nome().to_string()` — but
6843        // the envelope shape is different, so the pin exercises both.
6844        let mut c = caixa(CaixaKind::Binario);
6845        // `:exe` empty is the trigger — the fixture helper defaults
6846        // it to `vec![]`, so no mutation is needed.
6847        c.nome = "binario-demo".into();
6848        let expected_nome_via_accessor = c.nome().to_string();
6849        assert_eq!(
6850            expected_nome_via_accessor, "binario-demo",
6851            "the mutated fixture's `:nome` must be observable through \
6852             the accessor before layout verification fires",
6853        );
6854        let err = layout.verify(&c, &root).unwrap_err();
6855        let LayoutError::BinarioWithoutExe(c_nome) = err else {
6856            panic!("expected BinarioWithoutExe for empty :exe list on Binario kind, got {err:?}");
6857        };
6858        assert_eq!(
6859            c_nome, expected_nome_via_accessor,
6860            "the BinarioWithoutExe's payload must equal \
6861             `c.nome().to_string()` — the tuple-variant envelope's \
6862             per-axis projection must route through the lifted \
6863             [`Caixa::nome`] accessor's `.to_string()` extension, not \
6864             the raw `caixa.nome.clone()` `String::clone()` of the \
6865             underlying field",
6866        );
6867
6868        // (3) `ServicoWithoutServicos` on the sibling tuple-variant
6869        // envelope: same discipline on the peer kind-coherence
6870        // partition arm. Constructed alongside the Binario arm so any
6871        // future accessor drift lands on both arms in the same pin.
6872        let mut c = caixa(CaixaKind::Servico);
6873        // `:servicos` empty is the trigger — the fixture helper
6874        // defaults it to `vec![]`, so no mutation is needed.
6875        c.nome = "servico-demo".into();
6876        let expected_nome_via_accessor = c.nome().to_string();
6877        assert_eq!(
6878            expected_nome_via_accessor, "servico-demo",
6879            "the mutated fixture's `:nome` must be observable through \
6880             the accessor before layout verification fires",
6881        );
6882        let err = layout.verify(&c, &root).unwrap_err();
6883        let LayoutError::ServicoWithoutServicos(c_nome) = err else {
6884            panic!(
6885                "expected ServicoWithoutServicos for empty :servicos list on Servico kind, \
6886                 got {err:?}"
6887            );
6888        };
6889        assert_eq!(
6890            c_nome, expected_nome_via_accessor,
6891            "the ServicoWithoutServicos's payload must equal \
6892             `c.nome().to_string()` — same converge discipline as the \
6893             sibling `BinarioWithoutExe` tuple-variant arm above",
6894        );
6895    }
6896
6897    #[test]
6898    fn supervisor_must_not_have_bibliotecas() {
6899        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
6900        let root = PathBuf::from("/tmp/x");
6901        let manifest = root.join("caixa.lisp");
6902        let manifest_clone = manifest.clone();
6903        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6904        let mut c = caixa(CaixaKind::Supervisor);
6905        c.estrategia = Some(RestartStrategy::OneForOne);
6906        c.max_restarts = Some(5);
6907        c.bibliotecas = vec!["lib/code.lisp".into()];
6908        c.children = vec![ChildSpec {
6909            caixa: "worker".into(),
6910            versao: "^0.1".into(),
6911            restart: RestartPolicy::Permanent,
6912        }];
6913        let err = layout.verify(&c, &root).unwrap_err();
6914        assert!(matches!(err, LayoutError::SupervisorOwnsCode(_)));
6915    }
6916
6917    // ── Caixa::validate_restart_window wired into Supervisor verify ─────
6918    //
6919    // Until this wire-up landed `Caixa::validate_restart_window` lived as
6920    // `pub fn` on `Caixa` with full per-arm unit coverage in
6921    // `manifest::tests` (`validate_restart_window_rejects_*` — fractional,
6922    // decimal-shaped integer, half-unit minute, leading sign, unknown
6923    // unit, garbage, empty-after-trim) but no production path called it;
6924    // `feira build` silently accepted malformed `:restart-window` and
6925    // `Caixa::supervisor_view` soft-swallowed the parse failure as
6926    // `restart_window: None` (the canonical "no reset" sentinel), turning
6927    // every authoring footgun into a never-reset supervisor far from the
6928    // source caixa.lisp. The following pins fence the layout-pipeline
6929    // wire-up: every layout verify on a structurally-invalid `:restart-
6930    // window` axis surfaces the per-axis `RestartWindowViolation { caixa,
6931    // issue }` envelope before the typed `SupervisorSpec::validate` gate
6932    // sees the laundered `None`.
6933
6934    fn supervisor_with_window(window: Option<&str>) -> Caixa {
6935        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
6936        let mut c = caixa(CaixaKind::Supervisor);
6937        c.estrategia = Some(RestartStrategy::OneForOne);
6938        c.max_restarts = Some(5);
6939        c.restart_window = window.map(str::to_string);
6940        c.children = vec![ChildSpec {
6941            caixa: "worker".into(),
6942            versao: "^0.1".into(),
6943            restart: RestartPolicy::Permanent,
6944        }];
6945        c
6946    }
6947
6948    #[test]
6949    fn restart_window_violation_on_fractional_seconds() {
6950        // `"1.5s"` is the canonical fractional-seconds drift footgun the
6951        // shared integer-magnitude codec (1c55a2a) rejects: round-trips
6952        // through `render` as `"1500ms"` on first serialize, breaking
6953        // THEORY.md §V.2.7 render-determinism. Before this wire-up
6954        // `supervisor_view` soft-swallowed the parse error as
6955        // `restart_window: None`, masking the drift as a never-reset
6956        // supervisor.
6957        let root = PathBuf::from("/tmp/x");
6958        let manifest = root.join("caixa.lisp");
6959        let manifest_clone = manifest.clone();
6960        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6961        let c = supervisor_with_window(Some("1.5s"));
6962        let err = layout.verify(&c, &root).unwrap_err();
6963        let LayoutError::RestartWindowViolation { caixa, issue } = err else {
6964            panic!("expected LayoutError::RestartWindowViolation, got {err:?}");
6965        };
6966        assert_eq!(caixa, "demo");
6967        assert!(
6968            issue.contains("1.5s"),
6969            "issue must quote the offending raw value: {issue}",
6970        );
6971    }
6972
6973    #[test]
6974    fn restart_window_violation_on_decimal_shaped_integer() {
6975        // `"1.0s"` — decimal-shaped integer the codec also rejects (a
6976        // canonical authoring form is `"1s"`). Sibling of the fractional
6977        // case; same codec arm.
6978        let root = PathBuf::from("/tmp/x");
6979        let manifest = root.join("caixa.lisp");
6980        let manifest_clone = manifest.clone();
6981        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
6982        let c = supervisor_with_window(Some("1.0s"));
6983        let err = layout.verify(&c, &root).unwrap_err();
6984        assert!(
6985            matches!(
6986                err,
6987                LayoutError::RestartWindowViolation { ref caixa, ref issue }
6988                    if caixa == "demo" && issue.contains("1.0s")
6989            ),
6990            "got {err:?}",
6991        );
6992    }
6993
6994    #[test]
6995    fn restart_window_violation_on_leading_sign() {
6996        // `"+30s"` / `"-30s"` — leading-sign drift the codec rejects.
6997        // Canonical form is `"30s"`. Pin both signs separately because
6998        // a future relaxation might accept one but not the other.
6999        for raw in ["+30s", "-30s"] {
7000            let root = PathBuf::from("/tmp/x");
7001            let manifest = root.join("caixa.lisp");
7002            let manifest_clone = manifest.clone();
7003            let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7004            let c = supervisor_with_window(Some(raw));
7005            let err = layout.verify(&c, &root).unwrap_err();
7006            assert!(
7007                matches!(
7008                    err,
7009                    LayoutError::RestartWindowViolation { ref caixa, ref issue }
7010                        if caixa == "demo" && issue.contains(raw)
7011                ),
7012                "leading-sign {raw:?} got {err:?}",
7013            );
7014        }
7015    }
7016
7017    #[test]
7018    fn restart_window_violation_on_unknown_unit() {
7019        // `"30x"` — unknown duration unit. The codec admits only
7020        // `ms`/`s`/`m`/`h`.
7021        let root = PathBuf::from("/tmp/x");
7022        let manifest = root.join("caixa.lisp");
7023        let manifest_clone = manifest.clone();
7024        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7025        let c = supervisor_with_window(Some("30x"));
7026        let err = layout.verify(&c, &root).unwrap_err();
7027        assert!(
7028            matches!(
7029                err,
7030                LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"
7031            ),
7032            "got {err:?}",
7033        );
7034    }
7035
7036    #[test]
7037    fn restart_window_violation_on_garbage() {
7038        // `"abc"` — pure garbage. The codec's parse fails before the
7039        // unit dispatch; the wrap envelope still surfaces the
7040        // self-locating diagnostic at the source.
7041        let root = PathBuf::from("/tmp/x");
7042        let manifest = root.join("caixa.lisp");
7043        let manifest_clone = manifest.clone();
7044        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7045        let c = supervisor_with_window(Some("abc"));
7046        let err = layout.verify(&c, &root).unwrap_err();
7047        assert!(
7048            matches!(err, LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"),
7049            "got {err:?}",
7050        );
7051    }
7052
7053    #[test]
7054    fn restart_window_violation_on_empty_string() {
7055        // `""` — empty after trim. The shared codec's digit-only gate
7056        // refuses an empty magnitude. Distinguished here from the
7057        // `None` ("omit the slot") canonical authoring shape: an empty
7058        // string is an authored-but-empty slot, never the author's
7059        // intent.
7060        let root = PathBuf::from("/tmp/x");
7061        let manifest = root.join("caixa.lisp");
7062        let manifest_clone = manifest.clone();
7063        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7064        let c = supervisor_with_window(Some(""));
7065        let err = layout.verify(&c, &root).unwrap_err();
7066        assert!(
7067            matches!(err, LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"),
7068            "got {err:?}",
7069        );
7070    }
7071
7072    #[test]
7073    fn verify_accepts_supervisor_without_restart_window() {
7074        // `None` is the canonical "omit the slot to express no reset"
7075        // shape — never reaches the codec, validates cleanly.
7076        let root = PathBuf::from("/tmp/x");
7077        let manifest = root.join("caixa.lisp");
7078        let manifest_clone = manifest.clone();
7079        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7080        let c = supervisor_with_window(None);
7081        layout.verify(&c, &root).unwrap();
7082    }
7083
7084    #[test]
7085    fn verify_accepts_supervisor_with_canonical_restart_window() {
7086        // Every canonical form the shared codec round-trips losslessly
7087        // must pass — `"500ms"`, `"30s"`, `"60s"`, `"1m"`, `"2m"`,
7088        // `"1h"`. Pin every form so a future tightening of the codec's
7089        // accepted set surfaces here as a test failure.
7090        for form in ["500ms", "30s", "60s", "1m", "2m", "1h"] {
7091            let root = PathBuf::from("/tmp/x");
7092            let manifest = root.join("caixa.lisp");
7093            let manifest_clone = manifest.clone();
7094            let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7095            let c = supervisor_with_window(Some(form));
7096            layout
7097                .verify(&c, &root)
7098                .unwrap_or_else(|e| panic!("canonical {form:?} must validate, got {e:?}"));
7099        }
7100    }
7101
7102    #[test]
7103    fn restart_window_violation_fires_before_supervisor_view_validate() {
7104        // Diagnostic-precedence pin: a Supervisor with a malformed
7105        // `:restart-window` AND a typed-shape defect on the typed view
7106        // (zero `:max-restarts`, which `SupervisorSpec::validate`'s
7107        // `ZeroMaxRestarts` arm rejects) surfaces the raw-string
7108        // diagnostic first — the narrower self-locating gate wins. Until
7109        // this wire-up landed `supervisor_view` would silently launder
7110        // the malformed `:restart-window` to `None` and then the typed
7111        // view's `ZeroMaxRestarts` gate would surface, masking the
7112        // raw-string footgun.
7113        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
7114        let root = PathBuf::from("/tmp/x");
7115        let manifest = root.join("caixa.lisp");
7116        let manifest_clone = manifest.clone();
7117        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7118        let mut c = caixa(CaixaKind::Supervisor);
7119        c.estrategia = Some(RestartStrategy::OneForOne);
7120        c.max_restarts = Some(0);
7121        c.restart_window = Some("1.5s".into());
7122        c.children = vec![ChildSpec {
7123            caixa: "worker".into(),
7124            versao: "^0.1".into(),
7125            restart: RestartPolicy::Permanent,
7126        }];
7127        let err = layout.verify(&c, &root).unwrap_err();
7128        assert!(
7129            matches!(err, LayoutError::RestartWindowViolation { .. }),
7130            "got {err:?} — RestartWindowViolation must fire before SupervisorViolation",
7131        );
7132    }
7133
7134    #[test]
7135    fn supervisor_slots_on_non_supervisor_fires_before_restart_window_violation() {
7136        // Order pin: a non-Supervisor caixa with a malformed
7137        // `:restart-window` surfaces `SupervisorSlotsOnNonSupervisor`
7138        // (the kind-coherence gate at the top of verify) before the
7139        // raw-string parse gate inside the Supervisor branch — because
7140        // `:restart-window` is foreign to non-Supervisor kinds, the
7141        // kind-coherence diagnostic is the load-bearing one. Mirrors
7142        // the existing `nome_violation_on_*` ordering tests that fence
7143        // the precedence between universal and kind-specific gates.
7144        let root = PathBuf::from("/tmp/x");
7145        let manifest = root.join("caixa.lisp");
7146        let default_lib = root.join("lib").join("demo.lisp");
7147        let layout =
7148            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
7149        let mut c = caixa(CaixaKind::Biblioteca);
7150        c.restart_window = Some("1.5s".into());
7151        let err = layout.verify(&c, &root).unwrap_err();
7152        assert!(
7153            matches!(err, LayoutError::SupervisorSlotsOnNonSupervisor { .. }),
7154            "got {err:?} — kind-coherence must fire before RestartWindowViolation",
7155        );
7156    }
7157
7158    #[test]
7159    fn restart_window_violation_diagnostic_carries_offending_value() {
7160        // Diagnostic-shape pin: the wrap envelope's `issue` carries the
7161        // codec's parser-shaped reason verbatim (which names the
7162        // offending raw value), so the author can grep their caixa.lisp
7163        // for `:restart-window "<value>"` and fix in one edit. Mirrors
7164        // `nome_violation_*_carries_offending_*` shape pins.
7165        let root = PathBuf::from("/tmp/x");
7166        let manifest = root.join("caixa.lisp");
7167        let manifest_clone = manifest.clone();
7168        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7169        let c = supervisor_with_window(Some("0.5m"));
7170        let err = layout.verify(&c, &root).unwrap_err();
7171        let LayoutError::RestartWindowViolation { caixa, issue } = err else {
7172            panic!("expected LayoutError::RestartWindowViolation, got {err:?}");
7173        };
7174        assert_eq!(caixa, "demo");
7175        assert!(
7176            issue.contains("0.5m"),
7177            "issue must quote the offending raw value verbatim: {issue}",
7178        );
7179        assert!(
7180            !issue.is_empty(),
7181            "issue must carry the codec's parser-shaped reason",
7182        );
7183    }
7184
7185    // ── Aplicacao layout tests ──────────────────────────────────────────
7186
7187    #[test]
7188    fn aplicacao_must_have_membros() {
7189        use crate::{Membro, Placement, PlacementStrategy};
7190        let root = PathBuf::from("/tmp/x");
7191        let manifest = root.join("caixa.lisp");
7192        let manifest_clone = manifest.clone();
7193        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7194        let mut c = caixa(CaixaKind::Aplicacao);
7195        c.placement = Some(Placement {
7196            estrategia: PlacementStrategy::Replicated,
7197            clusters: vec!["rio".into()],
7198            affinity: None,
7199            shard_key: None,
7200        });
7201        // No membros → fails
7202        let err = layout.verify(&c, &root).unwrap_err();
7203        assert!(matches!(err, LayoutError::AplicacaoViolation { .. }));
7204
7205        // With membros → passes
7206        c.membros = vec![Membro {
7207            caixa: "service-a".into(),
7208            versao: "^0.1".into(),
7209        }];
7210        layout.verify(&c, &root).unwrap();
7211    }
7212
7213    #[test]
7214    fn aplicacao_self_referential_membro_is_violation() {
7215        // An Aplicacao whose `:membros` names its own `:nome` is a
7216        // one-node lacre-closure recursion. The cross-slot gate fires
7217        // at verify time, surfacing as an AplicacaoViolation that
7218        // names the offending aplicacao — not at lacre-resolve time
7219        // far from source. The `caixa()` helper's `:nome` is "demo".
7220        // Peer of `supervisor_self_referential_child_is_violation`
7221        // on the supervision-tree axis.
7222        use crate::{Membro, Placement, PlacementStrategy};
7223        let root = PathBuf::from("/tmp/x");
7224        let manifest = root.join("caixa.lisp");
7225        let manifest_clone = manifest.clone();
7226        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7227        let mut c = caixa(CaixaKind::Aplicacao);
7228        c.placement = Some(Placement {
7229            estrategia: PlacementStrategy::Replicated,
7230            clusters: vec!["rio".into()],
7231            affinity: None,
7232            shard_key: None,
7233        });
7234        c.membros = vec![
7235            Membro {
7236                caixa: "service-a".into(),
7237                versao: "^0.1".into(),
7238            },
7239            Membro {
7240                caixa: "demo".into(),
7241                versao: "^0.1".into(),
7242            },
7243        ];
7244        let err = layout.verify(&c, &root).unwrap_err();
7245        let LayoutError::AplicacaoViolation { caixa, issue } = err else {
7246            panic!("expected AplicacaoViolation for self-referential membro, got {err:?}");
7247        };
7248        assert_eq!(caixa, "demo");
7249        assert!(
7250            issue.contains("demo") && issue.contains("lists itself"),
7251            "issue must name the self-membering aplicacao, got {issue:?}"
7252        );
7253    }
7254
7255    #[test]
7256    fn aplicacao_distinct_membros_pass_self_membership_gate() {
7257        // Positive control: an Aplicacao whose membros are all distinct
7258        // from its own `:nome` verifies cleanly.
7259        use crate::{Membro, Placement, PlacementStrategy};
7260        let root = PathBuf::from("/tmp/x");
7261        let manifest = root.join("caixa.lisp");
7262        let manifest_clone = manifest.clone();
7263        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7264        let mut c = caixa(CaixaKind::Aplicacao);
7265        c.placement = Some(Placement {
7266            estrategia: PlacementStrategy::Replicated,
7267            clusters: vec!["rio".into()],
7268            affinity: None,
7269            shard_key: None,
7270        });
7271        c.membros = vec![
7272            Membro {
7273                caixa: "service-a".into(),
7274                versao: "^0.1".into(),
7275            },
7276            Membro {
7277                caixa: "service-b".into(),
7278                versao: "^0.1".into(),
7279            },
7280        ];
7281        layout.verify(&c, &root).unwrap();
7282    }
7283
7284    #[test]
7285    fn aplicacao_self_membership_fires_after_view_validate() {
7286        // Diagnostic-precedence pin: a self-referential membro alongside
7287        // a duplicate-:caixa shape surfaces the more-fundamental
7288        // `MembroDuplicate` (from `view.validate()`) first; only when the
7289        // per-membros shape diagnostics pass does the cross-slot
7290        // self-membership gate fire. Mirrors the ordering pin
7291        // `supervisor_self_referential_child_is_violation` carries on
7292        // the peer supervision-tree axis (`view.validate()` runs first,
7293        // then the cross-slot gate). Without this ordering a future
7294        // refactor that swaps the two calls would silently mask the
7295        // narrower per-membro defect.
7296        use crate::{Membro, Placement, PlacementStrategy};
7297        let root = PathBuf::from("/tmp/x");
7298        let manifest = root.join("caixa.lisp");
7299        let manifest_clone = manifest.clone();
7300        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7301        let mut c = caixa(CaixaKind::Aplicacao);
7302        c.placement = Some(Placement {
7303            estrategia: PlacementStrategy::Replicated,
7304            clusters: vec!["rio".into()],
7305            affinity: None,
7306            shard_key: None,
7307        });
7308        c.membros = vec![
7309            Membro {
7310                caixa: "service-a".into(),
7311                versao: "^0.1".into(),
7312            },
7313            Membro {
7314                caixa: "service-a".into(),
7315                versao: "^0.2".into(),
7316            },
7317            Membro {
7318                caixa: "demo".into(),
7319                versao: "^0.1".into(),
7320            },
7321        ];
7322        let err = layout.verify(&c, &root).unwrap_err();
7323        let LayoutError::AplicacaoViolation { issue, .. } = err else {
7324            panic!("expected AplicacaoViolation, got {err:?}");
7325        };
7326        // The per-membros duplicate diagnostic (from view.validate())
7327        // surfaces ahead of the cross-slot self-membership gate, so the
7328        // `service-a` duplicate is named — not the `demo` self-reference.
7329        assert!(
7330            issue.contains("service-a") && issue.contains("more than once"),
7331            "duplicate-:caixa diagnostic must surface before self-membership gate, \
7332             got {issue:?}"
7333        );
7334    }
7335
7336    #[test]
7337    fn mesh_slots_on_servico_rejected() {
7338        // The canonical real-world footgun: an author adds :entrada to a
7339        // :kind Servico expecting it to expose ingress. aplicacao_view
7340        // returns None for Servico, so the slot is the manifest's
7341        // "ignored otherwise" — never validated, never rendered. The
7342        // kind-coherence gate rejects it at build time (before the
7343        // :servicos existence loop), naming the offending slot + kind.
7344        use crate::Entrada;
7345        let root = PathBuf::from("/tmp/x");
7346        let manifest = root.join("caixa.lisp");
7347        let manifest_clone = manifest.clone();
7348        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7349        let mut c = caixa(CaixaKind::Servico);
7350        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7351        c.entrada = Some(Entrada {
7352            host: "demo.example.com".into(),
7353            para: "demo".into(),
7354            paths: vec![],
7355            port: 8080,
7356        });
7357        let err = layout.verify(&c, &root).unwrap_err();
7358        match err {
7359            LayoutError::MeshSlotsOnNonAplicacao { caixa, kind, slots } => {
7360                assert_eq!(caixa, "demo");
7361                assert_eq!(kind, CaixaKind::Servico);
7362                assert_eq!(slots, crate::render::M3_AUTHOR_KEY_ENTRADA);
7363            }
7364            other => panic!("expected MeshSlotsOnNonAplicacao, got {other:?}"),
7365        }
7366    }
7367
7368    #[test]
7369    fn mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order() {
7370        // All five mesh slots declared on a Biblioteca → the diagnostic
7371        // enumerates them in canonical declaration order, deterministic
7372        // across runs. The gate fires on declared-ness only (the values
7373        // need not be a *valid* AplicacaoSpec — aplicacao_view is never
7374        // called for a non-Aplicacao kind).
7375        use crate::{Entrada, Membro, MeshPolicy, Placement, PlacementStrategy, WitContract};
7376        let root = PathBuf::from("/tmp/x");
7377        let manifest = root.join("caixa.lisp");
7378        let manifest_clone = manifest.clone();
7379        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7380        let mut c = caixa(CaixaKind::Biblioteca);
7381        c.membros = vec![Membro {
7382            caixa: "a".into(),
7383            versao: "^0.1".into(),
7384        }];
7385        c.contratos = vec![WitContract {
7386            de: "a".into(),
7387            para: "a".into(),
7388            wit: "wasi:http/proxy".into(),
7389            endpoint: Some("/x".into()),
7390            subject: None,
7391            slot: None,
7392        }];
7393        c.politicas = Some(MeshPolicy::default());
7394        c.placement = Some(Placement {
7395            estrategia: PlacementStrategy::Replicated,
7396            clusters: vec!["rio".into()],
7397            affinity: None,
7398            shard_key: None,
7399        });
7400        c.entrada = Some(Entrada {
7401            host: "x.example.com".into(),
7402            para: "a".into(),
7403            paths: vec![],
7404            port: 8080,
7405        });
7406        let err = layout.verify(&c, &root).unwrap_err();
7407        match err {
7408            LayoutError::MeshSlotsOnNonAplicacao { slots, .. } => {
7409                assert_eq!(
7410                    slots,
7411                    format!(
7412                        "{} {} {} {} {}",
7413                        crate::render::M3_AUTHOR_KEY_MEMBROS,
7414                        crate::render::M3_AUTHOR_KEY_CONTRATOS,
7415                        crate::render::M3_AUTHOR_KEY_POLITICAS,
7416                        crate::render::M3_AUTHOR_KEY_PLACEMENT,
7417                        crate::render::M3_AUTHOR_KEY_ENTRADA,
7418                    )
7419                );
7420            }
7421            other => panic!("expected MeshSlotsOnNonAplicacao, got {other:?}"),
7422        }
7423    }
7424
7425    #[test]
7426    fn servico_without_mesh_slots_still_verifies() {
7427        // Pass-after control: a well-formed Servico carrying no mesh
7428        // slots must remain accepted — the gate keys off declared-ness,
7429        // so it must not over-fire on the common case.
7430        let root = PathBuf::from("/tmp/x");
7431        let servico = root.join("servicos/demo.computeunit.yaml");
7432        let manifest = root.join("caixa.lisp");
7433        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == servico);
7434        let mut c = caixa(CaixaKind::Servico);
7435        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7436        layout.verify(&c, &root).unwrap();
7437    }
7438
7439    #[test]
7440    fn supervisor_slots_on_servico_rejected() {
7441        // Mirror of `mesh_slots_on_servico_rejected` on the
7442        // supervisor-tree slot set: an author adds `:children` to a
7443        // `:kind Servico` expecting it to spawn workers. supervisor_view
7444        // returns None for Servico, so the slot is the manifest's
7445        // "ignored otherwise" — never validated, never reconciled. The
7446        // kind-coherence gate rejects it at build time (before the
7447        // :servicos existence loop), naming the offending slot + kind.
7448        use crate::{ChildSpec, RestartPolicy};
7449        let root = PathBuf::from("/tmp/x");
7450        let manifest = root.join("caixa.lisp");
7451        let manifest_clone = manifest.clone();
7452        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7453        let mut c = caixa(CaixaKind::Servico);
7454        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7455        c.children = vec![ChildSpec {
7456            caixa: "worker".into(),
7457            versao: "^0.1".into(),
7458            restart: RestartPolicy::Permanent,
7459        }];
7460        let err = layout.verify(&c, &root).unwrap_err();
7461        match err {
7462            LayoutError::SupervisorSlotsOnNonSupervisor { caixa, kind, slots } => {
7463                assert_eq!(caixa, "demo");
7464                assert_eq!(kind, CaixaKind::Servico);
7465                assert_eq!(slots, crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN);
7466            }
7467            other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
7468        }
7469    }
7470
7471    #[test]
7472    fn supervisor_slots_on_non_supervisor_lists_slots_in_canonical_order() {
7473        // All four supervisor slots declared on a Biblioteca → the
7474        // diagnostic enumerates them in canonical declaration order
7475        // (`:estrategia` → `:max-restarts` → `:restart-window` →
7476        // `:children`), deterministic across runs. The gate fires on
7477        // declared-ness only (the values need not be a *valid*
7478        // SupervisorSpec — supervisor_view is never called for a
7479        // non-Supervisor kind). Mirror of
7480        // `mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order`.
7481        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
7482        let root = PathBuf::from("/tmp/x");
7483        let manifest = root.join("caixa.lisp");
7484        let manifest_clone = manifest.clone();
7485        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7486        let mut c = caixa(CaixaKind::Biblioteca);
7487        c.estrategia = Some(RestartStrategy::OneForOne);
7488        c.max_restarts = Some(5);
7489        c.restart_window = Some("60s".into());
7490        c.children = vec![ChildSpec {
7491            caixa: "worker".into(),
7492            versao: "^0.1".into(),
7493            restart: RestartPolicy::Permanent,
7494        }];
7495        let err = layout.verify(&c, &root).unwrap_err();
7496        match err {
7497            LayoutError::SupervisorSlotsOnNonSupervisor { slots, .. } => {
7498                assert_eq!(slots, ":estrategia :max-restarts :restart-window :children");
7499            }
7500            other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
7501        }
7502    }
7503
7504    #[test]
7505    fn aplicacao_with_supervisor_slots_rejected() {
7506        // Cross-kind pin: an Aplicacao (the other no-code orchestrator
7507        // kind) that declares a supervisor slot is rejected by the
7508        // supervisor-slot gate, just as a Supervisor declaring a mesh
7509        // slot is rejected by the mesh-slot gate — the two kind ↔ slot
7510        // coherence gates are symmetric and mutually exclusive. The
7511        // gate fires before the Aplicacao typed-graph validation, so
7512        // the diagnostic names the foreign supervisor slot rather than
7513        // a downstream AplicacaoViolation.
7514        use crate::{Membro, Placement, PlacementStrategy, RestartStrategy};
7515        let root = PathBuf::from("/tmp/x");
7516        let manifest = root.join("caixa.lisp");
7517        let manifest_clone = manifest.clone();
7518        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7519        let mut c = caixa(CaixaKind::Aplicacao);
7520        c.membros = vec![Membro {
7521            caixa: "service-a".into(),
7522            versao: "^0.1".into(),
7523        }];
7524        c.placement = Some(Placement {
7525            estrategia: PlacementStrategy::Replicated,
7526            clusters: vec!["rio".into()],
7527            affinity: None,
7528            shard_key: None,
7529        });
7530        c.estrategia = Some(RestartStrategy::OneForAll);
7531        let err = layout.verify(&c, &root).unwrap_err();
7532        match err {
7533            LayoutError::SupervisorSlotsOnNonSupervisor { caixa, kind, slots } => {
7534                assert_eq!(caixa, "demo");
7535                assert_eq!(kind, CaixaKind::Aplicacao);
7536                assert_eq!(slots, crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA);
7537            }
7538            other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
7539        }
7540    }
7541
7542    #[test]
7543    fn servico_without_supervisor_slots_still_verifies() {
7544        // Pass-after control: a well-formed Servico carrying no
7545        // supervisor slots must remain accepted — the gate keys off
7546        // declared-ness, so it must not over-fire on the common case.
7547        let root = PathBuf::from("/tmp/x");
7548        let servico = root.join("servicos/demo.computeunit.yaml");
7549        let manifest = root.join("caixa.lisp");
7550        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == servico);
7551        let mut c = caixa(CaixaKind::Servico);
7552        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7553        layout.verify(&c, &root).unwrap();
7554    }
7555
7556    #[test]
7557    fn servico_slots_on_biblioteca_rejected() {
7558        // Mirror of `mesh_slots_on_servico_rejected` /
7559        // `supervisor_slots_on_servico_rejected` on the M2
7560        // Servico-runtime slot set: an author adds `:limits` to a
7561        // `:kind Biblioteca` expecting per-process sandboxing. The
7562        // caixa-helm / caixa-flux renderers gate on `require_kind(_,
7563        // Servico)`, so the slot is the manifest's "ignored otherwise" —
7564        // never rendered into any artifact. The kind-coherence gate
7565        // rejects it at build time (before the M2 validate blocks),
7566        // naming the offending slot + kind.
7567        use crate::LimitsSpec;
7568        let root = PathBuf::from("/tmp/x");
7569        let manifest = root.join("caixa.lisp");
7570        let lib = root.join("lib").join("demo.lisp");
7571        let manifest_clone = manifest.clone();
7572        let layout =
7573            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == lib);
7574        let mut c = caixa(CaixaKind::Biblioteca);
7575        c.limits = Some(LimitsSpec {
7576            fuel: Some(1_000_000),
7577            ..Default::default()
7578        });
7579        let err = layout.verify(&c, &root).unwrap_err();
7580        match err {
7581            LayoutError::ServicoSlotsOnNonServico { caixa, kind, slots } => {
7582                assert_eq!(caixa, "demo");
7583                assert_eq!(kind, CaixaKind::Biblioteca);
7584                assert_eq!(slots, crate::render::M2_AUTHOR_KEY_LIMITS);
7585            }
7586            other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
7587        }
7588    }
7589
7590    #[test]
7591    fn servico_slots_on_non_servico_lists_slots_in_canonical_order() {
7592        // All three M2 slots declared on a Biblioteca → the diagnostic
7593        // enumerates them in canonical declaration order (`:limits` →
7594        // `:behavior` → `:upgrade-from`), deterministic across runs. The
7595        // gate fires on declared-ness only (the values need not pass the
7596        // M2 validate blocks — those run only after the kind-coherence
7597        // gate, and never for a non-Servico declared-slot caixa). Mirror
7598        // of the mesh/supervisor `*_lists_slots_in_canonical_order` pins.
7599        use crate::{BehaviorSpec, LimitsSpec, UpgradeFromEntry, UpgradeInstruction};
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::Biblioteca);
7605        c.limits = Some(LimitsSpec {
7606            fuel: Some(1_000_000),
7607            ..Default::default()
7608        });
7609        c.behavior = Some(BehaviorSpec {
7610            on_init: Some(PathBuf::from("lib/init.lisp")),
7611            ..Default::default()
7612        });
7613        c.upgrade_from = vec![UpgradeFromEntry {
7614            from: "0.1.0".into(),
7615            instructions: vec![UpgradeInstruction::Restart],
7616        }];
7617        let err = layout.verify(&c, &root).unwrap_err();
7618        match err {
7619            LayoutError::ServicoSlotsOnNonServico { slots, .. } => {
7620                assert_eq!(
7621                    slots,
7622                    format!(
7623                        "{} {} {}",
7624                        crate::render::M2_AUTHOR_KEY_LIMITS,
7625                        crate::render::M2_AUTHOR_KEY_BEHAVIOR,
7626                        crate::render::M2_AUTHOR_KEY_UPGRADE_FROM,
7627                    )
7628                );
7629            }
7630            other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
7631        }
7632    }
7633
7634    #[test]
7635    fn aplicacao_with_servico_slots_rejected() {
7636        // Cross-kind pin (mirror of `aplicacao_with_supervisor_slots_rejected`):
7637        // an Aplicacao that declares an M2 Servico-runtime slot is
7638        // rejected by the Servico-slot gate, just as a Supervisor
7639        // declaring a mesh slot is rejected by the mesh-slot gate — the
7640        // three kind ↔ slot coherence gates are symmetric and mutually
7641        // exclusive. The gate fires before the Aplicacao typed-graph
7642        // validation, so the diagnostic names the foreign M2 slot rather
7643        // than a downstream AplicacaoViolation about missing :membros.
7644        use crate::{Membro, Placement, PlacementStrategy, UpgradeFromEntry, UpgradeInstruction};
7645        let root = PathBuf::from("/tmp/x");
7646        let manifest = root.join("caixa.lisp");
7647        let manifest_clone = manifest.clone();
7648        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7649        let mut c = caixa(CaixaKind::Aplicacao);
7650        c.membros = vec![Membro {
7651            caixa: "service-a".into(),
7652            versao: "^0.1".into(),
7653        }];
7654        c.placement = Some(Placement {
7655            estrategia: PlacementStrategy::Replicated,
7656            clusters: vec!["rio".into()],
7657            affinity: None,
7658            shard_key: None,
7659        });
7660        c.upgrade_from = vec![UpgradeFromEntry {
7661            from: "0.1.0".into(),
7662            instructions: vec![UpgradeInstruction::Restart],
7663        }];
7664        let err = layout.verify(&c, &root).unwrap_err();
7665        match err {
7666            LayoutError::ServicoSlotsOnNonServico { caixa, kind, slots } => {
7667                assert_eq!(caixa, "demo");
7668                assert_eq!(kind, CaixaKind::Aplicacao);
7669                assert_eq!(slots, crate::render::M2_AUTHOR_KEY_UPGRADE_FROM);
7670            }
7671            other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
7672        }
7673    }
7674
7675    #[test]
7676    fn servico_with_servico_slots_still_verifies() {
7677        // Pass-after control: a well-formed Servico carrying all three M2
7678        // slots must remain accepted — the gate is guarded by `kind !=
7679        // Servico`, so it must not over-fire on the kind these slots
7680        // exist for. Mirror of `servico_without_{mesh,supervisor}_slots_
7681        // still_verifies` on the legitimate-declaration axis.
7682        use crate::{BehaviorSpec, LimitsSpec, UpgradeFromEntry, UpgradeInstruction};
7683        let root = PathBuf::from("/tmp/x");
7684        let manifest = root.join("caixa.lisp");
7685        let svc = root.join("servicos/demo.computeunit.yaml");
7686        let init = root.join("lib/init.lisp");
7687        let layout =
7688            StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc || p == init);
7689        let mut c = caixa(CaixaKind::Servico);
7690        c.versao = "0.2.0".into();
7691        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7692        c.limits = Some(LimitsSpec {
7693            fuel: Some(1_000_000),
7694            ..Default::default()
7695        });
7696        c.behavior = Some(BehaviorSpec {
7697            on_init: Some(PathBuf::from("lib/init.lisp")),
7698            ..Default::default()
7699        });
7700        c.upgrade_from = vec![UpgradeFromEntry {
7701            from: "0.1.0".into(),
7702            instructions: vec![UpgradeInstruction::Restart],
7703        }];
7704        layout.verify(&c, &root).unwrap();
7705    }
7706
7707    #[test]
7708    fn aplicacao_must_not_have_bibliotecas() {
7709        use crate::{Membro, Placement, PlacementStrategy};
7710        let root = PathBuf::from("/tmp/x");
7711        let manifest = root.join("caixa.lisp");
7712        let manifest_clone = manifest.clone();
7713        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7714        let mut c = caixa(CaixaKind::Aplicacao);
7715        c.bibliotecas = vec!["lib/code.lisp".into()];
7716        c.membros = vec![Membro {
7717            caixa: "x".into(),
7718            versao: "^0.1".into(),
7719        }];
7720        c.placement = Some(Placement {
7721            estrategia: PlacementStrategy::Replicated,
7722            clusters: vec!["rio".into()],
7723            affinity: None,
7724            shard_key: None,
7725        });
7726        let err = layout.verify(&c, &root).unwrap_err();
7727        assert!(matches!(err, LayoutError::AplicacaoOwnsCode(_)));
7728    }
7729
7730    #[test]
7731    fn acao_must_not_have_bibliotecas() {
7732        // Mirror of `supervisor_must_not_have_bibliotecas` /
7733        // `aplicacao_must_not_have_bibliotecas` on the third no-code
7734        // kind. `has_code` fires before the `:ci`-presence gates below
7735        // it, so this must surface `AcaoOwnsCode` even though the
7736        // caixa also lacks a `:ci` slot (which would otherwise surface
7737        // as `MissingCi`) — the more-fundamental "this kind runs no
7738        // code at all" diagnostic wins.
7739        let root = PathBuf::from("/tmp/x");
7740        let manifest = root.join("caixa.lisp");
7741        let manifest_clone = manifest.clone();
7742        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7743        let mut c = caixa(CaixaKind::Acao);
7744        c.bibliotecas = vec!["lib/code.lisp".into()];
7745        let err = layout.verify(&c, &root).unwrap_err();
7746        assert!(matches!(err, LayoutError::AcaoOwnsCode(_)));
7747    }
7748
7749    #[test]
7750    fn acao_without_ci_errors() {
7751        // Mirror of `binario_without_exe_errors` on the fifth required-
7752        // slot axis.
7753        let root = PathBuf::from("/tmp/x");
7754        let manifest = root.join("caixa.lisp");
7755        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
7756        let err = layout.verify(&caixa(CaixaKind::Acao), &root).unwrap_err();
7757        assert!(matches!(err, LayoutError::MissingCi(_)));
7758    }
7759
7760    #[test]
7761    fn acao_with_ci_passes() {
7762        let root = PathBuf::from("/tmp/x");
7763        let manifest = root.join("caixa.lisp");
7764        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
7765        let mut c = caixa(CaixaKind::Acao);
7766        c.ci = Some(canteiro_types::CiRun {
7767            workspace: "pleme-io".into(),
7768            repo: "caixa".into(),
7769            nodes: vec![],
7770        });
7771        layout
7772            .verify(&c, &root)
7773            .expect("an Acao caixa with a declared :ci slot passes layout verify");
7774    }
7775
7776    #[test]
7777    fn acao_with_cyclic_ci_rejected_at_layout() {
7778        // Layout-side wire-up pin on the compound
7779        // [`crate::Caixa::validate_acao_shape`] gate: a `:kind Acao`
7780        // caixa declaring a structurally illegal `:ci` (here — a
7781        // minimal two-node cycle `a → b → a`, one of the three
7782        // `canteiro_types::DecomposeError` arms
7783        // [`crate::decompose_ci`] refuses) surfaces
7784        // [`LayoutError::AcaoViolation`] at `feira build` time rather
7785        // than passing the layout gate silently and deferring the
7786        // diagnostic to [`caixa_actions::validate`] at renderer time.
7787        //
7788        // Pre-lift the layout pipeline only checked `:ci` *presence*
7789        // via [`LayoutError::MissingCi`]; the decompose gate lived
7790        // only wired open-coded at
7791        // [`caixa_actions::validate`] via the substrate-canonical
7792        // [`crate::require_acao_view`] compound helper. This wire-up
7793        // pin locks the new layout-side compound-shape gate in place
7794        // — a future regression that dropped the `if
7795        // caixa.kind().is_acao() { validate_acao_shape() }` block or
7796        // relaxed the diagnostic surface trips here at caixa-core
7797        // build time. Sibling in shape to the peer
7798        // [`aplicacao_must_not_have_bibliotecas`] /
7799        // [`supervisor_must_not_have_bibliotecas`] /
7800        // [`acao_must_not_have_bibliotecas`] layout wire-up pins on
7801        // the sibling per-kind shape gates.
7802        let root = PathBuf::from("/tmp/x");
7803        let manifest = root.join("caixa.lisp");
7804        let manifest_clone = manifest.clone();
7805        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7806        let mut c = caixa(CaixaKind::Acao);
7807        c.ci = Some(canteiro_types::CiRun {
7808            workspace: "pleme-io".into(),
7809            repo: "caixa".into(),
7810            nodes: vec![
7811                canteiro_types::CiNode::new(
7812                    "a",
7813                    canteiro_types::EnvClass::None,
7814                    canteiro_types::ActionRef {
7815                        name: "a".into(),
7816                        command: "true".into(),
7817                        args: vec![],
7818                    },
7819                    vec!["b".into()],
7820                ),
7821                canteiro_types::CiNode::new(
7822                    "b",
7823                    canteiro_types::EnvClass::None,
7824                    canteiro_types::ActionRef {
7825                        name: "b".into(),
7826                        command: "true".into(),
7827                        args: vec![],
7828                    },
7829                    vec!["a".into()],
7830                ),
7831            ],
7832        });
7833        let err = layout.verify(&c, &root).unwrap_err();
7834        match err {
7835            LayoutError::AcaoViolation { caixa, issue } => {
7836                assert_eq!(caixa, "demo");
7837                assert!(
7838                    issue.contains("decompose"),
7839                    "AcaoViolation issue must name the decompose axis (got: {issue:?})",
7840                );
7841                assert!(
7842                    issue.contains("demo"),
7843                    "AcaoViolation issue must name the offending caixa nome via the folded \
7844                     CiDecomposeFailure Display (got: {issue:?})",
7845                );
7846            }
7847            other => panic!("expected AcaoViolation on a cyclic :ci, got {other:?}"),
7848        }
7849    }
7850
7851    #[test]
7852    fn ci_on_non_acao_errors() {
7853        // Mirror of `mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order`
7854        // on the Acao-only `:ci` axis — declaring `:ci` on any other
7855        // kind is the same "silently ignored" footgun the sibling
7856        // mesh-/supervisor-/servico-slot gates already close.
7857        let root = PathBuf::from("/tmp/x");
7858        let manifest = root.join("caixa.lisp");
7859        let manifest_clone = manifest.clone();
7860        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7861        let mut c = caixa(CaixaKind::Biblioteca);
7862        c.ci = Some(canteiro_types::CiRun {
7863            workspace: "pleme-io".into(),
7864            repo: "caixa".into(),
7865            nodes: vec![],
7866        });
7867        let err = layout.verify(&c, &root).unwrap_err();
7868        match err {
7869            LayoutError::CiOnNonAcao { caixa, kind } => {
7870                assert_eq!(caixa, "demo");
7871                assert_eq!(kind, CaixaKind::Biblioteca);
7872            }
7873            other => panic!("expected CiOnNonAcao, got {other:?}"),
7874        }
7875    }
7876
7877    // ── ForeignCodeSlot — kind ↔ code-surface coherence ────────────────
7878
7879    #[test]
7880    fn biblioteca_with_exe_rejected() {
7881        // Fail-before-pass-after pin: a `:kind Biblioteca` declaring
7882        // `:exe` is the "I added a CLI to my library" footgun — the nix
7883        // flake renderer for Binario gates on `require_kind(_, Binario)`,
7884        // so on a Biblioteca the `:exe` path is silently dropped past
7885        // the layout's path-existence check (no executable target is
7886        // ever generated). The diagnostic names the offending kind +
7887        // slot verbatim so the author can grep their caixa.lisp for
7888        // `:exe` and fix in one edit (drop the slot or change
7889        // `:kind Biblioteca` → `:kind Binario`).
7890        let root = PathBuf::from("/tmp/x");
7891        let manifest = root.join("caixa.lisp");
7892        let lib = root.join("lib").join("demo.lisp");
7893        let exe_path = root.join("exe").join("tool");
7894        let layout = StandardLayout::new()
7895            .with_path_exists(move |p| p == manifest || p == lib || p == exe_path);
7896        let mut c = caixa(CaixaKind::Biblioteca);
7897        c.exe = vec!["exe/tool".into()];
7898        let err = layout.verify(&c, &root).unwrap_err();
7899        match err {
7900            LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
7901                assert_eq!(caixa, "demo");
7902                assert_eq!(kind, CaixaKind::Biblioteca);
7903                assert_eq!(slots, ":exe");
7904            }
7905            other => panic!("expected ForeignCodeSlot, got {other:?}"),
7906        }
7907    }
7908
7909    #[test]
7910    fn biblioteca_with_servicos_rejected() {
7911        // Symmetric to `biblioteca_with_exe_rejected` on the
7912        // `:servicos` axis: a `:kind Biblioteca` declaring a Servico
7913        // computeunit silently passed validate and the daemon's
7914        // ComputeUnit / lareira chart never materialized (caixa-helm /
7915        // caixa-flux gate emission on `require_kind(_, Servico)`).
7916        let root = PathBuf::from("/tmp/x");
7917        let manifest = root.join("caixa.lisp");
7918        let lib = root.join("lib").join("demo.lisp");
7919        let svc = root.join("servicos").join("demo.computeunit.yaml");
7920        let layout =
7921            StandardLayout::new().with_path_exists(move |p| p == manifest || p == lib || p == svc);
7922        let mut c = caixa(CaixaKind::Biblioteca);
7923        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7924        let err = layout.verify(&c, &root).unwrap_err();
7925        match err {
7926            LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
7927                assert_eq!(caixa, "demo");
7928                assert_eq!(kind, CaixaKind::Biblioteca);
7929                assert_eq!(slots, ":servicos");
7930            }
7931            other => panic!("expected ForeignCodeSlot, got {other:?}"),
7932        }
7933    }
7934
7935    #[test]
7936    fn biblioteca_with_exe_and_servicos_lists_slots_in_canonical_order() {
7937        // Both foreign code slots declared on a Biblioteca → the
7938        // diagnostic enumerates them in canonical declaration order
7939        // (`:exe` → `:servicos`), deterministic across runs. Mirrors the
7940        // mesh/supervisor/servico-slot `*_lists_slots_in_canonical_order`
7941        // pins on the peer kind ↔ slot algebra axes; drift in the
7942        // [`Caixa::declared_foreign_code_slots`] iteration order surfaces
7943        // here.
7944        let root = PathBuf::from("/tmp/x");
7945        let manifest = root.join("caixa.lisp");
7946        let manifest_clone = manifest.clone();
7947        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
7948        let mut c = caixa(CaixaKind::Biblioteca);
7949        c.exe = vec!["exe/tool".into()];
7950        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7951        let err = layout.verify(&c, &root).unwrap_err();
7952        match err {
7953            LayoutError::ForeignCodeSlot { slots, .. } => {
7954                assert_eq!(slots, ":exe :servicos");
7955            }
7956            other => panic!("expected ForeignCodeSlot, got {other:?}"),
7957        }
7958    }
7959
7960    #[test]
7961    fn binario_with_servicos_rejected() {
7962        // The peer footgun on the Binario kind: declaring a Servico
7963        // computeunit on a `:kind Binario` caixa. The caixa-helm /
7964        // caixa-flux renderers gate on `require_kind(_, Servico)`, so
7965        // the `:servicos` slot vanishes past the layout's path-
7966        // existence check — no ComputeUnit, no Helm chart. `:exe` stays
7967        // valid (Binario's native code surface), so the kind-coherence
7968        // diagnostic targets only `:servicos`.
7969        let root = PathBuf::from("/tmp/x");
7970        let manifest = root.join("caixa.lisp");
7971        let exe_path = root.join("exe").join("tool");
7972        let svc = root.join("servicos").join("demo.computeunit.yaml");
7973        let layout = StandardLayout::new()
7974            .with_path_exists(move |p| p == manifest || p == exe_path || p == svc);
7975        let mut c = caixa(CaixaKind::Binario);
7976        c.exe = vec!["exe/tool".into()];
7977        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
7978        let err = layout.verify(&c, &root).unwrap_err();
7979        match err {
7980            LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
7981                assert_eq!(caixa, "demo");
7982                assert_eq!(kind, CaixaKind::Binario);
7983                assert_eq!(slots, ":servicos");
7984            }
7985            other => panic!("expected ForeignCodeSlot, got {other:?}"),
7986        }
7987    }
7988
7989    #[test]
7990    fn servico_with_exe_rejected() {
7991        // Symmetric to `binario_with_servicos_rejected` on the other
7992        // code-running peer: a `:kind Servico` declaring an `:exe` is
7993        // the "I added a host-side CLI to my wasm component" footgun —
7994        // the nix flake's Binario target gates on `require_kind(_,
7995        // Binario)`, so the `:exe` path vanishes past the layout's
7996        // path-existence check.
7997        let root = PathBuf::from("/tmp/x");
7998        let manifest = root.join("caixa.lisp");
7999        let svc = root.join("servicos").join("demo.computeunit.yaml");
8000        let exe_path = root.join("exe").join("tool");
8001        let layout = StandardLayout::new()
8002            .with_path_exists(move |p| p == manifest || p == svc || p == exe_path);
8003        let mut c = caixa(CaixaKind::Servico);
8004        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8005        c.exe = vec!["exe/tool".into()];
8006        let err = layout.verify(&c, &root).unwrap_err();
8007        match err {
8008            LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
8009                assert_eq!(caixa, "demo");
8010                assert_eq!(kind, CaixaKind::Servico);
8011                assert_eq!(slots, ":exe");
8012            }
8013            other => panic!("expected ForeignCodeSlot, got {other:?}"),
8014        }
8015    }
8016
8017    #[test]
8018    fn binario_without_servicos_still_verifies() {
8019        // Pass-after control: a well-formed Binario carrying only its
8020        // native `:exe` surface must remain accepted — the gate keys off
8021        // declared-ness of the *foreign* slots, so it must not over-fire
8022        // on the legitimate same-kind case. Mirror of
8023        // `servico_with_servico_slots_still_verifies` on the peer axis.
8024        let root = PathBuf::from("/tmp/x");
8025        let manifest = root.join("caixa.lisp");
8026        let exe_path = root.join("exe").join("tool");
8027        let layout =
8028            StandardLayout::new().with_path_exists(move |p| p == manifest || p == exe_path);
8029        let mut c = caixa(CaixaKind::Binario);
8030        c.exe = vec!["exe/tool".into()];
8031        layout.verify(&c, &root).unwrap();
8032    }
8033
8034    #[test]
8035    fn biblioteca_with_only_bibliotecas_still_verifies() {
8036        // Pass-after control: a well-formed Biblioteca carrying only
8037        // its native `:bibliotecas` surface (or the default
8038        // `lib/<nome>.lisp`) must remain accepted. The gate keys off
8039        // declared-ness of `:exe` + `:servicos` only — `:bibliotecas`
8040        // is deliberately excluded from the foreign-set on every
8041        // code-running kind (`declared_foreign_code_slots` doc), so a
8042        // Biblioteca with the canonical lib surface alone passes.
8043        let root = PathBuf::from("/tmp/x");
8044        let manifest = root.join("caixa.lisp");
8045        let lib = root.join("lib").join("demo.lisp");
8046        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == lib);
8047        layout
8048            .verify(&caixa(CaixaKind::Biblioteca), &root)
8049            .expect("Biblioteca with default lib must verify");
8050    }
8051
8052    #[test]
8053    fn binario_with_bibliotecas_helper_still_verifies() {
8054        // Pass-after control on the deliberate `:bibliotecas`-as-helper
8055        // shape: a `:kind Binario` may legitimately bundle a `lib/`
8056        // helper its nix flake build consumes (the same shape a
8057        // `:kind Servico` may bundle for its wasm-component source).
8058        // The foreign-code-slot gate must NOT fire on `:bibliotecas` for
8059        // either code-running kind; pinned here so a future tightening
8060        // that adds `:bibliotecas` to the foreign set on Binario /
8061        // Servico surfaces as a test failure rather than as a silent
8062        // over-reach.
8063        let root = PathBuf::from("/tmp/x");
8064        let manifest = root.join("caixa.lisp");
8065        let exe_path = root.join("exe").join("tool");
8066        let lib = root.join("lib").join("helper.lisp");
8067        let layout = StandardLayout::new()
8068            .with_path_exists(move |p| p == manifest || p == exe_path || p == lib);
8069        let mut c = caixa(CaixaKind::Binario);
8070        c.exe = vec!["exe/tool".into()];
8071        c.bibliotecas = vec!["lib/helper.lisp".into()];
8072        layout.verify(&c, &root).unwrap();
8073    }
8074
8075    #[test]
8076    fn supervisor_with_exe_still_surfaces_owns_code() {
8077        // Diagnostic-precedence pin: a `:kind Supervisor` declaring
8078        // `:exe` is *both* "Supervisor with code" and "foreign code
8079        // slot". The more-fundamental `SupervisorOwnsCode` must win
8080        // (Supervisor doesn't run code at all — the foreign-slot
8081        // diagnostic would mislead the author toward changing `:kind`
8082        // when the underlying defect is that supervisors orchestrate
8083        // children, not code). Guards the call order in `verify`
8084        // against silent reordering.
8085        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
8086        let root = PathBuf::from("/tmp/x");
8087        let manifest = root.join("caixa.lisp");
8088        let manifest_clone = manifest.clone();
8089        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
8090        let mut c = caixa(CaixaKind::Supervisor);
8091        c.estrategia = Some(RestartStrategy::OneForOne);
8092        c.max_restarts = Some(5);
8093        c.exe = vec!["exe/tool".into()];
8094        c.children = vec![ChildSpec {
8095            caixa: "worker".into(),
8096            versao: "^0.1".into(),
8097            restart: RestartPolicy::Permanent,
8098        }];
8099        let err = layout.verify(&c, &root).unwrap_err();
8100        assert!(
8101            matches!(err, LayoutError::SupervisorOwnsCode(_)),
8102            "Supervisor-with-:exe must surface as SupervisorOwnsCode (the more-fundamental \
8103             no-code-at-all diagnostic), got {err:?}"
8104        );
8105    }
8106
8107    #[test]
8108    fn declared_foreign_code_slots_returns_canonical_order() {
8109        // Unit-level pin for the lifted method: the canonical iteration
8110        // order is `:exe` → `:servicos`, independent of which subset is
8111        // populated. Empty input + each single-slot subset + the full
8112        // pair are all checked so a future axis added to the method
8113        // (a hypothetical fifth code-surface slot) is one extension
8114        // point + one assertion update here, not a coordinated rewrite
8115        // across the layout-test sites that reach for the canonical
8116        // order.
8117        let mut c = caixa(CaixaKind::Biblioteca);
8118        assert!(c.declared_foreign_code_slots().is_empty());
8119        c.exe = vec!["exe/tool".into()];
8120        assert_eq!(c.declared_foreign_code_slots(), vec![":exe"]);
8121        c.exe.clear();
8122        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8123        assert_eq!(c.declared_foreign_code_slots(), vec![":servicos"]);
8124        c.exe = vec!["exe/tool".into()];
8125        assert_eq!(c.declared_foreign_code_slots(), vec![":exe", ":servicos"]);
8126    }
8127
8128    #[test]
8129    fn aplicacao_with_unknown_contrato_member_fails() {
8130        use crate::{Membro, Placement, PlacementStrategy, WitContract};
8131        let root = PathBuf::from("/tmp/x");
8132        let manifest = root.join("caixa.lisp");
8133        let manifest_clone = manifest.clone();
8134        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
8135        let mut c = caixa(CaixaKind::Aplicacao);
8136        c.membros = vec![Membro {
8137            caixa: "service-a".into(),
8138            versao: "^0.1".into(),
8139        }];
8140        c.contratos = vec![WitContract {
8141            de: "service-a".into(),
8142            para: "phantom".into(),
8143            wit: "wasi:http/proxy".into(),
8144            endpoint: Some("/x".into()),
8145            subject: None,
8146            slot: None,
8147        }];
8148        c.placement = Some(Placement {
8149            estrategia: PlacementStrategy::Replicated,
8150            clusters: vec!["rio".into()],
8151            affinity: None,
8152            shard_key: None,
8153        });
8154        let err = layout.verify(&c, &root).unwrap_err();
8155        assert!(matches!(err, LayoutError::AplicacaoViolation { .. }));
8156    }
8157
8158    #[test]
8159    fn limits_zero_axis_surfaces_as_layout_violation() {
8160        use crate::LimitsSpec;
8161        let root = PathBuf::from("/tmp/x");
8162        let manifest = root.join("caixa.lisp");
8163        let svc = root.join("servicos/demo.computeunit.yaml");
8164        let mut c = caixa(CaixaKind::Servico);
8165        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8166        c.limits = Some(LimitsSpec {
8167            fuel: Some(0),
8168            ..Default::default()
8169        });
8170        let manifest_clone = manifest.clone();
8171        let svc_clone = svc.clone();
8172        let layout =
8173            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8174        let err = layout.verify(&c, &root).unwrap_err();
8175        let LayoutError::LimitsViolation { caixa, issue } = err else {
8176            panic!("expected LimitsViolation, got {err:?}");
8177        };
8178        assert_eq!(caixa, "demo");
8179        assert!(issue.contains(":fuel"), "issue must name the axis: {issue}");
8180    }
8181
8182    #[test]
8183    fn limits_well_formed_passes_layout() {
8184        use crate::LimitsSpec;
8185        use std::time::Duration;
8186        let root = PathBuf::from("/tmp/x");
8187        let manifest = root.join("caixa.lisp");
8188        let svc = root.join("servicos/demo.computeunit.yaml");
8189        let mut c = caixa(CaixaKind::Servico);
8190        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8191        c.limits = Some(LimitsSpec {
8192            memory: Some(64 * 1024 * 1024),
8193            fuel: Some(1_000_000),
8194            wall_clock: Some(Duration::from_secs(30)),
8195            cpu: Some(500),
8196        });
8197        let manifest_clone = manifest.clone();
8198        let svc_clone = svc.clone();
8199        let layout =
8200            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8201        layout.verify(&c, &root).unwrap();
8202    }
8203
8204    #[test]
8205    fn supervisor_with_valid_children_passes() {
8206        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
8207        let root = PathBuf::from("/tmp/x");
8208        let manifest = root.join("caixa.lisp");
8209        let manifest_clone = manifest.clone();
8210        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
8211        let mut c = caixa(CaixaKind::Supervisor);
8212        c.estrategia = Some(RestartStrategy::OneForOne);
8213        c.max_restarts = Some(5);
8214        c.children = vec![
8215            ChildSpec {
8216                caixa: "worker".into(),
8217                versao: "^0.1".into(),
8218                restart: RestartPolicy::Permanent,
8219            },
8220            ChildSpec {
8221                caixa: "cache".into(),
8222                versao: "^0.1".into(),
8223                restart: RestartPolicy::Transient,
8224            },
8225        ];
8226        layout.verify(&c, &root).unwrap();
8227    }
8228
8229    // ── :upgrade-from entry validation pipes through layout ─────────────
8230
8231    #[test]
8232    fn upgrade_invalid_module_surfaces_as_layout_violation() {
8233        // End-to-end pin that
8234        // [`crate::UpgradeFromEntry::validate`] runs *inside*
8235        // `LayoutInvariants::verify` and surfaces value-shape
8236        // violations through the new `UpgradeViolation` arm
8237        // (parallel to `BehaviorViolation`, `LimitsViolation`,
8238        // `SupervisorViolation`, `AplicacaoViolation`). Until this
8239        // wiring landed the entry validator was unreachable from any
8240        // build-pipeline caller — an `:upgrade-from
8241        // ((:from "0.1.0" :instructions ((:load-module "Hello")))` (uppercase
8242        // module name the K8s apiserver would reject on the per-
8243        // ComputeUnit `metadata.name` axis) silently passed
8244        // `feira lint` / `feira build` and surfaced only at wasm-engine
8245        // hot-upgrade time as a per-backend "module not found" /
8246        // `code:load_module/1` `badarg` runtime error, far from the
8247        // source caixa.lisp. Pinning the wiring here so a future
8248        // refactor that drops the `entry.validate()` call surfaces as
8249        // a build-pipeline regression at this test, not as a runtime
8250        // surprise per consumer.
8251        use crate::{UpgradeFromEntry, UpgradeInstruction};
8252        use std::path::PathBuf;
8253        let root = PathBuf::from("/tmp/x");
8254        let manifest = root.join("caixa.lisp");
8255        let svc = root.join("servicos/demo.computeunit.yaml");
8256        let mut c = caixa(CaixaKind::Servico);
8257        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8258        c.upgrade_from = vec![UpgradeFromEntry {
8259            from: "0.1.0".into(),
8260            instructions: vec![UpgradeInstruction::LoadModule {
8261                module: "Hello".into(), // uppercase — not DNS-1123
8262            }],
8263        }];
8264        let manifest_clone = manifest.clone();
8265        let svc_clone = svc.clone();
8266        let layout =
8267            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8268        let err = layout.verify(&c, &root).unwrap_err();
8269        let LayoutError::UpgradeViolation { caixa, issue } = err else {
8270            panic!("expected UpgradeViolation, got {err:?}");
8271        };
8272        assert_eq!(caixa, "demo");
8273        assert!(
8274            issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE),
8275            "issue must name the lisp-form of the offending instruction: {issue}"
8276        );
8277        assert!(
8278            issue.contains("Hello"),
8279            "issue must name the offending :module verbatim: {issue}"
8280        );
8281    }
8282
8283    #[test]
8284    fn upgrade_empty_module_surfaces_as_layout_violation() {
8285        // Companion to the DNS-1123 footgun above on the narrower
8286        // empty arm. Every Module-bearing variant's empty value
8287        // reaches the layout pipeline through the kind-tagged
8288        // `ModuleEmpty` diagnostic naming its lisp-form.
8289        use crate::{UpgradeFromEntry, UpgradeInstruction};
8290        use std::path::PathBuf;
8291        let root = PathBuf::from("/tmp/x");
8292        let manifest = root.join("caixa.lisp");
8293        let svc = root.join("servicos/demo.computeunit.yaml");
8294        let mut c = caixa(CaixaKind::Servico);
8295        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8296        c.upgrade_from = vec![UpgradeFromEntry {
8297            from: "0.1.0".into(),
8298            instructions: vec![UpgradeInstruction::SoftPurge {
8299                module: String::new(),
8300            }],
8301        }];
8302        let manifest_clone = manifest.clone();
8303        let svc_clone = svc.clone();
8304        let layout =
8305            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8306        let err = layout.verify(&c, &root).unwrap_err();
8307        let LayoutError::UpgradeViolation { caixa, issue } = err else {
8308            panic!("expected UpgradeViolation, got {err:?}");
8309        };
8310        assert_eq!(caixa, "demo");
8311        assert!(
8312            issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE),
8313            "issue must name the lisp-form of the empty instruction: {issue}"
8314        );
8315    }
8316
8317    #[test]
8318    fn upgrade_invalid_state_change_script_surfaces_as_layout_violation() {
8319        // Pins that the b0c8389 script value-shape gates
8320        // (AbsoluteScript / ParentEscapeScript) — previously
8321        // unreachable from any build-pipeline caller — now fire
8322        // through the same `UpgradeViolation` arm before the path-
8323        // existence pass would otherwise emit the less-helpful
8324        // "missing upgrade-script" (or, worse, *succeed* against
8325        // /etc/passwd, proving the sandbox bypass — same defect
8326        // the b0c8389 BehaviorSpec wiring closed on the peer M2
8327        // slot).
8328        use crate::{UpgradeFromEntry, UpgradeInstruction};
8329        use std::path::PathBuf;
8330        let root = PathBuf::from("/tmp/x");
8331        let manifest = root.join("caixa.lisp");
8332        let svc = root.join("servicos/demo.computeunit.yaml");
8333        let etc_passwd = PathBuf::from("/etc/passwd");
8334        let mut c = caixa(CaixaKind::Servico);
8335        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8336        c.upgrade_from = vec![UpgradeFromEntry {
8337            from: "0.1.0".into(),
8338            instructions: vec![UpgradeInstruction::StateChange {
8339                script: PathBuf::from("/etc/passwd"),
8340            }],
8341        }];
8342        let manifest_clone = manifest.clone();
8343        let svc_clone = svc.clone();
8344        let etc_passwd_clone = etc_passwd.clone();
8345        // Critically: /etc/passwd "exists" in our mock — without the
8346        // value-shape pre-check, the existence loop would *succeed*
8347        // and the path-traversal exit from the project sandbox would
8348        // pass `feira build` silently.
8349        let layout = StandardLayout::new().with_path_exists(move |p| {
8350            p == manifest_clone || p == svc_clone || p == etc_passwd_clone
8351        });
8352        let err = layout.verify(&c, &root).unwrap_err();
8353        let LayoutError::UpgradeViolation { caixa, issue } = err else {
8354            panic!("expected UpgradeViolation, got {err:?}");
8355        };
8356        assert_eq!(caixa, "demo");
8357        assert!(
8358            issue.contains("absolute") || issue.contains("Absolute"),
8359            "issue must name the violation kind (absolute): {issue}"
8360        );
8361    }
8362
8363    #[test]
8364    fn upgrade_well_formed_passes_layout() {
8365        // Positive control — every documented authoring shape
8366        // (`:load-module`, `:state-change` with a relative path,
8367        // `:soft-purge`, `:purge`, sole `:restart`) passes the wired
8368        // gate. The typed sequence (`:load-module` → `:state-change`
8369        // → `:soft-purge` → `:purge`) lives in one entry; the sole
8370        // `:restart` fallback lives in a *separate* entry on a
8371        // different `:from` (the within-entry restart-exclusivity
8372        // gate added in this commit rejects mixing the fallback with
8373        // the typed sequence — per the UpgradeInstruction::Restart
8374        // doc, `:restart` is terminal and any other instructions in
8375        // the same entry are dead code). Drift here = a future
8376        // tighten that rejects any canonical shape surfaces as a
8377        // regression at this layout-level pin, not piecemeal across
8378        // per-renderer call sites.
8379        //
8380        // `:soft-purge` and `:purge` target *distinct* old-version
8381        // modules (`hello-rio-old` and `hello-rio-oldest`) so the
8382        // within-entry cleanup-singularity gate
8383        // (`UpgradeError::DuplicateCleanup`) passes — that gate
8384        // rejects more than one cleanup per module per entry (one
8385        // semantic per old version; mixing drain + discard on one
8386        // module is the soft-then-hard fallback footgun the author
8387        // shouldn't write because the operator handles cleanup
8388        // failure escalation itself). The two distinct names cover
8389        // the legitimate "drain a recent old, hard-discard an
8390        // older-still" shape — both authoring forms remain load-
8391        // bearing in this positive-control enumeration.
8392        use crate::{BehaviorSpec, UpgradeFromEntry, UpgradeInstruction};
8393        use std::path::PathBuf;
8394        let root = PathBuf::from("/tmp/x");
8395        let manifest = root.join("caixa.lisp");
8396        let svc = root.join("servicos/demo.computeunit.yaml");
8397        let migration = root.join("lib/migrations/v01-to-v02.lisp");
8398        let on_state_change = root.join("lib/migrations.lisp");
8399        let mut c = caixa(CaixaKind::Servico);
8400        // `:versao` past both entries' `:from` so the cross-slot
8401        // precedence gate (`FromNotBeforeVersao`) lets this canonical
8402        // authoring shape through to the positive-control assertion.
8403        c.versao = "0.2.0".into();
8404        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8405        // `:on-state-change` declared alongside the `(:state-change …)`
8406        // instruction below — the cross-slot composition gate
8407        // (`validate_upgrade_from_against_behavior`) rejects a
8408        // `:state-change` without the callback, so the canonical
8409        // authoring shape this positive control pins now includes the
8410        // runtime delivery hook (the `gen_server:code_change/3` analog
8411        // that the per-version script is invoked through during hot
8412        // upgrade per the upgrade.rs module doc "Composes with"
8413        // promise).
8414        c.behavior = Some(BehaviorSpec {
8415            on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
8416            ..Default::default()
8417        });
8418        c.upgrade_from = vec![
8419            UpgradeFromEntry {
8420                from: "0.1.0".into(),
8421                instructions: vec![
8422                    UpgradeInstruction::LoadModule {
8423                        module: "hello-rio".into(),
8424                    },
8425                    UpgradeInstruction::StateChange {
8426                        script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
8427                    },
8428                    UpgradeInstruction::SoftPurge {
8429                        module: "hello-rio-old".into(),
8430                    },
8431                    UpgradeInstruction::Purge {
8432                        module: "hello-rio-oldest".into(),
8433                    },
8434                ],
8435            },
8436            UpgradeFromEntry {
8437                from: "0.0.9".into(),
8438                instructions: vec![UpgradeInstruction::Restart],
8439            },
8440        ];
8441        let manifest_clone = manifest.clone();
8442        let svc_clone = svc.clone();
8443        let migration_clone = migration.clone();
8444        let on_state_change_clone = on_state_change.clone();
8445        let layout = StandardLayout::new().with_path_exists(move |p| {
8446            p == manifest_clone
8447                || p == svc_clone
8448                || p == migration_clone
8449                || p == on_state_change_clone
8450        });
8451        layout.verify(&c, &root).unwrap();
8452    }
8453
8454    #[test]
8455    fn upgrade_from_restart_mixed_surfaces_as_upgrade_violation() {
8456        // Wiring pin: the within-entry `(:restart)`-exclusivity gate
8457        // (`UpgradeFromEntry::validate_restart_exclusive`) lands on
8458        // the same `LayoutError::UpgradeViolation` axis the per-entry
8459        // shape gate (26da2c7), the cross-entry duplicate-`:from`
8460        // gate (7c6aef2), and the cross-slot `:from < :versao`
8461        // precedence gate (de7ab1a) already do. A caixa.lisp whose
8462        // `:upgrade-from` entry mixes `(:restart)` with a typed
8463        // instruction surfaces at `feira build` time naming the
8464        // offending caixa + the entry's `:from` rather than silently
8465        // passing into the wasm-operator with semantically dead code
8466        // in the operator's dispatch table. Mirrors
8467        // `upgrade_from_duplicate_surfaces_as_upgrade_violation` on
8468        // the peer cross-entry gate.
8469        use crate::{UpgradeFromEntry, UpgradeInstruction};
8470        let root = PathBuf::from("/tmp/x");
8471        let manifest = root.join("caixa.lisp");
8472        let svc = root.join("servicos/demo.computeunit.yaml");
8473        let mut c = caixa(CaixaKind::Servico);
8474        c.versao = "0.2.0".into();
8475        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8476        c.upgrade_from = vec![UpgradeFromEntry {
8477            from: "0.1.0".into(),
8478            instructions: vec![
8479                UpgradeInstruction::LoadModule {
8480                    module: "hello-rio".into(),
8481                },
8482                UpgradeInstruction::Restart,
8483            ],
8484        }];
8485        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
8486        let err = layout.verify(&c, &root).unwrap_err();
8487        let LayoutError::UpgradeViolation { caixa, issue } = err else {
8488            panic!("expected LayoutError::UpgradeViolation for restart-mixed entry, got {err:?}");
8489        };
8490        assert_eq!(caixa, "demo");
8491        assert!(
8492            issue.contains("0.1.0"),
8493            "UpgradeViolation issue must name the offending entry's `:from` verbatim, got \
8494             {issue:?}"
8495        );
8496        assert!(
8497            issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART),
8498            "UpgradeViolation issue must name the `:restart` axis verbatim, got {issue:?}"
8499        );
8500        assert!(
8501            issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE),
8502            "UpgradeViolation issue must name the non-:restart peer instruction's lisp-form \
8503             verbatim, got {issue:?}"
8504        );
8505    }
8506
8507    #[test]
8508    fn upgrade_from_restart_duplicated_surfaces_as_upgrade_violation() {
8509        // Companion arm: the duplicate-`(:restart)` mode of
8510        // `RestartNotExclusive` (no typed peers, just multiple
8511        // `Restart` variants) surfaces through the same wiring as the
8512        // mixed-with-typed mode above. The diagnostic still names the
8513        // offending entry's `:from` verbatim even when `other_kinds`
8514        // is empty.
8515        use crate::{UpgradeFromEntry, UpgradeInstruction};
8516        let root = PathBuf::from("/tmp/x");
8517        let manifest = root.join("caixa.lisp");
8518        let svc = root.join("servicos/demo.computeunit.yaml");
8519        let mut c = caixa(CaixaKind::Servico);
8520        c.versao = "0.2.0".into();
8521        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8522        c.upgrade_from = vec![UpgradeFromEntry {
8523            from: "0.1.0".into(),
8524            instructions: vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
8525        }];
8526        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
8527        let err = layout.verify(&c, &root).unwrap_err();
8528        let LayoutError::UpgradeViolation { caixa, issue } = err else {
8529            panic!(
8530                "expected LayoutError::UpgradeViolation for duplicate-restart entry, got \
8531                 {err:?}"
8532            );
8533        };
8534        assert_eq!(caixa, "demo");
8535        assert!(
8536            issue.contains("0.1.0"),
8537            "UpgradeViolation issue must name the offending entry's `:from` verbatim, got \
8538             {issue:?}"
8539        );
8540        assert!(
8541            issue.contains("(:restart)")
8542                || issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART),
8543            "UpgradeViolation issue must name the `:restart` axis verbatim, got {issue:?}"
8544        );
8545    }
8546
8547    #[test]
8548    fn upgrade_from_invalid_surfaces_as_layout_violation() {
8549        // The `:from` semver gate (`UpgradeError::FromInvalid`)
8550        // was likewise unreachable before this wiring landed — a
8551        // typo-shaped `:from "v0.1.0"` (git-tag-shape leaking into
8552        // the semver slot) silently passed `feira build` and
8553        // surfaced only when the operator's hot-upgrade decision
8554        // engine tried to match against the version key it couldn't
8555        // parse. Now wired through `UpgradeViolation` with the
8556        // peer-shaped `{ from, reason }` payload — the
8557        // parser-shaped `reason` flows through `Display` so the
8558        // wrapped issue string carries both the offending value
8559        // *and* the SemVer-2 parser's wording (peer with the
8560        // `VersaoInvalid` / `MembroVersaoInvalid` envelopes on the
8561        // sibling SemVer-2 axes).
8562        use crate::{UpgradeFromEntry, UpgradeInstruction};
8563        use std::path::PathBuf;
8564        let root = PathBuf::from("/tmp/x");
8565        let manifest = root.join("caixa.lisp");
8566        let svc = root.join("servicos/demo.computeunit.yaml");
8567        let mut c = caixa(CaixaKind::Servico);
8568        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
8569        c.upgrade_from = vec![UpgradeFromEntry {
8570            from: "v0.1.0".into(), // git-tag-shape, not semver
8571            instructions: vec![UpgradeInstruction::Restart],
8572        }];
8573        let manifest_clone = manifest.clone();
8574        let svc_clone = svc.clone();
8575        let layout =
8576            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
8577        let err = layout.verify(&c, &root).unwrap_err();
8578        let LayoutError::UpgradeViolation { caixa, issue } = err else {
8579            panic!("expected UpgradeViolation, got {err:?}");
8580        };
8581        assert_eq!(caixa, "demo");
8582        assert!(
8583            issue.contains("v0.1.0"),
8584            "UpgradeViolation issue must name the offending :from value verbatim, got {issue:?}"
8585        );
8586        assert!(
8587            issue.contains(":from"),
8588            "UpgradeViolation issue must name the :from slot verbatim, got {issue:?}"
8589        );
8590        // Pin the parser-shaped reason flow-through: the renamed
8591        // `FromInvalid { from, reason }` carries the SemVer-2 parser's
8592        // wording verbatim, and the [`UpgradeError`] Display routes it
8593        // into the wrapped `issue` string so the layout envelope
8594        // surfaces both the offending value *and* the parser's
8595        // diagnosis. Mirrors the peer flow-through on
8596        // `ManifestError::VersaoInvalid` (top-level `:versao`) and
8597        // `AplicacaoError::MembroVersaoInvalid` (`:membros :versao`).
8598        assert!(
8599            issue.contains("SemVer-2"),
8600            "UpgradeViolation issue must carry the parser-shaped reason (\"SemVer-2\"), got {issue:?}"
8601        );
8602    }
8603
8604    #[test]
8605    fn missing_lib_gate_routes_through_kind_requires_lib_and_caixa_nome() {
8606        // Fail-before-pass-after pin on the two-part converge landed
8607        // at layout.rs:844-847:
8608        //   (a) `caixa.kind().is_biblioteca()` →
8609        //       `caixa.kind().requires_lib()` — routes the biblioteca
8610        //       required-slot gate onto the same `requires_*()`
8611        //       predicate family the three sibling required-slot
8612        //       gates (`requires_exe()` at :856, `requires_servicos()`
8613        //       at :860, `requires_ci()` at :874) already key off.
8614        //       All four gates in the block now share one convention;
8615        //       a future kind that gains its own required-slot gate
8616        //       (an M4/M5 typed arm the CAIXA-SDLC §I six-kind roster
8617        //       may grow) reaches for the same predicate family and
8618        //       inherits the accessor discipline for free.
8619        //   (b) raw `caixa.nome` → `caixa.nome()` — routes the
8620        //       `expected` path composition through the typed
8621        //       [`crate::Caixa::nome`] accessor, closing the last
8622        //       unlifted raw `caixa.nome` production field-access
8623        //       site in `caixa-core/src/layout.rs` (every peer
8624        //       diagnostic in the file already routes through
8625        //       `caixa.nome().to_string()`).
8626        //
8627        // The behavioral pin: for a Biblioteca kind with no fallback
8628        // `lib/<nome>.lisp` file, MissingLib fires and its `expected`
8629        // path composes through `Caixa::nome()`; for every other
8630        // kind, MissingLib does NOT fire (the gate short-circuits on
8631        // kinds where `requires_lib()` returns false), even when the
8632        // fallback file is likewise absent. A future regression that
8633        // reroutes the gate off `requires_lib()` (e.g. onto
8634        // `is_biblioteca()` again, or onto a hand-authored
8635        // `matches!(caixa.kind(), CaixaKind::Biblioteca)`) that
8636        // *happens* to agree byte-for-byte on today's arm-set trips
8637        // this test the moment a future kind's `requires_lib()`
8638        // returns true for a non-`Biblioteca` arm (or the sibling
8639        // required-slot gates diverge from the same convention).
8640        let root = PathBuf::from("/tmp/x");
8641        let manifest = root.join("caixa.lisp");
8642        let manifest_only = manifest.clone();
8643        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_only);
8644
8645        // Biblioteca kind + no lib fallback → MissingLib fires with
8646        // the expected path composed through `Caixa::nome()`.
8647        let bib = caixa(CaixaKind::Biblioteca);
8648        assert!(
8649            bib.kind().requires_lib(),
8650            "requires_lib() must return true for Biblioteca — the four-required-\
8651             slot-gate family's routing depends on this arm's assignment"
8652        );
8653        let err = layout.verify(&bib, &root).unwrap_err();
8654        let LayoutError::MissingLib {
8655            caixa: cname,
8656            expected,
8657        } = err
8658        else {
8659            panic!("expected MissingLib for Biblioteca kind with no lib fallback, got {err:?}");
8660        };
8661        assert_eq!(
8662            cname,
8663            bib.nome(),
8664            "MissingLib `caixa:` carrier must byte-equal Caixa::nome()"
8665        );
8666        assert_eq!(
8667            expected,
8668            root.join(crate::render::LAYOUT_DIR_LIB)
8669                .join(format!("{}.lisp", bib.nome())),
8670            "MissingLib `expected:` path must compose through Caixa::nome() \
8671             verbatim — a raw-field-access regression would silently drift \
8672             the composed path on any future `:nome` axis extension \
8673             (namespace-qualified rewrite, per-cluster alias overlay)"
8674        );
8675
8676        // Non-Biblioteca kinds → the MissingLib gate short-circuits.
8677        // Different kinds fail on their own required-slot gate
8678        // (BinarioWithoutExe, ServicoWithoutServicos, MissingCi) or
8679        // on downstream M2/M3 invariants; none of them may surface as
8680        // MissingLib, because `requires_lib()` returns false for each.
8681        for kind in [
8682            CaixaKind::Binario,
8683            CaixaKind::Servico,
8684            CaixaKind::Supervisor,
8685            CaixaKind::Aplicacao,
8686            CaixaKind::Acao,
8687        ] {
8688            assert!(
8689                !kind.requires_lib(),
8690                "requires_lib() must return false for {kind:?} — the \
8691                 four-required-slot-gate family's arm assignment pins \
8692                 exactly one kind (Biblioteca) as the arm that requires \
8693                 a `lib/` entry"
8694            );
8695            let c = caixa(kind);
8696            let result = layout.verify(&c, &root);
8697            assert!(
8698                !matches!(result, Err(LayoutError::MissingLib { .. })),
8699                "MissingLib gate at layout.rs:844 must short-circuit for \
8700                 kinds where requires_lib() returns false; unexpectedly \
8701                 fired for {kind:?}: {result:?}"
8702            );
8703        }
8704    }
8705
8706    #[test]
8707    fn missing_lib_ctor_matches_struct_literal_wrap() {
8708        // Equivalence pin locking [`LayoutError::missing_lib`] to its
8709        // struct-literal peer under PartialEq. The pre-lift wire-up at
8710        // layout.rs:1010 read `LayoutError::MissingLib { caixa:
8711        // caixa.nome().to_string(), expected }`; the post-lift
8712        // dispatch reads `LayoutError::missing_lib(caixa, expected)`.
8713        // Both must produce byte-equal variants — a silent divergence
8714        // (a `to_lowercase()`, a `trim()`, a lost `.to_string()` copy,
8715        // an accidental `.clone()` of the wrong side of the `expected`
8716        // path) surfaces here rather than at a downstream diagnostic-
8717        // shape drift.
8718        let bib = caixa(CaixaKind::Biblioteca);
8719        let expected = PathBuf::from("/tmp/x")
8720            .join(crate::render::LAYOUT_DIR_LIB)
8721            .join(format!("{}.lisp", bib.nome()));
8722        let struct_lit = LayoutError::MissingLib {
8723            caixa: bib.nome().to_string(),
8724            expected: expected.clone(),
8725        };
8726        let ctor = LayoutError::missing_lib(&bib, expected);
8727        assert_eq!(
8728            struct_lit, ctor,
8729            "missing_lib ctor must byte-equal the pre-lift struct-literal"
8730        );
8731    }
8732
8733    #[test]
8734    fn missing_lib_ctor_projects_nome_through_accessor() {
8735        // Accessor-fidelity pin: any future `:nome` axis extension
8736        // (namespace-qualified rewrite `pleme-io/<nome>`, per-cluster
8737        // alias overlay, case-normalization pass) that lands on
8738        // [`crate::Caixa::nome`] must reach the `caixa:` carrier
8739        // through this projection rather than a raw field access.
8740        // The neighbour required-slot ctor family
8741        // ([`layout_nome_only_ctors!`]) projects the same way; this
8742        // pin locks `missing_lib` onto the same discipline so the
8743        // whole `LayoutError` family stays coherent under any future
8744        // `:nome` rewrite.
8745        //
8746        // Deliberately uses a byte-distinctive nome ("named-lib") so
8747        // a regression that hard-codes a fixture literal at the ctor
8748        // body (rather than projecting through the accessor) drops
8749        // the bytes and trips the assertion.
8750        let mut bib = caixa(CaixaKind::Biblioteca);
8751        bib.nome = "named-lib".into();
8752        let expected = PathBuf::from("/srv")
8753            .join(crate::render::LAYOUT_DIR_LIB)
8754            .join(format!("{}.lisp", bib.nome()));
8755        let err = LayoutError::missing_lib(&bib, expected.clone());
8756        let LayoutError::MissingLib {
8757            caixa: cname,
8758            expected: got,
8759        } = err
8760        else {
8761            panic!("missing_lib ctor must construct the MissingLib variant, got a foreign arm");
8762        };
8763        assert_eq!(
8764            cname,
8765            bib.nome(),
8766            "missing_lib `caixa:` carrier must project through Caixa::nome()"
8767        );
8768        assert_eq!(
8769            got, expected,
8770            "missing_lib `expected:` path must pass through verbatim"
8771        );
8772    }
8773
8774    #[test]
8775    fn missing_lib_verify_wire_up_routes_through_ctor() {
8776        // Behavioural pin: [`StandardLayout::verify`] must reach the
8777        // `MissingLib` variant through the newly lifted ctor rather
8778        // than a residual struct-literal block. The end-to-end
8779        // observable — a Biblioteca with no lib fallback — must
8780        // surface a `MissingLib` whose `caixa:` and `expected:`
8781        // carriers are byte-equal to what the ctor would produce
8782        // when called directly.
8783        let root = PathBuf::from("/opt/pkg");
8784        let manifest = root.join("caixa.lisp");
8785        let manifest_only = manifest.clone();
8786        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_only);
8787        let bib = caixa(CaixaKind::Biblioteca);
8788        let expected = root
8789            .join(crate::render::LAYOUT_DIR_LIB)
8790            .join(format!("{}.lisp", bib.nome()));
8791
8792        let observed = layout.verify(&bib, &root).unwrap_err();
8793        let synthesized = LayoutError::missing_lib(&bib, expected);
8794        assert_eq!(
8795            observed, synthesized,
8796            "StandardLayout::verify must reach MissingLib through the missing_lib ctor \
8797             — a residual struct-literal block would silently diverge on any future \
8798             accessor projection change"
8799        );
8800    }
8801}