hiraku-engine 0.1.0

Hiraku visual-novel engine
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
//! Engine-facing story policy built on the generic execution runtime.
//!
//! It owns story capabilities and wait policy while ECS systems own effects.

use std::collections::{BTreeMap, VecDeque};

use hiraku_script::{Bytecode, Value};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::execution_runtime::{
    ExecutionEvent, ExecutionId, ExecutionMode, ExecutionRuntime, ExecutionRuntimeError,
    ExecutionRuntimeSnapshot,
};
use crate::script::capabilities::{
    CharacterCapabilityError, StoryCallOutcome, StoryControl, StoryEffect, StoryNativeHost,
    StoryNativeHostSnapshot, StoryTaskKind, StoryWait,
};

/// Engine-facing whole-story driver. It translates generic VM boundaries into
/// story effects without introducing a second executable representation.
pub struct StoryRuntime {
    execution: ExecutionRuntime,
    host: StoryNativeHost,
    pending: VecDeque<StoryRuntimeEvent>,
    active_task_effects: BTreeMap<ExecutionId, Vec<StoryEffect>>,
    deferred_task_completions: BTreeMap<ExecutionId, Value>,
    waiting_task: Option<ExecutionId>,
    waiting_interactive_task: Option<ExecutionId>,
    choice: Option<ChoiceState>,
    blocked: bool,
    blocked_wait: Option<StoryWait>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct ChoiceOption {
    label: String,
    body: Value,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
enum ChoiceState {
    Collecting {
        builder_task: ExecutionId,
        prompt: String,
        options: Vec<ChoiceOption>,
    },
    AwaitingSelection {
        prompt: String,
        options: Vec<ChoiceOption>,
    },
    RunningBranch {
        task: ExecutionId,
        selected: usize,
    },
}

#[derive(Clone, Debug, PartialEq)]
pub enum StoryRuntimeEvent {
    Effect(StoryEffect),
    Wait(StoryWait),
    OpenUi {
        path: String,
        arguments: Vec<Value>,
    },
    Choice {
        prompt: String,
        options: Vec<String>,
    },
    TaskEffect {
        task: ExecutionId,
        effect: StoryEffect,
    },
    Completed(Value),
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StoryRuntimeSnapshot {
    execution: ExecutionRuntimeSnapshot,
    host: StoryNativeHostSnapshot,
    active_task_effects: BTreeMap<ExecutionId, Vec<StoryEffect>>,
    deferred_task_completions: BTreeMap<ExecutionId, Value>,
    waiting_task: Option<ExecutionId>,
    waiting_interactive_task: Option<ExecutionId>,
    choice: Option<ChoiceState>,
    blocked: bool,
    #[serde(default)]
    blocked_wait: Option<StoryWait>,
}

impl StoryRuntime {
    pub fn new(bytecode: Bytecode) -> Result<Self, StoryRuntimeError> {
        Ok(Self {
            execution: ExecutionRuntime::new(bytecode)?,
            host: StoryNativeHost::new(),
            pending: VecDeque::new(),
            active_task_effects: BTreeMap::new(),
            deferred_task_completions: BTreeMap::new(),
            waiting_task: None,
            waiting_interactive_task: None,
            choice: None,
            blocked: false,
            blocked_wait: None,
        })
    }

    pub fn snapshot(&self) -> Result<StoryRuntimeSnapshot, StoryRuntimeError> {
        if !self.pending.is_empty() {
            return Err(StoryRuntimeError::NotAtSnapshotBoundary);
        }
        Ok(StoryRuntimeSnapshot {
            execution: self.execution.snapshot(),
            host: self.host.snapshot(),
            active_task_effects: self.active_task_effects.clone(),
            deferred_task_completions: self.deferred_task_completions.clone(),
            waiting_task: self.waiting_task,
            waiting_interactive_task: self.waiting_interactive_task,
            choice: self.choice.clone(),
            blocked: self.blocked,
            blocked_wait: self.blocked_wait.clone(),
        })
    }

    pub fn restore(
        bytecode: Bytecode,
        mut snapshot: StoryRuntimeSnapshot,
    ) -> Result<Self, StoryRuntimeError> {
        // Voice playback is transient output rather than durable story state.
        // The execution has already consumed the native call and only keeps an
        // active effect so seq/wait can observe its completion. Loading must
        // complete that effect without emitting PlayVoice again.
        let mut completed_voice_tasks = Vec::new();
        for (task, effects) in &mut snapshot.active_task_effects {
            let had_voice = effects
                .iter()
                .any(|effect| matches!(effect, StoryEffect::PlayVoice { .. }));
            effects.retain(|effect| !matches!(effect, StoryEffect::PlayVoice { .. }));
            if had_voice && effects.is_empty() {
                completed_voice_tasks.push(*task);
            }
        }
        snapshot
            .active_task_effects
            .retain(|_, effects| !effects.is_empty());
        let pending = snapshot
            .active_task_effects
            .iter()
            .flat_map(|(task, effects)| {
                effects.iter().map(|effect| StoryRuntimeEvent::TaskEffect {
                    task: *task,
                    effect: effect.clone(),
                })
            })
            .collect();
        let mut runtime = Self {
            execution: ExecutionRuntime::restore(bytecode, snapshot.execution)?,
            host: StoryNativeHost::restore(snapshot.host),
            pending,
            active_task_effects: snapshot.active_task_effects,
            deferred_task_completions: snapshot.deferred_task_completions,
            waiting_task: snapshot.waiting_task,
            waiting_interactive_task: snapshot.waiting_interactive_task,
            choice: snapshot.choice,
            blocked: snapshot.blocked,
            blocked_wait: snapshot.blocked_wait,
        };
        for task in completed_voice_tasks {
            runtime.finish_task_effects(task)?;
        }
        Ok(runtime)
    }

    pub fn set_globals(&mut self, globals: std::collections::BTreeMap<String, Value>) {
        self.execution.set_globals(globals);
    }

    pub fn globals(&self) -> &std::collections::BTreeMap<String, Value> {
        self.execution.globals()
    }

    pub(crate) fn enqueue_event(&mut self, event: StoryRuntimeEvent) {
        self.pending.push_back(event);
    }

    /// Reconstructs the host-visible boundary represented by a restored VM.
    /// The engine must not infer every blocked state as dialogue input: a
    /// waiting choice needs its prompt and options mounted again.
    pub fn restored_boundary_event(&self) -> Option<StoryRuntimeEvent> {
        if !self.blocked {
            return None;
        }
        match &self.choice {
            Some(ChoiceState::AwaitingSelection { prompt, options }) => {
                Some(StoryRuntimeEvent::Choice {
                    prompt: prompt.clone(),
                    options: options.iter().map(|option| option.label.clone()).collect(),
                })
            }
            _ => Some(StoryRuntimeEvent::Wait(
                self.blocked_wait
                    .clone()
                    .unwrap_or(StoryWait::DialogueAdvance),
            )),
        }
    }

    pub fn resume(&mut self, value: Value) -> Result<(), StoryRuntimeError> {
        if !self.blocked {
            return Err(StoryRuntimeError::NotBlocked);
        }
        if let Some(ChoiceState::AwaitingSelection { options, .. }) = &self.choice {
            let Value::Number(selected) = value else {
                return Err(StoryRuntimeError::InvalidChoice);
            };
            let selected = selected as usize;
            let closure = options
                .get(selected)
                .ok_or(StoryRuntimeError::InvalidChoice)?
                .body
                .clone();
            let task = self.execution.spawn(&closure, ExecutionMode::Interactive)?;
            self.choice = Some(ChoiceState::RunningBranch { task, selected });
            self.blocked = false;
            self.blocked_wait = None;
            return Ok(());
        }
        if let Some(task) = self.waiting_interactive_task.take() {
            self.blocked = false;
            self.blocked_wait = None;
            self.execution.unpause(task)?;
            return Ok(());
        }
        self.blocked = false;
        self.blocked_wait = None;
        if self.execution.is_waiting_for_host(ExecutionId::MAIN) {
            self.execution.resume(ExecutionId::MAIN, value)?;
        }
        Ok(())
    }

    /// Returns whether the story currently owns a host-side wait boundary.
    ///
    /// ECS completions can arrive after navigation or state restoration has
    /// invalidated their request. Callers must use this boundary state to
    /// discard such late completions instead of treating them as VM failures.
    pub fn is_waiting_for_host_response(&self) -> bool {
        self.blocked
    }

    pub fn resume_task(&mut self, task: ExecutionId) -> Result<(), StoryRuntimeError> {
        let effects = self
            .active_task_effects
            .get_mut(&task)
            .ok_or(StoryRuntimeError::UnknownTaskEffect(task))?;
        effects
            .pop()
            .ok_or(StoryRuntimeError::UnknownTaskEffect(task))?;
        if effects.is_empty() {
            self.active_task_effects.remove(&task);
            self.finish_task_effects(task)?;
        }
        Ok(())
    }

    fn finish_task_effects(&mut self, task: ExecutionId) -> Result<(), StoryRuntimeError> {
        if self.execution.mode(task) == Some(ExecutionMode::Sequence) {
            let _ = self.execution.unpause(task);
        }
        if let Some(value) = self.deferred_task_completions.remove(&task) {
            if self.waiting_task == Some(task) {
                self.waiting_task = None;
                self.execution.resume(ExecutionId::MAIN, value)?;
            }
        }
        Ok(())
    }

    pub fn step(&mut self) -> Result<Option<StoryRuntimeEvent>, StoryRuntimeError> {
        if let Some(event) = self.pending.pop_front() {
            self.mark_host_boundary(&event);
            return Ok(Some(event));
        }
        if self.blocked {
            loop {
                let Some(event) = self.execution.step_children()? else {
                    return Ok(None);
                };
                if let Some(event) = self.handle_task_event(event)? {
                    return Ok(Some(event));
                }
            }
        }
        loop {
            let Some(event) = self.execution.step()? else {
                return Ok(None);
            };
            match event {
                ExecutionEvent::Call { execution, call } if execution.is_main() => {
                    match self.host.call(&call)? {
                        StoryCallOutcome::Return(value) => {
                            self.execution.resume(ExecutionId::MAIN, value)?
                        }
                        StoryCallOutcome::Control(StoryControl::SpawnTask { kind, closure }) => {
                            let mode = match kind {
                                StoryTaskKind::Sequence => ExecutionMode::Sequence,
                                StoryTaskKind::Parallel => ExecutionMode::Parallel,
                            };
                            let task = self.execution.spawn(&closure, mode)?;
                            self.execution
                                .resume(ExecutionId::MAIN, Value::Task(task.task_handle()))?;
                        }
                        StoryCallOutcome::Control(StoryControl::BeginChoice {
                            prompt,
                            closure,
                        }) => {
                            let builder_task =
                                self.execution.spawn(&closure, ExecutionMode::Interactive)?;
                            self.choice = Some(ChoiceState::Collecting {
                                builder_task,
                                prompt,
                                options: Vec::new(),
                            });
                        }
                        StoryCallOutcome::Control(StoryControl::OpenUi { path, arguments }) => {
                            self.blocked = true;
                            return Ok(Some(StoryRuntimeEvent::OpenUi { path, arguments }));
                        }
                        StoryCallOutcome::Control(StoryControl::WaitTask { task }) => {
                            self.waiting_task = Some(ExecutionId::from_task_handle(task));
                        }
                        StoryCallOutcome::Control(
                            control @ StoryControl::AddChoiceOption { .. },
                        ) => {
                            return Err(StoryRuntimeError::UnexpectedMainControl(control));
                        }
                    }
                }
                ExecutionEvent::Statement { execution, value } if execution.is_main() => {
                    let statement = value;
                    self.host.handle_statement(&statement)?;
                    self.enqueue_host_boundaries();
                    if let Some(event) = self.pending.pop_front() {
                        self.mark_host_boundary(&event);
                        return Ok(Some(event));
                    }
                }
                event @ (ExecutionEvent::Call { .. }
                | ExecutionEvent::Statement { .. }
                | ExecutionEvent::Completed { .. })
                    if !event.execution().is_main() =>
                {
                    if let Some(event) = self.handle_task_event(event)? {
                        self.mark_host_boundary(&event);
                        return Ok(Some(event));
                    }
                }
                ExecutionEvent::Completed { execution, value } if execution.is_main() => {
                    return Ok(Some(StoryRuntimeEvent::Completed(value)));
                }
                _ => unreachable!("execution event guard must classify main or child execution"),
            }
        }
    }

    fn mark_host_boundary(&mut self, event: &StoryRuntimeEvent) {
        if matches!(
            event,
            StoryRuntimeEvent::Wait(_)
                | StoryRuntimeEvent::OpenUi { .. }
                | StoryRuntimeEvent::Choice { .. }
        ) {
            self.blocked = true;
        }
        if let StoryRuntimeEvent::Wait(wait) = event {
            self.blocked_wait = Some(wait.clone());
        }
    }

    fn enqueue_host_boundaries(&mut self) {
        self.pending.extend(
            self.host
                .drain_effects()
                .into_iter()
                .map(StoryRuntimeEvent::Effect),
        );
        if let Some(wait) = self.host.take_wait() {
            self.pending.push_back(StoryRuntimeEvent::Wait(wait));
        }
    }

    fn handle_task_event(
        &mut self,
        event: ExecutionEvent,
    ) -> Result<Option<StoryRuntimeEvent>, StoryRuntimeError> {
        match event {
            ExecutionEvent::Call {
                execution: task,
                call,
            } => match self.host.call(&call)? {
                StoryCallOutcome::Return(value) => {
                    self.execution.resume(task, value)?;
                }
                StoryCallOutcome::Control(StoryControl::AddChoiceOption { label, closure }) => {
                    let Some(ChoiceState::Collecting { options, .. }) = &mut self.choice else {
                        return Err(StoryRuntimeError::InvalidChoice);
                    };
                    options.push(ChoiceOption {
                        label,
                        body: closure,
                    });
                    self.execution.resume(task, Value::Unit)?;
                }
                StoryCallOutcome::Control(control) => {
                    return Err(StoryRuntimeError::UnsupportedTaskControl(control));
                }
            },
            ExecutionEvent::Statement {
                execution: task,
                value,
            } => {
                self.host.handle_statement(&value)?;
                self.enqueue_task_boundaries(task)?;
                return Ok(self.pending.pop_front());
            }
            ExecutionEvent::Completed {
                execution: task,
                value,
            } => {
                if self.active_task_effects.contains_key(&task) {
                    self.deferred_task_completions.insert(task, value);
                    return Ok(None);
                }
                if let Some(ChoiceState::Collecting {
                    builder_task,
                    prompt,
                    options,
                }) = &self.choice
                    && *builder_task == task
                {
                    let prompt = prompt.clone();
                    let options = options.clone();
                    let labels = options.iter().map(|option| option.label.clone()).collect();
                    self.choice = Some(ChoiceState::AwaitingSelection {
                        prompt: prompt.clone(),
                        options,
                    });
                    self.blocked = true;
                    return Ok(Some(StoryRuntimeEvent::Choice {
                        prompt,
                        options: labels,
                    }));
                }
                if let Some(ChoiceState::RunningBranch {
                    task: branch,
                    selected,
                }) = self.choice
                    && branch == task
                {
                    self.choice = None;
                    self.execution
                        .resume(ExecutionId::MAIN, Value::Number(selected as f64))?;
                    return Ok(None);
                }
                if self.waiting_task == Some(task) {
                    self.waiting_task = None;
                    self.execution.resume(ExecutionId::MAIN, value)?;
                }
            }
        }
        Ok(None)
    }

    fn enqueue_task_boundaries(&mut self, task: ExecutionId) -> Result<(), StoryRuntimeError> {
        for effect in self.host.drain_effects() {
            if matches!(effect, StoryEffect::PlayVoice { .. }) {
                self.active_task_effects
                    .entry(task)
                    .or_default()
                    .push(effect.clone());
                self.pending
                    .push_back(StoryRuntimeEvent::TaskEffect { task, effect });
            } else {
                self.pending.push_back(StoryRuntimeEvent::Effect(effect));
            }
        }
        let wait = self.host.take_wait();
        let task_mode = self.execution.mode(task);
        if matches!(wait, Some(StoryWait::Movie { .. }))
            && task_mode != Some(ExecutionMode::Interactive)
        {
            return Err(StoryRuntimeError::UnsupportedTaskWait(
                wait.expect("the movie wait was matched"),
            ));
        }
        let has_wait = wait.is_some();
        if let Some(wait) = wait
            && task_mode == Some(ExecutionMode::Interactive)
        {
            self.execution.pause(task)?;
            self.waiting_interactive_task = Some(task);
            self.pending.push_back(StoryRuntimeEvent::Wait(wait));
        }
        if task_mode == Some(ExecutionMode::Sequence)
            && has_wait
            && self.active_task_effects.contains_key(&task)
        {
            self.execution.pause(task)?;
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
pub enum StoryRuntimeError {
    #[error(transparent)]
    Bytecode(#[from] ExecutionRuntimeError),
    #[error(transparent)]
    Capability(#[from] CharacterCapabilityError),
    #[error("choice requires a string prompt and a list of string options")]
    InvalidChoice,
    #[error("story control {0:?} cannot be issued by the main program")]
    UnexpectedMainControl(StoryControl),
    #[error("story control {0:?} is not supported inside a task closure")]
    UnsupportedTaskControl(StoryControl),
    #[error(
        "story wait {0:?} is not supported inside seq/par; call it from the main story or an interactive choice branch"
    )]
    UnsupportedTaskWait(StoryWait),
    #[error("story runtime is not waiting for a host response")]
    NotBlocked,
    #[error("story runtime snapshot requires an empty effect queue")]
    NotAtSnapshotBoundary,
    #[error("task {0} has no pending host effect")]
    UnknownTaskEffect(ExecutionId),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::script::capabilities::{
        StoryEffect, StoryNativeHost, compile_story_bytecode, story_manifest,
    };
    use hiraku_script::StatementValue;

    #[test]
    fn whole_program_runtime_yields_native_calls_without_ir() {
        let bytecode = compile_story_bytecode("test.story.hks", "log(\"hello\")")
            .expect("whole HKS story must compile");
        let mut runtime = ExecutionRuntime::new(bytecode).expect("script runtime must initialize");
        let Some(ExecutionEvent::Call { execution, call }) =
            runtime.step().expect("runtime must advance")
        else {
            panic!("expected a native call")
        };
        assert_eq!(execution, ExecutionId::MAIN);
        assert_eq!(
            call.builtin,
            story_manifest().resolve("log").expect("log registration")
        );
        runtime
            .resume(ExecutionId::MAIN, Value::Unit)
            .expect("host result must resume the main VM");
    }

    #[test]
    fn child_closures_use_the_same_execution_event_protocol() {
        let bytecode = compile_story_bytecode("execution.hks", "par { log(\"child\") }")
            .expect("task story must compile");
        let mut runtime = ExecutionRuntime::new(bytecode).expect("runtime must initialize");
        let mut host = StoryNativeHost::new();
        let Some(ExecutionEvent::Call {
            execution: ExecutionId::MAIN,
            call,
        }) = runtime.step().expect("root execution must advance")
        else {
            panic!("expected the root par call")
        };
        let StoryCallOutcome::Control(StoryControl::SpawnTask { kind, closure }) =
            host.call(&call).expect("par must create a child execution")
        else {
            panic!("expected a task spawn control")
        };
        assert_eq!(kind, StoryTaskKind::Parallel);
        let child = runtime
            .spawn(&closure, ExecutionMode::Parallel)
            .expect("child execution must spawn");
        runtime
            .resume(ExecutionId::MAIN, Value::Task(child.task_handle()))
            .expect("task handle must resume the root execution");

        let Some(ExecutionEvent::Call { execution, .. }) = runtime
            .step_children()
            .expect("child execution must advance")
        else {
            panic!("expected the child log call")
        };
        assert_eq!(execution, child);
        assert!(!execution.is_main());
    }

    #[test]
    fn ui_roles_are_engine_effects_and_ui_open_is_a_selector_call() {
        let bytecode = compile_story_bytecode(
            "ui_roles.hks",
            concat!(
                "ui.set(\"dialogue\", \"ui/dialogue.ui.hks\")\n",
                "ui.mount(\"clock\", \"ui/clock.ui.hks\")\n",
                "ui.unmount(\"clock\")\n",
                "ui.open(\"dialogue\", \"Alice\", 3)",
            ),
        )
        .expect("UI role APIs must compile");
        let mut runtime = StoryRuntime::new(bytecode).expect("story runtime must initialize");
        assert_eq!(
            runtime.step().expect("ui.set must run"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::SetUiRole {
                role: "dialogue".to_string(),
                component: "ui/dialogue.ui.hks".to_string(),
            }))
        );
        assert_eq!(
            runtime.step().expect("ui.mount must run"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::MountUiOverlay {
                name: "clock".to_string(),
                component: "ui/clock.ui.hks".to_string(),
            }))
        );
        assert_eq!(
            runtime.step().expect("ui.unmount must run"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::UnmountUiOverlay {
                name: "clock".to_string(),
            }))
        );
        assert_eq!(
            runtime.step().expect("ui.open must run"),
            Some(StoryRuntimeEvent::OpenUi {
                path: "dialogue".to_string(),
                arguments: vec![Value::String("Alice".to_string()), Value::Number(3.0)],
            })
        );
    }

    #[test]
    fn whole_program_runtime_restores_at_a_host_boundary() {
        let bytecode = compile_story_bytecode("restore.story.hks", "log(\"before\")\n\"after\"")
            .expect("whole HKS story must compile");
        let mut runtime = ExecutionRuntime::new(bytecode.clone()).expect("runtime must initialize");
        assert!(matches!(
            runtime.step().expect("runtime must advance"),
            Some(ExecutionEvent::Call { .. })
        ));
        let snapshot = runtime.snapshot();
        let mut restored =
            ExecutionRuntime::restore(bytecode, snapshot).expect("snapshot must restore");
        restored
            .resume(ExecutionId::MAIN, Value::Unit)
            .expect("restored host call must resume");
        assert!(matches!(
            restored.step().expect("runtime must reach statement"),
            Some(ExecutionEvent::Statement {
                value: StatementValue::Commit,
                ..
            })
        ));
        assert!(matches!(
            restored.step().expect("runtime must reach string hook"),
            Some(ExecutionEvent::Statement {
                value: StatementValue::String(text),
                ..
            }) if text == "after"
        ));
    }

    #[test]
    fn whole_program_runtime_evaluates_dialogue_templates_from_globals() {
        let bytecode = compile_story_bytecode(
            "template.story.hks",
            "global player = .{ name: \"alice\" }\n\"Hi, ${player.name}\"",
        )
        .expect("template story must compile");
        let mut runtime = ExecutionRuntime::new(bytecode).expect("runtime must initialize");
        assert!(matches!(
            runtime.step().expect("global declaration must run"),
            Some(ExecutionEvent::Statement {
                value: StatementValue::Commit,
                ..
            })
        ));
        assert!(matches!(
            runtime.step().expect("dialogue statement must run"),
            Some(ExecutionEvent::Statement {
                value: StatementValue::String(text),
                ..
            }) if text == "Hi, alice"
        ));
    }

    #[test]
    fn direct_runtime_dispatches_native_calls_at_statement_boundaries() {
        let bytecode =
            compile_story_bytecode("test.story.hks", r#"char("alice").e("happy").at(.right)"#)
                .expect("character story must compile");
        let mut runtime = ExecutionRuntime::new(bytecode).expect("script runtime must initialize");
        let mut host = StoryNativeHost::new();

        loop {
            match runtime.step().expect("runtime must advance") {
                Some(ExecutionEvent::Call { call, .. }) => {
                    let value = host
                        .call(&call)
                        .expect("native call must succeed")
                        .into_return_value()
                        .expect("ordinary native call must return a value");
                    runtime
                        .resume(ExecutionId::MAIN, value)
                        .expect("native result must resume the VM");
                }
                Some(ExecutionEvent::Statement {
                    value: StatementValue::Commit,
                    ..
                }) => {
                    host.commit_statement()
                        .expect("statement commit must flush actor state");
                }
                Some(ExecutionEvent::Statement { value, .. }) => {
                    panic!("unexpected statement boundary: {value:?}")
                }
                Some(ExecutionEvent::Completed { .. }) => break,
                None => panic!("runtime stopped before completion"),
            }
        }

        assert!(matches!(
            host.drain_effects().as_slice(),
            [StoryEffect::ShowCharacter {
                actor_id,
                expressions,
                position,
                ..
            }] if actor_id == "alice" && expressions == &["happy"] && position == &[600.0, -200.0]
        ));
    }

    #[test]
    fn fluent_bgm_and_actor_focus_commit_as_typed_effects() {
        let bytecode = compile_story_bytecode(
            "fluent.story.hks",
            r#"
                bgm("music/theme").volume(0.75).fadeIn(600)
                char("alice").focus()
                char("bob").focus(false)
                camera().blur(2)
                camera(.canvas)
                    .offset(10, 20, 30)
                    .rotation(1, 2, 3)
                    .zoom(1.25)
                    .projection(.perspective)
                    .time(0.5)
                    .easing(.easeOut)
            "#,
        )
        .expect("fluent engine APIs must compile");
        let mut runtime = ExecutionRuntime::new(bytecode).expect("script runtime must initialize");
        let mut host = StoryNativeHost::new();

        loop {
            match runtime.step().expect("runtime must advance") {
                Some(ExecutionEvent::Call { call, .. }) => {
                    let value = host
                        .call(&call)
                        .expect("native call must succeed")
                        .into_return_value()
                        .expect("ordinary native call must return a value");
                    runtime
                        .resume(ExecutionId::MAIN, value)
                        .expect("native result must resume the VM");
                }
                Some(ExecutionEvent::Statement { value, .. }) => host
                    .handle_statement(&value)
                    .expect("statement commit must succeed"),
                Some(ExecutionEvent::Completed { .. }) => break,
                None => panic!("runtime stopped before completion"),
            }
        }

        let effects = host.drain_effects();
        assert!(effects.iter().any(|effect| matches!(
            effect,
            StoryEffect::PlayBgm { path, volume, fade_in_ms: Some(600) }
                if path == "music/theme" && (*volume - 0.75).abs() < f32::EPSILON
        )));
        assert!(effects.iter().any(|effect| matches!(
            effect,
            StoryEffect::ShowCharacter { actor_id, focused: true, .. } if actor_id == "alice"
        )));
        assert!(effects.iter().any(|effect| matches!(
            effect,
            StoryEffect::ShowCharacter { actor_id, focused: false, .. } if actor_id == "bob"
        )));
        assert!(effects.iter().any(|effect| matches!(
            effect,
            StoryEffect::SetCamera {
                blur: Some(blur),
                scope: crate::script::CameraEffectScope::World,
                ..
            } if (*blur - 2.0).abs() < f32::EPSILON
        )));
        assert!(effects.iter().any(|effect| matches!(
            effect,
            StoryEffect::SetCamera {
                zoom: Some(zoom),
                offset: Some([10.0, 20.0, 30.0]),
                rotation: Some([1.0, 2.0, 3.0]),
                projection: Some(crate::script::CameraProjectionMode::Perspective),
                duration_ms: 500,
                ease,
                scope: crate::script::CameraEffectScope::Canvas,
                ..
            } if (*zoom - 1.25).abs() < f32::EPSILON && ease == "easeOut"
        )));
    }

    #[test]
    fn story_driver_does_not_prefetch_past_dialogue_waits() {
        let bytecode = compile_story_bytecode(
            "driver.story.hks",
            r#"
                global player = .{ name: "alice" }
                "Hi, ${player.name}"
                "after"
            "#,
        )
        .expect("driver story must compile");
        let mut runtime = StoryRuntime::new(bytecode).expect("story driver must initialize");
        assert!(matches!(
            runtime.step().expect("first effect must run"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { ref text, .. }))
                if text == "Hi, alice"
        ));
        assert_eq!(
            runtime
                .step()
                .expect("dialogue wait must follow the effect"),
            Some(StoryRuntimeEvent::Wait(StoryWait::DialogueAdvance))
        );
        assert_eq!(
            runtime.step().expect("blocked runtime must stay idle"),
            None
        );
        runtime
            .resume(Value::Unit)
            .expect("dialogue wait must resume");
        assert!(matches!(
            runtime.step().expect("second effect must run after resume"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { ref text, .. }))
                if text == "after"
        ));
    }

    #[test]
    fn choice_blocks_suspend_and_resume_into_the_selected_branch() {
        let bytecode = compile_story_bytecode(
            "choice.story.hks",
            r#"
                choice("Select") {
                    option("Route A") { "selected A" }
                    option("Route B") { "selected B" }
                }
                "after choice"
            "#,
        )
        .expect("choice story must compile");
        let mut runtime = StoryRuntime::new(bytecode).expect("story driver must initialize");
        assert_eq!(
            runtime.step().expect("choice must suspend"),
            Some(StoryRuntimeEvent::Choice {
                prompt: "Select".into(),
                options: vec!["Route A".into(), "Route B".into()],
            })
        );
        assert_eq!(runtime.step().expect("choice remains blocked"), None);
        runtime
            .resume(Value::Number(1.0))
            .expect("choice response resumes the VM");
        assert!(matches!(
            runtime.step().expect("selected branch runs"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { ref text, .. }))
                if text == "selected B"
        ));
        assert_eq!(
            runtime.step().expect("selected branch must wait for input"),
            Some(StoryRuntimeEvent::Wait(StoryWait::DialogueAdvance))
        );
        runtime
            .resume(Value::Unit)
            .expect("branch dialogue must resume independently of the main VM");
        assert!(matches!(
            runtime.step().expect("main story continues after the branch"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { ref text, .. }))
                if text == "after choice"
        ));
    }

    #[test]
    fn movie_wait_inside_a_choice_branch_resumes_that_branch() {
        let bytecode = compile_story_bytecode(
            "choice-movie.story.hks",
            r#"
                choice {
                    option("Play movie") {
                        movie("opening")
                        "after movie"
                    }
                }
                "after choice"
            "#,
        )
        .expect("choice movie story must compile");
        let mut runtime = StoryRuntime::new(bytecode).expect("story driver must initialize");
        assert!(matches!(
            runtime.step().expect("choice must suspend"),
            Some(StoryRuntimeEvent::Choice { .. })
        ));
        runtime
            .resume(Value::Number(0.0))
            .expect("choice response must start the selected branch");
        assert_eq!(
            runtime.step().expect("movie must suspend its branch"),
            Some(StoryRuntimeEvent::Wait(StoryWait::Movie {
                path: "opening".into(),
            }))
        );
        assert!(runtime.is_waiting_for_host_response());
        runtime
            .resume(Value::Unit)
            .expect("movie completion must resume the selected branch");
        assert!(matches!(
            runtime.step().expect("branch dialogue must run after movie"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { ref text, .. }))
                if text == "after movie"
        ));
        assert_eq!(
            runtime.step().expect("branch dialogue must await input"),
            Some(StoryRuntimeEvent::Wait(StoryWait::DialogueAdvance))
        );
    }

    #[test]
    fn choice_selection_and_captured_branch_survive_snapshot_restore() {
        let bytecode = compile_story_bytecode(
            "choice-save.story.hks",
            r#"
                let greeting = "restored"
                choice {
                    option("Route A") { "ignored" }
                    option("Route B") { "${greeting}" }
                }
            "#,
        )
        .expect("choice story must compile");
        let mut runtime = StoryRuntime::new(bytecode.clone()).expect("runtime must initialize");
        let event = runtime.step().expect("choice must suspend");
        assert!(
            matches!(
                event,
                Some(StoryRuntimeEvent::Choice { ref options, .. })
                    if options == &["Route A", "Route B"]
            ),
            "unexpected choice event: {event:?}"
        );

        let snapshot = runtime.snapshot().expect("waiting choice must be saveable");
        let mut restored = StoryRuntime::restore(bytecode, snapshot).expect("choice must restore");
        assert_eq!(
            restored.restored_boundary_event(),
            Some(StoryRuntimeEvent::Choice {
                prompt: String::new(),
                options: vec!["Route A".into(), "Route B".into()],
            })
        );
        restored
            .resume(Value::Number(1.0))
            .expect("restored selection must start its branch");
        assert!(matches!(
            restored.step().expect("captured branch must run"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { ref text, .. }))
                if text == "restored"
        ));
    }

    #[test]
    fn a_blocked_movie_wait_survives_snapshot_restore() {
        let bytecode = compile_story_bytecode(
            "movie-save.hks",
            "movie(\"movies/opening.mkv\")\n\"after movie\"",
        )
        .expect("movie story must compile");
        let mut runtime = StoryRuntime::new(bytecode.clone()).expect("runtime must initialize");
        assert_eq!(
            runtime.step().expect("movie must suspend"),
            Some(StoryRuntimeEvent::Wait(StoryWait::Movie {
                path: "movies/opening.mkv".into(),
            }))
        );
        let snapshot = runtime.snapshot().expect("movie wait must be saveable");
        let restored = StoryRuntime::restore(bytecode, snapshot).expect("movie wait must restore");
        assert_eq!(
            restored.restored_boundary_event(),
            Some(StoryRuntimeEvent::Wait(StoryWait::Movie {
                path: "movies/opening.mkv".into(),
            }))
        );
    }

    #[test]
    fn parallel_tasks_continue_while_the_main_story_waits_for_input() {
        let bytecode = compile_story_bytecode(
            "parallel.story.hks",
            r#"
                par {
                    voice("voice/first")
                    voice("voice/second")
                }
                "dialogue"
            "#,
        )
        .expect("parallel story must compile");
        let mut runtime = StoryRuntime::new(bytecode).expect("story driver must initialize");
        assert!(matches!(
            runtime.step().expect("dialogue effect must run"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { .. }))
        ));
        assert_eq!(
            runtime.step().expect("dialogue must block the main VM"),
            Some(StoryRuntimeEvent::Wait(StoryWait::DialogueAdvance))
        );
        let task = match runtime.step().expect("parallel voice must keep advancing") {
            Some(StoryRuntimeEvent::TaskEffect {
                task,
                effect: StoryEffect::PlayVoice { ref path, .. },
            }) if path == "voice/first" => task,
            event => panic!("unexpected task event: {event:?}"),
        };
        assert!(matches!(
            runtime.step().expect("second parallel voice must start without waiting"),
            Some(StoryRuntimeEvent::TaskEffect {
                task: second_task,
                effect: StoryEffect::PlayVoice { ref path, .. },
            }) if second_task == task && path == "voice/second"
        ));
        runtime
            .resume_task(task)
            .expect("one parallel audio completion must be recorded");
        runtime
            .resume_task(task)
            .expect("the other parallel audio completion must be recorded");
        assert_eq!(
            runtime.step().expect("finished task must become idle"),
            None
        );
    }

    #[test]
    fn sequence_voice_waits_for_each_host_completion() {
        let bytecode = compile_story_bytecode(
            "sequence.story.hks",
            r#"
                seq {
                    voice("voice/first")
                    "first line"
                    voice("voice/second")
                    "second line"
                }
                "dialogue"
            "#,
        )
        .expect("sequence story must compile");
        let mut runtime = StoryRuntime::new(bytecode).expect("story driver must initialize");
        assert!(matches!(
            runtime.step().expect("dialogue effect must run"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { .. }))
        ));
        assert!(matches!(
            runtime.step().expect("dialogue must block"),
            Some(StoryRuntimeEvent::Wait(_))
        ));
        let first = match runtime.step().expect("first voice must start") {
            Some(StoryRuntimeEvent::TaskEffect {
                task,
                effect: StoryEffect::PlayVoice { ref path, .. },
            }) if path == "voice/first" => task,
            event => panic!("unexpected first sequence event: {event:?}"),
        };
        assert!(matches!(
            runtime.step().expect("the first line must be displayed immediately"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { ref text, .. })) if text == "first line"
        ));
        assert_eq!(
            runtime.step().expect("sequence must remain suspended"),
            None
        );
        runtime
            .resume_task(first)
            .expect("first audio completion must resume the task");
        assert!(matches!(
            runtime.step().expect("second voice must follow completion"),
            Some(StoryRuntimeEvent::TaskEffect {
                effect: StoryEffect::PlayVoice { ref path, .. },
                ..
            }) if path == "voice/second"
        ));
    }

    #[test]
    fn wait_handle_resumes_the_main_vm_after_task_completion() {
        let bytecode = compile_story_bytecode(
            "wait.story.hks",
            r#"
                let voices = seq {
                    voice("voice/first")
                    voice("voice/second")
                }
                wait(voices)
                "after voices"
            "#,
        )
        .expect("wait story must compile");
        let mut runtime = StoryRuntime::new(bytecode).expect("story driver must initialize");
        for expected in ["voice/first", "voice/second"] {
            let task = match runtime.step().expect("voice task must advance") {
                Some(StoryRuntimeEvent::TaskEffect {
                    task,
                    effect: StoryEffect::PlayVoice { ref path, .. },
                }) if path == expected => task,
                event => panic!("unexpected wait task event: {event:?}"),
            };
            runtime
                .resume_task(task)
                .expect("audio completion must resume sequence");
        }
        assert!(matches!(
            runtime.step().expect("main VM must resume after the task"),
            Some(StoryRuntimeEvent::Effect(StoryEffect::Say { ref text, .. }))
                if text == "after voices"
        ));
    }

    #[test]
    fn snapshot_completes_an_in_flight_voice_without_replaying_it() {
        let bytecode = compile_story_bytecode(
            "task-save.story.hks",
            r#"
                let voiceTask = seq { voice("voice/saved") }
                wait(voiceTask)
            "#,
        )
        .expect("task save story must compile");
        let mut runtime = StoryRuntime::new(bytecode.clone()).expect("runtime must initialize");
        assert!(matches!(
            runtime.step().expect("voice effect must start"),
            Some(StoryRuntimeEvent::TaskEffect { .. })
        ));
        let snapshot = runtime
            .snapshot()
            .expect("an externally waiting task must be saveable");
        let mut restored =
            StoryRuntime::restore(bytecode, snapshot).expect("snapshot must restore");
        loop {
            match restored.step().expect("restored story must continue") {
                Some(StoryRuntimeEvent::TaskEffect {
                    effect: StoryEffect::PlayVoice { .. },
                    ..
                }) => panic!("loading must not replay an in-flight voice"),
                Some(StoryRuntimeEvent::Completed(_)) => break,
                Some(_) => {}
                None => panic!("restored story stopped before completing"),
            }
        }
    }

    #[test]
    fn representative_inline_stories_compile_as_whole_programs() {
        for (path, source) in [
            ("<bootstrap>", r#"story.goto("chapter.hks")"#),
            (
                "<dialogue>",
                r#"
                    let alice = char("alice")
                    alice.at(.center).scale(0.5).e("happy")
                    alice: "Hello"
                    ...: " again"
                    "Narration"
                "#,
            ),
            (
                "<control-flow>",
                r#"
                    let count = 0
                    while count < 2 {
                        "Iteration ${count}"
                        count += 1
                    }
                    if count == 2 { log("done") }
                "#,
            ),
            (
                "<tasks>",
                r#"
                    let voices = par {
                        voice("voice/alice/first")
                        voice("voice/bob/second")
                    }
                    wait(voices)
                "#,
            ),
        ] {
            compile_story_bytecode(path, source).unwrap_or_else(|error| {
                panic!("`{path}` failed whole-program compilation: {error}")
            });
        }
    }
}