Skip to main content

delvewright_dsl/
stages.rs

1//! serde types for the six stage `content` payloads (spec-0001 v0.2).
2//!
3//! Every struct is `deny_unknown_fields`. Reserved enum values (objective and
4//! effect types a campaign's `dsl_version` is too low for) parse successfully
5//! and are checked by validation ([`crate::validate`]).
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12use crate::layout::StationKind;
13
14use crate::ids::{
15    ActorId, AmbushId, AnchorId, AreaId, BranchId, BranchPointId, ClassId, DialogueId, EditBatchId,
16    EndingId, FlagId, LethalVolumeId, LootId, NpcId, ObjectiveId, PoolId, PrefabId, QuestId,
17    RegionId, ShopId, ShortcutId, StakeId, StateId, TimedGateId, TrapId, TriggerId, WaveId,
18};
19
20/// serde default helper: `true` (used by DSL v0.4 `trigger.once`).
21fn default_true() -> bool {
22    true
23}
24
25/// serde `skip_serializing_if` helper: skip a `false` bool (DSL v0.4
26/// `objective.stealth`), keeping older campaigns byte-identical.
27fn is_false(b: &bool) -> bool {
28    !*b
29}
30
31// ---------------------------------------------------------------------------
32// Stage 1 — world
33// ---------------------------------------------------------------------------
34
35/// Stage 1 payload: setting, seed and the areas that make up the delve.
36#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
37#[serde(deny_unknown_fields)]
38pub struct WorldContent {
39    /// Player-facing delve title.
40    pub title: String,
41    /// One-line thematic description.
42    pub theme: String,
43    /// Short narrative premise.
44    pub premise: String,
45    /// The single downstream randomness source (ADR-0006).
46    pub seed: u64,
47    /// Informational pacing target in minutes (v0: not enforced).
48    pub target_minutes: u32,
49    /// The areas the delve is made of; each binds exactly one of `prefab` /
50    /// `prefab_pool`.
51    ///
52    /// **A campaign declares its placement in exactly one document, so this
53    /// list is empty on a site-plan campaign** (`DW0839`): where a
54    /// `site-plan.json` is present the plan is the placement authority, its one
55    /// place is `area/site`, and declaring `areas[]` as well gives every
56    /// question about where something is two answers. Empty is therefore a
57    /// legitimate and common value, not a campaign that forgot to place
58    /// anything.
59    pub areas: Vec<Area>,
60    /// Additional author-declared translation languages (BCP-47-style codes, e.g.
61    /// `["zh-cn"]`). English (`en`) is implicit, always canonical, and is **never**
62    /// listed here (spec-0001 i18n addendum). Absent or empty = English-only. Every
63    /// declared language must ship a fully-covering `l10n/<code>.json` sidecar
64    /// (`DW0180`/`DW0181`). Stage docs themselves stay pure English.
65    #[serde(default, skip_serializing_if = "Vec::is_empty")]
66    pub languages: Vec<String>,
67    /// **The hour this delve is played at** (DSL v0.5, spec-0010; required since
68    /// spec-0061). Dimension-global; frozen by environment sealing
69    /// (`advance_time false`) so the set state persists. Affects sky attenuation
70    /// in the compiler's assembled-light model.
71    ///
72    /// **Required, and it has no default.** "This delve is played at noon" is a
73    /// design decision, and a mechanism that supplies one silently when the
74    /// author said nothing is exactly what `CLAUDE.md` forbids a primitive from
75    /// encoding — the same ruling spec-0060 §4.1 made for `walk_y`. It is also
76    /// the world half of the comparison `DW0890` makes against the approved
77    /// design's rows, so every campaign has to state it for the comparison to
78    /// have two sides. Emission is unchanged: `time set <kw>` was always
79    /// emitted, so a campaign that already declared this builds
80    /// byte-identically.
81    pub time: WorldTime,
82    /// **The weather this delve is played in** (DSL v0.5, spec-0010; required
83    /// since spec-0061). Dimension-global; frozen by environment sealing
84    /// (`advance_weather false`). Rain and thunder attenuate effective sky
85    /// brightness in the assembled-light model.
86    ///
87    /// Required, with no default, for the reason [`WorldContent::time`] gives.
88    /// Emission is unchanged: `weather <kw>` is emitted only for a declared
89    /// non-`clear` weather, because `clear` is vanilla's own state.
90    pub weather: WorldWeather,
91    /// Declared combat difficulty (DSL v0.6). Absent =
92    /// the compiler's historical derivation — `easy` when the campaign fields any
93    /// wave, `peaceful` when it fields none — which is what keeps every campaign
94    /// written before this field byte-identical. Declaring it overrides the
95    /// derivation for **both** the shipped `server.properties` and a `/difficulty`
96    /// in the sealing baseline, so the declaration also holds when the datapack is
97    /// dropped into somebody else's world.
98    ///
99    /// `peaceful` is rejected (`DW0468`). Raising difficulty changes the damage
100    /// players take — easy halves it — so combat arithmetic tuned under the old
101    /// implicit `easy` must be redone.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub difficulty: Option<WorldDifficulty>,
104    /// The scenic horizon: the ground and the sky the map stands in
105    /// (spec-0026). Absent or `void` is the void world. `ocean` swaps the world
106    /// generator for a deterministic superflat sea (bedrock/stone/water, sea
107    /// level y=62) and drops the area datum to y=60 so island pieces meet the
108    /// sea at their authored waterline. `valley` rings the map in a generated
109    /// mountain annulus — the one base that builds terrain rather than picking
110    /// a generator. Either a string shorthand or the object form
111    /// `{base, …params}`; see [`Horizon`].
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub horizon: Option<Horizon>,
114    /// Playable-region boundary (DSL v0.6, spec-0013). When present, the compiler
115    /// derives a region from the placed geometry and a per-second clock returns any
116    /// player who leaves it to the last checkpoint. Required when `horizon` is
117    /// `ocean` (an infinite swimmable sea with no return rule is `DW0320`).
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub boundary: Option<Boundary>,
120    /// The closing line on the campaign-completion advancement — the last
121    /// player-visible sentence of the delve (DSL v0.6). Player-visible, so it is
122    /// l10n-inventoried as `world.outro` and sidecars translate it. Absent = the
123    /// finale quest's `goal`, which is already both campaign-derived and
124    /// inventoried; the description was previously the hardcoded English
125    /// "You left the keep." on *every* delve, whatever its theme or language.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub outro: Option<String>,
128    /// The party size this delve **requires** (DSL v0.6, spec-0018). Absent = 1: a
129    /// party of one is always legal and every pre-0.6 campaign keeps that reading.
130    /// A design whose beats genuinely need `n` players — two rooms whose switches
131    /// are two arms of one AND-join — declares `min_players: n` (max 4), and the
132    /// lobby then refuses to start below it: the class-selection dialog stays shut
133    /// and the waiting players get a party-count actionbar instead.
134    ///
135    /// Progression is party state either way (spec-0018), so this is a *declaration
136    /// of intent*, not a mechanism: it makes a mandatory-n design first-class
137    /// and turns on the analyzer's n-agent division
138    /// proof. Out of `1..=4` is `DW0370`.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub min_players: Option<u8>,
141}
142
143/// Who a granted item goes to (DSL v0.6, spec-0018).
144///
145/// Progression is a fact about the party, so the default for every `give-item` and
146/// every class-kit entry is **all**: a quest beat that arms the party arms all of
147/// it. `one` is the deliberate exception for a single quest prop (the wine-skin,
148/// the stake): exactly one copy enters the party, handed to the player whose action
149/// earned it, and the party passes it around physically.
150#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
151#[serde(rename_all = "kebab-case")]
152pub enum Carrier {
153    /// Every party member receives the item (the default).
154    #[default]
155    All,
156    /// Exactly one copy, to the player whose action fired the effect.
157    One,
158}
159
160/// A declared world time state (DSL v0.5, spec-0010). The sole difference from
161/// vanilla is that the daylight cycle is frozen (`advance_time false`), so a set
162/// state persists for the whole delve until a `set-time` effect cuts to another.
163///
164/// Vanilla's `/time set` primitive takes **either** one of four keywords or a raw
165/// tick count, and the tick form is the general one — so the states worth naming
166/// for a delve's pacing are not limited to the four keywords. `dusk` and `dawn`
167/// are the tick form exposed first-class, per the
168/// no-hack rule: the DSL names the beat, the compiler emits `/time set <ticks>`.
169/// Every keyword-to-tick mapping lives in exactly one table ([`WorldTime::spec`]),
170/// and the four vanilla keywords still emit their keyword verbatim, so existing
171/// campaigns are byte-identical.
172///
173/// **There is no `Default`** (spec-0061 §4). A default hour is a design decision
174/// wearing a mechanism's clothes, and `#[default] Noon` is what let a delve whose
175/// whole approved look was night build, light-check and render under a blue noon
176/// sky. Removing the impl is what makes that unwritable rather than merely
177/// discouraged: `WorldContent::time` is required, and nothing can supply an hour
178/// the author did not.
179#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
180#[serde(rename_all = "kebab-case")]
181pub enum WorldTime {
182    /// Morning daylight (`/time set day`, 1000 ticks).
183    Day,
184    /// Midday, brightest (`/time set noon`, 6000 ticks).
185    Noon,
186    /// Sunset — the sky visibly going orange and the day ending
187    /// (`/time set 12000`). Deliberately NOT 13000: that is the instant the sun
188    /// has finished setting, which is what the `night` keyword already sets, so
189    /// 13000 would make `dusk` a synonym rather than its own beat.
190    Dusk,
191    /// Night, sun fully down (`/time set night`, 13000 ticks).
192    Night,
193    /// Deep night, darkest (`/time set midnight`, 18000 ticks).
194    Midnight,
195    /// First light, just before sunrise (`/time set 23000`). Spelled `dawn`;
196    /// `sunrise` is accepted as a synonym on input.
197    #[serde(alias = "sunrise")]
198    Dawn,
199}
200
201impl WorldTime {
202    /// The single keyword/tick table: `(the /time set argument, daytime ticks)`.
203    ///
204    /// A state vanilla names keeps its keyword — the argument the compiler has
205    /// always emitted — so no shipped campaign's bytes move. A state vanilla does
206    /// not name emits the equivalent tick count, which is the same primitive.
207    const fn spec(self) -> (&'static str, i64) {
208        match self {
209            WorldTime::Day => ("day", 1000),
210            WorldTime::Noon => ("noon", 6000),
211            WorldTime::Dusk => ("12000", 12000),
212            WorldTime::Night => ("night", 13000),
213            WorldTime::Midnight => ("midnight", 18000),
214            WorldTime::Dawn => ("23000", 23000),
215        }
216    }
217
218    /// The vanilla `/time set` argument — a keyword for the four states vanilla
219    /// names, a tick count otherwise.
220    pub fn token(self) -> &'static str {
221        self.spec().0
222    }
223
224    /// The `daytime` tick value this state sets (the `time query daytime`
225    /// read-back). Vanilla constants: day=1000, noon=6000, dusk=12000 (sunset
226    /// onset), night=13000, midnight=18000, dawn=23000.
227    pub fn daytime_ticks(self) -> i64 {
228        self.spec().1
229    }
230
231    /// **The word an author writes** — this state's spelling in a document.
232    ///
233    /// Not [`WorldTime::token`], which is the `/time set` argument and is a raw
234    /// tick count for the two states vanilla does not name. A diagnostic that
235    /// asks an author to declare an hour has to say `dusk`, not `12000`: the
236    /// number is what the compiler emits and is not writable in `world.json`.
237    pub fn keyword(self) -> &'static str {
238        match self {
239            WorldTime::Day => "day",
240            WorldTime::Noon => "noon",
241            WorldTime::Dusk => "dusk",
242            WorldTime::Night => "night",
243            WorldTime::Midnight => "midnight",
244            WorldTime::Dawn => "dawn",
245        }
246    }
247}
248
249/// A declared weather state (DSL v0.5, spec-0010). Values are the vanilla
250/// `/weather` keywords; frozen (`advance_weather false`), so a set state persists.
251///
252/// **No `Default`**, for the reason [`WorldTime`] gives.
253#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
254#[serde(rename_all = "kebab-case")]
255pub enum WorldWeather {
256    /// Clear sky (`/weather clear`). Vanilla's own state, so emission writes no
257    /// `/weather` command for it.
258    Clear,
259    /// Rain (`/weather rain`).
260    Rain,
261    /// Thunderstorm (`/weather thunder`).
262    Thunder,
263}
264
265impl WorldWeather {
266    /// The word an author writes — identical to [`WorldWeather::token`] for
267    /// every state, and stated separately so a message that names a document's
268    /// vocabulary reads the document's vocabulary. See [`WorldTime::keyword`],
269    /// where the two differ.
270    pub fn keyword(self) -> &'static str {
271        self.token()
272    }
273
274    /// The vanilla `/weather` keyword.
275    pub fn token(self) -> &'static str {
276        match self {
277            WorldWeather::Clear => "clear",
278            WorldWeather::Rain => "rain",
279            WorldWeather::Thunder => "thunder",
280        }
281    }
282}
283
284/// The declared combat difficulty of the delve (DSL v0.6). Values are the
285/// vanilla `/difficulty` keywords.
286///
287/// Difficulty is the single largest lever on how hard a delve *feels*, so the
288/// campaign declares it rather than letting the compiler choose. Easy **halves
289/// incoming player damage** — `min(dmg / 2 + 1, dmg)` — so a campaign tuned
290/// under `easy` is tuned against a halved world. A campaign that
291/// raises this must redo that arithmetic.
292///
293/// [`WorldDifficulty::Peaceful`] parses but is **rejected** by validation
294/// (`DW0468`): peaceful makes the engine discard every hostile-category mob on
295/// the tick it is ticked, summoned or not, so every wave, actor and ambush in the
296/// campaign would silently vanish. It is a variant only so the compiler can say
297/// that in a diagnostic instead of a serde "unknown variant" parse error.
298#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
299#[serde(rename_all = "kebab-case")]
300pub enum WorldDifficulty {
301    /// `/difficulty easy` — the compiler's historical choice for a wave
302    /// campaign, and the default reading of an absent field. Incoming player
303    /// damage is halved (`min(dmg / 2 + 1, dmg)`).
304    #[default]
305    Easy,
306    /// `/difficulty normal` — vanilla-baseline damage. The souls-style baseline.
307    Normal,
308    /// `/difficulty hard` — amplified damage, and zombies reinforce.
309    Hard,
310    /// `/difficulty peaceful` — **always rejected** (`DW0468`). Present only so
311    /// the rejection can be a diagnostic with a rationale.
312    Peaceful,
313}
314
315impl WorldDifficulty {
316    /// The vanilla `/difficulty` keyword.
317    pub fn token(self) -> &'static str {
318        match self {
319            WorldDifficulty::Peaceful => "peaceful",
320            WorldDifficulty::Easy => "easy",
321            WorldDifficulty::Normal => "normal",
322            WorldDifficulty::Hard => "hard",
323        }
324    }
325
326    /// The vanilla `Difficulty#getId()` ordinal, which is also what the bare
327    /// `/difficulty` query command returns — the only vanilla read-back path for
328    /// the setting, and so what the generated PackTest asserts on.
329    pub fn id(self) -> i32 {
330        match self {
331            WorldDifficulty::Peaceful => 0,
332            WorldDifficulty::Easy => 1,
333            WorldDifficulty::Normal => 2,
334            WorldDifficulty::Hard => 3,
335        }
336    }
337}
338
339/// A scenic horizon (spec-0026). A horizon is a **composition of orthogonal
340/// axes**, not an enum of monoliths: a **base** — what surrounds the map — and
341/// that base's params. The field accepts a plain string shorthand
342/// ([`HorizonName`]) or the object form [`HorizonSpec`] `{base, …params}`.
343///
344/// Consumers never match this wire enum. [`Horizon::resolved`] desugars both
345/// forms into one [`ResolvedHorizon`] with the pinned defaults applied, and
346/// [`horizon_base`] answers the one question most callers have.
347#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
348#[serde(untagged)]
349pub enum Horizon {
350    /// A bare base name — `"ocean"` is exactly `{base: "ocean"}`. The two
351    /// bases that predate the horizon library were spelled this way and still
352    /// are, byte-identically; a base added since is spellable this way too,
353    /// because a base with every param at its default has nothing else to say.
354    Name(HorizonBase),
355    /// The object form `{base, …params}`.
356    Spec(HorizonSpec),
357}
358
359/// What surrounds the map.
360///
361/// **One enumeration of bases, reachable two ways.** The shorthand
362/// `horizon: "ocean"` and the object form `horizon: {base: "ocean"}` name this
363/// same variant, which is what stops a base from existing in one spelling and
364/// not the other. A separate list of "names" beside this one would be two
365/// enumerations of the same thing, and the second base added would land in
366/// whichever of them its author was looking at.
367///
368/// What is deliberately NOT here is a name that stands for a base plus a set of
369/// params. Such a name reads as a thing, and the whole claim of this design is
370/// that it is not one — it is a base with params set. A spelling that hides
371/// which params it sets makes that claim unverifiable by looking at the
372/// document, and buys a few saved keystrokes for it. Each base carries its own params on
373/// [`HorizonSpec`], and a param foreign to the declared base is refused rather
374/// than ignored.
375#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
376#[serde(rename_all = "kebab-case")]
377pub enum HorizonBase {
378    /// Void superflat; no surround. The default.
379    #[default]
380    Void,
381    /// Pinned water superflat, sea level 62; no surround.
382    Ocean,
383    /// A mountain annulus around a flat gap floor, with void ambient below the
384    /// tile skirt. The one base that generates terrain.
385    Valley,
386}
387
388impl HorizonBase {
389    /// The kebab wire name.
390    pub fn token(self) -> &'static str {
391        match self {
392            HorizonBase::Void => "void",
393            HorizonBase::Ocean => "ocean",
394            HorizonBase::Valley => "valley",
395        }
396    }
397
398    /// Whether this base generates a surround — compiler-built terrain outside
399    /// the map's own extent. `void` and `ocean` are pure ambient and build
400    /// nothing.
401    pub fn has_surround(self) -> bool {
402        matches!(self, HorizonBase::Valley)
403    }
404}
405
406/// The `horizon` object form: a `base` plus that base's params, all optional
407/// with pinned defaults ([`horizon_defaults`]).
408///
409/// The `valley` surround generator carries a second flora and a second surface
410/// palette (a cherry grove over `minecraft:cherry_grove`) and **this struct
411/// deliberately does not expose them yet.** Every engine surface owes a gallery
412/// element in the change that lands it, and the element a second flora needs is
413/// a second whole-map campaign — the surround only rings a map that DECLARES
414/// its extent (`DW0855`), so there is no two-file overlay that can write it.
415/// A surface whose element cannot land with it does not land. The shape is flat rather than
416/// per-base tagged, and a param foreign to the declared base is refused
417/// (`DW0853`) — so an `ocean` cannot quietly carry a `rim_height` that nothing
418/// reads.
419#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
420#[serde(deny_unknown_fields)]
421pub struct HorizonSpec {
422    /// The base — what surrounds the map.
423    pub base: HorizonBase,
424    /// `valley`: the surround's total footprint as a multiple of the map's, on
425    /// each axis (`2.0..=3.0`, default 2.5).
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub ratio: Option<f64>,
428    /// `valley`: crest height of the rim over the gap floor (`16..=128`,
429    /// default 48).
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub rim_height: Option<i32>,
432}
433
434/// Pinned horizon param defaults. One table, so the doc comments, the resolver
435/// and the diagnostics cannot drift.
436pub mod horizon_defaults {
437    /// `valley.ratio`.
438    pub const RATIO: f64 = 2.5;
439    /// `valley.ratio` lower bound — below 2.0 the annulus has no room for a
440    /// gap floor and a slope run both.
441    pub const RATIO_MIN: f64 = 2.0;
442    /// `valley.ratio` upper bound — above 3.0 the surround is mostly terrain a
443    /// body never reaches, at a cost that is all shipped bytes.
444    pub const RATIO_MAX: f64 = 3.0;
445    /// `valley.rim_height`.
446    pub const RIM_HEIGHT: i32 = 48;
447    /// `valley.rim_height` lower bound — a rim under 16 does not close the
448    /// horizon from a body standing on the gap floor.
449    pub const RIM_HEIGHT_MIN: i32 = 16;
450    /// `valley.rim_height` upper bound — the build range is 384 blocks tall and
451    /// the surround has to fit under whatever the map puts above it.
452    pub const RIM_HEIGHT_MAX: i32 = 128;
453}
454
455/// A horizon with both wire forms desugared and every default applied — the
456/// only view downstream code reads.
457#[derive(Clone, Copy, Debug, PartialEq)]
458pub struct ResolvedHorizon {
459    /// The base.
460    pub base: HorizonBase,
461    /// `valley.ratio`.
462    pub ratio: f64,
463    /// `valley.rim_height`.
464    pub rim_height: i32,
465}
466
467impl Default for ResolvedHorizon {
468    fn default() -> Self {
469        ResolvedHorizon {
470            base: HorizonBase::Void,
471            ratio: horizon_defaults::RATIO,
472            rim_height: horizon_defaults::RIM_HEIGHT,
473        }
474    }
475}
476
477impl ResolvedHorizon {
478    /// The resolved horizon of `base` with every param at its pinned default.
479    pub fn of_base(base: HorizonBase) -> Self {
480        ResolvedHorizon {
481            base,
482            ..Default::default()
483        }
484    }
485}
486
487impl Horizon {
488    /// Desugar either wire form to the one resolved view, defaults applied.
489    pub fn resolved(&self) -> ResolvedHorizon {
490        match self {
491            Horizon::Name(base) => ResolvedHorizon::of_base(*base),
492            Horizon::Spec(s) => ResolvedHorizon {
493                base: s.base,
494                ratio: s.ratio.unwrap_or(horizon_defaults::RATIO),
495                rim_height: s.rim_height.unwrap_or(horizon_defaults::RIM_HEIGHT),
496            },
497        }
498    }
499
500    /// The resolved base.
501    pub fn base(&self) -> HorizonBase {
502        self.resolved().base
503    }
504
505    /// True when this declaration needs the horizon-library surface: the object
506    /// form, or a bare name for a base that did not exist before it.
507    ///
508    /// The two bases that predate the library stay writable as bare names at
509    /// the version that introduced them, and their emission does not move —
510    /// which is what makes this a widening rather than a break. What is fenced
511    /// is saying something the old surface had no spelling for.
512    pub fn needs_horizon_library(&self) -> bool {
513        match self {
514            Horizon::Spec(_) => true,
515            Horizon::Name(base) => match base {
516                HorizonBase::Void | HorizonBase::Ocean => false,
517                HorizonBase::Valley => true,
518            },
519        }
520    }
521}
522
523/// The resolved base of an optional stage-1 `horizon` field — `Void` when
524/// absent. The one helper every downstream consumer (placement, the ambient
525/// model, emission) goes through, so that a new base cannot be forgotten at one
526/// of them.
527pub fn horizon_base(horizon: &Option<Horizon>) -> HorizonBase {
528    horizon.as_ref().map(|h| h.base()).unwrap_or_default()
529}
530
531/// The resolved view of an optional stage-1 `horizon` field, with defaults
532/// applied for an absent one.
533pub fn resolved_horizon(horizon: &Option<Horizon>) -> ResolvedHorizon {
534    horizon.as_ref().map(|h| h.resolved()).unwrap_or_default()
535}
536
537/// The default boundary `margin` (blocks of horizontal breathing room added
538/// around the derived region). Separate function so `serde(default = …)` and the
539/// documented literal cannot drift.
540fn default_margin() -> u16 {
541    16
542}
543
544/// A playable-region boundary declaration (DSL v0.6, spec-0013). The region
545/// itself is **derived** by the compiler (union of the final placed-piece AABBs,
546/// inflated horizontally by `margin`, unbounded upward, floored at the lowest
547/// placed block − 8) — never authored — so "every anchor is inside" is structural.
548/// Enforcement is a per-second clock that returns any player outside the region to
549/// the last checkpoint (`dw:cp`) with an actionbar message and a soft sound; no
550/// damage, no items lost.
551#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
552#[serde(deny_unknown_fields)]
553pub struct Boundary {
554    /// Horizontal breathing room in blocks added around the derived region on
555    /// every side (default 16). Range-checked to `0..=64` (`DW0321`).
556    #[serde(default = "default_margin")]
557    pub margin: u16,
558    /// Actionbar message shown on return. Absent = the compiler's English default.
559    /// When set, it is inventoried under l10n key `world.boundary.message` and is
560    /// translated like every other player-facing string.
561    #[serde(default, skip_serializing_if = "Option::is_none")]
562    pub message: Option<String>,
563}
564
565/// A supplemental-lighting fixture the relight pass may place (DSL v0.5,
566/// spec-0010 fixture registry v1). The theme choice stays in the DSL layer; the
567/// compiler owns the placement rule and block-light emission.
568#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
569#[serde(rename_all = "kebab-case")]
570pub enum Fixture {
571    /// Floor torch (block light 14); `wall_torch` on a wall face as fallback.
572    Torch,
573    /// Ceiling-hung lantern (block light 15); floor-sitting as fallback.
574    Lantern,
575    /// Floor campfire (block light 15); never on or adjacent to a required path
576    /// cell (it is a damage source).
577    Campfire,
578    /// Embedded shroomlight (block light 15); replaces a solid wall/ceiling block.
579    Shroomlight,
580}
581
582impl Fixture {
583    /// The kebab id (`torch` / `lantern` / `campfire` / `shroomlight`).
584    pub fn token(self) -> &'static str {
585        match self {
586            Fixture::Torch => "torch",
587            Fixture::Lantern => "lantern",
588            Fixture::Campfire => "campfire",
589            Fixture::Shroomlight => "shroomlight",
590        }
591    }
592}
593
594/// A per-area supplemental-lighting declaration (DSL v0.5, spec-0010). Its
595/// presence puts the area on the relight path: the compiler guarantees every
596/// reachable walkable cell reaches `min_light` by placing `fixture`s, or fails
597/// with `DW0211` if it cannot.
598#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
599#[serde(deny_unknown_fields)]
600pub struct AreaLighting {
601    /// The fixture the relight pass places.
602    pub fixture: Fixture,
603    /// The minimum block+sky light guaranteed on reachable walkable cells
604    /// (1..=14, default 7). Range-checked (`DW0196`).
605    #[serde(default = "default_min_light")]
606    pub min_light: u8,
607}
608
609/// Default `min_light` for an [`AreaLighting`] declaration (spec-0010).
610fn default_min_light() -> u8 {
611    7
612}
613
614/// A per-area **darkness mitigation** declaration (DSL v0.6).
615///
616/// The first-class answer to "this area is meant to be dark, and the players are
617/// equipped for it". Declaring it is what makes the compiler *emit* the mitigation
618/// (a clocked `effect give … night_vision` scoped to the area's placed bounds) and
619/// what satisfies the `DW0210` darkness gate — one declaration, one mechanism, no
620/// gap between the check and the feature.
621///
622/// It replaces the pre-0.6 heuristic that read a class kit item's display *name*
623/// for `night vision`: that accepted a renamed water bottle, so the gate passed
624/// while nothing in the world granted night vision (owner, island QA).
625#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
626#[serde(rename_all = "kebab-case")]
627pub enum AreaMitigation {
628    /// Every player inside the area's placed bounds is kept under
629    /// `minecraft:night_vision` by a compiler-emitted 1 s clock.
630    NightVision,
631}
632
633/// One area of the world, bound to a single prefab or a jigsaw prefab pool.
634///
635/// An area binds **exactly one of** `prefab` (single piece) or `prefab_pool`
636/// (+ `pieces`, jigsaw multi-piece assembly, ADR-0004). The exclusivity and
637/// pool-existence rules are enforced by validation (`DW0160` / `DW0161`); the
638/// full jigsaw layout semantics are spec-0002's.
639#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
640#[serde(deny_unknown_fields)]
641pub struct Area {
642    /// Unique area id.
643    pub id: AreaId,
644    /// Player-facing area name.
645    pub name: String,
646    /// The single prefab bound to this area (mutually exclusive with
647    /// `prefab_pool`).
648    #[serde(default, skip_serializing_if = "Option::is_none")]
649    pub prefab: Option<PrefabId>,
650    /// The jigsaw prefab pool bound to this area (mutually exclusive with
651    /// `prefab`); requires `pieces`.
652    #[serde(default, skip_serializing_if = "Option::is_none")]
653    pub prefab_pool: Option<PoolId>,
654    /// Jigsaw piece-count bounds (only with `prefab_pool`).
655    #[serde(default, skip_serializing_if = "Option::is_none")]
656    pub pieces: Option<Pieces>,
657    /// Optional supplemental-lighting declaration (DSL v0.5, spec-0010). When
658    /// present, the compiler's relight pass guarantees `min_light` on every
659    /// reachable walkable cell of this area by placing the declared fixture, or
660    /// fails with `DW0211`. Absent = no relight (the area is judged as-assembled,
661    /// with `DW0210` if a reachable walkable cell is dark and unmitigated).
662    #[serde(default, skip_serializing_if = "Option::is_none")]
663    pub lighting: Option<AreaLighting>,
664    /// Optional darkness-mitigation declaration (DSL v0.6). `night-vision` makes
665    /// the compiler emit a clocked `effect give` over this area's placed bounds and
666    /// is the (only) declaration that satisfies `DW0210` without `lighting`.
667    /// Independent of `lighting`: an area may declare both (fixtures *and* the
668    /// effect), either, or neither.
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub mitigation: Option<AreaMitigation>,
671}
672
673/// Inclusive piece-count bounds for a jigsaw `prefab_pool` area.
674#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
675#[serde(deny_unknown_fields)]
676pub struct Pieces {
677    /// Minimum number of pieces to assemble.
678    pub min: u32,
679    /// Maximum number of pieces to assemble.
680    pub max: u32,
681}
682
683// ---------------------------------------------------------------------------
684// Body traversal — the declaration every body that moves carries (DSL v0.11,
685// spec-0034)
686// ---------------------------------------------------------------------------
687
688/// How a body gets around.
689///
690/// The compiler DERIVES this from the entity id for every body (spiders climb,
691/// ghasts fly, `#minecraft:aquatic` swims, and everything else — including every
692/// id the table has never heard of — is [`Locomotion::Ground`], the checked
693/// class). [`BodyTraversal`] is the author's side of the same vocabulary: one
694/// enum, so a declaration and a derivation can never mean different things.
695///
696/// The vocabulary lives in this crate rather than in the compiler because it is
697/// now DSL surface; the compiler re-exports it and owns the derivation table
698/// (`compiler::traversal`).
699#[derive(
700    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
701)]
702#[serde(rename_all = "kebab-case")]
703pub enum Locomotion {
704    /// Walks, steps and jumps — the default and the CHECKED class.
705    Ground,
706    /// Climbs sheer vertical surfaces (vanilla's `Spider` class).
707    Climber,
708    /// Leaves the ground under its own power.
709    Flier,
710    /// A member of vanilla's `#minecraft:aquatic` tag. A ledger classification
711    /// that exempts nothing, which is why it may not be **declared**
712    /// (`DW0455`) — see [`BodyTraversal`].
713    Aquatic,
714}
715
716impl Locomotion {
717    /// The stable kebab token this class is written and reported under.
718    pub fn token(self) -> &'static str {
719        match self {
720            Locomotion::Ground => "ground",
721            Locomotion::Climber => "climber",
722            Locomotion::Flier => "flier",
723            Locomotion::Aquatic => "aquatic",
724        }
725    }
726
727    /// Every class, in ledger order — so a report can never silently drop a row
728    /// when a class is added.
729    pub const ALL: [Locomotion; 4] = [
730        Locomotion::Ground,
731        Locomotion::Climber,
732        Locomotion::Flier,
733        Locomotion::Aquatic,
734    ];
735}
736
737/// What a body can do when it moves, **declared by the author** (DSL v0.11,
738/// spec-0034).
739///
740/// Carried by every object class in the DSL that has a body and a position and
741/// is walked by a compiler-emitted route — the stage-2 [`Npc`] and the stage-5
742/// [`Actor`]. It is deliberately one shared type on both rather than a field
743/// per consumer: traversal is a property of a body that moves, not of the verb
744/// that first needed it (CLAUDE.md), and a second bespoke field would be the
745/// defect rather than the fix.
746///
747/// **A declaration is a claim the build holds you to, never an opt-out.** The
748/// compiler compares the verdicts this body earns under the declared class
749/// against the ones it earns under its species' derived class; a declaration
750/// that changes no verdict is inert and is `DW0454`. So declaring `climber` on
751/// a sheep is only accepted where that sheep's route really does go over a
752/// barrier line — the exception is authored and proven, instead of happening by
753/// accident and merely rendering.
754///
755/// **What is deliberately NOT here: `opens_gates`.** Passing a closed fence gate
756/// is a right-click, a scripted walk is a compiler-emitted `tp` polyline whose
757/// puppet performs no interaction at all, and no runtime verb changes a fence
758/// gate's block state. Declaring it would not make it true, so the error tier
759/// (`DW0452`) has no authorable exemption and a declaration can never reach it.
760#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
761#[serde(deny_unknown_fields)]
762pub struct BodyTraversal {
763    /// How this body gets around, overriding what its entity id implies.
764    pub locomotion: Locomotion,
765}
766
767/// One object class that has a **body the compiler stages**: a declared
768/// position, a declared species, and a compiler-emitted route.
769///
770/// A sum type rather than a flattened tuple, so **adding a body class is a
771/// compile error at every consumer** until each one says what it does with it.
772/// The alternative — each rule walking the classes it happens to remember — is
773/// the defect class CLAUDE.md names: a hand-rolled walk that
774/// enumerated three of five effect roots.
775///
776/// **Keyed to the object, not to the verb that first needed it.** This type was
777/// introduced for [`BodyTraversal`] and read, for a while, as "one consumer of
778/// `BodyTraversal`" — which is why its only enumeration
779/// ([`body_traversal_sites`]) was filtered to bodies declaring a traversal, and
780/// why the second property a body carries, its [`NpcSkin`], had no enumeration
781/// at all: the bake walked the stage-2 npc list by hand, and an actor's skin was
782/// emitted into the summon, never baked into the pack, and never refused.
783/// A body's properties belong to the body. [`body_sites`] is the unfiltered
784/// walk; a per-property enumeration is a *filter* over it, never a second walk.
785///
786/// Deliberately NOT a member: [`WaveMob`]. A wave mob has a body and a position,
787/// but it is driven by **native vanilla AI**, never by a compiler-emitted route,
788/// so the compiler makes no claim about the moves it makes and a locomotion
789/// declaration on it could change no verdict. It declares no `skin` either — the
790/// exclusion holds for both properties, and the schema says so
791/// (`crates/dsl/tests/body_skin_sites.rs`). It becomes a member the day the lane
792/// proof reasons about how its bodies move — and it joins here, through this
793/// same type, rather than through a field of its own.
794#[derive(Clone, Copy, Debug)]
795pub enum BodyRef<'a> {
796    /// A stage-2 NPC, walked by `move-npc`.
797    Npc(&'a Npc),
798    /// A stage-5 scripted actor, walked by `move-actor`.
799    Actor(&'a Actor),
800}
801
802impl<'a> BodyRef<'a> {
803    /// The declaring stage's wire name (`npcs` / `quests`) — also the stage
804    /// whose `dsl_version` fences this body's declaration.
805    pub fn stage(self) -> &'static str {
806        match self {
807            BodyRef::Npc(_) => "npcs",
808            BodyRef::Actor(_) => "quests",
809        }
810    }
811
812    /// The body's declared id.
813    pub fn id(self) -> &'a str {
814        match self {
815            BodyRef::Npc(n) => n.id.as_str(),
816            BodyRef::Actor(a) => a.id.as_str(),
817        }
818    }
819
820    /// The entity id written on the body. **Not necessarily the body that
821    /// ships**: a `skin` re-dresses it as a `minecraft:mannequin`, which is the
822    /// compiler's rule (`nav::npc_body_entity`) and stays there.
823    pub fn declared_entity(self) -> &'a str {
824        match self {
825            BodyRef::Npc(n) => n.base_entity.as_str(),
826            BodyRef::Actor(a) => a.entity.as_str(),
827        }
828    }
829
830    /// This body's traversal declaration, if it carries one.
831    pub fn traversal(self) -> Option<&'a BodyTraversal> {
832        match self {
833            BodyRef::Npc(n) => n.traversal.as_ref(),
834            BodyRef::Actor(a) => a.traversal.as_ref(),
835        }
836    }
837
838    /// This body's skin declaration, if it carries one.
839    ///
840    /// A skinned body of **either** class ships as a `minecraft:mannequin`
841    /// whose `profile.texture` resolves to `delvewright:npc/<texture_id>`, so
842    /// either one owes the same `skins/<texture_id>.png` under the same refusal
843    /// (`DW0309`). Answering it here is what stops the bake from being a
844    /// property of one class.
845    pub fn skin(self) -> Option<&'a NpcSkin> {
846        match self {
847            BodyRef::Npc(n) => n.skin.as_ref(),
848            BodyRef::Actor(a) => a.skin.as_ref(),
849        }
850    }
851
852    /// This class's name in the JSON Schema export (`delvec schema --stage all`).
853    ///
854    /// The join between the closed Rust set and the schema, which is the only
855    /// authority on *which object classes declare what*. `body_skin_sites.rs`
856    /// compares the two.
857    pub fn class(self) -> &'static str {
858        match self {
859            BodyRef::Npc(_) => "Npc",
860            BodyRef::Actor(_) => "Actor",
861        }
862    }
863
864    /// Every body class, by schema name. The closed set, stated once.
865    pub const ALL_CLASSES: [&'static str; 2] = ["Npc", "Actor"];
866}
867
868/// A staged body declaration, with the JSON pointer at the declaration itself.
869///
870/// The pointer is at the OBJECT (`/content/npcs/3`), not at any one of its
871/// fields: a per-property site appends its own field name. A pointer built per
872/// property is how two walks of one population start disagreeing about where a
873/// thing was declared.
874#[derive(Clone, Debug)]
875pub struct BodySite<'a> {
876    /// Which object class declared it, and the object itself.
877    pub body: BodyRef<'a>,
878    /// JSON pointer at the declaration, for a diagnostic path.
879    pub path: String,
880}
881
882/// **Every** body the campaign declares, in stage order: stage-2 npcs in
883/// declaration order, then stage-5 actors in declaration order.
884///
885/// The one walk of the campaign's bodies. A rule about a property a body carries
886/// is a *filter* over this ([`body_traversal_sites`], [`body_skin_sites`]) — never
887/// a second traversal, and never a hand-written loop over one stage's list,
888/// which is exactly how an actor's skin came to be emitted but never baked.
889pub fn body_sites(c: &crate::envelope::Campaign) -> Vec<BodySite<'_>> {
890    let mut out: Vec<BodySite<'_>> = Vec::new();
891    for (i, n) in c.npcs.content.npcs.iter().enumerate() {
892        out.push(BodySite {
893            body: BodyRef::Npc(n),
894            path: format!("/content/npcs/{i}"),
895        });
896    }
897    for (i, a) in c.quests.content.actors.iter().enumerate() {
898        out.push(BodySite {
899            body: BodyRef::Actor(a),
900            path: format!("/content/actors/{i}"),
901        });
902    }
903    out
904}
905
906/// A body that carries a [`BodyTraversal`] declaration, with the JSON pointer at
907/// it.
908#[derive(Clone, Debug)]
909pub struct BodyTraversalSite<'a> {
910    /// Which object class declared it, and the object itself.
911    pub body: BodyRef<'a>,
912    /// JSON pointer at the `traversal` field, for a diagnostic path.
913    pub path: String,
914    /// The declaration.
915    pub traversal: &'a BodyTraversal,
916}
917
918/// Every body in the campaign that DECLARES a traversal, in stage order.
919///
920/// The one enumeration of the declaration's consumers, shared by the DSL's value
921/// check (`DW0455`) and by the compiler's proof (`DW0454`), so "which object
922/// classes carry this" is answered in exactly one place.
923pub fn body_traversal_sites(c: &crate::envelope::Campaign) -> Vec<BodyTraversalSite<'_>> {
924    body_sites(c)
925        .into_iter()
926        .filter_map(|s| {
927            s.body.traversal().map(|t| BodyTraversalSite {
928                body: s.body,
929                path: format!("{}/traversal", s.path),
930                traversal: t,
931            })
932        })
933        .collect()
934}
935
936/// A body that carries an [`NpcSkin`] declaration, with the JSON pointer at it.
937#[derive(Clone, Debug)]
938pub struct BodySkinSite<'a> {
939    /// Which object class declared it, and the object itself.
940    pub body: BodyRef<'a>,
941    /// JSON pointer at the `skin` field, for a diagnostic path.
942    pub path: String,
943    /// The declaration.
944    pub skin: &'a NpcSkin,
945}
946
947/// Every body in the campaign that DECLARES a skin, in stage order.
948///
949/// The one enumeration of what the resource-pack bake must serve and what
950/// `DW0309` must refuse, for every class alike — a skinned npc and a skinned
951/// actor are the same fact about two bodies.
952///
953/// **Declarations, not textures.** Two bodies may name one `texture_id` (an npc
954/// and the puppet that plays it), and the caller decides what that means; the
955/// bake reads each file once.
956pub fn body_skin_sites(c: &crate::envelope::Campaign) -> Vec<BodySkinSite<'_>> {
957    body_sites(c)
958        .into_iter()
959        .filter_map(|s| {
960            s.body.skin().map(|k| BodySkinSite {
961                body: s.body,
962                path: format!("{}/skin", s.path),
963                skin: k,
964            })
965        })
966        .collect()
967}
968
969// ---------------------------------------------------------------------------
970// Stage 2 — npcs
971// ---------------------------------------------------------------------------
972
973/// Stage 2 payload: the campaign's NPCs (casting sheets).
974#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
975#[serde(deny_unknown_fields)]
976pub struct NpcsContent {
977    /// All NPCs in the campaign.
978    pub npcs: Vec<Npc>,
979}
980
981/// A stationary NPC bound to an area anchor (a casting sheet, spec-0001 v0.2).
982///
983/// Stage 2 carries **no dialogue** — the structured [`Persona`] is the character
984/// contract the stage-6 `dialogue` tree must honor.
985#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
986#[serde(deny_unknown_fields)]
987pub struct Npc {
988    /// Unique NPC id.
989    pub id: NpcId,
990    /// Player-facing name.
991    pub name: String,
992    /// NPC role.
993    pub role: Role,
994    /// The area this NPC stands in (stage-1 ref).
995    pub area: AreaId,
996    /// The prefab anchor this NPC stands on.
997    pub anchor: AnchorId,
998    /// The vanilla entity to re-dress, e.g. `minecraft:villager`.
999    pub base_entity: String,
1000    /// The structured persona (character contract for stage 6).
1001    pub persona: Persona,
1002    /// Optional player-model skin (DSL v0.4, spec-0008 §6 / spec-0009). When set,
1003    /// the compiler emits a `minecraft:mannequin` body carrying this skin profile
1004    /// instead of re-dressing `base_entity`; the interaction hitbox is unchanged.
1005    /// Non-skinned NPCs are byte-identical to v0.3.
1006    #[serde(default, skip_serializing_if = "Option::is_none")]
1007    pub skin: Option<NpcSkin>,
1008    /// Deferred entrance (DSL v0.6): when `true` the NPC is **not** summoned at
1009    /// world init — its body and interaction hitbox only appear when a
1010    /// [`Verb::SpawnNpc`] fires, at this same `anchor`. The dual of
1011    /// `despawn-npc`: a character with a scripted entrance must not stand at its
1012    /// mark as a statue from minute one. A deferred NPC that no `spawn-npc` ever
1013    /// spawns is unreachable content (`DW0197`). Default `false` = summoned at
1014    /// init, byte-identical to pre-0.6.
1015    #[serde(default, skip_serializing_if = "is_false")]
1016    pub deferred: bool,
1017    /// What this body can do when it moves (DSL v0.11, spec-0034). Absent = the
1018    /// class the compiler derives from `base_entity` (or from `minecraft:mannequin`
1019    /// when `skin` is set — the body that actually ships). See [`BodyTraversal`]:
1020    /// the declaration must change a verdict or it is `DW0454`, and it can never
1021    /// reach the error tier.
1022    #[serde(default, skip_serializing_if = "Option::is_none")]
1023    pub traversal: Option<BodyTraversal>,
1024}
1025
1026/// A mannequin NPC's player-model skin (DSL v0.4). The skin PNG ships in the
1027/// per-delve resource pack at `assets/delvewright/textures/npc/<texture_id>.png`
1028/// (sourced from the campaign dir's `skins/<texture_id>.png`); the mannequin's
1029/// `profile.texture` resolves to `delvewright:npc/<texture_id>`.
1030#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1031#[serde(deny_unknown_fields)]
1032pub struct NpcSkin {
1033    /// Skin id: the PNG basename under `skins/` and the resource-pack texture
1034    /// path segment (a bare kebab token; validated by `DW0190`).
1035    pub texture_id: String,
1036    /// Player model. **Required** (spec-0009): an omitted model renders slim, so
1037    /// a wide skin on a slim model is distorted — the compiler always emits it.
1038    pub model: SkinModel,
1039}
1040
1041/// Player-model shape for a mannequin skin (`wide` = classic/Steve, `slim` =
1042/// Alex). Emitted verbatim into the mannequin `profile.model`.
1043#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1044#[serde(rename_all = "kebab-case")]
1045pub enum SkinModel {
1046    /// Classic 4-pixel arms (Steve).
1047    Wide,
1048    /// Slim 3-pixel arms (Alex).
1049    Slim,
1050}
1051
1052impl SkinModel {
1053    /// The vanilla `profile.model` token.
1054    pub fn token(self) -> &'static str {
1055        match self {
1056            SkinModel::Wide => "wide",
1057            SkinModel::Slim => "slim",
1058        }
1059    }
1060}
1061
1062/// A structured casting sheet. Structure lives in the
1063/// keys; every value is free text. `archetype`, `speech_style` and `motivation`
1064/// are required; the rest are optional.
1065#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1066#[serde(deny_unknown_fields)]
1067pub struct Persona {
1068    /// One-line character archetype (required).
1069    pub archetype: String,
1070    /// How the NPC speaks — register, tics, formality (required).
1071    pub speech_style: String,
1072    /// Emotional bearing toward the player (optional).
1073    #[serde(default, skip_serializing_if = "Option::is_none")]
1074    pub demeanor: Option<String>,
1075    /// What the NPC wants (required).
1076    pub motivation: String,
1077    /// Something the NPC hides (optional).
1078    #[serde(default, skip_serializing_if = "Option::is_none")]
1079    pub secret: Option<String>,
1080    /// Backstory colour (optional).
1081    #[serde(default, skip_serializing_if = "Option::is_none")]
1082    pub backstory: Option<String>,
1083    /// Attitudes toward other same-stage NPCs (optional; refs validated).
1084    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1085    pub relationships: Vec<Relationship>,
1086}
1087
1088/// One persona relationship: an attitude toward another same-stage NPC.
1089#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1090#[serde(deny_unknown_fields)]
1091pub struct Relationship {
1092    /// The other NPC (stage-2 ref, validated within stage 2).
1093    pub npc: NpcId,
1094    /// Free-text attitude toward that NPC.
1095    pub attitude: String,
1096}
1097
1098/// What a speaking part does. A schema enum offers what the engine accepts,
1099/// so there are two of them: how hard a fight is billed is [`EncounterTier`] on
1100/// the body that fights (a `waves[]` entry or a stage-5 actor), not a role here.
1101#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1102#[serde(rename_all = "kebab-case")]
1103pub enum Role {
1104    /// Gives and advances quests.
1105    QuestGiver,
1106    /// Flavor only.
1107    Flavor,
1108}
1109
1110// ---------------------------------------------------------------------------
1111// Stage 6 — dialogue
1112// ---------------------------------------------------------------------------
1113
1114/// Stage 6 payload: one dialogue tree per stage-2 NPC (spec-0001 v0.2).
1115#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1116#[serde(deny_unknown_fields)]
1117pub struct DialogueContent {
1118    /// One tree per NPC (1:1 with stage 2, both directions).
1119    pub dialogues: Vec<NpcDialogue>,
1120}
1121
1122impl DialogueContent {
1123    /// The dialogue tree for an NPC id, if present.
1124    pub fn tree_for(&self, npc: &str) -> Option<&NpcDialogue> {
1125        self.dialogues.iter().find(|t| t.npc.as_str() == npc)
1126    }
1127}
1128
1129/// One NPC's dialogue tree: a root node plus a set of nodes.
1130#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1131#[serde(deny_unknown_fields)]
1132pub struct NpcDialogue {
1133    /// The NPC this tree belongs to (stage-2 ref).
1134    pub npc: NpcId,
1135    /// The entry node id; every node must be reachable from it.
1136    pub root: DialogueId,
1137    /// The dialogue nodes.
1138    pub nodes: Vec<DialogueNode>,
1139}
1140
1141impl NpcDialogue {
1142    /// The ids of the nodes reachable from `roots` by following option `next`
1143    /// edges, ignoring every option gate.
1144    ///
1145    /// **The one authority for "what can this tree show, entered here".** A
1146    /// dialogue tree has more than one entry point — the stage-6 `root`, and
1147    /// every node a quest's `cast` ledger names as a scene — so "reachable" is
1148    /// always relative to a root SET, and each consumer supplies the set its own
1149    /// question is about. `DW0120`/`DW0123` ask about every entry point at once;
1150    /// the cast ledger's `DW0858` asks about the scenes live during one
1151    /// objective. Gates are ignored on purpose: an option's flag gate is
1152    /// `DW0191`'s question, not this one's.
1153    ///
1154    /// Root ids that name no node of this tree contribute nothing (a dangling
1155    /// scene root is `DW0464`, and a dangling stage-6 `root` is `DW0121`).
1156    pub fn reachable_from<'a>(&'a self, roots: &[&str]) -> BTreeSet<&'a str> {
1157        let by_id: BTreeMap<&'a str, &'a DialogueNode> =
1158            self.nodes.iter().map(|n| (n.id.as_str(), n)).collect();
1159        let mut seen: BTreeSet<&'a str> = BTreeSet::new();
1160        let mut stack: Vec<&'a str> = roots
1161            .iter()
1162            .filter_map(|r| by_id.get_key_value(*r).map(|(k, _)| *k))
1163            .collect();
1164        while let Some(cur) = stack.pop() {
1165            if !seen.insert(cur) {
1166                continue;
1167            }
1168            let Some(node) = by_id.get(cur) else { continue };
1169            for opt in &node.options {
1170                if let Some(next) = &opt.next
1171                    && let Some((k, _)) = by_id.get_key_value(next.as_str())
1172                {
1173                    stack.push(k);
1174                }
1175            }
1176        }
1177        seen
1178    }
1179
1180    /// The objective ids some option reachable from `roots` completes — what a
1181    /// player entering this tree at those scenes can actually finish.
1182    pub fn completes_from<'a>(&'a self, roots: &[&str]) -> BTreeSet<&'a str> {
1183        let seen = self.reachable_from(roots);
1184        let mut out: BTreeSet<&'a str> = BTreeSet::new();
1185        for node in &self.nodes {
1186            if !seen.contains(node.id.as_str()) {
1187                continue;
1188            }
1189            for opt in &node.options {
1190                for eff in &opt.effects {
1191                    if let DialogueEffect::CompleteObjective { objective } = eff {
1192                        out.insert(objective.as_str());
1193                    }
1194                }
1195            }
1196        }
1197        out
1198    }
1199}
1200
1201/// One dialogue node: text plus branching options.
1202#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1203#[serde(deny_unknown_fields)]
1204pub struct DialogueNode {
1205    /// Node id (unique within this NPC's dialogue).
1206    pub id: DialogueId,
1207    /// The line the NPC speaks.
1208    pub text: String,
1209    /// Branching options; empty closes the dialog.
1210    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1211    pub options: Vec<DialogueOption>,
1212}
1213
1214/// One selectable dialogue option.
1215#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1216#[serde(deny_unknown_fields)]
1217pub struct DialogueOption {
1218    /// Button label.
1219    pub label: String,
1220    /// The full line this button is the caption of (DSL v0.8). Vanilla's dialog button codec
1221    /// (`CommonButtonData`) carries an optional `tooltip` component beside
1222    /// `label`, and the client hangs it on the button as a real hover tooltip —
1223    /// so a caption on the button and the sentence the character actually says
1224    /// can both exist. **Not** subject to `DW0331`: a tooltip is not drawn on the
1225    /// 150 px button, it is wrapped at 170 px into its own hover box, so it never
1226    /// scrolls. Player-visible, so it translates like the label
1227    /// (`dlg.<npc>.<node>.opt.<i>.tooltip`).
1228    #[serde(default, skip_serializing_if = "Option::is_none")]
1229    pub tooltip: Option<String>,
1230    /// Next node; omitted closes the dialog.
1231    #[serde(default, skip_serializing_if = "Option::is_none")]
1232    pub next: Option<DialogueId>,
1233    /// Flags that must be set for this option to be shown (DSL v0.4). Mirrors an
1234    /// objective's `requires_flags`: an ungated option (empty) is unchanged; a
1235    /// gated option is hidden until every referenced flag has been set by a
1236    /// `set-flag` effect (quest or dialogue). Validation guarantees a flag-gated
1237    /// option cannot make a critical-path node unreachable (`DW0191`).
1238    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1239    pub requires_flags: Vec<FlagId>,
1240    /// Negative flag gate (DSL v0.6): the option is
1241    /// **hidden** (and its `/trigger` handler inert) while ANY listed flag is set
1242    /// for the player — the dual of `requires_flags`. A `forbids_flags`-gated
1243    /// option counts as *gated* for the `DW0191` deadlock guard: it can be
1244    /// suppressed at any point, so it cannot be the only completing path.
1245    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1246    pub forbids_flags: Vec<FlagId>,
1247    /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison must
1248    /// hold for this gate to be open. The third field of the one gate, carried by
1249    /// every gate consumer — never by the verb that first wanted it. Default
1250    /// empty, so a pre-0.10 campaign is byte-identical.
1251    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1252    pub requires_state: Vec<StateCompare>,
1253    /// Effects fired when this option is chosen.
1254    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1255    pub effects: Vec<DialogueEffect>,
1256    /// What choosing this option does to the story (spec-0025). Required for a
1257    /// **story-weight** beat
1258    /// — an option carrying a `set-flag` effect, which is how a player's choice
1259    /// forks the world (`DW0481`). An option that only walks the tree or
1260    /// completes an objective needs none: the objective already declares one.
1261    #[serde(default, skip_serializing_if = "Option::is_none")]
1262    pub happening: Option<Happening>,
1263}
1264
1265/// Effect fired by a dialogue option. `complete-objective` (v0.2) and, from DSL
1266/// v0.4, `set-flag` (mirrors the quest effect — sets a campaign flag from a
1267/// dialogue choice, enabling flag-gated options/objectives/triggers).
1268#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1269#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
1270pub enum DialogueEffect {
1271    /// Marks a stage-5 objective complete.
1272    CompleteObjective {
1273        /// The objective to complete (resolved at the stage-5 boundary).
1274        objective: ObjectiveId,
1275    },
1276    /// Sets a campaign flag (DSL v0.4), mirroring [`Verb::SetFlag`].
1277    SetFlag {
1278        /// The flag to set.
1279        flag: FlagId,
1280    },
1281    /// Cuts the world time (DSL v0.5), mirroring [`Verb::SetTime`].
1282    SetTime {
1283        /// The time state to cut to.
1284        time: WorldTime,
1285    },
1286    /// Cuts the weather (DSL v0.5), mirroring [`Verb::SetWeather`].
1287    SetWeather {
1288        /// The weather state to cut to.
1289        weather: WorldWeather,
1290    },
1291    /// Sets the party-wide respawn checkpoint (DSL v0.6, spec-0012), mirroring
1292    /// [`Verb::SetCheckpoint`] — usable from a dialogue outcome.
1293    SetCheckpoint {
1294        /// The prefab checkpoint anchor the party respawns at.
1295        anchor: AnchorId,
1296        /// Per-player effects re-run on respawn while this checkpoint is active
1297        /// (scene reset). Empty = no hook.
1298        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1299        on_respawn: Vec<QuestEffect>,
1300    },
1301    /// Summons a `deferred` stage-2 NPC (DSL v0.6), mirroring
1302    /// [`Verb::SpawnNpc`] — a character who walks in mid-conversation.
1303    SpawnNpc {
1304        /// The NPC (stage-2 ref) to summon.
1305        npc: NpcId,
1306    },
1307}
1308
1309impl DialogueEffect {
1310    /// The v0.5 effect name if this dialogue effect is one introduced in DSL v0.5
1311    /// (`set-time`/`set-weather`, spec-0010).
1312    pub fn v05_effect(&self) -> Option<&'static str> {
1313        match self {
1314            DialogueEffect::SetTime { .. } => Some("set-time"),
1315            DialogueEffect::SetWeather { .. } => Some("set-weather"),
1316            _ => None,
1317        }
1318    }
1319
1320    /// The v0.6 effect name if this dialogue effect is one introduced in DSL v0.6
1321    /// (`set-checkpoint`, spec-0012; `spawn-npc`).
1322    pub fn v06_effect(&self) -> Option<&'static str> {
1323        match self {
1324            DialogueEffect::SetCheckpoint { .. } => Some("set-checkpoint"),
1325            DialogueEffect::SpawnNpc { .. } => Some("spawn-npc"),
1326            _ => None,
1327        }
1328    }
1329
1330    /// The NPC id if this is a v0.6 `spawn-npc` dialogue effect.
1331    pub fn spawn_npc(&self) -> Option<&NpcId> {
1332        match self {
1333            DialogueEffect::SpawnNpc { npc } => Some(npc),
1334            _ => None,
1335        }
1336    }
1337
1338    /// `(anchor, on_respawn)` if this is a v0.6 `set-checkpoint` dialogue effect.
1339    pub fn set_checkpoint(&self) -> Option<(&AnchorId, &[QuestEffect])> {
1340        match self {
1341            DialogueEffect::SetCheckpoint { anchor, on_respawn } => {
1342                Some((anchor, on_respawn.as_slice()))
1343            }
1344            _ => None,
1345        }
1346    }
1347
1348    /// The `on_respawn` bundle of a v0.6 `set-checkpoint` dialogue effect —
1349    /// **effect root 5** ([`crate::effects`]). Named separately from
1350    /// [`Self::set_checkpoint`] so the root walk and its mutable mirror name the
1351    /// same accessor modulo mutability, which is what lets one macro body generate
1352    /// both.
1353    pub fn set_checkpoint_on_respawn(&self) -> Option<&[QuestEffect]> {
1354        match self {
1355            DialogueEffect::SetCheckpoint { on_respawn, .. } => Some(on_respawn.as_slice()),
1356            _ => None,
1357        }
1358    }
1359
1360    /// The `on_respawn` bundle of a v0.6 `set-checkpoint` dialogue effect, exposed
1361    /// mutably so the localization pass can rewrite the player-visible strings
1362    /// nested inside it. Lockstep sibling of [`Self::set_checkpoint`] — the bundle
1363    /// is a plain `Vec<QuestEffect>` that emission really lowers, so every scan
1364    /// that reaches it read-only needs a way to reach it writable too.
1365    pub fn set_checkpoint_on_respawn_mut(&mut self) -> Option<&mut [QuestEffect]> {
1366        match self {
1367            DialogueEffect::SetCheckpoint { on_respawn, .. } => Some(on_respawn.as_mut_slice()),
1368            _ => None,
1369        }
1370    }
1371}
1372
1373impl DialogueEffect {
1374    /// The `set-flag` flag id if this is a v0.4 `set-flag` dialogue effect.
1375    pub fn set_flag(&self) -> Option<&FlagId> {
1376        match self {
1377            DialogueEffect::SetFlag { flag } => Some(flag),
1378            _ => None,
1379        }
1380    }
1381
1382    /// The v0.4 effect name if this dialogue effect is one introduced in DSL v0.4
1383    /// (`set-flag`).
1384    pub fn v04_effect(&self) -> Option<&'static str> {
1385        match self {
1386            DialogueEffect::SetFlag { .. } => Some("set-flag"),
1387            _ => None,
1388        }
1389    }
1390
1391    /// The target time if this is a v0.5 `set-time` dialogue effect.
1392    pub fn set_time(&self) -> Option<WorldTime> {
1393        match self {
1394            DialogueEffect::SetTime { time } => Some(*time),
1395            _ => None,
1396        }
1397    }
1398
1399    /// The target weather if this is a v0.5 `set-weather` dialogue effect.
1400    pub fn set_weather(&self) -> Option<WorldWeather> {
1401        match self {
1402            DialogueEffect::SetWeather { weather } => Some(*weather),
1403            _ => None,
1404        }
1405    }
1406}
1407
1408// ---------------------------------------------------------------------------
1409// Stage 3 — classes
1410// ---------------------------------------------------------------------------
1411
1412/// Stage 3 payload: 1..4 selectable classes.
1413#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1414#[serde(deny_unknown_fields)]
1415pub struct ClassesContent {
1416    /// The selectable classes.
1417    pub classes: Vec<Class>,
1418}
1419
1420/// A player class with a starting kit.
1421#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1422#[serde(deny_unknown_fields)]
1423pub struct Class {
1424    /// Unique class id.
1425    pub id: ClassId,
1426    /// Player-facing name.
1427    pub name: String,
1428    /// Selection-screen blurb.
1429    pub blurb: String,
1430    /// Granted items.
1431    pub kit: Vec<KitItem>,
1432}
1433
1434/// One item in a class kit.
1435///
1436/// Note: `lore`, `enchantments` and `attributes` are reserved for M2/M3
1437/// (spec-0001). They are intentionally *not* defined as fields in v0, so a
1438/// document using them is rejected as an unknown field (`DW0100`).
1439#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1440#[serde(deny_unknown_fields)]
1441pub struct KitItem {
1442    /// Vanilla item id, validated against the pinned 1.21.11 registry.
1443    pub item: String,
1444    /// Stack count.
1445    pub count: u32,
1446    /// Optional display name.
1447    #[serde(default, skip_serializing_if = "Option::is_none")]
1448    pub name: Option<String>,
1449    /// Who gets it (DSL v0.6, spec-0018). Absent = [`Carrier::All`]. A class kit is
1450    /// per-player gear by construction — every player who picks the class gets the
1451    /// kit — so `carrier` here marks a **party-unique** kit item: exactly one copy
1452    /// enters the party, given to the first player to pick this class.
1453    #[serde(default, skip_serializing_if = "Option::is_none")]
1454    pub carrier: Option<Carrier>,
1455    /// **The flask** (DSL v0.8, spec-0016 §1): this kit
1456    /// entry is the class's recovery item, and resting at a bonfire replenishes
1457    /// it to exactly `count`. A campaign that places a `bonfire` and declares no
1458    /// flask anywhere in its kits is `DW0476` — the estus loop is what makes
1459    /// dying an investment, so a souls campaign without one is a build error, not
1460    /// a design choice. Absent on every pre-0.8 kit → emission byte-identical.
1461    #[serde(default, skip_serializing_if = "is_false")]
1462    pub flask: bool,
1463    /// **What is in the bottle** (DSL v0.8, spec-0016 §1): the vanilla
1464    /// `minecraft:potion_contents` component of a
1465    /// potion-bearing item ([`POTION_BEARING_ITEMS`]). Without it a
1466    /// `minecraft:potion` is the *Uncraftable Potion* — a bottle that heals
1467    /// nothing — which is exactly the placeholder flask this field exists to
1468    /// abolish, so at `dsl_version` 0.8.0 a potion-bearing kit item that declares
1469    /// no `contents` is `DW0487`.
1470    #[serde(default, skip_serializing_if = "Option::is_none")]
1471    pub contents: Option<PotionContents>,
1472}
1473
1474/// The items whose vanilla item definition carries a `minecraft:potion_contents`
1475/// component — the only items a kit `contents` may be declared on (`DW0486`).
1476///
1477/// Read off the pinned 1.21.11 `item_components` summary (SHA-256
1478/// `51b191e13f86813ca02f1498942e5bc235947edb71eb8105a78401670b3665c4`, the same
1479/// misode/mcmeta ref `crates/delvec/data/PROVENANCE.md` pins): exactly these
1480/// four items declare the component, and on any other item the game drops the
1481/// data on the floor.
1482pub const POTION_BEARING_ITEMS: &[&str] = &[
1483    "minecraft:lingering_potion",
1484    "minecraft:potion",
1485    "minecraft:splash_potion",
1486    "minecraft:tipped_arrow",
1487];
1488
1489/// True if `item_id` (optionally un-namespaced) is one of the four
1490/// [`POTION_BEARING_ITEMS`].
1491pub fn is_potion_bearing_item(item_id: &str) -> bool {
1492    let norm = if item_id.contains(':') {
1493        item_id.to_string()
1494    } else {
1495        format!("minecraft:{item_id}")
1496    };
1497    POTION_BEARING_ITEMS.contains(&norm.as_str())
1498}
1499
1500/// The two **instantaneous** status effects: they are applied once, on the tick
1501/// the potion is drunk (`PotionContents.applyToLivingEntity` branches on
1502/// `isInstantenous` before any effect instance is ever added), so a `duration` on
1503/// one is a statement the game never reads — `DW0486` says so rather than letting
1504/// an author believe they wrote a thirty-second heal.
1505pub const INSTANT_EFFECTS: &[&str] = &["minecraft:instant_health", "minecraft:instant_damage"];
1506
1507/// A potion-bearing kit item's `minecraft:potion_contents` component (DSL v0.8),
1508/// modelled field for field on vanilla rather than invented: a **named** potion,
1509/// a list of **custom effects**, or both, plus the bottle-colour override.
1510///
1511/// Vanilla resolves a drink as the named potion's effects followed by the custom
1512/// ones, and derives the bottle colour from those effects unless `color`
1513/// overrides it — so `{"potion": "minecraft:strong_healing"}` is literally the
1514/// Potion of Healing II a player would brew, not an approximation of one.
1515#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1516#[serde(deny_unknown_fields)]
1517pub struct PotionContents {
1518    /// A named vanilla potion id (`minecraft:strong_healing`,
1519    /// `minecraft:long_night_vision`, …), validated against the pinned 1.21.11
1520    /// `potion` registry (`DW0486`).
1521    #[serde(default, skip_serializing_if = "Option::is_none")]
1522    pub potion: Option<String>,
1523    /// Custom effects applied on top of (or instead of) the named potion — the
1524    /// escape hatch for a recovery item vanilla has no brew for.
1525    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1526    pub effects: Vec<PotionEffect>,
1527    /// Bottle-colour override, `#rrggbb` (vanilla `custom_color`). Absent → the
1528    /// colour vanilla derives from the effects themselves.
1529    #[serde(default, skip_serializing_if = "Option::is_none")]
1530    pub color: Option<String>,
1531}
1532
1533/// One entry of a potion's `custom_effects` list.
1534#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1535#[serde(deny_unknown_fields)]
1536pub struct PotionEffect {
1537    /// Vanilla status-effect id (e.g. `minecraft:regeneration`), validated
1538    /// against the pinned registry (`DW0486`).
1539    pub effect: String,
1540    /// How long it lasts, in **ticks** (20 = one second). Required for every
1541    /// effect except the two [`INSTANT_EFFECTS`], which must NOT declare one.
1542    #[serde(default, skip_serializing_if = "Option::is_none")]
1543    pub duration: Option<u32>,
1544    /// Amplifier, 0 = level I (vanilla's unsigned byte, so 0–255). Absent = 0.
1545    #[serde(default, skip_serializing_if = "Option::is_none")]
1546    pub amplifier: Option<u32>,
1547}
1548
1549impl PotionEffect {
1550    /// True if this effect is applied once on drinking rather than over time.
1551    pub fn is_instant(&self) -> bool {
1552        let norm = crate::registry::namespaced_effect_id(&self.effect);
1553        INSTANT_EFFECTS.contains(&norm.as_str())
1554    }
1555}
1556
1557/// The largest `duration` a potion effect may declare, in ticks: 1 000 000 ticks
1558/// ≈ 13.9 hours, past the 10-hour delve ceiling, so nothing a delve can legally
1559/// need is refused — while a duration typed in *milliseconds*, or one that would
1560/// overflow vanilla's int, is caught (`DW0486`).
1561pub const MAX_POTION_DURATION_TICKS: u32 = 1_000_000;
1562
1563/// The largest `amplifier` a potion effect may declare: vanilla stores it in an
1564/// unsigned byte, so 255 is not a policy but the end of the field.
1565pub const MAX_POTION_AMPLIFIER: u32 = 255;
1566
1567/// The largest `seconds` a [`Verb::GiveEffect`] may declare, derived from
1568/// [`MAX_POTION_DURATION_TICKS`] rather than chosen again: the two are the same
1569/// quantity in different units, and a second independently-picked ceiling is how
1570/// two limits for one fact drift apart. ≈13.9 hours, past the 10-hour delve
1571/// ceiling, so nothing a delve can legally need is refused — while a duration
1572/// typed in *ticks* or in milliseconds is caught (`DW0541`).
1573pub const MAX_EFFECT_SECONDS: u32 = MAX_POTION_DURATION_TICKS / 20;
1574
1575/// The canonical English title of the bonfire rest dialog. Baked at emit time
1576/// when the campaign authors no `prompt`, in the
1577/// `world.boundary.message` tradition: a compiler default is not inventoried, an
1578/// authored line is — so a delve that wants this sentence in `zh-cn` authors it.
1579pub const BONFIRE_PROMPT_EN: &str = "Bonfire";
1580/// The canonical English label of the **rest and save** option.
1581pub const BONFIRE_REST_LABEL_EN: &str = "Rest and save";
1582/// The canonical English label of the **save only** option.
1583pub const BONFIRE_SAVE_LABEL_EN: &str = "Save only";
1584
1585/// A `bonfire`'s authored rest-dialog strings, each `None` when the campaign
1586/// leaves the compiler's canonical English in place
1587/// ([`QuestEffect::bonfire_labels`]).
1588#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1589pub struct BonfireLabels<'a> {
1590    /// Dialog title; `None` → [`BONFIRE_PROMPT_EN`].
1591    pub prompt: Option<&'a str>,
1592    /// **Rest and save** button label; `None` → [`BONFIRE_REST_LABEL_EN`].
1593    pub rest_label: Option<&'a str>,
1594    /// **Save only** button label; `None` → [`BONFIRE_SAVE_LABEL_EN`].
1595    pub save_label: Option<&'a str>,
1596}
1597
1598impl BonfireLabels<'_> {
1599    /// The dialog title actually emitted.
1600    pub fn prompt_or_default(&self) -> &str {
1601        self.prompt.unwrap_or(BONFIRE_PROMPT_EN)
1602    }
1603    /// The **rest and save** label actually emitted.
1604    pub fn rest_or_default(&self) -> &str {
1605        self.rest_label.unwrap_or(BONFIRE_REST_LABEL_EN)
1606    }
1607    /// The **save only** label actually emitted.
1608    pub fn save_or_default(&self) -> &str {
1609        self.save_label.unwrap_or(BONFIRE_SAVE_LABEL_EN)
1610    }
1611}
1612
1613// ---------------------------------------------------------------------------
1614// Stage 4 — quest-plan
1615// ---------------------------------------------------------------------------
1616
1617/// Stage 4 payload: the quest dependency plan.
1618#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1619#[serde(deny_unknown_fields)]
1620pub struct QuestPlanContent {
1621    /// Planned quests (expanded in stage 5).
1622    pub quests: Vec<PlannedQuest>,
1623    /// The quest whose completion ends the campaign.
1624    pub finale: QuestId,
1625    /// The campaign's declared **story forks** (DSL v0.8, spec-0025). Empty/absent = a campaign that claims to have no
1626    /// branch — which the compiler then *verifies* rather than assumes: any flag
1627    /// that gates casts, staging or structure and is set on some playthroughs and
1628    /// not others belongs to no declared point and is `DW0480`.
1629    ///
1630    /// Enumerated branches are the **product of the declared points**, so the
1631    /// branch set is authored and small — never a combinatorial sweep of every
1632    /// flag in the campaign.
1633    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1634    pub branch_points: Vec<BranchPoint>,
1635}
1636
1637impl QuestPlanContent {
1638    /// **The ONE authority on which quests are the spine**: the finale and every
1639    /// quest its `depends_on` chain transitively demands — the quests a body
1640    /// cannot reach the finale without.
1641    ///
1642    /// The capability belongs here, on the stage-4 document, because the spine is
1643    /// a fact about the quest plan and about nothing else. It had grown two
1644    /// derivations of the same closure in two files — one inline in
1645    /// [`crate::validate`]'s `DW0132` convergence check, one a private
1646    /// `mandatory_quests` in [`crate::layout`] read by the layout binding and by
1647    /// the critical-path spine obligation. Both were correct and neither said it
1648    /// was the authority, which is exactly the shape a later clean merge turns
1649    /// into two rules that disagree.
1650    ///
1651    /// **Why the closure is taken over the raw `depends_on` edges, unfiltered.**
1652    /// The `validate` copy first dropped every dep naming a quest the plan does
1653    /// not declare. That filtering is not this function's question: a dangling
1654    /// `depends_on` is `DW0112`'s finding, and silently pruning it here would
1655    /// make the set disagree with the document it is derived from. So an id the
1656    /// plan does not declare is reported in the spine and expands no further —
1657    /// and the one reader that could care, `DW0132`, only ever asks whether a
1658    /// **declared** quest is a member, so an undeclared member cannot change its
1659    /// verdict.
1660    ///
1661    /// Cycle-safe by construction (a quest already in the set is not expanded
1662    /// again), so a plan `DW0130` will refuse still yields a set rather than
1663    /// hanging.
1664    ///
1665    /// **Not the same question as the `mandatory` field**, and the name says so
1666    /// deliberately. Today the two sets always coincide, because `DW0132` demands
1667    /// every declared quest be a transitive dependency of the finale and `DW0866`
1668    /// demands every quest set `mandatory: true`. If `mandatory: false` ever
1669    /// becomes legal those coincide no longer, and this function keeps answering
1670    /// the graph question it has always answered.
1671    #[must_use]
1672    pub fn spine(&self) -> BTreeSet<&str> {
1673        let deps: BTreeMap<&str, &[QuestId]> = self
1674            .quests
1675            .iter()
1676            .map(|q| (q.id.as_str(), q.depends_on.as_slice()))
1677            .collect();
1678        let mut spine: BTreeSet<&str> = BTreeSet::new();
1679        let mut stack = vec![self.finale.as_str()];
1680        while let Some(q) = stack.pop() {
1681            if !spine.insert(q) {
1682                continue;
1683            }
1684            for dep in deps.get(q).copied().unwrap_or(&[]) {
1685                stack.push(dep.as_str());
1686            }
1687        }
1688        spine
1689    }
1690
1691    /// **The ONE authority on which quests are elective** (spec-0051): the
1692    /// quests declaring `mandatory: false`.
1693    ///
1694    /// The counterpart to [`Self::spine`], and deliberately a *different*
1695    /// question. `spine` asks what the graph demands; this asks what the author
1696    /// claims. `DW0866`/`DW0867` are exactly the rules that keep the two
1697    /// answers honest about each other, and they can only do that while each
1698    /// side has one derivation — which is the defect the spine function was
1699    /// created to end, and which a second private `!q.mandatory` filter in the
1700    /// compiler would re-introduce on the other half.
1701    #[must_use]
1702    pub fn optional(&self) -> BTreeSet<&str> {
1703        self.quests
1704            .iter()
1705            .filter(|q| !q.mandatory)
1706            .map(|q| q.id.as_str())
1707            .collect()
1708    }
1709}
1710
1711/// One declared story fork (DSL v0.8, spec-0025).
1712///
1713/// A branch point names the flag set the story forks on, the quest at which the
1714/// fork opens, and every branch it offers. Each branch pins the point's whole
1715/// flag set: the flags it lists are **set**, and every other flag of `forks_on`
1716/// is **not** — which is what makes exclusive-content leakage (`DW0484`) and
1717/// per-branch cast resolution (`DW0483`) decidable instead of hopeful.
1718#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1719#[serde(deny_unknown_fields)]
1720pub struct BranchPoint {
1721    /// Unique branch-point id.
1722    pub id: BranchPointId,
1723    /// The quest at which the fork opens — every branch's divergent content is at
1724    /// or after it in the stage-4 DAG.
1725    pub opens_at: QuestId,
1726    /// The flag set the story forks on. Every branch's `flags` is a subset of
1727    /// this, and the flags it does not list are pinned **unset** on that branch.
1728    pub forks_on: Vec<FlagId>,
1729    /// The alternatives (≥ 2).
1730    pub branches: Vec<BranchDecl>,
1731}
1732
1733/// One alternative of a [`BranchPoint`] (DSL v0.8, spec-0025).
1734#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1735#[serde(deny_unknown_fields)]
1736pub struct BranchDecl {
1737    /// Unique branch id (campaign-wide — it names the emitted chronicle file).
1738    pub id: BranchId,
1739    /// The subset of the point's `forks_on` that is SET on this branch. The rest
1740    /// of `forks_on` is pinned unset. An empty list is legal — the "took neither
1741    /// option" branch — as long as it is genuinely reachable.
1742    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1743    pub flags: Vec<FlagId>,
1744    /// Where this branch goes: either the `quest/<kebab>` the branches converge
1745    /// at, or the `ending/<kebab>` this branch runs to.
1746    ///
1747    /// One field, not two mutually exclusive ones, because the **id prefix
1748    /// already says which it is** — the same convention every cross-stage
1749    /// reference in the DSL uses. That is what makes "exactly one of them" an
1750    /// unrepresentable state rather than a rule some diagnostic has to police: a
1751    /// value that is neither a syntactically valid `quest/…` nor `ending/…` is
1752    /// the ordinary malformed-id `DW0110`, and one that names nothing is the
1753    /// ordinary dangling-reference `DW0112`.
1754    pub leads_to: String,
1755}
1756
1757impl BranchDecl {
1758    /// The convergence quest, if [`Self::leads_to`] names one.
1759    pub fn converges_at(&self) -> Option<QuestId> {
1760        let q = QuestId(self.leads_to.clone());
1761        q.is_valid_syntax().then_some(q)
1762    }
1763
1764    /// The ending, if [`Self::leads_to`] names one.
1765    pub fn ending(&self) -> Option<EndingId> {
1766        let e = EndingId(self.leads_to.clone());
1767        e.is_valid_syntax().then_some(e)
1768    }
1769}
1770
1771/// What a story node does to the story (DSL v0.8, spec-0025).
1772///
1773/// The generalization of spec-0020's `doing` from NPC presence to event flow: a
1774/// design that never got written down node by node cannot compile. It is
1775/// **node-local on purpose** — there is no parallel per-branch script document
1776/// that could itself drift from the graph.
1777///
1778/// `text` is authoring/validation metadata, never shown to a player, so it is
1779/// deliberately **excluded from the l10n inventory** exactly like `doing`. The
1780/// compiler reads only `verb` and `subject`; `text` is the flesh the per-branch
1781/// chronicle is assembled from.
1782#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1783#[serde(deny_unknown_fields)]
1784pub struct Happening {
1785    /// The structured event verb — the machine-decidable part.
1786    pub verb: HappeningVerb,
1787    /// One line of prose stating what this node does to the story.
1788    pub text: String,
1789    /// What the event happens TO: an `npc/`, `actor/`, `wave/` or `anchor/` id
1790    /// (validated — a dangling one is `DW0112`), or an `item/<kebab>` label for a
1791    /// story token the campaign tracks by hand. Optional, because not every beat
1792    /// is about somebody; the hard-contradiction proof (`DW0485`) reasons only
1793    /// over the beats that name one.
1794    #[serde(default, skip_serializing_if = "Option::is_none")]
1795    pub subject: Option<String>,
1796}
1797
1798/// The structured event vocabulary (DSL v0.8, spec-0025).
1799///
1800/// Deliberately small and closed. These ten verbs are what make a subset of
1801/// narrative errors machine-decidable per branch (`DW0485`); everything else a
1802/// beat means lives in [`Happening::text`], which the compiler never interprets.
1803/// Extend only when a real campaign cannot state its beat with what is here.
1804#[derive(
1805    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
1806)]
1807#[serde(rename_all = "kebab-case")]
1808pub enum HappeningVerb {
1809    /// The subject is killed / destroyed. Terminal: nothing the subject does may
1810    /// follow it on the same branch.
1811    Dies,
1812    /// The subject comes through alive — the explicit counterpart of `dies`,
1813    /// which is what lets a branch state that somebody *did not* die.
1814    Survives,
1815    /// The subject leaves the stage (offstage, not dead). Cleared by `arrives`.
1816    Departs,
1817    /// The subject enters the stage.
1818    Arrives,
1819    /// Somebody learns a fact — the true-information beat.
1820    Learns,
1821    /// Somebody comes to believe something (whether or not it is true) — the beat
1822    /// that carries a wrong belief forward, which is where branch drift shows.
1823    Believes,
1824    /// The party (or the subject) gains a thing.
1825    Gains,
1826    /// The party (or the subject) loses a thing. A second `loses` with no
1827    /// intervening `gains` is spending what is already spent (`DW0485`).
1828    Loses,
1829    /// A way is opened.
1830    Opens,
1831    /// A way is sealed. Cleared by `opens`.
1832    Seals,
1833}
1834
1835/// One planned quest (dependency-graph node).
1836#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1837#[serde(deny_unknown_fields)]
1838pub struct PlannedQuest {
1839    /// Unique quest id.
1840    pub id: QuestId,
1841    /// Human-readable goal.
1842    pub goal: String,
1843    /// Area this quest takes place in (stage-1 ref).
1844    pub area: AreaId,
1845    /// NPCs involved (stage-2 refs).
1846    pub npcs: Vec<NpcId>,
1847    /// Prerequisite quests; edges must form a DAG.
1848    pub depends_on: Vec<QuestId>,
1849    /// `false` declares an optional quest (spec-0051).
1850    pub mandatory: bool,
1851    /// Act number (informational).
1852    pub act: u32,
1853}
1854
1855// ---------------------------------------------------------------------------
1856// Stage 5 — quests
1857// ---------------------------------------------------------------------------
1858
1859/// Stage 5 payload: quest expansions.
1860#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
1861#[serde(deny_unknown_fields)]
1862pub struct QuestsContent {
1863    /// The expanded quests (1:1 with stage 4).
1864    pub quests: Vec<Quest>,
1865    /// Combat waves (DSL v0.3). Each wave is spawned by a `spawn-wave` effect and
1866    /// slain to complete a `kill` objective. Empty/absent in v0.2 campaigns.
1867    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1868    pub waves: Vec<Wave>,
1869    /// Environment triggers (DSL v0.4, spec-0008 §7): "the world answers". Each
1870    /// watches an anchor for a strike / use / approach event and fires a bundle
1871    /// of [`QuestEffect`]s. Empty/absent in v0.2/v0.3 campaigns.
1872    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1873    pub triggers: Vec<EnvTrigger>,
1874    /// Scripted actors (DSL v0.6, spec-0014): NoAI/Silent/no-loot puppets moved by
1875    /// compiler-emitted per-tick teleport. Distinct from stage-2 NPCs
1876    /// (no dialogue, any mob type). Summoned/removed/moved/unleashed by the actor
1877    /// staging effects. Empty/absent before v0.6.
1878    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1879    pub actors: Vec<Actor>,
1880    /// Traps (DSL v0.6, spec-0011; command payloads spec-0022): environmental
1881    /// hazards, each at one point anchor an area's prefab provides. Each says
1882    /// what springs the trap, what it then does (a command `payload`, a legacy
1883    /// dispenser `effect`, or both), how dangerous it is, how it is disarmed and
1884    /// whether it re-arms. Empty/absent in pre-0.6 campaigns, so a v0.5-or-earlier campaign that declares none stays
1885    /// byte-identical.
1886    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1887    pub traps: Vec<Trap>,
1888    /// Shortcut doors (spec-0016 §2): a gate that is sealed from world-load and
1889    /// is opened — permanently — from the FAR side. Empty/absent in pre-0.6
1890    /// campaigns, so a campaign that declares none stays
1891    /// byte-identical.
1892    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1893    pub shortcuts: Vec<Shortcut>,
1894    /// Ambushes (spec-0016 §3): sugar over "deferred actors + a trigger that
1895    /// springs them". Empty/absent in pre-0.6 campaigns.
1896    ///
1897    /// **Never serialized.** [`parse_campaign`](crate::parse_campaign) expands
1898    /// each ambush into `triggers`, so the canonical form of a campaign is its
1899    /// **desugared** form. That is what keeps the canonical round-trip idempotent
1900    /// (re-parsing canonical output finds no `ambushes` and so cannot expand a
1901    /// second time and duplicate the trigger ids), and it means the sugar exists
1902    /// at exactly one layer boundary — the authored `.json` — with nothing
1903    /// downstream needing to know it was ever there. The list itself is kept in
1904    /// memory so diagnostics can name the ambush the author wrote.
1905    /// Timed gates (spec-0016 §4): gates on a deterministic open/close clock.
1906    /// Empty/absent in pre-0.6 campaigns.
1907    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1908    pub timed_gates: Vec<TimedGate>,
1909    /// Container fills (spec-0021): pre-placed chests/barrels in the prefabs
1910    /// given contents at world init. Empty/absent in pre-0.6 campaigns
1911    ///.
1912    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1913    pub loot: Vec<Loot>,
1914    /// Runtime state data (DSL v0.10, spec-0031): named, scoped, integer-valued
1915    /// counters the campaign sets, adds to and clears at runtime, and compares
1916    /// against in any gate. A campaign that declares none emits none of it.
1917    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1918    pub state: Vec<StateDecl>,
1919    /// **The campaign's death beat** (DSL v0.10, spec-0031): effects run at the
1920    /// moment a player dies, for that player. Effect root **R7**
1921    /// ([`crate::EffectRootKind::OnDeath`]); a campaign that declares none emits
1922    /// none of it.
1923    ///
1924    /// **Why this is campaign-wide and not a field on a checkpoint.** The engine
1925    /// already has `on_respawn`, and it hangs off a `set-checkpoint` because
1926    /// *where you come back* is a property of the checkpoint. *That you died* is
1927    /// not: it is true at every point of the delve, under every checkpoint, and a
1928    /// bundle repeated on each checkpoint would be the same content written N
1929    /// times with N chances to forget one. So death is a moment in the campaign,
1930    /// and this is the one place it is named. Anything that should only happen in
1931    /// some phase of the delve is expressed by the ordinary per-effect
1932    /// `requires_flags` / `forbids_flags` gate every other root already carries —
1933    /// no second gating surface.
1934    ///
1935    /// **Audience is the dying player** (`Audience::Solo`, the audience
1936    /// `on_respawn` and `on_caught` already use): a death is one player's, and
1937    /// re-broadcasting it to the party would duplicate their narration and their
1938    /// kit. A beat the whole party should see is a `narrate` addressed by the
1939    /// author to the party through the effect's own vocabulary, not a different
1940    /// default here.
1941    ///
1942    /// **Timing.** It fires on the death edge while the player is still a corpse
1943    /// (`Health: 0.0f`, on the death screen) — see
1944    /// `emit::emit_checkpoint_functions`. That is the difference between this and
1945    /// `on_respawn`, which deliberately waits for the player to come back.
1946    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1947    pub on_death: Vec<QuestEffect>,
1948    /// Lethal volumes (DSL v0.10, spec-0031): declared boxes that kill whatever
1949    /// enters them. Empty/absent in pre-0.10 campaigns, so a
1950    /// campaign that declares none stays byte-identical.
1951    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1952    pub lethal_volumes: Vec<LethalVolume>,
1953    /// Shops (DSL v0.10, spec-0032): interaction points that open a list of
1954    /// gated offers. Empty/absent in pre-0.10 campaigns, so a
1955    /// campaign that declares none stays byte-identical.
1956    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1957    pub shops: Vec<Shop>,
1958    /// Recovery stakes (DSL v0.10, spec-0032): what a death forfeits, where the
1959    /// marker lands, and how it comes back. Empty/absent in pre-0.10 campaigns
1960    ///, so a campaign that declares none stays byte-identical.
1961    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1962    pub stakes: Vec<Stake>,
1963    #[serde(default, skip_serializing)]
1964    pub ambushes: Vec<Ambush>,
1965    /// Whether [`Self::expand_ambushes`] has already run (never serialized). The
1966    /// authored `ambushes` are deliberately KEPT after expansion so validation
1967    /// and the counterplay proof can attribute diagnostics to the ambush the
1968    /// author actually wrote; this flag is what makes a second expansion a no-op.
1969    #[serde(skip)]
1970    pub ambushes_expanded: bool,
1971}
1972
1973impl QuestsContent {
1974    /// Every environment trigger this stage produces: the authored `triggers`
1975    /// followed by the ones each `ambush` desugars to (spec-0016 §3), in
1976    /// declared order.
1977    ///
1978    /// **This is the single trigger authority.** Validation, the l10n
1979    /// inventory, the flag/wave producer scans, the nav proofs and emission all
1980    /// read triggers through it, so an ambush behaves exactly like the trigger
1981    /// an author would otherwise hand-write — there is no second code path for
1982    /// the sugar to drift down. Deterministic (declaration order, no hashing).
1983    pub fn all_triggers(&self) -> Vec<EnvTrigger> {
1984        let mut out = self.triggers.clone();
1985        out.extend(self.ambushes.iter().map(Ambush::to_trigger));
1986        out
1987    }
1988
1989    /// **Does the campaign itself answer a right-click at `anchor`?**
1990    ///
1991    /// One predicate, read by both consumers of the press-answer rule, so they can
1992    /// never disagree about what "the campaign answered it" means: the compiler's
1993    /// synthesis (`plan::collect_press_answers`, which stands down where this is
1994    /// true) and the obligation on a shortcut door (`DW0429`, which fires where it
1995    /// is false). Split across the two crates they would drift, and the drift
1996    /// would read as "the compiler refused a door I answered".
1997    ///
1998    /// Deliberately the widest reading — *any* `use` trigger anchored there.
1999    /// Pressing it already does something the author chose, and the engine does
2000    /// not adjudicate whether what they chose counts as an answer.
2001    pub fn answers_press_at(&self, anchor: &str) -> bool {
2002        self.all_triggers()
2003            .iter()
2004            .any(|t| matches!(t.on, TriggerOn::Use) && t.at_anchor() == Some(anchor))
2005    }
2006
2007    /// Desugar every `ambush` into a real environment trigger and clear the
2008    /// ambush list (spec-0016 §3). Called once, by
2009    /// [`parse_campaign`](crate::parse_campaign); idempotent by construction
2010    /// (a second call sees no ambushes left to expand).
2011    pub fn expand_ambushes(&mut self) {
2012        if self.ambushes_expanded || self.ambushes.is_empty() {
2013            return;
2014        }
2015        self.triggers = self.all_triggers();
2016        self.ambushes_expanded = true;
2017    }
2018
2019    /// The declared datum with this id, if any (DSL v0.10).
2020    pub fn state_decl(&self, id: &str) -> Option<&StateDecl> {
2021        self.state.iter().find(|s| s.id.as_str() == id)
2022    }
2023
2024    /// The declared stake with this id, if any (DSL v0.10, spec-0032).
2025    pub fn stake_decl(&self, id: &str) -> Option<&Stake> {
2026        self.stakes.iter().find(|s| s.id.as_str() == id)
2027    }
2028}
2029
2030// ---------------------------------------------------------------------------
2031// Stage 5 — runtime state (DSL v0.10, spec-0031)
2032// ---------------------------------------------------------------------------
2033
2034/// Who holds a datum's value (DSL v0.10, spec-0031).
2035///
2036/// **Declared, never inferred.** A datum's multiplayer semantics is the one
2037/// thing about it that cannot be recovered from its uses: a purse read on a
2038/// `talk-to` looks identical whether every player has their own or the party
2039/// shares one, and the difference decides the whole design. spec-0031 states it
2040/// as a rule, and the type makes it un-omittable — there is no default.
2041#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2042#[serde(rename_all = "kebab-case")]
2043pub enum StateScope {
2044    /// Each player holds their own value. Read and written against the acting
2045    /// player, so a bundle with no acting player (the scheduler) cannot touch one
2046    /// (`DW0503`).
2047    Player,
2048    /// One value the whole party shares — the same holder story flags use
2049    /// (spec-0018). Readable and writable from every audience, including the
2050    /// scheduler.
2051    Party,
2052}
2053
2054impl StateScope {
2055    /// The wire token (`player` / `party`).
2056    pub fn token(self) -> &'static str {
2057        match self {
2058            StateScope::Player => "player",
2059            StateScope::Party => "party",
2060        }
2061    }
2062}
2063
2064/// One declared runtime datum (DSL v0.10, spec-0031): a named, scoped,
2065/// integer-valued counter.
2066///
2067/// This is what [`FlagId`] is not. A flag is boolean, party-wide and
2068/// **monotonic** — no verb clears one — which is exactly right for "this has
2069/// happened" and useless for a balance, a floor number, or "a ride is in
2070/// progress". A datum clears, counts down as well as up, and states its scope.
2071#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2072#[serde(deny_unknown_fields)]
2073pub struct StateDecl {
2074    /// Unique datum id (`state/<kebab>`).
2075    pub id: StateId,
2076    /// Who holds the value. Required — see [`StateScope`].
2077    pub scope: StateScope,
2078    /// The value the datum starts at, and the value `clear-state` returns it to.
2079    /// Defaults to `0`.
2080    ///
2081    /// One field rather than a separate `initial` and `cleared`: "the value this
2082    /// datum has when nothing has happened to it yet" is one fact, and two fields
2083    /// would let a campaign declare a datum that can never be returned to its own
2084    /// starting state.
2085    #[serde(default, skip_serializing_if = "is_zero_i32")]
2086    pub initial: i32,
2087    /// Free prose: what this datum means. Never machine-checked, never shown to a
2088    /// player — the forcing function that makes an author say what the number is,
2089    /// the same role `cast[].doing` plays.
2090    #[serde(default, skip_serializing_if = "Option::is_none")]
2091    pub note: Option<String>,
2092    /// The player-visible name of this datum (DSL v0.10, spec-0032).
2093    ///
2094    /// **A named datum is a currency.** There is no separate `currencies` section
2095    /// and there deliberately is not: a purse is a runtime datum that the player
2096    /// can see, and "the player can see it" is a property of the datum, not a
2097    /// different object class. A second struct carrying `id` + `scope` +
2098    /// `initial` + `name` would be a private copy of this one, which is the defect
2099    /// CLAUDE.md names second.
2100    ///
2101    /// Present ⇒ every `set-state` / `add-state` / `clear-state` on this datum
2102    /// also states the new balance to whoever holds it, on the action bar, as
2103    /// `<name>: <value>` with the value carried by vanilla's own `score`
2104    /// component. Absent ⇒ the datum is silent bookkeeping and emission is exactly
2105    /// what it was.
2106    ///
2107    /// Player-visible, so it is inventoried under `state.<id>.name` and
2108    /// translated like any other authored line.
2109    #[serde(default, skip_serializing_if = "Option::is_none")]
2110    pub name: Option<String>,
2111}
2112
2113/// serde `skip_serializing_if` helper: skip a zero `i32` (`StateDecl.initial`).
2114fn is_zero_i32(v: &i32) -> bool {
2115    *v == 0
2116}
2117
2118/// How a [`StateCompare`] relates a datum to its operand (DSL v0.10).
2119///
2120/// Four operators, not six: over integers `less-than n` is `at-most n-1` and
2121/// `greater-than n` is `at-least n+1`, so the extra spellings would add a second
2122/// way to say one thing and a second emission path to keep honest.
2123#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2124#[serde(rename_all = "kebab-case")]
2125pub enum CompareOp {
2126    /// The datum is exactly `value`.
2127    Equals,
2128    /// The datum is anything but `value`.
2129    NotEquals,
2130    /// The datum is `value` or more.
2131    AtLeast,
2132    /// The datum is `value` or less.
2133    AtMost,
2134}
2135
2136impl CompareOp {
2137    /// The wire token (`equals` / `not-equals` / `at-least` / `at-most`).
2138    pub fn token(self) -> &'static str {
2139        match self {
2140            CompareOp::Equals => "equals",
2141            CompareOp::NotEquals => "not-equals",
2142            CompareOp::AtLeast => "at-least",
2143            CompareOp::AtMost => "at-most",
2144        }
2145    }
2146}
2147
2148/// What one of the DSL v0.10 state verbs does to a datum — the value half of
2149/// [`QuestEffect::writes_state`].
2150#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2151pub enum StateWrite {
2152    /// `set-state`: the datum becomes this value.
2153    Set(i32),
2154    /// `add-state`: the datum moves by this signed amount.
2155    Add(i32),
2156    /// `clear-state`: the datum returns to its declared `initial`.
2157    Clear,
2158}
2159
2160/// One numeric term of a gate (DSL v0.10, spec-0031): *this datum compares thus
2161/// to this value*.
2162///
2163/// It rides [`Gate`](crate::gate::Gate) — the shared gate, carried by every
2164/// consumer of `requires_flags`/`forbids_flags` — and not any one verb. The
2165/// comparison's consumers are exactly the gate's consumers ("this door opens at
2166/// 500", "this line is withheld below 200", "this lever does nothing while the
2167/// car is moving"), so hanging it off the first verb that asked would leave the
2168/// second with no surface and make a second bespoke field look like the fix.
2169#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2170#[serde(deny_unknown_fields)]
2171pub struct StateCompare {
2172    /// The datum to read. Must be declared in the stage-5 `state` list
2173    /// (`DW0502`).
2174    pub state: StateId,
2175    /// How to compare it.
2176    pub op: CompareOp,
2177    /// What to compare it against.
2178    pub value: i32,
2179}
2180
2181/// A stage-5 container fill (DSL v0.6, spec-0021): contents for a chest or
2182/// barrel the prefab already placed.
2183///
2184/// The container is **hardware the prefab authored**, exactly like a trap's
2185/// dispenser: this declaration gives an already-placed, already-lit, already
2186/// composed piece of furniture its contents. The compiler never places the
2187/// container itself — if the anchor's cell does not already hold one, that is a
2188/// content defect and a build error (`DW0431`), not something to paper over by
2189/// setblock-ing a chest into a wall.
2190#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2191#[serde(deny_unknown_fields)]
2192pub struct Loot {
2193    /// Unique loot id (`loot/<kebab>`).
2194    pub id: LootId,
2195    /// The anchor whose cell holds the container to fill.
2196    pub anchor: AnchorId,
2197    /// Contents, in declaration order. Slot assignment is positional and
2198    /// deterministic — the first entry lands in `container.0`, the second in
2199    /// `container.1`, and so on (ADR-0006: no RNG, no loot tables).
2200    pub items: Vec<LootItem>,
2201}
2202
2203/// One stack inside a [`Loot`] container.
2204#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2205#[serde(deny_unknown_fields)]
2206pub struct LootItem {
2207    /// Item id (e.g. `minecraft:cooked_cod`). Validated against the pinned
2208    /// 1.21.11 item registry (`DW0143`).
2209    pub item: String,
2210    /// Stack size. Defaults to 1.
2211    #[serde(default = "one_u32")]
2212    pub count: u32,
2213    /// Optional custom item name. Enters the l10n string inventory exactly like
2214    /// a class kit item's name.
2215    #[serde(default, skip_serializing_if = "Option::is_none")]
2216    pub name: Option<String>,
2217    /// Enchantments on this stack (`{"minecraft:sharpness": 3}`), emitted as the
2218    /// 1.21 `minecraft:enchantments` item component.
2219    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2220    pub enchantments: BTreeMap<String, u32>,
2221}
2222
2223fn one_u32() -> u32 {
2224    1
2225}
2226
2227/// A stage-5 trap (DSL v0.6, spec-0011; command payloads spec-0022): an
2228/// environmental hazard at one cell of a placed piece.
2229///
2230/// **What the prefab has to provide is one point anchor, and for most traps that
2231/// is all.** [`Trap::at`] names the trigger/hazard cell; the compiler models it
2232/// as a hazard for the completability proofs (`DW0342`) and, for a disarmable
2233/// trap, emits the disarm affordance. A [`payload`](Trap::payload) trap needs
2234/// nothing else: **the compiler owns the detection**, emitting a per-tick,
2235/// edge-latched `execute … if entity @a[<cell>]` and running the authored effect
2236/// bundle from it.
2237///
2238/// Two things a piece must pre-wire, each for one case and neither for the
2239/// common one:
2240///
2241/// * the legacy [`effect`](Trap::effect) — a `dispense` payload the prefab's own
2242///   redstone fires — needs the anchor's `dispenser` socket cell, which the
2243///   compiler fills. That is the case "harm is redstone-native" (spec-0011) was
2244///   written about, and the only one in which no detection is emitted.
2245/// * a **flag-gated** trap ([`requires_flags`](Trap::requires_flags) /
2246///   [`forbids_flags`](Trap::forbids_flags)) needs the anchor's `trigger_block`,
2247///   because gating removes the trigger block from the world while the gate is
2248///   shut and puts it back verbatim (`DW0363`).
2249///
2250/// Player-vs-mob distinguishing matters in a sealed box-garden with controlled
2251/// mobs, so `trapped-chest` (opened by a player) is called out as the only
2252/// player-distinct trigger.
2253#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2254#[serde(deny_unknown_fields)]
2255pub struct Trap {
2256    /// Unique trap id (`trap/<kebab>`).
2257    pub id: TrapId,
2258    /// **The point anchor this trap sits on** — any anchor an area's prefab
2259    /// provides, whatever it is called. Its cell is the trigger/hazard cell the
2260    /// compiler models, and for a `payload` trap that cell is the whole of what
2261    /// the piece has to provide: detection is the compiler's.
2262    ///
2263    /// The anchor additionally needs a `dispenser` socket for a legacy
2264    /// [`effect`](Trap::effect) trap, and a `trigger_block` for a flag-gated one
2265    /// (`DW0363`). `anchor/trap` is the name the shipped pieces use, and a name
2266    /// is all it is.
2267    pub at: AnchorId,
2268    /// What springs the trap (all redstone-native).
2269    pub trigger: TrapTrigger,
2270    /// The **legacy** redstone consequence (spec-0011): a static dispenser
2271    /// payload the prefab's own wiring fires. Superseded by [`Trap::payload`]
2272    /// (spec-0022) — redstone now keeps only the trigger — but kept meaningful
2273    /// so existing campaigns build unchanged. Optional since spec-0022; a trap
2274    /// must declare `effect`, `payload`, or both (`DW0440`).
2275    #[serde(default, skip_serializing_if = "Option::is_none")]
2276    pub effect: Option<TrapEffect>,
2277    /// The **command payload** (spec-0022): an ordered effect list in the same
2278    /// vocabulary quests use, run when the trigger fires. This is where a trap's
2279    /// consequence lives now — the compiler owns the detection tick and the
2280    /// effect vocabulary, so a trap's payload is authored like any other effect
2281    /// bundle rather than built out of dust and repeaters. Expressiveness moves
2282    /// from "what dust can carry" to "what the effect vocabulary can say":
2283    /// `volley` and `collapse` (spec-0022's trap verbs) join `damage-players`,
2284    /// `play-sound`, `narrate`, `set-flag` and `spawn-wave`.
2285    ///
2286    /// Empty = a pure spec-0011 redstone trap, which emits exactly what it
2287    /// emitted before (byte-identical).
2288    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2289    pub payload: Vec<QuestEffect>,
2290    /// How dangerous the trap is. A `lethal` trap on the forced critical path
2291    /// carries the completability obligation (`DW0342`); `harmful`/`nonlethal`
2292    /// carry none. Defaults to `harmful`.
2293    #[serde(default)]
2294    pub lethality: Lethality,
2295    /// Optional disarm affordance (quest-coupling): an anchor the player acts on to
2296    /// turn the trap off — setting a flag and emptying the dispenser — before the
2297    /// trap cell is forced.
2298    #[serde(default, skip_serializing_if = "Option::is_none")]
2299    pub disarm: Option<TrapDisarm>,
2300    /// Whether the trap re-arms after firing. `once` = single-shot (fires, then
2301    /// spent — the survivability path); `rearm` = re-fires each trigger (default).
2302    #[serde(default)]
2303    pub reset: TrapReset,
2304    /// Flags that must be set before the trap is considered active (mirrors
2305    /// [`EnvTrigger::requires_flags`]). Default empty.
2306    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2307    pub requires_flags: Vec<FlagId>,
2308    /// Negative flag gate (DSL v0.6): the trap is considered inactive while ANY
2309    /// listed flag is set (mirrors [`EnvTrigger::forbids_flags`]). Default empty.
2310    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2311    pub forbids_flags: Vec<FlagId>,
2312    /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison must
2313    /// hold for this gate to be open. The third field of the one gate, carried by
2314    /// every gate consumer — never by the verb that first wanted it. Default
2315    /// empty, so a pre-0.10 campaign is byte-identical.
2316    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2317    pub requires_state: Vec<StateCompare>,
2318}
2319
2320impl Trap {
2321    /// `(item, count)` if this trap declares a legacy `dispense` effect.
2322    pub fn dispense(&self) -> Option<(&str, u32)> {
2323        match &self.effect {
2324            Some(TrapEffect::Dispense { item, count }) => Some((item.as_str(), *count)),
2325            None => None,
2326        }
2327    }
2328
2329    /// Whether this trap is `lethal` (carries the `DW0342` obligation on the
2330    /// forced critical path).
2331    pub fn is_lethal(&self) -> bool {
2332        matches!(self.lethality, Lethality::Lethal)
2333    }
2334}
2335
2336/// The mechanism that springs a [`Trap`] (DSL v0.6, spec-0011). All three are
2337/// redstone-native — the hardware fires without any command — so the compiler
2338/// emits no detection for them; it only models the trigger cell as a hazard and
2339/// fills the dispenser payload. (`approach`, the compiler-detected v0.4 primitive,
2340/// is deliberately *not* a trap trigger: it is already fully expressible as an
2341/// [`EnvTrigger`], so admitting it here would only duplicate that surface.)
2342#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2343#[serde(rename_all = "kebab-case")]
2344pub enum TrapTrigger {
2345    /// A pressure plate: any entity stepping on the cell. Auto-rearms on step-off.
2346    PressurePlate,
2347    /// A tripwire line: any entity crossing it. Auto-rearms.
2348    Tripwire,
2349    /// A trapped chest: a *player opening it* (comparator pulse). The only
2350    /// player-distinct trigger — a controlled mob cannot spring it.
2351    TrappedChest,
2352}
2353
2354impl TrapTrigger {
2355    /// The kebab tag (`pressure-plate` / `tripwire` / `trapped-chest`).
2356    pub fn kind(&self) -> &'static str {
2357        match self {
2358            TrapTrigger::PressurePlate => "pressure-plate",
2359            TrapTrigger::Tripwire => "tripwire",
2360            TrapTrigger::TrappedChest => "trapped-chest",
2361        }
2362    }
2363}
2364
2365/// What a [`Trap`] does when sprung (DSL v0.6, spec-0011). Externally tagged so a
2366/// future effect adds a variant; a non-`dispense` key (e.g. `tnt`,
2367/// `release-falling-block`, `crusher`) is an unknown variant → `DW0100`, keeping
2368/// block-destroying and unmodeled effects out of the schema by construction
2369/// (spec-0011 non-goals — no hardware the compiler cannot model reaches a world).
2370#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2371#[serde(rename_all = "kebab-case", deny_unknown_fields)]
2372pub enum TrapEffect {
2373    /// Load the prefab's pre-wired dispenser with `count` of `item` (arrows, tipped
2374    /// arrows, splash potions). The redstone fires it; terrain is untouched
2375    /// (spec-0011 "primary lethal"). The item is round-tripped into the dispenser
2376    /// `Items` NBT — a deterministic, static payload.
2377    Dispense {
2378        /// Vanilla item id (validated against the pinned 1.21.11 registry, `DW0341`).
2379        item: String,
2380        /// How many to load into the dispenser stack.
2381        count: u32,
2382    },
2383}
2384
2385/// How dangerous a [`Trap`] is (DSL v0.6, spec-0011). Only `lethal` carries the
2386/// forced-critical-path completability obligation (`DW0342`).
2387#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2388#[serde(rename_all = "kebab-case")]
2389pub enum Lethality {
2390    /// Can kill a full-health player — carries the `DW0342` obligation on the path.
2391    Lethal,
2392    /// Hurts but is not designed to kill (the default).
2393    #[default]
2394    Harmful,
2395    /// Cosmetic / trivial (a stumble, a scare).
2396    Nonlethal,
2397}
2398
2399/// Whether a [`Trap`] re-arms after firing (DSL v0.6, spec-0011).
2400#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2401#[serde(rename_all = "kebab-case")]
2402pub enum TrapReset {
2403    /// Fires once, then is spent — the survivability path for a forced lethal trap
2404    /// (respawn-safe with `keep_inventory`, non-re-triggering on the walk back; no
2405    /// soft-loop).
2406    Once,
2407    /// Re-fires every time the trigger is met (default). A forced lethal `rearm`
2408    /// trap must be avoidable or disarmable, else `DW0342`.
2409    #[default]
2410    Rearm,
2411}
2412
2413/// A [`Trap`]'s disarm affordance (DSL v0.6, spec-0011): the player acts on the
2414/// `via` anchor (an interaction the compiler emits, reusing the v0.4 interaction
2415/// entity) to turn the trap off — setting `sets_flag` and emptying the dispenser —
2416/// before the trap cell is forced. Discharges the `DW0342` obligation when the
2417/// affordance is reachable ahead of the trap without crossing it.
2418#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2419#[serde(deny_unknown_fields)]
2420pub struct TrapDisarm {
2421    /// The anchor the player interacts with to disarm.
2422    pub via: AnchorId,
2423    /// The flag set when the trap is disarmed (a new flag this trap produces; other
2424    /// objectives/triggers may read it via `requires_flags`).
2425    pub sets_flag: FlagId,
2426}
2427
2428/// A stage-5 **timed gate** (spec-0016 §4): a gate region driven by a
2429/// deterministic open/close clock, so passage is a timing read rather than a
2430/// permanent state.
2431///
2432/// **The proof is deliberately NOT all-phase passability** — a gate that
2433/// punishes bad timing is the entire point. What the
2434/// compiler requires is that the gate is *readable*: the set of entry phases from
2435/// which a walking player clears the span before it shuts must cover **≥ 20% of
2436/// the cycle** (`DW0378`). Below that it is a coin flip, not a skill, and no
2437/// amount of learning the level makes it fair.
2438#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2439#[serde(deny_unknown_fields)]
2440pub struct TimedGate {
2441    /// Unique timed-gate id (`timed-gate/<kebab>`).
2442    pub id: TimedGateId,
2443    /// The gate anchor the clock drives. Its prefab metadata must declare a fill
2444    /// `block` (`DW0343`), the same requirement `close-gate` and `shortcut` have.
2445    pub gate: AnchorId,
2446    /// Ticks the gate stays OPEN each cycle (> 0).
2447    pub open_ticks: u32,
2448    /// Ticks the gate stays CLOSED each cycle (> 0).
2449    pub closed_ticks: u32,
2450    /// Ticks after world init before the first open window begins (default 0) —
2451    /// how two gates in the same room are put out of step with each other. Must
2452    /// be less than the full cycle.
2453    #[serde(default, skip_serializing_if = "is_zero")]
2454    pub phase: u32,
2455    /// Whether the gate **kills** a player caught inside its region when it
2456    /// shuts (spec-0016 §4 addendum). A portcullis
2457    /// that merely shoves you aside teaches nothing; mistiming the crossing is
2458    /// supposed to be a death you learn from, which is the whole point of §4's
2459    /// ≥20%-of-cycle window proof — the window is fair, so the penalty can be
2460    /// absolute.
2461    ///
2462    /// This is a real judgement issued by command on the closing tick, not
2463    /// suffocation: vanilla's in-wall damage is slow, gear-dependent and
2464    /// escapable, so it would make the portcullis a suggestion. `damage` at the
2465    /// closing edge is exact and unarguable.
2466    ///
2467    /// **Defaults to `false`**, so every campaign authored before this field
2468    /// existed compiles byte-identically; a delve opts its portcullis in.
2469    #[serde(default, skip_serializing_if = "is_false")]
2470    pub crush: bool,
2471    /// Optional **disarm** affordance (souls dossier §5.2): the third
2472    /// rung of the hazard ladder — readable, avoidable, and finally *disable-able*.
2473    /// The real games' best timed hazards can be removed for good (Smouldering
2474    /// Lake's ballista, the Fringefolk chariot); a clock the party can only ever
2475    /// dance with is one rung short of the vocabulary.
2476    ///
2477    /// Interacting with the affordance suppresses the clock **permanently, with
2478    /// the gate resting OPEN** — a jammed portcullis stays up. Permanence is
2479    /// structural exactly as a `shortcut`'s is: no emitted function ever re-arms
2480    /// the clock, and `DW0389` refuses a campaign that spells a re-seal.
2481    ///
2482    /// **Defaults to absent**, so every campaign authored before this field
2483    /// existed compiles byte-identically; a delve opts its portcullis in.
2484    #[serde(default, skip_serializing_if = "Option::is_none")]
2485    pub disarm: Option<TimedGateDisarm>,
2486}
2487
2488/// A [`TimedGate`]'s disarm affordance (souls dossier §5.2) — the
2489/// exact shape a trap's [`TrapDisarm`] takes, and deliberately so: one affordance
2490/// grammar for every mechanism the party can switch off.
2491///
2492/// The player acts on the `via` anchor (a compiler-emitted interaction entity
2493/// plus its visible hardware, `DW0420`) to jam the gate. The clock stops with the
2494/// span cleared, `sets_flag` is raised party-wide, and nothing in the delve can
2495/// put the gate back.
2496#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2497#[serde(deny_unknown_fields)]
2498pub struct TimedGateDisarm {
2499    /// The anchor the player interacts with to jam the gate. Must be an anchor
2500    /// some area's prefab provides, and never the gate anchor itself — the
2501    /// mechanism belongs beside the doorway, not inside the span that crushes.
2502    pub via: AnchorId,
2503    /// The flag set when the gate is disarmed (a new flag this gate produces;
2504    /// other objectives/triggers may read it via `requires_flags`).
2505    pub sets_flag: FlagId,
2506}
2507
2508/// serde `skip_serializing_if` helper: skip a `0`.
2509fn is_zero(n: &u32) -> bool {
2510    *n == 0
2511}
2512
2513/// A stage-5 **ambush** (spec-0016 §3) — one declaration for a beat that
2514/// otherwise takes a deferred actor set plus a hand-wired trigger.
2515///
2516/// **`telegraph` is optional, and that is a design ruling, not an oversight.**
2517/// The un-telegraphed ambush — the shove off the cliff you
2518/// could not have known about — is core souls vocabulary: 初见杀 is how the level
2519/// teaches. The engine does not sand that edge off.
2520///
2521/// What the engine *does* owe the player is **counterplay on the retry**: having
2522/// died once, an informed player must have something to do about it. Determinism
2523/// guarantees the second attempt meets the same ambushers in the same cells; the
2524/// compiler adds the missing half — `DW0376` proves the trigger cell is not a
2525/// sealed pocket, i.e. that with every ambusher standing where it will stand,
2526/// a route out still exists (a retreat, luring ground, a positioning line).
2527/// Dying uninformed is a lesson; dying with no play available is a broken beat.
2528#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2529#[serde(deny_unknown_fields)]
2530pub struct Ambush {
2531    /// Unique ambush id (`ambush/<kebab>`).
2532    pub id: AmbushId,
2533    /// The anchor the trigger watches — the corner, doorway or ledge the player
2534    /// walks into.
2535    pub at: AnchorId,
2536    /// The stage-5 actors that spring (1..N). Each is summoned at its own
2537    /// declared anchor and immediately unleashed to real AI.
2538    pub actors: Vec<ActorId>,
2539    /// What springs it (`approach{range}` / `strike` / `use`), exactly the v0.4
2540    /// environment-trigger vocabulary.
2541    pub trigger: TriggerOn,
2542    /// The **optional** tell, fired at the trigger before the ambushers exist:
2543    /// a sound, a shadow, a line of narration. Empty = un-telegraphed, which is
2544    /// fully legal.
2545    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2546    pub telegraph: Vec<QuestEffect>,
2547    /// What the spring does to the story (DSL v0.8, spec-0025; required at
2548    /// 0.8.0, `DW0481`).
2549    ///
2550    /// **The declaration lives here because this is the object the author
2551    /// wrote.** An ambush desugars into a `spawn-actor` plus an `unleash-actor`
2552    /// per listed actor, and every one of those is a story node `DW0481` demands
2553    /// a `happening` from — on effects the author never wrote and cannot reach.
2554    /// So for as long as this field did not exist, an `ambushes[]` entry could
2555    /// not compile at 0.8.0 or above at all: declared in the schema, accepted by
2556    /// the schema check, and refused at validation with a prescription naming a
2557    /// field that was not there. Nothing caught it because no campaign and no
2558    /// fixture had ever written an ambush at a version where the obligation was
2559    /// live — which is the case spec-0039 exists to make impossible.
2560    ///
2561    /// An ambush is **one** beat, not `2N` of them: the ambushers appearing and
2562    /// coming at you is a single dramatic moment, so one declaration covers the
2563    /// whole spring. [`Self::to_trigger`] stamps it onto the first generated
2564    /// `spawn-actor` so the chronicle carries the line at the right position,
2565    /// and `branch::check_happenings` reads the obligation off the ambush rather
2566    /// than off the beats derived from it. Repeating it on all `2N` is the
2567    /// obvious alternative and it is wrong twice over: the chronicle would gain
2568    /// `N` duplicate lines, and `DW0485` would see one subject act repeatedly
2569    /// and be right to call it a contradiction.
2570    #[serde(default, skip_serializing_if = "Option::is_none")]
2571    pub happening: Option<Happening>,
2572}
2573
2574impl Ambush {
2575    /// The environment trigger this ambush desugars to (spec-0016 §3): a
2576    /// one-shot trigger at `at` whose effects are the telegraph, then a
2577    /// `spawn-actor` + `unleash-actor` per listed actor, in declared order.
2578    ///
2579    /// This is the **single** expansion authority. Every consumer — validation,
2580    /// the l10n inventory, the flag/wave producer scans, nav, emission — reads
2581    /// triggers through [`QuestsContent::all_triggers`], so the sugar cannot
2582    /// diverge from a hand-written equivalent, and an ambush is exactly as
2583    /// debuggable as the trigger an author would otherwise type.
2584    pub fn to_trigger(&self) -> EnvTrigger {
2585        let mut effects = self.telegraph.clone();
2586        for (i, a) in self.actors.iter().enumerate() {
2587            effects.push(QuestEffect {
2588                when: None,
2589                // The ambush declaration, on the beat where the spring becomes
2590                // real. Only the FIRST, for the reason the field documents: one
2591                // ambush is one beat, and stamping the line on every generated
2592                // effect would pad the chronicle and trip `DW0485`.
2593                happening: if i == 0 { self.happening.clone() } else { None },
2594                verb: Verb::SpawnActor { actor: a.clone() },
2595            });
2596        }
2597        for a in &self.actors {
2598            effects.push(Verb::UnleashActor { actor: a.clone() }.into());
2599        }
2600        EnvTrigger {
2601            id: TriggerId(format!(
2602                "trigger/{}",
2603                crate::l10n::local_id(self.id.as_str())
2604            )),
2605            at: Some(self.at.clone()),
2606            on: self.trigger.clone(),
2607            requires_flags: Vec::new(),
2608            forbids_flags: Vec::new(),
2609            requires_state: Vec::new(),
2610            once: true,
2611            // An ambush is a party beat by construction — it springs actors at
2612            // the room, not a reply to the one who walked in.
2613            audience: TriggerAudience::Party,
2614            effects,
2615        }
2616    }
2617}
2618
2619/// A stage-5 **shortcut door** (spec-0016 §2) — the souls loop-back.
2620///
2621/// The owner's definition of the pattern: between two rest points there are two
2622/// routes. The **short** one starts sealed and holds nothing; the **long** one is
2623/// full of enemies and mechanisms. You earn the far side the hard way, pull one
2624/// mechanism, and the short route opens **forever**. That moment is the design.
2625///
2626/// The compiler owns three obligations, none of them optional:
2627/// 1. the `unlock` affordance is reachable while the gate is still sealed — the
2628///    long route genuinely exists (`DW0373`);
2629/// 2. opening the gate genuinely shortens the trip across it — a shortcut that
2630///    pays nothing is a leak, not a shortcut (`DW0360`);
2631/// 3. permanence is **structural**: no `close-gate` may target a shortcut gate
2632///    (`DW0372`). There is no re-sealing verb to reach for.
2633///
2634/// `close-gate` on a NON-shortcut gate (the point-of-no-return staging beat) is
2635/// untouched by this — the two verbs are deliberately disjoint.
2636#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2637#[serde(deny_unknown_fields)]
2638pub struct Shortcut {
2639    /// Unique shortcut id (`shortcut/<kebab>`).
2640    pub id: ShortcutId,
2641    /// The gate anchor this shortcut opens. Sealed from world-load (the prefab
2642    /// carries the physical fill), and its metadata must declare the fill `block`
2643    /// the compiler clears — the same requirement `close-gate` has.
2644    pub gate: AnchorId,
2645    /// The FAR-side anchor whose interaction fires the permanent open. The
2646    /// compiler summons the affordance there and polls it, reusing the v0.4
2647    /// interaction-entity `use` primitive.
2648    pub unlock: AnchorId,
2649    /// Effects fired once, when the shortcut opens — the bar lifting, the
2650    /// elevator descending, the sound of a door you will never have to earn
2651    /// again. Emitted server-source-safe (the poll lives on the tick).
2652    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2653    pub on_unlock: Vec<QuestEffect>,
2654}
2655
2656/// A stage-5 environment trigger (DSL v0.4). Emission uses vanilla-intended
2657/// primitives only (spec-0008 §7): `strike`/`use` read a `minecraft:interaction`
2658/// entity's attack/interaction records; `approach` is a `distance` selector on
2659/// the tick. Look-at / break-attempt detection is excluded on principle (no
2660/// vanilla primitive).
2661#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2662#[serde(deny_unknown_fields)]
2663pub struct EnvTrigger {
2664    /// Unique trigger id (`trigger/<kebab>`).
2665    pub id: TriggerId,
2666    /// The anchor this trigger watches. Required for `strike` / `use` /
2667    /// `approach`, which watch a *place*; **absent** for `strike-npc` (DSL
2668    /// v0.6), which watches a *character* and names it in `on.npc` instead —
2669    /// there is no cell for the author to supply and no cell the compiler
2670    /// would use. Either mismatch is `DW0194`.
2671    #[serde(default, skip_serializing_if = "Option::is_none")]
2672    pub at: Option<AnchorId>,
2673    /// The event that fires it.
2674    pub on: TriggerOn,
2675    /// Flags that must be set before the trigger can fire (DSL v0.4).
2676    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2677    pub requires_flags: Vec<FlagId>,
2678    /// Negative flag gate (DSL v0.6): the trigger is
2679    /// **suppressed** while ANY listed flag is set (by any player — flags are
2680    /// campaign state). The dual of `requires_flags`, so an "armed between two
2681    /// story beats" trigger needs no re-arm plumbing: e.g. a strike-the-giant
2682    /// retaliation trigger with `requires_flags: [flag/sealed]` and
2683    /// `forbids_flags: [flag/asleep]` arms when the cave seals and stands down
2684    /// the moment the wake beat takes over.
2685    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2686    pub forbids_flags: Vec<FlagId>,
2687    /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison must
2688    /// hold for this gate to be open. The third field of the one gate, carried by
2689    /// every gate consumer — never by the verb that first wanted it. Default
2690    /// empty, so a pre-0.10 campaign is byte-identical.
2691    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2692    pub requires_state: Vec<StateCompare>,
2693    /// Fire at most once (default `true`, mirroring objective completion). Set
2694    /// `false` to allow re-firing every time the condition is met.
2695    #[serde(default = "default_true")]
2696    pub once: bool,
2697    /// **Who the trigger's effects address** (DSL v0.11). Default
2698    /// [`TriggerAudience::Party`], so every campaign written before this field
2699    /// existed is byte-identical.
2700    ///
2701    /// A trigger is two different things depending on what the author means by
2702    /// it. A pressure plate that opens a gate and narrates the room is a **party
2703    /// beat**: everyone should see it, and it does not matter who stepped on the
2704    /// plate. A barred door that answers *"this cannot be opened from this
2705    /// side"* is a **reply to one person**: broadcasting it tells four players
2706    /// about a door three of them are nowhere near.
2707    ///
2708    /// Until this field the second was inexpressible, which is why the two verbs
2709    /// that needed it (`close-gate`'s seal answer, and nothing at all for a
2710    /// shortcut door) grew their own private reply machinery instead. The
2711    /// capability belongs to the press, not to the verb.
2712    #[serde(default, skip_serializing_if = "TriggerAudience::is_party")]
2713    pub audience: TriggerAudience,
2714    /// Effects fired when the trigger matches.
2715    pub effects: Vec<QuestEffect>,
2716}
2717
2718impl EnvTrigger {
2719    /// The anchor this trigger watches, if it watches a place at all. `None`
2720    /// for `strike-npc`, whose target is a character.
2721    pub fn at_anchor(&self) -> Option<&str> {
2722        self.at.as_ref().map(|a| a.as_str())
2723    }
2724
2725    /// Whether this trigger's bundle is addressed to the player who pressed it.
2726    pub fn addresses_presser(&self) -> bool {
2727        self.audience == TriggerAudience::Presser
2728    }
2729}
2730
2731/// Who an [`EnvTrigger`]'s effects address (DSL v0.11).
2732///
2733/// **This is a dispatch decision, not a cosmetic one.** A `party` trigger is
2734/// polled on the tick with no executor, so `@s` does not exist and every
2735/// player-facing command addresses `@a`. A `presser` trigger is dispatched by a
2736/// `minecraft:player_interacted_with_entity` advancement — the one vanilla
2737/// primitive that runs a function *as the player who clicked* — so `@s` is the
2738/// presser and the bundle addresses them alone.
2739///
2740/// That primitive exists for **right-clicks only**. Vanilla records a left-click
2741/// on an interaction entity in NBT (which names a UUID no command can become) and
2742/// offers no criterion for it, so `presser` on a `strike` is refused (`DW0427`)
2743/// rather than approximated: per CLAUDE.md's no-hack rule, a capability with no
2744/// vanilla primitive under it is excluded, never faked downstream.
2745#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2746#[serde(rename_all = "kebab-case")]
2747pub enum TriggerAudience {
2748    /// The whole party (the default, and what every trigger did before v0.11).
2749    #[default]
2750    Party,
2751    /// The one player whose click fired it.
2752    Presser,
2753}
2754
2755impl TriggerAudience {
2756    /// Serde skip predicate: the default needs no field on the wire, so a
2757    /// canonical round-trip of a pre-0.11 campaign is byte-identical.
2758    fn is_party(&self) -> bool {
2759        *self == TriggerAudience::Party
2760    }
2761}
2762
2763/// The event an [`EnvTrigger`] watches (DSL v0.4).
2764#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2765#[serde(tag = "on", rename_all = "kebab-case", deny_unknown_fields)]
2766pub enum TriggerOn {
2767    /// The player attacks (left-clicks) the interaction entity at the anchor.
2768    Strike,
2769    /// The player uses (right-clicks) the interaction entity at the anchor.
2770    Use,
2771    /// The player comes within `range` blocks of the anchor.
2772    Approach {
2773        /// Approach radius (blocks).
2774        range: u32,
2775    },
2776    /// The player attacks (left-clicks) an **NPC's body** (DSL v0.6).
2777    ///
2778    /// The place-based [`TriggerOn::Strike`] cannot express "hit the giant": it
2779    /// summons its own `minecraft:interaction` at a *cell*, and a large NPC's
2780    /// body eclipses that cell (`DW0359`), so the click never reaches the
2781    /// trigger — the owner's island round-7 finding. This form has no cell. It
2782    /// rides the interaction entity the NPC already owns, which is the entity a
2783    /// click on that NPC reaches by construction.
2784    ///
2785    /// Right-click and left-click stay separate all the way down: a
2786    /// `minecraft:interaction` records them in two distinct NBT fields
2787    /// (`interaction` and `attack`), so the NPC's dialogue keeps the right-click
2788    /// and this trigger takes the left-click, on one shared hitbox.
2789    StrikeNpc {
2790        /// The NPC (stage-2 ref) whose body is the target.
2791        npc: NpcId,
2792    },
2793}
2794
2795impl TriggerOn {
2796    /// The kebab tag (`strike` / `use` / `approach` / `strike-npc`).
2797    pub fn kind(&self) -> &'static str {
2798        match self {
2799            TriggerOn::Strike => "strike",
2800            TriggerOn::Use => "use",
2801            TriggerOn::Approach { .. } => "approach",
2802            TriggerOn::StrikeNpc { .. } => "strike-npc",
2803        }
2804    }
2805
2806    /// Whether this event needs an `at` anchor — true for everything that
2807    /// watches a place, false for `strike-npc`, which watches a character.
2808    pub fn needs_anchor(&self) -> bool {
2809        !matches!(self, TriggerOn::StrikeNpc { .. })
2810    }
2811
2812    /// The NPC whose body this event watches (`strike-npc` only).
2813    pub fn npc_target(&self) -> Option<&NpcId> {
2814        match self {
2815            TriggerOn::StrikeNpc { npc } => Some(npc),
2816            _ => None,
2817        }
2818    }
2819}
2820
2821/// A combat wave (DSL v0.3): a bundle of mobs spawned at an anchor and slain to
2822/// complete a `kill` objective. Emission (spec-0002): a `spawn-wave` effect
2823/// summons the mobs tagged `dw_wave_<id>` (AI enabled — they fight); a
2824/// `player_killed_entity` advancement per tag decrements a scoreboard countdown,
2825/// and the `kill` objective completes when the count reaches zero.
2826#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2827#[serde(deny_unknown_fields)]
2828pub struct Wave {
2829    /// Unique wave id.
2830    pub id: WaveId,
2831    /// The anchor the wave's mobs spawn at.
2832    pub anchor: AnchorId,
2833    /// The mobs that make up the wave (1..N).
2834    pub mobs: Vec<WaveMob>,
2835    /// Re-seat this wave every time the party rests at (or respawns from) a
2836    /// bonfire (spec-0016 §1) — the souls contract: progress is kept, the
2837    /// enemies come back. The compiler kills any survivor carrying the wave tag
2838    /// and re-runs the wave's own spawn function, so the room is restored to its
2839    /// authored composition and spawn cells.
2840    ///
2841    /// Inert without a `bonfire` in the campaign, which is a compile error
2842    /// (`DW0370`) rather than a silent no-op.
2843    #[serde(default, skip_serializing_if = "is_false")]
2844    pub respawns_on_rest: bool,
2845    /// Tower-defense lane routing (spec-0016 §6): march this wave along a
2846    /// waypoint polyline while distant, hand it to native AI the instant a
2847    /// player is inside `aggro_radius`. Absent = today's behaviour (spawn and
2848    /// stand), byte-identical.
2849    #[serde(default, skip_serializing_if = "Option::is_none")]
2850    pub lane: Option<WaveLane>,
2851    /// Where the wave's mobs materialize (spec-0016 §6). Absent =
2852    /// [`WaveSummon::Anchor`], the pre-0.6 behaviour: standable cells around the
2853    /// wave `anchor`.
2854    #[serde(default, skip_serializing_if = "Option::is_none")]
2855    pub summon: Option<WaveSummon>,
2856    /// How hard this encounter is *meant* to be (DSL v0.7, spec-0023). Absent =
2857    /// [`EncounterTier::Ordinary`], byte-identical to every pre-0.7 campaign.
2858    ///
2859    /// This is a **declaration, not a knob**: the compiler never scales content
2860    /// from it (spec-0023 "Out of scope"). It exists because the validation
2861    /// ladder's inverted floor gate needs to know which fights the content
2862    /// *claims* are hard — an `elite`/`boss` encounter the unassisted bot beats
2863    /// on its first attempt is reported as too easy for its billing. Marking it
2864    /// is how the author opts into that scrutiny; the alternative — inferring
2865    /// "elite" from how tuned a stack looks — is exactly the downstream folklore
2866    /// CLAUDE.md's no-hack rule forbids.
2867    ///
2868    /// **It does reach emission in exactly one place** (spec-0016 §1): in a
2869    /// campaign with a `bonfire`, a billed `elite`/
2870    /// `boss` wave that does not declare `respawns_on_rest` is refreshed by a
2871    /// rest *while it is still standing* — deleted and re-seated at full count
2872    /// and full health, so chipping it down one life at a time is never a path.
2873    /// Beat it and it stays beaten. `DW0499` forbids billing a wave `boss` and
2874    /// `respawns_on_rest` at once.
2875    #[serde(default, skip_serializing_if = "Option::is_none")]
2876    pub tier: Option<EncounterTier>,
2877}
2878
2879/// What a wave is billed as (DSL v0.7, spec-0023). Consumed by the validation
2880/// ladder (the run's combat plan) and — since spec-0016 §1's undefeated re-seat
2881/// — by one emission site: a bonfire refreshes a billed wave that is still
2882/// standing. Nothing about the encounter itself is scaled from it.
2883#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2884#[serde(rename_all = "kebab-case")]
2885pub enum EncounterTier {
2886    /// Trash / pressure. No floor expectation: a bot that wins it cold proves
2887    /// nothing either way. The default.
2888    #[default]
2889    Ordinary,
2890    /// A set-piece the content bills as a hard fight (spec-0016's optional-elite
2891    /// and spawn-and-unleash vocabulary).
2892    Elite,
2893    /// A campaign's named fight. Same floor rule as `elite`; the distinction is
2894    /// for the run report a human reads.
2895    Boss,
2896}
2897
2898impl EncounterTier {
2899    /// The kebab tag, as it appears in the DSL and in the emitted combat plan.
2900    pub fn token(self) -> &'static str {
2901        match self {
2902            EncounterTier::Ordinary => "ordinary",
2903            EncounterTier::Elite => "elite",
2904            EncounterTier::Boss => "boss",
2905        }
2906    }
2907
2908    /// Does the inverted floor gate (spec-0023) apply to this tier? A fight the
2909    /// content bills as hard carries an expectation the bot can measure; an
2910    /// ordinary one does not.
2911    pub fn has_floor_expectation(self) -> bool {
2912        matches!(self, EncounterTier::Elite | EncounterTier::Boss)
2913    }
2914}
2915
2916/// Where a wave's mobs materialize (spec-0016 §6).
2917#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
2918#[serde(rename_all = "kebab-case")]
2919pub enum WaveSummon {
2920    /// Standable cells around the wave `anchor`, nearest first — the pre-0.6
2921    /// behaviour and the default.
2922    Anchor,
2923    /// **Spirit-summoned at the edge of perception**:
2924    /// each mob appears on the ring at its own `attributes.follow_range` from
2925    /// the wave `anchor`, so it acquires a target the instant it exists and
2926    /// closes under pure native AI. Species without patrol AI never march a
2927    /// lane; this is what they do instead — never a spawn on top of the party,
2928    /// never a mob that brushes past.
2929    ///
2930    /// With this mode the wave `anchor` is the **defended point** (what the ring
2931    /// is drawn around), not the spawn point. Each mob stack must declare its
2932    /// own `attributes.follow_range` (`DW0385`) — the ring radius is authored,
2933    /// never guessed from a vanilla defaults table the compiler cannot verify.
2934    AggroEdge,
2935}
2936
2937/// Tower-defense lane routing for a wave (spec-0016 §6), built on vanilla's
2938/// **Raider patrol system** — the intended primitive, live-verified on 1.21.11
2939/// (`docs/notes/td-routing-spike.md`).
2940///
2941/// The squad spawns `Patrolling:1b` with one `PatrolLeader:1b` and a snake_case
2942/// `patrol_target` int-array; a compiler-emitted clock walks the shared waypoint
2943/// index forward, and per mob a player-proximity check releases `Patrolling:0b`.
2944/// From that instant the mob is a plain native hostile. "Combat preempts
2945/// routing" is engine semantics — vanilla's patrol goal is hard-gated on having
2946/// no target — so the owner's rule (march while distant, fight with NATIVE AI
2947/// once aggroed, never brush past) falls out of the primitive unforced.
2948///
2949/// Lanes are raider-family only (`DW0382`), squad ≥ 2 (`DW0383`), and a lane
2950/// pillager must keep its crossbow (`DW0384`).
2951#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2952#[serde(deny_unknown_fields)]
2953pub struct WaveLane {
2954    /// The lane polyline, in march order: anchors some area's prefab provides.
2955    /// At least one; consecutive legs (counting the wave `anchor` as the origin)
2956    /// must be more than 10 blocks apart — vanilla re-rolls a patrol target
2957    /// within 10 blocks of arrival, so a tighter lane is a lane the engine
2958    /// quietly stops following (`DW0386`).
2959    pub waypoints: Vec<AnchorId>,
2960    /// The release radius, in blocks: the compiler sets every lane mob's
2961    /// `follow_range` attribute to exactly this and releases `Patrolling:0b`
2962    /// at the same distance. The two MUST be equal — a patrolling raider that
2963    /// targets a player it cannot engage holds ground instead of marching, so a
2964    /// per-mob `attributes.follow_range` that disagrees is `DW0381`.
2965    pub aggro_radius: u32,
2966}
2967
2968/// One mob stack in a [`Wave`].
2969#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
2970#[serde(deny_unknown_fields)]
2971pub struct WaveMob {
2972    /// Vanilla entity id, validated against the pinned 1.21.11 registry.
2973    pub entity: String,
2974    /// How many to spawn.
2975    pub count: u32,
2976    /// Optional custom name (shown above the mob).
2977    #[serde(default, skip_serializing_if = "Option::is_none")]
2978    pub name: Option<String>,
2979    /// Optional attribute overrides (DSL v0.4), emitted as 1.21.11 attribute
2980    /// components. Enables e.g. a weakened live warden as a survivable stealth
2981    /// threat. Omitted = vanilla defaults.
2982    #[serde(default, skip_serializing_if = "Option::is_none")]
2983    pub attributes: Option<MobAttributes>,
2984    /// Optional permanent, ambient status effects (DSL v0.4).
2985    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2986    pub effects: Vec<MobEffect>,
2987    /// Optional worn/held equipment (DSL v0.6). A helmet is the
2988    /// sanctioned fix for daylight-burning undead — never
2989    /// `set-time`. Item ids validate against the pinned 1.21.11 item registry
2990    /// (`DW0143`, the give-item family); every emitted slot carries drop
2991    /// chance 0 so players can never farm wave gear (no-grind constitution).
2992    #[serde(default, skip_serializing_if = "Option::is_none")]
2993    pub equipment: Option<MobEquipment>,
2994    /// What this mob leaves behind when it dies (DSL v0.9). Only an `elite`/`boss` wave may declare it (`DW0491`)
2995    /// — an ordinary mob's kit is never farmable. Empty = drop chance 0 on
2996    /// every slot.
2997    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2998    pub drops: Vec<MobDrop>,
2999}
3000
3001/// Worn/held equipment for a wave mob (DSL v0.6). Each field is a vanilla item
3002/// id for the matching vanilla equipment slot; an unset slot stays empty —
3003/// except `main_hand`, where the compiler's armed-mob default (skeleton bow,
3004/// wither-skeleton sword) still applies unless overridden. Emitted as the
3005/// component-era `equipment`/`drop_chances` summon NBT (1.21.11 silently
3006/// ignores legacy `ArmorItems`/`HandItems` on `/summon`), all drop chances 0.
3007#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3008#[serde(deny_unknown_fields)]
3009pub struct MobEquipment {
3010    /// Head slot.
3011    #[serde(default, skip_serializing_if = "Option::is_none")]
3012    pub head: Option<EquipItem>,
3013    /// Chest slot.
3014    #[serde(default, skip_serializing_if = "Option::is_none")]
3015    pub chest: Option<EquipItem>,
3016    /// Legs slot.
3017    #[serde(default, skip_serializing_if = "Option::is_none")]
3018    pub legs: Option<EquipItem>,
3019    /// Feet slot.
3020    #[serde(default, skip_serializing_if = "Option::is_none")]
3021    pub feet: Option<EquipItem>,
3022    /// Main-hand slot. Overrides the compiler's armed-mob default.
3023    #[serde(default, skip_serializing_if = "Option::is_none")]
3024    pub main_hand: Option<EquipItem>,
3025    /// Off-hand slot.
3026    #[serde(default, skip_serializing_if = "Option::is_none")]
3027    pub off_hand: Option<EquipItem>,
3028}
3029
3030impl MobEquipment {
3031    /// Every slot as `(dsl_field_name, piece)`, in the fixed schema order —
3032    /// the single iteration source for validation paths and emission.
3033    pub fn slots(&self) -> [(&'static str, Option<&EquipItem>); 6] {
3034        [
3035            ("head", self.head.as_ref()),
3036            ("chest", self.chest.as_ref()),
3037            ("legs", self.legs.as_ref()),
3038            ("feet", self.feet.as_ref()),
3039            ("main_hand", self.main_hand.as_ref()),
3040            ("off_hand", self.off_hand.as_ref()),
3041        ]
3042    }
3043
3044    /// The piece this equipment declaration puts in `slot`, if any. The single
3045    /// question a `drops[]` `slot` entry asks: a mob can only drop a piece it
3046    /// actually wears (`DW0490`).
3047    pub fn filled(&self, slot: EquipSlot) -> Option<&EquipItem> {
3048        match slot {
3049            EquipSlot::Head => self.head.as_ref(),
3050            EquipSlot::Chest => self.chest.as_ref(),
3051            EquipSlot::Legs => self.legs.as_ref(),
3052            EquipSlot::Feet => self.feet.as_ref(),
3053            EquipSlot::MainHand => self.main_hand.as_ref(),
3054            EquipSlot::OffHand => self.off_hand.as_ref(),
3055        }
3056    }
3057}
3058
3059/// One vanilla equipment slot, named exactly as the [`MobEquipment`] field that
3060/// fills it (DSL v0.9). The DSL name and the summon-NBT key differ
3061/// (`main_hand` vs `mainhand`), so both live here and nowhere else.
3062#[derive(
3063    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
3064)]
3065#[serde(rename_all = "snake_case")]
3066pub enum EquipSlot {
3067    /// Head slot.
3068    Head,
3069    /// Chest slot.
3070    Chest,
3071    /// Legs slot.
3072    Legs,
3073    /// Feet slot.
3074    Feet,
3075    /// Main-hand slot.
3076    MainHand,
3077    /// Off-hand slot.
3078    OffHand,
3079}
3080
3081impl EquipSlot {
3082    /// The DSL field name (`main_hand`), for diagnostics and JSON pointers.
3083    pub fn field(self) -> &'static str {
3084        match self {
3085            EquipSlot::Head => "head",
3086            EquipSlot::Chest => "chest",
3087            EquipSlot::Legs => "legs",
3088            EquipSlot::Feet => "feet",
3089            EquipSlot::MainHand => "main_hand",
3090            EquipSlot::OffHand => "off_hand",
3091        }
3092    }
3093
3094    /// The 1.21.11 `equipment` / `drop_chances` NBT key (`mainhand`).
3095    pub fn nbt(self) -> &'static str {
3096        match self {
3097            EquipSlot::Head => "head",
3098            EquipSlot::Chest => "chest",
3099            EquipSlot::Legs => "legs",
3100            EquipSlot::Feet => "feet",
3101            EquipSlot::MainHand => "mainhand",
3102            EquipSlot::OffHand => "offhand",
3103        }
3104    }
3105}
3106
3107/// One declared drop of an elite or boss (DSL v0.9).
3108///
3109/// A mob may wear many pieces; what it *leaves behind* is a **declared subset**,
3110/// usually one piece and never automatically everything. Two forms, told apart
3111/// by which field is present:
3112///
3113/// ```json
3114/// { "slot": "main_hand" }                                  // its axe
3115/// { "item": "minecraft:tripwire_hook", "name": "Gate Key" } // a quest item
3116/// ```
3117///
3118/// A `slot` entry must name a slot the same entity's `equipment` really fills
3119/// (`DW0490`) — the drop is the piece the player has been *looking at* through
3120/// the whole fight, so the two declarations cannot disagree. An `item` entry is
3121/// a token the fight *yields* rather than wears, and rides the entity's own
3122/// death loot table.
3123///
3124/// Undeclared slots keep drop chance `0.0` — byte-for-byte today's behaviour, and
3125/// the no-grind constitution's guarantee that an ordinary kit is never farmable.
3126#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3127#[serde(untagged)]
3128pub enum MobDrop {
3129    /// A worn/held piece, named by its equipment slot.
3130    Slot(SlotDrop),
3131    /// A quest token the fight yields (not worn).
3132    Item(ItemDrop),
3133}
3134
3135/// The worn-piece form of a [`MobDrop`].
3136#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3137#[serde(deny_unknown_fields)]
3138pub struct SlotDrop {
3139    /// The equipment slot whose piece drops. Must be filled by the entity's own
3140    /// `equipment` declaration (`DW0490`).
3141    pub slot: EquipSlot,
3142}
3143
3144/// The quest-token form of a [`MobDrop`].
3145#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3146#[serde(deny_unknown_fields)]
3147pub struct ItemDrop {
3148    /// Vanilla item id, validated against the pinned 1.21.11 registry
3149    /// (`DW0143`, the give-item family).
3150    pub item: String,
3151    /// Display name the dropped stack carries as a `custom_name` component.
3152    /// Player-visible, so it enters the l10n string inventory and translates
3153    /// like any other line.
3154    #[serde(default, skip_serializing_if = "Option::is_none")]
3155    pub name: Option<String>,
3156}
3157
3158impl MobDrop {
3159    /// The equipment slot this entry names, or `None` for a quest-item drop.
3160    pub fn slot(&self) -> Option<EquipSlot> {
3161        match self {
3162            MobDrop::Slot(s) => Some(s.slot),
3163            MobDrop::Item(_) => None,
3164        }
3165    }
3166
3167    /// The item id this entry names, or `None` for a worn-piece drop.
3168    pub fn item(&self) -> Option<&str> {
3169        match self {
3170            MobDrop::Slot(_) => None,
3171            MobDrop::Item(i) => Some(&i.item),
3172        }
3173    }
3174
3175    /// The declared display name of a quest-item drop, when set.
3176    pub fn name(&self) -> Option<&String> {
3177        match self {
3178            MobDrop::Slot(_) => None,
3179            MobDrop::Item(i) => i.name.as_ref(),
3180        }
3181    }
3182
3183    /// Mutable access to the display name — the l10n traversal's hook.
3184    pub fn name_mut(&mut self) -> Option<&mut String> {
3185        match self {
3186            MobDrop::Slot(_) => None,
3187            MobDrop::Item(i) => i.name.as_mut(),
3188        }
3189    }
3190}
3191
3192/// One equipped item: either a bare item id, or an id carrying enchantments.
3193///
3194/// The plain form is the common case and stays a plain JSON string, which is
3195/// what keeps every campaign written before enchantments existed byte-identical
3196/// on re-serialisation:
3197///
3198/// ```json
3199/// "main_hand": "minecraft:netherite_sword"
3200/// "head": { "item": "minecraft:netherite_helmet",
3201///           "enchantments": { "minecraft:protection": 4 } }
3202/// ```
3203#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3204#[serde(untagged)]
3205pub enum EquipItem {
3206    /// A bare item id — no enchantments.
3207    Plain(String),
3208    /// An item id plus its enchantments.
3209    Enchanted(EnchantedItem),
3210}
3211
3212impl EquipItem {
3213    /// The item id, whichever form was authored.
3214    pub fn item(&self) -> &str {
3215        match self {
3216            EquipItem::Plain(s) => s,
3217            EquipItem::Enchanted(e) => &e.item,
3218        }
3219    }
3220
3221    /// The enchantments on this piece — empty for the plain form. `BTreeMap`
3222    /// ordered, so emission order is the id order and never hash order
3223    /// (ADR-0006).
3224    pub fn enchantments(&self) -> &BTreeMap<String, u32> {
3225        static EMPTY: std::sync::LazyLock<BTreeMap<String, u32>> =
3226            std::sync::LazyLock::new(BTreeMap::new);
3227        match self {
3228            EquipItem::Plain(_) => &EMPTY,
3229            EquipItem::Enchanted(e) => &e.enchantments,
3230        }
3231    }
3232}
3233
3234/// The enchanted form of [`EquipItem`].
3235#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3236#[serde(deny_unknown_fields)]
3237pub struct EnchantedItem {
3238    /// Item id (e.g. `minecraft:netherite_chestplate`).
3239    pub item: String,
3240    /// Enchantment id → level (e.g. `{"minecraft:protection": 4}`). Emitted as
3241    /// the 1.21 `minecraft:enchantments` item component.
3242    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3243    pub enchantments: BTreeMap<String, u32>,
3244}
3245
3246/// Attribute overrides for a wave mob (DSL v0.4). Each field maps to a 1.21.11
3247/// `minecraft:` attribute component; an unset field keeps the vanilla base value.
3248#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3249#[serde(deny_unknown_fields)]
3250pub struct MobAttributes {
3251    /// `minecraft:max_health` base value.
3252    #[serde(default, skip_serializing_if = "Option::is_none")]
3253    pub max_health: Option<f64>,
3254    /// `minecraft:attack_damage` base value.
3255    #[serde(default, skip_serializing_if = "Option::is_none")]
3256    pub attack_damage: Option<f64>,
3257    /// `minecraft:movement_speed` base value.
3258    #[serde(default, skip_serializing_if = "Option::is_none")]
3259    pub movement_speed: Option<f64>,
3260    /// `minecraft:follow_range` base value.
3261    #[serde(default, skip_serializing_if = "Option::is_none")]
3262    pub follow_range: Option<f64>,
3263}
3264
3265/// One permanent status effect on a wave mob (DSL v0.4), emitted as an ambient,
3266/// non-expiring `effect give`.
3267#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3268#[serde(deny_unknown_fields)]
3269pub struct MobEffect {
3270    /// Vanilla effect id (e.g. `minecraft:slowness`), validated against the
3271    /// pinned registry (`DW0192`).
3272    pub effect: String,
3273    /// Amplifier (0 = level I).
3274    pub amplifier: u32,
3275}
3276
3277/// One expanded quest.
3278#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3279#[serde(deny_unknown_fields)]
3280pub struct Quest {
3281    /// Quest id (matches a stage-4 planned quest).
3282    pub id: QuestId,
3283    /// What starts the quest.
3284    pub trigger: Trigger,
3285    /// Ordered objectives (intra-quest DAG via `after`).
3286    pub objectives: Vec<Objective>,
3287    /// Effects fired when a given objective completes.
3288    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3289    pub on_objective_complete: BTreeMap<ObjectiveId, Vec<QuestEffect>>,
3290    /// Effects fired when the whole quest completes.
3291    pub on_complete: Vec<QuestEffect>,
3292    /// The **cast ledger** (DSL v0.7, spec-0020): for every stage-2 NPC that is
3293    /// live during this quest — spawned and not explicitly removed — where it
3294    /// stands, what it is doing, and what its right-click offers *for this
3295    /// quest's duration*.
3296    ///
3297    /// The ledger exists because an NPC's dialogue used to be one tree for the
3298    /// whole campaign: after the climactic escape a crew member still offered
3299    /// "Tell me what he is." — a premise question absurd once the story moved on.
3300    /// Declaring the scene per quest makes the compiler able to check it
3301    /// (`DW0460`–`DW0467`) and makes the declaration itself the gate: the
3302    /// emitted right-click shows the root this quest declares, so a stale root
3303    /// retires *because the ledger says so*, not because an author remembered a
3304    /// flag.
3305    ///
3306    /// Every NPC live during the quest owes an entry (`DW0460`).
3307    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3308    pub cast: BTreeMap<NpcId, CastEntry>,
3309    /// What this quest does to the story (DSL v0.8, spec-0025; required at 0.8.0,
3310    /// `DW0481`).
3311    #[serde(default, skip_serializing_if = "Option::is_none")]
3312    pub happening: Option<Happening>,
3313}
3314
3315/// One NPC's entry in a quest's [`cast`](Quest::cast) ledger.
3316///
3317/// Three authored shapes, tried in order (untagged): the bare keyword `"dead"` /
3318/// `"offstage"`, a single flat [`CastPlacement`], or a **list** of placements —
3319/// per-branch casts, each gated by the flags that select its branch (spec-0020
3320/// proof 4: where the effect history is branch-dependent, a single flat
3321/// declaration cannot hold on every reachable branch, and `DW0462` says so).
3322#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3323#[serde(untagged)]
3324pub enum CastEntry {
3325    /// The bare keyword form: `"npc/antiphos": "dead"`. Shorthand for a
3326    /// placement whose `at` is that keyword and which carries no `doing` or
3327    /// `dialogue` — a character who is not in the world has no business and
3328    /// answers no right-click.
3329    Absent(CastAbsence),
3330    /// A single placement that must hold on every reachable branch.
3331    Placement(CastPlacement),
3332    /// Per-branch placements (spec-0020 proof 4). Each carries the
3333    /// `requires_flags`/`forbids_flags` that select its branch.
3334    Branches(Vec<CastPlacement>),
3335}
3336
3337impl CastEntry {
3338    /// Every placement this entry declares, in declared order. The bare-keyword
3339    /// form yields none — there is no scene to check.
3340    pub fn placements(&self) -> Vec<&CastPlacement> {
3341        match self {
3342            CastEntry::Absent(_) => Vec::new(),
3343            CastEntry::Placement(p) => vec![p],
3344            CastEntry::Branches(ps) => ps.iter().collect(),
3345        }
3346    }
3347
3348    /// Every placement this entry declares, mutably (the l10n traversal).
3349    pub fn placements_mut(&mut self) -> Vec<&mut CastPlacement> {
3350        match self {
3351            CastEntry::Absent(_) => Vec::new(),
3352            CastEntry::Placement(p) => vec![p],
3353            CastEntry::Branches(ps) => ps.iter_mut().collect(),
3354        }
3355    }
3356
3357    /// The bare-keyword absence this entry declares, if it is that form.
3358    pub fn absence(&self) -> Option<CastAbsence> {
3359        match self {
3360            CastEntry::Absent(a) => Some(*a),
3361            _ => None,
3362        }
3363    }
3364
3365    /// True if this entry declares the NPC out of the world entirely — the bare
3366    /// keyword, or every placement's `at` being a keyword.
3367    pub fn is_absent(&self) -> bool {
3368        match self {
3369            CastEntry::Absent(_) => true,
3370            CastEntry::Placement(p) => p.at.absence().is_some(),
3371            CastEntry::Branches(ps) => {
3372                !ps.is_empty() && ps.iter().all(|p| p.at.absence().is_some())
3373            }
3374        }
3375    }
3376}
3377
3378/// A declared absence: the NPC is deliberately not in the world.
3379#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
3380#[serde(rename_all = "kebab-case")]
3381pub enum CastAbsence {
3382    /// Removed from the story for good (must match a `despawn-npc` with no later
3383    /// `spawn-npc`).
3384    Dead,
3385    /// Not in the world for this quest, but may return (must match a
3386    /// `despawn-npc`).
3387    Offstage,
3388}
3389
3390impl CastAbsence {
3391    /// The authored keyword (`dead` / `offstage`).
3392    pub fn token(self) -> &'static str {
3393        match self {
3394            CastAbsence::Dead => "dead",
3395            CastAbsence::Offstage => "offstage",
3396        }
3397    }
3398}
3399
3400/// Where a cast entry puts an NPC: a prefab anchor, or a declared absence.
3401#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3402#[serde(untagged)]
3403pub enum CastPlace {
3404    /// `"dead"` or `"offstage"` — explicitly not in the world.
3405    Absent(CastAbsence),
3406    /// The anchor the NPC stands on for this quest's duration. Must equal the
3407    /// position the effect history actually produces (`DW0461`): declaring an
3408    /// anchor does not teleport anybody.
3409    Anchor(AnchorId),
3410}
3411
3412impl CastPlace {
3413    /// The anchor this place names, if it is an anchor.
3414    pub fn anchor(&self) -> Option<&AnchorId> {
3415        match self {
3416            CastPlace::Anchor(a) => Some(a),
3417            CastPlace::Absent(_) => None,
3418        }
3419    }
3420
3421    /// The declared absence, if this place is one.
3422    pub fn absence(&self) -> Option<CastAbsence> {
3423        match self {
3424            CastPlace::Absent(a) => Some(*a),
3425            CastPlace::Anchor(_) => None,
3426        }
3427    }
3428
3429    /// The authored token, for diagnostics.
3430    pub fn token(&self) -> &str {
3431        match self {
3432            CastPlace::Absent(a) => a.token(),
3433            CastPlace::Anchor(a) => a.as_str(),
3434        }
3435    }
3436}
3437
3438/// One declared scene for one NPC in one quest.
3439#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3440#[serde(deny_unknown_fields)]
3441pub struct CastPlacement {
3442    /// Where the NPC is: an anchor, or `"offstage"` / `"dead"`.
3443    pub at: CastPlace,
3444    /// What the character is *doing* — free prose, never machine-checked.
3445    ///
3446    /// This field is the forcing function, which is the whole reason it is
3447    /// required (`DW0463`) despite being unverifiable: you cannot fill it in
3448    /// without deciding the character's business in this beat, and stage 6
3449    /// receives it as the context the NPC's lines are written against.
3450    #[serde(default, skip_serializing_if = "Option::is_none")]
3451    pub doing: Option<String>,
3452    /// What right-click offers during this quest. Required for an on-stage
3453    /// placement (`DW0463`) — including the explicit `"none"`.
3454    #[serde(default, skip_serializing_if = "Option::is_none")]
3455    pub dialogue: Option<CastDialogue>,
3456    /// Branch gate (per-branch casts): this placement describes the world only
3457    /// once every listed flag is set. Mirrors an option's `requires_flags`.
3458    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3459    pub requires_flags: Vec<FlagId>,
3460    /// Negative branch gate: this placement describes the world only while no
3461    /// listed flag is set. Mirrors an option's `forbids_flags`.
3462    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3463    pub forbids_flags: Vec<FlagId>,
3464    /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison must
3465    /// hold for this gate to be open. The third field of the one gate, carried by
3466    /// every gate consumer — never by the verb that first wanted it. Default
3467    /// empty, so a pre-0.10 campaign is byte-identical.
3468    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3469    pub requires_state: Vec<StateCompare>,
3470}
3471
3472/// What an NPC's right-click offers for a quest's duration.
3473///
3474/// Untagged, tried in order: the keywords `"none"` / `"unchanged"`, a
3475/// `{"barks": […]}` pool, then a dialogue root id.
3476#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3477#[serde(untagged)]
3478pub enum CastDialogue {
3479    /// A keyword: `"none"` or `"unchanged"`.
3480    Keyword(CastDialogueKeyword),
3481    /// A bark pool: right-click yields one inconsequential in-character line —
3482    /// no tree, no options, no consequences.
3483    Barks(CastBarks),
3484    /// A dialogue root id: right-click opens this node of the NPC's stage-6
3485    /// tree. Must be a node of *that* NPC's tree (`DW0464`).
3486    Root(DialogueId),
3487}
3488
3489/// The keyword forms of [`CastDialogue`].
3490#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
3491#[serde(rename_all = "kebab-case")]
3492pub enum CastDialogueKeyword {
3493    /// Genuinely no reaction: the right-click is recorded and consumed, and
3494    /// nothing opens. Legal, but a last resort — if a body is clickable, the
3495    /// world should answer; prefer a bark.
3496    None,
3497    /// Carry forward whatever this NPC's dialogue was at its **previous**
3498    /// appearance in the quest-DAG ordering.
3499    ///
3500    /// The point is that carrying dialogue forward is a *conscious, declared
3501    /// act*. It is never an implicit default — an omitted `dialogue` is
3502    /// `DW0463`, not a carry-forward — and writing `"unchanged"` states the
3503    /// intent without re-spelling a root id that then drifts out of sync. It
3504    /// resolves transitively (`unchanged` → `unchanged` → a root), and using it
3505    /// at an NPC's first appearance is `DW0466`: there is nothing to carry.
3506    ///
3507    /// Emission is a **no-op** — no root swap is emitted for that NPC at that
3508    /// quest — which is what makes the sugar cheap and byte-stable.
3509    Unchanged,
3510}
3511
3512/// A bark pool: inconsequential in-character lines, cycled deterministically.
3513#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3514#[serde(deny_unknown_fields)]
3515pub struct CastBarks {
3516    /// The lines, in cycle order. At least one (`DW0464`). Player-visible, so
3517    /// they enter the l10n inventory like any narrate text.
3518    pub barks: Vec<String>,
3519}
3520
3521/// What triggers a quest.
3522#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3523#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
3524pub enum Trigger {
3525    /// Fires when the campaign starts.
3526    CampaignStart,
3527    /// Fires when another quest completes.
3528    QuestComplete {
3529        /// The prerequisite quest.
3530        quest: QuestId,
3531    },
3532}
3533
3534/// A quest objective.
3535///
3536/// Every variant may carry `requires_flags`:
3537/// flag-gated activation, satisfied only once each referenced flag has been set
3538/// by a `set-flag` effect.
3539#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3540#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
3541pub enum Objective {
3542    /// Completed by a dialogue option's `complete-objective` effect.
3543    TalkTo {
3544        /// Objective id.
3545        id: ObjectiveId,
3546        /// Short player-facing objective name (v0.3, optional).
3547        #[serde(default, skip_serializing_if = "Option::is_none")]
3548        title: Option<String>,
3549        /// One-line location/direction hint (v0.3, optional).
3550        #[serde(default, skip_serializing_if = "Option::is_none")]
3551        hint: Option<String>,
3552        /// The NPC to talk to.
3553        npc: NpcId,
3554        /// Prerequisite objectives (intra-quest ordering).
3555        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3556        after: Vec<ObjectiveId>,
3557        /// Flags that must be set before this objective activates (v0.3).
3558        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3559        requires_flags: Vec<FlagId>,
3560        /// Negative flag gate (DSL v0.6): the
3561        /// objective is suppressed (cannot activate or complete) while ANY listed
3562        /// flag is set for the player — the dual of `requires_flags`.
3563        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3564        forbids_flags: Vec<FlagId>,
3565        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
3566        /// must hold for this gate to be open. The third field of the one gate,
3567        /// carried by every gate consumer — never by the verb that first wanted
3568        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
3569        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3570        requires_state: Vec<StateCompare>,
3571        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
3572        /// bot should traverse sneaking (sprint disabled). Emitted into
3573        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
3574        /// hint; no datapack effect.
3575        #[serde(default, skip_serializing_if = "is_false")]
3576        stealth: bool,
3577        /// What this objective does to the story (DSL v0.8, spec-0025; required
3578        /// at 0.8.0, `DW0481`).
3579        #[serde(default, skip_serializing_if = "Option::is_none")]
3580        happening: Option<Happening>,
3581    },
3582    /// Completed by reaching an anchor once prerequisites are met.
3583    ReachAnchor {
3584        /// Objective id.
3585        id: ObjectiveId,
3586        /// Short player-facing objective name (v0.3, optional).
3587        #[serde(default, skip_serializing_if = "Option::is_none")]
3588        title: Option<String>,
3589        /// One-line location/direction hint (v0.3, optional).
3590        #[serde(default, skip_serializing_if = "Option::is_none")]
3591        hint: Option<String>,
3592        /// The anchor to reach.
3593        anchor: AnchorId,
3594        /// Completion radius (blocks).
3595        radius: u32,
3596        /// Prerequisite objectives (intra-quest ordering).
3597        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3598        after: Vec<ObjectiveId>,
3599        /// Flags that must be set before this objective activates (v0.3).
3600        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3601        requires_flags: Vec<FlagId>,
3602        /// Negative flag gate (DSL v0.6): the
3603        /// objective is suppressed (cannot activate or complete) while ANY listed
3604        /// flag is set for the player — the dual of `requires_flags`.
3605        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3606        forbids_flags: Vec<FlagId>,
3607        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
3608        /// must hold for this gate to be open. The third field of the one gate,
3609        /// carried by every gate consumer — never by the verb that first wanted
3610        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
3611        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3612        requires_state: Vec<StateCompare>,
3613        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
3614        /// bot should traverse sneaking (sprint disabled). Emitted into
3615        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
3616        /// hint; no datapack effect.
3617        #[serde(default, skip_serializing_if = "is_false")]
3618        stealth: bool,
3619        /// What this objective does to the story (DSL v0.8, spec-0025; required
3620        /// at 0.8.0, `DW0481`).
3621        #[serde(default, skip_serializing_if = "Option::is_none")]
3622        happening: Option<Happening>,
3623    },
3624    /// Completed when the referenced wave is fully slain (v0.3).
3625    Kill {
3626        /// Objective id.
3627        id: ObjectiveId,
3628        /// Short player-facing objective name (v0.3, optional).
3629        #[serde(default, skip_serializing_if = "Option::is_none")]
3630        title: Option<String>,
3631        /// One-line location/direction hint (v0.3, optional).
3632        #[serde(default, skip_serializing_if = "Option::is_none")]
3633        hint: Option<String>,
3634        /// The wave (stage-5 `waves` ref) whose mobs must be slain.
3635        wave: WaveId,
3636        /// Prerequisite objectives.
3637        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3638        after: Vec<ObjectiveId>,
3639        /// Flags that must be set before this objective activates (v0.3).
3640        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3641        requires_flags: Vec<FlagId>,
3642        /// Negative flag gate (DSL v0.6): the
3643        /// objective is suppressed (cannot activate or complete) while ANY listed
3644        /// flag is set for the player — the dual of `requires_flags`.
3645        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3646        forbids_flags: Vec<FlagId>,
3647        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
3648        /// must hold for this gate to be open. The third field of the one gate,
3649        /// carried by every gate consumer — never by the verb that first wanted
3650        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
3651        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3652        requires_state: Vec<StateCompare>,
3653        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
3654        /// bot should traverse sneaking (sprint disabled). Emitted into
3655        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
3656        /// hint; no datapack effect.
3657        #[serde(default, skip_serializing_if = "is_false")]
3658        stealth: bool,
3659        /// What this objective does to the story (DSL v0.8, spec-0025; required
3660        /// at 0.8.0, `DW0481`).
3661        #[serde(default, skip_serializing_if = "Option::is_none")]
3662        happening: Option<Happening>,
3663    },
3664    /// Completed when `count` of `item` have been collected (v0.3).
3665    ///
3666    /// The items are provided in a container: the compiler's own chest at
3667    /// `anchor` by default, or — since DSL v0.8 — the prefab's existing
3668    /// chest/barrel at [`Objective::Collect::container`], optionally carrying an
3669    /// [`Objective::Collect::item_name`] and padded to read full with
3670    /// [`Objective::Collect::fill_count`].
3671    Collect {
3672        /// Objective id.
3673        id: ObjectiveId,
3674        /// Short player-facing objective name (v0.3, optional).
3675        #[serde(default, skip_serializing_if = "Option::is_none")]
3676        title: Option<String>,
3677        /// One-line location/direction hint (v0.3, optional).
3678        #[serde(default, skip_serializing_if = "Option::is_none")]
3679        hint: Option<String>,
3680        /// Vanilla item id to collect (validated against the registry).
3681        item: String,
3682        /// How many are required.
3683        count: u32,
3684        /// The anchor items are provided at (chest / pickup).
3685        anchor: AnchorId,
3686        /// **Adopt the container the prefab already placed**: the anchor whose
3687        /// assembled-world cell holds
3688        /// a `chest` / `trapped_chest` / `barrel` this collect fills instead of
3689        /// conjuring its own chest at [`Objective::Collect::anchor`].
3690        ///
3691        /// Same division of labour a `loot` entry and a trap's dispenser already
3692        /// keep with the prefab: furniture belongs in the piece. A beach camp's
3693        /// barrel is scenery the player has been walking past since minute one —
3694        /// having the compiler `setblock` a *second*, floating chest beside it to
3695        /// hold the quest item is exactly the downstream workaround the no-hack
3696        /// rule forbids. A `container` whose cell holds no container is a build
3697        /// error (`DW0438`), never a silent fill into a wall.
3698        ///
3699        /// The critical-path step's position follows the container (the bot opens
3700        /// *this* block), and no chest is placed at `anchor` when it is set.
3701        #[serde(default, skip_serializing_if = "Option::is_none")]
3702        container: Option<AnchorId>,
3703        /// **The item comes off a body, not out of a box**: the wave whose
3704        /// declared `drops[]` yield
3705        /// this objective's item. No container is placed — not the compiler's own
3706        /// chest at `anchor`, not a prefab one — and `container` is therefore
3707        /// mutually exclusive with it (`DW0100`-adjacent; `DW0492`).
3708        ///
3709        /// This is what makes "kill the boss → pick up its key → open the door"
3710        /// a *proved* chain rather than an authoring intention. The compiler
3711        /// requires (a) that the named wave really declares an `{item}` drop of
3712        /// this item (`DW0492`), and (b) that a `kill` objective for that wave
3713        /// precedes this collect in the objective graph (`DW0493`). The existing
3714        /// flow machinery then carries the ordering the rest of the way: the
3715        /// door's `requires_flags` hangs off this collect exactly as it would off
3716        /// a chest one.
3717        ///
3718        /// **Waves only.** An actor's death is not observable by any objective —
3719        /// there is no vanilla-side signal the flow machinery could consume — so
3720        /// an actor-gated collect would be an unprovable claim, and per the
3721        /// no-hack doctrine it is excluded rather than approximated. An actor may
3722        /// still declare `drops[]`; those drops just cannot gate a quest.
3723        #[serde(default, skip_serializing_if = "Option::is_none")]
3724        dropped_by: Option<WaveId>,
3725        /// Display name for the collected item (DSL v0.8), emitted as the vanilla `custom_name` item component.
3726        ///
3727        /// A quest item is a *named thing* in the story ("Cheese", "Tide
3728        /// Ledger"), and a player who opens the barrel must read that name — an
3729        /// unnamed `minecraft:pumpkin_pie` says nothing about what the quest asked
3730        /// for. Player-visible, so it enters the l10n string inventory
3731        /// (`obj.<quest>.<obj>.item_name`) and translates like any other line.
3732        ///
3733        /// Naming changes nothing about adjudication: the completion advancement
3734        /// and the per-tick held check both match on the ITEM ID, which a named
3735        /// stack still carries.
3736        #[serde(default, skip_serializing_if = "Option::is_none")]
3737        item_name: Option<String>,
3738        /// Padding stacks that make the container **read full**. Default `0` =
3739        /// the single required
3740        /// stack and nothing else.
3741        ///
3742        /// A barrel of cheese that opens on one lonely wheel reads as a bug, and
3743        /// vanilla's notion of "full" is *occupied slots*, not stack size — so
3744        /// this counts SLOTS: the objective's own stack lands in `container.0` and
3745        /// each padding stack repeats it in `container.1`, `container.2`, … Slot
3746        /// assignment is positional and total, the same determinism story `loot`
3747        /// tells (ADR-0006): no RNG, no loot tables, nothing to reseed.
3748        ///
3749        /// The padding is the same item, so taking the whole barrel still
3750        /// completes the objective and never over- or under-counts it.
3751        #[serde(default, skip_serializing_if = "is_zero")]
3752        fill_count: u32,
3753        /// Prerequisite objectives.
3754        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3755        after: Vec<ObjectiveId>,
3756        /// Flags that must be set before this objective activates (v0.3).
3757        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3758        requires_flags: Vec<FlagId>,
3759        /// Negative flag gate (DSL v0.6): the
3760        /// objective is suppressed (cannot activate or complete) while ANY listed
3761        /// flag is set for the player — the dual of `requires_flags`.
3762        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3763        forbids_flags: Vec<FlagId>,
3764        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
3765        /// must hold for this gate to be open. The third field of the one gate,
3766        /// carried by every gate consumer — never by the verb that first wanted
3767        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
3768        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3769        requires_state: Vec<StateCompare>,
3770        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
3771        /// bot should traverse sneaking (sprint disabled). Emitted into
3772        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
3773        /// hint; no datapack effect.
3774        #[serde(default, skip_serializing_if = "is_false")]
3775        stealth: bool,
3776        /// What this objective does to the story (DSL v0.8, spec-0025; required
3777        /// at 0.8.0, `DW0481`).
3778        #[serde(default, skip_serializing_if = "Option::is_none")]
3779        happening: Option<Happening>,
3780    },
3781    /// Completed by interacting with an entity at `anchor`; if `requires_item` is
3782    /// set, the item must be **held in the main hand** (v0.3; held semantics since
3783    /// DSL v0.7 — see [`Objective::Interact::requires_item`]).
3784    Interact {
3785        /// Objective id.
3786        id: ObjectiveId,
3787        /// Short player-facing objective name (v0.3, optional).
3788        #[serde(default, skip_serializing_if = "Option::is_none")]
3789        title: Option<String>,
3790        /// One-line location/direction hint (v0.3, optional).
3791        #[serde(default, skip_serializing_if = "Option::is_none")]
3792        hint: Option<String>,
3793        /// The anchor the interaction entity stands at.
3794        anchor: AnchorId,
3795        /// Item the player must be **holding in the main hand** for the
3796        /// interaction to complete (optional).
3797        ///
3798        /// Held, not merely possessed: presenting the
3799        /// item IS the action — a player who right-clicks a sleeping giant with a
3800        /// sharpened stake buried in their backpack has not stabbed anything.
3801        /// Before this ruling the gate read the whole inventory, which made every
3802        /// `requires_item` interaction fire the moment the item was picked up
3803        /// anywhere, whatever the player was actually doing with their hands.
3804        #[serde(default, skip_serializing_if = "Option::is_none")]
3805        requires_item: Option<String>,
3806        /// Diegetic feedback for a click that arrives without the required item in
3807        /// hand (DSL v0.7): narrated to that player in
3808        /// chat instead of the silence the gate used to answer with. Requires
3809        /// `requires_item` (`DW0437`).
3810        ///
3811        /// Only fires while the objective is genuinely open — same activation gate
3812        /// as the affordance itself — so a finished or not-yet-active interaction
3813        /// stays quiet.
3814        #[serde(default, skip_serializing_if = "Option::is_none")]
3815        missing_item_hint: Option<String>,
3816        /// Prop block that IS the interaction affordance (DSL v0.4, spec-0008
3817        /// §2): the compiler `setblock`s it at the anchor on activation (exactly
3818        /// as `collect` uses a real chest). Omitted = the glowing-lantern
3819        /// hologram marker (the v0.3 fallback).
3820        #[serde(default, skip_serializing_if = "Option::is_none")]
3821        prop: Option<Prop>,
3822        /// Prerequisite objectives.
3823        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3824        after: Vec<ObjectiveId>,
3825        /// Flags that must be set before this objective activates (v0.3).
3826        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3827        requires_flags: Vec<FlagId>,
3828        /// Negative flag gate (DSL v0.6): the
3829        /// objective is suppressed (cannot activate or complete) while ANY listed
3830        /// flag is set for the player — the dual of `requires_flags`.
3831        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3832        forbids_flags: Vec<FlagId>,
3833        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
3834        /// must hold for this gate to be open. The third field of the one gate,
3835        /// carried by every gate consumer — never by the verb that first wanted
3836        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
3837        #[serde(default, skip_serializing_if = "Vec::is_empty")]
3838        requires_state: Vec<StateCompare>,
3839        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
3840        /// bot should traverse sneaking (sprint disabled). Emitted into
3841        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
3842        /// hint; no datapack effect.
3843        #[serde(default, skip_serializing_if = "is_false")]
3844        stealth: bool,
3845        /// What this objective does to the story (DSL v0.8, spec-0025; required
3846        /// at 0.8.0, `DW0481`).
3847        #[serde(default, skip_serializing_if = "Option::is_none")]
3848        happening: Option<Happening>,
3849    },
3850}
3851
3852/// A prop block for an `interact` objective (DSL v0.4). The block is the
3853/// affordance the player interacts with; its id is validated against the pinned
3854/// 1.21.11 block registry (`DW0193`).
3855#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3856#[serde(deny_unknown_fields)]
3857pub struct Prop {
3858    /// Vanilla block id (e.g. `minecraft:lever`).
3859    pub block: String,
3860}
3861
3862// ---------------------------------------------------------------------------
3863// Stage 5 — scripted actors (DSL v0.6, spec-0014)
3864// ---------------------------------------------------------------------------
3865
3866/// A scripted stage actor (DSL v0.6, spec-0014): a NoAI/Silent/no-loot puppet,
3867/// distinct from a stage-2 [`Npc`] (no dialogue, any mob type). Emitted with tag
3868/// `dw_actor_<id>`, `Invulnerable` unless `vulnerable` (a damageable puppet stays
3869/// knockback-immune — the tower-defense creep). `skin` re-dresses it as a
3870/// `minecraft:mannequin`, exactly as a stage-2 NPC skin. The puppet is summoned by
3871/// a `spawn-actor` effect (not at load), moved by `move-actor`, and can be replaced
3872/// by a real-AI twin with `unleash-actor`.
3873#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
3874#[serde(deny_unknown_fields)]
3875pub struct Actor {
3876    /// Unique actor id (`actor/<kebab>`).
3877    pub id: ActorId,
3878    /// The vanilla entity to puppet, e.g. `minecraft:warden`. Validated against the
3879    /// pinned 1.21.11 entity registry (`DW0173`).
3880    pub entity: String,
3881    /// Optional custom name shown above the puppet.
3882    #[serde(default, skip_serializing_if = "Option::is_none")]
3883    pub name: Option<String>,
3884    /// Optional player-model skin (mannequin), as a stage-2 NPC (`DW0190`).
3885    #[serde(default, skip_serializing_if = "Option::is_none")]
3886    pub skin: Option<NpcSkin>,
3887    /// The anchor the puppet is summoned on (resolved across areas, like an
3888    /// `open-gate` / `move-npc` destination).
3889    pub anchor: AnchorId,
3890    /// Initial facing (default `south`). The puppet spawns yawed this way.
3891    #[serde(default, skip_serializing_if = "Option::is_none")]
3892    pub facing: Option<Facing>,
3893    /// If `true`, the puppet is damageable (a tower-defense creep) but stays
3894    /// knockback-immune; default `false` (fully `Invulnerable`).
3895    #[serde(default, skip_serializing_if = "is_false")]
3896    pub vulnerable: bool,
3897    /// Gear the actor wears and holds, in the same shape a wave mob uses
3898    /// ([`MobEquipment`]). Emitted into BOTH the staged puppet and the
3899    /// unleashed twin, so the dormant elite the player has been circling is
3900    /// visibly the same armoured thing that stands up. Drop chances are zero —
3901    /// wave gear and actor gear are never farmable (no-grind constitution).
3902    #[serde(default, skip_serializing_if = "Option::is_none")]
3903    pub equipment: Option<MobEquipment>,
3904    /// Attribute overrides, in the same shape a wave mob uses ([`MobAttributes`],
3905    /// the v0.4 surface — one type, one rule set, so the two surfaces cannot
3906    /// drift). Emitted into BOTH the staged puppet and the unleashed twin, so the
3907    /// elite the party fights is the elite the author tuned; without it an actor
3908    /// was stuck at vanilla base values while every wave mob could be tuned,
3909    /// which is what blocked elite authoring. A `vulnerable` actor's
3910    /// knockback-immunity is emitted first and is not authorable.
3911    #[serde(default, skip_serializing_if = "Option::is_none")]
3912    pub attributes: Option<MobAttributes>,
3913    /// How hard this actor's fight is *meant* to be (DSL v0.8, spec-0023) — the
3914    /// same [`EncounterTier`] vocabulary a [`Wave`] declares. Absent =
3915    /// [`EncounterTier::Ordinary`], byte-identical to every pre-0.8 campaign.
3916    ///
3917    /// A wave is not the only shape an elite takes. The set-piece souls fight —
3918    /// the armoured thing kneeling among the graves that stands up when you hit
3919    /// it — is an **actor**: staged by `spawn-actor`, given AI by
3920    /// `unleash-actor`, killed by hand rather than by a `kill` objective. Before
3921    /// this field the validation ladder's inverted floor gate could only see
3922    /// `waves[].tier`, so such a boss was *structurally invisible* to it and an
3923    /// empty finding list read as a pass while covering nothing.
3924    ///
3925    /// Like the wave field this is a **declaration, not a knob**: the compiler
3926    /// never scales an actor from it, and emission is unchanged whichever tier is
3927    /// declared. What it buys is scrutiny — the actor enters
3928    /// `validation/combat-plan.json`, and the compiler states, per tiered actor,
3929    /// whether the floor gate can measure it and why not when it cannot
3930    /// (`DW0477`).
3931    #[serde(default, skip_serializing_if = "Option::is_none")]
3932    pub tier: Option<EncounterTier>,
3933    /// What this actor leaves behind when a player kills it. Only an
3934    /// `elite`/`boss` actor may
3935    /// declare it (`DW0491`). Emitted into BOTH the staged puppet and the
3936    /// unleashed twin, exactly as `equipment` is — the drop belongs to the body,
3937    /// not to one of its two lifecycles. A `despawn-actor` strips the
3938    /// declaration off the body before removing it, so re-caging an elite (a
3939    /// souls re-seat) never scatters its axe.
3940    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3941    pub drops: Vec<MobDrop>,
3942    /// What this body can do when it moves (DSL v0.11, spec-0034) — the same
3943    /// [`BodyTraversal`] a stage-2 [`Npc`] carries, because traversal belongs to
3944    /// the body and not to the stage that declares it. Absent = the class the
3945    /// compiler derives from `entity` (or from `minecraft:mannequin` when `skin`
3946    /// is set).
3947    #[serde(default, skip_serializing_if = "Option::is_none")]
3948    pub traversal: Option<BodyTraversal>,
3949}
3950
3951/// A cardinal facing keyword (DSL v0.6). Emitted as the puppet's spawn yaw
3952/// (MC: yaw 0 = +z/south).
3953#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
3954#[serde(rename_all = "kebab-case")]
3955pub enum Facing {
3956    /// Facing +z (yaw 0) — the default.
3957    South,
3958    /// Facing -z (yaw 180).
3959    North,
3960    /// Facing -x (yaw 90).
3961    West,
3962    /// Facing +x (yaw 270).
3963    East,
3964}
3965
3966impl Facing {
3967    /// The kebab token (`south` / `north` / `west` / `east`).
3968    pub fn token(self) -> &'static str {
3969        match self {
3970            Facing::South => "south",
3971            Facing::North => "north",
3972            Facing::West => "west",
3973            Facing::East => "east",
3974        }
3975    }
3976}
3977
3978/// How a `despawn-actor` removes its puppet (DSL v0.6).
3979#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
3980#[serde(rename_all = "kebab-case")]
3981pub enum DespawnStyle {
3982    /// Silent removal (`kill @e` with no death animation is not possible; the
3983    /// compiler removes the entity via `/kill` on an `Invulnerable` puppet, or a
3984    /// data-driven removal — see the emitter — so no death particles/sound show).
3985    Vanish,
3986    /// Plays the vanilla death animation (a cutscene death).
3987    Kill,
3988}
3989
3990impl DespawnStyle {
3991    /// The kebab token (`vanish` / `kill`).
3992    pub fn token(self) -> &'static str {
3993        match self {
3994            DespawnStyle::Vanish => "vanish",
3995            DespawnStyle::Kill => "kill",
3996        }
3997    }
3998}
3999
4000/// One step of a [`Verb::Sequence`] (DSL v0.6): a group of effects fired at
4001/// an exact tick offset from the sequence's start.
4002#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
4003#[serde(deny_unknown_fields)]
4004pub struct SequenceStep {
4005    /// Tick offset from the sequence start at which `effects` fire.
4006    pub at_ticks: u32,
4007    /// The effects fired at `at_ticks`. Any stage-5 effect except a nested
4008    /// `sequence` (rejected with `DW0329`).
4009    pub effects: Vec<QuestEffect>,
4010}
4011
4012impl Objective {
4013    /// This objective's id.
4014    pub fn id(&self) -> &ObjectiveId {
4015        match self {
4016            Objective::TalkTo { id, .. }
4017            | Objective::ReachAnchor { id, .. }
4018            | Objective::Kill { id, .. }
4019            | Objective::Collect { id, .. }
4020            | Objective::Interact { id, .. } => id,
4021        }
4022    }
4023
4024    /// This objective's prerequisites.
4025    pub fn after(&self) -> &[ObjectiveId] {
4026        match self {
4027            Objective::TalkTo { after, .. }
4028            | Objective::ReachAnchor { after, .. }
4029            | Objective::Kill { after, .. }
4030            | Objective::Collect { after, .. }
4031            | Objective::Interact { after, .. } => after,
4032        }
4033    }
4034
4035    /// The short player-facing objective title (v0.3, optional).
4036    pub fn title(&self) -> Option<&str> {
4037        match self {
4038            Objective::TalkTo { title, .. }
4039            | Objective::ReachAnchor { title, .. }
4040            | Objective::Kill { title, .. }
4041            | Objective::Collect { title, .. }
4042            | Objective::Interact { title, .. } => title.as_deref(),
4043        }
4044    }
4045
4046    /// The one-line location/direction hint (v0.3, optional).
4047    pub fn hint(&self) -> Option<&str> {
4048        match self {
4049            Objective::TalkTo { hint, .. }
4050            | Objective::ReachAnchor { hint, .. }
4051            | Objective::Kill { hint, .. }
4052            | Objective::Collect { hint, .. }
4053            | Objective::Interact { hint, .. } => hint.as_deref(),
4054        }
4055    }
4056
4057    /// Mutable access to the optional player-facing title (i18n localization).
4058    pub fn title_mut(&mut self) -> &mut Option<String> {
4059        match self {
4060            Objective::TalkTo { title, .. }
4061            | Objective::ReachAnchor { title, .. }
4062            | Objective::Kill { title, .. }
4063            | Objective::Collect { title, .. }
4064            | Objective::Interact { title, .. } => title,
4065        }
4066    }
4067
4068    /// Mutable access to the optional one-line hint (i18n localization).
4069    pub fn hint_mut(&mut self) -> &mut Option<String> {
4070        match self {
4071            Objective::TalkTo { hint, .. }
4072            | Objective::ReachAnchor { hint, .. }
4073            | Objective::Kill { hint, .. }
4074            | Objective::Collect { hint, .. }
4075            | Objective::Interact { hint, .. } => hint,
4076        }
4077    }
4078
4079    /// The flags that must be set before this objective activates (v0.3).
4080    pub fn requires_flags(&self) -> &[FlagId] {
4081        match self {
4082            Objective::TalkTo { requires_flags, .. }
4083            | Objective::ReachAnchor { requires_flags, .. }
4084            | Objective::Kill { requires_flags, .. }
4085            | Objective::Collect { requires_flags, .. }
4086            | Objective::Interact { requires_flags, .. } => requires_flags,
4087        }
4088    }
4089
4090    /// The negative flag gate (DSL v0.6): flags whose being set **suppresses**
4091    /// this objective. The dual of [`Objective::requires_flags`].
4092    pub fn forbids_flags(&self) -> &[FlagId] {
4093        match self {
4094            Objective::TalkTo { forbids_flags, .. }
4095            | Objective::ReachAnchor { forbids_flags, .. }
4096            | Objective::Kill { forbids_flags, .. }
4097            | Objective::Collect { forbids_flags, .. }
4098            | Objective::Interact { forbids_flags, .. } => forbids_flags,
4099        }
4100    }
4101
4102    /// The numeric gate terms (DSL v0.10, spec-0031): comparisons that must hold
4103    /// before this objective activates. See [`StateCompare`].
4104    pub fn requires_state(&self) -> &[StateCompare] {
4105        match self {
4106            Objective::TalkTo { requires_state, .. }
4107            | Objective::ReachAnchor { requires_state, .. }
4108            | Objective::Kill { requires_state, .. }
4109            | Objective::Collect { requires_state, .. }
4110            | Objective::Interact { requires_state, .. } => requires_state,
4111        }
4112    }
4113
4114    /// What this objective does to the story (DSL v0.8, spec-0025).
4115    pub fn happening(&self) -> Option<&Happening> {
4116        match self {
4117            Objective::TalkTo { happening, .. }
4118            | Objective::ReachAnchor { happening, .. }
4119            | Objective::Kill { happening, .. }
4120            | Objective::Collect { happening, .. }
4121            | Objective::Interact { happening, .. } => happening.as_ref(),
4122        }
4123    }
4124
4125    /// The bot stealth hint (DSL v0.4): traverse this leg sneaking.
4126    pub fn stealth(&self) -> bool {
4127        match self {
4128            Objective::TalkTo { stealth, .. }
4129            | Objective::ReachAnchor { stealth, .. }
4130            | Objective::Kill { stealth, .. }
4131            | Objective::Collect { stealth, .. }
4132            | Objective::Interact { stealth, .. } => *stealth,
4133        }
4134    }
4135
4136    /// The container this objective ADOPTS (DSL v0.8), if it is a `collect` that
4137    /// declares one: the anchor whose prefab-placed chest/barrel it fills instead
4138    /// of conjuring its own chest. `None` on every other objective and on a
4139    /// `collect` that keeps the compiler-placed chest.
4140    pub fn collect_container(&self) -> Option<&AnchorId> {
4141        match self {
4142            Objective::Collect { container, .. } => container.as_ref(),
4143            _ => None,
4144        }
4145    }
4146
4147    /// The wave whose declared drops provide this objective's item (DSL v0.9),
4148    /// if it is a `collect` that declares one. `None` on every other objective
4149    /// and on a `collect` fed by a container.
4150    pub fn collect_dropped_by(&self) -> Option<&WaveId> {
4151        match self {
4152            Objective::Collect { dropped_by, .. } => dropped_by.as_ref(),
4153            _ => None,
4154        }
4155    }
4156
4157    /// The padding-stack count of a `collect` (DSL v0.8); `0` for every other
4158    /// objective and for a `collect` that fills the single required stack only.
4159    pub fn collect_fill_count(&self) -> u32 {
4160        match self {
4161            Objective::Collect { fill_count, .. } => *fill_count,
4162            _ => 0,
4163        }
4164    }
4165
4166    /// The `interact` prop block (DSL v0.4), if this is an `interact` with a prop.
4167    pub fn prop(&self) -> Option<&Prop> {
4168        match self {
4169            Objective::Interact { prop, .. } => prop.as_ref(),
4170            _ => None,
4171        }
4172    }
4173
4174    /// The kebab type tag.
4175    pub fn kind(&self) -> &'static str {
4176        match self {
4177            Objective::TalkTo { .. } => "talk-to",
4178            Objective::ReachAnchor { .. } => "reach-anchor",
4179            Objective::Kill { .. } => "kill",
4180            Objective::Collect { .. } => "collect",
4181            Objective::Interact { .. } => "interact",
4182        }
4183    }
4184
4185    /// The v0.3 verb name if this objective is one of the verbs introduced in
4186    /// DSL v0.3 (`kill`/`collect`/`interact`). These validate in v0.3 campaigns
4187    ///.
4188    pub fn v03_verb(&self) -> Option<&'static str> {
4189        match self {
4190            Objective::Kill { .. } => Some("kill"),
4191            Objective::Collect { .. } => Some("collect"),
4192            Objective::Interact { .. } => Some("interact"),
4193            Objective::TalkTo { .. } | Objective::ReachAnchor { .. } => None,
4194        }
4195    }
4196}
4197
4198/// The condition under which an effect fires, as one object.
4199///
4200/// The three axes of [`crate::gate::Gate`] in their declared form: the flags that
4201/// must be set, the flags that must not be, and the numeric comparisons that must
4202/// hold. Declared once and carried by [`QuestEffect::when`], so every verb is
4203/// gatable on exactly the same terms and a fourth axis is one field here.
4204#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
4205#[serde(deny_unknown_fields)]
4206pub struct Guard {
4207    /// Flags that must ALL be set (per party) for the effect to fire. Emission
4208    /// wraps the effect's commands in `execute if score #party dw.f_<flag> matches 1`.
4209    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4210    pub requires_flags: Vec<FlagId>,
4211    /// Flags whose being set SUPPRESSES the effect — the dual of `requires_flags`,
4212    /// emitted as `execute unless score #party dw.f_<flag> matches 1`.
4213    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4214    pub forbids_flags: Vec<FlagId>,
4215    /// Numeric comparisons that must ALL hold (spec-0031), emitted as
4216    /// `execute if score <holder> dw.s_<state> matches <range>`.
4217    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4218    pub requires_state: Vec<StateCompare>,
4219}
4220
4221/// An effect fired by quest progress: **one guard, one story note, one verb.**
4222///
4223/// The guard is a property of an effect, not of the verb that first wanted one, so
4224/// it is declared once in [`Guard`] and every verb carries it — including the
4225/// staging and souls vocabulary (`spawn-actor`, `move-actor`, `set-checkpoint`,
4226/// `bonfire`, `begin-stealth`, `sequence`, …) that could not be branch-gated while
4227/// the fields lived on the variants. A gate that can never open on a
4228/// `campaign-complete` is caught where it belongs, by the completability proof.
4229///
4230/// `verb` is `#[serde(flatten)]`, so the JSON is unchanged in shape apart from the
4231/// guard moving under `when`: `{"type": "open-gate", "anchor": "…", "when":
4232/// {"requires_flags": ["…"]}}`. [`Verb`] keeps `deny_unknown_fields`, which is what
4233/// the flattened deserializer applies to everything the outer struct did not claim
4234/// — an author's typo is still `DW0100`.
4235#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
4236pub struct QuestEffect {
4237    /// When this effect fires. `None` is the always-open gate.
4238    #[serde(default, skip_serializing_if = "Option::is_none")]
4239    pub when: Option<Guard>,
4240    /// What this beat does to the story (spec-0025) — validation metadata with no
4241    /// emission of its own.
4242    #[serde(default, skip_serializing_if = "Option::is_none")]
4243    pub happening: Option<Happening>,
4244    /// What the effect does.
4245    #[serde(flatten)]
4246    pub verb: Verb,
4247}
4248
4249impl From<Verb> for QuestEffect {
4250    /// An unguarded effect with no story note — the shape a compiler-synthesized
4251    /// beat and most tests want.
4252    fn from(verb: Verb) -> Self {
4253        QuestEffect {
4254            when: None,
4255            happening: None,
4256            verb,
4257        }
4258    }
4259}
4260
4261/// What an effect does, without the guard: the closed set of verbs.
4262#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
4263#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
4264pub enum Verb {
4265    /// Opens a prefab-declared gate (one-way).
4266    OpenGate {
4267        /// The gate anchor to open.
4268        anchor: AnchorId,
4269    },
4270    /// Seals a prefab-declared gate — the physical dual of `open-gate` (DSL v0.6):
4271    /// fills the gate anchor's region with the block the anchor declares (e.g. the
4272    /// boulder's `minecraft:basalt`), turning an opened threshold back into a wall.
4273    /// The declared fill block is prefab metadata; a gate anchor with no `block` is
4274    /// rejected (`DW0343`). The completability model treats the region as **solid**
4275    /// from the point in the quest DAG where this fires (mirroring how `open-gate`'s
4276    /// clearing is modelled) — a critical path that must cross a gate after it seals
4277    /// fails the DW0311 reachability proof.
4278    CloseGate {
4279        /// The gate anchor to seal.
4280        anchor: AnchorId,
4281        /// What the seal *says* when a player right-clicks it (DSL v0.8). A sealed gate is a wall the party will walk back to
4282        /// and press: the compiler answers that press on the actionbar. Absent, the
4283        /// compiler's canonical English is baked in (`The way is sealed.`) exactly
4284        /// as `world.boundary.message` does; authored, the line is l10n-inventoried
4285        /// under `<effect-key>.sealed_hint` and translates like every other
4286        /// player-visible string.
4287        ///
4288        /// Unlike `happening`, this **does** print in the hand-written `Debug`
4289        /// below when present — it changes emission, so two otherwise-identical
4290        /// sequences that differ only in their seal's answer are different content.
4291        #[serde(default, skip_serializing_if = "Option::is_none")]
4292        sealed_hint: Option<String>,
4293    },
4294    /// Marks the campaign complete (final advancement + credits). Terminal — not
4295    /// flag-gatable (gating the campaign's own completion is a deadlock footgun),
4296    /// so this variant carries no `requires_flags`.
4297    CampaignComplete {
4298        /// Which ENDING this is (DSL v0.8, spec-0025).
4299        /// A campaign with more than one `campaign-complete` has more than one
4300        /// ending, and a branch that runs to an ending names it here — so the
4301        /// terminality proof (`DW0482`) can state *which* ending a branch reached
4302        /// instead of merely that something ended. There is no separate `endings`
4303        /// section: the set of endings is exactly the set named here, the same
4304        /// rule flags follow.
4305        #[serde(default, skip_serializing_if = "Option::is_none")]
4306        ending: Option<EndingId>,
4307    },
4308    /// Gives the party an item (v0.3; party-wide since v0.6/spec-0018).
4309    GiveItem {
4310        /// Vanilla item id to give (validated against the registry).
4311        item: String,
4312        /// How many to give.
4313        count: u32,
4314        /// Optional display name (DSL v0.4), matching [`KitItem::name`].
4315        #[serde(default, skip_serializing_if = "Option::is_none")]
4316        name: Option<String>,
4317        /// Who receives it (DSL v0.6, spec-0018). Absent = [`Carrier::All`] — every
4318        /// party member. `one` hands a single copy to the player whose action fired
4319        /// the effect; it is rejected in a scheduler-only bundle (`DW0371`), which
4320        /// has no acting player.
4321        #[serde(default, skip_serializing_if = "Option::is_none")]
4322        carrier: Option<Carrier>,
4323    },
4324    /// Sets a campaign flag, enabling flag-gated objectives (v0.3).
4325    SetFlag {
4326        /// The flag to set.
4327        flag: FlagId,
4328    },
4329    /// Writes a declared datum to an absolute value (DSL v0.10, spec-0031).
4330    SetState {
4331        /// The datum to write (stage-5 `state` ref).
4332        state: StateId,
4333        /// The value to write.
4334        value: i32,
4335    },
4336    /// Moves a declared datum by a signed amount (DSL v0.10, spec-0031).
4337    ///
4338    /// **Signed on purpose.** A purse that a shop debits and a stake that a death
4339    /// forfeits are the same operation with the sign flipped; a separate
4340    /// `subtract-state` would be a second verb for one mechanism, and the first
4341    /// campaign to need "add a negative" would have to choose between them.
4342    AddState {
4343        /// The datum to move (stage-5 `state` ref).
4344        state: StateId,
4345        /// How far to move it. Negative counts down.
4346        amount: i32,
4347    },
4348    /// Leaves a declared [`Stake`] behind for the acting player (DSL v0.10,
4349    /// spec-0032): forfeit the declared share of its datum, and place a
4350    /// collectable marker at the compile-time anchor for where they are.
4351    ///
4352    /// **Nothing about this verb says "death".** It is written in `on_death`
4353    /// because that is where a souls-shaped delve wants it, but the mechanism is
4354    /// "leave a recoverable cache where the acting player stands", and the effect
4355    /// carries the ordinary gate so any root may run it. What *is* death-specific
4356    /// — that the corpse stands on the death position, so the placement lookup has
4357    /// a position to key on — is a property of the `on_death` root, not of this
4358    /// verb.
4359    DropStake {
4360        /// The stake (stage-5 `stakes` ref) to leave.
4361        stake: StakeId,
4362    },
4363    /// Returns a declared datum to its declared `initial` (DSL v0.10,
4364    /// spec-0031) — the verb `FlagId` has never had.
4365    ClearState {
4366        /// The datum to clear (stage-5 `state` ref).
4367        state: StateId,
4368    },
4369    /// Spawns a stage-5 wave's mobs at its anchor (v0.3).
4370    SpawnWave {
4371        /// The wave (stage-5 `waves` ref) to spawn.
4372        wave: WaveId,
4373    },
4374    /// Narrates a player-visible line (DSL v0.4, spec-0008 §3). `text` enters the
4375    /// l10n key inventory like any player-visible string.
4376    Narrate {
4377        /// The line shown to the player.
4378        text: String,
4379        /// Presentation channel (default `chat`).
4380        #[serde(default, skip_serializing_if = "Option::is_none")]
4381        style: Option<NarrateStyle>,
4382        /// Optional sound id played alongside the line.
4383        #[serde(default, skip_serializing_if = "Option::is_none")]
4384        sound: Option<String>,
4385    },
4386    /// Sets a block at an anchor (DSL v0.4, spec-0008 §2). General form of a prop
4387    /// placement. Block id validated against the pinned 1.21.11 block registry;
4388    /// a vanilla blockstate suffix (`minecraft:grindstone[face=floor]`) is
4389    /// accepted and passed through verbatim (DSL v0.6).
4390    SetBlock {
4391        /// The anchor to place the block at.
4392        anchor: AnchorId,
4393        /// Vanilla block id to place.
4394        block: String,
4395    },
4396    /// **Fill a declared region with a block** at runtime (DSL v0.10, spec-0031).
4397    ///
4398    /// The general spelling of the capability `open-gate` / `close-gate` carried
4399    /// privately: a region, filled or cleared, from a point in the quest DAG.
4400    /// `close-gate` is this verb with the region and the block read off a prefab
4401    /// gate anchor instead of authored; `set-block` is the one-cell case at a
4402    /// point anchor. All three lower through one emission
4403    /// (`emit::fill_region_command`) and are modelled by one completability rule
4404    /// (`plan::RegionEvent`), so a third consumer inherits the proof instead of
4405    /// re-deriving it.
4406    ///
4407    /// From the DAG point at which this fires, the completability model treats the
4408    /// filled cells as whatever the **block** makes them. A full-cube block leaves
4409    /// them **solid**, exactly as a `close-gate` seal is: a critical path that must
4410    /// cross the region afterwards fails `DW0311`. `minecraft:water` /
4411    /// `minecraft:lava` leave them **flooded** — impassable and never floor, because
4412    /// nothing stands on a fluid — and because a fill carries no `replace` filter it
4413    /// takes away whatever floor was in the box, so a forced leg that needed that
4414    /// footing fails `DW0544`.
4415    FillRegion {
4416        /// The volume to fill, as an anchor-centred box (`anchor ± extent`).
4417        ///
4418        /// Deliberately the existing [`StealthZone`] — the engine's one
4419        /// anchor-centred box object class, already shared by `damage-players`'s
4420        /// `in` filter, `collapse`'s `region_anchor`, a `volley` kill zone and a
4421        /// `lethal_volumes[]` region, and resolved through the single
4422        /// `Plan::zone_box`. A private twin with the same two fields would be
4423        /// `tools/check-capability-ownership.py` check C by construction.
4424        ///
4425        /// An anchor-centred box rather than a prefab `region` anchor for the
4426        /// reason `collapse` states: the assembled model deletes every gate-region
4427        /// anchor's cells, so a slab declared that way would already be gone.
4428        region: StealthZone,
4429        /// The block the region is filled with (validated against the pinned
4430        /// 1.21.11 block registry, `DW0193`).
4431        block: String,
4432    },
4433    /// **Clear a declared region to air** at runtime (DSL v0.10, spec-0031) — the
4434    /// physical dual of [`Verb::FillRegion`], and the general spelling of
4435    /// what `open-gate` does to a gate anchor's region.
4436    ///
4437    /// The completability model treats the cleared cells as **passable** from the
4438    /// DAG point at which this fires, with one exception it states out loud: a
4439    /// cleared cell the model already floods stays impassable, because clearing a
4440    /// block does not remove water (`nav::World::with_cleared`).
4441    ClearRegion {
4442        /// The volume to clear, as an anchor-centred box (`anchor ± extent`) —
4443        /// the same object class [`Verb::FillRegion`] fills.
4444        region: StealthZone,
4445    },
4446    /// **Opens a placed piece's contingent way** (DSL v0.12, spec-0042 §2.4): the
4447    /// broken flight a beat repairs, the bridge a beat lowers, the rubble a beat
4448    /// clears.
4449    ///
4450    /// A piece's spatial contract may declare a traversal edge whose crossability
4451    /// depends on a named region — `laid` (empty as built, opening fills it) or
4452    /// `cleared` (built solid, opening voids it). The prefab checker proves the
4453    /// piece is severed as shipped and joined once that region is opened; this is
4454    /// the verb that opens it, and it is the only one, because a way is the object
4455    /// and opening it is the operation.
4456    ///
4457    /// **There is no region, no block and no sign on this effect, and that is the
4458    /// design rather than an omission.** All three are read from the piece's own
4459    /// exported metadata (`spatial_contract.edges[].way`), so the effect and the
4460    /// building cannot disagree about what a way is — two authorities plus an
4461    /// equality check is the defect this shape avoids, not a variant of the fix
4462    /// (spec-0042 AC8). What the campaign decides is *when*.
4463    ///
4464    /// Completability: the way is **shut until this fires**, and from the DAG
4465    /// point at which it fires the region is solid-and-footing (`laid`) or
4466    /// passable (`cleared`) — the same [`Verb::FillRegion`] /
4467    /// [`Verb::ClearRegion`] model, fed from metadata instead of from an
4468    /// authored box, so this verb inherits the forced-footing rule (`DW0546`)
4469    /// rather than restating it. Required content standing beyond a way that no
4470    /// forced opening precedes is `DW0548`, which names the way, the effect and
4471    /// the element.
4472    OpenWay {
4473        /// The placed piece whose way this opens (`prefab/<name>`).
4474        ///
4475        /// A piece, not an anchor: the way's cells are the contract's, not a gate
4476        /// anchor's, and a piece placed twice has two ways. The reference must
4477        /// name exactly one placement; naming none or several is `DW0547`.
4478        piece: PrefabId,
4479        /// The way's region name, as the piece's contract exports it
4480        /// (`spatial_contract.edges[].way.region`).
4481        way: String,
4482    },
4483    /// Despawns an NPC and its interaction hitbox (DSL v0.4, spec-0008 §5).
4484    DespawnNpc {
4485        /// The NPC (stage-2 ref) to remove.
4486        npc: NpcId,
4487    },
4488    /// Moves an NPC (and its interaction hitbox in lockstep) to an anchor (DSL
4489    /// v0.4, spec-0008 §5 + addendum). The compiler plans a **collision-safe walked
4490    /// path** by A* over the solved voxel grid and emits per-tick teleport
4491    /// waypoints along it, so the NPC never clips a wall and walks up to (not into)
4492    /// a solid affordance. An unroutable move is a compile error (`DW0307`).
4493    MoveNpc {
4494        /// The NPC (stage-2 ref) to move.
4495        npc: NpcId,
4496        /// The destination anchor.
4497        to_anchor: AnchorId,
4498        /// Optional travel speed in blocks/tick (defaults to ~0.15).
4499        #[serde(default, skip_serializing_if = "Option::is_none")]
4500        speed: Option<f64>,
4501        /// Effects fired once the NPC arrives at the destination cell — exact
4502        /// parity with [`Verb::MoveActor`]
4503        /// `on_arrive`: same arrival detection (the walk driver's final tick), same
4504        /// execution context, and every deep effect walker recurses into it via
4505        /// [`QuestEffect::nested_effect_lists`]. This is what lets content gate a
4506        /// beat on walk *completion* instead of fire-and-forgetting the walk (e.g.
4507        /// `on_arrive: [set-flag]` so a cutscene waits for the NPC to reach its
4508        /// mark).
4509        #[serde(default, skip_serializing_if = "Vec::is_empty")]
4510        on_arrive: Vec<QuestEffect>,
4511    },
4512    /// Plays a scripted camera cutscene (DSL v0.4 addendum). Per player: save
4513    /// gamemode+position, spectator, then dolly two co-located cameras along a
4514    /// straight-line lerp between waypoints and alternate `spectate` between them
4515    /// each tick (the two-camera bounce; the same-entity re-`spectate` is a server
4516    /// no-op and is never emitted), and restore on completion. The compiler
4517    /// validates the dolly path passes only through non-solid blocks — cameras
4518    /// fly but must not clip a solid (`DW0308`).
4519    ///
4520    /// Camera **aim** (DSL v0.6): with `look_at`, every dolly camera is rotated at
4521    /// emission to face that world point from its own position, so the shot keeps
4522    /// its subject framed for the whole move; without it, the camera faces along
4523    /// the direction of travel (the segment it is currently traversing).
4524    ///
4525    /// **Shape** — a cutscene is a list of [`CameraShot`]s played back-to-back
4526    /// inside one save/restore bracket (hard cut between shots). Two accepted,
4527    /// mutually exclusive spellings, both normalized by
4528    /// [`QuestEffect::cutscene_shots`]:
4529    /// - multi-shot (DSL v0.6): `{"shots": [{path, seconds, look_at?}, …]}`;
4530    /// - single-shot (DSL v0.4): `{"path": […], "seconds": n, "look_at"?: …}` —
4531    ///   exactly equivalent to a one-entry `shots` list.
4532    ///
4533    /// Mixing or omitting both is `DW0199`.
4534    Cutscene {
4535        /// Multi-shot form (DSL v0.6): the ordered shot list. Mutually exclusive
4536        /// with the single-shot `path`/`seconds` fields (`DW0199`).
4537        #[serde(default, skip_serializing_if = "Vec::is_empty")]
4538        shots: Vec<CameraShot>,
4539        /// Single-shot form (DSL v0.4): ordered camera waypoints (straight-line
4540        /// lerp between them).
4541        #[serde(default, skip_serializing_if = "Vec::is_empty")]
4542        path: Vec<CameraWaypoint>,
4543        /// Single-shot form (DSL v0.4): shot duration in seconds.
4544        #[serde(default, skip_serializing_if = "Option::is_none")]
4545        seconds: Option<u32>,
4546        /// Single-shot form (DSL v0.6): the subject the camera keeps framed.
4547        /// Absent = face along the direction of travel.
4548        #[serde(default, skip_serializing_if = "Option::is_none")]
4549        look_at: Option<CameraTarget>,
4550    },
4551    /// Cuts the dimension-global world time to a new state (DSL v0.5, spec-0010).
4552    /// Instantaneous (vanilla has no gradual transition); the state persists
4553    /// because the daylight cycle is frozen by sealing.
4554    SetTime {
4555        /// The time state to cut to.
4556        time: WorldTime,
4557    },
4558    /// Cuts the dimension-global weather to a new state (DSL v0.5, spec-0010).
4559    /// Instantaneous; persists because the weather cycle is frozen by sealing.
4560    SetWeather {
4561        /// The weather state to cut to.
4562        weather: WorldWeather,
4563    },
4564    /// Plays a vanilla sound event, positionally or per-player (DSL v0.6,
4565    /// spec-0014). `sound` is validated against the vendored pinned-1.21.11
4566    /// sound-event registry (`DW0326` unknown). `at` selects where the sound
4567    /// originates (default: each player's own position); `volume`/`pitch` map to
4568    /// the `playsound` command's trailing args (pitch clamps to 0.0..=2.0 in
4569    /// vanilla).
4570    PlaySound {
4571        /// The vanilla sound-event id (`minecraft:` prefix optional).
4572        sound: String,
4573        /// Where the sound plays from (default: `players`).
4574        #[serde(default, skip_serializing_if = "Option::is_none")]
4575        at: Option<SoundAt>,
4576        /// Playback volume (vanilla default 1.0; > 1.0 only extends audible range).
4577        #[serde(default, skip_serializing_if = "Option::is_none")]
4578        volume: Option<f64>,
4579        /// Playback pitch (vanilla 0.0..=2.0; default 1.0).
4580        #[serde(default, skip_serializing_if = "Option::is_none")]
4581        pitch: Option<f64>,
4582    },
4583    /// Deals damage to the acting player(s) (DSL v0.6): the real consequence a
4584    /// stealth `on_caught` or a souls-style beat needs — vanilla's `/damage`
4585    /// primitive. Runs in the effect's `as @a` / `as @s` context, so `@s` is each
4586    /// acting player: at top level it damages every player once; inside a stealth
4587    /// `on_caught` it damages the caught player (the "caught → death → respawn at
4588    /// checkpoint" beat). `amount` is in **half-hearts** (1 HP each); an amount ≥ 40
4589    /// is lethal through golden apples / absorption. `within` (JSON `in`) narrows to
4590    /// acting players standing inside an anchor-centred box (the same box model as a
4591    /// stealth zone), keeping the per-`@s` semantics. `damage_type` is the damage
4592    /// type — a curated set of vanilla types that all respect `keepInventory` and do
4593    /// **not** bypass totems (no `out_of_world`/`generic_kill`); default `generic`.
4594    /// (The field is `damage_type`, not `type`, because the effect enum is
4595    /// internally tagged on `type`.)
4596    DamagePlayers {
4597        /// Damage dealt, in half-hearts (1 = 1 HP; ≥ 40 is effectively lethal).
4598        amount: u32,
4599        /// Optional spatial filter: only damage an acting player inside this
4600        /// anchor-centred box (`anchor ± extent`). Absent = every acting player.
4601        #[serde(default, rename = "in", skip_serializing_if = "Option::is_none")]
4602        within: Option<StealthZone>,
4603        /// The damage type (default [`DamageKind::Generic`]).
4604        #[serde(default, skip_serializing_if = "Option::is_none")]
4605        damage_type: Option<DamageKind>,
4606    },
4607    /// Sets the party-wide respawn checkpoint (DSL v0.6, spec-0012). Emits
4608    /// `spawnpoint @a` at the anchor cell and mirrors the coords into
4609    /// `storage dw:cp pos`. Party-wide and monotonic by quest order (a later
4610    /// `set-checkpoint` always replaces an earlier one). The compiler proves the
4611    /// cell is standable (`DW0316`) and that the remaining critical path stays
4612    /// reachable from it (`DW0315`).
4613    SetCheckpoint {
4614        /// The prefab checkpoint anchor the party respawns at.
4615        anchor: AnchorId,
4616        /// Per-player effects re-run each time a player respawns while this
4617        /// checkpoint is the active one — scene reset (e.g. re-caging an
4618        /// unleashed actor). Emitted idempotently in declared order; empty = no
4619        /// hook. Respawn is detected via the vanilla `deathCount` criterion.
4620        #[serde(default, skip_serializing_if = "Vec::is_empty")]
4621        on_respawn: Vec<QuestEffect>,
4622    },
4623    /// Places a **bonfire** rest point (DSL v0.6, spec-0016 §1) — the sibling of
4624    /// [`Verb::SetCheckpoint`] for souls-mode pacing. The effect *arms*
4625    /// the rest affordance (a `minecraft:interaction` the player right-clicks at
4626    /// the anchor, the campfire prop being prefab dressing); the checkpoint moves
4627    /// only **when the party actually rests**. Resting fires `on_rest` — the
4628    /// scene reset that makes retry cheap: re-arming traps, re-seating waves
4629    /// declared `respawns_on_rest`, restoring actor postures. Death respawns the
4630    /// party at the last-rested bonfire and runs the **same** `on_rest` bundle,
4631    /// so the world's answer to a death and to a rest is identical (spec-0016:
4632    /// death is an investment, never a tax).
4633    ///
4634    /// Proofs are inherited from the checkpoint machinery: the anchor must be
4635    /// standable (`DW0316`) and must not strand the party (`DW0315`), rooted at
4636    /// the beat that arms the bonfire (the earliest moment a rest can happen).
4637    Bonfire {
4638        /// The prefab anchor the rest affordance stands at, and the cell the
4639        /// party respawns at once rested.
4640        anchor: AnchorId,
4641        /// Effects re-run on every rest **and** on every respawn at this bonfire
4642        /// — the scene reset. Emitted in declared order and expected to be
4643        /// idempotent (the same contract as `set-checkpoint`'s `on_respawn`).
4644        #[serde(default, skip_serializing_if = "Vec::is_empty")]
4645        on_rest: Vec<QuestEffect>,
4646        /// Title of the two-option rest dialog (DSL v0.8).
4647        /// Absent = the compiler's canonical English `Bonfire`,
4648        /// baked at emit time (the `world.boundary.message` precedent): an
4649        /// authored line is inventoried and translates like every other
4650        /// player-visible string.
4651        #[serde(default, skip_serializing_if = "Option::is_none")]
4652        prompt: Option<String>,
4653        /// Label of the **rest and save** button. Absent = `Rest and save`.
4654        /// A dialog button is a fixed-width caption, so keep it to ~20 Latin /
4655        /// ~12 Han characters (skill *Writing craft* §C) — a wider label scrolls.
4656        #[serde(default, skip_serializing_if = "Option::is_none")]
4657        rest_label: Option<String>,
4658        /// Label of the **save only** button. Absent = `Save only`.
4659        #[serde(default, skip_serializing_if = "Option::is_none")]
4660        save_label: Option<String>,
4661    },
4662    /// Begins a stealth beat (DSL v0.6, spec-0014):
4663    /// zone presence alone = hidden — no sneak requirement, which collides with
4664    /// the spectator cutscene camera. While active, every player must be
4665    /// inside some `zone` each tick; a player outside every zone for
4666    /// `grace_ticks` fires `on_caught` (typically a kill → checkpoint respawn).
4667    /// Zone membership is read from the player's position. The compiler proves
4668    /// each zone is standable and reachable from the activating beat (`DW0327`).
4669    BeginStealth {
4670        /// The "shadow" regions, each an anchor-centred box (see [`StealthZone`]).
4671        zones: Vec<StealthZone>,
4672        /// Per-player effects fired when a player is caught (out of every zone
4673        /// for `grace_ticks`). Empty = no consequence.
4674        #[serde(default, skip_serializing_if = "Vec::is_empty")]
4675        on_caught: Vec<QuestEffect>,
4676        /// Ticks a player may be exposed before `on_caught` fires (default 20).
4677        #[serde(default = "default_grace_ticks")]
4678        grace_ticks: u32,
4679    },
4680    /// Ends the active stealth beat (DSL v0.6, spec-0014). No-op if none active.
4681    EndStealth,
4682    /// Summons a `deferred` stage-2 NPC (body + interaction hitbox + name display)
4683    /// at its declared anchor (DSL v0.6) — the dual of `despawn-npc`, and the
4684    /// scripted entrance a staged character needs. Idempotent: spawning an NPC
4685    /// already in the world is a no-op. Only meaningful for an NPC declared
4686    /// `deferred: true`; a non-deferred NPC is already in the world from init.
4687    SpawnNpc {
4688        /// The NPC (stage-2 ref) to summon.
4689        npc: NpcId,
4690    },
4691    // --- DSL v0.6 actor staging effects (spec-0014) ---
4692    /// Summons a stage-5 actor's puppet at its anchor (DSL v0.6). Idempotent: a
4693    /// spawn of an already-present actor is a no-op (re-caging after `unleash`).
4694    SpawnActor {
4695        /// The actor (stage-5 `actors` ref) to summon.
4696        actor: ActorId,
4697    },
4698    /// Removes an actor's puppet (DSL v0.6). `kill` plays the vanilla death
4699    /// animation (cutscene deaths); `vanish` is silent removal.
4700    DespawnActor {
4701        /// The actor (stage-5 `actors` ref) to remove.
4702        actor: ActorId,
4703        /// How the puppet is removed.
4704        style: DespawnStyle,
4705    },
4706    /// Walks an actor's puppet to an anchor by A*-planned per-tick teleport over
4707    /// the assembled model, using the actor's hitbox footprint, yawed along the
4708    /// path tangent (DSL v0.6). Concurrent movers are allowed (a herded
4709    /// flock is N synchronized `move-actor`s). Unroutable → `DW0325`. `on_arrive`
4710    /// effects fire once the puppet reaches the destination cell.
4711    MoveActor {
4712        /// The actor (stage-5 `actors` ref) to move.
4713        actor: ActorId,
4714        /// The destination anchor.
4715        to_anchor: AnchorId,
4716        /// Optional travel speed in blocks/tick (defaults to ~0.15).
4717        #[serde(default, skip_serializing_if = "Option::is_none")]
4718        speed: Option<f64>,
4719        /// Effects fired once the puppet arrives at the destination cell.
4720        #[serde(default, skip_serializing_if = "Vec::is_empty")]
4721        on_arrive: Vec<QuestEffect>,
4722    },
4723    /// Replaces an actor's puppet with a real-AI twin of the same type / position /
4724    /// name / attributes / tag (DSL v0.6) — the "attack the idle giant → real
4725    /// fight" beat. Re-caging is `despawn-actor` + `spawn-actor` (idempotent), not a
4726    /// special verb.
4727    UnleashActor {
4728        /// The actor (stage-5 `actors` ref) to unleash.
4729        actor: ActorId,
4730    },
4731    /// A deterministic timeline (DSL v0.6): one schedule chain firing effect groups
4732    /// at exact tick offsets. Effects are any in the stage-5 set except a nested
4733    /// `sequence` (rejected with `DW0329`).
4734    Sequence {
4735        /// Timeline steps; each fires its `effects` at `at_ticks` from the start.
4736        steps: Vec<SequenceStep>,
4737    },
4738    /// **Saturating projectile volley** (DSL v0.6, spec-0022): command-summoned
4739    /// projectiles with real velocity vectors, fired from a gallery slot into a
4740    /// declared kill zone.
4741    ///
4742    /// The contract is **saturation, not sniping**.
4743    /// Every salvo puts one projectile on the trajectory to **every standable
4744    /// cell of `kill_zone`**, plus one aimed at the triggering player's
4745    /// fire-time position (which punishes standing still). A player therefore
4746    /// cannot dodge a volley by strafing — escaping means *leaving the zone*, a
4747    /// decision rather than a lucky step. Coverage is proven at compile time:
4748    /// `from_anchor` must have clear line of fire to every standable kill-zone
4749    /// cell (`DW0442`), so "the gallery slot can actually hit a player anywhere
4750    /// on the stairs" is a build-time fact, not a hope.
4751    ///
4752    /// Projectiles are summoned `NoGravity` so the flown path is exactly the
4753    /// straight segment the coverage proof checks — proof and runtime share one
4754    /// geometry. Drag scales speed but not direction, so the line is preserved.
4755    Volley {
4756        /// Projectile entity id (default `minecraft:arrow`; validated against
4757        /// the pinned 1.21.11 registry, `DW0441`).
4758        #[serde(default, skip_serializing_if = "Option::is_none")]
4759        projectile: Option<String>,
4760        /// The gallery slot the volley is fired FROM — a point anchor. Its cell
4761        /// must be clear (a projectile spawned inside a wall never leaves it).
4762        from_anchor: AnchorId,
4763        /// The zone the volley must blanket, as an anchor-centred box
4764        /// (`anchor ± extent`) — the same shape `damage-players`'s `in` and
4765        /// `begin-stealth`'s `zones` use. Every standable cell in it receives
4766        /// fire each salvo.
4767        ///
4768        /// Deliberately NOT a bare prefab `region` anchor: the assembled model
4769        /// clears every gate-region anchor's cells unconditionally, so
4770        /// describing a zone that way would delete the geometry it names.
4771        kill_zone: StealthZone,
4772        /// How many rounds the pattern repeats (default 3, `DW0443` bounds it).
4773        #[serde(default, skip_serializing_if = "Option::is_none")]
4774        salvos: Option<u32>,
4775        /// Ticks between salvos (default 10, `DW0443` bounds it).
4776        #[serde(default, skip_serializing_if = "Option::is_none")]
4777        interval: Option<u32>,
4778    },
4779    /// **Ceiling collapse** (DSL v0.6, spec-0022): delete a region's blocks and
4780    /// drop them as `falling_block` entities — the buried-alive trap redstone
4781    /// cannot express at all.
4782    ///
4783    /// The post-collapse world is **modeled, not guessed**: the compiler clears
4784    /// the region, settles every dropped column through the existing gravity
4785    /// model (spec-0010), optionally paves the landing surface with
4786    /// `then_floor`, and re-runs the critical-path completability proof against
4787    /// that mutated world (`DW0445`). A collapse that buries the only route is a
4788    /// build error, exactly as a `shortcut` seal that strands the party is.
4789    Collapse {
4790        /// The volume whose blocks fall, as an anchor-centred box
4791        /// (`anchor ± extent`). Must hold blocks and sit above standable footing
4792        /// (`DW0444`) — a collapse over nothing is scenery, not a trap.
4793        ///
4794        /// An anchor-centred box rather than a prefab `region` anchor for a
4795        /// load-bearing reason: the assembled model deletes every gate-region
4796        /// anchor's cells, so a ceiling slab declared that way would already be
4797        /// gone before the trap ever fired.
4798        region_anchor: StealthZone,
4799        /// The block the falling entities are made of (default
4800        /// `minecraft:gravel`; validated against the pinned registry, `DW0441`).
4801        #[serde(default, skip_serializing_if = "Option::is_none")]
4802        falling_block: Option<String>,
4803        /// Optional block the landing surface is paved with once the debris
4804        /// settles — the authored post-collapse floor the completability proof
4805        /// reasons over.
4806        #[serde(default, skip_serializing_if = "Option::is_none")]
4807        then_floor: Option<String>,
4808    },
4809    /// Grants a vanilla **status effect** for a stated duration (DSL v0.10,
4810    /// spec-0031). The engine has emitted status effects since v0.6 — the
4811    /// night-vision area mitigation is a self-rescheduling, region-scoped
4812    /// `effect give` — and exposed none, so an author who wanted blindness for a
4813    /// lift ride, slowness in deep water or regeneration at a shrine had no
4814    /// surface at all. This is that surface, over the whole pinned 1.21.11
4815    /// `mob_effect` registry (`DW0192` rejects an id outside it).
4816    ///
4817    /// **A grant carries a duration, and there is no way to spell one that does
4818    /// not.** Vanilla's `infinite` keyword is deliberately absent from this
4819    /// surface: an effect whose only removal is a later command is an effect the
4820    /// player keeps forever whenever that command does not run — a logout, a
4821    /// crash, a chain interrupted by a death. A duration expires on its own, with
4822    /// no cooperation from anything. `seconds` is therefore required and bounded
4823    /// (1..=[`MAX_EFFECT_SECONDS`], `DW0541`), and the *pattern* that reintroduces
4824    /// the same hazard — pairing a grant with a `clear-effect` that removes it
4825    /// while it is still live — is `DW0540`.
4826    ///
4827    /// `in` narrows to players inside an anchor-centred box, the same
4828    /// [`StealthZone`] a `begin-stealth` zone, a `damage-players` filter and a
4829    /// `lethal_volumes[]` region use, resolved through the one `Plan::zone_box`.
4830    /// It is what makes "blind whoever is riding the car" expressible without
4831    /// blinding the whole party.
4832    GiveEffect {
4833        /// Vanilla status-effect id (e.g. `minecraft:blindness`), validated
4834        /// against the pinned 1.21.11 registry (`DW0192`).
4835        effect: String,
4836        /// Duration in seconds. Required, `1..=`[`MAX_EFFECT_SECONDS`]
4837        /// (`DW0541`) — see the variant docs for why there is no infinite form.
4838        seconds: u32,
4839        /// Amplifier (0 = level I), `0..=`[`MAX_POTION_AMPLIFIER`] (`DW0541`).
4840        /// Absent = 0.
4841        #[serde(default, skip_serializing_if = "Option::is_none")]
4842        amplifier: Option<u32>,
4843        /// Suppress the swirling particles (vanilla's `hideParticles`). Absent =
4844        /// `false`, vanilla's own default.
4845        #[serde(default, skip_serializing_if = "Option::is_none")]
4846        hide_particles: Option<bool>,
4847        /// Optional spatial filter: only grant to a player inside this
4848        /// anchor-centred box (`anchor ± extent`). Absent = every player the
4849        /// effect's audience addresses.
4850        #[serde(default, rename = "in", skip_serializing_if = "Option::is_none")]
4851        within: Option<StealthZone>,
4852    },
4853    /// Removes a status effect (DSL v0.10, spec-0031) — vanilla's `effect clear`.
4854    ///
4855    /// This is **not** how a `give-effect` is supposed to end: a duration is. It
4856    /// exists for the effects the engine did not grant — a potion the player
4857    /// drank, a `wither` a mob applied, the whole set at a bonfire — which is why
4858    /// `effect` is optional (absent = clear everything, exactly as vanilla's
4859    /// `effect clear <targets>` does). Pairing it with a live grant of the same
4860    /// effect in the same bundle is `DW0540`.
4861    ClearEffect {
4862        /// The status-effect id to remove (`DW0192`). **Absent clears every
4863        /// effect**, matching `effect clear <targets>` with no id.
4864        #[serde(default, skip_serializing_if = "Option::is_none")]
4865        effect: Option<String>,
4866        /// Optional spatial filter, identical in shape and meaning to
4867        /// [`Verb::GiveEffect`]'s.
4868        #[serde(default, rename = "in", skip_serializing_if = "Option::is_none")]
4869        within: Option<StealthZone>,
4870    },
4871    /// Teleports **everything inside a declared volume** to an anchor (DSL v0.10,
4872    /// spec-0031).
4873    ///
4874    /// **The selector is a region, never a block.** "Whoever is standing on this
4875    /// block" has three different answers for a player half a foot over the edge,
4876    /// a player mid-jump and a player sneaking on the lip; a volume has one, and
4877    /// it is the same one every tick. `from` is the anchor-centred
4878    /// [`StealthZone`] box the rest of the engine already uses.
4879    ///
4880    /// **The selection is total over bodies.** Emission is a single `tp
4881    /// @e[<box>,tag=!dw_fixture] <cell>` with no `type=`, no `limit=` and no
4882    /// `sort=` — every body in the volume moves, and
4883    /// `crates/delvec/tests/v10_teleport.rs` asserts that from the emitted
4884    /// selector rather than from anyone's memory. A machinery-**type** exemption
4885    /// of the kind a `lethal_volumes[]` entry must carry was considered and
4886    /// **rejected**: an NPC is a body plus a co-located `minecraft:interaction`
4887    /// hitbox, so exempting `minecraft:interaction` — as the lethal volume does —
4888    /// would teleport the speaker and leave its dialogue box behind. Everyone on
4889    /// the car travels, players and entities
4890    /// alike; totality over bodies is how that is true.
4891    ///
4892    /// The one narrowing is a **class the engine's own furniture declares about
4893    /// itself**: `dw_fixture` means *my position IS engine state*. A bonfire's
4894    /// hitbox, a shortcut lever and a recovery stake's marker are places, not
4895    /// passengers, and carrying one does not move a thing — it rewrites a fact
4896    /// (for a stake, the ledger holds the marker's coordinates, and the next tick
4897    /// retires a marker nobody has a wager at). Places whose cell is known at
4898    /// compile time are refused outright instead, because the author can move
4899    /// them (`DW0542`); places the runtime puts down are excluded by the selector,
4900    /// because nobody can (`DW0545`). Nothing an author writes carries either tag,
4901    /// and no campaign JSON can turn either off.
4902    ///
4903    /// **A teleport is not a rescue.** Accumulated fall distance carries across
4904    /// one unchanged and is charged in full at the destination — measured Δ
4905    /// exactly `0.0000` in 46/46 trials on the pinned 1.21.11, including
4906    /// teleports 143 and 157 blocks straight *up*, with landing damage
4907    /// `floor(fall_distance) − 3` (`docs/notes/death-and-teleport-spike.md` §3).
4908    /// A platform that arrives under a falling player past ~20 blocks of fall is
4909    /// the surface they die on. The compiler does not try to reset the counter:
4910    /// what *does* reset it was explicitly not measured, and inventing a
4911    /// mechanism from recall is the folklore this project forbids.
4912    Teleport {
4913        /// The volume whose contents are moved, as an anchor-centred box
4914        /// (`anchor ± extent`) — the same shape a `begin-stealth` zone, a
4915        /// `damage-players` `in` filter and a `lethal_volumes[]` region take.
4916        ///
4917        /// Deliberately NOT a bare prefab `region` anchor, for the reason
4918        /// [`Verb::Collapse`] records: the assembled model clears every
4919        /// gate-region anchor's cells, so a volume described that way would
4920        /// delete the geometry it names.
4921        from: StealthZone,
4922        /// The destination anchor. Resolved to a literal cell at build time, so
4923        /// the emitted `tp` carries absolute coordinates and no runtime search.
4924        to: AnchorId,
4925    },
4926}
4927
4928/// Default `grace_ticks` for [`Verb::BeginStealth`] (spec-0014).
4929fn default_grace_ticks() -> u32 {
4930    20
4931}
4932
4933/// Default projectile for [`Verb::Volley`] (spec-0022).
4934pub const DEFAULT_VOLLEY_PROJECTILE: &str = "minecraft:arrow";
4935/// Default salvo count for [`Verb::Volley`] (spec-0022).
4936pub const DEFAULT_VOLLEY_SALVOS: u32 = 3;
4937/// Default ticks between salvos for [`Verb::Volley`] (spec-0022).
4938pub const DEFAULT_VOLLEY_INTERVAL: u32 = 10;
4939/// Largest admissible `salvos` — beyond this a volley is an entity-count
4940/// hazard rather than a trap (`DW0443`).
4941pub const MAX_VOLLEY_SALVOS: u32 = 16;
4942/// Largest admissible `interval` in ticks (`DW0443`): 10 seconds. A volley
4943/// slower than this is no longer one event the player reads as a trap.
4944pub const MAX_VOLLEY_INTERVAL: u32 = 200;
4945/// Default falling block for [`Verb::Collapse`] (spec-0022).
4946pub const DEFAULT_COLLAPSE_FALLING_BLOCK: &str = "minecraft:gravel";
4947
4948/// A stealth "shadow" region (DSL v0.6, spec-0014): an axis-aligned box centred
4949/// on `anchor`, extending `extent` blocks along each axis (so the box spans
4950/// `anchor ± extent`). Presented in-world via dark cells but judged purely by
4951/// region membership, so the check is deterministic and provable.
4952#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
4953#[serde(deny_unknown_fields)]
4954pub struct StealthZone {
4955    /// The prefab anchor at the centre of the zone box.
4956    pub anchor: AnchorId,
4957    /// Half-extents `[x, y, z]` in blocks from the anchor (each component ≥ 0);
4958    /// the zone AABB is `[anchor - extent, anchor + extent]`.
4959    pub extent: [u32; 3],
4960}
4961
4962/// Where a [`Verb::PlaySound`] originates (DSL v0.6, spec-0014). A sound
4963/// plays at fixed coordinates or at each listener's own position; the compiler
4964/// resolves no position for a live actor, so the `actor` variant is accepted by
4965/// the schema and rejected with `DW0335`.
4966#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
4967#[serde(tag = "at", rename_all = "kebab-case", deny_unknown_fields)]
4968pub enum SoundAt {
4969    /// Play the sound positioned at a resolved anchor, audible to all players.
4970    Anchor {
4971        /// The anchor the sound plays from.
4972        anchor: AnchorId,
4973    },
4974    /// Play the sound at each player's own position (the default).
4975    Players,
4976    /// Play the sound at a scripted actor's position (rejected — `DW0335`; no
4977    /// actor position resolves at emission).
4978    Actor {
4979        /// The actor id (stage-5 `actors[]`).
4980        actor: String,
4981    },
4982}
4983
4984/// The damage type of a [`Verb::DamagePlayers`] effect (DSL v0.6). A
4985/// **curated** subset of the vanilla 1.21.11 damage-type registry: every variant
4986/// respects the `keepInventory` death flow (a gamerule, so all deaths do) and does
4987/// **not** bypass a totem of undying — the totem-bypassing `out_of_world` /
4988/// `generic_kill` types are deliberately excluded, so a scripted consequence can
4989/// never silently void a player's held totem. Modelled as an enum (not a free
4990/// string) so an unknown type is a schema rejection (`DW0100`) and needs no separate
4991/// registry / diagnostic. `generic` is the default: command damage that respects
4992/// totems + absorption but ignores armor, so a scripted hit lands regardless of gear.
4993#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
4994#[serde(rename_all = "kebab-case")]
4995pub enum DamageKind {
4996    /// `minecraft:generic` — armor-ignoring command damage (default).
4997    Generic,
4998    /// `minecraft:magic` — magical damage.
4999    Magic,
5000    /// `minecraft:wither` — the wither/withering effect's damage type.
5001    Wither,
5002    /// `minecraft:on_fire` — burning damage.
5003    Fire,
5004    /// `minecraft:drown` — drowning damage.
5005    Drown,
5006    /// `minecraft:freeze` — powder-snow freezing damage.
5007    Freeze,
5008    /// `minecraft:fall` — fall damage.
5009    Fall,
5010    /// `minecraft:lightning_bolt` — a lightning strike's damage type.
5011    LightningBolt,
5012    /// `minecraft:explosion` — a (non-player) explosion's damage type.
5013    Explosion,
5014}
5015
5016impl DamageKind {
5017    /// The vanilla `minecraft:` damage-type id emitted to `/damage`.
5018    pub fn id(self) -> &'static str {
5019        match self {
5020            DamageKind::Generic => "minecraft:generic",
5021            DamageKind::Magic => "minecraft:magic",
5022            DamageKind::Wither => "minecraft:wither",
5023            DamageKind::Fire => "minecraft:on_fire",
5024            DamageKind::Drown => "minecraft:drown",
5025            DamageKind::Freeze => "minecraft:freeze",
5026            DamageKind::Fall => "minecraft:fall",
5027            DamageKind::LightningBolt => "minecraft:lightning_bolt",
5028            DamageKind::Explosion => "minecraft:explosion",
5029        }
5030    }
5031}
5032
5033/// A stage-5 **lethal volume** (DSL v0.10, spec-0031): a declared box that kills
5034/// whatever enters it, and states — in the campaign's own words — what killed it.
5035///
5036/// # A mechanism, not a fiction
5037///
5038/// The commissioning case was a cliff whose fall must be fatal, but nothing here
5039/// knows what a cliff is: a lava pit, an acid pool, an out-of-bounds plane and the
5040/// bottom of a lift shaft are the same declaration, differently dressed and
5041/// differently worded. The alternative considered and **rejected** for the cliff
5042/// was making the world's horizon void so the fall kills anyway — that changes
5043/// approved art to obtain a behaviour, and it serves exactly one fiction.
5044///
5045/// # It is geometry, so the completability proof owns it
5046///
5047/// A volume that kills is, for a route, a volume that cannot be crossed. The
5048/// compiler models its cells as impassable in the same navigation world every
5049/// other reachability proof runs on, exactly as a `close-gate`'s sealed region is
5050/// modelled solid — so a forced path that has no way to an objective except
5051/// through a lethal volume is a build failure (`DW0510`) naming the volume, never
5052/// a shipped delve that kills the player on the critical path. A respawn seat
5053/// inside one is the death loop that failure mode ends in, and is its own
5054/// error (`DW0511`).
5055///
5056/// # It rides the death edge that already exists
5057///
5058/// The kill is a `/damage`, exactly like `damage-players`, a trap payload or a
5059/// timed gate's crush. Everything downstream — the vanilla `deathCount` edge
5060/// (`dw.deaths` / `dw.death_ack`), the checkpoint re-seat (`cp_respawn_check`),
5061/// `keep_inventory` — sees an ordinary death and needs no second detector.
5062#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5063#[serde(deny_unknown_fields)]
5064pub struct LethalVolume {
5065    /// Unique lethal-volume id (`lethal/<kebab>`).
5066    pub id: LethalVolumeId,
5067    /// The volume: an anchor-centred box (`anchor ± extent`).
5068    ///
5069    /// **Deliberately the existing zone type**, not a second struct with the same
5070    /// two fields. `StealthZone` is already the engine's anchor-centred box object
5071    /// class — `damage-players`'s `in` filter reuses it, and the compiler resolves
5072    /// every one of them through the single `Plan::zone_box`. A private twin here
5073    /// would be `tools/check-capability-ownership.py` check C by construction, and
5074    /// would fork the resolution the very next time a box grew a capability.
5075    pub region: StealthZone,
5076    /// What this volume says when it kills — a player-visible line, inventoried
5077    /// under `lethal.<id>.message` and translated like every other one.
5078    ///
5079    /// Required, and deliberately so: a volume with no words is a player who dies
5080    /// with no idea why, and there is no compiler-owned default that could be
5081    /// right for a cliff, a lava pit and an acid pool at once.
5082    pub message: String,
5083    /// The damage type the kill is dealt with (default [`DamageKind::Generic`]).
5084    ///
5085    /// This is what words vanilla's own broadcast — `fall` says the party member
5086    /// fell from a high place, `on_fire` that they burnt to a crisp — while
5087    /// [`Self::message`] says what the *place* was. The curated enum is shared
5088    /// with `damage-players`, so a lethal volume can no more void a held totem
5089    /// than a scripted hit can.
5090    #[serde(default, skip_serializing_if = "Option::is_none")]
5091    pub damage_type: Option<DamageKind>,
5092}
5093
5094// ---------------------------------------------------------------------------
5095// Stage 5 — trade and the recovery stake (DSL v0.10, spec-0032)
5096// ---------------------------------------------------------------------------
5097
5098/// A stage-5 **shop** (DSL v0.10, spec-0032): an interaction point that opens a
5099/// list of offers, each of which is a gate and a bundle of effects.
5100///
5101/// # It is the rest flow with different buttons, and that is the whole design
5102///
5103/// A bonfire is already an interaction entity, a player-interaction advancement
5104/// that supplies the acting player, a `minecraft:multi_action` dialog, buttons
5105/// that run `/trigger`, and tick dispatch. A shop is that same hardware with an
5106/// authored button list, so nothing here is new machinery — it is the machinery
5107/// spec-0016 §1 shipped, made author-visible.
5108///
5109/// # There is no price field, and that is deliberate
5110///
5111/// A price is *"may this happen yet?"*, which is the question
5112/// [`Gate`](crate::gate::Gate) answers for six other object classes. An offer is
5113/// therefore the **seventh gate consumer**: it carries `requires_flags`,
5114/// `forbids_flags` and `requires_state`, and the numeric comparison it needs is
5115/// the one spec-0031 put in the gate rather than in the verb that first asked.
5116/// A `price` field would be a second comparison surface for one meaning, which is
5117/// the defect CLAUDE.md names first.
5118///
5119/// # Villager `Offers` is excluded
5120///
5121/// Three independent reasons, any one sufficient (spec-0032): a vanilla trade
5122/// cost can only ever be an item, never a scoreboard value; right-click on a
5123/// villager body is already allocated to dialogue; and the data-driven trade
5124/// registry post-dates the pinned 1.21.11.
5125#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5126#[serde(deny_unknown_fields)]
5127pub struct Shop {
5128    /// Unique shop id (`shop/<kebab>`).
5129    pub id: ShopId,
5130    /// The prefab anchor the shop's interaction point stands on.
5131    pub anchor: AnchorId,
5132    /// The dialog's title line. Player-visible, inventoried under
5133    /// `shop.<id>.title`.
5134    pub title: String,
5135    /// The item the visible marker renders as (default `minecraft:emerald`).
5136    /// Cosmetic only: the marker is a `minecraft:item_display`, so it never
5137    /// occupies the cell or obstructs the hitbox.
5138    #[serde(default, skip_serializing_if = "Option::is_none")]
5139    pub marker_item: Option<String>,
5140    /// The offers, in declaration order — which is button order, and the order
5141    /// the `/trigger` routing values are assigned in.
5142    pub offers: Vec<ShopOffer>,
5143}
5144
5145/// One button in a [`Shop`]: a gate, a label, and the effects choosing it runs.
5146///
5147/// **Effect root R8.** The bundle hangs off an object with runtime machinery of
5148/// its own (an advancement, a dialog, a trigger objective and a tick dispatch),
5149/// which is spec-0031's stated rule for adding a root rather than desugaring.
5150///
5151/// **Refusal is authored, not a field.** An offer whose own gate is closed is not
5152/// shown at all; an offer that should be *shown and refuse* leaves its own gate
5153/// open and gates its effects instead — the purchase behind `at-least <price>`,
5154/// the apology behind `at-most <price − 1>`. Both are the ordinary per-effect
5155/// gate every effect already carries, so the engine adds no `refused` field and
5156/// no second way to say one thing.
5157#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5158#[serde(deny_unknown_fields)]
5159pub struct ShopOffer {
5160    /// The button's caption. Player-visible, inventoried under
5161    /// `shop.<id>.offer.<i>.label`, and width-checked like any dialog button.
5162    pub label: String,
5163    /// The button's hover tooltip — the natural home for a price in words.
5164    /// Player-visible, inventoried under `shop.<id>.offer.<i>.tooltip`.
5165    #[serde(default, skip_serializing_if = "Option::is_none")]
5166    pub tooltip: Option<String>,
5167    /// Flags that must all be set for this offer to be shown (the one gate).
5168    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5169    pub requires_flags: Vec<FlagId>,
5170    /// Flags whose being set hides this offer (the one gate).
5171    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5172    pub forbids_flags: Vec<FlagId>,
5173    /// Numeric gate terms (the one gate) — **this is where a price lives**.
5174    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5175    pub requires_state: Vec<StateCompare>,
5176    /// What choosing this offer does. Effect root R8; runs with the choosing
5177    /// player as the acting player, so a `player`-scoped datum is writable here.
5178    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5179    pub effects: Vec<QuestEffect>,
5180}
5181
5182impl ShopOffer {
5183    /// This offer's whole gate, as one value (DSL v0.10) — see
5184    /// [`crate::gate::Gate`].
5185    pub fn gate(&self) -> crate::gate::Gate<'_> {
5186        crate::gate::Gate::of(
5187            &self.requires_flags,
5188            &self.forbids_flags,
5189            &self.requires_state,
5190        )
5191    }
5192}
5193
5194/// How much of a datum a death forfeits into a [`Stake`] (DSL v0.10, spec-0032).
5195///
5196/// A creator who wants **no death cost at all** picks [`Forfeit::None`]; the
5197/// stake then still marks where they fell, which is the memorial case.
5198#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
5199#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
5200pub enum Forfeit {
5201    /// The whole balance.
5202    All,
5203    /// A percentage of the balance, rounded toward zero (integer arithmetic —
5204    /// ADR-0006 forbids anything a second implementation could round differently).
5205    Proportion {
5206        /// 0–100.
5207        percent: u32,
5208    },
5209    /// A fixed amount, capped at the balance so a purse can never go negative.
5210    Fixed {
5211        /// The amount.
5212        amount: i32,
5213    },
5214    /// Nothing is taken. The stake is a marker, not a wager.
5215    None,
5216}
5217
5218/// What a death does when the player already holds the maximum number of live
5219/// stakes (DSL v0.10, spec-0032).
5220#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
5221#[serde(rename_all = "kebab-case")]
5222pub enum OnFull {
5223    /// Retire the player's oldest live stake — its contents are lost — and place a
5224    /// new one. With `max_live: 1` this is the souls behaviour.
5225    Replace,
5226    /// Leave the existing stakes alone: the new death places nothing and forfeits
5227    /// nothing. One wager at a time.
5228    Keep,
5229}
5230
5231impl OnFull {
5232    /// The wire token (`replace` / `keep`).
5233    pub fn token(self) -> &'static str {
5234        match self {
5235            OnFull::Replace => "replace",
5236            OnFull::Keep => "keep",
5237        }
5238    }
5239}
5240
5241/// Who may collect a stake that is not theirs (DSL v0.10, spec-0032).
5242#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
5243#[serde(rename_all = "kebab-case")]
5244pub enum CollectBy {
5245    /// Only the player who left it. The default.
5246    Owner,
5247    /// Anyone standing at it. The whole of every live stake at that place is
5248    /// transferred to the collector.
5249    Anyone,
5250}
5251
5252impl CollectBy {
5253    /// The wire token (`owner` / `anyone`).
5254    pub fn token(self) -> &'static str {
5255        match self {
5256            CollectBy::Owner => "owner",
5257            CollectBy::Anyone => "anyone",
5258        }
5259    }
5260}
5261
5262/// A stage-5 **recovery stake** (DSL v0.10, spec-0032): what a death leaves
5263/// behind, and the one chance to get it back.
5264///
5265/// # A mechanism, not a genre
5266///
5267/// "Souls" is one setting of this declaration and nothing here knows the word.
5268/// The mechanism is *a death forfeits some of a declared datum into a collectable
5269/// marker at a computed place, and collecting it returns exactly what was taken*.
5270/// A campaign with no death cost, a campaign with a permanent memorial at every
5271/// death site, and a campaign with the souls loop are three configurations, not
5272/// three engines.
5273///
5274/// # Where it lands is a compile-time answer
5275///
5276/// The owner's rule: *the anchor is the point, on the walkable path
5277/// from the respawn point in force at the moment of death to the death point
5278/// under the quest state in force at that moment, that minimises distance to the
5279/// death point.* Every term already has an owner in the compiler — walkability is
5280/// the navigation world the completability proof runs on, quest-state passability
5281/// is the DAG-indexed sealing `close-gate` established, and the respawn point in
5282/// force is engine state. So it is a table computed at build time and a lookup at
5283/// run time: **no runtime search, no nondeterminism.**
5284///
5285/// # It is hardware, so it inherits the hardware rules
5286///
5287/// The marker is an invisible `minecraft:interaction` for the hitbox plus a
5288/// glowing `minecraft:item_display` for the rendering — the same pair every other
5289/// affordance in the engine uses, and therefore the same invisible-affordance
5290/// (`DW0420`) and hardware-erasure (`DW0421`) proofs. It is deliberately **not**
5291/// a dropped item entity: an item despawns after 6000 ticks, burns in lava, sinks
5292/// in the void, and can be picked up by anyone.
5293#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5294#[serde(deny_unknown_fields)]
5295pub struct Stake {
5296    /// Unique stake id (`stake/<kebab>`).
5297    pub id: StakeId,
5298    /// The datum a death forfeits into this stake, and a collection returns.
5299    /// Must be declared in the stage-5 `state` list, and must be `player`-scoped:
5300    /// a stake is a personal wager, and a party-shared purse would turn one
5301    /// player's death into everyone's penalty.
5302    pub state: StateId,
5303    /// How much of [`Self::state`] a death takes. Default: the whole balance.
5304    #[serde(default, skip_serializing_if = "Option::is_none")]
5305    pub forfeit: Option<Forfeit>,
5306    /// How many live stakes one player may hold at once. Default 1; `0` means a
5307    /// death never places one (and never forfeits anything), which is the
5308    /// "no death cost" configuration.
5309    #[serde(default, skip_serializing_if = "Option::is_none")]
5310    pub max_live: Option<u32>,
5311    /// What a death does when the player is already at [`Self::max_live`].
5312    /// Default [`OnFull::Replace`].
5313    #[serde(default, skip_serializing_if = "Option::is_none")]
5314    pub on_full: Option<OnFull>,
5315    /// Who may collect. Default [`CollectBy::Owner`].
5316    #[serde(default, skip_serializing_if = "Option::is_none")]
5317    pub collect_by: Option<CollectBy>,
5318    /// The line a collection says, on the action bar. Player-visible, inventoried
5319    /// under `stake.<id>.collected`.
5320    pub collected_message: String,
5321    /// The item the glowing marker renders as (default `minecraft:soul_lantern`).
5322    #[serde(default, skip_serializing_if = "Option::is_none")]
5323    pub marker_item: Option<String>,
5324}
5325
5326impl Stake {
5327    /// The forfeit rule, with the documented default applied.
5328    pub fn forfeit(&self) -> Forfeit {
5329        self.forfeit.unwrap_or(Forfeit::All)
5330    }
5331
5332    /// How many live stakes one player may hold, with the documented default.
5333    pub fn max_live(&self) -> u32 {
5334        self.max_live.unwrap_or(1)
5335    }
5336
5337    /// The at-capacity rule, with the documented default.
5338    pub fn on_full(&self) -> OnFull {
5339        self.on_full.unwrap_or(OnFull::Replace)
5340    }
5341
5342    /// The collection rule, with the documented default.
5343    pub fn collect_by(&self) -> CollectBy {
5344        self.collect_by.unwrap_or(CollectBy::Owner)
5345    }
5346
5347    /// The item the marker renders as, with the documented default.
5348    pub fn marker_item(&self) -> &str {
5349        self.marker_item
5350            .as_deref()
5351            .unwrap_or("minecraft:soul_lantern")
5352    }
5353}
5354
5355/// The presentation channel for a [`Verb::Narrate`] (DSL v0.4).
5356#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
5357#[serde(rename_all = "kebab-case")]
5358pub enum NarrateStyle {
5359    /// A chat line (default).
5360    Chat,
5361    /// A large on-screen title.
5362    Title,
5363    /// An on-screen subtitle.
5364    Subtitle,
5365    /// An "art" title rendered through the delve's custom resource-pack pixel-banner
5366    /// font (`delve:art`) so endings can flash blocky all-caps text (DSL v0.6,
5367    /// spec-0014). Text is checked at compile time against the font's glyph inventory
5368    /// (`DW0328`); characters outside it (e.g. non-Latin script) are rejected. It
5369    /// renders in the vanilla title slot, so it is width-checked like any title
5370    /// (`DW0330`) — roughly 15 glyphs fit on screen.
5371    Art,
5372    /// The **actionbar** — the one-line strip above the hotbar (DSL v0.11).
5373    ///
5374    /// This is the channel a *reply* uses: it does not interrupt, it does not
5375    /// stack, and it is overwritten by the next one. Every reply the compiler
5376    /// itself writes has always used it — a sealed gate's answer, a checkpoint
5377    /// return, the lobby's party count — but `narrate` could not reach it, which
5378    /// is the mechanical reason `close-gate.sealed_hint` could not have been an
5379    /// ordinary `narrate` even had someone tried (capability-ownership audit
5380    /// finding 3b). A channel is a property of the message, not of the verb that
5381    /// first wanted it.
5382    ///
5383    /// Unlike a title it is never width-checked: vanilla truncates nothing and
5384    /// draws it at GUI width, and a reply is a fragment rather than a banner.
5385    Actionbar,
5386}
5387
5388impl NarrateStyle {
5389    /// The kebab tag (`chat` / `title` / `subtitle` / `art` / `actionbar`).
5390    pub fn token(self) -> &'static str {
5391        match self {
5392            NarrateStyle::Chat => "chat",
5393            NarrateStyle::Title => "title",
5394            NarrateStyle::Subtitle => "subtitle",
5395            NarrateStyle::Art => "art",
5396            NarrateStyle::Actionbar => "actionbar",
5397        }
5398    }
5399}
5400
5401/// One camera waypoint of a [`Verb::Cutscene`] (DSL v0.4): an anchor plus
5402/// an integer block offset from it, giving the camera's world position.
5403#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5404#[serde(deny_unknown_fields)]
5405pub struct CameraWaypoint {
5406    /// The anchor the waypoint is relative to.
5407    pub anchor: AnchorId,
5408    /// Integer `[x, y, z]` block offset from the anchor (default `[0, 0, 0]`).
5409    #[serde(default, skip_serializing_if = "is_zero3")]
5410    pub offset: [i32; 3],
5411}
5412
5413/// One shot of a [`Verb::Cutscene`] (DSL v0.6): a camera dolly with its
5414/// own duration and optional subject. A cutscene plays its shots back-to-back —
5415/// a hard cut between them — inside a single gamemode/position save-restore
5416/// bracket, so a wide establishing move can be followed by an interior close-up
5417/// without the players ever leaving the cinematic.
5418#[derive(Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
5419#[serde(deny_unknown_fields)]
5420pub struct CameraShot {
5421    /// Ordered camera waypoints (straight-line lerp between them). A one-waypoint
5422    /// path is a static shot. Required without `shot_style`; with one, optional —
5423    /// an explicit `path` always overrides the style's expanded dolly.
5424    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5425    pub path: Vec<CameraWaypoint>,
5426    /// This shot's duration in seconds. Required without `shot_style`; with one,
5427    /// optional — the style's default duration applies (see
5428    /// [`ShotStyle::default_seconds`]), and an explicit value always overrides.
5429    #[serde(default, skip_serializing_if = "Option::is_none")]
5430    pub seconds: Option<u32>,
5431    /// Optional subject the camera keeps framed for this shot. Absent = face
5432    /// along the direction of travel (or, under a `shot_style`, the style's own
5433    /// aim at its `subject`). An explicit `look_at` always overrides a style's
5434    /// aim.
5435    #[serde(default, skip_serializing_if = "Option::is_none")]
5436    pub look_at: Option<CameraTarget>,
5437    /// Shot-style preset (DSL v0.6, spec-0015 shot-grammar library): the
5438    /// compiler expands the style deterministically into a camera dolly +
5439    /// per-keyframe aim from the `subject`'s resolved geometry. Requires
5440    /// `subject`; `path`/`look_at`/`seconds` remain legal and always override
5441    /// the corresponding expanded part (`DW0348` polices the combinations).
5442    #[serde(default, skip_serializing_if = "Option::is_none")]
5443    pub shot_style: Option<ShotStyle>,
5444    /// The styled shot's subject — what the shot is *about*. Required with
5445    /// `shot_style`, rejected without one (`DW0348`).
5446    #[serde(default, skip_serializing_if = "Option::is_none")]
5447    pub subject: Option<CameraSubject>,
5448    /// `two-shot` only: the second framed subject (`DW0348` elsewhere).
5449    #[serde(default, skip_serializing_if = "Option::is_none")]
5450    pub subject_b: Option<CameraSubject>,
5451    /// Styled shots only: the style's characteristic camera distance in blocks
5452    /// (its *start* distance for the dolly styles). Default per style — see the
5453    /// `shot_style` table in `docs/reference/compiler.md`. Clamped range 1..=48
5454    /// (`DW0348`).
5455    #[serde(default, skip_serializing_if = "Option::is_none")]
5456    pub dist: Option<f64>,
5457    /// `orbit-arc` only: the sweep in degrees, 45..=120 (dossier range),
5458    /// default 90 (`DW0348` elsewhere or out of range).
5459    #[serde(default, skip_serializing_if = "Option::is_none")]
5460    pub degrees: Option<f64>,
5461    /// Styled shots only: placement bearing in degrees — where the camera sits
5462    /// (or starts) relative to the subject, measured like a Minecraft yaw
5463    /// *from* the subject: `0` puts the camera south of the subject (+Z), `90`
5464    /// west (−X), `-90` east (+X), `180` north (−Z). Default `0`. For
5465    /// `side-track` the bearing picks which side of the subject's travel the
5466    /// camera runs abeam (`0` = right of travel, `180` = left).
5467    #[serde(default, skip_serializing_if = "Option::is_none")]
5468    pub bearing: Option<f64>,
5469}
5470
5471/// A `shot_style` preset (DSL v0.6): the dossier's 9-template library
5472/// (`docs/notes/camera-dossier.md` §2), each expanded deterministically by the
5473/// compiler into a dolly + aim from the subject's geometry. Camera "lens feel"
5474/// is **distance only** — vanilla has no in-game FOV control.
5475#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
5476#[serde(rename_all = "kebab-case")]
5477pub enum ShotStyle {
5478    /// Fully static close framing of a prop/detail. The beat that always looks
5479    /// right.
5480    Insert,
5481    /// Static position; only the aim turns as the subject (ideally moving)
5482    /// passes. Rockstar's roadside "ground view".
5483    LockedOff,
5484    /// Straight dolly toward the subject along the view axis; medium → close.
5485    PushIn,
5486    /// Reverse of `push-in`: close → wide, revealing context.
5487    PullBackReveal,
5488    /// High and far, descending and closing on the subject. First sight of an
5489    /// area.
5490    EstablishingCrane,
5491    /// Constant-radius, constant-height arc around the subject.
5492    OrbitArc,
5493    /// Parallel dolly abeam a **moving** subject at constant offset — needs a
5494    /// compiler-known subject path (`DW0349`).
5495    SideTrack,
5496    /// Static placement solved so **both** subjects land on opposite thirds
5497    /// (Toric-space construction). Needs `subject_b`.
5498    TwoShot,
5499    /// Low, close, trailing a **moving** subject near ground level — needs a
5500    /// compiler-known subject path (`DW0349`).
5501    LowFollow,
5502}
5503
5504impl ShotStyle {
5505    /// The kebab token (diagnostics, digests).
5506    pub fn token(self) -> &'static str {
5507        match self {
5508            ShotStyle::Insert => "insert",
5509            ShotStyle::LockedOff => "locked-off",
5510            ShotStyle::PushIn => "push-in",
5511            ShotStyle::PullBackReveal => "pull-back-reveal",
5512            ShotStyle::EstablishingCrane => "establishing-crane",
5513            ShotStyle::OrbitArc => "orbit-arc",
5514            ShotStyle::SideTrack => "side-track",
5515            ShotStyle::TwoShot => "two-shot",
5516            ShotStyle::LowFollow => "low-follow",
5517        }
5518    }
5519
5520    /// Default shot duration in seconds, from the dossier's per-style duration
5521    /// ranges (§2, anchored on the film-editing ASL literature) — the value an
5522    /// omitted `seconds` resolves to.
5523    pub fn default_seconds(self) -> u32 {
5524        match self {
5525            ShotStyle::Insert => 2,
5526            ShotStyle::LockedOff => 6,
5527            ShotStyle::PushIn => 4,
5528            ShotStyle::PullBackReveal => 6,
5529            ShotStyle::EstablishingCrane => 8,
5530            ShotStyle::OrbitArc => 8,
5531            ShotStyle::SideTrack => 8,
5532            ShotStyle::TwoShot => 5,
5533            ShotStyle::LowFollow => 5,
5534        }
5535    }
5536
5537    /// `true` for the styles whose subject must be *moving* on a compiler-known
5538    /// path (`move-npc` / `move-actor` in the same effect group or sequence) —
5539    /// `side-track` and `low-follow` (`DW0349` otherwise).
5540    pub fn needs_moving_subject(self) -> bool {
5541        matches!(self, ShotStyle::SideTrack | ShotStyle::LowFollow)
5542    }
5543}
5544
5545/// A styled shot's subject (DSL v0.6): the world thing the shot frames — a
5546/// prefab anchor point, a stage-2 NPC, or a stage-5 actor — plus an integer
5547/// block offset. For `npc`/`actor` subjects the aim point is the entity's cell
5548/// **plus one block up** (torso height, so a close shot does not frame feet)
5549/// before `offset` is applied; an `anchor` subject aims at the block centre
5550/// exactly like a [`CameraTarget`].
5551/// Each variant's payload is a **named struct** carrying `deny_unknown_fields`
5552/// — serde has no variant-level `deny_unknown_fields`, so an untagged
5553/// enum with inline struct variants silently *ignores* any key it does not
5554/// recognise: `{"npc": …, "ofset": [0,1,0]}` would deserialize happily with the
5555/// offset dropped, and `{"anchor": …, "npc": …}` would quietly match `Anchor`
5556/// and discard the NPC. Lifting each variant into its own type keeps the repo-wide
5557/// deny-unknown rule for both serde and the published JSON Schema
5558/// (`additionalProperties: false`): a mistyped shot subject fails the schema
5559/// instead of rendering a shot pointed somewhere the author never asked for.
5560#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5561#[serde(untagged)]
5562pub enum CameraSubject {
5563    /// A fixed world point: prefab anchor + offset.
5564    Anchor(AnchorSubject),
5565    /// A stage-2 NPC — moving if a `move-npc` for it runs in the same effect
5566    /// group / sequence, else static at its declared (or spawn) anchor.
5567    Npc(NpcSubject),
5568    /// A stage-5 actor — moving if a `move-actor` for it runs in the same
5569    /// effect group / sequence, else static at its declared anchor.
5570    Actor(ActorSubject),
5571}
5572
5573/// A [`CameraSubject::Anchor`] payload: a fixed world point.
5574#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5575#[serde(deny_unknown_fields)]
5576pub struct AnchorSubject {
5577    /// The anchor the subject sits at.
5578    pub anchor: AnchorId,
5579    /// Integer `[x, y, z]` block offset (default `[0, 0, 0]`).
5580    #[serde(default, skip_serializing_if = "is_zero3")]
5581    pub offset: [i32; 3],
5582}
5583
5584/// A [`CameraSubject::Npc`] payload: a stage-2 NPC.
5585#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5586#[serde(deny_unknown_fields)]
5587pub struct NpcSubject {
5588    /// The NPC (stage-2 ref).
5589    pub npc: NpcId,
5590    /// Integer `[x, y, z]` block offset (default `[0, 0, 0]`).
5591    #[serde(default, skip_serializing_if = "is_zero3")]
5592    pub offset: [i32; 3],
5593}
5594
5595/// A [`CameraSubject::Actor`] payload: a stage-5 actor.
5596#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5597#[serde(deny_unknown_fields)]
5598pub struct ActorSubject {
5599    /// The actor (stage-5 `actors` ref).
5600    pub actor: ActorId,
5601    /// Integer `[x, y, z]` block offset (default `[0, 0, 0]`).
5602    #[serde(default, skip_serializing_if = "is_zero3")]
5603    pub offset: [i32; 3],
5604}
5605
5606impl CameraSubject {
5607    /// The subject's integer offset, whichever variant.
5608    pub fn offset(&self) -> [i32; 3] {
5609        match self {
5610            CameraSubject::Anchor(s) => s.offset,
5611            CameraSubject::Npc(s) => s.offset,
5612            CameraSubject::Actor(s) => s.offset,
5613        }
5614    }
5615
5616    /// A short canonical rendering for digests/diagnostics.
5617    pub fn canon(&self) -> String {
5618        let (kind, id, o) = match self {
5619            CameraSubject::Anchor(s) => ("a", s.anchor.as_str(), &s.offset),
5620            CameraSubject::Npc(s) => ("n", s.npc.as_str(), &s.offset),
5621            CameraSubject::Actor(s) => ("c", s.actor.as_str(), &s.offset),
5622        };
5623        format!("{kind}:{id}@{},{},{}", o[0], o[1], o[2])
5624    }
5625}
5626
5627/// `Debug` is hand-written because it is a **stable content-key rendering**:
5628/// the compiler's `payload_verb_key` (FNV over a verb's own `{:?}`) names the
5629/// generated `volley_`, `collapse_` and `teleport_` functions from it, so a shot
5630/// that uses none of the v0.6 style fields must render byte-identically to the
5631/// pre-style struct (`seconds` prints its inner value; absent style fields print
5632/// nothing) — otherwise a purely additive schema change would silently churn the
5633/// content key of every payload that carries a cutscene.
5634impl std::fmt::Debug for CameraShot {
5635    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5636        let mut d = f.debug_struct("CameraShot");
5637        d.field("path", &self.path);
5638        match self.seconds {
5639            Some(v) => d.field("seconds", &v),
5640            None => d.field("seconds", &self.seconds),
5641        };
5642        d.field("look_at", &self.look_at);
5643        if self.shot_style.is_some() {
5644            d.field("shot_style", &self.shot_style);
5645        }
5646        if self.subject.is_some() {
5647            d.field("subject", &self.subject);
5648        }
5649        if self.subject_b.is_some() {
5650            d.field("subject_b", &self.subject_b);
5651        }
5652        if self.dist.is_some() {
5653            d.field("dist", &self.dist);
5654        }
5655        if self.degrees.is_some() {
5656            d.field("degrees", &self.degrees);
5657        }
5658        if self.bearing.is_some() {
5659            d.field("bearing", &self.bearing);
5660        }
5661        d.finish()
5662    }
5663}
5664
5665impl CameraShot {
5666    /// The shot's resolved duration in seconds: explicit `seconds`, else the
5667    /// style default, else `1` (a shape-invalid shot — `DW0199` reports it; the
5668    /// fallback only keeps downstream passes total).
5669    pub fn resolved_seconds(&self) -> u32 {
5670        self.seconds
5671            .or(self.shot_style.map(ShotStyle::default_seconds))
5672            .unwrap_or(1)
5673    }
5674}
5675
5676/// The subject a [`Verb::Cutscene`] camera keeps framed (DSL v0.6): an
5677/// anchor plus an integer block offset from it, giving the world point every
5678/// dolly camera is aimed at. Same shape as a [`CameraWaypoint`] — a waypoint says
5679/// where the camera *is*, a target says what it *looks at*.
5680#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
5681#[serde(deny_unknown_fields)]
5682pub struct CameraTarget {
5683    /// The anchor the look target is relative to.
5684    pub anchor: AnchorId,
5685    /// Integer `[x, y, z]` block offset from the anchor (default `[0, 0, 0]`).
5686    #[serde(default, skip_serializing_if = "is_zero3")]
5687    pub offset: [i32; 3],
5688}
5689
5690/// serde `skip_serializing_if` helper: skip a `[0, 0, 0]` offset.
5691fn is_zero3(v: &[i32; 3]) -> bool {
5692    *v == [0, 0, 0]
5693}
5694
5695impl Verb {
5696    /// The kebab-case `type` tag this verb serializes as — the verb a
5697    /// diagnostic should name so the author can find it in the JSON.
5698    pub fn tag(&self) -> &'static str {
5699        match self {
5700            Verb::OpenGate { .. } => "open-gate",
5701            Verb::CloseGate { .. } => "close-gate",
5702            Verb::CampaignComplete { .. } => "campaign-complete",
5703            Verb::GiveItem { .. } => "give-item",
5704            Verb::SetFlag { .. } => "set-flag",
5705            Verb::SetState { .. } => "set-state",
5706            Verb::AddState { .. } => "add-state",
5707            Verb::ClearState { .. } => "clear-state",
5708            Verb::DropStake { .. } => "drop-stake",
5709            Verb::SpawnWave { .. } => "spawn-wave",
5710            Verb::Narrate { .. } => "narrate",
5711            Verb::SetBlock { .. } => "set-block",
5712            Verb::FillRegion { .. } => "fill-region",
5713            Verb::ClearRegion { .. } => "clear-region",
5714            Verb::OpenWay { .. } => "open-way",
5715            Verb::DespawnNpc { .. } => "despawn-npc",
5716            Verb::MoveNpc { .. } => "move-npc",
5717            Verb::Cutscene { .. } => "cutscene",
5718            Verb::SetTime { .. } => "set-time",
5719            Verb::SetWeather { .. } => "set-weather",
5720            Verb::PlaySound { .. } => "play-sound",
5721            Verb::DamagePlayers { .. } => "damage-players",
5722            Verb::SetCheckpoint { .. } => "set-checkpoint",
5723            Verb::Bonfire { .. } => "bonfire",
5724            Verb::BeginStealth { .. } => "begin-stealth",
5725            Verb::EndStealth => "end-stealth",
5726            Verb::SpawnNpc { .. } => "spawn-npc",
5727            Verb::SpawnActor { .. } => "spawn-actor",
5728            Verb::DespawnActor { .. } => "despawn-actor",
5729            Verb::MoveActor { .. } => "move-actor",
5730            Verb::UnleashActor { .. } => "unleash-actor",
5731            Verb::Sequence { .. } => "sequence",
5732            Verb::Volley { .. } => "volley",
5733            Verb::Collapse { .. } => "collapse",
5734            Verb::GiveEffect { .. } => "give-effect",
5735            Verb::ClearEffect { .. } => "clear-effect",
5736            Verb::Teleport { .. } => "teleport",
5737        }
5738    }
5739}
5740
5741impl QuestEffect {
5742    /// The gate anchor if this is `open-gate`.
5743    pub fn open_gate_anchor(&self) -> Option<&AnchorId> {
5744        match &self.verb {
5745            Verb::OpenGate { anchor, .. } => Some(anchor),
5746            _ => None,
5747        }
5748    }
5749
5750    /// The gate anchor if this is `close-gate` (DSL v0.6).
5751    pub fn close_gate_anchor(&self) -> Option<&AnchorId> {
5752        match &self.verb {
5753            Verb::CloseGate { anchor, .. } => Some(anchor),
5754            _ => None,
5755        }
5756    }
5757
5758    /// The authored `sealed_hint` if this is a `close-gate` that declares one (DSL
5759    /// v0.8). `None` for every other effect **and** for a `close-gate` that takes
5760    /// the compiler's canonical English seal line.
5761    pub fn close_gate_sealed_hint(&self) -> Option<&str> {
5762        match &self.verb {
5763            Verb::CloseGate { sealed_hint, .. } => sealed_hint.as_deref(),
5764            _ => None,
5765        }
5766    }
5767
5768    /// The wave id if this is `spawn-wave` (v0.3).
5769    pub fn spawn_wave(&self) -> Option<&WaveId> {
5770        match &self.verb {
5771            Verb::SpawnWave { wave, .. } => Some(wave),
5772            _ => None,
5773        }
5774    }
5775
5776    /// The flag id if this is `set-flag` (v0.3).
5777    pub fn set_flag(&self) -> Option<&FlagId> {
5778        match &self.verb {
5779            Verb::SetFlag { flag, .. } => Some(flag),
5780            _ => None,
5781        }
5782    }
5783
5784    /// The item id if this is `give-item` (v0.3).
5785    pub fn give_item(&self) -> Option<&str> {
5786        match &self.verb {
5787            Verb::GiveItem { item, .. } => Some(item),
5788            _ => None,
5789        }
5790    }
5791
5792    /// `true` if this is a `give-item` carrying a v0.4 display `name`.
5793    pub fn give_item_named(&self) -> bool {
5794        matches!(self.verb, Verb::GiveItem { name: Some(_), .. })
5795    }
5796
5797    /// The declared `carrier` if this is a `give-item` that states one (v0.6,
5798    /// spec-0018). `None` for any other effect **and** for a `give-item` that
5799    /// leaves it absent — absent reads as [`Carrier::All`], and the distinction
5800    /// matters only for the pre-0.6 reserved-field gate.
5801    pub fn give_carrier(&self) -> Option<Carrier> {
5802        match &self.verb {
5803            Verb::GiveItem { carrier, .. } => *carrier,
5804            _ => None,
5805        }
5806    }
5807
5808    /// Does this `give-item` hand a single copy to the acting player (v0.6,
5809    /// spec-0018)? `false` for every other effect and for the party-wide default.
5810    pub fn gives_to_one(&self) -> bool {
5811        matches!(self.give_carrier(), Some(Carrier::One))
5812    }
5813
5814    /// The `set-block` block id if this is a v0.4 `set-block` effect.
5815    pub fn set_block(&self) -> Option<(&AnchorId, &str)> {
5816        match &self.verb {
5817            Verb::SetBlock { anchor, block, .. } => Some((anchor, block.as_str())),
5818            _ => None,
5819        }
5820    }
5821
5822    /// The NPC id if this is a v0.4 `despawn-npc` effect.
5823    pub fn despawn_npc(&self) -> Option<&NpcId> {
5824        match &self.verb {
5825            Verb::DespawnNpc { npc, .. } => Some(npc),
5826            _ => None,
5827        }
5828    }
5829
5830    /// `(npc, to_anchor)` if this is a v0.4 `move-npc` effect.
5831    pub fn move_npc(&self) -> Option<(&NpcId, &AnchorId)> {
5832        match &self.verb {
5833            Verb::MoveNpc { npc, to_anchor, .. } => Some((npc, to_anchor)),
5834            _ => None,
5835        }
5836    }
5837
5838    /// The v0.3 effect name if this effect is one introduced in DSL v0.3
5839    /// (`give-item`/`set-flag`/`spawn-wave`). These validate in v0.3 campaigns
5840    ///.
5841    pub fn v03_effect(&self) -> Option<&'static str> {
5842        match &self.verb {
5843            Verb::GiveItem { .. } => Some("give-item"),
5844            Verb::SetFlag { .. } => Some("set-flag"),
5845            Verb::SpawnWave { .. } => Some("spawn-wave"),
5846            Verb::OpenGate { .. }
5847            | Verb::CloseGate { .. }
5848            | Verb::CampaignComplete { .. } => None,
5849            // v0.4 effects report via `v04_effect`; v0.5 via `v05_effect`; they
5850            // are not v0.3 verbs.
5851            Verb::Narrate { .. }
5852            | Verb::SetBlock { .. }
5853            | Verb::DespawnNpc { .. }
5854            | Verb::MoveNpc { .. }
5855            | Verb::Cutscene { .. }
5856            | Verb::SetTime { .. }
5857            | Verb::SetWeather { .. }
5858            | Verb::PlaySound { .. }
5859            | Verb::DamagePlayers { .. }
5860            | Verb::SetCheckpoint { .. }
5861            | Verb::Bonfire { .. }
5862            | Verb::BeginStealth { .. }
5863            | Verb::EndStealth
5864            | Verb::SpawnActor { .. }
5865            | Verb::DespawnActor { .. }
5866            | Verb::MoveActor { .. }
5867            | Verb::UnleashActor { .. }
5868            | Verb::SpawnNpc { .. }
5869            | Verb::Sequence { .. }
5870            // spec-0022 trap-payload verbs are v0.6 — they report via `v06_effect`.
5871            | Verb::Volley { .. }
5872            | Verb::Collapse { .. }
5873            // spec-0031's state verbs, region writes, status effects and teleport,
5874            // and spec-0032's `drop-stake`, are all v0.10 — they report via
5875            // `v10_effect`.
5876            | Verb::SetState { .. }
5877            | Verb::AddState { .. }
5878            | Verb::ClearState { .. }
5879            | Verb::FillRegion { .. }
5880            | Verb::ClearRegion { .. }
5881            // spec-0042's `open-way` is v0.12 — it reports via `v12_effect`.
5882            | Verb::OpenWay { .. }
5883            | Verb::GiveEffect { .. }
5884            | Verb::ClearEffect { .. }
5885            | Verb::Teleport { .. }
5886            | Verb::DropStake { .. } => None,
5887        }
5888    }
5889
5890    /// The v0.4 effect name if this effect is one introduced in DSL v0.4
5891    /// (`narrate`/`set-block`/`despawn-npc`/`move-npc`/`cutscene`). These validate
5892    /// in v0.4 campaigns.
5893    pub fn v04_effect(&self) -> Option<&'static str> {
5894        match &self.verb {
5895            Verb::Narrate { .. } => Some("narrate"),
5896            Verb::SetBlock { .. } => Some("set-block"),
5897            Verb::DespawnNpc { .. } => Some("despawn-npc"),
5898            Verb::MoveNpc { .. } => Some("move-npc"),
5899            Verb::Cutscene { .. } => Some("cutscene"),
5900            _ => None,
5901        }
5902    }
5903
5904    /// The v0.5 effect name if this effect is one introduced in DSL v0.5
5905    /// (`set-time`/`set-weather`, spec-0010).
5906    pub fn v05_effect(&self) -> Option<&'static str> {
5907        match &self.verb {
5908            Verb::SetTime { .. } => Some("set-time"),
5909            Verb::SetWeather { .. } => Some("set-weather"),
5910            _ => None,
5911        }
5912    }
5913
5914    /// The v0.6 effect name if this effect is one introduced in DSL v0.6
5915    /// (`set-checkpoint`, spec-0012; `begin-stealth`/`end-stealth`, spec-0014;
5916    /// `play-sound`, spec-0014; the scripted-actor staging verbs
5917    /// `spawn-actor`/`despawn-actor`/`move-actor`/`unleash-actor`/`sequence`,
5918    /// spec-0014). These validate in v0.6 campaigns
5919    /// earlier. (The `narrate` `art` style is a v0.6 addition to an existing verb
5920    /// — see [`QuestEffect::narrate_art`] — not a new effect.)
5921    pub fn v06_effect(&self) -> Option<&'static str> {
5922        match &self.verb {
5923            Verb::CloseGate { .. } => Some("close-gate"),
5924            Verb::SetCheckpoint { .. } => Some("set-checkpoint"),
5925            Verb::Bonfire { .. } => Some("bonfire"),
5926            Verb::BeginStealth { .. } => Some("begin-stealth"),
5927            Verb::EndStealth => Some("end-stealth"),
5928            Verb::PlaySound { .. } => Some("play-sound"),
5929            Verb::DamagePlayers { .. } => Some("damage-players"),
5930            Verb::SpawnActor { .. } => Some("spawn-actor"),
5931            Verb::DespawnActor { .. } => Some("despawn-actor"),
5932            Verb::MoveActor { .. } => Some("move-actor"),
5933            Verb::UnleashActor { .. } => Some("unleash-actor"),
5934            Verb::Sequence { .. } => Some("sequence"),
5935            Verb::SpawnNpc { .. } => Some("spawn-npc"),
5936            // spec-0022 trap-payload verbs — v0.6 surface, reserved earlier.
5937            Verb::Volley { .. } => Some("volley"),
5938            Verb::Collapse { .. } => Some("collapse"),
5939            _ => None,
5940        }
5941    }
5942
5943    /// The v0.10 effect name if this effect is one introduced in DSL v0.10
5944    /// (`set-state`/`add-state`/`clear-state` and the region writes
5945    /// `fill-region`/`clear-region`, spec-0031). These validate in v0.10
5946    /// campaigns.
5947    pub fn v10_effect(&self) -> Option<&'static str> {
5948        match &self.verb {
5949            Verb::SetState { .. } => Some("set-state"),
5950            Verb::AddState { .. } => Some("add-state"),
5951            Verb::ClearState { .. } => Some("clear-state"),
5952            Verb::FillRegion { .. } => Some("fill-region"),
5953            Verb::ClearRegion { .. } => Some("clear-region"),
5954            Verb::GiveEffect { .. } => Some("give-effect"),
5955            Verb::ClearEffect { .. } => Some("clear-effect"),
5956            Verb::Teleport { .. } => Some("teleport"),
5957            Verb::DropStake { .. } => Some("drop-stake"),
5958            _ => None,
5959        }
5960    }
5961
5962    /// The v0.12 effect name if this effect is one introduced in DSL v0.12
5963    /// (`open-way`, spec-0042).
5964    pub fn v12_effect(&self) -> Option<&'static str> {
5965        match &self.verb {
5966            Verb::OpenWay { .. } => Some("open-way"),
5967            _ => None,
5968        }
5969    }
5970
5971    /// **The way this effect opens** (DSL v0.12, spec-0042): the placed piece and
5972    /// the name of one way that piece's spatial contract exports.
5973    ///
5974    /// The third spelling of the one region write, beside
5975    /// [`QuestEffect::region_write`] (the author's own box) and
5976    /// [`QuestEffect::gate_region_write`] (a gate anchor's box). It answers with a
5977    /// *reference* and never with geometry, because the geometry is not the
5978    /// campaign's to state: the cells, the block and the direction all live in the
5979    /// piece's metadata, and the compiler resolves them there
5980    /// (`compiler::ways`). A region-shaped accessor here would be the second
5981    /// authority this surface exists to avoid.
5982    pub fn way_write(&self) -> Option<(&PrefabId, &str)> {
5983        match &self.verb {
5984            Verb::OpenWay { piece, way, .. } => Some((piece, way.as_str())),
5985            _ => None,
5986        }
5987    }
5988
5989    /// **The one region write**, whichever verb spelled it (DSL v0.10,
5990    /// spec-0031): the box to write and the block to write it with — `None` for
5991    /// the block meaning *clear to air*.
5992    ///
5993    /// This is the accessor the capability belongs to. It answers for
5994    /// `fill-region` / `clear-region`, which name their own box; `open-gate` /
5995    /// `close-gate` are the same operation over a box a prefab gate anchor
5996    /// declares, so they answer through
5997    /// [`QuestEffect::gate_region_write`](Self::gate_region_write) — the anchor
5998    /// is theirs, the *operation* is shared.
5999    pub fn region_write(&self) -> Option<(&StealthZone, Option<&str>)> {
6000        match &self.verb {
6001            Verb::FillRegion { region, block, .. } => Some((region, Some(block.as_str()))),
6002            Verb::ClearRegion { region, .. } => Some((region, None)),
6003            _ => None,
6004        }
6005    }
6006
6007    /// The gate anchor this effect writes, and whether the write **fills** it:
6008    /// `Some((anchor, true))` for `close-gate`, `Some((anchor, false))` for
6009    /// `open-gate`, `None` for everything else.
6010    ///
6011    /// The gate half of [`QuestEffect::region_write`]: same operation, but the box
6012    /// and the fill block come from the prefab's gate anchor rather than from the
6013    /// author. Everything that reasons about runtime region writes reads both
6014    /// accessors and nothing else.
6015    pub fn gate_region_write(&self) -> Option<(&AnchorId, bool)> {
6016        match &self.verb {
6017            Verb::CloseGate { anchor, .. } => Some((anchor, true)),
6018            Verb::OpenGate { anchor, .. } => Some((anchor, false)),
6019            _ => None,
6020        }
6021    }
6022
6023    /// `(projectile, from_anchor, kill_zone, salvos, interval)` if this is a
6024    /// `volley` (spec-0022), with the documented defaults already applied.
6025    pub fn volley(&self) -> Option<(&str, &AnchorId, &StealthZone, u32, u32)> {
6026        match &self.verb {
6027            Verb::Volley {
6028                projectile,
6029                from_anchor,
6030                kill_zone,
6031                salvos,
6032                interval,
6033                ..
6034            } => Some((
6035                projectile.as_deref().unwrap_or(DEFAULT_VOLLEY_PROJECTILE),
6036                from_anchor,
6037                kill_zone,
6038                salvos.unwrap_or(DEFAULT_VOLLEY_SALVOS),
6039                interval.unwrap_or(DEFAULT_VOLLEY_INTERVAL),
6040            )),
6041            _ => None,
6042        }
6043    }
6044
6045    /// `(region_anchor, falling_block, then_floor)` if this is a `collapse`
6046    /// (spec-0022), with the documented default already applied.
6047    pub fn collapse(&self) -> Option<(&StealthZone, &str, Option<&str>)> {
6048        match &self.verb {
6049            Verb::Collapse {
6050                region_anchor,
6051                falling_block,
6052                then_floor,
6053                ..
6054            } => Some((
6055                region_anchor,
6056                falling_block
6057                    .as_deref()
6058                    .unwrap_or(DEFAULT_COLLAPSE_FALLING_BLOCK),
6059                then_floor.as_deref(),
6060            )),
6061            _ => None,
6062        }
6063    }
6064
6065    /// The NPC id if this is a v0.6 `spawn-npc` effect (the dual of
6066    /// [`QuestEffect::despawn_npc`]).
6067    pub fn spawn_npc(&self) -> Option<&NpcId> {
6068        match &self.verb {
6069            Verb::SpawnNpc { npc, .. } => Some(npc),
6070            _ => None,
6071        }
6072    }
6073
6074    /// `(anchor, on_respawn)` if this is a v0.6 `set-checkpoint` effect.
6075    pub fn set_checkpoint(&self) -> Option<(&AnchorId, &[QuestEffect])> {
6076        match &self.verb {
6077            Verb::SetCheckpoint { anchor, on_respawn } => Some((anchor, on_respawn.as_slice())),
6078            _ => None,
6079        }
6080    }
6081
6082    /// `(anchor, on_rest)` if this is a `bonfire` effect (spec-0016 §1).
6083    pub fn bonfire(&self) -> Option<(&AnchorId, &[QuestEffect])> {
6084        match &self.verb {
6085            Verb::Bonfire {
6086                anchor, on_rest, ..
6087            } => Some((anchor, on_rest.as_slice())),
6088            _ => None,
6089        }
6090    }
6091
6092    /// The bonfire's authored rest-dialog strings, each `None` when unauthored
6093    /// (the compiler then bakes its canonical English). `None` for every other
6094    /// effect (spec-0016 §1).
6095    pub fn bonfire_labels(&self) -> Option<BonfireLabels<'_>> {
6096        match &self.verb {
6097            Verb::Bonfire {
6098                prompt,
6099                rest_label,
6100                save_label,
6101                ..
6102            } => Some(BonfireLabels {
6103                prompt: prompt.as_deref(),
6104                rest_label: rest_label.as_deref(),
6105                save_label: save_label.as_deref(),
6106            }),
6107            _ => None,
6108        }
6109    }
6110
6111    /// The `within` filter zone if this is a v0.6 `damage-players` effect that
6112    /// declares one (the `in` spatial scope). `None` for an unscoped
6113    /// `damage-players` and for every other effect.
6114    pub fn damage_within(&self) -> Option<&StealthZone> {
6115        match &self.verb {
6116            Verb::DamagePlayers { within, .. } => within.as_ref(),
6117            _ => None,
6118        }
6119    }
6120
6121    /// `(zones, on_caught, grace_ticks)` if this is a v0.6 `begin-stealth` effect.
6122    pub fn begin_stealth(&self) -> Option<(&[StealthZone], &[QuestEffect], u32)> {
6123        match &self.verb {
6124            Verb::BeginStealth {
6125                zones,
6126                on_caught,
6127                grace_ticks,
6128            } => Some((zones.as_slice(), on_caught.as_slice(), *grace_ticks)),
6129            _ => None,
6130        }
6131    }
6132
6133    /// The target time if this is a v0.5 `set-time` effect.
6134    pub fn set_time(&self) -> Option<WorldTime> {
6135        match &self.verb {
6136            Verb::SetTime { time, .. } => Some(*time),
6137            _ => None,
6138        }
6139    }
6140
6141    /// The target weather if this is a v0.5 `set-weather` effect.
6142    pub fn set_weather(&self) -> Option<WorldWeather> {
6143        match &self.verb {
6144            Verb::SetWeather { weather, .. } => Some(*weather),
6145            _ => None,
6146        }
6147    }
6148
6149    /// The effect lists nested one level inside this effect (DSL v0.6): a
6150    /// `sequence`'s per-step effects (in step order), a `set-checkpoint`'s
6151    /// `on_respawn`, a `begin-stealth`'s `on_caught`, and a `move-actor`'s /
6152    /// `move-npc`'s `on_arrive`. Empty for a leaf effect.
6153    ///
6154    /// This is the **single authority** on effect nesting. Every deep traversal —
6155    /// the flag/wave producer scans, the checkpoint/stealth collector, the l10n
6156    /// string inventory, and emission — walks the tree through it (see
6157    /// [`Self::visit_deep`]), so a new nesting site is picked up everywhere at
6158    /// once and no walker can silently miss a list (the class of bug where a
6159    /// `set-flag`/`set-checkpoint` nested in a `sequence` was skipped).
6160    pub fn nested_effect_lists(&self) -> Vec<&[QuestEffect]> {
6161        match &self.verb {
6162            Verb::Sequence { steps } => steps.iter().map(|s| s.effects.as_slice()).collect(),
6163            Verb::SetCheckpoint { on_respawn, .. } => vec![on_respawn.as_slice()],
6164            Verb::Bonfire { on_rest, .. } => vec![on_rest.as_slice()],
6165            Verb::BeginStealth { on_caught, .. } => vec![on_caught.as_slice()],
6166            Verb::MoveActor { on_arrive, .. } | Verb::MoveNpc { on_arrive, .. } => {
6167                vec![on_arrive.as_slice()]
6168            }
6169            _ => Vec::new(),
6170        }
6171    }
6172
6173    /// Visit `self` and every transitively nested effect (depth-first, pre-order),
6174    /// descending through [`Self::nested_effect_lists`].
6175    pub fn visit_deep<'a>(&'a self, f: &mut dyn FnMut(&'a QuestEffect)) {
6176        f(self);
6177        for list in self.nested_effect_lists() {
6178            for e in list {
6179                e.visit_deep(f);
6180            }
6181        }
6182    }
6183
6184    /// Each nested effect list ([`Self::nested_effect_lists`]) paired with the
6185    /// **stable key segment** used to derive child l10n keys / diagnostic paths, and
6186    /// exposed mutably so the localization pass can rewrite nested player-visible
6187    /// strings in place. Segments: `seq.<step>` for each sequence step (step index),
6188    /// `respawn` for `set-checkpoint.on_respawn`, `caught` for
6189    /// `begin-stealth.on_caught`, `arrive` for `move-actor.on_arrive`. Kept in
6190    /// lockstep with `nested_effect_lists` (same lists, same order) — the position-
6191    /// derived segments make every derived key deterministic and stable across
6192    /// builds (ADR-0006 byte-identity).
6193    pub fn nested_effect_lists_keyed_mut(&mut self) -> Vec<(String, &mut [QuestEffect])> {
6194        match &mut self.verb {
6195            Verb::Sequence { steps } => steps
6196                .iter_mut()
6197                .enumerate()
6198                .map(|(s, st)| (format!("seq.{s}"), st.effects.as_mut_slice()))
6199                .collect(),
6200            Verb::SetCheckpoint { on_respawn, .. } => {
6201                vec![("respawn".to_string(), on_respawn.as_mut_slice())]
6202            }
6203            Verb::Bonfire { on_rest, .. } => {
6204                vec![("rest".to_string(), on_rest.as_mut_slice())]
6205            }
6206            Verb::BeginStealth { on_caught, .. } => {
6207                vec![("caught".to_string(), on_caught.as_mut_slice())]
6208            }
6209            Verb::MoveActor { on_arrive, .. } | Verb::MoveNpc { on_arrive, .. } => {
6210                vec![("arrive".to_string(), on_arrive.as_mut_slice())]
6211            }
6212            _ => Vec::new(),
6213        }
6214    }
6215
6216    /// Immutable sibling of [`Self::nested_effect_lists_keyed_mut`] that additionally
6217    /// exposes the **JSON-pointer path segment** for each nested list, so a deep
6218    /// consumer scan (sound/art/give/wave refs) can report a precise diagnostic path
6219    /// *and* the matching l10n key. Each entry is `(path_seg, key_seg, list)`; the
6220    /// caller appends the per-effect index — `/{j}` to the path, `.{j}` to the key.
6221    /// Kept in lockstep with `nested_effect_lists` / `nested_effect_lists_keyed_mut`
6222    /// (same lists, same order): the l10n key segments match
6223    /// `nested_effect_lists_keyed_mut` exactly (`seq.<step>`/`respawn`/`caught`/
6224    /// `arrive`), and the path segments name the real fields
6225    /// (`steps/<step>/effects`, `on_respawn`, `on_caught`, `on_arrive`).
6226    pub fn nested_effect_lists_labeled(&self) -> Vec<(String, String, &[QuestEffect])> {
6227        match &self.verb {
6228            Verb::Sequence { steps } => steps
6229                .iter()
6230                .enumerate()
6231                .map(|(s, st)| {
6232                    (
6233                        format!("steps/{s}/effects"),
6234                        format!("seq.{s}"),
6235                        st.effects.as_slice(),
6236                    )
6237                })
6238                .collect(),
6239            Verb::SetCheckpoint { on_respawn, .. } => vec![(
6240                "on_respawn".to_string(),
6241                "respawn".to_string(),
6242                on_respawn.as_slice(),
6243            )],
6244            Verb::Bonfire { on_rest, .. } => vec![(
6245                "on_rest".to_string(),
6246                "rest".to_string(),
6247                on_rest.as_slice(),
6248            )],
6249            Verb::BeginStealth { on_caught, .. } => vec![(
6250                "on_caught".to_string(),
6251                "caught".to_string(),
6252                on_caught.as_slice(),
6253            )],
6254            Verb::MoveActor { on_arrive, .. } | Verb::MoveNpc { on_arrive, .. } => {
6255                vec![(
6256                    "on_arrive".to_string(),
6257                    "arrive".to_string(),
6258                    on_arrive.as_slice(),
6259                )]
6260            }
6261            _ => Vec::new(),
6262        }
6263    }
6264
6265    /// Every world anchor this effect names **at this node** — the single
6266    /// authority on the anchor-bearing effect surface, the referential sibling of
6267    /// [`Self::nested_effect_lists`]. Each entry is `(json_path_suffix, anchor)`,
6268    /// where the suffix is appended to the effect's own JSON pointer
6269    /// (`anchor`, `to_anchor`, `in/anchor`, `zones/<i>/anchor`, `at/anchor`,
6270    /// `shots/<i>/path/<j>/anchor`, …).
6271    ///
6272    /// Not recursive: pair it with [`Self::visit_deep`] to sweep a whole effect
6273    /// tree. Every consumer that must resolve an anchor — the DSL's `DW0142`
6274    /// reference scan, the compiler's build-time resolution seal (`DW0355`) —
6275    /// goes through here, so a new anchor-bearing variant (or a new anchor field
6276    /// on an existing one) is picked up by all of them at once. That closes the
6277    /// silent-drop class of bug: an anchor-bearing effect whose anchor is typo'd
6278    /// used to emit *nothing* (the emitter's `for … if name == anchor` loop simply
6279    /// found no match) while every shallow validator looked straight past it.
6280    ///
6281    /// # The third element is the SHAPE the site demands
6282    ///
6283    /// A reference is not only a name: `close-gate` fills and clears a region and
6284    /// `bonfire` seats a body, and until spec-0052 those two sat in one match arm
6285    /// with nothing recording the difference. The demand rides with the reference
6286    /// so that a new anchor-bearing variant cannot be added without stating what
6287    /// it does with the anchor — the same reason this is one authority and not
6288    /// three walks.
6289    ///
6290    /// **A demand is stated only where the shape is structurally required**, and
6291    /// the line is drawn where this engine's own `DW0845` already draws it — *a
6292    /// region is not a place to stand*:
6293    ///
6294    /// * [`StationKind::Gate`] where the verb cannot function without a region
6295    ///   that seals and clears: the two gate verbs. A point is not a gate, and
6296    ///   `gate_region_block_any` finds nothing for one.
6297    /// * [`StationKind::Point`] where a **body is put**: a checkpoint seat, a
6298    ///   bonfire, a `move-npc`/`move-actor` destination, a `teleport`
6299    ///   destination. A body cannot stand inside bars.
6300    /// * `None` wherever a reference merely names a **location** — every
6301    ///   anchor-centred volume's centre, every camera field, a `set-block`, a
6302    ///   `play-sound`. A gate region's own corner is a perfectly good answer
6303    ///   there, and refusing it would refuse correct content.
6304    ///
6305    /// That last case is not a gap left for later. An earlier draft of this rule
6306    /// demanded a point at every non-gate site, and the gallery refused to
6307    /// compile: `trigger/east-door-wrong-side` is a `use` trigger sitting on the
6308    /// very `anchor/seam-…` of a barred door so that it can say "the east door
6309    /// does not open from this side". A check that resolves against a smaller
6310    /// world than the campaign has refuses CONTENT, which is the lesson `DW0343`
6311    /// carries three files away.
6312    pub fn anchor_refs(&self) -> Vec<(String, &AnchorId, Option<StationKind>)> {
6313        // Every camera field is a point: a shot flies through cells and looks at
6314        // one.
6315        /// `(suffix, anchor, kind)` for a shot's own anchor-bearing fields, under `base`.
6316        fn shot_refs<'a>(
6317            base: &str,
6318            shot: &'a CameraShot,
6319        ) -> Vec<(String, &'a AnchorId, Option<StationKind>)> {
6320            let mut out: Vec<(String, &AnchorId, Option<StationKind>)> = shot
6321                .path
6322                .iter()
6323                .enumerate()
6324                .map(|(j, w)| (format!("{base}path/{j}/anchor"), &w.anchor, None))
6325                .collect();
6326            if let Some(t) = &shot.look_at {
6327                out.push((format!("{base}look_at/anchor"), &t.anchor, None));
6328            }
6329            for (field, subject) in [("subject", &shot.subject), ("subject_b", &shot.subject_b)] {
6330                if let Some(CameraSubject::Anchor(s)) = subject {
6331                    out.push((format!("{base}{field}/anchor"), &s.anchor, None));
6332                }
6333            }
6334            out
6335        }
6336        match &self.verb {
6337            // The two gate verbs address a REGION that seals and clears; the
6338            // three below them seat or write at a cell. They shared an arm until
6339            // the demand had somewhere to be written down.
6340            Verb::OpenGate { anchor, .. } | Verb::CloseGate { anchor, .. } => {
6341                vec![("anchor".to_string(), anchor, Some(StationKind::Gate))]
6342            }
6343            // A checkpoint and a bonfire are **respawn seats** — a body is put
6344            // there, so a region is not one. `set-block` writes a block at a
6345            // cell, which names a location and seats nothing.
6346            Verb::SetCheckpoint { anchor, .. } | Verb::Bonfire { anchor, .. } => {
6347                vec![("anchor".to_string(), anchor, Some(StationKind::Point))]
6348            }
6349            Verb::SetBlock { anchor, .. } => {
6350                vec![("anchor".to_string(), anchor, None)]
6351            }
6352            Verb::MoveNpc { to_anchor, .. } | Verb::MoveActor { to_anchor, .. } => {
6353                vec![("to_anchor".to_string(), to_anchor, Some(StationKind::Point))]
6354            }
6355            // The `in` filter is one capability on three verbs, so it registers
6356            // once: `damage-players` (v0.6) and the v0.10 status-effect pair.
6357            Verb::DamagePlayers {
6358                within: Some(zone), ..
6359            }
6360            | Verb::GiveEffect {
6361                within: Some(zone), ..
6362            }
6363            | Verb::ClearEffect {
6364                within: Some(zone), ..
6365            } => vec![("in/anchor".to_string(), &zone.anchor, None)],
6366            // Both of a `teleport`'s anchors are load-bearing — the source volume
6367            // decides WHAT moves and the destination decides WHERE — so a typo in
6368            // either is a dangling reference (`DW0142`), never a silently
6369            // zero-cell volume or a dropped command.
6370            Verb::Teleport { from, to, .. } => vec![
6371                ("from/anchor".to_string(), &from.anchor, None),
6372                ("to".to_string(), to, Some(StationKind::Point)),
6373            ],
6374            Verb::BeginStealth { zones, .. } => zones
6375                .iter()
6376                .enumerate()
6377                .map(|(i, z)| (format!("zones/{i}/anchor"), &z.anchor, None))
6378                .collect(),
6379            Verb::PlaySound {
6380                at: Some(SoundAt::Anchor { anchor }),
6381                ..
6382            } => vec![("at/anchor".to_string(), anchor, None)],
6383            // spec-0022 trap-payload verbs. Both anchors of a `volley` are
6384            // load-bearing for the coverage proof, so both register here — a
6385            // typo'd `kill_zone` must be a dangling-reference error, never a
6386            // silently zero-cell (and therefore vacuously "covered") volley.
6387            Verb::Volley {
6388                from_anchor,
6389                kill_zone,
6390                ..
6391            } => vec![
6392                ("from_anchor".to_string(), from_anchor, None),
6393                ("kill_zone/anchor".to_string(), &kill_zone.anchor, None),
6394            ],
6395            Verb::Collapse { region_anchor, .. } => {
6396                vec![(
6397                    "region_anchor/anchor".to_string(),
6398                    &region_anchor.anchor,
6399                    None,
6400                )]
6401            }
6402            // The v0.10 region writes: the box's anchor is load-bearing for both
6403            // the emission and the completability model, so a typo'd one must be a
6404            // dangling-reference error (`DW0142`/`DW0355`), never a silently
6405            // unwritten — and therefore vacuously proven — region.
6406            Verb::FillRegion { region, .. } | Verb::ClearRegion { region, .. } => {
6407                vec![("region/anchor".to_string(), &region.anchor, None)]
6408            }
6409            // Both cutscene spellings (`DW0199` polices mixing them): the v0.6
6410            // multi-shot list, or the v0.4 single-shot fields flattened at the
6411            // effect's own level.
6412            Verb::Cutscene {
6413                shots,
6414                path,
6415                look_at,
6416                ..
6417            } => {
6418                let mut out: Vec<(String, &AnchorId, Option<StationKind>)> = shots
6419                    .iter()
6420                    .enumerate()
6421                    .flat_map(|(i, s)| shot_refs(&format!("shots/{i}/"), s))
6422                    .collect();
6423                out.extend(
6424                    path.iter()
6425                        .enumerate()
6426                        .map(|(j, w)| (format!("path/{j}/anchor"), &w.anchor, None)),
6427                );
6428                if let Some(t) = look_at {
6429                    out.push(("look_at/anchor".to_string(), &t.anchor, None));
6430                }
6431                out
6432            }
6433            _ => Vec::new(),
6434        }
6435    }
6436
6437    /// The `cutscene` camera subject if this is a single-shot `cutscene` carrying
6438    /// the v0.6 `look_at` field.
6439    pub fn cutscene_look_at(&self) -> Option<&CameraTarget> {
6440        match &self.verb {
6441            Verb::Cutscene { look_at, .. } => look_at.as_ref(),
6442            _ => None,
6443        }
6444    }
6445
6446    /// `true` if this is a `cutscene` written in the v0.6 multi-shot form
6447    ///.
6448    pub fn cutscene_multi_shot(&self) -> bool {
6449        matches!(&self.verb, Verb::Cutscene { shots, .. } if !shots.is_empty())
6450    }
6451
6452    /// The normalized shot list of a `cutscene`, whichever spelling was used: the
6453    /// v0.6 `shots` list as-is, or the v0.4 `path`/`seconds`/`look_at` fields as a
6454    /// single shot. `None` for a non-cutscene effect; an empty list for a cutscene
6455    /// whose shape is invalid (`DW0199` reports that).
6456    pub fn cutscene_shots(&self) -> Option<Vec<CameraShot>> {
6457        match &self.verb {
6458            Verb::Cutscene {
6459                shots,
6460                path,
6461                seconds,
6462                look_at,
6463                ..
6464            } => {
6465                if !shots.is_empty() {
6466                    return Some(shots.clone());
6467                }
6468                match seconds {
6469                    Some(secs) => Some(vec![CameraShot {
6470                        path: path.clone(),
6471                        seconds: Some(*secs),
6472                        look_at: look_at.clone(),
6473                        shot_style: None,
6474                        subject: None,
6475                        subject_b: None,
6476                        dist: None,
6477                        degrees: None,
6478                        bearing: None,
6479                    }]),
6480                    None => Some(Vec::new()),
6481                }
6482            }
6483            _ => None,
6484        }
6485    }
6486
6487    /// `true` if this is a `narrate` carrying the `art` style (glyph-checked
6488    /// `DW0328`).
6489    pub fn narrate_art(&self) -> bool {
6490        matches!(
6491            &self.verb,
6492            Verb::Narrate {
6493                style: Some(NarrateStyle::Art),
6494                ..
6495            }
6496        )
6497    }
6498
6499    /// The `narrate` line's text if this is a `narrate` with the `art` style.
6500    pub fn narrate_art_text(&self) -> Option<&str> {
6501        match &self.verb {
6502            Verb::Narrate {
6503                text,
6504                style: Some(NarrateStyle::Art),
6505                ..
6506            } => Some(text.as_str()),
6507            _ => None,
6508        }
6509    }
6510
6511    /// The `narrate` line's style and text if this is a `narrate` rendered **on
6512    /// screen** — `title`, `subtitle` or `art` — rather than in chat. These are the
6513    /// styles vanilla draws centred and unwrapped, so their rendered width is
6514    /// length-checked against the screen (`DW0330`); `chat` scrolls and wraps, so it
6515    /// is exempt.
6516    pub fn narrate_on_screen(&self) -> Option<(NarrateStyle, &str)> {
6517        match &self.verb {
6518            Verb::Narrate {
6519                text,
6520                style: Some(s),
6521                ..
6522            } if matches!(
6523                s,
6524                NarrateStyle::Title | NarrateStyle::Subtitle | NarrateStyle::Art
6525            ) =>
6526            {
6527                Some((*s, text.as_str()))
6528            }
6529            _ => None,
6530        }
6531    }
6532
6533    /// Every vanilla sound-event id this effect references, for registry
6534    /// validation (`DW0326`): a `play-sound`'s `sound`, and a `narrate`'s optional
6535    /// `sound`. Returns `(subpath, id)` pairs where `subpath` locates the field
6536    /// within the effect (e.g. `sound`).
6537    pub fn sound_refs(&self) -> Vec<(&'static str, &str)> {
6538        match &self.verb {
6539            Verb::PlaySound { sound, .. } => vec![("sound", sound.as_str())],
6540            Verb::Narrate { sound: Some(s), .. } => vec![("sound", s.as_str())],
6541            _ => Vec::new(),
6542        }
6543    }
6544
6545    /// The `play-sound` `at: actor` id, if this effect is a `play-sound`
6546    /// targeting an actor (rejected `DW0335`).
6547    pub fn play_sound_actor(&self) -> Option<&str> {
6548        match &self.verb {
6549            Verb::PlaySound {
6550                at: Some(SoundAt::Actor { actor }),
6551                ..
6552            } => Some(actor.as_str()),
6553            _ => None,
6554        }
6555    }
6556
6557    /// The per-effect flag gate: flags that must ALL be set (per party) for this
6558    /// effect to fire. Empty for an ungated effect. Read off the one [`Guard`], so
6559    /// **every** verb answers it — the staging and souls vocabulary included.
6560    pub fn requires_flags(&self) -> &[FlagId] {
6561        self.when.as_ref().map_or(&[][..], |g| &g.requires_flags)
6562    }
6563
6564    /// The per-effect **negative** flag gate: flags whose being set suppresses this
6565    /// effect — the dual of [`QuestEffect::requires_flags`], on the same guard.
6566    pub fn forbids_flags(&self) -> &[FlagId] {
6567        self.when.as_ref().map_or(&[][..], |g| &g.forbids_flags)
6568    }
6569
6570    /// The numeric gate terms (spec-0031) — the third axis of the same guard, so
6571    /// "which verbs are gatable" has exactly one answer.
6572    pub fn requires_state(&self) -> &[StateCompare] {
6573        self.when.as_ref().map_or(&[][..], |g| &g.requires_state)
6574    }
6575
6576    /// The datum this effect writes and how, if it is one of the DSL v0.10 state
6577    /// verbs (`set-state` / `add-state` / `clear-state`).
6578    pub fn writes_state(&self) -> Option<(&StateId, StateWrite)> {
6579        match &self.verb {
6580            Verb::SetState { state, value, .. } => Some((state, StateWrite::Set(*value))),
6581            Verb::AddState { state, amount, .. } => Some((state, StateWrite::Add(*amount))),
6582            Verb::ClearState { state, .. } => Some((state, StateWrite::Clear)),
6583            _ => None,
6584        }
6585    }
6586
6587    /// The `on_arrive` bundle if this is a `move-npc` carrying one (DSL v0.6;
6588    /// parity with `move-actor`). `None` for a bare `move-npc` and every other
6589    /// effect.
6590    pub fn move_npc_on_arrive(&self) -> Option<&[QuestEffect]> {
6591        match &self.verb {
6592            Verb::MoveNpc { on_arrive, .. } if !on_arrive.is_empty() => Some(on_arrive.as_slice()),
6593            _ => None,
6594        }
6595    }
6596
6597    /// The actor id this effect targets, if it is one of the actor staging effects
6598    /// (`spawn-actor`/`despawn-actor`/`move-actor`/`unleash-actor`). `sequence` has
6599    /// no single actor (its nested effects each carry their own).
6600    pub fn actor_ref(&self) -> Option<&ActorId> {
6601        match &self.verb {
6602            Verb::SpawnActor { actor, .. }
6603            | Verb::DespawnActor { actor, .. }
6604            | Verb::MoveActor { actor, .. }
6605            | Verb::UnleashActor { actor, .. } => Some(actor),
6606            _ => None,
6607        }
6608    }
6609
6610    /// Every vanilla **status-effect** id this effect names, for registry
6611    /// validation (`DW0192`) — the sibling of [`Self::sound_refs`] and the single
6612    /// authority on the status-effect-bearing verb surface. `(subpath, id)`
6613    /// pairs; empty for a `clear-effect` that names none (which clears all).
6614    pub fn status_effect_refs(&self) -> Vec<(&'static str, &str)> {
6615        match &self.verb {
6616            Verb::GiveEffect { effect, .. } => vec![("effect", effect.as_str())],
6617            Verb::ClearEffect {
6618                effect: Some(e), ..
6619            } => vec![("effect", e.as_str())],
6620            _ => Vec::new(),
6621        }
6622    }
6623
6624    /// `(effect, seconds, amplifier, hide_particles, in)` if this is a
6625    /// `give-effect` (DSL v0.10), with the documented defaults already applied.
6626    pub fn give_effect(&self) -> Option<(&str, u32, u32, bool, Option<&StealthZone>)> {
6627        match &self.verb {
6628            Verb::GiveEffect {
6629                effect,
6630                seconds,
6631                amplifier,
6632                hide_particles,
6633                within,
6634                ..
6635            } => Some((
6636                effect.as_str(),
6637                *seconds,
6638                amplifier.unwrap_or(0),
6639                hide_particles.unwrap_or(false),
6640                within.as_ref(),
6641            )),
6642            _ => None,
6643        }
6644    }
6645
6646    /// `(effect, in)` if this is a `clear-effect` (DSL v0.10). The effect is
6647    /// `None` for the clear-everything form, exactly as vanilla spells it.
6648    pub fn clear_effect(&self) -> Option<(Option<&str>, Option<&StealthZone>)> {
6649        match &self.verb {
6650            Verb::ClearEffect { effect, within, .. } => Some((effect.as_deref(), within.as_ref())),
6651            _ => None,
6652        }
6653    }
6654
6655    /// `(from, to)` if this is a `teleport` (DSL v0.10): the source volume and
6656    /// the destination anchor.
6657    pub fn teleport(&self) -> Option<(&StealthZone, &AnchorId)> {
6658        match &self.verb {
6659            Verb::Teleport { from, to, .. } => Some((from, to)),
6660            _ => None,
6661        }
6662    }
6663}
6664
6665// ---------------------------------------------------------------------------
6666// Stage 7 — world-edits (the map editor edit script, DSL v0.6, spec-0017)
6667// ---------------------------------------------------------------------------
6668
6669/// Stage 7 payload (optional; DSL v0.6, spec-0017): the map-editor edit script.
6670///
6671/// The artifact of record for L3 world detailing: an ordered list of edit
6672/// batches the compiler replays deterministically **after** world assembly.
6673/// The world files are never truth — same DSL + same edits + same seed →
6674/// byte-identical world (ADR-0006). A campaign without a `world-edits.json`
6675/// builds byte-identically to one from before this stage existed.
6676#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
6677#[serde(deny_unknown_fields)]
6678pub struct WorldEditsContent {
6679    /// Ordered edit batches, replayed in order. After every batch the post-edit
6680    /// invariants re-prove (walkability, sealing + relight, boundary safety),
6681    /// so each batch is a valid, snapshot-reviewable world state.
6682    pub batches: Vec<EditBatch>,
6683}
6684
6685/// One edit batch: an ordered group of edit verbs applied to a single area,
6686/// checked and snapshot-rendered as a unit.
6687#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
6688#[serde(deny_unknown_fields)]
6689pub struct EditBatch {
6690    /// Batch id (`batch/<kebab>`), unique in the script. Also the batch's
6691    /// snapshot name and seed-stream label — renaming a batch deliberately
6692    /// reseeds its noise.
6693    pub id: EditBatchId,
6694    /// The stage-1 area this batch edits. Frames and regions resolve against
6695    /// this area's placed pieces and anchors.
6696    pub area: AreaId,
6697    /// Authoring context (why this batch exists). Machine-ignored; **excluded**
6698    /// from l10n like `theme`/`premise`.
6699    #[serde(default, skip_serializing_if = "Option::is_none")]
6700    pub note: Option<String>,
6701    /// Ordered edit verbs. `select` defines named regions; later verbs in the
6702    /// same batch refer back to them (strictly backward, like every DSL ref).
6703    pub edits: Vec<WorldEdit>,
6704}
6705
6706/// One edit verb (spec-0017 L3). Every verb operates on named regions and every
6707/// seeded verb derives its noise stream from the campaign seed + its script
6708/// position (`edits/<batch>/<index>`) — no wall clock, no unseeded RNG.
6709#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
6710#[serde(tag = "verb", rename_all = "kebab-case", deny_unknown_fields)]
6711pub enum WorldEdit {
6712    /// Define a named region (`region/<kebab>`) for later verbs in this batch.
6713    Select {
6714        /// The region name being defined (unique within the batch).
6715        name: RegionId,
6716        /// The region's shape (box, surface band, palette match, or a
6717        /// composition of earlier regions).
6718        shape: RegionShape,
6719    },
6720    /// Fill every cell of a region from a seeded palette recipe (value-noise
6721    /// keyed, so picks cluster into patches — never a uniform fill).
6722    Fill {
6723        /// The region (an earlier `select` in this batch) to fill.
6724        region: RegionId,
6725        /// The palette recipe to fill with.
6726        recipe: PaletteRecipe,
6727    },
6728    /// Like `fill`, but only rewrites cells whose current block matches one of
6729    /// `matching` (base ids; blockstate suffixes are ignored when matching).
6730    Replace {
6731        /// The region (an earlier `select` in this batch) to edit.
6732        region: RegionId,
6733        /// Base block ids to rewrite (e.g. `["minecraft:stone"]`).
6734        matching: Vec<String>,
6735        /// The palette recipe to rewrite them with.
6736        recipe: PaletteRecipe,
6737    },
6738    /// Clear a region to air. Sealing-aware: the carved region re-enters the
6739    /// sealing + relight passes and every walkability invariant re-proves.
6740    Carve {
6741        /// The region (an earlier `select` in this batch) to clear.
6742        region: RegionId,
6743    },
6744    /// Reshape terrain surface within a region (raise / lower / smooth).
6745    Morph {
6746        /// The region (an earlier `select` in this batch) whose columns to
6747        /// reshape. The region defines the footprint and where each column's
6748        /// surface is read (the highest occupied cell in the region's y-range);
6749        /// `raise`/`smooth` may add cells above the region's top — reshaping
6750        /// upward is the point — while removal only touches region cells.
6751        region: RegionId,
6752        /// The surface operation.
6753        op: MorphOp,
6754    },
6755    /// Seeded dressing scatter (spec-0017): drop weighted single-block
6756    /// dressing (flora, rocks, props) onto standable cells of a region —
6757    /// air cells with an occupied cell directly below — honoring keep-clear
6758    /// envelopes (`avoid`). Per-cell white-noise density gate (dressing wants
6759    /// speckle, not the fill verbs' clustered patches), deterministic from the
6760    /// campaign seed + script position.
6761    Scatter {
6762        /// The region (an earlier `select` in this batch) to dress.
6763        region: RegionId,
6764        /// Weighted dressing blocks (blockstate suffixes allowed).
6765        items: Vec<PaletteBlock>,
6766        /// Per-candidate placement probability in `(0, 1]`.
6767        density: f64,
6768        /// Keep-clear envelopes: earlier regions whose cells (and columns —
6769        /// matched by `(x, z)`) never receive dressing.
6770        #[serde(default, skip_serializing_if = "Vec::is_empty")]
6771        avoid: Vec<RegionId>,
6772        /// Optional minimum spacing: when set, candidates are taken in
6773        /// descending noise order and one is rejected while another accepted
6774        /// candidate is closer than this on **both** horizontal axes (the
6775        /// generators' spread rule).
6776        #[serde(default, skip_serializing_if = "Option::is_none")]
6777        spacing: Option<u32>,
6778        /// Optional cap on how many items are placed (highest-noise first).
6779        #[serde(default, skip_serializing_if = "Option::is_none")]
6780        limit: Option<u32>,
6781    },
6782    /// Structural flora (spec-0017): plant hand-shaped trees via the
6783    /// lean-or-grow canopy rules — a canopy that would reach a
6784    /// keep-clear (`avoid`) column first leans one block away from it; if that
6785    /// still covers the corridor the tree grows tall instead, arching its
6786    /// whole canopy 3 blocks above the trunk's floor. No leaf is ever sliced.
6787    Plant {
6788        /// The region (an earlier `select` in this batch) to plant in. Trunk
6789        /// cells are standable region cells (air over an occupied cell).
6790        region: RegionId,
6791        /// The tree species (canopy shape rules are per-species).
6792        tree: TreeKind,
6793        /// How many trees to plant (≥ 1; highest-noise candidates first).
6794        count: u32,
6795        /// Keep-clear envelopes: trunks never stand in these columns and
6796        /// canopies lean/grow to clear them.
6797        #[serde(default, skip_serializing_if = "Vec::is_empty")]
6798        avoid: Vec<RegionId>,
6799        /// Minimum trunk spacing (reject when closer on BOTH axes; default 4).
6800        #[serde(default, skip_serializing_if = "Option::is_none")]
6801        spacing: Option<u32>,
6802    },
6803    /// Stamp a prefab fragment (spec-0017): copy a library prefab's
6804    /// non-air cells into the world at a frame-resolved position. The fragment
6805    /// is a first-class library prefab — its provenance/license metadata is
6806    /// recorded and validated exactly like any placed prefab (ADR-0013);
6807    /// nothing outside the library can be stamped.
6808    Fragment {
6809        /// The library prefab to stamp.
6810        prefab: PrefabId,
6811        /// The frame `at` resolves in.
6812        frame: EditFrame,
6813        /// Where the fragment's local `(0, 0, 0)` lands (frame coordinates).
6814        at: [i32; 3],
6815        /// Placement rotation (default `none`), the same quarter-turn set as
6816        /// `/place template`.
6817        #[serde(default, skip_serializing_if = "Option::is_none")]
6818        rotation: Option<FragmentRotation>,
6819    },
6820    /// Explicit region relight (spec-0017, spec-0010 machinery): run the
6821    /// deterministic fixture-placement pass over ONE region and bake the
6822    /// resulting fixtures into the edit script's writes — authorial control of
6823    /// where fixtures land, instead of the whole-area pass's greedy siting.
6824    /// (The whole-area relight still re-proves after every batch either way.)
6825    Relight {
6826        /// The region (an earlier `select` in this batch) to relight: its
6827        /// reachable walkable cells are brought to `min_light`.
6828        region: RegionId,
6829        /// Fixture override; default = the area's declared `lighting.fixture`.
6830        #[serde(default, skip_serializing_if = "Option::is_none")]
6831        fixture: Option<Fixture>,
6832        /// Target light override (1..=14); default = the area's declared
6833        /// `lighting.min_light`. Required (with `fixture`) when the area
6834        /// declares no `lighting`.
6835        #[serde(default, skip_serializing_if = "Option::is_none")]
6836        min_light: Option<u8>,
6837    },
6838    /// L2 massing (spec-0017): replace a placed piece with another
6839    /// library prefab that re-mates every currently-mated socket at its exact
6840    /// world pose (any rotation; overlap-checked). Applied at **plan** time —
6841    /// the whole downstream ladder (anchors, gate reachability, assembly,
6842    /// relight, nav, L3 detailing) re-runs over the massaged layout. Massing
6843    /// verbs live in massing-only batches, ordered before every detailing
6844    /// batch.
6845    SwapPiece {
6846        /// The piece's placement index in its area's solved layout (0-based,
6847        /// entry first).
6848        piece: u32,
6849        /// The prefab the indexed piece must currently be (drift guard).
6850        prefab: PrefabId,
6851        /// The library prefab to swap in.
6852        with: PrefabId,
6853    },
6854    /// L2 massing (spec-0017): attach a new piece at a specific **open**
6855    /// (unmated) socket of an existing piece — the targeted form of the
6856    /// solver's frontier attach. The socket opens (its seal becomes a
6857    /// passage); the new piece's other sockets seal.
6858    InsertPiece {
6859        /// The host piece's placement index.
6860        at_piece: u32,
6861        /// The prefab the host piece must currently be (drift guard).
6862        prefab: PrefabId,
6863        /// The host's connector index (prefab metadata `connectors` order).
6864        socket: u32,
6865        /// The library prefab to attach.
6866        insert: PrefabId,
6867    },
6868    /// L2 massing (spec-0017): remove a **leaf** piece (exactly one
6869    /// mated socket; never the entry piece). The neighbour's socket unmates
6870    /// and re-seals. Removal shifts later placement indices — order removals
6871    /// before other index-referencing massing verbs.
6872    RemovePiece {
6873        /// The piece's placement index.
6874        piece: u32,
6875        /// The prefab the indexed piece must currently be (drift guard).
6876        prefab: PrefabId,
6877    },
6878    /// L2 massing (spec-0017): override one socket's seal — `open`
6879    /// clears the opening to a passage, `sealed` walls it up — independent of
6880    /// its mated state (sealing a mated doorway makes a wall between joined
6881    /// pieces; opening an unmated exterior socket exposes the outside, which
6882    /// the boundary-safety proof then judges).
6883    RewireSocket {
6884        /// The piece's placement index.
6885        piece: u32,
6886        /// The prefab the indexed piece must currently be (drift guard).
6887        prefab: PrefabId,
6888        /// The connector index (prefab metadata `connectors` order).
6889        socket: u32,
6890        /// The socket's new state.
6891        state: SocketState,
6892    },
6893    /// L2 massing (spec-0017): re-pick this piece from its area pool's
6894    /// compatible members (weighted, seeded from the campaign seed + this
6895    /// verb's script position — moving the verb deliberately re-rolls). The
6896    /// current prefab is excluded, so a reseed always changes the piece or
6897    /// errors loudly.
6898    ReseedPiece {
6899        /// The piece's placement index.
6900        piece: u32,
6901        /// The prefab the indexed piece must currently be (drift guard).
6902        prefab: PrefabId,
6903    },
6904}
6905
6906/// A socket seal state for `rewire-socket` (spec-0017).
6907#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
6908#[serde(rename_all = "kebab-case")]
6909pub enum SocketState {
6910    /// The opening is cleared to a passage.
6911    Open,
6912    /// The opening is walled up.
6913    Sealed,
6914}
6915
6916/// A tree species for the `plant` verb (spec-0017). One species per
6917/// canopy-rule implementation; the shipped rule set is the lean-or-grow oak.
6918#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
6919#[serde(rename_all = "kebab-case")]
6920pub enum TreeKind {
6921    /// Small hand-shaped oak (3–4 logs, 5-wide leaf ball) with the
6922    /// lean-or-grow corridor rules.
6923    Oak,
6924}
6925
6926/// A `fragment` stamp rotation (spec-0017) — the `/place template`
6927/// quarter-turn set.
6928#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
6929#[serde(rename_all = "kebab-case")]
6930pub enum FragmentRotation {
6931    /// No rotation.
6932    None,
6933    /// 90° clockwise.
6934    Clockwise90,
6935    /// 180°.
6936    Clockwise180,
6937    /// 90° counterclockwise.
6938    Counterclockwise90,
6939}
6940
6941/// A `select` verb's shape (spec-0017): primitive shapes resolve in a declared
6942/// frame; compositions combine earlier regions of the same batch.
6943#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
6944#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
6945pub enum RegionShape {
6946    /// An inclusive axis-aligned box, `min`/`max` in the declared frame.
6947    Box {
6948        /// The coordinate frame `min`/`max` resolve in.
6949        frame: EditFrame,
6950        /// Inclusive minimum corner (frame coordinates).
6951        min: [i32; 3],
6952        /// Inclusive maximum corner (frame coordinates; each axis ≥ `min`).
6953        max: [i32; 3],
6954    },
6955    /// The band of cells at `from..=to` blocks relative to each column's
6956    /// terrain surface (the highest non-air cell of the column) within an
6957    /// earlier region. `from: 1, to: 3` is the 3 cells of air-space above the
6958    /// surface; `from: 0, to: 0` is the surface cells themselves; negative
6959    /// offsets reach below the surface.
6960    SurfaceBand {
6961        /// The earlier region whose columns are scanned.
6962        over: RegionId,
6963        /// Inclusive band start, relative to each column's surface y.
6964        from: i32,
6965        /// Inclusive band end (≥ `from`), relative to each column's surface y.
6966        to: i32,
6967    },
6968    /// The cells of an earlier region whose current block matches one of
6969    /// `blocks` (base ids; blockstate suffixes ignored when matching).
6970    PaletteMatch {
6971        /// The earlier region to filter.
6972        within: RegionId,
6973        /// Base block ids to match (e.g. `["minecraft:grass_block"]`).
6974        blocks: Vec<String>,
6975    },
6976    /// The union of earlier regions.
6977    Union {
6978        /// The earlier regions to unite (≥ 2).
6979        of: Vec<RegionId>,
6980    },
6981    /// The intersection of earlier regions.
6982    Intersect {
6983        /// The earlier regions to intersect (≥ 2).
6984        of: Vec<RegionId>,
6985    },
6986    /// An earlier region minus other earlier regions.
6987    Subtract {
6988        /// The earlier region to start from.
6989        base: RegionId,
6990        /// The earlier regions to remove from it (≥ 1).
6991        remove: Vec<RegionId>,
6992    },
6993}
6994
6995/// The coordinate frame a primitive [`RegionShape`] resolves in (spec-0017):
6996/// piece-local or anchor-relative — never raw world coordinates, so an edit
6997/// script survives a layout's world placement moving.
6998#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
6999#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
7000pub enum EditFrame {
7001    /// The local frame of a placed piece of the batch's area: `[0, 0, 0]` is
7002    /// the piece's structure origin, axes as authored (the compiler applies
7003    /// the piece's placed rotation).
7004    PieceLocal {
7005        /// The piece's placement index in the area's solved layout (0-based,
7006        /// entry piece first — the order `delvec snapshot`'s manifest lists).
7007        piece: u32,
7008        /// The prefab the indexed piece must be (a drift guard: if a re-solve
7009        /// changed the layout, the mismatch is a loud compile error, never a
7010        /// silently misplaced edit).
7011        prefab: PrefabId,
7012    },
7013    /// Relative to a resolved anchor of the batch's area: `[0, 0, 0]` is the
7014    /// anchor cell, axes world-aligned.
7015    AnchorRelative {
7016        /// The anchor (prefab metadata, resolved by the compiler).
7017        anchor: AnchorId,
7018    },
7019}
7020
7021/// A surface operation for the `morph` verb (spec-0017).
7022#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
7023#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
7024pub enum MorphOp {
7025    /// Raise each column's surface by up to `by` blocks, drawing the added
7026    /// cells from `recipe` (value-noise keyed per cell, so a raised band reads
7027    /// as natural strata, not an extruded slab).
7028    Raise {
7029        /// How many blocks to raise each column (≥ 1).
7030        by: u32,
7031        /// The palette recipe for the added cells.
7032        recipe: PaletteRecipe,
7033    },
7034    /// Lower each column's surface by up to `by` blocks (carving the topmost
7035    /// solid cells to air).
7036    Lower {
7037        /// How many blocks to lower each column (≥ 1).
7038        by: u32,
7039    },
7040    /// Relax each column's surface toward the mean of its cardinal neighbours
7041    /// (one block per pass), turning steps into slopes. Added cells draw from
7042    /// `recipe`; removed cells carve to air. Deterministic double-buffered
7043    /// passes in fixed scan order.
7044    Smooth {
7045        /// Relaxation passes (≥ 1).
7046        passes: u32,
7047        /// The palette recipe for cells a pass adds.
7048        recipe: PaletteRecipe,
7049    },
7050}
7051
7052/// A seeded palette recipe (spec-0017): weighted blocks picked per cell by a
7053/// smooth value-noise sample, the island/cave generators' proven primitive —
7054/// picks cluster into strata/patches instead of per-cell speckle, and a
7055/// single-entry recipe is the degenerate (discouraged) uniform case.
7056#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
7057#[serde(deny_unknown_fields)]
7058pub struct PaletteRecipe {
7059    /// Weighted palette entries (≥ 1; ≥ 2 for any visible surface).
7060    pub blocks: Vec<PaletteBlock>,
7061    /// Noise frequency in blocks⁻¹ (default `0.35` — patches a few blocks
7062    /// across). Larger = smaller patches. Must be finite and > 0.
7063    #[serde(default, skip_serializing_if = "Option::is_none")]
7064    pub scale: Option<f64>,
7065}
7066
7067/// One weighted entry of a [`PaletteRecipe`].
7068#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
7069#[serde(deny_unknown_fields)]
7070pub struct PaletteBlock {
7071    /// Vanilla block id (validated against the pinned 1.21.11 registry), with
7072    /// an optional verbatim blockstate suffix (`minecraft:oak_leaves[persistent=true]`).
7073    pub block: String,
7074    /// Relative weight (finite, > 0).
7075    pub weight: f64,
7076}
7077
7078/// Where in the campaign one effect sits — the attribution every per-branch
7079/// proof and the branch chronicle need (spec-0025).
7080#[derive(Clone, Debug, PartialEq, Eq)]
7081pub enum EffectSite {
7082    /// A quest's `on_objective_complete[<objective>]` bundle.
7083    Objective {
7084        /// The owning quest.
7085        quest: String,
7086        /// The objective whose completion fires the bundle.
7087        objective: String,
7088    },
7089    /// A quest's `on_complete` bundle.
7090    QuestComplete {
7091        /// The owning quest.
7092        quest: String,
7093    },
7094    /// An environment trigger's `effects` bundle — ambient, no DAG position.
7095    Trigger {
7096        /// The trigger id.
7097        trigger: String,
7098    },
7099    /// A trap's spec-0022 `payload` bundle — ambient, no DAG position.
7100    Trap {
7101        /// The trap id.
7102        trap: String,
7103    },
7104    /// A **dialogue option's** `set-checkpoint` `on_respawn` bundle — ambient, no
7105    /// DAG position, and the only site that does not live in the quests stage.
7106    ///
7107    /// This variant did not exist until the effect-root sweep, and its absence was
7108    /// load-bearing: `EffectSite` had no way to *represent* a dialogue-hosted
7109    /// bundle, so the four proofs that walk [`for_each_campaign_effect`]
7110    /// (`combat::actor_beats`, `validate::difficulty_checks`,
7111    /// `daylight::fightable_actor`, `nav::actor_fights`) could not have seen root 5
7112    /// even if their authors had thought of it. Widening the type is what let the
7113    /// walk widen.
7114    DialogueRespawn {
7115        /// The NPC whose dialogue tree hosts the option.
7116        npc: String,
7117        /// The node the option sits under.
7118        node: String,
7119    },
7120    /// A `shortcuts[].on_unlock` bundle (spec-0016 §2) — ambient, no DAG
7121    /// position, and the sixth root: representable here only since spec-0031, for
7122    /// exactly the reason [`EffectSite::DialogueRespawn`] records above.
7123    ShortcutUnlock {
7124        /// The shortcut id.
7125        shortcut: String,
7126    },
7127    /// A `shops[].offers[].effects` bundle (DSL v0.10, spec-0032) — ambient, no
7128    /// DAG position: nobody is forced to buy anything.
7129    ShopOffer {
7130        /// The shop id.
7131        shop: String,
7132        /// The offer's index within that shop, which is also its button order.
7133        offer: usize,
7134    },
7135    /// The campaign's `on_death` bundle (spec-0031) — ambient, no DAG position,
7136    /// and no owning object: there is one per campaign.
7137    OnDeath,
7138}
7139
7140impl EffectSite {
7141    /// The quest this site belongs to, if it has a DAG position at all.
7142    ///
7143    /// **This `Option` is the capability, and it is on the enum rather than on the
7144    /// variants that happen to have a quest.** Only two of the eight sites name a
7145    /// quest, because only two of the eight roots HAVE a DAG position: an ambient
7146    /// root — a trigger, a trap payload, a dialogue `on_respawn`, a shortcut's
7147    /// `on_unlock`, the campaign's `on_death`, a shop offer — fires at a moment no
7148    /// static model can order, and inventing a quest for one would be exactly the
7149    /// over-attribution the completability model must not make. Asking the question
7150    /// of every variant and getting an honest `None` is the lift;
7151    /// `tools/check-capability-ownership.py` check D asked for it while the field
7152    /// was still cross-cutting, and spec-0032's eighth site took it below that
7153    /// threshold, so the reasoning lives here now rather than in an exemption.
7154    pub fn quest(&self) -> Option<&str> {
7155        match self {
7156            EffectSite::Objective { quest, .. } | EffectSite::QuestComplete { quest } => {
7157                Some(quest)
7158            }
7159            EffectSite::Trigger { .. }
7160            | EffectSite::Trap { .. }
7161            | EffectSite::DialogueRespawn { .. }
7162            | EffectSite::ShortcutUnlock { .. }
7163            | EffectSite::ShopOffer { .. }
7164            | EffectSite::OnDeath => None,
7165        }
7166    }
7167}
7168
7169/// Visit **every** effect the compiler can lower — at every one of the five
7170/// effect roots, top-level and transitively nested — in a fixed deterministic
7171/// order, invoking `f(json_pointer, site, effect)`.
7172///
7173/// The roots come from [`crate::effects::for_each_effect_root`], the single
7174/// enumeration; nesting is descended through the single
7175/// [`QuestEffect::nested_effect_lists_labeled`] authority. Neither axis is
7176/// enumerated here, which is the point: this walk used to hand-list four of the
7177/// five roots (it had no `EffectSite` variant for the fifth), so every proof
7178/// defined in terms of it inherited that blind spot.
7179pub fn for_each_campaign_effect<'a>(
7180    c: &'a crate::envelope::Campaign,
7181    f: &mut dyn FnMut(&str, &EffectSite, &'a QuestEffect),
7182) {
7183    crate::effects::for_each_effect_root(c, &mut |root, list| {
7184        let site = match root.owner {
7185            crate::effects::EffectRootOwner::ObjectiveComplete { quest, objective } => {
7186                EffectSite::Objective {
7187                    quest: quest.id.as_str().to_string(),
7188                    objective: objective.to_string(),
7189                }
7190            }
7191            crate::effects::EffectRootOwner::QuestComplete { quest } => EffectSite::QuestComplete {
7192                quest: quest.id.as_str().to_string(),
7193            },
7194            crate::effects::EffectRootOwner::Trigger(t) => EffectSite::Trigger {
7195                trigger: t.id.as_str().to_string(),
7196            },
7197            crate::effects::EffectRootOwner::TrapPayload(t) => EffectSite::Trap {
7198                trap: t.id.as_str().to_string(),
7199            },
7200            crate::effects::EffectRootOwner::DialogueRespawn => {
7201                // The npc and node are in the root's path; parse them back rather
7202                // than widening the root walk's owner for one consumer.
7203                let seg = |n: usize| -> String {
7204                    root.path.split('/').nth(n).unwrap_or_default().to_string()
7205                };
7206                EffectSite::DialogueRespawn {
7207                    npc: seg(3),
7208                    node: seg(5),
7209                }
7210            }
7211            crate::effects::EffectRootOwner::ShortcutUnlock(s) => EffectSite::ShortcutUnlock {
7212                shortcut: s.id.as_str().to_string(),
7213            },
7214            crate::effects::EffectRootOwner::OnDeath => EffectSite::OnDeath,
7215            crate::effects::EffectRootOwner::ShopOffer(h) => EffectSite::ShopOffer {
7216                shop: h.id.as_str().to_string(),
7217                // The offer index is in the root's path (`…/offers/<i>/effects`),
7218                // parsed back rather than widening the owner for one consumer —
7219                // the same call the dialogue arm above makes.
7220                offer: root
7221                    .path
7222                    .split('/')
7223                    .nth(4)
7224                    .and_then(|n| n.parse().ok())
7225                    .unwrap_or(0),
7226            },
7227        };
7228        for (i, eff) in list.iter().enumerate() {
7229            campaign_effect_deep(eff, &format!("{}/{i}", root.path), &site, f);
7230        }
7231    });
7232}
7233
7234fn campaign_effect_deep<'a>(
7235    eff: &'a QuestEffect,
7236    path: &str,
7237    site: &EffectSite,
7238    f: &mut dyn FnMut(&str, &EffectSite, &'a QuestEffect),
7239) {
7240    f(path, site, eff);
7241    for (pseg, _kseg, list) in eff.nested_effect_lists_labeled() {
7242        for (j, inner) in list.iter().enumerate() {
7243            campaign_effect_deep(inner, &format!("{path}/{pseg}/{j}"), site, f);
7244        }
7245    }
7246}
7247
7248// ---------------------------------------------------------------------------
7249// The spine authority (`QuestPlanContent::spine`)
7250// ---------------------------------------------------------------------------
7251
7252#[cfg(test)]
7253mod spine_tests {
7254    use super::QuestPlanContent;
7255
7256    /// Build a plan from `(id, deps)` pairs plus a finale. JSON rather than a
7257    /// struct literal on purpose: a field added to `PlannedQuest` later must not
7258    /// red these tests for a reason that has nothing to do with the spine.
7259    fn plan(finale: &str, quests: &[(&str, &[&str])]) -> QuestPlanContent {
7260        let quests: Vec<serde_json::Value> = quests
7261            .iter()
7262            .map(|(id, deps)| {
7263                serde_json::json!({
7264                    "id": id,
7265                    "goal": "g",
7266                    "area": "area/keep",
7267                    "npcs": [],
7268                    "depends_on": deps,
7269                    "mandatory": true,
7270                    "act": 1,
7271                })
7272            })
7273            .collect();
7274        serde_json::from_value(serde_json::json!({
7275            "finale": finale,
7276            "quests": quests,
7277        }))
7278        .expect("plan fixture parses")
7279    }
7280
7281    fn sorted(p: &QuestPlanContent) -> Vec<String> {
7282        p.spine().into_iter().map(str::to_owned).collect()
7283    }
7284
7285    #[test]
7286    fn a_chain_is_wholly_spine() {
7287        let p = plan(
7288            "quest/c",
7289            &[
7290                ("quest/a", &[]),
7291                ("quest/b", &["quest/a"]),
7292                ("quest/c", &["quest/b"]),
7293            ],
7294        );
7295        assert_eq!(sorted(&p), ["quest/a", "quest/b", "quest/c"]);
7296    }
7297
7298    #[test]
7299    fn a_quest_the_finale_does_not_depend_on_is_off_the_spine() {
7300        // Exactly the `DW0132` shape: the plan does not converge, and the spine
7301        // is the half that does. The authority answers, it does not refuse — the
7302        // refusal is `validate`'s, built on this answer.
7303        let p = plan("quest/end", &[("quest/end", &[]), ("quest/side-trip", &[])]);
7304        assert_eq!(sorted(&p), ["quest/end"]);
7305    }
7306
7307    #[test]
7308    fn a_diamond_counts_the_join_once() {
7309        let p = plan(
7310            "quest/d",
7311            &[
7312                ("quest/a", &[]),
7313                ("quest/b", &["quest/a"]),
7314                ("quest/c", &["quest/a"]),
7315                ("quest/d", &["quest/b", "quest/c"]),
7316            ],
7317        );
7318        assert_eq!(sorted(&p), ["quest/a", "quest/b", "quest/c", "quest/d"]);
7319    }
7320
7321    #[test]
7322    fn a_cycle_terminates_and_yields_a_set() {
7323        // `DW0130` refuses this plan, but the authority is asked before that
7324        // verdict is known (the layout binding prints on an erroring campaign),
7325        // so it must terminate rather than hang.
7326        let p = plan(
7327            "quest/b",
7328            &[("quest/a", &["quest/b"]), ("quest/b", &["quest/a"])],
7329        );
7330        assert_eq!(sorted(&p), ["quest/a", "quest/b"]);
7331    }
7332
7333    #[test]
7334    fn a_dangling_dependency_is_reported_and_expands_no_further() {
7335        // The deliberate difference between the two derivations this function
7336        // replaced. `validate` pruned undeclared ids before walking; the
7337        // authority does not, because pruning them would make the set disagree
7338        // with the document, and naming an id the plan does not declare is
7339        // `DW0112`'s finding rather than the spine's.
7340        let p = plan("quest/end", &[("quest/end", &["quest/ghost"])]);
7341        assert_eq!(sorted(&p), ["quest/end", "quest/ghost"]);
7342    }
7343
7344    #[test]
7345    fn an_undeclared_finale_is_the_whole_spine() {
7346        // `DW0131`'s shape. The answer is honest about the document: nothing the
7347        // plan declares is on the spine of a finale it never declared.
7348        let p = plan(
7349            "quest/ghost",
7350            &[("quest/a", &[]), ("quest/b", &["quest/a"])],
7351        );
7352        assert_eq!(sorted(&p), ["quest/ghost"]);
7353    }
7354}