delvewright-dsl 0.34.0

Staged JSON DSL types and schemas for Delvewright adventure-map campaigns — the format the delvec compiler reads.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! **The one enumeration of the campaign's effect roots.**
//!
//! An *effect root* is a `Vec<QuestEffect>` that emission can lower. There are
//! seven, they hang off two different stage documents, and nothing about the
//! shape of the DSL makes them findable by inspection — which is why every walk
//! that needed "every effect" was, historically, written by someone enumerating
//! the roots they happened to know about.
//!
//! Six separate investigations each found one such walk and fixed it in place
//! (`plan::collect_region_events`, `l10n::each_string`, `timeline::walk_campaign` /
//! `nav::all_effects`, `flow::read_flags`, `emit::check_effect_anchors`,
//! `emit::declared_flags`). A sweep after the sixth found **thirteen more**
//! walkers still enumerating three or four of the five. None of them was red:
//! a walk that visits four of five roots produces correct-looking output over
//! any campaign that happens not to use the fifth, and it stays green until a
//! campaign uses it.
//!
//! Fixing thirteen walkers by hand fixes thirteen walkers. This module exists so
//! that the *next* root — and there will be one; the fifth was added once
//! already — is added in **one** place and every consumer inherits it:
//!
//! * [`for_each_effect_root`] is the single immutable enumeration. Every
//!   campaign-wide effect walk in the workspace is defined in terms of it or of
//!   [`for_each_campaign_effect`], which is defined in terms of it.
//! * [`for_each_effect_root_mut`] is its mutable mirror, generated from the
//!   **same macro body** ([`effect_root_walk`]) rather than written out a second
//!   time, so the two cannot drift: the root list exists once as tokens.
//! * [`EffectRootKind`] names the roots. `EffectRootKind::ALL` is the closed set;
//!   the walk asserts it visited every member on every call ([`RootBinding`]),
//!   so a root that stops being enumerated is a panic in every build rather than
//!   a quietly narrower answer.
//! * Consumers that need to know *which* root a bundle is match on
//!   [`EffectRootOwner`]. Adding a variant there is a rustc error at every such
//!   site, so a new root cannot be silently mis-classified either.
//!
//! Roots 6 and 7 were added by spec-0031, and they are worth reading as a pair
//! because they are the two ways this defect class recurs after the enumeration
//! exists:
//!
//! * **R6 `shortcuts[].on_unlock` was already a root and nobody had noticed.**
//!   It is a `Vec<QuestEffect>` hanging off a stage-5 struct, structurally
//!   identical in kind to `traps[].payload` (which is R4), and emission really
//!   lowers it (`emit::emit_shortcut_functions`). It was simply never listed —
//!   so every proof, every l10n pass and every diagnostic written for "the
//!   general path" silently did not cover it: a `narrate` inside it was never
//!   inventoried, a `set-flag` inside it was invisible to the flag model, and a
//!   `sequence` inside it would have emitted a `function` call to a function
//!   nothing generated. Zero campaigns happened to use it, which is the only
//!   reason it never shipped as a bug. The sixth blind spot in the family that
//!   three earlier hand-rolled walks each closed one instance of.
//! * **R7 `on_death` is new surface that starts inside the enumeration.** The
//!   whole point of adding it as a root, rather than as a hook on the checkpoint
//!   machinery that detects death, is that "the purse is dropped on death" then
//!   stops being an engine feature and becomes ordinary content in a general
//!   mechanism.
//!
//! What this module deliberately does **not** try to be is a guard against a
//! fourteenth hand-rolled walk being written tomorrow. Nothing in the type system
//! can stop someone iterating `campaign.quests.content.quests` directly; that
//! half of the obligation is `tools/ci/check-effect-roots.py`, which fails CI when a
//! source file reaches for two or more root fields outside this module.
//!
//! Determinism (ADR-0006): iteration is over `BTreeMap` keys and slices, in a
//! fixed order that is part of this module's contract — see
//! [`for_each_effect_root`].

use crate::envelope::Campaign;
use crate::fight::Fight;
use crate::stages::{EnvTrigger, Quest, QuestEffect, Shop, Shortcut, Trap};

/// The local part of a type-prefixed id (`npc/keeper` → `keeper`), the segment
/// every l10n key is built from. Duplicated from `l10n::local` deliberately: this
/// module is below `l10n` and the key scheme is part of a root's identity.
fn local(id: &str) -> &str {
    id.split_once('/').map(|(_, r)| r).unwrap_or(id)
}

/// Which of the campaign's effect roots a bundle is.
///
/// `ALL` is the closed set. Adding a variant is a rustc error in
/// [`EffectRootOwner::kind`] and in every consumer that matches on an owner, and
/// makes `ALL`'s length wrong until it is listed — so a new root cannot be added
/// without visiting the walk.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub enum EffectRootKind {
    /// A quest's `on_objective_complete[<objective>]` bundle.
    ObjectiveComplete,
    /// A quest's `on_complete` bundle.
    QuestComplete,
    /// An environment trigger's `effects` bundle.
    Trigger,
    /// A trap's spec-0022 `payload` bundle.
    TrapPayload,
    /// A dialogue option's `set-checkpoint` `on_respawn` bundle — a plain
    /// `Vec<QuestEffect>` hanging off the **dialogue** stage. `DialogueEffect`
    /// carries no gate, movement or actor verb of its own, which is the reasoning
    /// that made every older walk stop at the quests stage; the bundle nested
    /// inside one is quest-effect vocabulary all the same, and it is lowered
    /// (into `cp_on_respawn_<i>`).
    DialogueRespawn,
    /// A `shortcuts[].on_unlock` bundle (spec-0016 §2) — the beat that plays as
    /// the bar lifts. Lowered by `emit::emit_shortcut_functions` into
    /// `shortcut_open_<id>`, and unenumerated until spec-0031: the sixth blind
    /// spot, structurally the same shape as R4.
    ShortcutUnlock,
    /// The campaign's `on_death` bundle (DSL v0.10, spec-0031) — the effects that
    /// run at the moment a player dies, for that player. One per campaign, and
    /// visited only when non-empty, so `unbound_roots` tells the truth about a
    /// campaign that declares no death beat.
    OnDeath,
    /// A `shops[].offers[].effects` bundle (DSL v0.10, spec-0032) — what choosing
    /// a shop button does, for the player who chose it.
    ///
    /// It is a root rather than sugar for the reason spec-0031 states: *add a root
    /// when the bundle hangs off an object that has runtime machinery of its own.*
    /// An offer's machinery is a player-interaction advancement, a
    /// `minecraft:multi_action` dialog, a `/trigger` objective and a tick
    /// dispatch — the same hardware a bonfire rest runs on. Desugaring it into a
    /// `use` trigger would put two independent detectors on one right-click.
    ShopOffer,
    /// A wave's or an actor's `on_kill` bundle (spec-0074) — what happens each
    /// time a player is credited with killing one of the fight's bodies, run as
    /// that player. A root rather than sugar for the reason R8 is: it hangs off an
    /// object with runtime machinery of its own (the `player_killed_entity`
    /// advancement over the fight's tag). Visited only where declared, so
    /// `unbound_roots` tells the truth about a campaign with none.
    OnKill,
}

impl EffectRootKind {
    /// Every root, in enumeration order. Not the *visit* order — see
    /// [`for_each_effect_root`], which interleaves R1/R2 per quest.
    pub const ALL: [EffectRootKind; 9] = [
        EffectRootKind::ObjectiveComplete,
        EffectRootKind::QuestComplete,
        EffectRootKind::Trigger,
        EffectRootKind::TrapPayload,
        EffectRootKind::DialogueRespawn,
        EffectRootKind::ShortcutUnlock,
        EffectRootKind::OnDeath,
        EffectRootKind::ShopOffer,
        EffectRootKind::OnKill,
    ];

    /// How many roots there are. The binding ledger reports coverage against this.
    pub const COUNT: usize = Self::ALL.len();

    /// The stage document this root lives in (`quests` or `dialogue`).
    pub fn stage(self) -> &'static str {
        match self {
            EffectRootKind::ObjectiveComplete
            | EffectRootKind::QuestComplete
            | EffectRootKind::Trigger
            | EffectRootKind::TrapPayload
            | EffectRootKind::ShortcutUnlock
            | EffectRootKind::OnDeath
            | EffectRootKind::ShopOffer
            | EffectRootKind::OnKill => "quests",
            EffectRootKind::DialogueRespawn => "dialogue",
        }
    }

    /// Whether emission runs this root's bundle **with an acting player**
    /// (`@s`), or from the server command source.
    ///
    /// This is a fact about the ROOT, not about any verb inside it, and it is
    /// stated here — on the object class — rather than in the one diagnostic that
    /// first needed it. Four roots have a player: `on_objective_complete` and
    /// `on_complete` are dispatched `as @a` from the tick
    /// (`Audience::Party`), and `on_death` and a dialogue `on_respawn` are the
    /// dying/respawning player's own (`Audience::Solo`). Three do not: a
    /// trigger's effects, a trap's payload and a shortcut's `on_unlock` are all
    /// polled on the tick with no executor (`Audience::Scheduled`) — their own
    /// doc comments in `emit` say so.
    ///
    /// **This is the class default, and one root now overrides it per
    /// declaration.** A trigger declaring `audience: presser` (DSL v0.11) is
    /// dispatched by a `player_interacted_with_entity` advancement and DOES run
    /// as the clicking player; every other trigger is polled with no executor.
    /// A consumer that must be right about a *particular* bundle therefore asks
    /// [`EffectRootSite::runs_with_acting_player`], which answers per site;
    /// this stays the answer for the kind.
    ///
    /// It is exhaustive, so an eighth root cannot be added without answering it,
    /// and `emit::root_audience` is bound to it in both directions by
    /// `emit`'s own test — the emitter and this answer cannot drift.
    ///
    /// The consumer that needs it today is `DW0503`: a `player`-scoped runtime
    /// datum (spec-0031) read or written inside a bundle with no acting player
    /// would emit `@s` into a sourceless function, which fails silently at
    /// runtime.
    pub fn runs_with_acting_player(self) -> bool {
        match self {
            EffectRootKind::ObjectiveComplete
            | EffectRootKind::QuestComplete
            | EffectRootKind::DialogueRespawn
            | EffectRootKind::OnDeath
            // A shop offer's handler is dispatched `as @a[scores={…}]`, so the
            // choosing player IS the acting player — which is what makes a
            // `player`-scoped purse debitable from a purchase.
            | EffectRootKind::ShopOffer
            // A kill's reward runs as the player the kill was credited to.
            | EffectRootKind::OnKill => true,
            EffectRootKind::Trigger
            | EffectRootKind::TrapPayload
            | EffectRootKind::ShortcutUnlock => false,
        }
    }

    /// A short human label, used by the binding ledger and by diagnostics that
    /// report which roots a proof examined.
    pub fn label(self) -> &'static str {
        match self {
            EffectRootKind::ObjectiveComplete => "quest on_objective_complete",
            EffectRootKind::QuestComplete => "quest on_complete",
            EffectRootKind::Trigger => "trigger effects",
            EffectRootKind::TrapPayload => "trap payload",
            EffectRootKind::DialogueRespawn => "dialogue set-checkpoint on_respawn",
            EffectRootKind::ShortcutUnlock => "shortcut on_unlock",
            EffectRootKind::OnDeath => "campaign on_death",
            EffectRootKind::ShopOffer => "shop offer effects",
            EffectRootKind::OnKill => "fight on_kill",
        }
    }
}

/// What a root hangs off, with the owning object attached.
///
/// This is what a consumer matches on when it needs to reason about *when* a
/// bundle fires (the completability model) or *who* gates it (a trigger's or
/// trap's `requires_flags`). Because the match is exhaustive at every such site,
/// an eighth root is a compile error everywhere the answer would have to change.
#[derive(Clone, Copy)]
pub enum EffectRootOwner<'a> {
    /// A quest's `on_objective_complete[<objective>]` — fires at that objective's
    /// `critical_path` step. Forced: completing the objective is the mainline.
    ObjectiveComplete {
        /// The owning quest.
        quest: &'a Quest,
        /// The objective whose completion fires the bundle.
        objective: &'a str,
    },
    /// A quest's `on_complete` — fires at the quest's completion step. Forced.
    QuestComplete {
        /// The owning quest.
        quest: &'a Quest,
    },
    /// An environment `triggers[].effects` — proximity/interaction-fired, so it
    /// has no step of its own. Carries the trigger, whose `requires_flags` gate
    /// the whole bundle.
    Trigger(&'a EnvTrigger),
    /// A `traps[].payload` (spec-0022) — proximity/interaction-fired exactly like
    /// a trigger, and **optional**: the party may never trip it. Carries the trap,
    /// whose `requires_flags` gate the whole payload.
    TrapPayload(&'a Trap),
    /// A dialogue option's `set-checkpoint` `on_respawn` bundle — re-run on death
    /// while that checkpoint is active, so it is optional too (nobody is forced to
    /// die). Carries no owning object: the npc, node and option are all named in
    /// the site's `path`, and no consumer needs to reach the tree itself.
    DialogueRespawn,
    /// A `shortcuts[].on_unlock` (spec-0016 §2) — fired once, by the far-side
    /// interaction, and **optional**: `Plan::build` registers every shortcut gate
    /// as sealed at step 0 precisely so the delve is proven completable with no
    /// shortcut ever taken. Carries the shortcut; it declares no flag gate of its
    /// own, so the whole bundle is ungated.
    ShortcutUnlock(&'a Shortcut),
    /// The campaign's `on_death` (spec-0031) — fired at the moment a player dies,
    /// so it has no step of its own and is **optional** in the strongest sense:
    /// nobody is forced to die. Carries no owning object; there is exactly one
    /// per campaign and its path is `/content/on_death`.
    OnDeath,
    /// A `shops[].offers[].effects` (spec-0032) — fired by the player pressing a
    /// button, so it has no step of its own and is **optional**: nobody is forced
    /// to buy anything. Carries the shop; the offer index is in the site's `path`.
    ShopOffer(&'a Shop),
    /// A wave's or an actor's `on_kill` (spec-0074) — fired by a player being
    /// credited with a kill, so it has no step of its own and is **optional**:
    /// nobody is forced to be credited with a kill (a body may fall, burn or be
    /// cut down by another mob). Carries the fight.
    OnKill(Fight<'a>),
}

impl<'a> EffectRootOwner<'a> {
    /// Which root this is. The one place a root's owner is mapped to its kind.
    pub fn kind(&self) -> EffectRootKind {
        match self {
            EffectRootOwner::ObjectiveComplete { .. } => EffectRootKind::ObjectiveComplete,
            EffectRootOwner::QuestComplete { .. } => EffectRootKind::QuestComplete,
            EffectRootOwner::Trigger(_) => EffectRootKind::Trigger,
            EffectRootOwner::TrapPayload(_) => EffectRootKind::TrapPayload,
            EffectRootOwner::DialogueRespawn => EffectRootKind::DialogueRespawn,
            EffectRootOwner::ShortcutUnlock(_) => EffectRootKind::ShortcutUnlock,
            EffectRootOwner::OnDeath => EffectRootKind::OnDeath,
            EffectRootOwner::ShopOffer(_) => EffectRootKind::ShopOffer,
            EffectRootOwner::OnKill(_) => EffectRootKind::OnKill,
        }
    }

    /// Whether emission runs **this site's** bundle with an acting player (`@s`).
    ///
    /// [`EffectRootKind::runs_with_acting_player`] answers for the root *class*,
    /// which is the right answer for six of the eight and was the right answer for
    /// all of them until DSL v0.11. A trigger is now the exception: an
    /// `audience: presser` click is dispatched by a
    /// `minecraft:player_interacted_with_entity` advancement and therefore runs as
    /// the player who pressed, while every other trigger is polled on the tick
    /// with no executor. The distinction is per-declaration, so it is answered
    /// where the declaration is reachable — here — and the kind-level answer stays
    /// the class default that `emit::root_audience` is bound to.
    pub fn runs_with_acting_player(&self) -> bool {
        match self {
            EffectRootOwner::Trigger(t) => t.addresses_presser(),
            other => other.kind().runs_with_acting_player(),
        }
    }

    /// The quest this root belongs to, if it has a DAG position at all.
    pub fn quest(&self) -> Option<&'a Quest> {
        match self {
            EffectRootOwner::ObjectiveComplete { quest, .. }
            | EffectRootOwner::QuestComplete { quest } => Some(quest),
            EffectRootOwner::Trigger(_)
            | EffectRootOwner::TrapPayload(_)
            | EffectRootOwner::DialogueRespawn
            | EffectRootOwner::ShortcutUnlock(_)
            | EffectRootOwner::OnDeath
            | EffectRootOwner::ShopOffer(_)
            | EffectRootOwner::OnKill(_) => None,
        }
    }
}

/// One effect root: which it is, where it is, and what its l10n keys hang off.
///
/// `path` points at the **list**; an element's pointer is `path` + `/<index>`.
/// `key` is likewise the list's keybase; an element's key is `key` + `.<index>`.
pub struct EffectRootSite<'a> {
    /// What this root hangs off, with the owning object.
    pub owner: EffectRootOwner<'a>,
    /// The stage document the list lives in (`quests` or `dialogue`).
    pub stage: &'static str,
    /// JSON pointer to the list within that document.
    pub path: String,
    /// The list's l10n key prefix.
    pub key: String,
}

impl EffectRootSite<'_> {
    /// Which root this site is.
    pub fn kind(&self) -> EffectRootKind {
        self.owner.kind()
    }

    /// Whether emission runs this site's bundle with an acting player — the
    /// per-declaration answer (see [`EffectRootOwner::runs_with_acting_player`]),
    /// which is what `DW0357`/`DW0503` must ask.
    pub fn runs_with_acting_player(&self) -> bool {
        self.owner.runs_with_acting_player()
    }
}

/// What a walk over the effect roots actually examined.
///
/// CLAUDE.md: *a green gate that binds to nothing is vacuous, not a pass*. A proof
/// over "every effect" is only as good as the roots it reached and the bundles it
/// found there, and neither number is visible from the proof's own output. This
/// is that ledger, filled in by [`for_each_effect_root`] on every call.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RootBinding {
    /// How many of [`EffectRootKind::COUNT`] roots the walk enumerated. Always
    /// `COUNT` for a walk that ran — a smaller number means a root stopped being
    /// enumerated, which the walk itself asserts against.
    pub roots_enumerated: usize,
    /// Per-root: how many bundles the campaign actually has there. A zero is not
    /// a failure — a campaign with no traps has no `traps[].payload` — but it is
    /// the reason a proof over that root binds to nothing, and it is reported
    /// rather than left for a reader to infer.
    pub sites: [(EffectRootKind, usize); EffectRootKind::COUNT],
    /// Total top-level effects across every root.
    pub effects: usize,
}

impl RootBinding {
    /// The roots this campaign has no bundles at — where any proof over the
    /// effect surface is necessarily unbound.
    pub fn unbound_roots(&self) -> Vec<EffectRootKind> {
        self.sites
            .iter()
            .filter(|(_, n)| *n == 0)
            .map(|(k, _)| *k)
            .collect()
    }

    /// The ledger as a JSON object, for `<out>/validation/effect-roots.json`.
    ///
    /// [`Self::summary`] renders the same numbers for a human reading stderr,
    /// and stderr is where they stayed: a build's stated binding was a *string*
    /// nothing downstream could read, so a gate that wants to assert "this
    /// campaign's effect walk bound to something" had to scrape prose or go
    /// without. Every other proof in this compiler already publishes its binding
    /// as a `validation/*.json` ledger; this is the one that did not, and
    /// spec-0039 criterion 6 needs it machine-readable — "printed somewhere" is
    /// explicitly not enough.
    ///
    /// `unbound_roots` is listed rather than left to be derived: a zero at a
    /// root is not a failure (a campaign with no traps has no trap payloads),
    /// but it is the reason any proof over that root binds to nothing, and the
    /// point of a ledger is that a reader does not have to infer it.
    pub fn to_json(&self) -> serde_json::Value {
        let mut sites = serde_json::Map::new();
        for (kind, n) in &self.sites {
            sites.insert(kind.label().to_string(), serde_json::json!(n));
        }
        serde_json::json!({
            "roots_enumerated": self.roots_enumerated,
            "roots_total": EffectRootKind::COUNT,
            "bundles": self.sites.iter().map(|(_, n)| n).sum::<usize>(),
            "effects": self.effects,
            "sites": serde_json::Value::Object(sites),
            "unbound_roots": self
                .unbound_roots()
                .iter()
                .map(|k| k.label())
                .collect::<Vec<_>>(),
        })
    }

    /// A one-line, deterministic rendering for a report or a `--json` field.
    pub fn summary(&self) -> String {
        let per: Vec<String> = self
            .sites
            .iter()
            .map(|(k, n)| format!("{}={n}", k.label()))
            .collect();
        format!(
            "roots {}/{}, bundles {}, effects {} [{}]",
            self.roots_enumerated,
            EffectRootKind::COUNT,
            self.sites.iter().map(|(_, n)| n).sum::<usize>(),
            self.effects,
            per.join(", ")
        )
    }
}

/// **The root list, written once, as tokens.**
///
/// Expanded twice — by [`for_each_effect_root`] with `iter`/`as_slice` and by
/// [`for_each_effect_root_mut`] with `iter_mut`/`as_mut_slice`. There is no second
/// copy of "which lists are roots" anywhere in the workspace, so adding a root is
/// one edit here and every consumer of either walk inherits it (roots 6 and 7 were
/// added by spec-0031 and this claim is what made it a small change). That is
/// the whole point of this module: the previous arrangement had the root list
/// written out four times (twice in `l10n`, once in `plan`, once in `stages`) and
/// approximated a further thirteen times by walkers that enumerated three or four
/// of the five.
///
/// `$visit` is called as `$visit((kind, owner, objective), path, key, list)`. The
/// per-root owner expressions are parameters because the mutable expansion cannot
/// produce them: it cannot hand out `&Quest` while holding `&mut [QuestEffect]`
/// from the same quest. That asymmetry is confined to what is *attached* to a
/// visit — never to which roots are visited, which is what this body fixes.
macro_rules! effect_root_walk {
    (
        campaign: $c:expr,
        iter: $iter:ident,
        slice: $slice:ident,
        respawn: $respawn:ident,
        note: $note:expr,
        visit: $visit:expr,
        quest_owner: |$q:ident| $ownq:expr,
        trigger_owner: |$t:ident| $ownt:expr,
        trap_owner: |$p:ident| $ownp:expr,
        dialogue_owner: $ownd:expr,
        shortcut_owner: |$s:ident| $owns:expr,
        death_owner: $ownx:expr,
        shop_owner: |$h:ident| $ownh:expr,
        opt: $opt:ident,
        wave_owner: |$w:ident| $ownw:expr,
        actor_owner: |$a:ident| $owna:expr,
    ) => {{
        #[allow(unused_mut)]
        let mut visit = $visit;
        // Fired once per root, before its loop, whether or not this campaign has a
        // single bundle there. That is the distinction the binding ledger exists to
        // make: "this walk enumerated the root" and "this campaign uses the root"
        // are different facts, and a proof that conflates them reports a vacuous
        // green as a pass (CLAUDE.md).
        #[allow(unused_mut)]
        let mut note = $note;
        // R1 `on_objective_complete` and R2 `on_complete`, interleaved per quest.
        // This order is contractual: it is the order emission writes bundles in and
        // the order the l10n inventory keys them in, so a campaign that predates a
        // later root produces byte-identical output.
        note(EffectRootKind::ObjectiveComplete);
        note(EffectRootKind::QuestComplete);
        for (qi, $q) in $c.quests.content.quests.$iter().enumerate() {
            let ql = local($q.id.as_str()).to_string();
            let owner = $ownq;
            for (oid, effs) in $q.on_objective_complete.$iter() {
                let ol = local(oid.as_str()).to_string();
                visit(
                    (EffectRootKind::ObjectiveComplete, owner, Some(oid.as_str())),
                    format!(
                        "/content/quests/{qi}/on_objective_complete/{}",
                        oid.as_str()
                    ),
                    format!("fx.{ql}.oc.{ol}"),
                    effs.$slice(),
                );
            }
            visit(
                (EffectRootKind::QuestComplete, owner, None),
                format!("/content/quests/{qi}/on_complete"),
                format!("fx.{ql}.done"),
                $q.on_complete.$slice(),
            );
        }
        // R3 `triggers[].effects`.
        note(EffectRootKind::Trigger);
        for (ti, $t) in $c.quests.content.triggers.$iter().enumerate() {
            let tl = local($t.id.as_str()).to_string();
            let owner = $ownt;
            visit(
                (EffectRootKind::Trigger, owner, None),
                format!("/content/triggers/{ti}/effects"),
                format!("fx.trig.{tl}"),
                $t.effects.$slice(),
            );
        }
        // R4 `traps[].payload` (spec-0022 — a payload is an effect root).
        note(EffectRootKind::TrapPayload);
        for (pi, $p) in $c.quests.content.traps.$iter().enumerate() {
            let pl = local($p.id.as_str()).to_string();
            let owner = $ownp;
            visit(
                (EffectRootKind::TrapPayload, owner, None),
                format!("/content/traps/{pi}/payload"),
                format!("fx.trap.{pl}"),
                $p.payload.$slice(),
            );
        }
        // R5 a dialogue option's `set-checkpoint` `on_respawn` bundle — the root
        // that hangs off a different stage document, and the one every walk written
        // from "effects live in the quests stage" missed.
        note(EffectRootKind::DialogueRespawn);
        for (di, tree) in $c.dialogue.content.dialogues.$iter().enumerate() {
            let np = local(tree.npc.as_str()).to_string();
            let owner = $ownd;
            for (ni, node) in tree.nodes.$iter().enumerate() {
                let nd = local(node.id.as_str()).to_string();
                for (oi, opt) in node.options.$iter().enumerate() {
                    for (ei, de) in opt.effects.$iter().enumerate() {
                        let Some(on_respawn) = de.$respawn() else {
                            continue;
                        };
                        visit(
                            (EffectRootKind::DialogueRespawn, owner, None),
                            format!(
                                "/content/dialogues/{di}/nodes/{ni}/options/{oi}/effects/{ei}/on_respawn"
                            ),
                            format!("fx.dlg.{np}.{nd}.{oi}.{ei}.respawn"),
                            on_respawn,
                        );
                    }
                }
            }
        }
        // R6 `shortcuts[].on_unlock` (spec-0016 §2) — an effect bundle emission
        // has always lowered and no enumeration knew about, closed by spec-0031.
        note(EffectRootKind::ShortcutUnlock);
        for (si, $s) in $c.quests.content.shortcuts.$iter().enumerate() {
            let sl = local($s.id.as_str()).to_string();
            let owner = $owns;
            visit(
                (EffectRootKind::ShortcutUnlock, owner, None),
                format!("/content/shortcuts/{si}/on_unlock"),
                format!("fx.sc.{sl}"),
                $s.on_unlock.$slice(),
            );
        }
        // R7 the campaign's `on_death` (DSL v0.10, spec-0031) — one bundle, no
        // owning object, visited only when the campaign declares one. An empty
        // list is NOT visited: `RootBinding` must be able to say "this campaign
        // has no death beat", which a site count that is always 1 could not.
        note(EffectRootKind::OnDeath);
        {
            let owner = $ownx;
            let on_death = $c.quests.content.on_death.$slice();
            if !on_death.is_empty() {
                visit(
                    (EffectRootKind::OnDeath, owner, None),
                    "/content/on_death".to_string(),
                    "fx.death".to_string(),
                    on_death,
                );
            }
        }
        // R8 `shops[].offers[].effects` (DSL v0.10, spec-0032) — appended after
        // R7 for the same reason every root is appended: a campaign that predates
        // it keys and emits byte-identically.
        note(EffectRootKind::ShopOffer);
        for (hi, $h) in $c.quests.content.shops.$iter().enumerate() {
            let hl = local($h.id.as_str()).to_string();
            let owner = $ownh;
            for (oi, off) in $h.offers.$iter().enumerate() {
                visit(
                    (EffectRootKind::ShopOffer, owner, None),
                    format!("/content/shops/{hi}/offers/{oi}/effects"),
                    format!("fx.shop.{hl}.{oi}"),
                    off.effects.$slice(),
                );
            }
        }
        // R9 `waves[].on_kill` then `actors[].on_kill` (spec-0074) — appended after
        // R8, and visited only where a fight declares a bundle, so a campaign
        // with none keys and emits byte-identically and `RootBinding` can say it
        // has none. The key is the fight's own (`wave.<id>.on_kill`,
        // `actor.<id>.on_kill`): the bundle belongs to the body, not to a beat.
        note(EffectRootKind::OnKill);
        for (wi, $w) in $c.quests.content.waves.$iter().enumerate() {
            let wl = local($w.id.as_str()).to_string();
            let owner = $ownw;
            if let Some(ok) = $w.on_kill.$opt() {
                visit(
                    (EffectRootKind::OnKill, owner, None),
                    format!("/content/waves/{wi}/on_kill/effects"),
                    format!("wave.{wl}.on_kill"),
                    ok.effects.$slice(),
                );
            }
        }
        for (ai, $a) in $c.quests.content.actors.$iter().enumerate() {
            let al = local($a.id.as_str()).to_string();
            let owner = $owna;
            if let Some(ok) = $a.on_kill.$opt() {
                visit(
                    (EffectRootKind::OnKill, owner, None),
                    format!("/content/actors/{ai}/on_kill/effects"),
                    format!("actor.{al}.on_kill"),
                    ok.effects.$slice(),
                );
            }
        }
    }};
}

/// The owning object as the macro yields it, before it is paired with the
/// objective id that only R1 has. Internal to [`for_each_effect_root`].
#[derive(Clone, Copy)]
enum RawOwner<'a> {
    Quest(&'a Quest),
    Trigger(&'a EnvTrigger),
    Trap(&'a Trap),
    Dialogue,
    Shortcut(&'a Shortcut),
    Death,
    Shop(&'a Shop),
    Fight(Fight<'a>),
}

impl<'a> RawOwner<'a> {
    fn attach(self, kind: EffectRootKind, objective: Option<&'a str>) -> EffectRootOwner<'a> {
        match (self, kind) {
            (RawOwner::Quest(quest), EffectRootKind::ObjectiveComplete) => {
                EffectRootOwner::ObjectiveComplete {
                    quest,
                    objective: objective
                        .expect("an on_objective_complete root always names its objective"),
                }
            }
            (RawOwner::Quest(quest), EffectRootKind::QuestComplete) => {
                EffectRootOwner::QuestComplete { quest }
            }
            (RawOwner::Trigger(t), EffectRootKind::Trigger) => EffectRootOwner::Trigger(t),
            (RawOwner::Trap(p), EffectRootKind::TrapPayload) => EffectRootOwner::TrapPayload(p),
            (RawOwner::Dialogue, EffectRootKind::DialogueRespawn) => {
                EffectRootOwner::DialogueRespawn
            }
            (RawOwner::Shortcut(s), EffectRootKind::ShortcutUnlock) => {
                EffectRootOwner::ShortcutUnlock(s)
            }
            (RawOwner::Death, EffectRootKind::OnDeath) => EffectRootOwner::OnDeath,
            (RawOwner::Shop(h), EffectRootKind::ShopOffer) => EffectRootOwner::ShopOffer(h),
            (RawOwner::Fight(f), EffectRootKind::OnKill) => EffectRootOwner::OnKill(f),
            (owner, kind) => unreachable!(
                "effect root {kind:?} was handed an owner of the wrong shape ({})",
                match owner {
                    RawOwner::Quest(_) => "quest",
                    RawOwner::Trigger(_) => "trigger",
                    RawOwner::Trap(_) => "trap",
                    RawOwner::Dialogue => "dialogue",
                    RawOwner::Shortcut(_) => "shortcut",
                    RawOwner::Death => "on_death",
                    RawOwner::Shop(_) => "shop",
                    RawOwner::Fight(_) => "fight",
                }
            ),
        }
    }
}

/// Visit **every effect root the compiler can lower**, in one fixed deterministic
/// order, as `f(&site, list)`.
///
/// The order is contractual, because emission and the l10n key scheme are defined
/// by it: per quest, `on_objective_complete` (a `BTreeMap`, so key-ordered) then
/// `on_complete`; then every trigger; then every trap payload; then every dialogue
/// `on_respawn` bundle; then every shortcut's `on_unlock`; then the campaign's
/// `on_death`. **Each new root is appended, never inserted**, so a campaign that
/// predates it produces byte-identical output — that is why R6 hangs off the
/// quests stage but comes after the dialogue-stage R5.
///
/// A list is a root if `emit::emit_quest_effect` can reach it, **not** if the
/// quests stage happens to own it. That distinction is the entire defect class:
/// six of the seven roots are reachable from `campaign.quests.content` and R5 is
/// not, so every walk reasoned from "effects live in the quests stage" was
/// correct-looking, green, and wrong. R6 is the mirror-image reading error —
/// `shortcuts[].on_unlock` *is* in `campaign.quests.content` and was still missed,
/// because the walks were written against a remembered list rather than against
/// what emission reaches.
///
/// Returns the [`RootBinding`] ledger — how many roots were enumerated and how
/// many bundles each actually bound to on this campaign. A proof that states what
/// it examined reports it; a caller that does not need it may drop it.
///
/// # Panics
///
/// If the walk failed to enumerate all [`EffectRootKind::COUNT`] roots. Unreachable
/// by construction — the macro emits one block per root — and asserted anyway, in
/// release builds too, because the failure it guards has no other symptom: a walk
/// that quietly stops visiting a root just answers a narrower question and stays
/// green over every campaign that does not use it. That is how this defect class
/// survived six independent fixes.
pub fn for_each_effect_root<'a>(
    c: &'a Campaign,
    f: &mut dyn FnMut(&EffectRootSite<'a>, &'a [QuestEffect]),
) -> RootBinding {
    let mut sites = [
        (EffectRootKind::ObjectiveComplete, 0usize),
        (EffectRootKind::QuestComplete, 0usize),
        (EffectRootKind::Trigger, 0usize),
        (EffectRootKind::TrapPayload, 0usize),
        (EffectRootKind::DialogueRespawn, 0usize),
        (EffectRootKind::ShortcutUnlock, 0usize),
        (EffectRootKind::OnDeath, 0usize),
        (EffectRootKind::ShopOffer, 0usize),
        (EffectRootKind::OnKill, 0usize),
    ];
    debug_assert_eq!(
        sites.map(|(k, _)| k),
        EffectRootKind::ALL,
        "the binding ledger's slots are EffectRootKind::ALL, in order"
    );
    let mut effects = 0usize;
    // Which roots the walk reached at all — set by `note`, independently of whether
    // this campaign has a bundle there.
    let mut enumerated = [false; EffectRootKind::COUNT];
    fn slot_of(kind: EffectRootKind) -> usize {
        EffectRootKind::ALL
            .iter()
            .position(|k| *k == kind)
            .expect("every root kind is a member of EffectRootKind::ALL")
    }

    effect_root_walk!(
        campaign: c,
        iter: iter,
        slice: as_slice,
        respawn: set_checkpoint_on_respawn,
        note: |kind: EffectRootKind| {
            enumerated[slot_of(kind)] = true;
        },
        visit: |(kind, owner, objective): (EffectRootKind, RawOwner<'a>, Option<&'a str>),
                path: String,
                key: String,
                list: &'a [QuestEffect]| {
            let owner = owner.attach(kind, objective);
            debug_assert_eq!(owner.kind(), kind, "a site's owner and kind must agree");
            let slot = slot_of(kind);
            sites[slot].1 += 1;
            effects += list.len();
            f(
                &EffectRootSite {
                    owner,
                    stage: kind.stage(),
                    path,
                    key,
                },
                list,
            );
        },
        quest_owner: |q| RawOwner::Quest(q),
        trigger_owner: |t| RawOwner::Trigger(t),
        trap_owner: |p| RawOwner::Trap(p),
        dialogue_owner: RawOwner::Dialogue,
        shortcut_owner: |s| RawOwner::Shortcut(s),
        death_owner: RawOwner::Death,
        shop_owner: |h| RawOwner::Shop(h),
        opt: as_ref,
        wave_owner: |w| RawOwner::Fight(Fight::Wave(w)),
        actor_owner: |a| RawOwner::Fight(Fight::Actor(a)),
    );

    let missed: Vec<&str> = EffectRootKind::ALL
        .iter()
        .zip(enumerated)
        .filter(|(_, s)| !*s)
        .map(|(k, _)| k.label())
        .collect();
    assert!(
        missed.is_empty(),
        "for_each_effect_root enumerated {} of {} effect roots — missing: {}. A root that \
         stops being enumerated has no other symptom.",
        EffectRootKind::COUNT - missed.len(),
        EffectRootKind::COUNT,
        missed.join(", ")
    );

    RootBinding {
        roots_enumerated: EffectRootKind::COUNT,
        sites,
        effects,
    }
}

/// The callback [`for_each_effect_root_mut`] hands each root to:
/// `(kind, json_pointer_to_the_list, l10n_keybase, list)`. `'a` ties the effects
/// to the campaign borrow, so a consumer may collect them; `'f` is the callback's
/// own borrow.
pub type RootVisitorMut<'a, 'f> = dyn FnMut(EffectRootKind, &str, &str, &'a mut [QuestEffect]) + 'f;

/// The **mutable mirror** of [`for_each_effect_root`]: the identical roots, in the
/// identical order, with the same `(stage, path, key)` descriptors, exposed mutably
/// so the localization pass can rewrite player-visible strings in place.
///
/// Generated from the same [`effect_root_walk`] body, so "which lists are roots" is
/// not written twice and the pair cannot drift the way two hand-written mirrors
/// can. `&mut Campaign` cannot yield the owning `&Quest` alongside
/// `&mut [QuestEffect]` from the same quest, so this walk carries the
/// [`EffectRootKind`] rather than an [`EffectRootOwner`]. That is the only
/// difference between the two, and it is a difference in what is attached to a
/// visit — never in which roots are visited.
pub fn for_each_effect_root_mut<'a>(c: &'a mut Campaign, f: &mut RootVisitorMut<'a, '_>) {
    effect_root_walk!(
        campaign: c,
        iter: iter_mut,
        slice: as_mut_slice,
        respawn: set_checkpoint_on_respawn_mut,
        note: |_kind: EffectRootKind| {},
        visit: |(kind, _owner, _objective): (EffectRootKind, (), Option<&str>),
                path: String,
                key: String,
                list: &'a mut [QuestEffect]| {
            f(kind, &path, &key, list);
        },
        quest_owner: |_q| (),
        trigger_owner: |_t| (),
        trap_owner: |_p| (),
        dialogue_owner: (),
        shortcut_owner: |_s| (),
        death_owner: (),
        shop_owner: |_h| (),
        opt: as_mut,
        wave_owner: |_w| (),
        actor_owner: |_a| (),
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The binding ledger's slots are `EffectRootKind::ALL`, in order — the
    /// property `summary()` and `unbound_roots()` both read off positionally.
    #[test]
    fn binding_slots_are_all_the_roots_in_order() {
        let b = RootBinding {
            roots_enumerated: EffectRootKind::COUNT,
            sites: [
                (EffectRootKind::ObjectiveComplete, 0),
                (EffectRootKind::QuestComplete, 0),
                (EffectRootKind::Trigger, 0),
                (EffectRootKind::TrapPayload, 0),
                (EffectRootKind::DialogueRespawn, 0),
                (EffectRootKind::ShortcutUnlock, 0),
                (EffectRootKind::OnDeath, 0),
                (EffectRootKind::ShopOffer, 0),
                (EffectRootKind::OnKill, 0),
            ],
            effects: 0,
        };
        assert_eq!(b.sites.map(|(k, _)| k), EffectRootKind::ALL);
        assert_eq!(b.unbound_roots().len(), EffectRootKind::COUNT);
    }

    /// Every root kind names a stage and a label, and the stages are exactly the
    /// two stage documents effect roots live in.
    #[test]
    fn every_root_names_its_stage() {
        for k in EffectRootKind::ALL {
            assert!(matches!(k.stage(), "quests" | "dialogue"), "{k:?}");
            assert!(!k.label().is_empty(), "{k:?}");
        }
    }
}