Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

ST0a: raea/story: stories as typed data in an ECS, with derived curves, exact checks and labelled mutation

shinyobjectz22dffb4170c6
diff --git a/docs/story.feature b/docs/story.feature
new file mode 100644
index 00000000..0d159bed
--- /dev/null
+++ b/docs/story.feature
@@ -0,0 +1,151 @@
+@spec
+Feature: Story: a story as ECS data, read through many frameworks, generated without a fixed answer, checked from tsc to the outcome
+ Shane, 2026-11-22: "a story skill tree that takes the hero's journey of a thousand faces, pixar story principles eg.
+ creativity inc, robert mckee's storynomics, propaganda by edward bernays, etc. ... an open non-deterministic story
+ framework for videos/games/dialogue ... a new type of story typescript sdk that also integrates with the
+ screenplay/avscript stuff but at a higher level so you could test and validate story beats in the code or across
+ themes". Then: "it should live in brief and be an import ... keep it open and explicitly used. story sdk can stay
+ typescript", and "build small language models or generative story models that are able to chart out things a brief
+ might want or need or to check if a story is right ... take the ecs, story as data approach by storm".
+ The plan, the state of the art and the reasons: docs/story.md.
+
+ The model this file sets:
+ 1. A story is data in three layers: the world (facts and the events that change them, with causes), tellings
+ (beats: which events the audience sees, in what order, what each reveals), and the render (script.ts).
+ 2. Its parts are entities with components in a small ECS; systems derive what is never written (value curves,
+ knowledge, suspense and mystery, the cause graph, beliefs, tension). Checks read only what's derived.
+ 3. Frameworks are lenses: stages, a map onto beats, checks and proposals. A story is read through all of them.
+ 4. Nothing reads a story unless something imports it: the brief's `story:`, a composition, a check, a drama manager.
+ 5. The SDK is TypeScript with no runtime dependencies. Rust only lets a story through and points back at it.
+
+ Background:
+ Given the package sdk/story (@raea/story, "raea/story" in sdk/tsconfig.base.json, which raea's bundler follows)
+ And its tests: sdk/story/test/*.test.ts (bun test)
+ And the launch corpus ~/.vd/launch (whatships' launch videos, X engagement, same-account pairs): the first data
+
+ Rule: ST0. The model: world, tellings and render as typed data
+
+ Scenario: ST0a. A story module type-checks its own references
+ Given a story written with story() from "raea/story"
+ When an event names a cause, a fact, an agent or a value the story doesn't declare
+ Or a beat shows an event, sets up or pays off a key the story doesn't declare
+ Then tsc refuses it, naming the key
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/model.ts | 300 | the types and story(): values, facts, agents, events, tellings |
+ | sdk | sdk/story/src/index.ts | 40 | the exports |
+ | sdk | sdk/story/test/types.ts | 120 | references refused by tsc (expect-error) and accepted ones |
+ | sdk | sdk/story/test/fixture.ts | 120 | the launch story every test uses |
+
+ Scenario: ST0b. A story is an ECS world
+ Given a story value
+ When it's loaded into a world
+ Then every value, fact, agent, event and beat is an entity with its components, and a query by components finds
+ them, in the telling's order for beats
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/ecs.ts | 160 | entities, components, resources, queries, systems |
+ | sdk | sdk/story/src/load.ts | 160 | a story and a telling into a world |
+ | sdk | sdk/story/src/resolve.ts | 120 | choice points resolved with a seed (mulberry32) |
+
+ Scenario: ST0c. The brief imports stories, and a script's scene names its beat
+ Given brief({ ..., story: launch }) or story: { launch, quest1 }
+ Then raea reads the brief with its story kept as it is (Brief.story, opaque to Rust)
+ And a script's scene may carry beat: "<id>", which the screenplay and the A/V table show
+
+ Rule: ST1. Systems derive what's never written
+
+ Scenario: ST1a. Value curves, the cause graph, knowledge, beliefs and tension
+ Given a world loaded from a story and one of its tellings
+ When the systems run
+ Then each value has its curve over the telling, and the curve's shape is named (rise, fall, fall-rise, rise-fall,
+ rise-fall-rise, fall-rise-fall)
+ And the audience's knowledge and each agent's are known at every beat, with suspense (the audience knows a fact an
+ agent on screen doesn't), mystery (an open question the audience is waiting on) and surprise (a reveal nothing
+ set up)
+ And an event whose agent acts on a fact they don't hold yet is a belief break
+ And the tension at each beat comes from open questions and value pressure
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/systems/values.ts | 140 | value curves and their shapes |
+ | sdk | sdk/story/src/systems/know.ts | 200 | audience and agents' knowledge, suspense, mystery, surprise, belief breaks |
+ | sdk | sdk/story/src/systems/cause.ts | 120 | the cause graph: uncaused beats, dead ends |
+ | sdk | sdk/story/src/systems/tension.ts| 100 | the tension curve |
+
+ Rule: ST2. Exact checks
+
+ Scenario: ST2a. A story is checked with no model
+ When checkStory runs
+ Then it finds: a beat that turns no value, an event with no cause (after the first), an unpaid setup, a payoff with
+ no setup, a belief break, an unmeant surprise, a run of beats all turning one way, an arc left open
+ And each finding names the beat or event, says what's wrong in a sentence, and suggests a fix
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/checks.ts | 260 | the exact checks and findings |
+ | sdk | sdk/story/test/checks.test.ts | 200 | the launch story passes; derived curves and questions; seeds |
+
+ Rule: ST3. Lenses
+
+ Scenario: ST3a. A lens maps, checks and proposes
+ Given the lenses mckee, pixar, storynomics and pas
+ When a story is read through each
+ Then each says which beats play its stages, what's missing or out of order, and proposes beats for what's missing
+ And a story read through every lens says which it passes
+
+ Scenario: ST3b. The rest of the frameworks
+ Given campbell, vogler, harmon, save-the-cat, kishotenketsu, propp and bernays as lenses
+ Then each has its stages, checks and proposals, and bernays only arranges true proof (a claim with no fact behind
+ it is a finding)
+
+ Rule: ST4. Generation without a fixed answer
+
+ Scenario: ST4a. Choice points, seeds, pruning
+ Given a story with choose([...]) in place of fixed parts
+ When it's sampled with a seed
+ Then the same seed gives the same story, a new seed may give another, and no sampled story fails an exact check
+ And a theme matrix runs one story pattern across many premises and says where it breaks
+
+ Rule: ST5. Into raea check, scripts and games
+
+ Scenario: ST5a. The SDK's checks run in raea check
+ Given a project whose brief imports a story and whose composition names its Sequences by beat id
+ When raea check runs
+ Then the story-only, on-screen and render checks run as ordinary raea/check checks
+ And they can be named by package path in taste.ts, and a story is checked with no composition (raea check story.ts)
+
+ Scenario: ST5b. A telling compiles to a script, to storylets and to dialogue
+ Then compileScript gives raea/brief's Script, each scene carrying its beat
+ And compileStorylets gives preconditions and effects over facts, with a drama manager that picks the next storylet
+ to keep a target tension curve
+ And dialogue lines carry what's said, what's meant, and the value they turn
+
+ Rule: ST6. Story models: small, on-device, schema-native
+
+ Scenario: ST6a. Exact labels by mutation
+ Given valid stories
+ When mutate() breaks one (drops a setup, breaks a cause, gives an agent a fact early, flattens a value, reorders
+ a reveal)
+ Then the broken story and its label (what was broken, where) are a training row, and checkStory finds it
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/mutate.ts | 300 | every way a story told one way can be broken, labelled |
+ | sdk | sdk/story/test/mutate.test.ts | 120 | every mutant with an expected check is found by it |
+
+ Scenario: ST6b. The extractor, the generator and the critic
+ Given small bases (about 2B parameters or less), trained with MLX on this Mac and exported to ONNX for ort
+ Then the extractor turns a transcript into story data, the generator proposes what a brief wants as data that
+ passes the schema, and the critic says whether a story is right and where
+ And each is measured held out against a zero-shot baseline and a frontier LLM judge, with the numbers written here
+
+ Rule: ST7. The launch corpus
+
+ Scenario: ST7a. What the better launch of a pair does
+ Given 158 same-account pairs of launch films, measured and transcribed
+ Then the paired comparison and a blind read of 30 pairs say whether craft shows at all, with numbers
+ And what holds up becomes a launch profile in raea fingerprint and the launch lens's priors
+
+ Rule: ST8. The skill tree
+
+ Scenario: ST8a. craft/story in the raea skill
+ Then craft/story/ holds a router and a page per framework in our own words with sources, and how to write, check,
+ sample and score a story with raea/story
diff --git a/docs/story.md b/docs/story.md
new file mode 100644
index 00000000..8a903b75
--- /dev/null
+++ b/docs/story.md
@@ -0,0 +1,397 @@
+# Story: the plan
+
+Shane, 2026-11-22: "a story skill tree that takes the hero's journey of a thousand faces, pixar story principles eg.
+creativity inc, robert mckee's storynomics, propaganda by edward bernays, etc. the goal here is to create an open
+non-deterministic story framework for videos/games/dialogue, themes and things in a new type of story typescript sdk
+that also integrates with the screenplay/avscript stuff but at a higher level so you could test and validate story
+beats in the code or across themes, ideas, etc. ill look to you to see how SOTA we can actually make that system".
+
+This is the one plan for `raea/story`: what it is, how it sits on `script.ts`, the frameworks it reads stories
+through, how a story is generated without being fixed, how it's tested, what's state of the art and what's new
+here, and the build order, with a confidence for each step. No code exists yet.
+
+## In one paragraph
+
+A story is a typed program, not a document. Its parts are a premise, the values at stake, a cast with wants and
+needs, a knowledge model (who knows what, and when), and beats. Each beat turns a value, opens or closes a gap in
+what the audience knows, and is caused by an earlier beat. The frameworks (Campbell, Pixar, McKee, Storynomics,
+Bernays, Kishōtenketsu and others) are **lenses**: each one reads the same story, maps its beats onto its own stages
+and checks it, and each can also *propose* beats. Generation is a seeded walk over choice points. Lenses and the
+priors learned from real outcomes weight the choices, and the checks prune them, so every run is a different story
+that still passes. A story compiles down to `script.ts` (the screenplay and A/V table the feed already shows), to a
+storylet graph for games, and to dialogue. It's tested at four levels: the type checker (a payoff without a setup
+doesn't compile), exact checks, learned judges (fingerprint text axes trained on real pairs), and measures of the
+finished piece.
+
+## Where it sits
+
+Shane, 11-22: "it should live in brief and be an import or something like that ... we might use it for a few
+different things in video and gaming so best to keep it open and explicitly used. story sdk can stay typescript."
+
+So a story is a module of its own (`story.ts`, or several: `launch.story.ts`, `quest-1.story.ts`), written with
+`raea/story`. The brief takes it as an import: `import launch from "./launch.story"` and `brief({ ..., story: launch })`,
+or `story: { launch, quest1 }` for several. Nothing in raea reads a story unless something imports it: the brief, a
+composition timing its scenes from the beats, a check, or a game's drama manager. That's what "explicitly used"
+means here: an opt-in import, never a convention raea assumes.
+
+```
+brief.ts what to make, for whom, the one thing to believe; `story:` imports one or more stories
+ └─ *.story.ts facts, events, beats, values, cast, lenses ◄── NEW: raea/story (TypeScript only)
+ │ compile
+ ├─► NAME.script.ts scenes of beats: on screen, lines, camera, cut, payoff (exists: core/brief Script; the feed
+ │ shows it as a screenplay and as an A/V table)
+ ├─► storylets preconditions and effects over qualities, for a game's drama manager
+ └─► dialogue lines with intent and subtext, barks, branches (Ink and Yarn export)
+render ─► film/game ─► measured (vd measure_film, fingerprint) ─► back onto the story's beats
+```
+
+`script.ts` stays the shot level: what's seen and heard. `story.ts` is the level above it: why each scene exists
+and what changes in it. One story compiles to many scripts: a 30 s cut, a 90 s cut, a 9:16 cut, a game level.
+
+## Story as data: how it works
+
+### Three layers, kept apart
+
+Narratology separates what happens from how it's told (the Russian formalists' *fabula* and *syuzhet*). Keeping
+them apart as data is what lets one story serve a film, a game and a dialogue. It's also what makes reveals,
+flashbacks, irony and branching computable instead of described.
+
+| layer | what it holds | who writes it | example |
+|---|---|---|---|
+| **world** (fabula) | facts, and events that change them: who did what, because of what, in story order | the author or an agent, once | `the backlog doubles` happens before `the team tries raea` |
+| **telling** (syuzhet) | beats: which events the audience sees, in what order, what each one reveals and to whom, the feeling it aims for | one per cut: the 30 s, the 90 s, the game | the 30 s cut opens on the proof and flashes back to the backlog |
+| **render** | `script.ts`: shots, lines, camera and cut, timed | compiled, then edited | scene 1: "the 50 finished ads, wide" |
+
+A film is a single linear telling. A game is many possible tellings: storylets chosen at runtime from the same world.
+A trailer is a telling that hides the ending.
+
+### The primitives (written)
+
+- **Value**: a quality at stake, with two poles (`freedom: buried ↔ free`). McKee's unit of change.
+- **Fact**: a proposition that can be true or false at a point in the world (`team.knowsRecipeCanRun`).
+- **Agent**: a character or a group, with a want, a need, the lie they believe, and their beliefs (the facts they
+ hold true, which may be wrong).
+- **Event**: an agent does something. It needs facts, changes facts, turns values, and is caused by earlier events
+ (`because`). Every event lives in the world layer.
+- **Beat**: a unit of telling. It shows one or more events, reveals facts to the audience or to characters, and
+ names the feeling it aims for. It may set something up, or pay something off.
+- **Idea**: the controlling idea and its counter (McKee). Each beat argues one side, which makes theme checkable
+ (Pixar's "what is the story about").
+
+All of these are typed keys: a beat that shows an event the world doesn't have, or pays a setup that doesn't exist,
+is a type error. That's the same trick `NAME.parts.ts` uses for parts.
+
+### What's derived (computed, never written)
+
+From those primitives the SDK computes, over the telling's order:
+- **value curves**: one per value, so the arc's shape can be named and checked (rise, fall, fall-rise, the six
+ shapes Reagan et al. found);
+- **the audience's knowledge**, beat by beat, against each character's. Where the audience knows more than a
+ character, that's suspense or irony. Where it knows less, that's mystery. A reveal with no earlier setup is a
+ surprise, which is a defect unless the beat says it's meant;
+- **the cause graph**: beats with no cause ("and then"), and causes that never lead anywhere;
+- **belief consistency**: an agent acting on a fact they don't hold yet, which is the plot hole FlawedFictions
+ measures, caught here from the data instead of read from prose;
+- **the tension curve**: from open questions (facts the audience is waiting on) and value pressure, laid against the
+ beats' intended feelings.
+
+Every check reads these derived curves. No lens or check parses prose to find structure: the structure is the data.
+
+### A worked example
+
+```ts
+// launch.story.ts
+import { story, value, choose } from "raea/story";
+
+export default story({
+ idea: { side: "your recipe, run for you, frees you", counter: "only hands-on work is good work" },
+ values: { freedom: value("buried", "free"), trust: value("doubt", "trust") },
+ agents: {
+ team: { want: "ship every client's ads this week", need: "stop being the bottleneck", lie: "if I don't touch it, it's worse" },
+ raea: { mask: "mentor" }, // Storynomics: the customer is the hero, the brand the mentor
+ },
+ facts: { backlog: "the backlog is out of hand", recipeRuns: "the recipe can run without them" },
+ world: { // events in story order, each with its cause
+ week: { who: "team", does: "edits the same ad again", turns: { freedom: -1 } },
+ doubles: { who: "team", does: choose(["the backlog doubles", "a client wants 50 versions"]), because: "week", sets: ["backlog"], turns: { freedom: -2 } },
+ tries: { who: "team", does: "hands raea the recipe once", because: "doubles", needs: ["backlog"], turns: { trust: -1 } },
+ runs: { who: "raea", does: "runs it on 50 courses; checks every cut", because: "tries", sets: ["recipeRuns"], turns: { trust: +2, freedom: +2 } },
+ },
+ tellings: {
+ "30s": [ // a beat shows events and reveals facts; order is the telling's
+ { shows: ["runs"], feel: "curiosity", reveal: { audience: ["recipeRuns"] }, setup: "how" }, // in medias res
+ { shows: ["week", "doubles"], feel: "recognition" }, // flashback
+ { shows: ["tries"], feel: "concern" },
+ { shows: ["runs"], feel: "relief", pays: "how" },
+ ],
+ },
+ lenses: ["mckee", "storynomics", "pas"],
+});
+```
+
+Derived for the "30s" telling:
+- `freedom` goes +2, -1, -2, +2: a fall-rise, the "man in a hole" shape;
+- the opening reveal makes the middle beats suspense rather than mystery, because the audience already knows it ends
+ well;
+- `tries` needs `backlog`, which `doubles` set earlier, so the beliefs are consistent;
+- the PAS lens maps problem → `week`/`doubles`, agitate → `tries`, solve → `runs`, and passes.
+
+### Lenses as code
+
+A lens is a function from a story and a telling to a mapping, findings and proposals:
+
+```ts
+export const mckee = lens({
+ name: "mckee",
+ stages: ["inciting", "complications", "crisis", "climax", "resolution"],
+ map: (s, t) => inferStages(s, t), // or the beats' own `stage:` labels
+ checks: [
+ every("beat turns a value", (b, d) => d.turned(b).length > 0),
+ rule("complications escalate", d => d.pressure.isRising("complications")),
+ rule("the crisis is a dilemma", d => d.choiceAt("crisis")?.options.length >= 2),
+ ],
+ propose: (stage, s) => /* candidate beats for a missing stage */ [],
+});
+```
+
+The frameworks become a library of these. A person's or an agency's own format is one more lens, written the same way.
+
+### How it reaches `raea check` (tested 11-22)
+
+A `raea/check` check is a TypeScript module, so it can import a story directly and compare it against the world's
+facts. Those facts already carry `Shot` (each `Sequence` by name and frames), `Line` (narration and dialogue with their
+words) and `Word`. Tested on 11-22 with a three-beat story and a composition naming its Sequences by beat id:
+- a check listed in `taste.ts` read every Shot frame by frame;
+- in `after` it walked the story's beats;
+- it reported `error story problem: the beat problem has no shot named for it`.
+
+This runs on main's build (0.1.9). The installed 0.1.8 refuses a check given by path: TypeScript checks in taste
+landed in 0.1.9 (PJ9, 822b73fc7d).
+
+So the story SDK ships its checks as ordinary checks, in three kinds:
+- **story-only**: structure, knowledge and lens checks, run once in `after`. They need no frames, but today they
+ still need a composition to run against;
+- **story on screen**: each beat is a shot in order, and the beat's line is spoken inside its frames (Line and Word
+ against the beat's frames);
+- **story in the render**: once rendered, the measures of the made piece, laid on the beats.
+
+A composition uses the story explicitly: `useBeat(launch, "30s", 2)` gives a beat's frames, and `<Beat>` is a
+`Sequence` named by its id. The world then carries the beats with no engine change.
+
+### The Rust changes it needs (small, and the only ones)
+
+The SDK stays TypeScript. Rust only has to let a story through and point back at it:
+1. **`Brief.story`**: the brief refuses unknown fields (`deny_unknown_fields`), so `brief({ story })` is refused today.
+ Add `story: Option<serde_json::Value>` that Rust keeps without reading. Its TypeScript type comes from
+ `raea/story`, not from ts-rs (the brief's TS type is widened in `brief.ts`).
+2. **`Scene.beat`**: an optional beat id on a script's scene, so the screenplay and the A/V table show which beat each
+ scene plays, and a check can follow it.
+3. **Story checks without a composition**: let `raea check story.ts` (or a brief with a story) run checks marked
+ `over: "story"` once, with no world, so a story is checked before anything is drawn.
+4. **Checks by package path**: let a taste line name `raea/story/checks/turns` as well as a project file, so a project
+ uses the SDK's checks without copying them.
+
+## The model, as a module
+
+Every field is data, written in TypeScript, so `tsc` catches what can be caught without running anything (the way
+`NAME.parts.ts` makes a skipped part a type error). The example below is the short form of the worked example above.
+
+```ts
+import { story, value, beat } from "raea/story";
+
+export default story({
+ premise: "A video team drowning in footage gets its week back",
+ // McKee's controlling idea: a value plus its cause. The story argues it; the counter-idea gets a fair voice.
+ idea: { value: "freedom", because: "the recipe they already know is run for them", counter: "only hands-on work is good work" },
+ values: {
+ freedom: value("buried", "free"), // each scene turns one of these, + or -
+ trust: value("doubt", "trust"),
+ },
+ cast: {
+ team: { want: "ship every client's ads this week", need: "stop being the bottleneck", lie: "if I don't touch it, it's worse" },
+ raea: { role: "mentor" }, // Storynomics: the customer is the hero, the brand is the mentor
+ },
+ setups: { recipe: "the hook, best moment, captions, logo they repeat by hand" },
+ beats: [
+ beat("ordinary", { who: "team", turns: { freedom: -1 }, shows: "the same edit, again" }),
+ beat("inciting", { who: "team", turns: { freedom: -2 }, because: "ordinary", reveals: { audience: "the backlog doubles" } }),
+ beat("refusal", { who: "team", turns: { trust: -1 }, because: "inciting", says: "a tool can't know our clients" }),
+ beat("proof", { who: "raea", turns: { trust: +2 }, because: "refusal", pays: "recipe" }),
+ // ...
+ ],
+ lenses: ["mckee", "storynomics", "pixar-spine"], // read and checked through these; others may still read it
+});
+```
+
+- **Values** (McKee): the qualities at stake, each with two poles. A beat that turns no value is a non-event, and
+ the checks say so.
+- **Cause** (`because`): every beat after the first names the beat that caused it. A story of "and then" links fails
+ the "therefore / but" rule (Parker and Stone's rule, the same idea as McKee's causality).
+- **Setups and payoffs** are typed keys. `pays: "recpie"` doesn't compile, and an unpaid setup is a check failure
+ (Chekhov).
+- **Knowledge**: each beat can reveal a fact to the audience, to a character, or to both. From that the SDK computes
+ **suspense** (the audience knows more than a character), **mystery** (less) and **surprise** (a reveal nobody was
+ set up for, which is a defect unless the story marks it as meant). It also catches the plot holes FlawedFictions
+ measures: a character acting on something they can't yet know.
+- **Cast**: a want (conscious), a need (unconscious), the lie they believe, and an arc (positive, negative, flat).
+ Campbell's and Vogler's archetypes are **masks a character wears in a beat** (mentor, threshold guardian,
+ shapeshifter), not fixed types.
+- **The audience's feeling** per beat (curiosity, concern, relief, delight) is a target, so a story can be checked
+ against the curve it means to draw.
+
+## Lenses: the frameworks
+
+A lens is a module with the same shape for every framework:
+- **stages**, with their order and where they fall in the running time;
+- **map**: which of the story's beats play each stage, inferred or declared;
+- **checks**, each one exact or learned;
+- **propose**: candidate beats for a stage that's missing.
+
+A story is read through every lens at once, so `raea story lenses` can say "this passes McKee and Storynomics, and
+reads as a Kishōtenketsu with no second turn". The lenses' words go in the skill tree, in our own words, with sources.
+
+| lens | what it adds | checks it brings |
+|---|---|---|
+| **Campbell / Vogler** (monomyth: 17 stages; Vogler's 12) | departure, initiation, return; archetypes as masks | stage order; the return carries something back (the "elixir") |
+| **Pixar** (story spine; Emma Coats' 22 rules; *Creativity, Inc.*'s Braintrust) | "Once upon a time... every day... until one day... because of that... until finally" | a causal spine with no gaps; the Braintrust is a *review* lens: candid notes on the problem, never the fix (our readers and the fingerprint's notes) |
+| **McKee** (*Story*: scene turning, gaps, controlling idea; inciting incident, progressive complications, crisis, climax, resolution) | values, the gap between what's expected and what happens | every scene turns; complications escalate; the crisis is a real dilemma (two goods or two evils) |
+| **Storynomics** (McKee and Gerace) | purpose-told stories for brands: the customer is the protagonist, the core value shifts, the brand's role is mentor or gift | the brand never steals the protagonist's climax; the value shift is measurable |
+| **Bernays** (*Propaganda*, 1928, public domain in the US since 2024) | persuasion through groups: trusted third parties, the leaders a group follows, events that make news, symbols | a **persuasion lens** for ads, held to raea's rule that claims are true (Film copy rule): it can arrange proof and authority; it can't invent them |
+| **Harmon circle** (8 steps) | a compact cycle for episodes and short films | you, need, go, search, find, take, return, change |
+| **Save the Cat** (15 beats) | page-percentage beats for features | proportions in the running time |
+| **Kishōtenketsu** | four parts with no conflict: introduction, development, twist, reconciliation | the twist recontextualises; no antagonist needed (good for brand and calm pieces) |
+| **Propp** (31 functions) | folk-tale functions as a generative vocabulary | ordering constraints between functions |
+| **Problem, agitate, solve; AIDA** | the ad formats launch videos use | problem stated before the product; the product shown doing the job |
+| **Launch** (learned) | the launch fingerprint's findings (docs: launch corpus below) | priors over hook, reveal time, length, voice, measured from real outcomes |
+
+New lenses are plain modules, so a person or an agent can add one ("my agency's format") with the same four parts.
+
+## Generation without a fixed answer
+
+A story module can hold **choice points** instead of fixed beats:
+
+```ts
+beat("inciting", { choose: ["the backlog doubles", "the client asks for 50 versions", "the editor quits"] })
+```
+
+- **Seeded.** `raea story sample story.ts --seed 7 --n 12` walks the choice points. The same seed gives the same
+ story, and a new seed gives a new one.
+- **Weighted by lenses and by data.** A lens's `propose` adds candidates for stages that are missing. Priors learned
+ from real outcomes (first, the launch corpus's pairs) weight them. The result is varied, but biased toward what has
+ worked.
+- **Pruned by the checks.** A candidate that breaks a type or an exact check is never shown. This is generate-and-test,
+ as `vd evolve` does for worlds.
+- **Leaves written by a model, structure kept by the SDK.** An agent writes a beat's words, but the SDK owns which
+ beats exist, why, and what they change. This split (plan, then write) is what the best LLM story systems do
+ (Dramatron, Re3/DOC, Agents' Room). Our difference is that the plan is typed and checked, not prose.
+- **Across themes.** A story *pattern* is a function from a theme to a story. `raea story matrix pattern.ts --themes
+ themes.ts` runs one pattern across many premises (a coffee brand, a game studio, a skincare line) and reports where
+ it breaks. This is how a beat is tested "across themes and ideas".
+
+## Testing: four levels
+
+1. **Types** (`tsc`, free, instant):
+ - unknown characters, setups and values;
+ - a lens's required stage missing when the story declares that lens strict.
+2. **Exact checks** (`raea story check`, milliseconds, no model):
+ - every beat turns a value;
+ - every beat after the first has a cause;
+ - every setup is paid off and every payoff was set up;
+ - the knowledge model is consistent (no acting on unknown facts);
+ - each lens's order and proportions hold;
+ - the rhythm: no long run of beats turning the same way;
+ - the arc completes (want met or refused, need met or failed).
+3. **Learned judges** (the fingerprint's text modality, EmbeddingGemma heads, milliseconds once trained):
+ - axes such as clear stakes, surprise that's earned, a crisis that's a real choice, and an ending that pays the
+ premise;
+ - each axis starts from its words (zero-shot) and trains from pairs: LitBench's result is that Bradley-Terry heads
+ trained on preference pairs beat every zero-shot LLM judge (78% against 73% agreement with people);
+ - an LLM judge is a checker on top, never the score (as with Clef-Omni).
+4. **Measures of the made piece**:
+ - the finished film's words (measure_film's transcript) and pictures are scored back onto the story's beats: did
+ the turn happen at its time, did the reveal land;
+ - the narrative-arc measures of Boyd, Blackburn and Pennebaker (staging, plot progression and cognitive tension from
+ word categories) are computed on the dialogue and narration, and the emotional arc on the six shapes of Reagan et
+ al.;
+ - for a launch, the outcome itself (engagement against the account's own baseline) is the last word.
+
+Tests are code:
+
+```ts
+test("the turn lands by the midpoint in every theme", () =>
+ forEachTheme(themes, t => expect(sample(pattern(t), { seed })).toTurn("trust", { from: "-", to: "+", by: 0.5 })));
+```
+
+## Games and dialogue
+
+- **Storylets** (quality-based narrative, as Failbetter's and Emily Short's): each beat can compile to a storylet with
+ preconditions on state and effects on it. A **drama manager** picks the next storylet to keep the live game near the
+ story's target tension curve (Façade's beat selection, made a library).
+- **Planning, where characters must act on their own goals and beliefs:** the knowledge model is the same structure a
+ belief-aware narrative planner searches (Ware's Sabre: intention, theory of mind, conflict). A small planner can fill
+ a gap between two beats with actions each character would plausibly take.
+- **Dialogue**: a line carries what's said, what's meant (subtext), and the value it turns. It compiles to `script.ts`
+ lines for a film, and to Ink or Yarn Spinner for a game, so authors can use either engine.
+
+## How state of the art this is
+
+| part | the state of the art | this plan |
+|---|---|---|
+| structure as data | Dramatica's storyform (1990s, closed); narrative planners (Sabre, AIIDE 2021) | typed TypeScript an agent writes; tsc and exact checks |
+| LLM story writing | plan, then write: Dramatron (2022), Re3/DOC (2022-23), Agents' Room (2024) | same split, but the plan is a checked program |
+| consistency | FlawedFictions (2025): plot holes beat nearly every model on longer stories; ConStory-Bench (2026): consistency bugs in long generation | the knowledge model catches the commonest kind by construction, before any words exist |
+| judging quality | LitBench (2025, EACL 2026): reward models trained on pairs reach 78% agreement and beat zero-shot judges | fingerprint text heads trained on our own pairs (launch outcomes, Shane's notes) |
+| measuring arcs | Boyd et al. (2020) narrative arc; Reagan et al. (2016) emotional arcs | computed on the finished piece and laid against the planned beats |
+| interactive story | storylets, drama managers (Façade, Versu), Ink, Yarn | one story model compiles to film and to game |
+
+What's new is the combination: one typed story model, read through many frameworks at once, generated without a
+fixed answer, and tested from the type checker through to the outcome of the finished piece. Nobody ships that, as far
+as I found. Each part is proven somewhere; the risk is in their joins, not in any one part.
+
+What it won't do: no lens and no judge makes a story good. They catch what's broken and rank options. The person still
+chooses (Shane's notes are the training data that matter most).
+
+## The launch corpus: the first data
+
+`~/.vd/launch` (11-22): the whatships.com catalog of 3,328 launch videos posted on X, with each post's engagement.
+- **The pairs:** 158 accounts posted several launches, so each account's best and worst launch is a pair with the
+ audience held fixed.
+- **What's measured:** each film's transcript, shots, sound and pictures (vd's measure_film).
+- **What it gives the story SDK:**
+ - its first learned priors (the launch lens);
+ - its first text-axis training pairs;
+ - a check on whether story structure predicts outcomes at all, apart from distribution.
+
+## Build order
+
+| step | what | confidence |
+|---|---|---|
+| ST0 | the model's types (world, telling, render) and `story()`, compiled to `script.ts`; the four Rust changes (`Brief.story`, `Scene.beat`, story-only checks, checks by package path); the feed shows the story above its script | high |
+| ST1 | exact checks: turns, causes, setups and payoffs, rhythm, arc | high |
+| ST2 | the knowledge model: suspense, mystery, surprise curves and the plot-hole check | medium-high |
+| ST3 | lenses: McKee, Pixar spine, Storynomics, PAS first (the ones ads need), then Campbell/Vogler, Harmon, Save the Cat, Kishōtenketsu, Propp, Bernays | high for the exact parts; their maps are inferred, so medium |
+| ST4 | sampling: choice points, seeds, lens proposals, pruning; `raea story sample`, `matrix` | medium-high |
+| ST5 | the skill tree: craft/story/ in the raea skill, one page a framework in our own words with sources, and a router | high |
+| ST6 | learned judges: text axes on the fingerprint, trained from launch pairs and Shane's notes | medium: depends on whether text predicts outcomes in our data |
+| ST7 | measures of the made piece laid back onto the beats (transcript arcs, beat timing) | medium |
+| ST8 | games: storylets, the drama manager, Ink and Yarn export | medium |
+| ST9 | a gap-filling planner for character actions | low-medium: research-grade, after ST2 shows the knowledge model holds |
+
+Decided 11-22 (Shane):
+- A story is its own module, imported into the brief explicitly (`story:`); nothing reads it unless something
+ imports it.
+- The SDK stays TypeScript. Rust gets only the four small changes above.
+
+Sources:
+- [Sabre](https://www.cs.uky.edu/~sgware/projects/sabre) (Ware and Siler, AIIDE 2021)
+- [FlawedFictions](https://arxiv.org/abs/2504.11900) (2025)
+- [ConStory-Bench](https://arxiv.org/abs/2603.05890) (2026)
+- [LitBench](https://arxiv.org/abs/2507.00769) (2025, EACL 2026)
+- Campbell, *The Hero with a Thousand Faces* (1949)
+- Vogler, *The Writer's Journey*
+- Catmull, *Creativity, Inc.* (2014)
+- McKee, *Story* (1997)
+- McKee and Gerace, *Storynomics* (2018)
+- Bernays, *Propaganda* (1928)
+- Boyd, Blackburn and Pennebaker, "The narrative arc" (Science Advances, 2020)
+- Reagan et al., "The emotional arcs of stories" (EPJ Data Science, 2016)
diff --git a/sdk/story/package.json b/sdk/story/package.json
new file mode 100644
index 00000000..aada3aa4
--- /dev/null
+++ b/sdk/story/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "@raea/story",
+ "license": "FSL-1.1-ALv2",
+ "private": true,
+ "version": "0.1.0",
+ "description": "raea's stories as data (docs/story.md, docs/story.feature): a world of facts and caused events, tellings of it as beats, an ECS whose systems derive value curves, knowledge, suspense, the cause graph and tension, lenses for the storytelling frameworks, seeded sampling, exact checks, mutation for training data, and compilers to raea/brief's Script, storylets and dialogue. No runtime dependencies.",
+ "type": "module",
+ "main": "src/index.ts",
+ "exports": {
+ ".": "./src/index.ts",
+ "./checks": "./src/raea/checks.ts"
+ },
+ "scripts": {
+ "test": "bun test test"
+ }
+}
diff --git a/sdk/story/src/checks.ts b/sdk/story/src/checks.ts
new file mode 100644
index 00000000..c6c0aa7a
--- /dev/null
+++ b/sdk/story/src/checks.ts
@@ -0,0 +1,95 @@
+// Exact checks (docs/story.feature ST2a): read only what the systems derived, never prose, and need no model. Each finding
+// names the beat (b0, b1 ...) or event it's about, says what's wrong in a sentence and how to fix it.
+import type { World } from "./ecs.ts";
+import { beatsOf, eventsOf, infoOf, keysOf, load, type RAgent } from "./load.ts";
+import { listOf, type AnyStory } from "./model.ts";
+import { causes, type Causes } from "./systems/cause.ts";
+import { knowledge, type Audience, type Break } from "./systems/know.ts";
+import { tension } from "./systems/tension.ts";
+import { values, type Curve } from "./systems/values.ts";
+
+export type Level = "error" | "warn" | "note";
+export type Finding = { check: string; level: Level; about: string; says: string; fix?: string };
+
+/** Every system, in the order they need each other. */
+export const derive = (w: World): World => w.run(values, knowledge, causes, tension);
+
+/** A story told one way, loaded and derived: what lenses, checks, compilers and models read. */
+export const analyze = (s: AnyStory, telling?: string, seed = 0): World => derive(load(s, telling, seed));
+
+const RUN = 4; // beats in a row all turning one way before it's worth a note
+
+export function checkWorld(w: World): Finding[] {
+ const out: Finding[] = [];
+ const add = (check: string, level: Level, about: string, says: string, fix?: string) => out.push({ check, level, about, says, fix });
+ const beats = beatsOf(w);
+ const events = eventsOf(w);
+ const c = w.resource<Causes>("Causes")!;
+
+ for (const { e, key, beat } of beats) {
+ const turns = w.must<Record<string, number>>(e, "Turns");
+ if (beat.shows.length && !Object.values(turns).some((d) => d !== 0))
+ add("turns", "warn", key, `${key} shows ${beat.shows.join(", ")} but turns no value: nothing changes`, "give a shown event a turn, or cut the beat");
+ if (!w.must<boolean>(e, "Linked"))
+ add("and-then", "warn", key, `${key} isn't caused by anything the audience has seen: an "and then", not a "therefore" or a "but"`, "show its cause earlier, or name a cause the audience saw");
+ const a = w.must<Audience>(e, "Audience");
+ if (a.surprise) add("surprise", "warn", key, `${key} turns hard on something nothing set up`, "set up a cause earlier, pay a setup here, or mark the beat surprise: \"meant\"");
+ }
+ for (const k of c.uncaused) add("cause", "error", k, `the event ${k} has no cause`, "name the earlier event that causes it (because), or mark it routine");
+ for (const { event, cause } of c.later) add("cause", "error", event, `${event} is caused by ${cause}, which happens later in the world`, "reorder the world, or change the cause");
+ for (const k of c.deadEnds) add("dead-end", "note", k, `the event ${k} causes nothing that follows`, "let a later event come from it, or cut it");
+
+ const planted = new Map<string, number>();
+ const paid = new Set<string>();
+ for (const { key, beat, index } of beats) {
+ for (const p of listOf(beat.pays)) {
+ const at = planted.get(p);
+ if (at === undefined) add("setup", "error", key, `${key} pays off "${p}", which nothing set up before it`, "plant it in an earlier beat (setup)");
+ else if (at === index) add("setup", "warn", key, `${key} sets up and pays off "${p}" in one beat`, "plant it earlier");
+ paid.add(p);
+ }
+ for (const s of listOf(beat.setup)) if (!planted.has(s)) planted.set(s, index);
+ }
+ for (const [s, at] of planted) if (!paid.has(s)) add("setup", "warn", `b${at}`, `b${at} sets up "${s}", which is never paid off`, "pay it off in a later beat (pays), or cut the setup");
+
+ for (const b of w.resource<Break[]>("BeliefBreaks") ?? [])
+ add("belief", "error", b.event, `${b.who} acts on "${b.fact}" in ${b.event} without knowing it yet`, `let ${b.who} learn it earlier (an event that sets or learns it), or drop it from needs`);
+
+ let run = 0, sign = 0;
+ beats.forEach(({ e, key }) => {
+ const net = Object.values(w.must<Record<string, number>>(e, "Turns")).reduce((x, y) => x + y, 0);
+ const s = Math.sign(net);
+ run = s !== 0 && s === sign ? run + 1 : s !== 0 ? 1 : 0;
+ sign = s || sign;
+ if (run === RUN) add("rhythm", "note", key, `${RUN} beats in a row all turn ${s > 0 ? "up" : "down"}, ending at ${key}`, "break the run with a turn the other way");
+ });
+
+ const shown = new Set(beats.flatMap((b) => b.beat.shows));
+ for (const [a, ent] of Object.entries(keysOf(w).agents)) {
+ const ag = w.must<RAgent>(ent, "Agent");
+ if (!ag.want && !ag.need) continue;
+ const settled = events.some((x) => shown.has(x.key) && x.ev.ends?.[a] !== undefined);
+ if (!settled) add("arc", "warn", a, `${a}'s ${ag.need ? "need" : "want"} is never settled in this telling`, `show an event that ends it (ends: { ${a}: "need" })`);
+ }
+
+ const set = new Set<string>();
+ for (const x of events.sort((p, q) => p.order - q.order)) {
+ for (const f of x.ev.sets ?? []) set.add(f);
+ if (x.ev.claim !== undefined) {
+ const proof = x.ev.proof ?? [];
+ if (!proof.length) add("claim", "error", x.key, `${x.key} claims "${x.ev.claim}" with no fact behind it`, "name the facts that prove it (proof), set by events the story shows");
+ for (const f of proof) if (!set.has(f)) add("claim", "error", x.key, `${x.key}'s claim rests on "${f}", which nothing in the world makes true by then`, "show the event that makes it true first");
+ }
+ }
+
+ const focus = infoOf(w).idea?.value;
+ const curves = w.resource<Record<string, Curve>>("Curves") ?? {};
+ if (focus && curves[focus]?.shape === "flat") add("idea", "warn", focus, `the story is about ${focus}, and ${focus} never moves`, "turn it in the beats that matter");
+ return out;
+}
+
+/** Check a story told one way: its findings, errors first. */
+export function checkStory(s: AnyStory, telling?: string, seed = 0): Finding[] {
+ const rank = { error: 0, warn: 1, note: 2 };
+ return checkWorld(analyze(s, telling, seed)).sort((a, b) => rank[a.level] - rank[b.level]);
+}
diff --git a/sdk/story/src/ecs.ts b/sdk/story/src/ecs.ts
new file mode 100644
index 00000000..3417052b
--- /dev/null
+++ b/sdk/story/src/ecs.ts
@@ -0,0 +1,69 @@
+// A small ECS for stories (docs/story.feature ST0b): entities are numbers, components are named plain values, resources
+// are named values on the world, and systems are functions over the world. Plain data throughout, so a world prints as
+// JSON, crosses into raea check, and feeds a model's training rows. It mirrors raea's Bevy world in shape (entities with
+// components, systems that derive) without depending on it: the SDK stays TypeScript with no runtime dependencies.
+
+export type Entity = number;
+export type System = (w: World) => void;
+
+export class World {
+ private next = 0;
+ private readonly comps = new Map<string, Map<Entity, unknown>>();
+ private readonly res = new Map<string, unknown>();
+
+ /** A new entity with these components. */
+ spawn(components: Record<string, unknown> = {}): Entity {
+ const e = this.next++;
+ for (const [k, v] of Object.entries(components)) this.insert(e, k, v);
+ return e;
+ }
+
+ insert<T>(e: Entity, name: string, value: T): void {
+ let m = this.comps.get(name);
+ if (!m) this.comps.set(name, (m = new Map()));
+ m.set(e, value);
+ }
+
+ get<T>(e: Entity, name: string): T | undefined {
+ return this.comps.get(name)?.get(e) as T | undefined;
+ }
+
+ /** A component the caller knows is there (a query found the entity by it). */
+ must<T>(e: Entity, name: string): T {
+ const v = this.get<T>(e, name);
+ if (v === undefined) throw new Error(`entity ${e} has no ${name}`);
+ return v;
+ }
+
+ has(e: Entity, name: string): boolean {
+ return this.comps.get(name)?.has(e) ?? false;
+ }
+
+ /** Entities with every named component, in the order they were spawned. */
+ query(...names: string[]): Entity[] {
+ if (names.length === 0) return [];
+ const [first, ...rest] = names.map((n) => this.comps.get(n) ?? new Map<Entity, unknown>());
+ return [...first.keys()].filter((e) => rest.every((m) => m.has(e))).sort((a, b) => a - b);
+ }
+
+ resource<T>(name: string): T | undefined {
+ return this.res.get(name) as T | undefined;
+ }
+
+ setResource<T>(name: string, value: T): void {
+ this.res.set(name, value);
+ }
+
+ /** Run systems in order. */
+ run(...systems: System[]): this {
+ for (const s of systems) s(this);
+ return this;
+ }
+
+ /** Every entity's components and every resource, as plain data (for printing, raea check and training rows). */
+ toJSON(): { entities: Record<string, Record<string, unknown>>; resources: Record<string, unknown> } {
+ const entities: Record<string, Record<string, unknown>> = {};
+ for (const [name, m] of this.comps) for (const [e, v] of m) (entities[e] ??= {})[name] = v;
+ return { entities, resources: Object.fromEntries(this.res) };
+ }
+}
diff --git a/sdk/story/src/index.ts b/sdk/story/src/index.ts
new file mode 100644
index 00000000..98f27a9e
--- /dev/null
+++ b/sdk/story/src/index.ts
@@ -0,0 +1,12 @@
+// raea/story (docs/story.md, docs/story.feature): stories as data. Write one with story(), load a telling of it into a
+// world, derive what's never written, check it, read it through lenses, sample it, mutate it, compile it.
+export * from "./model.ts";
+export { World, type Entity, type System } from "./ecs.ts";
+export { load, beatsOf, eventsOf, keysOf, infoOf, type Keys, type StoryInfo, type REvent, type RBeat } from "./load.ts";
+export { resolve, rng, pick, hasChoices } from "./resolve.ts";
+export { values, shapeOf, type Curve, type Shape } from "./systems/values.ts";
+export { knowledge, type Audience, type Break } from "./systems/know.ts";
+export { causes, type Causes } from "./systems/cause.ts";
+export { tension } from "./systems/tension.ts";
+export { analyze, derive, checkStory, checkWorld, type Finding, type Level } from "./checks.ts";
+export { mutants, sampleMutants, type Mutant, type Label, type Kind } from "./mutate.ts";
diff --git a/sdk/story/src/load.ts b/sdk/story/src/load.ts
new file mode 100644
index 00000000..98e8d270
--- /dev/null
+++ b/sdk/story/src/load.ts
@@ -0,0 +1,47 @@
+// A story and one of its tellings into a world (docs/story.feature ST0b). Choice points are resolved first, with the seed
+// given (sample.ts), so a loaded world is always one definite story. Components:
+// values { Key, Value } facts { Key, Fact } agents { Key, Agent }
+// events { Key, Event, Order } (Order: its place in the world's story order)
+// beats { Key, Beat, Index } (Index: its place in the telling; Key "b0", "b1" ...)
+// Resources: "Story" (title, premise, idea, lenses, telling's name) and "Keys" (each key's entity, by kind).
+import { World, type Entity } from "./ecs.ts";
+import type { Agent, AnyStory, Beat, Event, Value } from "./model.ts";
+import { resolve } from "./resolve.ts";
+
+export type Resolved<T> = T extends { choice: readonly (infer U)[] } ? U : T extends object ? { [K in keyof T]: Resolved<T[K]> } : T;
+export type REvent = Resolved<Event<string, string, string, string>>;
+export type RBeat = Resolved<Beat<string, string, string, string>>;
+export type RAgent = Agent<string>;
+
+export type Keys = { values: Record<string, Entity>; facts: Record<string, Entity>; agents: Record<string, Entity>; events: Record<string, Entity>; beats: Entity[] };
+export type StoryInfo = { title?: string; premise?: string; idea?: AnyStory["idea"]; lenses: string[]; telling: string };
+
+/** The world of a story told one way. `telling` defaults to the story's first. */
+export function load(s: AnyStory, telling?: string, seed = 0): World {
+ const r = resolve(s, seed);
+ const name = telling ?? Object.keys(r.tellings)[0];
+ const beats = r.tellings[name];
+ if (!beats) throw new Error(`the story has no telling named ${name} (it has ${Object.keys(r.tellings).join(", ")})`);
+ const w = new World();
+ const keys: Keys = { values: {}, facts: {}, agents: {}, events: {}, beats: [] };
+ for (const [k, v] of Object.entries(r.values as Record<string, Value>)) keys.values[k] = w.spawn({ Key: k, Value: v });
+ for (const [k, f] of Object.entries((r.facts ?? {}) as Record<string, string>)) keys.facts[k] = w.spawn({ Key: k, Fact: { text: f } });
+ for (const [k, a] of Object.entries(r.agents as Record<string, RAgent>)) keys.agents[k] = w.spawn({ Key: k, Agent: a });
+ Object.entries(r.world as Record<string, REvent>).forEach(([k, e], i) => (keys.events[k] = w.spawn({ Key: k, Event: e, Order: i })));
+ (beats as RBeat[]).forEach((b, i) => keys.beats.push(w.spawn({ Key: `b${i}`, Beat: b, Index: i })));
+ w.setResource<Keys>("Keys", keys);
+ w.setResource<StoryInfo>("Story", { title: r.title, premise: r.premise as string | undefined, idea: r.idea, lenses: r.lenses ?? [], telling: name });
+ return w;
+}
+
+/** Helpers every system uses. */
+export const keysOf = (w: World): Keys => w.resource<Keys>("Keys")!;
+export const infoOf = (w: World): StoryInfo => w.resource<StoryInfo>("Story")!;
+export const beatsOf = (w: World): { e: Entity; key: string; beat: RBeat; index: number }[] =>
+ keysOf(w).beats.map((e) => ({ e, key: w.must<string>(e, "Key"), beat: w.must<RBeat>(e, "Beat"), index: w.must<number>(e, "Index") }));
+export const eventsOf = (w: World): { e: Entity; key: string; ev: REvent; order: number }[] =>
+ Object.entries(keysOf(w).events).map(([key, e]) => ({ e, key, ev: w.must<REvent>(e, "Event"), order: w.must<number>(e, "Order") }));
+export const eventByKey = (w: World, key: string): REvent | undefined => {
+ const e = keysOf(w).events[key];
+ return e === undefined ? undefined : w.get<REvent>(e, "Event");
+};
diff --git a/sdk/story/src/model.ts b/sdk/story/src/model.ts
new file mode 100644
index 00000000..ca6c3fc3
--- /dev/null
+++ b/sdk/story/src/model.ts
@@ -0,0 +1,146 @@
+// The story model (docs/story.feature ST0a): a story is data in three layers. The world holds facts and the events that
+// change them, each event with the event that caused it, in story order. A telling is a list of beats: which events the
+// audience sees, in what order, what each one reveals and the feeling it aims for. The render is raea/brief's Script,
+// compiled from a telling (compile.ts). Every reference is a typed key, so tsc refuses a story that names an agent, a
+// fact, a value, an event or a setup it doesn't declare. Keys are inferred where they're declared and checked
+// (NoInfer) where they're used.
+
+/** A quality at stake, with two poles (McKee's value): `value("buried", "free")`. */
+export type Value = { neg: string; pos: string };
+export const value = (neg: string, pos: string): Value => ({ neg, pos });
+
+/** A choice point: the story holds options, and sampling picks one with a seed (sample.ts). */
+export type Choice<T> = { readonly choice: readonly T[]; readonly weights?: readonly number[] };
+export const choose = <const T>(options: readonly T[], weights?: readonly number[]): Choice<T> => ({ choice: options, weights });
+export const isChoice = (x: unknown): x is Choice<unknown> =>
+ typeof x === "object" && x !== null && Array.isArray((x as { choice?: unknown }).choice);
+/** A field that may be fixed or a choice point. */
+export type Maybe<T> = T | Choice<T>;
+
+/** The masks a character wears in a beat (Campbell and Vogler's archetypes as functions, not types). */
+export type Mask = "hero" | "mentor" | "ally" | "herald" | "threshold" | "shapeshifter" | "shadow" | "trickster" | "gift";
+
+/** The feeling a beat aims for in the audience. An open set; these are the ones the lenses read. */
+export type Feeling =
+ | "curiosity" | "recognition" | "concern" | "dread" | "hope" | "relief" | "delight" | "surprise" | "awe" | "resolve"
+ | (string & {});
+
+export type Agent<F extends string> = {
+ /** what they consciously want */
+ want?: string;
+ /** what they need, often against the want */
+ need?: string;
+ /** the lie they believe at the start */
+ lie?: string;
+ mask?: Mask;
+ /** facts they hold true from the start */
+ believes?: NoInfer<F>[];
+ arc?: "positive" | "negative" | "flat";
+ /** the customer, the brand: Storynomics reads these */
+ role?: "customer" | "brand" | (string & {});
+};
+
+export type Event<V extends string, F extends string, A extends string, E extends string> = {
+ who: NoInfer<A>;
+ /** others who act with them (the brand helping the customer act, Storynomics) */
+ with?: NoInfer<A>[];
+ does: Maybe<string>;
+ /** the earlier event or events that caused this one; every event after the first has one */
+ because?: NoInfer<E> | NoInfer<E>[];
+ /** facts `who` acts on: they must hold them when this happens */
+ needs?: NoInfer<F>[];
+ /** facts this makes true (everyone in the event learns them) */
+ sets?: NoInfer<F>[];
+ /** facts this makes false */
+ unsets?: NoInfer<F>[];
+ /** facts `who` comes to know without making them true */
+ learns?: NoInfer<F>[];
+ /** how far each value moves, in steps (+2 is a big turn toward the positive pole) */
+ turns?: Partial<Record<NoInfer<V>, number>>;
+ /** what this settles for an agent: their want met or refused, their need met, their lie dropped */
+ ends?: Partial<Record<NoInfer<A>, "want" | "need" | "lie" | "want-refused">>;
+ /** a dilemma: the options the agent chooses between (McKee's crisis) */
+ dilemma?: string[];
+ /** a claim made to the audience; `proof` names the facts behind it (Bernays: arrange proof, never invent it) */
+ claim?: string;
+ proof?: NoInfer<F>[];
+ /** a routine event: how things are every day (Pixar's spine) */
+ routine?: boolean;
+};
+
+export type Line<A extends string> = {
+ who: NoInfer<A> | "narrator";
+ says: Maybe<string>;
+ /** the subtext: what's meant */
+ means?: string;
+ /** how it's said (a screenplay's parenthetical) */
+ how?: string;
+};
+
+export type Beat<F extends string, A extends string, E extends string, S extends string> = {
+ /** the events the audience sees; a beat with none is narration or a title over them */
+ shows: NoInfer<E>[];
+ /** facts the audience learns here beyond what the shown events set */
+ reveals?: NoInfer<F>[];
+ /** facts a shown event sets that the audience does NOT learn here (a secret) */
+ hides?: NoInfer<F>[];
+ /** questions the beat raises: facts the audience now wants to know */
+ asks?: NoInfer<F>[];
+ feel?: Maybe<Feeling>;
+ /** a setup this beat plants, by a name of the story's choosing */
+ setup?: S | S[];
+ /** a setup this beat pays off */
+ pays?: NoInfer<S> | NoInfer<S>[];
+ /** this beat's stage in a lens, by lens name, when the lens shouldn't infer it */
+ stage?: Record<string, string>;
+ /** a surprise the story means (a reveal nothing set up) */
+ surprise?: "meant";
+ says?: Line<A>[];
+ /** what's on screen, when it says more than the events' `does` */
+ onScreen?: Maybe<string>;
+ seconds?: number;
+};
+
+export type Telling<F extends string, A extends string, E extends string, S extends string> = Beat<F, A, E, S>[];
+
+export type StorySpec<
+ V extends string, F extends string, A extends string, E extends string, S extends string, T extends string,
+> = {
+ title?: string;
+ premise?: Maybe<string>;
+ /** the controlling idea and its counter (McKee): the value it's about and what the story argues */
+ idea?: { value?: NoInfer<V>; side: string; counter?: string };
+ values: Record<V, Value>;
+ facts?: Record<F, string>;
+ agents: Record<A, Agent<F>>;
+ /** events in story order (the order things happen in the world) */
+ world: Record<E, Event<V, F, A, E>>;
+ /** each telling: one cut of the film, a trailer, a game's critical path */
+ tellings: Record<T, Telling<F, A, E, S>>;
+ /** the lenses it's read and checked through by default (lens.ts) */
+ lenses?: string[];
+};
+
+/** A story: the spec with its kind, so a brief, a check or a composition can tell it from other data. */
+export type Story<
+ V extends string = string, F extends string = string, A extends string = string,
+ E extends string = string, S extends string = string, T extends string = string,
+> = StorySpec<V, F, A, E, S, T> & { kind: "story" };
+
+/** Any story, whatever its keys: what systems, checks and lenses take. */
+export type AnyStory = Story<string, string, string, string, string, string>;
+
+/** A story (NAME.story.ts), its references checked by tsc. */
+export function story<
+ const V extends string, const F extends string = never, const A extends string = never,
+ const E extends string = never, const S extends string = never, const T extends string = never,
+>(s: StorySpec<V, F, A, E, S, T>): Story<V, F, A, E, S, T> {
+ return { ...s, kind: "story" };
+}
+
+export const isStory = (x: unknown): x is AnyStory => typeof x === "object" && x !== null && (x as { kind?: unknown }).kind === "story";
+
+/** The causes of an event as a list. */
+export const causesOf = (e: { because?: string | string[] }): string[] => (e.because === undefined ? [] : Array.isArray(e.because) ? e.because : [e.because]);
+/** A setup or payoff field as a list. */
+export const listOf = <T>(x: T | T[] | undefined): T[] => (x === undefined ? [] : Array.isArray(x) ? x : [x]);
diff --git a/sdk/story/src/mutate.ts b/sdk/story/src/mutate.ts
new file mode 100644
index 00000000..0557114a
--- /dev/null
+++ b/sdk/story/src/mutate.ts
@@ -0,0 +1,89 @@
+// Mutation (docs/story.feature ST6a): break a valid story in one known way and say exactly what was broken and where.
+// Because a story is data, these labels are exact and free, as many as wanted: the training rows for a critic. Some
+// breaks the exact checks find by construction (a dropped setup); others they can't (two beats swapped so the story
+// drags), and those are what a learned critic is for. `expect` names the check that should find it, when one should.
+import { listOf, type AnyStory } from "./model.ts";
+import { resolve, rng } from "./resolve.ts";
+
+export type Kind =
+ | "drop-setup" | "drop-payoff" | "drop-cause" | "early-need" | "flatten-beat" | "drop-proof" | "swap-beats" | "drop-cause-beat" | "orphan-event";
+export type Label = { kind: Kind; at: string; says: string; expect?: string };
+export type Mutant = { story: AnyStory; telling: string; label: Label };
+
+type Tell = AnyStory["tellings"][string];
+type Ev = AnyStory["world"][string];
+const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x)) as T;
+
+/** Every way this story told this way can be broken, each as one mutant. */
+export function mutants(s: AnyStory, telling?: string, seed = 0): Mutant[] {
+ const base = resolve(s, seed);
+ const t = telling ?? Object.keys(base.tellings)[0];
+ const out: Mutant[] = [];
+ const beats = (): Tell => out.length >= 0 ? (clone(base.tellings[t]) as Tell) : [];
+ const withTelling = (b: Tell, world = base.world): AnyStory => ({ ...clone(base), world: clone(world), tellings: { ...clone(base.tellings), [t]: b } });
+ const keys = Object.keys(base.world);
+
+ base.tellings[t].forEach((beat, i) => {
+ for (const p of listOf(beat.setup)) {
+ if (!base.tellings[t].some((x, j) => j > i && listOf(x.pays).includes(p))) continue;
+ const b = beats(); b[i] = { ...b[i], setup: listOf(b[i].setup).filter((x) => x !== p) };
+ out.push({ story: withTelling(b), telling: t, label: { kind: "drop-setup", at: `b${i}`, says: `the setup "${p}" was removed`, expect: "setup" } });
+ }
+ for (const p of listOf(beat.pays)) {
+ const b = beats(); b[i] = { ...b[i], pays: listOf(b[i].pays).filter((x) => x !== p) };
+ out.push({ story: withTelling(b), telling: t, label: { kind: "drop-payoff", at: `b${i}`, says: `the payoff of "${p}" was removed`, expect: "setup" } });
+ }
+ const turning = beat.shows.filter((k) => Object.values(base.world[k]?.turns ?? {}).some((d) => d));
+ if (turning.length && !base.tellings[t].some((x, j) => j !== i && x.shows.some((k) => turning.includes(k)))) {
+ const world = clone(base.world);
+ for (const k of turning) world[k] = { ...world[k], turns: {} } as Ev;
+ out.push({ story: withTelling(beats(), world), telling: t, label: { kind: "flatten-beat", at: `b${i}`, says: `b${i}'s events no longer turn anything`, expect: "turns" } });
+ }
+ if (i + 1 < base.tellings[t].length) {
+ const b = beats(); [b[i], b[i + 1]] = [b[i + 1], b[i]];
+ out.push({ story: withTelling(b), telling: t, label: { kind: "swap-beats", at: `b${i}`, says: `b${i} and b${i + 1} were swapped` } });
+ }
+ });
+
+ keys.forEach((k, i) => {
+ const ev = base.world[k];
+ if (i > 0 && ev.because !== undefined && !ev.routine) {
+ const world = clone(base.world); world[k] = { ...world[k], because: undefined } as Ev;
+ out.push({ story: withTelling(beats(), world), telling: t, label: { kind: "drop-cause", at: k, says: `${k} lost its cause`, expect: "cause" } });
+ }
+ const later = keys.slice(i + 1).flatMap((l) => base.world[l].sets ?? []).find((f) => !(ev.needs ?? []).includes(f) && !(base.agents[ev.who]?.believes ?? []).includes(f));
+ if (later) {
+ const world = clone(base.world); world[k] = { ...world[k], needs: [...(ev.needs ?? []), later] } as Ev;
+ out.push({ story: withTelling(beats(), world), telling: t, label: { kind: "early-need", at: k, says: `${ev.who} now acts in ${k} on "${later}" before it's true`, expect: "belief" } });
+ }
+ if (ev.claim !== undefined && (ev.proof ?? []).length) {
+ const world = clone(base.world); world[k] = { ...world[k], proof: [] } as Ev;
+ out.push({ story: withTelling(beats(), world), telling: t, label: { kind: "drop-proof", at: k, says: `${k}'s claim lost its proof`, expect: "claim" } });
+ }
+ });
+
+ // a beat that shows the only sight of a cause of a later big turn, dropped
+ base.tellings[t].forEach((beat, i) => {
+ const b = beats().filter((_, j) => j !== i);
+ const shownLater = new Set(b.slice(i).flatMap((x) => x.shows));
+ const causeOfLater = beat.shows.some((k) => [...shownLater].some((l) => listOf(base.world[l]?.because).includes(k)));
+ if (i > 0 && causeOfLater && !b.some((x) => x.shows.some((k) => beat.shows.includes(k))) && !b.some((x) => listOf(x.pays).some((p) => listOf(beat.setup).includes(p))))
+ out.push({ story: withTelling(b), telling: t, label: { kind: "drop-cause-beat", at: `b${i}`, says: `b${i}, the only sight of a cause, was cut`, expect: "and-then" } });
+ });
+
+ const world = clone(base.world);
+ const who = Object.keys(base.agents)[0];
+ world["orphan"] = { who, does: "does something unrelated", turns: {} } as Ev;
+ const b = beats();
+ const at = Math.max(1, Math.floor(b.length / 2));
+ b.splice(at, 0, { shows: ["orphan"] });
+ out.push({ story: withTelling(b, world), telling: t, label: { kind: "orphan-event", at: `b${at}`, says: "an uncaused event that turns nothing was inserted", expect: "cause" } });
+ return out;
+}
+
+/** A random selection of mutants, for training rows. */
+export function sampleMutants(s: AnyStory, n: number, seed = 0, telling?: string): Mutant[] {
+ const all = mutants(s, telling, seed);
+ const r = rng(seed + 1);
+ return Array.from({ length: Math.min(n, all.length) }, () => all.splice(Math.floor(r() * all.length), 1)[0]);
+}
diff --git a/sdk/story/src/resolve.ts b/sdk/story/src/resolve.ts
new file mode 100644
index 00000000..6cf9e7b9
--- /dev/null
+++ b/sdk/story/src/resolve.ts
@@ -0,0 +1,46 @@
+// Resolving choice points with a seed (docs/story.feature ST4a). The story is walked in a fixed order (keys as written),
+// and each choice point draws from one seeded generator, so the same seed always gives the same story and a story with
+// no choices is returned as it is (copied).
+import { isChoice, type AnyStory } from "./model.ts";
+
+/** mulberry32: small, fast, and the same in every engine. */
+export function rng(seed: number): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** One option of a choice, by its weights (equal when none). */
+export function pick<T>(options: readonly T[], weights: readonly number[] | undefined, r: () => number): T {
+ const ws = options.map((_, i) => Math.max(0, weights?.[i] ?? 1));
+ const total = ws.reduce((a, b) => a + b, 0);
+ if (total <= 0) return options[0];
+ let x = r() * total;
+ for (let i = 0; i < options.length; i++) if ((x -= ws[i]) < 0) return options[i];
+ return options[options.length - 1];
+}
+
+function walk(x: unknown, r: () => number): unknown {
+ if (isChoice(x)) return walk(pick(x.choice, x.weights, r), r);
+ if (Array.isArray(x)) return x.map((v) => walk(v, r));
+ if (x && typeof x === "object") return Object.fromEntries(Object.entries(x).map(([k, v]) => [k, walk(v, r)]));
+ return x;
+}
+
+/** The story with every choice point picked, for this seed. */
+export function resolve<S extends AnyStory>(s: S, seed = 0): S {
+ return walk(s, rng(seed)) as S;
+}
+
+/** Whether a story still holds choice points. */
+export function hasChoices(x: unknown): boolean {
+ if (isChoice(x)) return true;
+ if (Array.isArray(x)) return x.some(hasChoices);
+ if (x && typeof x === "object") return Object.values(x).some(hasChoices);
+ return false;
+}
diff --git a/sdk/story/src/systems/cause.ts b/sdk/story/src/systems/cause.ts
new file mode 100644
index 00000000..3a598b64
--- /dev/null
+++ b/sdk/story/src/systems/cause.ts
@@ -0,0 +1,46 @@
+// The cause graph (docs/story.feature ST1a). In the world: an event after the first with no cause (and not routine), a
+// cause that happens after its effect, and an event that causes nothing and isn't the last ("leads nowhere"). In a
+// telling: a beat none of whose events was caused by something the audience has already seen is an "and then" link
+// (Parker and Stone's "therefore / but" rule; McKee's causality). Showing an event again doesn't explain it: a
+// flash-forward's event shown a second time still needs a cause the audience has seen. Beats get "Linked"; the world
+// gets "Causes".
+import type { World } from "../ecs.ts";
+import { beatsOf, eventsOf } from "../load.ts";
+import { causesOf } from "../model.ts";
+
+export type Causes = { uncaused: string[]; later: { event: string; cause: string }[]; deadEnds: string[]; edges: [string, string][] };
+
+export function causes(w: World): void {
+ const events = eventsOf(w).sort((a, b) => a.order - b.order);
+ const order = Object.fromEntries(events.map((x) => [x.key, x.order]));
+ const out: Causes = { uncaused: [], later: [], deadEnds: [], edges: [] };
+ const causesSomething = new Set<string>();
+ for (const { key, ev, order: o } of events) {
+ const cs = causesOf(ev);
+ if (o > 0 && cs.length === 0 && !ev.routine) out.uncaused.push(key);
+ for (const c of cs) {
+ out.edges.push([c, key]);
+ causesSomething.add(c);
+ if ((order[c] ?? -1) >= o) out.later.push({ event: key, cause: c });
+ }
+ }
+ const last = events[events.length - 1]?.key;
+ for (const { key, ev } of events) if (key !== last && !causesSomething.has(key) && !ev.routine) out.deadEnds.push(key);
+ w.setResource<Causes>("Causes", out);
+
+ const byKey = Object.fromEntries(events.map((x) => [x.key, x.ev]));
+ const seen = new Set<string>();
+ for (const { e, beat, index } of beatsOf(w)) {
+ const linked =
+ index === 0 ||
+ beat.shows.length === 0 ||
+ beat.shows.some((s) => {
+ const ev = byKey[s];
+ if (!ev) return false;
+ if (ev.routine || order[s] === 0) return true;
+ return causesOf(ev).some((c) => seen.has(c) || beat.shows.includes(c));
+ });
+ w.insert(e, "Linked", linked);
+ for (const s of beat.shows) seen.add(s);
+ }
+}
diff --git a/sdk/story/src/systems/know.ts b/sdk/story/src/systems/know.ts
new file mode 100644
index 00000000..21a28e51
--- /dev/null
+++ b/sdk/story/src/systems/know.ts
@@ -0,0 +1,71 @@
+// Knowledge (docs/story.feature ST1a): who knows what, when.
+// In the world (story order): each agent starts with what they believe; an event's participants learn what it sets,
+// its agent learns what it `learns`; an event whose agent acts on (`needs`) a fact they don't hold is a belief break,
+// the plot hole FlawedFictions measures, found here from the data.
+// In a telling (the audience's order): a beat teaches the audience what its events set, less what it `hides`, plus what
+// it `reveals`; `asks` opens a question, and learning the fact closes it. On a beat:
+// suspense facts the audience holds that an agent on screen doesn't and will need (or that the world sets later)
+// mystery the questions still open
+// surprise a big turn none of whose causes the audience has seen, and no setup paid (unless the beat means it)
+import type { World } from "../ecs.ts";
+import { beatsOf, eventsOf, keysOf, type RAgent, type REvent } from "../load.ts";
+import { causesOf, listOf } from "../model.ts";
+
+export type Break = { event: string; who: string; fact: string };
+export type Audience = { knows: string[]; learned: string[]; open: string[]; answered: string[]; suspense: { who: string; fact: string }[]; surprise: boolean };
+
+export function knowledge(w: World): void {
+ const k = keysOf(w);
+ const known: Record<string, Set<string>> = {};
+ for (const [a, e] of Object.entries(k.agents)) known[a] = new Set(w.must<RAgent>(e, "Agent").believes ?? []);
+ const breaks: Break[] = [];
+ const events = eventsOf(w).sort((a, b) => a.order - b.order);
+ const knowsBefore: Record<string, Record<string, string[]>> = {};
+ for (const { e, key, ev } of events) {
+ knowsBefore[key] = Object.fromEntries(Object.entries(known).map(([a, s]) => [a, [...s]]));
+ for (const f of ev.needs ?? []) if (!known[ev.who]?.has(f)) breaks.push({ event: key, who: ev.who, fact: f });
+ for (const who of [ev.who, ...(ev.with ?? [])]) for (const f of ev.sets ?? []) known[who]?.add(f);
+ for (const f of ev.learns ?? []) known[ev.who]?.add(f);
+ w.insert(e, "KnowsBefore", knowsBefore[key]);
+ }
+ w.setResource<Break[]>("BeliefBreaks", breaks);
+
+ const byKey: Record<string, { order: number; ev: REvent }> = Object.fromEntries(events.map((x) => [x.key, { order: x.order, ev: x.ev }]));
+ const audience = new Set<string>();
+ const open = new Set<string>();
+ const seen = new Set<string>();
+ for (const { e, beat, index } of beatsOf(w)) {
+ const learned = new Set<string>();
+ for (const s of beat.shows) for (const f of byKey[s]?.ev.sets ?? []) if (!(beat.hides ?? []).includes(f)) learned.add(f);
+ for (const f of beat.reveals ?? []) learned.add(f);
+ for (const f of learned) audience.add(f);
+ const answered = [...open].filter((f) => audience.has(f));
+ for (const f of answered) open.delete(f);
+ for (const f of beat.asks ?? []) if (!audience.has(f)) open.add(f);
+
+ // suspense: an agent on screen lacks a fact the audience holds, and needs it later or the world sets it later
+ const suspense: { who: string; fact: string }[] = [];
+ const first = [...beat.shows].sort((a, b) => (byKey[a]?.order ?? 0) - (byKey[b]?.order ?? 0))[0];
+ const now = first !== undefined ? byKey[first]?.order ?? 0 : 0;
+ const onScreen = new Set(beat.shows.flatMap((s) => (byKey[s] ? [byKey[s].ev.who, ...(byKey[s].ev.with ?? [])] : [])));
+ for (const who of onScreen) {
+ const theirs = new Set(first !== undefined ? knowsBefore[first]?.[who] ?? [] : []);
+ for (const f of audience) {
+ if (theirs.has(f)) continue;
+ const later = events.some((x) => x.order >= now && ((x.ev.who === who && (x.ev.needs ?? []).includes(f)) || (x.order > now && (x.ev.sets ?? []).includes(f))));
+ if (later) suspense.push({ who, fact: f });
+ }
+ }
+
+ // surprise: a big turn whose causes the audience never saw, with no setup paid
+ const big = beat.shows.some((s) => Object.values(byKey[s]?.ev.turns ?? {}).reduce<number>((a, d) => a + Math.abs(d ?? 0), 0) >= 2);
+ const causesSeen = beat.shows.every((s) => {
+ const cs = causesOf(byKey[s]?.ev ?? {});
+ return cs.length === 0 || cs.some((c) => seen.has(c) || beat.shows.includes(c)) || seen.has(s);
+ });
+ const surprise = index > 0 && big && !causesSeen && listOf(beat.pays).length === 0 && beat.surprise !== "meant";
+ for (const s of beat.shows) seen.add(s);
+
+ w.insert<Audience>(e, "Audience", { knows: [...audience], learned: [...learned], open: [...open], answered, suspense, surprise });
+ }
+}
diff --git a/sdk/story/src/systems/tension.ts b/sdk/story/src/systems/tension.ts
new file mode 100644
index 00000000..e15ca2ae
--- /dev/null
+++ b/sdk/story/src/systems/tension.ts
@@ -0,0 +1,31 @@
+// Tension (docs/story.feature ST1a): at each beat, from what the audience is waiting on and how much is at stake.
+// open questions (mystery), capped at 3 weight 0.4
+// suspense (facts an agent lacks), capped at 3 weight 0.3
+// pressure: how near the idea's value (else every value, averaged) is to its lowest in this telling, 0 to 1 weight 0.3
+// Beats get "Tension" (0 to 1); the world gets "TensionCurve". Needs values and knowledge first.
+import type { World } from "../ecs.ts";
+import { beatsOf, infoOf } from "../load.ts";
+import type { Audience } from "./know.ts";
+import type { Curve } from "./values.ts";
+
+export function tension(w: World): void {
+ const curves = w.resource<Record<string, Curve>>("Curves") ?? {};
+ const focus = infoOf(w).idea?.value;
+ const names = focus && curves[focus] ? [focus] : Object.keys(curves);
+ const curve: number[] = [];
+ for (const { e, index } of beatsOf(w)) {
+ const a = w.must<Audience>(e, "Audience");
+ const pressure = names.length
+ ? names.reduce((sum, n) => {
+ const l = curves[n].levels.slice(1);
+ const lo = Math.min(...l), hi = Math.max(...l);
+ return sum + (hi === lo ? 0 : (hi - l[index]) / (hi - lo));
+ }, 0) / names.length
+ : 0;
+ const t = 0.4 * (Math.min(a.open.length, 3) / 3) + 0.3 * (Math.min(a.suspense.length, 3) / 3) + 0.3 * pressure;
+ const r = Math.round(t * 1000) / 1000;
+ w.insert(e, "Tension", r);
+ curve.push(r);
+ }
+ w.setResource<number[]>("TensionCurve", curve);
+}
diff --git a/sdk/story/src/systems/values.ts b/sdk/story/src/systems/values.ts
new file mode 100644
index 00000000..251ebad4
--- /dev/null
+++ b/sdk/story/src/systems/values.ts
@@ -0,0 +1,49 @@
+// Value curves (docs/story.feature ST1a). In the world, each event moves the values it turns, in story order, so every
+// event has the world's level after it. In a telling, a beat's level is the world's level after the latest event it
+// shows (a flash-forward shows a later level, a flashback an earlier one), and its turn is the sum of what its events
+// turn. Beats get "Turns" and "Level"; the world gets "Curves", each value's levels over the telling and its shape.
+import type { World } from "../ecs.ts";
+import { beatsOf, eventsOf, keysOf, type REvent } from "../load.ts";
+
+export type Shape = "flat" | "rise" | "fall" | "fall-rise" | "rise-fall" | "rise-fall-rise" | "fall-rise-fall" | "complex";
+export type Curve = { levels: number[]; shape: Shape };
+
+const SHAPES: Record<string, Shape> = { "": "flat", "+": "rise", "-": "fall", "-+": "fall-rise", "+-": "rise-fall", "+-+": "rise-fall-rise", "-+-": "fall-rise-fall" };
+
+/** The shape of a series: the signs of its moves, runs of one sign merged (Reagan et al.'s six arcs, and flat). */
+export function shapeOf(levels: number[]): Shape {
+ let signs = "";
+ for (let i = 1; i < levels.length; i++) {
+ const d = levels[i] - levels[i - 1];
+ if (d === 0) continue;
+ const s = d > 0 ? "+" : "-";
+ if (!signs.endsWith(s)) signs += s;
+ }
+ return SHAPES[signs] ?? "complex";
+}
+
+export function values(w: World): void {
+ const names = Object.keys(keysOf(w).values);
+ const level: Record<string, number> = Object.fromEntries(names.map((n) => [n, 0]));
+ const after: Record<string, Record<string, number>> = {};
+ for (const { e, key, ev } of eventsOf(w).sort((a, b) => a.order - b.order)) {
+ for (const [v, d] of Object.entries((ev as REvent).turns ?? {})) level[v] = (level[v] ?? 0) + (d ?? 0);
+ after[key] = { ...level };
+ w.insert(e, "LevelAfter", after[key]);
+ }
+ const start: Record<string, number> = Object.fromEntries(names.map((n) => [n, 0]));
+ let last = start;
+ const series: Record<string, number[]> = Object.fromEntries(names.map((n) => [n, [0]]));
+ const order = Object.fromEntries(eventsOf(w).map((x) => [x.key, x.order]));
+ for (const { e, beat } of beatsOf(w)) {
+ const turns: Record<string, number> = {};
+ for (const k of beat.shows) for (const [v, d] of Object.entries(eventsOf(w).find((x) => x.key === k)?.ev.turns ?? {})) turns[v] = (turns[v] ?? 0) + (d ?? 0);
+ const latest = [...beat.shows].sort((a, b) => (order[b] ?? -1) - (order[a] ?? -1))[0];
+ const lvl = latest !== undefined && after[latest] ? after[latest] : last;
+ w.insert(e, "Turns", turns);
+ w.insert(e, "Level", lvl);
+ for (const n of names) series[n].push(lvl[n]);
+ last = lvl;
+ }
+ w.setResource<Record<string, Curve>>("Curves", Object.fromEntries(names.map((n) => [n, { levels: series[n], shape: shapeOf(series[n]) }])));
+}
diff --git a/sdk/story/test/checks.test.ts b/sdk/story/test/checks.test.ts
new file mode 100644
index 00000000..f7967920
--- /dev/null
+++ b/sdk/story/test/checks.test.ts
@@ -0,0 +1,24 @@
+import { expect, test } from "bun:test";
+import { analyze, checkStory, type Curve, type Audience, beatsOf } from "../src/index.ts";
+import { launch } from "./fixture.ts";
+
+test("the launch story passes every exact check", () => {
+ const f = checkStory(launch, "30s");
+ expect(f.filter((x) => x.level !== "note")).toEqual([]);
+});
+
+test("derived: freedom falls then rises; the opening asks a question the last beat answers", () => {
+ const w = analyze(launch, "30s");
+ const curves = w.resource<Record<string, Curve>>("Curves")!;
+ expect(curves.freedom.levels).toEqual([0, 0, -3, -3, 0]);
+ expect(curves.freedom.shape).toBe("fall-rise");
+ const aud = beatsOf(w).map((b) => w.must<Audience>(b.e, "Audience"));
+ expect(aud[0].open).toEqual(["recipeRuns"]);
+ expect(aud[3].answered).toEqual(["recipeRuns"]);
+ expect(aud[3].open).toEqual([]);
+});
+
+test("the same seed gives the same story", () => {
+ const a = analyze(launch, "30s", 7).toJSON(), b = analyze(launch, "30s", 7).toJSON();
+ expect(a).toEqual(b);
+});
diff --git a/sdk/story/test/fixture.ts b/sdk/story/test/fixture.ts
new file mode 100644
index 00000000..cadd0a32
--- /dev/null
+++ b/sdk/story/test/fixture.ts
@@ -0,0 +1,28 @@
+// The launch story of docs/story.md, used by every test.
+import { choose, story, value } from "../src/model.ts";
+
+export const launch = story({
+ title: "raea cloud",
+ idea: { value: "freedom", side: "your recipe, run for you, frees you", counter: "only hands-on work is good work" },
+ values: { freedom: value("buried", "free"), trust: value("doubt", "trust") },
+ facts: { backlog: "the backlog is out of hand", recipeRuns: "the recipe can run without them" },
+ agents: {
+ team: { want: "ship every client's ads this week", need: "stop being the bottleneck", lie: "if I don't touch it, it's worse", role: "customer", mask: "hero" },
+ raea: { mask: "mentor", role: "brand" },
+ },
+ world: {
+ week: { who: "team", does: "edits the same ad again", turns: { freedom: -1 }, routine: true },
+ doubles: { who: "team", does: choose(["the backlog doubles", "a client wants 50 versions"]), because: "week", sets: ["backlog"], turns: { freedom: -2 } },
+ tries: { who: "team", does: "hands raea the recipe once", because: "doubles", needs: ["backlog"], turns: { trust: -1 }, dilemma: ["keep cutting by hand", "trust the recipe to run"] },
+ ships: { who: "team", with: ["raea"], does: "ships fifty checked cuts by Friday", because: "tries", sets: ["recipeRuns"], turns: { trust: 2, freedom: 3 }, ends: { team: "need" }, claim: "fifty checked cuts", proof: ["recipeRuns"] },
+ },
+ tellings: {
+ "30s": [
+ { shows: ["ships"], feel: "curiosity", hides: ["recipeRuns"], asks: ["recipeRuns"], setup: "how" },
+ { shows: ["week", "doubles"], feel: "recognition" },
+ { shows: ["tries"], feel: "concern" },
+ { shows: ["ships"], feel: "relief", reveals: ["recipeRuns"], pays: "how" },
+ ],
+ },
+ lenses: ["mckee", "storynomics", "pas"],
+});
diff --git a/sdk/story/test/mutate.test.ts b/sdk/story/test/mutate.test.ts
new file mode 100644
index 00000000..e2990a6d
--- /dev/null
+++ b/sdk/story/test/mutate.test.ts
@@ -0,0 +1,15 @@
+import { expect, test } from "bun:test";
+import { checkStory, mutants } from "../src/index.ts";
+import { launch } from "./fixture.ts";
+
+test("every mutant with an expected check is found by that check", () => {
+ const ms = mutants(launch, "30s");
+ expect(ms.length).toBeGreaterThan(8);
+ const missed = ms.filter((m) => m.label.expect && !checkStory(m.story, m.telling).some((f) => f.check === m.label.expect)).map((m) => `${m.label.kind} ${m.label.at}: ${m.label.says}`);
+ expect(missed).toEqual([]);
+});
+
+test("the kinds of break it makes", () => {
+ const kinds = new Set(mutants(launch, "30s").map((m) => m.label.kind));
+ for (const k of ["drop-setup", "drop-payoff", "drop-cause", "early-need", "flatten-beat", "drop-proof", "swap-beats", "orphan-event"]) expect(kinds.has(k as never)).toBe(true);
+});
diff --git a/sdk/story/test/types.ts b/sdk/story/test/types.ts
new file mode 100644
index 00000000..d97c6c56
--- /dev/null
+++ b/sdk/story/test/types.ts
@@ -0,0 +1,16 @@
+// tsc only (ST0a): each @ts-expect-error is a reference the story doesn't declare.
+import { story, value } from "../src/model.ts";
+const base = { values: { v: value("a", "b") }, facts: { f: "a fact" }, agents: { x: {} } } as const;
+story({ ...base, world: { e1: { who: "x", does: "acts" } }, tellings: { t: [{ shows: ["e1"] }] } });
+// @ts-expect-error an agent it doesn't have
+story({ ...base, world: { e1: { who: "y", does: "acts" } }, tellings: { t: [{ shows: ["e1"] }] } });
+// @ts-expect-error a value it doesn't have
+story({ ...base, world: { e1: { who: "x", does: "acts", turns: { w: 1 } } }, tellings: { t: [{ shows: ["e1"] }] } });
+// @ts-expect-error a fact it doesn't have
+story({ ...base, world: { e1: { who: "x", does: "acts", sets: ["g"] } }, tellings: { t: [{ shows: ["e1"] }] } });
+// @ts-expect-error a cause that isn't an event
+story({ ...base, world: { e1: { who: "x", does: "acts" }, e2: { who: "x", does: "acts", because: "e3" } }, tellings: { t: [{ shows: ["e1"] }] } });
+// @ts-expect-error a beat showing an event the world doesn't have
+story({ ...base, world: { e1: { who: "x", does: "acts" } }, tellings: { t: [{ shows: ["e2"] }] } });
+// @ts-expect-error a payoff of a setup nothing planted
+story({ ...base, world: { e1: { who: "x", does: "acts" } }, tellings: { t: [{ shows: ["e1"], setup: "gun" }, { shows: ["e1"], pays: "gnu" }] } });
diff --git a/sdk/story/tsconfig.json b/sdk/story/tsconfig.json
new file mode 100644
index 00000000..ea8e00e9
--- /dev/null
+++ b/sdk/story/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "extends": "../tsconfig.base.json",
+ "compilerOptions": {
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "erasableSyntaxOnly": true,
+ "noUnusedLocals": true,
+ "lib": ["ES2023"]
+ },
+ "include": ["src", "test/types.ts", "test/fixture.ts"]
+}
diff --git a/sdk/tsconfig.base.json b/sdk/tsconfig.base.json
index 184b2770..0fdf22c4 100644
--- a/sdk/tsconfig.base.json
+++ b/sdk/tsconfig.base.json
@@ -74,8 +74,12 @@
"raea/wear": ["./wear/src/index.ts"],
"raea/views": ["./dev_tools/src/views.tsx"],
"raea/window": ["./app/src/window.ts"],
+ "raea/story": ["./story/src/index.ts"],
+ "raea/story/*": ["./story/src/*"],
"raea/plugins/*": ["./plugins/src/*.gen"],
"raea/*": ["./raea/src/*"],
+ "@raea/story": ["./story/src/index.ts"],
+ "@raea/story/*": ["./story/src/*"],
"@raea/app": ["./app/src/index.ts"],
"@raea/app/*": ["./app/src/*"],
"@raea/math": ["./math/src/index.ts"],