brink-runtime 0.0.15

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
//! Regression tests for [`OutputLine::element`] (`Element`, issue #1683) —
//! the per-line classification field the `Step`/`OutputLine` redesign
//! (#1684) reserved but never populated.
//!
//! Scoped narrowly and honestly (see `Element`'s own doc): a plain, ink-
//! dialect line with no `@[element]`/`@[convention]` dispatch still reports
//! the degenerate [`Element::narrative`] case — these tests pin that the
//! field exists, is always the narrative default there, and survives both a
//! plain line and a line inside a choice-driven run.
//!
//! Issue #2108 (`docs/decision-log.md` 2026-08-03 "The element output
//! model") populates `element.data` for the one case the field's own doc
//! now scopes as real: an `attach = StructName` convention handler's
//! claimed line consumes itself (no event) and merges its declared struct's
//! fields into the block-level state every line in the following run
//! carries a copy of. `attach_convention_data_reaches_the_following_run`
//! below is that proof, run against native (`.brink`) source — the only
//! dialect `@[convention]` dispatch exists in.

use brink_runtime::{Element, FastRng, Step, Story};

/// Compile ink source and link it into a runnable story.
#[expect(clippy::unwrap_used)]
fn story_from_source(src: &str) -> Story<FastRng> {
    let data = brink_compiler::compile("main.ink", |_p| Ok(src.to_owned()))
        .unwrap()
        .data;
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    Story::new(std::sync::Arc::new(program), line_tables)
}

/// Compile native (`.brink`) source — the `.brink` extension is what routes
/// `brink_compiler::compile_path` through the native dialect
/// (`brink_syntax_native` + `hir::lower_native`), the only frontend
/// `@[convention]`/attach-mode dispatch exists in today.
///
/// Native compilation goes through `brink_compiler::compile_path` rather
/// than the closure-based `compile` used by [`story_from_source`] above:
/// native source discovery is tree-is-universe (every `.brink` file under
/// the entry's root joins the project, `CLAUDE.md`'s own note on this), so
/// it needs a real file on a real filesystem to discover from — a bare
/// per-path read callback with no directory to scan fails with "entry file
/// not found after discovery." The entry lives alone in its own uniquely-
/// named temp subdirectory (never a shared one) — "several probe files in
/// one directory silently become one project" is a known hazard of this
/// same tree-is-universe discovery, so isolation is per-directory, not
/// merely per-filename.
#[expect(clippy::unwrap_used)]
fn story_from_native_source(src: &str) -> Story<FastRng> {
    use std::sync::atomic::{AtomicU32, Ordering};
    static COUNTER: AtomicU32 = AtomicU32::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!("brink_element_test_{}_{n}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("main.brink");
    std::fs::write(&path, src).unwrap();
    // Issue #2289 part 2 (2026-08-05 ruling): a declared `@[convention]`
    // handler with no configured conventions module is now `E169`, not a
    // silent pass — `main.brink` inlines its own handlers, so it is its own
    // conventions module. `compile_path` never reads a co-located
    // `brink.toml` (its own doc says it bypasses `Environment`/config
    // entirely), so this has to be an explicit option, not a written file.
    let options = brink_analyzer::AnalysisOptions {
        conventions: Some("main.brink".to_owned()),
        ..brink_analyzer::AnalysisOptions::default()
    };
    let result = brink_compiler::compile_path_with_options(&path, options);
    let _ = std::fs::remove_dir_all(&dir);
    let data = result.unwrap().data;
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    Story::new(std::sync::Arc::new(program), line_tables)
}

/// Every `Step::Line` carries the degenerate narrative element — no
/// `@[element]` dispatch exists in this fixture, so there is nothing to
/// classify beyond the always-correct default.
#[test]
fn plain_lines_carry_the_narrative_default() {
    let mut story = story_from_source("One.\nTwo.\n-> END\n");
    let steps = story.continue_maximally().expect("drive to END");

    let lines: Vec<_> = steps
        .iter()
        .filter_map(|s| match s {
            Step::Line(line) => Some(line),
            _ => None,
        })
        .collect();
    assert_eq!(lines.len(), 2, "{steps:?}");
    for line in &lines {
        assert_eq!(line.element, Element::narrative(), "{steps:?}");
        assert_eq!(line.element.kind, "narrative");
        assert!(line.element.data.is_empty());
    }
}

/// The narrative default survives a choice-driven branch too — `element`
/// is stamped independently of `block_id`, so a fresh run after a choice
/// still reports the same degenerate classification.
#[test]
fn lines_after_a_choice_still_carry_the_narrative_default() {
    let mut story = story_from_source(
        "-> start\n\
         === start ===\n\
         Before.\n\
         * [left] Went left.\n-> END\n\
         * [right] Went right.\n-> END\n",
    );
    let _ = story.continue_maximally().expect("drive to choices");
    story.choose(0).expect("choose left");
    let after_steps = story.continue_maximally().expect("drive to END");

    let after_lines: Vec<_> = after_steps
        .iter()
        .filter_map(|s| match s {
            Step::Line(line) => Some(line),
            _ => None,
        })
        .collect();
    assert!(!after_lines.is_empty(), "{after_steps:?}");
    for line in &after_lines {
        assert_eq!(line.element, Element::narrative(), "{after_steps:?}");
    }
}

/// Issue #2108, the actual payoff: dialogue lines report their speaker.
///
/// Mirrors `tests/tier1-native/conventions-screenplay-preset/story.brink`'s
/// shape (two speaker turns, the second with no `parenthetical`) closely
/// enough to pin every corner the ruled model names:
///
/// - Ruling item 6 ("AN EVENT EXISTS IFF A LINE EXISTS"): `cue`/
///   `parenthetical`'s own claimed lines (`@VENDOR`, `(hushed)`, `@KID`)
///   produce **no** `Step::Line` at all — only the three ordinary dialogue/
///   transition lines do.
/// - Ruling item 3 ("attachment ACCUMULATES onto the following run"):
///   `cue` then `parenthetical` both merge into the SAME dialogue line's
///   data — `{speaker: VENDOR, delivery: hushed}`, not just one or the
///   other.
/// - Ruling item 4/`ElementAttachment`'s own doc ("the run IS the block"):
///   `KID`'s cue does not inherit `VENDOR`'s already-consumed data, and the
///   bare `transition` line after it carries NO attachment at all — the
///   block-level state resets between runs rather than leaking forward
///   forever.
#[test]
fn attach_convention_data_reaches_the_following_run() {
    let src = r#"
struct Cue {
  speaker: string,
}

struct Parenthetical {
  delivery: string,
}

@[convention(claims = "^(?<name>[A-Z][A-Z '-]*)$", attach = Cue, order = 10)]
fn cue(name: string): Cue {
  return Cue { speaker: name };
}

@[convention(claims = "^(?<delivery>[a-z][a-z' -]*)$", attach = Parenthetical, order = 20)]
fn parenthetical(delivery: string): Parenthetical {
  return Parenthetical { delivery: delivery };
}

@[convention(claims = "^(?<text>[A-Z][A-Z '-]*:)$", order = 30)]
fn transition(text: string) {
  return text;
}

flow main() {
  @VENDOR
  (hushed)
  You shouldn't be here after dark.

  @KID
  Says who?

  CUT TO:
  -> END
}
"#;
    let mut story = story_from_native_source(src);
    let steps = story.continue_maximally().expect("drive to END");

    let lines: Vec<_> = steps
        .iter()
        .filter_map(|s| match s {
            Step::Line(line) => Some(line),
            _ => None,
        })
        .collect();

    let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();
    assert_eq!(
        texts,
        vec![
            "You shouldn't be here after dark.\n",
            "Says who?\n",
            "CUT TO:\n",
        ],
        "attach conventions must consume their own line and produce no event: {steps:?}"
    );

    let vendor_line = lines[0];
    assert_eq!(
        vendor_line.element.data.get("speaker").map(String::as_str),
        Some("VENDOR"),
        "{vendor_line:?}"
    );
    assert_eq!(
        vendor_line.element.data.get("delivery").map(String::as_str),
        Some("hushed"),
        "{vendor_line:?}"
    );

    let kid_line = lines[1];
    assert_eq!(
        kid_line.element.data.get("speaker").map(String::as_str),
        Some("KID"),
        "{kid_line:?}"
    );
    assert!(
        !kid_line.element.data.contains_key("delivery"),
        "KID's turn has no parenthetical — must not inherit VENDOR's 'hushed': {kid_line:?}"
    );

    let transition_line = lines[2];
    assert_eq!(
        transition_line.element,
        Element::narrative(),
        "a bare transition after a dialogue run must not inherit its speaker: {transition_line:?}"
    );
}

/// Issue #2079, RULED 2026-08-06 "Compact cue desugars to cue + content
/// line": a compact cue (`@NAME: dialogue`) claims and attaches exactly
/// like the block form does — matching the pattern against the name
/// segment only — while the fused dialogue keeps full interpolation
/// rights, since it lowers as an ordinary content line *inside* `cue`'s
/// attached run rather than being flattened into the matched text.
///
/// Confirmed to fail without the fix (rule 20a): reverting the
/// `N::COMPACT_CUE` arm in `hir::lower_native::element::candidate` (and
/// its `try_claim` desugar) reproduces the pre-#2079 state — this exact
/// source fails to *compile* at all (`E169`/`E129`: `COMPACT_CUE` is
/// invisible to `candidate()`, so nothing claims `@KID: …` and it falls to
/// the loud "parses but has no HIR lowering yet" default) — never a wrong
/// transcript, always a hard compile failure, which is itself the
/// regression this test guards against reintroducing.
#[test]
fn compact_cue_fused_dialogue_attaches_and_keeps_interpolation() {
    let src = r#"
struct Cue {
  speaker: string,
}

@[convention(claims = "^(?<name>[A-Z][A-Z '-]*)$", attach = Cue, order = 10)]
fn cue(name: string): Cue {
  return Cue { speaker: name };
}

var count = 3

flow main() {
  @KID: I have {count} coins.
  -> END
}
"#;
    let mut story = story_from_native_source(src);
    let steps = story.continue_maximally().expect("drive to END");

    let lines: Vec<_> = steps
        .iter()
        .filter_map(|s| match s {
            Step::Line(line) => Some(line),
            _ => None,
        })
        .collect();

    let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();
    assert_eq!(
        texts,
        vec!["I have 3 coins.\n"],
        "cue's own claimed line must consume itself and produce no event; \
         the fused dialogue must interpolate `count` exactly like ordinary \
         prose: {steps:?}"
    );

    let dialogue_line = lines[0];
    assert_eq!(
        dialogue_line
            .element
            .data
            .get("speaker")
            .map(String::as_str),
        Some("KID"),
        "the fused dialogue must land INSIDE cue's attached run, carrying \
         its speaker data, not just render as plain unattached text: \
         {dialogue_line:?}"
    );
}

/// Review finding on issue #2079's PR: a compact cue's fused dialogue that
/// carries a fused divert must not be silently folded into the claim's
/// attached run — the divert would transfer control before that run's own
/// `EndElementRun`/`EndFragment` closes it, corrupting the runtime's
/// attachment bookkeeping (`speaker: KID` would otherwise leak onto every
/// line at the divert target). The claim declines instead (loud `E129`, the
/// same posture `try_dispatch` already takes when a `!name` dispatch's own
/// fused remainder isn't itself claimable), so this fixture must fail to
/// *compile*, not silently produce a corrupted transcript.
///
/// Confirmed to fail without the fix (rule 20a): before the
/// `is_plain_content_line` guard on `compact_dialogue` in `try_claim`, this
/// exact source compiled cleanly and merged `-> outside`'s divert into
/// `cue`'s captured attach run.
#[test]
fn compact_cue_dialogue_with_fused_divert_declines_the_claim() {
    use std::sync::atomic::{AtomicU32, Ordering};
    static COUNTER: AtomicU32 = AtomicU32::new(0);

    let src = r#"
struct Cue {
  speaker: string,
}

@[convention(claims = "^(?<name>[A-Z][A-Z '-]*)$", attach = Cue, order = 10)]
fn cue(name: string): Cue {
  return Cue { speaker: name };
}

flow main() {
  @KID: Goodbye. -> outside
}

flow outside() {
  You are outside.
  -> END
}
"#;
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!(
        "brink_element_compact_cue_divert_{}_{n}",
        std::process::id()
    ));
    std::fs::create_dir_all(&dir).expect("create temp dir");
    let path = dir.join("main.brink");
    std::fs::write(&path, src).expect("write fixture");
    let options = brink_analyzer::AnalysisOptions {
        conventions: Some("main.brink".to_owned()),
        ..brink_analyzer::AnalysisOptions::default()
    };
    let result = brink_compiler::compile_path_with_options(&path, options);
    let _ = std::fs::remove_dir_all(&dir);
    assert!(
        result.is_err(),
        "a compact cue whose fused dialogue carries a divert must decline \
         the claim and fail to compile (E129), not silently corrupt the \
         attached run: {result:?}"
    );
}

/// [`compact_cue_dialogue_with_fused_divert_declines_the_claim`]'s twin for
/// a fused `LABEL` (`(beat)`) instead of a divert — G-1's `(label)` syntax
/// parses right after a compact cue's `@NAME:` prefix exactly as it would
/// at the start of any other content line, and absorbing it unconditionally
/// into the claim's captured fragment would fold it into a
/// `Stmt::LabeledBlock` instead of the plain dialogue statement it should
/// be. Declines the same way, for the same reason.
#[test]
fn compact_cue_dialogue_with_fused_label_declines_the_claim() {
    use std::sync::atomic::{AtomicU32, Ordering};
    static COUNTER: AtomicU32 = AtomicU32::new(0);

    let src = r#"
struct Cue {
  speaker: string,
}

@[convention(claims = "^(?<name>[A-Z][A-Z '-]*)$", attach = Cue, order = 10)]
fn cue(name: string): Cue {
  return Cue { speaker: name };
}

flow main() {
  @KID: (beat) I have an idea.
  -> END
}
"#;
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!(
        "brink_element_compact_cue_label_{}_{n}",
        std::process::id()
    ));
    std::fs::create_dir_all(&dir).expect("create temp dir");
    let path = dir.join("main.brink");
    std::fs::write(&path, src).expect("write fixture");
    let options = brink_analyzer::AnalysisOptions {
        conventions: Some("main.brink".to_owned()),
        ..brink_analyzer::AnalysisOptions::default()
    };
    let result = brink_compiler::compile_path_with_options(&path, options);
    let _ = std::fs::remove_dir_all(&dir);
    assert!(
        result.is_err(),
        "a compact cue whose fused dialogue carries a label must decline \
         the claim and fail to compile (E129), not silently absorb it into \
         a labeled block: {result:?}"
    );
}

/// Review finding on issue #2108's PR: `OutputBuffer::flush_lines` seeded
/// `resolve_lines_annotated` with `pending_element` but never wrote the
/// end-of-slice state back (unlike `take_first_line`, which does) — so an
/// `ElementAttachEnd` consumed by a yield-point flush (a choice boundary,
/// here) was lost and the attach data stayed live on every line
/// afterward, in a different block.
///
/// `@VENDOR`'s two-line run is followed immediately by a choice point: the
/// trailing dialogue line has nothing after it in the transcript to prove
/// its own completion via `take_first_line` before the story yields
/// `Step::Choices`, so it — and the run-closing `ElementAttachEnd` — drain
/// through `flush_lines` at that yield point instead. Once a choice is
/// taken, the chosen branch's own line(s) belong to a new block entirely
/// and must not inherit `VENDOR`'s speaker.
#[test]
fn attach_element_data_does_not_leak_across_a_choice_boundary() {
    let src = r#"
struct Cue {
  speaker: string,
}

@[convention(claims = "^(?<name>[A-Z][A-Z '-]*)$", attach = Cue, order = 10)]
fn cue(name: string): Cue {
  return Cue { speaker: name };
}

flow main() {
  @VENDOR
  You shouldn't be here after dark.
  Get out now.

  {?
    * [Leave] You leave without a word.
  }
  -> END
}
"#;
    let mut story = story_from_native_source(src);
    let before_steps = story.continue_maximally().expect("drive to choices");
    assert!(
        matches!(before_steps.last(), Some(Step::Choices(_))),
        "{before_steps:?}"
    );

    story.choose(0).expect("choose Leave");
    let after_steps = story.continue_maximally().expect("drive to END");

    let after_lines: Vec<_> = after_steps
        .iter()
        .filter_map(|s| match s {
            Step::Line(line) => Some(line),
            _ => None,
        })
        .collect();
    assert!(!after_lines.is_empty(), "{after_steps:?}");
    for line in &after_lines {
        assert_eq!(
            line.element,
            Element::narrative(),
            "a line in the branch taken after the choice must not inherit \
             VENDOR's already-closed attach run: {after_steps:?}"
        );
    }
}

/// Issue #2077, the tag half's end-to-end proof: a claimed scene heading's
/// own trailing `#tag`s reach `OutputLine.tags` on the CLAIMED line's
/// output — not just the HIR `Content.tags` field a unit test can see, but
/// the real runtime output a host actually reads.
///
/// A `heading` handler here is Call-mode (no `attach`), same shape as
/// `tests/tier1-native/conventions-screenplay-preset/story.brink`'s own —
/// that fixture's own transcript is text-only (`brink_test_harness::
/// corpus::drive_native_transcript` appends only `line.text`, never
/// `line.tags`) and so, before this test, the tag half of issue #2077 had
/// zero coverage past the claimed line's own HIR statement.
#[test]
fn a_claimed_headings_own_tags_reach_the_output_line() {
    let src = r#"
@[convention(claims = "^(?<kind>INT|EXT)\\. (?<title>.+)$", order = 10)]
fn heading(kind: string, title: string) {
  return "-- {kind}. {title} --";
}

flow main() {
  INT. MARKET SQUARE - NIGHT [market] #act1
  The square is empty.
  -> END
}
"#;
    let mut story = story_from_native_source(src);
    let steps = story.continue_maximally().expect("drive to END");

    let lines: Vec<_> = steps
        .iter()
        .filter_map(|s| match s {
            Step::Line(line) => Some(line),
            _ => None,
        })
        .collect();

    let heading_line = lines
        .iter()
        .find(|l| l.text.contains("MARKET SQUARE"))
        .expect("expected the claimed heading's own line");
    assert_eq!(
        heading_line.tags,
        vec!["act1".to_string()],
        "the heading's own trailing tag must reach OutputLine.tags: {heading_line:?}"
    );
}