brink-runtime 0.0.9

Runtime/VM for executing compiled ink stories
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
//! Integration tests for [`StorySession`]: the journaling, replayable session
//! wrapper (#370 + #371 snapshots).
//!
//! Programs are built from the known-good `.ink.json` converter reference
//! pipeline. Every stepping loop is bounded — VM tests must not hang.

#![expect(
    clippy::unwrap_used,
    clippy::panic,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::default_trait_access,
    clippy::items_after_statements,
    reason = "test harness"
)]

use std::path::Path;

use brink_converter::convert;
use brink_format::{ListValue, SaveState, Value};
use brink_json::InkJson;
use brink_runtime::{
    DotNetRng, EventKind, ExternalFnHandler, ExternalReplayMode, ExternalResult, FailReason, Line,
    Program, ReplayOutcome, ReplayWarning, SESSION_JOURNAL_CAP, SessionError, SessionJournal,
    StepOutcome, Story, StorySession, diff,
};

/// Link a program from a tier `.ink.json` fixture path (relative to the repo).
fn link_fixture(rel: &str) -> (Program, Vec<Vec<brink_format::LineEntry>>) {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(rel);
    let json =
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
    let ink: InkJson = serde_json::from_str(&json).unwrap();
    let data = convert(&ink).unwrap();
    brink_runtime::link(&data).unwrap()
}

const CHOICE_STORY: &str = "tests/tier1/choices/I084-sticky-choices-stay-sticky/story.ink.json";
const LIST_STORY: &str = "tests/tier2/lists/I067-list-save-load/story.ink.json";
const EXTERNAL_STORY: &str = "tests/tier3/runtime/external-function-1-arg-v1/story.ink.json";
const FUNCTION_STORY: &str = "tests/tier2/function/func-none/story.ink.json";

/// Bounded run of a session to its first choice set (or terminal). Returns the
/// collected text.
fn run_to_pause(session: &mut StorySession<'_, DotNetRng>) -> Vec<Line> {
    session.continue_to_pause().unwrap()
}

// ── Journal round-trip (serde, tagged values incl. a List) ───────────────────

#[test]
fn journal_roundtrips_with_tagged_list_value() {
    let mut journal = SessionJournal::new(0xDEAD_BEEF, Some(42));
    let list = Value::List(
        ListValue {
            items: vec![brink_format::DefinitionId::new(
                brink_format::DefinitionTag::ListItem,
                7,
            )],
            origins: vec![],
        }
        .into(),
    );
    journal
        .events
        .push(brink_runtime::JournalEvent::new(EventKind::External {
            name: "get_flag".to_owned(),
            args: vec![Value::Int(3)],
            result: list.clone(),
        }));
    journal
        .events
        .push(brink_runtime::JournalEvent::new(EventKind::Choice {
            index: 1,
            label: Some("Choose me".to_owned()),
        }));

    let json = serde_json::to_string(&journal).unwrap();
    // The List variant must survive as a tagged value (not null).
    assert!(
        json.contains("List"),
        "list value must serialize tagged: {json}"
    );
    let back: SessionJournal = serde_json::from_str(&json).unwrap();
    assert_eq!(back, journal);
    // The list result round-trips exactly (no lossy null-ing).
    if let EventKind::External { result, .. } = &back.events[0].kind {
        assert_eq!(result, &list);
    } else {
        panic!("expected External event");
    }
}

/// `ReplayOutcome`/`FailReason` must actually be JSON-serializable (#387: the
/// wasm binding round-trips them through `serde_json::to_string` verbatim).
/// serde's internally-tagged representation can't serialize a newtype variant
/// wrapping a non-map payload (a bare `String`) — this pins `FailReason::RuntimeError`
/// as a struct variant (`{ message: String }`) so that regression can't return.
#[test]
fn replay_outcome_and_fail_reason_are_json_serializable() {
    let replayed = ReplayOutcome::Replayed {
        warnings: vec![ReplayWarning::ChoiceLabelDrift {
            at_event: 0,
            index: 1,
            recorded: "old".to_owned(),
            found: "new".to_owned(),
        }],
    };
    let json = serde_json::to_string(&replayed).unwrap();
    assert!(json.contains("\"type\":\"replayed\""), "{json}");
    assert!(json.contains("\"type\":\"choice_label_drift\""), "{json}");

    let budget = ReplayOutcome::Failed {
        at_event: 3,
        reason: FailReason::Budget,
    };
    let json = serde_json::to_string(&budget).unwrap();
    assert!(json.contains("\"type\":\"failed\""), "{json}");
    assert!(json.contains("\"type\":\"budget\""), "{json}");

    let runtime_err = ReplayOutcome::Failed {
        at_event: 5,
        reason: FailReason::RuntimeError {
            message: "boom".to_owned(),
        },
    };
    let json = serde_json::to_string(&runtime_err).unwrap();
    assert!(json.contains("\"type\":\"runtime_error\""), "{json}");
    assert!(json.contains("\"message\":\"boom\""), "{json}");
    let back: ReplayOutcome = serde_json::from_str(&json).unwrap();
    assert_eq!(back, runtime_err);

    let awaiting = ReplayOutcome::Failed {
        at_event: 2,
        reason: FailReason::AwaitingExternal {
            name: "ask".to_owned(),
        },
    };
    let json = serde_json::to_string(&awaiting).unwrap();
    assert!(json.contains("\"type\":\"awaiting_external\""), "{json}");
    assert!(json.contains("\"name\":\"ask\""), "{json}");
}

// ── Record → replay identical run ────────────────────────────────────────────

#[test]
fn record_then_replay_identical_run() {
    let (program, tables) = link_fixture(CHOICE_STORY);

    // Record: play, choose 0, play again.
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables.clone()), None);
    let _ = run_to_pause(&mut session);
    session.choose(0).unwrap();
    let _ = run_to_pause(&mut session);
    session.choose(2).unwrap(); // "Finish" -> END
    let _ = run_to_pause(&mut session); // drive to END
    let after_record = session.snapshot();
    let journal = session.journal().clone();

    // Replay against a fresh story.
    let (replayed, outcome) = StorySession::<DotNetRng>::replay(
        Story::new(&program, tables),
        &journal,
        ExternalReplayMode::Recorded,
        None,
    );
    assert!(
        matches!(outcome, ReplayOutcome::Replayed { ref warnings } if warnings.is_empty()),
        "expected clean replay, got {outcome:?}",
    );
    // Replayed end state matches the recorded run's.
    assert!(diff(&after_record, &replayed.snapshot()).is_empty());
}

// ── Divergence after an edit (choice removed) → Diverged + truncation ────────

#[test]
fn divergence_choice_out_of_range_truncates_and_parks() {
    let (program, tables) = link_fixture(CHOICE_STORY);

    // Record a run that selects choice index 1.
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables.clone()), None);
    let _ = run_to_pause(&mut session);
    session.choose(1).unwrap();
    let mut journal = session.journal().clone();

    // Simulate an edit that removed a choice: rewrite the recorded Choice to an
    // out-of-range index so replay cannot apply it.
    for ev in &mut journal.events {
        if let EventKind::Choice { index, .. } = &mut ev.kind {
            *index = 99;
        }
    }

    let (replayed, outcome) = StorySession::<DotNetRng>::replay(
        Story::new(&program, tables),
        &journal,
        ExternalReplayMode::Recorded,
        None,
    );
    match outcome {
        ReplayOutcome::Diverged {
            at_event, found, ..
        } => {
            assert!(matches!(
                found,
                brink_runtime::DivergenceFound::ChoiceIndexOutOfRange { index: 99, .. }
            ));
            // Journal truncated at divergence; parked at reached position.
            assert!(replayed.journal().truncated);
            assert!(replayed.journal().len() <= at_event + 1);
        }
        other => panic!("expected Diverged, got {other:?}"),
    }
}

// ── Recorded vs live external modes ──────────────────────────────────────────

/// Returns a fixed int for `externalFunction`, counting invocations so a test
/// can prove "recorded" replay does NOT re-invoke.
struct CountingExternal {
    value: i32,
    calls: std::cell::Cell<u32>,
}

impl ExternalFnHandler for CountingExternal {
    fn call(&self, name: &str, _args: &[Value]) -> ExternalResult {
        if name == "externalFunction" {
            self.calls.set(self.calls.get() + 1);
            ExternalResult::Resolved(Value::Int(self.value))
        } else {
            ExternalResult::Fallback
        }
    }
}

#[test]
fn recorded_replay_does_not_reinvoke_live_does() {
    let (program, tables) = link_fixture(EXTERNAL_STORY);

    // Record: play through, resolving the external live.
    let record_handler = CountingExternal {
        value: 77,
        calls: std::cell::Cell::new(0),
    };
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables.clone()), None);
    let mut steps = 0;
    loop {
        steps += 1;
        assert!(steps < 1000, "step budget");
        match session.advance_with(&record_handler).unwrap() {
            StepOutcome::Line(l) if l.is_terminal() => break,
            StepOutcome::Line(_) => {}
            StepOutcome::AwaitingExternal => panic!("handler resolves inline"),
        }
    }
    assert_eq!(
        record_handler.calls.get(),
        1,
        "recorded exactly one external"
    );
    let journal = session.journal().clone();
    // The external result was journaled.
    assert!(journal.events.iter().any(
        |e| matches!(&e.kind, EventKind::External { name, result, .. }
            if name == "externalFunction" && *result == Value::Int(77))
    ));

    // Replay Recorded: the handler must NOT be re-invoked (its count stays 0).
    let replay_handler = CountingExternal {
        value: 999,
        calls: std::cell::Cell::new(0),
    };
    let (_replayed, outcome) = StorySession::<DotNetRng>::replay(
        Story::new(&program, tables.clone()),
        &journal,
        ExternalReplayMode::Recorded,
        Some(&replay_handler),
    );
    assert!(
        matches!(outcome, ReplayOutcome::Replayed { .. }),
        "{outcome:?}"
    );
    assert_eq!(
        replay_handler.calls.get(),
        0,
        "recorded mode must not re-invoke externals",
    );

    // Replay Live: the handler IS re-invoked.
    let live_handler = CountingExternal {
        value: 123,
        calls: std::cell::Cell::new(0),
    };
    let (_replayed, outcome) = StorySession::<DotNetRng>::replay(
        Story::new(&program, tables),
        &journal,
        ExternalReplayMode::Live,
        Some(&live_handler),
    );
    assert!(
        matches!(outcome, ReplayOutcome::Replayed { .. }),
        "{outcome:?}"
    );
    assert_eq!(
        live_handler.calls.get(),
        1,
        "live mode re-invokes externals"
    );
}

// ── Label-drift warning ──────────────────────────────────────────────────────

#[test]
fn label_drift_is_a_soft_warning_on_replayed() {
    let (program, tables) = link_fixture(CHOICE_STORY);

    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables.clone()), None);
    let _ = run_to_pause(&mut session);
    session.choose(0).unwrap();
    let mut journal = session.journal().clone();

    // Rewrite the recorded label so it drifts from what the program presents at
    // the same index — a matching index with different text.
    for ev in &mut journal.events {
        if let EventKind::Choice { label, .. } = &mut ev.kind {
            *label = Some("STALE LABEL".to_owned());
        }
    }

    let (_replayed, outcome) = StorySession::<DotNetRng>::replay(
        Story::new(&program, tables),
        &journal,
        ExternalReplayMode::Recorded,
        None,
    );
    match outcome {
        ReplayOutcome::Replayed { warnings } => {
            assert!(
                warnings.iter().any(|w| matches!(
                    w,
                    ReplayWarning::ChoiceLabelDrift { recorded, .. } if recorded == "STALE LABEL"
                )),
                "expected label-drift warning, got {warnings:?}",
            );
        }
        other => panic!("label drift must be a soft warning on Replayed, got {other:?}"),
    }
}

// ── callFunction journaled but externals isolated ────────────────────────────

#[test]
fn call_function_is_journaled_but_externals_are_isolated() {
    // func-none defines `function f()` returning 3.8.
    let (program, tables) = link_fixture(FUNCTION_STORY);
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables), None);

    // Isolated handler: if its externals leaked into the journal we'd see them.
    struct Trap;
    impl ExternalFnHandler for Trap {
        fn call(&self, _name: &str, _args: &[Value]) -> ExternalResult {
            ExternalResult::Fallback
        }
    }
    let ret = session.call_function("f", &[], &Trap).unwrap();
    assert_eq!(ret, Value::Float(3.8));

    // The journal has exactly one Call event and no External events from it.
    let calls = session
        .journal()
        .events
        .iter()
        .filter(|e| matches!(&e.kind, EventKind::Call { name, .. } if name == "f"))
        .count();
    assert_eq!(calls, 1, "call_function journals a Call event");
    let externals = session
        .journal()
        .events
        .iter()
        .filter(|e| matches!(&e.kind, EventKind::External { .. }))
        .count();
    assert_eq!(externals, 0, "call_function externals must not journal");
}

// ── Checkpoint fast-restore skips replay ─────────────────────────────────────

#[test]
fn checkpoint_fast_restore_skips_replay() {
    let (program, tables) = link_fixture(CHOICE_STORY);
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables.clone()), None);
    let _ = run_to_pause(&mut session);
    session.choose(0).unwrap();
    let _ = run_to_pause(&mut session);
    // Export refreshes the checkpoint.
    let journal = session.export_journal();
    assert!(journal.checkpoint.is_some(), "export embeds a checkpoint");
    assert_eq!(journal.program_checksum, program.source_checksum());

    // Restore against the same program: checksum matches → fast path, no replay
    // warnings and no stepping needed.
    let (restored, outcome) =
        StorySession::<DotNetRng>::restore(Story::new(&program, tables), journal).unwrap();
    assert!(
        matches!(outcome, ReplayOutcome::Replayed { ref warnings } if warnings.is_empty()),
        "fast-restore returns clean Replayed, got {outcome:?}",
    );
    // Turn index survived the checkpoint restore.
    let snap = restored.snapshot();
    assert!(snap.turn_index >= 1);
}

#[test]
fn restore_without_checkpoint_on_mismatch_errors() {
    let (program, tables) = link_fixture(CHOICE_STORY);
    // Journal for a *different* program (bad checksum), no checkpoint.
    let journal = SessionJournal::new(program.source_checksum().wrapping_add(1), None);
    match StorySession::<DotNetRng>::restore(Story::new(&program, tables), journal) {
        Err(SessionError::ChecksumMismatch { .. }) => {}
        Err(other) => panic!("expected ChecksumMismatch, got {other:?}"),
        Ok(_) => panic!("expected ChecksumMismatch error"),
    }
}

// ── Cap sets truncated ───────────────────────────────────────────────────────

/// The cap is enforced by the session's internal `push`: journaling past the
/// cap sets `truncated` and drops. Exercised deterministically through the
/// replay re-journaling path with more `SetVar` events than the cap.
#[test]
fn journal_push_honors_cap() {
    let (program, tables) = link_fixture(EXTERNAL_STORY);
    let mut src = SessionJournal::new(program.source_checksum(), None);
    src.events
        .push(brink_runtime::JournalEvent::new(EventKind::Start {
            path: None,
            args: vec![],
        }));
    for i in 0..SESSION_JOURNAL_CAP + 5 {
        src.events
            .push(brink_runtime::JournalEvent::new(EventKind::SetVar {
                name: "x".to_owned(),
                value: Value::Int(i as i32),
            }));
    }
    let (replayed, _outcome) = StorySession::<DotNetRng>::replay(
        Story::new(&program, tables),
        &src,
        ExternalReplayMode::Recorded,
        None,
    );
    // Re-journaling more than the cap must set truncated and stop growing.
    assert!(replayed.journal().truncated, "cap must set truncated");
    assert!(replayed.journal().len() <= SESSION_JOURNAL_CAP);
}

// ── Turn-boundary queue/reject behavior ──────────────────────────────────────

#[test]
fn mutation_mid_turn_is_rejected() {
    let (program, tables) = link_fixture(CHOICE_STORY);
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables), None);
    // Advance exactly one step: the story is now Active (mid-turn), not paused.
    match session.advance().unwrap() {
        StepOutcome::Line(l) => assert!(!l.is_terminal(), "expected non-terminal first line"),
        StepOutcome::AwaitingExternal => panic!("no external here"),
    }
    // A mid-turn mutation is rejected.
    let err = session.set_var("whatever", Value::Int(1)).unwrap_err();
    assert!(
        matches!(err, SessionError::MutationMidTurn { op: "set_var" }),
        "{err:?}"
    );
    let err = session.go_to_path("test", &[]).unwrap_err();
    assert!(
        matches!(err, SessionError::MutationMidTurn { op: "go_to_path" }),
        "{err:?}"
    );
    let save = SaveState {
        version: brink_format::SAVE_FORMAT_VERSION,
        globals: Default::default(),
        visits: vec![],
        turns: vec![],
        turn_index: 0,
        rng_seed: 0,
        previous_random: 0,
    };
    let err = session.load_state(&save).unwrap_err();
    assert!(
        matches!(err, SessionError::MutationMidTurn { op: "load_state" }),
        "{err:?}"
    );
}

#[test]
fn mutation_at_boundary_is_allowed_and_journaled() {
    let (program, tables) = link_fixture(CHOICE_STORY);
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables), None);
    // Drain to a choice pause — a turn boundary.
    let _ = run_to_pause(&mut session);
    // go_to_path at a boundary is allowed and journaled.
    session.go_to_path("test", &[]).unwrap();
    assert!(
        session
            .journal()
            .events
            .iter()
            .any(|e| matches!(&e.kind, EventKind::GoToPath { path, .. } if path == "test"))
    );
}

// ── Snapshot / diff on a real story (var change, list add/remove, turn) ──────

#[test]
fn snapshot_and_diff_track_list_membership_and_turns() {
    // The list story: `t = l1 + l2` then in `elsewhere`, `t += z`. Globals `t`.
    let (program, tables) = link_fixture(LIST_STORY);
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables), None);

    // Snapshot at start (before any content).
    let before = session.snapshot();

    // Run to the first pause: this executes `~ t = l1 + l2` and prints it.
    let lines = run_to_pause(&mut session);
    assert!(!lines.is_empty());
    let after = session.snapshot();

    // `t` is a List global present in both, membership changed (added items).
    assert!(
        after.globals.contains_key("t"),
        "t global present: {:?}",
        after.globals.keys().collect::<Vec<_>>()
    );
    let d = diff(&before, &after);
    // Something changed between the two snapshots.
    assert!(
        !d.is_empty(),
        "snapshot diff should be non-empty after running"
    );

    // The list membership delta for `t` records added items (a, c, x from the
    // active-marked list items).
    if let Some(delta) = d.list_deltas.get("t") {
        assert!(
            !delta.added.is_empty(),
            "expected list items added to t: {delta:?}"
        );
    }
    // The snapshot exposes typed list membership.
    if let Some(list) = after.lists.get("t") {
        assert!(!list.items.is_empty(), "t has active list members");
        // Sorted for determinism.
        let mut sorted = list.items.clone();
        sorted.sort();
        assert_eq!(list.items, sorted);
    }
}

#[test]
fn diff_of_identical_snapshots_is_empty() {
    let (program, tables) = link_fixture(CHOICE_STORY);
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables), None);
    let _ = run_to_pause(&mut session);
    let a = session.snapshot();
    let b = session.snapshot();
    assert!(diff(&a, &b).is_empty());
}

// ── Escape hatch reachability ────────────────────────────────────────────────

#[test]
fn escape_hatch_exposes_wrapped_story() {
    let (program, tables) = link_fixture(CHOICE_STORY);
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables), None);
    // Reads through the escape hatch never journal.
    let before = session.journal().len();
    let _pending = session.story().has_pending_external();
    let _ = session.story_mut().stats();
    assert_eq!(
        session.journal().len(),
        before,
        "escape-hatch reads never journal"
    );
}

// ── Live replay parks on deferred external, resumes via continue_replay ──────

/// A handler that defers (`Pending`) on its first call, then resolves.
struct DeferOnce {
    deferred: std::cell::Cell<bool>,
}

impl ExternalFnHandler for DeferOnce {
    fn call(&self, name: &str, _args: &[Value]) -> ExternalResult {
        if name == "externalFunction" && !self.deferred.get() {
            self.deferred.set(true);
            ExternalResult::Pending
        } else {
            ExternalResult::Resolved(Value::Int(0))
        }
    }
}

#[test]
fn live_replay_parks_on_pending_external() {
    let (program, tables) = link_fixture(EXTERNAL_STORY);
    // Record a normal run first.
    let rec = CountingExternal {
        value: 5,
        calls: std::cell::Cell::new(0),
    };
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables.clone()), None);
    let mut steps = 0;
    loop {
        steps += 1;
        assert!(steps < 1000);
        match session.advance_with(&rec).unwrap() {
            StepOutcome::Line(l) if l.is_terminal() => break,
            StepOutcome::Line(_) => {}
            StepOutcome::AwaitingExternal => panic!(),
        }
    }
    let journal = session.journal().clone();

    // Live replay with a deferring handler parks as Failed::AwaitingExternal.
    let defer = DeferOnce {
        deferred: std::cell::Cell::new(false),
    };
    let (mut replayed, outcome) = StorySession::<DotNetRng>::replay(
        Story::new(&program, tables),
        &journal,
        ExternalReplayMode::Live,
        Some(&defer),
    );
    assert!(
        matches!(
            outcome,
            ReplayOutcome::Failed {
                reason: FailReason::AwaitingExternal { .. },
                ..
            }
        ),
        "live replay must park on a deferred external, got {outcome:?}",
    );

    // The parked session retains the replay tail: resolve the external and
    // resume — the replay completes.
    assert!(
        replayed.has_pending_replay(),
        "park retains the replay tail"
    );
    assert!(replayed.has_pending_external());
    replayed.resolve_external(Value::Int(5));
    let outcome = replayed.continue_replay(Some(&defer));
    assert!(
        matches!(outcome, ReplayOutcome::Replayed { .. }),
        "resumed replay completes, got {outcome:?}",
    );
    assert!(!replayed.has_pending_replay());
}

// ── Deferred external BETWEEN two recorded choices: resume replays the tail ──

/// Compile ink source with the brink compiler and link it. Used where no
/// converter fixture has the needed shape (choices + an external in between).
fn compile_source(source: &str) -> (Program, Vec<Vec<brink_format::LineEntry>>) {
    let out = brink_compiler::compile("main.ink", |_| Ok(source.to_owned())).unwrap();
    brink_runtime::link(&out.data).unwrap()
}

/// Story where an external fires between two choice points.
const BETWEEN_CHOICES_INK: &str = r"
EXTERNAL probe(x)
-> top
== top ==
First question.
* one
    Value is {probe(1)}.
    -> second
* two
    -> second
== second ==
Second question.
* alpha
    Done.
    -> END
* beta
    Also done.
    -> END

=== function probe(x) ===
~ return 0
";

/// Defers (`Pending`) the first `probe` call, resolves later ones inline.
struct DeferProbe {
    deferred: std::cell::Cell<bool>,
}

impl ExternalFnHandler for DeferProbe {
    fn call(&self, name: &str, _args: &[Value]) -> ExternalResult {
        if name == "probe" && !self.deferred.get() {
            self.deferred.set(true);
            ExternalResult::Pending
        } else {
            ExternalResult::Resolved(Value::Int(42))
        }
    }
}

#[test]
fn live_replay_resumes_tail_after_external_between_choices() {
    let (program, tables) = compile_source(BETWEEN_CHOICES_INK);

    // Record: choice 1 → external resolves inline → choice 2 → END.
    let record = DeferProbe {
        deferred: std::cell::Cell::new(true), // never defers while recording
    };
    let mut session = StorySession::<DotNetRng>::new(Story::new(&program, tables.clone()), None);
    let lines = session.continue_to_pause().unwrap();
    assert!(
        matches!(lines.last(), Some(Line::Choices { .. })),
        "expected first choice set, got {lines:?}",
    );
    session.choose(0).unwrap(); // "one" → probe(1) fires next turn
    let mut steps = 0;
    loop {
        steps += 1;
        assert!(steps < 1000, "step budget");
        match session.advance_with(&record).unwrap() {
            StepOutcome::Line(l) if l.is_terminal() => break,
            StepOutcome::Line(_) => {}
            StepOutcome::AwaitingExternal => panic!("recording handler resolves inline"),
        }
    }
    session.choose(0).unwrap(); // "alpha" → END
    let _ = session.continue_to_pause().unwrap();
    let journal = session.journal().clone();
    // Sanity: the journal holds two choices with an external between them.
    let kinds: Vec<&EventKind> = journal.events.iter().map(|e| &e.kind).collect();
    assert!(
        matches!(
            kinds.as_slice(),
            [
                EventKind::Start { .. },
                EventKind::Choice { .. },
                EventKind::External { .. },
                EventKind::Choice { .. },
            ]
        ),
        "unexpected journal shape: {kinds:?}",
    );

    // Live replay: the external defers → park BETWEEN the two choices.
    let defer = DeferProbe {
        deferred: std::cell::Cell::new(false),
    };
    let (mut replayed, outcome) = StorySession::<DotNetRng>::replay(
        Story::new(&program, tables),
        &journal,
        ExternalReplayMode::Live,
        Some(&defer),
    );
    assert!(
        matches!(
            outcome,
            ReplayOutcome::Failed {
                reason: FailReason::AwaitingExternal { .. },
                ..
            }
        ),
        "expected park on the deferred external, got {outcome:?}",
    );
    assert!(replayed.has_pending_replay(), "tail must be retained");
    // Only the first choice replayed so far.
    let choices_so_far = replayed
        .journal()
        .events
        .iter()
        .filter(|e| matches!(e.kind, EventKind::Choice { .. }))
        .count();
    assert_eq!(choices_so_far, 1);

    // Resolve the external and resume: the SECOND recorded choice replays and
    // the outcome is Replayed.
    replayed.resolve_external(Value::Int(42));
    let outcome = replayed.continue_replay(Some(&defer));
    assert!(
        matches!(outcome, ReplayOutcome::Replayed { ref warnings } if warnings.is_empty()),
        "resumed replay must complete cleanly, got {outcome:?}",
    );
    assert!(!replayed.has_pending_replay());
    let final_choices = replayed
        .journal()
        .events
        .iter()
        .filter(|e| matches!(e.kind, EventKind::Choice { .. }))
        .count();
    assert_eq!(final_choices, 2, "both recorded choices replayed");
    // The story reached END ("alpha" → Done. → END).
    assert_eq!(
        replayed.snapshot().status,
        brink_runtime::SnapshotStatus::Ended
    );
}