Skip to main content

Story

Struct Story 

Source
pub struct Story<R: StoryRng = FastRng> { /* private fields */ }
Expand description

Per-instance mutable state for executing stories.

Created from a Program via Story::new. Holds all mutable state (stacks, globals, output buffer) while the immutable program data lives in Program.

Generic over R: StoryRng — defaults to FastRng. Use DotNetRng for .NET-compatible deterministic output.

Implementations§

Source§

impl<R: StoryRng> Story<R>

Source

pub fn save_state(&self) -> SaveState

Capture the default flow’s game state as a durable, name-keyed SaveState. Does not capture execution position. Thin delegating wrapper over the free save_state function — see the module docs.

Source

pub fn load_state(&mut self, save: &SaveState) -> LoadReport

Reconcile a SaveState into the default flow’s context. Thin delegating wrapper over the free load_state function — see the module docs.

Source§

impl<R: StoryRng> Story<R>

Source

pub fn new(program: Arc<Program>, line_tables: Vec<Vec<LineEntry>>) -> Self

Create a new story instance from a linked program and its line tables.

Source

pub fn set_visibility_enforcement(&mut self, enforce: bool)

Enable or disable host visibility enforcement (M-2b, docs/modules-spec.md §4 boundary rule 3). Enforcement is on by default: host semantic access (variable get/set, entry lookup, function eval) to a #@private definition returns RuntimeError::PrivateAccess (or None/false for the infallible get/set). Dev tooling — editors, debug hosts, the play-from-here affordance — calls this with false to start flows at private knots and inspect private state. This is a host capability, not a language switch; the compiled program is identical either way. Persistence (save/load/journal/replay) ignores this flag entirely.

Propagates to every FlowInstance this Story currently owns (default, every named flow, every shared flow) — each carries its own copy of the flag (so bevy-brink/crate::Speculation can enforce it when driving a FlowInstance directly, without a Story), and Story keeps them synced so a Story-mediated dev override never diverges from the flows it delegates to. Flows spawned after this call (spawn_flow/ spawn_flow_shared) inherit the Story’s current setting at spawn time.

Source

pub fn visibility_enforced(&self) -> bool

Whether host visibility enforcement is currently on (default true).

Source

pub fn set_exec_mode(&mut self, mode: ExecMode)

Set the dev/prod execution mode (NS-A4, ExecMode — see its docs for the §4b ordering doctrine). Dev (the default) faults on a float NaN comparand in an ordering context; Prod keeps moving with the pinned non-fabricating total order. The knob’s home is project config (brink.toml profile) with this host-API override (ruled 2026-07-19); the mode is never embedded in .inkb and never persisted in saves or snapshots.

Propagates to every FlowInstance this Story currently owns (default, named, shared) — the same sync discipline as set_visibility_enforcement. Flows spawned after this call inherit the Story’s current setting at spawn time.

Source

pub fn exec_mode(&self) -> ExecMode

The current dev/prod execution mode (default ExecMode::Dev).

Source

pub fn set_plural_resolver(&mut self, resolver: Box<dyn PluralResolver>)

Set the plural resolver for Select resolution in localized lines.

Source

pub fn set_line_tables(&mut self, tables: Vec<Vec<LineEntry>>)

Replace the active line tables (e.g. for locale swapping).

Source

pub fn line_tables(&self) -> &[Vec<LineEntry>]

Read-only access to the current line tables.

Source

pub fn transcript(&self) -> &[OutputPart]

The full append-only transcript of all output parts produced so far.

Source

pub fn transcript_len(&self) -> usize

Number of parts in the transcript.

Source

pub fn reset_cursor(&mut self)

Reset the transcript read cursor to the beginning (for re-rendering).

Source

pub fn resolve_transcript_slice( &self, range: Range<usize>, ) -> Vec<(String, Vec<String>)>

Resolve a slice of the transcript against the current line tables. Returns (text, tags) tuples — one per line in the resolved output.

Source

pub fn pending_choices(&self) -> Vec<Choice>

Re-resolve all pending choices against the current line tables. Returns the same choices that would appear in Step::Choices, but freshly resolved (useful after locale switch).

Source

pub fn resolve_fragment(&self, idx: u32) -> String

Resolve a fragment against the current line tables.

Source

pub fn choice_fragment_idx(&self, choice_index: usize) -> Option<u32>

Get the fragment index for a pending choice’s display text, if any.

Source

pub fn fragments(&self) -> &[Fragment]

Read-only access to the fragment store (for transcript serialization).

Source

pub fn program(&self) -> &Program

Read-only access to the program.

Source

pub fn variable(&self, name: &str) -> Option<&Value>

Read a global variable’s current value by name. None if no global with that name is declared. Reads the default flow’s context.

Returns None for a #@private variable while visibility enforcement is on (M-2b) — the host is outside every module, so a private name is not host-visible. Dev tooling opts out via set_visibility_enforcement.

Source

pub fn set_variable(&mut self, name: &str, value: Value) -> bool

Set a global variable by name, returning false (no-op) if no global with that name is declared. Ink globals are dynamically typed, so the host is responsible for passing a sensibly-typed value.

Returns false (no write) for a #@private variable while visibility enforcement is on (M-2b). Dev tooling opts out via set_visibility_enforcement.

Source

pub fn set_rng_seed(&mut self, seed: i32)

Set the RNG seed for the default flow’s context. Seeding makes RANDOM/shuffle output reproducible — set it before running (or after a reset) so two runs of the same story on different machines match.

Source

pub fn advance_with( &mut self, handler: &dyn ExternalFnHandler, ) -> Result<StepOutcome, RuntimeError>

Advance the default flow by one step with a custom handler, surfacing a deferred external as StepOutcome::AwaitingExternal rather than erroring (unlike continue_single_with).

On AwaitingExternal, resolve the pending call (resolve_external, or invoke_fallback) and call advance_with again to resume. Inspect the pending call via pending_external_name / pending_external_args.

Source

pub fn pending_external_name(&self) -> Option<&str>

Name of the external the default flow is paused on, if any.

Source

pub fn pending_external_args(&self) -> &[Value]

Arguments of the external the default flow is paused on.

Source

pub fn call_function( &mut self, name: &str, args: &[Value], handler: &dyn ExternalFnHandler, ) -> Result<Value, RuntimeError>

Evaluate an ink function by name from engine code, returning its value.

Runs out-of-band on the default flow: output is isolated (the visible story is untouched), and the call completes synchronously. Externals the function calls are resolved inline by handler; an external the handler defers (ExternalResult::Pending) can’t be resolved in a synchronous call and yields RuntimeError::AsyncExternalInCall (the paused eval is cleaned up first).

§Errors

RuntimeError::FunctionNotFound for an unknown name; RuntimeError::AsyncExternalInCall if a called external defers; plus any runtime error raised during evaluation.

Source

pub fn speculate(&self) -> Speculation<R>

Fork a Speculation — a sandboxed, side-effect-proof speculative run — from the default flow’s current state.

The speculation owns an independent snapshot: driving it (via its own advance/choose/go_to_path/eval_function verbs) never mutates this Story. Dropping it discards everything it did. See crate::Speculation for the full picture, and crate::Speculation::fork_from for forking a non-default flow (e.g. a named flow spawned via spawn_flow).

Source

pub fn into_snapshot(self) -> (StorySnapshot<R>, Vec<Vec<LineEntry>>)

Detach story state from the program, consuming the story.

Source

pub fn from_snapshot( program: Arc<Program>, snapshot: StorySnapshot<R>, line_tables: Vec<Vec<LineEntry>>, ) -> Self

Reattach a snapshot to a program with line tables.

Source

pub fn continue_single(&mut self) -> Result<Step, RuntimeError>

Execute until one line of content (up to newline), or until a yield point (choices/end) if no newline occurs first.

The returned Step variant tells you what to do next:

Source

pub fn continue_single_observed( &mut self, observer: &mut dyn WriteObserver, ) -> Result<Step, RuntimeError>

Like continue_single but with a WriteObserver that receives notifications for every state mutation.

Source

pub fn continue_single_with( &mut self, handler: &dyn ExternalFnHandler, ) -> Result<Step, RuntimeError>

Like continue_single but with a custom external function handler.

Source

pub fn continue_maximally(&mut self) -> Result<Vec<Step>, RuntimeError>

Execute until the next yield point, collecting all lines.

Returns a Vec<Step> where the last element is always Step::Choices or Step::End, and all preceding elements are Step::Line.

Source

pub fn continue_maximally_with( &mut self, handler: &dyn ExternalFnHandler, ) -> Result<Vec<Step>, RuntimeError>

Like continue_maximally but with a custom external function handler.

Source

pub fn continue_maximally_observed( &mut self, observer: &mut dyn WriteObserver, ) -> Result<Vec<Step>, RuntimeError>

Execute until the next yield point with a WriteObserver that receives notifications for every state mutation.

Source

pub fn choose(&mut self, index: usize) -> Result<(), RuntimeError>

Select a choice by index, then resume with continue_single or continue_maximally.

Source

pub fn choose_path_string(&mut self, path: &str) -> Result<(), RuntimeError>

Move the default flow’s play head to a named knot/stitch path — ink’s ChoosePathString equivalent. The current flow is force-completed (callstack reset, pending choices cleared), the jump counts as a visit to the target exactly like a -> path divert, and subsequent continue_single / continue_maximally calls run from there. See FlowInstance::choose_path_string for full semantics.

§Errors

UnknownPath for an unknown path; JumpWhileAwaitingExternal if the flow is parked on an unresolved external call; AlreadyEvaluatingFunction if an engine→ink function evaluation is in progress.

Source

pub fn choose_path_string_with_args( &mut self, path: &str, args: &[Value], ) -> Result<(), RuntimeError>

Move the default flow’s play head to a parameterized knot/stitch, binding its declared parameters from args — ink’s ChoosePathString with arguments. Otherwise identical to choose_path_string. See FlowInstance::choose_path_string_with_args for full semantics.

§Errors

As choose_path_string, plus ArgCountMismatch when args.len() doesn’t match the target’s declared parameter count.

Source

pub fn stats(&self) -> &Stats

Read-only access to the default flow’s VM statistics.

Source

pub fn has_pending_external(&self) -> bool

Returns true if the default flow has a pending external call (an External frame on top of the call stack).

Source

pub fn resolve_external(&mut self, value: Value)

Resolve a pending external call on the default flow by providing the return value. For fire-and-forget calls, pass Value::Null.

After resolving, call continue_maximally to continue execution.

Source

pub fn invoke_fallback(&mut self) -> Result<(), RuntimeError>

Resolve a pending external call on the default flow by invoking the ink-defined fallback body. The fallback is a function call whose output becomes the return value.

After invoking, call continue_maximally to continue execution.

Source

pub fn spawn_flow( &mut self, name: &str, entry_point: DefinitionId, ) -> Result<(), RuntimeError>

Spawn a new flow instance starting at the given entry point.

entry_point is the DefinitionId of the target container (e.g., a knot). Each flow instance gets its own globals, visit counts, and execution state.

Source

pub fn continue_flow_maximally( &mut self, name: &str, ) -> Result<Vec<Step>, RuntimeError>

Run a named flow instance until the next yield point.

Source

pub fn continue_flow_maximally_with( &mut self, name: &str, handler: &dyn ExternalFnHandler, ) -> Result<Vec<Step>, RuntimeError>

Run a named flow instance with an external function handler.

Source

pub fn choose_flow( &mut self, name: &str, index: usize, ) -> Result<(), RuntimeError>

Select a choice in a named flow.

Source

pub fn destroy_flow(&mut self, name: &str) -> Result<(), RuntimeError>

Destroy a named flow instance — isolated or shared (#200).

Source

pub fn flow_names(&self) -> Vec<&str>

List active flow names (isolated + shared), sorted for determinism.

Source

pub fn wake_check(&mut self) -> Vec<String>

Re-evaluate the wake conditions of parked flows and return the ids of the flows that woke, sorted for determinism (docs/flow-suspension-spec.md §10.2). Waking never auto-continues: the host drives a woken flow via Story::continue_flow_single when it wants output.

Returns an empty list until parks exist (FS-3r). No flow can be parked in today’s runtime — the E052 lowering fence keeps await from producing bytecode (Step::Suspended is unreachable), so there are no conditions to re-evaluate. The method ships now (FS-3w) so hosts wire the wake loop against a stable shape; FS-3r fills in real condition evaluation + dirty-tracking without changing this signature. Dirty-tracking is not built here — this is the free stub.

Source

pub fn spawn_flow_shared( &mut self, name: &str, container_idx: Option<u32>, ) -> Result<(), RuntimeError>

Spawn a shared-context flow at container_idx (or the root if None).

Source

pub fn continue_flow_single(&mut self, name: &str) -> Result<Step, RuntimeError>

Advance a shared flow one line (against the shared context).

Source

pub fn continue_flow_single_with( &mut self, name: &str, handler: &dyn ExternalFnHandler, ) -> Result<Step, RuntimeError>

Advance a shared flow one line with an external-function handler.

Source

pub fn continue_flow_maximally_shared( &mut self, name: &str, ) -> Result<Vec<Step>, RuntimeError>

Run a shared flow to its next terminal line (against the shared context) — the shared-flow analogue of Self::continue_flow_maximally (which drives an isolated flow instead). Bounded by FlowInstance::LINE_LIMIT via drive_to_terminal: an infinite-emitting flow errors with RuntimeError::LineLimitExceeded rather than growing the returned Vec without bound (guard against unbounded growth).

Source

pub fn continue_flow_maximally_shared_with( &mut self, name: &str, handler: &dyn ExternalFnHandler, ) -> Result<Vec<Step>, RuntimeError>

Run a shared flow to its next terminal line with an external-function handler. See Self::continue_flow_maximally_shared.

Source

pub fn choose_flow_shared( &mut self, name: &str, index: usize, ) -> Result<(), RuntimeError>

Select a choice in a shared flow (against the shared context).

Source

pub fn debug_snapshot(&self) -> DebugSnapshot

A structured, name-resolved snapshot of the current runtime state for the studio State View: status, current location, globals, call stack, visit counts, pending choices, and rng. Read-only; built on demand and not on any hot path. See DebugSnapshot.

Source

pub fn debug_snapshot_flow( &self, name: &str, ) -> Result<DebugSnapshot, RuntimeError>

A debug snapshot of a named shared flow (#200), built against the shared default_context — so its globals / visit counts match the default flow’s, while its call stack + temps are the flow’s own. Falls back to a named isolated flow’s own context if name is one of those instead.

Source

pub fn debug_state(&self) -> String

Dump the current execution state for debugging.

Returns a human-readable summary of the call stack, current position, value stack, output buffer, globals, and pending choices.

Source

pub fn did_safe_exit(&self) -> bool

Returns whether the last execution cycle of the default flow ended with a safe exit (explicit -> DONE opcode). If false after a Done line, the story ran out of content — the next continue_single call will return RuntimeError::RanOutOfContent instead of more text. See FlowInstance::did_safe_exit for the full contract.

This reads only self.default — for a named flow (spawned via spawn_flow or one of the isolated instances), use did_safe_exit_flow instead. Calling this after continue_flow* on a named flow silently returns the default flow’s stale value.

Source

pub fn did_safe_exit_flow(&self, name: &str) -> Result<bool, RuntimeError>

Like did_safe_exit, but for a named flow (shared or isolated) rather than the default flow. Mirrors debug_snapshot_flow’s lookup shape: checks shared_instances first, then falls back to the isolated instances.

§Errors

UnknownFlow if no flow named name exists (shared or isolated).

Source

pub fn did_unsafe_yield(&self) -> bool

Returns whether the last execution cycle passed through an empty choice set (a Yield opcode with no pending choices).

Source

pub fn step_once( &mut self, ) -> Result<Option<(String, u32, usize)>, RuntimeError>

Execute a single VM step and return a debug trace of what happened.

Returns (opcode_description, container_idx, offset_before) or None if the step didn’t decode an opcode (frame exhaustion, thread completion, etc).

Trait Implementations§

Source§

impl<R: StoryRng> Clone for Story<R>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<R = FastRng> !RefUnwindSafe for Story<R>

§

impl<R = FastRng> !Send for Story<R>

§

impl<R = FastRng> !Sync for Story<R>

§

impl<R = FastRng> !UnwindSafe for Story<R>

§

impl<R> Freeze for Story<R>
where PhantomData<R>: Freeze,

§

impl<R> Unpin for Story<R>
where PhantomData<R>: Unpin,

§

impl<R> UnsafeUnpin for Story<R>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.