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()).map_err(|e| UpgradeError::FromInvalid {
324            from: self.prior_versao().to_string(),
325            reason: e.to_string(),
326        })?;
327        // Per-instruction typed shape: kind-tagged `:module` /
328        // `:script` value-shape gates fire here, *before* the
329        // within-entry restart-exclusivity gate below — so a
330        // malformed-shape diagnostic on a Module/Script-bearing
331        // instruction surfaces with its narrower self-locating
332        // wording (`ModuleEmpty`, `ModuleInvalid`, `EmptyScript`,
333        // `AbsoluteScript`, `ParentEscapeScript`) rather than
334        // collapsing two unrelated authoring errors into a single
335        // exclusivity diagnostic. Same empty-first cascade discipline
336        // every peer DNS-1123 / path-shape gate inside this module
337        // uses (`validate_module`'s ModuleEmpty arm precedes the
338        // DNS-1123 predicate; `validate` on `StateChange` consults
339        // the lifted `is_sandboxed_relative_path` shape gate first).
340        // Route the per-instruction shape-check fan-out through the
341        // lifted [`Self::instructions`] slice-return accessor rather
342        // than the raw `self.instructions` field access — first of
343        // nine paired production consumers of the per-`:upgrade-from
344        // :instructions` OTP-appup migration-instruction-list surface
345        // that now key off exactly one typed dispatch on the substrate
346        // primitive.
347        for instr in self.instructions() {
348            instr.validate()?;
349        }
350        self.validate_restart_exclusive()?;
351        self.validate_state_change_ordering()?;
352        self.validate_purge_ordering()?;
353        self.validate_state_change_before_cleanup()?;
354        self.validate_load_singularity()?;
355        self.validate_state_change_singularity()?;
356        self.validate_cleanup_singularity()?;
357        Ok(())
358    }
359
360    /// Reject `:upgrade-from :instructions` lists that carry
361    /// `(:restart)` alongside any other instruction, or that carry
362    /// more than one `(:restart)`. The valid Restart-bearing shape is
363    /// exactly `((:restart))` — a single `Restart` as the entry's
364    /// whole instructions list.
365    ///
366    /// Per [`UpgradeInstruction::Restart`]'s doc comment, `(:restart)`
367    /// is the *fallback* for an entry whose typed upgrade is
368    /// impossible (wasm component-model world incompatibility,
369    /// irreversible state shape change). The fallback is terminal by
370    /// construction: the operator restarts the pod and the new version
371    /// comes up fresh, so any other instructions in the same entry
372    /// are dead code in both directions — either the typed sequence
373    /// would have succeeded and `(:restart)` is unreached, or it
374    /// wouldn't and the typed instructions are dead because the
375    /// operator restarts anyway. Two canonical authoring footguns
376    /// close here:
377    ///
378    ///   - `((:load-module …) (:state-change …) (:restart))` — the
379    ///     "I'll try the typed path *then* restart anyway" footgun.
380    ///     There is no coherent OTP-shaped semantic for this: if the
381    ///     typed sequence succeeds, the trailing restart discards the
382    ///     work that just succeeded (defeating the whole point of
383    ///     declaring it); if it fails, the restart is never reached
384    ///     because the entry already failed.
385    ///   - `((:restart) (:restart))` — multiple `Restart` variants in
386    ///     one entry. The fallback is a single semantic; repeating it
387    ///     is at best redundant, at worst suggests the author thought
388    ///     the second one would re-trigger after the first.
389    ///
390    /// Same within-entry exclusivity discipline OTP's `relup` enforces
391    /// at the `restart_new_emulator | restart_emulator` instruction
392    /// boundary — those instructions are terminal in the upgrade
393    /// script (`systools(3)` rejects sequences that continue past
394    /// them); pleme-io lifts the same shape to a build-time gate,
395    /// matching the CAIXA-SDLC §III "build errors, not runtime
396    /// surprises" frame.
397    ///
398    /// Same within-entry cross-instruction discipline the
399    /// [`crate::AplicacaoSpec::validate_placement`] strategy ↔
400    /// shard-key partition (934bc58) and
401    /// [`validate_upgrade_from_against_versao`]'s `:from` ↔ `:versao`
402    /// precedence partition (de7ab1a) apply on cross-slot axes — now
403    /// extended onto the first within-list cross-instruction axis on
404    /// the `:upgrade-from` typed slot.
405    fn validate_restart_exclusive(&self) -> Result<(), UpgradeError> {
406        // Route the paired restart-count / instructions-len / other-
407        // kind projections through the lifted [`Self::instructions`]
408        // slice-return accessor rather than the raw `self.instructions`
409        // field access — three raw-access sites in one gate collapse
410        // onto exactly one typed dispatch on the substrate primitive.
411        //
412        // The paired positive / negated `Self::Restart` arm-discriminator
413        // predicates route through the `gen_platform::IsVariant`
414        // derive-generated [`UpgradeInstruction::is_restart`] rather than
415        // the raw `matches!(i, UpgradeInstruction::Restart)` /
416        // `!matches!(i, UpgradeInstruction::Restart)` open-coded pattern-
417        // matches — same closed-set-typed-enum arm-discriminator dispatch
418        // discipline the sibling [`crate::CaixaKind`] `IsVariant` derive
419        // (f5bba80) extended onto its ten `caixa.kind() == CaixaKind::X`
420        // / `!= CaixaKind::X` production sites in the substrate's own
421        // layout invariant verifier + typed-view projection gates,
422        // extended here onto the last unlifted `matches!`-based
423        // arm-discriminator axis on the [`UpgradeInstruction`] closed-set
424        // typed enum. A future sixth `UpgradeInstruction` arm (an
425        // adaptive-upgrade-shaped `AwaitReadiness` gate the M2.5
426        // wasm-operator's hot-upgrade runtime could adopt to bracket the
427        // typed instruction sequence against a per-cluster readiness
428        // probe, a `Downgrade` variant OTP's `relup` acknowledges on the
429        // reverse axis, a `CanaryTraffic` split-traffic variant the M4 CR
430        // materializer could resolve per-CR) migrates as a single
431        // enum-declaration edit — the derive auto-generates the paired
432        // `.is_<new_arm>()` predicate; every consumer inherits the new
433        // arm on the next re-derive, rather than the two `matches!` sites
434        // here having to be threaded through in lockstep.
435        let instructions = self.instructions();
436        let restart_count = instructions.iter().filter(|i| i.is_restart()).count();
437        if restart_count == 0 {
438            return Ok(());
439        }
440        if restart_count == 1 && instructions.len() == 1 {
441            return Ok(());
442        }
443        let other_kinds: Vec<&'static str> = instructions
444            .iter()
445            .filter(|i| !i.is_restart())
446            .map(UpgradeInstruction::lisp_form)
447            .collect();
448        Err(UpgradeError::RestartNotExclusive {
449            from: self.prior_versao().to_string(),
450            restart_count,
451            other_kinds,
452        })
453    }
454
455    /// Reject an entry whose `(:state-change …)` is not preceded by a
456    /// `(:load-module …)` in the same `:instructions` list.
457    ///
458    /// `StateChange` is the `gen_server:code_change/3` analog
459    /// ([`UpgradeInstruction::StateChange`] doc; INSPIRATIONS §II.4):
460    /// it runs the migration script that folds the *old* state into the
461    /// shape the *new* code expects. In OTP, `code_change/3` is invoked
462    /// in the context of the newly-loaded code — `release_handler`
463    /// always loads the new module before running the advanced update
464    /// that triggers the callback. caixa decomposes that into two
465    /// explicit instructions (`LoadModule` brings the new version up
466    /// "alongside the current one"; `StateChange` migrates the state),
467    /// and the module doc pins that the operator "runs the instructions
468    /// in order" and only swaps traffic after all succeed. So a
469    /// `:state-change` with no preceding `:load-module` migrates state
470    /// into code that was never loaded — the migration script runs while
471    /// the only resident version is still the *old* one, which expects
472    /// the *old* state. Two authoring footguns close here:
473    ///
474    ///   - `((:state-change "…"))` — the "I wrote the migration but
475    ///     forgot to load the new module" footgun. The new code that
476    ///     defines the new state representation (and that the migration
477    ///     output is destined for) never comes up; the operator runs
478    ///     the script against the old code and either no-ops or corrupts
479    ///     live state.
480    ///   - `((:state-change "…") (:load-module "…"))` — the
481    ///     right-instructions-wrong-order footgun. Because the operator
482    ///     executes in declared order, the migration runs *before* the
483    ///     new code is resident, then the load brings up code expecting
484    ///     already-migrated state that the just-run script produced
485    ///     against the old version's shape. The canonical order is
486    ///     `(:load-module …) (:state-change …) (:soft-purge …)`
487    ///     (module doc example).
488    ///
489    /// Same within-entry cross-instruction discipline as
490    /// [`Self::validate_restart_exclusive`] (the `(:restart)` terminal-
491    /// exclusivity gate it runs beside): both reject an
492    /// `:instructions` list whose instructions are individually
493    /// well-shaped but jointly incoherent, at the typed build surface
494    /// rather than as a runtime surprise. Runs *after*
495    /// `validate_restart_exclusive` so a `((:state-change …)
496    /// (:restart))` shape still surfaces the more-fundamental
497    /// `RestartNotExclusive` (a valid `(:restart)` entry is `(:restart)`
498    /// alone, so no Restart-bearing entry reaches this gate carrying a
499    /// `StateChange`).
500    fn validate_state_change_ordering(&self) -> Result<(), UpgradeError> {
501        // Route the per-instruction load-family arm-discriminator through
502        // the `gen_platform::IsVariant`-derive-generated
503        // [`UpgradeInstruction::is_load_module`] predicate and the
504        // per-instruction migration-family `:script` scalar projection
505        // through the sibling lifted [`UpgradeInstruction::declared_path`]
506        // `Option<&PathBuf>` accessor rather than the raw two-arm
507        // `match instr { UpgradeInstruction::LoadModule { .. } =>
508        // loaded = true, UpgradeInstruction::StateChange { script } if
509        // !loaded => …, _ => {} }` open-coded pattern-match — closes the
510        // last unlifted `match`-shaped per-arm-hand-rolled load-family
511        // arm-discriminator + migration-family script-projection pair
512        // inside `impl UpgradeFromEntry`. Sibling of the peer
513        // [`Self::validate_purge_ordering`] (580d0f1) routing already
514        // lifted onto [`UpgradeInstruction::is_load_module`] on the paired
515        // load → cleanup ordering axis, the peer
516        // [`Self::validate_load_singularity`] (c9ce91d) routing lifted
517        // onto the [`UpgradeInstruction::is_load_module`] +
518        // [`UpgradeInstruction::declared_module`] pair on the singularity
519        // axis, and the peer [`Self::validate_state_change_singularity`]
520        // routing already lifted onto the sibling
521        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
522        // accessor on the migration-family script-projection axis — both
523        // ordering-gate load-family sticky-latch dispatches now key off
524        // exactly one typed dispatch on the substrate primitive for
525        // their load-family arm-discriminator, and both migration-family
526        // projection sites (this ordering gate + the peer singularity
527        // gate) now key off exactly one typed dispatch on the substrate
528        // primitive for the `:script`-carrying axis. A future sixth arm
529        // on [`UpgradeInstruction`] (an `AwaitReadiness` gate, a
530        // `Downgrade` reverse-axis variant OTP's `relup` acknowledges, a
531        // `CanaryTraffic` split-traffic variant the M4 CR materializer
532        // could resolve per-CR — INSPIRATIONS §II.4) migrates as one
533        // enum-declaration edit through the derive rather than a
534        // coordinated rewrite of every ordering / singularity gate's
535        // per-arm hand-rolled pattern-match. Byte-identity of this
536        // dispatch against the pre-lift `match` shape is pinned by
537        // [`tests::validate_state_change_ordering_projects_scripts_through_is_load_module_and_declared_path_accessors`].
538        let mut loaded = false;
539        for instr in self.instructions() {
540            if instr.is_load_module() {
541                loaded = true;
542            } else if !loaded && let Some(script) = instr.declared_path() {
543                return Err(UpgradeError::state_change_without_prior_load(
544                    self.prior_versao(),
545                    script,
546                ));
547            }
548        }
549        Ok(())
550    }
551
552    /// Reject an entry whose `(:soft-purge …)` or `(:purge …)` is not
553    /// preceded by a `(:load-module …)` in the same `:instructions` list.
554    ///
555    /// `SoftPurge` and `Purge` are the `code:soft_purge/1` /
556    /// `code:purge/1` analogs (INSPIRATIONS §II.4): they remove the
557    /// *old* module from memory after the new one is resident. OTP's
558    /// two-phase code load is `code:load_module/1` *then*
559    /// `code:soft_purge/1` — load the new version alongside the old
560    /// (both in memory, new requests route to new), then purge the old
561    /// after in-flight callers drain. caixa decomposes that into two
562    /// explicit instructions (`LoadModule` brings the new version up
563    /// "alongside the current one", per [`UpgradeInstruction::LoadModule`]
564    /// doc; `SoftPurge` "waits for in-flight requests on a named module
565    /// to drain, then GC it", per [`UpgradeInstruction::SoftPurge`] doc),
566    /// and the module doc pins that the operator "runs the instructions
567    /// in order". So a `:soft-purge` / `:purge` with no preceding
568    /// `:load-module` purges old code while the only resident version is
569    /// still the *same* old code, leaving the upgrade entry asking the
570    /// operator to drain or discard the live module with no replacement
571    /// resident. Two authoring footguns close here:
572    ///
573    ///   - `((:soft-purge "…"))` / `((:purge "…"))` — the "I wrote the
574    ///     cleanup but forgot to load the new module" footgun. The new
575    ///     code never comes up alongside; the operator either drains the
576    ///     old version to nothing (`SoftPurge`) or discards it outright
577    ///     mid-request (`Purge`), with no replacement to route in-flight
578    ///     or future requests to.
579    ///   - `((:soft-purge "…") (:load-module "…"))` /
580    ///     `((:purge "…") (:load-module "…"))` — the right-instructions-
581    ///     wrong-order footgun. Because the operator executes in declared
582    ///     order, the cleanup runs *before* the new code is resident,
583    ///     leaving a window during which neither version is available;
584    ///     the canonical order is `(:load-module …) (:state-change …)
585    ///     (:soft-purge …)` (module doc example).
586    ///
587    /// Same within-entry cross-instruction discipline as
588    /// [`Self::validate_state_change_ordering`] (the `:state-change`-
589    /// ordering gate it runs beside): both close the same load-before-X
590    /// post-condition on the OTP appup ordering contract, now extending
591    /// the typed coverage from "new code resident before its state
592    /// migration runs" to "new code resident before the old code is
593    /// drained or discarded" — the second half of OTP's two-phase code
594    /// load. Runs *after* `validate_state_change_ordering` so an entry
595    /// like `((:state-change …) (:soft-purge …))` surfaces the more-
596    /// fundamental `StateChangeWithoutPriorLoad` first (both instructions
597    /// are load-less, but state-change is the load-bearing semantic — the
598    /// purge is meaningless either way without a preceding load, so the
599    /// author should see the migration-side diagnostic first).
600    fn validate_purge_ordering(&self) -> Result<(), UpgradeError> {
601        let mut loaded = false;
602        for instr in self.instructions() {
603            // Route the per-instruction cleanup-family arm-discriminator
604            // through the lifted [`UpgradeInstruction::is_cleanup`] typed
605            // predicate rather than the raw
606            // `UpgradeInstruction::SoftPurge { module } |
607            // UpgradeInstruction::Purge { module }` open-coded per-arm
608            // union pattern-match — the first of three within-entry cross-
609            // instruction cleanup-facing gates now keys off exactly one
610            // typed dispatch on the substrate primitive, so any future
611            // fifth cleanup-shaped variant (a `Discard` variant the
612            // `code:delete/1` peer inspires) added to
613            // [`UpgradeInstruction`] + a composing `|| self.is_discard()`
614            // term at [`UpgradeInstruction::is_cleanup`] reaches this gate
615            // through the accessor's one body. The paired cleanup-arm
616            // `:module` scalar is routed through the sibling
617            // [`UpgradeInstruction::declared_module`] accessor rather than
618            // the raw pattern-bound `module` binding — same substrate-
619            // primitive-owns-the-scalar discipline every peer
620            // per-`UpgradeInstruction` scalar-value axis already routes
621            // through, with the `is_cleanup`-implies-`declared_module`-is-
622            // `Some` composition pin at
623            // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
624            // making the `.expect(…)` structurally infallible at build
625            // time. Peer of the sibling
626            // [`UpgradeFromEntry::validate_restart_exclusive`]
627            // paired positive / negated
628            // [`UpgradeInstruction::is_restart`] routing (915a934) on the
629            // per-arm terminal-fallback partition — same closed-set-typed-
630            // enum arm-discriminator dispatch discipline extended from
631            // the single-arm terminal-fallback family onto the two-arm
632            // cleanup family here.
633            //
634            // Route the paired load-family arm-discriminator through the
635            // `gen_platform::IsVariant`-derive-generated
636            // [`UpgradeInstruction::is_load_module`] predicate rather than
637            // the raw `matches!(instr, UpgradeInstruction::LoadModule
638            // { .. })` open-coded pattern-match — closes the last
639            // unlifted `matches!`-based per-variant arm-discriminator
640            // axis on the [`UpgradeInstruction`] closed-set typed enum,
641            // sibling of the [`UpgradeInstruction::is_restart`] terminal-
642            // fallback routing (915a934) and the
643            // [`UpgradeInstruction::is_cleanup`] two-arm cleanup-family
644            // routing (0bc469f) that already lifted the paired
645            // arm-discriminator sites in this method. Every arm-family
646            // partition the gate keys off — load-family (`LoadModule`),
647            // cleanup-family (`SoftPurge | Purge`), terminal-fallback
648            // (`Restart`) — now consults exactly one typed dispatch on
649            // the substrate primitive, so a future sixth arm added to
650            // [`UpgradeInstruction`] (an `AwaitReadiness` gate, a
651            // `Downgrade` reverse-axis variant OTP's `relup` acknowledges,
652            // a `CanaryTraffic` split-traffic variant the M4 CR
653            // materializer could resolve per-CR — INSPIRATIONS §II.4)
654            // migrates as a single enum-declaration edit through the
655            // derive rather than a scattered per-consumer rewrite. The
656            // partition invariant is pinned by
657            // [`tests::upgrade_instruction_is_load_module_predicate_partitions_the_arm_set`]
658            // and the byte-identity of this dispatch against the pre-lift
659            // `matches!` pattern by
660            // [`tests::validate_purge_ordering_routes_through_is_load_module_predicate`].
661            if instr.is_load_module() {
662                loaded = true;
663            } else if instr.is_cleanup() && !loaded {
664                return Err(UpgradeError::PurgeWithoutPriorLoad {
665                    from: self.prior_versao().to_string(),
666                    kind: instr.lisp_form(),
667                    module: instr
668                        .declared_module()
669                        .expect("is_cleanup() implies declared_module() is Some")
670                        .to_string(),
671                });
672            }
673        }
674        Ok(())
675    }
676
677    /// Reject an entry whose `(:state-change …)` appears after any
678    /// `(:soft-purge …)` / `(:purge …)` in the same `:instructions`
679    /// list — completing the canonical OTP appup `code:load_module/1`
680    /// → `gen_server:code_change/3` → `code:soft_purge/1` ordering
681    /// chain on the typed `:upgrade-from` slot.
682    ///
683    /// `StateChange` is the `gen_server:code_change/3` analog
684    /// ([`UpgradeInstruction::StateChange`] doc; INSPIRATIONS §II.4
685    /// verbatim: "State migration uses `gen_server:code_change/3` …
686    /// migrate state from v0.1.0 shape to current shape"). The
687    /// callback's input is the *prior* version's state shape, which
688    /// only exists while the prior code is still resident — the running
689    /// `gen_server` processes hold the v0.1.0 state, and the operator's
690    /// dispatch invokes `code_change/3` to fold that state into the
691    /// current shape. `SoftPurge` / `Purge` are the `code:soft_purge/1`
692    /// / `code:purge/1` analogs ([`UpgradeInstruction::SoftPurge`] /
693    /// [`UpgradeInstruction::Purge`] docs): they drain or discard the
694    /// *old* module after the new one is resident. The operator runs
695    /// instructions in declared order (module doc), so a cleanup ahead
696    /// of a state-change discards the prior code before the migration
697    /// fold runs against the state it held — the canonical OTP error
698    /// mode "`code_change/3` invoked on a purged module" the
699    /// `release_handler` enforces by always emitting the migration
700    /// callback before the soft-purge step.
701    ///
702    /// `systools`-generated `.relup` files always emit `code_change`
703    /// before `soft_purge` for this reason; the appup cookbook's
704    /// canonical pattern (`[{load_module, m}, {update, m, soft},
705    /// {soft_purge, m}]`) places the migration-triggering `update`
706    /// strictly between the load and the cleanup. The caixa module
707    /// doc pins the same canonical order verbatim — `(:load-module
708    /// …) (:state-change …) (:soft-purge …)` — and this gate makes
709    /// that ordering a structural property at build time. Three
710    /// authoring footguns close here:
711    ///
712    ///   - `((:load-module "x") (:soft-purge "x-old") (:state-change
713    ///     "lib/m.lisp"))` — the right-instructions-wrong-order
714    ///     footgun on the migrate ↔ cleanup axis. Because the operator
715    ///     executes in declared order, the cleanup drains the v0.1.0
716    ///     module to nothing before the migration callback runs, and
717    ///     the script either no-ops (no v0.1.0 state left to fold) or
718    ///     crashes (`code_change/3` invoked on an unloaded version).
719    ///     The canonical order is `(:load-module …) (:state-change
720    ///     …) (:soft-purge …)` (module doc example).
721    ///   - `((:load-module "x") (:purge "x-old") (:state-change
722    ///     "lib/m.lisp"))` — same shape on the more catastrophic
723    ///     `:purge` variant. The immediate-discard semantic destroys
724    ///     v0.1.0 state mid-request; the trailing migration script
725    ///     has nothing to fold from and the `gen_server` processes that
726    ///     held v0.1.0 state were killed by the `:purge`.
727    ///   - `((:load-module "x") (:soft-purge "x-old") (:state-change
728    ///     "lib/m1.lisp") (:soft-purge "y-old"))` — the "migration
729    ///     sandwiched between two cleanups" footgun. The first
730    ///     cleanup discards v0.1.0; the migration runs against
731    ///     drained state; the second cleanup is irrelevant. The first
732    ///     cleanup → state-change boundary is the load-bearing defect
733    ///     surfaced.
734    ///
735    /// Same within-entry cross-instruction discipline as
736    /// [`Self::validate_state_change_ordering`] (the load → state-
737    /// change ordering gate it runs after) and
738    /// [`Self::validate_purge_ordering`] (the load → cleanup ordering
739    /// gate it runs after): all three close one boundary of the OTP
740    /// canonical sequence `code:load_module/1` →
741    /// `gen_server:code_change/3` → `code:soft_purge/1`. The
742    /// state-change-ordering gate closes the load → migrate boundary;
743    /// the purge-ordering gate closes the load → cleanup boundary;
744    /// this gate closes the migrate → cleanup boundary, completing
745    /// the typed coverage of the canonical sequence. Runs *after*
746    /// [`Self::validate_purge_ordering`] (and therefore after
747    /// [`Self::validate_state_change_ordering`]) so an entry like
748    /// `((:soft-purge "x-old") (:state-change "lib/m.lisp"))` —
749    /// which violates *both* the purge-without-load gate and this
750    /// state-change-after-cleanup gate — surfaces the more-
751    /// fundamental `PurgeWithoutPriorLoad` first (the missing-load
752    /// defect is load-bearing; once a coherent `(:load-module …)`
753    /// precedes both, the migrate ↔ cleanup ordering becomes the
754    /// next live defect). Runs *before* the per-instruction-class
755    /// singularity gates ([`Self::validate_load_singularity`],
756    /// [`Self::validate_state_change_singularity`],
757    /// [`Self::validate_cleanup_singularity`]) so an entry like
758    /// `((:load-module "x") (:soft-purge "x-old") (:state-change
759    /// "lib/m.lisp") (:state-change "lib/m.lisp"))` — which violates
760    /// *both* this ordering gate and the state-change-singularity
761    /// gate — surfaces the ordering defect first; the canonical
762    /// "ordering before singularity" precedence the peer
763    /// `validate_state_change_ordering` / `validate_purge_ordering`
764    /// gates already establish.
765    ///
766    /// Detection: linear scan of the instructions list with a
767    /// `prior_cleanup: Option<(module, kind)>` sticky-once latch
768    /// recording the first cleanup encountered; on any subsequent
769    /// `StateChange` the gate fires with the script + the prior
770    /// cleanup's kind/module. Diagnostic-order pin: the first
771    /// colliding state-change-after-cleanup pair surfaces, not the
772    /// last — mirrors every peer ordering gate's first-collision
773    /// posture ([`Self::validate_state_change_ordering`] returns on
774    /// the first `StateChange` without prior load,
775    /// [`Self::validate_purge_ordering`] on the first cleanup
776    /// without prior load).
777    fn validate_state_change_before_cleanup(&self) -> Result<(), UpgradeError> {
778        let mut prior_cleanup: Option<(&str, &'static str)> = None;
779        for instr in self.instructions() {
780            // Route the per-instruction cleanup-family arm-discriminator
781            // through the lifted [`UpgradeInstruction::is_cleanup`] typed
782            // predicate rather than the raw
783            // `UpgradeInstruction::SoftPurge { module } |
784            // UpgradeInstruction::Purge { module }` open-coded per-arm
785            // union pattern-match — the second of three within-entry
786            // cross-instruction cleanup-facing gates the peer
787            // [`Self::validate_purge_ordering`] routing already lifted;
788            // both now key off exactly one typed dispatch on the substrate
789            // primitive so the "which arms belong to the cleanup family"
790            // question resolves at exactly one caixa-core edit. The
791            // sticky-once latch's `:module` scalar is routed through the
792            // sibling [`UpgradeInstruction::declared_module`] accessor
793            // rather than the raw pattern-bound `module.as_str()`
794            // projection, with the `is_cleanup`-implies-`declared_module`-
795            // is-`Some` composition pin at
796            // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
797            // making the `.expect(…)` structurally infallible at build
798            // time.
799            if instr.is_cleanup() && prior_cleanup.is_none() {
800                prior_cleanup = Some((
801                    instr
802                        .declared_module()
803                        .expect("is_cleanup() implies declared_module() is Some"),
804                    instr.lisp_form(),
805                ));
806            } else if let Some(script) = instr.declared_path()
807                && let Some((prior_module, prior_kind)) = prior_cleanup
808            {
809                // Route the per-instruction `StateChange`-arm script-path
810                // projection through the sibling lifted
811                // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
812                // accessor rather than the raw
813                // `if let UpgradeInstruction::StateChange { script } = instr`
814                // open-coded pattern-match — the last unlifted per-
815                // `UpgradeInstruction` `PathBuf`-carrying-axis consumer
816                // inside `impl UpgradeFromEntry`, sibling to the four peer
817                // per-`UpgradeInstruction` consumers already routed through
818                // the accessor: [`UpgradeInstruction::validate`]'s per-
819                // `StateChange` sandbox-path fan-out, the layout-side per-
820                // `StateChange` script-existence fan-out at
821                // [`crate::layout::StandardLayout::verify`]
822                // (caixa-core/src/layout.rs:1058), the within-entry
823                // [`UpgradeFromEntry::validate_state_change_singularity`]
824                // per-`StateChange` script-projection fan-out, and the
825                // cross-slot
826                // [`validate_upgrade_from_against_behavior`]
827                // per-`StateChange` detection loop. Byte-equal today
828                // (`declared_path` returns `Some(script)` iff the
829                // instruction is [`UpgradeInstruction::StateChange`], per
830                // the sibling `declared_path_only_for_state_change` pin),
831                // so a state-change-after-cleanup surfaces
832                // `StateChangeAfterCleanup` byte-identical to the pattern-
833                // match shape. Any future accessor extension that promotes
834                // an additional variant onto the `PathBuf`-carrying axis
835                // reaches this gate through one caixa-core edit rather
836                // than a coordinated rewrite of five call sites — the
837                // migrate→cleanup ordering discipline extends to the
838                // promoted variant by construction. Same "one typed
839                // dispatch on the substrate primitive, thin projections at
840                // each consumer" trajectory the sibling
841                // [`UpgradeInstruction::declared_module`] `String`-axis
842                // per-variant unifier already established.
843                return Err(UpgradeError::StateChangeAfterCleanup {
844                    from: self.prior_versao().to_string(),
845                    script: script.clone(),
846                    prior_cleanup_kind: prior_kind,
847                    prior_cleanup_module: prior_module.to_string(),
848                });
849            }
850        }
851        Ok(())
852    }
853
854    /// Reject an entry whose `:instructions` list names the same module
855    /// as the target of more than one cleanup instruction (`:soft-purge`
856    /// or `:purge`) in total — set-not-multiset on the (cleanup-class,
857    /// module) axis, narrowed to the cleanup class.
858    ///
859    /// `SoftPurge` and `Purge` are the `code:soft_purge/1` /
860    /// `code:purge/1` analogs (INSPIRATIONS §II.4 verbatim: "1.
861    /// `code:load_module/1` — load v2 alongside v1 … 2.
862    /// `code:soft_purge/1` — wait until no process is running v1, then
863    /// discard. (`code:purge/1` kills v1 immediately if you don't
864    /// care.)"). The author picks *one* cleanup semantic per old
865    /// module — `:soft-purge` (preferred: waits for in-flight callers
866    /// to drain) or `:purge` (when the drain isn't possible) — and the
867    /// operator runs that one in declared order alongside any other
868    /// distinct-module cleanups. systools-generated `.relup` files
869    /// always emit at most one purge per module for this reason; any
870    /// retry / fallback decision is the operator's job on
871    /// instruction failure, not authored into the entry. Three
872    /// authoring footguns close here:
873    ///
874    ///   - `((:load-module "x") (:soft-purge "x-old") (:soft-purge "x-old"))`
875    ///     — the "I copy-pasted the cleanup line twice" footgun. The
876    ///     second `:soft-purge` is a no-op (the module is already gone
877    ///     after the first drain-and-discard) or undefined depending
878    ///     on the operator's handling of a non-resident-module purge
879    ///     request; either way the second instruction carries no
880    ///     observable semantic, far from the source caixa.lisp.
881    ///   - `((:load-module "x") (:soft-purge "x-old") (:purge "x-old"))`
882    ///     — the "soft-then-hard fallback" footgun. The author wrote
883    ///     "drain, and if drain didn't clean it up, force-discard",
884    ///     but the operator runs instructions unconditionally in
885    ///     declared order — the `:purge` fires whether the
886    ///     `:soft-purge` already discarded the module or not, so the
887    ///     fallback semantic the author imagined is missing; the
888    ///     pair is incoherent (drain *and* force-discard semantics
889    ///     on one module is two contradictory dispositions). The
890    ///     operator's failure-handling surface is its own
891    ///     responsibility: if `:soft-purge` doesn't drain within its
892    ///     cooldown the operator escalates, not the author's entry.
893    ///   - `((:load-module "x") (:purge "x-old") (:soft-purge "x-old"))`
894    ///     — same shape on the reversed ordering. The `:purge`
895    ///     discards immediately; the trailing `:soft-purge` has no
896    ///     module to drain.
897    ///
898    /// Same within-entry exclusivity discipline as
899    /// [`Self::validate_restart_exclusive`] (the `(:restart)` terminal-
900    /// exclusivity gate it joins on the per-module cleanup axis): both
901    /// reject an `:instructions` list whose instructions are
902    /// individually well-shaped but jointly incoherent on a chosen
903    /// semantic axis (restart-fallback for the whole entry there;
904    /// cleanup-semantic for one module here), at the typed build
905    /// surface rather than as a runtime surprise. Runs *after*
906    /// [`Self::validate_purge_ordering`] (the load-before-cleanup
907    /// ordering gate) so an entry like `((:soft-purge "x-old")
908    /// (:soft-purge "x-old"))` surfaces the more-fundamental
909    /// `PurgeWithoutPriorLoad` first (both cleanups are load-less, and
910    /// the missing-load defect is the load-bearing one — the duplicate
911    /// is meaningless either way without the preceding load).
912    ///
913    /// Same set-not-multiset discipline applied to every peer
914    /// duplicate-target axis: `:children :caixa` (dbf50a9 —
915    /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
916    /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
917    /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
918    /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
919    /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
920    /// and `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]).
921    /// Each closes the same authoring footgun: a Vec authoring surface
922    /// that silently accepts duplicate entries and renders the "second
923    /// wins" (or "operator processes both, second is a no-op or
924    /// errors") shape downstream, far from the source caixa.lisp.
925    /// This gate extends the discipline onto the within-entry
926    /// instruction-target axis — duplicate cleanup targets *within*
927    /// one `:upgrade-from` entry — the peer of the cross-entry
928    /// duplicate-`:from` axis at one level of nesting deeper.
929    ///
930    /// Detection: linear scan of the instructions list collecting
931    /// the (module, kind) pair from every `SoftPurge` / `Purge`
932    /// encountered; on the second occurrence of any module the gate
933    /// fires with the prior kind and the colliding kind in declaration
934    /// order. Diagnostic-order pin: the first colliding pair surfaces,
935    /// not the last — mirrors
936    /// [`validate_upgrade_from`]'s
937    /// `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
938    /// posture (the first detected collision wins) and every peer
939    /// duplicate gate's first-collision discipline.
940    fn validate_cleanup_singularity(&self) -> Result<(), UpgradeError> {
941        let mut seen: Vec<(&str, &'static str)> = Vec::new();
942        for instr in self.instructions() {
943            // Route the per-instruction cleanup-family arm-discriminator
944            // through the lifted [`UpgradeInstruction::is_cleanup`] typed
945            // predicate rather than the raw two-arm
946            // `UpgradeInstruction::SoftPurge { module } => (module.as_str(),
947            // M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE)` /
948            // `UpgradeInstruction::Purge { module } => (module.as_str(),
949            // M2_UPGRADE_INSTRUCTION_KIND_PURGE)` / `_ => continue`
950            // per-arm dispatch — the third of three within-entry cross-
951            // instruction cleanup-facing gates the peer
952            // [`Self::validate_purge_ordering`] +
953            // [`Self::validate_state_change_before_cleanup`] routing
954            // already lifted; all three now key off exactly one typed
955            // dispatch on the substrate primitive, structurally. The
956            // cleanup-target `(module, kind)` pair is projected through
957            // the peer [`UpgradeInstruction::declared_module`] /
958            // [`UpgradeInstruction::lisp_form`] accessors rather than
959            // the per-arm-hand-rolled scalar-value + kind-const pair,
960            // with the `is_cleanup`-implies-`declared_module`-is-`Some`
961            // composition pin at
962            // [`tests::upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
963            // making the `.expect(…)` structurally infallible at build
964            // time. Any future fifth cleanup-shaped variant added under
965            // the `is_cleanup` predicate + registered through the peer
966            // `lisp_form` per-arm kebab-case-const dispatch reaches this
967            // dedup gate through the accessor's one body rather than a
968            // fourth per-arm-hand-rolled scalar/kind projection here.
969            if !instr.is_cleanup() {
970                continue;
971            }
972            let module = instr
973                .declared_module()
974                .expect("is_cleanup() implies declared_module() is Some");
975            let kind = instr.lisp_form();
976            if let Some(prior_idx) = seen.iter().position(|(m, _)| *m == module) {
977                let prior_kind = seen[prior_idx].1;
978                return Err(UpgradeError::DuplicateCleanup {
979                    from: self.prior_versao().to_string(),
980                    module: module.to_string(),
981                    kinds: vec![prior_kind, kind],
982                });
983            }
984            seen.push((module, kind));
985        }
986        Ok(())
987    }
988
989    /// Reject an entry whose `:instructions` list names the same module
990    /// as the target of more than one `(:load-module …)` instruction —
991    /// set-not-multiset on the `LoadModule` axis.
992    ///
993    /// `LoadModule` is the `code:load_module/1` analog (INSPIRATIONS
994    /// §II.4 verbatim: "1. `code:load_module/1` — load v2 alongside v1;
995    /// new code is 'current', old code is 'old'."). The instruction
996    /// brings the new wasm component up resident alongside the old
997    /// one so the operator can route new traffic to the new code
998    /// while in-flight callers drain on the old — and the operator's
999    /// dispatch table reads the module *name* (a caixa name) to bind
1000    /// the component, so two `(:load-module "x")` instructions in one
1001    /// entry ask the operator to re-bind the same component twice.
1002    /// `systools`-generated `.relup` files emit at most one
1003    /// `load_module` per module per upgrade step for this reason; the
1004    /// second load has no observable semantic relative to the first
1005    /// (the component is already resident). Three authoring footguns
1006    /// close here:
1007    ///
1008    ///   - `((:load-module "x") (:load-module "x"))` — the "I
1009    ///     copy-pasted the load line twice" footgun. The second
1010    ///     `:load-module` re-reads the same module name and re-binds
1011    ///     the same wasm component — a no-op in both directions
1012    ///     (no new code becomes resident; no old code is purged) —
1013    ///     and any cleanup / migration the author intended for a
1014    ///     *distinct* module is silently absent from the entry.
1015    ///   - `((:load-module "x") (:load-module "x") (:state-change …))`
1016    ///     — the "I meant to load two distinct modules" typo. The
1017    ///     author intended `((:load-module "x") (:load-module "y"))`
1018    ///     but renamed both to "x" (or copied the first line and
1019    ///     forgot to change the module). The migration runs against
1020    ///     code that's resident only on one module name, and the
1021    ///     second module the author imagined was being loaded never
1022    ///     comes up at all — far from the source caixa.lisp.
1023    ///   - `((:load-module "x") (:load-module "x") (:soft-purge "x-old"))`
1024    ///     — same shape with a trailing cleanup. The duplicate load
1025    ///     is dead code; the cleanup still fires correctly, masking
1026    ///     the load-side duplication as a silently-passing entry.
1027    ///
1028    /// Same within-entry exclusivity discipline as
1029    /// [`Self::validate_cleanup_singularity`] (the per-module cleanup-
1030    /// singularity gate this runs beside) on the sibling
1031    /// `LoadModule` axis: both reject an `:instructions` list whose
1032    /// instructions are individually well-shaped but jointly
1033    /// incoherent on a per-module-per-class basis (load-once for the
1034    /// load axis here; cleanup-once for the cleanup axis there), at
1035    /// the typed build surface rather than as a runtime surprise.
1036    /// Runs *after* [`Self::validate_purge_ordering`] (the load-
1037    /// before-cleanup ordering gate) so an entry like
1038    /// `((:state-change "m.lisp") (:load-module "x") (:load-module "x"))`
1039    /// surfaces the more-fundamental `StateChangeWithoutPriorLoad`
1040    /// first (the missing-load defect is load-bearing — the migration
1041    /// runs against unloaded code; the duplicate is meaningless either
1042    /// way without the preceding load). Runs *before*
1043    /// [`Self::validate_cleanup_singularity`] so an entry like
1044    /// `((:load-module "x") (:load-module "x") (:soft-purge "y-old")
1045    /// (:soft-purge "y-old"))` surfaces `DuplicateLoadModule` first —
1046    /// the load axis precedes the cleanup axis in the canonical OTP
1047    /// sequence (`code:load_module/1` then `code:soft_purge/1`) and
1048    /// in [`UpgradeInstruction`] declaration order (`LoadModule`
1049    /// before `SoftPurge`/`Purge`), so the load-side singularity is
1050    /// the load-bearing diagnostic when both fire.
1051    ///
1052    /// Same set-not-multiset discipline applied to every peer
1053    /// duplicate-target axis: `:children :caixa` (dbf50a9 —
1054    /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
1055    /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
1056    /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1057    /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1058    /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
1059    /// `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]), and
1060    /// the per-module cleanup-target axis (9cedd8b —
1061    /// [`UpgradeError::DuplicateCleanup`]). This gate extends the
1062    /// discipline onto the within-entry `LoadModule` instruction-target
1063    /// axis — the third within-entry per-module singularity completing
1064    /// the load+cleanup pair across the OTP two-phase code-load
1065    /// contract.
1066    ///
1067    /// Detection: linear scan of the instructions list collecting the
1068    /// module name from every `LoadModule` encountered; on the second
1069    /// occurrence of any module the gate fires. Diagnostic-order pin:
1070    /// the first colliding occurrence surfaces, not the last — mirrors
1071    /// [`Self::validate_cleanup_singularity`]'s first-collision posture
1072    /// and every peer duplicate gate's first-collision discipline.
1073    fn validate_load_singularity(&self) -> Result<(), UpgradeError> {
1074        let mut seen: Vec<&str> = Vec::new();
1075        for instr in self.instructions() {
1076            // Route the per-instruction load-family arm-discriminator
1077            // through the `gen_platform::IsVariant`-derive-generated
1078            // [`UpgradeInstruction::is_load_module`] predicate rather
1079            // than the raw single-arm `match instr {
1080            // UpgradeInstruction::LoadModule { module } =>
1081            // module.as_str(), _ => continue }` open-coded pattern-
1082            // match — closes the last unlifted `matches!`-shaped
1083            // per-arm-hand-rolled scalar-value + arm-discriminator
1084            // pair inside `impl UpgradeFromEntry`, sibling of the
1085            // peer [`Self::validate_cleanup_singularity`] (0bc469f)
1086            // routing already lifted onto the two-arm cleanup-family
1087            // axis's per-arm arm-discriminator + `:module` projection
1088            // dispatch. The load-target `:module` scalar is projected
1089            // through the sibling [`UpgradeInstruction::declared_module`]
1090            // accessor rather than the per-arm-hand-rolled scalar-
1091            // value binding, with the
1092            // `is_load_module`-implies-`declared_module`-is-`Some`
1093            // composition pin at
1094            // [`tests::upgrade_instruction_is_load_module_implies_declared_module_is_some`]
1095            // making the `.expect(…)` structurally infallible at
1096            // build time. Every arm-family partition the three
1097            // within-entry per-instruction-class singularity gates
1098            // key off — load-family
1099            // ([`UpgradeInstruction::LoadModule`]), cleanup-family
1100            // ([`UpgradeInstruction::SoftPurge`] |
1101            // [`UpgradeInstruction::Purge`]), migration-family
1102            // ([`UpgradeInstruction::StateChange`]) — now consults
1103            // exactly one typed dispatch on the substrate primitive
1104            // (`is_load_module()` here, `is_cleanup()` at
1105            // [`Self::validate_cleanup_singularity`],
1106            // `declared_path()` at
1107            // [`Self::validate_state_change_singularity`]), so a
1108            // future sixth arm added to [`UpgradeInstruction`] (an
1109            // `AwaitReadiness` gate, a `Downgrade` reverse-axis
1110            // variant OTP's `relup` acknowledges, a `CanaryTraffic`
1111            // split-traffic variant the M4 CR materializer could
1112            // resolve per-CR — INSPIRATIONS §II.4) migrates as a
1113            // single enum-declaration edit through the derive rather
1114            // than a scattered per-consumer rewrite. Byte-identity of
1115            // this dispatch against the pre-lift match-pattern is
1116            // pinned by
1117            // [`tests::validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors`].
1118            if !instr.is_load_module() {
1119                continue;
1120            }
1121            let module = instr
1122                .declared_module()
1123                .expect("is_load_module() implies declared_module() is Some");
1124            if seen.contains(&module) {
1125                return Err(UpgradeError::DuplicateLoadModule {
1126                    from: self.prior_versao().to_string(),
1127                    module: module.to_string(),
1128                });
1129            }
1130            seen.push(module);
1131        }
1132        Ok(())
1133    }
1134
1135    /// Reject an entry whose `:instructions` list names the same script
1136    /// as the target of more than one `(:state-change …)` instruction —
1137    /// set-not-multiset on the `StateChange` axis.
1138    ///
1139    /// `StateChange` is the `gen_server:code_change/3` analog
1140    /// (INSPIRATIONS §II.4: "State migration uses
1141    /// `gen_server:code_change/3`"). The instruction folds the *old*
1142    /// state into the shape the *new* code expects — a one-shot
1143    /// transition from one declared state representation to another.
1144    /// OTP's `release_handler:install_release/1` invokes `code_change/3`
1145    /// exactly once per upgrade per `gen_server`; `systools`-generated
1146    /// `.relup` files emit at most one `code_change` per `gen_server` per
1147    /// upgrade step for this reason. A second `(:state-change "m.lisp")`
1148    /// instruction targeting the same script in one entry re-runs the
1149    /// migration fold — at best a no-op (idempotent script masking a
1150    /// typo where the author intended two distinct scripts) and at
1151    /// worst silent state corruption (non-idempotent fold double-
1152    /// applied: an `add column` migration that runs twice, an
1153    /// `increment counter` that double-bumps, a `rename field` that
1154    /// renames-then-fails the second time). Three authoring footguns
1155    /// close here:
1156    ///
1157    ///   - `((:load-module "x") (:state-change "lib/m.lisp")
1158    ///     (:state-change "lib/m.lisp"))` — the "I copy-pasted the
1159    ///     migration line twice" footgun. The second `:state-change`
1160    ///     re-runs the same fold on the already-migrated state — a
1161    ///     no-op if the script is idempotent (dead code masking the
1162    ///     duplication) or state corruption if not (the migration's
1163    ///     pre-condition no longer holds because the post-condition is
1164    ///     already in place).
1165    ///   - `((:load-module "x") (:state-change "lib/m.lisp")
1166    ///     (:state-change "lib/m.lisp") (:soft-purge "x-old"))` — the
1167    ///     "duplicate migrate masked by trailing cleanup" footgun. The
1168    ///     cleanup still fires correctly, masking the migration-side
1169    ///     duplication as a silently-passing entry.
1170    ///   - `((:load-module "x") (:state-change "lib/m1.lisp")
1171    ///     (:state-change "lib/m1.lisp"))` — the "I meant to migrate
1172    ///     two distinct modules" typo. The author intended
1173    ///     `(:state-change "lib/m1.lisp") (:state-change "lib/m2.lisp")`
1174    ///     but renamed both to `m1.lisp` (or copy-pasted the first line
1175    ///     and forgot to change the script). The migration that should
1176    ///     have folded the second module's state never runs, far from
1177    ///     the source caixa.lisp.
1178    ///
1179    /// Same within-entry exclusivity discipline as
1180    /// [`Self::validate_load_singularity`] (the per-module load-
1181    /// singularity gate it runs after) and
1182    /// [`Self::validate_cleanup_singularity`] (the per-module cleanup-
1183    /// singularity gate it runs before) on the sibling `StateChange`
1184    /// axis: each rejects an `:instructions` list whose instructions
1185    /// are individually well-shaped but jointly incoherent on a per-
1186    /// instruction-class basis (load-once per module for the load
1187    /// axis; migrate-once per script for the migration axis here;
1188    /// cleanup-once per module for the cleanup axis), at the typed
1189    /// build surface rather than as a runtime surprise. Runs *after*
1190    /// [`Self::validate_load_singularity`] so an entry like
1191    /// `((:load-module "x") (:load-module "x") (:state-change
1192    /// "lib/m.lisp") (:state-change "lib/m.lisp"))` surfaces
1193    /// `DuplicateLoadModule` first — the load axis precedes the
1194    /// migration axis in the canonical OTP sequence
1195    /// (`code:load_module/1` then `gen_server:code_change/3`) and in
1196    /// [`UpgradeInstruction`] declaration order (`LoadModule` before
1197    /// `StateChange`), so the load-side singularity is the load-
1198    /// bearing diagnostic when both fire. Runs *before*
1199    /// [`Self::validate_cleanup_singularity`] so an entry like
1200    /// `((:load-module "x") (:state-change "lib/m.lisp") (:state-change
1201    /// "lib/m.lisp") (:soft-purge "y-old") (:soft-purge "y-old"))`
1202    /// surfaces `DuplicateStateChange` first — the migration axis
1203    /// precedes the cleanup axis in the canonical OTP sequence
1204    /// (`code:code_change/3` then `code:soft_purge/1`) and in
1205    /// [`UpgradeInstruction`] declaration order (`StateChange` before
1206    /// `SoftPurge`/`Purge`).
1207    ///
1208    /// Same set-not-multiset discipline applied to every peer
1209    /// duplicate-target axis: `:children :caixa` (dbf50a9 —
1210    /// `SupervisorError::DuplicateChildCaixa`), `:membros :caixa`
1211    /// (4bb3f3d — `AplicacaoError::MembroDuplicate`), `:contratos`
1212    /// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1213    /// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1214    /// `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`),
1215    /// `:upgrade-from :from` ([`UpgradeError::DuplicateFrom`]), the
1216    /// per-module cleanup-target axis (9cedd8b —
1217    /// [`UpgradeError::DuplicateCleanup`]), and the per-module load-
1218    /// target axis (a503978 — [`UpgradeError::DuplicateLoadModule`]).
1219    /// This gate extends the discipline onto the within-entry
1220    /// `StateChange` instruction-target axis — the third within-entry
1221    /// per-instruction-class singularity, completing the OTP two-phase
1222    /// code-load + state-migration coverage triad
1223    /// (`code:load_module/1` → `gen_server:code_change/3` →
1224    /// `code:soft_purge/1`).
1225    ///
1226    /// Detection: linear scan of the instructions list collecting the
1227    /// script path from every `StateChange` encountered; on the second
1228    /// occurrence of any script the gate fires. Diagnostic-order pin:
1229    /// the first colliding occurrence surfaces, not the last — mirrors
1230    /// [`Self::validate_load_singularity`]'s and
1231    /// [`Self::validate_cleanup_singularity`]'s first-collision posture
1232    /// and every peer duplicate gate's first-collision discipline.
1233    fn validate_state_change_singularity(&self) -> Result<(), UpgradeError> {
1234        // Route the per-instruction `StateChange`-arm script-path
1235        // projection through the sibling lifted
1236        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
1237        // accessor rather than the raw
1238        // `match instr { UpgradeInstruction::StateChange { script } =>
1239        // script.as_path(), _ => continue }` open-coded pattern-match —
1240        // the third within-entry singularity gate's per-instruction
1241        // script-projection site now keys off exactly one typed
1242        // dispatch on the substrate primitive's `PathBuf`-carrying
1243        // axis, sibling to the four peer per-`UpgradeInstruction`
1244        // consumers ([`Self::validate`]'s per-`StateChange`
1245        // sandbox-path fan-out, the layout-side per-`StateChange`
1246        // script-existence fan-out at
1247        // `caixa-core/src/layout.rs:1017`, the cross-slot
1248        // [`validate_upgrade_from_against_behavior`] gate's
1249        // per-`StateChange` detection loop, the future wasm-operator's
1250        // per-`StateChange` runtime hook-dispatch) that already route
1251        // through `declared_path` / `declared_module`. Byte-equal
1252        // today (`declared_path` returns `Some(script)` iff the
1253        // instruction is [`UpgradeInstruction::StateChange`], per the
1254        // sibling `declared_path_only_for_state_change` pin), so a
1255        // duplicate `:state-change` script surfaces
1256        // `DuplicateStateChange` byte-identical to the pattern-match
1257        // shape. Same "one typed dispatch on the substrate primitive,
1258        // thin projections at each consumer" discipline the sibling
1259        // [`UpgradeInstruction::declared_module`] accessor established
1260        // (b13c4f9) on the peer `String`-carrying axis's per-variant
1261        // consumers, extended here onto the last unlifted
1262        // pattern-match on the `PathBuf`-carrying axis inside
1263        // `impl UpgradeFromEntry`.
1264        let mut seen: Vec<&std::path::Path> = Vec::new();
1265        for instr in self.instructions() {
1266            let Some(script) = instr.declared_path() else {
1267                continue;
1268            };
1269            let script = script.as_path();
1270            if seen.contains(&script) {
1271                return Err(UpgradeError::duplicate_state_change(
1272                    self.prior_versao(),
1273                    script,
1274                ));
1275            }
1276            seen.push(script);
1277        }
1278        Ok(())
1279    }
1280}
1281
1282/// Validate a whole `:upgrade-from` list: per-entry typed shape via
1283/// [`UpgradeFromEntry::validate`] *and* the cross-entry graph-edge-set
1284/// invariant — at most one `(:from <prior>)` block per parsed semver.
1285///
1286/// OTP's appup picks at most one matching block to apply to the running
1287/// release (`release_handler:install_release/1` matches the loaded
1288/// `:from` against the currently-running version and executes the
1289/// associated instruction sequence; the wasm-operator picks the matching
1290/// block at upgrade time, per `upgrade.rs` module doc). Two blocks with
1291/// the same parsed-semver `:from` are an ambiguous edge in the typed
1292/// upgrade graph — the operator can pick either set deterministically,
1293/// but each set may carry different `LoadModule | StateChange |
1294/// SoftPurge | Purge | Restart` instructions, so the *chosen* path is
1295/// non-deterministic relative to the source caixa.lisp. The author's
1296/// intent is one path per prior version; the typed graph must enforce
1297/// that shape.
1298///
1299/// Same set-not-multiset discipline already applied to every peer
1300/// typed-graph axis: `:children :caixa` (dbf50a9 —
1301/// `SupervisorError::DuplicateChildCaixa`, `child_spec.id` is required-
1302/// unique per supervisor in OTP), `:membros :caixa` (4bb3f3d —
1303/// `AplicacaoError::MembroDuplicate`), `:contratos`
1304/// (5dbcfaf — `AplicacaoError::ContratoDuplicate`), `:placement
1305/// :clusters` (c7c7799 — `AplicacaoError::PlacementClusterDuplicate`),
1306/// and `:entrada :paths` (eb3456d — `AplicacaoError::EntradaPathDuplicate`).
1307/// Each closes the same authoring footgun: a Vec authoring surface that
1308/// silently accepts duplicate entries and renders the "second wins"
1309/// (or "operator picks arbitrarily") shape downstream, far from the
1310/// source caixa.lisp.
1311///
1312/// Duplicates are detected by [`semver::Version`] equality (the
1313/// crate's `PartialEq` compares the full identity — major.minor.patch +
1314/// pre-release + build metadata — so `1.0.0` and `1.0.0-rc.1` and
1315/// `1.0.0+build1` and `1.0.0+build2` are all distinct upgrade paths).
1316/// The conservative choice mirrors what the wasm-operator's
1317/// `:from`-match dispatch can see; collapsing build metadata to catch
1318/// a wider net of duplicates is a future tightening that requires
1319/// coordinating with the operator's match step.
1320///
1321/// Per-entry shape errors fire before the duplicate gate so the
1322/// diagnostic names the malformed slot (`FromInvalid`, `EmptyScript`,
1323/// `ModuleInvalid`, …) rather than collapsing two unrelated authoring
1324/// errors into a single duplicate diagnostic. Mirrors the
1325/// `*_invalid_fires_before_duplicate_check` order pins on every peer
1326/// axis ([`crate::SupervisorSpec::validate`],
1327/// [`crate::AplicacaoSpec::validate_membros`],
1328/// [`crate::AplicacaoSpec::validate_placement`]).
1329pub fn validate_upgrade_from(entries: &[UpgradeFromEntry]) -> Result<(), UpgradeError> {
1330    use semver::Version;
1331    let mut seen: Vec<Version> = Vec::with_capacity(entries.len());
1332    for entry in entries {
1333        entry.validate()?;
1334        // `entry.validate()` accepted this `:from`, so parse cannot
1335        // fail here — the FromInvalid arm above is the only gate
1336        // and both call `Version::parse(entry.prior_versao())`.
1337        let parsed = Version::parse(entry.prior_versao()).expect(
1338            "UpgradeFromEntry::validate must accept `:from` iff Version::parse does — keep the \
1339             two gates aligned",
1340        );
1341        if seen.contains(&parsed) {
1342            return Err(UpgradeError::DuplicateFrom {
1343                from: entry.prior_versao().to_string(),
1344            });
1345        }
1346        seen.push(parsed);
1347    }
1348    Ok(())
1349}
1350
1351/// Reject `:upgrade-from` entries whose `:from` is not strictly less
1352/// than the caixa's current `:versao` (under SemVer-2 precedence — the
1353/// same ordering [`semver::Version::cmp`] implements, with build
1354/// metadata ignored per [SemVer §11][semver-11]).
1355///
1356/// The whole point of an `:upgrade-from :from "<prior>"` block is the
1357/// declarative answer to "given the wasm-operator is loading a node
1358/// running `<prior>`, how do I upgrade it to the *current* `:versao`?"
1359/// (`upgrade.rs` module doc, OTP appup `release_handler:install_release/1`
1360/// semantic). The operator's `:from`-match dispatch loads the
1361/// current `:versao` and matches the *running* version against each
1362/// entry's `:from`; an entry whose `:from >= :versao` is structurally
1363/// unreachable — the operator never runs a version greater than or
1364/// equal to the current `:versao` that it could then "upgrade *to*"
1365/// the current `:versao`. Two authoring footguns close here:
1366///
1367///   - `:from > :versao` (downgrade-shaped) — the canonical
1368///     "I copy-pasted from the next minor version and forgot to bump
1369///     `:versao`" / "I bumped `:versao` then reverted but left the
1370///     `:upgrade-from` entry behind" footgun. Until this gate landed
1371///     `(defcaixa :versao "0.1.5" :upgrade-from ((:from "0.2.0" …)))`
1372///     silently passed `feira build` and the wasm-operator's
1373///     `:from`-match dispatch would never fire on the entry — the
1374///     instructions sat dormant in the caixa.lisp forever, the
1375///     author's intent ("upgrade users coming from 0.2.0") permanently
1376///     unreached because they actually meant to bump `:versao`.
1377///
1378///   - `:from == :versao` (precedence-equal self-upgrade) — the
1379///     "I declared an upgrade from myself to myself" no-op the
1380///     operator's dispatch would either skip silently (no semantic
1381///     transition) or attempt and trivially "succeed" with no
1382///     observable state change. Includes the build-metadata-only
1383///     difference case (`:versao "0.2.0"`, `:from "0.2.0+build.1"`):
1384///     SemVer-2 precedence ignores build metadata so they compare
1385///     equal under [`semver::Version::cmp`] — the gate rejects this
1386///     even though [`UpgradeError::DuplicateFrom`] doesn't (the peer
1387///     gate uses derived `PartialEq` which keeps them distinct;
1388///     they're distinct dispatch keys but the same "from" version
1389///     for our purposes here).
1390///
1391/// Same cross-slot value-shape discipline as
1392/// [`crate::AplicacaoSpec::validate_placement`]'s strategy ↔ shard-key
1393/// partition (934bc58 — the typed partition between two declared
1394/// slots): one slot's value constrains the valid set of another's,
1395/// and the constraint is a structural property visible at validate
1396/// time. The validated set after this gate satisfies
1397/// `entry.from.parse::<Version>().unwrap() < versao.parse::<Version>().unwrap()`
1398/// for every entry, so the future operator-side hot-upgrade dispatch
1399/// step can reach for `entry.from` knowing the precedence relation
1400/// holds without re-deriving it from inline checks.
1401///
1402/// Silent-pass semantics on malformed inputs:
1403///
1404///   - When `versao` itself doesn't parse as semver, this gate
1405///     returns `Ok(())` silently — the narrower
1406///     [`crate::ManifestError::VersaoInvalid`] / [`UpgradeError::FromInvalid`]
1407///     diagnostics are the load-bearing surfaces for those failure
1408///     modes, and surfacing a `FromNotBeforeVersao` over an
1409///     unparseable `:versao` would mask the more actionable root
1410///     cause.
1411///   - Likewise, an entry whose `:from` itself doesn't parse falls
1412///     through to its narrower diagnostic surface
1413///     ([`UpgradeError::FromInvalid`]), which is expected to fire
1414///     via [`validate_upgrade_from`] *before* this gate runs at the
1415///     [`crate::LayoutInvariants`] call site.
1416///
1417/// [semver-11]: https://semver.org/#spec-item-11
1418pub fn validate_upgrade_from_against_versao(
1419    entries: &[UpgradeFromEntry],
1420    versao: &str,
1421) -> Result<(), UpgradeError> {
1422    use semver::Version;
1423    let Ok(current) = Version::parse(versao) else {
1424        // Malformed `:versao` is a separate gate (ManifestError::VersaoInvalid);
1425        // surfacing a precedence-relation diagnostic over an unparseable
1426        // top-level version would mask the more actionable root cause.
1427        return Ok(());
1428    };
1429    for entry in entries {
1430        // Per-entry shape — including a malformed `:from` — is gated
1431        // by [`validate_upgrade_from`] / [`UpgradeFromEntry::validate`]
1432        // upstream at the LayoutInvariants call site; an unparseable
1433        // `:from` here falls through silently to keep the
1434        // FromInvalid diagnostic load-bearing. Same fall-through
1435        // posture as the `versao` arm above.
1436        let Ok(prior) = Version::parse(entry.prior_versao()) else {
1437            continue;
1438        };
1439        if prior >= current {
1440            return Err(UpgradeError::FromNotBeforeVersao {
1441                from: entry.prior_versao().to_string(),
1442                versao: versao.to_string(),
1443            });
1444        }
1445    }
1446    Ok(())
1447}
1448
1449/// Reject `:upgrade-from` entries whose `:instructions` list carries any
1450/// `(:state-change <script>)` instruction unless the caixa also declares
1451/// `:behavior :on-state-change` — the runtime callback the per-version
1452/// migration script is delivered through during hot upgrade.
1453///
1454/// The module doc on [`crate::upgrade`] pins the composition verbatim:
1455/// the `:upgrade-from` slot "Composes with the `:behavior :on-state-change`
1456/// callback to deliver state migration during hot upgrades." The peer
1457/// module doc on [`crate::BehaviorSpec::on_state_change`] mirrors the
1458/// promise from the callback side: the slot is the
1459/// `gen_server:code_change/3` analog — "receives old state + version,
1460/// returns new state. Composes with the `:upgrade-from` slot declared at
1461/// the Caixa root." OTP's `release_handler:install_release/1` realizes
1462/// the composition by invoking the running `gen_server`'s
1463/// `code_change/3` callback during the appup's `code_change` /
1464/// `update, m, soft` step — the appup's instruction triggers the
1465/// callback, the callback folds the prior-version state shape into the
1466/// current-version shape, and the operator advances to the next
1467/// instruction only after the callback returns successfully. caixa
1468/// decomposes the same composition into two typed slots: the per-version
1469/// migration logic lives in the `(:state-change "lib/migrations/v01-to-v02.lisp")`
1470/// instruction's `:script` (the `:upgrade-from` author surface), and the
1471/// runtime hook the operator dispatches the migration through lives in
1472/// the `:behavior :on-state-change` callback (the `:behavior` author
1473/// surface). A `:state-change` instruction declared without the callback
1474/// is half the composition: the per-version script the author wrote has
1475/// no runtime delivery path, and the operator's hot-upgrade dispatch
1476/// reaches for `caixa.behavior.on_state_change` at the migration step,
1477/// finds `None`, and either fails the upgrade mid-flight (the
1478/// transactional rollback the module doc names — "On any failure, the
1479/// current version stays load-bearing — a typed atomic upgrade") or
1480/// silently skips the migration depending on the operator's handling of
1481/// a missing callback, both far from the source caixa.lisp.
1482///
1483/// Two authoring footguns close here:
1484///
1485///   - `(:behavior ((:on-init …)))` + `(:upgrade-from ((:from "0.1.0"
1486///     :instructions ((:load-module "x") (:state-change "lib/m.lisp")
1487///     (:soft-purge "x-old")))))` — the "I declared the migration script
1488///     but forgot the callback" footgun. The author wrote the per-version
1489///     fold against the prior state shape, the typed `:upgrade-from`
1490///     slot validated every per-instruction shape + ordering + singularity
1491///     gate, and the missing callback only surfaces at upgrade time as
1492///     either a transactional rollback to the prior version (no progress
1493///     across the upgrade) or as a silently-skipped migration that leaves
1494///     v0.2.0 code running against unmigrated v0.1.0 state (corrupted
1495///     state shape).
1496///   - `:behavior` absent entirely + `:upgrade-from` carrying any
1497///     `:state-change` — the "I added the upgrade path but never declared
1498///     `:behavior`" footgun. `:behavior` is optional at the typed root
1499///     ([`crate::Caixa::behavior: Option<BehaviorSpec>`]) so the typed
1500///     `:upgrade-from` slot validates on its own merits, but a `Caixa`
1501///     with `behavior: None` and a `:state-change` instruction is the
1502///     same missing-callback shape — the operator's dispatch can't reach
1503///     a callback that doesn't exist.
1504///
1505/// Same cross-slot composition discipline as
1506/// [`validate_upgrade_from_against_versao`] (the `:from` ↔ `:versao`
1507/// precedence gate at the peer wire-up site): one slot's value
1508/// (`:from` < `:versao` there; `:state-change` declared here) constrains
1509/// the valid set of another's (the entry must be dispatchable there; the
1510/// callback must be declared here), and the constraint is a structural
1511/// property visible at validate time. The validated set after this gate
1512/// satisfies the documented composition: every `:state-change`
1513/// instruction the operator iterates at hot-upgrade time has a
1514/// corresponding `:on-state-change` callback declared on the same caixa,
1515/// so the future wasm-operator's hot-upgrade dispatch (the OTP
1516/// `release_handler` canonical-sequence loop) can reach for
1517/// `behavior.on_state_change` at the migration step knowing the
1518/// `Option<PathBuf>` is `Some(_)` without re-deriving the precondition
1519/// from inline checks.
1520///
1521/// Diagnostic-precedence:
1522///
1523///   - Runs *after* [`UpgradeFromEntry::validate`] (per-instruction
1524///     shape + the within-entry ordering / singularity gates) and
1525///     [`validate_upgrade_from`] (the cross-entry duplicate-`:from`
1526///     gate), so a malformed `:state-change` (`EmptyScript`,
1527///     `AbsoluteScript`, `ParentEscapeScript`) or an ill-ordered entry
1528///     (`StateChangeWithoutPriorLoad`, `StateChangeAfterCleanup`) or a
1529///     duplicate `:from` (`DuplicateFrom`) surfaces its narrower
1530///     self-locating diagnostic first — the canonical "per-instr-shape +
1531///     within-entry ordering + cross-entry uniqueness before
1532///     cross-slot composition" precedence the peer
1533///     `validate_upgrade_from_against_versao` gate establishes at the
1534///     same wire-up site. Without this precedence pin a malformed
1535///     `:state-change` instruction would surface this gate's
1536///     missing-callback diagnostic over the narrower
1537///     `EmptyScript` / `StateChangeWithoutPriorLoad`, masking the
1538///     load-bearing per-instruction defect with a cross-slot composition
1539///     diagnostic.
1540///   - Within the entries, walks the list in declaration order and
1541///     surfaces the *first* `:state-change` instruction encountered —
1542///     mirrors every peer first-collision diagnostic posture on this
1543///     module (`validate_state_change_ordering` returns on the first
1544///     `StateChange` without prior load,
1545///     `validate_load_singularity` returns on the second matching
1546///     module, etc.). A future entry's later `:state-change` doesn't
1547///     surface a different diagnostic — the missing callback is the same
1548///     defect regardless of which entry's `:state-change` exposes it.
1549///
1550/// Silent-pass semantics:
1551///
1552///   - Entries carrying no `:state-change` instruction (load-only,
1553///     cleanup-only, restart-only, or empty `:instructions`) leave the
1554///     gate vacuous — no per-version migration means no callback to
1555///     dispatch through, so the absence of `:on-state-change` is
1556///     coherent. Pins the gate's identity element on the empty-set side
1557///     of the composition.
1558///   - `behavior: None` is *not* a free pass when a `:state-change`
1559///     instruction is present — the same missing-callback shape as
1560///     `behavior: Some(_)` with `on_state_change: None`. The gate reads
1561///     `behavior.and_then(BehaviorSpec::on_state_change)` so both shapes
1562///     surface the same diagnostic.
1563pub fn validate_upgrade_from_against_behavior(
1564    entries: &[UpgradeFromEntry],
1565    behavior: Option<&crate::BehaviorSpec>,
1566) -> Result<(), UpgradeError> {
1567    if behavior
1568        .and_then(crate::BehaviorSpec::on_state_change)
1569        .is_some()
1570    {
1571        return Ok(());
1572    }
1573    for entry in entries {
1574        // Route the per-instruction `StateChange`-arm script-path
1575        // projection through the sibling lifted
1576        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
1577        // accessor rather than the raw
1578        // `if let UpgradeInstruction::StateChange { script } = instr`
1579        // open-coded pattern-match — the cross-slot
1580        // `:upgrade-from ↔ :behavior` composition gate's per-instruction
1581        // script-projection site now keys off exactly one typed dispatch
1582        // on the substrate primitive's `PathBuf`-carrying axis, sibling
1583        // to the four peer per-`UpgradeInstruction` consumers
1584        // ([`UpgradeInstruction::validate`]'s per-`StateChange`
1585        // sandbox-path fan-out, the layout-side per-`StateChange`
1586        // script-existence fan-out at
1587        // [`crate::layout::StandardLayout::verify`] (caixa-core/src/layout.rs:1058),
1588        // the within-entry [`UpgradeFromEntry::validate_state_change_singularity`]
1589        // (2bf3ce5) per-`StateChange` script-projection fan-out, the
1590        // peer [`UpgradeInstruction::declared_module`] `String`-axis
1591        // per-variant unifier) that already route through
1592        // `declared_path` / `declared_module`. Byte-equal today
1593        // (`declared_path` returns `Some(script)` iff the instruction is
1594        // [`UpgradeInstruction::StateChange`], per the sibling
1595        // `declared_path_only_for_state_change` pin), so a
1596        // `:state-change`-without-`:on-state-change`-callback
1597        // composition surfaces `StateChangeWithoutOnStateChangeCallback`
1598        // byte-identical to the pattern-match shape. Fourth (and last)
1599        // per-`UpgradeInstruction`-consumer of the `PathBuf`-carrying
1600        // axis now routed through the accessor — closes the last
1601        // unlifted `if let UpgradeInstruction::StateChange { script } = instr`
1602        // site outside `impl UpgradeFromEntry`, so the peer four
1603        // consumer set named in the sibling
1604        // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
1605        // pin (caixa-core/src/upgrade.rs:4598) is now structurally
1606        // closed.
1607        for instr in entry.instructions() {
1608            if let Some(script) = instr.declared_path() {
1609                return Err(UpgradeError::state_change_without_on_state_change_callback(
1610                    entry.prior_versao(),
1611                    script,
1612                ));
1613            }
1614        }
1615    }
1616    Ok(())
1617}
1618
1619impl UpgradeInstruction {
1620    /// Kebab-case lisp form name for this instruction, used as the
1621    /// `:kind` tag in [`UpgradeError::ModuleEmpty`] /
1622    /// [`UpgradeError::ModuleInvalid`] diagnostics so the author can
1623    /// grep their caixa.lisp for `(:load-module …)` / `(:soft-purge …)`
1624    /// / `(:purge …)` and fix it in one edit. Mirrors the kebab-case
1625    /// slot tags `BehaviorError::EmptyPath` (b0c8389) and
1626    /// `UpgradeFromEntry`'s `:from` field already carry.
1627    #[must_use]
1628    const fn lisp_form(&self) -> &'static str {
1629        match self {
1630            Self::LoadModule { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
1631            Self::StateChange { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
1632            Self::SoftPurge { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
1633            Self::Purge { .. } => crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
1634            Self::Restart => crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
1635        }
1636    }
1637
1638    /// Validate the instruction's typed shape. Path existence is
1639    /// checked separately by [`crate::layout::StandardLayout`].
1640    ///
1641    /// The per-variant scalar the value-shape gates fire against is
1642    /// read through this method's two sibling accessors — the
1643    /// `String`-carrying axis via [`Self::declared_module`] (the
1644    /// `LoadModule` / `SoftPurge` / `Purge` variants unifying on their
1645    /// K8s DNS-1123-label `:module` reference) and the `PathBuf`-
1646    /// carrying axis via [`Self::declared_path`] (the `StateChange`
1647    /// variant's tatara-lisp `:script`) — rather than the per-arm
1648    /// `Self::LoadModule { module } | Self::SoftPurge { module } |
1649    /// Self::Purge { module }` pattern the module-axis previously
1650    /// open-coded and the per-arm `Self::StateChange { script }` the
1651    /// script-axis previously open-coded. Every scalar this enum
1652    /// carries now flows through one of the two `Option<&…>`
1653    /// accessors, so a future extension of either axis (a fifth
1654    /// module-bearing variant, an operator-side pre-parsed scalar
1655    /// cache the accessors materialize behind the same return
1656    /// contract, an M4 typed sub-slot the accessors could route
1657    /// alongside the existing scalar) migrates as a single edit on
1658    /// the accessor rather than a coordinated rewrite of every
1659    /// downstream value-shape gate. `Restart` (the only variant that
1660    /// carries neither scalar) falls through both `Option` checks and
1661    /// returns `Ok(())` — the terminal-fallback shape the
1662    /// [`Self::Restart`] variant doc pins.
1663    pub fn validate(&self) -> Result<(), UpgradeError> {
1664        if let Some(module) = self.declared_module() {
1665            return validate_module(self.lisp_form(), module);
1666        }
1667        if let Some(script) = self.declared_path() {
1668            // Delegate the four-arm cascade (empty / absolute /
1669            // parent-escape / non-`.lisp`-extension) to the lifted
1670            // [`crate::render::require_sandboxed_lisp_path`] helper —
1671            // same `Empty → Absolute → ParentEscape → NonLispExtension`
1672            // arm-ordering this method previously inlined verbatim,
1673            // now shared with [`crate::BehaviorSpec::validate`]'s
1674            // per-`:on-*`-callback gate so every author-supplied
1675            // tatara-lisp source path on every M2 typed slot consults
1676            // one gate, not two-and-counting verbatim copies of the
1677            // same four-arm cascade. Each closure wraps the tag in
1678            // the same `*Script` variant the original inline code
1679            // raised, so the diagnostic shape every caller depends
1680            // on (the `:state-change :script` self-locating error)
1681            // is preserved by construction. See
1682            // [`crate::render::require_sandboxed_lisp_path`] for the
1683            // smallest-scope-arm-fires-last ordering rationale.
1684            crate::render::require_sandboxed_lisp_path(
1685                script,
1686                || UpgradeError::EmptyScript,
1687                || UpgradeError::AbsoluteScript {
1688                    script: script.clone(),
1689                },
1690                || UpgradeError::ParentEscapeScript {
1691                    script: script.clone(),
1692                },
1693                || UpgradeError::NonLispExtensionScript {
1694                    script: script.clone(),
1695                },
1696            )?;
1697        }
1698        // `Restart` (the only variant with no `Option<&…>`-carrying
1699        // scalar) falls through both accessor gates and returns
1700        // `Ok(())` — the terminal-fallback shape.
1701        Ok(())
1702    }
1703
1704    /// The `:module` scalar carried by this instruction — the
1705    /// K8s DNS-1123-label OTP-appup caixa-name reference every
1706    /// [`Self::LoadModule`] / [`Self::SoftPurge`] / [`Self::Purge`]
1707    /// variant declares against, and every author expects `feira lint`
1708    /// to name verbatim in per-instruction diagnostics. Returns `None`
1709    /// on [`Self::StateChange`] (which carries a `:script` — closed by
1710    /// the sibling [`Self::declared_path`]) and on [`Self::Restart`]
1711    /// (which carries no data at all, the OTP terminal-fallback
1712    /// shape).
1713    ///
1714    /// Sibling in shape to [`Self::declared_path`] on the second and
1715    /// final scalar-carrying axis of [`UpgradeInstruction`]:
1716    /// `declared_path` closes the `PathBuf`-carrying arm
1717    /// (`StateChange`); `declared_module` closes the `String`-carrying
1718    /// arms (`LoadModule` / `SoftPurge` / `Purge`). Every scalar the
1719    /// enum carries now routes through one of the two `Option<&…>`
1720    /// accessors — a caller that doesn't care which variant declared
1721    /// the scalar reads through one `if let Some(…)` rather than a
1722    /// per-variant pattern match. The pair is the enum-variant-
1723    /// unifying peer of the per-mesh-slot-atom scalar-accessor family
1724    /// on the M3 side ([`crate::WitContract::source`] /
1725    /// [`crate::WitContract::destination`] /
1726    /// [`crate::WitContract::world_ref`] closing `:contratos`;
1727    /// [`crate::Entrada::hostname`] / [`crate::Entrada::destination`]
1728    /// closing `:entrada`; [`crate::Membro::nome`] /
1729    /// [`crate::Membro::versao_requirement`] closing `:membros`) and
1730    /// on the M2 side ([`crate::UpgradeFromEntry::prior_versao`]
1731    /// closing per-entry `:from`; the [`crate::LimitsSpec`] /
1732    /// [`crate::BehaviorSpec`] closed families; the [`crate::ChildSpec`]
1733    /// closed OTP-shape supervisor family) — those peer accessors
1734    /// return a struct field verbatim; this pair unifies enum-
1735    /// variant-carried scalars into one accessor per typed axis.
1736    ///
1737    /// Byte-for-byte from the typed variant's own `String` storage;
1738    /// no cloning, no re-parsing. A future extension of the axis (an
1739    /// M4 typed sub-slot the module string is derived from, an
1740    /// operator-side pre-parsed caixa-name cache the accessor could
1741    /// materialize behind the same `&str` return contract, a fifth
1742    /// module-bearing OTP-appup variant the enum grows) migrates as
1743    /// a single caixa-core edit rather than a coordinated rewrite
1744    /// of every downstream module-axis consumer (currently
1745    /// [`Self::validate`]'s DNS-1123-label gate through
1746    /// [`validate_module`]; extensible to future consumers on the
1747    /// same axis without further per-variant match sites).
1748    #[must_use]
1749    pub const fn declared_module(&self) -> Option<&str> {
1750        match self {
1751            Self::LoadModule { module } | Self::SoftPurge { module } | Self::Purge { module } => {
1752                Some(module.as_str())
1753            }
1754            Self::StateChange { .. } | Self::Restart => None,
1755        }
1756    }
1757
1758    /// If the instruction references an on-disk path, return it —
1759    /// used by the layout checker to verify the path resolves.
1760    ///
1761    /// Sibling on the `PathBuf`-carrying axis to [`Self::declared_module`]
1762    /// on the `String`-carrying axis: `declared_path` closes the
1763    /// `StateChange` arm's `:script`; `declared_module` closes the
1764    /// `LoadModule` / `SoftPurge` / `Purge` arms' `:module`. Together
1765    /// they route every scalar this enum carries through one of two
1766    /// `Option<&…>` accessors, so [`Self::validate`]'s value-shape
1767    /// gates dispatch on the accessor return rather than a per-variant
1768    /// pattern match on the enum shape itself.
1769    ///
1770    /// Four per-`UpgradeInstruction` consumers now key off this
1771    /// accessor's `PathBuf`-carrying axis:
1772    /// [`Self::validate`]'s per-`StateChange` sandbox-path fan-out,
1773    /// [`crate::layout::StandardLayout::verify`]'s per-`StateChange`
1774    /// script-existence fan-out at `caixa-core/src/layout.rs:1058`, the
1775    /// within-entry
1776    /// [`UpgradeFromEntry::validate_state_change_singularity`] (2bf3ce5)
1777    /// per-`StateChange` script-projection fan-out, and the cross-slot
1778    /// [`validate_upgrade_from_against_behavior`] `:upgrade-from ↔
1779    /// :behavior` composition gate's per-`StateChange` detection loop
1780    /// — every downstream consumer of the `PathBuf`-carrying axis
1781    /// reaches through this one dispatch, so a future accessor
1782    /// extension (an M4 typed sub-slot the script path is derived from,
1783    /// an operator-side pre-resolved-path cache the accessor
1784    /// materializes behind the same `Option<&PathBuf>` return contract,
1785    /// a fifth `PathBuf`-bearing OTP-appup variant the enum grows)
1786    /// migrates as a single caixa-core edit rather than a coordinated
1787    /// rewrite of four call sites.
1788    #[must_use]
1789    pub const fn declared_path(&self) -> Option<&PathBuf> {
1790        match self {
1791            Self::StateChange { script } => Some(script),
1792            _ => None,
1793        }
1794    }
1795
1796    /// Substrate-canonical per-`UpgradeInstruction` OTP-appup cleanup-
1797    /// family arm-discriminator predicate every within-entry cross-
1798    /// instruction cleanup-facing gate keys off — true iff `self` is
1799    /// [`Self::SoftPurge`] (`code:soft_purge/1` analog: drain the
1800    /// named module until no process is running it, then GC) or
1801    /// [`Self::Purge`] (`code:purge/1` analog: discard the named
1802    /// module immediately, without waiting for drain), the two OTP
1803    /// two-phase-code-load cleanup arms the closed-set enum's
1804    /// non-terminal / non-migration / non-load variants exhaust.
1805    /// Every non-cleanup arm ([`Self::LoadModule`] on the paired
1806    /// two-phase-load half, [`Self::StateChange`] on the
1807    /// `gen_server:code_change/3`-analog migration axis,
1808    /// [`Self::Restart`] on the OTP terminal-fallback shape)
1809    /// returns `false`.
1810    ///
1811    /// Prior to this lift the `Self::SoftPurge { module } |
1812    /// Self::Purge { module }` two-arm cleanup-family pattern-
1813    /// match sat inline at three within-entry cross-instruction
1814    /// gate sites, each hand-rolling its own copy of the union
1815    /// with no compile-time link back to the substrate primitive's
1816    /// closed-set arm-family: [`UpgradeFromEntry::validate_purge_ordering`]
1817    /// at caixa-core/src/upgrade.rs:570 (guarded arm firing
1818    /// [`UpgradeError::PurgeWithoutPriorLoad`] on any cleanup
1819    /// arriving before a preceding [`Self::LoadModule`]),
1820    /// [`UpgradeFromEntry::validate_state_change_before_cleanup`]
1821    /// at caixa-core/src/upgrade.rs:689 (sticky-once latch
1822    /// recording the first-encountered cleanup so a subsequent
1823    /// [`Self::StateChange`] fires [`UpgradeError::StateChangeAfterCleanup`]),
1824    /// and [`UpgradeFromEntry::validate_cleanup_singularity`] at
1825    /// caixa-core/src/upgrade.rs:800 (per-module cleanup-target
1826    /// dedup ejecting [`UpgradeError::DuplicateCleanup`] on the
1827    /// second cleanup targeting the same `:module`). Three open-
1828    /// coded per-arm-union pattern-matches that expressed no
1829    /// compile-time link back to the substrate primitive. A future
1830    /// fifth cleanup-shaped variant (a `Discard` variant the
1831    /// `code:delete/1` peer inspires that folds under the same
1832    /// two-phase-load cleanup partition, an M4 `SoftPurge` split
1833    /// into `SoftPurgeCoop` / `SoftPurgeForce` peers as the drain-
1834    /// cool-down policy grows a two-arm shape, an operator-side
1835    /// pre-resolved cleanup-decision cache the predicate could
1836    /// route through the same `bool` return contract) would have
1837    /// had to be threaded through every open-coded per-arm-union
1838    /// pattern-match in lockstep or one gate would silently
1839    /// classify the new arm outside the cleanup family while the
1840    /// peer gates classified it in (or vice versa) — a
1841    /// classification split across the three within-entry cross-
1842    /// instruction gates at build time that lands far from the
1843    /// source [`UpgradeInstruction`] declaration with no field
1844    /// naming which gate carries the drifted arm-set. Lifting the
1845    /// resolution to a typed predicate on the substrate primitive
1846    /// means every downstream cleanup-facing consumer of the
1847    /// [`UpgradeInstruction`] closed-set enum reaches for exactly
1848    /// one typed dispatch — the resolver's arm-set migrates as a
1849    /// unit on any future arm addition composing under this
1850    /// predicate's `||` chain.
1851    ///
1852    /// Sibling in shape to the peer [`gen_platform::IsVariant`]-
1853    /// derive-generated [`Self::is_restart`] terminal-fallback
1854    /// arm-discriminator predicate on the same closed-set
1855    /// [`UpgradeInstruction`] enum (each names an OTP-appup arm-
1856    /// family partition as one typed dispatch on the substrate
1857    /// primitive; `is_restart` on the single-arm terminal-
1858    /// fallback family, `is_cleanup` on the two-arm cleanup
1859    /// family), extended here from the single-arm case onto the
1860    /// two-arm arm-family union case. Composes through the
1861    /// [`gen_platform::IsVariant`]-derive-generated
1862    /// [`Self::is_soft_purge`] / [`Self::is_purge`] per-variant
1863    /// predicates rather than an open-coded raw `matches!`
1864    /// pattern-match, so a future rebrand on either underlying
1865    /// per-arm classifier flows through this predicate's one
1866    /// body without a coordinated per-consumer rewrite across
1867    /// the three within-entry cross-instruction gates that route
1868    /// through it. Peer of the sibling per-`:contratos`
1869    /// shape-family union predicates [`crate::WitContract::is_http`] /
1870    /// [`crate::WitContract::is_pubsub`] / [`crate::WitContract::is_store`]
1871    /// on the M3 mesh-slot per-`:wit` world-ref axis (each unions a
1872    /// per-shape WIT-prefix rule the substrate primitive's arm-
1873    /// family partition names as one typed dispatch) — the same
1874    /// "one typed dispatch on the substrate primitive, thin
1875    /// projections at each consumer" discipline extended onto the
1876    /// M2 `:upgrade-from :instructions` per-`UpgradeInstruction`
1877    /// cleanup-family axis.
1878    ///
1879    /// The name `is_cleanup` maps directly onto the canonical
1880    /// OTP-appup vocabulary (INSPIRATIONS §II.4 verbatim: "2.
1881    /// `code:soft_purge/1` — wait until no process is running v1,
1882    /// then discard. (`code:purge/1` kills v1 immediately if you
1883    /// don't care.)" — the two `code:*_purge/1` operations are
1884    /// the two-phase-load contract's cleanup half, paired under
1885    /// one concept), and the peer [`Self::validate_cleanup_singularity`]
1886    /// / [`UpgradeError::DuplicateCleanup`] / [`UpgradeError::PurgeWithoutPriorLoad`]
1887    /// / [`UpgradeError::StateChangeAfterCleanup`] surface already
1888    /// reaches for the same "cleanup" vocabulary in identifier +
1889    /// diagnostic form.
1890    #[must_use]
1891    pub const fn is_cleanup(&self) -> bool {
1892        self.is_soft_purge() || self.is_purge()
1893    }
1894}
1895
1896/// Reject upgrade instruction `:module` values that aren't K8s
1897/// DNS-1123 labels. Thin wrapper around
1898/// [`crate::render::is_dns_1123_label`] that maps the shared
1899/// parser-shaped reason into the kind-tagged
1900/// [`UpgradeError::ModuleEmpty`] / [`UpgradeError::ModuleInvalid`]
1901/// diagnostics, so the author can grep their caixa.lisp for the
1902/// offending `(:<kind> <module>)` form and fix it in one edit.
1903///
1904/// The contract — the same DNS-1123 label rule the K8s apiserver
1905/// enforces on every `metadata.name` / Service name / label value the
1906/// module name lands in. Each upgrade instruction's `:module` is a
1907/// reference to a caixa name (the wasm-engine resolves it through the
1908/// same `ComputeUnit` registry the operator manages), so the value must
1909/// match every downstream apiserver-side schema: the per-Servico
1910/// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` the operator
1911/// creates, the `LABEL_PROGRAM` label value the wasm-engine matches
1912/// against the loaded-module table at hot-upgrade dispatch, and the
1913/// future `:upgrade-from`-driven `app-operator` rolling-load CR's
1914/// per-module reference axis. Same trajectory as `:children :caixa`
1915/// (31bfa43), `:membros :caixa` (3f9d7a0), and `:placement :clusters`
1916/// (6cbb900) onto the fourth DNS-1123-label-shaped identifier axis —
1917/// appup's `LoadModule | SoftPurge | Purge` `:module` references.
1918///
1919/// Empty input is rejected via the narrower [`UpgradeError::ModuleEmpty`]
1920/// variant before this predicate is consulted, mirroring
1921/// `validate_membro_caixa`'s empty-first cascade.
1922fn validate_module(kind: &'static str, module: &str) -> Result<(), UpgradeError> {
1923    // Routes through the shared
1924    // [`crate::render::require_valid_dns_1123_label`] gate the peer
1925    // name axes each land on. The `kind: &'static str` field flows
1926    // through both error variants so the diagnostic names which
1927    // per-instruction slot (`LoadModule` / `SoftPurge` / `Purge`) the
1928    // offending value came from.
1929    crate::render::require_valid_dns_1123_label(
1930        module,
1931        || UpgradeError::ModuleEmpty { kind },
1932        |reason| UpgradeError::ModuleInvalid {
1933            kind,
1934            module: module.to_string(),
1935            reason,
1936        },
1937    )
1938}
1939
1940#[derive(Debug, Error, PartialEq, Eq)]
1941pub enum UpgradeError {
1942    #[error(
1943        ":upgrade-from :from {from:?} is not a valid SemVer-2 version: {reason} (the substrate \
1944         consumes this string as `semver::Version` — three-part `MAJOR.MINOR.PATCH` with optional \
1945         `-prerelease` and `+build`, the same shape every top-level `:versao` carries — across \
1946         every artifact derived from `:from`: the wasm-operator's `:from`-match dispatch loads \
1947         the running version through `semver::Version::parse` and matches it against each entry's \
1948         `:from`, so a malformed `:from` is structurally unreachable at dispatch time; use a \
1949         SemVer-2 literal like `\"0.1.0\"`, `\"0.2.0-rc.1\"`, or `\"1.0.0+build.42\"` — not a \
1950         git-tag-shape like `\"v0.1.0\"`, a docker-tag-shape like `\"latest\"`, a \
1951         requirement-shape like `\"^0.1\"`, or a four-part `\"0.1.0.0\"`)"
1952    )]
1953    FromInvalid { from: String, reason: String },
1954    #[error(
1955        "upgrade instruction `{kind}` :module is empty (every appup module reference \
1956         must name a caixa; use a non-empty caixa name like `\"hello-rio\"` or omit \
1957         the instruction entirely)"
1958    )]
1959    ModuleEmpty { kind: &'static str },
1960    #[error(
1961        "upgrade instruction `{kind}` :module {module:?} is not a valid DNS-1123 label: \
1962         {reason} (every appup module reference resolves to a caixa name, which lands \
1963         verbatim as a K8s `metadata.name` on the per-Servico ComputeUnit the operator \
1964         creates, the `LABEL_PROGRAM` label value the wasm-engine matches at hot-upgrade \
1965         dispatch, and every future `app-operator` rolling-load CR's per-module reference \
1966         axis; use a lowercase alphanumeric + hyphen identifier like `\"hello-rio\"` or \
1967         `\"cache-v2\"`)"
1968    )]
1969    ModuleInvalid {
1970        kind: &'static str,
1971        module: String,
1972        reason: String,
1973    },
1974    #[error("instruction's :script is empty")]
1975    EmptyScript,
1976    #[error(
1977        "instruction's :script {} is absolute — upgrade scripts must be relative to the caixa \
1978         root (Path::join would otherwise escape the project sandbox)",
1979        script.display()
1980    )]
1981    AbsoluteScript { script: PathBuf },
1982    #[error(
1983        "instruction's :script {} contains a `..` component — upgrade scripts must not traverse \
1984         above the caixa root",
1985        script.display()
1986    )]
1987    ParentEscapeScript { script: PathBuf },
1988    #[error(
1989        ":upgrade-from (:state-change {}) does not terminate in the `.lisp` extension — the M2.5 \
1990         wasm-engine instantiator reads every migration script as tatara-lisp source through \
1991         `tatara_lisp::read` at hot-upgrade migration time (the same downstream consumer the \
1992         peer `:behavior :on-*` axis routes through at instance-start time, c97815a), so any \
1993         other extension (`.txt`, `.rs`, `.lisp.bak`) or no-extension shape is structurally a \
1994         parser error far from the source caixa.lisp, with no field naming the offending \
1995         `(:state-change …)` instruction. Pin a relative path under the caixa root whose \
1996         terminating extension is lowercase-`.lisp` (e.g. `\"lib/migrations.lisp\"`, \
1997         `\"lib/migrations/v01-to-v02.lisp\"`).",
1998        script.display()
1999    )]
2000    NonLispExtensionScript { script: PathBuf },
2001    #[error(
2002        ":upgrade-from carries more than one `(:from {from:?})` entry — OTP appup picks at most \
2003         one matching block per running version (`release_handler:install_release/1` dispatches \
2004         on the loaded `:from` against the currently-running release), so two entries with the \
2005         same parsed semver are an ambiguous edge in the typed upgrade graph (the operator would \
2006         pick either set non-deterministically). Author one path per prior version; if two \
2007         distinct instruction sequences are needed, fold them into one ordered list under the \
2008         single matching `(:from {from:?} :instructions (…))` block."
2009    )]
2010    DuplicateFrom { from: String },
2011    #[error(
2012        ":upgrade-from `(:from {from:?})` is not strictly less than the caixa's current \
2013         `:versao {versao:?}` under SemVer-2 precedence — an upgrade block whose `:from` is \
2014         greater than or equal to the caixa's own version is structurally unreachable \
2015         (the wasm-operator's `:from`-match dispatch loads the current `:versao` and matches \
2016         the running version against each entry's `:from`; an entry whose `:from >= :versao` \
2017         is never reached because the operator never runs a version greater than or equal to \
2018         the current one that it could then upgrade *to* the current one). Bump the caixa's \
2019         `:versao` past {from:?} (the typical fix — you added the entry intending to upgrade \
2020         *to* a new version but forgot to bump `:versao`), drop the entry (if it's a stale \
2021         reference left over from a reverted `:versao` bump), or correct `:from` to a prior \
2022         version (if it's a typo). Pre-release values like `\"0.2.0-rc.1\"` are strictly less \
2023         than the corresponding release `\"0.2.0\"` under SemVer §11 precedence; build-metadata \
2024         values like `\"0.2.0+build.1\"` are equal to `\"0.2.0\"` under precedence and rejected \
2025         here as a self-upgrade no-op."
2026    )]
2027    FromNotBeforeVersao { from: String, versao: String },
2028    #[error(
2029        ":upgrade-from `(:from {from:?})` :instructions list violates the `(:restart)` \
2030         exclusivity invariant — an entry containing `(:restart)` must contain exactly one \
2031         `(:restart)` and nothing else (found {restart_count} `(:restart)` plus other \
2032         instruction(s): {other_kinds:?}). Per the UpgradeInstruction::Restart doc comment, \
2033         `(:restart)` is the fallback for an entry whose typed upgrade is impossible (wasm \
2034         component-model world incompatibility, irreversible state shape change), and the \
2035         fallback is terminal by construction (the operator restarts the pod and the new \
2036         version comes up fresh). Mixing the fallback with the typed sequence is dead code \
2037         in both directions: if the typed instructions would succeed, `(:restart)` is \
2038         unreached; if they wouldn't, the typed instructions are dead because the operator \
2039         restarts anyway. Author *either* a typed sequence (`(:load-module …) \
2040         (:state-change …) (:soft-purge …)`) *or* a single `((:restart))` — never both, \
2041         never repeated. If two distinct upgrade strategies are needed for the same prior \
2042         version, that is itself a typed-graph ambiguity (the operator's `:from`-match \
2043         dispatch picks exactly one block per running version) — keep the typed sequence; \
2044         the fallback restart is what the operator does on any typed-sequence failure \
2045         already."
2046    )]
2047    RestartNotExclusive {
2048        from: String,
2049        restart_count: usize,
2050        other_kinds: Vec<&'static str>,
2051    },
2052    #[error(
2053        ":upgrade-from `(:from {from:?})` runs `(:state-change {})` before any \
2054         `(:load-module …)` in its :instructions list — a state migration is the \
2055         gen_server:code_change/3 analog and must run in the context of the newly-loaded \
2056         code, but the operator executes instructions in declared order, so this migration \
2057         runs while the only resident version is still the prior one (which expects the \
2058         pre-migration state shape). Load the new module first: author the canonical \
2059         `(:load-module …) (:state-change {}) (:soft-purge …)` order so the new code is \
2060         resident before its state migration runs.",
2061        script.display(),
2062        script.display()
2063    )]
2064    StateChangeWithoutPriorLoad { from: String, script: PathBuf },
2065    #[error(
2066        ":upgrade-from `(:from {from:?})` runs `({kind} {module:?})` before any \
2067         `(:load-module …)` in its :instructions list — `:soft-purge` and `:purge` are the \
2068         code:soft_purge/1 / code:purge/1 analogs and must run after the new code is \
2069         resident alongside the old (OTP's two-phase code load: `code:load_module/1` \
2070         then `code:soft_purge/1`), but the operator executes instructions in declared \
2071         order, so this cleanup runs while the only resident version is still the same \
2072         old code (`:soft-purge` drains it to nothing; `:purge` discards it outright \
2073         mid-request), leaving no replacement to route in-flight or future requests \
2074         to. Load the new module first: author the canonical `(:load-module …) \
2075         (:state-change …) ({kind} {module:?})` order so the new code is resident \
2076         before the old code is drained or discarded."
2077    )]
2078    PurgeWithoutPriorLoad {
2079        from: String,
2080        kind: &'static str,
2081        module: String,
2082    },
2083    #[error(
2084        ":upgrade-from `(:from {from:?})` :instructions list targets module {module:?} with \
2085         more than one cleanup instruction ({kinds:?}) — `:soft-purge` and `:purge` are the \
2086         code:soft_purge/1 / code:purge/1 analogs (INSPIRATIONS §II.4: \"`code:soft_purge/1` — \
2087         wait until no process is running v1, then discard. (`code:purge/1` kills v1 immediately \
2088         if you don't care.)\"), and each module's old version is cleaned up by exactly one of \
2089         them: either drain-then-discard (`:soft-purge`) or immediate-discard (`:purge`), never \
2090         both, never repeated. systools-generated `.relup` files emit at most one purge per \
2091         module for this reason. A second cleanup on the same module is at best redundant (the \
2092         module is already gone after the first cleanup, so the second is a no-op or undefined \
2093         depending on the operator's handling of a non-resident-module purge request) and at \
2094         worst incoherent (mixing drain and discard semantics on one module suggests the author \
2095         wanted a fallback, but the operator runs declared instructions unconditionally — \
2096         fallback on cleanup failure is the operator's job, not authored into the entry). \
2097         Author one cleanup per module: prefer `(:soft-purge {module:?})` (waits for in-flight \
2098         callers to drain before GC); fall back to `(:purge {module:?})` only when the drain \
2099         can't complete (cron / oneShot / stuck callers). If two distinct old versions need \
2100         cleanup, name them distinctly (e.g. `(:soft-purge {module:?}) (:soft-purge \"…-older\")`)."
2101    )]
2102    DuplicateCleanup {
2103        from: String,
2104        module: String,
2105        kinds: Vec<&'static str>,
2106    },
2107    #[error(
2108        ":upgrade-from `(:from {from:?})` :instructions list loads module {module:?} more than \
2109         once — `:load-module` is the code:load_module/1 analog (INSPIRATIONS §II.4: \"1. \
2110         `code:load_module/1` — load v2 alongside v1; new code is 'current', old code is \
2111         'old'.\"), and the instruction binds the named wasm component once: the operator's \
2112         dispatch table reads the module name and brings up the corresponding component \
2113         alongside the running version. systools-generated `.relup` files emit at most one \
2114         `load_module` per module per upgrade step for this reason. A second `(:load-module \
2115         {module:?})` instruction has no observable semantic relative to the first (the \
2116         component is already resident) — either dead code (copy-pasted load line) or a typo \
2117         masking a distinct module the author intended to load alongside (renamed both to \
2118         {module:?} by mistake), leaving the second module silently absent from the entry. \
2119         Author one `(:load-module {module:?})` per old module per entry; if two distinct old \
2120         versions need loading alongside the running one, name them distinctly (e.g. \
2121         `(:load-module {module:?}) (:load-module \"…-v2\")`)."
2122    )]
2123    DuplicateLoadModule { from: String, module: String },
2124    #[error(
2125        ":upgrade-from `(:from {from:?})` :instructions list runs state migration {} more than \
2126         once — `:state-change` is the gen_server:code_change/3 analog (INSPIRATIONS §II.4: \
2127         \"State migration uses gen_server:code_change/3\"), and the script folds the prior-version \
2128         state shape into the current-version shape: a one-shot transition, not a step that \
2129         composes with itself. systools-generated `.relup` files emit at most one `code_change` \
2130         per gen_server per upgrade step for this reason; OTP's release_handler invokes the \
2131         callback exactly once. A second `(:state-change {})` instruction re-runs the same fold on \
2132         the already-migrated state — at best a no-op (idempotent script masking a typo where the \
2133         author intended two distinct migration scripts) and at worst silent state corruption \
2134         (non-idempotent fold double-applied: an `add column` that runs twice, an `increment \
2135         counter` that double-bumps, a `rename field` that renames-then-fails the second time). \
2136         Author one `(:state-change {})` per migration script per entry; if two distinct state \
2137         transitions are needed (e.g. one module's schema *and* another module's projection), \
2138         name them distinctly (e.g. `(:state-change {}) (:state-change \"lib/migrations/v01-to-v02-projection.lisp\")`).",
2139        script.display(),
2140        script.display(),
2141        script.display(),
2142        script.display()
2143    )]
2144    DuplicateStateChange { from: String, script: PathBuf },
2145    #[error(
2146        ":upgrade-from `(:from {from:?})` runs `(:state-change {})` after `({prior_cleanup_kind} \
2147         {prior_cleanup_module:?})` in its :instructions list — `:state-change` is the \
2148         gen_server:code_change/3 analog and folds the prior-version state shape into the \
2149         current shape, but the prior version's state only exists while the prior code is \
2150         still resident; `:soft-purge` and `:purge` are the code:soft_purge/1 / code:purge/1 \
2151         analogs and drain or discard that prior code. The operator executes instructions in \
2152         declared order, so a cleanup ahead of a state-change has already drained the prior \
2153         module to nothing (`:soft-purge`) or discarded it mid-request (`:purge`) by the time \
2154         the migration script runs, leaving the script either no-op (no prior-version state \
2155         left to fold) or crashing (`code_change/3` invoked on an unloaded version). The OTP \
2156         canonical sequence is `code:load_module/1` → `gen_server:code_change/3` → \
2157         `code:soft_purge/1`; the appup cookbook's recommended pattern is `[{{load_module, m}}, \
2158         {{update, m, soft}}, {{soft_purge, m}}]` with the migration-triggering `update` \
2159         strictly between load and cleanup. Author the canonical `(:load-module …) \
2160         (:state-change {}) ({prior_cleanup_kind} {prior_cleanup_module:?})` order so the \
2161         migration runs against the prior-version state before the cleanup drains it.",
2162        script.display(),
2163        script.display()
2164    )]
2165    StateChangeAfterCleanup {
2166        from: String,
2167        script: PathBuf,
2168        prior_cleanup_kind: &'static str,
2169        prior_cleanup_module: String,
2170    },
2171    #[error(
2172        ":upgrade-from `(:from {from:?})` declares `(:state-change {})` but the caixa does not \
2173         declare `:behavior :on-state-change` — the per-version migration script is the \
2174         gen_server:code_change/3 analog and the runtime hook it is delivered through during \
2175         hot upgrade is the `:on-state-change` callback. OTP's release_handler:install_release/1 \
2176         realizes the composition by invoking the running gen_server's code_change/3 callback \
2177         during the appup's `code_change` / `update, m, soft` step; caixa decomposes the same \
2178         composition into two typed slots, the per-version migration logic in this \
2179         `(:state-change …)` instruction's `:script` and the runtime dispatch hook in the \
2180         `:behavior :on-state-change` callback (the upgrade.rs module doc pins the composition \
2181         verbatim: \"Composes with the `:behavior :on-state-change` callback to deliver state \
2182         migration during hot upgrades\"). The missing callback leaves the per-version script \
2183         with no runtime delivery path: the operator's hot-upgrade dispatch reaches for the \
2184         callback at the migration step, finds it absent, and either fails the upgrade \
2185         mid-flight (the transactional rollback the module doc names — \"On any failure, the \
2186         current version stays load-bearing\") or silently skips the migration leaving the \
2187         new code running against unmigrated prior-version state. Add the callback: \
2188         `(:behavior ((:on-state-change \"lib/migrations.lisp\") …))` (the runtime delivery \
2189         path) alongside the existing `(:state-change {})` instruction (the per-version \
2190         script). If the upgrade truly carries no state migration, drop the `(:state-change \
2191         …)` instruction from the entry (a metadata-only upgrade — load + cleanup, no \
2192         migration — is the canonical shape).",
2193        script.display(),
2194        script.display()
2195    )]
2196    StateChangeWithoutOnStateChangeCallback { from: String, script: PathBuf },
2197}
2198
2199// Fold the three `UpgradeError::{StateChangeWithoutPriorLoad,
2200// DuplicateStateChange, StateChangeWithoutOnStateChangeCallback}
2201// { from: <prior-versao>.to_string(), script: <script>.to_path_buf() }`
2202// two-slot struct-variant wire-up sites at
2203// [`UpgradeFromEntry::validate_state_change_ordering`] (`self.prior_versao()`
2204// / `script` from `instr.declared_path()`),
2205// [`UpgradeFromEntry::validate_state_change_uniqueness`]
2206// (`self.prior_versao()` / `script.as_path()` from
2207// `instr.declared_path()`), and
2208// [`validate_state_change_on_state_change_callback`] (`entry.prior_versao()`
2209// / `script` from `instr.declared_path()`) onto one substrate primitive
2210// per typed variant — the paired `{ from: String, script: PathBuf }`
2211// two-slot sibling on [`UpgradeError`] of the peer
2212// [`crate::supervisor::supervisor_caixa_only_ctors!`] (db09650, 3
2213// variants on `{ caixa: String }`) on the sibling `SupervisorError`
2214// envelope, the peer [`crate::aplicacao::contrato_empty_pair_ctors!`]
2215// (8580068, 4 variants on `{ de, para }`),
2216// [`crate::aplicacao::contrato_target_ctors!`] (14b81d5, 2 variants on
2217// `{ de, para, wit, expected }`),
2218// [`crate::aplicacao::aplicacao_field_reason_ctors!`] (981060b, 7
2219// variants on `{ <field>: String, reason: String }`), and
2220// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] (14e13f1, 3
2221// variants on `{ de, para, <field>: String, reason: String }`) on the
2222// sibling `AplicacaoError` envelopes, and the peer
2223// [`crate::layout::layout_violation_ctors!`] (131ca0d, 16 variants on
2224// `{ caixa, issue }`), [`crate::layout::layout_slot_kind_ctors!`]
2225// (0419438, 4 variants on `{ caixa, kind, slots }`),
2226// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on
2227// `{ kind, path }`), and [`crate::layout::layout_nome_only_ctors!`]
2228// (3fe3dd7, 6 variants on `<Variant>(String)`) on the sibling
2229// `LayoutError` envelopes, plus the peer
2230// [`crate::limits::limits_codec_value_only_ctors!`] /
2231// [`crate::limits::limits_codec_value_byte_ctors!`] /
2232// [`crate::limits::limits_codec_value_char_ctors!`] (81c856c, 12 codec
2233// wire-ups) on the sibling `LimitsError` envelopes.
2234//
2235// Each of the three wire-up sites on this shape opens the identical
2236// `UpgradeError::<Variant> { from: <prior-versao>.to_string(),
2237// script: <script>.to_path_buf() }` struct-literal against a local
2238// `prior_versao()` and `declared_path()` accessor pair — the exact
2239// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
2240// names as a bug, on the same altitude the peer `SupervisorError` /
2241// `AplicacaoError` / `LayoutError` / `LimitsError` families each
2242// closed on their sibling envelopes. The three variants share one
2243// `{ from: String, script: PathBuf }` shape, so the fold routes each
2244// wire-up site through one dispatch per typed variant.
2245//
2246// The macro below generates one `#[must_use]` inherent constructor per
2247// variant of shape `fn <ctor>(from: &str, script: &std::path::Path) ->
2248// Self`, so every wire-up site collapses onto one dispatch:
2249// `UpgradeError::<ctor>(<prior-versao>, <script>)`, byte-equal to the
2250// pre-lift struct-literal on the same `(&str, &Path)` fixture. The
2251// uniform two-field construction (`from.to_string()` /
2252// `script.to_path_buf()`) is spelled once — inside the macro — rather
2253// than at every wire-up site. The `&Path` parameter accepts both
2254// `&Path` (from `script.as_path()` at the uniqueness gate) and
2255// `&PathBuf` (from `instr.declared_path()` at the ordering /
2256// callback-declaration gates, via Deref coercion), so every existing
2257// wire-up threads through the ctor without a pre-conversion.
2258//
2259// Every future consumer that wants to construct one of these three
2260// variants outside the three in-crate `UpgradeFromEntry` /
2261// `validate_state_change_on_state_change_callback` gates (a deferred
2262// wasm-operator's `install_release/1` per-entry ordering / uniqueness
2263// re-checker at hot-upgrade dispatch time, a future
2264// `feira validate --upgrade-from` per-caixa admission verb re-checking
2265// the three axes, a per-`Caixa` overlay resolver rejecting an
2266// ordering / uniqueness / callback-declaration invariant against a
2267// cluster-local snapshot) now reaches each variant through one call
2268// rather than re-inlining the three-line struct-literal in lockstep
2269// with the three in-crate wire-up sites.
2270macro_rules! upgrade_from_script_ctors {
2271    ($($ctor:ident => $variant:ident),* $(,)?) => {
2272        impl UpgradeError {
2273            $(
2274                #[doc = concat!(
2275                    "Construct an [`UpgradeError::",
2276                    stringify!($variant),
2277                    "`] naming the offending `(:from <prior-versao>)` and ",
2278                    "`(:state-change <script>)` pair. Folds the uniform ",
2279                    "`Self::",
2280                    stringify!($variant),
2281                    " { from: from.to_string(), script: script.to_path_buf() }` ",
2282                    "two-field struct-literal onto one substrate primitive so ",
2283                    "every wire-up on this variant reads through one dispatch ",
2284                    "rather than the pre-lift three-line open-coded block. The ",
2285                    "`from` string threads verbatim from ",
2286                    "[`UpgradeFromEntry::prior_versao`] and the `script` path ",
2287                    "from [`UpgradeInstruction::declared_path`] at the call site."
2288                )]
2289                #[must_use]
2290                pub fn $ctor(from: &str, script: &std::path::Path) -> Self {
2291                    Self::$variant {
2292                        from: from.to_string(),
2293                        script: script.to_path_buf(),
2294                    }
2295                }
2296            )*
2297        }
2298    };
2299}
2300
2301upgrade_from_script_ctors! {
2302    state_change_without_prior_load => StateChangeWithoutPriorLoad,
2303    duplicate_state_change => DuplicateStateChange,
2304    state_change_without_on_state_change_callback => StateChangeWithoutOnStateChangeCallback,
2305}
2306
2307#[cfg(test)]
2308mod tests {
2309    use std::path::Path;
2310
2311    use super::*;
2312
2313    fn entry(from: &str, instrs: Vec<UpgradeInstruction>) -> UpgradeFromEntry {
2314        UpgradeFromEntry {
2315            from: from.into(),
2316            instructions: instrs,
2317        }
2318    }
2319
2320    #[test]
2321    fn upgrade_from_entry_prior_versao_accessor_is_const_fn() {
2322        // Fail-before-pass-after pin on
2323        // [`UpgradeFromEntry::prior_versao`]'s `const`-eval-surface
2324        // posture. The accessor projects the per-`:upgrade-from :from`
2325        // [`String`] storage through the `pub const fn`
2326        // [`String::as_str`] (const-stable since Rust 1.87, well within
2327        // the workspace MSRV) — any future accidental downgrade to
2328        // non-`const` fails `prior_versao_via_const_fn` at caixa-core
2329        // build time with E0015 (`cannot call non-const method`),
2330        // strictly stronger than a runtime `assert!`. Sibling of the
2331        // peer M2/M3 slot family pins on the sibling `const`-eval-
2332        // surface passes ([`crate::Caixa::nome`] /
2333        // [`crate::Caixa::versao`], [`crate::CaixaVersion::as_str`],
2334        // [`crate::aplicacao::Membro::nome`] /
2335        // [`crate::aplicacao::Membro::versao_requirement`],
2336        // [`crate::aplicacao::Entrada::hostname`] /
2337        // [`crate::aplicacao::Entrada::destination`],
2338        // [`crate::supervisor::ChildSpec::nome`] /
2339        // [`crate::supervisor::ChildSpec::versao_requirement`],
2340        // [`crate::dep::Dep::nome`] /
2341        // [`crate::dep::Dep::versao_requirement`], and the
2342        // per-`:contratos`
2343        // [`crate::aplicacao::WitContract::source`] /
2344        // [`crate::aplicacao::WitContract::destination`] /
2345        // [`crate::aplicacao::WitContract::world_ref`] trio the
2346        // sibling pin at 279823b already anchors).
2347        const fn prior_versao_via_const_fn(e: &UpgradeFromEntry) -> &str {
2348            e.prior_versao()
2349        }
2350        for from in ["0.1.0", "1.2.3-alpha.1", "0.0.0"] {
2351            let e = entry(from, vec![]);
2352            assert_eq!(prior_versao_via_const_fn(&e), e.prior_versao());
2353            assert_eq!(e.prior_versao(), from);
2354        }
2355    }
2356
2357    #[test]
2358    fn upgrade_from_entry_instructions_slice_return_accessor_is_const_fn() {
2359        // Fail-before-pass-after pin on
2360        // [`UpgradeFromEntry::instructions`]'s `const`-eval-surface
2361        // posture. The accessor destructures the per-`:upgrade-from
2362        // :instructions` `Vec<UpgradeInstruction>` storage through the
2363        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
2364        // 1.66, well within the workspace MSRV) — any future
2365        // accidental downgrade to non-`const` fails
2366        // `instructions_via_const_fn` at caixa-core build time with
2367        // E0015 (`cannot call non-const method`), strictly stronger
2368        // than a runtime `assert!`. Sibling of the peer per-M3-mesh-
2369        // slot `Vec → &[T]` slice-return accessor family pin
2370        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
2371        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
2372        // per-`:membros` / per-`:contratos` slice-return axes, and of
2373        // the peer M2 supervisor-tree axis pin
2374        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
2375        // on the per-`:children` slice-return axis.
2376        const fn instructions_via_const_fn(e: &UpgradeFromEntry) -> &[UpgradeInstruction] {
2377            e.instructions()
2378        }
2379        // Sweep both the empty-instructions arm (author-declared
2380        // per-`:from` entry with no migration steps — the degenerate
2381        // shape the appup `restart`-only path folds through) and the
2382        // populated-instructions arm (the canonical OTP-appup shape
2383        // carrying a `LoadModule` + `StateChange` + `SoftPurge`
2384        // chain) so the accessor carries a const-dispatch pin on
2385        // both arms.
2386        let e_empty = entry("0.1.0", vec![]);
2387        assert!(instructions_via_const_fn(&e_empty).is_empty());
2388        assert_eq!(instructions_via_const_fn(&e_empty), e_empty.instructions());
2389        let e_full = entry(
2390            "0.1.0",
2391            vec![
2392                UpgradeInstruction::LoadModule {
2393                    module: "hello-rio".into(),
2394                },
2395                UpgradeInstruction::StateChange {
2396                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
2397                },
2398                UpgradeInstruction::SoftPurge {
2399                    module: "hello-rio-old".into(),
2400                },
2401            ],
2402        );
2403        assert_eq!(instructions_via_const_fn(&e_full).len(), 3);
2404        assert_eq!(instructions_via_const_fn(&e_full), e_full.instructions());
2405    }
2406
2407    #[test]
2408    fn round_trip_load_module() {
2409        let i = UpgradeInstruction::LoadModule {
2410            module: "hello-rio".into(),
2411        };
2412        let json = serde_json::to_string(&i).unwrap();
2413        assert!(json.contains("\"kind\":\"load-module\""));
2414        let back: UpgradeInstruction = serde_json::from_str(&json).unwrap();
2415        assert_eq!(i, back);
2416    }
2417
2418    #[test]
2419    fn round_trip_all_variants() {
2420        let cases = vec![
2421            UpgradeInstruction::LoadModule { module: "x".into() },
2422            UpgradeInstruction::StateChange {
2423                script: PathBuf::from("lib/migrations.lisp"),
2424            },
2425            UpgradeInstruction::SoftPurge {
2426                module: "x-old".into(),
2427            },
2428            UpgradeInstruction::Purge {
2429                module: "x-old".into(),
2430            },
2431            UpgradeInstruction::Restart,
2432        ];
2433        for c in cases {
2434            let json = serde_json::to_string(&c).unwrap();
2435            let back: UpgradeInstruction = serde_json::from_str(&json).unwrap();
2436            assert_eq!(c, back);
2437        }
2438    }
2439
2440    #[test]
2441    fn validate_accepts_well_formed() {
2442        let e = entry(
2443            "0.1.0",
2444            vec![
2445                UpgradeInstruction::LoadModule {
2446                    module: "hello-rio".into(),
2447                },
2448                UpgradeInstruction::StateChange {
2449                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
2450                },
2451                UpgradeInstruction::SoftPurge {
2452                    module: "hello-rio-old".into(),
2453                },
2454            ],
2455        );
2456        e.validate().unwrap();
2457    }
2458
2459    #[test]
2460    fn validate_rejects_non_semver_from() {
2461        let e = entry("not-a-semver", vec![]);
2462        let err = e.validate().unwrap_err();
2463        assert!(
2464            matches!(err, UpgradeError::FromInvalid { ref from, .. } if from == "not-a-semver")
2465        );
2466    }
2467
2468    #[test]
2469    fn from_invalid_diagnostic_carries_offending_from_and_reason() {
2470        // Diagnostic-shape pin: the error names the offending
2471        // `:upgrade-from :from` verbatim with a non-empty parser-shaped
2472        // reason, so a `feira lint` run can render the diagnostic
2473        // without re-parsing — the author can grep their caixa.lisp for
2474        // `:from "<value>"` and fix it in one edit. Mirrors the peer
2475        // `versao_invalid_diagnostic_carries_offending_versao` pin on
2476        // the sibling SemVer-2 axis (the top-level `:versao`), the
2477        // peer `membro_versao_invalid_diagnostic_carries_offending_value`
2478        // pin on `:membros :versao`, and the peer
2479        // `deps_invalid_diagnostic_carries_offending_value` pin on
2480        // `:deps :versao` — every SemVer-2-parsing slot's invalid
2481        // diagnostic is now structurally equivalent.
2482        let e = entry("v0.1.0", vec![]);
2483        let err = e.validate().unwrap_err();
2484        let UpgradeError::FromInvalid { from, reason } = err else {
2485            panic!("expected FromInvalid variant, got {err:?}");
2486        };
2487        assert_eq!(from, "v0.1.0");
2488        assert!(
2489            !reason.is_empty(),
2490            "FromInvalid `reason` must carry the parser's wording verbatim"
2491        );
2492    }
2493
2494    #[test]
2495    fn prior_versao_returns_from_byte_equal_across_permutations() {
2496        // Byte-identity pin on the lifted `UpgradeFromEntry::prior_versao`
2497        // accessor across the SemVer-2 shape lattice every consumer
2498        // reaches through it — the numeric-triad canonical shape, a
2499        // pre-release build with a dotted identifier chain, a full-
2500        // metadata build, a large-magnitude triad, and the empty
2501        // string (which reaches this accessor unchanged before any
2502        // validate gate rejects it). Sibling to the peer
2503        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
2504        // (a40b0e3) / `membro_nome_returns_caixa_byte_equal_across_permutations`
2505        // (4a32abf) pins on the sibling M3 mesh-slot scalar-accessor
2506        // family — extended here onto the first M2 slot scalar-value
2507        // axis. Any silent detour on the accessor (a `.to_string()`
2508        // + retained ownership shape, a canonicalization pass, a
2509        // trim-whitespace on the return path) surfaces as a byte-
2510        // inequality failure here rather than as a downstream error-
2511        // diagnostic drift.
2512        let cases = ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42", "10.20.30", ""];
2513        for from in cases {
2514            let e = entry(from, vec![]);
2515            assert_eq!(
2516                e.prior_versao(),
2517                from,
2518                "prior_versao() must return the `:from` field byte-for-byte for {from:?}",
2519            );
2520            assert_eq!(
2521                e.prior_versao().len(),
2522                from.len(),
2523                "prior_versao() byte-length must equal the `:from` field's for {from:?}",
2524            );
2525        }
2526    }
2527
2528    #[test]
2529    fn prior_versao_borrows_from_from_storage() {
2530        // Same-address pin: `UpgradeFromEntry::prior_versao` returns
2531        // a borrow into `self.from`'s heap allocation, never a fresh
2532        // owned copy. Guards against a future silent detour where
2533        // the accessor materializes a `Cow<'_, str>` / `String` /
2534        // `Rc<str>` intermediate — the return path stays zero-cost
2535        // even under a refactor that reshapes the storage. Sibling
2536        // to the peer `membro_versao_requirement_borrows_from_versao_storage`
2537        // (a40b0e3) / `membro_nome_borrows_from_caixa_storage`
2538        // (4a32abf) pins — extended onto the M2 slot's first
2539        // scalar-value axis.
2540        let e = entry("0.1.0", vec![]);
2541        assert!(
2542            std::ptr::eq(e.prior_versao().as_ptr(), e.from.as_ptr()),
2543            "prior_versao() must borrow from `self.from`'s storage, not allocate a fresh copy",
2544        );
2545    }
2546
2547    #[test]
2548    fn validate_parses_prior_versao_through_lifted_accessor() {
2549        // Coherence pin between the accessor and the SemVer-2 parse
2550        // gate: every `:upgrade-from :from` value the validator
2551        // accepts (resp. rejects) must be identical to what
2552        // `Version::parse(entry.prior_versao())` accepts (resp.
2553        // rejects) — the two must remain in lockstep across the
2554        // shape lattice so `validate_upgrade_from`'s
2555        // `Version::parse(entry.prior_versao()).expect(...)` re-parse
2556        // assertion holds by construction. If a future extension of
2557        // `prior_versao` reshapes the return (a canonicalization
2558        // pass, a leading/trailing whitespace trim, an empty-to-
2559        // "0.0.0" fallback) it would either loosen the validator
2560        // (silently accepting shapes the parser rejects) or
2561        // tighten the parser's re-parse (silently panicking on
2562        // shapes the validator accepts) — this pin catches either
2563        // shift at caixa-core build time.
2564        let accepted = ["0.1.0", "0.2.0-rc.1", "1.0.0+build.42", "10.20.30"];
2565        for from in accepted {
2566            let e = entry(from, vec![]);
2567            e.validate().unwrap_or_else(|err| {
2568                panic!("validate() must accept {from:?} that Version::parse accepts, got {err:?}");
2569            });
2570            semver::Version::parse(e.prior_versao()).unwrap_or_else(|err| {
2571                panic!(
2572                    "Version::parse(prior_versao()) must accept {from:?} that validate() accepts, \
2573                     got {err:?}",
2574                );
2575            });
2576        }
2577        let rejected = ["", "v0.1.0", "0.1", "not-a-semver", "0.1.0.0"];
2578        for from in rejected {
2579            let e = entry(from, vec![]);
2580            assert!(
2581                matches!(e.validate(), Err(UpgradeError::FromInvalid { .. })),
2582                "validate() must reject {from:?} that Version::parse rejects",
2583            );
2584            assert!(
2585                semver::Version::parse(e.prior_versao()).is_err(),
2586                "Version::parse(prior_versao()) must reject {from:?} that validate() rejects",
2587            );
2588        }
2589    }
2590
2591    #[test]
2592    fn validate_rejects_empty_module() {
2593        // Per-arm coverage: every Module-bearing variant surfaces the
2594        // kind-tagged `ModuleEmpty` diagnostic naming its lisp-form,
2595        // so the author can grep their caixa.lisp for `(:load-module
2596        // …)` / `(:soft-purge …)` / `(:purge …)` and fix it in one
2597        // edit — same self-locating shape `BehaviorError::EmptyPath`
2598        // (b0c8389) carries on the peer M2 typed slot.
2599        let cases: &[(UpgradeInstruction, &'static str)] = &[
2600            (
2601                UpgradeInstruction::LoadModule {
2602                    module: String::new(),
2603                },
2604                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
2605            ),
2606            (
2607                UpgradeInstruction::SoftPurge {
2608                    module: String::new(),
2609                },
2610                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
2611            ),
2612            (
2613                UpgradeInstruction::Purge {
2614                    module: String::new(),
2615                },
2616                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
2617            ),
2618        ];
2619        for (instr, expected_kind) in cases {
2620            assert_eq!(
2621                instr.validate().unwrap_err(),
2622                UpgradeError::ModuleEmpty {
2623                    kind: expected_kind
2624                },
2625                "empty :module on {instr:?} must surface as ModuleEmpty {{ kind: {expected_kind:?} }}"
2626            );
2627        }
2628    }
2629
2630    #[test]
2631    fn validate_rejects_non_dns_1123_module() {
2632        // Every appup `:module` reference is a caixa name (the
2633        // wasm-engine resolves it through the same ComputeUnit
2634        // registry the operator manages), so the value-shape gate
2635        // matches the K8s apiserver-side DNS-1123 label rule. Sweep
2636        // the canonical authoring footguns — uppercase letters, `_`
2637        // separator, embedded `.`, leading/trailing `-`, an embedded
2638        // whitespace byte, the >63-byte UUID-shaped slug — across
2639        // every Module-bearing variant; each must surface as
2640        // `ModuleInvalid { kind, module, reason }` carrying the
2641        // offending value verbatim and the parser-shaped reason.
2642        type Build = fn(String) -> UpgradeInstruction;
2643        let footguns: &[&str] = &[
2644            "Hello-Rio",
2645            "hello_rio",
2646            "hello.rio",
2647            "-hello",
2648            "hello-",
2649            "hello rio",
2650            &"x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
2651        ];
2652        let variants: &[(Build, &'static str)] = &[
2653            (
2654                |m| UpgradeInstruction::LoadModule { module: m },
2655                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
2656            ),
2657            (
2658                |m| UpgradeInstruction::SoftPurge { module: m },
2659                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
2660            ),
2661            (
2662                |m| UpgradeInstruction::Purge { module: m },
2663                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
2664            ),
2665        ];
2666        for (build, expected_kind) in variants {
2667            for module in footguns {
2668                let instr = build((*module).to_string());
2669                let err = instr.validate().unwrap_err();
2670                match err {
2671                    UpgradeError::ModuleInvalid {
2672                        kind,
2673                        module: m,
2674                        reason,
2675                    } => {
2676                        assert_eq!(
2677                            kind, *expected_kind,
2678                            ":module footgun on {instr:?} must tag the lisp-form"
2679                        );
2680                        assert_eq!(
2681                            m, *module,
2682                            "ModuleInvalid must carry the offending value verbatim"
2683                        );
2684                        assert!(
2685                            !reason.is_empty(),
2686                            "ModuleInvalid reason must name the specific violation \
2687                             (the predicate's parser-shaped wording from \
2688                             `is_dns_1123_label`), got empty"
2689                        );
2690                    }
2691                    other => panic!("expected ModuleInvalid on {instr:?}, got {other:?}"),
2692                }
2693            }
2694        }
2695    }
2696
2697    #[test]
2698    fn validate_accepts_canonical_module_names() {
2699        // Positive control: every documented authoring shape — bare
2700        // identifier, with hyphens, with digits, the
2701        // suffix-versioned alias `<nome>-old` `SoftPurge` typically
2702        // references — passes the gate. Drift here = a future
2703        // tighten that rejects any of these surfaces as a
2704        // test-failure at the predicate boundary, not piecemeal
2705        // across per-instruction call sites.
2706        let canonical: &[&str] = &[
2707            "hello-rio",
2708            "hello-rio-old",
2709            "cache",
2710            "cache-v2",
2711            "x",
2712            "a1",
2713            "0a",
2714            "abc-123-def",
2715        ];
2716        for module in canonical {
2717            UpgradeInstruction::LoadModule {
2718                module: (*module).to_string(),
2719            }
2720            .validate()
2721            .unwrap_or_else(|e| panic!("LoadModule {module:?} must pass, got {e:?}"));
2722            UpgradeInstruction::SoftPurge {
2723                module: (*module).to_string(),
2724            }
2725            .validate()
2726            .unwrap_or_else(|e| panic!("SoftPurge {module:?} must pass, got {e:?}"));
2727            UpgradeInstruction::Purge {
2728                module: (*module).to_string(),
2729            }
2730            .validate()
2731            .unwrap_or_else(|e| panic!("Purge {module:?} must pass, got {e:?}"));
2732        }
2733    }
2734
2735    #[test]
2736    fn validate_empty_takes_precedence_over_invalid() {
2737        // Empty input is rejected via the narrower `ModuleEmpty`
2738        // diagnostic before the DNS-1123 predicate is consulted, so
2739        // a future tighten that adds another stage between the two
2740        // doesn't accidentally reorder the diagnostic precedence.
2741        // Mirrors the empty-first cascade on every peer DNS-1123
2742        // gate (`validate_membro_caixa`, `validate_placement_cluster`,
2743        // `SupervisorSpec::validate`'s child-name arm).
2744        let err = UpgradeInstruction::LoadModule {
2745            module: String::new(),
2746        }
2747        .validate()
2748        .unwrap_err();
2749        assert_eq!(
2750            err,
2751            UpgradeError::ModuleEmpty {
2752                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
2753            }
2754        );
2755    }
2756
2757    #[test]
2758    fn validate_rejects_empty_script() {
2759        let i = UpgradeInstruction::StateChange {
2760            script: PathBuf::new(),
2761        };
2762        assert_eq!(i.validate().unwrap_err(), UpgradeError::EmptyScript);
2763    }
2764
2765    #[test]
2766    fn validate_rejects_absolute_script() {
2767        let i = UpgradeInstruction::StateChange {
2768            script: PathBuf::from("/etc/migrations.lisp"),
2769        };
2770        assert!(matches!(
2771            i.validate().unwrap_err(),
2772            UpgradeError::AbsoluteScript { .. }
2773        ));
2774    }
2775
2776    #[test]
2777    fn validate_rejects_parent_escape_script() {
2778        let i = UpgradeInstruction::StateChange {
2779            script: PathBuf::from("../sibling/migrations.lisp"),
2780        };
2781        assert!(matches!(
2782            i.validate().unwrap_err(),
2783            UpgradeError::ParentEscapeScript { .. }
2784        ));
2785        // mid-path `..` is also caught
2786        let i2 = UpgradeInstruction::StateChange {
2787            script: PathBuf::from("lib/../../escaped.lisp"),
2788        };
2789        assert!(matches!(
2790            i2.validate().unwrap_err(),
2791            UpgradeError::ParentEscapeScript { .. }
2792        ));
2793    }
2794
2795    // ── :upgrade-from :state-change :script `.lisp` extension gate ─
2796    // Mirrors the c97815a `BehaviorError::NonLispExtension` arm on
2797    // the peer `:behavior :on-*` tatara-lisp-source-path axis. Both
2798    // axes route through the same M2.5 wasm-engine `tatara_lisp::read`
2799    // consumer; the file-type contract is identical, so the per-axis
2800    // test grid is mirrored leg-for-leg.
2801
2802    #[test]
2803    fn validate_rejects_no_extension_script() {
2804        // Fail-before-pass-after: the canonical "I declared the
2805        // migration script but forgot the `.lisp` extension"
2806        // authoring footgun (e.g. `(:state-change "lib/migrations")`).
2807        // The wasm-engine's `tatara_lisp::read` consumer needs a
2808        // file-type contract beyond the structural-shape gate; a
2809        // no-extension path past `is_sandboxed_relative_path` would
2810        // surface a parser-shaped diagnostic at hot-upgrade migration
2811        // time far from the source caixa.lisp.
2812        for relpath in ["lib/migrations", "migrations", "lib/handlers/migrate"] {
2813            let i = UpgradeInstruction::StateChange {
2814                script: PathBuf::from(relpath),
2815            };
2816            let err = i.validate().unwrap_err();
2817            assert!(
2818                matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
2819                         if s == Path::new(relpath)),
2820                "no-extension script {relpath:?} must surface as NonLispExtensionScript \
2821                 carrying the offending path verbatim, got {err:?}"
2822            );
2823        }
2824    }
2825
2826    #[test]
2827    fn validate_rejects_non_lisp_extension_script() {
2828        // Wrong-extension sweep across common authoring footguns: the
2829        // `.txt` / `.md` / `.json` / `.yaml` shapes an author might
2830        // drag in from the workspace tree, the `.rs` shape that an
2831        // IDE auto-complete might propose, the `.lisp.bak` shape an
2832        // editor might leave behind, and the `.lispx` near-miss that
2833        // a typo would produce. Each must surface as
2834        // `NonLispExtensionScript` carrying the offending path
2835        // verbatim — the wasm-engine's `tatara_lisp::read` consumer
2836        // rejects all of these at hot-upgrade migration time, and
2837        // the gate lifts that contract to validate time. Mirrors the
2838        // peer `BehaviorError::NonLispExtension` sweep (c97815a) on
2839        // the `:behavior :on-*` axis leg-for-leg — same downstream
2840        // consumer, same accepted set, same per-axis test grid.
2841        let footguns: &[&str] = &[
2842            "lib/migrations.rs",
2843            "lib/migrations.txt",
2844            "lib/migrations.md",
2845            "lib/migrations.json",
2846            "lib/migrations.yaml",
2847            "lib/migrations.toml",
2848            "lib/migrations.lisp.bak",
2849            "lib/migrations.lispx",
2850            "lib/migrations.lis",
2851        ];
2852        for relpath in footguns {
2853            let i = UpgradeInstruction::StateChange {
2854                script: PathBuf::from(relpath),
2855            };
2856            let err = i.validate().unwrap_err();
2857            assert!(
2858                matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
2859                         if s == Path::new(relpath)),
2860                "wrong-extension script {relpath:?} must surface as NonLispExtensionScript \
2861                 carrying the offending path verbatim, got {err:?}"
2862            );
2863        }
2864    }
2865
2866    #[test]
2867    fn validate_rejects_uppercase_lisp_extension_script() {
2868        // Strict lowercase: `.LISP` / `.Lisp` / `.LiSp` are
2869        // case-folded shapes a case-insensitive volume's existence
2870        // check would match the on-disk file — but the
2871        // canonical-form codec emits lowercase `.lisp` verbatim, so
2872        // a case-folded shape mismatches the round-trip-stable
2873        // canonical form (THEORY.md §V.2.7 render-determinism).
2874        // Same case-sensitive discipline the byte-size / duration
2875        // codecs use on unit suffixes (`MiB`, `ms`, `s`, `m`, `h`)
2876        // and every other shape-gate predicate in `render.rs` (label
2877        // / scheme / unit boundaries). Mirrors the peer
2878        // `BehaviorError::NonLispExtension` case-fold sweep (c97815a).
2879        for relpath in [
2880            "lib/migrations.LISP",
2881            "lib/migrations.Lisp",
2882            "lib/migrations.LiSp",
2883            "lib/migrations.lISP",
2884        ] {
2885            let i = UpgradeInstruction::StateChange {
2886                script: PathBuf::from(relpath),
2887            };
2888            let err = i.validate().unwrap_err();
2889            assert!(
2890                matches!(&err, UpgradeError::NonLispExtensionScript { script: s }
2891                         if s == Path::new(relpath)),
2892                "case-folded `.lisp` extension {relpath:?} must surface as \
2893                 NonLispExtensionScript (strict lowercase, canonical-form \
2894                 round-trip pin), got {err:?}"
2895            );
2896        }
2897    }
2898
2899    #[test]
2900    fn validate_accepts_canonical_lisp_extension_scripts() {
2901        // Positive-control sweep across every canonical in-tree
2902        // authoring shape: bare filename, standard `lib/`
2903        // subdirectory, deeply-nested migrations subdirectory,
2904        // explicit current-dir-relative prefix, mid-path `./`
2905        // segment, multi-dot stem (the version-suffix shape
2906        // `lib/migrations/v.0.1.lisp` an author might use to encode
2907        // the migration's `:from` version into the filename). Drift
2908        // here = a future tightening that rejects any of these
2909        // surfaces as a test-failure at the per-axis validator
2910        // boundary, not piecemeal across renderer / layout-checker
2911        // call sites. Mirrors the peer `BehaviorSpec` positive-set
2912        // sweep (c97815a).
2913        let canonical: &[&str] = &[
2914            "lib/migrations.lisp",
2915            "lib/migrations/v01-to-v02.lisp",
2916            "migrations.lisp",
2917            "a.lisp",
2918            "./lib/migrations.lisp",
2919            "lib/./migrations.lisp",
2920            "lib/migrations/v.0.1.lisp",
2921        ];
2922        for relpath in canonical {
2923            UpgradeInstruction::StateChange {
2924                script: PathBuf::from(relpath),
2925            }
2926            .validate()
2927            .unwrap_or_else(|e| {
2928                panic!("canonical `.lisp` script {relpath:?} must pass, got {e:?}")
2929            });
2930        }
2931    }
2932
2933    #[test]
2934    fn validate_sandbox_shape_takes_precedence_over_lisp_extension() {
2935        // Cross-arm precedence pin: a script that is *both*
2936        // sandbox-escaping (Empty / Absolute / ParentEscape) and
2937        // non-`.lisp` must surface the more-fundamental
2938        // sandbox-shape diagnostic first — the canonical fix
2939        // collapses both into "pin a relative `.lisp` path under the
2940        // caixa root", and the `.lisp` remediation would be
2941        // misleading when the offending path can never resolve under
2942        // the caixa root anyway. Mirrors the peer
2943        // `BehaviorError` cross-arm precedence (c97815a) and the
2944        // sibling `LimitsError`
2945        // (`MemoryZero` → `MemoryBelowWasm32Page` →
2946        // `MemoryExceedsWasm32Cap` → `MemoryNotPageMultiple`)
2947        // smallest-scope-arm-fires-last posture.
2948        let i_empty = UpgradeInstruction::StateChange {
2949            script: PathBuf::new(),
2950        };
2951        assert_eq!(i_empty.validate().unwrap_err(), UpgradeError::EmptyScript);
2952        let i_abs = UpgradeInstruction::StateChange {
2953            script: PathBuf::from("/etc/migrations.txt"),
2954        };
2955        assert!(
2956            matches!(
2957                i_abs.validate().unwrap_err(),
2958                UpgradeError::AbsoluteScript { .. }
2959            ),
2960            "absolute + non-`.lisp` must surface AbsoluteScript first"
2961        );
2962        let i_esc = UpgradeInstruction::StateChange {
2963            script: PathBuf::from("../sibling/migrations.rs"),
2964        };
2965        assert!(
2966            matches!(
2967                i_esc.validate().unwrap_err(),
2968                UpgradeError::ParentEscapeScript { .. }
2969            ),
2970            "parent-escape + non-`.lisp` must surface ParentEscapeScript first"
2971        );
2972    }
2973
2974    #[test]
2975    fn non_lisp_extension_script_diagnostic_carries_offending_path() {
2976        // Diagnostic-shape pin: the surfaced error message names the
2977        // offending path verbatim (so the author can grep their
2978        // caixa.lisp for the literal value), the `.lisp` extension
2979        // is named in the remediation, and the downstream consumer
2980        // (`tatara_lisp::read` at hot-upgrade migration time) is
2981        // named so the author can trace the contract back to its
2982        // source. Same self-locating shape every per-axis variant
2983        // carries (`BehaviorError::NonLispExtension`, c97815a;
2984        // `LimitsError::MemoryNotPageMultiple`, ec266d8).
2985        let bad = PathBuf::from("lib/migrations.txt");
2986        let err = UpgradeInstruction::StateChange {
2987            script: bad.clone(),
2988        }
2989        .validate()
2990        .unwrap_err();
2991        let msg = err.to_string();
2992        assert!(
2993            msg.contains("lib/migrations.txt"),
2994            "diagnostic must name the offending path verbatim, got {msg:?}"
2995        );
2996        assert!(
2997            msg.contains(".lisp"),
2998            "diagnostic must name the expected `.lisp` extension, got {msg:?}"
2999        );
3000        assert!(
3001            msg.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE),
3002            "diagnostic must name the offending `:state-change` instruction, got {msg:?}"
3003        );
3004        match err {
3005            UpgradeError::NonLispExtensionScript { script } => {
3006                assert_eq!(
3007                    script, bad,
3008                    "variant must carry the offending path verbatim"
3009                );
3010            }
3011            other => panic!("expected NonLispExtensionScript, got {other:?}"),
3012        }
3013    }
3014
3015    #[test]
3016    fn declared_path_only_for_state_change() {
3017        let load = UpgradeInstruction::LoadModule { module: "x".into() };
3018        assert!(load.declared_path().is_none());
3019        let mig = UpgradeInstruction::StateChange {
3020            script: PathBuf::from("lib/m.lisp"),
3021        };
3022        assert_eq!(mig.declared_path(), Some(&PathBuf::from("lib/m.lisp")));
3023    }
3024
3025    #[test]
3026    fn upgrade_instruction_is_restart_predicate_partitions_the_arm_set() {
3027        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
3028        // derive's [`UpgradeInstruction::is_restart`] arm-discriminator
3029        // predicate: [`UpgradeInstruction::Restart`] is the only variant
3030        // that satisfies `.is_restart()`; every module-bearing arm
3031        // (`LoadModule` / `SoftPurge` / `Purge`) and the script-carrying
3032        // `StateChange` arm all return `false`. This pin makes the
3033        // partition invariant load-bearing at caixa-core test time so a
3034        // future derive regression (a hole that returns `false` for
3035        // `Restart` too, or a byte-collision that flips a second variant
3036        // to `true`) trips here rather than laundering the arm at
3037        // [`Self::validate_restart_exclusive`]'s paired positive /
3038        // negated filter sites (a hole flips restart-count to 0 →
3039        // vacuous OK; a collision flips restart-count > 1 → false
3040        // `RestartNotExclusive` on an entry the author declared without
3041        // any `(:restart)`). Peer of the sibling
3042        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
3043        // pin on the M0 `CaixaKind` axis.
3044        let cases: &[(UpgradeInstruction, bool)] = &[
3045            (UpgradeInstruction::LoadModule { module: "a".into() }, false),
3046            (UpgradeInstruction::SoftPurge { module: "b".into() }, false),
3047            (UpgradeInstruction::Purge { module: "c".into() }, false),
3048            (
3049                UpgradeInstruction::StateChange {
3050                    script: PathBuf::from("lib/m.lisp"),
3051                },
3052                false,
3053            ),
3054            (UpgradeInstruction::Restart, true),
3055        ];
3056        for (variant, expected) in cases {
3057            assert_eq!(
3058                variant.is_restart(),
3059                *expected,
3060                "UpgradeInstruction::{variant:?}.is_restart() must \
3061                 return {expected} (partition invariant on the \
3062                 IsVariant-derived arm-discriminator predicate)"
3063            );
3064        }
3065    }
3066
3067    #[test]
3068    fn validate_restart_exclusive_routes_through_is_restart_predicate() {
3069        // Byte-identity pin on the paired positive / negated
3070        // `.is_restart()` filters at
3071        // [`Self::validate_restart_exclusive`] against the pre-lift
3072        // `matches!(i, UpgradeInstruction::Restart)` /
3073        // `!matches!(i, UpgradeInstruction::Restart)` predicates every
3074        // consumer of the gate previously coupled to inline. Asserts
3075        // the two projections agree byte-for-byte on every arm of the
3076        // enum, so a future derive regression that flipped either
3077        // predicate's arm-set would surface here at caixa-core test
3078        // time rather than at
3079        // [`Self::validate_restart_exclusive`]'s per-entry restart-
3080        // count / other-kinds tabulation far from the derive site.
3081        // Same peer-shape pin every sibling
3082        // `IsVariant`-derive-routed gate carries on the substrate's
3083        // closed-set typed-enum surface.
3084        let cases: Vec<UpgradeInstruction> = vec![
3085            UpgradeInstruction::LoadModule { module: "a".into() },
3086            UpgradeInstruction::SoftPurge { module: "b".into() },
3087            UpgradeInstruction::Purge { module: "c".into() },
3088            UpgradeInstruction::StateChange {
3089                script: PathBuf::from("lib/m.lisp"),
3090            },
3091            UpgradeInstruction::Restart,
3092        ];
3093        for instr in &cases {
3094            let via_predicate = instr.is_restart();
3095            let via_matches = matches!(instr, UpgradeInstruction::Restart);
3096            assert_eq!(
3097                via_predicate, via_matches,
3098                "UpgradeInstruction::{instr:?}: is_restart() must \
3099                 byte-equal matches!(_, UpgradeInstruction::Restart) — \
3100                 the pre-lift open-coded pattern and the \
3101                 IsVariant-derived predicate are the same axis, \
3102                 one typed dispatch"
3103            );
3104        }
3105    }
3106
3107    #[test]
3108    fn upgrade_instruction_is_cleanup_predicate_partitions_the_arm_set() {
3109        // The fail-before-pass-after pin on the lifted
3110        // [`UpgradeInstruction::is_cleanup`] two-arm cleanup-family
3111        // arm-discriminator predicate:
3112        // [`UpgradeInstruction::SoftPurge`] and
3113        // [`UpgradeInstruction::Purge`] are the two OTP-appup two-
3114        // phase-code-load cleanup arms that satisfy `.is_cleanup()`;
3115        // every non-cleanup arm ([`UpgradeInstruction::LoadModule`]
3116        // on the paired two-phase-load half,
3117        // [`UpgradeInstruction::StateChange`] on the
3118        // `gen_server:code_change/3`-analog migration axis,
3119        // [`UpgradeInstruction::Restart`] on the OTP terminal-
3120        // fallback shape) returns `false`. This pin makes the
3121        // partition invariant load-bearing at caixa-core test time
3122        // so a future accessor regression (a hole that returns
3123        // `false` for `SoftPurge` or `Purge`, or a byte-collision
3124        // that flips `LoadModule` / `StateChange` / `Restart` to
3125        // `true`) trips here rather than laundering the arm at the
3126        // three within-entry cross-instruction cleanup-facing gates
3127        // ([`UpgradeFromEntry::validate_purge_ordering`],
3128        // [`UpgradeFromEntry::validate_state_change_before_cleanup`],
3129        // [`UpgradeFromEntry::validate_cleanup_singularity`]) — a
3130        // hole would silently accept a cleanup-shaped entry the
3131        // three gates should refuse; a collision would fire a
3132        // `PurgeWithoutPriorLoad` / `StateChangeAfterCleanup` /
3133        // `DuplicateCleanup` refusal on a well-shaped
3134        // [`UpgradeInstruction::LoadModule`] / `StateChange` /
3135        // `Restart` arm the three gates should pass through. Peer
3136        // of the sibling
3137        // [`upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
3138        // pin on the single-arm terminal-fallback partition —
3139        // extended here from the single-arm case onto the two-arm
3140        // cleanup-family union case.
3141        let cases: &[(UpgradeInstruction, bool)] = &[
3142            (UpgradeInstruction::LoadModule { module: "a".into() }, false),
3143            (UpgradeInstruction::SoftPurge { module: "b".into() }, true),
3144            (UpgradeInstruction::Purge { module: "c".into() }, true),
3145            (
3146                UpgradeInstruction::StateChange {
3147                    script: PathBuf::from("lib/m.lisp"),
3148                },
3149                false,
3150            ),
3151            (UpgradeInstruction::Restart, false),
3152        ];
3153        for (variant, expected) in cases {
3154            assert_eq!(
3155                variant.is_cleanup(),
3156                *expected,
3157                "UpgradeInstruction::{variant:?}.is_cleanup() must \
3158                 return {expected} (partition invariant on the \
3159                 lifted OTP-appup two-arm cleanup-family arm-\
3160                 discriminator predicate)"
3161            );
3162        }
3163    }
3164
3165    #[test]
3166    fn upgrade_instruction_is_cleanup_composes_through_is_soft_purge_or_is_purge() {
3167        // Byte-identity pin on the [`UpgradeInstruction::is_cleanup`]
3168        // composition against the two [`gen_platform::IsVariant`]-
3169        // derive-generated per-variant classifiers it routes through
3170        // — the accessor's one body must byte-equal
3171        // `self.is_soft_purge() || self.is_purge()` across every arm
3172        // of the closed-set enum, so a future silent detour that
3173        // reintroduced a raw `matches!` pattern or that stopped
3174        // composing through the derive-generated per-variant
3175        // predicates (an accidental `self.is_soft_purge()` on its
3176        // own — silently dropping the `Purge` arm; an accidental
3177        // `self.is_purge() || self.is_state_change()` — silently
3178        // folding the migration arm into the cleanup family; a
3179        // typo `&&` for the union `||` — silently classifying no
3180        // arm as cleanup) trips here at caixa-core test time
3181        // rather than laundering the arm at the three within-entry
3182        // cross-instruction cleanup-facing gates. Same peer-shape
3183        // pin the sibling
3184        // [`validate_restart_exclusive_routes_through_is_restart_predicate`]
3185        // carries on the paired terminal-fallback axis.
3186        let cases: Vec<UpgradeInstruction> = vec![
3187            UpgradeInstruction::LoadModule { module: "a".into() },
3188            UpgradeInstruction::SoftPurge { module: "b".into() },
3189            UpgradeInstruction::Purge { module: "c".into() },
3190            UpgradeInstruction::StateChange {
3191                script: PathBuf::from("lib/m.lisp"),
3192            },
3193            UpgradeInstruction::Restart,
3194        ];
3195        for instr in &cases {
3196            let via_predicate = instr.is_cleanup();
3197            let via_composition = instr.is_soft_purge() || instr.is_purge();
3198            assert_eq!(
3199                via_predicate, via_composition,
3200                "UpgradeInstruction::{instr:?}: is_cleanup() must \
3201                 byte-equal is_soft_purge() || is_purge() — the \
3202                 lifted union predicate and its per-variant \
3203                 composition are the same axis, one typed dispatch"
3204            );
3205        }
3206    }
3207
3208    #[test]
3209    fn upgrade_instruction_is_cleanup_implies_declared_module_is_some() {
3210        // Composition-pin the load-bearing invariant every consumer
3211        // that routes through `is_cleanup()` + `declared_module()`
3212        // relies on: any [`UpgradeInstruction`] value whose
3213        // `.is_cleanup()` returns `true` must have a `Some(_)`
3214        // `.declared_module()`. This makes the three within-entry
3215        // cross-instruction cleanup-facing gates' `.expect("is_cleanup()
3216        // implies declared_module() is Some")` structurally
3217        // infallible at build time — a future refactor that added
3218        // a cleanup-shaped variant carrying no `:module` would trip
3219        // here rather than panic at
3220        // [`UpgradeFromEntry::validate_purge_ordering`] /
3221        // [`UpgradeFromEntry::validate_state_change_before_cleanup`] /
3222        // [`UpgradeFromEntry::validate_cleanup_singularity`] at
3223        // runtime on the offending author's caixa.lisp.
3224        let cases: Vec<UpgradeInstruction> = vec![
3225            UpgradeInstruction::LoadModule { module: "a".into() },
3226            UpgradeInstruction::SoftPurge { module: "b".into() },
3227            UpgradeInstruction::Purge { module: "c".into() },
3228            UpgradeInstruction::StateChange {
3229                script: PathBuf::from("lib/m.lisp"),
3230            },
3231            UpgradeInstruction::Restart,
3232        ];
3233        for instr in &cases {
3234            if instr.is_cleanup() {
3235                assert!(
3236                    instr.declared_module().is_some(),
3237                    "UpgradeInstruction::{instr:?}: is_cleanup() \
3238                     must imply declared_module().is_some() — the \
3239                     three within-entry cross-instruction cleanup-\
3240                     facing gates rely on this invariant to route \
3241                     the cleanup-target :module scalar through the \
3242                     sibling declared_module accessor without a \
3243                     pattern-bound `module` binding"
3244                );
3245            }
3246        }
3247    }
3248
3249    #[test]
3250    fn upgrade_instruction_is_load_module_implies_declared_module_is_some() {
3251        // Composition-pin the load-bearing invariant
3252        // [`UpgradeFromEntry::validate_load_singularity`] relies on
3253        // when routing the per-instruction load-family arm-discriminator
3254        // through the sibling
3255        // [`UpgradeInstruction::is_load_module`] +
3256        // [`UpgradeInstruction::declared_module`] accessor pair: any
3257        // [`UpgradeInstruction`] value whose `.is_load_module()`
3258        // returns `true` must have a `Some(_)` `.declared_module()`.
3259        // This makes the gate's `.expect("is_load_module() implies
3260        // declared_module() is Some")` structurally infallible at
3261        // build time — a future refactor that added a load-shaped
3262        // variant carrying no `:module` would trip here rather than
3263        // panic at [`UpgradeFromEntry::validate_load_singularity`]
3264        // at runtime on the offending author's caixa.lisp. Sibling
3265        // of the peer
3266        // [`upgrade_instruction_is_cleanup_implies_declared_module_is_some`]
3267        // composition pin on the two-arm cleanup-family axis — same
3268        // "predicate implies accessor" discipline extended onto the
3269        // single-arm load-family axis, closes the load-vs-cleanup
3270        // pair on the substrate primitive's typed dispatch discipline.
3271        let cases: Vec<UpgradeInstruction> = vec![
3272            UpgradeInstruction::LoadModule { module: "a".into() },
3273            UpgradeInstruction::SoftPurge { module: "b".into() },
3274            UpgradeInstruction::Purge { module: "c".into() },
3275            UpgradeInstruction::StateChange {
3276                script: PathBuf::from("lib/m.lisp"),
3277            },
3278            UpgradeInstruction::Restart,
3279        ];
3280        for instr in &cases {
3281            if instr.is_load_module() {
3282                assert!(
3283                    instr.declared_module().is_some(),
3284                    "UpgradeInstruction::{instr:?}: is_load_module() \
3285                     must imply declared_module().is_some() — the \
3286                     within-entry load-singularity gate relies on this \
3287                     invariant to route the load-target :module scalar \
3288                     through the sibling declared_module accessor \
3289                     without a pattern-bound `module` binding"
3290                );
3291            }
3292        }
3293    }
3294
3295    #[test]
3296    fn validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors()
3297     {
3298        // Byte-identity pin on the
3299        // [`UpgradeFromEntry::validate_load_singularity`] load-family
3300        // dispatch against the pre-lift
3301        // `match instr { UpgradeInstruction::LoadModule { module } =>
3302        // module.as_str(), _ => continue }` open-coded pattern-match
3303        // the site previously carried. Asserts the two projections
3304        // agree byte-for-byte on every arm of the enum — the
3305        // arm-discriminator via `is_load_module()` and the `:module`
3306        // scalar via `declared_module()` — so a future derive
3307        // regression that flipped the predicate's arm-set (a hole
3308        // returning `false` for [`UpgradeInstruction::LoadModule`], a
3309        // byte-collision flipping a second variant to `true`) or an
3310        // accessor extension that promoted an additional variant onto
3311        // the `String`-carrying axis would trip here at caixa-core
3312        // test time rather than laundering the arm at the gate's
3313        // per-entry load-singularity scan far from the derive site.
3314        // Peer of the sibling
3315        // [`validate_purge_ordering_routes_through_is_load_module_predicate`]
3316        // byte-identity pin on the paired ordering-side load-family
3317        // sticky-latch dispatch (both consumers now agree on one
3318        // typed dispatch for the load-family axis) and the peer
3319        // [`validate_state_change_singularity_projects_scripts_through_declared_path_accessor`]
3320        // pin on the migration-family script-projection axis — the
3321        // three within-entry per-instruction-class singularity gates
3322        // now share one byte-identity pin apiece against their
3323        // respective substrate-primitive typed dispatches.
3324        //
3325        // Three-arm projective coverage:
3326        //   (a) `LoadModule` modules project through
3327        //       `declared_module()` byte-equal to the raw
3328        //       `module.as_str()` field access;
3329        //   (b) a duplicate-`LoadModule` input trips the gate on the
3330        //       second occurrence with `DuplicateLoadModule` carrying
3331        //       the offending module verbatim;
3332        //   (c) a non-`LoadModule`-only input (`SoftPurge` / `Purge` /
3333        //       `StateChange` / `Restart`) leaves the gate vacuous
3334        //       with `Ok(())` — the `!instr.is_load_module()`
3335        //       `continue` fall-through pins.
3336        //
3337        // Fail-before-pass-after verified locally: swapping the
3338        // production `if !instr.is_load_module() { continue; } let
3339        // module = instr.declared_module().expect(…);` back to `let
3340        // module = match instr { UpgradeInstruction::LoadModule
3341        // { module } => module.as_str(), _ => continue, };` keeps
3342        // arms (a)-(c) passing but silently detaches the gate from
3343        // the accessor's typed dispatch — any future
3344        // `is_load_module` / `declared_module` extension (a hole in
3345        // either predicate, a promotion of an additional variant
3346        // onto the `String`-carrying axis, an operator-side
3347        // pre-parsed caixa-name cache the accessor materializes)
3348        // would then silently disagree between this gate's raw
3349        // pattern-match and the peer per-`UpgradeInstruction`
3350        // consumers that route through the accessor pair.
3351
3352        // (a) LoadModule projection byte-equal via
3353        //     is_load_module() + declared_module().
3354        let lm = UpgradeInstruction::LoadModule {
3355            module: "hello-rio".into(),
3356        };
3357        assert!(
3358            lm.is_load_module(),
3359            "LoadModule must satisfy is_load_module() — the gate's \
3360             load-family arm-discriminator relies on this partition"
3361        );
3362        assert_eq!(
3363            lm.declared_module(),
3364            Some("hello-rio"),
3365            "declared_module() must project the LoadModule :module \
3366             byte-equal to the raw field access — accessor divergence \
3367             would silently detach the gate from the projection every \
3368             peer per-`UpgradeInstruction` consumer routes through"
3369        );
3370
3371        // (b) Duplicate-LoadModule input trips the gate.
3372        let dup = entry(
3373            "0.1.0",
3374            vec![
3375                UpgradeInstruction::LoadModule { module: "x".into() },
3376                UpgradeInstruction::LoadModule { module: "x".into() },
3377            ],
3378        );
3379        assert_eq!(
3380            dup.validate_load_singularity(),
3381            Err(UpgradeError::DuplicateLoadModule {
3382                from: "0.1.0".into(),
3383                module: "x".into(),
3384            }),
3385            "duplicate LoadModule modules within one entry must fire \
3386             DuplicateLoadModule byte-identical to the pre-lift \
3387             pattern-match shape"
3388        );
3389
3390        // (c) Non-LoadModule-only input leaves the gate vacuous.
3391        let no_load = entry(
3392            "0.1.0",
3393            vec![
3394                UpgradeInstruction::StateChange {
3395                    script: PathBuf::from("lib/m.lisp"),
3396                },
3397                UpgradeInstruction::Restart,
3398            ],
3399        );
3400        assert_eq!(
3401            no_load.validate_load_singularity(),
3402            Ok(()),
3403            "non-LoadModule-only entries must leave the load-\
3404             singularity gate vacuous — the `!is_load_module()` \
3405             continue fall-through pins"
3406        );
3407    }
3408
3409    #[test]
3410    fn upgrade_instruction_is_load_module_predicate_partitions_the_arm_set() {
3411        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
3412        // derive's [`UpgradeInstruction::is_load_module`] arm-discriminator
3413        // predicate: [`UpgradeInstruction::LoadModule`] is the only
3414        // variant that satisfies `.is_load_module()`; every cleanup arm
3415        // (`SoftPurge` / `Purge`), the migration arm (`StateChange`),
3416        // and the terminal-fallback arm (`Restart`) all return `false`.
3417        // This pin makes the partition invariant load-bearing at
3418        // caixa-core test time so a future derive regression (a hole
3419        // that returns `false` for `LoadModule` too, or a byte-collision
3420        // that flips a second variant to `true`) trips here rather than
3421        // laundering the arm at
3422        // [`Self::validate_purge_ordering`]'s load-family sticky-latch
3423        // dispatch — a hole would silently keep `loaded = false` through
3424        // a well-shaped [`UpgradeInstruction::LoadModule`] prefix and
3425        // false-fire `PurgeWithoutPriorLoad` on the trailing cleanup;
3426        // a collision would flip `loaded = true` on a well-shaped
3427        // cleanup-only entry and silently swallow the load-less
3428        // `PurgeWithoutPriorLoad` refusal. Peer of the sibling
3429        // [`upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
3430        // and
3431        // [`upgrade_instruction_is_cleanup_predicate_partitions_the_arm_set`]
3432        // pins on the paired terminal-fallback and cleanup-family
3433        // arm-discriminator axes — closes the last unlifted `matches!`-
3434        // based arm-discriminator axis on the OTP-appup closed-set
3435        // typed enum.
3436        let cases: &[(UpgradeInstruction, bool)] = &[
3437            (UpgradeInstruction::LoadModule { module: "a".into() }, true),
3438            (UpgradeInstruction::SoftPurge { module: "b".into() }, false),
3439            (UpgradeInstruction::Purge { module: "c".into() }, false),
3440            (
3441                UpgradeInstruction::StateChange {
3442                    script: PathBuf::from("lib/m.lisp"),
3443                },
3444                false,
3445            ),
3446            (UpgradeInstruction::Restart, false),
3447        ];
3448        for (variant, expected) in cases {
3449            assert_eq!(
3450                variant.is_load_module(),
3451                *expected,
3452                "UpgradeInstruction::{variant:?}.is_load_module() must \
3453                 return {expected} (partition invariant on the \
3454                 IsVariant-derived arm-discriminator predicate)"
3455            );
3456        }
3457    }
3458
3459    #[test]
3460    fn validate_purge_ordering_routes_through_is_load_module_predicate() {
3461        // Byte-identity pin on the [`Self::validate_purge_ordering`]
3462        // load-family sticky-latch dispatch against the pre-lift
3463        // `matches!(instr, UpgradeInstruction::LoadModule { .. })`
3464        // predicate the site previously open-coded. Asserts the two
3465        // projections agree byte-for-byte on every arm of the enum, so
3466        // a future derive regression that flipped the predicate's
3467        // arm-set would surface here at caixa-core test time rather
3468        // than at [`Self::validate_purge_ordering`]'s per-entry
3469        // load-before-cleanup ordering scan far from the derive site.
3470        // Same peer-shape pin the sibling
3471        // [`validate_restart_exclusive_routes_through_is_restart_predicate`]
3472        // carries on the paired terminal-fallback axis and the
3473        // [`upgrade_instruction_is_cleanup_composes_through_is_soft_purge_or_is_purge`]
3474        // carries on the two-arm cleanup-family axis — the third and
3475        // final byte-identity pin closes the substrate primitive's
3476        // arm-discriminator dispatch discipline on the OTP-appup
3477        // closed-set typed enum.
3478        let cases: Vec<UpgradeInstruction> = vec![
3479            UpgradeInstruction::LoadModule { module: "a".into() },
3480            UpgradeInstruction::SoftPurge { module: "b".into() },
3481            UpgradeInstruction::Purge { module: "c".into() },
3482            UpgradeInstruction::StateChange {
3483                script: PathBuf::from("lib/m.lisp"),
3484            },
3485            UpgradeInstruction::Restart,
3486        ];
3487        for instr in &cases {
3488            let via_predicate = instr.is_load_module();
3489            let via_matches = matches!(instr, UpgradeInstruction::LoadModule { .. });
3490            assert_eq!(
3491                via_predicate, via_matches,
3492                "UpgradeInstruction::{instr:?}: is_load_module() must \
3493                 byte-equal matches!(_, UpgradeInstruction::LoadModule \
3494                 {{ .. }}) — the pre-lift open-coded pattern and the \
3495                 IsVariant-derived predicate are the same axis, one \
3496                 typed dispatch"
3497            );
3498        }
3499    }
3500
3501    #[test]
3502    fn declared_module_only_for_module_bearing_variants() {
3503        // Pinned partition of the `UpgradeInstruction` closed-set
3504        // variant space against the sibling of the peer
3505        // `declared_path` accessor: every OTP-appup module-bearing
3506        // variant (`LoadModule` / `SoftPurge` / `Purge`) surfaces its
3507        // `:module` string byte-for-byte through the lifted
3508        // `declared_module` accessor; every non-module-bearing variant
3509        // (`StateChange` on the peer `:script`-carrying axis;
3510        // `Restart` on the OTP terminal-fallback data-less axis)
3511        // returns `None`. Mirrors the peer
3512        // `declared_path_only_for_state_change` pin — the pair now
3513        // closes both scalar-carrying axes on the enum on one lifted
3514        // `Option<&…>` accessor apiece.
3515        let load = UpgradeInstruction::LoadModule {
3516            module: "hello-rio".into(),
3517        };
3518        assert_eq!(load.declared_module(), Some("hello-rio"));
3519        let soft = UpgradeInstruction::SoftPurge {
3520            module: "hello-rio-old".into(),
3521        };
3522        assert_eq!(soft.declared_module(), Some("hello-rio-old"));
3523        let hard = UpgradeInstruction::Purge {
3524            module: "hello-rio-ancient".into(),
3525        };
3526        assert_eq!(hard.declared_module(), Some("hello-rio-ancient"));
3527        let mig = UpgradeInstruction::StateChange {
3528            script: PathBuf::from("lib/m.lisp"),
3529        };
3530        assert!(mig.declared_module().is_none());
3531        assert!(UpgradeInstruction::Restart.declared_module().is_none());
3532    }
3533
3534    #[test]
3535    fn declared_module_and_declared_path_partition_the_enum_variant_space() {
3536        // Byte-identity pin on the two-accessor partition: every
3537        // `UpgradeInstruction` variant returns `Some` from *exactly
3538        // one* of {`declared_module`, `declared_path`} (the two
3539        // module-bearing / script-carrying axes) or from *neither*
3540        // (the OTP terminal-fallback `Restart` shape). No variant
3541        // returns `Some` from both — the two axes are disjoint by
3542        // construction, and this pin closes the disjointness at the
3543        // test surface so a future variant that leaks a scalar across
3544        // both axes fails at build time. Mirrors the peer
3545        // `declared_paths_iter_covers_each_declared_slot_exactly_once`
3546        // discipline on the `BehaviorSpec` per-slot family.
3547        let cases: Vec<UpgradeInstruction> = vec![
3548            UpgradeInstruction::LoadModule { module: "a".into() },
3549            UpgradeInstruction::SoftPurge { module: "b".into() },
3550            UpgradeInstruction::Purge { module: "c".into() },
3551            UpgradeInstruction::StateChange {
3552                script: PathBuf::from("lib/m.lisp"),
3553            },
3554            UpgradeInstruction::Restart,
3555        ];
3556        for instr in &cases {
3557            let has_module = instr.declared_module().is_some();
3558            let has_path = instr.declared_path().is_some();
3559            assert!(
3560                !(has_module && has_path),
3561                "no variant may declare both a module and a path — offending: {instr:?}"
3562            );
3563            match instr {
3564                UpgradeInstruction::LoadModule { .. }
3565                | UpgradeInstruction::SoftPurge { .. }
3566                | UpgradeInstruction::Purge { .. } => {
3567                    assert!(has_module && !has_path, "module axis: {instr:?}");
3568                }
3569                UpgradeInstruction::StateChange { .. } => {
3570                    assert!(!has_module && has_path, "script axis: {instr:?}");
3571                }
3572                UpgradeInstruction::Restart => {
3573                    assert!(!has_module && !has_path, "data-less axis: {instr:?}");
3574                }
3575            }
3576        }
3577    }
3578
3579    #[test]
3580    fn entry_with_chain_of_versions() {
3581        // Middle entry pairs a `:load-module` with the trailing
3582        // `:soft-purge` so it satisfies the within-entry purge-ordering
3583        // gate (`PurgeWithoutPriorLoad` rejects `:soft-purge` without a
3584        // preceding `:load-module`, mirroring the state-change-ordering
3585        // gate's `StateChangeWithoutPriorLoad`). The chain shape under
3586        // test is *cross-entry* `:from` values; the within-entry shape
3587        // is incidental — keeping it canonical (`:load-module` before
3588        // `:soft-purge`) leaves the chain assertion load-bearing.
3589        let entries = vec![
3590            entry(
3591                "0.1.0",
3592                vec![UpgradeInstruction::LoadModule { module: "x".into() }],
3593            ),
3594            entry(
3595                "0.1.5",
3596                vec![
3597                    UpgradeInstruction::LoadModule { module: "x".into() },
3598                    UpgradeInstruction::SoftPurge {
3599                        module: "x-old".into(),
3600                    },
3601                ],
3602            ),
3603            entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart]),
3604        ];
3605        for e in &entries {
3606            e.validate().unwrap();
3607        }
3608        let json = serde_json::to_string(&entries).unwrap();
3609        let back: Vec<UpgradeFromEntry> = serde_json::from_str(&json).unwrap();
3610        assert_eq!(entries, back);
3611    }
3612
3613    #[test]
3614    fn empty_instructions_list_is_valid() {
3615        let e = entry("0.1.0", vec![]);
3616        e.validate().unwrap();
3617    }
3618
3619    #[test]
3620    fn json_uses_kebab_case_kind_tags() {
3621        let i = UpgradeInstruction::SoftPurge {
3622            module: "x-old".into(),
3623        };
3624        let json = serde_json::to_string(&i).unwrap();
3625        assert!(json.contains("\"kind\":\"soft-purge\""));
3626        let i2 = UpgradeInstruction::StateChange {
3627            script: PathBuf::from("m.lisp"),
3628        };
3629        let json2 = serde_json::to_string(&i2).unwrap();
3630        assert!(json2.contains("\"kind\":\"state-change\""));
3631    }
3632
3633    // ── validate_upgrade_from: cross-entry graph-edge-set invariant ────
3634
3635    #[test]
3636    fn validate_upgrade_from_accepts_disjoint_versions() {
3637        // Positive control: the canonical "chain v0.1.0 → 0.1.5 →
3638        // 0.2.0-rc.1" authoring shape from ABSORPTION-ROADMAP §M2.3
3639        // (and `entry_with_chain_of_versions` above) passes the cross-
3640        // entry gate. Different `:from` per entry is the intended
3641        // shape; the gate must not regress this baseline. Middle entry
3642        // pairs `:load-module` with `:soft-purge` to satisfy the
3643        // within-entry purge-ordering gate (see
3644        // `entry_with_chain_of_versions` for the same shape).
3645        let entries = vec![
3646            entry(
3647                "0.1.0",
3648                vec![UpgradeInstruction::LoadModule { module: "x".into() }],
3649            ),
3650            entry(
3651                "0.1.5",
3652                vec![
3653                    UpgradeInstruction::LoadModule { module: "x".into() },
3654                    UpgradeInstruction::SoftPurge {
3655                        module: "x-old".into(),
3656                    },
3657                ],
3658            ),
3659            entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart]),
3660        ];
3661        validate_upgrade_from(&entries).unwrap();
3662    }
3663
3664    #[test]
3665    fn validate_upgrade_from_accepts_empty_list() {
3666        // Absent `:upgrade-from` (the bare `feira init` shape) — the
3667        // gate must trivially pass an empty list. Mirrors the per-axis
3668        // "empty list passes" positive control on every peer typed-
3669        // graph gate (`validate_membros` empty list, `validate_placement`
3670        // requires non-empty clusters but only after a `Placement`
3671        // exists, etc.).
3672        validate_upgrade_from(&[]).unwrap();
3673    }
3674
3675    #[test]
3676    fn validate_upgrade_from_rejects_duplicate_from() {
3677        // Fail-before-pass-after pin: two entries with the same parsed-
3678        // semver `:from` are an ambiguous edge in the typed upgrade
3679        // graph (OTP appup picks at most one matching block per running
3680        // version; with two matching blocks the operator picks either
3681        // set non-deterministically — author intent is one path per
3682        // prior version). Same set-not-multiset discipline as
3683        // `:children :caixa` (dbf50a9), `:membros :caixa` (4bb3f3d),
3684        // `:contratos` (5dbcfaf), `:placement :clusters` (c7c7799),
3685        // `:entrada :paths` (eb3456d) — now extended onto the fifth
3686        // typed-graph axis.
3687        let entries = vec![
3688            entry(
3689                "0.1.0",
3690                vec![UpgradeInstruction::LoadModule { module: "x".into() }],
3691            ),
3692            entry(
3693                "0.1.0",
3694                vec![
3695                    UpgradeInstruction::LoadModule { module: "x".into() },
3696                    UpgradeInstruction::SoftPurge {
3697                        module: "x-old".into(),
3698                    },
3699                ],
3700            ),
3701        ];
3702        let err = validate_upgrade_from(&entries).unwrap_err();
3703        assert_eq!(
3704            err,
3705            UpgradeError::DuplicateFrom {
3706                from: "0.1.0".into()
3707            },
3708            "two entries with `:from \"0.1.0\"` must surface as DuplicateFrom carrying the \
3709             offending value verbatim"
3710        );
3711    }
3712
3713    #[test]
3714    fn validate_upgrade_from_treats_pre_release_as_distinct() {
3715        // Negative-of-positive: `1.0.0` and `1.0.0-rc.1` are *not*
3716        // equal under semver (pre-release version is part of the
3717        // identity), so they're distinct upgrade paths and must not
3718        // collide. A future tightening that collapses pre-release into
3719        // the release version surfaces here.
3720        let entries = vec![
3721            entry("1.0.0", vec![UpgradeInstruction::Restart]),
3722            entry("1.0.0-rc.1", vec![UpgradeInstruction::Restart]),
3723        ];
3724        validate_upgrade_from(&entries).unwrap();
3725    }
3726
3727    #[test]
3728    fn validate_upgrade_from_treats_build_metadata_as_distinct() {
3729        // Conservative-by-design: [`semver::Version`]'s `PartialEq`
3730        // compares build metadata (it derives equality across all
3731        // fields including `pre` + `build`), so `1.0.0+build1` and
3732        // `1.0.0+build2` are *not* duplicates from the gate's
3733        // perspective — the operator may treat the build-metadata
3734        // suffix as a tiebreaker even though the semver spec says
3735        // build metadata is ignored for precedence
3736        // (https://semver.org/#spec-item-10). Pin the conservative
3737        // behavior here so a future switch to a build-metadata-
3738        // stripping comparator surfaces as a test failure first; that
3739        // change would require coordinating with the wasm-operator's
3740        // `:from`-match dispatch step, which is the load-bearing
3741        // semantic we'd be mirroring.
3742        let entries = vec![
3743            entry("1.0.0+build1", vec![UpgradeInstruction::Restart]),
3744            entry("1.0.0+build2", vec![UpgradeInstruction::Restart]),
3745        ];
3746        validate_upgrade_from(&entries).unwrap();
3747    }
3748
3749    #[test]
3750    fn validate_upgrade_from_per_entry_shape_fires_before_duplicate() {
3751        // Order pin: a malformed `:from` on the second entry surfaces
3752        // its `FromInvalid` diagnostic, not a (less-useful)
3753        // `DuplicateFrom`. The per-entry shape pass runs *inline*
3754        // before the duplicate-key insert — parallel to
3755        // `child_versao_invalid_fires_before_duplicate_check`
3756        // (b38ff3a) and `membro_versao_invalid_fires_before_duplicate_check`
3757        // (9888b13). Without this pin a future shortcut that runs the
3758        // cross-entry gate first would surface a duplicate diagnostic
3759        // on a string that isn't even parsable as a version.
3760        let entries = vec![
3761            entry("0.1.0", vec![UpgradeInstruction::Restart]),
3762            entry("not-a-semver", vec![UpgradeInstruction::Restart]),
3763        ];
3764        let err = validate_upgrade_from(&entries).unwrap_err();
3765        assert!(
3766            matches!(err, UpgradeError::FromInvalid { ref from, .. } if from == "not-a-semver"),
3767            "malformed `:from` on a non-duplicate entry must surface as FromInvalid, got {err:?}"
3768        );
3769    }
3770
3771    #[test]
3772    fn validate_upgrade_from_per_entry_shape_fires_before_duplicate_on_first_entry() {
3773        // Symmetric arm: a malformed shape on the *first* entry of a
3774        // duplicate pair surfaces its per-entry diagnostic too (not
3775        // the duplicate diagnostic that would otherwise fire on the
3776        // second entry). Pinned separately so a future shortcut that
3777        // walks the duplicate-check ahead of the per-entry pass for the
3778        // first entry only — easy regression to introduce — surfaces
3779        // here.
3780        let entries = vec![
3781            entry(
3782                "0.1.0",
3783                vec![UpgradeInstruction::LoadModule {
3784                    module: String::new(),
3785                }],
3786            ),
3787            entry("0.1.0", vec![UpgradeInstruction::Restart]),
3788        ];
3789        let err = validate_upgrade_from(&entries).unwrap_err();
3790        assert_eq!(
3791            err,
3792            UpgradeError::ModuleEmpty {
3793                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
3794            },
3795            "malformed instruction on the first entry of a duplicate pair must surface its \
3796             per-entry diagnostic before the duplicate gate fires, got {err:?}"
3797        );
3798    }
3799
3800    #[test]
3801    fn validate_upgrade_from_duplicate_diagnostic_names_second_collision() {
3802        // Diagnostic-shape pin: when three entries carry the same
3803        // `:from`, the gate reports the *first* collision (the second
3804        // entry) and stops — the third entry's duplicate is masked by
3805        // the first surfaced one. Mirrors
3806        // `validate_duplicate_child_diagnostic_names_first_collision`
3807        // (dbf50a9) on the supervisor axis.
3808        let entries = vec![
3809            entry("0.1.0", vec![UpgradeInstruction::Restart]),
3810            entry("0.1.0", vec![UpgradeInstruction::Restart]),
3811            entry("0.1.0", vec![UpgradeInstruction::Restart]),
3812        ];
3813        let err = validate_upgrade_from(&entries).unwrap_err();
3814        assert_eq!(
3815            err,
3816            UpgradeError::DuplicateFrom {
3817                from: "0.1.0".into()
3818            }
3819        );
3820    }
3821
3822    #[test]
3823    fn validate_upgrade_from_single_entry_never_duplicates() {
3824        // Boundary control: a list of one entry can never produce a
3825        // duplicate, regardless of `:from` value (any single-element
3826        // set is trivially without duplicates). Pin this so a future
3827        // off-by-one in the seen-set insert doesn't accidentally flag
3828        // a single entry as duplicating itself.
3829        let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
3830        validate_upgrade_from(&entries).unwrap();
3831    }
3832
3833    // ── validate_upgrade_from_against_versao: cross-slot precedence gate ─
3834
3835    #[test]
3836    fn versao_gate_accepts_strict_upgrade() {
3837        // Positive control: the canonical "chain prior versions →
3838        // current" authoring shape from ABSORPTION-ROADMAP §M2.3 — each
3839        // `:from` strictly less than the current `:versao` under
3840        // SemVer-2 precedence. The gate must not regress this baseline.
3841        let entries = vec![
3842            entry("0.1.0", vec![UpgradeInstruction::Restart]),
3843            entry("0.1.5", vec![UpgradeInstruction::Restart]),
3844            entry("0.1.9", vec![UpgradeInstruction::Restart]),
3845        ];
3846        validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
3847    }
3848
3849    #[test]
3850    fn versao_gate_accepts_empty_entries() {
3851        // Bare `feira init` shape (no `:upgrade-from`) trivially passes;
3852        // the gate is a no-op when the entries list is empty. Mirrors
3853        // `validate_upgrade_from_accepts_empty_list` on the peer gate.
3854        validate_upgrade_from_against_versao(&[], "0.1.0").unwrap();
3855    }
3856
3857    #[test]
3858    fn versao_gate_rejects_equal_from() {
3859        // Self-upgrade no-op: declaring `:from "0.2.0"` while
3860        // `:versao "0.2.0"` means "upgrade from myself to myself" —
3861        // the operator's dispatch either skips silently or
3862        // trivially "succeeds" with no observable state change.
3863        // Reject as the canonical "I forgot to bump :versao when
3864        // adding this entry" footgun.
3865        let entries = vec![entry("0.2.0", vec![UpgradeInstruction::Restart])];
3866        let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
3867        assert_eq!(
3868            err,
3869            UpgradeError::FromNotBeforeVersao {
3870                from: "0.2.0".into(),
3871                versao: "0.2.0".into(),
3872            },
3873            ":from == :versao under precedence must surface as FromNotBeforeVersao naming both \
3874             values verbatim, got {err:?}"
3875        );
3876    }
3877
3878    #[test]
3879    fn versao_gate_rejects_downgrade_from() {
3880        // Downgrade-shaped: `:from "0.3.0"` while `:versao "0.2.0"`
3881        // means "upgrade nodes coming from 0.3.0 to 0.2.0", which
3882        // the operator's `:from`-match dispatch can never reach (it
3883        // never runs a version >= the current one). Reject as the
3884        // canonical "I copy-pasted from the next minor version and
3885        // forgot to bump :versao" footgun.
3886        let entries = vec![entry("0.3.0", vec![UpgradeInstruction::Restart])];
3887        let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
3888        assert_eq!(
3889            err,
3890            UpgradeError::FromNotBeforeVersao {
3891                from: "0.3.0".into(),
3892                versao: "0.2.0".into(),
3893            }
3894        );
3895    }
3896
3897    #[test]
3898    fn versao_gate_accepts_prerelease_before_release() {
3899        // SemVer §11 precedence: pre-release versions are *less than*
3900        // the corresponding release (`0.2.0-rc.1 < 0.2.0`). Upgrading
3901        // FROM an RC TO the GA release is the canonical authoring
3902        // shape — must pass. A regression that collapses pre-release
3903        // into the release version (treating them as equal) surfaces
3904        // here as a false-positive rejection.
3905        let entries = vec![entry("0.2.0-rc.1", vec![UpgradeInstruction::Restart])];
3906        validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
3907    }
3908
3909    #[test]
3910    fn versao_gate_rejects_release_after_prerelease() {
3911        // Symmetric arm: with `:versao "0.2.0-rc.1"` and
3912        // `:from "0.2.0"`, precedence says `0.2.0 > 0.2.0-rc.1` —
3913        // the typical "I'm on an RC of a release that already
3914        // shipped" footgun. The gate names both values verbatim
3915        // so the author can grep for either side and fix in one
3916        // edit.
3917        let entries = vec![entry("0.2.0", vec![UpgradeInstruction::Restart])];
3918        let err = validate_upgrade_from_against_versao(&entries, "0.2.0-rc.1").unwrap_err();
3919        assert_eq!(
3920            err,
3921            UpgradeError::FromNotBeforeVersao {
3922                from: "0.2.0".into(),
3923                versao: "0.2.0-rc.1".into(),
3924            }
3925        );
3926    }
3927
3928    #[test]
3929    fn versao_gate_rejects_build_metadata_only_difference() {
3930        // SemVer §11 explicitly excludes build metadata from
3931        // precedence comparison: `0.2.0+build.1` and `0.2.0` are
3932        // *equal* under [`semver::Version::cmp`]. From the
3933        // operator's `:from`-match dispatch perspective this is a
3934        // self-upgrade no-op (no semantic transition between the
3935        // two), so the gate rejects it — *unlike* the peer
3936        // duplicate-`:from` gate which uses derived `PartialEq` and
3937        // treats build-metadata variants as distinct dispatch keys.
3938        // The two gates' different equality notions are deliberate:
3939        // duplicate-check is conservative (preserves operator-side
3940        // tiebreaking surface), precedence-check is permissive
3941        // (matches operator-side dispatch semantic).
3942        let entries = vec![entry("0.2.0+build.1", vec![UpgradeInstruction::Restart])];
3943        let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
3944        assert_eq!(
3945            err,
3946            UpgradeError::FromNotBeforeVersao {
3947                from: "0.2.0+build.1".into(),
3948                versao: "0.2.0".into(),
3949            }
3950        );
3951    }
3952
3953    #[test]
3954    fn versao_gate_silently_passes_on_unparseable_versao() {
3955        // Defensive arm: a malformed `:versao` (gated by the
3956        // narrower `ManifestError::VersaoInvalid` surface at the
3957        // load-bearing call site) must not regress into a
3958        // `FromNotBeforeVersao` diagnostic from this gate. Surfacing
3959        // the precedence error over an unparseable `:versao` would
3960        // mask the more actionable root cause (the author meant to
3961        // type `"0.2.0"`, not `"v0.2.0"`).
3962        let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
3963        validate_upgrade_from_against_versao(&entries, "not-a-semver").unwrap();
3964    }
3965
3966    #[test]
3967    fn versao_gate_silently_passes_on_unparseable_from() {
3968        // Symmetric defensive arm: a malformed `:from` is gated by
3969        // [`UpgradeFromEntry::validate`] / [`validate_upgrade_from`]
3970        // upstream at the LayoutInvariants call site. Surfacing the
3971        // precedence error over an unparseable `:from` from this
3972        // gate alone would mask the narrower `FromInvalid`
3973        // diagnostic that's expected to lead — same fall-through
3974        // posture as the unparseable-`:versao` arm above. The
3975        // wiring in `LayoutInvariants::verify` runs
3976        // `validate_upgrade_from` *before* this gate, so in practice
3977        // an unparseable `:from` surfaces as `FromInvalid` first
3978        // and this gate is never reached on that input.
3979        let entries = vec![entry("not-a-semver", vec![UpgradeInstruction::Restart])];
3980        validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap();
3981    }
3982
3983    #[test]
3984    fn versao_gate_reports_first_offending_entry() {
3985        // Determinism pin: with multiple offending entries the gate
3986        // surfaces the *first* one in declaration order — same
3987        // posture as `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
3988        // on the peer gate. Walks the entries in order; first
3989        // failing `:from >= :versao` short-circuits.
3990        let entries = vec![
3991            entry("0.1.0", vec![UpgradeInstruction::Restart]),
3992            entry("0.3.0", vec![UpgradeInstruction::Restart]),
3993            entry("0.4.0", vec![UpgradeInstruction::Restart]),
3994        ];
3995        let err = validate_upgrade_from_against_versao(&entries, "0.2.0").unwrap_err();
3996        assert_eq!(
3997            err,
3998            UpgradeError::FromNotBeforeVersao {
3999                from: "0.3.0".into(),
4000                versao: "0.2.0".into(),
4001            },
4002            "the first offending `:from` (0.3.0) must surface, not the later one (0.4.0)"
4003        );
4004    }
4005
4006    // ── UpgradeFromEntry::validate_restart_exclusive: within-entry gate ─
4007
4008    #[test]
4009    fn validate_rejects_restart_mixed_with_load_module() {
4010        // The "I'll try the typed path *then* restart anyway" footgun:
4011        // an instructions list with `(:restart)` plus `(:load-module …)`
4012        // is dead code in both directions (succeed → restart discards
4013        // the work that just succeeded, defeating the typed sequence's
4014        // whole point; fail → restart never reached because the entry
4015        // already failed). The gate names the offending entry's `:from`
4016        // verbatim plus the kebab-case lisp-form of every non-`:restart`
4017        // peer so the author can grep their caixa.lisp for either side
4018        // and fix in one edit.
4019        let e = entry(
4020            "0.1.0",
4021            vec![
4022                UpgradeInstruction::LoadModule {
4023                    module: "hello-rio".into(),
4024                },
4025                UpgradeInstruction::Restart,
4026            ],
4027        );
4028        let err = e.validate().unwrap_err();
4029        assert_eq!(
4030            err,
4031            UpgradeError::RestartNotExclusive {
4032                from: "0.1.0".into(),
4033                restart_count: 1,
4034                other_kinds: vec![crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE],
4035            },
4036            "restart + load-module mix must surface as RestartNotExclusive naming the \
4037             offending `:from` + the non-:restart kinds verbatim, got {err:?}"
4038        );
4039    }
4040
4041    #[test]
4042    fn validate_rejects_restart_mixed_with_full_typed_sequence() {
4043        // Sweep the typed-sequence universe — every non-`:restart`
4044        // variant alongside `:restart` — and assert every typed
4045        // instruction's lisp-form appears in `other_kinds` in
4046        // declaration order. The author should be able to grep for
4047        // each verbatim (`:load-module`, `:state-change`, `:soft-purge`,
4048        // `:purge`) and resolve in one pass. Drift in the `lisp_form`
4049        // mapping surfaces here.
4050        let e = entry(
4051            "0.1.0",
4052            vec![
4053                UpgradeInstruction::LoadModule {
4054                    module: "hello-rio".into(),
4055                },
4056                UpgradeInstruction::StateChange {
4057                    script: PathBuf::from("lib/m.lisp"),
4058                },
4059                UpgradeInstruction::SoftPurge {
4060                    module: "hello-rio-old".into(),
4061                },
4062                UpgradeInstruction::Purge {
4063                    module: "hello-rio-old".into(),
4064                },
4065                UpgradeInstruction::Restart,
4066            ],
4067        );
4068        let err = e.validate().unwrap_err();
4069        assert_eq!(
4070            err,
4071            UpgradeError::RestartNotExclusive {
4072                from: "0.1.0".into(),
4073                restart_count: 1,
4074                other_kinds: vec![
4075                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
4076                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
4077                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4078                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4079                ],
4080            },
4081        );
4082    }
4083
4084    #[test]
4085    fn validate_rejects_restart_duplicated() {
4086        // `((:restart) (:restart))` — multiple Restart variants in one
4087        // entry. The fallback is a single semantic (restart the pod;
4088        // the new version comes up fresh); repeating it is at best
4089        // redundant, at worst suggests the author thought the second
4090        // would re-trigger after the first. The gate reports
4091        // `restart_count: 2` so the diagnostic surfaces the duplication
4092        // mode unambiguously even when `other_kinds` is empty.
4093        let e = entry(
4094            "0.1.0",
4095            vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
4096        );
4097        let err = e.validate().unwrap_err();
4098        assert_eq!(
4099            err,
4100            UpgradeError::RestartNotExclusive {
4101                from: "0.1.0".into(),
4102                restart_count: 2,
4103                other_kinds: vec![],
4104            },
4105        );
4106    }
4107
4108    #[test]
4109    fn validate_accepts_sole_restart() {
4110        // Positive control: the canonical "this prior version's typed
4111        // upgrade is impossible — restart" authoring shape from the
4112        // UpgradeInstruction::Restart doc comment. `((:restart))` alone
4113        // is the entry's whole instructions list and the only valid
4114        // Restart-bearing shape.
4115        let e = entry("0.1.0", vec![UpgradeInstruction::Restart]);
4116        e.validate().unwrap();
4117    }
4118
4119    #[test]
4120    fn validate_accepts_typed_sequence_without_restart() {
4121        // Positive control: the canonical typed hot-upgrade authoring
4122        // shape from ABSORPTION-ROADMAP §M2.3 — `:load-module` →
4123        // `:state-change` → `:soft-purge`. Absent `:restart` is the
4124        // only shape that lets the sequence run to completion under
4125        // the wasm-operator's `:from`-match dispatch. Drift here =
4126        // a future tighten that rejects any canonical typed-only shape
4127        // surfaces as a regression at this gate.
4128        let e = entry(
4129            "0.1.0",
4130            vec![
4131                UpgradeInstruction::LoadModule {
4132                    module: "hello-rio".into(),
4133                },
4134                UpgradeInstruction::StateChange {
4135                    script: PathBuf::from("lib/m.lisp"),
4136                },
4137                UpgradeInstruction::SoftPurge {
4138                    module: "hello-rio-old".into(),
4139                },
4140            ],
4141        );
4142        e.validate().unwrap();
4143    }
4144
4145    // ── within-entry state-change-ordering invariant ───────────────────
4146
4147    #[test]
4148    fn validate_rejects_state_change_without_load() {
4149        // Fail-before-pass-after pin: a `:state-change` migrates state
4150        // into the newly-loaded code (gen_server:code_change/3 analog),
4151        // so an entry that runs it with no preceding `:load-module`
4152        // migrates state into code that was never loaded. The operator
4153        // runs instructions in declared order, so this is a build error,
4154        // not a runtime surprise (CAIXA-SDLC §III).
4155        let e = entry(
4156            "0.1.0",
4157            vec![UpgradeInstruction::StateChange {
4158                script: PathBuf::from("lib/m.lisp"),
4159            }],
4160        );
4161        let err = e.validate().unwrap_err();
4162        assert_eq!(
4163            err,
4164            UpgradeError::StateChangeWithoutPriorLoad {
4165                from: "0.1.0".into(),
4166                script: PathBuf::from("lib/m.lisp"),
4167            },
4168            "a `:state-change` with no preceding `:load-module` must surface as \
4169             StateChangeWithoutPriorLoad naming the offending entry + script verbatim"
4170        );
4171    }
4172
4173    #[test]
4174    fn validate_rejects_state_change_before_load() {
4175        // Right-instructions-wrong-order: the load is present but runs
4176        // *after* the migration. Because the operator executes in
4177        // declared order, the migration runs before the new code is
4178        // resident — the same incoherence as the missing-load case.
4179        let e = entry(
4180            "0.1.0",
4181            vec![
4182                UpgradeInstruction::StateChange {
4183                    script: PathBuf::from("lib/m.lisp"),
4184                },
4185                UpgradeInstruction::LoadModule {
4186                    module: "hello-rio".into(),
4187                },
4188            ],
4189        );
4190        let err = e.validate().unwrap_err();
4191        assert!(
4192            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
4193            "a `:state-change` ahead of its `:load-module` must surface as \
4194             StateChangeWithoutPriorLoad, got {err:?}"
4195        );
4196    }
4197
4198    #[test]
4199    fn validate_accepts_state_change_after_load() {
4200        // Positive control: the canonical `(:load-module …)
4201        // (:state-change …)` order validates. The load need not name
4202        // the same module the migration targets (StateChange carries a
4203        // script, not a module ref), so any preceding `:load-module`
4204        // satisfies "new code is resident before its migration runs".
4205        let e = entry(
4206            "0.1.0",
4207            vec![
4208                UpgradeInstruction::LoadModule {
4209                    module: "hello-rio".into(),
4210                },
4211                UpgradeInstruction::StateChange {
4212                    script: PathBuf::from("lib/m.lisp"),
4213                },
4214            ],
4215        );
4216        e.validate().unwrap();
4217    }
4218
4219    #[test]
4220    fn validate_accepts_multiple_state_changes_after_one_load() {
4221        // A single leading `:load-module` covers every subsequent
4222        // `:state-change` — the `loaded` latch stays set once the new
4223        // code is resident.
4224        let e = entry(
4225            "0.1.0",
4226            vec![
4227                UpgradeInstruction::LoadModule {
4228                    module: "hello-rio".into(),
4229                },
4230                UpgradeInstruction::StateChange {
4231                    script: PathBuf::from("lib/m1.lisp"),
4232                },
4233                UpgradeInstruction::StateChange {
4234                    script: PathBuf::from("lib/m2.lisp"),
4235                },
4236            ],
4237        );
4238        e.validate().unwrap();
4239    }
4240
4241    #[test]
4242    fn validate_state_change_ordering_projects_scripts_through_is_load_module_and_declared_path_accessors()
4243     {
4244        // Byte-identity pin on the
4245        // [`UpgradeFromEntry::validate_state_change_ordering`] load →
4246        // migrate ordering dispatch against the pre-lift
4247        // `match instr { UpgradeInstruction::LoadModule { .. } =>
4248        // loaded = true, UpgradeInstruction::StateChange { script } if
4249        // !loaded => …, _ => {} }` open-coded pattern-match the site
4250        // previously carried. Asserts the two projections agree
4251        // byte-for-byte on every arm of the enum — the load-family
4252        // arm-discriminator via `is_load_module()` and the migration-
4253        // family `:script` scalar via `declared_path()` — so a future
4254        // derive regression that flipped the predicate's arm-set (a
4255        // hole returning `false` for [`UpgradeInstruction::LoadModule`],
4256        // a byte-collision flipping a second variant to `true`) or an
4257        // accessor extension that promoted an additional variant onto
4258        // the `PathBuf`-carrying axis would trip here at caixa-core
4259        // test time rather than laundering the arm at the gate's
4260        // per-entry ordering scan far from the derive site.
4261        //
4262        // Peer of the sibling
4263        // [`validate_load_singularity_projects_modules_through_is_load_module_and_declared_module_accessors`]
4264        // (c9ce91d) pin on the peer within-entry per-instruction-class
4265        // singularity gate's load-family + `String`-carrying dispatch,
4266        // the [`validate_purge_ordering_routes_through_is_load_module_predicate`]
4267        // (580d0f1) pin on the paired load → cleanup ordering gate's
4268        // load-family sticky-latch dispatch, and the
4269        // [`validate_state_change_singularity_projects_scripts_through_declared_path_accessor`]
4270        // pin on the peer within-entry per-instruction-class singularity
4271        // gate's migration-family script-projection dispatch — closes
4272        // the last unlifted `match`-shaped per-arm-hand-rolled load-
4273        // family arm-discriminator + migration-family script-projection
4274        // pair inside `impl UpgradeFromEntry`. The four within-entry
4275        // ordering / singularity gates now share one byte-identity pin
4276        // apiece against their respective substrate-primitive typed
4277        // dispatches on the OTP-appup closed-set enum.
4278        //
4279        // Three-arm projective coverage:
4280        //   (a) `LoadModule` satisfies `is_load_module()`, so the
4281        //       sticky-latch advances byte-equal to the pre-lift
4282        //       `UpgradeInstruction::LoadModule { .. }` arm; every
4283        //       other variant leaves the latch untouched;
4284        //   (b) a `((:state-change …))`-only entry (no preceding load)
4285        //       trips the gate on the first `StateChange` with
4286        //       `StateChangeWithoutPriorLoad` carrying the offending
4287        //       script verbatim — the migration-family script surfaces
4288        //       through `declared_path()` byte-equal to the raw
4289        //       `StateChange { script }` pattern-bound field;
4290        //   (c) a `((:load-module …) (:state-change …))` entry leaves
4291        //       the gate vacuous with `Ok(())` — the `loaded = true`
4292        //       latch on the first arm satisfies the `!loaded` guard
4293        //       negation on the second, so the `declared_path()`
4294        //       `Some(script)` fall-through does not fire — and a
4295        //       non-`StateChange`-non-`LoadModule` sequence
4296        //       (`SoftPurge` / `Purge` / `Restart` alone) also leaves
4297        //       the gate vacuous because `declared_path()` is `None`
4298        //       on all three of those arms.
4299        //
4300        // Fail-before-pass-after verified locally: swapping the
4301        // production `if instr.is_load_module() { loaded = true; }
4302        // else if !loaded && let Some(script) = instr.declared_path()
4303        // { … }` back to `match instr { UpgradeInstruction::LoadModule
4304        // { .. } => loaded = true, UpgradeInstruction::StateChange
4305        // { script } if !loaded => …, _ => {} }` keeps arms (a)-(c)
4306        // passing but silently detaches the gate from the accessor's
4307        // typed dispatch — any future `is_load_module` / `declared_path`
4308        // extension (a hole in either predicate, a promotion of an
4309        // additional variant onto either axis, an operator-side
4310        // pre-resolved-path cache the accessor materializes) would
4311        // then silently disagree between this gate's raw pattern-match
4312        // and the peer per-`UpgradeInstruction` consumers that route
4313        // through the accessor pair.
4314
4315        // (a) is_load_module() partitions the arm-set byte-equal to
4316        //     the pre-lift `matches!(_, UpgradeInstruction::LoadModule
4317        //     { .. })` and declared_path() surfaces the StateChange
4318        //     `:script` byte-equal to the raw field access.
4319        let lm = UpgradeInstruction::LoadModule {
4320            module: "hello-rio".into(),
4321        };
4322        assert!(
4323            lm.is_load_module(),
4324            "LoadModule must satisfy is_load_module() — the gate's \
4325             load-family sticky-latch relies on this partition"
4326        );
4327        assert!(
4328            lm.declared_path().is_none(),
4329            "LoadModule must not carry a declared_path — the gate's \
4330             else-if migration-family arm must not fire on load arms"
4331        );
4332        let sc = UpgradeInstruction::StateChange {
4333            script: PathBuf::from("lib/m.lisp"),
4334        };
4335        assert!(
4336            !sc.is_load_module(),
4337            "StateChange must not satisfy is_load_module() — the gate's \
4338             sticky-latch must not advance on migration arms"
4339        );
4340        assert_eq!(
4341            sc.declared_path().map(std::path::PathBuf::as_path),
4342            Some(PathBuf::from("lib/m.lisp").as_path()),
4343            "declared_path() must project the StateChange :script \
4344             byte-equal to the raw field access — accessor divergence \
4345             would silently detach the gate from the projection every \
4346             peer per-`UpgradeInstruction` consumer routes through"
4347        );
4348
4349        // (b) A `((:state-change …))`-only entry trips
4350        //     StateChangeWithoutPriorLoad byte-identical to the
4351        //     pre-lift match-pattern shape.
4352        let no_prior_load = entry(
4353            "0.1.0",
4354            vec![UpgradeInstruction::StateChange {
4355                script: PathBuf::from("lib/m.lisp"),
4356            }],
4357        );
4358        assert_eq!(
4359            no_prior_load.validate_state_change_ordering(),
4360            Err(UpgradeError::StateChangeWithoutPriorLoad {
4361                from: "0.1.0".into(),
4362                script: PathBuf::from("lib/m.lisp"),
4363            }),
4364            "a `:state-change` with no preceding `:load-module` must fire \
4365             StateChangeWithoutPriorLoad carrying the offending script \
4366             verbatim through the declared_path() accessor"
4367        );
4368
4369        // (c) `((:load-module …) (:state-change …))` leaves the gate
4370        //     vacuous; so does a non-StateChange-non-LoadModule
4371        //     sequence (SoftPurge / Purge / Restart alone).
4372        let load_before_migrate = entry(
4373            "0.1.0",
4374            vec![
4375                UpgradeInstruction::LoadModule {
4376                    module: "hello-rio".into(),
4377                },
4378                UpgradeInstruction::StateChange {
4379                    script: PathBuf::from("lib/m.lisp"),
4380                },
4381            ],
4382        );
4383        assert_eq!(
4384            load_before_migrate.validate_state_change_ordering(),
4385            Ok(()),
4386            "load-before-migrate entries must leave the ordering gate \
4387             vacuous — the `loaded = true` sticky-latch on the first arm \
4388             satisfies the `!loaded` guard negation on the else-if arm"
4389        );
4390        for instr in [
4391            UpgradeInstruction::SoftPurge {
4392                module: "x-old".into(),
4393            },
4394            UpgradeInstruction::Purge {
4395                module: "x-old".into(),
4396            },
4397            UpgradeInstruction::Restart,
4398        ] {
4399            let e = entry("0.1.0", vec![instr.clone()]);
4400            assert_eq!(
4401                e.validate_state_change_ordering(),
4402                Ok(()),
4403                "non-StateChange-non-LoadModule sequence ({instr:?}) must \
4404                 leave the ordering gate vacuous — declared_path() is None \
4405                 on every non-StateChange arm, so the else-if migration-\
4406                 family arm never fires"
4407            );
4408        }
4409    }
4410
4411    #[test]
4412    fn validate_state_change_ordering_fires_after_restart_exclusive() {
4413        // Diagnostic-precedence pin: a `((:state-change …) (:restart))`
4414        // shape is *both* state-change-without-load and restart-mixed.
4415        // The more-fundamental `RestartNotExclusive` must win (a valid
4416        // `(:restart)` entry is `(:restart)` alone, so no Restart-bearing
4417        // entry should reach the ordering gate). Guards the call order
4418        // in `validate` against silent reordering.
4419        let e = entry(
4420            "0.1.0",
4421            vec![
4422                UpgradeInstruction::StateChange {
4423                    script: PathBuf::from("lib/m.lisp"),
4424                },
4425                UpgradeInstruction::Restart,
4426            ],
4427        );
4428        let err = e.validate().unwrap_err();
4429        assert!(
4430            matches!(err, UpgradeError::RestartNotExclusive { .. }),
4431            "restart-mixed must surface before the ordering gate, got {err:?}"
4432        );
4433    }
4434
4435    // ── within-entry purge-ordering invariant ──────────────────────────
4436
4437    #[test]
4438    fn validate_rejects_soft_purge_without_load() {
4439        // Fail-before-pass-after pin: `:soft-purge` drains the *old*
4440        // module after the new one is resident (OTP's two-phase code
4441        // load — code:load_module/1 then code:soft_purge/1), so an
4442        // entry that runs it with no preceding `:load-module` drains
4443        // the live module with no replacement. The operator runs
4444        // instructions in declared order, so this is a build error,
4445        // not a runtime surprise (CAIXA-SDLC §III).
4446        let e = entry(
4447            "0.1.0",
4448            vec![UpgradeInstruction::SoftPurge {
4449                module: "x-old".into(),
4450            }],
4451        );
4452        let err = e.validate().unwrap_err();
4453        assert_eq!(
4454            err,
4455            UpgradeError::PurgeWithoutPriorLoad {
4456                from: "0.1.0".into(),
4457                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4458                module: "x-old".into(),
4459            },
4460            "a `:soft-purge` with no preceding `:load-module` must surface as \
4461             PurgeWithoutPriorLoad naming the offending entry + kind + module verbatim"
4462        );
4463    }
4464
4465    #[test]
4466    fn validate_rejects_purge_without_load() {
4467        // Per-arm coverage: `:purge` (immediate discard, no drain) is
4468        // the more catastrophic peer of `:soft-purge`; same gate, same
4469        // shape, kind-tag differs so the author can grep their
4470        // caixa.lisp for the offending `(:purge …)` form.
4471        let e = entry(
4472            "0.1.0",
4473            vec![UpgradeInstruction::Purge {
4474                module: "x-old".into(),
4475            }],
4476        );
4477        let err = e.validate().unwrap_err();
4478        assert_eq!(
4479            err,
4480            UpgradeError::PurgeWithoutPriorLoad {
4481                from: "0.1.0".into(),
4482                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4483                module: "x-old".into(),
4484            },
4485        );
4486    }
4487
4488    #[test]
4489    fn validate_rejects_soft_purge_before_load() {
4490        // Right-instructions-wrong-order: the load is present but runs
4491        // *after* the purge. Because the operator executes in declared
4492        // order, the cleanup drains the old code before the new code
4493        // is resident — same incoherence as the missing-load case,
4494        // leaving a window during which neither version is available.
4495        let e = entry(
4496            "0.1.0",
4497            vec![
4498                UpgradeInstruction::SoftPurge {
4499                    module: "x-old".into(),
4500                },
4501                UpgradeInstruction::LoadModule { module: "x".into() },
4502            ],
4503        );
4504        let err = e.validate().unwrap_err();
4505        assert!(
4506            matches!(
4507                err,
4508                UpgradeError::PurgeWithoutPriorLoad {
4509                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4510                    ..
4511                }
4512            ),
4513            "a `:soft-purge` ahead of its `:load-module` must surface as \
4514             PurgeWithoutPriorLoad, got {err:?}"
4515        );
4516    }
4517
4518    #[test]
4519    fn validate_rejects_purge_before_load() {
4520        // Symmetric arm on the `:purge` variant — the kind tag
4521        // distinguishes the diagnostic so the author lands on the
4522        // offending form directly.
4523        let e = entry(
4524            "0.1.0",
4525            vec![
4526                UpgradeInstruction::Purge {
4527                    module: "x-old".into(),
4528                },
4529                UpgradeInstruction::LoadModule { module: "x".into() },
4530            ],
4531        );
4532        let err = e.validate().unwrap_err();
4533        assert!(
4534            matches!(
4535                err,
4536                UpgradeError::PurgeWithoutPriorLoad {
4537                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4538                    ..
4539                }
4540            ),
4541            "a `:purge` ahead of its `:load-module` must surface as \
4542             PurgeWithoutPriorLoad, got {err:?}"
4543        );
4544    }
4545
4546    #[test]
4547    fn validate_accepts_soft_purge_after_load() {
4548        // Positive control: the canonical `(:load-module …)
4549        // (:soft-purge …)` order validates. The load need not name the
4550        // same module the purge targets — the cleanup typically targets
4551        // the *old* module name (e.g. `"x-old"`) and the load brings up
4552        // the *new* one (`"x"`); the gate only requires that *some*
4553        // `:load-module` precedes the purge, so the new code is resident
4554        // before the old one is drained.
4555        let e = entry(
4556            "0.1.0",
4557            vec![
4558                UpgradeInstruction::LoadModule { module: "x".into() },
4559                UpgradeInstruction::SoftPurge {
4560                    module: "x-old".into(),
4561                },
4562            ],
4563        );
4564        e.validate().unwrap();
4565    }
4566
4567    #[test]
4568    fn validate_accepts_multiple_purges_after_one_load() {
4569        // A single leading `:load-module` covers every subsequent
4570        // `:soft-purge` / `:purge` — the `loaded` latch stays set once
4571        // the new code is resident. Same shape as
4572        // `validate_accepts_multiple_state_changes_after_one_load` on
4573        // the peer ordering gate.
4574        let e = entry(
4575            "0.1.0",
4576            vec![
4577                UpgradeInstruction::LoadModule { module: "x".into() },
4578                UpgradeInstruction::SoftPurge {
4579                    module: "x-old".into(),
4580                },
4581                UpgradeInstruction::Purge {
4582                    module: "x-oldest".into(),
4583                },
4584            ],
4585        );
4586        e.validate().unwrap();
4587    }
4588
4589    #[test]
4590    fn validate_purge_ordering_fires_after_state_change_ordering() {
4591        // Diagnostic-precedence pin: an entry like `((:state-change …)
4592        // (:soft-purge …))` is *both* state-change-without-load and
4593        // purge-without-load. The state-change gate must win — it's
4594        // the load-bearing semantic on this ordering contract, and
4595        // surfacing the purge diagnostic first would mask the more-
4596        // fundamental migration-against-stale-code defect. Guards the
4597        // call order in `validate` against silent reordering.
4598        let e = entry(
4599            "0.1.0",
4600            vec![
4601                UpgradeInstruction::StateChange {
4602                    script: PathBuf::from("lib/m.lisp"),
4603                },
4604                UpgradeInstruction::SoftPurge {
4605                    module: "x-old".into(),
4606                },
4607            ],
4608        );
4609        let err = e.validate().unwrap_err();
4610        assert!(
4611            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
4612            "state-change-without-load must surface before purge-without-load, got {err:?}"
4613        );
4614    }
4615
4616    #[test]
4617    fn validate_purge_ordering_fires_after_per_instr_shape() {
4618        // Order pin: a malformed `:module` value on a `:soft-purge` (an
4619        // empty string) surfaces its narrower kind-tagged `ModuleEmpty`
4620        // diagnostic *before* the within-entry purge-ordering gate fires.
4621        // The per-instruction shape pass walks the list inline before
4622        // the ordering checks, so the narrower self-locating diagnostic
4623        // surfaces first — mirrors the empty-first cascade on every peer
4624        // DNS-1123 gate and the `validate_restart_exclusive_fires_after_
4625        // per_instr_shape` pin on the sibling ordering gate.
4626        let e = entry(
4627            "0.1.0",
4628            vec![UpgradeInstruction::SoftPurge {
4629                module: String::new(),
4630            }],
4631        );
4632        let err = e.validate().unwrap_err();
4633        assert_eq!(
4634            err,
4635            UpgradeError::ModuleEmpty {
4636                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE
4637            },
4638            "malformed instruction must surface its kind-tagged diagnostic before the \
4639             purge-ordering gate fires, got {err:?}"
4640        );
4641    }
4642
4643    #[test]
4644    fn validate_purge_ordering_threads_through_validate_upgrade_from() {
4645        // The whole-list entry-point surfaces the per-entry ordering
4646        // error (mirrors
4647        // `validate_state_change_ordering_threads_through_validate_upgrade_from`):
4648        // the gate is reachable from the LayoutInvariants call site, not
4649        // only from a direct `entry.validate()`.
4650        let entries = vec![entry(
4651            "0.1.0",
4652            vec![UpgradeInstruction::Purge {
4653                module: "x-old".into(),
4654            }],
4655        )];
4656        let err = validate_upgrade_from(&entries).unwrap_err();
4657        assert!(
4658            matches!(
4659                err,
4660                UpgradeError::PurgeWithoutPriorLoad {
4661                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4662                    ..
4663                }
4664            ),
4665            "validate_upgrade_from must thread the purge-ordering error, got {err:?}"
4666        );
4667    }
4668
4669    #[test]
4670    fn validate_state_change_ordering_threads_through_validate_upgrade_from() {
4671        // The whole-list entry-point surfaces the per-entry ordering
4672        // error (mirrors `validate_restart_exclusive_threads_through_…`):
4673        // the gate is reachable from the LayoutInvariants call site, not
4674        // only from a direct `entry.validate()`.
4675        let entries = vec![entry(
4676            "0.1.0",
4677            vec![UpgradeInstruction::StateChange {
4678                script: PathBuf::from("lib/m.lisp"),
4679            }],
4680        )];
4681        let err = validate_upgrade_from(&entries).unwrap_err();
4682        assert!(
4683            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
4684            "validate_upgrade_from must thread the ordering error, got {err:?}"
4685        );
4686    }
4687
4688    // ── within-entry cleanup-singularity invariant ─────────────────────
4689
4690    #[test]
4691    fn validate_rejects_duplicate_soft_purge_for_same_module() {
4692        // Fail-before-pass-after pin: `:soft-purge` drains-then-GCs
4693        // its target module (code:soft_purge/1 analog); after the
4694        // first the module is gone, so a second `:soft-purge` of the
4695        // same module is at best a no-op and at worst undefined
4696        // (depending on the operator's handling of a non-resident-
4697        // module purge). Author one cleanup per module.
4698        let e = entry(
4699            "0.1.0",
4700            vec![
4701                UpgradeInstruction::LoadModule { module: "x".into() },
4702                UpgradeInstruction::SoftPurge {
4703                    module: "x-old".into(),
4704                },
4705                UpgradeInstruction::SoftPurge {
4706                    module: "x-old".into(),
4707                },
4708            ],
4709        );
4710        let err = e.validate().unwrap_err();
4711        assert_eq!(
4712            err,
4713            UpgradeError::DuplicateCleanup {
4714                from: "0.1.0".into(),
4715                module: "x-old".into(),
4716                kinds: vec![
4717                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4718                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4719                ],
4720            },
4721            "two `:soft-purge` of the same module must surface as DuplicateCleanup naming the \
4722             module + both kinds in declaration order, got {err:?}"
4723        );
4724    }
4725
4726    #[test]
4727    fn validate_rejects_duplicate_purge_for_same_module() {
4728        // Per-arm coverage: `:purge` (immediate discard, no drain) is
4729        // the more catastrophic peer of `:soft-purge`; same gate, same
4730        // shape, kind-tag distinguishes so the author can grep their
4731        // caixa.lisp for the offending `(:purge …)` form.
4732        let e = entry(
4733            "0.1.0",
4734            vec![
4735                UpgradeInstruction::LoadModule { module: "x".into() },
4736                UpgradeInstruction::Purge {
4737                    module: "x-old".into(),
4738                },
4739                UpgradeInstruction::Purge {
4740                    module: "x-old".into(),
4741                },
4742            ],
4743        );
4744        let err = e.validate().unwrap_err();
4745        assert_eq!(
4746            err,
4747            UpgradeError::DuplicateCleanup {
4748                from: "0.1.0".into(),
4749                module: "x-old".into(),
4750                kinds: vec![
4751                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4752                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4753                ],
4754            },
4755        );
4756    }
4757
4758    #[test]
4759    fn validate_rejects_soft_purge_then_purge_for_same_module() {
4760        // Soft-then-hard footgun: the author wrote "drain, and if
4761        // drain doesn't clean up, force-discard", but the operator
4762        // runs declared instructions unconditionally — the `:purge`
4763        // fires whether the `:soft-purge` already discarded the
4764        // module or not, so the imagined fallback semantic is
4765        // missing. Fallback on cleanup failure is the operator's
4766        // job, not authored into the entry. Both kinds carry in
4767        // declaration order so the author can grep for either side
4768        // and pick one.
4769        let e = entry(
4770            "0.1.0",
4771            vec![
4772                UpgradeInstruction::LoadModule { module: "x".into() },
4773                UpgradeInstruction::SoftPurge {
4774                    module: "x-old".into(),
4775                },
4776                UpgradeInstruction::Purge {
4777                    module: "x-old".into(),
4778                },
4779            ],
4780        );
4781        let err = e.validate().unwrap_err();
4782        assert_eq!(
4783            err,
4784            UpgradeError::DuplicateCleanup {
4785                from: "0.1.0".into(),
4786                module: "x-old".into(),
4787                kinds: vec![
4788                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4789                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4790                ],
4791            },
4792        );
4793    }
4794
4795    #[test]
4796    fn validate_rejects_purge_then_soft_purge_for_same_module() {
4797        // Reversed-ordering arm: `:purge` discards immediately; the
4798        // trailing `:soft-purge` has no module to drain. The kinds
4799        // list reflects declaration order so the diagnostic locates
4800        // both forms in the source.
4801        let e = entry(
4802            "0.1.0",
4803            vec![
4804                UpgradeInstruction::LoadModule { module: "x".into() },
4805                UpgradeInstruction::Purge {
4806                    module: "x-old".into(),
4807                },
4808                UpgradeInstruction::SoftPurge {
4809                    module: "x-old".into(),
4810                },
4811            ],
4812        );
4813        let err = e.validate().unwrap_err();
4814        assert_eq!(
4815            err,
4816            UpgradeError::DuplicateCleanup {
4817                from: "0.1.0".into(),
4818                module: "x-old".into(),
4819                kinds: vec![
4820                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
4821                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4822                ],
4823            },
4824        );
4825    }
4826
4827    #[test]
4828    fn validate_accepts_distinct_cleanup_modules() {
4829        // Positive control: `:soft-purge` and `:purge` on *different*
4830        // modules pass the gate. Mirrors
4831        // `validate_accepts_multiple_purges_after_one_load` — the
4832        // cleanup-singularity gate is keyed on (module), not on
4833        // (kind, module) pair, so distinct old-version names render
4834        // distinct cleanup targets and don't collide. Sweep both
4835        // same-class (two `:soft-purge` distinct modules) and cross-
4836        // class (`:soft-purge` then `:purge` distinct modules) so a
4837        // future tighten to a kind-only key (which would over-fire on
4838        // distinct modules) surfaces here.
4839        let two_soft = entry(
4840            "0.1.0",
4841            vec![
4842                UpgradeInstruction::LoadModule { module: "x".into() },
4843                UpgradeInstruction::SoftPurge {
4844                    module: "x-old".into(),
4845                },
4846                UpgradeInstruction::SoftPurge {
4847                    module: "x-older".into(),
4848                },
4849            ],
4850        );
4851        two_soft.validate().unwrap();
4852        let mixed = entry(
4853            "0.1.0",
4854            vec![
4855                UpgradeInstruction::LoadModule { module: "x".into() },
4856                UpgradeInstruction::SoftPurge {
4857                    module: "x-old".into(),
4858                },
4859                UpgradeInstruction::Purge {
4860                    module: "x-oldest".into(),
4861                },
4862            ],
4863        );
4864        mixed.validate().unwrap();
4865    }
4866
4867    #[test]
4868    fn validate_accepts_single_cleanup_per_module() {
4869        // Boundary control: a list with exactly one `:soft-purge` and
4870        // one `:purge` (distinct modules, the canonical "drain one,
4871        // hard-discard the other" shape) is the gate's identity
4872        // element. Pin so a future off-by-one in the duplicate-detection
4873        // scan doesn't accidentally flag a single occurrence as
4874        // duplicating itself — mirrors
4875        // `validate_upgrade_from_single_entry_never_duplicates` on
4876        // the peer cross-entry duplicate axis.
4877        let e = entry(
4878            "0.1.0",
4879            vec![
4880                UpgradeInstruction::LoadModule { module: "x".into() },
4881                UpgradeInstruction::SoftPurge {
4882                    module: "x-old".into(),
4883                },
4884                UpgradeInstruction::Purge {
4885                    module: "y-old".into(),
4886                },
4887            ],
4888        );
4889        e.validate().unwrap();
4890    }
4891
4892    #[test]
4893    fn validate_cleanup_singularity_fires_after_purge_ordering() {
4894        // Diagnostic-precedence pin: an entry like `((:soft-purge "x")
4895        // (:soft-purge "x"))` is *both* purge-without-load and
4896        // duplicate-cleanup. The more-fundamental ordering gate must
4897        // win — the missing-load defect is load-bearing (the canonical
4898        // OTP shape requires the new code be resident before any
4899        // cleanup runs), and surfacing the duplicate diagnostic first
4900        // would mask the no-replacement-window defect the ordering
4901        // gate exists to close. Guards the call order in `validate`
4902        // against silent reordering. Same posture as
4903        // `validate_purge_ordering_fires_after_state_change_ordering`
4904        // on the sibling ordering gate.
4905        let e = entry(
4906            "0.1.0",
4907            vec![
4908                UpgradeInstruction::SoftPurge {
4909                    module: "x-old".into(),
4910                },
4911                UpgradeInstruction::SoftPurge {
4912                    module: "x-old".into(),
4913                },
4914            ],
4915        );
4916        let err = e.validate().unwrap_err();
4917        assert!(
4918            matches!(
4919                err,
4920                UpgradeError::PurgeWithoutPriorLoad {
4921                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
4922                    ..
4923                }
4924            ),
4925            "purge-without-load must surface before duplicate-cleanup, got {err:?}"
4926        );
4927    }
4928
4929    #[test]
4930    fn validate_cleanup_singularity_fires_after_per_instr_shape() {
4931        // Order pin: a malformed `:module` value on a `:soft-purge`
4932        // (an empty string) surfaces its narrower kind-tagged
4933        // `ModuleEmpty` diagnostic *before* the within-entry cleanup-
4934        // singularity gate fires. The per-instruction shape pass walks
4935        // the list inline before the singularity check, so the
4936        // narrower self-locating diagnostic surfaces first — mirrors
4937        // the empty-first cascade on every peer DNS-1123 gate and the
4938        // `validate_purge_ordering_fires_after_per_instr_shape` pin on
4939        // the sibling ordering gate.
4940        //
4941        // Two empty-string `:soft-purge` would *otherwise* duplicate
4942        // (both modules are the same empty string), so this pin
4943        // double-locks the precedence: the per-instr shape gate must
4944        // win on the first malformed instruction before the duplicate
4945        // scan even reaches the second.
4946        let e = entry(
4947            "0.1.0",
4948            vec![
4949                UpgradeInstruction::LoadModule { module: "x".into() },
4950                UpgradeInstruction::SoftPurge {
4951                    module: String::new(),
4952                },
4953                UpgradeInstruction::SoftPurge {
4954                    module: String::new(),
4955                },
4956            ],
4957        );
4958        let err = e.validate().unwrap_err();
4959        assert_eq!(
4960            err,
4961            UpgradeError::ModuleEmpty {
4962                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE
4963            },
4964            "malformed instruction must surface its kind-tagged diagnostic before the \
4965             cleanup-singularity gate fires, got {err:?}"
4966        );
4967    }
4968
4969    #[test]
4970    fn validate_cleanup_singularity_reports_first_collision() {
4971        // Determinism pin: with three cleanups of the same module the
4972        // gate reports the *first* collision (the second occurrence)
4973        // and stops — the third's duplicate is masked by the first
4974        // surfaced one. Mirrors
4975        // `validate_upgrade_from_duplicate_diagnostic_names_second_collision`
4976        // on the peer cross-entry duplicate axis.
4977        let e = entry(
4978            "0.1.0",
4979            vec![
4980                UpgradeInstruction::LoadModule { module: "x".into() },
4981                UpgradeInstruction::SoftPurge {
4982                    module: "x-old".into(),
4983                },
4984                UpgradeInstruction::SoftPurge {
4985                    module: "x-old".into(),
4986                },
4987                UpgradeInstruction::Purge {
4988                    module: "x-old".into(),
4989                },
4990            ],
4991        );
4992        let err = e.validate().unwrap_err();
4993        assert_eq!(
4994            err,
4995            UpgradeError::DuplicateCleanup {
4996                from: "0.1.0".into(),
4997                module: "x-old".into(),
4998                kinds: vec![
4999                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5000                    crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5001                ],
5002            },
5003            "the first colliding pair must surface, not the later `:purge` collision"
5004        );
5005    }
5006
5007    #[test]
5008    fn validate_cleanup_singularity_threads_through_validate_upgrade_from() {
5009        // The whole-list entry-point surfaces the per-entry singularity
5010        // error (mirrors
5011        // `validate_purge_ordering_threads_through_validate_upgrade_from`):
5012        // the gate is reachable from the LayoutInvariants call site,
5013        // not only from a direct `entry.validate()`.
5014        let entries = vec![entry(
5015            "0.1.0",
5016            vec![
5017                UpgradeInstruction::LoadModule { module: "x".into() },
5018                UpgradeInstruction::SoftPurge {
5019                    module: "x-old".into(),
5020                },
5021                UpgradeInstruction::Purge {
5022                    module: "x-old".into(),
5023                },
5024            ],
5025        )];
5026        let err = validate_upgrade_from(&entries).unwrap_err();
5027        assert!(
5028            matches!(err, UpgradeError::DuplicateCleanup { .. }),
5029            "validate_upgrade_from must thread the cleanup-singularity error, got {err:?}"
5030        );
5031    }
5032
5033    #[test]
5034    fn validate_rejects_duplicate_load_module_for_same_module() {
5035        // `LoadModule` is the `code:load_module/1` analog (INSPIRATIONS
5036        // §II.4): each module is loaded exactly once per upgrade entry,
5037        // the operator's dispatch table reads the module name to bind
5038        // the wasm component, and a second `(:load-module "x")` re-reads
5039        // the same module name and re-binds the same component — a
5040        // no-op the second time. systools-generated `.relup` files emit
5041        // at most one `load_module` per module per upgrade step for
5042        // this reason. Author one `(:load-module "x")` per old module.
5043        let e = entry(
5044            "0.1.0",
5045            vec![
5046                UpgradeInstruction::LoadModule { module: "x".into() },
5047                UpgradeInstruction::LoadModule { module: "x".into() },
5048            ],
5049        );
5050        let err = e.validate().unwrap_err();
5051        assert_eq!(
5052            err,
5053            UpgradeError::DuplicateLoadModule {
5054                from: "0.1.0".into(),
5055                module: "x".into(),
5056            },
5057            "two `:load-module` of the same module must surface as DuplicateLoadModule naming \
5058             the module, got {err:?}"
5059        );
5060    }
5061
5062    #[test]
5063    fn validate_accepts_distinct_load_modules() {
5064        // Positive control: `:load-module` instructions on *different*
5065        // modules pass the gate. Mirrors
5066        // `validate_accepts_distinct_cleanup_modules` on the sibling
5067        // singularity axis — the load-singularity gate is keyed on
5068        // (module), so distinct module names render distinct load
5069        // targets and don't collide. Sweep both the bare two-load shape
5070        // and the canonical load-pair-with-cleanup shape so a future
5071        // tighten that over-fires on distinct loads surfaces here.
5072        let two_loads = entry(
5073            "0.1.0",
5074            vec![
5075                UpgradeInstruction::LoadModule { module: "x".into() },
5076                UpgradeInstruction::LoadModule { module: "y".into() },
5077            ],
5078        );
5079        two_loads.validate().unwrap();
5080        let with_cleanup = entry(
5081            "0.1.0",
5082            vec![
5083                UpgradeInstruction::LoadModule { module: "x".into() },
5084                UpgradeInstruction::LoadModule { module: "y".into() },
5085                UpgradeInstruction::SoftPurge {
5086                    module: "x-old".into(),
5087                },
5088                UpgradeInstruction::SoftPurge {
5089                    module: "y-old".into(),
5090                },
5091            ],
5092        );
5093        with_cleanup.validate().unwrap();
5094    }
5095
5096    #[test]
5097    fn validate_accepts_single_load_per_module() {
5098        // Boundary control: a list with exactly one `:load-module`
5099        // followed by the canonical `:state-change` + `:soft-purge`
5100        // sequence (the module-doc OTP shape) is the gate's identity
5101        // element. Pin so a future off-by-one in the duplicate-
5102        // detection scan doesn't accidentally flag a single occurrence
5103        // as duplicating itself — mirrors
5104        // `validate_accepts_single_cleanup_per_module` on the sibling
5105        // singularity axis.
5106        let e = entry(
5107            "0.1.0",
5108            vec![
5109                UpgradeInstruction::LoadModule { module: "x".into() },
5110                UpgradeInstruction::StateChange {
5111                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5112                },
5113                UpgradeInstruction::SoftPurge {
5114                    module: "x-old".into(),
5115                },
5116            ],
5117        );
5118        e.validate().unwrap();
5119    }
5120
5121    #[test]
5122    fn validate_load_singularity_fires_after_state_change_ordering() {
5123        // Diagnostic-precedence pin: an entry like `((:state-change
5124        // "m.lisp") (:load-module "x") (:load-module "x"))` is *both*
5125        // state-change-without-load and duplicate-load. The more-
5126        // fundamental ordering gate must win — the missing-load defect
5127        // is load-bearing (the migration runs against unloaded code),
5128        // and surfacing the duplicate diagnostic first would mask the
5129        // migrate-into-unloaded-code defect the ordering gate exists
5130        // to close. Guards the call order in `validate` against silent
5131        // reordering. Same posture as
5132        // `validate_cleanup_singularity_fires_after_purge_ordering`
5133        // on the sibling singularity gate.
5134        let e = entry(
5135            "0.1.0",
5136            vec![
5137                UpgradeInstruction::StateChange {
5138                    script: PathBuf::from("lib/m.lisp"),
5139                },
5140                UpgradeInstruction::LoadModule { module: "x".into() },
5141                UpgradeInstruction::LoadModule { module: "x".into() },
5142            ],
5143        );
5144        let err = e.validate().unwrap_err();
5145        assert!(
5146            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5147            "state-change-without-load must surface before duplicate-load, got {err:?}"
5148        );
5149    }
5150
5151    #[test]
5152    fn validate_load_singularity_fires_after_purge_ordering() {
5153        // Diagnostic-precedence pin: an entry like `((:soft-purge
5154        // "x-old") (:load-module "x") (:load-module "x"))` is *both*
5155        // purge-without-load and duplicate-load. The more-fundamental
5156        // ordering gate must win — the missing-load defect is load-
5157        // bearing (the cleanup runs against no-replacement-window),
5158        // and surfacing the duplicate diagnostic first would mask the
5159        // drain-to-nothing defect the ordering gate exists to close.
5160        // Sibling of
5161        // `validate_cleanup_singularity_fires_after_purge_ordering` on
5162        // the load-singularity axis.
5163        let e = entry(
5164            "0.1.0",
5165            vec![
5166                UpgradeInstruction::SoftPurge {
5167                    module: "x-old".into(),
5168                },
5169                UpgradeInstruction::LoadModule { module: "x".into() },
5170                UpgradeInstruction::LoadModule { module: "x".into() },
5171            ],
5172        );
5173        let err = e.validate().unwrap_err();
5174        assert!(
5175            matches!(
5176                err,
5177                UpgradeError::PurgeWithoutPriorLoad {
5178                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5179                    ..
5180                }
5181            ),
5182            "purge-without-load must surface before duplicate-load, got {err:?}"
5183        );
5184    }
5185
5186    #[test]
5187    fn validate_load_singularity_fires_after_per_instr_shape() {
5188        // Order pin: a malformed `:module` value on a `:load-module`
5189        // (an empty string) surfaces its narrower kind-tagged
5190        // `ModuleEmpty` diagnostic *before* the within-entry load-
5191        // singularity gate fires. The per-instruction shape pass walks
5192        // the list inline before the singularity check, so the
5193        // narrower self-locating diagnostic surfaces first — mirrors
5194        // the empty-first cascade on every peer DNS-1123 gate and the
5195        // `validate_cleanup_singularity_fires_after_per_instr_shape`
5196        // pin on the sibling singularity gate.
5197        //
5198        // Two empty-string `:load-module` would *otherwise* duplicate
5199        // (both modules are the same empty string), so this pin
5200        // double-locks the precedence: the per-instr shape gate must
5201        // win on the first malformed instruction before the duplicate
5202        // scan even reaches the second.
5203        let e = entry(
5204            "0.1.0",
5205            vec![
5206                UpgradeInstruction::LoadModule {
5207                    module: String::new(),
5208                },
5209                UpgradeInstruction::LoadModule {
5210                    module: String::new(),
5211                },
5212            ],
5213        );
5214        let err = e.validate().unwrap_err();
5215        assert_eq!(
5216            err,
5217            UpgradeError::ModuleEmpty {
5218                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
5219            },
5220            "malformed instruction must surface its kind-tagged diagnostic before the \
5221             load-singularity gate fires, got {err:?}"
5222        );
5223    }
5224
5225    #[test]
5226    fn validate_load_singularity_fires_before_cleanup_singularity() {
5227        // Diagnostic-precedence pin: an entry that violates *both*
5228        // singularities — duplicate load on "x" *and* duplicate cleanup
5229        // on "y-old" — must surface the load-side diagnostic first.
5230        // The load axis precedes the cleanup axis in the canonical OTP
5231        // sequence (`code:load_module/1` then `code:soft_purge/1`) and
5232        // in [`UpgradeInstruction`] declaration order (LoadModule
5233        // before SoftPurge/Purge), so the load-side singularity is the
5234        // load-bearing diagnostic when both fire — the cleanup-side
5235        // duplicate is meaningless either way without a coherent load.
5236        // Guards the call order in `validate`: `validate_load_singularity`
5237        // runs before `validate_cleanup_singularity`.
5238        let e = entry(
5239            "0.1.0",
5240            vec![
5241                UpgradeInstruction::LoadModule { module: "x".into() },
5242                UpgradeInstruction::LoadModule { module: "x".into() },
5243                UpgradeInstruction::SoftPurge {
5244                    module: "y-old".into(),
5245                },
5246                UpgradeInstruction::SoftPurge {
5247                    module: "y-old".into(),
5248                },
5249            ],
5250        );
5251        let err = e.validate().unwrap_err();
5252        assert_eq!(
5253            err,
5254            UpgradeError::DuplicateLoadModule {
5255                from: "0.1.0".into(),
5256                module: "x".into(),
5257            },
5258            "duplicate-load must surface before duplicate-cleanup, got {err:?}"
5259        );
5260    }
5261
5262    #[test]
5263    fn validate_load_singularity_reports_first_collision() {
5264        // Determinism pin: with three loads of the same module the gate
5265        // reports the *first* collision (the second occurrence) and
5266        // stops — the third's duplicate is masked by the first surfaced
5267        // one. Mirrors
5268        // `validate_cleanup_singularity_reports_first_collision` on the
5269        // sibling singularity axis and every peer duplicate gate's
5270        // first-collision discipline.
5271        let e = entry(
5272            "0.1.0",
5273            vec![
5274                UpgradeInstruction::LoadModule { module: "x".into() },
5275                UpgradeInstruction::LoadModule { module: "x".into() },
5276                UpgradeInstruction::LoadModule { module: "x".into() },
5277            ],
5278        );
5279        let err = e.validate().unwrap_err();
5280        assert_eq!(
5281            err,
5282            UpgradeError::DuplicateLoadModule {
5283                from: "0.1.0".into(),
5284                module: "x".into(),
5285            },
5286            "the first colliding occurrence must surface, not the later third-load collision"
5287        );
5288    }
5289
5290    #[test]
5291    fn validate_load_singularity_threads_through_validate_upgrade_from() {
5292        // The whole-list entry-point surfaces the per-entry singularity
5293        // error (mirrors
5294        // `validate_cleanup_singularity_threads_through_validate_upgrade_from`):
5295        // the gate is reachable from the LayoutInvariants call site,
5296        // not only from a direct `entry.validate()`.
5297        let entries = vec![entry(
5298            "0.1.0",
5299            vec![
5300                UpgradeInstruction::LoadModule { module: "x".into() },
5301                UpgradeInstruction::LoadModule { module: "x".into() },
5302            ],
5303        )];
5304        let err = validate_upgrade_from(&entries).unwrap_err();
5305        assert!(
5306            matches!(err, UpgradeError::DuplicateLoadModule { .. }),
5307            "validate_upgrade_from must thread the load-singularity error, got {err:?}"
5308        );
5309    }
5310
5311    // ── within-entry state-change-singularity invariant ────────────────
5312
5313    #[test]
5314    fn validate_rejects_duplicate_state_change_for_same_script() {
5315        // `StateChange` is the `gen_server:code_change/3` analog
5316        // (INSPIRATIONS §II.4): the script folds the prior-version
5317        // state shape into the current-version shape — a one-shot
5318        // transition, not a step that composes with itself. OTP's
5319        // release_handler invokes `code_change/3` exactly once per
5320        // upgrade per gen_server; systools-generated `.relup` files
5321        // emit at most one `code_change` per gen_server per upgrade
5322        // step for this reason. A second `(:state-change "m.lisp")`
5323        // re-runs the same fold on the already-migrated state — at
5324        // best a no-op and at worst silent state corruption from
5325        // double-applied non-idempotent transforms (`add column`,
5326        // `increment counter`, `rename field`). Author one
5327        // `(:state-change "m.lisp")` per migration script per entry.
5328        let e = entry(
5329            "0.1.0",
5330            vec![
5331                UpgradeInstruction::LoadModule { module: "x".into() },
5332                UpgradeInstruction::StateChange {
5333                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5334                },
5335                UpgradeInstruction::StateChange {
5336                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5337                },
5338            ],
5339        );
5340        let err = e.validate().unwrap_err();
5341        assert_eq!(
5342            err,
5343            UpgradeError::DuplicateStateChange {
5344                from: "0.1.0".into(),
5345                script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5346            },
5347            "two `:state-change` of the same script must surface as DuplicateStateChange naming \
5348             the script, got {err:?}"
5349        );
5350    }
5351
5352    #[test]
5353    fn validate_accepts_distinct_state_change_scripts() {
5354        // Positive control: `:state-change` instructions on *different*
5355        // scripts pass the gate. Mirrors
5356        // `validate_accepts_distinct_cleanup_modules` /
5357        // `validate_accepts_distinct_load_modules` on the sibling
5358        // singularity axes — the state-change-singularity gate is keyed
5359        // on the script PathBuf, so distinct scripts render distinct
5360        // migration targets and don't collide. Sweep both the bare two-
5361        // migration shape and the canonical load-pair-with-cleanup shape
5362        // so a future tighten that over-fires on distinct scripts
5363        // surfaces here. This positive control is the gate-level peer of
5364        // `validate_accepts_multiple_state_changes_after_one_load` (the
5365        // ordering-gate positive control on distinct scripts), pinned
5366        // here independently so a future refactor that decouples the
5367        // gates can't accidentally drop coverage on either.
5368        let two_migrations = entry(
5369            "0.1.0",
5370            vec![
5371                UpgradeInstruction::LoadModule { module: "x".into() },
5372                UpgradeInstruction::StateChange {
5373                    script: PathBuf::from("lib/m1.lisp"),
5374                },
5375                UpgradeInstruction::StateChange {
5376                    script: PathBuf::from("lib/m2.lisp"),
5377                },
5378            ],
5379        );
5380        two_migrations.validate().unwrap();
5381        let with_cleanup = entry(
5382            "0.1.0",
5383            vec![
5384                UpgradeInstruction::LoadModule { module: "x".into() },
5385                UpgradeInstruction::StateChange {
5386                    script: PathBuf::from("lib/m1.lisp"),
5387                },
5388                UpgradeInstruction::StateChange {
5389                    script: PathBuf::from("lib/m2.lisp"),
5390                },
5391                UpgradeInstruction::SoftPurge {
5392                    module: "x-old".into(),
5393                },
5394            ],
5395        );
5396        with_cleanup.validate().unwrap();
5397    }
5398
5399    #[test]
5400    fn validate_accepts_single_state_change_per_script() {
5401        // Boundary control: a list with exactly one `:state-change`
5402        // wrapped by the canonical `:load-module` + `:soft-purge`
5403        // sequence (the module-doc OTP shape) is the gate's identity
5404        // element. Pin so a future off-by-one in the duplicate-
5405        // detection scan doesn't accidentally flag a single occurrence
5406        // as duplicating itself — mirrors
5407        // `validate_accepts_single_load_per_module` /
5408        // `validate_accepts_single_cleanup_per_module` on the sibling
5409        // singularity axes.
5410        let e = entry(
5411            "0.1.0",
5412            vec![
5413                UpgradeInstruction::LoadModule { module: "x".into() },
5414                UpgradeInstruction::StateChange {
5415                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
5416                },
5417                UpgradeInstruction::SoftPurge {
5418                    module: "x-old".into(),
5419                },
5420            ],
5421        );
5422        e.validate().unwrap();
5423    }
5424
5425    #[test]
5426    fn validate_state_change_singularity_fires_after_state_change_ordering() {
5427        // Diagnostic-precedence pin: an entry like `((:state-change
5428        // "m.lisp") (:state-change "m.lisp"))` is *both* state-change-
5429        // without-load and duplicate-state-change. The more-fundamental
5430        // ordering gate must win — the missing-load defect is load-
5431        // bearing (the migration runs against unloaded code), and
5432        // surfacing the duplicate diagnostic first would mask the
5433        // migrate-into-unloaded-code defect the ordering gate exists to
5434        // close. Guards the call order in `validate` against silent
5435        // reordering. Same posture as
5436        // `validate_load_singularity_fires_after_state_change_ordering`
5437        // on the sibling singularity gate.
5438        //
5439        // Two same-script `:state-change` would *otherwise* duplicate
5440        // (both scripts collide on the very first `:state-change`-
5441        // without-load encountered), so this pin double-locks the
5442        // precedence: the ordering gate must win on the first un-loaded
5443        // `:state-change` before the singularity scan even reaches the
5444        // second.
5445        let e = entry(
5446            "0.1.0",
5447            vec![
5448                UpgradeInstruction::StateChange {
5449                    script: PathBuf::from("lib/m.lisp"),
5450                },
5451                UpgradeInstruction::StateChange {
5452                    script: PathBuf::from("lib/m.lisp"),
5453                },
5454            ],
5455        );
5456        let err = e.validate().unwrap_err();
5457        assert!(
5458            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
5459            "state-change-without-load must surface before duplicate-state-change, got {err:?}"
5460        );
5461    }
5462
5463    #[test]
5464    fn validate_state_change_singularity_fires_after_purge_ordering() {
5465        // Diagnostic-precedence pin: an entry like `((:soft-purge
5466        // "x-old") (:load-module "x") (:state-change "m.lisp")
5467        // (:state-change "m.lisp"))` is *both* purge-without-load and
5468        // duplicate-state-change. The more-fundamental ordering gate
5469        // must win — the missing-load defect (a cleanup that drains the
5470        // only resident version to nothing) is load-bearing, and
5471        // surfacing the duplicate diagnostic first would mask the
5472        // drain-to-nothing defect the ordering gate exists to close.
5473        // Sibling of `validate_load_singularity_fires_after_purge_ordering`
5474        // on the state-change-singularity axis.
5475        let e = entry(
5476            "0.1.0",
5477            vec![
5478                UpgradeInstruction::SoftPurge {
5479                    module: "x-old".into(),
5480                },
5481                UpgradeInstruction::LoadModule { module: "x".into() },
5482                UpgradeInstruction::StateChange {
5483                    script: PathBuf::from("lib/m.lisp"),
5484                },
5485                UpgradeInstruction::StateChange {
5486                    script: PathBuf::from("lib/m.lisp"),
5487                },
5488            ],
5489        );
5490        let err = e.validate().unwrap_err();
5491        assert!(
5492            matches!(
5493                err,
5494                UpgradeError::PurgeWithoutPriorLoad {
5495                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5496                    ..
5497                }
5498            ),
5499            "purge-without-load must surface before duplicate-state-change, got {err:?}"
5500        );
5501    }
5502
5503    #[test]
5504    fn validate_state_change_singularity_fires_after_per_instr_shape() {
5505        // Order pin: a malformed `:script` value on a `:state-change`
5506        // (an empty path) surfaces its narrower `EmptyScript` diagnostic
5507        // *before* the within-entry state-change-singularity gate fires.
5508        // The per-instruction shape pass walks the list inline before
5509        // the singularity check, so the narrower self-locating
5510        // diagnostic surfaces first — mirrors the empty-first cascade on
5511        // every peer path-shape gate and the
5512        // `validate_load_singularity_fires_after_per_instr_shape` /
5513        // `validate_cleanup_singularity_fires_after_per_instr_shape`
5514        // pins on the sibling singularity gates.
5515        //
5516        // Two empty-path `:state-change` would *otherwise* duplicate
5517        // (both scripts are the same empty PathBuf), so this pin double-
5518        // locks the precedence: the per-instr shape gate must win on the
5519        // first malformed instruction before the duplicate scan even
5520        // reaches the second.
5521        let e = entry(
5522            "0.1.0",
5523            vec![
5524                UpgradeInstruction::LoadModule { module: "x".into() },
5525                UpgradeInstruction::StateChange {
5526                    script: PathBuf::new(),
5527                },
5528                UpgradeInstruction::StateChange {
5529                    script: PathBuf::new(),
5530                },
5531            ],
5532        );
5533        let err = e.validate().unwrap_err();
5534        assert_eq!(
5535            err,
5536            UpgradeError::EmptyScript,
5537            "malformed instruction must surface its narrower diagnostic before the \
5538             state-change-singularity gate fires, got {err:?}"
5539        );
5540    }
5541
5542    #[test]
5543    fn validate_state_change_singularity_fires_after_load_singularity() {
5544        // Diagnostic-precedence pin: an entry that violates *both*
5545        // singularities — duplicate load on "x" *and* duplicate
5546        // state-change on "m.lisp" — must surface the load-side
5547        // diagnostic first. The load axis precedes the migration axis
5548        // in the canonical OTP sequence (`code:load_module/1` then
5549        // `gen_server:code_change/3`) and in [`UpgradeInstruction`]
5550        // declaration order (LoadModule before StateChange), so the
5551        // load-side singularity is the load-bearing diagnostic when
5552        // both fire — the migration-side duplicate is meaningless
5553        // either way without a coherent load. Guards the call order in
5554        // `validate`: `validate_load_singularity` runs before
5555        // `validate_state_change_singularity`.
5556        let e = entry(
5557            "0.1.0",
5558            vec![
5559                UpgradeInstruction::LoadModule { module: "x".into() },
5560                UpgradeInstruction::LoadModule { module: "x".into() },
5561                UpgradeInstruction::StateChange {
5562                    script: PathBuf::from("lib/m.lisp"),
5563                },
5564                UpgradeInstruction::StateChange {
5565                    script: PathBuf::from("lib/m.lisp"),
5566                },
5567            ],
5568        );
5569        let err = e.validate().unwrap_err();
5570        assert_eq!(
5571            err,
5572            UpgradeError::DuplicateLoadModule {
5573                from: "0.1.0".into(),
5574                module: "x".into(),
5575            },
5576            "duplicate-load must surface before duplicate-state-change, got {err:?}"
5577        );
5578    }
5579
5580    #[test]
5581    fn validate_state_change_singularity_fires_before_cleanup_singularity() {
5582        // Diagnostic-precedence pin: an entry that violates *both*
5583        // singularities — duplicate state-change on "m.lisp" *and*
5584        // duplicate cleanup on "y-old" — must surface the migration-
5585        // side diagnostic first. The migration axis precedes the
5586        // cleanup axis in the canonical OTP sequence
5587        // (`gen_server:code_change/3` then `code:soft_purge/1`) and in
5588        // [`UpgradeInstruction`] declaration order (StateChange before
5589        // SoftPurge/Purge), so the migration-side singularity is the
5590        // load-bearing diagnostic when both fire — the cleanup-side
5591        // duplicate is irrelevant once the migration has corrupted
5592        // state by double-applying. Guards the call order in
5593        // `validate`: `validate_state_change_singularity` runs before
5594        // `validate_cleanup_singularity`.
5595        let e = entry(
5596            "0.1.0",
5597            vec![
5598                UpgradeInstruction::LoadModule { module: "x".into() },
5599                UpgradeInstruction::StateChange {
5600                    script: PathBuf::from("lib/m.lisp"),
5601                },
5602                UpgradeInstruction::StateChange {
5603                    script: PathBuf::from("lib/m.lisp"),
5604                },
5605                UpgradeInstruction::SoftPurge {
5606                    module: "y-old".into(),
5607                },
5608                UpgradeInstruction::SoftPurge {
5609                    module: "y-old".into(),
5610                },
5611            ],
5612        );
5613        let err = e.validate().unwrap_err();
5614        assert_eq!(
5615            err,
5616            UpgradeError::DuplicateStateChange {
5617                from: "0.1.0".into(),
5618                script: PathBuf::from("lib/m.lisp"),
5619            },
5620            "duplicate-state-change must surface before duplicate-cleanup, got {err:?}"
5621        );
5622    }
5623
5624    #[test]
5625    fn validate_state_change_singularity_reports_first_collision() {
5626        // Determinism pin: with three state-changes on the same script
5627        // the gate reports the *first* collision (the second
5628        // occurrence) and stops — the third's duplicate is masked by
5629        // the first surfaced one. Mirrors
5630        // `validate_load_singularity_reports_first_collision` /
5631        // `validate_cleanup_singularity_reports_first_collision` on the
5632        // sibling singularity axes and every peer duplicate gate's
5633        // first-collision discipline.
5634        let e = entry(
5635            "0.1.0",
5636            vec![
5637                UpgradeInstruction::LoadModule { module: "x".into() },
5638                UpgradeInstruction::StateChange {
5639                    script: PathBuf::from("lib/m.lisp"),
5640                },
5641                UpgradeInstruction::StateChange {
5642                    script: PathBuf::from("lib/m.lisp"),
5643                },
5644                UpgradeInstruction::StateChange {
5645                    script: PathBuf::from("lib/m.lisp"),
5646                },
5647            ],
5648        );
5649        let err = e.validate().unwrap_err();
5650        assert_eq!(
5651            err,
5652            UpgradeError::DuplicateStateChange {
5653                from: "0.1.0".into(),
5654                script: PathBuf::from("lib/m.lisp"),
5655            },
5656            "the first colliding occurrence must surface, not the later third-migration collision"
5657        );
5658    }
5659
5660    #[test]
5661    fn validate_state_change_singularity_threads_through_validate_upgrade_from() {
5662        // The whole-list entry-point surfaces the per-entry singularity
5663        // error (mirrors
5664        // `validate_load_singularity_threads_through_validate_upgrade_from`
5665        // / `validate_cleanup_singularity_threads_through_validate_upgrade_from`):
5666        // the gate is reachable from the LayoutInvariants call site,
5667        // not only from a direct `entry.validate()`.
5668        let entries = vec![entry(
5669            "0.1.0",
5670            vec![
5671                UpgradeInstruction::LoadModule { module: "x".into() },
5672                UpgradeInstruction::StateChange {
5673                    script: PathBuf::from("lib/m.lisp"),
5674                },
5675                UpgradeInstruction::StateChange {
5676                    script: PathBuf::from("lib/m.lisp"),
5677                },
5678            ],
5679        )];
5680        let err = validate_upgrade_from(&entries).unwrap_err();
5681        assert!(
5682            matches!(err, UpgradeError::DuplicateStateChange { .. }),
5683            "validate_upgrade_from must thread the state-change-singularity error, got {err:?}"
5684        );
5685    }
5686
5687    #[test]
5688    fn validate_state_change_singularity_projects_scripts_through_declared_path_accessor() {
5689        // Composition pin: [`UpgradeFromEntry::validate_state_change_singularity`]'s
5690        // per-instruction `StateChange`-arm script-path projection must
5691        // route through the sibling lifted
5692        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
5693        // accessor, not the raw
5694        // `match instr { UpgradeInstruction::StateChange { script } =>
5695        // script.as_path(), _ => continue }` open-coded pattern-match
5696        // the gate previously carried.
5697        //
5698        // Structurally: the gate's projection accept-set is the union
5699        // of every [`UpgradeInstruction`] variant for which
5700        // `declared_path().is_some()` — today exactly
5701        // [`UpgradeInstruction::StateChange`] per the sibling
5702        // `declared_path_only_for_state_change` pin, so a
5703        // duplicate-scripts input trips `DuplicateStateChange` and a
5704        // non-`StateChange` input (module-bearing / terminal) leaves
5705        // `seen` empty and the gate returns `Ok(())` byte-identical to
5706        // the pattern-match shape.
5707        //
5708        // Byte-equal today (`declared_path` returns `Some(script)` iff
5709        // `StateChange`, byte-for-byte from the variant's own storage);
5710        // the pin catches any future accessor extension that promotes
5711        // an additional variant onto the `PathBuf`-carrying axis — the
5712        // gate then fires on duplicate scripts from that variant too,
5713        // and the singularity discipline the sibling
5714        // `validate_load_singularity` / `validate_cleanup_singularity`
5715        // gates share on the `String`-carrying axis's per-variant
5716        // consumers extends to the promoted variant by construction.
5717        //
5718        // Peer of the sibling four per-`UpgradeInstruction` consumers
5719        // ([`UpgradeInstruction::validate`]'s per-`StateChange`
5720        // sandbox-path fan-out, the layout-side per-`StateChange`
5721        // script-existence fan-out at
5722        // `caixa-core/src/layout.rs:1017`, the cross-slot
5723        // [`validate_upgrade_from_against_behavior`] gate's per-
5724        // `StateChange` detection loop, the peer
5725        // [`UpgradeInstruction::declared_module`] `String`-axis
5726        // per-variant unifier) — this gate now shares one typed
5727        // dispatch on the substrate primitive's `PathBuf`-carrying
5728        // axis with those consumers, so a future rebrand on the axis
5729        // migrates as a single caixa-core edit rather than a
5730        // coordinated rewrite of five call sites.
5731        //
5732        // Three-arm projective coverage:
5733        //   (a) `StateChange` scripts project through `declared_path()`
5734        //       byte-equal to the raw `script.as_path()` field access;
5735        //   (b) a duplicate-`StateChange` input trips the gate on the
5736        //       second occurrence with `DuplicateStateChange` carrying
5737        //       the offending script verbatim;
5738        //   (c) a non-`StateChange`-only input (`LoadModule` /
5739        //       `SoftPurge` / `Purge` / `Restart`) leaves the gate
5740        //       vacuous with `Ok(())` — the `declared_path().is_none()`
5741        //       arm's `continue` fall-through pins.
5742        //
5743        // Fail-before-pass-after verified locally: swapping the
5744        // production `let Some(script) = instr.declared_path() else {
5745        // continue };` back to `let script = match instr {
5746        // UpgradeInstruction::StateChange { script } =>
5747        // script.as_path(), _ => continue, };` keeps arms (a)-(c)
5748        // passing but silently detaches the gate from the accessor's
5749        // typed dispatch — any future `declared_path` extension
5750        // (promotion of an additional variant onto the axis, an
5751        // operator-side pre-resolved-path cache the accessor
5752        // materializes) would then silently disagree between this
5753        // gate's raw pattern-match and the peer four sibling consumers
5754        // that route through the accessor.
5755        use std::path::PathBuf;
5756
5757        // (a) StateChange projection byte-equal via declared_path.
5758        let sc = UpgradeInstruction::StateChange {
5759            script: PathBuf::from("lib/m.lisp"),
5760        };
5761        assert_eq!(
5762            sc.declared_path().map(std::path::PathBuf::as_path),
5763            Some(PathBuf::from("lib/m.lisp").as_path()),
5764            "declared_path() must project the StateChange :script byte-equal to the raw \
5765             field access — accessor divergence would silently detach the gate from the \
5766             projection every peer per-`UpgradeInstruction` consumer routes through"
5767        );
5768
5769        // (b) Duplicate-StateChange input trips the gate.
5770        let dup = entry(
5771            "0.1.0",
5772            vec![
5773                UpgradeInstruction::LoadModule { module: "x".into() },
5774                UpgradeInstruction::StateChange {
5775                    script: PathBuf::from("lib/m.lisp"),
5776                },
5777                UpgradeInstruction::StateChange {
5778                    script: PathBuf::from("lib/m.lisp"),
5779                },
5780            ],
5781        );
5782        assert_eq!(
5783            dup.validate_state_change_singularity(),
5784            Err(UpgradeError::DuplicateStateChange {
5785                from: "0.1.0".into(),
5786                script: PathBuf::from("lib/m.lisp"),
5787            }),
5788            "duplicate StateChange scripts must trip the gate on the second occurrence \
5789             through the declared_path accessor's Some(script) arm"
5790        );
5791
5792        // (c) Non-StateChange-only inputs leave the gate vacuous.
5793        for instrs in [
5794            vec![UpgradeInstruction::LoadModule { module: "x".into() }],
5795            vec![
5796                UpgradeInstruction::LoadModule { module: "x".into() },
5797                UpgradeInstruction::SoftPurge {
5798                    module: "x-old".into(),
5799                },
5800            ],
5801            vec![
5802                UpgradeInstruction::LoadModule { module: "x".into() },
5803                UpgradeInstruction::Purge {
5804                    module: "x-old".into(),
5805                },
5806            ],
5807            vec![UpgradeInstruction::Restart],
5808        ] {
5809            for instr in &instrs {
5810                assert!(
5811                    instr.declared_path().is_none(),
5812                    "non-StateChange variants must project None through declared_path — \
5813                     accessor divergence would let this gate silently fire on a duplicate \
5814                     module reference far from any :state-change site"
5815                );
5816            }
5817            let e = entry("0.1.0", instrs);
5818            assert_eq!(
5819                e.validate_state_change_singularity(),
5820                Ok(()),
5821                "the state-change-singularity gate must return Ok(()) on an entry whose \
5822                 instructions all project None through declared_path — the accessor's \
5823                 continue arm the pattern-match's `_ => continue` previously carried"
5824            );
5825        }
5826    }
5827
5828    // ── within-entry state-change-before-cleanup ordering invariant ──
5829
5830    #[test]
5831    fn validate_rejects_state_change_after_soft_purge() {
5832        // Fail-before-pass-after pin: `:state-change` is the
5833        // gen_server:code_change/3 analog and folds the prior-version
5834        // state shape into the current shape; `:soft-purge` drains the
5835        // prior code. The operator runs instructions in declared order,
5836        // so a `:soft-purge` ahead of a `:state-change` drains the
5837        // prior module before the migration callback runs against the
5838        // state it held — the canonical OTP error mode
5839        // "`code_change/3` invoked on a purged module" the
5840        // release_handler closes by always ordering the migration
5841        // before the cleanup.
5842        let e = entry(
5843            "0.1.0",
5844            vec![
5845                UpgradeInstruction::LoadModule { module: "x".into() },
5846                UpgradeInstruction::SoftPurge {
5847                    module: "x-old".into(),
5848                },
5849                UpgradeInstruction::StateChange {
5850                    script: PathBuf::from("lib/m.lisp"),
5851                },
5852            ],
5853        );
5854        let err = e.validate().unwrap_err();
5855        assert_eq!(
5856            err,
5857            UpgradeError::StateChangeAfterCleanup {
5858                from: "0.1.0".into(),
5859                script: PathBuf::from("lib/m.lisp"),
5860                prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
5861                prior_cleanup_module: "x-old".into(),
5862            },
5863            "a `:state-change` after a `:soft-purge` must surface as StateChangeAfterCleanup \
5864             naming the offending entry + script + the prior cleanup's kind/module, got {err:?}"
5865        );
5866    }
5867
5868    #[test]
5869    fn validate_rejects_state_change_after_purge() {
5870        // Per-arm coverage: `:purge` (immediate discard, no drain) is
5871        // the more catastrophic peer of `:soft-purge` on the cleanup
5872        // axis; same gate, same shape, the `prior_cleanup_kind` field
5873        // distinguishes the diagnostic so the author can grep their
5874        // caixa.lisp for the offending `(:purge …)` form.
5875        let e = entry(
5876            "0.1.0",
5877            vec![
5878                UpgradeInstruction::LoadModule { module: "x".into() },
5879                UpgradeInstruction::Purge {
5880                    module: "x-old".into(),
5881                },
5882                UpgradeInstruction::StateChange {
5883                    script: PathBuf::from("lib/m.lisp"),
5884                },
5885            ],
5886        );
5887        let err = e.validate().unwrap_err();
5888        assert_eq!(
5889            err,
5890            UpgradeError::StateChangeAfterCleanup {
5891                from: "0.1.0".into(),
5892                script: PathBuf::from("lib/m.lisp"),
5893                prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
5894                prior_cleanup_module: "x-old".into(),
5895            },
5896            "a `:state-change` after a `:purge` must surface as StateChangeAfterCleanup with \
5897             `prior_cleanup_kind: \":purge\"`, got {err:?}"
5898        );
5899    }
5900
5901    #[test]
5902    fn validate_accepts_state_change_before_cleanup() {
5903        // Positive control: the canonical `(:load-module …)
5904        // (:state-change …) (:soft-purge …)` order validates — the
5905        // exact shape the module doc example and `validate_accepts_
5906        // well_formed` already pin, restated here on the new gate's
5907        // identity element so a future shortcut that runs the
5908        // singularity gates first doesn't silently mask a regression
5909        // here.
5910        let e = entry(
5911            "0.1.0",
5912            vec![
5913                UpgradeInstruction::LoadModule { module: "x".into() },
5914                UpgradeInstruction::StateChange {
5915                    script: PathBuf::from("lib/m.lisp"),
5916                },
5917                UpgradeInstruction::SoftPurge {
5918                    module: "x-old".into(),
5919                },
5920            ],
5921        );
5922        e.validate().unwrap();
5923    }
5924
5925    #[test]
5926    fn validate_accepts_cleanup_without_state_change() {
5927        // Empty-set identity: an entry that carries no `:state-change`
5928        // at all has nothing to order against the cleanup, so the gate
5929        // passes regardless of how the cleanups are placed (after the
5930        // single required `:load-module`). Mirrors the
5931        // `validate_accepts_multiple_purges_after_one_load` positive
5932        // control on the peer purge-ordering gate; metadata-only
5933        // upgrades with cleanup-but-no-migration land here.
5934        let e = entry(
5935            "0.1.0",
5936            vec![
5937                UpgradeInstruction::LoadModule { module: "x".into() },
5938                UpgradeInstruction::SoftPurge {
5939                    module: "x-old".into(),
5940                },
5941                UpgradeInstruction::Purge {
5942                    module: "x-oldest".into(),
5943                },
5944            ],
5945        );
5946        e.validate().unwrap();
5947    }
5948
5949    #[test]
5950    fn validate_accepts_state_change_without_cleanup() {
5951        // Empty-set identity on the dual axis: an entry that carries no
5952        // cleanup at all has nothing to order against the state-change,
5953        // so the gate passes — additive-upgrade shapes (load new code,
5954        // migrate state, leave old code resident for in-flight callers
5955        // to drain naturally) land here.
5956        let e = entry(
5957            "0.1.0",
5958            vec![
5959                UpgradeInstruction::LoadModule { module: "x".into() },
5960                UpgradeInstruction::StateChange {
5961                    script: PathBuf::from("lib/m.lisp"),
5962                },
5963            ],
5964        );
5965        e.validate().unwrap();
5966    }
5967
5968    #[test]
5969    fn validate_accepts_multiple_state_changes_before_cleanup() {
5970        // Coverage: every state-change must precede every cleanup, not
5971        // just the first. A chain `(load) (sc) (sc) (sp)` is the
5972        // canonical "two distinct migration scripts on a chained
5973        // upgrade" shape (one module's schema *and* another's
5974        // projection per the DuplicateStateChange diagnostic), and
5975        // it must pass when each state-change has distinct script
5976        // paths. Pinned here so a future shortcut that only checks
5977        // the first state-change doesn't silently accept a
5978        // `(load) (sc-1) (sp) (sc-2)` regression.
5979        let e = entry(
5980            "0.1.0",
5981            vec![
5982                UpgradeInstruction::LoadModule { module: "x".into() },
5983                UpgradeInstruction::StateChange {
5984                    script: PathBuf::from("lib/m1.lisp"),
5985                },
5986                UpgradeInstruction::StateChange {
5987                    script: PathBuf::from("lib/m2.lisp"),
5988                },
5989                UpgradeInstruction::SoftPurge {
5990                    module: "x-old".into(),
5991                },
5992            ],
5993        );
5994        e.validate().unwrap();
5995    }
5996
5997    #[test]
5998    fn validate_rejects_state_change_sandwiched_between_cleanups() {
5999        // First-cleanup-wins pin: an entry like `(load) (sp-1) (sc)
6000        // (sp-2)` violates the gate because the state-change runs
6001        // after the first cleanup. The reported `prior_cleanup_*`
6002        // names the *first* cleanup (the load-bearing one), not the
6003        // last — mirrors every peer first-collision diagnostic
6004        // posture on this module (`validate_state_change_ordering`,
6005        // `validate_purge_ordering`, `validate_load_singularity`,
6006        // `validate_state_change_singularity`,
6007        // `validate_cleanup_singularity` all report the first
6008        // colliding instruction, not the last).
6009        let e = entry(
6010            "0.1.0",
6011            vec![
6012                UpgradeInstruction::LoadModule { module: "x".into() },
6013                UpgradeInstruction::SoftPurge {
6014                    module: "x-old".into(),
6015                },
6016                UpgradeInstruction::StateChange {
6017                    script: PathBuf::from("lib/m.lisp"),
6018                },
6019                UpgradeInstruction::Purge {
6020                    module: "y-old".into(),
6021                },
6022            ],
6023        );
6024        let err = e.validate().unwrap_err();
6025        assert_eq!(
6026            err,
6027            UpgradeError::StateChangeAfterCleanup {
6028                from: "0.1.0".into(),
6029                script: PathBuf::from("lib/m.lisp"),
6030                prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6031                prior_cleanup_module: "x-old".into(),
6032            },
6033            "the first cleanup the state-change follows must surface (not the trailing one), \
6034             got {err:?}"
6035        );
6036    }
6037
6038    #[test]
6039    fn validate_state_change_before_cleanup_fires_after_purge_ordering() {
6040        // Diagnostic-precedence pin: an entry like `((:soft-purge
6041        // "x-old") (:load-module "x") (:state-change "m.lisp"))` is
6042        // *both* purge-without-load (the cleanup runs before the
6043        // load) and state-change-after-cleanup (the state-change
6044        // runs after the cleanup). The more-fundamental ordering
6045        // gate must win — the missing-load defect (a cleanup that
6046        // drains the only resident version to nothing) is load-
6047        // bearing, and surfacing the state-change-after-cleanup
6048        // diagnostic first would mask the drain-to-nothing defect
6049        // the peer purge-ordering gate exists to close. Guards the
6050        // call order in `validate` against silent reordering. Same
6051        // posture as `validate_purge_ordering_fires_after_state_
6052        // change_ordering` on the sibling ordering gate.
6053        //
6054        // Pin specifically uses the load-after-cleanup shape (rather
6055        // than load-less) so the state-change-ordering gate (which
6056        // would otherwise fire first on a `((:soft-purge …)
6057        // (:state-change …))` shape with no leading load) is
6058        // sidestepped: with the load present after the cleanup,
6059        // state-change-ordering passes (its `loaded` latch is set
6060        // before the state-change is encountered) but purge-ordering
6061        // still fails (the cleanup precedes the load). That isolates
6062        // the precedence between purge-ordering and this gate
6063        // cleanly.
6064        let e = entry(
6065            "0.1.0",
6066            vec![
6067                UpgradeInstruction::SoftPurge {
6068                    module: "x-old".into(),
6069                },
6070                UpgradeInstruction::LoadModule { module: "x".into() },
6071                UpgradeInstruction::StateChange {
6072                    script: PathBuf::from("lib/m.lisp"),
6073                },
6074            ],
6075        );
6076        let err = e.validate().unwrap_err();
6077        assert!(
6078            matches!(
6079                err,
6080                UpgradeError::PurgeWithoutPriorLoad {
6081                    kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6082                    ..
6083                }
6084            ),
6085            "purge-without-load must surface before state-change-after-cleanup, got {err:?}"
6086        );
6087    }
6088
6089    #[test]
6090    fn validate_state_change_before_cleanup_fires_after_state_change_ordering() {
6091        // Diagnostic-precedence pin: an entry like `((:state-change
6092        // "m.lisp") (:soft-purge "x-old"))` is state-change-without-
6093        // load (because no `:load-module` precedes the state-change)
6094        // but *not* state-change-after-cleanup (the state-change
6095        // precedes the cleanup textually). The state-change-ordering
6096        // gate must surface first regardless — the missing-load
6097        // defect on the migration axis is the load-bearing semantic
6098        // and surfacing a different ordering diagnostic would mask
6099        // the migration-against-stale-code defect. Guards the call
6100        // order in `validate` against silent reordering on a shape
6101        // that fires only the state-change-ordering gate (not this
6102        // one), pinning that the state-change-ordering gate wins
6103        // ahead of this gate's chance to look at the list.
6104        let e = entry(
6105            "0.1.0",
6106            vec![
6107                UpgradeInstruction::StateChange {
6108                    script: PathBuf::from("lib/m.lisp"),
6109                },
6110                UpgradeInstruction::SoftPurge {
6111                    module: "x-old".into(),
6112                },
6113            ],
6114        );
6115        let err = e.validate().unwrap_err();
6116        assert!(
6117            matches!(err, UpgradeError::StateChangeWithoutPriorLoad { .. }),
6118            "state-change-without-load must surface before purge-without-load (the canonical \
6119             validate_purge_ordering_fires_after_state_change_ordering pin), got {err:?}"
6120        );
6121    }
6122
6123    #[test]
6124    fn validate_state_change_before_cleanup_fires_after_per_instr_shape() {
6125        // Order pin: a malformed `:script` value on a `:state-change`
6126        // (an empty path) surfaces its narrower `EmptyScript`
6127        // diagnostic *before* the within-entry state-change-before-
6128        // cleanup gate fires. The per-instruction shape pass walks
6129        // the list inline before the ordering check, so the narrower
6130        // self-locating diagnostic surfaces first — mirrors the
6131        // empty-first cascade on every peer path-shape gate and the
6132        // `validate_purge_ordering_fires_after_per_instr_shape` pin
6133        // on the sibling ordering gate.
6134        let e = entry(
6135            "0.1.0",
6136            vec![
6137                UpgradeInstruction::LoadModule { module: "x".into() },
6138                UpgradeInstruction::SoftPurge {
6139                    module: "x-old".into(),
6140                },
6141                UpgradeInstruction::StateChange {
6142                    script: PathBuf::new(),
6143                },
6144            ],
6145        );
6146        let err = e.validate().unwrap_err();
6147        assert_eq!(
6148            err,
6149            UpgradeError::EmptyScript,
6150            "malformed instruction must surface its narrower diagnostic before the \
6151             state-change-before-cleanup gate fires, got {err:?}"
6152        );
6153    }
6154
6155    #[test]
6156    fn validate_state_change_before_cleanup_fires_before_state_change_singularity() {
6157        // Diagnostic-precedence pin: an entry like `((:load-module
6158        // "x") (:soft-purge "x-old") (:state-change "m.lisp")
6159        // (:state-change "m.lisp"))` violates *both* this ordering
6160        // gate (the first state-change follows the cleanup) and the
6161        // state-change-singularity gate (the same script appears
6162        // twice). The ordering gate must win — the canonical
6163        // "ordering before singularity" precedence the peer
6164        // `validate_state_change_ordering` / `validate_purge_
6165        // ordering` gates already establish over their own singularity
6166        // gates, applied uniformly across the OTP canonical-sequence
6167        // ordering axis here. Guards the call order in `validate`:
6168        // `validate_state_change_before_cleanup` runs before the
6169        // per-instruction-class singularity gates.
6170        let e = entry(
6171            "0.1.0",
6172            vec![
6173                UpgradeInstruction::LoadModule { module: "x".into() },
6174                UpgradeInstruction::SoftPurge {
6175                    module: "x-old".into(),
6176                },
6177                UpgradeInstruction::StateChange {
6178                    script: PathBuf::from("lib/m.lisp"),
6179                },
6180                UpgradeInstruction::StateChange {
6181                    script: PathBuf::from("lib/m.lisp"),
6182                },
6183            ],
6184        );
6185        let err = e.validate().unwrap_err();
6186        assert!(
6187            matches!(err, UpgradeError::StateChangeAfterCleanup { .. }),
6188            "state-change-after-cleanup must surface before duplicate-state-change, got {err:?}"
6189        );
6190    }
6191
6192    #[test]
6193    fn validate_state_change_before_cleanup_threads_through_validate_upgrade_from() {
6194        // The whole-list entry-point surfaces the per-entry ordering
6195        // error (mirrors `validate_purge_ordering_threads_through_
6196        // validate_upgrade_from` and every peer wiring pin): the gate
6197        // is reachable from the LayoutInvariants call site, not only
6198        // from a direct `entry.validate()`.
6199        let entries = vec![entry(
6200            "0.1.0",
6201            vec![
6202                UpgradeInstruction::LoadModule { module: "x".into() },
6203                UpgradeInstruction::SoftPurge {
6204                    module: "x-old".into(),
6205                },
6206                UpgradeInstruction::StateChange {
6207                    script: PathBuf::from("lib/m.lisp"),
6208                },
6209            ],
6210        )];
6211        let err = validate_upgrade_from(&entries).unwrap_err();
6212        assert!(
6213            matches!(err, UpgradeError::StateChangeAfterCleanup { .. }),
6214            "validate_upgrade_from must thread the state-change-before-cleanup error, \
6215             got {err:?}"
6216        );
6217    }
6218
6219    #[test]
6220    fn validate_state_change_before_cleanup_projects_scripts_through_declared_path_accessor() {
6221        // Composition pin: [`UpgradeFromEntry::validate_state_change_before_cleanup`]'s
6222        // per-instruction `StateChange`-arm script-path projection must
6223        // route through the sibling lifted
6224        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
6225        // accessor, not the raw
6226        // `if let UpgradeInstruction::StateChange { script } = instr`
6227        // open-coded pattern-match the gate previously carried inside
6228        // `impl UpgradeFromEntry` at caixa-core/src/upgrade.rs:806.
6229        //
6230        // Structurally: the gate's projection accept-set is the union
6231        // of every [`UpgradeInstruction`] variant for which
6232        // `declared_path().is_some()` — today exactly
6233        // [`UpgradeInstruction::StateChange`] per the sibling
6234        // `declared_path_only_for_state_change` pin, so a
6235        // state-change-after-cleanup input trips
6236        // `StateChangeAfterCleanup` and a non-`StateChange` input
6237        // (module-bearing / terminal) leaves the sticky-once latch
6238        // sweep quiet byte-identical to the pattern-match shape.
6239        //
6240        // Byte-equal today (`declared_path` returns `Some(script)` iff
6241        // `StateChange`, byte-for-byte from the variant's own storage);
6242        // the pin catches any future accessor extension that promotes
6243        // an additional variant onto the `PathBuf`-carrying axis — the
6244        // gate then fires on migrate-after-cleanup for that variant too,
6245        // and the migrate→cleanup ordering discipline the peer
6246        // [`validate_state_change_singularity`] /
6247        // [`validate_upgrade_from_against_behavior`] gates share on the
6248        // same axis extends to the promoted variant by construction.
6249        //
6250        // Peer of the sibling four per-`UpgradeInstruction` consumers
6251        // ([`UpgradeInstruction::validate`]'s per-`StateChange`
6252        // sandbox-path fan-out, the layout-side per-`StateChange`
6253        // script-existence fan-out at
6254        // `caixa-core/src/layout.rs:1058`, the within-entry
6255        // [`UpgradeFromEntry::validate_state_change_singularity`]
6256        // per-`StateChange` script-projection fan-out, the cross-slot
6257        // [`validate_upgrade_from_against_behavior`] per-`StateChange`
6258        // detection loop) — the fifth (and last unlifted inside
6259        // `impl UpgradeFromEntry`) per-`UpgradeInstruction`-consumer of
6260        // the `PathBuf`-carrying axis to now route through the accessor.
6261        // Same shape as the sibling
6262        // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
6263        // and `validate_upgrade_from_against_behavior_projects_scripts_through_declared_path_accessor`
6264        // pins extended onto the within-entry migrate→cleanup ordering
6265        // gate.
6266        //
6267        // Three-arm projective coverage:
6268        //   (a) `StateChange` scripts project through `declared_path()`
6269        //       byte-equal to the raw `script.clone()` field access
6270        //       the diagnostic previously carried;
6271        //   (b) a `:state-change`-after-cleanup input trips the gate
6272        //       with `StateChangeAfterCleanup` carrying the offending
6273        //       script + the prior cleanup's kind/module verbatim;
6274        //   (c) a non-`StateChange`-only input (`LoadModule` /
6275        //       `SoftPurge` / `Purge` / `Restart`) leaves the gate
6276        //       vacuous with `Ok(())` — the `declared_path().is_none()`
6277        //       arm's fall-through pins.
6278        //
6279        // Fail-before-pass-after verified structurally: swapping the
6280        // production
6281        //   `else if let Some(script) = instr.declared_path() && … { … }`
6282        // back to
6283        //   `else if let UpgradeInstruction::StateChange { script } = instr && … { … }`
6284        // keeps arms (a)-(c) passing but silently detaches this within-
6285        // entry ordering gate from the accessor's typed dispatch — any
6286        // future `declared_path` extension (promotion of an additional
6287        // variant onto the axis, an operator-side pre-resolved-path
6288        // cache the accessor materializes) would then silently disagree
6289        // between this gate's raw pattern-match and the peer four
6290        // sibling consumers that route through the accessor.
6291
6292        // (a) StateChange projection byte-equal via declared_path.
6293        let sc = UpgradeInstruction::StateChange {
6294            script: PathBuf::from("lib/m.lisp"),
6295        };
6296        assert_eq!(
6297            sc.declared_path().cloned(),
6298            Some(PathBuf::from("lib/m.lisp")),
6299            "declared_path() must project the StateChange :script byte-equal to the raw \
6300             field access — accessor divergence would silently detach this within-entry \
6301             migrate→cleanup ordering gate from the projection every peer per-`UpgradeInstruction` \
6302             consumer routes through"
6303        );
6304
6305        // (b) StateChange-after-cleanup trips the gate through the accessor.
6306        let after = entry(
6307            "0.1.0",
6308            vec![
6309                UpgradeInstruction::LoadModule { module: "x".into() },
6310                UpgradeInstruction::SoftPurge {
6311                    module: "x-old".into(),
6312                },
6313                UpgradeInstruction::StateChange {
6314                    script: PathBuf::from("lib/m.lisp"),
6315                },
6316            ],
6317        );
6318        assert_eq!(
6319            after.validate(),
6320            Err(UpgradeError::StateChangeAfterCleanup {
6321                from: "0.1.0".into(),
6322                script: PathBuf::from("lib/m.lisp"),
6323                prior_cleanup_kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
6324                prior_cleanup_module: "x-old".into(),
6325            }),
6326            "a :state-change following a cleanup must trip the gate through the declared_path \
6327             accessor's Some(script) arm — carrying the offending script + the prior cleanup's \
6328             kind/module verbatim byte-identical to the pattern-match shape"
6329        );
6330
6331        // (c) Non-StateChange-only inputs leave the gate vacuous.
6332        for instrs in [
6333            vec![UpgradeInstruction::LoadModule { module: "x".into() }],
6334            vec![
6335                UpgradeInstruction::LoadModule { module: "x".into() },
6336                UpgradeInstruction::SoftPurge {
6337                    module: "x-old".into(),
6338                },
6339            ],
6340            vec![
6341                UpgradeInstruction::LoadModule { module: "x".into() },
6342                UpgradeInstruction::Purge {
6343                    module: "x-old".into(),
6344                },
6345            ],
6346            vec![UpgradeInstruction::Restart],
6347        ] {
6348            for instr in &instrs {
6349                assert!(
6350                    instr.declared_path().is_none(),
6351                    "non-StateChange variants must project None through declared_path — \
6352                     accessor divergence would let this within-entry ordering gate silently \
6353                     fire on a cleanup-only sequence far from any :state-change site"
6354                );
6355            }
6356            let e = entry("0.1.0", instrs);
6357            assert_eq!(
6358                e.validate(),
6359                Ok(()),
6360                "the state-change-before-cleanup gate must return Ok(()) on an entry whose \
6361                 instructions all project None through declared_path — the accessor's \
6362                 None arm the pattern-match's implicit fall-through previously carried"
6363            );
6364        }
6365    }
6366
6367    #[test]
6368    fn validate_restart_order_independent() {
6369        // Position-agnostic: `(:restart)` leading or trailing the
6370        // mixed sequence surfaces the same RestartNotExclusive shape.
6371        // Mirrors OTP appup's order-insensitive
6372        // `restart_emulator | restart_new_emulator` terminal rule —
6373        // the position of the restart instruction in the script is
6374        // irrelevant; what matters is the script *contains* it
6375        // alongside other instructions at all. The gate must not
6376        // gain a false positive by depending on instruction ordering.
6377        let leading = entry(
6378            "0.1.0",
6379            vec![
6380                UpgradeInstruction::Restart,
6381                UpgradeInstruction::LoadModule { module: "x".into() },
6382            ],
6383        );
6384        let trailing = entry(
6385            "0.1.0",
6386            vec![
6387                UpgradeInstruction::LoadModule { module: "x".into() },
6388                UpgradeInstruction::Restart,
6389            ],
6390        );
6391        let middle = entry(
6392            "0.1.0",
6393            vec![
6394                UpgradeInstruction::LoadModule { module: "a".into() },
6395                UpgradeInstruction::Restart,
6396                UpgradeInstruction::SoftPurge {
6397                    module: "a-old".into(),
6398                },
6399            ],
6400        );
6401        for e in [&leading, &trailing, &middle] {
6402            assert!(
6403                matches!(
6404                    e.validate().unwrap_err(),
6405                    UpgradeError::RestartNotExclusive {
6406                        restart_count: 1,
6407                        ..
6408                    }
6409                ),
6410                "mixed-with-:restart entry must surface RestartNotExclusive regardless of \
6411                 instruction order, got {:?}",
6412                e.validate()
6413            );
6414        }
6415    }
6416
6417    #[test]
6418    fn validate_restart_exclusive_fires_after_per_instr_shape() {
6419        // Order pin: a malformed `:module` value on a Module-bearing
6420        // instruction (an empty string) surfaces its narrower
6421        // kind-tagged `ModuleEmpty` diagnostic *before* the within-
6422        // entry restart-exclusivity gate fires. The per-instruction
6423        // shape pass walks the list inline before the restart-
6424        // exclusive check, so the narrower self-locating diagnostic
6425        // surfaces first — mirrors the empty-first cascade on every
6426        // peer DNS-1123 gate (`validate_module`,
6427        // `validate_membro_caixa`, `validate_placement_cluster`) and
6428        // the `*_invalid_fires_before_duplicate_check` arm-ordering
6429        // pins on every typed-graph axis. Without this pin a future
6430        // shortcut that runs the restart-exclusive check ahead of
6431        // per-instruction shape would surface a less-actionable
6432        // RestartNotExclusive over an instruction list that's also
6433        // malformed at the per-instruction layer.
6434        let e = entry(
6435            "0.1.0",
6436            vec![
6437                UpgradeInstruction::LoadModule {
6438                    module: String::new(),
6439                },
6440                UpgradeInstruction::Restart,
6441            ],
6442        );
6443        let err = e.validate().unwrap_err();
6444        assert_eq!(
6445            err,
6446            UpgradeError::ModuleEmpty {
6447                kind: crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE
6448            },
6449            "malformed instruction must surface its kind-tagged diagnostic before the \
6450             restart-exclusivity gate fires, got {err:?}"
6451        );
6452    }
6453
6454    fn behavior_with_state_change_callback() -> crate::BehaviorSpec {
6455        // Helper for the cross-slot composition gate's pass arm: a
6456        // BehaviorSpec carrying just the `:on-state-change` callback,
6457        // the runtime hook the per-version `(:state-change "…")`
6458        // instruction is delivered through during hot upgrade. Mirrors
6459        // the canonical authoring shape pinned in the module doc.
6460        crate::BehaviorSpec {
6461            on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
6462            ..Default::default()
6463        }
6464    }
6465
6466    #[test]
6467    fn behavior_gate_rejects_state_change_without_any_behavior() {
6468        // `:upgrade-from` with a `(:state-change "lib/m.lisp")` and the
6469        // caixa carries no `:behavior` at all surfaces the missing-
6470        // callback diagnostic naming the offending entry's `:from` +
6471        // script. The "I added the upgrade path but never declared
6472        // `:behavior`" footgun: `:behavior` is optional at the typed
6473        // root, the typed `:upgrade-from` slot validates on its own
6474        // merits, and the operator's hot-upgrade dispatch reaches for
6475        // a callback that doesn't exist.
6476        let entries = vec![entry(
6477            "0.1.0",
6478            vec![
6479                UpgradeInstruction::LoadModule { module: "x".into() },
6480                UpgradeInstruction::StateChange {
6481                    script: PathBuf::from("lib/m.lisp"),
6482                },
6483            ],
6484        )];
6485        let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
6486        assert_eq!(
6487            err,
6488            UpgradeError::StateChangeWithoutOnStateChangeCallback {
6489                from: "0.1.0".into(),
6490                script: PathBuf::from("lib/m.lisp"),
6491            },
6492        );
6493    }
6494
6495    #[test]
6496    fn behavior_gate_rejects_state_change_when_on_state_change_is_none() {
6497        // `:behavior` declared with *other* callbacks set
6498        // (`:on-init`, `:on-terminate`, etc.) but `:on-state-change`
6499        // None still surfaces the missing-callback diagnostic — only
6500        // the `:on-state-change` axis matters for this gate. The
6501        // "I declared `:behavior` but missed the migration callback"
6502        // footgun: a caixa that registers its lifecycle hooks but
6503        // forgets the migration delivery path leaves the
6504        // `:state-change` instruction with no runtime hook to
6505        // dispatch through.
6506        let entries = vec![entry(
6507            "0.1.0",
6508            vec![
6509                UpgradeInstruction::LoadModule { module: "x".into() },
6510                UpgradeInstruction::StateChange {
6511                    script: PathBuf::from("lib/m.lisp"),
6512                },
6513            ],
6514        )];
6515        let b = crate::BehaviorSpec {
6516            on_init: Some(PathBuf::from("lib/init.lisp")),
6517            on_terminate: Some(PathBuf::from("lib/cleanup.lisp")),
6518            ..Default::default()
6519        };
6520        let err = validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap_err();
6521        assert_eq!(
6522            err,
6523            UpgradeError::StateChangeWithoutOnStateChangeCallback {
6524                from: "0.1.0".into(),
6525                script: PathBuf::from("lib/m.lisp"),
6526            },
6527            "only `:on-state-change` satisfies the composition; other callbacks must not mask \
6528             the missing migration hook"
6529        );
6530    }
6531
6532    #[test]
6533    fn behavior_gate_accepts_state_change_with_on_state_change_callback() {
6534        // The canonical composition shape: a per-version
6535        // `(:state-change "lib/m.lisp")` instruction paired with the
6536        // `:behavior :on-state-change "lib/migrations.lisp"` callback
6537        // it is delivered through at hot-upgrade time. Pins the gate's
6538        // pass arm — drift here = a future tighten that rejects the
6539        // canonical OTP-shape composition surfaces as a regression at
6540        // this positive-control pin.
6541        let entries = vec![entry(
6542            "0.1.0",
6543            vec![
6544                UpgradeInstruction::LoadModule { module: "x".into() },
6545                UpgradeInstruction::StateChange {
6546                    script: PathBuf::from("lib/m.lisp"),
6547                },
6548            ],
6549        )];
6550        let b = behavior_with_state_change_callback();
6551        validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
6552    }
6553
6554    #[test]
6555    fn behavior_gate_accepts_entries_without_any_state_change() {
6556        // Empty-set identity: entries carrying no `:state-change`
6557        // instruction at all (load + cleanup only — the metadata-only
6558        // upgrade shape the module doc names, "On any failure, the
6559        // current version stays load-bearing — a typed atomic
6560        // upgrade") leave the gate vacuous. The composition only
6561        // requires a callback when the per-version script exists; a
6562        // load + cleanup pair has no migration to deliver, so the
6563        // absence of `:on-state-change` is coherent.
6564        let entries = vec![entry(
6565            "0.1.0",
6566            vec![
6567                UpgradeInstruction::LoadModule { module: "x".into() },
6568                UpgradeInstruction::SoftPurge {
6569                    module: "x-old".into(),
6570                },
6571            ],
6572        )];
6573        validate_upgrade_from_against_behavior(&entries, None).unwrap();
6574    }
6575
6576    #[test]
6577    fn behavior_gate_accepts_restart_only_entry() {
6578        // The terminal-fallback `((:restart))` shape carries no
6579        // `:state-change` — the operator restarts the pod and the
6580        // new version comes up fresh against its initial state, no
6581        // migration. Pinned alongside the metadata-only positive
6582        // control above as the second empty-state-change shape.
6583        let entries = vec![entry("0.1.0", vec![UpgradeInstruction::Restart])];
6584        validate_upgrade_from_against_behavior(&entries, None).unwrap();
6585    }
6586
6587    #[test]
6588    fn behavior_gate_accepts_empty_entries_list() {
6589        // Empty `:upgrade-from` (a caixa with no declared upgrade
6590        // paths — the v0.1.0 caixa before any upgrade entries are
6591        // added) trivially passes the gate. Pinned so the gate
6592        // doesn't accidentally fire on a caixa that hasn't yet
6593        // declared any upgrades.
6594        let entries: Vec<UpgradeFromEntry> = vec![];
6595        validate_upgrade_from_against_behavior(&entries, None).unwrap();
6596    }
6597
6598    #[test]
6599    fn behavior_gate_reports_first_state_change_in_first_entry() {
6600        // First-collision determinism: with multiple `:state-change`
6601        // instructions across multiple entries, the gate reports the
6602        // *first* one encountered in declaration order — the entry's
6603        // declaration order first, then the within-entry instruction
6604        // order. Mirrors every peer first-collision diagnostic posture
6605        // on this module (`validate_state_change_ordering`,
6606        // `validate_purge_ordering`, the singularity gates), so a
6607        // future shortcut that walks the list in reverse or returns
6608        // the last collision surfaces as a regression here.
6609        let entries = vec![
6610            entry(
6611                "0.1.0",
6612                vec![
6613                    UpgradeInstruction::LoadModule { module: "x".into() },
6614                    UpgradeInstruction::StateChange {
6615                        script: PathBuf::from("lib/m1.lisp"),
6616                    },
6617                    UpgradeInstruction::StateChange {
6618                        script: PathBuf::from("lib/m2.lisp"),
6619                    },
6620                ],
6621            ),
6622            entry(
6623                "0.1.5",
6624                vec![
6625                    UpgradeInstruction::LoadModule { module: "x".into() },
6626                    UpgradeInstruction::StateChange {
6627                        script: PathBuf::from("lib/m3.lisp"),
6628                    },
6629                ],
6630            ),
6631        ];
6632        let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
6633        assert_eq!(
6634            err,
6635            UpgradeError::StateChangeWithoutOnStateChangeCallback {
6636                from: "0.1.0".into(),
6637                script: PathBuf::from("lib/m1.lisp"),
6638            },
6639            "the first :state-change in the first entry must surface, not later collisions"
6640        );
6641    }
6642
6643    #[test]
6644    fn behavior_gate_reports_second_entry_when_first_has_no_state_change() {
6645        // Cross-entry pin: a first entry with no `:state-change` (just
6646        // a load + cleanup) leaves the gate's per-entry walk continuing
6647        // to the second entry, where the offending instruction lives.
6648        // The diagnostic names the *second* entry's `:from` because
6649        // that's where the missing-callback shape is exposed — pinned
6650        // so a shortcut that bails on the first entry without a
6651        // `:state-change` (rather than continuing) doesn't mask the
6652        // defect in a later entry.
6653        let entries = vec![
6654            entry(
6655                "0.1.0",
6656                vec![
6657                    UpgradeInstruction::LoadModule { module: "x".into() },
6658                    UpgradeInstruction::SoftPurge {
6659                        module: "x-old".into(),
6660                    },
6661                ],
6662            ),
6663            entry(
6664                "0.1.5",
6665                vec![
6666                    UpgradeInstruction::LoadModule { module: "x".into() },
6667                    UpgradeInstruction::StateChange {
6668                        script: PathBuf::from("lib/m.lisp"),
6669                    },
6670                ],
6671            ),
6672        ];
6673        let err = validate_upgrade_from_against_behavior(&entries, None).unwrap_err();
6674        assert_eq!(
6675            err,
6676            UpgradeError::StateChangeWithoutOnStateChangeCallback {
6677                from: "0.1.5".into(),
6678                script: PathBuf::from("lib/m.lisp"),
6679            },
6680            "the offending entry's `:from` must surface even when an earlier entry carries no \
6681             :state-change"
6682        );
6683    }
6684
6685    #[test]
6686    fn behavior_gate_does_not_fire_when_callback_is_declared_across_many_entries() {
6687        // Positive control: a multi-entry `:upgrade-from` (chained
6688        // upgrades from v0.1.0 *and* v0.1.5) where every entry carries
6689        // a `:state-change` passes when the callback is declared once
6690        // at the caixa root. The callback is a single per-caixa
6691        // runtime hook; one declaration covers every entry's
6692        // `:state-change`, mirroring OTP's
6693        // `release_handler:install_release/1` which dispatches every
6694        // appup's `code_change` instruction through the single
6695        // `gen_server:code_change/3` callback registered on the
6696        // module.
6697        let entries = vec![
6698            entry(
6699                "0.1.0",
6700                vec![
6701                    UpgradeInstruction::LoadModule { module: "x".into() },
6702                    UpgradeInstruction::StateChange {
6703                        script: PathBuf::from("lib/m1.lisp"),
6704                    },
6705                ],
6706            ),
6707            entry(
6708                "0.1.5",
6709                vec![
6710                    UpgradeInstruction::LoadModule { module: "x".into() },
6711                    UpgradeInstruction::StateChange {
6712                        script: PathBuf::from("lib/m2.lisp"),
6713                    },
6714                ],
6715            ),
6716        ];
6717        let b = behavior_with_state_change_callback();
6718        validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
6719    }
6720
6721    #[test]
6722    fn behavior_gate_accepts_load_and_cleanup_only_when_behavior_carries_on_state_change() {
6723        // Symmetry pin: the gate's pass arm doesn't depend on the
6724        // entry actually carrying a `:state-change` — if no
6725        // `:state-change` is declared, the gate is vacuous regardless
6726        // of the callback (an `:on-state-change` declared without a
6727        // matching per-version script is fine, the callback is the
6728        // runtime default for any *future* migration the author hasn't
6729        // yet added). Pins that a caixa author can declare the
6730        // callback ahead of any migration without the gate
6731        // complaining.
6732        let entries = vec![entry(
6733            "0.1.0",
6734            vec![
6735                UpgradeInstruction::LoadModule { module: "x".into() },
6736                UpgradeInstruction::SoftPurge {
6737                    module: "x-old".into(),
6738                },
6739            ],
6740        )];
6741        let b = behavior_with_state_change_callback();
6742        validate_upgrade_from_against_behavior(&entries, Some(&b)).unwrap();
6743    }
6744
6745    #[test]
6746    fn validate_upgrade_from_against_behavior_projects_scripts_through_declared_path_accessor() {
6747        // Composition pin: [`validate_upgrade_from_against_behavior`]'s
6748        // per-instruction `StateChange`-arm script-path projection must
6749        // route through the sibling lifted
6750        // [`UpgradeInstruction::declared_path`] `Option<&PathBuf>`
6751        // accessor, not the raw
6752        // `if let UpgradeInstruction::StateChange { script } = instr`
6753        // open-coded pattern-match the cross-slot gate previously
6754        // carried at caixa-core/src/upgrade.rs:1365.
6755        //
6756        // Structurally: the gate's projection accept-set is the union
6757        // of every [`UpgradeInstruction`] variant for which
6758        // `declared_path().is_some()` — today exactly
6759        // [`UpgradeInstruction::StateChange`] per the sibling
6760        // `declared_path_only_for_state_change` pin, so a
6761        // `:state-change`-carrying entry without an `:on-state-change`
6762        // callback trips `StateChangeWithoutOnStateChangeCallback` and
6763        // a non-`StateChange` entry (load-only / cleanup-only /
6764        // restart-only / empty-`:instructions`) leaves the per-entry
6765        // walk continuing past every non-projecting instruction
6766        // byte-identical to the pattern-match shape.
6767        //
6768        // Byte-equal today (`declared_path` returns `Some(script)` iff
6769        // `StateChange`, byte-for-byte from the variant's own storage);
6770        // the pin catches any future accessor extension that promotes
6771        // an additional variant onto the `PathBuf`-carrying axis — the
6772        // gate then fires on scripts from that variant too, and the
6773        // cross-slot composition discipline the sibling per-
6774        // `UpgradeInstruction` consumers share on the `PathBuf`-
6775        // carrying axis extends to the promoted variant by
6776        // construction.
6777        //
6778        // Peer of the sibling four per-`UpgradeInstruction` consumers
6779        // ([`UpgradeInstruction::validate`]'s per-`StateChange`
6780        // sandbox-path fan-out, the layout-side per-`StateChange`
6781        // script-existence fan-out at
6782        // `caixa-core/src/layout.rs:1058`, the within-entry
6783        // [`UpgradeFromEntry::validate_state_change_singularity`]
6784        // (2bf3ce5) per-`StateChange` script-projection fan-out, the
6785        // peer [`UpgradeInstruction::declared_module`] `String`-axis
6786        // per-variant unifier) — the fourth (and last) per-
6787        // `UpgradeInstruction`-consumer of the `PathBuf`-carrying axis
6788        // to now route through the accessor. Same shape as the
6789        // sibling
6790        // `validate_state_change_singularity_projects_scripts_through_declared_path_accessor`
6791        // pin extended onto the cross-slot composition gate.
6792        //
6793        // Three-arm projective coverage:
6794        //   (a) `StateChange` scripts project through `declared_path()`
6795        //       byte-equal to the raw `script.clone()` field access
6796        //       the diagnostic previously carried;
6797        //   (b) a `:state-change`-carrying entry with `behavior: None`
6798        //       trips the gate with `StateChangeWithoutOnStateChangeCallback`
6799        //       carrying the offending script verbatim;
6800        //   (c) a non-`StateChange`-only entry (`LoadModule` /
6801        //       `SoftPurge` / `Purge` / `Restart`) leaves the gate
6802        //       vacuous with `Ok(())` — the `declared_path().is_none()`
6803        //       arm's fall-through pins.
6804        //
6805        // Fail-before-pass-after verified structurally: swapping the
6806        // production
6807        //   `if let Some(script) = instr.declared_path() { … }`
6808        // back to
6809        //   `if let UpgradeInstruction::StateChange { script } = instr { … }`
6810        // keeps arms (a)-(c) passing but silently detaches the gate
6811        // from the accessor's typed dispatch — any future
6812        // `declared_path` extension (promotion of an additional
6813        // variant onto the axis, an operator-side pre-resolved-path
6814        // cache the accessor materializes) would then silently
6815        // disagree between this cross-slot gate's raw pattern-match
6816        // and the peer four sibling consumers that route through the
6817        // accessor.
6818
6819        // (a) StateChange projection byte-equal via declared_path.
6820        let sc = UpgradeInstruction::StateChange {
6821            script: PathBuf::from("lib/m.lisp"),
6822        };
6823        assert_eq!(
6824            sc.declared_path().cloned(),
6825            Some(PathBuf::from("lib/m.lisp")),
6826            "declared_path() must project the StateChange :script byte-equal to the raw \
6827             field access — accessor divergence would silently detach this cross-slot \
6828             composition gate from the projection every peer per-`UpgradeInstruction` \
6829             consumer routes through"
6830        );
6831
6832        // (b) StateChange-carrying entry with behavior: None trips gate.
6833        let entries = vec![entry(
6834            "0.1.0",
6835            vec![
6836                UpgradeInstruction::LoadModule { module: "x".into() },
6837                UpgradeInstruction::StateChange {
6838                    script: PathBuf::from("lib/m.lisp"),
6839                },
6840            ],
6841        )];
6842        assert_eq!(
6843            validate_upgrade_from_against_behavior(&entries, None),
6844            Err(UpgradeError::StateChangeWithoutOnStateChangeCallback {
6845                from: "0.1.0".into(),
6846                script: PathBuf::from("lib/m.lisp"),
6847            }),
6848            "a :state-change-carrying entry with behavior: None must trip the gate through \
6849             the declared_path accessor's Some(script) arm — carrying the offending script \
6850             verbatim byte-identical to the pattern-match shape"
6851        );
6852
6853        // (c) Non-StateChange-only inputs leave the gate vacuous.
6854        for instrs in [
6855            vec![UpgradeInstruction::LoadModule { module: "x".into() }],
6856            vec![
6857                UpgradeInstruction::LoadModule { module: "x".into() },
6858                UpgradeInstruction::SoftPurge {
6859                    module: "x-old".into(),
6860                },
6861            ],
6862            vec![
6863                UpgradeInstruction::LoadModule { module: "x".into() },
6864                UpgradeInstruction::Purge {
6865                    module: "x-old".into(),
6866                },
6867            ],
6868            vec![UpgradeInstruction::Restart],
6869        ] {
6870            for instr in &instrs {
6871                assert!(
6872                    instr.declared_path().is_none(),
6873                    "non-StateChange variants must project None through declared_path — \
6874                     accessor divergence would let this cross-slot composition gate silently \
6875                     fire on a module reference far from any :state-change site"
6876                );
6877            }
6878            let entries = vec![entry("0.1.0", instrs)];
6879            assert_eq!(
6880                validate_upgrade_from_against_behavior(&entries, None),
6881                Ok(()),
6882                "the cross-slot composition gate must return Ok(()) on an entry whose \
6883                 instructions all project None through declared_path — the accessor's \
6884                 None arm the pattern-match's implicit fall-through previously carried"
6885            );
6886        }
6887    }
6888
6889    #[test]
6890    fn validate_restart_exclusive_threads_through_validate_upgrade_from() {
6891        // Wiring pin: the within-entry restart-exclusivity gate fires
6892        // through [`validate_upgrade_from`] (which delegates to
6893        // [`UpgradeFromEntry::validate`] per entry) before the cross-
6894        // entry duplicate-`:from` gate would have a chance to run on
6895        // the malformed entry. Pinned here so a future refactor that
6896        // walks the cross-entry gate first doesn't accidentally
6897        // surface a DuplicateFrom over an entry that's also malformed
6898        // at the within-entry restart-exclusivity layer.
6899        let entries = vec![
6900            entry(
6901                "0.1.0",
6902                vec![
6903                    UpgradeInstruction::LoadModule { module: "x".into() },
6904                    UpgradeInstruction::Restart,
6905                ],
6906            ),
6907            entry("0.1.0", vec![UpgradeInstruction::Restart]),
6908        ];
6909        let err = validate_upgrade_from(&entries).unwrap_err();
6910        assert!(
6911            matches!(
6912                err,
6913                UpgradeError::RestartNotExclusive {
6914                    restart_count: 1,
6915                    ..
6916                }
6917            ),
6918            "within-entry restart-exclusivity diagnostic must surface before the cross-entry \
6919             duplicate-`:from` gate fires, got {err:?}"
6920        );
6921    }
6922
6923    // ── drift-detection: serde-derive-to-M2_UPGRADE_FROM_KEY_* identity ──
6924
6925    #[test]
6926    fn upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts() {
6927        // Load-bearing invariant: the two `M2_UPGRADE_FROM_KEY_*` consts
6928        // (`M2_UPGRADE_FROM_KEY_FROM` / `M2_UPGRADE_FROM_KEY_INSTRUCTIONS`)
6929        // name the exact camelCase JSON keys the `#[serde(rename_all =
6930        // "camelCase")]` attribute on `UpgradeFromEntry` emits, and every
6931        // test-side probe across the caixa-core / caixa-flux renderer
6932        // test fixtures navigates into each element of the rendered
6933        // `:upgrade-from` overlay sequence by consulting one of these two
6934        // `&'static str`s. Serialize a fully-populated UpgradeFromEntry
6935        // and pin that each canonical byte-sequence appears verbatim in
6936        // the JSON — a future accidental `rename_all = "snake_case"` /
6937        // `"kebab-case"` / verbatim-field-name flip at the derive
6938        // attribute (any of which would silently break every test-side
6939        // probe that reaches for one of the two consts) surfaces here as
6940        // a build-time test failure at `upgrade.rs`, not as an apply-time
6941        // `.get(<stale-canonical-const>)` returning `None` far from the
6942        // derive-attr drift's commit. Same discipline the sibling
6943        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6944        // (d8b8b4f) and
6945        // `behavior_spec_serde_keys_match_lifted_m2_behavior_key_consts`
6946        // (21fe462) pins established on the peer `:limits` / `:behavior`
6947        // sub-slot axes: one canonical byte-string per typed sub-key
6948        // axis, pinned to the load-bearing serde derivation at the type
6949        // itself.
6950        let e = UpgradeFromEntry {
6951            from: "0.1.0".into(),
6952            instructions: vec![UpgradeInstruction::LoadModule {
6953                module: "hello-rio".into(),
6954            }],
6955        };
6956        let json = serde_json::to_string(&e).unwrap();
6957        for key in [
6958            crate::render::M2_UPGRADE_FROM_KEY_FROM,
6959            crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
6960        ] {
6961            let quoted = format!("\"{key}\"");
6962            assert!(
6963                json.contains(&quoted),
6964                "serialized UpgradeFromEntry must carry the lifted \
6965                 M2_UPGRADE_FROM_KEY_* byte-sequence {quoted} verbatim in \
6966                 the JSON emission (got: {json})",
6967            );
6968        }
6969    }
6970
6971    #[test]
6972    fn m2_upgrade_from_key_consts_are_pairwise_distinct() {
6973        // Cross-axis drift-detection pin: a future collapse of the two
6974        // canonical sub-key byte-strings onto the same value (e.g. an
6975        // accidental copy-paste flip of `M2_UPGRADE_FROM_KEY_INSTRUCTIONS`
6976        // to also read `"from"`) would silently reroute every test-side
6977        // probe on one axis onto the sibling axis's per-entry field and
6978        // pass every propagation-probe test that expected only the stale
6979        // axis's value. Peer of `m2_limits_key_consts_are_pairwise_distinct`
6980        // (d8b8b4f) and `m2_behavior_key_consts_are_pairwise_distinct`
6981        // (21fe462) on the sibling `:limits` / `:behavior` sub-slot axes.
6982        let all = [
6983            crate::render::M2_UPGRADE_FROM_KEY_FROM,
6984            crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
6985        ];
6986        for (i, a) in all.iter().enumerate() {
6987            for b in all.iter().skip(i + 1) {
6988                assert_ne!(
6989                    a, b,
6990                    "M2_UPGRADE_FROM_KEY_* consts must be pairwise-distinct \
6991                     canonical byte-sequences — got `{a}` == `{b}`",
6992                );
6993            }
6994        }
6995    }
6996
6997    #[test]
6998    fn upgrade_instruction_serde_tag_key_matches_lifted_m2_upgrade_instruction_key_kind_const() {
6999        // Load-bearing invariant on the M2 `:upgrade-from :instructions`
7000        // per-entry OTP-appup [`UpgradeInstruction`] enum's internally-
7001        // tagged variant-discriminator key axis: the
7002        // `M2_UPGRADE_INSTRUCTION_KEY_KIND` const names the exact tag-slot
7003        // JSON key the `#[serde(tag = "kind", rename_all = "kebab-case")]`
7004        // attribute on [`UpgradeInstruction`] emits, and every downstream
7005        // consumer that navigates the serialized instruction blob to
7006        // route by variant (the caixa-core reflection-vs-serde round-trip
7007        // check in `dispatcher_registration.rs` that probes
7008        // `v.get("kind")` against every variant's expected kebab-case
7009        // tag, the future M4 admission-webhook path, any wasm-operator
7010        // dispatch step consuming the serialized instruction blob) reads
7011        // through the same `&'static str`. Serialize every variant and
7012        // pin that the const's byte-sequence appears verbatim as the
7013        // tag-slot JSON key with the expected kebab-case value — a
7014        // future accidental `tag = "type"` / `tag = "op"` /
7015        // `tag = "instruction"` rebrand at the derive attribute (any of
7016        // which would silently break every consumer probe reaching for
7017        // the stale-tag-key const) surfaces here as a build-time test
7018        // failure at `upgrade.rs`, not as an apply-time
7019        // `.get(<stale-tag-key>)` returning `None` far from the derive-
7020        // attr drift's commit.
7021        //
7022        // Same "one canonical byte-string per typed axis" discipline the
7023        // sibling `upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts`
7024        // pin (36ffe65) established on the peer `:upgrade-from` per-entry
7025        // outer-container axis — this pin extends the discipline one
7026        // altitude deeper onto the per-instruction *tag* axis inside
7027        // each element of the `:instructions` list, completing the
7028        // typed coverage of the `:upgrade-from :instructions` dual
7029        // (key = "kind" + five variant-value tags): the five
7030        // `M2_UPGRADE_INSTRUCTION_KIND_*` consts (56120ef) pin the
7031        // per-variant kebab-case *values*; this pin pins the tag *key*
7032        // above them.
7033        let samples: [(UpgradeInstruction, &'static str); 5] = [
7034            (
7035                UpgradeInstruction::LoadModule {
7036                    module: "hello-rio".into(),
7037                },
7038                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE.trim_start_matches(':'),
7039            ),
7040            (
7041                UpgradeInstruction::StateChange {
7042                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7043                },
7044                crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE.trim_start_matches(':'),
7045            ),
7046            (
7047                UpgradeInstruction::SoftPurge {
7048                    module: "hello-rio-old".into(),
7049                },
7050                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE.trim_start_matches(':'),
7051            ),
7052            (
7053                UpgradeInstruction::Purge {
7054                    module: "hello-rio-old".into(),
7055                },
7056                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE.trim_start_matches(':'),
7057            ),
7058            (
7059                UpgradeInstruction::Restart,
7060                crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART.trim_start_matches(':'),
7061            ),
7062        ];
7063        for (sample, expected_value) in &samples {
7064            let v: serde_json::Value = serde_json::to_value(sample).unwrap();
7065            let got = v
7066                .get(crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND)
7067                .and_then(|k| k.as_str());
7068            assert_eq!(
7069                got,
7070                Some(*expected_value),
7071                "serialized {sample:?} must carry the lifted \
7072                 M2_UPGRADE_INSTRUCTION_KEY_KIND byte-sequence \
7073                 ({:?}) verbatim as the tag-slot JSON key, holding the \
7074                 expected kebab-case value {expected_value:?} (got: {v})",
7075                crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND,
7076            );
7077        }
7078    }
7079
7080    #[test]
7081    fn m2_upgrade_instruction_key_kind_const_is_lower_camel_case_shape() {
7082        // Shape-pin: the `M2_UPGRADE_INSTRUCTION_KEY_KIND` const must be
7083        // a lowerCamelCase byte-sequence (non-empty, ASCII-lowercase
7084        // leader, ASCII-alphanumeric only — no `snake_case` underscores,
7085        // no `kebab-case` hyphens, no `PascalCase` leading capital, no
7086        // whitespace / colons / dots) — the canonical shape a serde
7087        // internally-tagged discriminator key takes across every peer
7088        // enum in this crate. A future flip to a non-camelCase byte at
7089        // the const surfaces here at build time. Peer of
7090        // `m2_upgrade_from_key_consts_are_lower_camel_case_shape` on the
7091        // sibling per-entry outer-container axis.
7092        let key = crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND;
7093        assert!(
7094            !key.is_empty(),
7095            "M2_UPGRADE_INSTRUCTION_KEY_KIND must be non-empty (got {key:?})"
7096        );
7097        let first = key.chars().next().unwrap();
7098        assert!(
7099            first.is_ascii_lowercase(),
7100            "M2_UPGRADE_INSTRUCTION_KEY_KIND must lead with an ASCII-lowercase \
7101             byte (got {key:?}, leads with {first:?})",
7102        );
7103        assert!(
7104            key.chars().all(|c| c.is_ascii_alphanumeric()),
7105            "M2_UPGRADE_INSTRUCTION_KEY_KIND must be ASCII-alphanumeric only \
7106             — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7107        );
7108    }
7109
7110    #[test]
7111    fn m2_upgrade_instruction_key_kind_const_disjoint_from_variant_data_keys() {
7112        // Cross-axis drift-detection pin: the tag-slot key
7113        // `M2_UPGRADE_INSTRUCTION_KEY_KIND` (`"kind"`) must be
7114        // disjoint from every per-variant data-field key the
7115        // internally-tagged serialization also emits (`"module"` for
7116        // LoadModule/SoftPurge/Purge, `"script"` for StateChange). A
7117        // future accidental rebrand that collapses `tag = "kind"` onto
7118        // one of the data-field names (e.g. `tag = "module"`) would
7119        // silently corrupt every serialized LoadModule blob (the
7120        // module string and the variant tag would collide on the same
7121        // JSON key) and every consumer probe would either misread the
7122        // tag or fail to distinguish variants. Pin the disjointness at
7123        // build time. Same cross-axis discipline the sibling
7124        // `m2_upgrade_from_key_consts_are_pairwise_distinct` pin
7125        // (36ffe65) established on the outer container's own
7126        // `from`/`instructions` pair.
7127        let key = crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND;
7128        // Enumerate every per-variant data-field key across all five
7129        // variants of [`UpgradeInstruction`], routing through the two
7130        // lifted `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` byte-string consts
7131        // that name the same per-variant data-field JSON keys the
7132        // `variant_fields` reflection in
7133        // `caixa-core/tests/dispatcher_registration.rs` surfaces. A future
7134        // per-variant struct-field rebrand (`module` → `component`,
7135        // `script` → `path`) lands as an edit to exactly one const and
7136        // reaches this disjointness pin by construction — the two axes
7137        // (tag-slot key on one side, per-variant data-field keys on the
7138        // other) share one source of truth per axis.
7139        for data_field in [
7140            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7141            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7142        ] {
7143            assert_ne!(
7144                key, data_field,
7145                "M2_UPGRADE_INSTRUCTION_KEY_KIND (the serde `tag` slot) \
7146                 must be disjoint from every UpgradeInstruction per-variant \
7147                 data-field key — got tag-key {key:?} colliding with \
7148                 data-field {data_field:?}, which would silently corrupt \
7149                 the internally-tagged serialization",
7150            );
7151        }
7152    }
7153
7154    #[test]
7155    fn upgrade_instruction_variant_data_field_keys_match_lifted_field_key_consts() {
7156        // Load-bearing invariant on the M2 `:upgrade-from :instructions`
7157        // per-entry OTP-appup [`UpgradeInstruction`] enum's per-variant
7158        // data-field JSON key axis: the two
7159        // `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` consts (`_MODULE`,
7160        // `_SCRIPT`) name the exact per-variant field JSON keys the
7161        // `#[serde(tag = "kind", rename_all = "kebab-case")]` attribute on
7162        // [`UpgradeInstruction`] emits alongside the tag-slot key from the
7163        // sibling [`crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND`]
7164        // const — the `module: String` struct-field on
7165        // `LoadModule`/`SoftPurge`/`Purge` and the `script: PathBuf`
7166        // struct-field on `StateChange` are promoted to sibling JSON keys
7167        // at the same nesting level as the tag by the internally-tagged
7168        // serialization, and every downstream consumer that navigates the
7169        // serialized instruction blob to reach the payload (the caixa-core
7170        // reflection round-trip in `dispatcher_registration.rs` that
7171        // consults `variant_fields`, the sibling disjointness pin below,
7172        // any future wasm-operator upgrade-dispatch step consuming the
7173        // serialized instruction blob to route the per-module load /
7174        // soft-purge / purge action or the per-script state-change action)
7175        // reads through the same `&'static str`. Serialize one Module-
7176        // bearing variant and one Script-bearing variant, then pin that
7177        // each const's byte-sequence appears verbatim in the JSON emission
7178        // — a future accidental struct-field rebrand (`module: String` →
7179        // `component: String`, `script: PathBuf` → `path: PathBuf`) at
7180        // either variant surfaces here as a build-time test failure at
7181        // `upgrade.rs`, not as an apply-time `.get(<stale-field-key>)`
7182        // returning `None` far from the field-name drift's commit.
7183        //
7184        // Same "one canonical byte-string per typed axis" discipline the
7185        // sibling `upgrade_instruction_serde_tag_key_matches_lifted_m2_upgrade_instruction_key_kind_const`
7186        // pin established on the peer tag-slot key axis on the same
7187        // enum — this pin extends the discipline onto the per-variant
7188        // data-field key axis, completing the `:upgrade-from :instructions`
7189        // variant-JSON dual (tag key + tag values + per-variant field keys)
7190        // fully into caixa-core.
7191        let module_sample = UpgradeInstruction::LoadModule {
7192            module: "hello-rio".into(),
7193        };
7194        let v: serde_json::Value = serde_json::to_value(&module_sample).unwrap();
7195        assert_eq!(
7196            v.get(crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE)
7197                .and_then(|k| k.as_str()),
7198            Some("hello-rio"),
7199            "serialized {module_sample:?} must carry the lifted \
7200             M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE byte-sequence \
7201             ({:?}) verbatim as the data-field JSON key holding the \
7202             module string (got: {v})",
7203            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7204        );
7205
7206        let script_sample = UpgradeInstruction::StateChange {
7207            script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7208        };
7209        let v: serde_json::Value = serde_json::to_value(&script_sample).unwrap();
7210        assert_eq!(
7211            v.get(crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT)
7212                .and_then(|k| k.as_str()),
7213            Some("lib/migrations/v01-to-v02.lisp"),
7214            "serialized {script_sample:?} must carry the lifted \
7215             M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT byte-sequence \
7216             ({:?}) verbatim as the data-field JSON key holding the \
7217             script path (got: {v})",
7218            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7219        );
7220    }
7221
7222    #[test]
7223    fn m2_upgrade_instruction_field_key_consts_are_lower_camel_case_shape() {
7224        // Shape-pin: every `M2_UPGRADE_INSTRUCTION_FIELD_KEY_*` const must
7225        // be a lowerCamelCase byte-sequence (non-empty, ASCII-lowercase
7226        // leader, ASCII-alphanumeric only — no `snake_case` underscores,
7227        // no `kebab-case` hyphens, no `PascalCase` leading capital, no
7228        // whitespace / colons / dots) — the canonical shape a Rust
7229        // struct-field name promoted to a JSON key by serde takes on this
7230        // internally-tagged variant surface, matching the sibling
7231        // [`crate::render::M2_UPGRADE_INSTRUCTION_KEY_KIND`] tag-slot key
7232        // shape. A future flip to a non-camelCase byte at either const
7233        // (an accidental `rename_all` regime interleave, or a struct-
7234        // field flip like `module` → `module_name`) surfaces here at
7235        // build time. Peer of
7236        // `m2_upgrade_instruction_key_kind_const_is_lower_camel_case_shape`
7237        // and `m2_upgrade_from_key_consts_are_lower_camel_case_shape` on
7238        // the sibling wire-key axes.
7239        for key in [
7240            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7241            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7242        ] {
7243            assert!(
7244                !key.is_empty(),
7245                "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must be non-empty (got {key:?})"
7246            );
7247            let first = key.chars().next().unwrap();
7248            assert!(
7249                first.is_ascii_lowercase(),
7250                "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must lead with an ASCII-lowercase \
7251                 byte (got {key:?}, leads with {first:?})",
7252            );
7253            assert!(
7254                key.chars().all(|c| c.is_ascii_alphanumeric()),
7255                "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* must be ASCII-alphanumeric only \
7256                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7257            );
7258        }
7259    }
7260
7261    #[test]
7262    fn m2_upgrade_instruction_field_key_consts_are_pairwise_distinct() {
7263        // Cross-axis drift-detection pin: a future collapse of the two
7264        // canonical per-variant data-field byte-strings onto the same
7265        // value (e.g. an accidental copy-paste flip of
7266        // `M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT` to also read
7267        // `"module"`) would silently reroute every test-side probe on one
7268        // variant's payload onto the sibling variant's payload and pass
7269        // every propagation-probe test that expected only the stale
7270        // axis's value. Peer of `m2_upgrade_from_key_consts_are_pairwise_distinct`
7271        // on the sibling per-entry outer-container axis, and of
7272        // `m2_upgrade_instruction_key_kind_const_disjoint_from_variant_data_keys`
7273        // on the sibling tag-slot key ↔ per-variant data-field key axis.
7274        let all = [
7275            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_MODULE,
7276            crate::render::M2_UPGRADE_INSTRUCTION_FIELD_KEY_SCRIPT,
7277        ];
7278        for (i, a) in all.iter().enumerate() {
7279            for b in all.iter().skip(i + 1) {
7280                assert_ne!(
7281                    a, b,
7282                    "M2_UPGRADE_INSTRUCTION_FIELD_KEY_* consts must be pairwise-distinct \
7283                     canonical byte-sequences — got `{a}` == `{b}`",
7284                );
7285            }
7286        }
7287    }
7288
7289    #[test]
7290    fn m2_upgrade_from_key_consts_are_lower_camel_case_shape() {
7291        // Shape-pin: every `M2_UPGRADE_FROM_KEY_*` const must be a
7292        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7293        // `kebab-case` hyphens, no `PascalCase` leading capital, no
7294        // whitespace / colons / dots) — the canonical shape the
7295        // `#[serde(rename_all = "camelCase")]` derive produces on
7296        // `UpgradeFromEntry`. A future flip to a non-camelCase attribute
7297        // at the derive surfaces both here (this test fails on the
7298        // stale-constant shape) and at
7299        // `upgrade_from_entry_serde_keys_match_lifted_m2_upgrade_from_key_consts`
7300        // (that test fails on the mismatch between const and derive).
7301        // Peer of `m2_limits_key_consts_are_lower_camel_case_shape`
7302        // (d8b8b4f) and `m2_behavior_key_consts_are_lower_camel_case_shape`
7303        // (21fe462) on the sibling `:limits` / `:behavior` sub-slot axes.
7304        for key in [
7305            crate::render::M2_UPGRADE_FROM_KEY_FROM,
7306            crate::render::M2_UPGRADE_FROM_KEY_INSTRUCTIONS,
7307        ] {
7308            assert!(
7309                !key.is_empty(),
7310                "M2_UPGRADE_FROM_KEY_* must be non-empty (got {key:?})"
7311            );
7312            let first = key.chars().next().unwrap();
7313            assert!(
7314                first.is_ascii_lowercase(),
7315                "M2_UPGRADE_FROM_KEY_* must lead with an ASCII-lowercase \
7316                 byte (got {key:?}, leads with {first:?})",
7317            );
7318            assert!(
7319                key.chars().all(|c| c.is_ascii_alphanumeric()),
7320                "M2_UPGRADE_FROM_KEY_* must be ASCII-alphanumeric only \
7321                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7322            );
7323        }
7324    }
7325
7326    #[test]
7327    fn m2_upgrade_instruction_kind_consts_pin_canonical_kebab_case_labels() {
7328        // Scalar-value pin on the M2 `:upgrade-from :instructions` per-entry
7329        // OTP-appup variant-tag axis: the five canonical author-facing
7330        // kebab-case labels (`:load-module` / `:state-change` /
7331        // `:soft-purge` / `:purge` / `:restart`) the substrate's
7332        // per-variant [`UpgradeInstruction::lisp_form`] dispatch reads
7333        // from and every downstream consumer probes for verbatim. Same
7334        // scalar-value discipline the peer
7335        // `contrato_author_key_consts_pin_canonical_kebab_case_labels`
7336        // (f50c875), `m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7337        // (882f498), `m2_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7338        // (f49c8b0), and `supervisor_top_level_author_key_consts_pin_canonical_kebab_case_labels`
7339        // (be40492) established for the sibling M2 / M3 / Supervisor
7340        // top-level and sub-slot author-facing-label axes. Fail-before-
7341        // pass-after locally verified by mutating
7342        // `M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE` to `":load"` — this
7343        // pin fires as expected; restoring passes.
7344        //
7345        // A future OTP-lineage per-variant rebrand (e.g.
7346        // `:load-module` → `:load` matching Erlang's abbreviated
7347        // `code:load_module` name, `:state-change` → `:code-change`
7348        // matching Erlang's verbatim `code_change/3` callback,
7349        // `:soft-purge` → `:drain` matching a hypothetical operator-side
7350        // vocabulary flip, `:purge` → `:discard` matching a hypothetical
7351        // Elixir/Phoenix hot-reload rebrand, `:restart` → `:reboot`
7352        // matching a supervisor-tree vocabulary alignment) lands as an
7353        // edit to exactly one const, and every consumer that reaches for
7354        // the label (the [`UpgradeInstruction::lisp_form`] dispatch, the
7355        // [`validate_cleanup_singularity`] per-variant `kind:` tagger,
7356        // every [`UpgradeError`] `kind:` / `kinds:` / `other_kinds:` /
7357        // `prior_cleanup_kind:` diagnostic field, the
7358        // [`LayoutError::UpgradeViolation`] `issue:` probe in
7359        // `layout.rs`) picks it up at build time rather than at runtime
7360        // as a downstream `kind: <stale-kebab-case>` diagnostic mismatch
7361        // far from the rename's commit.
7362        assert_eq!(
7363            crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
7364            ":load-module"
7365        );
7366        assert_eq!(
7367            crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
7368            ":state-change"
7369        );
7370        assert_eq!(
7371            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
7372            ":soft-purge"
7373        );
7374        assert_eq!(crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE, ":purge");
7375        assert_eq!(
7376            crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
7377            ":restart"
7378        );
7379    }
7380
7381    #[test]
7382    fn m2_upgrade_instruction_kind_consts_are_pairwise_distinct() {
7383        // Cross-arm drift-detection pin on the M2
7384        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE`] /
7385        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE`] /
7386        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`] /
7387        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE`] /
7388        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART`]
7389        // closed-set OTP-appup variant-tag pentad: a future collapse
7390        // of two canonical variant byte-strings onto the same value
7391        // (an accidental copy-paste flip of
7392        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`]
7393        // to also read `":purge"`, a per-arm rebrand that lands one
7394        // const without touching its paired peer) would silently
7395        // reroute every downstream OTP-appup dispatcher's per-
7396        // instruction branch onto the sibling arm's runtime
7397        // behavior and pass every propagation-probe test that
7398        // expected only the stale arm's tag — a `:soft-purge`
7399        // instruction (drain-then-swap: existing callers finish
7400        // under the old module, new callers land on the new one)
7401        // would come up under the `:purge` reconcile branch
7402        // (drop-existing: every in-flight caller terminates
7403        // immediately) on every hot-upgrade cycle, so a rolling
7404        // module swap would silently downgrade to a hard cutover
7405        // against its declared appup discipline, with no field
7406        // naming the instruction-tag drift root cause. Every
7407        // [`crate::UpgradeError`] diagnostic that surfaces the tag
7408        // ([`crate::UpgradeError::ModuleEmpty`] with `kind:` field,
7409        // [`crate::UpgradeError::CleanupCollision`] with `kinds:`
7410        // slice, [`crate::UpgradeError::CleanupPrecedes`] with
7411        // `prior_cleanup_kind:` field, the
7412        // [`crate::LayoutError::UpgradeViolation`] `issue:` probe in
7413        // `layout.rs`) would emit the sibling arm's stale bytes at
7414        // the operator's console, far from the source rebrand
7415        // commit. Peer of the sibling
7416        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
7417        // (09ffb2d) /
7418        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
7419        // (ccdf955) /
7420        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
7421        // (d739850) distinctness pins on the sibling OTP-shape /
7422        // caixa-kind closed-set typed-enum discriminator axes —
7423        // the fifth closed-set OTP-appup / typed-enum axis to
7424        // converge on the same
7425        // "pairwise-distinct-by-construction" discipline, and the
7426        // canonical companion to the peer
7427        // [`m2_upgrade_instruction_field_key_consts_are_pairwise_distinct`]
7428        // (ff980bb) distinctness pin on the sibling internally-
7429        // tagged-JSON per-variant data-field-key axis (the tag axis
7430        // this pin covers vs. the data-field-key axis its peer
7431        // covers — two paired axes on the same
7432        // [`crate::UpgradeInstruction`] typed enum surface).
7433        //
7434        // Fail-before-pass-after locally verified by mutating
7435        // [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE`]
7436        // to also read `":purge"` — this pin fires as expected;
7437        // restoring passes.
7438        let all = [
7439            crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
7440            crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
7441            crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
7442            crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
7443            crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
7444        ];
7445        for (i, a) in all.iter().enumerate() {
7446            for (j, b) in all.iter().enumerate() {
7447                if i != j {
7448                    assert_ne!(
7449                        a, b,
7450                        "M2_UPGRADE_INSTRUCTION_KIND_* consts must be pairwise \
7451                         distinct — got duplicate {a:?} at indices {i} and {j}",
7452                    );
7453                }
7454            }
7455        }
7456    }
7457
7458    #[test]
7459    fn upgrade_instruction_lisp_form_routes_through_lifted_kind_consts() {
7460        // Production-through-const pin: the five per-variant labels
7461        // [`UpgradeInstruction::lisp_form`] returns route through the
7462        // lifted [`crate::render::M2_UPGRADE_INSTRUCTION_KIND_*`] consts,
7463        // so a future rebrand that reaches the const but not the
7464        // dispatch (or vice versa) surfaces here at build time rather
7465        // than at runtime as a downstream
7466        // [`UpgradeError::ModuleEmpty`] `kind: <stale-kebab-case>`
7467        // diagnostic drift far from the rename's commit. Mirror of the
7468        // peer `contrato_shape_gate_routes_through_lifted_contrato_author_key_consts`
7469        // (f50c875), `declared_mesh_slots_route_through_lifted_m3_author_key_consts`
7470        // (882f498), and `declared_servico_slots_route_through_lifted_m2_author_key_consts`
7471        // (f49c8b0) production-through-const pins on the sibling M3 /
7472        // M2 top-level slot axes.
7473        //
7474        // Fail-before-pass-after locally verified by mutating
7475        // `UpgradeInstruction::lisp_form`'s `Self::Purge` arm to return
7476        // `":purge-drift"` — this pin fires as expected; restoring
7477        // passes.
7478        let cases: &[(UpgradeInstruction, &'static str)] = &[
7479            (
7480                UpgradeInstruction::LoadModule { module: "x".into() },
7481                crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE,
7482            ),
7483            (
7484                UpgradeInstruction::StateChange {
7485                    script: PathBuf::from("lib/m.lisp"),
7486                },
7487                crate::render::M2_UPGRADE_INSTRUCTION_KIND_STATE_CHANGE,
7488            ),
7489            (
7490                UpgradeInstruction::SoftPurge {
7491                    module: "x-old".into(),
7492                },
7493                crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE,
7494            ),
7495            (
7496                UpgradeInstruction::Purge {
7497                    module: "x-old".into(),
7498                },
7499                crate::render::M2_UPGRADE_INSTRUCTION_KIND_PURGE,
7500            ),
7501            (
7502                UpgradeInstruction::Restart,
7503                crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART,
7504            ),
7505        ];
7506        for (instr, expected) in cases {
7507            assert_eq!(
7508                instr.lisp_form(),
7509                *expected,
7510                "UpgradeInstruction::lisp_form on {instr:?} must route through the lifted \
7511                 const (expected {expected:?})",
7512            );
7513        }
7514    }
7515
7516    #[test]
7517    fn upgrade_from_entry_instructions_returns_instructions_slice_byte_equal_across_permutations() {
7518        // The canonical per-`:upgrade-from :instructions` OTP-appup
7519        // migration-instruction-list slice-shape pin:
7520        // [`UpgradeFromEntry::instructions`] must return the
7521        // `:instructions` typed `Vec<UpgradeInstruction>` verbatim as
7522        // a `&[UpgradeInstruction]` slice-view over the same backing
7523        // buffer the raw `self.instructions.as_slice()` field access
7524        // borrows from, byte-equal across every representative fixture
7525        // in the accept-set — the empty slice (the "no-op upgrade" /
7526        // metadata-only sentinel the [`UpgradeFromEntry::instructions`]
7527        // field's own docstring names), the singleton slice on every
7528        // variant of the [`UpgradeInstruction`] arm-space
7529        // (`LoadModule` / `StateChange` / `SoftPurge` / `Purge` /
7530        // `Restart` — the five OTP-appup runtime-primitive variants),
7531        // and multi-instruction cohorts (the canonical
7532        // `LoadModule → StateChange → SoftPurge` OTP two-phase code-
7533        // load + state-migration triad the module doc names as the
7534        // "runs the instructions in order" example).
7535        //
7536        // Pins against a future silent detour that returned
7537        // `&Vec<UpgradeInstruction>` (which would type-check but leak
7538        // the storage-side `Vec`'s grow/push/reserve surface no
7539        // consumer of the typed view reaches for), a fresh-allocated
7540        // `Vec<UpgradeInstruction>` copy (which would type-check via
7541        // a coercion but silently break every downstream caller that
7542        // relied on the slice sharing the backing buffer's identity),
7543        // or an out-of-order or length-drifted projection (which
7544        // would silently split the paired within-entry cross-
7545        // instruction ordering gates' inputs from the peer per-
7546        // instruction shape-check loop's input, one seven-gate cohort
7547        // silently drifting from the peer gate's actual traversal
7548        // input).
7549        //
7550        // Peer of the sibling
7551        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
7552        // (0dcc926) `&[WitContract]` byte-equal pin on the M3 per-
7553        // `:contratos` edge-list axis, extended onto the M2 per-
7554        // `:upgrade-from :instructions` migration-instruction-list
7555        // axis — the fifth `&[T]`-return byte-equal pin, closing the
7556        // last unlifted `Vec`-carry axis on any M2 or M3 typed slot.
7557        let fixtures: Vec<Vec<UpgradeInstruction>> = vec![
7558            Vec::new(),
7559            vec![UpgradeInstruction::LoadModule { module: "x".into() }],
7560            vec![UpgradeInstruction::StateChange {
7561                script: PathBuf::from("lib/m.lisp"),
7562            }],
7563            vec![UpgradeInstruction::SoftPurge {
7564                module: "x-old".into(),
7565            }],
7566            vec![UpgradeInstruction::Purge {
7567                module: "x-old".into(),
7568            }],
7569            vec![UpgradeInstruction::Restart],
7570            vec![
7571                UpgradeInstruction::LoadModule { module: "x".into() },
7572                UpgradeInstruction::StateChange {
7573                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7574                },
7575                UpgradeInstruction::SoftPurge {
7576                    module: "x-old".into(),
7577                },
7578            ],
7579        ];
7580        for instructions in fixtures {
7581            let e = UpgradeFromEntry {
7582                from: "0.1.0".into(),
7583                instructions: instructions.clone(),
7584            };
7585            assert_eq!(
7586                e.instructions(),
7587                e.instructions.as_slice(),
7588                "UpgradeFromEntry::instructions must project the raw \
7589                 `:instructions` `Vec<UpgradeInstruction>` verbatim as a \
7590                 `&[UpgradeInstruction]` slice-view over the same backing buffer \
7591                 (fixture: {instructions:?})",
7592            );
7593            assert_eq!(
7594                e.instructions().len(),
7595                instructions.len(),
7596                "UpgradeFromEntry::instructions length must match the raw \
7597                 `:instructions` `Vec<UpgradeInstruction>` length (fixture: {instructions:?})",
7598            );
7599        }
7600    }
7601
7602    #[test]
7603    fn validate_reads_through_lifted_instructions_accessor() {
7604        // Three-consumer coherence pin on the lifted
7605        // [`UpgradeFromEntry::instructions`] slice-return accessor:
7606        // exercises three of the nine paired production consumers of
7607        // the per-`:upgrade-from :instructions` OTP-appup migration-
7608        // instruction-list surface through end-to-end validate() paths
7609        // that require the accessor to reach each of the fixture's
7610        // instructions.
7611        //
7612        // (1) The per-instruction shape-check fan-out
7613        // ([`UpgradeFromEntry::validate`]'s `for instr in
7614        // self.instructions()` loop): pass the well-formed load →
7615        // state-change → soft-purge triad — `validate()` must accept
7616        // it, which requires the accessor to project every entry so
7617        // each `instr.validate()` fires.
7618        //
7619        // (2) The within-entry state-change-ordering gate
7620        // ([`Self::validate_state_change_ordering`]): pass a
7621        // `((:state-change …))` singleton — `validate()` must return
7622        // [`UpgradeError::StateChangeWithoutPriorLoad`], which
7623        // requires the accessor to reach the state-change so the
7624        // no-prior-load probe fires.
7625        //
7626        // (3) The within-entry per-module cleanup-singularity gate
7627        // ([`Self::validate_cleanup_singularity`]): pass a
7628        // `((:load-module "x") (:soft-purge "x-old") (:soft-purge
7629        // "x-old"))` cohort — `validate()` must return
7630        // [`UpgradeError::DuplicateCleanup`], which requires the
7631        // accessor to iterate the whole list so the second `SoftPurge`
7632        // matches the first via the `seen` set.
7633        //
7634        // Peer of the sibling
7635        // `validate_reads_through_lifted_contratos_accessor` (0dcc926)
7636        // three-consumer coherence pin on the M3 per-`:contratos`
7637        // edge-list axis, extended onto the M2 per-`:upgrade-from
7638        // :instructions` migration-instruction-list axis.
7639
7640        // (1) accept the well-formed OTP two-phase code-load triad
7641        let well_formed = entry(
7642            "0.1.0",
7643            vec![
7644                UpgradeInstruction::LoadModule { module: "x".into() },
7645                UpgradeInstruction::StateChange {
7646                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
7647                },
7648                UpgradeInstruction::SoftPurge {
7649                    module: "x-old".into(),
7650                },
7651            ],
7652        );
7653        assert!(
7654            well_formed.validate().is_ok(),
7655            "well-formed `LoadModule → StateChange → SoftPurge` triad must accept — \
7656             the per-instruction shape-check fan-out requires the accessor to reach every entry"
7657        );
7658
7659        // (2) refuse a `((:state-change …))` singleton — the
7660        // state-change-without-prior-load gate must fire, which
7661        // requires the accessor to reach the single instruction.
7662        let no_prior_load = entry(
7663            "0.1.0",
7664            vec![UpgradeInstruction::StateChange {
7665                script: PathBuf::from("lib/m.lisp"),
7666            }],
7667        );
7668        match no_prior_load.validate() {
7669            Err(UpgradeError::StateChangeWithoutPriorLoad { .. }) => {}
7670            other => panic!(
7671                "expected StateChangeWithoutPriorLoad on a `((:state-change …))` singleton \
7672                 — the within-entry state-change-ordering gate must reach the single \
7673                 instruction through the lifted accessor; got: {other:?}"
7674            ),
7675        }
7676
7677        // (3) refuse a `((:load-module "x") (:soft-purge "x-old")
7678        // (:soft-purge "x-old"))` cohort — the per-module cleanup-
7679        // singularity gate must fire on the second `SoftPurge`, which
7680        // requires the accessor to iterate the whole list.
7681        let duplicate_cleanup = entry(
7682            "0.1.0",
7683            vec![
7684                UpgradeInstruction::LoadModule { module: "x".into() },
7685                UpgradeInstruction::SoftPurge {
7686                    module: "x-old".into(),
7687                },
7688                UpgradeInstruction::SoftPurge {
7689                    module: "x-old".into(),
7690                },
7691            ],
7692        );
7693        match duplicate_cleanup.validate() {
7694            Err(UpgradeError::DuplicateCleanup { module, .. }) => {
7695                assert_eq!(
7696                    module, "x-old",
7697                    "DuplicateCleanup must name the colliding module `x-old` — the per-module \
7698                     cleanup-singularity gate must iterate through the lifted accessor to \
7699                     match the second SoftPurge against the first via the `seen` set"
7700                );
7701            }
7702            other => panic!(
7703                "expected DuplicateCleanup on `((:load-module x) (:soft-purge x-old) \
7704                 (:soft-purge x-old))` — the within-entry cleanup-singularity gate must \
7705                 iterate the whole list through the lifted accessor; got: {other:?}"
7706            ),
7707        }
7708
7709        // Path::new suppresses the unused-import warning if the
7710        // outer module trims `use std::path::Path;` in a future edit.
7711        let _ = Path::new("lib/m.lisp");
7712    }
7713
7714    // Per-variant equivalence pins for the [`upgrade_from_script_ctors!`]
7715    // macro definition (see the paired doc-block above the macro
7716    // definition) — every generated `<ctor>(from: &str, script: &Path)
7717    // -> Self` constructor folds the uniform `Self::<Variant> { from:
7718    // from.to_string(), script: script.to_path_buf() }` two-field
7719    // struct-literal onto one substrate primitive. The three per-variant
7720    // equivalence pins below (fail-before-pass-after by construction — a
7721    // byte-mismatched macro arm would trip its equivalence pin first)
7722    // lock each generated constructor to its struct-literal peer under
7723    // `PartialEq`, so every wire-up in
7724    // [`UpgradeFromEntry::validate_state_change_ordering`],
7725    // [`UpgradeFromEntry::validate_state_change_uniqueness`], and
7726    // [`validate_state_change_on_state_change_callback`] on that
7727    // variant produces a byte-equal `UpgradeError` to the pre-lift
7728    // open-coded struct-literal. The cross-axis pin that follows
7729    // (non-default `(from, script)` pair) routes both constructor input
7730    // axes through `.to_string()` / `.to_path_buf()`, so the fold does
7731    // not silently collapse onto a fixed `from` / `script` value.
7732    //
7733    // Peer of the sibling `empty_child_version_ctor_matches_struct_
7734    // literal_wrap` / `duplicate_child_caixa_ctor_matches_struct_
7735    // literal_wrap` / `child_supervises_self_ctor_matches_struct_
7736    // literal_wrap` / `supervisor_caixa_only_ctors_route_caixa_through_
7737    // to_string` equivalence + cross-axis pins the sibling
7738    // [`crate::supervisor::supervisor_caixa_only_ctors!`] family (db09650)
7739    // established on the peer `SupervisorError` envelope; extended
7740    // here onto the `UpgradeError` `{ from: String, script: PathBuf }`
7741    // two-slot envelope so every substrate-primitive ctor family in
7742    // caixa-core guarantees the same-shape fold every wire-up on the
7743    // family reads through one dispatch.
7744
7745    #[test]
7746    fn state_change_without_prior_load_ctor_matches_struct_literal_wrap() {
7747        let from = "0.1.0";
7748        let script = Path::new("lib/migrations/v01-to-v02.lisp");
7749        assert_eq!(
7750            UpgradeError::state_change_without_prior_load(from, script),
7751            UpgradeError::StateChangeWithoutPriorLoad {
7752                from: from.to_string(),
7753                script: script.to_path_buf(),
7754            },
7755            "generated state_change_without_prior_load ctor must produce \
7756             byte-equal UpgradeError to the open-coded struct-literal \
7757             wrap on the same (&str, &Path) fixture",
7758        );
7759    }
7760
7761    #[test]
7762    fn duplicate_state_change_ctor_matches_struct_literal_wrap() {
7763        let from = "0.1.0";
7764        let script = Path::new("lib/migrations/v01-to-v02.lisp");
7765        assert_eq!(
7766            UpgradeError::duplicate_state_change(from, script),
7767            UpgradeError::DuplicateStateChange {
7768                from: from.to_string(),
7769                script: script.to_path_buf(),
7770            },
7771            "generated duplicate_state_change ctor must produce byte-equal \
7772             UpgradeError to the open-coded struct-literal wrap on the \
7773             same (&str, &Path) fixture",
7774        );
7775    }
7776
7777    #[test]
7778    fn state_change_without_on_state_change_callback_ctor_matches_struct_literal_wrap() {
7779        let from = "0.1.0";
7780        let script = Path::new("lib/migrations/v01-to-v02.lisp");
7781        assert_eq!(
7782            UpgradeError::state_change_without_on_state_change_callback(from, script),
7783            UpgradeError::StateChangeWithoutOnStateChangeCallback {
7784                from: from.to_string(),
7785                script: script.to_path_buf(),
7786            },
7787            "generated state_change_without_on_state_change_callback ctor \
7788             must produce byte-equal UpgradeError to the open-coded \
7789             struct-literal wrap on the same (&str, &Path) fixture",
7790        );
7791    }
7792
7793    #[test]
7794    fn upgrade_from_script_ctors_route_from_and_script_verbatim() {
7795        // Cross-axis pin: sweep both constructor input axes (`from:
7796        // &str`, `script: &Path`) through non-default fixtures against
7797        // every generated arm in the [`upgrade_from_script_ctors!`]
7798        // macro, so any wrapper-side lowercase / trim / truncate /
7799        // re-order / fixed-path substitution on the two-field
7800        // construction surfaces here rather than at a downstream
7801        // diagnostic-shape mismatch. Also exercises the `&Path`
7802        // parameter under both `&Path` (direct `Path::new`) and
7803        // `&PathBuf` (via Deref coercion), matching the two shapes the
7804        // three wire-up sites thread through — the ordering /
7805        // callback-declaration gates hand a `&PathBuf` from
7806        // `instr.declared_path()`; the uniqueness gate hands a `&Path`
7807        // from `script.as_path()`. Peer of the sibling
7808        // `supervisor_caixa_only_ctors_route_caixa_through_to_string`
7809        // cross-axis pin on the peer `SupervisorError` `{ caixa:
7810        // String }` envelope.
7811        let from = "1.2.3-rc.1";
7812        let script_owned = PathBuf::from("lib/migrations/v02-to-v03.lisp");
7813        let script_ref: &Path = script_owned.as_path();
7814        for script in [script_ref, &script_owned as &Path] {
7815            assert_eq!(
7816                UpgradeError::state_change_without_prior_load(from, script),
7817                UpgradeError::StateChangeWithoutPriorLoad {
7818                    from: from.to_string(),
7819                    script: script.to_path_buf(),
7820                },
7821            );
7822            assert_eq!(
7823                UpgradeError::duplicate_state_change(from, script),
7824                UpgradeError::DuplicateStateChange {
7825                    from: from.to_string(),
7826                    script: script.to_path_buf(),
7827                },
7828            );
7829            assert_eq!(
7830                UpgradeError::state_change_without_on_state_change_callback(from, script),
7831                UpgradeError::StateChangeWithoutOnStateChangeCallback {
7832                    from: from.to_string(),
7833                    script: script.to_path_buf(),
7834                },
7835            );
7836        }
7837    }
7838}