Runtime
Reusable, data-driven branching dialogue, quest progression, named-character history and narrative consequences for Zero games. The module interprets JSON-compatible definitions; it contains no SPITE//SHIFT characters, boss rules, weapons, morality score or presentation code.
BranchingStory
Reusable, data-driven branching dialogue, quest progression, named-character history and narrative consequences for Zero games. The module interprets JSON-compatible definitions; it contains no SPITE//SHIFT characters, boss rules, weapons, morality score or presentation code.
Identity: Narrative.Runtime
Definition schema: 1; snapshot format: 2 (legacy format 1 accepted for an identical definition)
Location: this world. Publication stays under the world owner's control; no separate publication is required.
Separation of responsibilities
| Layer | Owns | Adding content |
|---|---|---|
| Shared module | Validation, expression evaluation, transactional events, history, graph flow, save/replay and pending effects | Change only to add an engine capability or fix a bug |
| Game definition (JSON) | Typed facts, sets, event contracts, reusable conditions, rules, dialogue nodes, challenge outcomes and ending gates | Edit data; no module edits |
| Game adapter | Real gameplay events, minigame execution, UI, sound, inventory, encounter changes and checkpoint persistence | Existing handlers consume authored topic/payload data |
A new character, tracked property, quest, relationship, combination of conditions or consequence rule belongs in the definition. Conditions are expressions, not callbacks or hardcoded flag names. A new physical mechanic still needs its gameplay implementation: writing an emit record alone cannot implement a gun or a minigame.
Quick start
local Story = require("Narrative.Runtime")
local codec = require("@builtin::modules.json")
local definition = codec.decode(vfs.read(
"/zero/source/Narrative.package/examples/harbor-rpg.json"
))
local session = Story.new(definition)
Story.dispatch(session, {
id = "campaign-42/rescue-mira", -- stable identity of this actual occurrence
kind = "mira.rescued",
data = {},
})
Story.dispatch(session, {
id = "campaign-42/discover-charter",
kind = "lore.found",
data = { id = "ferry_charter" },
})
Story.begin(session, "harbormaster", "campaign-42/meeting-1")
local screen = Story.view(session).dialogue
Story.advance(session, "campaign-42/meeting-1/line-1", screen)
screen = Story.view(session).dialogue
Story.choose(session, "vouch", "campaign-42/meeting-1/choice-1", screen)
local state = Story.view(session)
-- state.facts["harbor.route"] == "ferry"
-- state.pending contains a travel.unlock command.
local save = Story.snapshot(session)
local restored = Story.new(definition, save)
The core performs no I/O; Projects and Sessions provide the package's I/O adapters. Supply any decoded JSON definition to the module. If importing this asset as a library, use its qualified module identity and load your definition from your own content path. The core uses no VFS, assets, entities, scene globals or third-party dependencies.
Definition format
Top-level keys: id (stable nonempty string), version (positive integer), optional description, facts, sets, events, conditions, rules, graphs, endings. Unknown top-level keys are rejected. Omitted collections are empty.
- facts: object keyed by authored stable IDs. Each declaration has
type,default, optionaldescription; number facts may havemin/max; enum facts requirevalues. Types: boolean, finite number, string, enum (string members). A name such asmira.fateis one literal ID, not an object path. - sets: object of initial arrays of unique nonempty string IDs. Use for discoveries, released actors, completed entries and collections where repeated reporting must not increase a count.
- events: object keyed by gameplay event kind. Each has
fields(typed scalar declarations like facts, without defaults; fields may beoptional) and optionalwhenprecondition. Unknown kinds/fields, missing required fields and invalid state transitions are rejected. Names beginning with$are reserved. - conditions: object of named expressions. Names can reference other conditions, including forward references; cycles and unknown names are rejected.
- rules: ordered array of
{id,on,when?,once?,effects}. Unique IDs. A rule sees the current incoming event and the state produced by earlier rules.once:truemeans once per session after it actually fires, not once per checkpoint load. - graphs: named dialogue graphs (below).
- endings: object of
{when,priority?,description?}. All eligible entries are returned, highest priority first with stable ID as tie breaker. The game authors final selection, exclusions and fallback; the library invents no ending.
Definitions contain data only: no callbacks, functions, cycles, engine handles, metatables or nonfinite numbers. Optional values are omitted; JSON null is not an authored expression.
Expressions: create conditions in data
Expressions are scalar literals or one of these objects:
| Expression | Value |
|---|---|
{"literal":["charter","permit"]} | Literal array/object value |
{"fact":"mira.fate"} | Current named scalar |
{"set":"lore"} | Sorted membership array |
{"event":"actor"} | Incoming event's data field |
{"event":"$graph"} | Incoming event's source dialogue graph |
{"condition":"can.vouch"} | Another named condition |
{"history":{"kind":"person.killed","where":{"actor":"mira"}}} | Matching accepted-event count |
{"history":{"kind":"person.killed","distinct":"actor"}} | Matching distinct actor count |
{"op":"all","args":[...]} | Boolean AND |
{"op":"any","args":[...]} | Boolean OR |
{"op":"not","args":[...]} | Boolean NOT (one operand) |
{"op":"eq","args":[a,b]}, ne | Structural equality/inequality |
gt/gte/lt/lte | Numeric comparison, two operands |
contains | Array contains value (two operands) |
in | Value belongs to array (two operands) |
add/sub/mul | Numeric arithmetic, two operands |
concat | Join string operands |
all / any short-circuit and require boolean results. Empty all is true; empty any is false. Conditions are strictly boolean, not Lua truthiness.
History where is an exact-match map: expected values are expressions evaluated in the current context. distinct ignores events missing the field. $graph, $node, and $run_id access recorded dialogue origin; regular keys access event data. The incoming event counts during its transaction, so an event can satisfy a threshold immediately.
Keep conditions used by screens/endings based on persistent facts/history. Event fields exist only while a command is processing. Persist anything a later screen needs using an effect.
Example: adding a new condition requires only JSON:
{
"can.vouch": {
"op": "all",
"args": [
{"op": "eq", "args": [{"fact": "mira.fate"}, "rescued"]},
{"op": "contains", "args": [{"set": "lore"}, "ferry_charter"]},
{"op": "eq", "args": [
{"history": {"kind": "promise.broken", "where": {"person": "mira"}}},
0
]}
]
}
}
Declare referenced events/facts/sets in the same definition. This is an illustration; the runnable harbor example uses its own smaller event vocabulary.
Effects and game integration
An effect may include a when expression. Effects run in authored array order.
{op:"set",fact:"id",value:expression}{op:"add",fact:"numeric-id",value:expression}{op:"include",set:"id",value:expression}/exclude(nonempty string member){op:"emit",topic:"encounter.configure",payload:{variant:expression,...}}
A transaction either commits all its facts/sets/rules/graph movement/pending effects and history or commits none. It does not call game code while evaluating.
Read view(session).pending. Each emitted record contains id, topic, payload; its stable ID derives from the originating event and emission order. Apply using a topic handler, then call ack(session,effectId,stableAckEventId). Persist the session and gameplay state at the same checkpoint boundary. External handlers must deduplicate using the effect ID: a crash between application and acknowledgement can redeliver a command. This is an outbox with idempotent consumers, not a promise of atomic transactions across arbitrary game systems.
Use gameplay state setters (configure encounter variant X) where possible, rather than unguarded additive operations (grant one more weapon). Do not acknowledge until application succeeds.
Dialogue graphs
A graph has start, optional when, optional description, and nodes keyed by stable ID. Entry and subsequent player inputs check the graph condition; abort remains available if the condition ceases to hold.
| Node kind | Required content | Behavior |
|---|---|---|
| line | next; optional speaker,text | Wait for advance |
| choice | options | Each has id,next, optional text,when,locked_text,effects |
| branch | branches:[{when,next}],otherwise | First matching branch, otherwise fallback |
| action | effects,next | Commit effects then continue |
| challenge | challenge,outcomes | Host runs named minigame; each outcome has next,effects? |
| end | optional result,text,speaker | Explicit terminus; no automatic reward |
Action/branch traversal is capped at 128 automatic steps per command; accidental loops reject the whole command. Authors can intentionally loop through interactive nodes.
view().dialogue contains graph/node/run identity, presentation text, available choices and challenge ID, without hidden effects. Pass that exact presentation token back to advance, choose, resolve or abort. Stale callbacks from a different node or run reject. Each input also has its own stable event ID for retries.
resolve(session,outcome,eventId,presentation,performance?) accepts only an authored outcome. The trusted game adapter decides whether the minigame actually succeeded; the core does not verify inputs, animate a romance scene or run combat. Performance is recorded numerically and can be assigned to a fact using {"event":"performance"}.
Skipping text advances a line only; it cannot silently select an option or resolve a challenge. Aborting is distinct from losing. If a particular game treats an abort as consequential, author a $abort rule explicitly.
Recorded system events: $begin, $advance, $choose, $resolve, $abort, $ack. The journal preserves graph, node and run context alongside the chosen option/outcome/performance.
API and persistence
Exports: validate, new, dispatch, view, test, explain, eligible, begin, advance, choose, resolve, abort, ack, snapshot, history. Describe the module in the asset browser for signatures.
validate(definition)returns{ok,error?}. Runtime values and effect results are also checked at the transaction boundary; validation is not an exhaustive proof of every authored branch.new(definition,snapshot?)creates independent private session state.- Stable event IDs deduplicate identical retries. Conflicting reuse rejects. Never generate a new occurrence ID merely because a checkpoint callback retried.
view,historyandsnapshotreturn detached data; edits cannot mutate the live session.- Saves contain version, definition identity, SHA-256 fingerprint of the normalized definition and accepted-event journal. Restore reconstructs state deterministically without invoking external effects. Pending/acknowledged effects and active dialogue survive.
- Definition changes require explicit migration, including same-version edits. The library rejects incompatible saves rather than silently reinterpret history. A migration should rewrite a copy, validate replay under the new definition, preserve the original and have its own regression fixtures.
- Module hot reload invalidates session handles. Snapshot before code reload; re-require and restore afterward.
- Checkpoint rewind restores both narrative and physical game state. Replays/debug experiments use separate sessions and never merge into the campaign automatically.
- The package's Sessions module supplies local-device and current-player persistence with one previous checkpoint. The host still owns network authority, concurrency ordering and checkpoint cadence, and supplies/restores physical game state. See the package guide.
This engine is for committed progression events, not per-bullet telemetry or per-frame simulation. History is indexed by event kind; filtered history queries scan that kind. Sets use transaction-local copy-on-write. Save creation copies the journal, and restore replays it. Large campaigns should benchmark representative journals and schedule persistence outside combat-critical work.
Included examples and verification
examples/harbor-rpg.json: unrelated RPG, entirely data-defined. Rescue/evidence unlock ferry access; failed negotiation opens a ridge route.tests/run.luau: isolated runtime contract tests. Execute it in edit mode. It changes no entities, scenes or real campaign saves.- SPITE//SHIFT's example is deliberately outside this module at
/zero/source/narrative/spite-shift.contract.json, with its own tests. It is a consequence contract fixture, not finished campaign content.
The reusable asset remains inside this private world until its owner publishes the world. No public upload, separate world or visibility change has been made.
Scoped to this part · feeds back into the world's score.