BeSpoke Engine Architecture & Developer Guide

The 3x What/How/Why manual and developer guide for the Engine-as-Spine narrative simulation runtime

BeSpoke is a bespoke game development language and standalone simulation engine written in pure Zig, designed from the ground up for systemic, emergent, and narrative game simulations. Every component, pipeline, and architectural decision is documented with its behavior (What), mechanism (How), and design intent (Why).

Engine-as-SpineDeveloper GuidePure Zig 0.17.1Wasm32 Browser TargetZero DependenciesDeterministic Discrete Ticks3x Documented
The 3x reading contract: every entry explains what it does, how it works, and why it works that way.
No entries match that search.

Core Architecture & Principles

Foundational architectural decisions defining the simulation engine boundary, clock model, and memory layout.

Engine-as-Spine Architecture

#
architecturespinetenet

The simulation VM is main() and owns the master clock, entities, and state, treating graphics engines strictly as peripherals.

pub fn main() !void { var world = World.init(...); var vm = VM.init(...); while (running) { vm.step_tick(); bridge.capture_frame(); } }

What it does

Inverts the traditional game engine model: rather than embedding a scripting language as a guest plugin inside Unity or Godot, BeSpoke is the host spine that owns simulation state, rules, pathfinding, and narrative logic, publishing read-only render frames to peripheral presentation layers.

How it works

  1. src/main.zig drives the master simulation loop, allocating the World arena and SpatialSystem.
  2. The Virtual Machine steps discrete simulation ticks at a fixed frequency (e.g. 20 Hz or 60 Hz).
  3. DisplayBridge captures double-buffered snapshot frames (RenderFrame) containing entities, waypoints, and dialogue.
  4. Peripheral display renderers (like SDL2 or headless runners) read double-buffered frames and deliver input intents as UserAction events.

Why it works this wayrecorded

Scripting embedded in a frame-driven engine tends to inherit frame-rate dependent logic, garbage collection pauses, and coupling to the renderer. Owning the spine keeps the simulation deterministic, testable without a window, and rewindable.

Evidence

Discrete Simulation Tick Clock

#
timingdeterminismsimulation

Simulation state advances strictly in integer ticks without floating-point delta accumulation.

pub fn step_tick(self: *VM) !void { self.world.current_tick += 1; ... }

What it does

Governs all motor movement, TTL fact expirations, fiber waits, and reactive rule edges using integer tick counters rather than floating-point delta seconds (dt).

How it works

  1. VM.step_tick() increments World.current_tick by 1 on each discrete simulation step.
  2. Fact TTLs decay by integer ticks and are automatically pruned when current_tick exceeds expires_at_tick.
  3. Fibers suspended via wait_ticks or wait_until wake up when the integer tick target is met.
  4. Visual renderers interpolate fractional positions between consecutive ticks for smooth 60 Hz screen motion.

Why it works this wayrecorded

Floating-point delta time introduces accumulation errors, platform-dependent rounding discrepancies, and non-deterministic divergence that destroys replayability and networking. With integer ticks, repeated runs produce identical states; the proof goldens check this on every test run (on Linux x86_64; other platforms are untested).

Evidence

Contiguous Arena Allocation & Zero Raw Pointers

#
memoryperformanceserialization

World state is stored in a fixed byte arena with no internal pointers, so a snapshot copies the fact columns as raw bytes.

pub const World = struct { arena: std.heap.ArenaAllocator, facts: std.MultiArrayList(Fact), ... }

What it does

Houses all simulation entities, relations, and fact rows in contiguous array allocations, referencing entities and strings by integer handles rather than raw virtual memory addresses.

How it works

  1. World initializes an arena allocator with a fixed reserve (e.g. 1 MB).
  2. Facts are stored in Structure-of-Arrays layout via std.MultiArrayList(Fact) with subject, relation, object, and expires_at columns.
  3. Entities are typed 32-bit handles (EntityId) indexing interned string tables.
  4. Serialization (save_state and restore_state) writes and reads raw memory buffers with CRC32 checksums.

Why it works this wayrecorded

Raw pointers break across processes, prevent binary snapshot persistence, and cause cache misses during bulk queries. Flat columns keep queries cache-friendly, and a rewind copies the columns back and rebuilds two name maps rather than reconstructing an object graph.

Evidence

Zero External Dependencies Policy

#
dependenciestoolchainportability

The core simulation runtime, compiler, and VM require zero external C or package dependencies beyond pure Zig.

build.zig: exe = b.addExecutable(.{ .name = "bespoke", .root_source_file = b.path("src/main.zig") });

What it does

The compiler, relational database, bytecode VM, pathfinding, and REPL need only the Zig 0.13 compiler. They are built and tested on Linux x86_64 and wasm32; macOS and Windows builds are written into the template's CI workflow but have never run.

How it works

  1. The compiler front-end uses custom recursive-descent lexing and Pratt parsing written from scratch.
  2. Display rendering optionally links SDL2 as a peripheral consumer, but falls back seamlessly to headless terminal mode if unavailable.
  3. Documentation tools rely exclusively on the Python 3 standard library.

Why it works this wayrecorded

Heavy third-party package dependencies create fragile build pipelines, security supply chain risks, and platform incompatibilities. Zero-dependency design keeps BeSpoke lean, auditable, and easily embeddable.

Evidence

Relational World Database & State

The flat 4-tuple relational knowledge graph that drives systemic entity behaviors and world state.

Flat 4-Tuple Relational Facts

#
factsrelationalstate

World state is composed of relational rows: (subject, relation, object, expires_at_tick).

pub const Fact = struct { subject: EntityId, relation: RelationId, object: i32, expires_at: u64 };

What it does

Replaces traditional object-oriented properties and component hierarchies with flat relational fact tuples representing systemic knowledge, inventory possession, spatial co-location, and emotional states.

How it works

  1. Facts are asserted via World.remember(subject, relation, object, ttl_ticks).
  2. Facts are retracted via World.forget(subject, relation, object).
  3. TTL decay: when ttl_ticks > 0, expires_at is set to current_tick + ttl_ticks.
  4. Pruning: World.prune_expired() scans the facts list at the start of each tick, recording expired rows into a recently_expired ring buffer for expiration hooks.

Why it works this wayrecorded

OOP class hierarchies create rigid coupling where adding a new emergent interaction requires modifying multiple classes. Relational facts decouple subjects from attributes, enabling dynamic pattern queries without schema migrations.

Evidence

Functional Single-Value Property Overwrite

#
relationsfunctionalproperties

Relations marked as functional auto-overwrite previous values on assertion.

const carries = try world.intern_relation("Carries", .set); try world.remember(actor, carries, item, 0);

What it does

Distinguishes between multi-valued relations (e.g. FriendsWith, KnowsSecret) and single-valued functional properties (e.g. Carries, CurrentRoom, Health), automatically retracting old values when a new value is remembered.

How it works

  1. Relations are registered with RelationKind (.set for functional single-value, .bag for multi-value).
  2. When World.remember is called on a .set relation, World scans for any existing fact matching (subject, relation, _) and overwrites its object and expiry in place.
  3. Ensures an entity cannot simultaneously occupy multiple rooms or hold mutually exclusive single states.

Why it works this wayrecorded

Without functional auto-overwrite, script authors would be forced to manually write pair-wise forget statements before every state change, introducing subtle desynchronization bugs when forgetting is overlooked.

Evidence

Multi-Clause Relational Joins & Unification

#
querypattern-matcherunification

Evaluates conjunctive fact patterns across active simulation state with backtracking variable unification.

when CharmedBy(listener, musician) and Carries(listener, loot):

What it does

Queries active relational facts using multi-clause patterns joined by 'and', binding wildcard variables (e.g. victim, loot) and returning matching entity tuples.

How it works

  1. World.find_first_match, has_multi_match, and find_all_matches accept arrays of PatternClause.
  2. Terms can be concrete entities, wildcards, or named variables (PatternTerm.variable).
  3. VariableBindings maintains a scoped mapping of bound entity identifiers.
  4. A backtracking search resolves multi-variable joins across facts in the contiguous MultiArrayList.

Why it works this wayrecorded

Systemic games require querying complex social and physical arrangements (e.g. 'Is an alert guard standing in the same room as a distracted thief carrying gold?'). First-class unification eliminates hardcoded conditional checks.

Evidence

CRC32 Snapshots & Time-Travel Rewind

#
time-travelsnapshotsrewind

Serialization of the complete world state into a memory buffer, with a CRC32 check on restore.

try world.save_state(writer); ... try world.restore_state(reader);

What it does

Captures the entire relational world state into an in-memory byte buffer on each tick, allowing players and developers to scrub backward or forward across history instantaneously.

How it works

  1. World.save_state serializes tick count, interned entity names, relations, and fact columns, appending a CRC32 checksum.
  2. World.restore_state verifies the CRC32 checksum, clears the current arena, and restores memory in-place.
  3. DisplayBridge captures a fresh render frame immediately after restore to synchronize peripheral visualization.
  4. When simulation advances after scrubbing into the past, divergent future snapshots are automatically pruned.

Why it works this wayrecorded

Debugging systemic simulation bugs requires reproducing non-deterministic edge cases. Snapshot rewind lets developers scrub directly to the tick where a state transition occurred, inspect facts, and test alternative actions.

Evidence

Compiler Pipeline & Bytecode Virtual Machine

Source-to-bytecode compilation, stack VM execution, cooperative fibers, and cue dispatching.

Bytecode Instruction Set & Stack Machine

#
vmbytecodeopcodes

Compact stack-based virtual machine executing variable-length bytecode chunks.

pub const Opcode = enum(u8) { push_const, remember, forget, wait_ticks, call_routine, emit_cue, halt, ... };

What it does

Executes compiled BeSpoke programs via a compact bytecode interpreter supporting constants, relational mutations, math, routine calls, cues, and control flow.

How it works

  1. BytecodeChunk stores an array of byte opcodes and a pool of 32-bit constants.
  2. VM evaluates instructions using an operand stack per fiber.
  3. Relational opcodes (op_remember, op_forget, op_query) operate directly on the World database.
  4. Execution is bounded per tick by max_steps_per_fiber to prevent runaway loops from freezing the engine.

Why it works this wayrecorded

Direct AST evaluation has poor cache locality and high tree-walking overhead. A flat bytecode chunk executes in a tight loop and allows serialization of fiber instruction pointers.

Evidence

Cooperative Fiber Scheduler & Temporal Suspension

#
fibersschedulerconcurrency

Fiber-based routine execution suspended across ticks via wait_ticks and wait_until.

pub const Fiber = struct { id: FiberId, entity: EntityId, ip: usize, wait_ticks: u32, ... };

What it does

Executes actor routines concurrently within a single simulation thread using lightweight fibers that yield voluntarily when waiting for time or events.

How it works

  1. VM maintains an active list of Fiber descriptors, each with its own instruction pointer, call stack, and operand stack.
  2. Instructions like wait_ticks set fiber.wait_ticks, suspending the fiber until the specified tick delay elapses.
  3. wait_until evaluates a relational condition pattern each tick and resumes when satisfied.
  4. On each simulation tick, VM steps all active, non-waiting fibers up to their yield points.

Why it works this wayrecorded

Operating system threads introduce non-deterministic race conditions, locks, and heavy memory overhead. Cooperative fibers run in a fixed order on one thread, cost nothing while waiting except their stored state, and serialize cleanly.

Evidence

Recursive-Descent Lexer, Parser & Codegen

#
compilerlexerparsercodegen

Compiles high-level narrative DSL script text directly into bytecode chunks and reactive rule tables.

pub fn compile_source(allocator: Allocator, world: *World, spatial: ?*SpatialSystem, source: []const u8) !CompiledProgram

What it does

Transforms plain-text BeSpoke game scripts into executable bytecode, registering entities, relations, stage marks, hotspots, routines, cue handlers, and reactive when rules.

How it works

  1. src/compiler/lexer.zig scans source into tokens, handling Python-style indentation (indent/dedent), keywords, and comments.
  2. src/compiler/parser.zig builds an Abstract Syntax Tree (ProgramAst) containing routines, cues, stageplay declarations, and rules.
  3. src/compiler/codegen.zig lowers the AST into BytecodeChunk instructions, populates entry-point lookup tables, and builds CompiledWhenRule arrays.

Why it works this wayrecorded

Writing narrative simulations in raw Zig or assembly is tedious for game designers. The BeSpoke DSL provides clean theatrical syntax while compiling to zero-overhead bytecode.

Evidence

Cue Event Dispatch & Priority Interruption

#
cueseventsinterrupts

Discrete event cues trigger routine fibers with priority-tiered preemption stacks.

vm.fire_cue(compiled, "Uses", actor, target_a, target_b);

What it does

Delivers external player interactions and systemic world events to registered cue handlers, preempting lower-priority routines and cleanly resuming them upon completion.

How it works

  1. Cues are emitted via VM.fire_cue, which asks CompiledProgram.select_cue_handler for the most specific matching handler whose where guard holds, with the handler's variable parameters bound to the cue's arguments; a failed guard falls through to the next, less specific handler (D-072).
  2. When an interrupt occurs (e.g. thief alert), the entity's active fiber is pushed onto an interrupt stack.
  3. The higher-priority handler executes to completion.
  4. Opcode resume_routine pops the interrupted fiber state, restoring its instruction pointer and continuing its original routine.

Why it works this wayrecorded

Standard event callbacks discard context, forcing actors to restart tasks from scratch after an interruption. Priority stacks let NPCs react urgently to emergencies and then smoothly resume their previous actions.

Evidence

Two-Operand Inventory Combining & Commutative Cues

#
inventorycombiningcuescrafting

Supports 3-argument in-hand item combinations with automatic commutative parameter matching.

on cue Uses(Player, ItemA, ItemB): ... // Matches ItemA on ItemB and ItemB on ItemA

What it does

Enables classic adventure game item combining in hand (e.g. using MapleSyrup with CatHairTape) where applying item A to B is functionally identical to applying B to A.

How it works

  1. Codegen registers composite signature keys: Uses:Actor:ItemA:ItemB and the commutative permutation Uses:Actor:ItemB:ItemA.
  2. CompiledProgram.find_cue_handler checks ternary commutative signatures, falling back to binary and unary forms.
  3. VM.fire_cue resolves entities, matches the handler PC, records an EmittedCue for display peripherals, and spawns the executing routine.
  4. DisplayWindow tracks selected_inventory_item, highlighting the tray item and emitting combine_inventory_items on a second item click.

Why it works this wayrecorded

Requiring narrative designers to author two identical script handlers for every combination is error-prone and redundant. Built-in commutativity guarantees symmetric interaction.

Evidence

Spatial System & Navigation

2D topological waypoint graphs, discrete room graphs, A* pathfinding, and screen layout algorithms.

Waypoint Node Graphs & Topological Pathfinding

#
spatialwaypointspathfindinga-star

Spatial environments are modeled as discrete 2D waypoint graphs with A* shortest-path routing.

pub const WaypointGraph = struct { waypoints: std.ArrayList(Waypoint), edges: std.ArrayList(Edge), ... };

What it does

Defines rooms and navigable ground locations as integer-coordinate waypoint nodes connected by bidirectional edges, calculating walking paths via discrete A* search.

How it works

  1. SpatialGraph stores waypoints with room IDs, integer coordinates (x, y), and names.
  2. Edges represent unobstructed walking paths between waypoints.
  3. SpatialGraph.find_path computes the shortest sequence of waypoints using Manhattan/Euclidean integer heuristics.
  4. Actors traverse edges step-by-step at discrete velocities.

Why it works this wayrecorded

Continuous 3D physics sandboxes require complex collision meshes and floating-point math that destroy determinism. Topological waypoint graphs fit narrative graphic adventures and keep pathfinding small and deterministic.

Evidence

Asynchronous Motor Intents & Walking

#
movementmotor-intentagents

Actor movement is non-blocking and driven by motor intents updated on simulation ticks.

spatial.walk_to(actor, target_waypoint_id);

What it does

Initiates autonomous, asynchronous movement for an agent across the waypoint graph without stalling other fibers or game simulation logic.

How it works

  1. SpatialSystem.walk_to assigns a target destination and generates a path queue for the agent.
  2. SpatialSystem.update advances agent coordinates toward their next waypoint each tick.
  3. When the final waypoint is reached, agent.is_moving is set to false and arrival events fire.

Why it works this wayrecorded

Blocking sleep calls inside entity scripts lock the main thread. Asynchronous motor intents allow actors to navigate while continuously listening for sensory events and dialogue interruptions.

Evidence

Interactive Hotspots & Scene Props

#
hotspotspropsinteraction

Static interactive objects in the environment with spatial hitboxes, examination text, and verb hooks.

spatial.register_hotspot(room, x, y, radius, "Flags", "A pair of starting flags.");

What it does

Registers interactive scene scenery and props (e.g. Fireplace, Wine Cask, Flags) with radial click hitboxes, examine descriptions, and verb cue triggers.

How it works

  1. SpatialSystem.register_hotspot interns the hotspot entity and stores its room, coordinates, and radius.
  2. DisplayWindow hit-tests mouse coordinates against active hotspots via hit_test_hotspot.
  3. Clicking a hotspot emits interact_hotspot with the active verb (.look_at, .use_with, .talk_to, .pick_up).

Why it works this wayrecorded

Treating scenery as first-class entities allows them to participate in relational facts (e.g. Tampered(Flags, 1)) and reactive when rules alongside living actors.

Evidence

Actor Standoff Separation & Non-Overlapping Labels

#
layoutstandoffrenderinglabelscollision-avoidance

Automated 60px horizontal separation, priority-based 2D text layout solver, and standardized scale hierarchy prevent label collision.

pub const TextLayoutResolver = text_layout.TextLayoutResolver;
pub fn get_entity_screen_layout(idx: usize, entities: []const RenderEntity, w: i32, h: i32) EntityScreenLayout

What it does

Solves the visual crowding problem when multiple actors occupy the exact same waypoint or proximate stage marks by combining actor horizontal standoff spacing with a centralized 2D collision-avoidance label layout engine.

How it works

  1. get_entity_screen_layout groups entities within 32 pixels into a spatial cluster and spreads them horizontally by ±30px.
  2. TextLayoutResolver collects all floating in-world labels (actor names, status badges, waypoint names, hotspot prompts) and registers actor and waypoint tokens as physical obstacles.
  3. Labels are sorted and placed in descending priority order (hover tooltips = 10, actor alerts = 9, actor names = 8, actor statuses = 7, waypoints = 6/2, props = 1).
  4. Actor names use font scale 2 above tokens; actor status badges use font scale 1 below tokens, cutting width by 50% to establish a clean visual hierarchy.
  5. Contested labels automatically stagger downward across vertical tiers (Tiers 1-3) or flip above, while idle waypoint names yield to preserve legibility without hiding the physical ground mark.

Why it works this wayrecorded

In theater and adventure scenes (e.g. Tamsin and Judge Marrow at the Chalk Line, or Tamsin and Cudgel on Lamp Point), actors frequently gather at proximate marks. Drawing labels at fixed coordinates produces illegible text overlap. Centralized collision resolution guarantees every string a legible, collision-free slot.

Evidence

Multi-Scene Graph Partitioning & Transitions

#
scenestransitionsspatialpartitioning

Spatial waypoints and props partition by scene while global facts persist across transitions.

pub fn transition_actor(self: *SpatialSystem, entity: EntityId, target_room: EntityId, entry_wp: ?WaypointId) !bool

What it does

Partitions spatial waypoints and interactive hotspots across distinct narrative scenes and rooms, allowing actors to transition between environments via transition to scene statements.

How it works

  1. Waypoints and hotspots store room EntityIds, scoping navigable nodes and interactables to the active scene.
  2. The compiler AST groups cast, props, and marks under each scene declaration, registering them under the scene entity.
  3. Executing transition to scene updates vm.current_scene, pauses ambient fibers of the previous scene, and wakes target scene fibers.
  4. SpatialSystem.transition_actor relocates actors onto the designated or primary entry waypoint of the new room.
  5. All relational facts in World (inventory, causal puzzle state) persist continuously across scene changes.

Why it works this wayrecorded

Destroying world state on room transitions loses cross-scene inventory and puzzle facts, while a single monolithic coordinate space clutters the screen and leaks ambient events across distant rooms. Partitioned spatial graphs with continuous relational facts give clean scene encapsulation with zero serialization overhead.

Evidence

Discrete Grid Overlay

#
gridspatialcellshazards

An optional per-room grid whose cell attributes and fire, smoke, and water automata live in World facts.

grid <Name> in <Room>:  size W H  cell N  [origin X Y]  flammable|liquid|blocking x y [w h]  place <Mark> x y

What it does

Overlays a room with a discrete grid of cells carrying flammable, liquid, and blocking attributes, and maps each waypoint to the cell under its position.

How it works

  1. src/grid.zig defines Grid geometry (room, width, height, cell size, origin); SpatialSystem.grids holds at most one overlay per room.
  2. Each set attribute is a CellFlammable, CellLiquid, or CellBlocking fact on the grid entity whose value is the cell index y*W+x; empty cells have no facts.
  3. A grid script declaration compiles into CompiledProgram.grids; host.initialize_subsystems seeds the layout once and marks it with GridSeeded.
  4. place moves a mark to a cell centre and refreshes its edge costs; SpatialSystem.waypoint_blocked treats a blocking cell like WaypointBlocked for world-aware walks.
  5. .bspk version 7 stores grids; versions 1 through 6 load without them.
  6. Rates burn, spread, dissipate, and flow drive grid.step each host.tick: fires are CellBurning facts whose TTL is their remaining burn, smoke is CellSmoke refreshed by each fire, and liquid floods non-blocking neighbours and douses fire.
  7. All ignitions and floods are decided from the start-of-step state before any applies; agents then carry InBurningCell, InSmokeCell, and InLiquidCell states that when rules react to on the next tick.

Why it works this wayrecorded

Fire, flooding, and line-of-sight need area state that a sparse waypoint graph cannot express, while adventure scenes still navigate by waypoints. Keeping cell attributes in World facts lets save, rewind, and temporal branches carry hazard state with no new snapshot channel, and storing only set attributes keeps the fixed-capacity fact table small.

Evidence

Continuous Reactive Simulation Engine

Autonomous pattern-matching rule cascades, edge-triggered transitions, and fact expiration hooks in the VM.

Continuous When Rule Pattern Matching

#
reactiverulespattern-matching

Rules are checked against the world's facts on every tick and fire interrupts without any script polling for them.

when currently Wind is blowing: loop: animate wind-blowing

What it does

Provides declarative rule evaluation inside the engine spine: whenever world state matches the rule's relational pattern, the VM triggers associated behavior routines automatically.

How it works

  1. Codegen compiles when clauses into CompiledWhenRule records with pattern clauses, priority, and entry PC.
  2. VM.evaluate_reactive_rules checks rules on tick boundaries or following fact mutations.
  3. Pattern matches are verified against World using multi-clause relational unification.

Why it works this wayrecorded

Polling inside entity scripts creates bloated boilerplate, missed frame events, and CPU thrashing. Built-in reactive evaluation fires a rule on the tick its condition first holds, with no polling code in scripts.

Evidence

Edge-Triggered State Transitions (Rising & Falling)

#
edge-triggeredrising-edgefalling-edge

Fires rule handlers on state boundary transitions (false -> true and true -> false).

when Wind stops being blowing: stop animate wind-blowing

What it does

Distinguishes between continuous state and transitional edges, firing rising-edge handlers on positive transition and falling-edge handlers on negative transition without repeated triggers.

How it works

  1. ReactiveRule tracks was_active from the preceding tick.
  2. Rising edge fires when was_active is false and the pattern match becomes true.
  3. Falling edge (when X stops being Y) fires when was_active was true and the condition becomes false.
  4. Re-arming occurs automatically once the condition clears.

Why it works this wayrecorded

Continuous level-triggered rules would re-execute every tick while a condition remains true, spawning runaway fibers. Edge-triggering ensures handlers fire exactly once per state transition.

Evidence

TTL Fact Expiration Hooks (when forgets)

#
ttlexpirationhookslifecycle

Fires reactive routines when temporary timed facts expire naturally from the world database.

when Organiser forgets Distracted: walk Organiser to Starting Line

What it does

Allows scripts to react to the natural decay of temporary facts (e.g. distraction timers, charmed status, temporary alerts) without requiring manual bookkeeping or timers.

How it works

  1. When World.prune_expired removes a fact whose TTL has elapsed, it copies the row into a recently_expired buffer.
  2. VM evaluates on_expire reactive rules against recently_expired during the tick step.
  3. Matches trigger interrupt routines (e.g. Organiser walks back to the starting line after crowd distraction ends).

Why it works this wayrecorded

Manual timer countdown routines in scripts are error-prone and hard to synchronize with world state. Integrating expiration into the fact store means an expiry and its rule fire on the same tick every run.

Evidence

Arrival Rules (when arrives at)

#
arrivalmarkswalkinghooks

Fires a reactive routine when an actor completes a walk at a named mark.

when Tamsin arrives at HatchMark: transition to scene: Wreckers Cellar

What it does

Lets a script react to an actor reaching a mark, so rules such as a guard animal charging whoever reaches a doorway live in the script and not in host code. The rule fires once per completed walk. Resting on the mark, walking through it toward another mark, and being placed there by the host do not fire it.

How it works

  1. The parser reads when <Actor> arrives at <Mark>: and rejects an undeclared mark or a missing 'at' with line and column.
  2. Codegen emits a reactive rule with the on_arrive edge and one clause holding the actor and the mark's waypoint id.
  3. MotorAgent raises arrival_pending when a walk intent completes, including a walk to the mark the actor already stands on.
  4. VM.evaluate_reactive_rules checks arrival rules after the motor steps in the same tick, interrupts the actor's routine (or spawns one), then clears every pending arrival.

Why it works this wayrecorded

A host loop that polls an actor's waypoint each tick is a level check: it re-fires while the actor stands still and keeps game rules outside the script. An edge fired inside the tick needs no host dispatch, so every host gets the same behaviour.

Evidence

Priority Rule Cascades & Preemption

#
prioritypreemptioninterrupts

Rules with higher priority preempt lower-priority routines and restore them upon completion.

active_priority: u8, interrupt_entity_priority: [16]u8

What it does

Enforces behavioral priority hierarchies among reactive rules (e.g. theft alarms supersede charming melodies, which supersede idle wandering).

How it works

  1. Each CompiledWhenRule carries a priority value (default 0, higher numbers indicate greater urgency).
  2. VM checks if rule.priority > vm.active_priority before interrupting an entity.
  3. The active fiber is pushed onto an interrupt stack.
  4. When the high-priority routine completes, the VM pops the previous routine and continues execution.

Why it works this wayrecorded

Without priority stacks, any incidental event could permanently overwrite a critical reaction (such as a guard failing to raise an alarm because an idle bard started playing a song).

Evidence

State Inspector: Facts, Dialogue, and Deadlines

#
inspectordebugfactsbeliefsdialoguettl

A paused view of relational state, dialogue availability and pruning reasons, and the next fact deadlines.

[P] then [Tab] to STATE; arrows, Enter, Backspace, Home, F

What it does

Draws the selected entity and its relationships, lists values and states, explains which dialogue branches are active or pruned, and orders upcoming fact expirations.

How it works

  1. DisplayBridge.capture_frame copies up to 128 facts per frame with subject and object ids, whether the object names an entity, and the facts that just expired.
  2. state_graph.default_focus picks the entity with most edges; state_graph.build places it in the centre and its neighbours on a ring in entity-id order.
  3. Facts whose object is an entity are arrows; Believes, Knows, and Rejects arrows are purple; value and state facts are listed beside the graph.
  4. Colours: white permanent, then green, amber, and red as fewer than 60 and 20 ticks remain, grey for just expired.
  5. Newly compiled choice blocks write source-order DialogueBranch facts. Active branches are green; pruned branches are red and show the first guard that failed. Generated and older sets show their offered choices as active.
  6. state_graph.next_expiring sorts the next six captured live TTL deadlines by expiration tick and stable fact identity; it does not execute future ticks.
  7. The inspector is the third tab of the P drawer, so the game is paused; Enter, digits, and Space never save or load there.
  8. Left and Right select a ring node; Enter or a click centres on it, Backspace returns through up to eight earlier centres, and Home resets. F cycles the filter: all, beliefs, then each relation in the frame. Navigation is window state and never enters a save.

Why it works this wayrecorded

A text list cannot show how state connects or why a conversation option disappeared. Persisting branch diagnostics as World facts keeps the explanation correct after save, rewind, and temporal restore; projecting only known deadlines keeps the inspector read-only and deterministic.

Evidence

Typed Commands: Words, Frames, and Nouns

#
parsertextcommandsvocabulary

The vocabulary that turns a typed line into a cue and the entities it names.

command <Cue>: "verb <thing> prep <thing>"   alias <Entity>: "phrase", "phrase"

What it does

Lets players type commands such as pour grog into mug: input becomes words, a frame names the cue, and each noun resolves to an entity the actor can see or holds.

How it works

  1. command.tokenize lowercases input and drops punctuation and the articles a, an, the; prepositions such as with, into, and about are kept.
  2. A frame is lowercase words with up to two <thing> slots; the engine provides frames for LooksAt, Uses, TalksTo, and WalksTo, and script command lines add more.
  3. An entity's name splits into words at capitals and separators, and alias lines add words; a noun matches when all its words belong to the entity.
  4. Scope.gather collects agents, hotspots, and marks in the actor's room plus what it Carries or holds InInventory; resolve reports one match, several, or none.
  5. .bspk version 10 stores command and alias declarations.
  6. command.Interpreter matches script frames before the defaults, resolves each slot in scope, and keeps one open Which do you mean question that a following bare noun answers.
  7. host.run_command fires the matched cue, walks for WalksTo, and returns a reply when a word is unknown, a sentence or noun does not fit, or no handler answers (Nothing happens).
  8. DisplayWindow.enable_command_bar shows a bar above the verb row: Enter focuses it, every key is then text, Esc leaves, Up and Down recall history, and Tab completes from host.command_words; submitted lines arrive as UserAction.typed_command.

Why it works this wayrecorded

Proofs name their own cues, so typed commands need script-owned verbs on top of a few shared defaults. Resolving nouns only in scope keeps typed commands from reaching what the player cannot see, and refusing to guess between two matches keeps the parser predictable.

Evidence

Agendas: Proactive Social Agency

#
agencyagendanpcomission

Script-declared intentions that set an NPC pursuing a target when facts hold or are missing.

agenda <Name>:  actor A  target T  [priority N]  [cooldown N]  [once]  requires Rel(A, B)  unless Rel(A, B)

What it does

Lets an NPC react to what the player did, or failed to do, by starting to pursue them; the engine chooses which agendas pursue and keeps their stages as facts.

How it works

  1. An agenda declaration compiles into CompiledProgram.agendas; requires lines must hold, unless lines must not, with names or _ wildcards.
  2. Each agenda entity carries AgendaState(Agenda, Idle | Pursuing | Done); cooldowns are AgendaCooldown facts that expire after N ticks.
  3. agency.step runs in host.tick: a pursuing agenda whose trigger lapses returns to Idle, and for each target one triggered agenda starts pursuing, chosen by priority, then route cost, then declaration order.
  4. agency.resolve ends a pursuit: once agendas become Done, others return to Idle with their cooldown.
  5. .bspk version 9 stores agendas.
  6. agency.pursue walks each pursuer to its target's last waypoint, re-planning when the target reaches a new one; once both stand idle on one waypoint the agenda resolves and host.tick fires Intercepts(Actor, Target, Agenda).
  7. A Pursuing(Actor) fact holds while an actor pursues, and Society routines do not move an actor that holds it.

Why it works this wayrecorded

Wandering characters on fixed schedules only answer when asked. Agendas let them act on player behaviour, including omissions, while every stage stays in the fact store so saves, rewinds, and branches carry it, and constant trigger lines avoid changing the reactive rule engine.

Evidence

Narrative DSL & Adventure UI

High-level theater declarations, natural language state transitions, verb interfaces, and dialogue trees.

Declarative Stageplay Syntax & Taxonomy

#
dslstageplaysyntax

Theater-like script headers declaring scenes, cast, props, marks, and natural state assertions.

scene: Pip-Spitting Green; cast: Tamsin, JudgeMarrow; props: Pegs; marks: Chalk Line

What it does

Allows authors to declare game environments using natural stageplay vocabulary (scene, cast, props, marks) and transition states using readable sentences (now Flags are tampered with).

How it works

  1. Parser registers cast members as actor agents, props as hotspots, and marks as spatial waypoints automatically.
  2. State declarations ('now X is Y' and 'now X is not Y') are lowered directly into World.remember and World.forget operations.
  3. Natural state queries ('if Flags are Tampered With:') compile to relational database queries.

Why it works this wayrecorded

Requiring narrative designers to write low-level registration functions and numeric IDs causes cognitive friction and high bug rates. Natural stageplay syntax reads like a screenplay while compiling to fast bytecode.

Evidence

Stageplay Paths & Route Pruning

#
dslpathsroutespruningtopology

Named operational approaches own fact assertions and guarded routines; PathActive prunes dialogue and WaypointBlocked facts lock spatial waypoints.

path Wits: remember WaypointBlocked(BackAlley)  |  VM.select_path(compiled, "Wits")

What it does

Adds top-level path blocks for mutually exclusive narrative approaches. A path owns its initial fact statements and routines, and only the selected route can run them. A path can also lock waypoints, assert obstacle facts that feed portal access, and prune rival dialogue repertoires.

How it works

  1. The parser accepts path Name: blocks containing remember, forget, and now statements plus nested routines.
  2. VM.select_path asserts PathActive(Name) in World facts and spawns the reserved #path:<Name> initializer, which runs on the next tick.
  3. Every path-owned routine starts with a PathActive(Name) guard and halts before its body when another route is active.
  4. WaypointBlocked(Mark) facts are read by SpatialSystem.walk_to_with_world, which asks A* to exclude each locked waypoint when a scripted walk is planned.
  5. Path initializers can assert existing obstacle predicates such as Trapped or PortalBlocked; can_access_portal reads current World facts. choice ... if PathActive(Name) prunes route-specific dialogue.
  6. The existing .bspk routine and relation tables carry path initializers without a format bump; save and rewind restore the selected route and its topology effects as ordinary facts.

Why it works this wayrecorded

Operational approaches in multi-path adventures must prune incompatible puzzle branches without host-language flags. Keeping the route, waypoint locks, and obstacle facts in World facts preserves determinism, saves, and rewind; routine-local guards mute alternatives even when a host spawns them directly.

Evidence

Three-Path Saltmarket & Route Selector

#
pathstopologydialogueselectorsaltmarket

A generated selector chooses Cunning, Muscle, or Crew; each path locks the rival gates, prunes Broker Quince's dialogue, and runs only its own solution.

path Cunning: remember WaypointBlocked(MuscleGate)  |  VM.select_path(compiled, "Cunning")  |  --saltmarket

What it does

The Saltmarket proof stages Broker Quince's market as one spatial graph with three gates. The selected path asserts WaypointBlocked facts on the two rival gates, so the same walk plans through the chosen approach, and PathActive guards reduce Quince's dialogue to the matching clue plus a neutral exit.

How it works

  1. The script declares path Cunning, path Muscle, and path Crew, each with route facts and a Solve... routine.
  2. A generated dialogue opens three selector options in the native window; clicking one or pressing 1 to 3 calls VM.select_path.
  3. The path initializer runs on the next tick, locks the rival gates, and records Chosen(Tamsin, <Path>).
  4. Scripted walks call SpatialSystem.walk_to_with_world, so A* plans around the locked gates and reaches LogbookMark through the open route.
  5. Talk offers only the selected path's choice plus the neutral exit, and [S] runs only that path's solution routine.

Why it works this wayrecorded

Multi-path adventures need one topology and one dialogue source that reshape themselves around an operational choice. Keeping the choice, gate locks, and obstacle facts in World facts means saves, rewinds, and snapshots carry the whole route without a host-side branch table.

Evidence

Classic 5-Verb Interaction Bar

#
verbsuiinteraction

Five classic adventure verbs: WALK, LOOK, TALK, TAKE, USE with active button highlight and right-click cycling.

pub const AdventureVerb = enum(u8) { walk = 0, look_at = 1, talk_to = 2, pick_up = 3, use_with = 4 };

What it does

Implements the foundational SCUMM-inspired adventure interface: players choose a verb via the bottom HUD bar or right-click cycling, then click objects, actors, or waypoints in the scene.

How it works

  1. DisplayWindow renders verb buttons in the bottom HUD bar, highlighting the active verb in amber gold.
  2. Right-click cycles active_verb through the enumeration.
  3. Left-click evaluates hit testing: waypoints trigger walk_player, actors trigger interact_actor, and hotspots trigger interact_hotspot.

Why it works this wayrecorded

Direct point-and-click single-verb interfaces lack expressiveness. The 5-verb system empowers players to inspect, converse, take, and use objects systemically.

Evidence

Branching Dialogue Trees & Dynamic Choice Pruning

#
dialoguespeechballoonschoicespruning

A wrapped dialogue panel with the speaker's name, the line, and relational fact-guarded choices that suspend the script until selection.

choice "Book a berth" if Carries(Tamsin, Papers): say PurserWick: "Ticket."

What it does

Shows the open dialogue in a parchment panel centred above the bottom of the stage and as wide as its text: the speaker's display name, the line word-wrapped at 60 characters, and numbered choices that wrap and grow the panel upward, with a scroll bar past six and keyboard hotkeys (1-9). The window and the browser draw the same layout (D-077, D-084).

How it works

  1. dialogue_panel.layout wraps the speaker, prompt, and choices into rows for a panel width and font scale, and reports each choice's vertical span; it has no SDL dependency, and the desktop and the browser draw it with the same window code (D-097).
  2. dialogue_panel.display_name splits CamelCase entity names for display (BosunPike reads Bosun Pike).
  3. Fibers executing choice blocks evaluate relational guards, record the eligible options as World facts, and suspend until a selection resumes the chosen body.
  4. The renderer displays numbered hotkey labels [1] through [9] and supports mouse clicks on any row of a choice, mouse wheel scrolling, and number keys 1-9; the browser answers clicks and number keys.
  5. The open set lives in World facts, so snapshots and rewinds carry it; RenderFrame.dialogue publishes it to the balloon by revision.
  6. Dismissing a balloon or choosing an option emits dialogue_choice or dismiss_dialogue user actions.
  7. A host can queue click-through messages (queue_message, D-080): each shows alone in the panel's place with a continue hint, a click, Enter, or Space dismisses it, and the choices beneath stay hidden and unanswerable until all are read.

Why it works this wayrecorded

Hardcoding dialogue choices in host language ladders causes script fragmentation and breaks time-travel rewinds. Fact-guarded choice trees declared in DSL prune systemically based on active inventory and knowledge facts.

Evidence

In-Hand Tray Selection & Crafting UX

#
inventoryin-handcraftingux

Two-step inventory click flow with golden highlight, in-hand status prompts, and combining feedback.

selected_inventory_item: ?usize = null; UserAction.combine_inventory_items

What it does

Provides an intuitive point-and-click inventory crafting experience: clicking an item selects it into hand, displaying a golden glow, while subsequent clicks apply it to scene targets or combine it with another inventory item.

How it works

  1. Clicking an inventory item sets selected_inventory_item and switches verb to USE, displaying '[IN HAND: Item]' and banner prompts.
  2. The selected item renders with an amber background (rgb 85, 65, 25) and a glowing golden double border (rgb 250, 204, 21).
  3. Clicking a different item emits combine_inventory_items.
  4. Clicking an actor emits use_inventory_on_actor; clicking a hotspot emits use_inventory_on_hotspot.
  5. Right-click cancels in-hand mode with an 'Action cancelled' banner.

Why it works this wayrecorded

Classic multi-step puzzles (like The Borrowed Beard) require crafting composite items before using them in the world. Visual in-hand indicators make the player's intent crystal clear.

Evidence

The Borrowed Beard Scenario

#
beardscenariocraftingmulti-scenedialogue

Multi-scene vertical slice demonstrating ambient routines, in-hand crafting, fact-guarded dialogue pruning, and disguise evaluation.

zig build run-proof -- --borrowed-beard [--headless]

What it does

Implements the classic multi-step disguise puzzle across three partitioned scenes (Inn Landing, Net Loft Yard, Harbour Office), combining borrowed sailing papers, a taped gate gap, a watering can, honey adhesive, and fact-guarded dialogue choice validation.

How it works

  1. Declares three partitioned scenes with distinct waypoints, marks, hotspots, and ambient actor routines.
  2. Uses two-operand inventory combining (Uses(Tamsin, DogFur, HoneyPot)) to craft composite items.
  3. Evaluates composite disguise validity via relational fact conjunctions (papers, fur, honey, charcoal).
  4. Runs dialogue choice pruning when talking to Purser Wick, granting the berth ticket only when the disguise condition holds.

Why it works this wayrecorded

Proves that BeSpoke's engine spine effortlessly coordinates complex adventure game logic across multiple scenes, ambient actor schedules, dynamic fact guards, and time-travel snapshot state without custom ad-hoc engine extensions.

Evidence

The Donkey of Lamp Point Scenario

#
donkeylamp-pointthreat-radiustiming-windowmulti-scene

A threat-radius interrupt, a 30-tick retreat window, hauling an obstacle into a rope line, and a move down to a lower scene, each step an arrival rule.

zig build run-proof -- --lamp-point [--headless]

What it does

Tamsin must reach the wreckers' cellar under the ruined lighthouse on Lamp Point, past Cudgel, the keeper's donkey, who is tied to a mooring post by a long rope. The proof models a guard animal that charges, a knockback interrupt, a 30-tick retreat window, hauling an old anchor into the rope line to tangle it, and the move down into the cellar.

How it works

  1. Arriving at the hatch while Cudgel's rope is free fires the arrival rule: Cudgel shoves Tamsin back to FallMark and the script remembers DonkeyRetreating for 30 ticks.
  2. Arriving at the anchor while that fact holds tangles the rope around the anchor; arriving without it only explains that Cudgel would kick first.
  3. Arriving at the hatch with the rope caught transitions to the Wreckers Cellar; walking back to CellarSteps climbs out.
  4. The art draws the rope from the post to Cudgel, or wrapped round the anchor once it is caught.

Why it works this wayrecorded

Demonstrates that BeSpoke's relational facts and discrete ticks express a timing puzzle deterministically: the window is a fact with an expiry tick, not a frame-rate timer, so the headless run and the window agree on every step.

Evidence

The Well of Three Tides: Three Players in Three Eras

#
three-tidesmulti-partyitem-transferepistemic-dialoguetemporal-causalitytime-travel

Multi-character party switching, generalized inventory transfers across actors, epistemic dialogue belief pruning, and DAG temporal causality cascades across 400 years.

zig build run-proof -- --three-tides [--headless]

What it does

Ossie in 1712, Nell in 1912, and Juno in 2112 pass items through Doctor Brine's Tide Wells across the Charter Yard, the Boarding House, and the Gull Roost: port sealed in a cornerstone box comes out two centuries later as vinegar, and a tree felled in 1712 is gone in 2112.

How it works

  1. Tracks party coordination via party array and active_character, rendering top HUD character portrait buttons for instant protagonist switching.
  2. Executes generalized inventory item transfer (World.transfer_item) via atomic relational swaps, enforcing matter conservation without pointer manipulation.
  3. Evaluates NPC dialogue options through epistemic belief facts (Believes, Knows, Rejects), pruning Persuade choices dynamically until supporting evidence is established.
  4. Enforces strict past-to-future DAG causality cascades where past physical modifications (painting a tree, sealing port in a cornerstone box, sewing a banner) instantaneously project forward across present and future eras.

Why it works this wayrecorded

Demonstrates that BeSpoke's relational fact engine, fiber scheduler, and discrete tick clock natively support non-linear multi-protagonist agency and historical causality without paradoxical state duplication or ad-hoc temporal flags.

Evidence

Branch Worlds (Temporal Hypervisor) & Path Previews

#
weathercockhypervisorbranch-worldvector-conduitstime-travel

A temporary copy of the world that runs on a countdown and either merges back or is discarded, plus precomputed path lines drawn ahead of an actor.

zig build run-proof -- --weathercock [--headless]

What it does

TemporalHypervisor forks the primary World into a temporary branch world with a countdown. The branch merges back when its closure condition holds, or is discarded when the countdown runs out. The Copper Weathercock proof uses it for a time-loop puzzle.

How it works

  1. fork_branch copies the primary World with World.clone() and starts a countdown of collapse_budget_ticks.
  2. Each step_tick advances the branch one tick and runs check_loop_closure: the keystone entity must stand on the convergence waypoint and a ConvergenceReady or LoopClosed fact must hold (D-073).
  3. On closure, collapse_branch commits the keystone and any recorded residue facts to the primary World (resolved_and_merged). If the countdown runs out first, the branch is discarded (budget_expired) and the player rewinds.
  4. SpatialSystem.get_agent_vector_conduit precomputes an actor's A* route as a polyline that the renderer draws as a preview line.
  5. VM.spawn_hyper_temporal_routine starts a routine at priority 255 so a guide character's lines cannot be preempted.
  6. Hosts register cause-to-effect edges between relations with register_teleological_dependency. is_teleologically_justified follows them (a bounded search, so a cycle terminates), and is_novikov_consistent rejects an action that the edges lead to a paradox, or any action while the actor holds the paradox (D-073).

Why it works this wayrecorded

A branch that is a full World copy needs no special rules for which facts it may touch: everything inside it is ordinary facts, and save, rewind, and the inspector treat it like the primary World (D-048, D-049). D-044 gives the mechanism neutral names so other games can use it.

Evidence

Musical Drafts and The Bell Tower Scenario

#
draftsdistaffaudioreversalcuesbell-tower

Four-note pitch drafts declared in the DSL, played on a distaff, reversed for complementary effects, and dispatched through Weave cues.

draft Kindle(C, D, E, C) reverse Douse  |  weave Kindle on Beacon  |  zig build run-proof -- --bell-tower [--headless]

What it does

Adds pitch-based spellcraft: draft declarations name four-note sequences over C to B, weave statements and player note input cast them on targets, and the original Bell Tower slice teaches drafts by observation and gates the high notes behind the distaff's reach.

How it works

  1. The parser rejects malformed drafts and any sequence that matches another draft forward or reversed, so a played phrase names at most one draft; a declared reverse becomes its own table entry.
  2. VM.weave_notes resolves played notes and runs the exact Weave(caster, draft, target) handler, or records a WeaveFizzled cue; in-script weaves queue until the host calls dispatch_pending_weaves after each tick.
  3. DistaffInput holds the phrase in progress and the reach limit host-side, never in the world arena; the display bridge copies it into RenderFrame.distaff for the staff HUD, and notes sound through AudioEvent.play_note.
  4. The Bell Tower requires reversing a taught draft (Bind into Loose), extends reach with the tuning fork, and lights the beacon from inside the Toll handler through host re-dispatch.

Why it works this wayrecorded

Drafts reuse the verb-as-cue path and the relational store instead of adding a parallel spell system, so effects stay scriptable, rewindable, and testable headless.

Evidence

Container Degradation and The Caustic Grog Sprint

#
containersdegradationttlspillpourscaustic-grog

Script-declared vessels lose volume through movement spill and advance through ordered TTL damage stages to a terminal failure location, while atomic pours conserve every remaining measure.

degradation CausticGrogCups: stage GrogSound 4 ... vessel CupA 10 10 GrogSound  |  spill 1  |  zig build run-proof -- --grog [--headless]

What it does

Adds fact-backed container lifecycles: a top-level degradation declaration names a substance, ordered damage stages with exposure durations, vessels with capacities and starting stages, and a per-tick spill rate. The original Caustic Grog sprint carries corrosive grog from a dockside barrel to a prison lock before three cups dissolve.

How it works

  1. ContainerSystem.init validates the declaration, interns its fact vocabulary, and seeds each vessel's stage, volume, and exposure deadline as World facts; host.tick advances the lifecycle automatically.
  2. ContainerSystem.pour moves the source's whole volume into one empty compatible vessel or changes nothing. Damage stays with each vessel and only the destination's exposure deadline restarts.
  3. Moving spill follows Carries(holder, vessel) and the holder's motor state; a vessel that reaches its terminal stage empties and records its holder's waypoint as the failure location.
  4. The proof demonstrates terminal failure before the sprint, a rewind to the pristine opening, a full World/Spatial/VM save round-trip, two exact pours, transit spill, and delivery of at least four measures to the lock.
  5. The showcase site's seventh browser deck stages the same three cups with a deck-owned after-tick rule, so the mechanic is playable without compiling a script into the wasm module.

Why it works this wayrecorded

Container decay belongs to the same relational spine as every other mechanic: stage, volume, deadline, and failure location are facts, so snapshots, rewinds, and saves carry the whole cascade without subsystem-specific state.

Evidence

Script Scores: MML Music and Its Triggers

#
audiommlmusicscoresdsl

Scripts compose four-part chiptune music in Music Macro Language and choose it by scene or by narrative event.

score Calm: (lead, bass, chords, drums, scene lines) | play score Chase | stop score

What it does

A score declares lead, bass, chords, and drums parts in MML, optionally bound to scenes. play score and stop score override scene music from any routine, cue, or rule. The synthesizer plays the four parts in step and loops them together.

How it works

  1. mml.parse turns each part's text into integer-timed events at 192 ticks per whole note: notes, rests, k/s/h drum hits, tempo, volume, and envelope presets, with ties, re-read [ ]n repeats, and one L loop point. Errors report the script line and column.
  2. The synthesizer runs one integer tick clock for all four parts; a tempo in any part sets it for all. When every part has ended, each part with an L restarts there on the same tick.
  3. @0 sounds like the engine's grid music; @1 to @7 are organ, pluck, long fade, swell, staccato, tremolo, and soft pad, released at each note's written length. v0 to v15 scale volume.
  4. scene lines seed SceneScore(Scene, Score) facts; play score sets the PlayingScore property of Music and stop score removes it. The frame resolves the override, else the scene default, to current_score.
  5. host.ScriptSoundtrack turns a program's scores into a soundtrack whose tracks are named after them; the audio bridge plays the track whose name the frame gives. bespoke run registers it and, headless, prints each change of music.
  6. Packages (version 11) store the MML text and re-parse it on load.

Why it works this wayrecorded

Music that follows the story belongs in the script, beside the scenes and rules that cause it. Keeping the choice in World facts makes save, rewind, and temporal branches restore the music with everything else, and integer time keeps four parts from drifting.

Evidence

Authoring Games

Starting a project, writing scenes, dialogue, and reactive puzzles, and driving the engine from a Zig host.

Authoring Guide: Scenes, Dialogue, and Reactive Puzzles

#
authoringguidedialoguepuzzlesscenesdsl

docs/AUTHORING.md teaches a game author the script language through three walkthroughs whose scripts the test suite compiles and plays.

docs/AUTHORING.md | <!-- example: scene|dialogue|puzzle --> | zig build test

What it does

The guide starts from bespoke init, explains entities, facts, routines, cues, and rules, then builds a two-scene quay, a conversation whose options depend on facts, and a timed lantern-and-bell puzzle. It ends with testing, the host API, and known limits.

How it works

  1. Every bespoke-fenced block in the guide is a whole script. src/authoring_guide_test.zig reads the guide, compiles each block in a fresh World, and reports a failure by guide line and script position.
  2. The three walkthroughs are found by their example markers and played headless: the test types commands with host.run_command, answers choices with VM.choose, and checks the facts, speech, scene, and music the guide describes.
  3. The build declares docs/AUTHORING.md as an input of the test run, so an edit to the guide re-runs the tests instead of reusing a cached pass.
  4. The stock runner supports the walkthroughs end to end: the window answers dialogue clicks and number keys and enables the command bar for the first routine's actor; a headless run prints speech, scene changes, and offered choices.

Why it works this wayrecorded

Examples drift when nothing runs them. Compiling and playing the guide's own text makes a stale example a test failure, and wiring the stock runner means the guide's instructions work in the program every new project starts from.

Evidence

Starter Template: Bundled Releases, Browser Builds, and CI

#
templatescaffoldingwasmcireleaseauthoring

bespoke init writes a project that tests, builds a self-contained release, builds a browser version, and carries a CI workflow for Linux, macOS, Windows, and the web.

zig build test | zig build -Dbundle -Doptimize=ReleaseSafe | zig build web | node web/smoke.js | zig build test-template

What it does

The generated project's build compiles the script with the engine's own compiler for releases and for the browser, embeds the package, and runs it through the stock runner or the wasm runtime. A GitHub Actions workflow repeats the build and tests on three operating systems and checks the browser build.

How it works

  1. -Dbundle runs the engine's bespoke compile, built for the build machine, on scripts/main.bespoke and embeds the .bspk as game_package; src/main.zig passes it to bespoke.run_bytes.
  2. zig build web builds src/web.zig for wasm32-freestanding against the engine module (no libc or SDL there) with the same package, and installs it with web/index.html into zig-out/web/.
  3. wasm.script_deck loads the package, starts it with host.start_script, ticks through host.tick, shows speech and choices in the banner, and lets the number keys answer an open dialogue.
  4. The workflow fetches the engine at BESPOKE_ENGINE_REF beside the game, rewrites .path in build.zig.zon, installs SDL2 per platform, tests, builds and runs the bundled release headless, and smoke-tests the browser build with Node.
  5. zig build test-template in the engine generates a project into the cache and runs its tests, bundled build, and web build.

Why it works this wayrecorded

A starter that only builds on the author's machine teaches the wrong habit. Compiling the script at build time catches script errors before release and gives one file to ship, and running the same package in the browser keeps the web version in step with the native one.

Evidence

Host Kit API: Driving the Engine from Zig

#
hostapiziglifecycleauthoring

A host compiles a script, ticks it through host.tick, reads speech after each tick, and routes typed commands and dialogue choices to the VM.

compile_source | host.initialize_subsystems | host.run_initial_statements | host.place_cast | host.tick | host.run_command | VM.choose | host.Session

What it does

The bespoke module exports the calls every game host needs: compilation and checking, package loading, the lifecycle tick, speech collection, typed-command dispatch, dialogue views and answers, path selection, the interactive Session loop, and the script soundtrack.

How it works

  1. compile_source interns a script's entities and marks into a World and SpatialSystem; host.initialize_subsystems seeds declared grids, agendas, and containers and is safe to repeat.
  2. host.tick runs one lifecycle tick: the VM, containers, grids, agendas, and queued weaves. Hosts never call VM.step_tick alone, or declared rules do not run.
  3. Speech is read after every tick with host.speech_this_tick or SpeechLog, because the next tick clears the emitted cues.
  4. host.run_command interprets a typed line for an actor and fires its cue; dialogue.view and VM.choose present and answer the open set of choices.
  5. host.start_script runs the top-level statements, places the cast, starts every routine, and returns the player; the stock runner, the guide test, and browser script decks all start scripts this way (D-066).
  6. host.place_cast puts each cast member on the first mark of its scene unless the host already placed it (D-065); call it before starting routines.
  7. host.Session owns the timeline, rewind, scrub, saves, pause, and single step for a window host.

Why it works this wayrecorded

Hosts that copied loop and speech plumbing drifted apart. One documented kit keeps every host on the same lifecycle, and the authoring guide's table gives authors the contract without reading engine source.

Evidence

Developer Tooling & Diagnostics

Interactive developer inspection HUD, time-travel timeline scrubber, live REPL console, and CLI runners.

In-Engine Relational Fact & Fiber HUD

#
huddebuggerinspectordashboard

Live developer dashboard overlay displaying active facts, TTL counters, fibers, call stacks, and spatial coordinates.

Toggle via [F1] or [D] key in running interactive window

What it does

Provides a HUD overlay drawn directly in the running game window to inspect the live simulation spine.

How it works

  1. DisplayWindow.render_frame inspects RenderFrame debug fields when show_debug_overlay is true.
  2. Lists all active relational facts with remaining TTL ticks.
  3. Displays active fiber IDs, program counters, priority levels, and call stacks.
  4. Displays agent spatial coordinates, waypoints, and transit statuses.

Why it works this wayrecorded

Attaching external debuggers (gdb/lldb) halts execution and cannot display high-level domain concepts like relational facts, TTLs, or fibers. An in-engine HUD gives instant visibility at 60 Hz.

Evidence

Interactive Timeline Scrubber & Replay

#
timelinescrubbertime-travelreplay

Graphical timeline scrubber bar allowing point-and-click time-travel scrubbing across simulation history.

Click timeline bar or use [<] / [>] keys to scrub ticks live

What it does

Enables developers and players to pause time, scrub backward across recorded historical ticks, inspect the world at any previous tick, and resume from the past.

How it works

  1. The top HUD bar renders a full-width timeline scrubber indicating current tick and max recorded tick.
  2. Left-clicking anywhere on the bar computes target tick from horizontal mouse position and emits scrub_to_tick.
  3. Keyboard left/right arrow keys step single ticks backward and forward.
  4. World.restore_state unpacks the snapshot into memory, and DisplayBridge refreshes the frame.
  5. If the simulation steps forward after scrubbing backward, divergent future history is cleanly truncated.

Why it works this wayrecorded

Diagnosing why an NPC took an action 50 ticks ago normally requires restarting the game and adding print statements. The timeline scrubber turns time into a navigable spatial axis.

Evidence

Live Interactive REPL Console Drawer

#
replconsolecliinteractive

In-engine slide-out console drawer executing live simulation commands without pausing or recompiling.

Toggle via [Tab], [C], or [`]; commands: remember, forget, cue, walk, facts, step, help

What it does

Provides an interactive command drawer inside the running simulation to query facts, inject new relations, emit cues, or move actors on the fly.

How it works

  1. src/repl.zig implements a pure Zig command interpreter (Repl) with zero GUI dependencies.
  2. DisplayWindow captures keyboard text input via SDL_TEXTINPUT when show_console is active.
  3. Commands modify World, SpatialSystem, and VM directly and log output to the console history buffer.

Why it works this wayrecorded

Testing whether a puzzle reacts to a specific fact requires either playing through prerequisites or recompiling. The live REPL allows instant hypothesis testing in a live simulation.

Evidence

Dual Interactive & Headless CLI Modes

#
cliheadlessrunner

Command-line flags supporting headless deterministic simulation runs and interactive graphics mode.

zig build run -- [--headless] [--spitting-contest] [--borrowed-beard] [--help]

What it does

Provides flexible command-line execution modes for CI pipelines, automated integration testing, and interactive human gameplay.

How it works

  1. --headless runs the simulation without creating an SDL2 window, printing tick snapshots to standard output.
  2. --spitting-contest launches the Pip-Spitting Green contest puzzle scenario.
  3. --borrowed-beard launches The Borrowed Beard puzzle scenario.
  4. Running without flags launches the interactive graphical Tavern Heist simulation at 60 Hz.

Why it works this wayrecorded

Continuous integration servers and developer workstations without display servers must be able to run and verify entire multi-scene simulation scenarios with zero GUI dependencies.

Evidence

Standalone Script Runner & Bytecode Packager

#
clicompilerpackagerunnerdiagnostics

CLI subcommands to check, compile, and execute external .bespoke scripts and binary .bspk packages.

bespoke run <script.bespoke | game.bspk> [--headless] [--ticks N] | bespoke compile <script> -o <pkg.bspk> | bespoke check <script> | bespoke init <name>

What it does

Enables narrative designers to author external scenario files on disk, validate syntax with line and column diagnostics, compile them into standalone CRC32-checksummed binary packages (.bspk), and execute them directly without recompiling engine source.

How it works

  1. bespoke check validates syntax and semantics, reporting file, line, and column error diagnostics on syntax mistakes.
  2. bespoke compile lowers narrative DSL text directly to standalone binary asset packages (.bspk) with magic header BSPB and CRC32 payload verification.
  3. bespoke run executes either text scripts or compiled packages in headless simulation mode or full 60 Hz SDL2 graphical mode.
  4. The asset loader validates header magic, version, payload checksum, and element bounds before allocation, protecting host boundaries from corrupt packages.
  5. bespoke init <name> writes a standalone game project from embedded templates: a build that depends on this engine checkout by relative path, a host, a starter script, and tests (P29-01, D-063).

Why it works this wayrecorded

Narrative authors require a decoupled toolchain where content can be written, validated in CI, packaged, and distributed without touching the engine's core Zig code.

Evidence

Peripheral Audio & Procedural Synthesizer

#
audiosynthchiptunedspperipheral

Decoupled audio bridge, procedural chiptune action SFX, and multi-track scene BGM without audio asset files.

var bridge = AudioBridge.init(); bridge.enqueue_sfx(.footstep); bridge.set_track(.tavern); bridge.render_samples(&pcm_buffer);

What it does

A decoupled audio peripheral subsystem synthesizing real-time chiptune action sound effects and 4-channel background musical accompaniments in pure Zig, consuming simulation cues asynchronously with zero WAV/MP3 asset files.

How it works

  1. AudioBridge consumes discrete audio cues from simulation ticks via an atomic/mutex-guarded ring buffer without blocking the simulation clock.
  2. Procedural ChiptuneSynth generates variable-duty pulse waves, linear triangles, sawteeth, and LCG noise using 32-bit integer phase accumulators and a precomputed 44.1 kHz MIDI table borrowed from Whimsy Machine.
  3. SfxVoice pool synthesizes 10 action sound effects (footsteps, pickups, combining items, horn blasts, splashes, sword clashes, alert stingers, dialogue chirps, clicks, whistles) with attack/decay envelopes and pitch sweeps.
  4. A 4-channel step sequencer plays each host track as arranged two-bar sections, each pass optionally transposed or with parts muted (D-089), so the eleven proof tracks run over two minutes before repeating, with automatic crossfades.
  5. DisplayWindow initializes an SDL2 audio callback feeding 16-bit stereo PCM samples, falling back gracefully to silent offline rendering in headless mode.

Why it works this wayrecorded

Narrative immersion requires rich auditory feedback, but BeSpoke's Engine-as-Spine tenet forbids external asset dependencies, blocking audio threads, or non-deterministic simulation execution. Pure procedural integer synthesis guarantees zero asset bloat, instant loading, and 100% headless testability.

Evidence

Persistent Save/Load Storage & Slot Manager

#
saveloadpersistenceslotscrc32thumbnail

File-backed .sav format with CRC32 integrity, 16x12 RGB332 thumbnails, .bak recovery, and in-engine Save/Load drawer.

var sm = try SaveManager.init(allocator, io, "saves"); _ = try sm.save_slot(1, &world, &spatial, &vm, "Tavern"); _ = try sm.load_slot(1, &world, &spatial, &vm);

What it does

Provides durable cross-session save/load persistence on disk (.sav), managing 8 numbered save slots plus a dedicated Quick-Save slot with metadata headers, miniature visual frame thumbnails, automatic backup recovery, and an interactive SDL2 Save/Load drawer.

How it works

  1. write_save_state and read_save_state serialize and restore World relational arenas, SpatialSystem motor agent paths, and VM fiber/interrupt stacks inside a BSAV binary envelope protected by a 32-bit CRC32 checksum.
  2. SaveMetadata embeds playtime, simulation tick, Unix timestamp, fact count, active scene name, actor coordinates, and a 16x12 RGB332 miniature graphical scene thumbnail.
  3. SaveManager preserves any existing valid save as .sav.bak before overwriting; if a primary .sav file fails checksum or header validation on load, it automatically recovers from .sav.bak and repairs the primary file.
  4. DisplayWindow integrates an in-engine Pause & Save/Load Drawer overlay ([P], [F2], [F3]) and 1-key Quick-Save/Quick-Load ([F5], [F9]), rendering each slot's miniature RGB332 thumbnail and metadata.

Why it works this wayrecorded

While in-memory arena snapshots enable instant timeline scrubbing during a single session, players and developers also need durable disk saves that preserve mid-walk spatial paths and fiber call stacks while defending against disk truncation or file corruption.

Evidence

Emergent Society Simulation (The Living Village)

#
emergencevillagedrivesrumorsjusticesandbox

Core emergent society mechanic: needs-driven agents, witness detection, rumor propagation, and justice cascades, demonstrated by The Living Village proof.

society Hamlet: ... | var soc = try bespoke.society.Society.init(&world, compiled.societies.items[0].config); try soc.step(&world, &spatial, &vm);

What it does

An engine mechanic for unscripted social simulation (src/society.zig). A script-level society declaration or direct Zig config supplies a list of needs, a roster with data roles (merchant, broadcaster, enforcer) and routines, friendships, and the places the systems use. The Living Village script declares one configuration: 6 villagers across a 6-building settlement.

How it works

  1. Each need is a property relation with a direction, a per-tick rate, and a seek threshold, met by staying at a place (rest) or by trading with a merchant; past a critical value, a member who cannot pay steals the merchant's goods.
  2. Each tick a member takes the first applicable branch: held, staying, decay, enforcer on duty, start a stay, desperation theft, flight, trade, broadcast, routine.
  3. Aware members near a crime scene while the culprit is there record Witnessed, KnowsRumor, and expiring Grudge facts.
  4. Rumors spread one hop per tick between co-located members who are friends, or when the speaker is a witness or broadcaster, or the listener is the enforcer.
  5. The enforcer issues a warrant with a priority fiber interrupt, pursues, arrests on contact, recovers stolen goods, and escorts the culprit to the holding place. All of this is World facts, so rewind and saves cover it.
  6. CompiledProgram owns society declarations in source order; .bspk format version 4 serializes them and validates their member, waypoint, and entity references.

Why it works this wayrecorded

Shows that the flat relational fact store, property auto-overwrite, and priority interrupt spine support unscripted systemic emergence for any cast and setting, with full time-travel scrubbing and disk save compatibility.

Evidence

Script-Declared Dialogue Duels

#
dialogueduelchoicestiersfatiguedsl

Challenge/reply contests with learned counters, opponent tiers, fact-guarded candidates, wins, and per-NPC inquiry fatigue.

duel RiddleContest: ... | var duel = try bespoke.duel.Duel.init(&world, compiled.duels.items[0].config); try compiled.duels.items[0].apply_tiers(&duel);

What it does

A reusable dialogue-duel mechanic configured by a script-level duel declaration or direct Zig data. Declarations contain challenge/reply pairs, optional tier variants and opponent assignments, fallback lines, a win threshold, relation vocabulary, and staged inquiry-fatigue moods.

How it works

  1. Duel.init asserts the immutable Counters and VariantOf knowledge base as World facts; what each fighter heard or mastered, opponent tiers, advantage, wins, inquiry counts, and moods are also facts.
  2. Duel.challenges and Duel.replies submit candidates through VM.prune_dialogue_choices, so the ordinary fact-guarded dialogue query path controls what can be offered.
  3. A duel declaration preserves pair, variant, tier, and fatigue-stage source order. The host applies its tier assignments after Duel.init and may initialize InquiryFatigue from the same declaration.
  4. Fighters learn what they hear (D-078): resolve_round teaches the defender the challenge and the attacker the reply it got back, so a lost round teaches the defender nothing more. Duel.answer gives a host-driven opponent's reply: the countering comeback if it knows it, else the fallback.
  5. Duel.concede lets a fighter give up its turn to attack (D-082): the opponent scores, the fighter's fallback rotation advances, and nobody learns anything.
  6. A fighter with no learned reply is offered one fallback line. The fighter's DuelFumbles count, a fact, picks the line, so successive fumbles rotate through the list and a rewind restores the rotation (D-076).
  7. The Brackwater Barbs proof opens each round as a runtime-generated dialogue set from Duel.replies, resolves the selected reply through Duel.resolve_round, takes turns through the proof's Bout (whoever wins a round attacks next; a master always attacks), moves an attacking opponent to Duel.next_challenge, fires the script's WinsDuel cue for the victory line, and stores the active opponent, barb, and turn as facts so a rewind restores the round (P32-23, D-046).
  8. .bspk format version 4 serializes complete duel declarations; versions 1 through 3 load with an empty declaration table. Version 14 stores up to eight fallback lines; earlier packages hold at most one.

Why it works this wayrecorded

Game-facing configuration belongs in distributable .bespoke source. The mechanic remains generic while each game controls its dialogue, tiers, vocabulary, and mood cadence.

Evidence

Showcase Gallery, Script Viewer, and Diagrams

#
sitegalleryscriptsdiagrams

The showcase lists every proof, plays eleven in the viewport, and shows each proof's real script in a viewer that follows the active deck.

tools/site_gallery.json -> python3 tools/build_site.py -> SITE_GALLERY region in site/index.html

What it does

A generated gallery of thirteen proof cards with Play and View script buttons, a line-numbered script viewer under the viewport, and a How It Works section of three inline SVG diagrams.

How it works

  1. build_site.py reads tools/site_gallery.json and extracts each script from a .bespoke file or a Zig multiline constant (file.zig#CONSTANT).
  2. Scripts are highlighted at build time with the keyword list read from src/compiler/lexer.zig, escaped, and embedded as JSON with </ escaped.
  3. site_simulator.js shows the active deck's script whenever a deck loads, and any proof's script when its View script button is pressed.
  4. build_site.py --check, and deploy_site.py export, treat a changed script or gallery entry as a stale page.

Why it works this wayrecorded

Hand-copied snippets had drifted from the proofs. Extracting the scripts at build time keeps the showcase honest, and labelling them as the desktop proofs' source keeps it honest about the browser decks being Zig reconstructions.

Evidence

Showcase Export: Sharing Metadata and an Offline Cache

#
siteexportwasmoffline

tools/deploy_site.py turns the self-contained showcase page into a static site with sharing metadata and an offline cache, ready to upload by hand.

python3 tools/deploy_site.py export [--site-url https://NAME.neocities.org/]

What it does

export writes dist/site/index.html and sw.js from site/index.html, which stays unchanged. The maintainer uploads dist/site/ to the host by hand.

How it works

  1. export refuses a stale page, then adds OpenGraph, Twitter, and theme-colour tags from the page's own title and description, plus canonical and og:url when --site-url is given.
  2. A registration script added before </body> registers sw.js only over http(s), so the file:// page is unaffected.
  3. sw.js names its cache after a hash of the exported page, deletes older caches on activation, and answers from the network first, falling back to the cache offline.
  4. The embedded module is small because the wasm runtime's state is an uninitialised global; node tools/wasm_smoke.js fails any module over 1 MiB.

Why it works this wayrecorded

Neocities serves static files and allows no custom headers, so caching and metadata live in the files themselves. Publishing stays a manual step the maintainer takes (D-074), so the repository holds no host credentials.

Evidence

WebAssembly (wasm32-freestanding) Target & Browser Runtime

#
wasmbrowsercanvaseventsruntimeframebuffer

Zero-dependency wasm32-freestanding runtime that draws the desktop window's frame, with a browser event bridge; games supply its scenes as decks.

zig build wasm wasm-proofs | wasm_init(deck); wasm_step_tick(); wasm_render_frame(); wasm_on_pointer_down(x, y); wasm_set_verb(i);

What it does

Compiles the BeSpoke Engine simulation spine to a zero-dependency wasm32-freestanding WebAssembly module with a 1280x720 RGBA8888 framebuffer and a browser mouse/keyboard/touch event bridge. It draws the same frame as the desktop window, with the same code. What is on stage comes from a deck table the host compiles in: the engine's own module has a neutral demo deck and a script deck, and bespoke-proofs.wasm carries thirteen proof decks, and a deck can turn on the desktop's typed-command bar.

How it works

  1. The runtime captures the desktop RenderFrame and draws it with a DisplayWindow made by init_canvas into a 1280x720x4 RGBA8888 buffer in linear memory (D-097): the deck's theme draws its proof's scenery, and the window draws the verb bar, item tray, dialogue panel, banners, and timeline. The desktop draws into the same Canvas (src/display/canvas.zig) and SDL only shows it, so the two match pixel for pixel.
  2. WasmRuntime manages World, SpatialSystem, BytecodeChunk, VM, and a 32-slot ring buffer of binary World snapshots under a 16 MiB capped allocator. Each Deck supplies load, after-tick, and catalyst callbacks, a theme, and a status hook, and wasm.export_runtime(decks) emits the C-ABI exports (wasm_init, wasm_step_tick, wasm_framebuffer_ptr, wasm_scrub_to_tick) for a build's decks.
  3. dispatch_event normalizes browser pointer_down, pointer_move, right_click, key_down, and touch events into walk_to motor intents, verb selection, cue firing, item use, catalyst triggers, and timeline scrubbing, hit-testing with the desktop layout.
  4. The engine synthesizer plays in the browser (D-071): the runtime's AudioBridge renders the script's scores or a deck's soundtrack, and the page pulls stereo samples with wasm_audio_render into Web Audio. A deck can own a TemporalHypervisor whose live branch the VM, story, and inspector follow and the timeline records; draft decks play notes on C to B.
  5. I opens the state inspector (D-070, D-098): the desktop State tab itself, drawn in the save drawer's place, with the clock paused and the desktop's keys sent as DOM key codes.
  6. Script decks (wasm.script_deck_with) compile a game's or a proof's script in the browser, start it with host.start_script, and tick through host.tick. Verbs on people and props fire LooksAt, TalksTo, Takes, or Uses for the deck's player; the number keys answer an open dialogue; the stage shows only the current scene, as on desktop (D-066, D-069).
  7. The standalone showcase website (site/index.html) embeds bespoke-proofs.wasm via tools/build_site.py to provide a live interactive simulation viewport. tools/wasm_smoke.js exercises both modules in Node.

Why it works this wayrecorded

Targeting wasm32-freestanding with an in-memory RGBA8888 framebuffer preserves BeSpoke's zero-external-dependency guarantee (no Emscripten or SDL2 required). Drawing both surfaces through one canvas means a game's art and interface are written once (D-097). Decks keep game content out of the engine module (D-042), and the interactive simulator lives on the public showcase site rather than inside the reference manual (D-047).

Evidence

Developer Guide & Engineering Standards

Contribution standards, verification hierarchies, architectural decision records, and documentation tooling.

Test Verification Hierarchy

#
testingverificationci

Multi-tiered automated test suite verifying compiler, VM, spatial system, renderer, and scenarios.

zig test -lc -lSDL2 src/root.zig && zig build test && python3 tools/check_docs.py

What it does

Enforces code correctness across all engine modules via fast, unit-level Zig test blocks, build-system tests, headless simulations, and documentation consistency checks.

How it works

  1. zig test -lc -lSDL2 src/root.zig runs 95 core compiler, VM, world, spatial, audio, save, village, and wasm tests.
  2. zig test -lc -lSDL2 src/display.zig runs 61 display bridge, font, and renderer tests.
  3. zig test src/wasm.zig && zig build wasm verifies the freestanding WebAssembly runtime and browser event bridge.
  4. python3 -m unittest discover -s tests -v runs 29 documentation manual tests.
  5. python3 tools/check_docs.py validates cross-references, decision numbers, and session logs.
  6. python3 tools/manual.py check scheme/bespoke.manual.json --check-evidence --root . verifies manual integrity.

Why it works this wayrecorded

Unit tests, proof transcripts compared with goldens, render and audio hashes, and documentation checks catch changes to grammar, opcodes, or layout that alter simulation behaviour.

Evidence

Architectural Decision Records (D-NNN)

#
decisionsadrarchitecture

Append-only architectural decision log in docs/DECISIONS.md recording rationale and alternatives.

## D-NNN Title (YYYY-MM-DD, status: accepted)
Context: ...
Decision: ...
Alternatives: ...
Consequences: ...

What it does

Maintains an immutable record of technical and design choices, documenting the context, trade-offs, evaluated alternatives, and consequences for every significant architectural evolution.

How it works

  1. Decisions are assigned monotonically increasing IDs (D-001 through D-031).
  2. Each decision details Context, Decision, Alternatives Considered, and Consequences.
  3. Open architectural questions are logged in the same document with permanent Q-NNN IDs until answered.

Why it works this wayrecorded

Without written decision records, future maintainers and AI agents revisit already-rejected trade-offs or accidentally undo foundational constraints (such as zero-dependency or tick determinism).

Evidence

The 3x What/How/Why Documentation Contract

#
documentation3xmanualcontract

Every documented component answers What it does, How it works, and Why, backed by explicit evidence.

python3 tools/manual.py build scheme/bespoke.manual.json --output docs/manual.html

What it does

Governs all technical documentation using the 3x documentation scheme: every subject answers What, How, and Why, and cites verifiable code and decision evidence.

How it works

  1. Source is defined in JSON validated against scheme/manual.schema.json.
  2. tools/manual.py builds a portable, zero-dependency HTML manual with interactive search and navigation.
  3. why_basis tracks provenance: recorded, observed, inferred, or external.
  4. tools/manual.py check --check-evidence verifies that every cited file, decision, and test exists in the repository.

Why it works this wayrecorded

Traditional freeform documentation frequently omits rationale, goes stale, or drifts from code reality. The 3x contract gives human developers and coding agents the reason behind each component and the code that backs it.

Evidence