Skip to main content

caixa_core/
upgrade.rs

1//! Erlang/OTP-style appup — declarative upgrade instructions per
2//! prior caixa version. Composes with the `:behavior :on-state-change`
3//! callback to deliver state migration during hot upgrades.
4//!
5//! See `theory/INSPIRATIONS.md` §II.4 for the prior-art frame.
6//!
7//! ```lisp
8//! (defcaixa
9//!   :nome   "hello-rio"
10//!   :versao "0.2.0"
11//!   :upgrade-from
12//!     ((:from "0.1.0"
13//!       :instructions ((:load-module "hello-rio")
14//!                      (:state-change "lib/migrations/v01-to-v02.lisp")
15//!                      (:soft-purge "hello-rio-old")))
16//!      (:from "0.1.5"
17//!       :instructions ((:load-module "hello-rio")
18//!                      (:soft-purge "hello-rio-old")))))
19//! ```
20//!
21//! Each `(:from <prior>)` block declares the upgrade path *from* that
22//! version *to* the current `:versao`. wasm-operator picks the
23//! matching block at upgrade time, runs the instructions in order,
24//! and only swaps traffic to the new instance after all instructions
25//! succeed (transactional upgrade). On any failure, the current
26//! version stays load-bearing — a typed atomic upgrade.
27
28use std::path::PathBuf;
29
30use serde::{Deserialize, Serialize};
31use thiserror::Error;
32
33/// One upgrade instruction. The set mirrors OTP's appup low-level
34/// instructions: enough to express every common upgrade pattern,
35/// few enough that the wasm-operator can implement each
36/// deterministically.
37#[derive(
38    Serialize,
39    Deserialize,
40    Debug,
41    Clone,
42    PartialEq,
43    Eq,
44    gen_platform::TypedDispatcher,
45    gen_platform::Discriminant,
46    gen_platform::IsVariant,
47)]
48#[serde(tag = "kind", rename_all = "kebab-case")]
49pub enum UpgradeInstruction {
50    /// Load a new wasm module alongside the current one — the analog
51    /// of OTP's `code:load_module/1`. Both versions remain in memory
52    /// after this instruction; in-flight requests stay on the old
53    /// version, new requests route to the new version.
54    LoadModule { module: String },
55
56    /// Run a state-migration tatara-lisp file. Receives the old state
57    /// + the prior version string; returns the new state. Analog of
58    /// `gen_server:code_change/3`.
59    StateChange { script: PathBuf },
60
61    /// Wait for in-flight requests on a named module to drain, then
62    /// GC it — the analog of `code:soft_purge/1`. Default cooldown is
63    /// 60s; longer-running requests block the upgrade.
64    SoftPurge { module: String },
65
66    /// Discard a named module immediately, without waiting for
67    /// drain — the analog of `code:purge/1`. Used when we don't
68    /// care about in-flight callers (cron, oneShot).
69    Purge { module: String },
70
71    /// Fall back to a full restart for this entry. Used when a typed
72    /// upgrade is impossible (e.g. wasm component world incompatible).
73    Restart,
74}
75
76// Fleet-wide dispatcher-catalog registration. UpgradeInstruction is
77// the OTP-style hot-upgrade primitive (load_module/code_change/
78// soft_purge/purge/restart) — the first NON-ADAPTER consumer of
79// gen-platform's typed-dispatcher catamorphism, satisfying the ★★
80// "two classes of consumer" promotion criterion from
81// theory/QUIRK-APPLIER.md §V.1.
82//
83// Operators query via:
84//   gen dispatchers --from-catalog | jq '.[] | select(.label=="caixa.upgrade-instruction")'
85//
86// The substrate's lib/build/shared/fleet-catalog-coverage-test.nix
87// adds an assertion row for this label on the next snapshot refresh.
88gen_platform::register_dispatcher!("caixa.upgrade-instruction", UpgradeInstruction);
89
90/// One upgrade entry: the *prior* version we're upgrading from, plus
91/// the instruction sequence to execute.
92#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
93#[serde(rename_all = "camelCase")]
94pub struct UpgradeFromEntry {
95    /// Semver of the *prior* version. Authored as a literal string;
96    /// validated lazily by [`UpgradeFromEntry::validate`].
97    pub from: String,
98
99    /// Ordered list of instructions to execute. Empty list = "no-op
100    /// upgrade" (rare; usually means only documentation changed).
101    #[serde(default)]
102    pub instructions: Vec<UpgradeInstruction>,
103}
104
105impl UpgradeFromEntry {
106    /// Prior-versao semver-2 literal this entry declares an upgrade
107    /// path *from* — the string the OTP-shape `release_handler:install_release/1`
108    /// analog matches the running caixa's `:versao` against at hot-
109    /// upgrade dispatch time to pick this entry's `:instructions`
110    /// sequence. Returned byte-for-byte from the typed slot's own
111    /// `String` storage; no cloning, no re-parsing.
112    ///
113    /// The M2 companion of the closed M3 mesh-slot scalar-accessor
114    /// family — sibling in shape to [`crate::Membro::versao_requirement`]
115    /// (a40b0e3), [`crate::Membro::nome`] (4a32abf), and the
116    /// [`crate::WitContract::{source, destination, world_ref}`]
117    /// (7f0fd43 / 0804823) / [`crate::Entrada::{hostname, destination}`]
118    /// (11f3dfe / 6db982c) `&str` accessors already routing every
119    /// per-mesh-slot-atom scalar-value axis through one typed dispatch
120    /// on the substrate primitive — extended here onto the first per-
121    /// M2-slot scalar-value axis. Every downstream consumer of the
122    /// M2 `:upgrade-from :from` axis (the [`UpgradeFromEntry::validate`]
123    /// SemVer-2 parse gate, the [`validate_upgrade_from`] cross-entry
124    /// duplicate-detection re-parse assertion, the
125    /// [`validate_upgrade_from_against_versao`] precedence gate,
126    /// the [`validate_upgrade_from_against_behavior`] state-change-
127    /// callback coherence gate, every per-arm error variant carrying
128    /// the offending `:from` verbatim for `feira lint` rendering)
129    /// now reads through this one accessor rather than open-coding
130    /// `&self.from` / `&entry.from` / `self.from.clone()` /
131    /// `entry.from.clone()`.
132    ///
133    /// A future extension of the axis (an M4 typed `:from`-range slot
134    /// composing multiple prior versions into one entry, an operator-
135    /// side pre-parsed [`semver::Version`] cache the accessor could
136    /// materialize behind the same `&str` return contract, a per-
137    /// cluster `:placement`-scoped prior-versao overlay the
138    /// `caixa-operator` reconciles ahead of dispatch) migrates as a
139    /// single caixa-core edit rather than a coordinated rewrite of
140    /// the four validate-side call sites + every downstream error-
141    /// variant carrying `:from`.
142    #[must_use]
143    pub const fn prior_versao(&self) -> &str {
144        self.from.as_str()
145    }
146
147    /// Substrate-canonical per-`:upgrade-from :instructions`
148    /// OTP-appup migration-instruction-list slice-return accessor
149    /// every per-entry instructions-list reader keys off — returns
150    /// the author-declared `:instructions` list verbatim as a
151    /// `&[UpgradeInstruction]` slice-view over the same backing
152    /// buffer the raw `self.instructions.as_slice()` field access
153    /// borrows from. Non-optional: an empty slice is the load-bearing
154    /// "author declared `:instructions ()`" sentinel — the
155    /// `Vec<UpgradeInstruction>::default()`-produced empty tail the
156    /// [`UpgradeFromEntry::instructions`] field's own docstring already
157    /// names as the "no-op upgrade" shape (a metadata-only upgrade
158    /// entry — the operator's `:from`-match dispatch matches the entry
159    /// but runs no instructions, advancing straight to the "traffic
160    /// swap" step) and every peer within-entry cross-instruction gate
161    /// no-ops against without allocating a new `Vec` per gate.
162    ///
163    /// The `:upgrade-from :instructions` slot carries the per-`:from`
164    /// OTP-appup ordered instruction list the wasm-operator's hot-
165    /// upgrade dispatch materializes one per-instruction runtime
166    /// primitive from — the Erlang/OTP appup's per-`{from, to,
167    /// UpgradeInstructions, DowngradeInstructions}` entry's
168    /// `UpgradeInstructions` list (`code:load_module/1` /
169    /// `gen_server:code_change/3` / `code:soft_purge/1` /
170    /// `code:purge/1` / `restart_new_emulator` — see INSPIRATIONS
171    /// §II.4), projected through the tatara-lisp
172    /// `:upgrade-from ((:from … :instructions …))` author surface
173    /// onto a typed `Vec<UpgradeInstruction>` whose per-element
174    /// variant is [`UpgradeInstruction::LoadModule`] /
175    /// [`UpgradeInstruction::StateChange`] /
176    /// [`UpgradeInstruction::SoftPurge`] / [`UpgradeInstruction::Purge`]
177    /// / [`UpgradeInstruction::Restart`]. Every downstream consumer
178    /// that fans on the per-entry instruction list keys off this
179    /// slice (the [`UpgradeFromEntry::validate`] per-instruction
180    /// shape-check fan-out, the seven paired within-entry cross-
181    /// instruction gates [`Self::validate_restart_exclusive`] /
182    /// [`Self::validate_state_change_ordering`] /
183    /// [`Self::validate_purge_ordering`] /
184    /// [`Self::validate_state_change_before_cleanup`] /
185    /// [`Self::validate_load_singularity`] /
186    /// [`Self::validate_state_change_singularity`] /
187    /// [`Self::validate_cleanup_singularity`], the layout-side
188    /// [`crate::layout::StandardLayout`]'s per-`:state-change`
189    /// script-existence fan-out
190    /// ([`crate::layout::LayoutError::MissingEntry`]'s
191    /// `LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT` arm), the cross-slot
192    /// [`validate_upgrade_from_against_behavior`] gate's per-entry
193    /// `:state-change`-instruction detection loop, every future
194    /// wasm-operator (M2.5) per-`:from`-match hot-upgrade dispatch's
195    /// per-instruction runtime-primitive fan-out, every future M4
196    /// `mesh.pleme.io/v1alpha1/Caixa` CR materializer's per-entry
197    /// upgrade-plan admission-webhook fan-out).
198    ///
199    /// Prior to this lift the `.instructions` `Vec<UpgradeInstruction>`
200    /// was accessed inline at nine production sites across
201    /// `caixa-core/src/upgrade.rs` and `caixa-core/src/layout.rs` —
202    /// the [`UpgradeFromEntry::validate`] per-instruction shape-check
203    /// fan-out (`for instr in &self.instructions`), the paired
204    /// [`Self::validate_restart_exclusive`] restart-count / other-kind
205    /// projections + `.len()` probe (three raw-access sites in one
206    /// gate), the [`Self::validate_state_change_ordering`] /
207    /// [`Self::validate_purge_ordering`] /
208    /// [`Self::validate_state_change_before_cleanup`] /
209    /// [`Self::validate_load_singularity`] /
210    /// [`Self::validate_state_change_singularity`] /
211    /// [`Self::validate_cleanup_singularity`] within-entry cross-
212    /// instruction gate traversal heads, the peer
213    /// [`validate_upgrade_from_against_behavior`] cross-slot
214    /// composition gate's `for instr in &entry.instructions`
215    /// per-entry `:state-change` detection loop, and the
216    /// [`crate::layout::StandardLayout`]-side
217    /// `for instr in &entry.instructions` per-`:state-change`
218    /// script-existence fan-out — nine open-coded field-accesses
219    /// that expressed no compile-time link back to the typed slot.
220    /// A future extension of the `:instructions` axis to a richer
221    /// author surface (a per-cluster overlay the operator pins
222    /// through a future `:upgrade-from :instructions-overrides` slot
223    /// so a canary cluster runs a `(:state-change …)` before the
224    /// production fleet does, a per-tenant instruction-list overlay
225    /// the M4 CR materializer resolves per-CR to inject cluster-
226    /// specific `(:soft-purge …)` cooldown adjustments, a promotion
227    /// of the plain `Vec<UpgradeInstruction>` to a richer
228    /// `{static, dynamic}` partition once virtual-actor-style
229    /// dynamic-instruction composition (an operator-derived
230    /// `(:load-module …)` sequence computed from the running
231    /// module set at upgrade time) comes into typed scope, a
232    /// per-instruction pre-condition scalar the future adaptive-
233    /// upgrade engine reads to bias per-instruction retry
234    /// strategy) would have had to be threaded through all nine
235    /// open-coded copies in lockstep or one consumer would silently
236    /// disagree with the peers on which instruction sequence a
237    /// given `:upgrade-from` entry resolves to — the per-
238    /// instruction shape-check reading the raw slot while the
239    /// paired within-entry ordering gates read an operator-resolved
240    /// slot would silently split the build-time per-entry gate
241    /// cohort from the layout-side script-existence gate + the
242    /// cross-slot behavior-composition gate + the runtime hot-
243    /// upgrade dispatch, a nine-consumer split across the seven
244    /// within-entry cross-instruction gates + the layout invariant +
245    /// the cross-slot composition gate far from the source
246    /// `caixa.lisp` with no field naming the instruction-sequence-
247    /// drift root cause. Lifting the resolution rule to a typed
248    /// method on the substrate primitive means every downstream
249    /// consumer of the per-entry OTP-appup instruction-list surface
250    /// reaches for exactly one typed dispatch — the resolver's
251    /// accept-set migrates as a unit on any future axis addition.
252    ///
253    /// Fifth slice-return (`&[T]`) accessor on any M2 or M3 typed
254    /// slot — sibling to the seed M2
255    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
256    /// accessor on the peer per-`:supervisor` static-child-list
257    /// `Vec`-carry axis, the M3 [`crate::Placement::clusters`]
258    /// (a6e18d7) `&[String]` accessor on the peer per-`:placement`
259    /// distribution-target-list `Vec`-carry axis, the M3
260    /// [`crate::AplicacaoSpec::membros`] (6c77e36) `&[Membro]`
261    /// accessor on the peer per-`:membros` node-list `Vec`-carry
262    /// axis, and the M3 [`crate::AplicacaoSpec::contratos`]
263    /// (0dcc926) `&[WitContract]` accessor on the peer per-
264    /// `:contratos` edge-list `Vec`-carry axis. This lift closes the
265    /// last unlifted `Vec`-carry axis on any M2 or M3 typed slot in
266    /// the substrate — the four peer axes named in the
267    /// [`crate::SupervisorSpec::children`] seed docstring
268    /// (`Placement::clusters`, `AplicacaoSpec::membros`,
269    /// `AplicacaoSpec::contratos`, `UpgradeFromEntry::instructions`)
270    /// are now all closed. The per-`UpgradeFromEntry` type carried
271    /// two axes: the scalar `Copy`-return
272    /// [`UpgradeFromEntry::prior_versao`] (75d27a8) on the
273    /// `:from` axis, and now the slice-return
274    /// [`UpgradeFromEntry::instructions`] on the peer
275    /// `:instructions` axis. Named `instructions()` to match the
276    /// storage field's name verbatim and the tatara-lisp
277    /// author-surface term (`:instructions`) the field's own
278    /// docstring already carries; the accessor's identity maps
279    /// onto the canonical OTP-appup vocabulary the
280    /// [`crate::upgrade`] module doc already reaches for ("runs
281    /// the instructions in order"). Returns `&[UpgradeInstruction]`
282    /// (not `&Vec<UpgradeInstruction>`) because every downstream
283    /// consumer of the instruction list treats it as a read-only
284    /// sequence — the slice-view is the narrowest borrow that
285    /// supports every present + roadmapped consumer (`.iter()`,
286    /// `.len()`, `.filter(...).count()`) without leaking the
287    /// backing `Vec`'s grow/push/reserve surface that no consumer
288    /// of the typed view reaches for (the storage-side `Vec`
289    /// remains reachable through the `pub instructions` field for
290    /// the mutation-carrying `Serialize`/`Deserialize` derive
291    /// round-trip and per-test fixture-mutation paths).
292    #[must_use]
293    pub const fn instructions(&self) -> &[UpgradeInstruction] {
294        self.instructions.as_slice()
295    }
296
297    /// Verify the `:from` field is a valid semver, every instruction's
298    /// typed shape, the within-entry `(:restart)`-exclusivity invariant
299    /// (an entry containing `(:restart)` must contain exactly one
300    /// `(:restart)` and nothing else — see
301    /// [`Self::validate_restart_exclusive`]), the within-entry
302    /// state-change-ordering invariant (every `(:state-change …)` must
303    /// be preceded by a `(:load-module …)` — see
304    /// [`Self::validate_state_change_ordering`]), the within-entry
305    /// purge-ordering invariant (every `(:soft-purge …)` / `(:purge …)`
306    /// must be preceded by a `(:load-module …)` — see
307    /// [`Self::validate_purge_ordering`]), the within-entry
308    /// state-change-before-cleanup ordering invariant (no
309    /// `(:state-change …)` may appear after any `(:soft-purge …)` /
310    /// `(:purge …)` — see
311    /// [`Self::validate_state_change_before_cleanup`]), the within-
312    /// entry load-singularity invariant (no module appears as the
313    /// target of `(:load-module …)` more than once — see
314    /// [`Self::validate_load_singularity`]), the within-entry
315    /// state-change-singularity invariant (no script appears as the
316    /// target of `(:state-change …)` more than once — see
317    /// [`Self::validate_state_change_singularity`]), and the within-
318    /// entry cleanup-singularity invariant (no module appears as the
319    /// target of `(:soft-purge …)` or `(:purge …)` more than once
320    /// total — see [`Self::validate_cleanup_singularity`]).
321    pub fn validate(&self) -> Result<(), UpgradeError> {
322        use semver::Version;
323        Version::parse(self.prior_versao())
324            .map_err(|e| UpgradeError::from_invalid(self.prior_versao(), &e.to_string()))?;
325        // Per-instruction typed shape: kind-tagged `:module` /
326        // `:script` value-shape gates fire here, *before* the
327        // within-entry restart-exclusivity gate below — so a
328        // malformed-shape diagnostic on a Module/Script-bearing
329        // instruction surfaces with its narrower self-locating
330        // wording (`ModuleEmpty`, `ModuleInvalid`, `EmptyScript`,
331        // `AbsoluteScript`, `ParentEscapeScript`) rather than
332        // collapsing two unrelated authoring errors into a single
333        // exclusivity diagnostic. Same empty-first cascade discipline
334        // every peer DNS-1123 / path-shape gate inside this module
335        // uses (`validate_module`'s ModuleEmpty arm precedes the
336        // DNS-1123 predicate; `validate` on `StateChange` consults
337        // the lifted `is_sandboxed_relative_path` shape gate first).
338        // Route the per-instruction shape-check fan-out through the
339        // lifted [`Self::instructions`] slice-return accessor rather
340        // than the raw `self.instructions` field access — first of
341        // nine paired production consumers of the per-`:upgrade-from
342        // :instructions` OTP-appup migration-instruction-list surface
343        // that now key off exactly one typed dispatch on the substrate
344        // primitive.
345        for instr in self.instructions() {
346            instr.validate()?;
347        }
348        self.validate_restart_exclusive()?;
349        self.validate_state_change_ordering()?;
350        self.validate_purge_ordering()?;
351        self.validate_state_change_before_cleanup()?;
352        self.validate_load_singularity()?;
353        self.validate_state_change_singularity()?;
354        self.validate_cleanup_singularity()?;
355        Ok(())
356    }
357
358    /// Reject `:upgrade-from :instructions` lists that carry
359    /// `(:restart)` alongside any other instruction, or that carry
360    /// more than one `(:restart)`. The valid Restart-bearing shape is
361    /// exactly `((:restart))` — a single `Restart` as the entry's
362    /// whole instructions list.
363    ///
364    /// Per [`UpgradeInstruction::Restart`]'s doc comment, `(:restart)`
365    /// is the *fallback* for an entry whose typed upgrade is
366    /// impossible (wasm component-model world incompatibility,
367    /// irreversible state shape change). The fallback is terminal by
368    /// construction: the operator restarts the pod and the new version
369    /// comes up fresh, so any other instructions in the same entry
370    /// are dead code in both directions — either the typed sequence
371    /// would have succeeded and `(:restart)` is unreached, or it
372    /// wouldn't and the typed instructions are dead because the
373    /// operator restarts anyway. Two canonical authoring footguns
374    /// close here:
375    ///
376    ///   - `((:load-module …) (:state-change …) (:restart))` — the
377    ///     "I'll try the typed path *then* restart anyway" footgun.
378    ///     There is no coherent OTP-shaped semantic for this: if the
379    ///     typed sequence succeeds, the trailing restart discards the
380    ///     work that just succeeded (defeating the whole point of
381    ///     declaring it); if it fails, the restart is never reached
382    ///     because the entry already failed.
383    ///   - `((:restart) (:restart))` — multiple `Restart` variants in
384    ///     one entry. The fallback is a single semantic; repeating it
385    ///     is at best redundant, at worst suggests the author thought
386    ///     the second one would re-trigger after the first.
387    ///
388    /// Same within-entry exclusivity discipline OTP's `relup` enforces
389    /// at the `restart_new_emulator | restart_emulator` instruction
390    /// boundary — those instructions are terminal in the upgrade
391    /// script (`systools(3)` rejects sequences that continue past
392    /// them); pleme-io lifts the same shape to a build-time gate,
393    /// matching the CAIXA-SDLC §III "build errors, not runtime
394    /// surprises" frame.
395    ///
396    /// Same within-entry cross-instruction discipline the
397    /// [`crate::AplicacaoSpec::validate_placement`] strategy ↔
398    /// shard-key partition (934bc58) and
399    /// [`validate_upgrade_from_against_versao`]'s `:from` ↔ `:versao`
400    /// precedence partition (de7ab1a) apply on cross-slot axes — now
401    /// extended onto the first within-list cross-instruction axis on
402    /// the `:upgrade-from` typed slot.
403    fn validate_restart_exclusive(&self) -> Result<(), UpgradeError> {
404        // Route the paired restart-count / instructions-len / other-
405        // kind projections through the lifted [`Self::instructions`]
406        // slice-return accessor rather than the raw `self.instructions`
407        // field access — three raw-access sites in one gate collapse
408        // onto exactly one typed dispatch on the substrate primitive.
409        //
410        // The paired positive / negated `Self::Restart` arm-discriminator
411        // predicates route through the `gen_platform::IsVariant`
412        // derive-generated [`UpgradeInstruction::is_restart`] rather than
413        // the raw `matches!(i, UpgradeInstruction::Restart)` /
414        // `!matches!(i, UpgradeInstruction::Restart)` open-coded pattern-
415        // matches — same closed-set-typed-enum arm-discriminator dispatch
416        // discipline the sibling [`crate::CaixaKind`] `IsVariant` derive
417        // (f5bba80) extended onto its ten `caixa.kind() == CaixaKind::X`
418        // / `!= CaixaKind::X` production sites in the substrate's own
419        // layout invariant verifier + typed-view projection gates,
420        // extended here onto the last unlifted `matches!`-based
421        // arm-discriminator axis on the [`UpgradeInstruction`] closed-set
422        // typed enum. A future sixth `UpgradeInstruction` arm (an
423        // adaptive-upgrade-shaped `AwaitReadiness` gate the M2.5
424        // wasm-operator's hot-upgrade runtime could adopt to bracket the
425        // typed instruction sequence against a per-cluster readiness
426        // probe, a `Downgrade` variant OTP's `relup` acknowledges on the
427        // reverse axis, a `CanaryTraffic` split-traffic variant the M4 CR
428        // materializer could resolve per-CR) migrates as a single
429        // enum-declaration edit — the derive auto-generates the paired
430        // `.is_<new_arm>()` predicate; every consumer inherits the new
431        // arm on the next re-derive, rather than the two `matches!` sites
432        // here having to be threaded through in lockstep.
433        let instructions = self.instructions();
434        let restart_count = instructions.iter().filter(|i| i.is_restart()).count();
435        if restart_count == 0 {
436            return Ok(());
437        }
438        if restart_count == 1 && instructions.len() == 1 {
439            return Ok(());
440        }
441        let other_kinds: Vec<&'static str> = instructions
442            .iter()
443            .filter(|i| !i.is_restart())
444            .map(UpgradeInstruction::lisp_form)
445            .collect();
446        Err(UpgradeError::restart_not_exclusive(
447            self.prior_versao(),
448            restart_count,
449            other_kinds,
450        ))
451    }
452
453    /// Reject an entry whose `(:state-change …)` is not preceded by a
454    /// `(:load-module …)` in the same `:instructions` list.
455    ///
456    /// `StateChange` is the `gen_server:code_change/3` analog
457    /// ([`UpgradeInstruction::StateChange`] doc; INSPIRATIONS §II.4):
458    /// it runs the migration script that folds the *old* state into the
459    /// shape the *new* code expects. In OTP, `code_change/3` is invoked
460    /// in the context of the newly-loaded code — `release_handler`
461    /// always loads the new module before running the advanced update
462    /// that triggers the callback. caixa decomposes that into two
463    /// explicit instructions (`LoadModule` brings the new version up
464    /// "alongside the current one"; `StateChange` migrates the state),
465    /// and the module doc pins that the operator "runs the instructions
466    /// in order" and only swaps traffic after all succeed. So a
467    /// `:state-change` with no preceding `:load-module` migrates state
468    /// into code that was never loaded — the migration script runs while
469    /// the only resident version is still the *old* one, which expects
470    /// the *old* state. Two authoring footguns close here:
471    ///
472    ///   - `((:state-change "…"))` — the "I wrote the migration but
473    ///     forgot to load the new module" footgun. The new code that
474    ///     defines the new state representation (and that the migration
475    ///     output is destined for) never comes up; the operator runs
476    ///     the script against the old code and either no-ops or corrupts
477    ///     live state.
478    ///   - `((:state-change "…") (:load-module "…"))` — the
479    ///     right-instructions-wrong-order footgun. Because the operator
480    ///     executes in declared order, the migration runs *before* the
481    ///     new code is resident, then the load brings up code expecting
482    ///     already-migrated state that the just-run script produced
483    ///     against the old version's shape. The canonical order is
484    ///     `(:load-module …) (:state-change …) (:soft-purge …)`
485    ///     (module doc example).
486    ///
487    /// Same within-entry cross-instruction discipline as
488    /// [`Self::validate_restart_exclusive`] (the `(:restart)` terminal-
489    /// exclusivity gate it runs beside): both reject an
490    /// `:instructions` list whose instructions are individually
491    /// well-shaped but jointly incoherent, at the typed build surface
492    /// rather than as a runtime surprise. Runs *after*
493    /// `validate_restart_exclusive` so a `((:state-change …)
494    /// (:restart))` shape still surfaces the more-fundamental
495    /// `RestartNotExclusive` (a valid `(:restart)` entry is `(:restart)`
496    /// alone, so no Restart-bearing entry reaches this gate carrying a
497    /// `StateChange`).
498    fn validate_state_change_ordering(&self) -> Result<(), UpgradeError> {
499        // Route the per-instruction load-family arm-discriminator through
500        // the `gen_platform::IsVariant`-derive-generated
501        // [`UpgradeInstruction::is_load_module`] predicate and the
502        // per-instruction migration-family `:script` scalar projection
503        // through the sibling lifted [`UpgradeInstruction::declared_path`]
504        // `Option<&PathBuf>` accessor rather than the raw two-arm
505        // `match instr { UpgradeInstruction::LoadModule { .. } =>
506        // loaded = true, UpgradeInstruction::StateChange { script } if
507        // !loaded => …, _ => {} }` open-coded pattern-match — closes the
508        // last unlifted `match`-shaped per-arm-hand-rolled load-family
509        // arm-discriminator + migration-family script-projection pair
510        // inside `impl UpgradeFromEntry`. Sibling of the peer
511        // [`Self::validate_purge_ordering`] (580d0f1) routing already
512        // lifted onto [`UpgradeInstruction::is_load_module`] on the paired
513        // load → cleanup ordering axis, the peer
514        // [`Self::validate_load_singularity`] (c9ce91d) routing lifted
515        // onto the [`UpgradeInstruction::is_load_module`] +
516        // [`UpgradeInstruction::declared_module`] pair on the singularity
517        // axis, and the peer [`Self::validate_state_change_singularity`]
518        // routing already lifted onto the sibling
519        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
520        // accessor on the migration-family script-projection axis — both
521        // ordering-gate load-family sticky-latch dispatches now key off
522        // exactly one typed dispatch on the substrate primitive for
523        // their load-family arm-discriminator, and both migration-family
524        // projection sites (this ordering gate + the peer singularity
525        // gate) now key off exactly one typed dispatch on the substrate
526        // primitive for the `:script`-carrying axis. A future sixth arm
527        // on [`UpgradeInstruction`] (an `AwaitReadiness` gate, a
528        // `Downgrade` reverse-axis variant OTP's `relup` acknowledges, a
529        // `CanaryTraffic` split-traffic variant the M4 CR materializer
530        // could resolve per-CR — INSPIRATIONS §II.4) migrates as one
531        // enum-declaration edit through the derive rather than a
532        // coordinated rewrite of every ordering / singularity gate's
533        // per-arm hand-rolled pattern-match. Byte-identity of this
534        // dispatch against the pre-lift `match` shape is pinned by
535        // [`tests::validate_state_change_ordering_projects_scripts_through_is_load_module_and_declared_path_accessors`].
536        let mut loaded = false;
537        for instr in self.instructions() {
538            if instr.is_load_module() {
539                loaded = true;
540            } else if !loaded && let Some(script) = instr.declared_path() {
541                return Err(UpgradeError::state_change_without_prior_load(
542                    self.prior_versao(),
543                    script,
544                ));
545            }
546        }
547        Ok(())
548    }
549
550    /// Reject an entry whose `(:soft-purge …)` or `(:purge …)` is not
551    /// preceded by a `(:load-module …)` in the same `:instructions` list.
552    ///
553    /// `SoftPurge` and `Purge` are the `code:soft_purge/1` /
554    /// `code:purge/1` analogs (INSPIRATIONS §II.4): they remove the
555    /// *old* module from memory after the new one is resident. OTP's
556    /// two-phase code load is `code:load_module/1` *then*
557    /// `code:soft_purge/1` — load the new version alongside the old
558    /// (both in memory, new requests route to new), then purge the old
559    /// after in-flight callers drain. caixa decomposes that into two
560    /// explicit instructions (`LoadModule` brings the new version up
561    /// "alongside the current one", per [`UpgradeInstruction::LoadModule`]
562    /// doc; `SoftPurge` "waits for in-flight requests on a named module
563    /// to drain, then GC it", per [`UpgradeInstruction::SoftPurge`] doc),
564    /// and the module doc pins that the operator "runs the instructions
565    /// in order". So a `:soft-purge` / `:purge` with no preceding
566    /// `:load-module` purges old code while the only resident version is
567    /// still the *same* old code, leaving the upgrade entry asking the
568    /// operator to drain or discard the live module with no replacement
569    /// resident. Two authoring footguns close here:
570    ///
571    ///   - `((:soft-purge "…"))` / `((:purge "…"))` — the "I wrote the
572    ///     cleanup but forgot to load the new module" footgun. The new
573    ///     code never comes up alongside; the operator either drains the
574    ///     old version to nothing (`SoftPurge`) or discards it outright
575    ///     mid-request (`Purge`), with no replacement to route in-flight
576    ///     or future requests to.
577    ///   - `((:soft-purge "…") (:load-module "…"))` /
578    ///     `((:purge "…") (:load-module "…"))` — the right-instructions-
579    ///     wrong-order footgun. Because the operator executes in declared
580    ///     order, the cleanup runs *before* the new code is resident,
581    ///     leaving a window during which neither version is available;
582    ///     the canonical order is `(:load-module …) (:state-change …)
583    ///     (:soft-purge …)` (module doc example).
584    ///
585    /// Same within-entry cross-instruction discipline as
586    /// [`Self::validate_state_change_ordering`] (the `:state-change`-
587    /// ordering gate it runs beside): both close the same load-before-X
588    /// post-condition on the OTP appup ordering contract, now extending
589    /// the typed coverage from "new code resident before its state
590    /// migration runs" to "new code resident before the old code is
591    /// drained or discarded" — the second half of OTP's two-phase code
592    /// load. Runs *after* `validate_state_change_ordering` so an entry
593    /// like `((:state-change …) (:soft-purge …))` surfaces the more-
594    /// fundamental `StateChangeWithoutPriorLoad` first (both instructions
595    /// are load-less, but state-change is the load-bearing semantic — the
596    /// purge is meaningless either way without a preceding load, so the
597    /// author should see the migration-side diagnostic first).
598    fn validate_purge_ordering(&self) -> Result<(), UpgradeError> {
599        let mut loaded = false;
600        for instr in self.instructions() {
601            // Route the per-instruction cleanup-family arm-discriminator
602            // through the lifted [`UpgradeInstruction::is_cleanup`] typed
603            // predicate rather than the raw
604            // `UpgradeInstruction::SoftPurge { module } |
605            // UpgradeInstruction::Purge { module }` open-coded per-arm
606            // union pattern-match — the first of three within-entry cross-
607            // instruction cleanup-facing gates now keys off exactly one
608            // typed dispatch on the substrate primitive, so any future
609            // fifth cleanup-shaped variant (a `Discard` variant the
610            // `code:delete/1` peer inspires) added to
611            // [`UpgradeInstruction`] + a composing `|| self.is_discard()`
612            // term at [`UpgradeInstruction::is_cleanup`] reaches this gate
613            // through the accessor's one body. The paired cleanup-arm
614            // `:module` scalar is routed through the sibling
615            // [`UpgradeInstruction::declared_module`] accessor rather than
616            // the raw pattern-bound `module` binding — same substrate-
617            // primitive-owns-the-scalar discipline every peer
618            // per-`UpgradeInstruction` scalar-value axis already routes
619            // through, with the `is_cleanup`-implies-`declared_module`-is-
620            // `Some` composition pin at
621            // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
622            // making the `.expect(…)` structurally infallible at build
623            // time. Peer of the sibling
624            // [`UpgradeFromEntry::validate_restart_exclusive`]
625            // paired positive / negated
626            // [`UpgradeInstruction::is_restart`] routing (915a934) on the
627            // per-arm terminal-fallback partition — same closed-set-typed-
628            // enum arm-discriminator dispatch discipline extended from
629            // the single-arm terminal-fallback family onto the two-arm
630            // cleanup family here.
631            //
632            // Route the paired load-family arm-discriminator through the
633            // `gen_platform::IsVariant`-derive-generated
634            // [`UpgradeInstruction::is_load_module`] predicate rather than
635            // the raw `matches!(instr, UpgradeInstruction::LoadModule
636            // { .. })` open-coded pattern-match — closes the last
637            // unlifted `matches!`-based per-variant arm-discriminator
638            // axis on the [`UpgradeInstruction`] closed-set typed enum,
639            // sibling of the [`UpgradeInstruction::is_restart`] terminal-
640            // fallback routing (915a934) and the
641            // [`UpgradeInstruction::is_cleanup`] two-arm cleanup-family
642            // routing (0bc469f) that already lifted the paired
643            // arm-discriminator sites in this method. Every arm-family
644            // partition the gate keys off — load-family (`LoadModule`),
645            // cleanup-family (`SoftPurge | Purge`), terminal-fallback
646            // (`Restart`) — now consults exactly one typed dispatch on
647            // the substrate primitive, so a future sixth arm added to
648            // [`UpgradeInstruction`] (an `AwaitReadiness` gate, a
649            // `Downgrade` reverse-axis variant OTP's `relup` acknowledges,
650            // a `CanaryTraffic` split-traffic variant the M4 CR
651            // materializer could resolve per-CR — INSPIRATIONS §II.4)
652            // migrates as a single enum-declaration edit through the
653            // derive rather than a scattered per-consumer rewrite. The
654            // partition invariant is pinned by
655            // [`tests::upgrade_instruction_is_load_module_predicate_partitions_the_arm_set`]
656            // and the byte-identity of this dispatch against the pre-lift
657            // `matches!` pattern by
658            // [`tests::validate_purge_ordering_routes_through_is_load_module_predicate`].
659            if instr.is_load_module() {
660                loaded = true;
661            } else if instr.is_cleanup() && !loaded {
662                return Err(UpgradeError::purge_without_prior_load(
663                    self.prior_versao(),
664                    instr.lisp_form(),
665                    instr
666                        .declared_module()
667                        .expect("is_cleanup() implies declared_module() is Some"),
668                ));
669            }
670        }
671        Ok(())
672    }
673
674    /// Reject an entry whose `(:state-change …)` appears after any
675    /// `(:soft-purge …)` / `(:purge …)` in the same `:instructions`
676    /// list — completing the canonical OTP appup `code:load_module/1`
677    /// → `gen_server:code_change/3` → `code:soft_purge/1` ordering
678    /// chain on the typed `:upgrade-from` slot.
679    ///
680    /// `StateChange` is the `gen_server:code_change/3` analog
681    /// ([`UpgradeInstruction::StateChange`] doc; INSPIRATIONS §II.4
682    /// verbatim: "State migration uses `gen_server:code_change/3` …
683    /// migrate state from v0.1.0 shape to current shape"). The
684    /// callback's input is the *prior* version's state shape, which
685    /// only exists while the prior code is still resident — the running
686    /// `gen_server` processes hold the v0.1.0 state, and the operator's
687    /// dispatch invokes `code_change/3` to fold that state into the
688    /// current shape. `SoftPurge` / `Purge` are the `code:soft_purge/1`
689    /// / `code:purge/1` analogs ([`UpgradeInstruction::SoftPurge`] /
690    /// [`UpgradeInstruction::Purge`] docs): they drain or discard the
691    /// *old* module after the new one is resident. The operator runs
692    /// instructions in declared order (module doc), so a cleanup ahead
693    /// of a state-change discards the prior code before the migration
694    /// fold runs against the state it held — the canonical OTP error
695    /// mode "`code_change/3` invoked on a purged module" the
696    /// `release_handler` enforces by always emitting the migration
697    /// callback before the soft-purge step.
698    ///
699    /// `systools`-generated `.relup` files always emit `code_change`
700    /// before `soft_purge` for this reason; the appup cookbook's
701    /// canonical pattern (`[{load_module, m}, {update, m, soft},
702    /// {soft_purge, m}]`) places the migration-triggering `update`
703    /// strictly between the load and the cleanup. The caixa module
704    /// doc pins the same canonical order verbatim — `(:load-module
705    /// …) (:state-change …) (:soft-purge …)` — and this gate makes
706    /// that ordering a structural property at build time. Three
707    /// authoring footguns close here:
708    ///
709    ///   - `((:load-module "x") (:soft-purge "x-old") (:state-change
710    ///     "lib/m.lisp"))` — the right-instructions-wrong-order
711    ///     footgun on the migrate ↔ cleanup axis. Because the operator
712    ///     executes in declared order, the cleanup drains the v0.1.0
713    ///     module to nothing before the migration callback runs, and
714    ///     the script either no-ops (no v0.1.0 state left to fold) or
715    ///     crashes (`code_change/3` invoked on an unloaded version).
716    ///     The canonical order is `(:load-module …) (:state-change
717    ///     …) (:soft-purge …)` (module doc example).
718    ///   - `((:load-module "x") (:purge "x-old") (:state-change
719    ///     "lib/m.lisp"))` — same shape on the more catastrophic
720    ///     `:purge` variant. The immediate-discard semantic destroys
721    ///     v0.1.0 state mid-request; the trailing migration script
722    ///     has nothing to fold from and the `gen_server` processes that
723    ///     held v0.1.0 state were killed by the `:purge`.
724    ///   - `((:load-module "x") (:soft-purge "x-old") (:state-change
725    ///     "lib/m1.lisp") (:soft-purge "y-old"))` — the "migration
726    ///     sandwiched between two cleanups" footgun. The first
727    ///     cleanup discards v0.1.0; the migration runs against
728    ///     drained state; the second cleanup is irrelevant. The first
729    ///     cleanup → state-change boundary is the load-bearing defect
730    ///     surfaced.
731    ///
732    /// Same within-entry cross-instruction discipline as
733    /// [`Self::validate_state_change_ordering`] (the load → state-
734    /// change ordering gate it runs after) and
735    /// [`Self::validate_purge_ordering`] (the load → cleanup ordering
736    /// gate it runs after): all three close one boundary of the OTP
737    /// canonical sequence `code:load_module/1` →
738    /// `gen_server:code_change/3` → `code:soft_purge/1`. The
739    /// state-change-ordering gate closes the load → migrate boundary;
740    /// the purge-ordering gate closes the load → cleanup boundary;
741    /// this gate closes the migrate → cleanup boundary, completing
742    /// the typed coverage of the canonical sequence. Runs *after*
743    /// [`Self::validate_purge_ordering`] (and therefore after
744    /// [`Self::validate_state_change_ordering`]) so an entry like
745    /// `((:soft-purge "x-old") (:state-change "lib/m.lisp"))` —
746    /// which violates *both* the purge-without-load gate and this
747    /// state-change-after-cleanup gate — surfaces the more-
748    /// fundamental `PurgeWithoutPriorLoad` first (the missing-load
749    /// defect is load-bearing; once a coherent `(:load-module …)`
750    /// precedes both, the migrate ↔ cleanup ordering becomes the
751    /// next live defect). Runs *before* the per-instruction-class
752    /// singularity gates ([`Self::validate_load_singularity`],
753    /// [`Self::validate_state_change_singularity`],
754    /// [`Self::validate_cleanup_singularity`]) so an entry like
755    /// `((:load-module "x") (:soft-purge "x-old") (:state-change
756    /// "lib/m.lisp") (:state-change "lib/m.lisp"))` — which violates
757    /// *both* this ordering gate and the state-change-singularity
758    /// gate — surfaces the ordering defect first; the canonical
759    /// "ordering before singularity" precedence the peer
760    /// `validate_state_change_ordering` / `validate_purge_ordering`
761    /// gates already establish.
762    ///
763    /// Detection: linear scan of the instructions list with a
764    /// `prior_cleanup: Option<(module, kind)>` sticky-once latch
765    /// recording the first cleanup encountered; on any subsequent
766    /// `StateChange` the gate fires with the script + the prior
767    /// cleanup's kind/module. Diagnostic-order pin: the first
768    /// colliding state-change-after-cleanup pair surfaces, not the
769    /// last — mirrors every peer ordering gate's first-collision
770    /// posture ([`Self::validate_state_change_ordering`] returns on
771    /// the first `StateChange` without prior load,
772    /// [`Self::validate_purge_ordering`] on the first cleanup
773    /// without prior load).
774    fn validate_state_change_before_cleanup(&self) -> Result<(), UpgradeError> {
775        let mut prior_cleanup: Option<(&str, &'static str)> = None;
776        for instr in self.instructions() {
777            // Route the per-instruction cleanup-family arm-discriminator
778            // through the lifted [`UpgradeInstruction::is_cleanup`] typed
779            // predicate rather than the raw
780            // `UpgradeInstruction::SoftPurge { module } |
781            // UpgradeInstruction::Purge { module }` open-coded per-arm
782            // union pattern-match — the second of three within-entry
783            // cross-instruction cleanup-facing gates the peer
784            // [`Self::validate_purge_ordering`] routing already lifted;
785            // both now key off exactly one typed dispatch on the substrate
786            // primitive so the "which arms belong to the cleanup family"
787            // question resolves at exactly one caixa-core edit. The
788            // sticky-once latch's `:module` scalar is routed through the
789            // sibling [`UpgradeInstruction::declared_module`] accessor
790            // rather than the raw pattern-bound `module.as_str()`
791            // projection, with the `is_cleanup`-implies-`declared_module`-
792            // is-`Some` composition pin at
793            // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
794            // making the `.expect(…)` structurally infallible at build
795            // time.
796            if instr.is_cleanup() && prior_cleanup.is_none() {
797                prior_cleanup = Some((
798                    instr
799                        .declared_module()
800                        .expect("is_cleanup() implies declared_module() is Some"),
801                    instr.lisp_form(),
802                ));
803            } else if let Some(script) = instr.declared_path()
804                && let Some((prior_module, prior_kind)) = prior_cleanup
805            {
806                // Route the per-instruction `StateChange`-arm script-path
807                // projection through the sibling lifted
808                // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
809                // accessor rather than the raw
810                // `if let UpgradeInstruction::StateChange { script } = instr`
811                // open-coded pattern-match — the last unlifted per-
812                // `UpgradeInstruction` `PathBuf`-carrying-axis consumer
813                // inside `impl UpgradeFromEntry`, sibling to the four peer
814                // per-`UpgradeInstruction` consumers already routed through
815                // the accessor: [`UpgradeInstruction::validate`]'s per-
816                // `StateChange` sandbox-path fan-out, the layout-side per-
817                // `StateChange` script-existence fan-out at
818                // [`crate::layout::StandardLayout::verify`]
819                // (caixa-core/src/layout.rs:1058), the within-entry
820                // [`UpgradeFromEntry::validate_state_change_singularity`]
821                // per-`StateChange` script-projection fan-out, and the
822                // cross-slot
823                // [`validate_upgrade_from_against_behavior`]
824                // per-`StateChange` detection loop. Byte-equal today
825                // (`declared_path` returns `Some(script)` iff the
826                // instruction is [`UpgradeInstruction::StateChange`], per
827                // the sibling `declared_path_only_for_state_change` pin),
828                // so a state-change-after-cleanup surfaces
829                // `StateChangeAfterCleanup` byte-identical to the pattern-
830                // match shape. Any future accessor extension that promotes
831                // an additional variant onto the `PathBuf`-carrying axis
832                // reaches this gate through one caixa-core edit rather
833                // than a coordinated rewrite of five call sites — the
834                // migrate→cleanup ordering discipline extends to the
835                // promoted variant by construction. Same "one typed
836                // dispatch on the substrate primitive, thin projections at
837                // each consumer" trajectory the sibling
838                // [`UpgradeInstruction::declared_module`] `String`-axis
839                // per-variant unifier already established.
840                return Err(UpgradeError::state_change_after_cleanup(
841                    self.prior_versao(),
842                    script,
843                    prior_kind,
844                    prior_module,
845                ));
846            }
847        }
848        Ok(())
849    }
850
851    /// Reject an entry whose `:instructions` list names the same module
852    /// as the target of more than one cleanup instruction (`:soft-purge`
853    /// or `:purge`) in total — set-not-multiset on the (cleanup-class,
854    /// module) axis, narrowed to the cleanup class.
855    ///
856    /// `SoftPurge` and `Purge` are the `code:soft_purge/1` /
857    /// `code:purge/1` analogs (INSPIRATIONS §II.4 verbatim: "1.
858    /// `code:load_module/1` — load v2 alongside v1 … 2.
859    /// `code:soft_purge/1` — wait until no process is running v1, then
860    /// discard. (`code:purge/1` kills v1 immediately if you don't
861    /// care.)"). The author picks *one* cleanup semantic per old
862    /// module — `:soft-purge` (preferred: waits for in-flight callers
863    /// to drain) or `:purge` (when the drain isn't possible) — and the
864    /// operator runs that one in declared order alongside any other
865    /// distinct-module cleanups. systools-generated `.relup` files
866    /// always emit at most one purge per module for this reason; any
867    /// retry / fallback decision is the operator's job on
868    /// instruction failure, not authored into the entry. Three
869    /// authoring footguns close here:
870    ///
871    ///   - `((:load-module "x") (:soft-purge "x-old") (:soft-purge "x-old"))`
872    ///     — the "I copy-pasted the cleanup line twice" footgun. The
873    ///     second `:soft-purge` is a no-op (the module is already gone
874    ///     after the first drain-and-discard) or undefined depending
875    ///     on the operator's handling of a non-resident-module purge
876    ///     request; either way the second instruction carries no
877    ///     observable semantic, far from the source caixa.lisp.
878    ///   - `((:load-module "x") (:soft-purge "x-old") (:purge "x-old"))`
879    ///     — the "soft-then-hard fallback" footgun. The author wrote
880    ///     "drain, and if drain didn't clean it up, force-discard",
881    ///     but the operator runs instructions unconditionally in
882    ///     declared order — the `:purge` fires whether the
883    ///     `:soft-purge` already discarded the module or not, so the
884    ///     fallback semantic the author imagined is missing; the
885    ///     pair is incoherent (drain *and* force-discard semantics
886    ///     on one module is two contradictory dispositions). The
887    ///     operator's failure-handling surface is its own
888    ///     responsibility: if `:soft-purge` doesn't drain within its
889    ///     cooldown the operator escalates, not the author's entry.
890    ///   - `((:load-module "x") (:purge "x-old") (:soft-purge "x-old"))`
891    ///     — same shape on the reversed ordering. The `:purge`
892    ///     discards immediately; the trailing `:soft-purge` has no
893    ///     module to drain.
894    ///
895    /// Same within-entry exclusivity discipline as
896    /// [`Self::validate_restart_exclusive`] (the `(:restart)` terminal-
897    /// exclusivity gate it joins on the per-module cleanup axis): both
898    /// reject an `:instructions` list whose instructions are
899    /// individually well-shaped but jointly incoherent on a chosen
900    /// semantic axis (restart-fallback for the whole entry there;
901    /// cleanup-semantic for one module here), at the typed build
902    /// surface rather than as a runtime surprise. Runs *after*
903    /// [`Self::validate_purge_ordering`] (the load-before-cleanup
904    /// ordering gate) so an entry like `((:soft-purge "x-old")
905    /// (:soft-purge "x-old"))` surfaces the more-fundamental
906    /// `PurgeWithoutPriorLoad` first (both cleanups are load-less, and
907    /// the missing-load defect is the load-bearing one — the duplicate
908    /// is meaningless either way without the preceding load).
909    ///
910    /// Same set-not-multiset discipline applied to every peer
911    /// duplicate-target axis: `:children :caixa` (dbf50a9 —
912    /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
913    /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
914    /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
915    /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
916    /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
917    /// and `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]).
918    /// Each closes the same authoring footgun: a Vec authoring surface
919    /// that silently accepts duplicate entries and renders the "second
920    /// wins" (or "operator processes both, second is a no-op or
921    /// errors") shape downstream, far from the source caixa.lisp.
922    /// This gate extends the discipline onto the within-entry
923    /// instruction-target axis — duplicate cleanup targets *within*
924    /// one `:upgrade-from` entry — the peer of the cross-entry
925    /// duplicate-`:from` axis at one level of nesting deeper.
926    ///
927    /// Detection: linear scan of the instructions list collecting
928    /// the (module, kind) pair from every `SoftPurge` / `Purge`
929    /// encountered; on the second occurrence of any module the gate
930    /// fires with the prior kind and the colliding kind in declaration
931    /// order. Diagnostic-order pin: the first colliding pair surfaces,
932    /// not the last — mirrors
933    /// [`validate_upgrade_from`]'s
934    /// `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
935    /// posture (the first detected collision wins) and every peer
936    /// duplicate gate's first-collision discipline.
937    fn validate_cleanup_singularity(&self) -> Result<(), UpgradeError> {
938        let mut seen: Vec<(&str, &'static str)> = Vec::new();
939        for instr in self.instructions() {
940            // Route the per-instruction cleanup-family arm-discriminator
941            // through the lifted [`UpgradeInstruction::is_cleanup`] typed
942            // predicate rather than the raw two-arm
943            // `UpgradeInstruction::SoftPurge { module } => (module.as_str(),
944            // M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE)` /
945            // `UpgradeInstruction::Purge { module } => (module.as_str(),
946            // M2_UPGRADE_INSTRUCTION_KIND_PURGE)` / `_ => continue`
947            // per-arm dispatch — the third of three within-entry cross-
948            // instruction cleanup-facing gates the peer
949            // [`Self::validate_purge_ordering`] +
950            // [`Self::validate_state_change_before_cleanup`] routing
951            // already lifted; all three now key off exactly one typed
952            // dispatch on the substrate primitive, structurally. The
953            // cleanup-target `(module, kind)` pair is projected through
954            // the peer [`UpgradeInstruction::declared_module`] /
955            // [`UpgradeInstruction::lisp_form`] accessors rather than
956            // the per-arm-hand-rolled scalar-value + kind-const pair,
957            // with the `is_cleanup`-implies-`declared_module`-is-`Some`
958            // composition pin at
959            // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
960            // making the `.expect(…)` structurally infallible at build
961            // time. Any future fifth cleanup-shaped variant added under
962            // the `is_cleanup` predicate + registered through the peer
963            // `lisp_form` per-arm kebab-case-const dispatch reaches this
964            // dedup gate through the accessor's one body rather than a
965            // fourth per-arm-hand-rolled scalar/kind projection here.
966            if !instr.is_cleanup() {
967                continue;
968            }
969            let module = instr
970                .declared_module()
971                .expect("is_cleanup() implies declared_module() is Some");
972            let kind = instr.lisp_form();
973            if let Some(prior_idx) = seen.iter().position(|(m, _)| *m == module) {
974                let prior_kind = seen[prior_idx].1;
975                return Err(UpgradeError::duplicate_cleanup(
976                    self.prior_versao(),
977                    module,
978                    vec![prior_kind, kind],
979                ));
980            }
981            seen.push((module, kind));
982        }
983        Ok(())
984    }
985
986    /// Reject an entry whose `:instructions` list names the same module
987    /// as the target of more than one `(:load-module …)` instruction —
988    /// set-not-multiset on the `LoadModule` axis.
989    ///
990    /// `LoadModule` is the `code:load_module/1` analog (INSPIRATIONS
991    /// §II.4 verbatim: "1. `code:load_module/1` — load v2 alongside v1;
992    /// new code is 'current', old code is 'old'."). The instruction
993    /// brings the new wasm component up resident alongside the old
994    /// one so the operator can route new traffic to the new code
995    /// while in-flight callers drain on the old — and the operator's
996    /// dispatch table reads the module *name* (a caixa name) to bind
997    /// the component, so two `(:load-module "x")` instructions in one
998    /// entry ask the operator to re-bind the same component twice.
999    /// `systools`-generated `.relup` files emit at most one
1000    /// `load_module` per module per upgrade step for this reason; the
1001    /// second load has no observable semantic relative to the first
1002    /// (the component is already resident). Three authoring footguns
1003    /// close here:
1004    ///
1005    ///   - `((:load-module "x") (:load-module "x"))` — the "I
1006    ///     copy-pasted the load line twice" footgun. The second
1007    ///     `:load-module` re-reads the same module name and re-binds
1008    ///     the same wasm component — a no-op in both directions
1009    ///     (no new code becomes resident; no old code is purged) —
1010    ///     and any cleanup / migration the author intended for a
1011    ///     *distinct* module is silently absent from the entry.
1012    ///   - `((:load-module "x") (:load-module "x") (:state-change …))`
1013    ///     — the "I meant to load two distinct modules" typo. The
1014    ///     author intended `((:load-module "x") (:load-module "y"))`
1015    ///     but renamed both to "x" (or copied the first line and
1016    ///     forgot to change the module). The migration runs against
1017    ///     code that's resident only on one module name, and the
1018    ///     second module the author imagined was being loaded never
1019    ///     comes up at all — far from the source caixa.lisp.
1020    ///   - `((:load-module "x") (:load-module "x") (:soft-purge "x-old"))`
1021    ///     — same shape with a trailing cleanup. The duplicate load
1022    ///     is dead code; the cleanup still fires correctly, masking
1023    ///     the load-side duplication as a silently-passing entry.
1024    ///
1025    /// Same within-entry exclusivity discipline as
1026    /// [`Self::validate_cleanup_singularity`] (the per-module cleanup-
1027    /// singularity gate this runs beside) on the sibling
1028    /// `LoadModule` axis: both reject an `:instructions` list whose
1029    /// instructions are individually well-shaped but jointly
1030    /// incoherent on a per-module-per-class basis (load-once for the
1031    /// load axis here; cleanup-once for the cleanup axis there), at
1032    /// the typed build surface rather than as a runtime surprise.
1033    /// Runs *after* [`Self::validate_purge_ordering`] (the load-
1034    /// before-cleanup ordering gate) so an entry like
1035    /// `((:state-change "m.lisp") (:load-module "x") (:load-module "x"))`
1036    /// surfaces the more-fundamental `StateChangeWithoutPriorLoad`
1037    /// first (the missing-load defect is load-bearing — the migration
1038    /// runs against unloaded code; the duplicate is meaningless either
1039    /// way without the preceding load). Runs *before*
1040    /// [`Self::validate_cleanup_singularity`] so an entry like
1041    /// `((:load-module "x") (:load-module "x") (:soft-purge "y-old")
1042    /// (:soft-purge "y-old"))` surfaces `DuplicateLoadModule` first —
1043    /// the load axis precedes the cleanup axis in the canonical OTP
1044    /// sequence (`code:load_module/1` then `code:soft_purge/1`) and
1045    /// in [`UpgradeInstruction`] declaration order (`LoadModule`
1046    /// before `SoftPurge`/`Purge`), so the load-side singularity is
1047    /// the load-bearing diagnostic when both fire.
1048    ///
1049    /// Same set-not-multiset discipline applied to every peer
1050    /// duplicate-target axis: `:children :caixa` (dbf50a9 —
1051    /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
1052    /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
1053    /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1054    /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1055    /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
1056    /// `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]), and
1057    /// the per-module cleanup-target axis (9cedd8b —
1058    /// [`UpgradeError::DuplicateCleanup`]). This gate extends the
1059    /// discipline onto the within-entry `LoadModule` instruction-target
1060    /// axis — the third within-entry per-module singularity completing
1061    /// the load+cleanup pair across the OTP two-phase code-load
1062    /// contract.
1063    ///
1064    /// Detection: linear scan of the instructions list collecting the
1065    /// module name from every `LoadModule` encountered; on the second
1066    /// occurrence of any module the gate fires. Diagnostic-order pin:
1067    /// the first colliding occurrence surfaces, not the last — mirrors
1068    /// [`Self::validate_cleanup_singularity`]'s first-collision posture
1069    /// and every peer duplicate gate's first-collision discipline.
1070    fn validate_load_singularity(&self) -> Result<(), UpgradeError> {
1071        let mut seen: Vec<&str> = Vec::new();
1072        for instr in self.instructions() {
1073            // Route the per-instruction load-family arm-discriminator
1074            // through the `gen_platform::IsVariant`-derive-generated
1075            // [`UpgradeInstruction::is_load_module`] predicate rather
1076            // than the raw single-arm `match instr {
1077            // UpgradeInstruction::LoadModule { module } =>
1078            // module.as_str(), _ => continue }` open-coded pattern-
1079            // match — closes the last unlifted `matches!`-shaped
1080            // per-arm-hand-rolled scalar-value + arm-discriminator
1081            // pair inside `impl UpgradeFromEntry`, sibling of the
1082            // peer [`Self::validate_cleanup_singularity`] (0bc469f)
1083            // routing already lifted onto the two-arm cleanup-family
1084            // axis's per-arm arm-discriminator + `:module` projection
1085            // dispatch. The load-target `:module` scalar is projected
1086            // through the sibling [`UpgradeInstruction::declared_module`]
1087            // accessor rather than the per-arm-hand-rolled scalar-
1088            // value binding, with the
1089            // `is_load_module`-implies-`declared_module`-is-`Some`
1090            // composition pin at
1091            // [`tests::upgrade_instruction_is_load_module_implies_declared_module_is_some`]
1092            // making the `.expect(…)` structurally infallible at
1093            // build time. Every arm-family partition the three
1094            // within-entry per-instruction-class singularity gates
1095            // key off — load-family
1096            // ([`UpgradeInstruction::LoadModule`]), cleanup-family
1097            // ([`UpgradeInstruction::SoftPurge`] |
1098            // [`UpgradeInstruction::Purge`]), migration-family
1099            // ([`UpgradeInstruction::StateChange`]) — now consults
1100            // exactly one typed dispatch on the substrate primitive
1101            // (`is_load_module()` here, `is_cleanup()` at
1102            // [`Self::validate_cleanup_singularity`],
1103            // `declared_path()` at
1104            // [`Self::validate_state_change_singularity`]), so a
1105            // future sixth arm added to [`UpgradeInstruction`] (an
1106            // `AwaitReadiness` gate, a `Downgrade` reverse-axis
1107            // variant OTP's `relup` acknowledges, a `CanaryTraffic`
1108            // split-traffic variant the M4 CR materializer could
1109            // resolve per-CR — INSPIRATIONS §II.4) migrates as a
1110            // single enum-declaration edit through the derive rather
1111            // than a scattered per-consumer rewrite. Byte-identity of
1112            // this dispatch against the pre-lift match-pattern is
1113            // pinned by
1114            // [`tests::validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors`].
1115            if !instr.is_load_module() {
1116                continue;
1117            }
1118            let module = instr
1119                .declared_module()
1120                .expect("is_load_module() implies declared_module() is Some");
1121            if seen.contains(&module) {
1122                return Err(UpgradeError::duplicate_load_module(
1123                    self.prior_versao(),
1124                    module,
1125                ));
1126            }
1127            seen.push(module);
1128        }
1129        Ok(())
1130    }
1131
1132    /// Reject an entry whose `:instructions` list names the same script
1133    /// as the target of more than one `(:state-change …)` instruction —
1134    /// set-not-multiset on the `StateChange` axis.
1135    ///
1136    /// `StateChange` is the `gen_server:code_change/3` analog
1137    /// (INSPIRATIONS §II.4: "State migration uses
1138    /// `gen_server:code_change/3`"). The instruction folds the *old*
1139    /// state into the shape the *new* code expects — a one-shot
1140    /// transition from one declared state representation to another.
1141    /// OTP's `release_handler:install_release/1` invokes `code_change/3`
1142    /// exactly once per upgrade per `gen_server`; `systools`-generated
1143    /// `.relup` files emit at most one `code_change` per `gen_server` per
1144    /// upgrade step for this reason. A second `(:state-change "m.lisp")`
1145    /// instruction targeting the same script in one entry re-runs the
1146    /// migration fold — at best a no-op (idempotent script masking a
1147    /// typo where the author intended two distinct scripts) and at
1148    /// worst silent state corruption (non-idempotent fold double-
1149    /// applied: an `add column` migration that runs twice, an
1150    /// `increment counter` that double-bumps, a `rename field` that
1151    /// renames-then-fails the second time). Three authoring footguns
1152    /// close here:
1153    ///
1154    ///   - `((:load-module "x") (:state-change "lib/m.lisp")
1155    ///     (:state-change "lib/m.lisp"))` — the "I copy-pasted the
1156    ///     migration line twice" footgun. The second `:state-change`
1157    ///     re-runs the same fold on the already-migrated state — a
1158    ///     no-op if the script is idempotent (dead code masking the
1159    ///     duplication) or state corruption if not (the migration's
1160    ///     pre-condition no longer holds because the post-condition is
1161    ///     already in place).
1162    ///   - `((:load-module "x") (:state-change "lib/m.lisp")
1163    ///     (:state-change "lib/m.lisp") (:soft-purge "x-old"))` — the
1164    ///     "duplicate migrate masked by trailing cleanup" footgun. The
1165    ///     cleanup still fires correctly, masking the migration-side
1166    ///     duplication as a silently-passing entry.
1167    ///   - `((:load-module "x") (:state-change "lib/m1.lisp")
1168    ///     (:state-change "lib/m1.lisp"))` — the "I meant to migrate
1169    ///     two distinct modules" typo. The author intended
1170    ///     `(:state-change "lib/m1.lisp") (:state-change "lib/m2.lisp")`
1171    ///     but renamed both to `m1.lisp` (or copy-pasted the first line
1172    ///     and forgot to change the script). The migration that should
1173    ///     have folded the second module's state never runs, far from
1174    ///     the source caixa.lisp.
1175    ///
1176    /// Same within-entry exclusivity discipline as
1177    /// [`Self::validate_load_singularity`] (the per-module load-
1178    /// singularity gate it runs after) and
1179    /// [`Self::validate_cleanup_singularity`] (the per-module cleanup-
1180    /// singularity gate it runs before) on the sibling `StateChange`
1181    /// axis: each rejects an `:instructions` list whose instructions
1182    /// are individually well-shaped but jointly incoherent on a per-
1183    /// instruction-class basis (load-once per module for the load
1184    /// axis; migrate-once per script for the migration axis here;
1185    /// cleanup-once per module for the cleanup axis), at the typed
1186    /// build surface rather than as a runtime surprise. Runs *after*
1187    /// [`Self::validate_load_singularity`] so an entry like
1188    /// `((:load-module "x") (:load-module "x") (:state-change
1189    /// "lib/m.lisp") (:state-change "lib/m.lisp"))` surfaces
1190    /// `DuplicateLoadModule` first — the load axis precedes the
1191    /// migration axis in the canonical OTP sequence
1192    /// (`code:load_module/1` then `gen_server:code_change/3`) and in
1193    /// [`UpgradeInstruction`] declaration order (`LoadModule` before
1194    /// `StateChange`), so the load-side singularity is the load-
1195    /// bearing diagnostic when both fire. Runs *before*
1196    /// [`Self::validate_cleanup_singularity`] so an entry like
1197    /// `((:load-module "x") (:state-change "lib/m.lisp") (:state-change
1198    /// "lib/m.lisp") (:soft-purge "y-old") (:soft-purge "y-old"))`
1199    /// surfaces `DuplicateStateChange` first — the migration axis
1200    /// precedes the cleanup axis in the canonical OTP sequence
1201    /// (`code:code_change/3` then `code:soft_purge/1`) and in
1202    /// [`UpgradeInstruction`] declaration order (`StateChange` before
1203    /// `SoftPurge`/`Purge`).
1204    ///
1205    /// Same set-not-multiset discipline applied to every peer
1206    /// duplicate-target axis: `:children :caixa` (dbf50a9 —
1207    /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
1208    /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
1209    /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1210    /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1211    /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
1212    /// `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]), the
1213    /// per-module cleanup-target axis (9cedd8b —
1214    /// [`UpgradeError::DuplicateCleanup`]), and the per-module load-
1215    /// target axis (a503978 — [`UpgradeError::DuplicateLoadModule`]).
1216    /// This gate extends the discipline onto the within-entry
1217    /// `StateChange` instruction-target axis — the third within-entry
1218    /// per-instruction-class singularity, completing the OTP two-phase
1219    /// code-load + state-migration coverage triad
1220    /// (`code:load_module/1` → `gen_server:code_change/3` →
1221    /// `code:soft_purge/1`).
1222    ///
1223    /// Detection: linear scan of the instructions list collecting the
1224    /// script path from every `StateChange` encountered; on the second
1225    /// occurrence of any script the gate fires. Diagnostic-order pin:
1226    /// the first colliding occurrence surfaces, not the last — mirrors
1227    /// [`Self::validate_load_singularity`]'s and
1228    /// [`Self::validate_cleanup_singularity`]'s first-collision posture
1229    /// and every peer duplicate gate's first-collision discipline.
1230    fn validate_state_change_singularity(&self) -> Result<(), UpgradeError> {
1231        // Route the per-instruction `StateChange`-arm script-path
1232        // projection through the sibling lifted
1233        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
1234        // accessor rather than the raw
1235        // `match instr { UpgradeInstruction::StateChange { script } =>
1236        // script.as_path(), _ => continue }` open-coded pattern-match —
1237        // the third within-entry singularity gate's per-instruction
1238        // script-projection site now keys off exactly one typed
1239        // dispatch on the substrate primitive's `PathBuf`-carrying
1240        // axis, sibling to the four peer per-`UpgradeInstruction`
1241        // consumers ([`Self::validate`]'s per-`StateChange`
1242        // sandbox-path fan-out, the layout-side per-`StateChange`
1243        // script-existence fan-out at
1244        // `caixa-core/src/layout.rs:1017`, the cross-slot
1245        // [`validate_upgrade_from_against_behavior`] gate's
1246        // per-`StateChange` detection loop, the future wasm-operator's
1247        // per-`StateChange` runtime hook-dispatch) that already route
1248        // through `declared_path` / `declared_module`. Byte-equal
1249        // today (`declared_path` returns `Some(script)` iff the
1250        // instruction is [`UpgradeInstruction::StateChange`], per the
1251        // sibling `declared_path_only_for_state_change` pin), so a
1252        // duplicate `:state-change` script surfaces
1253        // `DuplicateStateChange` byte-identical to the pattern-match
1254        // shape. Same "one typed dispatch on the substrate primitive,
1255        // thin projections at each consumer" discipline the sibling
1256        // [`UpgradeInstruction::declared_module`] accessor established
1257        // (b13c4f9) on the peer `String`-carrying axis's per-variant
1258        // consumers, extended here onto the last unlifted
1259        // pattern-match on the `PathBuf`-carrying axis inside
1260        // `impl UpgradeFromEntry`.
1261        let mut seen: Vec<&std::path::Path> = Vec::new();
1262        for instr in self.instructions() {
1263            let Some(script) = instr.declared_path() else {
1264                continue;
1265            };
1266            let script = script.as_path();
1267            if seen.contains(&script) {
1268                return Err(UpgradeError::duplicate_state_change(
1269                    self.prior_versao(),
1270                    script,
1271                ));
1272            }
1273            seen.push(script);
1274        }
1275        Ok(())
1276    }
1277}
1278
1279/// Validate a whole `:upgrade-from` list: per-entry typed shape via
1280/// [`UpgradeFromEntry::validate`] *and* the cross-entry graph-edge-set
1281/// invariant — at most one `(:from <prior>)` block per parsed semver.
1282///
1283/// OTP's appup picks at most one matching block to apply to the running
1284/// release (`release_handler:install_release/1` matches the loaded
1285/// `:from` against the currently-running version and executes the
1286/// associated instruction sequence; the wasm-operator picks the matching
1287/// block at upgrade time, per `upgrade.rs` module doc). Two blocks with
1288/// the same parsed-semver `:from` are an ambiguous edge in the typed
1289/// upgrade graph — the operator can pick either set deterministically,
1290/// but each set may carry different `LoadModule | StateChange |
1291/// SoftPurge | Purge | Restart` instructions, so the *chosen* path is
1292/// non-deterministic relative to the source caixa.lisp. The author's
1293/// intent is one path per prior version; the typed graph must enforce
1294/// that shape.
1295///
1296/// Same set-not-multiset discipline already applied to every peer
1297/// typed-graph axis: `:children :caixa` (dbf50a9 —
1298/// `SupervisorError::DuplicateChildCaixa`, `child_spec.id` is required-
1299/// unique per supervisor in OTP), `:membros :caixa` (4bb3f3d —
1300/// `AplicacaoError::MembroDuplicate`), `:contratos`
1301/// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1302/// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1303/// and `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`).
1304/// Each closes the same authoring footgun: a Vec authoring surface that
1305/// silently accepts duplicate entries and renders the "second wins"
1306/// (or "operator picks arbitrarily") shape downstream, far from the
1307/// source caixa.lisp.
1308///
1309/// Duplicates are detected by [`semver::Version`] equality (the
1310/// crate's `PartialEq` compares the full identity — major.minor.patch +
1311/// pre-release + build metadata — so `1.0.0` and `1.0.0-rc.1` and
1312/// `1.0.0+build1` and `1.0.0+build2` are all distinct upgrade paths).
1313/// The conservative choice mirrors what the wasm-operator's
1314/// `:from`-match dispatch can see; collapsing build metadata to catch
1315/// a wider net of duplicates is a future tightening that requires
1316/// coordinating with the operator's match step.
1317///
1318/// Per-entry shape errors fire before the duplicate gate so the
1319/// diagnostic names the malformed slot (`FromInvalid`, `EmptyScript`,
1320/// `ModuleInvalid`, …) rather than collapsing two unrelated authoring
1321/// errors into a single duplicate diagnostic. Mirrors the
1322/// `*_invalid_fires_before_duplicate_check` order pins on every peer
1323/// axis ([`crate::SupervisorSpec::validate`],
1324/// [`crate::AplicacaoSpec::validate_membros`],
1325/// [`crate::AplicacaoSpec::validate_placement`]).
1326pub fn validate_upgrade_from(entries: &[UpgradeFromEntry]) -> Result<(), UpgradeError> {
1327    use semver::Version;
1328    let mut seen: Vec<Version> = Vec::with_capacity(entries.len());
1329    for entry in entries {
1330        entry.validate()?;
1331        // `entry.validate()` accepted this `:from`, so parse cannot
1332        // fail here — the FromInvalid arm above is the only gate
1333        // and both call `Version::parse(entry.prior_versao())`.
1334        let parsed = Version::parse(entry.prior_versao()).expect(
1335            "UpgradeFromEntry::validate must accept `:from` iff Version::parse does — keep the \
1336             two gates aligned",
1337        );
1338        if seen.contains(&parsed) {
1339            return Err(UpgradeError::duplicate_from(entry));
1340        }
1341        seen.push(parsed);
1342    }
1343    Ok(())
1344}
1345
1346/// Reject `:upgrade-from` entries whose `:from` is not strictly less
1347/// than the caixa's current `:versao` (under SemVer-2 precedence — the
1348/// same ordering [`semver::Version::cmp`] implements, with build
1349/// metadata ignored per [SemVer §11][semver-11]).
1350///
1351/// The whole point of an `:upgrade-from :from "<prior>"` block is the
1352/// declarative answer to "given the wasm-operator is loading a node
1353/// running `<prior>`, how do I upgrade it to the *current* `:versao`?"
1354/// (`upgrade.rs` module doc, OTP appup `release_handler:install_release/1`
1355/// semantic). The operator's `:from`-match dispatch loads the
1356/// current `:versao` and matches the *running* version against each
1357/// entry's `:from`; an entry whose `:from >= :versao` is structurally
1358/// unreachable — the operator never runs a version greater than or
1359/// equal to the current `:versao` that it could then "upgrade *to*"
1360/// the current `:versao`. Two authoring footguns close here:
1361///
1362///   - `:from > :versao` (downgrade-shaped) — the canonical
1363///     "I copy-pasted from the next minor version and forgot to bump
1364///     `:versao`" / "I bumped `:versao` then reverted but left the
1365///     `:upgrade-from` entry behind" footgun. Until this gate landed
1366///     `(defcaixa :versao "0.1.5" :upgrade-from ((:from "0.2.0" …)))`
1367///     silently passed `feira build` and the wasm-operator's
1368///     `:from`-match dispatch would never fire on the entry — the
1369///     instructions sat dormant in the caixa.lisp forever, the
1370///     author's intent ("upgrade users coming from 0.2.0") permanently
1371///     unreached because they actually meant to bump `:versao`.
1372///
1373///   - `:from == :versao` (precedence-equal self-upgrade) — the
1374///     "I declared an upgrade from myself to myself" no-op the
1375///     operator's dispatch would either skip silently (no semantic
1376///     transition) or attempt and trivially "succeed" with no
1377///     observable state change. Includes the build-metadata-only
1378///     difference case (`:versao "0.2.0"`, `:from "0.2.0+build.1"`):
1379///     SemVer-2 precedence ignores build metadata so they compare
1380///     equal under [`semver::Version::cmp`] — the gate rejects this
1381///     even though [`UpgradeError::DuplicateFrom`] doesn't (the peer
1382///     gate uses derived `PartialEq` which keeps them distinct;
1383///     they're distinct dispatch keys but the same "from" version
1384///     for our purposes here).
1385///
1386/// Same cross-slot value-shape discipline as
1387/// [`crate::AplicacaoSpec::validate_placement`]'s strategy ↔ shard-key
1388/// partition (934bc58 — the typed partition between two declared
1389/// slots): one slot's value constrains the valid set of another's,
1390/// and the constraint is a structural property visible at validate
1391/// time. The validated set after this gate satisfies
1392/// `entry.from.parse::<Version>().unwrap() < versao.parse::<Version>().unwrap()`
1393/// for every entry, so the future operator-side hot-upgrade dispatch
1394/// step can reach for `entry.from` knowing the precedence relation
1395/// holds without re-deriving it from inline checks.
1396///
1397/// Silent-pass semantics on malformed inputs:
1398///
1399///   - When `versao` itself doesn't parse as semver, this gate
1400///     returns `Ok(())` silently — the narrower
1401///     [`crate::ManifestError::VersaoInvalid`] / [`UpgradeError::FromInvalid`]
1402///     diagnostics are the load-bearing surfaces for those failure
1403///     modes, and surfacing a `FromNotBeforeVersao` over an
1404///     unparseable `:versao` would mask the more actionable root
1405///     cause.
1406///   - Likewise, an entry whose `:from` itself doesn't parse falls
1407///     through to its narrower diagnostic surface
1408///     ([`UpgradeError::FromInvalid`]), which is expected to fire
1409///     via [`validate_upgrade_from`] *before* this gate runs at the
1410///     [`crate::LayoutInvariants`] call site.
1411///
1412/// [semver-11]: https://semver.org/#spec-item-11
1413pub fn validate_upgrade_from_against_versao(
1414    entries: &[UpgradeFromEntry],
1415    versao: &str,
1416) -> Result<(), UpgradeError> {
1417    use semver::Version;
1418    let Ok(current) = Version::parse(versao) else {
1419        // Malformed `:versao` is a separate gate (ManifestError::VersaoInvalid);
1420        // surfacing a precedence-relation diagnostic over an unparseable
1421        // top-level version would mask the more actionable root cause.
1422        return Ok(());
1423    };
1424    for entry in entries {
1425        // Per-entry shape — including a malformed `:from` — is gated
1426        // by [`validate_upgrade_from`] / [`UpgradeFromEntry::validate`]
1427        // upstream at the LayoutInvariants call site; an unparseable
1428        // `:from` here falls through silently to keep the
1429        // FromInvalid diagnostic load-bearing. Same fall-through
1430        // posture as the `versao` arm above.
1431        let Ok(prior) = Version::parse(entry.prior_versao()) else {
1432            continue;
1433        };
1434        if prior >= current {
1435            return Err(UpgradeError::from_not_before_versao(
1436                entry.prior_versao(),
1437                versao,
1438            ));
1439        }
1440    }
1441    Ok(())
1442}
1443
1444/// Reject `:upgrade-from` entries whose `:instructions` list carries any
1445/// `(:state-change <script>)` instruction unless the caixa also declares
1446/// `:behavior :on-state-change` — the runtime callback the per-version
1447/// migration script is delivered through during hot upgrade.
1448///
1449/// The module doc on [`crate::upgrade`] pins the composition verbatim:
1450/// the `:upgrade-from` slot "Composes with the `:behavior :on-state-change`
1451/// callback to deliver state migration during hot upgrades." The peer
1452/// module doc on [`crate::BehaviorSpec::on_state_change`] mirrors the
1453/// promise from the callback side: the slot is the
1454/// `gen_server:code_change/3` analog — "receives old state + version,
1455/// returns new state. Composes with the `:upgrade-from` slot declared at
1456/// the Caixa root." OTP's `release_handler:install_release/1` realizes
1457/// the composition by invoking the running `gen_server`'s
1458/// `code_change/3` callback during the appup's `code_change` /
1459/// `update, m, soft` step — the appup's instruction triggers the
1460/// callback, the callback folds the prior-version state shape into the
1461/// current-version shape, and the operator advances to the next
1462/// instruction only after the callback returns successfully. caixa
1463/// decomposes the same composition into two typed slots: the per-version
1464/// migration logic lives in the `(:state-change "lib/migrations/v01-to-v02.lisp")`
1465/// instruction's `:script` (the `:upgrade-from` author surface), and the
1466/// runtime hook the operator dispatches the migration through lives in
1467/// the `:behavior :on-state-change` callback (the `:behavior` author
1468/// surface). A `:state-change` instruction declared without the callback
1469/// is half the composition: the per-version script the author wrote has
1470/// no runtime delivery path, and the operator's hot-upgrade dispatch
1471/// reaches for `caixa.behavior.on_state_change` at the migration step,
1472/// finds `None`, and either fails the upgrade mid-flight (the
1473/// transactional rollback the module doc names — "On any failure, the
1474/// current version stays load-bearing — a typed atomic upgrade") or
1475/// silently skips the migration depending on the operator's handling of
1476/// a missing callback, both far from the source caixa.lisp.
1477///
1478/// Two authoring footguns close here:
1479///
1480///   - `(:behavior ((:on-init …)))` + `(:upgrade-from ((:from "0.1.0"
1481///     :instructions ((:load-module "x") (:state-change "lib/m.lisp")
1482///     (:soft-purge "x-old")))))` — the "I declared the migration script
1483///     but forgot the callback" footgun. The author wrote the per-version
1484///     fold against the prior state shape, the typed `:upgrade-from`
1485///     slot validated every per-instruction shape + ordering + singularity
1486///     gate, and the missing callback only surfaces at upgrade time as
1487///     either a transactional rollback to the prior version (no progress
1488///     across the upgrade) or as a silently-skipped migration that leaves
1489///     v0.2.0 code running against unmigrated v0.1.0 state (corrupted
1490///     state shape).
1491///   - `:behavior` absent entirely + `:upgrade-from` carrying any
1492///     `:state-change` — the "I added the upgrade path but never declared
1493///     `:behavior`" footgun. `:behavior` is optional at the typed root
1494///     ([`crate::Caixa::behavior: Option<BehaviorSpec>`]) so the typed
1495///     `:upgrade-from` slot validates on its own merits, but a `Caixa`
1496///     with `behavior: None` and a `:state-change` instruction is the
1497///     same missing-callback shape — the operator's dispatch can't reach
1498///     a callback that doesn't exist.
1499///
1500/// Same cross-slot composition discipline as
1501/// [`validate_upgrade_from_against_versao`] (the `:from` ↔ `:versao`
1502/// precedence gate at the peer wire-up site): one slot's value
1503/// (`:from` < `:versao` there; `:state-change` declared here) constrains
1504/// the valid set of another's (the entry must be dispatchable there; the
1505/// callback must be declared here), and the constraint is a structural
1506/// property visible at validate time. The validated set after this gate
1507/// satisfies the documented composition: every `:state-change`
1508/// instruction the operator iterates at hot-upgrade time has a
1509/// corresponding `:on-state-change` callback declared on the same caixa,
1510/// so the future wasm-operator's hot-upgrade dispatch (the OTP
1511/// `release_handler` canonical-sequence loop) can reach for
1512/// `behavior.on_state_change` at the migration step knowing the
1513/// `Option<PathBuf>` is `Some(_)` without re-deriving the precondition
1514/// from inline checks.
1515///
1516/// Diagnostic-precedence:
1517///
1518///   - Runs *after* [`UpgradeFromEntry::validate`] (per-instruction
1519///     shape + the within-entry ordering / singularity gates) and
1520///     [`validate_upgrade_from`] (the cross-entry duplicate-`:from`
1521///     gate), so a malformed `:state-change` (`EmptyScript`,
1522///     `AbsoluteScript`, `ParentEscapeScript`) or an ill-ordered entry
1523///     (`StateChangeWithoutPriorLoad`, `StateChangeAfterCleanup`) or a
1524///     duplicate `:from` (`DuplicateFrom`) surfaces its narrower
1525///     self-locating diagnostic first — the canonical "per-instr-shape +
1526///     within-entry ordering + cross-entry uniqueness before
1527///     cross-slot composition" precedence the peer
1528///     `validate_upgrade_from_against_versao` gate establishes at the
1529///     same wire-up site. Without this precedence pin a malformed
1530///     `:state-change` instruction would surface this gate's
1531///     missing-callback diagnostic over the narrower
1532///     `EmptyScript` / `StateChangeWithoutPriorLoad`, masking the
1533///     load-bearing per-instruction defect with a cross-slot composition
1534///     diagnostic.
1535///   - Within the entries, walks the list in declaration order and
1536///     surfaces the *first* `:state-change` instruction encountered —
1537///     mirrors every peer first-collision diagnostic posture on this
1538///     module (`validate_state_change_ordering` returns on the first
1539///     `StateChange` without prior load,
1540///     `validate_load_singularity` returns on the second matching
1541///     module, etc.). A future entry's later `:state-change` doesn't
1542///     surface a different diagnostic — the missing callback is the same
1543///     defect regardless of which entry's `:state-change` exposes it.
1544///
1545/// Silent-pass semantics:
1546///
1547///   - Entries carrying no `:state-change` instruction (load-only,
1548///     cleanup-only, restart-only, or empty `:instructions`) leave the
1549///     gate vacuous — no per-version migration means no callback to
1550///     dispatch through, so the absence of `:on-state-change` is
1551///     coherent. Pins the gate's identity element on the empty-set side
1552///     of the composition.
1553///   - `behavior: None` is *not* a free pass when a `:state-change`
1554///     instruction is present — the same missing-callback shape as
1555///     `behavior: Some(_)` with `on_state_change: None`. The gate reads
1556///     `behavior.and_then(BehaviorSpec::on_state_change)` so both shapes
1557///     surface the same diagnostic.
1558pub fn validate_upgrade_from_against_behavior(
1559    entries: &[UpgradeFromEntry],
1560    behavior: Option<&crate::BehaviorSpec>,
1561) -> Result<(), UpgradeError> {
1562    if behavior
1563        .and_then(crate::BehaviorSpec::on_state_change)
1564        .is_some()
1565    {
1566        return Ok(());
1567    }
1568    for entry in entries {
1569        // Route the per-instruction `StateChange`-arm script-path
1570        // projection through the sibling lifted
1571        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
1572        // accessor rather than the raw
1573        // `if let UpgradeInstruction::StateChange { script } = instr`
1574        // open-coded pattern-match — the cross-slot
1575        // `:upgrade-from ↔ :behavior` composition gate's per-instruction
1576        // script-projection site now keys off exactly one typed dispatch
1577        // on the substrate primitive's `PathBuf`-carrying axis, sibling
1578        // to the four peer per-`UpgradeInstruction` consumers
1579        // ([`UpgradeInstruction::validate`]'s per-`StateChange`
1580        // sandbox-path fan-out, the layout-side per-`StateChange`
1581        // script-existence fan-out at
1582        // [`crate::layout::StandardLayout::verify`] (caixa-core/src/layout.rs:1058),
1583        // the within-entry [`UpgradeFromEntry::validate_state_change_singularity`]
1584        // (2bf3ce5) per-`StateChange` script-projection fan-out, the
1585        // peer [`UpgradeInstruction::declared_module`] `String`-axis
1586        // per-variant unifier) that already route through
1587        // `declared_path` / `declared_module`. Byte-equal today
1588        // (`declared_path` returns `Some(script)` iff the instruction is
1589        // [`UpgradeInstruction::StateChange`], per the sibling
1590        // `declared_path_only_for_state_change` pin), so a
1591        // `:state-change`-without-`:on-state-change`-callback
1592        // composition surfaces `StateChangeWithoutOnStateChangeCallback`
1593        // byte-identical to the pattern-match shape. Fourth (and last)
1594        // per-`UpgradeInstruction`-consumer of the `PathBuf`-carrying
1595        // axis now routed through the accessor — closes the last
1596        // unlifted `if let UpgradeInstruction::StateChange { script } = instr`
1597        // site outside `impl UpgradeFromEntry`, so the peer four
1598        // consumer set named in the sibling
1599        // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
1600        // pin (caixa-core/src/upgrade.rs:4598) is now structurally
1601        // closed.
1602        for instr in entry.instructions() {
1603            if let Some(script) = instr.declared_path() {
1604                return Err(UpgradeError::state_change_without_on_state_change_callback(
1605                    entry.prior_versao(),
1606                    script,
1607                ));
1608            }
1609        }
1610    }
1611    Ok(())
1612}
1613
1614impl UpgradeInstruction {
1615    /// Kebab-case lisp form name for this instruction, used as the
1616    /// `:kind` tag in [`UpgradeError::ModuleEmpty`] /
1617    /// [`UpgradeError::ModuleInvalid`] diagnostics so the author can
1618    /// grep their caixa.lisp for `(:load-module …)` / `(:soft-purge …)`
1619    /// / `(:purge …)` and fix it in one edit. Mirrors the kebab-case
1620    /// slot tags `BehaviorError::EmptyPath` (b0c8389) and
1621    /// `UpgradeFromEntry`'s `:from` field already carry.
1622    #[must_use]
1623    const fn lisp_form(&self) -> &'static str {
1624        match self {
1625            Self::LoadModule { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
1626            Self::StateChange { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
1627            Self::SoftPurge { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
1628            Self::Purge { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
1629            Self::Restart => crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
1630        }
1631    }
1632
1633    /// Validate the instruction's typed shape. Path existence is
1634    /// checked separately by [`crate::layout::StandardLayout`].
1635    ///
1636    /// The per-variant scalar the value-shape gates fire against is
1637    /// read through this method's two sibling accessors — the
1638    /// `String`-carrying axis via [`Self::declared_module`] (the
1639    /// `LoadModule` / `SoftPurge` / `Purge` variants unifying on their
1640    /// K8s DNS-1123-label `:module` reference) and the `PathBuf`-
1641    /// carrying axis via [`Self::declared_path`] (the `StateChange`
1642    /// variant's tatara-lisp `:script`) — rather than the per-arm
1643    /// `Self::LoadModule { module } | Self::SoftPurge { module } |
1644    /// Self::Purge { module }` pattern the module-axis previously
1645    /// open-coded and the per-arm `Self::StateChange { script }` the
1646    /// script-axis previously open-coded. Every scalar this enum
1647    /// carries now flows through one of the two `Option<&…>`
1648    /// accessors, so a future extension of either axis (a fifth
1649    /// module-bearing variant, an operator-side pre-parsed scalar
1650    /// cache the accessors materialize behind the same return
1651    /// contract, an M4 typed sub-slot the accessors could route
1652    /// alongside the existing scalar) migrates as a single edit on
1653    /// the accessor rather than a coordinated rewrite of every
1654    /// downstream value-shape gate. `Restart` (the only variant that
1655    /// carries neither scalar) falls through both `Option` checks and
1656    /// returns `Ok(())` — the terminal-fallback shape the
1657    /// [`Self::Restart`] variant doc pins.
1658    pub fn validate(&self) -> Result<(), UpgradeError> {
1659        if let Some(module) = self.declared_module() {
1660            return validate_module(self.lisp_form(), module);
1661        }
1662        if let Some(script) = self.declared_path() {
1663            // Delegate the four-arm cascade (empty / absolute /
1664            // parent-escape / non-`.lisp`-extension) to the lifted
1665            // [`crate::render::require_sandboxed_lisp_path`] helper —
1666            // same `Empty → Absolute → ParentEscape → NonLispExtension`
1667            // arm-ordering this method previously inlined verbatim,
1668            // now shared with [`crate::BehaviorSpec::validate`]'s
1669            // per-`:on-*`-callback gate so every author-supplied
1670            // tatara-lisp source path on every M2 typed slot consults
1671            // one gate, not two-and-counting verbatim copies of the
1672            // same four-arm cascade. Each closure wraps the tag in
1673            // the same `*Script` variant the original inline code
1674            // raised, so the diagnostic shape every caller depends
1675            // on (the `:state-change :script` self-locating error)
1676            // is preserved by construction. See
1677            // [`crate::render::require_sandboxed_lisp_path`] for the
1678            // smallest-scope-arm-fires-last ordering rationale.
1679            crate::render::require_sandboxed_lisp_path(
1680                script,
1681                || UpgradeError::EmptyScript,
1682                || UpgradeError::absolute_script(script),
1683                || UpgradeError::parent_escape_script(script),
1684                || UpgradeError::non_lisp_extension_script(script),
1685            )?;
1686        }
1687        // `Restart` (the only variant with no `Option<&…>`-carrying
1688        // scalar) falls through both accessor gates and returns
1689        // `Ok(())` — the terminal-fallback shape.
1690        Ok(())
1691    }
1692
1693    /// The `:module` scalar carried by this instruction — the
1694    /// K8s DNS-1123-label OTP-appup caixa-name reference every
1695    /// [`Self::LoadModule`] / [`Self::SoftPurge`] / [`Self::Purge`]
1696    /// variant declares against, and every author expects `feira lint`
1697    /// to name verbatim in per-instruction diagnostics. Returns `None`
1698    /// on [`Self::StateChange`] (which carries a `:script` — closed by
1699    /// the sibling [`Self::declared_path`]) and on [`Self::Restart`]
1700    /// (which carries no data at all, the OTP terminal-fallback
1701    /// shape).
1702    ///
1703    /// Sibling in shape to [`Self::declared_path`] on the second and
1704    /// final scalar-carrying axis of [`UpgradeInstruction`]:
1705    /// `declared_path` closes the `PathBuf`-carrying arm
1706    /// (`StateChange`); `declared_module` closes the `String`-carrying
1707    /// arms (`LoadModule` / `SoftPurge` / `Purge`). Every scalar the
1708    /// enum carries now routes through one of the two `Option<&…>`
1709    /// accessors — a caller that doesn't care which variant declared
1710    /// the scalar reads through one `if let Some(…)` rather than a
1711    /// per-variant pattern match. The pair is the enum-variant-
1712    /// unifying peer of the per-mesh-slot-atom scalar-accessor family
1713    /// on the M3 side ([`crate::WitContract::source`] /
1714    /// [`crate::WitContract::destination`] /
1715    /// [`crate::WitContract::world_ref`] closing `:contratos`;
1716    /// [`crate::Entrada::hostname`] / [`crate::Entrada::destination`]
1717    /// closing `:entrada`; [`crate::Membro::nome`] /
1718    /// [`crate::Membro::versao_requirement`] closing `:membros`) and
1719    /// on the M2 side ([`crate::UpgradeFromEntry::prior_versao`]
1720    /// closing per-entry `:from`; the [`crate::LimitsSpec`] /
1721    /// [`crate::BehaviorSpec`] closed families; the [`crate::ChildSpec`]
1722    /// closed OTP-shape supervisor family) — those peer accessors
1723    /// return a struct field verbatim; this pair unifies enum-
1724    /// variant-carried scalars into one accessor per typed axis.
1725    ///
1726    /// Byte-for-byte from the typed variant's own `String` storage;
1727    /// no cloning, no re-parsing. A future extension of the axis (an
1728    /// M4 typed sub-slot the module string is derived from, an
1729    /// operator-side pre-parsed caixa-name cache the accessor could
1730    /// materialize behind the same `&str` return contract, a fifth
1731    /// module-bearing OTP-appup variant the enum grows) migrates as
1732    /// a single caixa-core edit rather than a coordinated rewrite
1733    /// of every downstream module-axis consumer (currently
1734    /// [`Self::validate`]'s DNS-1123-label gate through
1735    /// [`validate_module`]; extensible to future consumers on the
1736    /// same axis without further per-variant match sites).
1737    #[must_use]
1738    pub const fn declared_module(&self) -> Option<&str> {
1739        match self {
1740            Self::LoadModule { module } | Self::SoftPurge { module } | Self::Purge { module } => {
1741                Some(module.as_str())
1742            }
1743            Self::StateChange { .. } | Self::Restart => None,
1744        }
1745    }
1746
1747    /// If the instruction references an on-disk path, return it —
1748    /// used by the layout checker to verify the path resolves.
1749    ///
1750    /// Sibling on the `PathBuf`-carrying axis to [`Self::declared_module`]
1751    /// on the `String`-carrying axis: `declared_path` closes the
1752    /// `StateChange` arm's `:script`; `declared_module` closes the
1753    /// `LoadModule` / `SoftPurge` / `Purge` arms' `:module`. Together
1754    /// they route every scalar this enum carries through one of two
1755    /// `Option<&…>` accessors, so [`Self::validate`]'s value-shape
1756    /// gates dispatch on the accessor return rather than a per-variant
1757    /// pattern match on the enum shape itself.
1758    ///
1759    /// Four per-`UpgradeInstruction` consumers now key off this
1760    /// accessor's `PathBuf`-carrying axis:
1761    /// [`Self::validate`]'s per-`StateChange` sandbox-path fan-out,
1762    /// [`crate::layout::StandardLayout::verify`]'s per-`StateChange`
1763    /// script-existence fan-out at `caixa-core/src/layout.rs:1058`, the
1764    /// within-entry
1765    /// [`UpgradeFromEntry::validate_state_change_singularity`] (2bf3ce5)
1766    /// per-`StateChange` script-projection fan-out, and the cross-slot
1767    /// [`validate_upgrade_from_against_behavior`] `:upgrade-from ↔
1768    /// :behavior` composition gate's per-`StateChange` detection loop
1769    /// — every downstream consumer of the `PathBuf`-carrying axis
1770    /// reaches through this one dispatch, so a future accessor
1771    /// extension (an M4 typed sub-slot the script path is derived from,
1772    /// an operator-side pre-resolved-path cache the accessor
1773    /// materializes behind the same `Option<&PathBuf>` return contract,
1774    /// a fifth `PathBuf`-bearing OTP-appup variant the enum grows)
1775    /// migrates as a single caixa-core edit rather than a coordinated
1776    /// rewrite of four call sites.
1777    #[must_use]
1778    pub const fn declared_path(&self) -> Option<&PathBuf> {
1779        match self {
1780            Self::StateChange { script } => Some(script),
1781            _ => None,
1782        }
1783    }
1784
1785    /// Substrate-canonical per-`UpgradeInstruction` OTP-appup cleanup-
1786    /// family arm-discriminator predicate every within-entry cross-
1787    /// instruction cleanup-facing gate keys off — true iff `self` is
1788    /// [`Self::SoftPurge`] (`code:soft_purge/1` analog: drain the
1789    /// named module until no process is running it, then GC) or
1790    /// [`Self::Purge`] (`code:purge/1` analog: discard the named
1791    /// module immediately, without waiting for drain), the two OTP
1792    /// two-phase-code-load cleanup arms the closed-set enum's
1793    /// non-terminal / non-migration / non-load variants exhaust.
1794    /// Every non-cleanup arm ([`Self::LoadModule`] on the paired
1795    /// two-phase-load half, [`Self::StateChange`] on the
1796    /// `gen_server:code_change/3`-analog migration axis,
1797    /// [`Self::Restart`] on the OTP terminal-fallback shape)
1798    /// returns `false`.
1799    ///
1800    /// Prior to this lift the `Self::SoftPurge { module } |
1801    /// Self::Purge { module }` two-arm cleanup-family pattern-
1802    /// match sat inline at three within-entry cross-instruction
1803    /// gate sites, each hand-rolling its own copy of the union
1804    /// with no compile-time link back to the substrate primitive's
1805    /// closed-set arm-family: [`UpgradeFromEntry::validate_purge_ordering`]
1806    /// at caixa-core/src/upgrade.rs:570 (guarded arm firing
1807    /// [`UpgradeError::PurgeWithoutPriorLoad`] on any cleanup
1808    /// arriving before a preceding [`Self::LoadModule`]),
1809    /// [`UpgradeFromEntry::validate_state_change_before_cleanup`]
1810    /// at caixa-core/src/upgrade.rs:689 (sticky-once latch
1811    /// recording the first-encountered cleanup so a subsequent
1812    /// [`Self::StateChange`] fires [`UpgradeError::StateChangeAfterCleanup`]),
1813    /// and [`UpgradeFromEntry::validate_cleanup_singularity`] at
1814    /// caixa-core/src/upgrade.rs:800 (per-module cleanup-target
1815    /// dedup ejecting [`UpgradeError::DuplicateCleanup`] on the
1816    /// second cleanup targeting the same `:module`). Three open-
1817    /// coded per-arm-union pattern-matches that expressed no
1818    /// compile-time link back to the substrate primitive. A future
1819    /// fifth cleanup-shaped variant (a `Discard` variant the
1820    /// `code:delete/1` peer inspires that folds under the same
1821    /// two-phase-load cleanup partition, an M4 `SoftPurge` split
1822    /// into `SoftPurgeCoop` / `SoftPurgeForce` peers as the drain-
1823    /// cool-down policy grows a two-arm shape, an operator-side
1824    /// pre-resolved cleanup-decision cache the predicate could
1825    /// route through the same `bool` return contract) would have
1826    /// had to be threaded through every open-coded per-arm-union
1827    /// pattern-match in lockstep or one gate would silently
1828    /// classify the new arm outside the cleanup family while the
1829    /// peer gates classified it in (or vice versa) — a
1830    /// classification split across the three within-entry cross-
1831    /// instruction gates at build time that lands far from the
1832    /// source [`UpgradeInstruction`] declaration with no field
1833    /// naming which gate carries the drifted arm-set. Lifting the
1834    /// resolution to a typed predicate on the substrate primitive
1835    /// means every downstream cleanup-facing consumer of the
1836    /// [`UpgradeInstruction`] closed-set enum reaches for exactly
1837    /// one typed dispatch — the resolver's arm-set migrates as a
1838    /// unit on any future arm addition composing under this
1839    /// predicate's `||` chain.
1840    ///
1841    /// Sibling in shape to the peer [`gen_platform::IsVariant`]-
1842    /// derive-generated [`Self::is_restart`] terminal-fallback
1843    /// arm-discriminator predicate on the same closed-set
1844    /// [`UpgradeInstruction`] enum (each names an OTP-appup arm-
1845    /// family partition as one typed dispatch on the substrate
1846    /// primitive; `is_restart` on the single-arm terminal-
1847    /// fallback family, `is_cleanup` on the two-arm cleanup
1848    /// family), extended here from the single-arm case onto the
1849    /// two-arm arm-family union case. Composes through the
1850    /// [`gen_platform::IsVariant`]-derive-generated
1851    /// [`Self::is_soft_purge`] / [`Self::is_purge`] per-variant
1852    /// predicates rather than an open-coded raw `matches!`
1853    /// pattern-match, so a future rebrand on either underlying
1854    /// per-arm classifier flows through this predicate's one
1855    /// body without a coordinated per-consumer rewrite across
1856    /// the three within-entry cross-instruction gates that route
1857    /// through it. Peer of the sibling per-`:contratos`
1858    /// shape-family union predicates [`crate::WitContract::is_http`] /
1859    /// [`crate::WitContract::is_pubsub`] / [`crate::WitContract::is_store`]
1860    /// on the M3 mesh-slot per-`:wit` world-ref axis (each unions a
1861    /// per-shape WIT-prefix rule the substrate primitive's arm-
1862    /// family partition names as one typed dispatch) — the same
1863    /// "one typed dispatch on the substrate primitive, thin
1864    /// projections at each consumer" discipline extended onto the
1865    /// M2 `:upgrade-from :instructions` per-`UpgradeInstruction`
1866    /// cleanup-family axis.
1867    ///
1868    /// The name `is_cleanup` maps directly onto the canonical
1869    /// OTP-appup vocabulary (INSPIRATIONS §II.4 verbatim: "2.
1870    /// `code:soft_purge/1` — wait until no process is running v1,
1871    /// then discard. (`code:purge/1` kills v1 immediately if you
1872    /// don't care.)" — the two `code:*_purge/1` operations are
1873    /// the two-phase-load contract's cleanup half, paired under
1874    /// one concept), and the peer [`Self::validate_cleanup_singularity`]
1875    /// / [`UpgradeError::DuplicateCleanup`] / [`UpgradeError::PurgeWithoutPriorLoad`]
1876    /// / [`UpgradeError::StateChangeAfterCleanup`] surface already
1877    /// reaches for the same "cleanup" vocabulary in identifier +
1878    /// diagnostic form.
1879    #[must_use]
1880    pub const fn is_cleanup(&self) -> bool {
1881        self.is_soft_purge() || self.is_purge()
1882    }
1883}
1884
1885/// Reject upgrade instruction `:module` values that aren't K8s
1886/// DNS-1123 labels. Thin wrapper around
1887/// [`crate::render::is_dns_1123_label`] that maps the shared
1888/// parser-shaped reason into the kind-tagged
1889/// [`UpgradeError::ModuleEmpty`] / [`UpgradeError::ModuleInvalid`]
1890/// diagnostics, so the author can grep their caixa.lisp for the
1891/// offending `(:<kind> <module>)` form and fix it in one edit.
1892///
1893/// The contract — the same DNS-1123 label rule the K8s apiserver
1894/// enforces on every `metadata.name` / Service name / label value the
1895/// module name lands in. Each upgrade instruction's `:module` is a
1896/// reference to a caixa name (the wasm-engine resolves it through the
1897/// same `ComputeUnit` registry the operator manages), so the value must
1898/// match every downstream apiserver-side schema: the per-Servico
1899/// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` the operator
1900/// creates, the `LABEL_PROGRAM` label value the wasm-engine matches
1901/// against the loaded-module table at hot-upgrade dispatch, and the
1902/// future `:upgrade-from`-driven `app-operator` rolling-load CR's
1903/// per-module reference axis. Same trajectory as `:children :caixa`
1904/// (31bfa43), `:membros :caixa` (3f9d7a0), and `:placement :clusters`
1905/// (6cbb900) onto the fourth DNS-1123-label-shaped identifier axis —
1906/// appup's `LoadModule | SoftPurge | Purge` `:module` references.
1907///
1908/// Empty input is rejected via the narrower [`UpgradeError::ModuleEmpty`]
1909/// variant before this predicate is consulted, mirroring
1910/// `validate_membro_caixa`'s empty-first cascade.
1911fn validate_module(kind: &'static str, module: &str) -> Result<(), UpgradeError> {
1912    // Routes through the shared
1913    // [`crate::render::require_valid_dns_1123_label`] gate the peer
1914    // name axes each land on. The `kind: &'static str` field flows
1915    // through both error variants so the diagnostic names which
1916    // per-instruction slot (`LoadModule` / `SoftPurge` / `Purge`) the
1917    // offending value came from.
1918    crate::render::require_valid_dns_1123_label(
1919        module,
1920        || UpgradeError::ModuleEmpty { kind },
1921        |reason| UpgradeError::module_invalid(kind, module, reason),
1922    )
1923}
1924
1925#[derive(Debug, Error, PartialEq, Eq)]
1926pub enum UpgradeError {
1927    #[error(
1928        ":upgrade-from :from {from:?} is not a valid SemVer-2 version: {reason} (the substrate \
1929         consumes this string as `semver::Version` — three-part `MAJOR.MINOR.PATCH` with optional \
1930         `-prerelease` and `+build`, the same shape every top-level `:versao` carries — across \
1931         every artifact derived from `:from`: the wasm-operator's `:from`-match dispatch loads \
1932         the running version through `semver::Version::parse` and matches it against each entry's \
1933         `:from`, so a malformed `:from` is structurally unreachable at dispatch time; use a \
1934         SemVer-2 literal like `\"0.1.0\"`, `\"0.2.0-rc.1\"`, or `\"1.0.0+build.42\"` — not a \
1935         git-tag-shape like `\"v0.1.0\"`, a docker-tag-shape like `\"latest\"`, a \
1936         requirement-shape like `\"^0.1\"`, or a four-part `\"0.1.0.0\"`)"
1937    )]
1938    FromInvalid { from: String, reason: String },
1939    #[error(
1940        "upgrade instruction `{kind}` :module is empty (every appup module reference \
1941         must name a caixa; use a non-empty caixa name like `\"hello-rio\"` or omit \
1942         the instruction entirely)"
1943    )]
1944    ModuleEmpty { kind: &'static str },
1945    #[error(
1946        "upgrade instruction `{kind}` :module {module:?} is not a valid DNS-1123 label: \
1947         {reason} (every appup module reference resolves to a caixa name, which lands \
1948         verbatim as a K8s `metadata.name` on the per-Servico ComputeUnit the operator \
1949         creates, the `LABEL_PROGRAM` label value the wasm-engine matches at hot-upgrade \
1950         dispatch, and every future `app-operator` rolling-load CR's per-module reference \
1951         axis; use a lowercase alphanumeric + hyphen identifier like `\"hello-rio\"` or \
1952         `\"cache-v2\"`)"
1953    )]
1954    ModuleInvalid {
1955        kind: &'static str,
1956        module: String,
1957        reason: String,
1958    },
1959    #[error("instruction's :script is empty")]
1960    EmptyScript,
1961    #[error(
1962        "instruction's :script {} is absolute — upgrade scripts must be relative to the caixa \
1963         root (Path::join would otherwise escape the project sandbox)",
1964        script.display()
1965    )]
1966    AbsoluteScript { script: PathBuf },
1967    #[error(
1968        "instruction's :script {} contains a `..` component — upgrade scripts must not traverse \
1969         above the caixa root",
1970        script.display()
1971    )]
1972    ParentEscapeScript { script: PathBuf },
1973    #[error(
1974        ":upgrade-from (:state-change {}) does not terminate in the `.lisp` extension — the M2.5 \
1975         wasm-engine instantiator reads every migration script as tatara-lisp source through \
1976         `tatara_lisp::read` at hot-upgrade migration time (the same downstream consumer the \
1977         peer `:behavior :on-*` axis routes through at instance-start time, c97815a), so any \
1978         other extension (`.txt`, `.rs`, `.lisp.bak`) or no-extension shape is structurally a \
1979         parser error far from the source caixa.lisp, with no field naming the offending \
1980         `(:state-change …)` instruction. Pin a relative path under the caixa root whose \
1981         terminating extension is lowercase-`.lisp` (e.g. `\"lib/migrations.lisp\"`, \
1982         `\"lib/migrations/v01-to-v02.lisp\"`).",
1983        script.display()
1984    )]
1985    NonLispExtensionScript { script: PathBuf },
1986    #[error(
1987        ":upgrade-from carries more than one `(:from {from:?})` entry — OTP appup picks at most \
1988         one matching block per running version (`release_handler:install_release/1` dispatches \
1989         on the loaded `:from` against the currently-running release), so two entries with the \
1990         same parsed semver are an ambiguous edge in the typed upgrade graph (the operator would \
1991         pick either set non-deterministically). Author one path per prior version; if two \
1992         distinct instruction sequences are needed, fold them into one ordered list under the \
1993         single matching `(:from {from:?} :instructions (…))` block."
1994    )]
1995    DuplicateFrom { from: String },
1996    #[error(
1997        ":upgrade-from `(:from {from:?})` is not strictly less than the caixa's current \
1998         `:versao {versao:?}` under SemVer-2 precedence — an upgrade block whose `:from` is \
1999         greater than or equal to the caixa's own version is structurally unreachable \
2000         (the wasm-operator's `:from`-match dispatch loads the current `:versao` and matches \
2001         the running version against each entry's `:from`; an entry whose `:from >= :versao` \
2002         is never reached because the operator never runs a version greater than or equal to \
2003         the current one that it could then upgrade *to* the current one). Bump the caixa's \
2004         `:versao` past {from:?} (the typical fix — you added the entry intending to upgrade \
2005         *to* a new version but forgot to bump `:versao`), drop the entry (if it's a stale \
2006         reference left over from a reverted `:versao` bump), or correct `:from` to a prior \
2007         version (if it's a typo). Pre-release values like `\"0.2.0-rc.1\"` are strictly less \
2008         than the corresponding release `\"0.2.0\"` under SemVer §11 precedence; build-metadata \
2009         values like `\"0.2.0+build.1\"` are equal to `\"0.2.0\"` under precedence and rejected \
2010         here as a self-upgrade no-op."
2011    )]
2012    FromNotBeforeVersao { from: String, versao: String },
2013    #[error(
2014        ":upgrade-from `(:from {from:?})` :instructions list violates the `(:restart)` \
2015         exclusivity invariant — an entry containing `(:restart)` must contain exactly one \
2016         `(:restart)` and nothing else (found {restart_count} `(:restart)` plus other \
2017         instruction(s): {other_kinds:?}). Per the UpgradeInstruction::Restart doc comment, \
2018         `(:restart)` is the fallback for an entry whose typed upgrade is impossible (wasm \
2019         component-model world incompatibility, irreversible state shape change), and the \
2020         fallback is terminal by construction (the operator restarts the pod and the new \
2021         version comes up fresh). Mixing the fallback with the typed sequence is dead code \
2022         in both directions: if the typed instructions would succeed, `(:restart)` is \
2023         unreached; if they wouldn't, the typed instructions are dead because the operator \
2024         restarts anyway. Author *either* a typed sequence (`(:load-module …) \
2025         (:state-change …) (:soft-purge …)`) *or* a single `((:restart))` — never both, \
2026         never repeated. If two distinct upgrade strategies are needed for the same prior \
2027         version, that is itself a typed-graph ambiguity (the operator's `:from`-match \
2028         dispatch picks exactly one block per running version) — keep the typed sequence; \
2029         the fallback restart is what the operator does on any typed-sequence failure \
2030         already."
2031    )]
2032    RestartNotExclusive {
2033        from: String,
2034        restart_count: usize,
2035        other_kinds: Vec<&'static str>,
2036    },
2037    #[error(
2038        ":upgrade-from `(:from {from:?})` runs `(:state-change {})` before any \
2039         `(:load-module …)` in its :instructions list — a state migration is the \
2040         gen_server:code_change/3 analog and must run in the context of the newly-loaded \
2041         code, but the operator executes instructions in declared order, so this migration \
2042         runs while the only resident version is still the prior one (which expects the \
2043         pre-migration state shape). Load the new module first: author the canonical \
2044         `(:load-module …) (:state-change {}) (:soft-purge …)` order so the new code is \
2045         resident before its state migration runs.",
2046        script.display(),
2047        script.display()
2048    )]
2049    StateChangeWithoutPriorLoad { from: String, script: PathBuf },
2050    #[error(
2051        ":upgrade-from `(:from {from:?})` runs `({kind} {module:?})` before any \
2052         `(:load-module …)` in its :instructions list — `:soft-purge` and `:purge` are the \
2053         code:soft_purge/1 / code:purge/1 analogs and must run after the new code is \
2054         resident alongside the old (OTP's two-phase code load: `code:load_module/1` \
2055         then `code:soft_purge/1`), but the operator executes instructions in declared \
2056         order, so this cleanup runs while the only resident version is still the same \
2057         old code (`:soft-purge` drains it to nothing; `:purge` discards it outright \
2058         mid-request), leaving no replacement to route in-flight or future requests \
2059         to. Load the new module first: author the canonical `(:load-module …) \
2060         (:state-change …) ({kind} {module:?})` order so the new code is resident \
2061         before the old code is drained or discarded."
2062    )]
2063    PurgeWithoutPriorLoad {
2064        from: String,
2065        kind: &'static str,
2066        module: String,
2067    },
2068    #[error(
2069        ":upgrade-from `(:from {from:?})` :instructions list targets module {module:?} with \
2070         more than one cleanup instruction ({kinds:?}) — `:soft-purge` and `:purge` are the \
2071         code:soft_purge/1 / code:purge/1 analogs (INSPIRATIONS §II.4: \"`code:soft_purge/1` — \
2072         wait until no process is running v1, then discard. (`code:purge/1` kills v1 immediately \
2073         if you don't care.)\"), and each module's old version is cleaned up by exactly one of \
2074         them: either drain-then-discard (`:soft-purge`) or immediate-discard (`:purge`), never \
2075         both, never repeated. systools-generated `.relup` files emit at most one purge per \
2076         module for this reason. A second cleanup on the same module is at best redundant (the \
2077         module is already gone after the first cleanup, so the second is a no-op or undefined \
2078         depending on the operator's handling of a non-resident-module purge request) and at \
2079         worst incoherent (mixing drain and discard semantics on one module suggests the author \
2080         wanted a fallback, but the operator runs declared instructions unconditionally — \
2081         fallback on cleanup failure is the operator's job, not authored into the entry). \
2082         Author one cleanup per module: prefer `(:soft-purge {module:?})` (waits for in-flight \
2083         callers to drain before GC); fall back to `(:purge {module:?})` only when the drain \
2084         can't complete (cron / oneShot / stuck callers). If two distinct old versions need \
2085         cleanup, name them distinctly (e.g. `(:soft-purge {module:?}) (:soft-purge \"…-older\")`)."
2086    )]
2087    DuplicateCleanup {
2088        from: String,
2089        module: String,
2090        kinds: Vec<&'static str>,
2091    },
2092    #[error(
2093        ":upgrade-from `(:from {from:?})` :instructions list loads module {module:?} more than \
2094         once — `:load-module` is the code:load_module/1 analog (INSPIRATIONS §II.4: \"1. \
2095         `code:load_module/1` — load v2 alongside v1; new code is 'current', old code is \
2096         'old'.\"), and the instruction binds the named wasm component once: the operator's \
2097         dispatch table reads the module name and brings up the corresponding component \
2098         alongside the running version. systools-generated `.relup` files emit at most one \
2099         `load_module` per module per upgrade step for this reason. A second `(:load-module \
2100         {module:?})` instruction has no observable semantic relative to the first (the \
2101         component is already resident) — either dead code (copy-pasted load line) or a typo \
2102         masking a distinct module the author intended to load alongside (renamed both to \
2103         {module:?} by mistake), leaving the second module silently absent from the entry. \
2104         Author one `(:load-module {module:?})` per old module per entry; if two distinct old \
2105         versions need loading alongside the running one, name them distinctly (e.g. \
2106         `(:load-module {module:?}) (:load-module \"…-v2\")`)."
2107    )]
2108    DuplicateLoadModule { from: String, module: String },
2109    #[error(
2110        ":upgrade-from `(:from {from:?})` :instructions list runs state migration {} more than \
2111         once — `:state-change` is the gen_server:code_change/3 analog (INSPIRATIONS §II.4: \
2112         \"State migration uses gen_server:code_change/3\"), and the script folds the prior-version \
2113         state shape into the current-version shape: a one-shot transition, not a step that \
2114         composes with itself. systools-generated `.relup` files emit at most one `code_change` \
2115         per gen_server per upgrade step for this reason; OTP's release_handler invokes the \
2116         callback exactly once. A second `(:state-change {})` instruction re-runs the same fold on \
2117         the already-migrated state — at best a no-op (idempotent script masking a typo where the \
2118         author intended two distinct migration scripts) and at worst silent state corruption \
2119         (non-idempotent fold double-applied: an `add column` that runs twice, an `increment \
2120         counter` that double-bumps, a `rename field` that renames-then-fails the second time). \
2121         Author one `(:state-change {})` per migration script per entry; if two distinct state \
2122         transitions are needed (e.g. one module's schema *and* another module's projection), \
2123         name them distinctly (e.g. `(:state-change {}) (:state-change \"lib/migrations/v01-to-v02-projection.lisp\")`).",
2124        script.display(),
2125        script.display(),
2126        script.display(),
2127        script.display()
2128    )]
2129    DuplicateStateChange { from: String, script: PathBuf },
2130    #[error(
2131        ":upgrade-from `(:from {from:?})` runs `(:state-change {})` after `({prior_cleanup_kind} \
2132         {prior_cleanup_module:?})` in its :instructions list — `:state-change` is the \
2133         gen_server:code_change/3 analog and folds the prior-version state shape into the \
2134         current shape, but the prior version's state only exists while the prior code is \
2135         still resident; `:soft-purge` and `:purge` are the code:soft_purge/1 / code:purge/1 \
2136         analogs and drain or discard that prior code. The operator executes instructions in \
2137         declared order, so a cleanup ahead of a state-change has already drained the prior \
2138         module to nothing (`:soft-purge`) or discarded it mid-request (`:purge`) by the time \
2139         the migration script runs, leaving the script either no-op (no prior-version state \
2140         left to fold) or crashing (`code_change/3` invoked on an unloaded version). The OTP \
2141         canonical sequence is `code:load_module/1` → `gen_server:code_change/3` → \
2142         `code:soft_purge/1`; the appup cookbook's recommended pattern is `[{{load_module, m}}, \
2143         {{update, m, soft}}, {{soft_purge, m}}]` with the migration-triggering `update` \
2144         strictly between load and cleanup. Author the canonical `(:load-module …) \
2145         (:state-change {}) ({prior_cleanup_kind} {prior_cleanup_module:?})` order so the \
2146         migration runs against the prior-version state before the cleanup drains it.",
2147        script.display(),
2148        script.display()
2149    )]
2150    StateChangeAfterCleanup {
2151        from: String,
2152        script: PathBuf,
2153        prior_cleanup_kind: &'static str,
2154        prior_cleanup_module: String,
2155    },
2156    #[error(
2157        ":upgrade-from `(:from {from:?})` declares `(:state-change {})` but the caixa does not \
2158         declare `:behavior :on-state-change` — the per-version migration script is the \
2159         gen_server:code_change/3 analog and the runtime hook it is delivered through during \
2160         hot upgrade is the `:on-state-change` callback. OTP's release_handler:install_release/1 \
2161         realizes the composition by invoking the running gen_server's code_change/3 callback \
2162         during the appup's `code_change` / `update, m, soft` step; caixa decomposes the same \
2163         composition into two typed slots, the per-version migration logic in this \
2164         `(:state-change …)` instruction's `:script` and the runtime dispatch hook in the \
2165         `:behavior :on-state-change` callback (the upgrade.rs module doc pins the composition \
2166         verbatim: \"Composes with the `:behavior :on-state-change` callback to deliver state \
2167         migration during hot upgrades\"). The missing callback leaves the per-version script \
2168         with no runtime delivery path: the operator's hot-upgrade dispatch reaches for the \
2169         callback at the migration step, finds it absent, and either fails the upgrade \
2170         mid-flight (the transactional rollback the module doc names — \"On any failure, the \
2171         current version stays load-bearing\") or silently skips the migration leaving the \
2172         new code running against unmigrated prior-version state. Add the callback: \
2173         `(:behavior ((:on-state-change \"lib/migrations.lisp\") …))` (the runtime delivery \
2174         path) alongside the existing `(:state-change {})` instruction (the per-version \
2175         script). If the upgrade truly carries no state migration, drop the `(:state-change \
2176         …)` instruction from the entry (a metadata-only upgrade — load + cleanup, no \
2177         migration — is the canonical shape).",
2178        script.display(),
2179        script.display()
2180    )]
2181    StateChangeWithoutOnStateChangeCallback { from: String, script: PathBuf },
2182}
2183
2184// Fold the three `UpgradeError::{StateChangeWithoutPriorLoad,
2185// DuplicateStateChange, StateChangeWithoutOnStateChangeCallback}
2186// { from: <prior-versao>.to_string(), script: <script>.to_path_buf() }`
2187// two-slot struct-variant wire-up sites at
2188// [`UpgradeFromEntry::validate_state_change_ordering`] (`self.prior_versao()`
2189// / `script` from `instr.declared_path()`),
2190// [`UpgradeFromEntry::validate_state_change_uniqueness`]
2191// (`self.prior_versao()` / `script.as_path()` from
2192// `instr.declared_path()`), and
2193// [`validate_state_change_on_state_change_callback`] (`entry.prior_versao()`
2194// / `script` from `instr.declared_path()`) onto one substrate primitive
2195// per typed variant — the paired `{ from: String, script: PathBuf }`
2196// two-slot sibling on [`UpgradeError`] of the peer
2197// [`crate::supervisor::supervisor_caixa_only_ctors!`] (db09650, 3
2198// variants on `{ caixa: String }`) on the sibling `SupervisorError`
2199// envelope, the peer [`crate::aplicacao::contrato_empty_pair_ctors!`]
2200// (8580068, 4 variants on `{ de, para }`),
2201// [`crate::aplicacao::contrato_target_ctors!`] (14b81d5, 2 variants on
2202// `{ de, para, wit, expected }`),
2203// [`crate::aplicacao::aplicacao_field_reason_ctors!`] (981060b, 7
2204// variants on `{ <field>: String, reason: String }`), and
2205// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] (14e13f1, 3
2206// variants on `{ de, para, <field>: String, reason: String }`) on the
2207// sibling `AplicacaoError` envelopes, and the peer
2208// [`crate::layout::layout_violation_ctors!`] (131ca0d, 16 variants on
2209// `{ caixa, issue }`), [`crate::layout::layout_slot_kind_ctors!`]
2210// (0419438, 4 variants on `{ caixa, kind, slots }`),
2211// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on
2212// `{ kind, path }`), and [`crate::layout::layout_nome_only_ctors!`]
2213// (3fe3dd7, 6 variants on `<Variant>(String)`) on the sibling
2214// `LayoutError` envelopes, plus the peer
2215// [`crate::limits::limits_codec_value_only_ctors!`] /
2216// [`crate::limits::limits_codec_value_byte_ctors!`] /
2217// [`crate::limits::limits_codec_value_char_ctors!`] (81c856c, 12 codec
2218// wire-ups) on the sibling `LimitsError` envelopes.
2219//
2220// Each of the three wire-up sites on this shape opens the identical
2221// `UpgradeError::<Variant> { from: <prior-versao>.to_string(),
2222// script: <script>.to_path_buf() }` struct-literal against a local
2223// `prior_versao()` and `declared_path()` accessor pair — the exact
2224// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
2225// names as a bug, on the same altitude the peer `SupervisorError` /
2226// `AplicacaoError` / `LayoutError` / `LimitsError` families each
2227// closed on their sibling envelopes. The three variants share one
2228// `{ from: String, script: PathBuf }` shape, so the fold routes each
2229// wire-up site through one dispatch per typed variant.
2230//
2231// The macro below generates one `#[must_use]` inherent constructor per
2232// variant of shape `fn <ctor>(from: &str, script: &std::path::Path) ->
2233// Self`, so every wire-up site collapses onto one dispatch:
2234// `UpgradeError::<ctor>(<prior-versao>, <script>)`, byte-equal to the
2235// pre-lift struct-literal on the same `(&str, &Path)` fixture. The
2236// uniform two-field construction (`from.to_string()` /
2237// `script.to_path_buf()`) is spelled once — inside the macro — rather
2238// than at every wire-up site. The `&Path` parameter accepts both
2239// `&Path` (from `script.as_path()` at the uniqueness gate) and
2240// `&PathBuf` (from `instr.declared_path()` at the ordering /
2241// callback-declaration gates, via Deref coercion), so every existing
2242// wire-up threads through the ctor without a pre-conversion.
2243//
2244// Every future consumer that wants to construct one of these three
2245// variants outside the three in-crate `UpgradeFromEntry` /
2246// `validate_state_change_on_state_change_callback` gates (a deferred
2247// wasm-operator's `install_release/1` per-entry ordering / uniqueness
2248// re-checker at hot-upgrade dispatch time, a future
2249// `feira validate --upgrade-from` per-caixa admission verb re-checking
2250// the three axes, a per-`Caixa` overlay resolver rejecting an
2251// ordering / uniqueness / callback-declaration invariant against a
2252// cluster-local snapshot) now reaches each variant through one call
2253// rather than re-inlining the three-line struct-literal in lockstep
2254// with the three in-crate wire-up sites.
2255macro_rules! upgrade_from_script_ctors {
2256    ($($ctor:ident => $variant:ident),* $(,)?) => {
2257        impl UpgradeError {
2258            $(
2259                #[doc = concat!(
2260                    "Construct an [`UpgradeError::",
2261                    stringify!($variant),
2262                    "`] naming the offending `(:from <prior-versao>)` and ",
2263                    "`(:state-change <script>)` pair. Folds the uniform ",
2264                    "`Self::",
2265                    stringify!($variant),
2266                    " { from: from.to_string(), script: script.to_path_buf() }` ",
2267                    "two-field struct-literal onto one substrate primitive so ",
2268                    "every wire-up on this variant reads through one dispatch ",
2269                    "rather than the pre-lift three-line open-coded block. The ",
2270                    "`from` string threads verbatim from ",
2271                    "[`UpgradeFromEntry::prior_versao`] and the `script` path ",
2272                    "from [`UpgradeInstruction::declared_path`] at the call site."
2273                )]
2274                #[must_use]
2275                pub fn $ctor(from: &str, script: &std::path::Path) -> Self {
2276                    Self::$variant {
2277                        from: from.to_string(),
2278                        script: script.to_path_buf(),
2279                    }
2280                }
2281            )*
2282        }
2283    };
2284}
2285
2286upgrade_from_script_ctors! {
2287    state_change_without_prior_load => StateChangeWithoutPriorLoad,
2288    duplicate_state_change => DuplicateStateChange,
2289    state_change_without_on_state_change_callback => StateChangeWithoutOnStateChangeCallback,
2290}
2291
2292// Fold the three `UpgradeError::{AbsoluteScript, ParentEscapeScript,
2293// NonLispExtensionScript} { script: <script>.clone() }` single-slot
2294// struct-variant wire-up sites at [`UpgradeInstruction::validate`]'s
2295// three closures passed to [`crate::render::require_sandboxed_lisp_path`]
2296// onto one substrate primitive per typed variant — the paired
2297// `{ script: PathBuf }` single-slot sibling on [`UpgradeError`] of the
2298// sibling [`upgrade_from_script_ctors!`] (8e67041, 3 variants on
2299// `{ from: String, script: PathBuf }`) two-slot family on the same
2300// envelope, and of the peer
2301// [`crate::supervisor::supervisor_caixa_only_ctors!`] (db09650, 3
2302// variants on `{ caixa: String }`) and
2303// [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
2304// `{ nome: String }`) single-slot families on the sibling
2305// `SupervisorError` / `DepError` envelopes, and of the peer
2306// [`crate::aplicacao::contrato_empty_pair_ctors!`] (8580068, 4 variants
2307// on `{ de, para }`), [`crate::aplicacao::contrato_target_ctors!`]
2308// (14b81d5, 2 variants on `{ de, para, wit, expected }`),
2309// [`crate::aplicacao::aplicacao_field_reason_ctors!`] (981060b, 7
2310// variants on `{ <field>: String, reason: String }`), and
2311// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] (14e13f1, 3
2312// variants on `{ de, para, <field>: String, reason: String }`) on the
2313// sibling `AplicacaoError` envelopes, plus the peer four `LayoutError`
2314// families ([`crate::layout::layout_violation_ctors!`] 131ca0d;
2315// [`crate::layout::layout_slot_kind_ctors!`] 0419438;
2316// [`crate::LayoutError::missing_entry`] 1b09f9d;
2317// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7), the three
2318// `LimitsError` codec families (81c856c), and the sibling
2319// [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11 variants on
2320// `{ nome, caminho }`) two-slot family.
2321//
2322// The three wire-up sites this fold closes are the three closures
2323// (`|| UpgradeError::AbsoluteScript { script: script.clone() }`,
2324// `|| UpgradeError::ParentEscapeScript { script: script.clone() }`,
2325// `|| UpgradeError::NonLispExtensionScript { script: script.clone() }`)
2326// passed to [`crate::render::require_sandboxed_lisp_path`] at
2327// [`UpgradeInstruction::validate`] — each opens the identical
2328// `UpgradeError::<Variant> { script: script.clone() }` three-line
2329// struct-literal against the same `script: &PathBuf` local threaded
2330// from [`UpgradeInstruction::declared_path`], the exact "same block
2331// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
2332// bug. The three variants share one `{ script: PathBuf }` shape, so
2333// the fold routes each closure through one dispatch per typed variant.
2334// The sibling `EmptyScript` unit-variant on the same envelope stays on
2335// its pre-lift open-coded shape — it carries no `script` field (the
2336// offending `:script` value *is* the empty path this variant catches),
2337// so the uniform `fn(script: &Path) -> Self` signature this macro
2338// promises does not apply, and the peer helper's `|| Self::EmptyScript`
2339// closure is already a one-liner. This is the second fold family on
2340// the `UpgradeError` envelope (sibling of the [`upgrade_from_script_ctors!`]
2341// two-slot family established in 8e67041, which explicitly named this
2342// `{ script: PathBuf }` single-slot family as the next fold to land
2343// on the envelope; per that commit's coverage roster, both of the two
2344// most-populated shapes on `UpgradeError` — the two-slot
2345// `{ from, script }` and the one-slot `{ script }` — are now closed.)
2346//
2347// The macro below generates one `#[must_use]` inherent constructor per
2348// variant of shape `fn <ctor>(script: &std::path::Path) -> Self`, so
2349// every closure collapses onto one dispatch:
2350// `UpgradeError::<ctor>(script)`, byte-equal to the pre-lift
2351// struct-literal on the same `&Path` fixture. The uniform one-field
2352// construction (`script.to_path_buf()`) is spelled once — inside the
2353// macro — rather than at every wire-up site. The `&Path` parameter
2354// accepts both `&Path` (direct `Path::new(…)`) and `&PathBuf` (from
2355// `instr.declared_path()` at the three closures, via Deref coercion),
2356// so every existing closure threads through the ctor without a
2357// pre-conversion.
2358//
2359// Every future consumer that wants to construct one of these three
2360// variants outside the three in-crate closures (a deferred
2361// wasm-operator's `install_release/1` per-instruction script-shape
2362// re-checker at hot-upgrade dispatch time, a future
2363// `feira validate --upgrade-from` per-caixa admission verb re-checking
2364// the same script-shape axis, a per-`Caixa` overlay resolver rejecting
2365// an author-supplied `:state-change :script` against a cluster-local
2366// snapshot) now reaches each variant through one call rather than
2367// re-inlining the three-line struct-literal in lockstep with the three
2368// in-crate closure sites.
2369macro_rules! upgrade_script_only_ctors {
2370    ($($ctor:ident => $variant:ident),* $(,)?) => {
2371        impl UpgradeError {
2372            $(
2373                #[doc = concat!(
2374                    "Construct an [`UpgradeError::",
2375                    stringify!($variant),
2376                    "`] naming the offending `(:state-change <script>)`. ",
2377                    "Folds the uniform `Self::",
2378                    stringify!($variant),
2379                    " { script: script.to_path_buf() }` one-field ",
2380                    "struct-literal onto one substrate primitive so every ",
2381                    "closure passed to ",
2382                    "[`crate::render::require_sandboxed_lisp_path`] at ",
2383                    "[`UpgradeInstruction::validate`] on this variant reads ",
2384                    "through one dispatch rather than the pre-lift three-line ",
2385                    "open-coded block. The `script` path threads verbatim ",
2386                    "from [`UpgradeInstruction::declared_path`] at the call ",
2387                    "site."
2388                )]
2389                #[must_use]
2390                pub fn $ctor(script: &std::path::Path) -> Self {
2391                    Self::$variant {
2392                        script: script.to_path_buf(),
2393                    }
2394                }
2395            )*
2396        }
2397    };
2398}
2399
2400upgrade_script_only_ctors! {
2401    absolute_script => AbsoluteScript,
2402    parent_escape_script => ParentEscapeScript,
2403    non_lisp_extension_script => NonLispExtensionScript,
2404}
2405
2406// Fold the three `UpgradeError::{FromInvalid, FromNotBeforeVersao,
2407// DuplicateLoadModule} { from: <from>.to_string(), <axis>:
2408// <value>.to_string() }` two-slot struct-variant wire-up sites at
2409// [`UpgradeFromEntry::validate`]'s per-`:from` SemVer-2 parse gate
2410// (`Version::parse(self.prior_versao()).map_err(|e| … FromInvalid
2411// { from: self.prior_versao().to_string(), reason: e.to_string() })`),
2412// [`UpgradeFromEntry::validate_load_singularity`]'s per-module
2413// dedup gate (`return Err(UpgradeError::DuplicateLoadModule { from:
2414// self.prior_versao().to_string(), module: module.to_string() });`),
2415// and [`validate_upgrade_from_against_versao`]'s per-`:from >= :versao`
2416// self-upgrade gate (`return Err(UpgradeError::FromNotBeforeVersao
2417// { from: entry.prior_versao().to_string(), versao: versao.to_string()
2418// });`) onto one substrate-primitive family per typed variant — the
2419// missing paired two-slot rung on the `UpgradeError`-side four-family
2420// ladder ([`upgrade_script_only_ctors!`] (7468ca9) one-slot
2421// `{ script: PathBuf }` → this two-slot `{ from: String, <axis>: String }`
2422// → [`upgrade_from_script_ctors!`] (8e67041) two-slot `{ from: String,
2423// script: PathBuf }`), and mirror-symmetric sibling of the peer
2424// [`crate::dep::dep_nome_axis_ctors!`] (7f7c950) two-slot `{ nome:
2425// String, <axis>: String }` fold on the `DepError` envelope — same
2426// `<axis>: <value>.to_string()` owned-forward payload shape, `nome`
2427// axis renamed `from` at the per-`:upgrade-from :from`-owned altitude
2428// the `UpgradeError` envelope keys off (every `UpgradeError` variant
2429// carries the offending prior-version `:from` verbatim so the author
2430// can grep their caixa.lisp for the offending `(:from "<value>")` /
2431// `(:load-module …)` / `:versao` block in one edit). The three
2432// variants share the same `{ from: String, <axis>: String }` two-slot
2433// shape: the `from` field names the offending per-`:upgrade-from` block's
2434// prior-version tag the diagnostic points the author back at, and the
2435// middle `<axis>: String` field carries the offending per-envelope axis
2436// value verbatim (`reason` on `FromInvalid` carries the wrapped
2437// `semver::Version::parse` error message that pinpoints why the tag
2438// failed SemVer-2; `versao` on `FromNotBeforeVersao` carries the caixa's
2439// own current-`:versao` the entry's `:from` failed to precede; `module`
2440// on `DuplicateLoadModule` carries the caixa name the second
2441// `(:load-module …)` instruction re-loaded within the same entry).
2442// The middle axis-field name differs across variants (`reason` /
2443// `versao` / `module`) so the ctor family below takes the axis field
2444// name as a macro parameter (`$axis:ident`) alongside the ctor +
2445// variant names, generating one `pub fn $ctor(from: &str, $axis: &str)
2446// -> Self` inherent constructor per typed variant that spells the
2447// uniform two-field construction (`from.to_string()` /
2448// `<axis>.to_string()`) exactly once.
2449//
2450// Peer of the sibling [`upgrade_from_script_ctors!`] (8e67041, 3
2451// variants on `{ from: String, script: PathBuf }`) two-slot family on
2452// the same envelope — both key off the same `from: String` axis at the
2453// same per-`:upgrade-from :from`-owned altitude; this family carries the
2454// owned-`String` second axis (per-`reason` / per-`versao` / per-`module`
2455// carrier) where the script-slot family carries the owned-`PathBuf`
2456// second axis. Peer also of the sibling [`upgrade_script_only_ctors!`]
2457// (7468ca9, 3 variants on `{ script: PathBuf }`) one-slot family on the
2458// same envelope, of the sibling
2459// [`crate::supervisor::supervisor_caixa_only_ctors!`] (db09650, 3
2460// variants on `{ caixa: String }`) and
2461// [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
2462// `{ nome: String }`) single-slot families on the sibling
2463// `SupervisorError` / `DepError` envelopes, and of the peer
2464// [`crate::aplicacao::contrato_empty_pair_ctors!`] (8580068, 4 variants
2465// on `{ de, para }`), [`crate::aplicacao::contrato_target_ctors!`]
2466// (14b81d5, 2 variants on `{ de, para, wit, expected }`),
2467// [`crate::aplicacao::aplicacao_field_reason_ctors!`] (981060b, 7
2468// variants on `{ <field>: String, reason: String }`),
2469// [`crate::aplicacao::aplicacao_caixa_only_ctors!`] (d9f6867, 5
2470// variants on `{ caixa: String }`),
2471// [`crate::aplicacao::aplicacao_path_only_ctors!`] (3ba8de6, 3 variants
2472// on `{ path: String }`), and
2473// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] (14e13f1, 3
2474// variants on `{ de, para, <field>: String, reason: String }`) on the
2475// sibling `AplicacaoError` envelopes, plus the peer four `LayoutError`
2476// families ([`crate::layout::layout_violation_ctors!`] 131ca0d;
2477// [`crate::layout::layout_slot_kind_ctors!`] 0419438;
2478// [`crate::LayoutError::missing_entry`] 1b09f9d;
2479// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7), the three
2480// `LimitsError` codec families (81c856c), the sibling
2481// [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11 variants on
2482// `{ nome, caminho }`), [`crate::dep::fonte_caminho_byte_ctors!`]
2483// (0e35793, 12 variants on `{ nome, caminho, byte }`),
2484// [`crate::dep::dep_nome_list_ctors!`] (6f5e0cd, 4 variants on
2485// `{ nome, list: &'static str }`), and
2486// [`crate::dep::dep_nome_axis_reason_ctors!`] (5621f8a, 3 variants on
2487// `{ nome, <axis>: String, reason: String }`) families.
2488//
2489// Each of the three wire-up sites on this shape opens the identical
2490// `UpgradeError::<Variant> { from: <from>.to_string(), <axis>:
2491// <value>.to_string() }` four-line struct-literal against a local
2492// `(prior_versao(), <axis-value>)` pair threaded from
2493// [`UpgradeFromEntry::prior_versao`] (or, at the
2494// [`validate_upgrade_from_against_versao`] site, directly from the
2495// caller-supplied `versao: &str` argument) — the exact "same block
2496// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
2497// bug, on the same altitude the peer sibling `upgrade_from_script_ctors!`
2498// / `upgrade_script_only_ctors!` families closed on the sibling
2499// `{ from, script }` / `{ script }` shape-envelopes. The three variant /
2500// axis-field discriminators are the only things that vary between them;
2501// the rest of the struct-literal is a byte-for-byte re-inline.
2502//
2503// The macro below generates one `#[must_use]` inherent constructor per
2504// variant of shape `fn <ctor>(from: &str, <axis>: &str) -> Self`, so
2505// every wire-up site collapses onto one dispatch:
2506// `UpgradeError::<ctor>(<from>, <axis-value>)`, byte-equal to the
2507// pre-lift struct-literal on the same `(&str, &str)` fixture. Both
2508// parameters accept `&str` literals and `&String` (via Deref coercion)
2509// so every existing wire-up threads through the ctor without a
2510// pre-conversion.
2511//
2512// Every future consumer that wants to construct one of these three
2513// variants outside the three in-crate `UpgradeFromEntry::validate` /
2514// `validate_load_singularity` / `validate_upgrade_from_against_versao`
2515// gates (a deferred wasm-operator's `install_release/1` per-entry
2516// `:from`-parse / per-`:load-module` singularity / per-entry
2517// `:from < :versao` re-checker at hot-upgrade dispatch time, a future
2518// `feira validate --upgrade-from` per-caixa admission verb re-checking
2519// the three axes, a per-`Caixa` overlay resolver rejecting a
2520// `:from`-shape / `:load-module`-singularity / `:from < :versao`
2521// invariant against a cluster-local snapshot) now reaches each variant
2522// through one call rather than re-inlining the four-line struct-literal
2523// in lockstep with the three in-crate wire-up sites.
2524macro_rules! upgrade_from_axis_ctors {
2525    ($($ctor:ident => $variant:ident { $axis:ident }),* $(,)?) => {
2526        impl UpgradeError {
2527            $(
2528                #[doc = concat!(
2529                    "Construct an [`UpgradeError::",
2530                    stringify!($variant),
2531                    "`] naming the offending `(:from <prior-versao>)` and ",
2532                    "the offending `:", stringify!($axis), "` axis value. ",
2533                    "Folds the uniform `Self::",
2534                    stringify!($variant),
2535                    " { from: from.to_string(), ",
2536                    stringify!($axis),
2537                    ": ",
2538                    stringify!($axis),
2539                    ".to_string() }` two-field struct-literal onto one ",
2540                    "substrate primitive so every in-crate wire-up on ",
2541                    "this variant reads through one dispatch rather than ",
2542                    "the pre-lift four-line open-coded block. Both `from: ",
2543                    "&str` and `",
2544                    stringify!($axis),
2545                    ": &str` parameters accept `&str` literals and ",
2546                    "`&String` (via Deref coercion) so every existing ",
2547                    "wire-up threads through the ctor without a pre-",
2548                    "conversion."
2549                )]
2550                #[must_use]
2551                pub fn $ctor(from: &str, $axis: &str) -> Self {
2552                    Self::$variant {
2553                        from: from.to_string(),
2554                        $axis: $axis.to_string(),
2555                    }
2556                }
2557            )*
2558        }
2559    };
2560}
2561
2562upgrade_from_axis_ctors! {
2563    from_invalid => FromInvalid { reason },
2564    from_not_before_versao => FromNotBeforeVersao { versao },
2565    duplicate_load_module => DuplicateLoadModule { module },
2566}
2567
2568// Fold the last open-coded `UpgradeError::DuplicateFrom { from:
2569// entry.prior_versao().to_string() }` one-slot struct-literal inside
2570// [`validate_upgrade_from`]'s cross-entry `:from`-duplicate gate onto
2571// one substrate primitive on the [`UpgradeError`] envelope, projecting
2572// through the paired [`UpgradeFromEntry::prior_versao`] scalar accessor
2573// on the substrate primitive. The `DuplicateFrom` variant is the last
2574// unlifted single-slot `{ from: String }` envelope on `UpgradeError` —
2575// every peer envelope shape (`{ script: PathBuf }` one-slot via
2576// [`upgrade_script_only_ctors!`] 7468ca9; `{ from: String, <axis>:
2577// String }` two-slot via [`upgrade_from_axis_ctors!`] 41d08db; `{ from:
2578// String, script: PathBuf }` two-slot via [`upgrade_from_script_ctors!`]
2579// 8e67041) already reads through one substrate-primitive dispatch, so
2580// this fold closes the last one-off single-slot on the envelope.
2581//
2582// Peer of the sibling standalone-ctor `AplicacaoError::contrato_self_loop`
2583// (b30edfe) on the paired [`WitContract`] projection — same
2584// `pub fn <ctor>(primitive: &<Primitive>) -> Self` shape, projecting
2585// through the substrate primitive's own scalar accessor rather than
2586// re-inlining the `.to_string()` at the call site. Extended here onto
2587// the sibling [`UpgradeFromEntry`] scalar-accessor family the closed
2588// M2 companion of the M3 mesh-slot accessors (see
2589// [`UpgradeFromEntry::prior_versao`] doc — sibling in shape to
2590// [`crate::Membro::versao_requirement`] a40b0e3, [`crate::Membro::nome`]
2591// 4a32abf, and the [`crate::WitContract::{source, destination,
2592// world_ref}`] 7f0fd43 / 0804823 / [`crate::Entrada::{hostname,
2593// destination}`] 11f3dfe / 6db982c `&str` accessors) established.
2594//
2595// The one wire-up site this fold closes opens the identical
2596// `UpgradeError::DuplicateFrom { from: entry.prior_versao().to_string() }`
2597// three-line struct-literal against the `entry: &UpgradeFromEntry` local
2598// threaded from [`validate_upgrade_from`]'s per-entry loop — the exact
2599// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
2600// names as a bug, on the same altitude the peer `contrato_self_loop`
2601// closed on the sibling `{ caixa: String, wit: String }` two-slot
2602// envelope inside `impl AplicacaoSpec`. The `entry: &UpgradeFromEntry`
2603// parameter accepts the borrowed entry verbatim so the wire-up site
2604// threads through the ctor without a pre-projection — the ctor body
2605// spells the paired `prior_versao().to_string()` projection once.
2606//
2607// Every future consumer that wants to construct this variant outside
2608// `validate_upgrade_from`'s cross-entry duplicate gate — a deferred
2609// wasm-operator's `install_release/1` cross-entry `:from`-duplicate
2610// re-checker at hot-upgrade dispatch time rejecting a second entry
2611// with the same prior-versao tag, a future `feira validate --upgrade-
2612// from` per-caixa admission verb re-running the cross-entry duplicate
2613// pass on demand, a per-`Caixa` overlay resolver rejecting an author-
2614// supplied duplicate `(:from "<value>")` against a cluster-local
2615// snapshot — now reaches the variant through one call rather than
2616// re-inlining the three-line struct-literal in lockstep with the one
2617// in-crate wire-up site.
2618impl UpgradeError {
2619    /// Construct an [`UpgradeError::DuplicateFrom`] naming the offending
2620    /// duplicate `(:from <prior-versao>)` entry, projecting through the
2621    /// paired [`UpgradeFromEntry::prior_versao`] scalar accessor on the
2622    /// substrate primitive. Folds the uniform `Self::DuplicateFrom {
2623    /// from: entry.prior_versao().to_string() }` one-field struct-literal
2624    /// onto one substrate primitive so every wire-up on this variant
2625    /// reads through one dispatch, matching the sibling
2626    /// [`crate::AplicacaoError::contrato_self_loop`] (b30edfe)
2627    /// substrate-primitive-projection ctor's shape on the peer
2628    /// [`AplicacaoError`] envelope. The `entry: &UpgradeFromEntry`
2629    /// parameter accepts the borrowed entry verbatim so the paired
2630    /// `prior_versao().to_string()` projection is spelled once — inside
2631    /// the ctor body — rather than at every wire-up site.
2632    #[must_use]
2633    pub fn duplicate_from(entry: &UpgradeFromEntry) -> Self {
2634        Self::DuplicateFrom {
2635            from: entry.prior_versao().to_string(),
2636        }
2637    }
2638
2639    /// Construct an [`UpgradeError::PurgeWithoutPriorLoad`] naming the
2640    /// offending `(:from <prior-versao>)` entry, the offending cleanup
2641    /// instruction's `:kind` lisp-form (`:soft-purge` / `:purge`), and
2642    /// its `:module` target. Folds the uniform
2643    /// `Self::PurgeWithoutPriorLoad { from: from.to_string(), kind,
2644    /// module: module.to_string() }` three-field struct-literal onto one
2645    /// substrate primitive so every wire-up on this sole-variant
2646    /// cleanup-family load-before-cleanup ordering-refusal envelope reads
2647    /// through one dispatch rather than the pre-lift seven-line
2648    /// open-coded block.
2649    ///
2650    /// The `from: &str` parameter accepts `&str` literals and `&String`
2651    /// via Deref coercion so the sole in-crate wire-up site threads
2652    /// [`UpgradeFromEntry::prior_versao`] verbatim without a
2653    /// pre-conversion. The `kind: &'static str` parameter accepts the
2654    /// lisp-form `&'static str` [`UpgradeInstruction::lisp_form`]
2655    /// returns for the two [`UpgradeInstruction::is_cleanup`] arms —
2656    /// `M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE` /
2657    /// `M2_UPGRADE_INSTRUCTION_KIND_PURGE` — verbatim without a per-arm
2658    /// re-projection at the ctor path. The `module: &str` parameter
2659    /// takes the `&str` [`UpgradeInstruction::declared_module`] returns
2660    /// via `.expect("is_cleanup() implies declared_module() is Some")`
2661    /// at the caller — the `is_cleanup`-implies-`declared_module`-is-
2662    /// `Some` composition pin at
2663    /// [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
2664    /// makes the `.expect(…)` structurally infallible at build time.
2665    ///
2666    /// Peer of the sibling one-off standalone-ctor
2667    /// [`UpgradeError::duplicate_from`] on the paired one-slot `{ from:
2668    /// String }` envelope on the same `UpgradeError` envelope, and of
2669    /// the sibling `AplicacaoError::contrato_endpoint_not_absolute`
2670    /// (cdf1a2c) three-slot `{ de, para, endpoint: String }` sole-
2671    /// variant standalone ctor on the peer `AplicacaoError` envelope.
2672    /// Closes the last unlifted `{ from: String, kind: &'static str,
2673    /// module: String }` three-slot open-coded struct-literal wire-up
2674    /// on the OTP-appup load-before-cleanup ordering axis, sibling of
2675    /// the peer sub-family generated by [`upgrade_from_axis_ctors!`]
2676    /// (41d08db, three variants on `{ from: String, <axis>: String }`)
2677    /// on the paired ordering / uniqueness / callback-declaration axes,
2678    /// and of the peer standalone [`UpgradeError::duplicate_from`]
2679    /// (7e52aec) one-slot ctor on the sibling cross-entry duplicate-
2680    /// `:from` gate. Every future consumer that raises this refusal
2681    /// outside `UpgradeFromEntry::validate_purge_ordering` — a deferred
2682    /// wasm-operator's `install_release/1` per-entry load-before-cleanup
2683    /// re-checker at hot-upgrade dispatch time, a future
2684    /// `feira validate --upgrade-from` per-caixa admission verb
2685    /// re-running the load-before-cleanup gate on demand, a per-`Caixa`
2686    /// overlay resolver rejecting a cluster-local `:soft-purge` /
2687    /// `:purge` overlay lacking a preceding `:load-module` — reaches
2688    /// the variant through one call rather than re-inlining the
2689    /// seven-line struct-literal in lockstep with the sole in-crate
2690    /// wire-up site.
2691    #[must_use]
2692    pub fn purge_without_prior_load(from: &str, kind: &'static str, module: &str) -> Self {
2693        Self::PurgeWithoutPriorLoad {
2694            from: from.to_string(),
2695            kind,
2696            module: module.to_string(),
2697        }
2698    }
2699
2700    /// Construct an [`UpgradeError::StateChangeAfterCleanup`] naming the
2701    /// offending `(:from <prior-versao>)` entry, the offending
2702    /// `(:state-change …)` `:script` path, and the prior cleanup
2703    /// instruction's `:kind` lisp-form (`:soft-purge` / `:purge`) +
2704    /// `:module` target. Folds the uniform
2705    /// `Self::StateChangeAfterCleanup { from: from.to_string(), script:
2706    /// script.to_path_buf(), prior_cleanup_kind, prior_cleanup_module:
2707    /// prior_cleanup_module.to_string() }` four-field struct-literal
2708    /// onto one substrate primitive so every wire-up on this sole-
2709    /// variant migrate-after-cleanup ordering-refusal envelope reads
2710    /// through one dispatch rather than the pre-lift seven-line open-
2711    /// coded block. Closes the last unlifted `{ from: String, script:
2712    /// PathBuf, prior_cleanup_kind: &'static str, prior_cleanup_module:
2713    /// String }` four-slot open-coded struct-literal wire-up on the
2714    /// OTP-appup migrate-before-cleanup ordering axis, filling the
2715    /// missing four-slot rung on the `UpgradeError`-side ctor-family
2716    /// ladder alongside the sibling one-slot
2717    /// [`UpgradeError::duplicate_from`] (7e52aec) and three-slot
2718    /// [`UpgradeError::purge_without_prior_load`] (9752da1) standalone
2719    /// ctors, the two-slot [`upgrade_from_axis_ctors!`] (41d08db) /
2720    /// [`upgrade_from_script_ctors!`] (8e67041) macro-generated
2721    /// families, and the one-slot [`upgrade_script_only_ctors!`]
2722    /// (7468ca9) family. Sole in-crate wire-up site is inside
2723    /// [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
2724    /// migrate-family sticky-latch dispatch — the third of three
2725    /// within-entry cross-instruction OTP-appup ordering gates the
2726    /// module doc pins (`validate_state_change_ordering` on the load →
2727    /// migrate boundary via [`upgrade_from_script_ctors!`]-generated
2728    /// `state_change_without_prior_load`; `validate_purge_ordering` on
2729    /// the load → cleanup boundary via `purge_without_prior_load`;
2730    /// `validate_state_change_before_cleanup` on the migrate → cleanup
2731    /// boundary via this ctor — now).
2732    ///
2733    /// The `from: &str` parameter accepts `&str` literals and `&String`
2734    /// via Deref coercion so the sole in-crate wire-up site threads
2735    /// [`UpgradeFromEntry::prior_versao`] (a `&str` accessor) verbatim
2736    /// without a pre-conversion. The `script: &std::path::Path`
2737    /// parameter accepts `&Path` (direct `Path::new(…)`) and `&PathBuf`
2738    /// (from [`UpgradeInstruction::declared_path`]'s `Option<&PathBuf>`
2739    /// via Deref coercion) so the wire-up threads the sticky-latch
2740    /// script projection through the ctor without a pre-conversion; the
2741    /// uniform `script.to_path_buf()` one-field construction is spelled
2742    /// once — inside the ctor body — rather than at every wire-up site.
2743    /// The `prior_cleanup_kind: &'static str` parameter accepts the
2744    /// lisp-form `&'static str` [`UpgradeInstruction::lisp_form`]
2745    /// returns for the two [`UpgradeInstruction::is_cleanup`] arms —
2746    /// `M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE` /
2747    /// `M2_UPGRADE_INSTRUCTION_KIND_PURGE` — verbatim without a per-arm
2748    /// re-projection at the ctor path. The `prior_cleanup_module: &str`
2749    /// parameter takes the `&str` [`UpgradeInstruction::declared_module`]
2750    /// returns via `.expect("is_cleanup() implies declared_module() is
2751    /// Some")` at the caller — the `is_cleanup`-implies-`declared_module`-
2752    /// is-`Some` composition pin at
2753    /// [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
2754    /// makes the `.expect(…)` structurally infallible at build time.
2755    ///
2756    /// Every future consumer that raises this refusal outside
2757    /// [`UpgradeFromEntry::validate_state_change_before_cleanup`] — a
2758    /// deferred wasm-operator's `install_release/1` per-entry
2759    /// migrate-before-cleanup re-checker at hot-upgrade dispatch time,
2760    /// a future `feira validate --upgrade-from` per-caixa admission verb
2761    /// re-running the migrate-before-cleanup gate on demand, a
2762    /// per-`Caixa` overlay resolver rejecting a cluster-local
2763    /// `:state-change` overlay authored after a `:soft-purge` /
2764    /// `:purge`, the M4 `mesh.pleme.io/v1alpha1/Caixa` CR admission
2765    /// webhook re-checking a per-`:upgrade-from`-patched candidate
2766    /// before the migrate-before-cleanup gate re-fires — reaches the
2767    /// variant through one call rather than re-inlining the seven-line
2768    /// struct-literal in lockstep with the sole in-crate wire-up site.
2769    #[must_use]
2770    pub fn state_change_after_cleanup(
2771        from: &str,
2772        script: &std::path::Path,
2773        prior_cleanup_kind: &'static str,
2774        prior_cleanup_module: &str,
2775    ) -> Self {
2776        Self::StateChangeAfterCleanup {
2777            from: from.to_string(),
2778            script: script.to_path_buf(),
2779            prior_cleanup_kind,
2780            prior_cleanup_module: prior_cleanup_module.to_string(),
2781        }
2782    }
2783
2784    /// Construct an [`UpgradeError::DuplicateCleanup`] naming the
2785    /// offending `(:from <prior-versao>)` entry, the colliding `:module`
2786    /// target, and the ordered pair of colliding cleanup `:kind` lisp-
2787    /// forms (`:soft-purge` / `:purge`). Folds the uniform
2788    /// `Self::DuplicateCleanup { from: from.to_string(), module:
2789    /// module.to_string(), kinds }` three-field struct-literal onto one
2790    /// substrate primitive so every wire-up on this sole-variant within-
2791    /// entry per-module cleanup-singularity refusal envelope reads
2792    /// through one dispatch rather than the pre-lift five-line open-coded
2793    /// block. Closes the last unlifted `{ from: String, module: String,
2794    /// kinds: Vec<&'static str> }` three-slot open-coded struct-literal
2795    /// wire-up on the OTP-appup per-module cleanup-singularity axis,
2796    /// filling a peer three-slot rung on the `UpgradeError`-side ctor-
2797    /// family ladder alongside the sibling three-slot
2798    /// [`UpgradeError::purge_without_prior_load`] (9752da1) standalone
2799    /// ctor on the paired within-entry load → cleanup ordering axis, the
2800    /// one-slot [`UpgradeError::duplicate_from`] (7e52aec) standalone
2801    /// ctor on the sibling cross-entry duplicate-`:from` gate, the four-
2802    /// slot [`UpgradeError::state_change_after_cleanup`] (be68237)
2803    /// standalone ctor on the migrate → cleanup boundary, the two-slot
2804    /// [`upgrade_from_axis_ctors!`] (41d08db) /
2805    /// [`upgrade_from_script_ctors!`] (8e67041) macro-generated families,
2806    /// and the one-slot [`upgrade_script_only_ctors!`] (7468ca9) family.
2807    /// Sole in-crate wire-up site is inside
2808    /// [`UpgradeFromEntry::validate_cleanup_singularity`]'s per-module
2809    /// cleanup-family dedup arm.
2810    ///
2811    /// The `from: &str` parameter accepts `&str` literals and `&String`
2812    /// via Deref coercion so the sole in-crate wire-up threads
2813    /// [`UpgradeFromEntry::prior_versao`] (a `&str` accessor) verbatim
2814    /// without a pre-conversion. The `module: &str` parameter takes the
2815    /// `&str` [`UpgradeInstruction::declared_module`] returns via
2816    /// `.expect("is_cleanup() implies declared_module() is Some")` at the
2817    /// caller — the `is_cleanup`-implies-`declared_module`-is-`Some`
2818    /// composition pin at
2819    /// [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
2820    /// makes the `.expect(…)` structurally infallible at build time. The
2821    /// `kinds: Vec<&'static str>` parameter takes the ordered pair
2822    /// `vec![prior_kind, kind]` built at the caller from the two
2823    /// [`UpgradeInstruction::lisp_form`] `&'static str` returns
2824    /// (`M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE` /
2825    /// `M2_UPGRADE_INSTRUCTION_KIND_PURGE`) — the same substrate-
2826    /// primitive `&'static str` projection the paired three-slot
2827    /// [`UpgradeError::purge_without_prior_load`] ctor threads on the
2828    /// sibling load → cleanup ordering axis.
2829    ///
2830    /// Every future consumer that raises this refusal outside
2831    /// [`UpgradeFromEntry::validate_cleanup_singularity`] — a deferred
2832    /// wasm-operator's `install_release/1` per-entry per-module
2833    /// cleanup-singularity re-checker at hot-upgrade dispatch time, a
2834    /// future `feira validate --upgrade-from` per-caixa admission verb
2835    /// re-running the singularity pass on demand, a per-`Caixa` overlay
2836    /// resolver rejecting a cluster-local `:soft-purge` / `:purge`
2837    /// overlay that collides with a base-entry cleanup on the same
2838    /// module, the M4 `mesh.pleme.io/v1alpha1/Caixa` CR admission webhook
2839    /// re-checking a per-`:upgrade-from`-patched candidate before the
2840    /// singularity gate re-fires — reaches the variant through one call
2841    /// rather than re-inlining the five-line struct-literal in lockstep
2842    /// with the sole in-crate wire-up site.
2843    #[must_use]
2844    pub fn duplicate_cleanup(from: &str, module: &str, kinds: Vec<&'static str>) -> Self {
2845        Self::DuplicateCleanup {
2846            from: from.to_string(),
2847            module: module.to_string(),
2848            kinds,
2849        }
2850    }
2851
2852    /// Construct an [`UpgradeError::RestartNotExclusive`] naming the
2853    /// offending `(:from <prior-versao>)` entry, the observed `(:restart)`
2854    /// instruction count, and the ordered list of non-`:restart`
2855    /// instruction lisp-forms the entry mixed with the terminal fallback.
2856    /// Folds the uniform `Self::RestartNotExclusive { from: from.to_string(),
2857    /// restart_count, other_kinds }` three-field struct-literal onto one
2858    /// substrate primitive so every wire-up on this sole-variant within-
2859    /// entry `(:restart)`-exclusivity refusal envelope reads through one
2860    /// dispatch rather than the pre-lift five-line open-coded block. Closes
2861    /// the last unlifted `{ from: String, restart_count: usize, other_kinds:
2862    /// Vec<&'static str> }` three-slot open-coded struct-literal wire-up on
2863    /// the OTP-appup within-entry `(:restart)`-fallback-exclusivity axis —
2864    /// the last-remaining open-coded emission site the sibling
2865    /// [`UpgradeError::duplicate_cleanup`] (10a5b48) commit body pinned as
2866    /// the natural next lift on the `UpgradeError` envelope. Fills a peer
2867    /// three-slot rung on the `UpgradeError`-side ctor-family ladder
2868    /// alongside the sibling three-slot
2869    /// [`UpgradeError::purge_without_prior_load`] (9752da1) standalone
2870    /// ctor on the paired within-entry load → cleanup ordering axis and
2871    /// [`UpgradeError::duplicate_cleanup`] (10a5b48) standalone ctor on
2872    /// the per-module cleanup-singularity axis, the one-slot
2873    /// [`UpgradeError::duplicate_from`] (7e52aec) standalone ctor on the
2874    /// cross-entry duplicate-`:from` gate, the four-slot
2875    /// [`UpgradeError::state_change_after_cleanup`] (be68237) standalone
2876    /// ctor on the migrate → cleanup boundary, the two-slot
2877    /// [`upgrade_from_axis_ctors!`] (41d08db) /
2878    /// [`upgrade_from_script_ctors!`] (8e67041) macro-generated families,
2879    /// and the one-slot [`upgrade_script_only_ctors!`] (7468ca9) family.
2880    /// Sole in-crate wire-up site is inside
2881    /// [`UpgradeFromEntry::validate_restart_exclusive`]'s mixed-`(:restart)`
2882    /// arm.
2883    ///
2884    /// The `from: &str` parameter accepts `&str` literals and `&String`
2885    /// via Deref coercion so the sole in-crate wire-up threads
2886    /// [`UpgradeFromEntry::prior_versao`] (a `&str` accessor) verbatim
2887    /// without a pre-conversion. The `restart_count: usize` parameter
2888    /// takes the observed `(:restart)` occurrence count built at the
2889    /// caller from `instructions.iter().filter(|i| i.is_restart()).count()`
2890    /// — the same `IsVariant`-derived arm-discriminator dispatch the
2891    /// paired `other_kinds` projection routes through — so the diagnostic
2892    /// surfaces the duplication mode unambiguously even when `other_kinds`
2893    /// is empty (the `((:restart) (:restart))` shape the sibling
2894    /// `validate_rejects_restart_duplicated` test pins with
2895    /// `restart_count: 2, other_kinds: vec![]`). The `other_kinds:
2896    /// Vec<&'static str>` parameter takes the ordered list of non-
2897    /// `:restart` instruction lisp-forms built at the caller from
2898    /// `instructions.iter().filter(|i| !i.is_restart()).map(
2899    /// UpgradeInstruction::lisp_form).collect()` — the same substrate-
2900    /// primitive `&'static str` projection the peer three-slot
2901    /// [`UpgradeError::purge_without_prior_load`] /
2902    /// [`UpgradeError::duplicate_cleanup`] ctors thread on the sibling
2903    /// within-entry cleanup axes.
2904    ///
2905    /// Every future consumer that raises this refusal outside
2906    /// [`UpgradeFromEntry::validate_restart_exclusive`] — a deferred
2907    /// wasm-operator's `install_release/1` per-entry `(:restart)`-
2908    /// exclusivity re-checker at hot-upgrade dispatch time, a future
2909    /// `feira validate --upgrade-from` per-caixa admission verb re-running
2910    /// the exclusivity pass on demand, a per-`Caixa` overlay resolver
2911    /// rejecting a cluster-local `(:restart)` overlay that mixes with a
2912    /// base-entry typed sequence, the M4 `mesh.pleme.io/v1alpha1/Caixa`
2913    /// CR admission webhook re-checking a per-`:upgrade-from`-patched
2914    /// candidate before the exclusivity gate re-fires — reaches the
2915    /// variant through one call rather than re-inlining the five-line
2916    /// struct-literal in lockstep with the sole in-crate wire-up site.
2917    #[must_use]
2918    pub fn restart_not_exclusive(
2919        from: &str,
2920        restart_count: usize,
2921        other_kinds: Vec<&'static str>,
2922    ) -> Self {
2923        Self::RestartNotExclusive {
2924            from: from.to_string(),
2925            restart_count,
2926            other_kinds,
2927        }
2928    }
2929
2930    /// Construct an [`UpgradeError::ModuleInvalid`] naming the offending
2931    /// instruction's `:kind` lisp-form (`:load-module` / `:soft-purge` /
2932    /// `:purge`), the malformed `:module` value, and the parser-shaped
2933    /// `reason` from
2934    /// [`crate::render::is_dns_1123_label`]. Folds the uniform
2935    /// `Self::ModuleInvalid { kind, module: module.to_string(), reason }`
2936    /// three-field struct-literal onto one substrate primitive so every
2937    /// wire-up on this variant reads through one dispatch rather than the
2938    /// pre-lift open-coded closure block inside [`validate_module`]'s
2939    /// [`crate::render::require_valid_dns_1123_label`] shape-arm.
2940    ///
2941    /// The `kind: &'static str` parameter accepts the lisp-form
2942    /// [`UpgradeInstruction::lisp_form`] returns for the three
2943    /// [`UpgradeInstruction::declared_module`]-bearing arms —
2944    /// [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE`] /
2945    /// [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`] /
2946    /// [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE`] — verbatim
2947    /// without a per-arm re-projection at the ctor path. The `module: &str`
2948    /// parameter threads the offending author-supplied `:module` value
2949    /// verbatim from [`UpgradeInstruction::declared_module`]. The
2950    /// `reason: impl Into<String>` bound accepts both `&str` literals and
2951    /// the `String` [`crate::render::is_dns_1123_label`] returns via
2952    /// `.into()`, matching the peer
2953    /// [`crate::AplicacaoError::contrato_caixa_invalid`] /
2954    /// [`crate::SupervisorError::child_caixa_invalid`] /
2955    /// [`crate::DepError::nome_invalid`] `{ *, reason: String }`
2956    /// three-slot invalid-arm ctor discipline on the sibling
2957    /// DNS-1123-label per-envelope shape.
2958    ///
2959    /// Peer of the sibling standalone-ctor
2960    /// [`crate::AplicacaoError::contrato_caixa_invalid`] (3d1e484) on the
2961    /// paired [`crate::AplicacaoError`] envelope's `:contratos` per-edge
2962    /// caixa-reference axis — same `pub fn <ctor>(kind, module: &str,
2963    /// reason: impl Into<String>) -> Self` shape closing the invalid-arm
2964    /// side of a `require_valid_dns_1123_label` two-closure cascade, so
2965    /// [`validate_module`]'s cascade now reads through one substrate
2966    /// primitive on the invalid-arm rather than an open-coded four-line
2967    /// struct-literal in lockstep with the sole in-crate wire-up site.
2968    ///
2969    /// Every future consumer that raises this refusal outside
2970    /// [`validate_module`] — a deferred wasm-operator's
2971    /// `install_release/1` per-instruction `:module` re-validator at
2972    /// hot-upgrade dispatch time re-running the same DNS-1123-label
2973    /// floor against a candidate module reference, a future
2974    /// `feira validate --upgrade-from` per-caixa admission verb
2975    /// re-running the module-shape gate on demand, an M4
2976    /// `mesh.pleme.io/v1alpha1/Caixa` CR admission webhook re-checking a
2977    /// per-`:upgrade-from`-patched candidate before the module-shape
2978    /// gate re-fires, a per-`Caixa` overlay resolver rejecting a
2979    /// cluster-local `(:load-module|:soft-purge|:purge <bad-module>)`
2980    /// overlay against a cluster-local snapshot — now reaches this
2981    /// variant through one call rather than re-inlining the four-line
2982    /// struct-literal in lockstep with the [`validate_module`]
2983    /// closure-form wire-up.
2984    #[must_use]
2985    pub fn module_invalid(kind: &'static str, module: &str, reason: impl Into<String>) -> Self {
2986        Self::ModuleInvalid {
2987            kind,
2988            module: module.to_string(),
2989            reason: reason.into(),
2990        }
2991    }
2992}
2993
2994#[cfg(test)]
2995mod tests {
2996    use std::path::Path;
2997
2998    use super::*;
2999
3000    fn entry(from: &str, instrs: Vec<UpgradeInstruction>) -> UpgradeFromEntry {
3001        UpgradeFromEntry {
3002            from: from.into(),
3003            instructions: instrs,
3004        }
3005    }
3006
3007    #[test]
3008    fn upgrade_from_entry_prior_versao_accessor_is_const_fn() {
3009        // Fail-before-pass-after pin on
3010        // [`UpgradeFromEntry::prior_versao`]'s `const`-eval-surface
3011        // posture. The accessor projects the per-`:upgrade-from :from`
3012        // [`String`] storage through the `pub const fn`
3013        // [`String::as_str`] (const-stable since Rust 1.87, well within
3014        // the workspace MSRV) — any future accidental downgrade to
3015        // non-`const` fails `prior_versao_via_const_fn` at caixa-core
3016        // build time with E0015 (`cannot call non-const method`),
3017        // strictly stronger than a runtime `assert!`. Sibling of the
3018        // peer M2/M3 slot family pins on the sibling `const`-eval-
3019        // surface passes ([`crate::Caixa::nome`] /
3020        // [`crate::Caixa::versao`], [`crate::CaixaVersion::as_str`],
3021        // [`crate::aplicacao::Membro::nome`] /
3022        // [`crate::aplicacao::Membro::versao_requirement`],
3023        // [`crate::aplicacao::Entrada::hostname`] /
3024        // [`crate::aplicacao::Entrada::destination`],
3025        // [`crate::supervisor::ChildSpec::nome`] /
3026        // [`crate::supervisor::ChildSpec::versao_requirement`],
3027        // [`crate::dep::Dep::nome`] /
3028        // [`crate::dep::Dep::versao_requirement`], and the
3029        // per-`:contratos`
3030        // [`crate::aplicacao::WitContract::source`] /
3031        // [`crate::aplicacao::WitContract::destination`] /
3032        // [`crate::aplicacao::WitContract::world_ref`] trio the
3033        // sibling pin at 279823b already anchors).
3034        const fn prior_versao_via_const_fn(e: &UpgradeFromEntry) -> &str {
3035            e.prior_versao()
3036        }
3037        for from in ["0.1.0", "1.2.3-alpha.1", "0.0.0"] {
3038            let e = entry(from, vec![]);
3039            assert_eq!(prior_versao_via_const_fn(&e), e.prior_versao());
3040            assert_eq!(e.prior_versao(), from);
3041        }
3042    }
3043
3044    #[test]
3045    fn upgrade_from_entry_instructions_slice_return_accessor_is_const_fn() {
3046        // Fail-before-pass-after pin on
3047        // [`UpgradeFromEntry::instructions`]'s `const`-eval-surface
3048        // posture. The accessor destructures the per-`:upgrade-from
3049        // :instructions` `Vec<UpgradeInstruction>` storage through the
3050        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3051        // 1.66, well within the workspace MSRV) — any future
3052        // accidental downgrade to non-`const` fails
3053        // `instructions_via_const_fn` at caixa-core build time with
3054        // E0015 (`cannot call non-const method`), strictly stronger
3055        // than a runtime `assert!`. Sibling of the peer per-M3-mesh-
3056        // slot `Vec → &[T]` slice-return accessor family pin
3057        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3058        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3059        // per-`:membros` / per-`:contratos` slice-return axes, and of
3060        // the peer M2 supervisor-tree axis pin
3061        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
3062        // on the per-`:children` slice-return axis.
3063        const fn instructions_via_const_fn(e: &UpgradeFromEntry) -> &[UpgradeInstruction] {
3064            e.instructions()
3065        }
3066        // Sweep both the empty-instructions arm (author-declared
3067        // per-`:from` entry with no migration steps — the degenerate
3068        // shape the appup `restart`-only path folds through) and the
3069        // populated-instructions arm (the canonical OTP-appup shape
3070        // carrying a `LoadModule` + `StateChange` + `SoftPurge`
3071        // chain) so the accessor carries a const-dispatch pin on
3072        // both arms.
3073        let e_empty = entry("0.1.0", vec![]);
3074        assert!(instructions_via_const_fn(&e_empty).is_empty());
3075        assert_eq!(instructions_via_const_fn(&e_empty), e_empty.instructions());
3076        let e_full = entry(
3077            "0.1.0",
3078            vec![
3079                UpgradeInstruction::LoadModule {
3080                    module: "hello-rio".into(),
3081                },
3082                UpgradeInstruction::StateChange {
3083                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
3084                },
3085                UpgradeInstruction::SoftPurge {
3086                    module: "hello-rio-old".into(),
3087                },
3088            ],
3089        );
3090        assert_eq!(instructions_via_const_fn(&e_full).len(), 3);
3091        assert_eq!(instructions_via_const_fn(&e_full), e_full.instructions());
3092    }
3093
3094    #[test]
3095    fn round_trip_load_module() {
3096        let i = UpgradeInstruction::LoadModule {
3097            module: "hello-rio".into(),
3098        };
3099        let json = serde_json::to_string(&i).unwrap();
3100        assert!(json.contains("\"kind\":\"load-module\""));
3101        let back: UpgradeInstruction = serde_json::from_str(&json).unwrap();
3102        assert_eq!(i, back);
3103    }
3104
3105    #[test]
3106    fn round_trip_all_variants() {
3107        let cases = vec![
3108            UpgradeInstruction::LoadModule { module: "x".into() },
3109            UpgradeInstruction::StateChange {
3110                script: PathBuf::from("lib/migrations.lisp"),
3111            },
3112            UpgradeInstruction::SoftPurge {
3113                module: "x-old".into(),
3114            },
3115            UpgradeInstruction::Purge {
3116                module: "x-old".into(),
3117            },
3118            UpgradeInstruction::Restart,
3119        ];
3120        for c in cases {
3121            let json = serde_json::to_string(&c).unwrap();
3122            let back: UpgradeInstruction = serde_json::from_str(&json).unwrap();
3123            assert_eq!(c, back);
3124        }
3125    }
3126
3127    #[test]
3128    fn validate_accepts_well_formed() {
3129        let e = entry(
3130            "0.1.0",
3131            vec![
3132                UpgradeInstruction::LoadModule {
3133                    module: "hello-rio".into(),
3134                },
3135                UpgradeInstruction::StateChange {
3136                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
3137                },
3138                UpgradeInstruction::SoftPurge {
3139                    module: "hello-rio-old".into(),
3140                },
3141            ],
3142        );
3143        e.validate().unwrap();
3144    }
3145
3146    #[test]
3147    fn validate_rejects_non_semver_from() {
3148        let e = entry("not-a-semver", vec![]);
3149        let err = e.validate().unwrap_err();
3150        assert!(
3151            matches!(err, UpgradeError::FromInvalid { ref from, .. } if from == "not-a-semver")
3152        );
3153    }
3154
3155    #[test]
3156    fn from_invalid_diagnostic_carries_offending_from_and_reason() {
3157        // Diagnostic-shape pin: the error names the offending
3158        // `:upgrade-from :from` verbatim with a non-empty parser-shaped
3159        // reason, so a `feira lint` run can render the diagnostic
3160        // without re-parsing — the author can grep their caixa.lisp for
3161        // `:from "<value>"` and fix it in one edit. Mirrors the peer
3162        // `versao_invalid_diagnostic_carries_offending_versao` pin on
3163        // the sibling SemVer-2 axis (the top-level `:versao`), the
3164        // peer `membro_versao_invalid_diagnostic_carries_offending_value`
3165        // pin on `:membros :versao`, and the peer
3166        // `deps_invalid_diagnostic_carries_offending_value` pin on
3167        // `:deps :versao` — every SemVer-2-parsing slot's invalid
3168        // diagnostic is now structurally equivalent.
3169        let e = entry("v0.1.0", vec![]);
3170        let err = e.validate().unwrap_err();
3171        let UpgradeError::FromInvalid { from, reason } = err else {
3172            panic!("expected FromInvalid variant, got {err:?}");
3173        };
3174        assert_eq!(from, "v0.1.0");
3175        assert!(
3176            !reason.is_empty(),
3177            "FromInvalid `reason` must carry the parser's wording verbatim"
3178        );
3179    }
3180
3181    #[test]
3182    fn prior_versao_returns_from_byte_equal_across_permutations() {
3183        // Byte-identity pin on the lifted `UpgradeFromEntry::prior_versao`
3184        // accessor across the SemVer-2 shape lattice every consumer
3185        // reaches through it — the numeric-triad canonical shape, a
3186        // pre-release build with a dotted identifier chain, a full-
3187        // metadata build, a large-magnitude triad, and the empty
3188        // string (which reaches this accessor unchanged before any
3189        // validate gate rejects it). Sibling to the peer
3190        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
3191        // (a40b0e3) / `membro_nome_returns_caixa_byte_equal_across_permutations`
3192        // (4a32abf) pins on the sibling M3 mesh-slot scalar-accessor
3193        // family — extended here onto the first M2 slot scalar-value
3194        // axis. Any silent detour on the accessor (a `.to_string()`
3195        // + retained ownership shape, a canonicalization pass, a
3196        // trim-whitespace on the return path) surfaces as a byte-
3197        // inequality failure here rather than as a downstream error-
3198        // diagnostic drift.
3199        let cases = ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42", "10.20.30", ""];
3200        for from in cases {
3201            let e = entry(from, vec![]);
3202            assert_eq!(
3203                e.prior_versao(),
3204                from,
3205                "prior_versao() must return the `:from` field byte-for-byte for {from:?}",
3206            );
3207            assert_eq!(
3208                e.prior_versao().len(),
3209                from.len(),
3210                "prior_versao() byte-length must equal the `:from` field's for {from:?}",
3211            );
3212        }
3213    }
3214
3215    #[test]
3216    fn prior_versao_borrows_from_from_storage() {
3217        // Same-address pin: `UpgradeFromEntry::prior_versao` returns
3218        // a borrow into `self.from`'s heap allocation, never a fresh
3219        // owned copy. Guards against a future silent detour where
3220        // the accessor materializes a `Cow<'_, str>` / `String` /
3221        // `Rc<str>` intermediate — the return path stays zero-cost
3222        // even under a refactor that reshapes the storage. Sibling
3223        // to the peer `membro_versao_requirement_borrows_from_versao_storage`
3224        // (a40b0e3) / `membro_nome_borrows_from_caixa_storage`
3225        // (4a32abf) pins — extended onto the M2 slot's first
3226        // scalar-value axis.
3227        let e = entry("0.1.0", vec![]);
3228        assert!(
3229            std::ptr::eq(e.prior_versao().as_ptr(), e.from.as_ptr()),
3230            "prior_versao() must borrow from `self.from`'s storage, not allocate a fresh copy",
3231        );
3232    }
3233
3234    #[test]
3235    fn validate_parses_prior_versao_through_lifted_accessor() {
3236        // Coherence pin between the accessor and the SemVer-2 parse
3237        // gate: every `:upgrade-from :from` value the validator
3238        // accepts (resp. rejects) must be identical to what
3239        // `Version::parse(entry.prior_versao())` accepts (resp.
3240        // rejects) — the two must remain in lockstep across the
3241        // shape lattice so `validate_upgrade_from`'s
3242        // `Version::parse(entry.prior_versao()).expect(...)` re-parse
3243        // assertion holds by construction. If a future extension of
3244        // `prior_versao` reshapes the return (a canonicalization
3245        // pass, a leading/trailing whitespace trim, an empty-to-
3246        // "0.0.0" fallback) it would either loosen the validator
3247        // (silently accepting shapes the parser rejects) or
3248        // tighten the parser's re-parse (silently panicking on
3249        // shapes the validator accepts) — this pin catches either
3250        // shift at caixa-core build time.
3251        let accepted = ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42", "10.20.30"];
3252        for from in accepted {
3253            let e = entry(from, vec![]);
3254            e.validate().unwrap_or_else(|err| {
3255                panic!("validate() must accept {from:?} that Version::parse accepts, got {err:?}");
3256            });
3257            semver::Version::parse(e.prior_versao()).unwrap_or_else(|err| {
3258                panic!(
3259                    "Version::parse(prior_versao()) must accept {from:?} that validate() accepts, \
3260                     got {err:?}",
3261                );
3262            });
3263        }
3264        let rejected = ["", "v0.1.0", "0.1", "not-a-semver", "0.1.0.0"];
3265        for from in rejected {
3266            let e = entry(from, vec![]);
3267            assert!(
3268                matches!(e.validate(), Err(UpgradeError::FromInvalid { .. })),
3269                "validate() must reject {from:?} that Version::parse rejects",
3270            );
3271            assert!(
3272                semver::Version::parse(e.prior_versao()).is_err(),
3273                "Version::parse(prior_versao()) must reject {from:?} that validate() rejects",
3274            );
3275        }
3276    }
3277
3278    #[test]
3279    fn validate_rejects_empty_module() {
3280        // Per-arm coverage: every Module-bearing variant surfaces the
3281        // kind-tagged `ModuleEmpty` diagnostic naming its lisp-form,
3282        // so the author can grep their caixa.lisp for `(:load-module
3283        // …)` / `(:soft-purge …)` / `(:purge …)` and fix it in one
3284        // edit — same self-locating shape `BehaviorError::EmptyPath`
3285        // (b0c8389) carries on the peer M2 typed slot.
3286        let cases: &[(UpgradeInstruction, &'static str)] = &[
3287            (
3288                UpgradeInstruction::LoadModule {
3289                    module: String::new(),
3290                },
3291                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
3292            ),
3293            (
3294                UpgradeInstruction::SoftPurge {
3295                    module: String::new(),
3296                },
3297                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
3298            ),
3299            (
3300                UpgradeInstruction::Purge {
3301                    module: String::new(),
3302                },
3303                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
3304            ),
3305        ];
3306        for (instr, expected_kind) in cases {
3307            assert_eq!(
3308                instr.validate().unwrap_err(),
3309                UpgradeError::ModuleEmpty {
3310                    kind: expected_kind
3311                },
3312                "empty :module on {instr:?} must surface as ModuleEmpty {{ kind: {expected_kind:?} }}"
3313            );
3314        }
3315    }
3316
3317    #[test]
3318    fn validate_rejects_non_dns_1123_module() {
3319        // Every appup `:module` reference is a caixa name (the
3320        // wasm-engine resolves it through the same ComputeUnit
3321        // registry the operator manages), so the value-shape gate
3322        // matches the K8s apiserver-side DNS-1123 label rule. Sweep
3323        // the canonical authoring footguns — uppercase letters, `_`
3324        // separator, embedded `.`, leading/trailing `-`, an embedded
3325        // whitespace byte, the >63-byte UUID-shaped slug — across
3326        // every Module-bearing variant; each must surface as
3327        // `ModuleInvalid { kind, module, reason }` carrying the
3328        // offending value verbatim and the parser-shaped reason.
3329        type Build = fn(String) -> UpgradeInstruction;
3330        let footguns: &[&str] = &[
3331            "Hello-Rio",
3332            "hello_rio",
3333            "hello.rio",
3334            "-hello",
3335            "hello-",
3336            "hello rio",
3337            &"x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
3338        ];
3339        let variants: &[(Build, &'static str)] = &[
3340            (
3341                |m| UpgradeInstruction::LoadModule { module: m },
3342                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
3343            ),
3344            (
3345                |m| UpgradeInstruction::SoftPurge { module: m },
3346                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
3347            ),
3348            (
3349                |m| UpgradeInstruction::Purge { module: m },
3350                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
3351            ),
3352        ];
3353        for (build, expected_kind) in variants {
3354            for module in footguns {
3355                let instr = build((*module).to_string());
3356                let err = instr.validate().unwrap_err();
3357                match err {
3358                    UpgradeError::ModuleInvalid {
3359                        kind,
3360                        module: m,
3361                        reason,
3362                    } => {
3363                        assert_eq!(
3364                            kind, *expected_kind,
3365                            ":module footgun on {instr:?} must tag the lisp-form"
3366                        );
3367                        assert_eq!(
3368                            m, *module,
3369                            "ModuleInvalid must carry the offending value verbatim"
3370                        );
3371                        assert!(
3372                            !reason.is_empty(),
3373                            "ModuleInvalid reason must name the specific violation \
3374                             (the predicate's parser-shaped wording from \
3375                             `is_dns_1123_label`), got empty"
3376                        );
3377                    }
3378                    other => panic!("expected ModuleInvalid on {instr:?}, got {other:?}"),
3379                }
3380            }
3381        }
3382    }
3383
3384    #[test]
3385    fn validate_accepts_canonical_module_names() {
3386        // Positive control: every documented authoring shape — bare
3387        // identifier, with hyphens, with digits, the
3388        // suffix-versioned alias `<nome>-old` `SoftPurge` typically
3389        // references — passes the gate. Drift here = a future
3390        // tighten that rejects any of these surfaces as a
3391        // test-failure at the predicate boundary, not piecemeal
3392        // across per-instruction call sites.
3393        let canonical: &[&str] = &[
3394            "hello-rio",
3395            "hello-rio-old",
3396            "cache",
3397            "cache-v2",
3398            "x",
3399            "a1",
3400            "0a",
3401            "abc-123-def",
3402        ];
3403        for module in canonical {
3404            UpgradeInstruction::LoadModule {
3405                module: (*module).to_string(),
3406            }
3407            .validate()
3408            .unwrap_or_else(|e| panic!("LoadModule {module:?} must pass, got {e:?}"));
3409            UpgradeInstruction::SoftPurge {
3410                module: (*module).to_string(),
3411            }
3412            .validate()
3413            .unwrap_or_else(|e| panic!("SoftPurge {module:?} must pass, got {e:?}"));
3414            UpgradeInstruction::Purge {
3415                module: (*module).to_string(),
3416            }
3417            .validate()
3418            .unwrap_or_else(|e| panic!("Purge {module:?} must pass, got {e:?}"));
3419        }
3420    }
3421
3422    #[test]
3423    fn validate_empty_takes_precedence_over_invalid() {
3424        // Empty input is rejected via the narrower `ModuleEmpty`
3425        // diagnostic before the DNS-1123 predicate is consulted, so
3426        // a future tighten that adds another stage between the two
3427        // doesn't accidentally reorder the diagnostic precedence.
3428        // Mirrors the empty-first cascade on every peer DNS-1123
3429        // gate (`validate_membro_caixa`, `validate_placement_cluster`,
3430        // `SupervisorSpec::validate`'s child-name arm).
3431        let err = UpgradeInstruction::LoadModule {
3432            module: String::new(),
3433        }
3434        .validate()
3435        .unwrap_err();
3436        assert_eq!(
3437            err,
3438            UpgradeError::ModuleEmpty {
3439                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
3440            }
3441        );
3442    }
3443
3444    #[test]
3445    fn validate_rejects_empty_script() {
3446        let i = UpgradeInstruction::StateChange {
3447            script: PathBuf::new(),
3448        };
3449        assert_eq!(i.validate().unwrap_err(), UpgradeError::EmptyScript);
3450    }
3451
3452    #[test]
3453    fn validate_rejects_absolute_script() {
3454        let i = UpgradeInstruction::StateChange {
3455            script: PathBuf::from("/etc/migrations.lisp"),
3456        };
3457        assert!(matches!(
3458            i.validate().unwrap_err(),
3459            UpgradeError::AbsoluteScript { .. }
3460        ));
3461    }
3462
3463    #[test]
3464    fn validate_rejects_parent_escape_script() {
3465        let i = UpgradeInstruction::StateChange {
3466            script: PathBuf::from("../sibling/migrations.lisp"),
3467        };
3468        assert!(matches!(
3469            i.validate().unwrap_err(),
3470            UpgradeError::ParentEscapeScript { .. }
3471        ));
3472        // mid-path `..` is also caught
3473        let i2 = UpgradeInstruction::StateChange {
3474            script: PathBuf::from("lib/../../escaped.lisp"),
3475        };
3476        assert!(matches!(
3477            i2.validate().unwrap_err(),
3478            UpgradeError::ParentEscapeScript { .. }
3479        ));
3480    }
3481
3482    // ── :upgrade-from :state-change :script `.lisp` extension gate ─
3483    // Mirrors the c97815a `BehaviorError::NonLispExtension` arm on
3484    // the peer `:behavior :on-*` tatara-lisp-source-path axis. Both
3485    // axes route through the same M2.5 wasm-engine `tatara_lisp::read`
3486    // consumer; the file-type contract is identical, so the per-axis
3487    // test grid is mirrored leg-for-leg.
3488
3489    #[test]
3490    fn validate_rejects_no_extension_script() {
3491        // Fail-before-pass-after: the canonical "I declared the
3492        // migration script but forgot the `.lisp` extension"
3493        // authoring footgun (e.g. `(:state-change "lib/migrations")`).
3494        // The wasm-engine's `tatara_lisp::read` consumer needs a
3495        // file-type contract beyond the structural-shape gate; a
3496        // no-extension path past `is_sandboxed_relative_path` would
3497        // surface a parser-shaped diagnostic at hot-upgrade migration
3498        // time far from the source caixa.lisp.
3499        for relpath in ["lib/migrations", "migrations", "lib/handlers/migrate"] {
3500            let i = UpgradeInstruction::StateChange {
3501                script: PathBuf::from(relpath),
3502            };
3503            let err = i.validate().unwrap_err();
3504            assert!(
3505                matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
3506                         if s == Path::new(relpath)),
3507                "no-extension script {relpath:?} must surface as NonLispExtensionScript \
3508                 carrying the offending path verbatim, got {err:?}"
3509            );
3510        }
3511    }
3512
3513    #[test]
3514    fn validate_rejects_non_lisp_extension_script() {
3515        // Wrong-extension sweep across common authoring footguns: the
3516        // `.txt` / `.md` / `.json` / `.yaml` shapes an author might
3517        // drag in from the workspace tree, the `.rs` shape that an
3518        // IDE auto-complete might propose, the `.lisp.bak` shape an
3519        // editor might leave behind, and the `.lispx` near-miss that
3520        // a typo would produce. Each must surface as
3521        // `NonLispExtensionScript` carrying the offending path
3522        // verbatim — the wasm-engine's `tatara_lisp::read` consumer
3523        // rejects all of these at hot-upgrade migration time, and
3524        // the gate lifts that contract to validate time. Mirrors the
3525        // peer `BehaviorError::NonLispExtension` sweep (c97815a) on
3526        // the `:behavior :on-*` axis leg-for-leg — same downstream
3527        // consumer, same accepted set, same per-axis test grid.
3528        let footguns: &[&str] = &[
3529            "lib/migrations.rs",
3530            "lib/migrations.txt",
3531            "lib/migrations.md",
3532            "lib/migrations.json",
3533            "lib/migrations.yaml",
3534            "lib/migrations.toml",
3535            "lib/migrations.lisp.bak",
3536            "lib/migrations.lispx",
3537            "lib/migrations.lis",
3538        ];
3539        for relpath in footguns {
3540            let i = UpgradeInstruction::StateChange {
3541                script: PathBuf::from(relpath),
3542            };
3543            let err = i.validate().unwrap_err();
3544            assert!(
3545                matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
3546                         if s == Path::new(relpath)),
3547                "wrong-extension script {relpath:?} must surface as NonLispExtensionScript \
3548                 carrying the offending path verbatim, got {err:?}"
3549            );
3550        }
3551    }
3552
3553    #[test]
3554    fn validate_rejects_uppercase_lisp_extension_script() {
3555        // Strict lowercase: `.LISP` / `.Lisp` / `.LiSp` are
3556        // case-folded shapes a case-insensitive volume's existence
3557        // check would match the on-disk file — but the
3558        // canonical-form codec emits lowercase `.lisp` verbatim, so
3559        // a case-folded shape mismatches the round-trip-stable
3560        // canonical form (THEORY.md §V.2.7 render-determinism).
3561        // Same case-sensitive discipline the byte-size / duration
3562        // codecs use on unit suffixes (`MiB`, `ms`, `s`, `m`, `h`)
3563        // and every other shape-gate predicate in `render.rs` (label
3564        // / scheme / unit boundaries). Mirrors the peer
3565        // `BehaviorError::NonLispExtension` case-fold sweep (c97815a).
3566        for relpath in [
3567            "lib/migrations.LISP",
3568            "lib/migrations.Lisp",
3569            "lib/migrations.LiSp",
3570            "lib/migrations.lISP",
3571        ] {
3572            let i = UpgradeInstruction::StateChange {
3573                script: PathBuf::from(relpath),
3574            };
3575            let err = i.validate().unwrap_err();
3576            assert!(
3577                matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
3578                         if s == Path::new(relpath)),
3579                "case-folded `.lisp` extension {relpath:?} must surface as \
3580                 NonLispExtensionScript (strict lowercase, canonical-form \
3581                 round-trip pin), got {err:?}"
3582            );
3583        }
3584    }
3585
3586    #[test]
3587    fn validate_accepts_canonical_lisp_extension_scripts() {
3588        // Positive-control sweep across every canonical in-tree
3589        // authoring shape: bare filename, standard `lib/`
3590        // subdirectory, deeply-nested migrations subdirectory,
3591        // explicit current-dir-relative prefix, mid-path `./`
3592        // segment, multi-dot stem (the version-suffix shape
3593        // `lib/migrations/v.0.1.lisp` an author might use to encode
3594        // the migration's `:from` version into the filename). Drift
3595        // here = a future tightening that rejects any of these
3596        // surfaces as a test-failure at the per-axis validator
3597        // boundary, not piecemeal across renderer / layout-checker
3598        // call sites. Mirrors the peer `BehaviorSpec` positive-set
3599        // sweep (c97815a).
3600        let canonical: &[&str] = &[
3601            "lib/migrations.lisp",
3602            "lib/migrations/v01-to-v02.lisp",
3603            "migrations.lisp",
3604            "a.lisp",
3605            "./lib/migrations.lisp",
3606            "lib/./migrations.lisp",
3607            "lib/migrations/v.0.1.lisp",
3608        ];
3609        for relpath in canonical {
3610            UpgradeInstruction::StateChange {
3611                script: PathBuf::from(relpath),
3612            }
3613            .validate()
3614            .unwrap_or_else(|e| {
3615                panic!("canonical `.lisp` script {relpath:?} must pass, got {e:?}")
3616            });
3617        }
3618    }
3619
3620    #[test]
3621    fn validate_sandbox_shape_takes_precedence_over_lisp_extension() {
3622        // Cross-arm precedence pin: a script that is *both*
3623        // sandbox-escaping (Empty / Absolute / ParentEscape) and
3624        // non-`.lisp` must surface the more-fundamental
3625        // sandbox-shape diagnostic first — the canonical fix
3626        // collapses both into "pin a relative `.lisp` path under the
3627        // caixa root", and the `.lisp` remediation would be
3628        // misleading when the offending path can never resolve under
3629        // the caixa root anyway. Mirrors the peer
3630        // `BehaviorError` cross-arm precedence (c97815a) and the
3631        // sibling `LimitsError`
3632        // (`MemoryZero` → `MemoryBelowWasm32Page` →
3633        // `MemoryExceedsWasm32Cap` → `MemoryNotPageMultiple`)
3634        // smallest-scope-arm-fires-last posture.
3635        let i_empty = UpgradeInstruction::StateChange {
3636            script: PathBuf::new(),
3637        };
3638        assert_eq!(i_empty.validate().unwrap_err(), UpgradeError::EmptyScript);
3639        let i_abs = UpgradeInstruction::StateChange {
3640            script: PathBuf::from("/etc/migrations.txt"),
3641        };
3642        assert!(
3643            matches!(
3644                i_abs.validate().unwrap_err(),
3645                UpgradeError::AbsoluteScript { .. }
3646            ),
3647            "absolute + non-`.lisp` must surface AbsoluteScript first"
3648        );
3649        let i_esc = UpgradeInstruction::StateChange {
3650            script: PathBuf::from("../sibling/migrations.rs"),
3651        };
3652        assert!(
3653            matches!(
3654                i_esc.validate().unwrap_err(),
3655                UpgradeError::ParentEscapeScript { .. }
3656            ),
3657            "parent-escape + non-`.lisp` must surface ParentEscapeScript first"
3658        );
3659    }
3660
3661    #[test]
3662    fn non_lisp_extension_script_diagnostic_carries_offending_path() {
3663        // Diagnostic-shape pin: the surfaced error message names the
3664        // offending path verbatim (so the author can grep their
3665        // caixa.lisp for the literal value), the `.lisp` extension
3666        // is named in the remediation, and the downstream consumer
3667        // (`tatara_lisp::read` at hot-upgrade migration time) is
3668        // named so the author can trace the contract back to its
3669        // source. Same self-locating shape every per-axis variant
3670        // carries (`BehaviorError::NonLispExtension`, c97815a;
3671        // `LimitsError::MemoryNotPageMultiple`, ec266d8).
3672        let bad = PathBuf::from("lib/migrations.txt");
3673        let err = UpgradeInstruction::StateChange {
3674            script: bad.clone(),
3675        }
3676        .validate()
3677        .unwrap_err();
3678        let msg = err.to_string();
3679        assert!(
3680            msg.contains("lib/migrations.txt"),
3681            "diagnostic must name the offending path verbatim, got {msg:?}"
3682        );
3683        assert!(
3684            msg.contains(".lisp"),
3685            "diagnostic must name the expected `.lisp` extension, got {msg:?}"
3686        );
3687        assert!(
3688            msg.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE),
3689            "diagnostic must name the offending `:state-change` instruction, got {msg:?}"
3690        );
3691        match err {
3692            UpgradeError::NonLispExtensionScript { script } => {
3693                assert_eq!(
3694                    script, bad,
3695                    "variant must carry the offending path verbatim"
3696                );
3697            }
3698            other => panic!("expected NonLispExtensionScript, got {other:?}"),
3699        }
3700    }
3701
3702    #[test]
3703    fn declared_path_only_for_state_change() {
3704        let load = UpgradeInstruction::LoadModule { module: "x".into() };
3705        assert!(load.declared_path().is_none());
3706        let mig = UpgradeInstruction::StateChange {
3707            script: PathBuf::from("lib/m.lisp"),
3708        };
3709        assert_eq!(mig.declared_path(), Some(&PathBuf::from("lib/m.lisp")));
3710    }
3711
3712    #[test]
3713    fn upgrade_instruction_is_restart_predicate_partitions_the_arm_set() {
3714        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
3715        // derive's [`UpgradeInstruction::is_restart`] arm-discriminator
3716        // predicate: [`UpgradeInstruction::Restart`] is the only variant
3717        // that satisfies `.is_restart()`; every module-bearing arm
3718        // (`LoadModule` / `SoftPurge` / `Purge`) and the script-carrying
3719        // `StateChange` arm all return `false`. This pin makes the
3720        // partition invariant load-bearing at caixa-core test time so a
3721        // future derive regression (a hole that returns `false` for
3722        // `Restart` too, or a byte-collision that flips a second variant
3723        // to `true`) trips here rather than laundering the arm at
3724        // [`Self::validate_restart_exclusive`]'s paired positive /
3725        // negated filter sites (a hole flips restart-count to 0 →
3726        // vacuous OK; a collision flips restart-count > 1 → false
3727        // `RestartNotExclusive` on an entry the author declared without
3728        // any `(:restart)`). Peer of the sibling
3729        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
3730        // pin on the M0 `CaixaKind` axis.
3731        let cases: &[(UpgradeInstruction, bool)] = &[
3732            (UpgradeInstruction::LoadModule { module: "a".into() }, false),
3733            (UpgradeInstruction::SoftPurge { module: "b".into() }, false),
3734            (UpgradeInstruction::Purge { module: "c".into() }, false),
3735            (
3736                UpgradeInstruction::StateChange {
3737                    script: PathBuf::from("lib/m.lisp"),
3738                },
3739                false,
3740            ),
3741            (UpgradeInstruction::Restart, true),
3742        ];
3743        for (variant, expected) in cases {
3744            assert_eq!(
3745                variant.is_restart(),
3746                *expected,
3747                "UpgradeInstruction::{variant:?}.is_restart() must \
3748                 return {expected} (partition invariant on the \
3749                 IsVariant-derived arm-discriminator predicate)"
3750            );
3751        }
3752    }
3753
3754    #[test]
3755    fn validate_restart_exclusive_routes_through_is_restart_predicate() {
3756        // Byte-identity pin on the paired positive / negated
3757        // `.is_restart()` filters at
3758        // [`Self::validate_restart_exclusive`] against the pre-lift
3759        // `matches!(i, UpgradeInstruction::Restart)` /
3760        // `!matches!(i, UpgradeInstruction::Restart)` predicates every
3761        // consumer of the gate previously coupled to inline. Asserts
3762        // the two projections agree byte-for-byte on every arm of the
3763        // enum, so a future derive regression that flipped either
3764        // predicate's arm-set would surface here at caixa-core test
3765        // time rather than at
3766        // [`Self::validate_restart_exclusive`]'s per-entry restart-
3767        // count / other-kinds tabulation far from the derive site.
3768        // Same peer-shape pin every sibling
3769        // `IsVariant`-derive-routed gate carries on the substrate's
3770        // closed-set typed-enum surface.
3771        let cases: Vec<UpgradeInstruction> = vec![
3772            UpgradeInstruction::LoadModule { module: "a".into() },
3773            UpgradeInstruction::SoftPurge { module: "b".into() },
3774            UpgradeInstruction::Purge { module: "c".into() },
3775            UpgradeInstruction::StateChange {
3776                script: PathBuf::from("lib/m.lisp"),
3777            },
3778            UpgradeInstruction::Restart,
3779        ];
3780        for instr in &cases {
3781            let via_predicate = instr.is_restart();
3782            let via_matches = matches!(instr, UpgradeInstruction::Restart);
3783            assert_eq!(
3784                via_predicate, via_matches,
3785                "UpgradeInstruction::{instr:?}: is_restart() must \
3786                 byte-equal matches!(_, UpgradeInstruction::Restart) — \
3787                 the pre-lift open-coded pattern and the \
3788                 IsVariant-derived predicate are the same axis, \
3789                 one typed dispatch"
3790            );
3791        }
3792    }
3793
3794    #[test]
3795    fn upgrade_instruction_is_cleanup_predicate_partitions_the_arm_set() {
3796        // The fail-before-pass-after pin on the lifted
3797        // [`UpgradeInstruction::is_cleanup`] two-arm cleanup-family
3798        // arm-discriminator predicate:
3799        // [`UpgradeInstruction::SoftPurge`] and
3800        // [`UpgradeInstruction::Purge`] are the two OTP-appup two-
3801        // phase-code-load cleanup arms that satisfy `.is_cleanup()`;
3802        // every non-cleanup arm ([`UpgradeInstruction::LoadModule`]
3803        // on the paired two-phase-load half,
3804        // [`UpgradeInstruction::StateChange`] on the
3805        // `gen_server:code_change/3`-analog migration axis,
3806        // [`UpgradeInstruction::Restart`] on the OTP terminal-
3807        // fallback shape) returns `false`. This pin makes the
3808        // partition invariant load-bearing at caixa-core test time
3809        // so a future accessor regression (a hole that returns
3810        // `false` for `SoftPurge` or `Purge`, or a byte-collision
3811        // that flips `LoadModule` / `StateChange` / `Restart` to
3812        // `true`) trips here rather than laundering the arm at the
3813        // three within-entry cross-instruction cleanup-facing gates
3814        // ([`UpgradeFromEntry::validate_purge_ordering`],
3815        // [`UpgradeFromEntry::validate_state_change_before_cleanup`],
3816        // [`UpgradeFromEntry::validate_cleanup_singularity`]) — a
3817        // hole would silently accept a cleanup-shaped entry the
3818        // three gates should refuse; a collision would fire a
3819        // `PurgeWithoutPriorLoad` / `StateChangeAfterCleanup` /
3820        // `DuplicateCleanup` refusal on a well-shaped
3821        // [`UpgradeInstruction::LoadModule`] / `StateChange` /
3822        // `Restart` arm the three gates should pass through. Peer
3823        // of the sibling
3824        // [`upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
3825        // pin on the single-arm terminal-fallback partition —
3826        // extended here from the single-arm case onto the two-arm
3827        // cleanup-family union case.
3828        let cases: &[(UpgradeInstruction, bool)] = &[
3829            (UpgradeInstruction::LoadModule { module: "a".into() }, false),
3830            (UpgradeInstruction::SoftPurge { module: "b".into() }, true),
3831            (UpgradeInstruction::Purge { module: "c".into() }, true),
3832            (
3833                UpgradeInstruction::StateChange {
3834                    script: PathBuf::from("lib/m.lisp"),
3835                },
3836                false,
3837            ),
3838            (UpgradeInstruction::Restart, false),
3839        ];
3840        for (variant, expected) in cases {
3841            assert_eq!(
3842                variant.is_cleanup(),
3843                *expected,
3844                "UpgradeInstruction::{variant:?}.is_cleanup() must \
3845                 return {expected} (partition invariant on the \
3846                 lifted OTP-appup two-arm cleanup-family arm-\
3847                 discriminator predicate)"
3848            );
3849        }
3850    }
3851
3852    #[test]
3853    fn upgrade_instruction_is_cleanup_composes_through_is_soft_purge_or_is_purge() {
3854        // Byte-identity pin on the [`UpgradeInstruction::is_cleanup`]
3855        // composition against the two [`gen_platform::IsVariant`]-
3856        // derive-generated per-variant classifiers it routes through
3857        // — the accessor's one body must byte-equal
3858        // `self.is_soft_purge() || self.is_purge()` across every arm
3859        // of the closed-set enum, so a future silent detour that
3860        // reintroduced a raw `matches!` pattern or that stopped
3861        // composing through the derive-generated per-variant
3862        // predicates (an accidental `self.is_soft_purge()` on its
3863        // own — silently dropping the `Purge` arm; an accidental
3864        // `self.is_purge() || self.is_state_change()` — silently
3865        // folding the migration arm into the cleanup family; a
3866        // typo `&&` for the union `||` — silently classifying no
3867        // arm as cleanup) trips here at caixa-core test time
3868        // rather than laundering the arm at the three within-entry
3869        // cross-instruction cleanup-facing gates. Same peer-shape
3870        // pin the sibling
3871        // [`validate_restart_exclusive_routes_through_is_restart_predicate`]
3872        // carries on the paired terminal-fallback axis.
3873        let cases: Vec<UpgradeInstruction> = vec![
3874            UpgradeInstruction::LoadModule { module: "a".into() },
3875            UpgradeInstruction::SoftPurge { module: "b".into() },
3876            UpgradeInstruction::Purge { module: "c".into() },
3877            UpgradeInstruction::StateChange {
3878                script: PathBuf::from("lib/m.lisp"),
3879            },
3880            UpgradeInstruction::Restart,
3881        ];
3882        for instr in &cases {
3883            let via_predicate = instr.is_cleanup();
3884            let via_composition = instr.is_soft_purge() || instr.is_purge();
3885            assert_eq!(
3886                via_predicate, via_composition,
3887                "UpgradeInstruction::{instr:?}: is_cleanup() must \
3888                 byte-equal is_soft_purge() || is_purge() — the \
3889                 lifted union predicate and its per-variant \
3890                 composition are the same axis, one typed dispatch"
3891            );
3892        }
3893    }
3894
3895    #[test]
3896    fn upgrade_instruction_is_cleanup_implies_declared_module_is_some() {
3897        // Composition-pin the load-bearing invariant every consumer
3898        // that routes through `is_cleanup()` + `declared_module()`
3899        // relies on: any [`UpgradeInstruction`] value whose
3900        // `.is_cleanup()` returns `true` must have a `Some(_)`
3901        // `.declared_module()`. This makes the three within-entry
3902        // cross-instruction cleanup-facing gates' `.expect("is_cleanup()
3903        // implies declared_module() is Some")` structurally
3904        // infallible at build time — a future refactor that added
3905        // a cleanup-shaped variant carrying no `:module` would trip
3906        // here rather than panic at
3907        // [`UpgradeFromEntry::validate_purge_ordering`] /
3908        // [`UpgradeFromEntry::validate_state_change_before_cleanup`] /
3909        // [`UpgradeFromEntry::validate_cleanup_singularity`] at
3910        // runtime on the offending author's caixa.lisp.
3911        let cases: Vec<UpgradeInstruction> = vec![
3912            UpgradeInstruction::LoadModule { module: "a".into() },
3913            UpgradeInstruction::SoftPurge { module: "b".into() },
3914            UpgradeInstruction::Purge { module: "c".into() },
3915            UpgradeInstruction::StateChange {
3916                script: PathBuf::from("lib/m.lisp"),
3917            },
3918            UpgradeInstruction::Restart,
3919        ];
3920        for instr in &cases {
3921            if instr.is_cleanup() {
3922                assert!(
3923                    instr.declared_module().is_some(),
3924                    "UpgradeInstruction::{instr:?}: is_cleanup() \
3925                     must imply declared_module().is_some() — the \
3926                     three within-entry cross-instruction cleanup-\
3927                     facing gates rely on this invariant to route \
3928                     the cleanup-target :module scalar through the \
3929                     sibling declared_module accessor without a \
3930                     pattern-bound `module` binding"
3931                );
3932            }
3933        }
3934    }
3935
3936    #[test]
3937    fn upgrade_instruction_is_load_module_implies_declared_module_is_some() {
3938        // Composition-pin the load-bearing invariant
3939        // [`UpgradeFromEntry::validate_load_singularity`] relies on
3940        // when routing the per-instruction load-family arm-discriminator
3941        // through the sibling
3942        // [`UpgradeInstruction::is_load_module`] +
3943        // [`UpgradeInstruction::declared_module`] accessor pair: any
3944        // [`UpgradeInstruction`] value whose `.is_load_module()`
3945        // returns `true` must have a `Some(_)` `.declared_module()`.
3946        // This makes the gate's `.expect("is_load_module() implies
3947        // declared_module() is Some")` structurally infallible at
3948        // build time — a future refactor that added a load-shaped
3949        // variant carrying no `:module` would trip here rather than
3950        // panic at [`UpgradeFromEntry::validate_load_singularity`]
3951        // at runtime on the offending author's caixa.lisp. Sibling
3952        // of the peer
3953        // [`upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
3954        // composition pin on the two-arm cleanup-family axis — same
3955        // "predicate implies accessor" discipline extended onto the
3956        // single-arm load-family axis, closes the load-vs-cleanup
3957        // pair on the substrate primitive's typed dispatch discipline.
3958        let cases: Vec<UpgradeInstruction> = vec![
3959            UpgradeInstruction::LoadModule { module: "a".into() },
3960            UpgradeInstruction::SoftPurge { module: "b".into() },
3961            UpgradeInstruction::Purge { module: "c".into() },
3962            UpgradeInstruction::StateChange {
3963                script: PathBuf::from("lib/m.lisp"),
3964            },
3965            UpgradeInstruction::Restart,
3966        ];
3967        for instr in &cases {
3968            if instr.is_load_module() {
3969                assert!(
3970                    instr.declared_module().is_some(),
3971                    "UpgradeInstruction::{instr:?}: is_load_module() \
3972                     must imply declared_module().is_some() — the \
3973                     within-entry load-singularity gate relies on this \
3974                     invariant to route the load-target :module scalar \
3975                     through the sibling declared_module accessor \
3976                     without a pattern-bound `module` binding"
3977                );
3978            }
3979        }
3980    }
3981
3982    #[test]
3983    fn validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors()
3984     {
3985        // Byte-identity pin on the
3986        // [`UpgradeFromEntry::validate_load_singularity`] load-family
3987        // dispatch against the pre-lift
3988        // `match instr { UpgradeInstruction::LoadModule { module } =>
3989        // module.as_str(), _ => continue }` open-coded pattern-match
3990        // the site previously carried. Asserts the two projections
3991        // agree byte-for-byte on every arm of the enum — the
3992        // arm-discriminator via `is_load_module()` and the `:module`
3993        // scalar via `declared_module()` — so a future derive
3994        // regression that flipped the predicate's arm-set (a hole
3995        // returning `false` for [`UpgradeInstruction::LoadModule`], a
3996        // byte-collision flipping a second variant to `true`) or an
3997        // accessor extension that promoted an additional variant onto
3998        // the `String`-carrying axis would trip here at caixa-core
3999        // test time rather than laundering the arm at the gate's
4000        // per-entry load-singularity scan far from the derive site.
4001        // Peer of the sibling
4002        // [`validate_purge_ordering_routes_through_is_load_module_predicate`]
4003        // byte-identity pin on the paired ordering-side load-family
4004        // sticky-latch dispatch (both consumers now agree on one
4005        // typed dispatch for the load-family axis) and the peer
4006        // [`validate_state_change_singularity_projects_scripts_through_declared_path_accessor`]
4007        // pin on the migration-family script-projection axis — the
4008        // three within-entry per-instruction-class singularity gates
4009        // now share one byte-identity pin apiece against their
4010        // respective substrate-primitive typed dispatches.
4011        //
4012        // Three-arm projective coverage:
4013        //   (a) `LoadModule` modules project through
4014        //       `declared_module()` byte-equal to the raw
4015        //       `module.as_str()` field access;
4016        //   (b) a duplicate-`LoadModule` input trips the gate on the
4017        //       second occurrence with `DuplicateLoadModule` carrying
4018        //       the offending module verbatim;
4019        //   (c) a non-`LoadModule`-only input (`SoftPurge` / `Purge` /
4020        //       `StateChange` / `Restart`) leaves the gate vacuous
4021        //       with `Ok(())` — the `!instr.is_load_module()`
4022        //       `continue` fall-through pins.
4023        //
4024        // Fail-before-pass-after verified locally: swapping the
4025        // production `if !instr.is_load_module() { continue; } let
4026        // module = instr.declared_module().expect(…);` back to `let
4027        // module = match instr { UpgradeInstruction::LoadModule
4028        // { module } => module.as_str(), _ => continue, };` keeps
4029        // arms (a)-(c) passing but silently detaches the gate from
4030        // the accessor's typed dispatch — any future
4031        // `is_load_module` / `declared_module` extension (a hole in
4032        // either predicate, a promotion of an additional variant
4033        // onto the `String`-carrying axis, an operator-side
4034        // pre-parsed caixa-name cache the accessor materializes)
4035        // would then silently disagree between this gate's raw
4036        // pattern-match and the peer per-`UpgradeInstruction`
4037        // consumers that route through the accessor pair.
4038
4039        // (a) LoadModule projection byte-equal via
4040        //     is_load_module() + declared_module().
4041        let lm = UpgradeInstruction::LoadModule {
4042            module: "hello-rio".into(),
4043        };
4044        assert!(
4045            lm.is_load_module(),
4046            "LoadModule must satisfy is_load_module() — the gate's \
4047             load-family arm-discriminator relies on this partition"
4048        );
4049        assert_eq!(
4050            lm.declared_module(),
4051            Some("hello-rio"),
4052            "declared_module() must project the LoadModule :module \
4053             byte-equal to the raw field access — accessor divergence \
4054             would silently detach the gate from the projection every \
4055             peer per-`UpgradeInstruction` consumer routes through"
4056        );
4057
4058        // (b) Duplicate-LoadModule input trips the gate.
4059        let dup = entry(
4060            "0.1.0",
4061            vec![
4062                UpgradeInstruction::LoadModule { module: "x".into() },
4063                UpgradeInstruction::LoadModule { module: "x".into() },
4064            ],
4065        );
4066        assert_eq!(
4067            dup.validate_load_singularity(),
4068            Err(UpgradeError::DuplicateLoadModule {
4069                from: "0.1.0".into(),
4070                module: "x".into(),
4071            }),
4072            "duplicate LoadModule modules within one entry must fire \
4073             DuplicateLoadModule byte-identical to the pre-lift \
4074             pattern-match shape"
4075        );
4076
4077        // (c) Non-LoadModule-only input leaves the gate vacuous.
4078        let no_load = entry(
4079            "0.1.0",
4080            vec![
4081                UpgradeInstruction::StateChange {
4082                    script: PathBuf::from("lib/m.lisp"),
4083                },
4084                UpgradeInstruction::Restart,
4085            ],
4086        );
4087        assert_eq!(
4088            no_load.validate_load_singularity(),
4089            Ok(()),
4090            "non-LoadModule-only entries must leave the load-\
4091             singularity gate vacuous — the `!is_load_module()` \
4092             continue fall-through pins"
4093        );
4094    }
4095
4096    #[test]
4097    fn upgrade_instruction_is_load_module_predicate_partitions_the_arm_set() {
4098        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
4099        // derive's [`UpgradeInstruction::is_load_module`] arm-discriminator
4100        // predicate: [`UpgradeInstruction::LoadModule`] is the only
4101        // variant that satisfies `.is_load_module()`; every cleanup arm
4102        // (`SoftPurge` / `Purge`), the migration arm (`StateChange`),
4103        // and the terminal-fallback arm (`Restart`) all return `false`.
4104        // This pin makes the partition invariant load-bearing at
4105        // caixa-core test time so a future derive regression (a hole
4106        // that returns `false` for `LoadModule` too, or a byte-collision
4107        // that flips a second variant to `true`) trips here rather than
4108        // laundering the arm at
4109        // [`Self::validate_purge_ordering`]'s load-family sticky-latch
4110        // dispatch — a hole would silently keep `loaded = false` through
4111        // a well-shaped [`UpgradeInstruction::LoadModule`] prefix and
4112        // false-fire `PurgeWithoutPriorLoad` on the trailing cleanup;
4113        // a collision would flip `loaded = true` on a well-shaped
4114        // cleanup-only entry and silently swallow the load-less
4115        // `PurgeWithoutPriorLoad` refusal. Peer of the sibling
4116        // [`upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
4117        // and
4118        // [`upgrade_instruction_is_cleanup_predicate_partitions_the_arm_set`]
4119        // pins on the paired terminal-fallback and cleanup-family
4120        // arm-discriminator axes — closes the last unlifted `matches!`-
4121        // based arm-discriminator axis on the OTP-appup closed-set
4122        // typed enum.
4123        let cases: &[(UpgradeInstruction, bool)] = &[
4124            (UpgradeInstruction::LoadModule { module: "a".into() }, true),
4125            (UpgradeInstruction::SoftPurge { module: "b".into() }, false),
4126            (UpgradeInstruction::Purge { module: "c".into() }, false),
4127            (
4128                UpgradeInstruction::StateChange {
4129                    script: PathBuf::from("lib/m.lisp"),
4130                },
4131                false,
4132            ),
4133            (UpgradeInstruction::Restart, false),
4134        ];
4135        for (variant, expected) in cases {
4136            assert_eq!(
4137                variant.is_load_module(),
4138                *expected,
4139                "UpgradeInstruction::{variant:?}.is_load_module() must \
4140                 return {expected} (partition invariant on the \
4141                 IsVariant-derived arm-discriminator predicate)"
4142            );
4143        }
4144    }
4145
4146    #[test]
4147    fn validate_purge_ordering_routes_through_is_load_module_predicate() {
4148        // Byte-identity pin on the [`Self::validate_purge_ordering`]
4149        // load-family sticky-latch dispatch against the pre-lift
4150        // `matches!(instr, UpgradeInstruction::LoadModule { .. })`
4151        // predicate the site previously open-coded. Asserts the two
4152        // projections agree byte-for-byte on every arm of the enum, so
4153        // a future derive regression that flipped the predicate's
4154        // arm-set would surface here at caixa-core test time rather
4155        // than at [`Self::validate_purge_ordering`]'s per-entry
4156        // load-before-cleanup ordering scan far from the derive site.
4157        // Same peer-shape pin the sibling
4158        // [`validate_restart_exclusive_routes_through_is_restart_predicate`]
4159        // carries on the paired terminal-fallback axis and the
4160        // [`upgrade_instruction_is_cleanup_composes_through_is_soft_purge_or_is_purge`]
4161        // carries on the two-arm cleanup-family axis — the third and
4162        // final byte-identity pin closes the substrate primitive's
4163        // arm-discriminator dispatch discipline on the OTP-appup
4164        // closed-set typed enum.
4165        let cases: Vec<UpgradeInstruction> = vec![
4166            UpgradeInstruction::LoadModule { module: "a".into() },
4167            UpgradeInstruction::SoftPurge { module: "b".into() },
4168            UpgradeInstruction::Purge { module: "c".into() },
4169            UpgradeInstruction::StateChange {
4170                script: PathBuf::from("lib/m.lisp"),
4171            },
4172            UpgradeInstruction::Restart,
4173        ];
4174        for instr in &cases {
4175            let via_predicate = instr.is_load_module();
4176            let via_matches = matches!(instr, UpgradeInstruction::LoadModule { .. });
4177            assert_eq!(
4178                via_predicate, via_matches,
4179                "UpgradeInstruction::{instr:?}: is_load_module() must \
4180                 byte-equal matches!(_, UpgradeInstruction::LoadModule \
4181                 {{ .. }}) — the pre-lift open-coded pattern and the \
4182                 IsVariant-derived predicate are the same axis, one \
4183                 typed dispatch"
4184            );
4185        }
4186    }
4187
4188    #[test]
4189    fn declared_module_only_for_module_bearing_variants() {
4190        // Pinned partition of the `UpgradeInstruction` closed-set
4191        // variant space against the sibling of the peer
4192        // `declared_path` accessor: every OTP-appup module-bearing
4193        // variant (`LoadModule` / `SoftPurge` / `Purge`) surfaces its
4194        // `:module` string byte-for-byte through the lifted
4195        // `declared_module` accessor; every non-module-bearing variant
4196        // (`StateChange` on the peer `:script`-carrying axis;
4197        // `Restart` on the OTP terminal-fallback data-less axis)
4198        // returns `None`. Mirrors the peer
4199        // `declared_path_only_for_state_change` pin — the pair now
4200        // closes both scalar-carrying axes on the enum on one lifted
4201        // `Option<&…>` accessor apiece.
4202        let load = UpgradeInstruction::LoadModule {
4203            module: "hello-rio".into(),
4204        };
4205        assert_eq!(load.declared_module(), Some("hello-rio"));
4206        let soft = UpgradeInstruction::SoftPurge {
4207            module: "hello-rio-old".into(),
4208        };
4209        assert_eq!(soft.declared_module(), Some("hello-rio-old"));
4210        let hard = UpgradeInstruction::Purge {
4211            module: "hello-rio-ancient".into(),
4212        };
4213        assert_eq!(hard.declared_module(), Some("hello-rio-ancient"));
4214        let mig = UpgradeInstruction::StateChange {
4215            script: PathBuf::from("lib/m.lisp"),
4216        };
4217        assert!(mig.declared_module().is_none());
4218        assert!(UpgradeInstruction::Restart.declared_module().is_none());
4219    }
4220
4221    #[test]
4222    fn declared_module_and_declared_path_partition_the_enum_variant_space() {
4223        // Byte-identity pin on the two-accessor partition: every
4224        // `UpgradeInstruction` variant returns `Some` from *exactly
4225        // one* of {`declared_module`, `declared_path`} (the two
4226        // module-bearing / script-carrying axes) or from *neither*
4227        // (the OTP terminal-fallback `Restart` shape). No variant
4228        // returns `Some` from both — the two axes are disjoint by
4229        // construction, and this pin closes the disjointness at the
4230        // test surface so a future variant that leaks a scalar across
4231        // both axes fails at build time. Mirrors the peer
4232        // `declared_paths_iter_covers_each_declared_slot_exactly_once`
4233        // discipline on the `BehaviorSpec` per-slot family.
4234        let cases: Vec<UpgradeInstruction> = vec![
4235            UpgradeInstruction::LoadModule { module: "a".into() },
4236            UpgradeInstruction::SoftPurge { module: "b".into() },
4237            UpgradeInstruction::Purge { module: "c".into() },
4238            UpgradeInstruction::StateChange {
4239                script: PathBuf::from("lib/m.lisp"),
4240            },
4241            UpgradeInstruction::Restart,
4242        ];
4243        for instr in &cases {
4244            let has_module = instr.declared_module().is_some();
4245            let has_path = instr.declared_path().is_some();
4246            assert!(
4247                !(has_module && has_path),
4248                "no variant may declare both a module and a path — offending: {instr:?}"
4249            );
4250            match instr {
4251                UpgradeInstruction::LoadModule { .. }
4252                | UpgradeInstruction::SoftPurge { .. }
4253                | UpgradeInstruction::Purge { .. } => {
4254                    assert!(has_module && !has_path, "module axis: {instr:?}");
4255                }
4256                UpgradeInstruction::StateChange { .. } => {
4257                    assert!(!has_module && has_path, "script axis: {instr:?}");
4258                }
4259                UpgradeInstruction::Restart => {
4260                    assert!(!has_module && !has_path, "data-less axis: {instr:?}");
4261                }
4262            }
4263        }
4264    }
4265
4266    #[test]
4267    fn entry_with_chain_of_versions() {
4268        // Middle entry pairs a `:load-module` with the trailing
4269        // `:soft-purge` so it satisfies the within-entry purge-ordering
4270        // gate (`PurgeWithoutPriorLoad` rejects `:soft-purge` without a
4271        // preceding `:load-module`, mirroring the state-change-ordering
4272        // gate's `StateChangeWithoutPriorLoad`). The chain shape under
4273        // test is *cross-entry* `:from` values; the within-entry shape
4274        // is incidental — keeping it canonical (`:load-module` before
4275        // `:soft-purge`) leaves the chain assertion load-bearing.
4276        let entries = vec![
4277            entry(
4278                "0.1.0",
4279                vec![UpgradeInstruction::LoadModule { module: "x".into() }],
4280            ),
4281            entry(
4282                "0.1.5",
4283                vec![
4284                    UpgradeInstruction::LoadModule { module: "x".into() },
4285                    UpgradeInstruction::SoftPurge {
4286                        module: "x-old".into(),
4287                    },
4288                ],
4289            ),
4290            entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart]),
4291        ];
4292        for e in &entries {
4293            e.validate().unwrap();
4294        }
4295        let json = serde_json::to_string(&entries).unwrap();
4296        let back: Vec<UpgradeFromEntry> = serde_json::from_str(&json).unwrap();
4297        assert_eq!(entries, back);
4298    }
4299
4300    #[test]
4301    fn empty_instructions_list_is_valid() {
4302        let e = entry("0.1.0", vec![]);
4303        e.validate().unwrap();
4304    }
4305
4306    #[test]
4307    fn json_uses_kebab_case_kind_tags() {
4308        let i = UpgradeInstruction::SoftPurge {
4309            module: "x-old".into(),
4310        };
4311        let json = serde_json::to_string(&i).unwrap();
4312        assert!(json.contains("\"kind\":\"soft-purge\""));
4313        let i2 = UpgradeInstruction::StateChange {
4314            script: PathBuf::from("m.lisp"),
4315        };
4316        let json2 = serde_json::to_string(&i2).unwrap();
4317        assert!(json2.contains("\"kind\":\"state-change\""));
4318    }
4319
4320    // ── validate_upgrade_from: cross-entry graph-edge-set invariant ────
4321
4322    #[test]
4323    fn validate_upgrade_from_accepts_disjoint_versions() {
4324        // Positive control: the canonical "chain v0.1.0 → 0.1.5 →
4325        // 0.2.0-rc.1" authoring shape from ABSORPTION-ROADMAP §M2.3
4326        // (and `entry_with_chain_of_versions` above) passes the cross-
4327        // entry gate. Different `:from` per entry is the intended
4328        // shape; the gate must not regress this baseline. Middle entry
4329        // pairs `:load-module` with `:soft-purge` to satisfy the
4330        // within-entry purge-ordering gate (see
4331        // `entry_with_chain_of_versions` for the same shape).
4332        let entries = vec![
4333            entry(
4334                "0.1.0",
4335                vec![UpgradeInstruction::LoadModule { module: "x".into() }],
4336            ),
4337            entry(
4338                "0.1.5",
4339                vec![
4340                    UpgradeInstruction::LoadModule { module: "x".into() },
4341                    UpgradeInstruction::SoftPurge {
4342                        module: "x-old".into(),
4343                    },
4344                ],
4345            ),
4346            entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart]),
4347        ];
4348        validate_upgrade_from(&entries).unwrap();
4349    }
4350
4351    #[test]
4352    fn validate_upgrade_from_accepts_empty_list() {
4353        // Absent `:upgrade-from` (the bare `feira init` shape) — the
4354        // gate must trivially pass an empty list. Mirrors the per-axis
4355        // "empty list passes" positive control on every peer typed-
4356        // graph gate (`validate_membros` empty list, `validate_placement`
4357        // requires non-empty clusters but only after a `Placement`
4358        // exists, etc.).
4359        validate_upgrade_from(&[]).unwrap();
4360    }
4361
4362    #[test]
4363    fn validate_upgrade_from_rejects_duplicate_from() {
4364        // Fail-before-pass-after pin: two entries with the same parsed-
4365        // semver `:from` are an ambiguous edge in the typed upgrade
4366        // graph (OTP appup picks at most one matching block per running
4367        // version; with two matching blocks the operator picks either
4368        // set non-deterministically — author intent is one path per
4369        // prior version). Same set-not-multiset discipline as
4370        // `:children :caixa` (dbf50a9), `:membros :caixa` (4bb3f3d),
4371        // `:contratos` (5dbcfaf), `:placement :clusters` (c7c7799),
4372        // `:entrada :paths` (eb3456d) — now extended onto the fifth
4373        // typed-graph axis.
4374        let entries = vec![
4375            entry(
4376                "0.1.0",
4377                vec![UpgradeInstruction::LoadModule { module: "x".into() }],
4378            ),
4379            entry(
4380                "0.1.0",
4381                vec![
4382                    UpgradeInstruction::LoadModule { module: "x".into() },
4383                    UpgradeInstruction::SoftPurge {
4384                        module: "x-old".into(),
4385                    },
4386                ],
4387            ),
4388        ];
4389        let err = validate_upgrade_from(&entries).unwrap_err();
4390        assert_eq!(
4391            err,
4392            UpgradeError::DuplicateFrom {
4393                from: "0.1.0".into()
4394            },
4395            "two entries with `:from \"0.1.0\"` must surface as DuplicateFrom carrying the \
4396             offending value verbatim"
4397        );
4398    }
4399
4400    #[test]
4401    fn validate_upgrade_from_treats_pre_release_as_distinct() {
4402        // Negative-of-positive: `1.0.0` and `1.0.0-rc.1` are *not*
4403        // equal under semver (pre-release version is part of the
4404        // identity), so they're distinct upgrade paths and must not
4405        // collide. A future tightening that collapses pre-release into
4406        // the release version surfaces here.
4407        let entries = vec![
4408            entry("1.0.0", vec![UpgradeInstruction::Restart]),
4409            entry("1.0.0-rc.1", vec![UpgradeInstruction::Restart]),
4410        ];
4411        validate_upgrade_from(&entries).unwrap();
4412    }
4413
4414    #[test]
4415    fn validate_upgrade_from_treats_build_metadata_as_distinct() {
4416        // Conservative-by-design: [`semver::Version`]'s `PartialEq`
4417        // compares build metadata (it derives equality across all
4418        // fields including `pre` + `build`), so `1.0.0+build1` and
4419        // `1.0.0+build2` are *not* duplicates from the gate's
4420        // perspective — the operator may treat the build-metadata
4421        // suffix as a tiebreaker even though the semver spec says
4422        // build metadata is ignored for precedence
4423        // (https://semver.org/#spec-item-10). Pin the conservative
4424        // behavior here so a future switch to a build-metadata-
4425        // stripping comparator surfaces as a test failure first; that
4426        // change would require coordinating with the wasm-operator's
4427        // `:from`-match dispatch step, which is the load-bearing
4428        // semantic we'd be mirroring.
4429        let entries = vec![
4430            entry("1.0.0+build1", vec![UpgradeInstruction::Restart]),
4431            entry("1.0.0+build2", vec![UpgradeInstruction::Restart]),
4432        ];
4433        validate_upgrade_from(&entries).unwrap();
4434    }
4435
4436    #[test]
4437    fn validate_upgrade_from_per_entry_shape_fires_before_duplicate() {
4438        // Order pin: a malformed `:from` on the second entry surfaces
4439        // its `FromInvalid` diagnostic, not a (less-useful)
4440        // `DuplicateFrom`. The per-entry shape pass runs *inline*
4441        // before the duplicate-key insert — parallel to
4442        // `child_versao_invalid_fires_before_duplicate_check`
4443        // (b38ff3a) and `membro_versao_invalid_fires_before_duplicate_check`
4444        // (9888b13). Without this pin a future shortcut that runs the
4445        // cross-entry gate first would surface a duplicate diagnostic
4446        // on a string that isn't even parsable as a version.
4447        let entries = vec![
4448            entry("0.1.0", vec![UpgradeInstruction::Restart]),
4449            entry("not-a-semver", vec![UpgradeInstruction::Restart]),
4450        ];
4451        let err = validate_upgrade_from(&entries).unwrap_err();
4452        assert!(
4453            matches!(err, UpgradeError::FromInvalid { ref from, .. } if from == "not-a-semver"),
4454            "malformed `:from` on a non-duplicate entry must surface as FromInvalid, got {err:?}"
4455        );
4456    }
4457
4458    #[test]
4459    fn validate_upgrade_from_per_entry_shape_fires_before_duplicate_on_first_entry() {
4460        // Symmetric arm: a malformed shape on the *first* entry of a
4461        // duplicate pair surfaces its per-entry diagnostic too (not
4462        // the duplicate diagnostic that would otherwise fire on the
4463        // second entry). Pinned separately so a future shortcut that
4464        // walks the duplicate-check ahead of the per-entry pass for the
4465        // first entry only — easy regression to introduce — surfaces
4466        // here.
4467        let entries = vec![
4468            entry(
4469                "0.1.0",
4470                vec![UpgradeInstruction::LoadModule {
4471                    module: String::new(),
4472                }],
4473            ),
4474            entry("0.1.0", vec![UpgradeInstruction::Restart]),
4475        ];
4476        let err = validate_upgrade_from(&entries).unwrap_err();
4477        assert_eq!(
4478            err,
4479            UpgradeError::ModuleEmpty {
4480                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
4481            },
4482            "malformed instruction on the first entry of a duplicate pair must surface its \
4483             per-entry diagnostic before the duplicate gate fires, got {err:?}"
4484        );
4485    }
4486
4487    #[test]
4488    fn validate_upgrade_from_duplicate_diagnostic_names_second_collision() {
4489        // Diagnostic-shape pin: when three entries carry the same
4490        // `:from`, the gate reports the *first* collision (the second
4491        // entry) and stops — the third entry's duplicate is masked by
4492        // the first surfaced one. Mirrors
4493        // `validate_duplicate_child_diagnostic_names_first_collision`
4494        // (dbf50a9) on the supervisor axis.
4495        let entries = vec![
4496            entry("0.1.0", vec![UpgradeInstruction::Restart]),
4497            entry("0.1.0", vec![UpgradeInstruction::Restart]),
4498            entry("0.1.0", vec![UpgradeInstruction::Restart]),
4499        ];
4500        let err = validate_upgrade_from(&entries).unwrap_err();
4501        assert_eq!(
4502            err,
4503            UpgradeError::DuplicateFrom {
4504                from: "0.1.0".into()
4505            }
4506        );
4507    }
4508
4509    #[test]
4510    fn validate_upgrade_from_single_entry_never_duplicates() {
4511        // Boundary control: a list of one entry can never produce a
4512        // duplicate, regardless of `:from` value (any single-element
4513        // set is trivially without duplicates). Pin this so a future
4514        // off-by-one in the seen-set insert doesn't accidentally flag
4515        // a single entry as duplicating itself.
4516        let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
4517        validate_upgrade_from(&entries).unwrap();
4518    }
4519
4520    // ── validate_upgrade_from_against_versao: cross-slot precedence gate ─
4521
4522    #[test]
4523    fn versao_gate_accepts_strict_upgrade() {
4524        // Positive control: the canonical "chain prior versions →
4525        // current" authoring shape from ABSORPTION-ROADMAP §M2.3 — each
4526        // `:from` strictly less than the current `:versao` under
4527        // SemVer-2 precedence. The gate must not regress this baseline.
4528        let entries = vec![
4529            entry("0.1.0", vec![UpgradeInstruction::Restart]),
4530            entry("0.1.5", vec![UpgradeInstruction::Restart]),
4531            entry("0.1.9", vec![UpgradeInstruction::Restart]),
4532        ];
4533        validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
4534    }
4535
4536    #[test]
4537    fn versao_gate_accepts_empty_entries() {
4538        // Bare `feira init` shape (no `:upgrade-from`) trivially passes;
4539        // the gate is a no-op when the entries list is empty. Mirrors
4540        // `validate_upgrade_from_accepts_empty_list` on the peer gate.
4541        validate_upgrade_from_against_versao(&[], "0.1.0").unwrap();
4542    }
4543
4544    #[test]
4545    fn versao_gate_rejects_equal_from() {
4546        // Self-upgrade no-op: declaring `:from "0.2.0"` while
4547        // `:versao "0.2.0"` means "upgrade from myself to myself" —
4548        // the operator's dispatch either skips silently or
4549        // trivially "succeeds" with no observable state change.
4550        // Reject as the canonical "I forgot to bump :versao when
4551        // adding this entry" footgun.
4552        let entries = vec![entry("0.2.0", vec![UpgradeInstruction::Restart])];
4553        let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
4554        assert_eq!(
4555            err,
4556            UpgradeError::FromNotBeforeVersao {
4557                from: "0.2.0".into(),
4558                versao: "0.2.0".into(),
4559            },
4560            ":from == :versao under precedence must surface as FromNotBeforeVersao naming both \
4561             values verbatim, got {err:?}"
4562        );
4563    }
4564
4565    #[test]
4566    fn versao_gate_rejects_downgrade_from() {
4567        // Downgrade-shaped: `:from "0.3.0"` while `:versao "0.2.0"`
4568        // means "upgrade nodes coming from 0.3.0 to 0.2.0", which
4569        // the operator's `:from`-match dispatch can never reach (it
4570        // never runs a version >= the current one). Reject as the
4571        // canonical "I copy-pasted from the next minor version and
4572        // forgot to bump :versao" footgun.
4573        let entries = vec![entry("0.3.0", vec![UpgradeInstruction::Restart])];
4574        let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
4575        assert_eq!(
4576            err,
4577            UpgradeError::FromNotBeforeVersao {
4578                from: "0.3.0".into(),
4579                versao: "0.2.0".into(),
4580            }
4581        );
4582    }
4583
4584    #[test]
4585    fn versao_gate_accepts_prerelease_before_release() {
4586        // SemVer §11 precedence: pre-release versions are *less than*
4587        // the corresponding release (`0.2.0-rc.1 < 0.2.0`). Upgrading
4588        // FROM an RC TO the GA release is the canonical authoring
4589        // shape — must pass. A regression that collapses pre-release
4590        // into the release version (treating them as equal) surfaces
4591        // here as a false-positive rejection.
4592        let entries = vec![entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart])];
4593        validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
4594    }
4595
4596    #[test]
4597    fn versao_gate_rejects_release_after_prerelease() {
4598        // Symmetric arm: with `:versao "0.2.0-rc.1"` and
4599        // `:from "0.2.0"`, precedence says `0.2.0 > 0.2.0-rc.1` —
4600        // the typical "I'm on an RC of a release that already
4601        // shipped" footgun. The gate names both values verbatim
4602        // so the author can grep for either side and fix in one
4603        // edit.
4604        let entries = vec![entry("0.2.0", vec![UpgradeInstruction::Restart])];
4605        let err = validate_upgrade_from_against_versao(&entries, "0.2.0-rc.1").unwrap_err();
4606        assert_eq!(
4607            err,
4608            UpgradeError::FromNotBeforeVersao {
4609                from: "0.2.0".into(),
4610                versao: "0.2.0-rc.1".into(),
4611            }
4612        );
4613    }
4614
4615    #[test]
4616    fn versao_gate_rejects_build_metadata_only_difference() {
4617        // SemVer §11 explicitly excludes build metadata from
4618        // precedence comparison: `0.2.0+build.1` and `0.2.0` are
4619        // *equal* under [`semver::Version::cmp`]. From the
4620        // operator's `:from`-match dispatch perspective this is a
4621        // self-upgrade no-op (no semantic transition between the
4622        // two), so the gate rejects it — *unlike* the peer
4623        // duplicate-`:from` gate which uses derived `PartialEq` and
4624        // treats build-metadata variants as distinct dispatch keys.
4625        // The two gates' different equality notions are deliberate:
4626        // duplicate-check is conservative (preserves operator-side
4627        // tiebreaking surface), precedence-check is permissive
4628        // (matches operator-side dispatch semantic).
4629        let entries = vec![entry("0.2.0+build.1", vec![UpgradeInstruction::Restart])];
4630        let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
4631        assert_eq!(
4632            err,
4633            UpgradeError::FromNotBeforeVersao {
4634                from: "0.2.0+build.1".into(),
4635                versao: "0.2.0".into(),
4636            }
4637        );
4638    }
4639
4640    #[test]
4641    fn versao_gate_silently_passes_on_unparseable_versao() {
4642        // Defensive arm: a malformed `:versao` (gated by the
4643        // narrower `ManifestError::VersaoInvalid` surface at the
4644        // load-bearing call site) must not regress into a
4645        // `FromNotBeforeVersao` diagnostic from this gate. Surfacing
4646        // the precedence error over an unparseable `:versao` would
4647        // mask the more actionable root cause (the author meant to
4648        // type `"0.2.0"`, not `"v0.2.0"`).
4649        let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
4650        validate_upgrade_from_against_versao(&entries, "not-a-semver").unwrap();
4651    }
4652
4653    #[test]
4654    fn versao_gate_silently_passes_on_unparseable_from() {
4655        // Symmetric defensive arm: a malformed `:from` is gated by
4656        // [`UpgradeFromEntry::validate`] / [`validate_upgrade_from`]
4657        // upstream at the LayoutInvariants call site. Surfacing the
4658        // precedence error over an unparseable `:from` from this
4659        // gate alone would mask the narrower `FromInvalid`
4660        // diagnostic that's expected to lead — same fall-through
4661        // posture as the unparseable-`:versao` arm above. The
4662        // wiring in `LayoutInvariants::verify` runs
4663        // `validate_upgrade_from` *before* this gate, so in practice
4664        // an unparseable `:from` surfaces as `FromInvalid` first
4665        // and this gate is never reached on that input.
4666        let entries = vec![entry("not-a-semver", vec![UpgradeInstruction::Restart])];
4667        validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
4668    }
4669
4670    #[test]
4671    fn versao_gate_reports_first_offending_entry() {
4672        // Determinism pin: with multiple offending entries the gate
4673        // surfaces the *first* one in declaration order — same
4674        // posture as `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
4675        // on the peer gate. Walks the entries in order; first
4676        // failing `:from >= :versao` short-circuits.
4677        let entries = vec![
4678            entry("0.1.0", vec![UpgradeInstruction::Restart]),
4679            entry("0.3.0", vec![UpgradeInstruction::Restart]),
4680            entry("0.4.0", vec![UpgradeInstruction::Restart]),
4681        ];
4682        let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
4683        assert_eq!(
4684            err,
4685            UpgradeError::FromNotBeforeVersao {
4686                from: "0.3.0".into(),
4687                versao: "0.2.0".into(),
4688            },
4689            "the first offending `:from` (0.3.0) must surface, not the later one (0.4.0)"
4690        );
4691    }
4692
4693    // ── UpgradeFromEntry::validate_restart_exclusive: within-entry gate ─
4694
4695    #[test]
4696    fn validate_rejects_restart_mixed_with_load_module() {
4697        // The "I'll try the typed path *then* restart anyway" footgun:
4698        // an instructions list with `(:restart)` plus `(:load-module …)`
4699        // is dead code in both directions (succeed → restart discards
4700        // the work that just succeeded, defeating the typed sequence's
4701        // whole point; fail → restart never reached because the entry
4702        // already failed). The gate names the offending entry's `:from`
4703        // verbatim plus the kebab-case lisp-form of every non-`:restart`
4704        // peer so the author can grep their caixa.lisp for either side
4705        // and fix in one edit.
4706        let e = entry(
4707            "0.1.0",
4708            vec![
4709                UpgradeInstruction::LoadModule {
4710                    module: "hello-rio".into(),
4711                },
4712                UpgradeInstruction::Restart,
4713            ],
4714        );
4715        let err = e.validate().unwrap_err();
4716        assert_eq!(
4717            err,
4718            UpgradeError::RestartNotExclusive {
4719                from: "0.1.0".into(),
4720                restart_count: 1,
4721                other_kinds: vec![crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE],
4722            },
4723            "restart + load-module mix must surface as RestartNotExclusive naming the \
4724             offending `:from` + the non-:restart kinds verbatim, got {err:?}"
4725        );
4726    }
4727
4728    #[test]
4729    fn validate_rejects_restart_mixed_with_full_typed_sequence() {
4730        // Sweep the typed-sequence universe — every non-`:restart`
4731        // variant alongside `:restart` — and assert every typed
4732        // instruction's lisp-form appears in `other_kinds` in
4733        // declaration order. The author should be able to grep for
4734        // each verbatim (`:load-module`, `:state-change`, `:soft-purge`,
4735        // `:purge`) and resolve in one pass. Drift in the `lisp_form`
4736        // mapping surfaces here.
4737        let e = entry(
4738            "0.1.0",
4739            vec![
4740                UpgradeInstruction::LoadModule {
4741                    module: "hello-rio".into(),
4742                },
4743                UpgradeInstruction::StateChange {
4744                    script: PathBuf::from("lib/m.lisp"),
4745                },
4746                UpgradeInstruction::SoftPurge {
4747                    module: "hello-rio-old".into(),
4748                },
4749                UpgradeInstruction::Purge {
4750                    module: "hello-rio-old".into(),
4751                },
4752                UpgradeInstruction::Restart,
4753            ],
4754        );
4755        let err = e.validate().unwrap_err();
4756        assert_eq!(
4757            err,
4758            UpgradeError::RestartNotExclusive {
4759                from: "0.1.0".into(),
4760                restart_count: 1,
4761                other_kinds: vec![
4762                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
4763                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
4764                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4765                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4766                ],
4767            },
4768        );
4769    }
4770
4771    #[test]
4772    fn validate_rejects_restart_duplicated() {
4773        // `((:restart) (:restart))` — multiple Restart variants in one
4774        // entry. The fallback is a single semantic (restart the pod;
4775        // the new version comes up fresh); repeating it is at best
4776        // redundant, at worst suggests the author thought the second
4777        // would re-trigger after the first. The gate reports
4778        // `restart_count: 2` so the diagnostic surfaces the duplication
4779        // mode unambiguously even when `other_kinds` is empty.
4780        let e = entry(
4781            "0.1.0",
4782            vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
4783        );
4784        let err = e.validate().unwrap_err();
4785        assert_eq!(
4786            err,
4787            UpgradeError::RestartNotExclusive {
4788                from: "0.1.0".into(),
4789                restart_count: 2,
4790                other_kinds: vec![],
4791            },
4792        );
4793    }
4794
4795    #[test]
4796    fn validate_accepts_sole_restart() {
4797        // Positive control: the canonical "this prior version's typed
4798        // upgrade is impossible — restart" authoring shape from the
4799        // UpgradeInstruction::Restart doc comment. `((:restart))` alone
4800        // is the entry's whole instructions list and the only valid
4801        // Restart-bearing shape.
4802        let e = entry("0.1.0", vec![UpgradeInstruction::Restart]);
4803        e.validate().unwrap();
4804    }
4805
4806    #[test]
4807    fn validate_accepts_typed_sequence_without_restart() {
4808        // Positive control: the canonical typed hot-upgrade authoring
4809        // shape from ABSORPTION-ROADMAP §M2.3 — `:load-module` →
4810        // `:state-change` → `:soft-purge`. Absent `:restart` is the
4811        // only shape that lets the sequence run to completion under
4812        // the wasm-operator's `:from`-match dispatch. Drift here =
4813        // a future tighten that rejects any canonical typed-only shape
4814        // surfaces as a regression at this gate.
4815        let e = entry(
4816            "0.1.0",
4817            vec![
4818                UpgradeInstruction::LoadModule {
4819                    module: "hello-rio".into(),
4820                },
4821                UpgradeInstruction::StateChange {
4822                    script: PathBuf::from("lib/m.lisp"),
4823                },
4824                UpgradeInstruction::SoftPurge {
4825                    module: "hello-rio-old".into(),
4826                },
4827            ],
4828        );
4829        e.validate().unwrap();
4830    }
4831
4832    // ── within-entry state-change-ordering invariant ───────────────────
4833
4834    #[test]
4835    fn validate_rejects_state_change_without_load() {
4836        // Fail-before-pass-after pin: a `:state-change` migrates state
4837        // into the newly-loaded code (gen_server:code_change/3 analog),
4838        // so an entry that runs it with no preceding `:load-module`
4839        // migrates state into code that was never loaded. The operator
4840        // runs instructions in declared order, so this is a build error,
4841        // not a runtime surprise (CAIXA-SDLC §III).
4842        let e = entry(
4843            "0.1.0",
4844            vec![UpgradeInstruction::StateChange {
4845                script: PathBuf::from("lib/m.lisp"),
4846            }],
4847        );
4848        let err = e.validate().unwrap_err();
4849        assert_eq!(
4850            err,
4851            UpgradeError::StateChangeWithoutPriorLoad {
4852                from: "0.1.0".into(),
4853                script: PathBuf::from("lib/m.lisp"),
4854            },
4855            "a `:state-change` with no preceding `:load-module` must surface as \
4856             StateChangeWithoutPriorLoad naming the offending entry + script verbatim"
4857        );
4858    }
4859
4860    #[test]
4861    fn validate_rejects_state_change_before_load() {
4862        // Right-instructions-wrong-order: the load is present but runs
4863        // *after* the migration. Because the operator executes in
4864        // declared order, the migration runs before the new code is
4865        // resident — the same incoherence as the missing-load case.
4866        let e = entry(
4867            "0.1.0",
4868            vec![
4869                UpgradeInstruction::StateChange {
4870                    script: PathBuf::from("lib/m.lisp"),
4871                },
4872                UpgradeInstruction::LoadModule {
4873                    module: "hello-rio".into(),
4874                },
4875            ],
4876        );
4877        let err = e.validate().unwrap_err();
4878        assert!(
4879            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
4880            "a `:state-change` ahead of its `:load-module` must surface as \
4881             StateChangeWithoutPriorLoad, got {err:?}"
4882        );
4883    }
4884
4885    #[test]
4886    fn validate_accepts_state_change_after_load() {
4887        // Positive control: the canonical `(:load-module …)
4888        // (:state-change …)` order validates. The load need not name
4889        // the same module the migration targets (StateChange carries a
4890        // script, not a module ref), so any preceding `:load-module`
4891        // satisfies "new code is resident before its migration runs".
4892        let e = entry(
4893            "0.1.0",
4894            vec![
4895                UpgradeInstruction::LoadModule {
4896                    module: "hello-rio".into(),
4897                },
4898                UpgradeInstruction::StateChange {
4899                    script: PathBuf::from("lib/m.lisp"),
4900                },
4901            ],
4902        );
4903        e.validate().unwrap();
4904    }
4905
4906    #[test]
4907    fn validate_accepts_multiple_state_changes_after_one_load() {
4908        // A single leading `:load-module` covers every subsequent
4909        // `:state-change` — the `loaded` latch stays set once the new
4910        // code is resident.
4911        let e = entry(
4912            "0.1.0",
4913            vec![
4914                UpgradeInstruction::LoadModule {
4915                    module: "hello-rio".into(),
4916                },
4917                UpgradeInstruction::StateChange {
4918                    script: PathBuf::from("lib/m1.lisp"),
4919                },
4920                UpgradeInstruction::StateChange {
4921                    script: PathBuf::from("lib/m2.lisp"),
4922                },
4923            ],
4924        );
4925        e.validate().unwrap();
4926    }
4927
4928    #[test]
4929    fn validate_state_change_ordering_projects_scripts_through_is_load_module_and_declared_path_accessors()
4930     {
4931        // Byte-identity pin on the
4932        // [`UpgradeFromEntry::validate_state_change_ordering`] load →
4933        // migrate ordering dispatch against the pre-lift
4934        // `match instr { UpgradeInstruction::LoadModule { .. } =>
4935        // loaded = true, UpgradeInstruction::StateChange { script } if
4936        // !loaded => …, _ => {} }` open-coded pattern-match the site
4937        // previously carried. Asserts the two projections agree
4938        // byte-for-byte on every arm of the enum — the load-family
4939        // arm-discriminator via `is_load_module()` and the migration-
4940        // family `:script` scalar via `declared_path()` — so a future
4941        // derive regression that flipped the predicate's arm-set (a
4942        // hole returning `false` for [`UpgradeInstruction::LoadModule`],
4943        // a byte-collision flipping a second variant to `true`) or an
4944        // accessor extension that promoted an additional variant onto
4945        // the `PathBuf`-carrying axis would trip here at caixa-core
4946        // test time rather than laundering the arm at the gate's
4947        // per-entry ordering scan far from the derive site.
4948        //
4949        // Peer of the sibling
4950        // [`validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors`]
4951        // (c9ce91d) pin on the peer within-entry per-instruction-class
4952        // singularity gate's load-family + `String`-carrying dispatch,
4953        // the [`validate_purge_ordering_routes_through_is_load_module_predicate`]
4954        // (580d0f1) pin on the paired load → cleanup ordering gate's
4955        // load-family sticky-latch dispatch, and the
4956        // [`validate_state_change_singularity_projects_scripts_through_declared_path_accessor`]
4957        // pin on the peer within-entry per-instruction-class singularity
4958        // gate's migration-family script-projection dispatch — closes
4959        // the last unlifted `match`-shaped per-arm-hand-rolled load-
4960        // family arm-discriminator + migration-family script-projection
4961        // pair inside `impl UpgradeFromEntry`. The four within-entry
4962        // ordering / singularity gates now share one byte-identity pin
4963        // apiece against their respective substrate-primitive typed
4964        // dispatches on the OTP-appup closed-set enum.
4965        //
4966        // Three-arm projective coverage:
4967        //   (a) `LoadModule` satisfies `is_load_module()`, so the
4968        //       sticky-latch advances byte-equal to the pre-lift
4969        //       `UpgradeInstruction::LoadModule { .. }` arm; every
4970        //       other variant leaves the latch untouched;
4971        //   (b) a `((:state-change …))`-only entry (no preceding load)
4972        //       trips the gate on the first `StateChange` with
4973        //       `StateChangeWithoutPriorLoad` carrying the offending
4974        //       script verbatim — the migration-family script surfaces
4975        //       through `declared_path()` byte-equal to the raw
4976        //       `StateChange { script }` pattern-bound field;
4977        //   (c) a `((:load-module …) (:state-change …))` entry leaves
4978        //       the gate vacuous with `Ok(())` — the `loaded = true`
4979        //       latch on the first arm satisfies the `!loaded` guard
4980        //       negation on the second, so the `declared_path()`
4981        //       `Some(script)` fall-through does not fire — and a
4982        //       non-`StateChange`-non-`LoadModule` sequence
4983        //       (`SoftPurge` / `Purge` / `Restart` alone) also leaves
4984        //       the gate vacuous because `declared_path()` is `None`
4985        //       on all three of those arms.
4986        //
4987        // Fail-before-pass-after verified locally: swapping the
4988        // production `if instr.is_load_module() { loaded = true; }
4989        // else if !loaded && let Some(script) = instr.declared_path()
4990        // { … }` back to `match instr { UpgradeInstruction::LoadModule
4991        // { .. } => loaded = true, UpgradeInstruction::StateChange
4992        // { script } if !loaded => …, _ => {} }` keeps arms (a)-(c)
4993        // passing but silently detaches the gate from the accessor's
4994        // typed dispatch — any future `is_load_module` / `declared_path`
4995        // extension (a hole in either predicate, a promotion of an
4996        // additional variant onto either axis, an operator-side
4997        // pre-resolved-path cache the accessor materializes) would
4998        // then silently disagree between this gate's raw pattern-match
4999        // and the peer per-`UpgradeInstruction` consumers that route
5000        // through the accessor pair.
5001
5002        // (a) is_load_module() partitions the arm-set byte-equal to
5003        //     the pre-lift `matches!(_, UpgradeInstruction::LoadModule
5004        //     { .. })` and declared_path() surfaces the StateChange
5005        //     `:script` byte-equal to the raw field access.
5006        let lm = UpgradeInstruction::LoadModule {
5007            module: "hello-rio".into(),
5008        };
5009        assert!(
5010            lm.is_load_module(),
5011            "LoadModule must satisfy is_load_module() — the gate's \
5012             load-family sticky-latch relies on this partition"
5013        );
5014        assert!(
5015            lm.declared_path().is_none(),
5016            "LoadModule must not carry a declared_path — the gate's \
5017             else-if migration-family arm must not fire on load arms"
5018        );
5019        let sc = UpgradeInstruction::StateChange {
5020            script: PathBuf::from("lib/m.lisp"),
5021        };
5022        assert!(
5023            !sc.is_load_module(),
5024            "StateChange must not satisfy is_load_module() — the gate's \
5025             sticky-latch must not advance on migration arms"
5026        );
5027        assert_eq!(
5028            sc.declared_path().map(std::path::PathBuf::as_path),
5029            Some(PathBuf::from("lib/m.lisp").as_path()),
5030            "declared_path() must project the StateChange :script \
5031             byte-equal to the raw field access — accessor divergence \
5032             would silently detach the gate from the projection every \
5033             peer per-`UpgradeInstruction` consumer routes through"
5034        );
5035
5036        // (b) A `((:state-change …))`-only entry trips
5037        //     StateChangeWithoutPriorLoad byte-identical to the
5038        //     pre-lift match-pattern shape.
5039        let no_prior_load = entry(
5040            "0.1.0",
5041            vec![UpgradeInstruction::StateChange {
5042                script: PathBuf::from("lib/m.lisp"),
5043            }],
5044        );
5045        assert_eq!(
5046            no_prior_load.validate_state_change_ordering(),
5047            Err(UpgradeError::StateChangeWithoutPriorLoad {
5048                from: "0.1.0".into(),
5049                script: PathBuf::from("lib/m.lisp"),
5050            }),
5051            "a `:state-change` with no preceding `:load-module` must fire \
5052             StateChangeWithoutPriorLoad carrying the offending script \
5053             verbatim through the declared_path() accessor"
5054        );
5055
5056        // (c) `((:load-module …) (:state-change …))` leaves the gate
5057        //     vacuous; so does a non-StateChange-non-LoadModule
5058        //     sequence (SoftPurge / Purge / Restart alone).
5059        let load_before_migrate = entry(
5060            "0.1.0",
5061            vec![
5062                UpgradeInstruction::LoadModule {
5063                    module: "hello-rio".into(),
5064                },
5065                UpgradeInstruction::StateChange {
5066                    script: PathBuf::from("lib/m.lisp"),
5067                },
5068            ],
5069        );
5070        assert_eq!(
5071            load_before_migrate.validate_state_change_ordering(),
5072            Ok(()),
5073            "load-before-migrate entries must leave the ordering gate \
5074             vacuous — the `loaded = true` sticky-latch on the first arm \
5075             satisfies the `!loaded` guard negation on the else-if arm"
5076        );
5077        for instr in [
5078            UpgradeInstruction::SoftPurge {
5079                module: "x-old".into(),
5080            },
5081            UpgradeInstruction::Purge {
5082                module: "x-old".into(),
5083            },
5084            UpgradeInstruction::Restart,
5085        ] {
5086            let e = entry("0.1.0", vec![instr.clone()]);
5087            assert_eq!(
5088                e.validate_state_change_ordering(),
5089                Ok(()),
5090                "non-StateChange-non-LoadModule sequence ({instr:?}) must \
5091                 leave the ordering gate vacuous — declared_path() is None \
5092                 on every non-StateChange arm, so the else-if migration-\
5093                 family arm never fires"
5094            );
5095        }
5096    }
5097
5098    #[test]
5099    fn validate_state_change_ordering_fires_after_restart_exclusive() {
5100        // Diagnostic-precedence pin: a `((:state-change …) (:restart))`
5101        // shape is *both* state-change-without-load and restart-mixed.
5102        // The more-fundamental `RestartNotExclusive` must win (a valid
5103        // `(:restart)` entry is `(:restart)` alone, so no Restart-bearing
5104        // entry should reach the ordering gate). Guards the call order
5105        // in `validate` against silent reordering.
5106        let e = entry(
5107            "0.1.0",
5108            vec![
5109                UpgradeInstruction::StateChange {
5110                    script: PathBuf::from("lib/m.lisp"),
5111                },
5112                UpgradeInstruction::Restart,
5113            ],
5114        );
5115        let err = e.validate().unwrap_err();
5116        assert!(
5117            matches!(err, UpgradeError::RestartNotExclusive { .. }),
5118            "restart-mixed must surface before the ordering gate, got {err:?}"
5119        );
5120    }
5121
5122    // ── within-entry purge-ordering invariant ──────────────────────────
5123
5124    #[test]
5125    fn validate_rejects_soft_purge_without_load() {
5126        // Fail-before-pass-after pin: `:soft-purge` drains the *old*
5127        // module after the new one is resident (OTP's two-phase code
5128        // load — code:load_module/1 then code:soft_purge/1), so an
5129        // entry that runs it with no preceding `:load-module` drains
5130        // the live module with no replacement. The operator runs
5131        // instructions in declared order, so this is a build error,
5132        // not a runtime surprise (CAIXA-SDLC §III).
5133        let e = entry(
5134            "0.1.0",
5135            vec![UpgradeInstruction::SoftPurge {
5136                module: "x-old".into(),
5137            }],
5138        );
5139        let err = e.validate().unwrap_err();
5140        assert_eq!(
5141            err,
5142            UpgradeError::PurgeWithoutPriorLoad {
5143                from: "0.1.0".into(),
5144                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5145                module: "x-old".into(),
5146            },
5147            "a `:soft-purge` with no preceding `:load-module` must surface as \
5148             PurgeWithoutPriorLoad naming the offending entry + kind + module verbatim"
5149        );
5150    }
5151
5152    #[test]
5153    fn validate_rejects_purge_without_load() {
5154        // Per-arm coverage: `:purge` (immediate discard, no drain) is
5155        // the more catastrophic peer of `:soft-purge`; same gate, same
5156        // shape, kind-tag differs so the author can grep their
5157        // caixa.lisp for the offending `(:purge …)` form.
5158        let e = entry(
5159            "0.1.0",
5160            vec![UpgradeInstruction::Purge {
5161                module: "x-old".into(),
5162            }],
5163        );
5164        let err = e.validate().unwrap_err();
5165        assert_eq!(
5166            err,
5167            UpgradeError::PurgeWithoutPriorLoad {
5168                from: "0.1.0".into(),
5169                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5170                module: "x-old".into(),
5171            },
5172        );
5173    }
5174
5175    #[test]
5176    fn validate_rejects_soft_purge_before_load() {
5177        // Right-instructions-wrong-order: the load is present but runs
5178        // *after* the purge. Because the operator executes in declared
5179        // order, the cleanup drains the old code before the new code
5180        // is resident — same incoherence as the missing-load case,
5181        // leaving a window during which neither version is available.
5182        let e = entry(
5183            "0.1.0",
5184            vec![
5185                UpgradeInstruction::SoftPurge {
5186                    module: "x-old".into(),
5187                },
5188                UpgradeInstruction::LoadModule { module: "x".into() },
5189            ],
5190        );
5191        let err = e.validate().unwrap_err();
5192        assert!(
5193            matches!(
5194                err,
5195                UpgradeError::PurgeWithoutPriorLoad {
5196                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5197                    ..
5198                }
5199            ),
5200            "a `:soft-purge` ahead of its `:load-module` must surface as \
5201             PurgeWithoutPriorLoad, got {err:?}"
5202        );
5203    }
5204
5205    #[test]
5206    fn validate_rejects_purge_before_load() {
5207        // Symmetric arm on the `:purge` variant — the kind tag
5208        // distinguishes the diagnostic so the author lands on the
5209        // offending form directly.
5210        let e = entry(
5211            "0.1.0",
5212            vec![
5213                UpgradeInstruction::Purge {
5214                    module: "x-old".into(),
5215                },
5216                UpgradeInstruction::LoadModule { module: "x".into() },
5217            ],
5218        );
5219        let err = e.validate().unwrap_err();
5220        assert!(
5221            matches!(
5222                err,
5223                UpgradeError::PurgeWithoutPriorLoad {
5224                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5225                    ..
5226                }
5227            ),
5228            "a `:purge` ahead of its `:load-module` must surface as \
5229             PurgeWithoutPriorLoad, got {err:?}"
5230        );
5231    }
5232
5233    #[test]
5234    fn validate_accepts_soft_purge_after_load() {
5235        // Positive control: the canonical `(:load-module …)
5236        // (:soft-purge …)` order validates. The load need not name the
5237        // same module the purge targets — the cleanup typically targets
5238        // the *old* module name (e.g. `"x-old"`) and the load brings up
5239        // the *new* one (`"x"`); the gate only requires that *some*
5240        // `:load-module` precedes the purge, so the new code is resident
5241        // before the old one is drained.
5242        let e = entry(
5243            "0.1.0",
5244            vec![
5245                UpgradeInstruction::LoadModule { module: "x".into() },
5246                UpgradeInstruction::SoftPurge {
5247                    module: "x-old".into(),
5248                },
5249            ],
5250        );
5251        e.validate().unwrap();
5252    }
5253
5254    #[test]
5255    fn validate_accepts_multiple_purges_after_one_load() {
5256        // A single leading `:load-module` covers every subsequent
5257        // `:soft-purge` / `:purge` — the `loaded` latch stays set once
5258        // the new code is resident. Same shape as
5259        // `validate_accepts_multiple_state_changes_after_one_load` on
5260        // the peer ordering gate.
5261        let e = entry(
5262            "0.1.0",
5263            vec![
5264                UpgradeInstruction::LoadModule { module: "x".into() },
5265                UpgradeInstruction::SoftPurge {
5266                    module: "x-old".into(),
5267                },
5268                UpgradeInstruction::Purge {
5269                    module: "x-oldest".into(),
5270                },
5271            ],
5272        );
5273        e.validate().unwrap();
5274    }
5275
5276    #[test]
5277    fn validate_purge_ordering_fires_after_state_change_ordering() {
5278        // Diagnostic-precedence pin: an entry like `((:state-change …)
5279        // (:soft-purge …))` is *both* state-change-without-load and
5280        // purge-without-load. The state-change gate must win — it's
5281        // the load-bearing semantic on this ordering contract, and
5282        // surfacing the purge diagnostic first would mask the more-
5283        // fundamental migration-against-stale-code defect. Guards the
5284        // call order in `validate` against silent reordering.
5285        let e = entry(
5286            "0.1.0",
5287            vec![
5288                UpgradeInstruction::StateChange {
5289                    script: PathBuf::from("lib/m.lisp"),
5290                },
5291                UpgradeInstruction::SoftPurge {
5292                    module: "x-old".into(),
5293                },
5294            ],
5295        );
5296        let err = e.validate().unwrap_err();
5297        assert!(
5298            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5299            "state-change-without-load must surface before purge-without-load, got {err:?}"
5300        );
5301    }
5302
5303    #[test]
5304    fn validate_purge_ordering_fires_after_per_instr_shape() {
5305        // Order pin: a malformed `:module` value on a `:soft-purge` (an
5306        // empty string) surfaces its narrower kind-tagged `ModuleEmpty`
5307        // diagnostic *before* the within-entry purge-ordering gate fires.
5308        // The per-instruction shape pass walks the list inline before
5309        // the ordering checks, so the narrower self-locating diagnostic
5310        // surfaces first — mirrors the empty-first cascade on every peer
5311        // DNS-1123 gate and the `validate_restart_exclusive_fires_after_
5312        // per_instr_shape` pin on the sibling ordering gate.
5313        let e = entry(
5314            "0.1.0",
5315            vec![UpgradeInstruction::SoftPurge {
5316                module: String::new(),
5317            }],
5318        );
5319        let err = e.validate().unwrap_err();
5320        assert_eq!(
5321            err,
5322            UpgradeError::ModuleEmpty {
5323                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE
5324            },
5325            "malformed instruction must surface its kind-tagged diagnostic before the \
5326             purge-ordering gate fires, got {err:?}"
5327        );
5328    }
5329
5330    #[test]
5331    fn validate_purge_ordering_threads_through_validate_upgrade_from() {
5332        // The whole-list entry-point surfaces the per-entry ordering
5333        // error (mirrors
5334        // `validate_state_change_ordering_threads_through_validate_upgrade_from`):
5335        // the gate is reachable from the LayoutInvariants call site, not
5336        // only from a direct `entry.validate()`.
5337        let entries = vec![entry(
5338            "0.1.0",
5339            vec![UpgradeInstruction::Purge {
5340                module: "x-old".into(),
5341            }],
5342        )];
5343        let err = validate_upgrade_from(&entries).unwrap_err();
5344        assert!(
5345            matches!(
5346                err,
5347                UpgradeError::PurgeWithoutPriorLoad {
5348                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5349                    ..
5350                }
5351            ),
5352            "validate_upgrade_from must thread the purge-ordering error, got {err:?}"
5353        );
5354    }
5355
5356    #[test]
5357    fn validate_state_change_ordering_threads_through_validate_upgrade_from() {
5358        // The whole-list entry-point surfaces the per-entry ordering
5359        // error (mirrors `validate_restart_exclusive_threads_through_…`):
5360        // the gate is reachable from the LayoutInvariants call site, not
5361        // only from a direct `entry.validate()`.
5362        let entries = vec![entry(
5363            "0.1.0",
5364            vec![UpgradeInstruction::StateChange {
5365                script: PathBuf::from("lib/m.lisp"),
5366            }],
5367        )];
5368        let err = validate_upgrade_from(&entries).unwrap_err();
5369        assert!(
5370            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5371            "validate_upgrade_from must thread the ordering error, got {err:?}"
5372        );
5373    }
5374
5375    // ── within-entry cleanup-singularity invariant ─────────────────────
5376
5377    #[test]
5378    fn validate_rejects_duplicate_soft_purge_for_same_module() {
5379        // Fail-before-pass-after pin: `:soft-purge` drains-then-GCs
5380        // its target module (code:soft_purge/1 analog); after the
5381        // first the module is gone, so a second `:soft-purge` of the
5382        // same module is at best a no-op and at worst undefined
5383        // (depending on the operator's handling of a non-resident-
5384        // module purge). Author one cleanup per module.
5385        let e = entry(
5386            "0.1.0",
5387            vec![
5388                UpgradeInstruction::LoadModule { module: "x".into() },
5389                UpgradeInstruction::SoftPurge {
5390                    module: "x-old".into(),
5391                },
5392                UpgradeInstruction::SoftPurge {
5393                    module: "x-old".into(),
5394                },
5395            ],
5396        );
5397        let err = e.validate().unwrap_err();
5398        assert_eq!(
5399            err,
5400            UpgradeError::DuplicateCleanup {
5401                from: "0.1.0".into(),
5402                module: "x-old".into(),
5403                kinds: vec![
5404                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5405                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5406                ],
5407            },
5408            "two `:soft-purge` of the same module must surface as DuplicateCleanup naming the \
5409             module + both kinds in declaration order, got {err:?}"
5410        );
5411    }
5412
5413    #[test]
5414    fn validate_rejects_duplicate_purge_for_same_module() {
5415        // Per-arm coverage: `:purge` (immediate discard, no drain) is
5416        // the more catastrophic peer of `:soft-purge`; same gate, same
5417        // shape, kind-tag distinguishes so the author can grep their
5418        // caixa.lisp for the offending `(:purge …)` form.
5419        let e = entry(
5420            "0.1.0",
5421            vec![
5422                UpgradeInstruction::LoadModule { module: "x".into() },
5423                UpgradeInstruction::Purge {
5424                    module: "x-old".into(),
5425                },
5426                UpgradeInstruction::Purge {
5427                    module: "x-old".into(),
5428                },
5429            ],
5430        );
5431        let err = e.validate().unwrap_err();
5432        assert_eq!(
5433            err,
5434            UpgradeError::DuplicateCleanup {
5435                from: "0.1.0".into(),
5436                module: "x-old".into(),
5437                kinds: vec![
5438                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5439                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5440                ],
5441            },
5442        );
5443    }
5444
5445    #[test]
5446    fn validate_rejects_soft_purge_then_purge_for_same_module() {
5447        // Soft-then-hard footgun: the author wrote "drain, and if
5448        // drain doesn't clean up, force-discard", but the operator
5449        // runs declared instructions unconditionally — the `:purge`
5450        // fires whether the `:soft-purge` already discarded the
5451        // module or not, so the imagined fallback semantic is
5452        // missing. Fallback on cleanup failure is the operator's
5453        // job, not authored into the entry. Both kinds carry in
5454        // declaration order so the author can grep for either side
5455        // and pick one.
5456        let e = entry(
5457            "0.1.0",
5458            vec![
5459                UpgradeInstruction::LoadModule { module: "x".into() },
5460                UpgradeInstruction::SoftPurge {
5461                    module: "x-old".into(),
5462                },
5463                UpgradeInstruction::Purge {
5464                    module: "x-old".into(),
5465                },
5466            ],
5467        );
5468        let err = e.validate().unwrap_err();
5469        assert_eq!(
5470            err,
5471            UpgradeError::DuplicateCleanup {
5472                from: "0.1.0".into(),
5473                module: "x-old".into(),
5474                kinds: vec![
5475                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5476                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5477                ],
5478            },
5479        );
5480    }
5481
5482    #[test]
5483    fn validate_rejects_purge_then_soft_purge_for_same_module() {
5484        // Reversed-ordering arm: `:purge` discards immediately; the
5485        // trailing `:soft-purge` has no module to drain. The kinds
5486        // list reflects declaration order so the diagnostic locates
5487        // both forms in the source.
5488        let e = entry(
5489            "0.1.0",
5490            vec![
5491                UpgradeInstruction::LoadModule { module: "x".into() },
5492                UpgradeInstruction::Purge {
5493                    module: "x-old".into(),
5494                },
5495                UpgradeInstruction::SoftPurge {
5496                    module: "x-old".into(),
5497                },
5498            ],
5499        );
5500        let err = e.validate().unwrap_err();
5501        assert_eq!(
5502            err,
5503            UpgradeError::DuplicateCleanup {
5504                from: "0.1.0".into(),
5505                module: "x-old".into(),
5506                kinds: vec![
5507                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5508                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5509                ],
5510            },
5511        );
5512    }
5513
5514    #[test]
5515    fn validate_accepts_distinct_cleanup_modules() {
5516        // Positive control: `:soft-purge` and `:purge` on *different*
5517        // modules pass the gate. Mirrors
5518        // `validate_accepts_multiple_purges_after_one_load` — the
5519        // cleanup-singularity gate is keyed on (module), not on
5520        // (kind, module) pair, so distinct old-version names render
5521        // distinct cleanup targets and don't collide. Sweep both
5522        // same-class (two `:soft-purge` distinct modules) and cross-
5523        // class (`:soft-purge` then `:purge` distinct modules) so a
5524        // future tighten to a kind-only key (which would over-fire on
5525        // distinct modules) surfaces here.
5526        let two_soft = entry(
5527            "0.1.0",
5528            vec![
5529                UpgradeInstruction::LoadModule { module: "x".into() },
5530                UpgradeInstruction::SoftPurge {
5531                    module: "x-old".into(),
5532                },
5533                UpgradeInstruction::SoftPurge {
5534                    module: "x-older".into(),
5535                },
5536            ],
5537        );
5538        two_soft.validate().unwrap();
5539        let mixed = entry(
5540            "0.1.0",
5541            vec![
5542                UpgradeInstruction::LoadModule { module: "x".into() },
5543                UpgradeInstruction::SoftPurge {
5544                    module: "x-old".into(),
5545                },
5546                UpgradeInstruction::Purge {
5547                    module: "x-oldest".into(),
5548                },
5549            ],
5550        );
5551        mixed.validate().unwrap();
5552    }
5553
5554    #[test]
5555    fn validate_accepts_single_cleanup_per_module() {
5556        // Boundary control: a list with exactly one `:soft-purge` and
5557        // one `:purge` (distinct modules, the canonical "drain one,
5558        // hard-discard the other" shape) is the gate's identity
5559        // element. Pin so a future off-by-one in the duplicate-detection
5560        // scan doesn't accidentally flag a single occurrence as
5561        // duplicating itself — mirrors
5562        // `validate_upgrade_from_single_entry_never_duplicates` on
5563        // the peer cross-entry duplicate axis.
5564        let e = entry(
5565            "0.1.0",
5566            vec![
5567                UpgradeInstruction::LoadModule { module: "x".into() },
5568                UpgradeInstruction::SoftPurge {
5569                    module: "x-old".into(),
5570                },
5571                UpgradeInstruction::Purge {
5572                    module: "y-old".into(),
5573                },
5574            ],
5575        );
5576        e.validate().unwrap();
5577    }
5578
5579    #[test]
5580    fn validate_cleanup_singularity_fires_after_purge_ordering() {
5581        // Diagnostic-precedence pin: an entry like `((:soft-purge "x")
5582        // (:soft-purge "x"))` is *both* purge-without-load and
5583        // duplicate-cleanup. The more-fundamental ordering gate must
5584        // win — the missing-load defect is load-bearing (the canonical
5585        // OTP shape requires the new code be resident before any
5586        // cleanup runs), and surfacing the duplicate diagnostic first
5587        // would mask the no-replacement-window defect the ordering
5588        // gate exists to close. Guards the call order in `validate`
5589        // against silent reordering. Same posture as
5590        // `validate_purge_ordering_fires_after_state_change_ordering`
5591        // on the sibling ordering gate.
5592        let e = entry(
5593            "0.1.0",
5594            vec![
5595                UpgradeInstruction::SoftPurge {
5596                    module: "x-old".into(),
5597                },
5598                UpgradeInstruction::SoftPurge {
5599                    module: "x-old".into(),
5600                },
5601            ],
5602        );
5603        let err = e.validate().unwrap_err();
5604        assert!(
5605            matches!(
5606                err,
5607                UpgradeError::PurgeWithoutPriorLoad {
5608                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5609                    ..
5610                }
5611            ),
5612            "purge-without-load must surface before duplicate-cleanup, got {err:?}"
5613        );
5614    }
5615
5616    #[test]
5617    fn validate_cleanup_singularity_fires_after_per_instr_shape() {
5618        // Order pin: a malformed `:module` value on a `:soft-purge`
5619        // (an empty string) surfaces its narrower kind-tagged
5620        // `ModuleEmpty` diagnostic *before* the within-entry cleanup-
5621        // singularity gate fires. The per-instruction shape pass walks
5622        // the list inline before the singularity check, so the
5623        // narrower self-locating diagnostic surfaces first — mirrors
5624        // the empty-first cascade on every peer DNS-1123 gate and the
5625        // `validate_purge_ordering_fires_after_per_instr_shape` pin on
5626        // the sibling ordering gate.
5627        //
5628        // Two empty-string `:soft-purge` would *otherwise* duplicate
5629        // (both modules are the same empty string), so this pin
5630        // double-locks the precedence: the per-instr shape gate must
5631        // win on the first malformed instruction before the duplicate
5632        // scan even reaches the second.
5633        let e = entry(
5634            "0.1.0",
5635            vec![
5636                UpgradeInstruction::LoadModule { module: "x".into() },
5637                UpgradeInstruction::SoftPurge {
5638                    module: String::new(),
5639                },
5640                UpgradeInstruction::SoftPurge {
5641                    module: String::new(),
5642                },
5643            ],
5644        );
5645        let err = e.validate().unwrap_err();
5646        assert_eq!(
5647            err,
5648            UpgradeError::ModuleEmpty {
5649                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE
5650            },
5651            "malformed instruction must surface its kind-tagged diagnostic before the \
5652             cleanup-singularity gate fires, got {err:?}"
5653        );
5654    }
5655
5656    #[test]
5657    fn validate_cleanup_singularity_reports_first_collision() {
5658        // Determinism pin: with three cleanups of the same module the
5659        // gate reports the *first* collision (the second occurrence)
5660        // and stops — the third's duplicate is masked by the first
5661        // surfaced one. Mirrors
5662        // `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
5663        // on the peer cross-entry duplicate axis.
5664        let e = entry(
5665            "0.1.0",
5666            vec![
5667                UpgradeInstruction::LoadModule { module: "x".into() },
5668                UpgradeInstruction::SoftPurge {
5669                    module: "x-old".into(),
5670                },
5671                UpgradeInstruction::SoftPurge {
5672                    module: "x-old".into(),
5673                },
5674                UpgradeInstruction::Purge {
5675                    module: "x-old".into(),
5676                },
5677            ],
5678        );
5679        let err = e.validate().unwrap_err();
5680        assert_eq!(
5681            err,
5682            UpgradeError::DuplicateCleanup {
5683                from: "0.1.0".into(),
5684                module: "x-old".into(),
5685                kinds: vec![
5686                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5687                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5688                ],
5689            },
5690            "the first colliding pair must surface, not the later `:purge` collision"
5691        );
5692    }
5693
5694    #[test]
5695    fn validate_cleanup_singularity_threads_through_validate_upgrade_from() {
5696        // The whole-list entry-point surfaces the per-entry singularity
5697        // error (mirrors
5698        // `validate_purge_ordering_threads_through_validate_upgrade_from`):
5699        // the gate is reachable from the LayoutInvariants call site,
5700        // not only from a direct `entry.validate()`.
5701        let entries = vec![entry(
5702            "0.1.0",
5703            vec![
5704                UpgradeInstruction::LoadModule { module: "x".into() },
5705                UpgradeInstruction::SoftPurge {
5706                    module: "x-old".into(),
5707                },
5708                UpgradeInstruction::Purge {
5709                    module: "x-old".into(),
5710                },
5711            ],
5712        )];
5713        let err = validate_upgrade_from(&entries).unwrap_err();
5714        assert!(
5715            matches!(err, UpgradeError::DuplicateCleanup { .. }),
5716            "validate_upgrade_from must thread the cleanup-singularity error, got {err:?}"
5717        );
5718    }
5719
5720    #[test]
5721    fn validate_rejects_duplicate_load_module_for_same_module() {
5722        // `LoadModule` is the `code:load_module/1` analog (INSPIRATIONS
5723        // §II.4): each module is loaded exactly once per upgrade entry,
5724        // the operator's dispatch table reads the module name to bind
5725        // the wasm component, and a second `(:load-module "x")` re-reads
5726        // the same module name and re-binds the same component — a
5727        // no-op the second time. systools-generated `.relup` files emit
5728        // at most one `load_module` per module per upgrade step for
5729        // this reason. Author one `(:load-module "x")` per old module.
5730        let e = entry(
5731            "0.1.0",
5732            vec![
5733                UpgradeInstruction::LoadModule { module: "x".into() },
5734                UpgradeInstruction::LoadModule { module: "x".into() },
5735            ],
5736        );
5737        let err = e.validate().unwrap_err();
5738        assert_eq!(
5739            err,
5740            UpgradeError::DuplicateLoadModule {
5741                from: "0.1.0".into(),
5742                module: "x".into(),
5743            },
5744            "two `:load-module` of the same module must surface as DuplicateLoadModule naming \
5745             the module, got {err:?}"
5746        );
5747    }
5748
5749    #[test]
5750    fn validate_accepts_distinct_load_modules() {
5751        // Positive control: `:load-module` instructions on *different*
5752        // modules pass the gate. Mirrors
5753        // `validate_accepts_distinct_cleanup_modules` on the sibling
5754        // singularity axis — the load-singularity gate is keyed on
5755        // (module), so distinct module names render distinct load
5756        // targets and don't collide. Sweep both the bare two-load shape
5757        // and the canonical load-pair-with-cleanup shape so a future
5758        // tighten that over-fires on distinct loads surfaces here.
5759        let two_loads = entry(
5760            "0.1.0",
5761            vec![
5762                UpgradeInstruction::LoadModule { module: "x".into() },
5763                UpgradeInstruction::LoadModule { module: "y".into() },
5764            ],
5765        );
5766        two_loads.validate().unwrap();
5767        let with_cleanup = entry(
5768            "0.1.0",
5769            vec![
5770                UpgradeInstruction::LoadModule { module: "x".into() },
5771                UpgradeInstruction::LoadModule { module: "y".into() },
5772                UpgradeInstruction::SoftPurge {
5773                    module: "x-old".into(),
5774                },
5775                UpgradeInstruction::SoftPurge {
5776                    module: "y-old".into(),
5777                },
5778            ],
5779        );
5780        with_cleanup.validate().unwrap();
5781    }
5782
5783    #[test]
5784    fn validate_accepts_single_load_per_module() {
5785        // Boundary control: a list with exactly one `:load-module`
5786        // followed by the canonical `:state-change` + `:soft-purge`
5787        // sequence (the module-doc OTP shape) is the gate's identity
5788        // element. Pin so a future off-by-one in the duplicate-
5789        // detection scan doesn't accidentally flag a single occurrence
5790        // as duplicating itself — mirrors
5791        // `validate_accepts_single_cleanup_per_module` on the sibling
5792        // singularity axis.
5793        let e = entry(
5794            "0.1.0",
5795            vec![
5796                UpgradeInstruction::LoadModule { module: "x".into() },
5797                UpgradeInstruction::StateChange {
5798                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5799                },
5800                UpgradeInstruction::SoftPurge {
5801                    module: "x-old".into(),
5802                },
5803            ],
5804        );
5805        e.validate().unwrap();
5806    }
5807
5808    #[test]
5809    fn validate_load_singularity_fires_after_state_change_ordering() {
5810        // Diagnostic-precedence pin: an entry like `((:state-change
5811        // "m.lisp") (:load-module "x") (:load-module "x"))` is *both*
5812        // state-change-without-load and duplicate-load. The more-
5813        // fundamental ordering gate must win — the missing-load defect
5814        // is load-bearing (the migration runs against unloaded code),
5815        // and surfacing the duplicate diagnostic first would mask the
5816        // migrate-into-unloaded-code defect the ordering gate exists
5817        // to close. Guards the call order in `validate` against silent
5818        // reordering. Same posture as
5819        // `validate_cleanup_singularity_fires_after_purge_ordering`
5820        // on the sibling singularity gate.
5821        let e = entry(
5822            "0.1.0",
5823            vec![
5824                UpgradeInstruction::StateChange {
5825                    script: PathBuf::from("lib/m.lisp"),
5826                },
5827                UpgradeInstruction::LoadModule { module: "x".into() },
5828                UpgradeInstruction::LoadModule { module: "x".into() },
5829            ],
5830        );
5831        let err = e.validate().unwrap_err();
5832        assert!(
5833            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5834            "state-change-without-load must surface before duplicate-load, got {err:?}"
5835        );
5836    }
5837
5838    #[test]
5839    fn validate_load_singularity_fires_after_purge_ordering() {
5840        // Diagnostic-precedence pin: an entry like `((:soft-purge
5841        // "x-old") (:load-module "x") (:load-module "x"))` is *both*
5842        // purge-without-load and duplicate-load. The more-fundamental
5843        // ordering gate must win — the missing-load defect is load-
5844        // bearing (the cleanup runs against no-replacement-window),
5845        // and surfacing the duplicate diagnostic first would mask the
5846        // drain-to-nothing defect the ordering gate exists to close.
5847        // Sibling of
5848        // `validate_cleanup_singularity_fires_after_purge_ordering` on
5849        // the load-singularity axis.
5850        let e = entry(
5851            "0.1.0",
5852            vec![
5853                UpgradeInstruction::SoftPurge {
5854                    module: "x-old".into(),
5855                },
5856                UpgradeInstruction::LoadModule { module: "x".into() },
5857                UpgradeInstruction::LoadModule { module: "x".into() },
5858            ],
5859        );
5860        let err = e.validate().unwrap_err();
5861        assert!(
5862            matches!(
5863                err,
5864                UpgradeError::PurgeWithoutPriorLoad {
5865                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5866                    ..
5867                }
5868            ),
5869            "purge-without-load must surface before duplicate-load, got {err:?}"
5870        );
5871    }
5872
5873    #[test]
5874    fn validate_load_singularity_fires_after_per_instr_shape() {
5875        // Order pin: a malformed `:module` value on a `:load-module`
5876        // (an empty string) surfaces its narrower kind-tagged
5877        // `ModuleEmpty` diagnostic *before* the within-entry load-
5878        // singularity gate fires. The per-instruction shape pass walks
5879        // the list inline before the singularity check, so the
5880        // narrower self-locating diagnostic surfaces first — mirrors
5881        // the empty-first cascade on every peer DNS-1123 gate and the
5882        // `validate_cleanup_singularity_fires_after_per_instr_shape`
5883        // pin on the sibling singularity gate.
5884        //
5885        // Two empty-string `:load-module` would *otherwise* duplicate
5886        // (both modules are the same empty string), so this pin
5887        // double-locks the precedence: the per-instr shape gate must
5888        // win on the first malformed instruction before the duplicate
5889        // scan even reaches the second.
5890        let e = entry(
5891            "0.1.0",
5892            vec![
5893                UpgradeInstruction::LoadModule {
5894                    module: String::new(),
5895                },
5896                UpgradeInstruction::LoadModule {
5897                    module: String::new(),
5898                },
5899            ],
5900        );
5901        let err = e.validate().unwrap_err();
5902        assert_eq!(
5903            err,
5904            UpgradeError::ModuleEmpty {
5905                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
5906            },
5907            "malformed instruction must surface its kind-tagged diagnostic before the \
5908             load-singularity gate fires, got {err:?}"
5909        );
5910    }
5911
5912    #[test]
5913    fn validate_load_singularity_fires_before_cleanup_singularity() {
5914        // Diagnostic-precedence pin: an entry that violates *both*
5915        // singularities — duplicate load on "x" *and* duplicate cleanup
5916        // on "y-old" — must surface the load-side diagnostic first.
5917        // The load axis precedes the cleanup axis in the canonical OTP
5918        // sequence (`code:load_module/1` then `code:soft_purge/1`) and
5919        // in [`UpgradeInstruction`] declaration order (LoadModule
5920        // before SoftPurge/Purge), so the load-side singularity is the
5921        // load-bearing diagnostic when both fire — the cleanup-side
5922        // duplicate is meaningless either way without a coherent load.
5923        // Guards the call order in `validate`: `validate_load_singularity`
5924        // runs before `validate_cleanup_singularity`.
5925        let e = entry(
5926            "0.1.0",
5927            vec![
5928                UpgradeInstruction::LoadModule { module: "x".into() },
5929                UpgradeInstruction::LoadModule { module: "x".into() },
5930                UpgradeInstruction::SoftPurge {
5931                    module: "y-old".into(),
5932                },
5933                UpgradeInstruction::SoftPurge {
5934                    module: "y-old".into(),
5935                },
5936            ],
5937        );
5938        let err = e.validate().unwrap_err();
5939        assert_eq!(
5940            err,
5941            UpgradeError::DuplicateLoadModule {
5942                from: "0.1.0".into(),
5943                module: "x".into(),
5944            },
5945            "duplicate-load must surface before duplicate-cleanup, got {err:?}"
5946        );
5947    }
5948
5949    #[test]
5950    fn validate_load_singularity_reports_first_collision() {
5951        // Determinism pin: with three loads of the same module the gate
5952        // reports the *first* collision (the second occurrence) and
5953        // stops — the third's duplicate is masked by the first surfaced
5954        // one. Mirrors
5955        // `validate_cleanup_singularity_reports_first_collision` on the
5956        // sibling singularity axis and every peer duplicate gate's
5957        // first-collision discipline.
5958        let e = entry(
5959            "0.1.0",
5960            vec![
5961                UpgradeInstruction::LoadModule { module: "x".into() },
5962                UpgradeInstruction::LoadModule { module: "x".into() },
5963                UpgradeInstruction::LoadModule { module: "x".into() },
5964            ],
5965        );
5966        let err = e.validate().unwrap_err();
5967        assert_eq!(
5968            err,
5969            UpgradeError::DuplicateLoadModule {
5970                from: "0.1.0".into(),
5971                module: "x".into(),
5972            },
5973            "the first colliding occurrence must surface, not the later third-load collision"
5974        );
5975    }
5976
5977    #[test]
5978    fn validate_load_singularity_threads_through_validate_upgrade_from() {
5979        // The whole-list entry-point surfaces the per-entry singularity
5980        // error (mirrors
5981        // `validate_cleanup_singularity_threads_through_validate_upgrade_from`):
5982        // the gate is reachable from the LayoutInvariants call site,
5983        // not only from a direct `entry.validate()`.
5984        let entries = vec![entry(
5985            "0.1.0",
5986            vec![
5987                UpgradeInstruction::LoadModule { module: "x".into() },
5988                UpgradeInstruction::LoadModule { module: "x".into() },
5989            ],
5990        )];
5991        let err = validate_upgrade_from(&entries).unwrap_err();
5992        assert!(
5993            matches!(err, UpgradeError::DuplicateLoadModule { .. }),
5994            "validate_upgrade_from must thread the load-singularity error, got {err:?}"
5995        );
5996    }
5997
5998    // ── within-entry state-change-singularity invariant ────────────────
5999
6000    #[test]
6001    fn validate_rejects_duplicate_state_change_for_same_script() {
6002        // `StateChange` is the `gen_server:code_change/3` analog
6003        // (INSPIRATIONS §II.4): the script folds the prior-version
6004        // state shape into the current-version shape — a one-shot
6005        // transition, not a step that composes with itself. OTP's
6006        // release_handler invokes `code_change/3` exactly once per
6007        // upgrade per gen_server; systools-generated `.relup` files
6008        // emit at most one `code_change` per gen_server per upgrade
6009        // step for this reason. A second `(:state-change "m.lisp")`
6010        // re-runs the same fold on the already-migrated state — at
6011        // best a no-op and at worst silent state corruption from
6012        // double-applied non-idempotent transforms (`add column`,
6013        // `increment counter`, `rename field`). Author one
6014        // `(:state-change "m.lisp")` per migration script per entry.
6015        let e = entry(
6016            "0.1.0",
6017            vec![
6018                UpgradeInstruction::LoadModule { module: "x".into() },
6019                UpgradeInstruction::StateChange {
6020                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6021                },
6022                UpgradeInstruction::StateChange {
6023                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6024                },
6025            ],
6026        );
6027        let err = e.validate().unwrap_err();
6028        assert_eq!(
6029            err,
6030            UpgradeError::DuplicateStateChange {
6031                from: "0.1.0".into(),
6032                script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6033            },
6034            "two `:state-change` of the same script must surface as DuplicateStateChange naming \
6035             the script, got {err:?}"
6036        );
6037    }
6038
6039    #[test]
6040    fn validate_accepts_distinct_state_change_scripts() {
6041        // Positive control: `:state-change` instructions on *different*
6042        // scripts pass the gate. Mirrors
6043        // `validate_accepts_distinct_cleanup_modules` /
6044        // `validate_accepts_distinct_load_modules` on the sibling
6045        // singularity axes — the state-change-singularity gate is keyed
6046        // on the script PathBuf, so distinct scripts render distinct
6047        // migration targets and don't collide. Sweep both the bare two-
6048        // migration shape and the canonical load-pair-with-cleanup shape
6049        // so a future tighten that over-fires on distinct scripts
6050        // surfaces here. This positive control is the gate-level peer of
6051        // `validate_accepts_multiple_state_changes_after_one_load` (the
6052        // ordering-gate positive control on distinct scripts), pinned
6053        // here independently so a future refactor that decouples the
6054        // gates can't accidentally drop coverage on either.
6055        let two_migrations = entry(
6056            "0.1.0",
6057            vec![
6058                UpgradeInstruction::LoadModule { module: "x".into() },
6059                UpgradeInstruction::StateChange {
6060                    script: PathBuf::from("lib/m1.lisp"),
6061                },
6062                UpgradeInstruction::StateChange {
6063                    script: PathBuf::from("lib/m2.lisp"),
6064                },
6065            ],
6066        );
6067        two_migrations.validate().unwrap();
6068        let with_cleanup = entry(
6069            "0.1.0",
6070            vec![
6071                UpgradeInstruction::LoadModule { module: "x".into() },
6072                UpgradeInstruction::StateChange {
6073                    script: PathBuf::from("lib/m1.lisp"),
6074                },
6075                UpgradeInstruction::StateChange {
6076                    script: PathBuf::from("lib/m2.lisp"),
6077                },
6078                UpgradeInstruction::SoftPurge {
6079                    module: "x-old".into(),
6080                },
6081            ],
6082        );
6083        with_cleanup.validate().unwrap();
6084    }
6085
6086    #[test]
6087    fn validate_accepts_single_state_change_per_script() {
6088        // Boundary control: a list with exactly one `:state-change`
6089        // wrapped by the canonical `:load-module` + `:soft-purge`
6090        // sequence (the module-doc OTP shape) is the gate's identity
6091        // element. Pin so a future off-by-one in the duplicate-
6092        // detection scan doesn't accidentally flag a single occurrence
6093        // as duplicating itself — mirrors
6094        // `validate_accepts_single_load_per_module` /
6095        // `validate_accepts_single_cleanup_per_module` on the sibling
6096        // singularity axes.
6097        let e = entry(
6098            "0.1.0",
6099            vec![
6100                UpgradeInstruction::LoadModule { module: "x".into() },
6101                UpgradeInstruction::StateChange {
6102                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
6103                },
6104                UpgradeInstruction::SoftPurge {
6105                    module: "x-old".into(),
6106                },
6107            ],
6108        );
6109        e.validate().unwrap();
6110    }
6111
6112    #[test]
6113    fn validate_state_change_singularity_fires_after_state_change_ordering() {
6114        // Diagnostic-precedence pin: an entry like `((:state-change
6115        // "m.lisp") (:state-change "m.lisp"))` is *both* state-change-
6116        // without-load and duplicate-state-change. The more-fundamental
6117        // ordering gate must win — the missing-load defect is load-
6118        // bearing (the migration runs against unloaded code), and
6119        // surfacing the duplicate diagnostic first would mask the
6120        // migrate-into-unloaded-code defect the ordering gate exists to
6121        // close. Guards the call order in `validate` against silent
6122        // reordering. Same posture as
6123        // `validate_load_singularity_fires_after_state_change_ordering`
6124        // on the sibling singularity gate.
6125        //
6126        // Two same-script `:state-change` would *otherwise* duplicate
6127        // (both scripts collide on the very first `:state-change`-
6128        // without-load encountered), so this pin double-locks the
6129        // precedence: the ordering gate must win on the first un-loaded
6130        // `:state-change` before the singularity scan even reaches the
6131        // second.
6132        let e = entry(
6133            "0.1.0",
6134            vec![
6135                UpgradeInstruction::StateChange {
6136                    script: PathBuf::from("lib/m.lisp"),
6137                },
6138                UpgradeInstruction::StateChange {
6139                    script: PathBuf::from("lib/m.lisp"),
6140                },
6141            ],
6142        );
6143        let err = e.validate().unwrap_err();
6144        assert!(
6145            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
6146            "state-change-without-load must surface before duplicate-state-change, got {err:?}"
6147        );
6148    }
6149
6150    #[test]
6151    fn validate_state_change_singularity_fires_after_purge_ordering() {
6152        // Diagnostic-precedence pin: an entry like `((:soft-purge
6153        // "x-old") (:load-module "x") (:state-change "m.lisp")
6154        // (:state-change "m.lisp"))` is *both* purge-without-load and
6155        // duplicate-state-change. The more-fundamental ordering gate
6156        // must win — the missing-load defect (a cleanup that drains the
6157        // only resident version to nothing) is load-bearing, and
6158        // surfacing the duplicate diagnostic first would mask the
6159        // drain-to-nothing defect the ordering gate exists to close.
6160        // Sibling of `validate_load_singularity_fires_after_purge_ordering`
6161        // on the state-change-singularity axis.
6162        let e = entry(
6163            "0.1.0",
6164            vec![
6165                UpgradeInstruction::SoftPurge {
6166                    module: "x-old".into(),
6167                },
6168                UpgradeInstruction::LoadModule { module: "x".into() },
6169                UpgradeInstruction::StateChange {
6170                    script: PathBuf::from("lib/m.lisp"),
6171                },
6172                UpgradeInstruction::StateChange {
6173                    script: PathBuf::from("lib/m.lisp"),
6174                },
6175            ],
6176        );
6177        let err = e.validate().unwrap_err();
6178        assert!(
6179            matches!(
6180                err,
6181                UpgradeError::PurgeWithoutPriorLoad {
6182                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6183                    ..
6184                }
6185            ),
6186            "purge-without-load must surface before duplicate-state-change, got {err:?}"
6187        );
6188    }
6189
6190    #[test]
6191    fn validate_state_change_singularity_fires_after_per_instr_shape() {
6192        // Order pin: a malformed `:script` value on a `:state-change`
6193        // (an empty path) surfaces its narrower `EmptyScript` diagnostic
6194        // *before* the within-entry state-change-singularity gate fires.
6195        // The per-instruction shape pass walks the list inline before
6196        // the singularity check, so the narrower self-locating
6197        // diagnostic surfaces first — mirrors the empty-first cascade on
6198        // every peer path-shape gate and the
6199        // `validate_load_singularity_fires_after_per_instr_shape` /
6200        // `validate_cleanup_singularity_fires_after_per_instr_shape`
6201        // pins on the sibling singularity gates.
6202        //
6203        // Two empty-path `:state-change` would *otherwise* duplicate
6204        // (both scripts are the same empty PathBuf), so this pin double-
6205        // locks the precedence: the per-instr shape gate must win on the
6206        // first malformed instruction before the duplicate scan even
6207        // reaches the second.
6208        let e = entry(
6209            "0.1.0",
6210            vec![
6211                UpgradeInstruction::LoadModule { module: "x".into() },
6212                UpgradeInstruction::StateChange {
6213                    script: PathBuf::new(),
6214                },
6215                UpgradeInstruction::StateChange {
6216                    script: PathBuf::new(),
6217                },
6218            ],
6219        );
6220        let err = e.validate().unwrap_err();
6221        assert_eq!(
6222            err,
6223            UpgradeError::EmptyScript,
6224            "malformed instruction must surface its narrower diagnostic before the \
6225             state-change-singularity gate fires, got {err:?}"
6226        );
6227    }
6228
6229    #[test]
6230    fn validate_state_change_singularity_fires_after_load_singularity() {
6231        // Diagnostic-precedence pin: an entry that violates *both*
6232        // singularities — duplicate load on "x" *and* duplicate
6233        // state-change on "m.lisp" — must surface the load-side
6234        // diagnostic first. The load axis precedes the migration axis
6235        // in the canonical OTP sequence (`code:load_module/1` then
6236        // `gen_server:code_change/3`) and in [`UpgradeInstruction`]
6237        // declaration order (LoadModule before StateChange), so the
6238        // load-side singularity is the load-bearing diagnostic when
6239        // both fire — the migration-side duplicate is meaningless
6240        // either way without a coherent load. Guards the call order in
6241        // `validate`: `validate_load_singularity` runs before
6242        // `validate_state_change_singularity`.
6243        let e = entry(
6244            "0.1.0",
6245            vec![
6246                UpgradeInstruction::LoadModule { module: "x".into() },
6247                UpgradeInstruction::LoadModule { module: "x".into() },
6248                UpgradeInstruction::StateChange {
6249                    script: PathBuf::from("lib/m.lisp"),
6250                },
6251                UpgradeInstruction::StateChange {
6252                    script: PathBuf::from("lib/m.lisp"),
6253                },
6254            ],
6255        );
6256        let err = e.validate().unwrap_err();
6257        assert_eq!(
6258            err,
6259            UpgradeError::DuplicateLoadModule {
6260                from: "0.1.0".into(),
6261                module: "x".into(),
6262            },
6263            "duplicate-load must surface before duplicate-state-change, got {err:?}"
6264        );
6265    }
6266
6267    #[test]
6268    fn validate_state_change_singularity_fires_before_cleanup_singularity() {
6269        // Diagnostic-precedence pin: an entry that violates *both*
6270        // singularities — duplicate state-change on "m.lisp" *and*
6271        // duplicate cleanup on "y-old" — must surface the migration-
6272        // side diagnostic first. The migration axis precedes the
6273        // cleanup axis in the canonical OTP sequence
6274        // (`gen_server:code_change/3` then `code:soft_purge/1`) and in
6275        // [`UpgradeInstruction`] declaration order (StateChange before
6276        // SoftPurge/Purge), so the migration-side singularity is the
6277        // load-bearing diagnostic when both fire — the cleanup-side
6278        // duplicate is irrelevant once the migration has corrupted
6279        // state by double-applying. Guards the call order in
6280        // `validate`: `validate_state_change_singularity` runs before
6281        // `validate_cleanup_singularity`.
6282        let e = entry(
6283            "0.1.0",
6284            vec![
6285                UpgradeInstruction::LoadModule { module: "x".into() },
6286                UpgradeInstruction::StateChange {
6287                    script: PathBuf::from("lib/m.lisp"),
6288                },
6289                UpgradeInstruction::StateChange {
6290                    script: PathBuf::from("lib/m.lisp"),
6291                },
6292                UpgradeInstruction::SoftPurge {
6293                    module: "y-old".into(),
6294                },
6295                UpgradeInstruction::SoftPurge {
6296                    module: "y-old".into(),
6297                },
6298            ],
6299        );
6300        let err = e.validate().unwrap_err();
6301        assert_eq!(
6302            err,
6303            UpgradeError::DuplicateStateChange {
6304                from: "0.1.0".into(),
6305                script: PathBuf::from("lib/m.lisp"),
6306            },
6307            "duplicate-state-change must surface before duplicate-cleanup, got {err:?}"
6308        );
6309    }
6310
6311    #[test]
6312    fn validate_state_change_singularity_reports_first_collision() {
6313        // Determinism pin: with three state-changes on the same script
6314        // the gate reports the *first* collision (the second
6315        // occurrence) and stops — the third's duplicate is masked by
6316        // the first surfaced one. Mirrors
6317        // `validate_load_singularity_reports_first_collision` /
6318        // `validate_cleanup_singularity_reports_first_collision` on the
6319        // sibling singularity axes and every peer duplicate gate's
6320        // first-collision discipline.
6321        let e = entry(
6322            "0.1.0",
6323            vec![
6324                UpgradeInstruction::LoadModule { module: "x".into() },
6325                UpgradeInstruction::StateChange {
6326                    script: PathBuf::from("lib/m.lisp"),
6327                },
6328                UpgradeInstruction::StateChange {
6329                    script: PathBuf::from("lib/m.lisp"),
6330                },
6331                UpgradeInstruction::StateChange {
6332                    script: PathBuf::from("lib/m.lisp"),
6333                },
6334            ],
6335        );
6336        let err = e.validate().unwrap_err();
6337        assert_eq!(
6338            err,
6339            UpgradeError::DuplicateStateChange {
6340                from: "0.1.0".into(),
6341                script: PathBuf::from("lib/m.lisp"),
6342            },
6343            "the first colliding occurrence must surface, not the later third-migration collision"
6344        );
6345    }
6346
6347    #[test]
6348    fn validate_state_change_singularity_threads_through_validate_upgrade_from() {
6349        // The whole-list entry-point surfaces the per-entry singularity
6350        // error (mirrors
6351        // `validate_load_singularity_threads_through_validate_upgrade_from`
6352        // / `validate_cleanup_singularity_threads_through_validate_upgrade_from`):
6353        // the gate is reachable from the LayoutInvariants call site,
6354        // not only from a direct `entry.validate()`.
6355        let entries = vec![entry(
6356            "0.1.0",
6357            vec![
6358                UpgradeInstruction::LoadModule { module: "x".into() },
6359                UpgradeInstruction::StateChange {
6360                    script: PathBuf::from("lib/m.lisp"),
6361                },
6362                UpgradeInstruction::StateChange {
6363                    script: PathBuf::from("lib/m.lisp"),
6364                },
6365            ],
6366        )];
6367        let err = validate_upgrade_from(&entries).unwrap_err();
6368        assert!(
6369            matches!(err, UpgradeError::DuplicateStateChange { .. }),
6370            "validate_upgrade_from must thread the state-change-singularity error, got {err:?}"
6371        );
6372    }
6373
6374    #[test]
6375    fn validate_state_change_singularity_projects_scripts_through_declared_path_accessor() {
6376        // Composition pin: [`UpgradeFromEntry::validate_state_change_singularity`]'s
6377        // per-instruction `StateChange`-arm script-path projection must
6378        // route through the sibling lifted
6379        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
6380        // accessor, not the raw
6381        // `match instr { UpgradeInstruction::StateChange { script } =>
6382        // script.as_path(), _ => continue }` open-coded pattern-match
6383        // the gate previously carried.
6384        //
6385        // Structurally: the gate's projection accept-set is the union
6386        // of every [`UpgradeInstruction`] variant for which
6387        // `declared_path().is_some()` — today exactly
6388        // [`UpgradeInstruction::StateChange`] per the sibling
6389        // `declared_path_only_for_state_change` pin, so a
6390        // duplicate-scripts input trips `DuplicateStateChange` and a
6391        // non-`StateChange` input (module-bearing / terminal) leaves
6392        // `seen` empty and the gate returns `Ok(())` byte-identical to
6393        // the pattern-match shape.
6394        //
6395        // Byte-equal today (`declared_path` returns `Some(script)` iff
6396        // `StateChange`, byte-for-byte from the variant's own storage);
6397        // the pin catches any future accessor extension that promotes
6398        // an additional variant onto the `PathBuf`-carrying axis — the
6399        // gate then fires on duplicate scripts from that variant too,
6400        // and the singularity discipline the sibling
6401        // `validate_load_singularity` / `validate_cleanup_singularity`
6402        // gates share on the `String`-carrying axis's per-variant
6403        // consumers extends to the promoted variant by construction.
6404        //
6405        // Peer of the sibling four per-`UpgradeInstruction` consumers
6406        // ([`UpgradeInstruction::validate`]'s per-`StateChange`
6407        // sandbox-path fan-out, the layout-side per-`StateChange`
6408        // script-existence fan-out at
6409        // `caixa-core/src/layout.rs:1017`, the cross-slot
6410        // [`validate_upgrade_from_against_behavior`] gate's per-
6411        // `StateChange` detection loop, the peer
6412        // [`UpgradeInstruction::declared_module`] `String`-axis
6413        // per-variant unifier) — this gate now shares one typed
6414        // dispatch on the substrate primitive's `PathBuf`-carrying
6415        // axis with those consumers, so a future rebrand on the axis
6416        // migrates as a single caixa-core edit rather than a
6417        // coordinated rewrite of five call sites.
6418        //
6419        // Three-arm projective coverage:
6420        //   (a) `StateChange` scripts project through `declared_path()`
6421        //       byte-equal to the raw `script.as_path()` field access;
6422        //   (b) a duplicate-`StateChange` input trips the gate on the
6423        //       second occurrence with `DuplicateStateChange` carrying
6424        //       the offending script verbatim;
6425        //   (c) a non-`StateChange`-only input (`LoadModule` /
6426        //       `SoftPurge` / `Purge` / `Restart`) leaves the gate
6427        //       vacuous with `Ok(())` — the `declared_path().is_none()`
6428        //       arm's `continue` fall-through pins.
6429        //
6430        // Fail-before-pass-after verified locally: swapping the
6431        // production `let Some(script) = instr.declared_path() else {
6432        // continue };` back to `let script = match instr {
6433        // UpgradeInstruction::StateChange { script } =>
6434        // script.as_path(), _ => continue, };` keeps arms (a)-(c)
6435        // passing but silently detaches the gate from the accessor's
6436        // typed dispatch — any future `declared_path` extension
6437        // (promotion of an additional variant onto the axis, an
6438        // operator-side pre-resolved-path cache the accessor
6439        // materializes) would then silently disagree between this
6440        // gate's raw pattern-match and the peer four sibling consumers
6441        // that route through the accessor.
6442        use std::path::PathBuf;
6443
6444        // (a) StateChange projection byte-equal via declared_path.
6445        let sc = UpgradeInstruction::StateChange {
6446            script: PathBuf::from("lib/m.lisp"),
6447        };
6448        assert_eq!(
6449            sc.declared_path().map(std::path::PathBuf::as_path),
6450            Some(PathBuf::from("lib/m.lisp").as_path()),
6451            "declared_path() must project the StateChange :script byte-equal to the raw \
6452             field access — accessor divergence would silently detach the gate from the \
6453             projection every peer per-`UpgradeInstruction` consumer routes through"
6454        );
6455
6456        // (b) Duplicate-StateChange input trips the gate.
6457        let dup = entry(
6458            "0.1.0",
6459            vec![
6460                UpgradeInstruction::LoadModule { module: "x".into() },
6461                UpgradeInstruction::StateChange {
6462                    script: PathBuf::from("lib/m.lisp"),
6463                },
6464                UpgradeInstruction::StateChange {
6465                    script: PathBuf::from("lib/m.lisp"),
6466                },
6467            ],
6468        );
6469        assert_eq!(
6470            dup.validate_state_change_singularity(),
6471            Err(UpgradeError::DuplicateStateChange {
6472                from: "0.1.0".into(),
6473                script: PathBuf::from("lib/m.lisp"),
6474            }),
6475            "duplicate StateChange scripts must trip the gate on the second occurrence \
6476             through the declared_path accessor's Some(script) arm"
6477        );
6478
6479        // (c) Non-StateChange-only inputs leave the gate vacuous.
6480        for instrs in [
6481            vec![UpgradeInstruction::LoadModule { module: "x".into() }],
6482            vec![
6483                UpgradeInstruction::LoadModule { module: "x".into() },
6484                UpgradeInstruction::SoftPurge {
6485                    module: "x-old".into(),
6486                },
6487            ],
6488            vec![
6489                UpgradeInstruction::LoadModule { module: "x".into() },
6490                UpgradeInstruction::Purge {
6491                    module: "x-old".into(),
6492                },
6493            ],
6494            vec![UpgradeInstruction::Restart],
6495        ] {
6496            for instr in &instrs {
6497                assert!(
6498                    instr.declared_path().is_none(),
6499                    "non-StateChange variants must project None through declared_path — \
6500                     accessor divergence would let this gate silently fire on a duplicate \
6501                     module reference far from any :state-change site"
6502                );
6503            }
6504            let e = entry("0.1.0", instrs);
6505            assert_eq!(
6506                e.validate_state_change_singularity(),
6507                Ok(()),
6508                "the state-change-singularity gate must return Ok(()) on an entry whose \
6509                 instructions all project None through declared_path — the accessor's \
6510                 continue arm the pattern-match's `_ => continue` previously carried"
6511            );
6512        }
6513    }
6514
6515    // ── within-entry state-change-before-cleanup ordering invariant ──
6516
6517    #[test]
6518    fn validate_rejects_state_change_after_soft_purge() {
6519        // Fail-before-pass-after pin: `:state-change` is the
6520        // gen_server:code_change/3 analog and folds the prior-version
6521        // state shape into the current shape; `:soft-purge` drains the
6522        // prior code. The operator runs instructions in declared order,
6523        // so a `:soft-purge` ahead of a `:state-change` drains the
6524        // prior module before the migration callback runs against the
6525        // state it held — the canonical OTP error mode
6526        // "`code_change/3` invoked on a purged module" the
6527        // release_handler closes by always ordering the migration
6528        // before the cleanup.
6529        let e = entry(
6530            "0.1.0",
6531            vec![
6532                UpgradeInstruction::LoadModule { module: "x".into() },
6533                UpgradeInstruction::SoftPurge {
6534                    module: "x-old".into(),
6535                },
6536                UpgradeInstruction::StateChange {
6537                    script: PathBuf::from("lib/m.lisp"),
6538                },
6539            ],
6540        );
6541        let err = e.validate().unwrap_err();
6542        assert_eq!(
6543            err,
6544            UpgradeError::StateChangeAfterCleanup {
6545                from: "0.1.0".into(),
6546                script: PathBuf::from("lib/m.lisp"),
6547                prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6548                prior_cleanup_module: "x-old".into(),
6549            },
6550            "a `:state-change` after a `:soft-purge` must surface as StateChangeAfterCleanup \
6551             naming the offending entry + script + the prior cleanup's kind/module, got {err:?}"
6552        );
6553    }
6554
6555    #[test]
6556    fn validate_rejects_state_change_after_purge() {
6557        // Per-arm coverage: `:purge` (immediate discard, no drain) is
6558        // the more catastrophic peer of `:soft-purge` on the cleanup
6559        // axis; same gate, same shape, the `prior_cleanup_kind` field
6560        // distinguishes the diagnostic so the author can grep their
6561        // caixa.lisp for the offending `(:purge …)` form.
6562        let e = entry(
6563            "0.1.0",
6564            vec![
6565                UpgradeInstruction::LoadModule { module: "x".into() },
6566                UpgradeInstruction::Purge {
6567                    module: "x-old".into(),
6568                },
6569                UpgradeInstruction::StateChange {
6570                    script: PathBuf::from("lib/m.lisp"),
6571                },
6572            ],
6573        );
6574        let err = e.validate().unwrap_err();
6575        assert_eq!(
6576            err,
6577            UpgradeError::StateChangeAfterCleanup {
6578                from: "0.1.0".into(),
6579                script: PathBuf::from("lib/m.lisp"),
6580                prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
6581                prior_cleanup_module: "x-old".into(),
6582            },
6583            "a `:state-change` after a `:purge` must surface as StateChangeAfterCleanup with \
6584             `prior_cleanup_kind: \":purge\"`, got {err:?}"
6585        );
6586    }
6587
6588    #[test]
6589    fn validate_accepts_state_change_before_cleanup() {
6590        // Positive control: the canonical `(:load-module …)
6591        // (:state-change …) (:soft-purge …)` order validates — the
6592        // exact shape the module doc example and `validate_accepts_
6593        // well_formed` already pin, restated here on the new gate's
6594        // identity element so a future shortcut that runs the
6595        // singularity gates first doesn't silently mask a regression
6596        // here.
6597        let e = entry(
6598            "0.1.0",
6599            vec![
6600                UpgradeInstruction::LoadModule { module: "x".into() },
6601                UpgradeInstruction::StateChange {
6602                    script: PathBuf::from("lib/m.lisp"),
6603                },
6604                UpgradeInstruction::SoftPurge {
6605                    module: "x-old".into(),
6606                },
6607            ],
6608        );
6609        e.validate().unwrap();
6610    }
6611
6612    #[test]
6613    fn validate_accepts_cleanup_without_state_change() {
6614        // Empty-set identity: an entry that carries no `:state-change`
6615        // at all has nothing to order against the cleanup, so the gate
6616        // passes regardless of how the cleanups are placed (after the
6617        // single required `:load-module`). Mirrors the
6618        // `validate_accepts_multiple_purges_after_one_load` positive
6619        // control on the peer purge-ordering gate; metadata-only
6620        // upgrades with cleanup-but-no-migration land here.
6621        let e = entry(
6622            "0.1.0",
6623            vec![
6624                UpgradeInstruction::LoadModule { module: "x".into() },
6625                UpgradeInstruction::SoftPurge {
6626                    module: "x-old".into(),
6627                },
6628                UpgradeInstruction::Purge {
6629                    module: "x-oldest".into(),
6630                },
6631            ],
6632        );
6633        e.validate().unwrap();
6634    }
6635
6636    #[test]
6637    fn validate_accepts_state_change_without_cleanup() {
6638        // Empty-set identity on the dual axis: an entry that carries no
6639        // cleanup at all has nothing to order against the state-change,
6640        // so the gate passes — additive-upgrade shapes (load new code,
6641        // migrate state, leave old code resident for in-flight callers
6642        // to drain naturally) land here.
6643        let e = entry(
6644            "0.1.0",
6645            vec![
6646                UpgradeInstruction::LoadModule { module: "x".into() },
6647                UpgradeInstruction::StateChange {
6648                    script: PathBuf::from("lib/m.lisp"),
6649                },
6650            ],
6651        );
6652        e.validate().unwrap();
6653    }
6654
6655    #[test]
6656    fn validate_accepts_multiple_state_changes_before_cleanup() {
6657        // Coverage: every state-change must precede every cleanup, not
6658        // just the first. A chain `(load) (sc) (sc) (sp)` is the
6659        // canonical "two distinct migration scripts on a chained
6660        // upgrade" shape (one module's schema *and* another's
6661        // projection per the DuplicateStateChange diagnostic), and
6662        // it must pass when each state-change has distinct script
6663        // paths. Pinned here so a future shortcut that only checks
6664        // the first state-change doesn't silently accept a
6665        // `(load) (sc-1) (sp) (sc-2)` regression.
6666        let e = entry(
6667            "0.1.0",
6668            vec![
6669                UpgradeInstruction::LoadModule { module: "x".into() },
6670                UpgradeInstruction::StateChange {
6671                    script: PathBuf::from("lib/m1.lisp"),
6672                },
6673                UpgradeInstruction::StateChange {
6674                    script: PathBuf::from("lib/m2.lisp"),
6675                },
6676                UpgradeInstruction::SoftPurge {
6677                    module: "x-old".into(),
6678                },
6679            ],
6680        );
6681        e.validate().unwrap();
6682    }
6683
6684    #[test]
6685    fn validate_rejects_state_change_sandwiched_between_cleanups() {
6686        // First-cleanup-wins pin: an entry like `(load) (sp-1) (sc)
6687        // (sp-2)` violates the gate because the state-change runs
6688        // after the first cleanup. The reported `prior_cleanup_*`
6689        // names the *first* cleanup (the load-bearing one), not the
6690        // last — mirrors every peer first-collision diagnostic
6691        // posture on this module (`validate_state_change_ordering`,
6692        // `validate_purge_ordering`, `validate_load_singularity`,
6693        // `validate_state_change_singularity`,
6694        // `validate_cleanup_singularity` all report the first
6695        // colliding instruction, not the last).
6696        let e = entry(
6697            "0.1.0",
6698            vec![
6699                UpgradeInstruction::LoadModule { module: "x".into() },
6700                UpgradeInstruction::SoftPurge {
6701                    module: "x-old".into(),
6702                },
6703                UpgradeInstruction::StateChange {
6704                    script: PathBuf::from("lib/m.lisp"),
6705                },
6706                UpgradeInstruction::Purge {
6707                    module: "y-old".into(),
6708                },
6709            ],
6710        );
6711        let err = e.validate().unwrap_err();
6712        assert_eq!(
6713            err,
6714            UpgradeError::StateChangeAfterCleanup {
6715                from: "0.1.0".into(),
6716                script: PathBuf::from("lib/m.lisp"),
6717                prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6718                prior_cleanup_module: "x-old".into(),
6719            },
6720            "the first cleanup the state-change follows must surface (not the trailing one), \
6721             got {err:?}"
6722        );
6723    }
6724
6725    #[test]
6726    fn validate_state_change_before_cleanup_fires_after_purge_ordering() {
6727        // Diagnostic-precedence pin: an entry like `((:soft-purge
6728        // "x-old") (:load-module "x") (:state-change "m.lisp"))` is
6729        // *both* purge-without-load (the cleanup runs before the
6730        // load) and state-change-after-cleanup (the state-change
6731        // runs after the cleanup). The more-fundamental ordering
6732        // gate must win — the missing-load defect (a cleanup that
6733        // drains the only resident version to nothing) is load-
6734        // bearing, and surfacing the state-change-after-cleanup
6735        // diagnostic first would mask the drain-to-nothing defect
6736        // the peer purge-ordering gate exists to close. Guards the
6737        // call order in `validate` against silent reordering. Same
6738        // posture as `validate_purge_ordering_fires_after_state_
6739        // change_ordering` on the sibling ordering gate.
6740        //
6741        // Pin specifically uses the load-after-cleanup shape (rather
6742        // than load-less) so the state-change-ordering gate (which
6743        // would otherwise fire first on a `((:soft-purge …)
6744        // (:state-change …))` shape with no leading load) is
6745        // sidestepped: with the load present after the cleanup,
6746        // state-change-ordering passes (its `loaded` latch is set
6747        // before the state-change is encountered) but purge-ordering
6748        // still fails (the cleanup precedes the load). That isolates
6749        // the precedence between purge-ordering and this gate
6750        // cleanly.
6751        let e = entry(
6752            "0.1.0",
6753            vec![
6754                UpgradeInstruction::SoftPurge {
6755                    module: "x-old".into(),
6756                },
6757                UpgradeInstruction::LoadModule { module: "x".into() },
6758                UpgradeInstruction::StateChange {
6759                    script: PathBuf::from("lib/m.lisp"),
6760                },
6761            ],
6762        );
6763        let err = e.validate().unwrap_err();
6764        assert!(
6765            matches!(
6766                err,
6767                UpgradeError::PurgeWithoutPriorLoad {
6768                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6769                    ..
6770                }
6771            ),
6772            "purge-without-load must surface before state-change-after-cleanup, got {err:?}"
6773        );
6774    }
6775
6776    #[test]
6777    fn validate_state_change_before_cleanup_fires_after_state_change_ordering() {
6778        // Diagnostic-precedence pin: an entry like `((:state-change
6779        // "m.lisp") (:soft-purge "x-old"))` is state-change-without-
6780        // load (because no `:load-module` precedes the state-change)
6781        // but *not* state-change-after-cleanup (the state-change
6782        // precedes the cleanup textually). The state-change-ordering
6783        // gate must surface first regardless — the missing-load
6784        // defect on the migration axis is the load-bearing semantic
6785        // and surfacing a different ordering diagnostic would mask
6786        // the migration-against-stale-code defect. Guards the call
6787        // order in `validate` against silent reordering on a shape
6788        // that fires only the state-change-ordering gate (not this
6789        // one), pinning that the state-change-ordering gate wins
6790        // ahead of this gate's chance to look at the list.
6791        let e = entry(
6792            "0.1.0",
6793            vec![
6794                UpgradeInstruction::StateChange {
6795                    script: PathBuf::from("lib/m.lisp"),
6796                },
6797                UpgradeInstruction::SoftPurge {
6798                    module: "x-old".into(),
6799                },
6800            ],
6801        );
6802        let err = e.validate().unwrap_err();
6803        assert!(
6804            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
6805            "state-change-without-load must surface before purge-without-load (the canonical \
6806             validate_purge_ordering_fires_after_state_change_ordering pin), got {err:?}"
6807        );
6808    }
6809
6810    #[test]
6811    fn validate_state_change_before_cleanup_fires_after_per_instr_shape() {
6812        // Order pin: a malformed `:script` value on a `:state-change`
6813        // (an empty path) surfaces its narrower `EmptyScript`
6814        // diagnostic *before* the within-entry state-change-before-
6815        // cleanup gate fires. The per-instruction shape pass walks
6816        // the list inline before the ordering check, so the narrower
6817        // self-locating diagnostic surfaces first — mirrors the
6818        // empty-first cascade on every peer path-shape gate and the
6819        // `validate_purge_ordering_fires_after_per_instr_shape` pin
6820        // on the sibling ordering gate.
6821        let e = entry(
6822            "0.1.0",
6823            vec![
6824                UpgradeInstruction::LoadModule { module: "x".into() },
6825                UpgradeInstruction::SoftPurge {
6826                    module: "x-old".into(),
6827                },
6828                UpgradeInstruction::StateChange {
6829                    script: PathBuf::new(),
6830                },
6831            ],
6832        );
6833        let err = e.validate().unwrap_err();
6834        assert_eq!(
6835            err,
6836            UpgradeError::EmptyScript,
6837            "malformed instruction must surface its narrower diagnostic before the \
6838             state-change-before-cleanup gate fires, got {err:?}"
6839        );
6840    }
6841
6842    #[test]
6843    fn validate_state_change_before_cleanup_fires_before_state_change_singularity() {
6844        // Diagnostic-precedence pin: an entry like `((:load-module
6845        // "x") (:soft-purge "x-old") (:state-change "m.lisp")
6846        // (:state-change "m.lisp"))` violates *both* this ordering
6847        // gate (the first state-change follows the cleanup) and the
6848        // state-change-singularity gate (the same script appears
6849        // twice). The ordering gate must win — the canonical
6850        // "ordering before singularity" precedence the peer
6851        // `validate_state_change_ordering` / `validate_purge_
6852        // ordering` gates already establish over their own singularity
6853        // gates, applied uniformly across the OTP canonical-sequence
6854        // ordering axis here. Guards the call order in `validate`:
6855        // `validate_state_change_before_cleanup` runs before the
6856        // per-instruction-class singularity gates.
6857        let e = entry(
6858            "0.1.0",
6859            vec![
6860                UpgradeInstruction::LoadModule { module: "x".into() },
6861                UpgradeInstruction::SoftPurge {
6862                    module: "x-old".into(),
6863                },
6864                UpgradeInstruction::StateChange {
6865                    script: PathBuf::from("lib/m.lisp"),
6866                },
6867                UpgradeInstruction::StateChange {
6868                    script: PathBuf::from("lib/m.lisp"),
6869                },
6870            ],
6871        );
6872        let err = e.validate().unwrap_err();
6873        assert!(
6874            matches!(err, UpgradeError::StateChangeAfterCleanup { .. }),
6875            "state-change-after-cleanup must surface before duplicate-state-change, got {err:?}"
6876        );
6877    }
6878
6879    #[test]
6880    fn validate_state_change_before_cleanup_threads_through_validate_upgrade_from() {
6881        // The whole-list entry-point surfaces the per-entry ordering
6882        // error (mirrors `validate_purge_ordering_threads_through_
6883        // validate_upgrade_from` and every peer wiring pin): the gate
6884        // is reachable from the LayoutInvariants call site, not only
6885        // from a direct `entry.validate()`.
6886        let entries = vec![entry(
6887            "0.1.0",
6888            vec![
6889                UpgradeInstruction::LoadModule { module: "x".into() },
6890                UpgradeInstruction::SoftPurge {
6891                    module: "x-old".into(),
6892                },
6893                UpgradeInstruction::StateChange {
6894                    script: PathBuf::from("lib/m.lisp"),
6895                },
6896            ],
6897        )];
6898        let err = validate_upgrade_from(&entries).unwrap_err();
6899        assert!(
6900            matches!(err, UpgradeError::StateChangeAfterCleanup { .. }),
6901            "validate_upgrade_from must thread the state-change-before-cleanup error, \
6902             got {err:?}"
6903        );
6904    }
6905
6906    #[test]
6907    fn validate_state_change_before_cleanup_projects_scripts_through_declared_path_accessor() {
6908        // Composition pin: [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
6909        // per-instruction `StateChange`-arm script-path projection must
6910        // route through the sibling lifted
6911        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
6912        // accessor, not the raw
6913        // `if let UpgradeInstruction::StateChange { script } = instr`
6914        // open-coded pattern-match the gate previously carried inside
6915        // `impl UpgradeFromEntry` at caixa-core/src/upgrade.rs:806.
6916        //
6917        // Structurally: the gate's projection accept-set is the union
6918        // of every [`UpgradeInstruction`] variant for which
6919        // `declared_path().is_some()` — today exactly
6920        // [`UpgradeInstruction::StateChange`] per the sibling
6921        // `declared_path_only_for_state_change` pin, so a
6922        // state-change-after-cleanup input trips
6923        // `StateChangeAfterCleanup` and a non-`StateChange` input
6924        // (module-bearing / terminal) leaves the sticky-once latch
6925        // sweep quiet byte-identical to the pattern-match shape.
6926        //
6927        // Byte-equal today (`declared_path` returns `Some(script)` iff
6928        // `StateChange`, byte-for-byte from the variant's own storage);
6929        // the pin catches any future accessor extension that promotes
6930        // an additional variant onto the `PathBuf`-carrying axis — the
6931        // gate then fires on migrate-after-cleanup for that variant too,
6932        // and the migrate→cleanup ordering discipline the peer
6933        // [`validate_state_change_singularity`] /
6934        // [`validate_upgrade_from_against_behavior`] gates share on the
6935        // same axis extends to the promoted variant by construction.
6936        //
6937        // Peer of the sibling four per-`UpgradeInstruction` consumers
6938        // ([`UpgradeInstruction::validate`]'s per-`StateChange`
6939        // sandbox-path fan-out, the layout-side per-`StateChange`
6940        // script-existence fan-out at
6941        // `caixa-core/src/layout.rs:1058`, the within-entry
6942        // [`UpgradeFromEntry::validate_state_change_singularity`]
6943        // per-`StateChange` script-projection fan-out, the cross-slot
6944        // [`validate_upgrade_from_against_behavior`] per-`StateChange`
6945        // detection loop) — the fifth (and last unlifted inside
6946        // `impl UpgradeFromEntry`) per-`UpgradeInstruction`-consumer of
6947        // the `PathBuf`-carrying axis to now route through the accessor.
6948        // Same shape as the sibling
6949        // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
6950        // and `validate_upgrade_from_against_behavior_projects_scripts_through_declared_path_accessor`
6951        // pins extended onto the within-entry migrate→cleanup ordering
6952        // gate.
6953        //
6954        // Three-arm projective coverage:
6955        //   (a) `StateChange` scripts project through `declared_path()`
6956        //       byte-equal to the raw `script.clone()` field access
6957        //       the diagnostic previously carried;
6958        //   (b) a `:state-change`-after-cleanup input trips the gate
6959        //       with `StateChangeAfterCleanup` carrying the offending
6960        //       script + the prior cleanup's kind/module verbatim;
6961        //   (c) a non-`StateChange`-only input (`LoadModule` /
6962        //       `SoftPurge` / `Purge` / `Restart`) leaves the gate
6963        //       vacuous with `Ok(())` — the `declared_path().is_none()`
6964        //       arm's fall-through pins.
6965        //
6966        // Fail-before-pass-after verified structurally: swapping the
6967        // production
6968        //   `else if let Some(script) = instr.declared_path() && … { … }`
6969        // back to
6970        //   `else if let UpgradeInstruction::StateChange { script } = instr && … { … }`
6971        // keeps arms (a)-(c) passing but silently detaches this within-
6972        // entry ordering gate from the accessor's typed dispatch — any
6973        // future `declared_path` extension (promotion of an additional
6974        // variant onto the axis, an operator-side pre-resolved-path
6975        // cache the accessor materializes) would then silently disagree
6976        // between this gate's raw pattern-match and the peer four
6977        // sibling consumers that route through the accessor.
6978
6979        // (a) StateChange projection byte-equal via declared_path.
6980        let sc = UpgradeInstruction::StateChange {
6981            script: PathBuf::from("lib/m.lisp"),
6982        };
6983        assert_eq!(
6984            sc.declared_path().cloned(),
6985            Some(PathBuf::from("lib/m.lisp")),
6986            "declared_path() must project the StateChange :script byte-equal to the raw \
6987             field access — accessor divergence would silently detach this within-entry \
6988             migrate→cleanup ordering gate from the projection every peer per-`UpgradeInstruction` \
6989             consumer routes through"
6990        );
6991
6992        // (b) StateChange-after-cleanup trips the gate through the accessor.
6993        let after = entry(
6994            "0.1.0",
6995            vec![
6996                UpgradeInstruction::LoadModule { module: "x".into() },
6997                UpgradeInstruction::SoftPurge {
6998                    module: "x-old".into(),
6999                },
7000                UpgradeInstruction::StateChange {
7001                    script: PathBuf::from("lib/m.lisp"),
7002                },
7003            ],
7004        );
7005        assert_eq!(
7006            after.validate(),
7007            Err(UpgradeError::StateChangeAfterCleanup {
7008                from: "0.1.0".into(),
7009                script: PathBuf::from("lib/m.lisp"),
7010                prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
7011                prior_cleanup_module: "x-old".into(),
7012            }),
7013            "a :state-change following a cleanup must trip the gate through the declared_path \
7014             accessor's Some(script) arm — carrying the offending script + the prior cleanup's \
7015             kind/module verbatim byte-identical to the pattern-match shape"
7016        );
7017
7018        // (c) Non-StateChange-only inputs leave the gate vacuous.
7019        for instrs in [
7020            vec![UpgradeInstruction::LoadModule { module: "x".into() }],
7021            vec![
7022                UpgradeInstruction::LoadModule { module: "x".into() },
7023                UpgradeInstruction::SoftPurge {
7024                    module: "x-old".into(),
7025                },
7026            ],
7027            vec![
7028                UpgradeInstruction::LoadModule { module: "x".into() },
7029                UpgradeInstruction::Purge {
7030                    module: "x-old".into(),
7031                },
7032            ],
7033            vec![UpgradeInstruction::Restart],
7034        ] {
7035            for instr in &instrs {
7036                assert!(
7037                    instr.declared_path().is_none(),
7038                    "non-StateChange variants must project None through declared_path — \
7039                     accessor divergence would let this within-entry ordering gate silently \
7040                     fire on a cleanup-only sequence far from any :state-change site"
7041                );
7042            }
7043            let e = entry("0.1.0", instrs);
7044            assert_eq!(
7045                e.validate(),
7046                Ok(()),
7047                "the state-change-before-cleanup gate must return Ok(()) on an entry whose \
7048                 instructions all project None through declared_path — the accessor's \
7049                 None arm the pattern-match's implicit fall-through previously carried"
7050            );
7051        }
7052    }
7053
7054    #[test]
7055    fn validate_restart_order_independent() {
7056        // Position-agnostic: `(:restart)` leading or trailing the
7057        // mixed sequence surfaces the same RestartNotExclusive shape.
7058        // Mirrors OTP appup's order-insensitive
7059        // `restart_emulator | restart_new_emulator` terminal rule —
7060        // the position of the restart instruction in the script is
7061        // irrelevant; what matters is the script *contains* it
7062        // alongside other instructions at all. The gate must not
7063        // gain a false positive by depending on instruction ordering.
7064        let leading = entry(
7065            "0.1.0",
7066            vec![
7067                UpgradeInstruction::Restart,
7068                UpgradeInstruction::LoadModule { module: "x".into() },
7069            ],
7070        );
7071        let trailing = entry(
7072            "0.1.0",
7073            vec![
7074                UpgradeInstruction::LoadModule { module: "x".into() },
7075                UpgradeInstruction::Restart,
7076            ],
7077        );
7078        let middle = entry(
7079            "0.1.0",
7080            vec![
7081                UpgradeInstruction::LoadModule { module: "a".into() },
7082                UpgradeInstruction::Restart,
7083                UpgradeInstruction::SoftPurge {
7084                    module: "a-old".into(),
7085                },
7086            ],
7087        );
7088        for e in [&leading, &trailing, &middle] {
7089            assert!(
7090                matches!(
7091                    e.validate().unwrap_err(),
7092                    UpgradeError::RestartNotExclusive {
7093                        restart_count: 1,
7094                        ..
7095                    }
7096                ),
7097                "mixed-with-:restart entry must surface RestartNotExclusive regardless of \
7098                 instruction order, got {:?}",
7099                e.validate()
7100            );
7101        }
7102    }
7103
7104    #[test]
7105    fn validate_restart_exclusive_fires_after_per_instr_shape() {
7106        // Order pin: a malformed `:module` value on a Module-bearing
7107        // instruction (an empty string) surfaces its narrower
7108        // kind-tagged `ModuleEmpty` diagnostic *before* the within-
7109        // entry restart-exclusivity gate fires. The per-instruction
7110        // shape pass walks the list inline before the restart-
7111        // exclusive check, so the narrower self-locating diagnostic
7112        // surfaces first — mirrors the empty-first cascade on every
7113        // peer DNS-1123 gate (`validate_module`,
7114        // `validate_membro_caixa`, `validate_placement_cluster`) and
7115        // the `*_invalid_fires_before_duplicate_check` arm-ordering
7116        // pins on every typed-graph axis. Without this pin a future
7117        // shortcut that runs the restart-exclusive check ahead of
7118        // per-instruction shape would surface a less-actionable
7119        // RestartNotExclusive over an instruction list that's also
7120        // malformed at the per-instruction layer.
7121        let e = entry(
7122            "0.1.0",
7123            vec![
7124                UpgradeInstruction::LoadModule {
7125                    module: String::new(),
7126                },
7127                UpgradeInstruction::Restart,
7128            ],
7129        );
7130        let err = e.validate().unwrap_err();
7131        assert_eq!(
7132            err,
7133            UpgradeError::ModuleEmpty {
7134                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
7135            },
7136            "malformed instruction must surface its kind-tagged diagnostic before the \
7137             restart-exclusivity gate fires, got {err:?}"
7138        );
7139    }
7140
7141    fn behavior_with_state_change_callback() -> crate::BehaviorSpec {
7142        // Helper for the cross-slot composition gate's pass arm: a
7143        // BehaviorSpec carrying just the `:on-state-change` callback,
7144        // the runtime hook the per-version `(:state-change "…")`
7145        // instruction is delivered through during hot upgrade. Mirrors
7146        // the canonical authoring shape pinned in the module doc.
7147        crate::BehaviorSpec {
7148            on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
7149            ..Default::default()
7150        }
7151    }
7152
7153    #[test]
7154    fn behavior_gate_rejects_state_change_without_any_behavior() {
7155        // `:upgrade-from` with a `(:state-change "lib/m.lisp")` and the
7156        // caixa carries no `:behavior` at all surfaces the missing-
7157        // callback diagnostic naming the offending entry's `:from` +
7158        // script. The "I added the upgrade path but never declared
7159        // `:behavior`" footgun: `:behavior` is optional at the typed
7160        // root, the typed `:upgrade-from` slot validates on its own
7161        // merits, and the operator's hot-upgrade dispatch reaches for
7162        // a callback that doesn't exist.
7163        let entries = vec![entry(
7164            "0.1.0",
7165            vec![
7166                UpgradeInstruction::LoadModule { module: "x".into() },
7167                UpgradeInstruction::StateChange {
7168                    script: PathBuf::from("lib/m.lisp"),
7169                },
7170            ],
7171        )];
7172        let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
7173        assert_eq!(
7174            err,
7175            UpgradeError::StateChangeWithoutOnStateChangeCallback {
7176                from: "0.1.0".into(),
7177                script: PathBuf::from("lib/m.lisp"),
7178            },
7179        );
7180    }
7181
7182    #[test]
7183    fn behavior_gate_rejects_state_change_when_on_state_change_is_none() {
7184        // `:behavior` declared with *other* callbacks set
7185        // (`:on-init`, `:on-terminate`, etc.) but `:on-state-change`
7186        // None still surfaces the missing-callback diagnostic — only
7187        // the `:on-state-change` axis matters for this gate. The
7188        // "I declared `:behavior` but missed the migration callback"
7189        // footgun: a caixa that registers its lifecycle hooks but
7190        // forgets the migration delivery path leaves the
7191        // `:state-change` instruction with no runtime hook to
7192        // dispatch through.
7193        let entries = vec![entry(
7194            "0.1.0",
7195            vec![
7196                UpgradeInstruction::LoadModule { module: "x".into() },
7197                UpgradeInstruction::StateChange {
7198                    script: PathBuf::from("lib/m.lisp"),
7199                },
7200            ],
7201        )];
7202        let b = crate::BehaviorSpec {
7203            on_init: Some(PathBuf::from("lib/init.lisp")),
7204            on_terminate: Some(PathBuf::from("lib/cleanup.lisp")),
7205            ..Default::default()
7206        };
7207        let err = validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap_err();
7208        assert_eq!(
7209            err,
7210            UpgradeError::StateChangeWithoutOnStateChangeCallback {
7211                from: "0.1.0".into(),
7212                script: PathBuf::from("lib/m.lisp"),
7213            },
7214            "only `:on-state-change` satisfies the composition; other callbacks must not mask \
7215             the missing migration hook"
7216        );
7217    }
7218
7219    #[test]
7220    fn behavior_gate_accepts_state_change_with_on_state_change_callback() {
7221        // The canonical composition shape: a per-version
7222        // `(:state-change "lib/m.lisp")` instruction paired with the
7223        // `:behavior :on-state-change "lib/migrations.lisp"` callback
7224        // it is delivered through at hot-upgrade time. Pins the gate's
7225        // pass arm — drift here = a future tighten that rejects the
7226        // canonical OTP-shape composition surfaces as a regression at
7227        // this positive-control pin.
7228        let entries = vec![entry(
7229            "0.1.0",
7230            vec![
7231                UpgradeInstruction::LoadModule { module: "x".into() },
7232                UpgradeInstruction::StateChange {
7233                    script: PathBuf::from("lib/m.lisp"),
7234                },
7235            ],
7236        )];
7237        let b = behavior_with_state_change_callback();
7238        validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
7239    }
7240
7241    #[test]
7242    fn behavior_gate_accepts_entries_without_any_state_change() {
7243        // Empty-set identity: entries carrying no `:state-change`
7244        // instruction at all (load + cleanup only — the metadata-only
7245        // upgrade shape the module doc names, "On any failure, the
7246        // current version stays load-bearing — a typed atomic
7247        // upgrade") leave the gate vacuous. The composition only
7248        // requires a callback when the per-version script exists; a
7249        // load + cleanup pair has no migration to deliver, so the
7250        // absence of `:on-state-change` is coherent.
7251        let entries = vec![entry(
7252            "0.1.0",
7253            vec![
7254                UpgradeInstruction::LoadModule { module: "x".into() },
7255                UpgradeInstruction::SoftPurge {
7256                    module: "x-old".into(),
7257                },
7258            ],
7259        )];
7260        validate_upgrade_from_against_behavior(&entries, None).unwrap();
7261    }
7262
7263    #[test]
7264    fn behavior_gate_accepts_restart_only_entry() {
7265        // The terminal-fallback `((:restart))` shape carries no
7266        // `:state-change` — the operator restarts the pod and the
7267        // new version comes up fresh against its initial state, no
7268        // migration. Pinned alongside the metadata-only positive
7269        // control above as the second empty-state-change shape.
7270        let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
7271        validate_upgrade_from_against_behavior(&entries, None).unwrap();
7272    }
7273
7274    #[test]
7275    fn behavior_gate_accepts_empty_entries_list() {
7276        // Empty `:upgrade-from` (a caixa with no declared upgrade
7277        // paths — the v0.1.0 caixa before any upgrade entries are
7278        // added) trivially passes the gate. Pinned so the gate
7279        // doesn't accidentally fire on a caixa that hasn't yet
7280        // declared any upgrades.
7281        let entries: Vec<UpgradeFromEntry> = vec![];
7282        validate_upgrade_from_against_behavior(&entries, None).unwrap();
7283    }
7284
7285    #[test]
7286    fn behavior_gate_reports_first_state_change_in_first_entry() {
7287        // First-collision determinism: with multiple `:state-change`
7288        // instructions across multiple entries, the gate reports the
7289        // *first* one encountered in declaration order — the entry's
7290        // declaration order first, then the within-entry instruction
7291        // order. Mirrors every peer first-collision diagnostic posture
7292        // on this module (`validate_state_change_ordering`,
7293        // `validate_purge_ordering`, the singularity gates), so a
7294        // future shortcut that walks the list in reverse or returns
7295        // the last collision surfaces as a regression here.
7296        let entries = vec![
7297            entry(
7298                "0.1.0",
7299                vec![
7300                    UpgradeInstruction::LoadModule { module: "x".into() },
7301                    UpgradeInstruction::StateChange {
7302                        script: PathBuf::from("lib/m1.lisp"),
7303                    },
7304                    UpgradeInstruction::StateChange {
7305                        script: PathBuf::from("lib/m2.lisp"),
7306                    },
7307                ],
7308            ),
7309            entry(
7310                "0.1.5",
7311                vec![
7312                    UpgradeInstruction::LoadModule { module: "x".into() },
7313                    UpgradeInstruction::StateChange {
7314                        script: PathBuf::from("lib/m3.lisp"),
7315                    },
7316                ],
7317            ),
7318        ];
7319        let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
7320        assert_eq!(
7321            err,
7322            UpgradeError::StateChangeWithoutOnStateChangeCallback {
7323                from: "0.1.0".into(),
7324                script: PathBuf::from("lib/m1.lisp"),
7325            },
7326            "the first :state-change in the first entry must surface, not later collisions"
7327        );
7328    }
7329
7330    #[test]
7331    fn behavior_gate_reports_second_entry_when_first_has_no_state_change() {
7332        // Cross-entry pin: a first entry with no `:state-change` (just
7333        // a load + cleanup) leaves the gate's per-entry walk continuing
7334        // to the second entry, where the offending instruction lives.
7335        // The diagnostic names the *second* entry's `:from` because
7336        // that's where the missing-callback shape is exposed — pinned
7337        // so a shortcut that bails on the first entry without a
7338        // `:state-change` (rather than continuing) doesn't mask the
7339        // defect in a later entry.
7340        let entries = vec![
7341            entry(
7342                "0.1.0",
7343                vec![
7344                    UpgradeInstruction::LoadModule { module: "x".into() },
7345                    UpgradeInstruction::SoftPurge {
7346                        module: "x-old".into(),
7347                    },
7348                ],
7349            ),
7350            entry(
7351                "0.1.5",
7352                vec![
7353                    UpgradeInstruction::LoadModule { module: "x".into() },
7354                    UpgradeInstruction::StateChange {
7355                        script: PathBuf::from("lib/m.lisp"),
7356                    },
7357                ],
7358            ),
7359        ];
7360        let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
7361        assert_eq!(
7362            err,
7363            UpgradeError::StateChangeWithoutOnStateChangeCallback {
7364                from: "0.1.5".into(),
7365                script: PathBuf::from("lib/m.lisp"),
7366            },
7367            "the offending entry's `:from` must surface even when an earlier entry carries no \
7368             :state-change"
7369        );
7370    }
7371
7372    #[test]
7373    fn behavior_gate_does_not_fire_when_callback_is_declared_across_many_entries() {
7374        // Positive control: a multi-entry `:upgrade-from` (chained
7375        // upgrades from v0.1.0 *and* v0.1.5) where every entry carries
7376        // a `:state-change` passes when the callback is declared once
7377        // at the caixa root. The callback is a single per-caixa
7378        // runtime hook; one declaration covers every entry's
7379        // `:state-change`, mirroring OTP's
7380        // `release_handler:install_release/1` which dispatches every
7381        // appup's `code_change` instruction through the single
7382        // `gen_server:code_change/3` callback registered on the
7383        // module.
7384        let entries = vec![
7385            entry(
7386                "0.1.0",
7387                vec![
7388                    UpgradeInstruction::LoadModule { module: "x".into() },
7389                    UpgradeInstruction::StateChange {
7390                        script: PathBuf::from("lib/m1.lisp"),
7391                    },
7392                ],
7393            ),
7394            entry(
7395                "0.1.5",
7396                vec![
7397                    UpgradeInstruction::LoadModule { module: "x".into() },
7398                    UpgradeInstruction::StateChange {
7399                        script: PathBuf::from("lib/m2.lisp"),
7400                    },
7401                ],
7402            ),
7403        ];
7404        let b = behavior_with_state_change_callback();
7405        validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
7406    }
7407
7408    #[test]
7409    fn behavior_gate_accepts_load_and_cleanup_only_when_behavior_carries_on_state_change() {
7410        // Symmetry pin: the gate's pass arm doesn't depend on the
7411        // entry actually carrying a `:state-change` — if no
7412        // `:state-change` is declared, the gate is vacuous regardless
7413        // of the callback (an `:on-state-change` declared without a
7414        // matching per-version script is fine, the callback is the
7415        // runtime default for any *future* migration the author hasn't
7416        // yet added). Pins that a caixa author can declare the
7417        // callback ahead of any migration without the gate
7418        // complaining.
7419        let entries = vec![entry(
7420            "0.1.0",
7421            vec![
7422                UpgradeInstruction::LoadModule { module: "x".into() },
7423                UpgradeInstruction::SoftPurge {
7424                    module: "x-old".into(),
7425                },
7426            ],
7427        )];
7428        let b = behavior_with_state_change_callback();
7429        validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
7430    }
7431
7432    #[test]
7433    fn validate_upgrade_from_against_behavior_projects_scripts_through_declared_path_accessor() {
7434        // Composition pin: [`validate_upgrade_from_against_behavior`]'s
7435        // per-instruction `StateChange`-arm script-path projection must
7436        // route through the sibling lifted
7437        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
7438        // accessor, not the raw
7439        // `if let UpgradeInstruction::StateChange { script } = instr`
7440        // open-coded pattern-match the cross-slot gate previously
7441        // carried at caixa-core/src/upgrade.rs:1365.
7442        //
7443        // Structurally: the gate's projection accept-set is the union
7444        // of every [`UpgradeInstruction`] variant for which
7445        // `declared_path().is_some()` — today exactly
7446        // [`UpgradeInstruction::StateChange`] per the sibling
7447        // `declared_path_only_for_state_change` pin, so a
7448        // `:state-change`-carrying entry without an `:on-state-change`
7449        // callback trips `StateChangeWithoutOnStateChangeCallback` and
7450        // a non-`StateChange` entry (load-only / cleanup-only /
7451        // restart-only / empty-`:instructions`) leaves the per-entry
7452        // walk continuing past every non-projecting instruction
7453        // byte-identical to the pattern-match shape.
7454        //
7455        // Byte-equal today (`declared_path` returns `Some(script)` iff
7456        // `StateChange`, byte-for-byte from the variant's own storage);
7457        // the pin catches any future accessor extension that promotes
7458        // an additional variant onto the `PathBuf`-carrying axis — the
7459        // gate then fires on scripts from that variant too, and the
7460        // cross-slot composition discipline the sibling per-
7461        // `UpgradeInstruction` consumers share on the `PathBuf`-
7462        // carrying axis extends to the promoted variant by
7463        // construction.
7464        //
7465        // Peer of the sibling four per-`UpgradeInstruction` consumers
7466        // ([`UpgradeInstruction::validate`]'s per-`StateChange`
7467        // sandbox-path fan-out, the layout-side per-`StateChange`
7468        // script-existence fan-out at
7469        // `caixa-core/src/layout.rs:1058`, the within-entry
7470        // [`UpgradeFromEntry::validate_state_change_singularity`]
7471        // (2bf3ce5) per-`StateChange` script-projection fan-out, the
7472        // peer [`UpgradeInstruction::declared_module`] `String`-axis
7473        // per-variant unifier) — the fourth (and last) per-
7474        // `UpgradeInstruction`-consumer of the `PathBuf`-carrying axis
7475        // to now route through the accessor. Same shape as the
7476        // sibling
7477        // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
7478        // pin extended onto the cross-slot composition gate.
7479        //
7480        // Three-arm projective coverage:
7481        //   (a) `StateChange` scripts project through `declared_path()`
7482        //       byte-equal to the raw `script.clone()` field access
7483        //       the diagnostic previously carried;
7484        //   (b) a `:state-change`-carrying entry with `behavior: None`
7485        //       trips the gate with `StateChangeWithoutOnStateChangeCallback`
7486        //       carrying the offending script verbatim;
7487        //   (c) a non-`StateChange`-only entry (`LoadModule` /
7488        //       `SoftPurge` / `Purge` / `Restart`) leaves the gate
7489        //       vacuous with `Ok(())` — the `declared_path().is_none()`
7490        //       arm's fall-through pins.
7491        //
7492        // Fail-before-pass-after verified structurally: swapping the
7493        // production
7494        //   `if let Some(script) = instr.declared_path() { … }`
7495        // back to
7496        //   `if let UpgradeInstruction::StateChange { script } = instr { … }`
7497        // keeps arms (a)-(c) passing but silently detaches the gate
7498        // from the accessor's typed dispatch — any future
7499        // `declared_path` extension (promotion of an additional
7500        // variant onto the axis, an operator-side pre-resolved-path
7501        // cache the accessor materializes) would then silently
7502        // disagree between this cross-slot gate's raw pattern-match
7503        // and the peer four sibling consumers that route through the
7504        // accessor.
7505
7506        // (a) StateChange projection byte-equal via declared_path.
7507        let sc = UpgradeInstruction::StateChange {
7508            script: PathBuf::from("lib/m.lisp"),
7509        };
7510        assert_eq!(
7511            sc.declared_path().cloned(),
7512            Some(PathBuf::from("lib/m.lisp")),
7513            "declared_path() must project the StateChange :script byte-equal to the raw \
7514             field access — accessor divergence would silently detach this cross-slot \
7515             composition gate from the projection every peer per-`UpgradeInstruction` \
7516             consumer routes through"
7517        );
7518
7519        // (b) StateChange-carrying entry with behavior: None trips gate.
7520        let entries = vec![entry(
7521            "0.1.0",
7522            vec![
7523                UpgradeInstruction::LoadModule { module: "x".into() },
7524                UpgradeInstruction::StateChange {
7525                    script: PathBuf::from("lib/m.lisp"),
7526                },
7527            ],
7528        )];
7529        assert_eq!(
7530            validate_upgrade_from_against_behavior(&entries, None),
7531            Err(UpgradeError::StateChangeWithoutOnStateChangeCallback {
7532                from: "0.1.0".into(),
7533                script: PathBuf::from("lib/m.lisp"),
7534            }),
7535            "a :state-change-carrying entry with behavior: None must trip the gate through \
7536             the declared_path accessor's Some(script) arm — carrying the offending script \
7537             verbatim byte-identical to the pattern-match shape"
7538        );
7539
7540        // (c) Non-StateChange-only inputs leave the gate vacuous.
7541        for instrs in [
7542            vec![UpgradeInstruction::LoadModule { module: "x".into() }],
7543            vec![
7544                UpgradeInstruction::LoadModule { module: "x".into() },
7545                UpgradeInstruction::SoftPurge {
7546                    module: "x-old".into(),
7547                },
7548            ],
7549            vec![
7550                UpgradeInstruction::LoadModule { module: "x".into() },
7551                UpgradeInstruction::Purge {
7552                    module: "x-old".into(),
7553                },
7554            ],
7555            vec![UpgradeInstruction::Restart],
7556        ] {
7557            for instr in &instrs {
7558                assert!(
7559                    instr.declared_path().is_none(),
7560                    "non-StateChange variants must project None through declared_path — \
7561                     accessor divergence would let this cross-slot composition gate silently \
7562                     fire on a module reference far from any :state-change site"
7563                );
7564            }
7565            let entries = vec![entry("0.1.0", instrs)];
7566            assert_eq!(
7567                validate_upgrade_from_against_behavior(&entries, None),
7568                Ok(()),
7569                "the cross-slot composition gate must return Ok(()) on an entry whose \
7570                 instructions all project None through declared_path — the accessor's \
7571                 None arm the pattern-match's implicit fall-through previously carried"
7572            );
7573        }
7574    }
7575
7576    #[test]
7577    fn validate_restart_exclusive_threads_through_validate_upgrade_from() {
7578        // Wiring pin: the within-entry restart-exclusivity gate fires
7579        // through [`validate_upgrade_from`] (which delegates to
7580        // [`UpgradeFromEntry::validate`] per entry) before the cross-
7581        // entry duplicate-`:from` gate would have a chance to run on
7582        // the malformed entry. Pinned here so a future refactor that
7583        // walks the cross-entry gate first doesn't accidentally
7584        // surface a DuplicateFrom over an entry that's also malformed
7585        // at the within-entry restart-exclusivity layer.
7586        let entries = vec![
7587            entry(
7588                "0.1.0",
7589                vec![
7590                    UpgradeInstruction::LoadModule { module: "x".into() },
7591                    UpgradeInstruction::Restart,
7592                ],
7593            ),
7594            entry("0.1.0", vec![UpgradeInstruction::Restart]),
7595        ];
7596        let err = validate_upgrade_from(&entries).unwrap_err();
7597        assert!(
7598            matches!(
7599                err,
7600                UpgradeError::RestartNotExclusive {
7601                    restart_count: 1,
7602                    ..
7603                }
7604            ),
7605            "within-entry restart-exclusivity diagnostic must surface before the cross-entry \
7606             duplicate-`:from` gate fires, got {err:?}"
7607        );
7608    }
7609
7610    // ── drift-detection: serde-derive-to-M2_UPGRADE_FROM_KEY_* identity ──
7611
7612    #[test]
7613    fn upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts() {
7614        // Load-bearing invariant: the two `M2_UPGRADE_FROM_KEY_*` consts
7615        // (`M2_UPGRADE_FROM_KEY_FROM` / `M2_UPGRADE_FROM_KEY_INSTRUCTIONS`)
7616        // name the exact camelCase JSON keys the `#[serde(rename_all =
7617        // "camelCase")]` attribute on `UpgradeFromEntry` emits, and every
7618        // test-side probe across the caixa-core / caixa-flux renderer
7619        // test fixtures navigates into each element of the rendered
7620        // `:upgrade-from` overlay sequence by consulting one of these two
7621        // `&'static str`s. Serialize a fully-populated UpgradeFromEntry
7622        // and pin that each canonical byte-sequence appears verbatim in
7623        // the JSON — a future accidental `rename_all = "snake_case"` /
7624        // `"kebab-case"` / verbatim-field-name flip at the derive
7625        // attribute (any of which would silently break every test-side
7626        // probe that reaches for one of the two consts) surfaces here as
7627        // a build-time test failure at `upgrade.rs`, not as an apply-time
7628        // `.get(<stale-canonical-const>)` returning `None` far from the
7629        // derive-attr drift's commit. Same discipline the sibling
7630        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7631        // (d8b8b4f) and
7632        // `behavior_spec_serde_keys_match_lifted_m2_behavior_key_consts`
7633        // (21fe462) pins established on the peer `:limits` / `:behavior`
7634        // sub-slot axes: one canonical byte-string per typed sub-key
7635        // axis, pinned to the load-bearing serde derivation at the type
7636        // itself.
7637        let e = UpgradeFromEntry {
7638            from: "0.1.0".into(),
7639            instructions: vec![UpgradeInstruction::LoadModule {
7640                module: "hello-rio".into(),
7641            }],
7642        };
7643        let json = serde_json::to_string(&e).unwrap();
7644        for key in [
7645            crate::render::M2_UPGRADE_FROM_KEY_FROM,
7646            crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
7647        ] {
7648            let quoted = format!("\"{key}\"");
7649            assert!(
7650                json.contains(&quoted),
7651                "serialized UpgradeFromEntry must carry the lifted \
7652                 M2_UPGRADE_FROM_KEY_* byte-sequence {quoted} verbatim in \
7653                 the JSON emission (got: {json})",
7654            );
7655        }
7656    }
7657
7658    #[test]
7659    fn m2_upgrade_from_key_consts_are_pairwise_distinct() {
7660        // Cross-axis drift-detection pin: a future collapse of the two
7661        // canonical sub-key byte-strings onto the same value (e.g. an
7662        // accidental copy-paste flip of `M2_UPGRADE_FROM_KEY_INSTRUCTIONS`
7663        // to also read `"from"`) would silently reroute every test-side
7664        // probe on one axis onto the sibling axis's per-entry field and
7665        // pass every propagation-probe test that expected only the stale
7666        // axis's value. Peer of `m2_limits_key_consts_are_pairwise_distinct`
7667        // (d8b8b4f) and `m2_behavior_key_consts_are_pairwise_distinct`
7668        // (21fe462) on the sibling `:limits` / `:behavior` sub-slot axes.
7669        let all = [
7670            crate::render::M2_UPGRADE_FROM_KEY_FROM,
7671            crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
7672        ];
7673        for (i, a) in all.iter().enumerate() {
7674            for b in all.iter().skip(i + 1) {
7675                assert_ne!(
7676                    a, b,
7677                    "M2_UPGRADE_FROM_KEY_* consts must be pairwise-distinct \
7678                     canonical byte-sequences — got `{a}` == `{b}`",
7679                );
7680            }
7681        }
7682    }
7683
7684    #[test]
7685    fn upgrade_instruction_serde_tag_key_matches_lifted_m2_upgrade_instruction_key_kind_const() {
7686        // Load-bearing invariant on the M2 `:upgrade-from :instructions`
7687        // per-entry OTP-appup [`UpgradeInstruction`] enum's internally-
7688        // tagged variant-discriminator key axis: the
7689        // `M2_UPGRADE_INSTRUCTION_KEY_KIND` const names the exact tag-slot
7690        // JSON key the `#[serde(tag = "kind", rename_all = "kebab-case")]`
7691        // attribute on [`UpgradeInstruction`] emits, and every downstream
7692        // consumer that navigates the serialized instruction blob to
7693        // route by variant (the caixa-core reflection-vs-serde round-trip
7694        // check in `dispatcher_registration.rs` that probes
7695        // `v.get("kind")` against every variant's expected kebab-case
7696        // tag, the future M4 admission-webhook path, any wasm-operator
7697        // dispatch step consuming the serialized instruction blob) reads
7698        // through the same `&'static str`. Serialize every variant and
7699        // pin that the const's byte-sequence appears verbatim as the
7700        // tag-slot JSON key with the expected kebab-case value — a
7701        // future accidental `tag = "type"` / `tag = "op"` /
7702        // `tag = "instruction"` rebrand at the derive attribute (any of
7703        // which would silently break every consumer probe reaching for
7704        // the stale-tag-key const) surfaces here as a build-time test
7705        // failure at `upgrade.rs`, not as an apply-time
7706        // `.get(<stale-tag-key>)` returning `None` far from the derive-
7707        // attr drift's commit.
7708        //
7709        // Same "one canonical byte-string per typed axis" discipline the
7710        // sibling `upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts`
7711        // pin (36ffe65) established on the peer `:upgrade-from` per-entry
7712        // outer-container axis — this pin extends the discipline one
7713        // altitude deeper onto the per-instruction *tag* axis inside
7714        // each element of the `:instructions` list, completing the
7715        // typed coverage of the `:upgrade-from :instructions` dual
7716        // (key = "kind" + five variant-value tags): the five
7717        // `M2_UPGRADE_INSTRUCTION_KIND_*` consts (56120ef) pin the
7718        // per-variant kebab-case *values*; this pin pins the tag *key*
7719        // above them.
7720        let samples: [(UpgradeInstruction, &'static str); 5] = [
7721            (
7722                UpgradeInstruction::LoadModule {
7723                    module: "hello-rio".into(),
7724                },
7725                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE.trim_start_matches(':'),
7726            ),
7727            (
7728                UpgradeInstruction::StateChange {
7729                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7730                },
7731                crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE.trim_start_matches(':'),
7732            ),
7733            (
7734                UpgradeInstruction::SoftPurge {
7735                    module: "hello-rio-old".into(),
7736                },
7737                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE.trim_start_matches(':'),
7738            ),
7739            (
7740                UpgradeInstruction::Purge {
7741                    module: "hello-rio-old".into(),
7742                },
7743                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE.trim_start_matches(':'),
7744            ),
7745            (
7746                UpgradeInstruction::Restart,
7747                crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART.trim_start_matches(':'),
7748            ),
7749        ];
7750        for (sample, expected_value) in &samples {
7751            let v: serde_json::Value = serde_json::to_value(sample).unwrap();
7752            let got = v
7753                .get(crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND)
7754                .and_then(|k| k.as_str());
7755            assert_eq!(
7756                got,
7757                Some(*expected_value),
7758                "serialized {sample:?} must carry the lifted \
7759                 M2_UPGRADE_INSTRUCTION_KEY_KIND byte-sequence \
7760                 ({:?}) verbatim as the tag-slot JSON key, holding the \
7761                 expected kebab-case value {expected_value:?} (got: {v})",
7762                crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND,
7763            );
7764        }
7765    }
7766
7767    #[test]
7768    fn m2_upgrade_instruction_key_kind_const_is_lower_camel_case_shape() {
7769        // Shape-pin: the `M2_UPGRADE_INSTRUCTION_KEY_KIND` const must be
7770        // a lowerCamelCase byte-sequence (non-empty, ASCII-lowercase
7771        // leader, ASCII-alphanumeric only — no `snake_case` underscores,
7772        // no `kebab-case` hyphens, no `PascalCase` leading capital, no
7773        // whitespace / colons / dots) — the canonical shape a serde
7774        // internally-tagged discriminator key takes across every peer
7775        // enum in this crate. A future flip to a non-camelCase byte at
7776        // the const surfaces here at build time. Peer of
7777        // `m2_upgrade_from_key_consts_are_lower_camel_case_shape` on the
7778        // sibling per-entry outer-container axis.
7779        let key = crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND;
7780        assert!(
7781            !key.is_empty(),
7782            "M2_UPGRADE_INSTRUCTION_KEY_KIND must be non-empty (got {key:?})"
7783        );
7784        let first = key.chars().next().unwrap();
7785        assert!(
7786            first.is_ascii_lowercase(),
7787            "M2_UPGRADE_INSTRUCTION_KEY_KIND must lead with an ASCII-lowercase \
7788             byte (got {key:?}, leads with {first:?})",
7789        );
7790        assert!(
7791            key.chars().all(|c| c.is_ascii_alphanumeric()),
7792            "M2_UPGRADE_INSTRUCTION_KEY_KIND must be ASCII-alphanumeric only \
7793             — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7794        );
7795    }
7796
7797    #[test]
7798    fn m2_upgrade_instruction_key_kind_const_disjoint_from_variant_data_keys() {
7799        // Cross-axis drift-detection pin: the tag-slot key
7800        // `M2_UPGRADE_INSTRUCTION_KEY_KIND` (`"kind"`) must be
7801        // disjoint from every per-variant data-field key the
7802        // internally-tagged serialization also emits (`"module"` for
7803        // LoadModule/SoftPurge/Purge, `"script"` for StateChange). A
7804        // future accidental rebrand that collapses `tag = "kind"` onto
7805        // one of the data-field names (e.g. `tag = "module"`) would
7806        // silently corrupt every serialized LoadModule blob (the
7807        // module string and the variant tag would collide on the same
7808        // JSON key) and every consumer probe would either misread the
7809        // tag or fail to distinguish variants. Pin the disjointness at
7810        // build time. Same cross-axis discipline the sibling
7811        // `m2_upgrade_from_key_consts_are_pairwise_distinct` pin
7812        // (36ffe65) established on the outer container's own
7813        // `from`/`instructions` pair.
7814        let key = crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND;
7815        // Enumerate every per-variant data-field key across all five
7816        // variants of [`UpgradeInstruction`], routing through the two
7817        // lifted `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` byte-string consts
7818        // that name the same per-variant data-field JSON keys the
7819        // `variant_fields` reflection in
7820        // `caixa-core/tests/dispatcher_registration.rs` surfaces. A future
7821        // per-variant struct-field rebrand (`module` → `component`,
7822        // `script` → `path`) lands as an edit to exactly one const and
7823        // reaches this disjointness pin by construction — the two axes
7824        // (tag-slot key on one side, per-variant data-field keys on the
7825        // other) share one source of truth per axis.
7826        for data_field in [
7827            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7828            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7829        ] {
7830            assert_ne!(
7831                key, data_field,
7832                "M2_UPGRADE_INSTRUCTION_KEY_KIND (the serde `tag` slot) \
7833                 must be disjoint from every UpgradeInstruction per-variant \
7834                 data-field key — got tag-key {key:?} colliding with \
7835                 data-field {data_field:?}, which would silently corrupt \
7836                 the internally-tagged serialization",
7837            );
7838        }
7839    }
7840
7841    #[test]
7842    fn upgrade_instruction_variant_data_field_keys_match_lifted_field_key_consts() {
7843        // Load-bearing invariant on the M2 `:upgrade-from :instructions`
7844        // per-entry OTP-appup [`UpgradeInstruction`] enum's per-variant
7845        // data-field JSON key axis: the two
7846        // `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` consts (`_MODULE`,
7847        // `_SCRIPT`) name the exact per-variant field JSON keys the
7848        // `#[serde(tag = "kind", rename_all = "kebab-case")]` attribute on
7849        // [`UpgradeInstruction`] emits alongside the tag-slot key from the
7850        // sibling [`crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND`]
7851        // const — the `module: String` struct-field on
7852        // `LoadModule`/`SoftPurge`/`Purge` and the `script: PathBuf`
7853        // struct-field on `StateChange` are promoted to sibling JSON keys
7854        // at the same nesting level as the tag by the internally-tagged
7855        // serialization, and every downstream consumer that navigates the
7856        // serialized instruction blob to reach the payload (the caixa-core
7857        // reflection round-trip in `dispatcher_registration.rs` that
7858        // consults `variant_fields`, the sibling disjointness pin below,
7859        // any future wasm-operator upgrade-dispatch step consuming the
7860        // serialized instruction blob to route the per-module load /
7861        // soft-purge / purge action or the per-script state-change action)
7862        // reads through the same `&'static str`. Serialize one Module-
7863        // bearing variant and one Script-bearing variant, then pin that
7864        // each const's byte-sequence appears verbatim in the JSON emission
7865        // — a future accidental struct-field rebrand (`module: String` →
7866        // `component: String`, `script: PathBuf` → `path: PathBuf`) at
7867        // either variant surfaces here as a build-time test failure at
7868        // `upgrade.rs`, not as an apply-time `.get(<stale-field-key>)`
7869        // returning `None` far from the field-name drift's commit.
7870        //
7871        // Same "one canonical byte-string per typed axis" discipline the
7872        // sibling `upgrade_instruction_serde_tag_key_matches_lifted_m2_upgrade_instruction_key_kind_const`
7873        // pin established on the peer tag-slot key axis on the same
7874        // enum — this pin extends the discipline onto the per-variant
7875        // data-field key axis, completing the `:upgrade-from :instructions`
7876        // variant-JSON dual (tag key + tag values + per-variant field keys)
7877        // fully into caixa-core.
7878        let module_sample = UpgradeInstruction::LoadModule {
7879            module: "hello-rio".into(),
7880        };
7881        let v: serde_json::Value = serde_json::to_value(&module_sample).unwrap();
7882        assert_eq!(
7883            v.get(crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE)
7884                .and_then(|k| k.as_str()),
7885            Some("hello-rio"),
7886            "serialized {module_sample:?} must carry the lifted \
7887             M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE byte-sequence \
7888             ({:?}) verbatim as the data-field JSON key holding the \
7889             module string (got: {v})",
7890            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7891        );
7892
7893        let script_sample = UpgradeInstruction::StateChange {
7894            script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7895        };
7896        let v: serde_json::Value = serde_json::to_value(&script_sample).unwrap();
7897        assert_eq!(
7898            v.get(crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT)
7899                .and_then(|k| k.as_str()),
7900            Some("lib/migrations/v01-to-v02.lisp"),
7901            "serialized {script_sample:?} must carry the lifted \
7902             M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT byte-sequence \
7903             ({:?}) verbatim as the data-field JSON key holding the \
7904             script path (got: {v})",
7905            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7906        );
7907    }
7908
7909    #[test]
7910    fn m2_upgrade_instruction_field_key_consts_are_lower_camel_case_shape() {
7911        // Shape-pin: every `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` const must
7912        // be a lowerCamelCase byte-sequence (non-empty, ASCII-lowercase
7913        // leader, ASCII-alphanumeric only — no `snake_case` underscores,
7914        // no `kebab-case` hyphens, no `PascalCase` leading capital, no
7915        // whitespace / colons / dots) — the canonical shape a Rust
7916        // struct-field name promoted to a JSON key by serde takes on this
7917        // internally-tagged variant surface, matching the sibling
7918        // [`crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND`] tag-slot key
7919        // shape. A future flip to a non-camelCase byte at either const
7920        // (an accidental `rename_all` regime interleave, or a struct-
7921        // field flip like `module` → `module_name`) surfaces here at
7922        // build time. Peer of
7923        // `m2_upgrade_instruction_key_kind_const_is_lower_camel_case_shape`
7924        // and `m2_upgrade_from_key_consts_are_lower_camel_case_shape` on
7925        // the sibling wire-key axes.
7926        for key in [
7927            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7928            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7929        ] {
7930            assert!(
7931                !key.is_empty(),
7932                "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must be non-empty (got {key:?})"
7933            );
7934            let first = key.chars().next().unwrap();
7935            assert!(
7936                first.is_ascii_lowercase(),
7937                "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must lead with an ASCII-lowercase \
7938                 byte (got {key:?}, leads with {first:?})",
7939            );
7940            assert!(
7941                key.chars().all(|c| c.is_ascii_alphanumeric()),
7942                "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must be ASCII-alphanumeric only \
7943                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7944            );
7945        }
7946    }
7947
7948    #[test]
7949    fn m2_upgrade_instruction_field_key_consts_are_pairwise_distinct() {
7950        // Cross-axis drift-detection pin: a future collapse of the two
7951        // canonical per-variant data-field byte-strings onto the same
7952        // value (e.g. an accidental copy-paste flip of
7953        // `M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT` to also read
7954        // `"module"`) would silently reroute every test-side probe on one
7955        // variant's payload onto the sibling variant's payload and pass
7956        // every propagation-probe test that expected only the stale
7957        // axis's value. Peer of `m2_upgrade_from_key_consts_are_pairwise_distinct`
7958        // on the sibling per-entry outer-container axis, and of
7959        // `m2_upgrade_instruction_key_kind_const_disjoint_from_variant_data_keys`
7960        // on the sibling tag-slot key ↔ per-variant data-field key axis.
7961        let all = [
7962            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7963            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7964        ];
7965        for (i, a) in all.iter().enumerate() {
7966            for b in all.iter().skip(i + 1) {
7967                assert_ne!(
7968                    a, b,
7969                    "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* consts must be pairwise-distinct \
7970                     canonical byte-sequences — got `{a}` == `{b}`",
7971                );
7972            }
7973        }
7974    }
7975
7976    #[test]
7977    fn m2_upgrade_from_key_consts_are_lower_camel_case_shape() {
7978        // Shape-pin: every `M2_UPGRADE_FROM_KEY_*` const must be a
7979        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7980        // `kebab-case` hyphens, no `PascalCase` leading capital, no
7981        // whitespace / colons / dots) — the canonical shape the
7982        // `#[serde(rename_all = "camelCase")]` derive produces on
7983        // `UpgradeFromEntry`. A future flip to a non-camelCase attribute
7984        // at the derive surfaces both here (this test fails on the
7985        // stale-constant shape) and at
7986        // `upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts`
7987        // (that test fails on the mismatch between const and derive).
7988        // Peer of `m2_limits_key_consts_are_lower_camel_case_shape`
7989        // (d8b8b4f) and `m2_behavior_key_consts_are_lower_camel_case_shape`
7990        // (21fe462) on the sibling `:limits` / `:behavior` sub-slot axes.
7991        for key in [
7992            crate::render::M2_UPGRADE_FROM_KEY_FROM,
7993            crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
7994        ] {
7995            assert!(
7996                !key.is_empty(),
7997                "M2_UPGRADE_FROM_KEY_* must be non-empty (got {key:?})"
7998            );
7999            let first = key.chars().next().unwrap();
8000            assert!(
8001                first.is_ascii_lowercase(),
8002                "M2_UPGRADE_FROM_KEY_* must lead with an ASCII-lowercase \
8003                 byte (got {key:?}, leads with {first:?})",
8004            );
8005            assert!(
8006                key.chars().all(|c| c.is_ascii_alphanumeric()),
8007                "M2_UPGRADE_FROM_KEY_* must be ASCII-alphanumeric only \
8008                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8009            );
8010        }
8011    }
8012
8013    #[test]
8014    fn m2_upgrade_instruction_kind_consts_pin_canonical_kebab_case_labels() {
8015        // Scalar-value pin on the M2 `:upgrade-from :instructions` per-entry
8016        // OTP-appup variant-tag axis: the five canonical author-facing
8017        // kebab-case labels (`:load-module` / `:state-change` /
8018        // `:soft-purge` / `:purge` / `:restart`) the substrate's
8019        // per-variant [`UpgradeInstruction::lisp_form`] dispatch reads
8020        // from and every downstream consumer probes for verbatim. Same
8021        // scalar-value discipline the peer
8022        // `contrato_author_key_consts_pin_canonical_kebab_case_labels`
8023        // (f50c875), `m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8024        // (882f498), `m2_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8025        // (f49c8b0), and `supervisor_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8026        // (be40492) established for the sibling M2 / M3 / Supervisor
8027        // top-level and sub-slot author-facing-label axes. Fail-before-
8028        // pass-after locally verified by mutating
8029        // `M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE` to `":load"` — this
8030        // pin fires as expected; restoring passes.
8031        //
8032        // A future OTP-lineage per-variant rebrand (e.g.
8033        // `:load-module` → `:load` matching Erlang's abbreviated
8034        // `code:load_module` name, `:state-change` → `:code-change`
8035        // matching Erlang's verbatim `code_change/3` callback,
8036        // `:soft-purge` → `:drain` matching a hypothetical operator-side
8037        // vocabulary flip, `:purge` → `:discard` matching a hypothetical
8038        // Elixir/Phoenix hot-reload rebrand, `:restart` → `:reboot`
8039        // matching a supervisor-tree vocabulary alignment) lands as an
8040        // edit to exactly one const, and every consumer that reaches for
8041        // the label (the [`UpgradeInstruction::lisp_form`] dispatch, the
8042        // [`validate_cleanup_singularity`] per-variant `kind:` tagger,
8043        // every [`UpgradeError`] `kind:` / `kinds:` / `other_kinds:` /
8044        // `prior_cleanup_kind:` diagnostic field, the
8045        // [`LayoutError::UpgradeViolation`] `issue:` probe in
8046        // `layout.rs`) picks it up at build time rather than at runtime
8047        // as a downstream `kind: <stale-kebab-case>` diagnostic mismatch
8048        // far from the rename's commit.
8049        assert_eq!(
8050            crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
8051            ":load-module"
8052        );
8053        assert_eq!(
8054            crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
8055            ":state-change"
8056        );
8057        assert_eq!(
8058            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8059            ":soft-purge"
8060        );
8061        assert_eq!(crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE, ":purge");
8062        assert_eq!(
8063            crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
8064            ":restart"
8065        );
8066    }
8067
8068    #[test]
8069    fn m2_upgrade_instruction_kind_consts_are_pairwise_distinct() {
8070        // Cross-arm drift-detection pin on the M2
8071        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE`] /
8072        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE`] /
8073        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`] /
8074        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE`] /
8075        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART`]
8076        // closed-set OTP-appup variant-tag pentad: a future collapse
8077        // of two canonical variant byte-strings onto the same value
8078        // (an accidental copy-paste flip of
8079        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`]
8080        // to also read `":purge"`, a per-arm rebrand that lands one
8081        // const without touching its paired peer) would silently
8082        // reroute every downstream OTP-appup dispatcher's per-
8083        // instruction branch onto the sibling arm's runtime
8084        // behavior and pass every propagation-probe test that
8085        // expected only the stale arm's tag — a `:soft-purge`
8086        // instruction (drain-then-swap: existing callers finish
8087        // under the old module, new callers land on the new one)
8088        // would come up under the `:purge` reconcile branch
8089        // (drop-existing: every in-flight caller terminates
8090        // immediately) on every hot-upgrade cycle, so a rolling
8091        // module swap would silently downgrade to a hard cutover
8092        // against its declared appup discipline, with no field
8093        // naming the instruction-tag drift root cause. Every
8094        // [`crate::UpgradeError`] diagnostic that surfaces the tag
8095        // ([`crate::UpgradeError::ModuleEmpty`] with `kind:` field,
8096        // [`crate::UpgradeError::CleanupCollision`] with `kinds:`
8097        // slice, [`crate::UpgradeError::CleanupPrecedes`] with
8098        // `prior_cleanup_kind:` field, the
8099        // [`crate::LayoutError::UpgradeViolation`] `issue:` probe in
8100        // `layout.rs`) would emit the sibling arm's stale bytes at
8101        // the operator's console, far from the source rebrand
8102        // commit. Peer of the sibling
8103        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
8104        // (09ffb2d) /
8105        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
8106        // (ccdf955) /
8107        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
8108        // (d739850) distinctness pins on the sibling OTP-shape /
8109        // caixa-kind closed-set typed-enum discriminator axes —
8110        // the fifth closed-set OTP-appup / typed-enum axis to
8111        // converge on the same
8112        // "pairwise-distinct-by-construction" discipline, and the
8113        // canonical companion to the peer
8114        // [`m2_upgrade_instruction_field_key_consts_are_pairwise_distinct`]
8115        // (ff980bb) distinctness pin on the sibling internally-
8116        // tagged-JSON per-variant data-field-key axis (the tag axis
8117        // this pin covers vs. the data-field-key axis its peer
8118        // covers — two paired axes on the same
8119        // [`crate::UpgradeInstruction`] typed enum surface).
8120        //
8121        // Fail-before-pass-after locally verified by mutating
8122        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`]
8123        // to also read `":purge"` — this pin fires as expected;
8124        // restoring passes.
8125        let all = [
8126            crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
8127            crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
8128            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8129            crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
8130            crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
8131        ];
8132        for (i, a) in all.iter().enumerate() {
8133            for (j, b) in all.iter().enumerate() {
8134                if i != j {
8135                    assert_ne!(
8136                        a, b,
8137                        "M2_UPGRADE_INSTRUCTION_KIND_* consts must be pairwise \
8138                         distinct — got duplicate {a:?} at indices {i} and {j}",
8139                    );
8140                }
8141            }
8142        }
8143    }
8144
8145    #[test]
8146    fn upgrade_instruction_lisp_form_routes_through_lifted_kind_consts() {
8147        // Production-through-const pin: the five per-variant labels
8148        // [`UpgradeInstruction::lisp_form`] returns route through the
8149        // lifted [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_*`] consts,
8150        // so a future rebrand that reaches the const but not the
8151        // dispatch (or vice versa) surfaces here at build time rather
8152        // than at runtime as a downstream
8153        // [`UpgradeError::ModuleEmpty`] `kind: <stale-kebab-case>`
8154        // diagnostic drift far from the rename's commit. Mirror of the
8155        // peer `contrato_shape_gate_routes_through_lifted_contrato_author_key_consts`
8156        // (f50c875), `declared_mesh_slots_route_through_lifted_m3_author_key_consts`
8157        // (882f498), and `declared_servico_slots_route_through_lifted_m2_author_key_consts`
8158        // (f49c8b0) production-through-const pins on the sibling M3 /
8159        // M2 top-level slot axes.
8160        //
8161        // Fail-before-pass-after locally verified by mutating
8162        // `UpgradeInstruction::lisp_form`'s `Self::Purge` arm to return
8163        // `":purge-drift"` — this pin fires as expected; restoring
8164        // passes.
8165        let cases: &[(UpgradeInstruction, &'static str)] = &[
8166            (
8167                UpgradeInstruction::LoadModule { module: "x".into() },
8168                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
8169            ),
8170            (
8171                UpgradeInstruction::StateChange {
8172                    script: PathBuf::from("lib/m.lisp"),
8173                },
8174                crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
8175            ),
8176            (
8177                UpgradeInstruction::SoftPurge {
8178                    module: "x-old".into(),
8179                },
8180                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8181            ),
8182            (
8183                UpgradeInstruction::Purge {
8184                    module: "x-old".into(),
8185                },
8186                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
8187            ),
8188            (
8189                UpgradeInstruction::Restart,
8190                crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
8191            ),
8192        ];
8193        for (instr, expected) in cases {
8194            assert_eq!(
8195                instr.lisp_form(),
8196                *expected,
8197                "UpgradeInstruction::lisp_form on {instr:?} must route through the lifted \
8198                 const (expected {expected:?})",
8199            );
8200        }
8201    }
8202
8203    #[test]
8204    fn upgrade_from_entry_instructions_returns_instructions_slice_byte_equal_across_permutations() {
8205        // The canonical per-`:upgrade-from :instructions` OTP-appup
8206        // migration-instruction-list slice-shape pin:
8207        // [`UpgradeFromEntry::instructions`] must return the
8208        // `:instructions` typed `Vec<UpgradeInstruction>` verbatim as
8209        // a `&[UpgradeInstruction]` slice-view over the same backing
8210        // buffer the raw `self.instructions.as_slice()` field access
8211        // borrows from, byte-equal across every representative fixture
8212        // in the accept-set — the empty slice (the "no-op upgrade" /
8213        // metadata-only sentinel the [`UpgradeFromEntry::instructions`]
8214        // field's own docstring names), the singleton slice on every
8215        // variant of the [`UpgradeInstruction`] arm-space
8216        // (`LoadModule` / `StateChange` / `SoftPurge` / `Purge` /
8217        // `Restart` — the five OTP-appup runtime-primitive variants),
8218        // and multi-instruction cohorts (the canonical
8219        // `LoadModule → StateChange → SoftPurge` OTP two-phase code-
8220        // load + state-migration triad the module doc names as the
8221        // "runs the instructions in order" example).
8222        //
8223        // Pins against a future silent detour that returned
8224        // `&Vec<UpgradeInstruction>` (which would type-check but leak
8225        // the storage-side `Vec`'s grow/push/reserve surface no
8226        // consumer of the typed view reaches for), a fresh-allocated
8227        // `Vec<UpgradeInstruction>` copy (which would type-check via
8228        // a coercion but silently break every downstream caller that
8229        // relied on the slice sharing the backing buffer's identity),
8230        // or an out-of-order or length-drifted projection (which
8231        // would silently split the paired within-entry cross-
8232        // instruction ordering gates' inputs from the peer per-
8233        // instruction shape-check loop's input, one seven-gate cohort
8234        // silently drifting from the peer gate's actual traversal
8235        // input).
8236        //
8237        // Peer of the sibling
8238        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
8239        // (0dcc926) `&[WitContract]` byte-equal pin on the M3 per-
8240        // `:contratos` edge-list axis, extended onto the M2 per-
8241        // `:upgrade-from :instructions` migration-instruction-list
8242        // axis — the fifth `&[T]`-return byte-equal pin, closing the
8243        // last unlifted `Vec`-carry axis on any M2 or M3 typed slot.
8244        let fixtures: Vec<Vec<UpgradeInstruction>> = vec![
8245            Vec::new(),
8246            vec![UpgradeInstruction::LoadModule { module: "x".into() }],
8247            vec![UpgradeInstruction::StateChange {
8248                script: PathBuf::from("lib/m.lisp"),
8249            }],
8250            vec![UpgradeInstruction::SoftPurge {
8251                module: "x-old".into(),
8252            }],
8253            vec![UpgradeInstruction::Purge {
8254                module: "x-old".into(),
8255            }],
8256            vec![UpgradeInstruction::Restart],
8257            vec![
8258                UpgradeInstruction::LoadModule { module: "x".into() },
8259                UpgradeInstruction::StateChange {
8260                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
8261                },
8262                UpgradeInstruction::SoftPurge {
8263                    module: "x-old".into(),
8264                },
8265            ],
8266        ];
8267        for instructions in fixtures {
8268            let e = UpgradeFromEntry {
8269                from: "0.1.0".into(),
8270                instructions: instructions.clone(),
8271            };
8272            assert_eq!(
8273                e.instructions(),
8274                e.instructions.as_slice(),
8275                "UpgradeFromEntry::instructions must project the raw \
8276                 `:instructions` `Vec<UpgradeInstruction>` verbatim as a \
8277                 `&[UpgradeInstruction]` slice-view over the same backing buffer \
8278                 (fixture: {instructions:?})",
8279            );
8280            assert_eq!(
8281                e.instructions().len(),
8282                instructions.len(),
8283                "UpgradeFromEntry::instructions length must match the raw \
8284                 `:instructions` `Vec<UpgradeInstruction>` length (fixture: {instructions:?})",
8285            );
8286        }
8287    }
8288
8289    #[test]
8290    fn validate_reads_through_lifted_instructions_accessor() {
8291        // Three-consumer coherence pin on the lifted
8292        // [`UpgradeFromEntry::instructions`] slice-return accessor:
8293        // exercises three of the nine paired production consumers of
8294        // the per-`:upgrade-from :instructions` OTP-appup migration-
8295        // instruction-list surface through end-to-end validate() paths
8296        // that require the accessor to reach each of the fixture's
8297        // instructions.
8298        //
8299        // (1) The per-instruction shape-check fan-out
8300        // ([`UpgradeFromEntry::validate`]'s `for instr in
8301        // self.instructions()` loop): pass the well-formed load →
8302        // state-change → soft-purge triad — `validate()` must accept
8303        // it, which requires the accessor to project every entry so
8304        // each `instr.validate()` fires.
8305        //
8306        // (2) The within-entry state-change-ordering gate
8307        // ([`Self::validate_state_change_ordering`]): pass a
8308        // `((:state-change …))` singleton — `validate()` must return
8309        // [`UpgradeError::StateChangeWithoutPriorLoad`], which
8310        // requires the accessor to reach the state-change so the
8311        // no-prior-load probe fires.
8312        //
8313        // (3) The within-entry per-module cleanup-singularity gate
8314        // ([`Self::validate_cleanup_singularity`]): pass a
8315        // `((:load-module "x") (:soft-purge "x-old") (:soft-purge
8316        // "x-old"))` cohort — `validate()` must return
8317        // [`UpgradeError::DuplicateCleanup`], which requires the
8318        // accessor to iterate the whole list so the second `SoftPurge`
8319        // matches the first via the `seen` set.
8320        //
8321        // Peer of the sibling
8322        // `validate_reads_through_lifted_contratos_accessor` (0dcc926)
8323        // three-consumer coherence pin on the M3 per-`:contratos`
8324        // edge-list axis, extended onto the M2 per-`:upgrade-from
8325        // :instructions` migration-instruction-list axis.
8326
8327        // (1) accept the well-formed OTP two-phase code-load triad
8328        let well_formed = entry(
8329            "0.1.0",
8330            vec![
8331                UpgradeInstruction::LoadModule { module: "x".into() },
8332                UpgradeInstruction::StateChange {
8333                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
8334                },
8335                UpgradeInstruction::SoftPurge {
8336                    module: "x-old".into(),
8337                },
8338            ],
8339        );
8340        assert!(
8341            well_formed.validate().is_ok(),
8342            "well-formed `LoadModule → StateChange → SoftPurge` triad must accept — \
8343             the per-instruction shape-check fan-out requires the accessor to reach every entry"
8344        );
8345
8346        // (2) refuse a `((:state-change …))` singleton — the
8347        // state-change-without-prior-load gate must fire, which
8348        // requires the accessor to reach the single instruction.
8349        let no_prior_load = entry(
8350            "0.1.0",
8351            vec![UpgradeInstruction::StateChange {
8352                script: PathBuf::from("lib/m.lisp"),
8353            }],
8354        );
8355        match no_prior_load.validate() {
8356            Err(UpgradeError::StateChangeWithoutPriorLoad { .. }) => {}
8357            other => panic!(
8358                "expected StateChangeWithoutPriorLoad on a `((:state-change …))` singleton \
8359                 — the within-entry state-change-ordering gate must reach the single \
8360                 instruction through the lifted accessor; got: {other:?}"
8361            ),
8362        }
8363
8364        // (3) refuse a `((:load-module "x") (:soft-purge "x-old")
8365        // (:soft-purge "x-old"))` cohort — the per-module cleanup-
8366        // singularity gate must fire on the second `SoftPurge`, which
8367        // requires the accessor to iterate the whole list.
8368        let duplicate_cleanup = entry(
8369            "0.1.0",
8370            vec![
8371                UpgradeInstruction::LoadModule { module: "x".into() },
8372                UpgradeInstruction::SoftPurge {
8373                    module: "x-old".into(),
8374                },
8375                UpgradeInstruction::SoftPurge {
8376                    module: "x-old".into(),
8377                },
8378            ],
8379        );
8380        match duplicate_cleanup.validate() {
8381            Err(UpgradeError::DuplicateCleanup { module, .. }) => {
8382                assert_eq!(
8383                    module, "x-old",
8384                    "DuplicateCleanup must name the colliding module `x-old` — the per-module \
8385                     cleanup-singularity gate must iterate through the lifted accessor to \
8386                     match the second SoftPurge against the first via the `seen` set"
8387                );
8388            }
8389            other => panic!(
8390                "expected DuplicateCleanup on `((:load-module x) (:soft-purge x-old) \
8391                 (:soft-purge x-old))` — the within-entry cleanup-singularity gate must \
8392                 iterate the whole list through the lifted accessor; got: {other:?}"
8393            ),
8394        }
8395
8396        // Path::new suppresses the unused-import warning if the
8397        // outer module trims `use std::path::Path;` in a future edit.
8398        let _ = Path::new("lib/m.lisp");
8399    }
8400
8401    // Per-variant equivalence pins for the [`upgrade_from_script_ctors!`]
8402    // macro definition (see the paired doc-block above the macro
8403    // definition) — every generated `<ctor>(from: &str, script: &Path)
8404    // -> Self` constructor folds the uniform `Self::<Variant> { from:
8405    // from.to_string(), script: script.to_path_buf() }` two-field
8406    // struct-literal onto one substrate primitive. The three per-variant
8407    // equivalence pins below (fail-before-pass-after by construction — a
8408    // byte-mismatched macro arm would trip its equivalence pin first)
8409    // lock each generated constructor to its struct-literal peer under
8410    // `PartialEq`, so every wire-up in
8411    // [`UpgradeFromEntry::validate_state_change_ordering`],
8412    // [`UpgradeFromEntry::validate_state_change_uniqueness`], and
8413    // [`validate_state_change_on_state_change_callback`] on that
8414    // variant produces a byte-equal `UpgradeError` to the pre-lift
8415    // open-coded struct-literal. The cross-axis pin that follows
8416    // (non-default `(from, script)` pair) routes both constructor input
8417    // axes through `.to_string()` / `.to_path_buf()`, so the fold does
8418    // not silently collapse onto a fixed `from` / `script` value.
8419    //
8420    // Peer of the sibling `empty_child_version_ctor_matches_struct_
8421    // literal_wrap` / `duplicate_child_caixa_ctor_matches_struct_
8422    // literal_wrap` / `child_supervises_self_ctor_matches_struct_
8423    // literal_wrap` / `supervisor_caixa_only_ctors_route_caixa_through_
8424    // to_string` equivalence + cross-axis pins the sibling
8425    // [`crate::supervisor::supervisor_caixa_only_ctors!`] family (db09650)
8426    // established on the peer `SupervisorError` envelope; extended
8427    // here onto the `UpgradeError` `{ from: String, script: PathBuf }`
8428    // two-slot envelope so every substrate-primitive ctor family in
8429    // caixa-core guarantees the same-shape fold every wire-up on the
8430    // family reads through one dispatch.
8431
8432    #[test]
8433    fn state_change_without_prior_load_ctor_matches_struct_literal_wrap() {
8434        let from = "0.1.0";
8435        let script = Path::new("lib/migrations/v01-to-v02.lisp");
8436        assert_eq!(
8437            UpgradeError::state_change_without_prior_load(from, script),
8438            UpgradeError::StateChangeWithoutPriorLoad {
8439                from: from.to_string(),
8440                script: script.to_path_buf(),
8441            },
8442            "generated state_change_without_prior_load ctor must produce \
8443             byte-equal UpgradeError to the open-coded struct-literal \
8444             wrap on the same (&str, &Path) fixture",
8445        );
8446    }
8447
8448    #[test]
8449    fn duplicate_state_change_ctor_matches_struct_literal_wrap() {
8450        let from = "0.1.0";
8451        let script = Path::new("lib/migrations/v01-to-v02.lisp");
8452        assert_eq!(
8453            UpgradeError::duplicate_state_change(from, script),
8454            UpgradeError::DuplicateStateChange {
8455                from: from.to_string(),
8456                script: script.to_path_buf(),
8457            },
8458            "generated duplicate_state_change ctor must produce byte-equal \
8459             UpgradeError to the open-coded struct-literal wrap on the \
8460             same (&str, &Path) fixture",
8461        );
8462    }
8463
8464    #[test]
8465    fn state_change_without_on_state_change_callback_ctor_matches_struct_literal_wrap() {
8466        let from = "0.1.0";
8467        let script = Path::new("lib/migrations/v01-to-v02.lisp");
8468        assert_eq!(
8469            UpgradeError::state_change_without_on_state_change_callback(from, script),
8470            UpgradeError::StateChangeWithoutOnStateChangeCallback {
8471                from: from.to_string(),
8472                script: script.to_path_buf(),
8473            },
8474            "generated state_change_without_on_state_change_callback ctor \
8475             must produce byte-equal UpgradeError to the open-coded \
8476             struct-literal wrap on the same (&str, &Path) fixture",
8477        );
8478    }
8479
8480    #[test]
8481    fn upgrade_from_script_ctors_route_from_and_script_verbatim() {
8482        // Cross-axis pin: sweep both constructor input axes (`from:
8483        // &str`, `script: &Path`) through non-default fixtures against
8484        // every generated arm in the [`upgrade_from_script_ctors!`]
8485        // macro, so any wrapper-side lowercase / trim / truncate /
8486        // re-order / fixed-path substitution on the two-field
8487        // construction surfaces here rather than at a downstream
8488        // diagnostic-shape mismatch. Also exercises the `&Path`
8489        // parameter under both `&Path` (direct `Path::new`) and
8490        // `&PathBuf` (via Deref coercion), matching the two shapes the
8491        // three wire-up sites thread through — the ordering /
8492        // callback-declaration gates hand a `&PathBuf` from
8493        // `instr.declared_path()`; the uniqueness gate hands a `&Path`
8494        // from `script.as_path()`. Peer of the sibling
8495        // `supervisor_caixa_only_ctors_route_caixa_through_to_string`
8496        // cross-axis pin on the peer `SupervisorError` `{ caixa:
8497        // String }` envelope.
8498        let from = "1.2.3-rc.1";
8499        let script_owned = PathBuf::from("lib/migrations/v02-to-v03.lisp");
8500        let script_ref: &Path = script_owned.as_path();
8501        for script in [script_ref, &script_owned as &Path] {
8502            assert_eq!(
8503                UpgradeError::state_change_without_prior_load(from, script),
8504                UpgradeError::StateChangeWithoutPriorLoad {
8505                    from: from.to_string(),
8506                    script: script.to_path_buf(),
8507                },
8508            );
8509            assert_eq!(
8510                UpgradeError::duplicate_state_change(from, script),
8511                UpgradeError::DuplicateStateChange {
8512                    from: from.to_string(),
8513                    script: script.to_path_buf(),
8514                },
8515            );
8516            assert_eq!(
8517                UpgradeError::state_change_without_on_state_change_callback(from, script),
8518                UpgradeError::StateChangeWithoutOnStateChangeCallback {
8519                    from: from.to_string(),
8520                    script: script.to_path_buf(),
8521                },
8522            );
8523        }
8524    }
8525
8526    // Per-variant equivalence pins for the [`upgrade_script_only_ctors!`]
8527    // macro definition (see the paired doc-block above the macro
8528    // definition) — every generated `<ctor>(script: &Path) -> Self`
8529    // constructor folds the uniform `Self::<Variant> { script:
8530    // script.to_path_buf() }` one-field struct-literal onto one substrate
8531    // primitive. The three per-variant equivalence pins below
8532    // (fail-before-pass-after by construction — a byte-mismatched macro
8533    // arm would trip its equivalence pin first) lock each generated
8534    // constructor to its struct-literal peer under `PartialEq`, so every
8535    // closure passed to [`crate::render::require_sandboxed_lisp_path`]
8536    // at [`UpgradeInstruction::validate`] on that variant produces a
8537    // byte-equal `UpgradeError` to the pre-lift open-coded
8538    // struct-literal. The cross-axis pin that follows (non-default
8539    // `script` path, both `&Path` and `&PathBuf` shapes) routes the
8540    // constructor input axis through `.to_path_buf()`, so the fold does
8541    // not silently collapse onto a fixed `script` value or drop the
8542    // Deref-coercion arm the wire-up sites depend on.
8543    //
8544    // Peer of the sibling
8545    // `state_change_without_prior_load_ctor_matches_struct_literal_wrap`
8546    // / `duplicate_state_change_ctor_matches_struct_literal_wrap` /
8547    // `state_change_without_on_state_change_callback_ctor_matches_struct_literal_wrap`
8548    // / `upgrade_from_script_ctors_route_from_and_script_verbatim`
8549    // equivalence + cross-axis pins the sibling
8550    // [`upgrade_from_script_ctors!`] family (8e67041) established on the
8551    // peer `{ from: String, script: PathBuf }` two-slot envelope shape;
8552    // extended here onto the `{ script: PathBuf }` one-slot envelope
8553    // shape so every substrate-primitive ctor family on `UpgradeError`
8554    // guarantees the same-shape fold every wire-up on the family reads
8555    // through one dispatch.
8556
8557    #[test]
8558    fn absolute_script_ctor_matches_struct_literal_wrap() {
8559        let script = Path::new("/etc/nope.lisp");
8560        assert_eq!(
8561            UpgradeError::absolute_script(script),
8562            UpgradeError::AbsoluteScript {
8563                script: script.to_path_buf(),
8564            },
8565            "generated absolute_script ctor must produce byte-equal \
8566             UpgradeError to the open-coded struct-literal wrap on the \
8567             same &Path fixture",
8568        );
8569    }
8570
8571    #[test]
8572    fn parent_escape_script_ctor_matches_struct_literal_wrap() {
8573        let script = Path::new("../oops.lisp");
8574        assert_eq!(
8575            UpgradeError::parent_escape_script(script),
8576            UpgradeError::ParentEscapeScript {
8577                script: script.to_path_buf(),
8578            },
8579            "generated parent_escape_script ctor must produce byte-equal \
8580             UpgradeError to the open-coded struct-literal wrap on the \
8581             same &Path fixture",
8582        );
8583    }
8584
8585    #[test]
8586    fn non_lisp_extension_script_ctor_matches_struct_literal_wrap() {
8587        let script = Path::new("lib/migrations.rs");
8588        assert_eq!(
8589            UpgradeError::non_lisp_extension_script(script),
8590            UpgradeError::NonLispExtensionScript {
8591                script: script.to_path_buf(),
8592            },
8593            "generated non_lisp_extension_script ctor must produce \
8594             byte-equal UpgradeError to the open-coded struct-literal \
8595             wrap on the same &Path fixture",
8596        );
8597    }
8598
8599    #[test]
8600    fn upgrade_script_only_ctors_route_script_through_to_path_buf() {
8601        // Cross-axis pin: sweep the constructor input axis (`script:
8602        // &Path`) through a non-default fixture against every generated
8603        // arm in the [`upgrade_script_only_ctors!`] macro, so any
8604        // wrapper-side lowercase / trim / truncate / re-order /
8605        // fixed-path substitution on the one-field construction
8606        // surfaces here rather than at a downstream diagnostic-shape
8607        // mismatch. Also exercises the `&Path` parameter under both
8608        // `&Path` (direct `Path::new`) and `&PathBuf` (via Deref
8609        // coercion), matching the shape the three closures at
8610        // [`UpgradeInstruction::validate`] thread through — the
8611        // wire-ups hand a `&PathBuf` from `instr.declared_path()` into
8612        // each closure, so the Deref-coercion arm the ctor advertises
8613        // must actually route through `.to_path_buf()` and not
8614        // silently swap in a fixed path.
8615        //
8616        // Peer of the sibling
8617        // `upgrade_from_script_ctors_route_from_and_script_verbatim`
8618        // cross-axis pin on the sibling `{ from, script }` two-slot
8619        // envelope shape.
8620        let script_owned = PathBuf::from("lib/migrations/v02-to-v03.lisp");
8621        let script_ref: &Path = script_owned.as_path();
8622        for script in [script_ref, &script_owned as &Path] {
8623            assert_eq!(
8624                UpgradeError::absolute_script(script),
8625                UpgradeError::AbsoluteScript {
8626                    script: script.to_path_buf(),
8627                },
8628            );
8629            assert_eq!(
8630                UpgradeError::parent_escape_script(script),
8631                UpgradeError::ParentEscapeScript {
8632                    script: script.to_path_buf(),
8633                },
8634            );
8635            assert_eq!(
8636                UpgradeError::non_lisp_extension_script(script),
8637                UpgradeError::NonLispExtensionScript {
8638                    script: script.to_path_buf(),
8639                },
8640            );
8641        }
8642    }
8643
8644    // Per-variant equivalence pins for the [`upgrade_from_axis_ctors!`]
8645    // macro definition (see the paired doc-block above the macro
8646    // definition) — every generated `<ctor>(from: &str, <axis>: &str)
8647    // -> Self` constructor folds the uniform `Self::<Variant> { from:
8648    // from.to_string(), <axis>: <axis>.to_string() }` two-field
8649    // struct-literal onto one substrate primitive. The three per-variant
8650    // equivalence pins below (fail-before-pass-after by construction — a
8651    // byte-mismatched macro arm would trip its equivalence pin first)
8652    // lock each generated constructor to its struct-literal peer under
8653    // `PartialEq`, so every wire-up in
8654    // [`UpgradeFromEntry::validate`]'s `:from` SemVer-2 parse gate,
8655    // [`UpgradeFromEntry::validate_load_singularity`]'s per-module dedup
8656    // gate, and [`validate_upgrade_from_against_versao`]'s per-entry
8657    // `:from < :versao` gate on that variant produces a byte-equal
8658    // `UpgradeError` to the pre-lift open-coded struct-literal. The
8659    // cross-axis pin that follows (distinct-per-axis `from` / `<axis>`
8660    // pair) routes both constructor input axes through `.to_string()`
8661    // in declared field order, so the fold does not silently swap `from`
8662    // and the middle `<axis>` field, or silently collapse onto a fixed
8663    // `from` / `<axis>` value on any one variant.
8664    //
8665    // Peer of the sibling `state_change_without_prior_load_ctor_matches_
8666    // struct_literal_wrap` / `duplicate_state_change_ctor_matches_
8667    // struct_literal_wrap` / `state_change_without_on_state_change_
8668    // callback_ctor_matches_struct_literal_wrap` / `upgrade_from_script_
8669    // ctors_route_from_and_script_verbatim` equivalence + cross-axis
8670    // pins the sibling [`upgrade_from_script_ctors!`] family (8e67041)
8671    // established on the sibling `{ from: String, script: PathBuf }`
8672    // two-slot envelope shape; extended here onto the `{ from: String,
8673    // <axis>: String }` two-slot envelope shape so every substrate-
8674    // primitive ctor family on `UpgradeError` guarantees the same-shape
8675    // fold every wire-up on the family reads through one dispatch. Also
8676    // mirror-symmetric peer of the sibling
8677    // `dep_nome_axis_ctors_route_nome_and_axis_through_to_string_uniformly`
8678    // (7f7c950) cross-axis pin on the peer `DepError` `{ nome: String,
8679    // <axis>: String }` two-slot envelope shape.
8680
8681    #[test]
8682    fn from_invalid_ctor_matches_struct_literal_wrap() {
8683        let from = "not-a-semver";
8684        let reason = "unexpected character '-' at position 3";
8685        assert_eq!(
8686            UpgradeError::from_invalid(from, reason),
8687            UpgradeError::FromInvalid {
8688                from: from.to_string(),
8689                reason: reason.to_string(),
8690            },
8691            "generated from_invalid ctor must produce byte-equal \
8692             UpgradeError to the open-coded struct-literal wrap on the \
8693             same (&str, &str) fixture",
8694        );
8695    }
8696
8697    #[test]
8698    fn from_not_before_versao_ctor_matches_struct_literal_wrap() {
8699        let from = "0.2.0";
8700        let versao = "0.1.0";
8701        assert_eq!(
8702            UpgradeError::from_not_before_versao(from, versao),
8703            UpgradeError::FromNotBeforeVersao {
8704                from: from.to_string(),
8705                versao: versao.to_string(),
8706            },
8707            "generated from_not_before_versao ctor must produce byte-equal \
8708             UpgradeError to the open-coded struct-literal wrap on the \
8709             same (&str, &str) fixture",
8710        );
8711    }
8712
8713    #[test]
8714    fn duplicate_load_module_ctor_matches_struct_literal_wrap() {
8715        let from = "0.1.0";
8716        let module = "hello-rio";
8717        assert_eq!(
8718            UpgradeError::duplicate_load_module(from, module),
8719            UpgradeError::DuplicateLoadModule {
8720                from: from.to_string(),
8721                module: module.to_string(),
8722            },
8723            "generated duplicate_load_module ctor must produce byte-equal \
8724             UpgradeError to the open-coded struct-literal wrap on the \
8725             same (&str, &str) fixture",
8726        );
8727    }
8728
8729    #[test]
8730    fn upgrade_from_axis_ctors_route_from_and_axis_through_to_string_uniformly() {
8731        // Cross-axis routing pin: sweep the two constructor input axes
8732        // (`from: &str`, `<axis>: &str`) through distinct-per-axis
8733        // fixtures against every generated arm in the
8734        // [`upgrade_from_axis_ctors!`] macro, so any wrapper-side
8735        // lowercase / trim / truncate at codegen time — a silent field
8736        // swap between `from` and the middle `<axis>` field, or a
8737        // `<axis>` axis silently rerouted through the wrong field on any
8738        // one variant — surfaces here rather than at a downstream
8739        // diagnostic-shape mismatch. Peer of the sibling
8740        // `upgrade_from_script_ctors_route_from_and_script_verbatim`
8741        // (8e67041) cross-axis pin on the same envelope's sibling
8742        // `{ from: String, script: PathBuf }` two-slot family, and of the
8743        // sibling
8744        // `dep_nome_axis_ctors_route_nome_and_axis_through_to_string_uniformly`
8745        // (7f7c950) cross-axis pin on the peer `DepError` `{ nome:
8746        // String, <axis>: String }` two-slot envelope. Distinct-per-
8747        // axis fixtures rule out any two-axis swap (`from` ↔ `<axis>`)
8748        // that would still pass a same-fixture-per-axis pin. Both
8749        // `&str`-literal and `&String` (via Deref coercion) carriers
8750        // are exercised because the three wire-up sites hand a mix of
8751        // both (the `from_invalid` site hands `&e.to_string()` — an
8752        // owned `String` — for `reason`; the `duplicate_load_module`
8753        // site hands a `&str` slice for `module`; the
8754        // `from_not_before_versao` site hands the caller-supplied
8755        // `versao: &str` for `versao`).
8756        let from = "0.1.0";
8757        let axis = "distinct-axis-value";
8758        let from_owned: String = from.to_string();
8759        let axis_owned: String = axis.to_string();
8760        for (from_in, axis_in) in [(from, axis), (from_owned.as_str(), axis_owned.as_str())] {
8761            assert_eq!(
8762                UpgradeError::from_invalid(from_in, axis_in),
8763                UpgradeError::FromInvalid {
8764                    from: from.to_string(),
8765                    reason: axis.to_string(),
8766                },
8767                "from_invalid must route `from` → `from`, `axis` → `reason` \
8768                 in declared field order",
8769            );
8770            assert_eq!(
8771                UpgradeError::from_not_before_versao(from_in, axis_in),
8772                UpgradeError::FromNotBeforeVersao {
8773                    from: from.to_string(),
8774                    versao: axis.to_string(),
8775                },
8776                "from_not_before_versao must route `from` → `from`, \
8777                 `axis` → `versao` in declared field order",
8778            );
8779            assert_eq!(
8780                UpgradeError::duplicate_load_module(from_in, axis_in),
8781                UpgradeError::DuplicateLoadModule {
8782                    from: from.to_string(),
8783                    module: axis.to_string(),
8784                },
8785                "duplicate_load_module must route `from` → `from`, \
8786                 `axis` → `module` in declared field order",
8787            );
8788        }
8789    }
8790
8791    // Per-variant equivalence + accessor-fidelity + cross-axis pins for
8792    // the standalone [`UpgradeError::duplicate_from`] inherent ctor (see
8793    // the paired doc-block above the ctor definition) — the fold of the
8794    // last open-coded one-slot `{ from: entry.prior_versao().to_string() }`
8795    // struct-literal inside [`validate_upgrade_from`]'s cross-entry
8796    // duplicate gate onto one substrate primitive on the
8797    // [`UpgradeError`] envelope, projecting through the paired
8798    // [`UpgradeFromEntry::prior_versao`] scalar accessor on the substrate
8799    // primitive. A byte-mismatched ctor body would trip the equivalence
8800    // pin first, ahead of any downstream diagnostic-shape drift.
8801    //
8802    // Peer of the sibling standalone-ctor equivalence pins on the peer
8803    // one-off variants across caixa-core:
8804    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) on
8805    // the paired two-slot `{ caixa, wit }` [`AplicacaoError`] envelope,
8806    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
8807    // (cdf1a2c) on the paired three-slot `{ de, para, endpoint }`
8808    // envelope, the sibling
8809    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
8810    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` pins,
8811    // and the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
8812    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
8813
8814    #[test]
8815    fn duplicate_from_ctor_matches_struct_literal_wrap() {
8816        // Equivalence pin: the ctor produces byte-equal
8817        // `UpgradeError::DuplicateFrom` to the pre-lift open-coded
8818        // struct-literal that read the same `from` field through
8819        // [`UpgradeFromEntry::prior_versao`]. Guards any future field-
8820        // addition / reordering / string-conversion tweak on the
8821        // variant. Same equivalence-pin shape as the sibling
8822        // `contrato_self_loop_ctor_matches_struct_literal_wrap`
8823        // (b30edfe) on the paired two-slot `{ caixa, wit }`
8824        // envelope inside `impl AplicacaoSpec`.
8825        let entry = entry("0.1.0", vec![UpgradeInstruction::Restart]);
8826        let lifted = UpgradeError::duplicate_from(&entry);
8827        let struct_literal = UpgradeError::DuplicateFrom {
8828            from: entry.prior_versao().to_string(),
8829        };
8830        assert_eq!(lifted, struct_literal);
8831    }
8832
8833    #[test]
8834    fn duplicate_from_ctor_routes_prior_versao_through_verbatim() {
8835        // Routing pin sweeping a non-default `:from` value
8836        // (`"1.2.3-rc.4+build.5"` — a full SemVer-2 identity with pre-
8837        // release and build metadata) through the paired
8838        // [`UpgradeFromEntry::prior_versao`] scalar accessor axis so any
8839        // wrapper-side lowercase / trim / truncate on the one-field
8840        // construction surfaces here rather than at a downstream
8841        // diagnostic-shape drift. Peer of the sibling
8842        // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
8843        // (b30edfe) routing pin on the sibling two-slot envelope.
8844        //
8845        // The pre-release + build-metadata carrier value is deliberately
8846        // chosen to exercise the `.to_string()` path against a `:from`
8847        // shape [`semver::Version::PartialEq`] treats as distinct from
8848        // its release-only sibling (per the
8849        // `validate_upgrade_from_treats_pre_release_as_distinct` and
8850        // build-metadata-tightening-note doc-block on
8851        // [`validate_upgrade_from`]) — so any silent normalization at
8852        // the ctor body (a `.trim_matches('+')` / `.split_once('+')` /
8853        // `.split_once('-')` collapse) would drop bytes from the
8854        // rendered diagnostic and surface here.
8855        let entry = entry("1.2.3-rc.4+build.5", vec![UpgradeInstruction::Restart]);
8856        let built = UpgradeError::duplicate_from(&entry);
8857        match built {
8858            UpgradeError::DuplicateFrom { from } => {
8859                assert_eq!(
8860                    from, "1.2.3-rc.4+build.5",
8861                    "from slot must thread UpgradeFromEntry::prior_versao() verbatim, \
8862                     preserving pre-release + build-metadata bytes"
8863                );
8864            }
8865            other => panic!("expected DuplicateFrom, got {other:?}"),
8866        }
8867    }
8868
8869    #[test]
8870    fn duplicate_from_ctor_projects_prior_versao_scalar_accessor() {
8871        // Accessor-fidelity pin: the ctor's `from` slot keys off the
8872        // [`UpgradeFromEntry::prior_versao`] scalar accessor (matching
8873        // the pre-lift open-coded body's field selection), not any
8874        // stringified rendering of the full entry (e.g. the
8875        // `impl Display for UpgradeFromEntry` output, if one were later
8876        // added, or a `format!("{:?}", entry)` debug dump). Pins the
8877        // projection axis so a silent swap at the ctor body — say, a
8878        // future refactor that projects through `entry.instructions()`
8879        // in shape (dropping the `:from` axis entirely) or through a
8880        // whole-entry `format!` — surfaces here rather than at a
8881        // downstream diagnostic mis-attribution far from the duplicate
8882        // gate's owner.
8883        //
8884        // A future consumer that constructs the ctor against a not-yet-
8885        // gated candidate entry (an M4 `mesh.pleme.io/v1alpha1/Caixa`
8886        // CR admission webhook re-checking a per-`:upgrade-from`-patched
8887        // candidate before the cross-entry duplicate gate re-fires, a
8888        // per-tenant per-`Caixa` overlay resolver rejecting a duplicate
8889        // `(:from …)` introduced by a cluster-local `:upgrade-from`
8890        // override) needs the pre-lift projection axis pinned.
8891        //
8892        // The fixture threads a distinctive `:from` (`"0.2.0-alpha.7"`)
8893        // paired with a distinctive multi-instruction sequence so a
8894        // silent swap that projects through the whole-entry rendering
8895        // instead of the paired scalar accessor would land debug bytes
8896        // from the `:instructions` list into the `from` slot and trip
8897        // the assertion here.
8898        let entry = entry(
8899            "0.2.0-alpha.7",
8900            vec![
8901                UpgradeInstruction::LoadModule {
8902                    module: "distinctive-load-target".into(),
8903                },
8904                UpgradeInstruction::StateChange {
8905                    script: PathBuf::from("lib/distinctive-migrate.lisp"),
8906                },
8907                UpgradeInstruction::Restart,
8908            ],
8909        );
8910        let built = UpgradeError::duplicate_from(&entry);
8911        match built {
8912            UpgradeError::DuplicateFrom { from } => {
8913                assert_eq!(
8914                    from, "0.2.0-alpha.7",
8915                    "from slot must project UpgradeFromEntry::prior_versao() \
8916                     (not any whole-entry rendering)"
8917                );
8918            }
8919            other => panic!("expected DuplicateFrom, got {other:?}"),
8920        }
8921    }
8922
8923    // Per-variant equivalence + cross-axis + end-to-end wire-up pins for
8924    // the standalone [`UpgradeError::purge_without_prior_load`] inherent
8925    // ctor (see the paired doc-block above the ctor definition) — the
8926    // fold of the last open-coded three-slot `{ from: String, kind:
8927    // &'static str, module: String }` struct-literal wire-up on
8928    // [`UpgradeError`] closes the sole in-crate wire-up site inside
8929    // [`UpgradeFromEntry::validate_purge_ordering`]'s per-instruction
8930    // load-family sticky-latch dispatch onto one substrate primitive.
8931    // A byte-mismatched ctor body would trip the equivalence pin first,
8932    // ahead of any downstream diagnostic-shape drift.
8933    //
8934    // Peer of the sibling standalone-ctor equivalence + routing pins on
8935    // the sibling one-off variants across `UpgradeError`
8936    // (`duplicate_from_ctor_matches_struct_literal_wrap` /
8937    // `duplicate_from_ctor_routes_prior_versao_through_verbatim` /
8938    // `duplicate_from_ctor_projects_prior_versao_scalar_accessor` on
8939    // the paired one-slot `{ from: String }` envelope) and across
8940    // caixa-core (`contrato_endpoint_not_absolute_ctor_matches_struct_
8941    // literal_wrap` on the paired three-slot `{ de, para, endpoint:
8942    // String }` `AplicacaoError` envelope).
8943
8944    #[test]
8945    fn purge_without_prior_load_ctor_matches_struct_literal_wrap() {
8946        // Equivalence pin: the ctor produces byte-equal
8947        // `UpgradeError::PurgeWithoutPriorLoad` to the pre-lift
8948        // open-coded three-field struct-literal on the same `(&str,
8949        // &'static str, &str)` fixture. Guards any future field-
8950        // addition / reordering / string-conversion tweak on the
8951        // variant. Same equivalence-pin shape as the sibling
8952        // `duplicate_from_ctor_matches_struct_literal_wrap` (7e52aec)
8953        // on the peer one-slot `{ from: String }` envelope.
8954        let from = "0.1.0";
8955        let kind = crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE;
8956        let module = "hello-rio-old";
8957        assert_eq!(
8958            UpgradeError::purge_without_prior_load(from, kind, module),
8959            UpgradeError::PurgeWithoutPriorLoad {
8960                from: from.to_string(),
8961                kind,
8962                module: module.to_string(),
8963            },
8964            "generated purge_without_prior_load ctor must produce \
8965             byte-equal UpgradeError to the open-coded struct-literal \
8966             wrap on the same (&str, &'static str, &str) fixture",
8967        );
8968    }
8969
8970    #[test]
8971    fn purge_without_prior_load_ctor_routes_from_kind_and_module_through_verbatim() {
8972        // Cross-axis routing pin: sweep the three constructor input
8973        // axes (`from: &str`, `kind: &'static str`, `module: &str`)
8974        // through distinct-per-axis fixtures across every cleanup-family
8975        // [`UpgradeInstruction::lisp_form`] variant + a boundary mix of
8976        // SemVer-2 `from` shapes (pre-release, build-metadata) + DNS-1123
8977        // module shapes (leaf, hyphenated, deeply-hyphenated) so any
8978        // wrapper-side lowercase / trim / truncate / silent axis-swap
8979        // (`from` ↔ `module`, `kind` misrouted onto `from`) on the
8980        // three-field construction surfaces at assert time rather than
8981        // at a downstream diagnostic consumer that reads the fields
8982        // back and gets a different value than the one it stored. Both
8983        // `&str`-literal and `&String` (via Deref coercion) carriers
8984        // are exercised for `from` / `module` because the sole wire-up
8985        // hands `self.prior_versao()` (a `&str` accessor) and
8986        // `instr.declared_module().expect(…)` (also a `&str`) — the
8987        // ctor must accept both shapes without a pre-conversion.
8988        let kinds: [&'static str; 2] = [
8989            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
8990            crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
8991        ];
8992        let froms: [&str; 4] = ["0.1.0", "1.2.3-rc.1", "0.2.0-alpha.7+build.5", "0.0.0"];
8993        let modules: [&str; 4] = ["x", "hello-rio-old", "cache-v2-ancient", "a-b-c-d-e-f"];
8994        for kind in kinds {
8995            for from in froms {
8996                for module in modules {
8997                    let from_owned: String = from.to_string();
8998                    let module_owned: String = module.to_string();
8999                    for (from_in, module_in) in
9000                        [(from, module), (from_owned.as_str(), module_owned.as_str())]
9001                    {
9002                        assert_eq!(
9003                            UpgradeError::purge_without_prior_load(from_in, kind, module_in),
9004                            UpgradeError::PurgeWithoutPriorLoad {
9005                                from: from.to_string(),
9006                                kind,
9007                                module: module.to_string(),
9008                            },
9009                            "purge_without_prior_load must route from → from, \
9010                             kind → kind, module → module in declared field \
9011                             order verbatim on ({from:?}, {kind:?}, {module:?})",
9012                        );
9013                    }
9014                }
9015            }
9016        }
9017    }
9018
9019    #[test]
9020    fn validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor() {
9021        // End-to-end wire-up pin: build an entry whose declared
9022        // `:instructions` list places a `:soft-purge` (and separately a
9023        // `:purge`) before any `:load-module` so
9024        // [`UpgradeFromEntry::validate_purge_ordering`]'s load-family
9025        // sticky-latch dispatch surfaces
9026        // `UpgradeError::PurgeWithoutPriorLoad`, then pin that the
9027        // observed `Err` byte-equals the substrate-primitive
9028        // [`UpgradeError::purge_without_prior_load`] ctor's output on
9029        // the same fixture. A future silent de-lift of the wire-up back
9030        // to the open-coded struct-literal (or a silent axis-swap on
9031        // the three-field construction at the wire-up site) trips at
9032        // caixa-core test time rather than at a downstream diagnostic
9033        // consumer far from the wire-up commit. Same end-to-end-wire-up
9034        // discipline as the sibling
9035        // `validate_upgrade_from_duplicate_diagnostic_arm_routes_through_duplicate_from_ctor`
9036        // on the peer cross-entry duplicate-`:from` gate; both key off
9037        // exactly one typed dispatch on the substrate primitive.
9038        let cases: [(&str, UpgradeInstruction, &'static str, &str); 2] = [
9039            (
9040                "0.1.0",
9041                UpgradeInstruction::SoftPurge {
9042                    module: "hello-rio-old".into(),
9043                },
9044                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9045                "hello-rio-old",
9046            ),
9047            (
9048                "1.2.3-rc.1",
9049                UpgradeInstruction::Purge {
9050                    module: "cache-v2-ancient".into(),
9051                },
9052                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9053                "cache-v2-ancient",
9054            ),
9055        ];
9056        for (from, instr, kind, module) in cases {
9057            let e = entry(from, vec![instr]);
9058            let observed = e.validate().unwrap_err();
9059            assert_eq!(
9060                observed,
9061                UpgradeError::purge_without_prior_load(from, kind, module),
9062                "validate_purge_ordering must route its refusal through \
9063                 UpgradeError::purge_without_prior_load(from, kind, \
9064                 module) on a bare-cleanup {kind:?} entry, byte-equal \
9065                 to the pre-lift open-coded struct-literal wrap on the \
9066                 same fixture",
9067            );
9068        }
9069    }
9070
9071    // Per-variant equivalence + cross-axis + end-to-end wire-up pins for
9072    // the standalone [`UpgradeError::state_change_after_cleanup`]
9073    // inherent ctor (see the paired doc-block above the ctor
9074    // definition) — the fold of the last open-coded four-slot `{ from:
9075    // String, script: PathBuf, prior_cleanup_kind: &'static str,
9076    // prior_cleanup_module: String }` struct-literal wire-up on
9077    // [`UpgradeError`] closes the sole in-crate wire-up site inside
9078    // [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
9079    // migrate-family sticky-latch dispatch onto one substrate primitive.
9080    // A byte-mismatched ctor body would trip the equivalence pin first,
9081    // ahead of any downstream diagnostic-shape drift. Peer of the
9082    // sibling standalone-ctor equivalence + routing pins on the sibling
9083    // one-off variants across `UpgradeError`
9084    // (`purge_without_prior_load_ctor_matches_struct_literal_wrap` /
9085    // `purge_without_prior_load_ctor_routes_from_kind_and_module_through_verbatim`
9086    // / `validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor`
9087    // on the paired three-slot `{ from, kind, module }` envelope;
9088    // `duplicate_from_ctor_matches_struct_literal_wrap` on the paired
9089    // one-slot `{ from }` envelope).
9090
9091    #[test]
9092    fn state_change_after_cleanup_ctor_matches_struct_literal_wrap() {
9093        // Equivalence pin: the ctor produces byte-equal
9094        // `UpgradeError::StateChangeAfterCleanup` to the pre-lift
9095        // open-coded four-field struct-literal on the same `(&str,
9096        // &Path, &'static str, &str)` fixture. Guards any future
9097        // field-addition / reordering / string-conversion tweak on the
9098        // variant. Same equivalence-pin shape as the sibling
9099        // `purge_without_prior_load_ctor_matches_struct_literal_wrap`
9100        // (9752da1) on the peer three-slot envelope.
9101        let from = "0.1.0";
9102        let script = Path::new("lib/m.lisp");
9103        let prior_cleanup_kind = crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE;
9104        let prior_cleanup_module = "x-old";
9105        assert_eq!(
9106            UpgradeError::state_change_after_cleanup(
9107                from,
9108                script,
9109                prior_cleanup_kind,
9110                prior_cleanup_module,
9111            ),
9112            UpgradeError::StateChangeAfterCleanup {
9113                from: from.to_string(),
9114                script: script.to_path_buf(),
9115                prior_cleanup_kind,
9116                prior_cleanup_module: prior_cleanup_module.to_string(),
9117            },
9118            "generated state_change_after_cleanup ctor must produce \
9119             byte-equal UpgradeError to the open-coded struct-literal \
9120             wrap on the same (&str, &Path, &'static str, &str) fixture",
9121        );
9122    }
9123
9124    #[test]
9125    fn state_change_after_cleanup_ctor_routes_from_script_kind_and_module_through_verbatim() {
9126        // Cross-axis routing pin: sweep the four constructor input
9127        // axes (`from: &str`, `script: &Path`, `prior_cleanup_kind:
9128        // &'static str`, `prior_cleanup_module: &str`) through
9129        // distinct-per-axis fixtures across every cleanup-family
9130        // [`UpgradeInstruction::lisp_form`] variant + a boundary mix of
9131        // SemVer-2 `from` shapes (release, pre-release, pre-release +
9132        // build-metadata, zero), sibling-`.lisp` script-path shapes
9133        // (leaf, nested, deeply-nested), and DNS-1123 module shapes
9134        // (leaf, hyphenated, deeply-hyphenated) so any wrapper-side
9135        // lowercase / trim / truncate / silent axis-swap
9136        // (`from` ↔ `prior_cleanup_module`, `script` misrouted onto
9137        // `from`, `prior_cleanup_kind` misrouted onto
9138        // `prior_cleanup_module`) on the four-field construction
9139        // surfaces at assert time rather than at a downstream diagnostic
9140        // consumer that reads the fields back and gets a different value
9141        // than the one it stored. Both `&str`-literal and `&String` (via
9142        // Deref coercion) carriers are exercised for `from` /
9143        // `prior_cleanup_module` because the sole wire-up hands
9144        // `self.prior_versao()` (a `&str` accessor) and `prior_module`
9145        // (also `&str`, from `declared_module().expect(…)`) — the ctor
9146        // must accept both shapes without a pre-conversion. Both
9147        // `&Path`-direct and `&PathBuf` (via Deref coercion) carriers
9148        // are exercised for `script` because the sole wire-up hands a
9149        // `&PathBuf` sticky-latch projection from `declared_path()`'s
9150        // `Option<&PathBuf>` return — the ctor must accept both shapes
9151        // without a pre-conversion.
9152        let kinds: [&'static str; 2] = [
9153            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9154            crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9155        ];
9156        let froms: [&str; 4] = ["0.1.0", "1.2.3-rc.1", "0.2.0-alpha.7+build.5", "0.0.0"];
9157        let scripts: [&str; 3] = [
9158            "m.lisp",
9159            "lib/migrations.lisp",
9160            "lib/migrations/v01/step-1.lisp",
9161        ];
9162        let modules: [&str; 3] = ["x", "hello-rio-old", "cache-v2-ancient"];
9163        for kind in kinds {
9164            for from in froms {
9165                for script_str in scripts {
9166                    for module in modules {
9167                        let from_owned: String = from.to_string();
9168                        let module_owned: String = module.to_string();
9169                        let script_path = Path::new(script_str);
9170                        let script_pathbuf = PathBuf::from(script_str);
9171                        for (from_in, module_in, script_in) in [
9172                            (from, module, script_path),
9173                            (
9174                                from_owned.as_str(),
9175                                module_owned.as_str(),
9176                                script_pathbuf.as_path(),
9177                            ),
9178                        ] {
9179                            assert_eq!(
9180                                UpgradeError::state_change_after_cleanup(
9181                                    from_in, script_in, kind, module_in,
9182                                ),
9183                                UpgradeError::StateChangeAfterCleanup {
9184                                    from: from.to_string(),
9185                                    script: PathBuf::from(script_str),
9186                                    prior_cleanup_kind: kind,
9187                                    prior_cleanup_module: module.to_string(),
9188                                },
9189                                "state_change_after_cleanup must route from → from, \
9190                                 script → script, prior_cleanup_kind → prior_cleanup_kind, \
9191                                 prior_cleanup_module → prior_cleanup_module in declared \
9192                                 field order verbatim on ({from:?}, {script_str:?}, \
9193                                 {kind:?}, {module:?})",
9194                            );
9195                        }
9196                    }
9197                }
9198            }
9199        }
9200    }
9201
9202    #[test]
9203    fn validate_state_change_before_cleanup_arm_routes_through_state_change_after_cleanup_ctor() {
9204        // End-to-end wire-up pin: build an entry whose declared
9205        // `:instructions` list places a `:soft-purge` (and separately a
9206        // `:purge`) before a `:state-change` so
9207        // [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
9208        // migrate-family sticky-latch dispatch surfaces
9209        // `UpgradeError::StateChangeAfterCleanup`, then pin that the
9210        // observed `Err` byte-equals the substrate-primitive
9211        // [`UpgradeError::state_change_after_cleanup`] ctor's output on
9212        // the same fixture. A future silent de-lift of the wire-up back
9213        // to the open-coded struct-literal (or a silent axis-swap on
9214        // the four-field construction at the wire-up site) trips at
9215        // caixa-core test time rather than at a downstream diagnostic
9216        // consumer far from the wire-up commit. Same end-to-end-wire-up
9217        // discipline as the sibling
9218        // `validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor`
9219        // on the peer load → cleanup ordering gate; both key off
9220        // exactly one typed dispatch on the substrate primitive. Every
9221        // entry here front-loads a `:load-module` so the sole surviving
9222        // ordering refusal is the migrate → cleanup one this gate
9223        // owns — the peer `validate_purge_ordering` load → cleanup gate
9224        // returns `Ok(())` on these fixtures, so the migrate-after-
9225        // cleanup arm is the only path to an `Err`.
9226        let cases: [(&str, UpgradeInstruction, &'static str, &str, &str); 2] = [
9227            (
9228                "0.1.0",
9229                UpgradeInstruction::SoftPurge {
9230                    module: "hello-rio-old".into(),
9231                },
9232                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9233                "hello-rio-old",
9234                "lib/migrations/v01.lisp",
9235            ),
9236            (
9237                "1.2.3-rc.1",
9238                UpgradeInstruction::Purge {
9239                    module: "cache-v2-ancient".into(),
9240                },
9241                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9242                "cache-v2-ancient",
9243                "lib/migrations/v02.lisp",
9244            ),
9245        ];
9246        for (from, cleanup, kind, module, script_str) in cases {
9247            let script = PathBuf::from(script_str);
9248            let e = entry(
9249                from,
9250                vec![
9251                    UpgradeInstruction::LoadModule {
9252                        module: "hello-rio".into(),
9253                    },
9254                    cleanup,
9255                    UpgradeInstruction::StateChange {
9256                        script: script.clone(),
9257                    },
9258                ],
9259            );
9260            let observed = e.validate().unwrap_err();
9261            assert_eq!(
9262                observed,
9263                UpgradeError::state_change_after_cleanup(from, &script, kind, module),
9264                "validate_state_change_before_cleanup must route its \
9265                 refusal through \
9266                 UpgradeError::state_change_after_cleanup(from, script, \
9267                 prior_cleanup_kind, prior_cleanup_module) on a \
9268                 `:state-change` after a bare-cleanup {kind:?} entry, \
9269                 byte-equal to the pre-lift open-coded struct-literal \
9270                 wrap on the same fixture",
9271            );
9272        }
9273    }
9274
9275    // Per-variant equivalence + cross-axis + end-to-end wire-up pins for
9276    // the standalone [`UpgradeError::duplicate_cleanup`] inherent ctor
9277    // (see the paired doc-block above the ctor definition) — the fold of
9278    // the last open-coded three-slot `{ from: String, module: String,
9279    // kinds: Vec<&'static str> }` struct-literal wire-up on
9280    // [`UpgradeError`] closes the sole in-crate wire-up site inside
9281    // [`UpgradeFromEntry::validate_cleanup_singularity`]'s per-module
9282    // cleanup-family dedup arm onto one substrate primitive. A byte-
9283    // mismatched ctor body would trip the equivalence pin first, ahead of
9284    // any downstream diagnostic-shape drift. Peer of the sibling
9285    // standalone-ctor equivalence + routing pins on the sibling one-off
9286    // variants across `UpgradeError`
9287    // (`purge_without_prior_load_ctor_matches_struct_literal_wrap` on the
9288    // paired three-slot `{ from, kind, module }` envelope for the sibling
9289    // load → cleanup ordering axis;
9290    // `state_change_after_cleanup_ctor_matches_struct_literal_wrap` on
9291    // the paired four-slot `{ from, script, prior_cleanup_kind,
9292    // prior_cleanup_module }` envelope for the migrate → cleanup
9293    // boundary; `duplicate_from_ctor_matches_struct_literal_wrap` on the
9294    // paired one-slot `{ from }` envelope for the cross-entry duplicate-
9295    // `:from` gate).
9296
9297    #[test]
9298    fn duplicate_cleanup_ctor_matches_struct_literal_wrap() {
9299        // Equivalence pin: the ctor produces byte-equal
9300        // `UpgradeError::DuplicateCleanup` to the pre-lift open-coded
9301        // three-field struct-literal on the same `(&str, &str,
9302        // Vec<&'static str>)` fixture. Guards any future field-addition /
9303        // reordering / string-conversion tweak on the variant. Same
9304        // equivalence-pin shape as the sibling
9305        // `purge_without_prior_load_ctor_matches_struct_literal_wrap`
9306        // (9752da1) on the peer three-slot envelope.
9307        let from = "0.1.0";
9308        let module = "x-old";
9309        let kinds: Vec<&'static str> = vec![
9310            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9311            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9312        ];
9313        assert_eq!(
9314            UpgradeError::duplicate_cleanup(from, module, kinds.clone()),
9315            UpgradeError::DuplicateCleanup {
9316                from: from.to_string(),
9317                module: module.to_string(),
9318                kinds,
9319            },
9320            "generated duplicate_cleanup ctor must produce byte-equal \
9321             UpgradeError to the open-coded struct-literal wrap on the \
9322             same (&str, &str, Vec<&'static str>) fixture",
9323        );
9324    }
9325
9326    #[test]
9327    fn duplicate_cleanup_ctor_routes_from_module_and_kinds_through_verbatim() {
9328        // Cross-axis routing pin: sweep the three constructor input axes
9329        // (`from: &str`, `module: &str`, `kinds: Vec<&'static str>`)
9330        // through distinct-per-axis fixtures across every ordered pair of
9331        // cleanup-family [`UpgradeInstruction::lisp_form`] variants (the
9332        // four `(prior_kind, kind)` combinations `validate_cleanup_
9333        // singularity` can emit: SS, PP, SP, PS) + a boundary mix of
9334        // SemVer-2 `from` shapes (release, pre-release, pre-release +
9335        // build-metadata, zero) + DNS-1123 module shapes (leaf,
9336        // hyphenated, deeply-hyphenated) so any wrapper-side lowercase /
9337        // trim / truncate / silent axis-swap (`from` ↔ `module`, kinds
9338        // pair-reorder, kinds-vec drop-or-duplicate on the two-element
9339        // owned `Vec<&'static str>`) on the three-field construction
9340        // surfaces at assert time rather than at a downstream diagnostic
9341        // consumer that reads the fields back and gets a different value
9342        // than the one it stored. Both `&str`-literal and `&String` (via
9343        // Deref coercion) carriers are exercised for `from` / `module`
9344        // because the sole wire-up hands `self.prior_versao()` (a `&str`
9345        // accessor) and `module` (also `&str`, from `declared_module().
9346        // expect(…)`) — the ctor must accept both shapes without a
9347        // pre-conversion.
9348        let all_kinds: [&'static str; 2] = [
9349            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9350            crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9351        ];
9352        let froms: [&str; 4] = ["0.1.0", "1.2.3-rc.1", "0.2.0-alpha.7+build.5", "0.0.0"];
9353        let modules: [&str; 3] = ["x", "hello-rio-old", "cache-v2-ancient"];
9354        for prior_kind in all_kinds {
9355            for kind in all_kinds {
9356                for from in froms {
9357                    for module in modules {
9358                        let from_owned: String = from.to_string();
9359                        let module_owned: String = module.to_string();
9360                        for (from_in, module_in) in
9361                            [(from, module), (from_owned.as_str(), module_owned.as_str())]
9362                        {
9363                            let kinds: Vec<&'static str> = vec![prior_kind, kind];
9364                            assert_eq!(
9365                                UpgradeError::duplicate_cleanup(from_in, module_in, kinds.clone(),),
9366                                UpgradeError::DuplicateCleanup {
9367                                    from: from.to_string(),
9368                                    module: module.to_string(),
9369                                    kinds,
9370                                },
9371                                "duplicate_cleanup must route from → from, \
9372                                 module → module, kinds → kinds in declared \
9373                                 field order verbatim on ({from:?}, \
9374                                 {module:?}, [{prior_kind:?}, {kind:?}])",
9375                            );
9376                        }
9377                    }
9378                }
9379            }
9380        }
9381    }
9382
9383    #[test]
9384    fn validate_cleanup_singularity_arm_routes_through_duplicate_cleanup_ctor() {
9385        // End-to-end wire-up pin: build an entry whose declared
9386        // `:instructions` list front-loads a `:load-module` (so the
9387        // sibling `validate_purge_ordering` load → cleanup gate returns
9388        // `Ok(())` on the fixture) and then places two cleanup
9389        // instructions targeting the same module so
9390        // [`UpgradeFromEntry::validate_cleanup_singularity`]'s per-module
9391        // cleanup-family dedup arm surfaces
9392        // `UpgradeError::DuplicateCleanup`, then pin that the observed
9393        // `Err` byte-equals the substrate-primitive
9394        // [`UpgradeError::duplicate_cleanup`] ctor's output on the same
9395        // fixture. A future silent de-lift of the wire-up back to the
9396        // open-coded struct-literal (or a silent axis-swap on the three-
9397        // field construction at the wire-up site, or a kinds-pair
9398        // reorder) trips at caixa-core test time rather than at a
9399        // downstream diagnostic consumer far from the wire-up commit.
9400        // Same end-to-end-wire-up discipline as the sibling
9401        // `validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor`
9402        // on the peer load → cleanup ordering gate and
9403        // `validate_state_change_before_cleanup_arm_routes_through_state_change_after_cleanup_ctor`
9404        // on the peer migrate → cleanup boundary; all three key off
9405        // exactly one typed dispatch on the substrate primitive.
9406        let cases: [(
9407            &str,
9408            UpgradeInstruction,
9409            UpgradeInstruction,
9410            &str,
9411            [&'static str; 2],
9412        ); 4] = [
9413            (
9414                "0.1.0",
9415                UpgradeInstruction::SoftPurge {
9416                    module: "hello-rio-old".into(),
9417                },
9418                UpgradeInstruction::SoftPurge {
9419                    module: "hello-rio-old".into(),
9420                },
9421                "hello-rio-old",
9422                [
9423                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9424                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9425                ],
9426            ),
9427            (
9428                "1.2.3-rc.1",
9429                UpgradeInstruction::Purge {
9430                    module: "cache-v2-ancient".into(),
9431                },
9432                UpgradeInstruction::Purge {
9433                    module: "cache-v2-ancient".into(),
9434                },
9435                "cache-v2-ancient",
9436                [
9437                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9438                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9439                ],
9440            ),
9441            (
9442                "0.2.0-alpha.7+build.5",
9443                UpgradeInstruction::SoftPurge {
9444                    module: "x-old".into(),
9445                },
9446                UpgradeInstruction::Purge {
9447                    module: "x-old".into(),
9448                },
9449                "x-old",
9450                [
9451                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9452                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9453                ],
9454            ),
9455            (
9456                "0.0.0",
9457                UpgradeInstruction::Purge {
9458                    module: "x-old".into(),
9459                },
9460                UpgradeInstruction::SoftPurge {
9461                    module: "x-old".into(),
9462                },
9463                "x-old",
9464                [
9465                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9466                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9467                ],
9468            ),
9469        ];
9470        for (from, first, second, module, kinds) in cases {
9471            let e = entry(
9472                from,
9473                vec![
9474                    UpgradeInstruction::LoadModule {
9475                        module: "hello-rio".into(),
9476                    },
9477                    first,
9478                    second,
9479                ],
9480            );
9481            let observed = e.validate().unwrap_err();
9482            assert_eq!(
9483                observed,
9484                UpgradeError::duplicate_cleanup(from, module, kinds.to_vec()),
9485                "validate_cleanup_singularity must route its refusal \
9486                 through UpgradeError::duplicate_cleanup(from, module, \
9487                 kinds) on a two-cleanup {kinds:?} entry targeting the \
9488                 same module, byte-equal to the pre-lift open-coded \
9489                 struct-literal wrap on the same fixture",
9490            );
9491        }
9492    }
9493
9494    #[test]
9495    fn restart_not_exclusive_ctor_matches_struct_literal_wrap() {
9496        // Equivalence pin: the ctor produces byte-equal
9497        // `UpgradeError::RestartNotExclusive` to the pre-lift open-coded
9498        // three-field struct-literal on the same `(&str, usize,
9499        // Vec<&'static str>)` fixture. Guards any future field-addition /
9500        // reordering / string-conversion tweak on the variant. Same
9501        // equivalence-pin shape as the sibling
9502        // `duplicate_cleanup_ctor_matches_struct_literal_wrap` (10a5b48)
9503        // on the peer three-slot envelope.
9504        let from = "0.1.0";
9505        let restart_count: usize = 1;
9506        let other_kinds: Vec<&'static str> =
9507            vec![crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE];
9508        assert_eq!(
9509            UpgradeError::restart_not_exclusive(from, restart_count, other_kinds.clone()),
9510            UpgradeError::RestartNotExclusive {
9511                from: from.to_string(),
9512                restart_count,
9513                other_kinds,
9514            },
9515            "generated restart_not_exclusive ctor must produce byte-equal \
9516             UpgradeError to the open-coded struct-literal wrap on the \
9517             same (&str, usize, Vec<&'static str>) fixture",
9518        );
9519    }
9520
9521    #[test]
9522    fn restart_not_exclusive_ctor_routes_from_restart_count_and_other_kinds_through_verbatim() {
9523        // Cross-axis routing pin: sweep the three constructor input axes
9524        // (`from: &str`, `restart_count: usize`, `other_kinds:
9525        // Vec<&'static str>`) through distinct-per-axis fixtures across a
9526        // boundary matrix of SemVer-2 `from` shapes (release, pre-release,
9527        // pre-release + build-metadata, zero) × non-degenerate
9528        // `restart_count` values (1 — the mixed-with-typed shape, 2 — the
9529        // pure-duplication shape, 3 — the deeply-duplicated shape) ×
9530        // ordered `other_kinds` lisp-form lists spanning the four
9531        // non-`:restart` [`UpgradeInstruction::lisp_form`] arms
9532        // (`:load-module`, `:state-change`, `:soft-purge`, `:purge`) —
9533        // empty (the `((:restart) (:restart))` shape), singleton
9534        // (`((:load-module …) (:restart))`), and the full typed sequence
9535        // (`((:load-module …) (:state-change …) (:soft-purge …) (:purge
9536        // …) (:restart))`) — so any wrapper-side silent lowercase / trim
9537        // / truncate / silent axis-swap (`from` ↔ swap onto
9538        // `restart_count`'s numeric axis, `other_kinds`-vec drop-or-
9539        // duplicate on the four-element owned `Vec<&'static str>`,
9540        // `other_kinds` reorder against declared instruction order) on
9541        // the three-field construction surfaces at assert time rather
9542        // than at a downstream diagnostic consumer that reads the fields
9543        // back and gets a different value than the one it stored. Both
9544        // `&str`-literal and `&String` (via Deref coercion) carriers are
9545        // exercised for `from` because the sole wire-up hands
9546        // `self.prior_versao()` (a `&str` accessor).
9547        let all_typed_kinds: [&'static str; 4] = [
9548            crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
9549            crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
9550            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9551            crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9552        ];
9553        let other_kinds_matrix: [Vec<&'static str>; 3] =
9554            [vec![], vec![all_typed_kinds[0]], all_typed_kinds.to_vec()];
9555        let froms: [&str; 4] = ["0.1.0", "1.2.3-rc.1", "0.2.0-alpha.7+build.5", "0.0.0"];
9556        let restart_counts: [usize; 3] = [1, 2, 3];
9557        for other_kinds in &other_kinds_matrix {
9558            for restart_count in restart_counts {
9559                for from in froms {
9560                    let from_owned: String = from.to_string();
9561                    for from_in in [from, from_owned.as_str()] {
9562                        assert_eq!(
9563                            UpgradeError::restart_not_exclusive(
9564                                from_in,
9565                                restart_count,
9566                                other_kinds.clone(),
9567                            ),
9568                            UpgradeError::RestartNotExclusive {
9569                                from: from.to_string(),
9570                                restart_count,
9571                                other_kinds: other_kinds.clone(),
9572                            },
9573                            "restart_not_exclusive must route from → from, \
9574                             restart_count → restart_count, other_kinds → \
9575                             other_kinds in declared field order verbatim \
9576                             on ({from:?}, {restart_count:?}, \
9577                             {other_kinds:?})",
9578                        );
9579                    }
9580                }
9581            }
9582        }
9583    }
9584
9585    #[test]
9586    fn validate_restart_exclusive_arm_routes_through_restart_not_exclusive_ctor() {
9587        // End-to-end wire-up pin: sweep the three canonical exclusivity-
9588        // violation shapes the `validate_restart_exclusive` gate can
9589        // refuse — restart + one typed instruction (`restart_count: 1,
9590        // other_kinds: [load-module]`), restart + full typed sequence
9591        // (`restart_count: 1, other_kinds: [load-module, state-change,
9592        // soft-purge, purge]`), and duplicated restart only
9593        // (`restart_count: 2, other_kinds: []`) — and pin that each
9594        // observed `Err` byte-equals the substrate-primitive
9595        // [`UpgradeError::restart_not_exclusive`] ctor's output on the
9596        // same fixture. A future silent de-lift of the wire-up back to
9597        // the open-coded struct-literal (or a silent axis-swap on the
9598        // three-field construction at the wire-up site, or an
9599        // `other_kinds` reorder / drop) trips at caixa-core test time
9600        // rather than at a downstream diagnostic consumer far from the
9601        // wire-up commit. Same end-to-end-wire-up discipline as the
9602        // sibling
9603        // `validate_cleanup_singularity_arm_routes_through_duplicate_cleanup_ctor`
9604        // (10a5b48) on the peer per-module cleanup-singularity axis and
9605        // `validate_purge_ordering_arm_routes_through_purge_without_prior_load_ctor`
9606        // on the peer load → cleanup ordering gate; all three key off
9607        // exactly one typed dispatch on the substrate primitive.
9608        let cases: [(&str, Vec<UpgradeInstruction>, usize, Vec<&'static str>); 3] = [
9609            (
9610                "0.1.0",
9611                vec![
9612                    UpgradeInstruction::LoadModule {
9613                        module: "hello-rio".into(),
9614                    },
9615                    UpgradeInstruction::Restart,
9616                ],
9617                1,
9618                vec![crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE],
9619            ),
9620            (
9621                "1.2.3-rc.1",
9622                vec![
9623                    UpgradeInstruction::LoadModule {
9624                        module: "hello-rio".into(),
9625                    },
9626                    UpgradeInstruction::StateChange {
9627                        script: PathBuf::from("lib/m.lisp"),
9628                    },
9629                    UpgradeInstruction::SoftPurge {
9630                        module: "hello-rio-old".into(),
9631                    },
9632                    UpgradeInstruction::Purge {
9633                        module: "hello-rio-old".into(),
9634                    },
9635                    UpgradeInstruction::Restart,
9636                ],
9637                1,
9638                vec![
9639                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
9640                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
9641                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9642                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9643                ],
9644            ),
9645            (
9646                "0.0.0",
9647                vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
9648                2,
9649                vec![],
9650            ),
9651        ];
9652        for (from, instructions, restart_count, other_kinds) in cases {
9653            let e = entry(from, instructions);
9654            let observed = e.validate().unwrap_err();
9655            assert_eq!(
9656                observed,
9657                UpgradeError::restart_not_exclusive(from, restart_count, other_kinds.clone()),
9658                "validate_restart_exclusive must route its refusal \
9659                 through UpgradeError::restart_not_exclusive(from, \
9660                 restart_count, other_kinds) on a mixed-`(:restart)` \
9661                 entry, byte-equal to the pre-lift open-coded struct-\
9662                 literal wrap on the same fixture",
9663            );
9664        }
9665    }
9666
9667    #[test]
9668    fn module_invalid_ctor_matches_struct_literal_wrap() {
9669        // Fail-before-pass-after equivalence pin on
9670        // [`UpgradeError::module_invalid`] — the constructor must
9671        // produce a byte-equal `UpgradeError` to the pre-lift open-
9672        // coded `Self::ModuleInvalid { kind, module: module.to_string(),
9673        // reason }` struct-literal on the same `(:load-module …)` /
9674        // `:module "Hello-Rio"` / parser-shaped-reason fixture. A byte-
9675        // mismatched constructor body (a stray `.trim()`, a rebased
9676        // field order, a `String::new()` reason substitution) would
9677        // trip this pin first, byte-for-byte against the sibling
9678        // [`crate::AplicacaoError::contrato_caixa_invalid`] (3d1e484) /
9679        // [`crate::SupervisorError::child_caixa_invalid`] /
9680        // [`crate::DepError::nome_invalid`] (077aa3d) per-envelope pin
9681        // discipline on the peer three-slot `{ *, reason: String }`
9682        // invalid-arm ctor family.
9683        let kind = crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE;
9684        let module = "Hello-Rio";
9685        let reason = "must be lowercase alphanumeric or `-`";
9686        assert_eq!(
9687            UpgradeError::module_invalid(kind, module, reason),
9688            UpgradeError::ModuleInvalid {
9689                kind,
9690                module: module.to_string(),
9691                reason: reason.to_string(),
9692            },
9693            "generated module_invalid ctor must produce byte-equal \
9694             UpgradeError to the open-coded struct-literal wrap on the \
9695             same (kind, module, reason) fixture",
9696        );
9697    }
9698
9699    #[test]
9700    fn module_invalid_ctor_routes_kind_verbatim_across_every_declared_module_variant() {
9701        // Cross-axis pin: sweep the constructor's `kind: &'static str`
9702        // input across every [`UpgradeInstruction::declared_module`]-
9703        // bearing variant's canonical
9704        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_*`] tag —
9705        // `:load-module` / `:soft-purge` / `:purge` — plus a non-
9706        // canonical `":phantom"` fourth arm proving the ctor does not
9707        // silently clamp `kind` to the three-arm roster. The
9708        // `reason: impl Into<String>` bound accepts both `&str`
9709        // literals and the [`String`] the underlying
9710        // [`crate::render::is_dns_1123_label`] predicate returns via
9711        // `.into()`, matching the peer
9712        // [`crate::AplicacaoError::contrato_caixa_invalid`] cross-axis
9713        // sweep on the sibling `:contratos` per-edge envelope.
9714        let module = "Hello-Rio";
9715        let reason = "must be lowercase alphanumeric or `-`";
9716        for kind in [
9717            crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
9718            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9719            crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9720            ":phantom",
9721        ] {
9722            assert_eq!(
9723                UpgradeError::module_invalid(kind, module, reason),
9724                UpgradeError::ModuleInvalid {
9725                    kind,
9726                    module: module.to_string(),
9727                    reason: reason.to_string(),
9728                },
9729                "module_invalid ctor must thread kind={kind:?} verbatim",
9730            );
9731        }
9732    }
9733
9734    #[test]
9735    fn validate_module_wire_up_routes_invalid_through_module_invalid_ctor() {
9736        // End-to-end wire-up pin: [`validate_module`]'s
9737        // [`crate::render::require_valid_dns_1123_label`] invalid-arm
9738        // must emit a diagnostic byte-equal to the ctor's output on the
9739        // same `(kind, module)` fixture — the fold's invariant that
9740        // [`validate_module`]'s cascade reaches the
9741        // [`UpgradeError::ModuleInvalid`] envelope through the
9742        // substrate primitive [`UpgradeError::module_invalid`] rather
9743        // than the pre-lift open-coded struct-literal. Sweep every
9744        // [`UpgradeInstruction::declared_module`]-bearing variant
9745        // against a canonical footgun (`"Hello-Rio"` — the uppercase-
9746        // lead footgun the peer `validate_rejects_non_dns_1123_module`
9747        // test above already carries) so every wire-up on the invalid-
9748        // arm cascade lands on the ctor's output. Matches the peer
9749        // sibling end-to-end pin
9750        // [`crate::AplicacaoError::contrato_caixa_invalid`] (3d1e484)
9751        // carries on `validate_contrato_caixa`'s
9752        // `require_valid_dns_1123_label` invalid-arm.
9753        let module = "Hello-Rio";
9754        let cases: &[(UpgradeInstruction, &'static str)] = &[
9755            (
9756                UpgradeInstruction::LoadModule {
9757                    module: module.to_string(),
9758                },
9759                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
9760            ),
9761            (
9762                UpgradeInstruction::SoftPurge {
9763                    module: module.to_string(),
9764                },
9765                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
9766            ),
9767            (
9768                UpgradeInstruction::Purge {
9769                    module: module.to_string(),
9770                },
9771                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
9772            ),
9773        ];
9774        for (instr, expected_kind) in cases {
9775            let observed = instr.validate().unwrap_err();
9776            let UpgradeError::ModuleInvalid {
9777                reason: observed_reason,
9778                ..
9779            } = &observed
9780            else {
9781                panic!("expected ModuleInvalid on {instr:?}, got {observed:?}");
9782            };
9783            assert_eq!(
9784                observed,
9785                UpgradeError::module_invalid(expected_kind, module, observed_reason.clone()),
9786                "validate_module must route its invalid-arm refusal \
9787                 through UpgradeError::module_invalid(kind, module, \
9788                 reason) on {instr:?}, byte-equal to the pre-lift open-\
9789                 coded struct-literal wrap on the same fixture",
9790            );
9791        }
9792    }
9793}