# Narrative
Reusable branching-story package for Zero: data-defined progression and dialogue, multi-file content authoring, a registered agent toolbox, history inspection, and persistent local/player save slots. Game-specific content lives outside the package.
Version 0.1.0. Stored in this private world. Committing and pushing syncs the work; making the world public is a separate owner-controlled visibility change.
## Start here
Agents: inspect `tools.list().value.story`, then read the requested tool with `describe_tool({tool:"story.condition"})`. Unpushed tools are not yet in the semantic index. Push the world changes and allow indexing; direct registry discovery and calls also work before pushing. The package asset identity is `Narrative.story`; the registered callable toolbox namespace is **`story`**, so calls are `story.create`, `story.condition`, etc., not `Narrative.story.create`.
Read `guides({path:"Narrative.package/authoring"})` or [the authoring guide](authoring.guide/guide.md) for the complete workflow and [the runtime contract](Runtime.module/README.md) for the expression language. The package includes JSON Schemas under `schemas/` for editor association; runtime validation additionally checks references and graph integrity.
## What installs
| Asset | Responsibility |
|---|---|
| `Narrative.Runtime` | Pure state, history, condition evaluation, dialogue graphs and snapshots |
| `Narrative.Projects` | Manifest loading, separate content records, validation and revision-checked edits |
| `Narrative.Sessions` | Named sessions; persistent local/player save/load; previous checkpoint |
| `Narrative.Fingerprint` | SHA-256 definition/content compatibility fingerprints |
| `Narrative.story` toolbox | 24 discoverable tools for authoring, simulation, inspection and persistence |
| `Narrative.authoring` guide | Setup, storage locations, examples and integration requirements |
| `examples/harbor/` | Complete unrelated RPG example split into records |
| `schemas/` and `tests/` | Machine-readable formats and regression suites |
Package-internal imports use `~.` so the implementation does not depend on the host world's name. The only external module dependency is the engine's builtin JSON codec. Runtime storage adapters use documented VFS and player-data APIs.
The old world-level `BranchingStory` module is a compatibility bridge to this package and is not a dependency of it.
## Storage
Authored content: a caller-chosen JSON manifest plus relative record files. Neither its filename nor its directory is hardcoded. Tools return each record's path and the project revision. Updating one condition does not rewrite every conversation.
Live state: an isolated session in memory.
Local save: `/zero/source/local/narrative/<encoded-game-id>/<encoded-slot>.json`. This is per world/user/device, durable, and excluded from published world content.
Player save: `runtime_data.player(runtime_data.localId())`, under `narrative/<encoded-game-id>/<encoded-slot>`. This is per signed-in player and follows the player's replicated store. IDs are UTF-8 bytes encoded as hex to avoid path collisions/traversal. `story.slots` and `story.save` report actual paths.
Player saves are divided into bounded chunks to respect the store's 256 KB per-value limit. Chunks are written and confirmed before replacing the slot pointer. Hash/length are checked on load. A previous checkpoint is retained. Old chunk generations are retired after a later successful commit; failed writes can leave unreachable chunks but do not intentionally advance the slot.
Authored JSON is never used as a player save. Save format 2 contains a compact definition fingerprint and accepted-event journal, not a copy of every authored dialogue line. Exact-compatible legacy format-1 runtime snapshots can still load.
## Scope
This package supplies runtime APIs and agent authoring tools. It does not contain a graphical dialogue editor or a game-specific dialogue HUD. Games report real events, run their minigames, apply pending gameplay effects idempotently, and supply/restore physical checkpoint data alongside the story state.
The save revision check rejects stale writes within the calling workflow; local concurrent saves are serialized by slot. A game must designate one writer per player slot across devices: the underlying store is not a distributed compare-and-swap service.
No campaign content or public installation is implied by these tools. SPITE's data project stays at `/zero/source/narrative/spite-shift/manifest.json`.
## Verification
Execute `tests/runtime.luau` (19 runtime checks) and `tests/integration.luau` (12 package/tool/storage checks) through the engine. Integration tests create uniquely named scratch projects and private save slots, then remove their test saves. They include 120 NPC fate records, 200 quest-stage records, an eight-layer dialogue gate, SHA-256 vectors, previous-checkpoint recovery and a player save larger than one store leaf. The separate SPITE consequence suite contains 15 checks.
These tests do not claim that 120 fully authored NPCs or 200 actual quests exist, and are not a complete campaign performance benchmark.
# 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
```luau
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`, optional `description`; number facts may have `min/max`; enum facts require `values`. Types: boolean, finite number, string, enum (string members). A name such as `mira.fate` is 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 be `optional`) and optional `when` precondition. 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:true` means 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:
```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`, `history` and `snapshot` return 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.