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.

ST0c, ST5a: raea check reads stories. brief({ story }) is kept as written (Brief.story, opaque to Rust); a script's scene names its beat (Scene.beat, compileScript writes it); a .ts check declares over: "frames" | "story" | "both", and raea check NAME.story.ts runs the story checks once with no frames, before anything is drawn. raea/story/raea/checks gives storyCheck (the story's exact and lens findings, then every beat on screen in order with its lines spoken inside its shot) and raea/story/raea/compose gives beatTimes and <Beat>. Beats take an optional id. data.ts reads a story from JSON with every bad reference named, and gives the schemas the story models decode under (a beat's schema holds the story's own keys). models/: the corpus writer, the training rows, MLX training with constrained decoding, and the scorer.

shinyobjectzf0372580bb64
diff --git a/apps/direction/src/check.rs b/apps/direction/src/check.rs
index 05489dd1..8086db64 100644
--- a/apps/direction/src/check.rs
+++ b/apps/direction/src/check.rs
@@ -325,6 +325,9 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
return Err(format!("--only {only}: no rule here has that id"));
}
}
+ if target.is_file() && target.to_string_lossy().ends_with(".story.ts") {
+ return check_story(&target, &rules, unread, args, host);
+ }
let mut all = Vec::new();
for (tsx, id) in compositions(&target, args)? {
let mine: Vec<Rule> = rules.iter().filter(|r| applies(r, &project, &tsx, id.as_deref())).cloned().collect();
@@ -363,6 +366,43 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
Ok((out.join("\n"), bad))
}
+/// `raea check NAME.story.ts` (docs/story.feature ST5a): a story checked before anything is drawn. Every rule whose .ts
+/// check reads stories (`over: "story"` or `"both"`) runs once with no frames, so only its `after` speaks; the check
+/// imports the story it holds (raea/story's storyCheck), and the file named says which project and that no composition
+/// is wanted.
+fn check_story(file: &Path, rules: &[Rule], unread: Vec<Finding>, args: &[String], host: &Host) -> R<(String, bool)> {
+ let (mut found, mut files, mut plan) = (Vec::new(), Vec::<PathBuf>::new(), Vec::new());
+ for r in rules {
+ let Some(f) = r.file() else { continue };
+ match ts::meta(f, &host.ts) {
+ Ok(m) if m.story => {
+ let k = files.iter().position(|x| *x == m.file).unwrap_or_else(|| {
+ files.push(m.file.clone());
+ files.len() - 1
+ });
+ plan.push(ts::Planned { check: k, frames: Vec::new(), values: r.values.clone(), level: r.level, by: r.by.clone() });
+ }
+ Ok(_) => {}
+ Err(e) => found.push(Finding::new(&r.id, Level::Error, e, &r.by)),
+ }
+ }
+ if plan.is_empty() {
+ found.push(Finding::new("story", Level::Note, "no check here reads a story: a .ts check over \"story\" or \"both\" (raea/story's storyCheck is one) named in taste.ts", "raea check"));
+ }
+ found.extend(ts::run(&files, &plan, &[], &host.ts)?);
+ let found = finding::ranked(found);
+ let bad = unread.iter().chain(&found).any(|f| f.level == Level::Error);
+ if args.iter().any(|a| a == "--json") {
+ return Ok((serde_json::to_string_pretty(&json!({"unread": unread, "story": file, "findings": found})).unwrap_or_default(), bad));
+ }
+ let mut out: Vec<String> = unread.iter().map(Finding::line).collect();
+ out.push(format!("raea check {} (a story: no frames)", file.display()));
+ out.extend(found.iter().map(Finding::line));
+ let every: Vec<Finding> = unread.into_iter().chain(found).collect();
+ out.push(format!("raea check: {}", finding::count(&every)));
+ Ok((out.join("\n"), bad))
+}
+
/// `raea check ...`: its exit code (1 on an error found, 2 when it couldn't check).
pub fn cli(args: &[String], host: &Host) -> i32 {
raea_app_check::said(check(args, host), "raea check: ")
diff --git a/apps/direction/src/ts.rs b/apps/direction/src/ts.rs
index 59daae46..729dd6b5 100644
--- a/apps/direction/src/ts.rs
+++ b/apps/direction/src/ts.rs
@@ -27,6 +27,8 @@ pub struct Meta {
pub render: bool,
pub level: Level,
pub frames: Frames,
+ /// it runs on a story with no frames (`over: "story" | "both"`): what `raea check NAME.story.ts` runs
+ pub story: bool,
}
/// The declaration of the check `file`'s default export is.
@@ -46,7 +48,12 @@ pub fn meta(file: &Path, host: &Host) -> R<Meta> {
Some(o) => return Err(format!("{name}: a check's level is error, warn or note, not \"{o}\"")),
};
let frames = Frames::of(&v["frames"]).map_err(|e| format!("{name}: {e}"))?;
- Ok(Meta { file: file.to_path_buf(), id, text: s("text").unwrap_or_default(), render, level, frames })
+ let story = match s("over").as_deref() {
+ None | Some("frames") => false,
+ Some("story" | "both") => true,
+ Some(o) => return Err(format!("{name}: a check is over \"frames\", \"story\" or \"both\", not \"{o}\"")),
+ };
+ Ok(Meta { file: file.to_path_buf(), id, text: s("text").unwrap_or_default(), render, level, frames, story })
}
/// One planned run: the check (its index in `files`), its frames, and its rule's values, level (None: the check's
diff --git a/core/brief/src/brief.rs b/core/brief/src/brief.rs
index 840eaf41..b081f864 100644
--- a/core/brief/src/brief.rs
+++ b/core/brief/src/brief.rs
@@ -56,6 +56,11 @@ pub struct Brief {
#[serde(default)]
#[ts(as = "Option<Vec<Agent>>", optional)]
pub agents: Vec<Agent>,
+ /// the project's stories, imported explicitly (raea/story, docs/story.md): one, or several by name. Kept as written:
+ /// raea reads nothing in it, the story SDK and the checks that import it do
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[ts(type = "unknown", optional)]
+ pub story: Option<serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
diff --git a/core/brief/src/script.rs b/core/brief/src/script.rs
index beb491fc..d1484ed9 100644
--- a/core/brief/src/script.rs
+++ b/core/brief/src/script.rs
@@ -23,6 +23,8 @@ pub struct Scene {
pub beats: Vec<Beat>,
/// what the scene must land
pub payoff: Option<String>,
+ /// the story beat it plays, by its id (raea/story's compileScript writes it; docs/story.feature ST0c)
+ pub beat: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
diff --git a/docs/story.feature b/docs/story.feature
index 666f2a66..0bc123cd 100644
--- a/docs/story.feature
+++ b/docs/story.feature
@@ -51,7 +51,11 @@ Feature: Story: a story as ECS data, read through many frameworks, generated wit
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
+ And a script's scene may carry beat: "<id>" (compileScript writes it)
+ And the plan:
+ | crate | file | lines | job |
+ | raea-core-brief | core/brief/src/brief.rs | 140 | Brief.story, kept as written |
+ | raea-core-brief | core/brief/src/script.rs | 90 | Scene.beat |
Rule: ST1. Systems derive what's never written
@@ -124,7 +128,14 @@ Feature: Story: a story as ECS data, read through many frameworks, generated wit
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)
+ And a story is checked with no composition: raea check NAME.story.ts runs every check over "story" or "both" once,
+ with no frames
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/raea/checks.ts | 120 | storyCheck: the story's findings and its beats on screen |
+ | sdk | sdk/story/src/raea/compose.tsx | 80 | beatTimes and <Beat> |
+ | raea-app-direction | apps/direction/src/check.rs | 420 | raea check NAME.story.ts |
+ | raea-app-direction | apps/direction/src/ts.rs | 120 | a check's `over` |
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
diff --git a/docs/story.md b/docs/story.md
index 8a903b75..1ba6e014 100644
--- a/docs/story.md
+++ b/docs/story.md
@@ -181,15 +181,16 @@ A composition uses the story explicitly: `useBeat(launch, "30s", 2)` gives a bea
### 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.
+1. **`Brief.story`**: the brief refuses unknown fields (`deny_unknown_fields`), so `brief({ story })` was refused.
+ It's now `story?: unknown` (Rust keeps it as written and reads nothing in it).
+2. **`Scene.beat`**: an optional beat id on a script's scene; `compileScript` writes it, so a scene says which beat it
+ plays.
+3. **Story checks without a composition**: `raea check launch.story.ts` runs every taste rule whose `.ts` check is
+ `over: "story"` or `"both"` once, with no frames, so only its `after` speaks. A story is checked before anything is
+ drawn.
+
+A fourth was planned (naming the SDK's checks by package path in taste.ts) and dropped: a project's own three-line
+`checks/story.ts` that imports its story and calls `storyCheck` is more explicit, which is what Shane asked for.
## The model, as a module
@@ -366,7 +367,7 @@ chooses (Shane's notes are the training data that matter most).
| 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 |
+| ST0 | the model's types (world, telling, render) and `story()`, compiled to `script.ts`; the three Rust changes (`Brief.story`, `Scene.beat`, story-only checks) | 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 |
diff --git a/sdk/raea/src/brief.gen.ts b/sdk/raea/src/brief.gen.ts
index 8025909e..c321c893 100644
--- a/sdk/raea/src/brief.gen.ts
+++ b/sdk/raea/src/brief.gen.ts
@@ -40,7 +40,12 @@ assumed?: Array<string>,
/**
* prose sections beyond the fields above (Goal, Background), in order
*/
-sections?: Array<Section>, deliver?: Array<Deliverable>, references?: Array<Reference>, agents?: Array<Agent>, };
+sections?: Array<Section>, deliver?: Array<Deliverable>, references?: Array<Reference>, agents?: Array<Agent>,
+/**
+ * the project's stories, imported explicitly (raea/story, docs/story.md): one, or several by name. Kept as written:
+ * raea reads nothing in it, the story SDK and the checks that import it do
+ */
+story?: unknown, };
export type Section = { heading: string, text: string, };
@@ -76,7 +81,11 @@ heading?: string, beats: Array<Beat>,
/**
* what the scene must land
*/
-payoff?: string, };
+payoff?: string,
+/**
+ * the story beat it plays, by its id (raea/story's compileScript writes it; docs/story.feature ST0c)
+ */
+beat?: string, };
export type Beat = {
/**
diff --git a/sdk/raea/src/check.ts b/sdk/raea/src/check.ts
index 8fb94f8d..0e6d9ef7 100644
--- a/sdk/raea/src/check.ts
+++ b/sdk/raea/src/check.ts
@@ -36,6 +36,9 @@ export interface CheckMeta {
level?: Level;
/** where it runs ("all" when unset) */
frames?: Frames;
+ /** what it reads: a composition's frames (the default), a story with no frames (`raea check NAME.story.ts` runs only
+ * these and "both", with its `after` alone), or both (docs/story.feature ST5a) */
+ over?: "frames" | "story" | "both";
}
/** A rule's values for its check (a taste line's `values`, an ask's). */
diff --git a/sdk/story/models/corpus.ts b/sdk/story/models/corpus.ts
new file mode 100644
index 00000000..03f677cb
--- /dev/null
+++ b/sdk/story/models/corpus.ts
@@ -0,0 +1,128 @@
+// The story corpus (docs/story.feature ST6a): stories written as raea/story JSON by a cheap model, across a matrix of
+// kinds and made-up premises, each read back with fromData and checked with checkStory. A story with errors gets one
+// repair with its findings; what still fails is kept apart (rejects.jsonl, the critic's real-world negatives). Every
+// beat carries the words a viewer gets (onScreen and lines), so a telling reads as a script with no annotations: what
+// the extractor reads and the critic judges.
+//
+// bun models/corpus.ts N [--out ~/.vd/story] [--model anthropic/claude-haiku-5.5] [--jobs 16] [--seed 0]
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { checkStory, fromData, rng, toData, type AnyStory } from "../src/index.ts";
+import { launch } from "../test/fixture.ts";
+
+const arg = (k: string, d: string) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
+const N = Number(process.argv[2] ?? 10);
+const OUT = arg("--out", join(homedir(), ".vd/story"));
+const MODEL = arg("--model", "anthropic/claude-haiku-5.5");
+const JOBS = Number(arg("--jobs", "16"));
+const SEED = Number(arg("--seed", "0"));
+const KEY = readFileSync(join(homedir(), ".raea/env"), "utf8").match(/^OPENROUTER_API_KEY=(.+)$/m)?.[1]?.trim();
+if (!KEY) throw new Error("no OPENROUTER_API_KEY in ~/.raea/env");
+mkdirSync(OUT, { recursive: true });
+
+// made-up names only (never a real brand)
+const A = ["Halden", "Northwind", "Lumen", "Bramble", "Quillfield", "Tidewell", "Ferrow", "Ashgrove", "Calloway", "Merrin", "Oxley", "Pellam", "Rookery", "Saltmarsh", "Thistledown", "Umberly", "Vantor", "Wrenfield", "Yarrowby", "Zephyrine", "Cobblestone", "Driftmark", "Emberline", "Foxhollow", "Glimmerton", "Hearthway", "Ironvale", "Juniper Row", "Kestrel", "Larkspur"];
+const B = { product: ["Outdoor", "Coffee", "Skincare", "Bikes", "Audio", "Notes", "Tea", "Running", "Garden", "Pet Food", "Sleep", "Bank", "Studio", "Analytics", "Kitchen", "Robotics", "Maps", "Language", "Insurance", "Fitness"] };
+const KINDS: [string, number, string][] = [
+ ["launch film for a software product", 30, "30 to 45 seconds, 4 to 7 beats; the customer is the hero, the product the mentor; a claim backed by proof"],
+ ["launch film for a physical product", 15, "30 to 45 seconds, 4 to 7 beats; the customer is the hero, the product the mentor or gift"],
+ ["30-second brand ad", 15, "3 to 6 beats; one value turns; a person's problem, agitated, then solved"],
+ ["short drama scene", 12, "4 to 8 beats; two or three characters, a want against a need, a dilemma, a secret the audience learns before a character does"],
+ ["game quest", 10, "4 to 8 beats; a player character, a quest giver, an obstacle, a reward; setups paid off"],
+ ["explainer film", 8, "4 to 6 beats; a question raised early and answered late"],
+ ["fable", 5, "4 to 7 beats; animals or objects; a lie the hero believes and drops"],
+ ["documentary short", 5, "4 to 7 beats; real-feeling people, a turn from bad to better or worse"],
+];
+const MOODS = ["hopeful", "funny", "tense", "quiet", "bittersweet", "urgent", "warm", "dry", "eerie", "triumphant"];
+
+function premise(i: number): { kind: string; shape: string; brand: string; mood: string } {
+ const r = rng(SEED * 100003 + i);
+ const total = KINDS.reduce((a, k) => a + k[1], 0);
+ let x = r() * total, k = KINDS[0];
+ for (const c of KINDS) { if ((x -= c[1]) < 0) { k = c; break; } }
+ const brand = `${A[Math.floor(r() * A.length)]} ${B.product[Math.floor(r() * B.product.length)]}`;
+ return { kind: k[0], shape: k[2], brand, mood: MOODS[Math.floor(r() * MOODS.length)] };
+}
+
+const GUIDE = `You write stories as data for raea/story. A story is one JSON object:
+- values: what's at stake, each {neg, pos} (McKee's value, e.g. {"neg":"buried","pos":"free"}).
+- facts: named facts, each a sentence.
+- agents: characters, each {want, need, lie, mask, role, believes}. mask is one of hero, mentor, ally, herald, threshold, shapeshifter, shadow, trickster, gift. For an ad or launch, role "customer" for the person and "brand" for the product.
+- world: events IN THE ORDER THEY HAPPEN, each {who, with, does, because, needs, sets, unsets, learns, turns, ends, dilemma, claim, proof, routine}. Every event after the first names its cause in "because" (an earlier event), unless it's "routine": true (how things are every day). "turns" moves values in whole steps from -3 to 3 (e.g. {"freedom": -2}); every event that matters turns something. "ends" settles an agent's want or need ({"hero": "need"}). A "dilemma" lists the two options a character chooses between. A "claim" made to the audience names its "proof" (facts that event sets).
+- tellings: one telling named "main": a list of beats in the order the audience sees them. Each beat: {shows: [event keys], feel, reveals, hides, asks, setup, pays, onScreen, says}. A beat can show an event out of order (a flash-forward hook). "asks" raises a question (a fact the audience wants); a later beat "reveals" it. "setup" plants a named setup; a later beat "pays" it. EVERY beat has "onScreen": one or two concrete sentences of what the viewer sees, and usually "says": lines [{who, says}] (who is an agent key or "narrator"). onScreen and says are the only words a viewer gets, so they must carry the story on their own.
+- idea: {value, side, counter}: the value the story is about and what it argues.
+Facts are KEYS: believes, needs, sets, unsets, learns, proof, reveals, hides and asks hold fact keys you declared in "facts", never sentences (a question the audience has is a fact key in asks, revealed later). Knowledge is tracked: an agent can only act on ("needs") a fact they believe from the start, or that an earlier event they were in (as who or with) set or learned.
+Rules the checker holds you to: every beat turns a value or reveals something; each beat after the first follows from what was seen (a cause shown earlier or in the same beat); a big turn (2 or more) is set up; every setup is paid; a want or need is settled by the end; a claim has proof shown by then; the focus value ends somewhere different from where it began. Keys are short camelCase words. Use only the keys you declare.
+Here is one valid story, a 30-second launch film:
+${JSON.stringify(toData(launch as AnyStory))}
+Answer with the JSON object only.`;
+
+async function ask(messages: { role: string; content: string }[]): Promise<{ text: string; usd: number }> {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
+ method: "POST",
+ headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json", "X-Title": "story-corpus" },
+ body: JSON.stringify({ model: MODEL, messages, temperature: 1, max_tokens: 9000, reasoning: { max_tokens: 1500 }, response_format: { type: "json_object" }, usage: { include: true } }),
+ });
+ if (res.status === 429 || res.status >= 500) { await new Promise((r) => setTimeout(r, 2000 * (attempt + 1))); continue; }
+ const j: any = await res.json();
+ if (!res.ok) throw new Error(`${res.status} ${JSON.stringify(j).slice(0, 300)}`);
+ const text = j.choices?.[0]?.message?.content ?? "";
+ if (!text) appendFileSync(join(OUT, "empty.jsonl"), JSON.stringify({ finish: j.choices?.[0]?.finish_reason, native: j.choices?.[0]?.native_finish_reason, usage: j.usage, err: j.error }) + "\n");
+ return { text, usd: j.usage?.cost ?? 0 };
+ }
+ throw new Error("openrouter kept refusing");
+}
+
+const parse = (t: string) => { try { return JSON.parse(t.replace(/^```(json)?|```$/g, "").trim()); } catch { return null; } };
+
+function judgeIt(j: unknown) {
+ const { story, errors } = fromData(j);
+ if (!story) return { story, errors: errors.map((e) => `${e.at}: ${e.says}`), findings: [] as string[] };
+ let findings: string[] = [];
+ if (!errors.length) {
+ try { findings = checkStory(story, "main").filter((f) => f.level === "error").map((f) => `${f.check} at ${f.about}: ${f.says}`); }
+ catch (e) { findings = [`the checker couldn't read it: ${(e as Error).message}`]; }
+ }
+ return { story, errors: errors.map((e) => `${e.at}: ${e.says}`), findings };
+}
+
+let spent = 0, kept = 0, rejected = 0, done = 0;
+const start = existsSync(join(OUT, "stories.jsonl")) ? readFileSync(join(OUT, "stories.jsonl"), "utf8").split("\n").filter(Boolean).length + (existsSync(join(OUT, "rejects.jsonl")) ? readFileSync(join(OUT, "rejects.jsonl"), "utf8").split("\n").filter(Boolean).length : 0) : 0;
+
+async function one(i: number) {
+ const p = premise(i);
+ const msgs = [
+ { role: "system", content: GUIDE },
+ { role: "user", content: `Write a ${p.mood} ${p.kind}${p.kind.includes("launch") || p.kind.includes("ad") ? ` for ${p.brand} (a made-up company: invent what it makes, in its line)` : ""}. Shape: ${p.shape}. Make it specific and surprising, not generic.` },
+ ];
+ const first = await ask(msgs);
+ spent += first.usd;
+ let j = parse(first.text), r = judgeIt(j), repaired = false;
+ if (!j) appendFileSync(join(OUT, "unparsed.txt"), `--- ${i}\n${first.text.slice(0, 400)}\n...\n${first.text.slice(-300)}\n`);
+ const convo = [...msgs, { role: "assistant", content: first.text }];
+ for (let round = 0; round < 2 && j && (r.errors.length || r.findings.length); round++) {
+ convo.push({ role: "user", content: `The checker found:\n${[...r.errors, ...r.findings].join("\n")}\nFix every one and answer with the whole corrected JSON object only.` });
+ const fix = await ask(convo);
+ spent += fix.usd;
+ convo.push({ role: "assistant", content: fix.text });
+ const j2 = parse(fix.text), r2 = judgeIt(j2);
+ appendFileSync(join(OUT, "repairs.jsonl"), JSON.stringify({ i, round, before: j, found: [...r.errors, ...r.findings], after: j2, fixed: !!j2 && !r2.errors.length && !r2.findings.length }) + "\n");
+ j = j2; r = r2; repaired = true;
+ }
+ const ok = !!j && !r.errors.length && !r.findings.length;
+ appendFileSync(join(OUT, ok ? "stories.jsonl" : "rejects.jsonl"), JSON.stringify({ i, premise: p, repaired, model: MODEL, story: j, found: [...r.errors, ...r.findings] }) + "\n");
+ ok ? kept++ : rejected++;
+ if (++done % 10 === 0) console.log(`${done}/${N}: kept ${kept}, rejected ${rejected}, spent $${spent.toFixed(3)}`);
+}
+
+let next = start;
+const end = start + N;
+await Promise.all(Array.from({ length: JOBS }, async () => {
+ while (next < end) {
+ const i = next++;
+ try { await one(i); } catch (e) { console.log(`story ${i}: ${(e as Error).message}`); }
+ }
+}));
+console.log(`done: kept ${kept}, rejected ${rejected} of ${N}, spent $${spent.toFixed(3)} (${OUT})`);
diff --git a/sdk/story/models/rows.ts b/sdk/story/models/rows.ts
new file mode 100644
index 00000000..f2be8bb9
--- /dev/null
+++ b/sdk/story/models/rows.ts
@@ -0,0 +1,111 @@
+// Training rows for the three story models (docs/story.feature ST6b), from the checked corpus (corpus.ts). The split is
+// by story (a story's rows are all in one of train, val and test), so a held-out number is on stories never seen.
+//
+// extract script prose -> the story as data (no onScreen or lines in the answer: they're the input)
+// generate a story with one beat cut, and where -> that beat, as JSON under the story's own beat schema
+// critic script prose -> where it breaks: [{beat, check, level}], labelled exactly by checkStory on the structure
+// behind the prose. Negatives are cuts a viewer could see: a beat cut, two beats swapped, a beat from
+// another story spliced in. A cut that breaks nothing is labelled clean, so the critic must read, not count.
+//
+// bun models/rows.ts [--in ~/.vd/story] [--out ~/.vd/story/rows]
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { beatSchema, checkStory, fromData, rng, storySchema, type AnyStory } from "../src/index.ts";
+
+const arg = (k: string, d: string) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
+const IN = arg("--in", join(homedir(), ".vd/story"));
+const OUT = arg("--out", join(IN, "rows"));
+mkdirSync(OUT, { recursive: true });
+
+type J = Record<string, any>;
+const stories: { i: number; s: J; premise: J }[] = readFileSync(join(IN, "stories.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)).map((d) => ({ i: d.i, s: d.story, premise: d.premise }));
+
+/** The split a story falls in, by its index. */
+export const split = (i: number) => { const h = (Math.imul(i + 1, 2654435761) >>> 0) % 10; return h === 0 ? "test" : h === 1 ? "val" : "train"; };
+
+const name = (k: string) => (k === "narrator" ? "NARRATOR" : k.replace(/([a-z])([A-Z])/g, "$1 $2").toUpperCase());
+
+/** A telling as a script a person would write: numbered beats, what's seen, who says what. No keys, no annotations. */
+export function prose(beats: J[]): string {
+ return beats.map((b, n) => [`${n + 1}. ${b.onScreen ?? ""}`.trimEnd(), ...(b.says ?? []).map((l: J) => ` ${name(l.who)}: ${l.says}`)].join("\n")).join("\n");
+}
+
+const withTelling = (s: J, beats: J[]): J => ({ ...s, tellings: { main: beats } });
+const breaks = (s: J, beats: J[]) => {
+ const st = fromData(withTelling(s, beats)).story as AnyStory;
+ const keys = beats.map((b, i) => b.id ?? `b${i}`);
+ const firstShowing = (ev: string) => beats.findIndex((b) => (b.shows ?? []).includes(ev));
+ return checkStory(st, "main")
+ .filter((f) => f.level !== "note")
+ .map((f) => {
+ let beat: number | null = keys.indexOf(f.about);
+ if (beat < 0) beat = s.world?.[f.about] ? firstShowing(f.about) : -1;
+ return { beat: beat >= 0 ? beat + 1 : null, check: f.check, level: f.level };
+ })
+ .sort((a, b) => (a.beat ?? 0) - (b.beat ?? 0) || a.check.localeCompare(b.check));
+};
+
+/** The story as the extractor answers it: everything but the words on screen. */
+const bare = (s: J): J => ({
+ ...(s.title ? { title: s.title } : {}),
+ ...(s.idea ? { idea: s.idea } : {}),
+ values: s.values, facts: s.facts ?? {}, agents: s.agents, world: s.world,
+ tellings: { main: s.tellings.main.map(({ onScreen: _o, says: _s, id: _i, ...b }: J) => b) },
+});
+
+const out: Record<string, Record<string, J[]>> = { extract: {}, generate: {}, critic: {} };
+const push = (task: string, sp: string, row: J) => ((out[task][sp] ??= []).push(row));
+let clean = 0, broken = 0;
+
+for (const { i, s } of stories) {
+ const sp = split(i);
+ const beats: J[] = s.tellings.main;
+ if (!beats?.length) continue;
+ const r = rng(i * 7919 + 17);
+ const p = prose(beats);
+ push("extract", sp, { i, prompt: p, answer: JSON.stringify(bare(s)) });
+
+ // generate: each beat cut in turn on test and val; one at random on train (keeps the set balanced by story)
+ const cuts = sp === "train" ? [Math.floor(r() * beats.length)] : beats.map((_, k) => k);
+ for (const k of cuts) {
+ const rest = beats.filter((_, n) => n !== k);
+ const partial = { ...s, tellings: { main: rest } };
+ push("generate", sp, { i, at: k, prompt: JSON.stringify({ story: partial, write: `the beat that goes at place ${k + 1} of ${beats.length}` }), answer: JSON.stringify(beats[k]), schema: beatSchema(s) });
+ }
+
+ // critic: the story as written, then cuts a viewer could see
+ const variants: { kind: string; beats: J[]; world?: J }[] = [{ kind: "clean", beats }];
+ const k = Math.floor(r() * beats.length);
+ if (beats.length > 2) variants.push({ kind: "cut", beats: beats.filter((_, n) => n !== k) });
+ if (beats.length > 2) { const a = Math.floor(r() * (beats.length - 1)); const b2 = [...beats]; [b2[a], b2[a + 1]] = [b2[a + 1], b2[a]]; variants.push({ kind: "swap", beats: b2 }); }
+ const other = stories[Math.floor(r() * stories.length)];
+ if (other.i !== i && other.s.tellings?.main?.length) {
+ const ob = other.s.tellings.main[Math.floor(r() * other.s.tellings.main.length)];
+ const firstAgent = Object.keys(s.agents)[0];
+ const ev = `spliced${other.i}`;
+ const at = 1 + Math.floor(r() * (beats.length - 1));
+ const b2 = [...beats.slice(0, at), { shows: [ev], onScreen: ob.onScreen, says: (ob.says ?? []).map((l: J) => ({ ...l, who: "narrator" })) }, ...beats.slice(at)];
+ variants.push({ kind: "splice", beats: b2, world: { ...s.world, [ev]: { who: firstAgent, does: "something unrelated happens" } } });
+ }
+ for (const v of variants) {
+ const base = v.world ? { ...s, world: v.world } : s;
+ let label: J[];
+ try { label = breaks(base, v.beats); } catch { continue; }
+ label.length ? broken++ : clean++;
+ push("critic", sp, { i, kind: v.kind, prompt: prose(v.beats), answer: JSON.stringify({ breaks: label }) });
+ }
+}
+
+const CHECKS = ["turns", "and-then", "surprise", "cause", "dead-end", "setup", "belief", "rhythm", "arc", "claim", "idea"];
+const criticSchema = {
+ type: "object", additionalProperties: false, required: ["breaks"],
+ properties: { breaks: { type: "array", items: { type: "object", additionalProperties: false, required: ["beat", "check", "level"], properties: { beat: { anyOf: [{ type: "integer", minimum: 1 }, { type: "null" }] }, check: { type: "string", enum: CHECKS }, level: { type: "string", enum: ["error", "warn"] } } } } },
+};
+writeFileSync(join(OUT, "schemas.json"), JSON.stringify({ extract: storySchema(), critic: criticSchema }, null, 1));
+for (const [task, sps] of Object.entries(out)) {
+ mkdirSync(join(OUT, task), { recursive: true });
+ for (const [sp, rows] of Object.entries(sps)) writeFileSync(join(OUT, task, `${sp}.jsonl`), rows.map((x) => JSON.stringify(x)).join("\n") + "\n");
+ console.log(task, Object.fromEntries(Object.entries(sps).map(([k, v]) => [k, v.length])));
+}
+console.log(`critic labels: ${clean} clean, ${broken} with a break`);
diff --git a/sdk/story/models/score.ts b/sdk/story/models/score.ts
new file mode 100644
index 00000000..5bf90a9f
--- /dev/null
+++ b/sdk/story/models/score.ts
@@ -0,0 +1,105 @@
+// Scores the story models' predictions (story_models.py) with raea/story itself (docs/story.feature ST6b):
+// extract valid (reads back with no reference errors), holds (checkStory finds no error), beats (the script's
+// beat count), events F1 (each gold event matched by its words), arc (each beat's turn sign agrees)
+// generate valid, holds (the story with the written beat in it has no error), clean (no warn either, where the
+// gold story had none at that beat), shows (Jaccard of the events shown, against the cut beat)
+// critic right (it says "breaks" exactly when there is one), F1 on (beat, check), F1 on check alone
+//
+// bun models/score.ts TASK [--rows ~/.vd/story/rows] [--split test]
+import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { checkStory, fromData, type AnyStory } from "../src/index.ts";
+
+const arg = (k: string, d: string) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
+const TASK = process.argv[2];
+const ROWS = arg("--rows", join(homedir(), ".vd/story/rows")).replace(/^~/, homedir());
+const SPLIT = arg("--split", "test");
+type J = Record<string, any>;
+const read = (p: string): J[] => (existsSync(p) ? readFileSync(p, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)) : []);
+const parse = (t: string): J | null => { try { const j = JSON.parse(String(t).replace(/^```(json)?|```$/g, "").trim()); return j && typeof j === "object" ? j : null; } catch { return null; } };
+const rows = read(join(ROWS, TASK, `${SPLIT}.jsonl`));
+const byKey = new Map(rows.map((r) => [`${r.i}:${r.at ?? r.kind ?? ""}`, r]));
+const words = (s: string) => new Set(String(s ?? "").toLowerCase().match(/[a-z0-9']+/g) ?? []);
+const jac = (a: Set<string>, b: Set<string>) => { const i = [...a].filter((x) => b.has(x)).length; const u = new Set([...a, ...b]).size; return u ? i / u : 1; };
+const f1 = (tp: number, fp: number, fn: number) => (tp ? (2 * tp) / (2 * tp + fp + fn) : fp + fn ? 0 : 1);
+const errorsOf = (s: AnyStory, level: "error" | "warn" = "error") => { try { return checkStory(s, "main").filter((f) => (level === "error" ? f.level === "error" : f.level !== "note")); } catch (e) { return [{ check: "unreadable", level: "error", about: "", says: String(e) }]; } };
+const sign = (x: number) => (x > 0 ? 1 : x < 0 ? -1 : 0);
+const beatSigns = (s: J) => (s.tellings?.main ?? []).map((b: J) => sign((b.shows ?? []).reduce((a: number, e: string) => a + Object.values((s.world?.[e]?.turns ?? {}) as Record<string, number>).reduce((x, y) => x + (Number(y) || 0), 0), 0)));
+
+function scoreExtract(gold: J, pred: J | null): J {
+ if (!pred) return { valid: 0, holds: 0, beats: 0, eventsF1: 0, arc: 0 };
+ const { story, errors } = fromData(pred);
+ const valid = story && !errors.length ? 1 : 0;
+ const holds = valid ? (errorsOf(story!).length ? 0 : 1) : 0;
+ const g = JSON.parse(gold.answer);
+ const gb = g.tellings.main.length, pb = pred.tellings?.main?.length ?? 0;
+ const ge = Object.values(g.world).map((e: any) => words(e.does)), pe = Object.values(pred.world ?? {}).map((e: any) => words(e?.does));
+ const used = new Set<number>();
+ let tp = 0;
+ for (const w of ge) {
+ let best = -1, bj = 0.25;
+ pe.forEach((p, k) => { const j = jac(w, p); if (!used.has(k) && j >= bj) { bj = j; best = k; } });
+ if (best >= 0) { used.add(best); tp++; }
+ }
+ const gs = beatSigns(g), ps = beatSigns(pred);
+ const arc = gs.length ? gs.filter((x: number, k: number) => ps[k] === x).length / gs.length : 0;
+ return { valid, holds, beats: gb === pb ? 1 : 0, eventsF1: f1(tp, pe.length - tp, ge.length - tp), arc };
+}
+
+function scoreGenerate(row: J, pred: J | null): J {
+ if (!pred) return { valid: 0, holds: 0, clean: 0, shows: 0 };
+ const { story: partial, write } = JSON.parse(row.prompt);
+ const at = row.at as number;
+ const beats = [...partial.tellings.main.slice(0, at), pred, ...partial.tellings.main.slice(at)];
+ const full = { ...partial, tellings: { main: beats } };
+ const { story, errors } = fromData(full);
+ const valid = story && !errors.length ? 1 : 0;
+ const gold = JSON.parse(row.answer);
+ const goldStory = fromData({ ...partial, tellings: { main: [...partial.tellings.main.slice(0, at), gold, ...partial.tellings.main.slice(at)] } }).story!;
+ const holds = valid ? (errorsOf(story!).length ? 0 : 1) : 0;
+ const warns = valid ? errorsOf(story!, "warn").length : 99, goldWarns = errorsOf(goldStory, "warn").length;
+ void write;
+ return { valid, holds, clean: valid && warns <= goldWarns ? 1 : 0, shows: jac(new Set(pred.shows ?? []), new Set(gold.shows ?? [])) };
+}
+
+function scoreCritic(row: J, pred: J | null): J {
+ const gold: J[] = JSON.parse(row.answer).breaks;
+ const p: J[] = Array.isArray(pred?.breaks) ? pred!.breaks : [];
+ const k1 = (b: J) => `${b.beat}:${b.check}`, k2 = (b: J) => String(b.check);
+ const set = (xs: J[], k: (b: J) => string) => new Set(xs.map(k));
+ const count = (k: (b: J) => string) => { const g = set(gold, k), q = set(p, k); const tp = [...q].filter((x) => g.has(x)).length; return [tp, q.size - tp, g.size - tp]; };
+ return { parsed: pred ? 1 : 0, right: (gold.length > 0) === (p.length > 0) ? 1 : 0, at: count(k1), check: count(k2) };
+}
+
+const files = readdirSync(join(ROWS, TASK)).filter((f) => f.startsWith("pred-") && f.endsWith(`-${SPLIT}.jsonl`));
+const results: J = {};
+for (const f of files) {
+ const who = f.slice(5, -(`-${SPLIT}.jsonl`.length));
+ const preds = read(join(ROWS, TASK, f));
+ const per: J[] = [];
+ for (const p of preds) {
+ const row = byKey.get(p.key);
+ if (!row) continue;
+ const j = parse(p.pred);
+ per.push(TASK === "extract" ? scoreExtract(row, j) : TASK === "generate" ? scoreGenerate(row, j) : scoreCritic(row, j));
+ }
+ if (!per.length) continue;
+ const mean = (k: string) => per.reduce((a, x) => a + x[k], 0) / per.length;
+ let r: J;
+ if (TASK === "critic") {
+ const sum = (k: string) => per.reduce((a, x) => [a[0] + x[k][0], a[1] + x[k][1], a[2] + x[k][2]], [0, 0, 0]);
+ const [a1, a2, a3] = sum("at"), [c1, c2, c3] = sum("check");
+ r = { n: per.length, parsed: mean("parsed"), right: mean("right"), atF1: f1(a1, a2, a3), checkF1: f1(c1, c2, c3) };
+ } else {
+ r = { n: per.length, ...Object.fromEntries(Object.keys(per[0]).map((k) => [k, mean(k)])) };
+ }
+ const secs = preds.map((p) => p.secs).filter((x) => typeof x === "number");
+ r.secsMedian = secs.sort((a, b) => a - b)[Math.floor(secs.length / 2)] ?? null;
+ results[who] = r;
+}
+const fmt = (x: unknown) => (typeof x === "number" ? (Number.isInteger(x) ? String(x) : x.toFixed(3)) : String(x));
+const cols = [...new Set(Object.values(results).flatMap((r: J) => Object.keys(r)))];
+console.log(["who", ...cols].join("\t"));
+for (const [who, r] of Object.entries(results)) console.log([who, ...cols.map((c) => fmt((r as J)[c]))].join("\t"));
+writeFileSync(join(ROWS, TASK, `scores-${SPLIT}.json`), JSON.stringify(results, null, 1));
diff --git a/sdk/story/models/story_models.py b/sdk/story/models/story_models.py
new file mode 100644
index 00000000..5d7bf0d5
--- /dev/null
+++ b/sdk/story/models/story_models.py
@@ -0,0 +1,292 @@
+"""The story models (docs/story.feature ST6b): an extractor, a generator and a critic, each a LoRA on one small base,
+trained with MLX on this Mac and decoded under a JSON schema (llguidance), so every answer is data raea/story reads.
+The generator's schema is the story's own (data.ts beatSchema): it can't name an event or a setup the story lacks.
+
+ python story_models.py train TASK [--rows ~/.vd/story/rows] [--iters N] [--base Qwen/Qwen3-0.6B]
+ python story_models.py predict TASK --split test [--adapter DIR | --zero-shot] [--limit N]
+ python story_models.py frontier TASK --split test --model anthropic/claude-sonnet-5.5 [--limit N]
+
+Predictions go to ROWS/TASK/pred-<who>-<split>.jsonl; models/score.ts scores them with raea/story's exact checks.
+"""
+
+import argparse
+import json
+import math
+import os
+import re
+import sys
+import time
+import urllib.request
+from pathlib import Path
+
+HOME = Path.home()
+
+SYSTEM = {
+ "extract": (
+ "You read a short film or game script and write the story behind it as raea/story JSON: values (what's at "
+ "stake, each {neg, pos}), facts (named facts), agents (want, need, lie, mask, role), world (events in the order "
+ "they happen, each {who, does, because, sets, turns ...}; every event after the first names its cause or is "
+ "routine; turns move values -3..3) and tellings.main (the beats in the script's order, each {shows: [event "
+ "keys], feel, reveals, hides, asks, setup, pays}). Keys are short camelCase words. Answer with JSON only."
+ ),
+ "generate": (
+ "You are given a story as raea/story JSON with one beat missing from tellings.main, and where it goes. Write "
+ "that beat as JSON: {shows: [event keys], feel, reveals, hides, asks, setup, pays, onScreen, says}. It must "
+ "follow from what's shown before it, turn a value or reveal something, and pay off what's still open. "
+ "onScreen is what the viewer sees; says are the lines [{who, says}]. Answer with JSON only."
+ ),
+ "critic": (
+ "You read a short film or game script, numbered by beat, and say where its story breaks: {breaks: [{beat, "
+ "check, level}]}. beat is the beat's number, or null for the whole story. check is one of: turns (a beat "
+ "changes nothing), and-then (a beat doesn't follow from anything seen), surprise (a big turn nothing set up), "
+ "cause (an event with no cause), dead-end, setup (planted and never paid, or paid with no setup), belief (a "
+ "character acts on what they can't know), rhythm, arc (a want or need never settled), claim (a claim with no "
+ "proof shown), idea (the story ends where it began). level is error or warn. A story that holds has "
+ "{breaks: []}. Answer with JSON only."
+ ),
+}
+
+
+def rows_dir(a):
+ return Path(os.path.expanduser(a.rows))
+
+
+def read_jsonl(p):
+ return [json.loads(l) for l in open(p) if l.strip()]
+
+
+def canon(x, schema):
+ """x with its keys in the schema's order: llguidance writes properties in that order, so training answers do too."""
+ if schema is None:
+ return x
+ if "anyOf" in schema:
+ for s in schema["anyOf"]:
+ t = s.get("type")
+ if (t == "array" and isinstance(x, list)) or (t == "object" and isinstance(x, dict)):
+ return canon(x, s)
+ return x
+ if isinstance(x, dict):
+ props = schema.get("properties", {})
+ extra = schema.get("additionalProperties")
+ out = {k: canon(x[k], props[k]) for k in props if k in x}
+ for k, v in x.items():
+ if k not in props and isinstance(extra, dict):
+ out[k] = canon(v, extra)
+ return out
+ if isinstance(x, list):
+ return [canon(v, schema.get("items")) for v in x]
+ return x
+
+
+def schema_for(task, row, schemas):
+ s = row["schema"] if task == "generate" else schemas[task]
+ s = json.loads(json.dumps(s))
+ s["x-guidance"] = {"whitespace_flexible": False, "item_separator": ",", "key_separator": ":"}
+ return s
+
+
+def prompt_text(tok, task, user):
+ msgs = [{"role": "system", "content": SYSTEM[task]}, {"role": "user", "content": user}]
+ return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
+
+
+class Rows:
+ """A task's rows as (tokens, offset): the loss is on the answer alone."""
+
+ def __init__(self, tok, task, rows, schemas, max_len):
+ self.items = []
+ for r in rows:
+ p = prompt_text(tok, task, r["prompt"])
+ ans = json.dumps(canon(json.loads(r["answer"]), schema_for(task, r, schemas)), separators=(",", ":"), ensure_ascii=False)
+ pt = tok.encode(p)
+ at = tok.encode(ans + "<|im_end|>\n")
+ if len(pt) + len(at) <= max_len:
+ self.items.append((pt + at, len(pt)))
+
+ def __getitem__(self, i):
+ return self.items[i]
+
+ def __len__(self):
+ return len(self.items)
+
+ def itemlen(self, i):
+ return len(self.items[i][0])
+
+
+def train(a):
+ import mlx.core as mx
+ import mlx.optimizers as optim
+ from mlx_lm import load
+ from mlx_lm.tuner.trainer import TrainingArgs, train as mtrain
+ from mlx_lm.tuner.utils import linear_to_lora_layers, print_trainable_parameters
+
+ rd = rows_dir(a)
+ schemas = json.load(open(rd / "schemas.json"))
+ model, tok = load(a.base)
+ tr = Rows(tok, a.task, read_jsonl(rd / a.task / "train.jsonl"), schemas, a.max_len)
+ va = Rows(tok, a.task, read_jsonl(rd / a.task / "val.jsonl"), schemas, a.max_len)
+ print(f"{a.task}: {len(tr)} train rows, {len(va)} val rows (max {a.max_len} tokens)", flush=True)
+ mx.random.seed(0)
+ model.freeze()
+ linear_to_lora_layers(model, a.layers, {"rank": a.rank, "scale": 20.0, "dropout": 0.05})
+ print_trainable_parameters(model)
+ out = Path(a.adapter or (rd / a.task / f"adapter-{a.name}"))
+ out.mkdir(parents=True, exist_ok=True)
+ json.dump({"base": a.base, "rank": a.rank, "layers": a.layers, "iters": a.iters, "lr": a.lr, "rows": len(tr), "task": a.task}, open(out / "story_adapter.json", "w"))
+ # mlx-lm's own adapter config, so mlx_lm.fuse and load(adapter_path=) read it
+ json.dump({"fine_tune_type": "lora", "num_layers": a.layers, "lora_parameters": {"rank": a.rank, "scale": 20.0, "dropout": 0.05}, "model": a.base}, open(out / "adapter_config.json", "w"))
+ steps = a.iters
+ sched = optim.join_schedules([optim.linear_schedule(0, a.lr, max(1, steps // 20)), optim.cosine_decay(a.lr, steps)], [max(1, steps // 20)])
+ args = TrainingArgs(batch_size=a.batch, iters=steps, val_batches=-1, steps_per_report=20, steps_per_eval=max(50, steps // 6),
+ steps_per_save=steps, adapter_file=str(out / "adapters.safetensors"), max_seq_length=a.max_len, grad_checkpoint=True)
+ t = time.time()
+ mtrain(model, optim.AdamW(learning_rate=sched, weight_decay=0.0), tr, va, args)
+ print(f"trained {a.task} in {time.time() - t:.0f}s -> {out}", flush=True)
+
+
+class Constrained:
+ """Decoding under a JSON schema: llguidance's matcher masks every token the schema can't take next."""
+
+ def __init__(self, tok, schema):
+ import llguidance
+ import llguidance.hf
+
+ self.ll_tok = getattr(Constrained, "_ll", None)
+ if self.ll_tok is None:
+ Constrained._ll = self.ll_tok = llguidance.hf.from_tokenizer(tok._tokenizer)
+ grammar = llguidance.LLMatcher.grammar_from_json_schema(schema)
+ self.m = llguidance.LLMatcher(self.ll_tok, grammar)
+ err = self.m.get_error()
+ if err:
+ raise ValueError(err)
+ from llguidance.numpy import allocate_token_bitmask
+
+ self.mask = allocate_token_bitmask(1, self.ll_tok.vocab_size)
+ self.n = None
+
+ def __call__(self, tokens, logits):
+ from llguidance.mlx import apply_token_bitmask
+ from llguidance.numpy import fill_next_token_bitmask
+
+ toks = tokens.tolist() if hasattr(tokens, "tolist") else list(tokens)
+ if self.n is None:
+ self.n = len(toks)
+ else:
+ for t in toks[self.n:]:
+ self.m.consume_token(t)
+ self.n = len(toks)
+ if self.m.is_stopped():
+ return logits
+ fill_next_token_bitmask(self.m, self.mask, 0)
+ v = logits.shape[-1]
+ out = apply_token_bitmask(logits[..., : self.ll_tok.vocab_size] if v > self.ll_tok.vocab_size else logits, self.mask)
+ if v > self.ll_tok.vocab_size:
+ import mlx.core as mx
+
+ out = mx.concatenate([out, mx.full((1, v - self.ll_tok.vocab_size), -float("inf"), dtype=out.dtype)], axis=-1)
+ return out
+
+
+def zero_shot_user(task, row, schemas):
+ """An untrained model gets the schema in words too: it has never seen the format."""
+ s = schema_for(task, row, schemas)
+ s.pop("x-guidance", None)
+ return f"{row['prompt']}\n\nThe answer's JSON schema:\n{json.dumps(s, separators=(',', ':'))}"
+
+
+def predict(a):
+ from mlx_lm import load, stream_generate
+ from mlx_lm.sample_utils import make_sampler
+
+ rd = rows_dir(a)
+ schemas = json.load(open(rd / "schemas.json"))
+ rows = read_jsonl(rd / a.task / f"{a.split}.jsonl")[: a.limit or None]
+ who = "zero" if a.zero_shot else Path(a.adapter).name
+ model, tok = load(a.base, adapter_path=None if a.zero_shot else a.adapter)
+ out = rd / a.task / f"pred-{who}-{a.split}.jsonl"
+ done = {json.loads(l)["key"] for l in open(out)} if out.exists() else set()
+ sampler = make_sampler(temp=0.0)
+ t0, n = time.time(), 0
+ with open(out, "a") as f:
+ for r in rows:
+ key = f"{r['i']}:{r.get('at', r.get('kind', ''))}"
+ if key in done:
+ continue
+ user = zero_shot_user(a.task, r, schemas) if a.zero_shot else r["prompt"]
+ p = prompt_text(tok, a.task, user)
+ proc = Constrained(tok, schema_for(a.task, r, schemas))
+ text, t = "", time.time()
+ for resp in stream_generate(model, tok, p, max_tokens=a.max_new, sampler=sampler, logits_processors=[proc]):
+ text += resp.text
+ if proc.m.is_stopped():
+ break
+ n += 1
+ f.write(json.dumps({"key": key, "i": r["i"], "at": r.get("at"), "kind": r.get("kind"), "pred": text, "secs": round(time.time() - t, 2)}) + "\n")
+ f.flush()
+ if n % 10 == 0:
+ print(f"{n}/{len(rows)} in {time.time() - t0:.0f}s", flush=True)
+ print(f"predicted {n} -> {out}", flush=True)
+
+
+def frontier(a):
+ rd = rows_dir(a)
+ schemas = json.load(open(rd / "schemas.json"))
+ rows = read_jsonl(rd / a.task / f"{a.split}.jsonl")[: a.limit or None]
+ key_ = re.search(r"^OPENROUTER_API_KEY=(.+)$", open(HOME / ".raea/env").read(), re.M).group(1).strip()
+ who = "frontier-" + a.model.split("/")[-1]
+ out = rd / a.task / f"pred-{who}-{a.split}.jsonl"
+ done = {json.loads(l)["key"] for l in open(out)} if out.exists() else set()
+ spent = 0.0
+ from concurrent.futures import ThreadPoolExecutor
+
+ def one(r):
+ key = f"{r['i']}:{r.get('at', r.get('kind', ''))}"
+ body = {"model": a.model, "temperature": 0, "max_tokens": 4000, "usage": {"include": True}, "response_format": {"type": "json_object"},
+ "messages": [{"role": "system", "content": SYSTEM[a.task]}, {"role": "user", "content": zero_shot_user(a.task, r, schemas)}]}
+ for attempt in range(3):
+ try:
+ req = urllib.request.Request("https://openrouter.ai/api/v1/chat/completions", data=json.dumps(body).encode(),
+ headers={"Authorization": f"Bearer {key_}", "Content-Type": "application/json", "User-Agent": "story-eval"})
+ t = time.time()
+ j = json.load(urllib.request.urlopen(req, timeout=180))
+ return {"key": key, "i": r["i"], "at": r.get("at"), "kind": r.get("kind"), "pred": j["choices"][0]["message"]["content"] or "",
+ "secs": round(time.time() - t, 2), "usd": j.get("usage", {}).get("cost", 0)}
+ except Exception as e: # retried, then said
+ err = str(e)
+ time.sleep(2 * (attempt + 1))
+ return {"key": key, "i": r["i"], "at": r.get("at"), "kind": r.get("kind"), "pred": "", "error": err}
+
+ todo = [r for r in rows if f"{r['i']}:{r.get('at', r.get('kind', ''))}" not in done]
+ with open(out, "a") as f, ThreadPoolExecutor(8) as ex:
+ for res in ex.map(one, todo):
+ spent += res.get("usd", 0) or 0
+ f.write(json.dumps(res) + "\n")
+ f.flush()
+ print(f"frontier {a.model}: {len(todo)} rows, ${spent:.3f} -> {out}", flush=True)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("cmd", choices=["train", "predict", "frontier"])
+ ap.add_argument("task", choices=["extract", "generate", "critic"])
+ ap.add_argument("--rows", default="~/.vd/story/rows")
+ ap.add_argument("--base", default="Qwen/Qwen3-0.6B")
+ ap.add_argument("--name", default="q06")
+ ap.add_argument("--adapter")
+ ap.add_argument("--iters", type=int, default=600)
+ ap.add_argument("--batch", type=int, default=4)
+ ap.add_argument("--lr", type=float, default=2e-4)
+ ap.add_argument("--rank", type=int, default=16)
+ ap.add_argument("--layers", type=int, default=28)
+ ap.add_argument("--max-len", dest="max_len", type=int, default=4096)
+ ap.add_argument("--max-new", dest="max_new", type=int, default=2500)
+ ap.add_argument("--split", default="test")
+ ap.add_argument("--limit", type=int, default=0)
+ ap.add_argument("--zero-shot", dest="zero_shot", action="store_true")
+ ap.add_argument("--model", default="anthropic/claude-sonnet-5.5")
+ a = ap.parse_args()
+ {"train": train, "predict": predict, "frontier": frontier}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/sdk/story/package.json b/sdk/story/package.json
index aada3aa4..7b25014b 100644
--- a/sdk/story/package.json
+++ b/sdk/story/package.json
@@ -8,9 +8,13 @@
"main": "src/index.ts",
"exports": {
".": "./src/index.ts",
- "./checks": "./src/raea/checks.ts"
+ "./raea/checks": "./src/raea/checks.ts",
+ "./raea/compose": "./src/raea/compose.tsx"
},
"scripts": {
"test": "bun test test"
+ },
+ "peerDependencies": {
+ "react": "19.2.0"
}
}
diff --git a/sdk/story/src/checks.ts b/sdk/story/src/checks.ts
index c6c0aa7a..4e81d9c9 100644
--- a/sdk/story/src/checks.ts
+++ b/sdk/story/src/checks.ts
@@ -39,6 +39,7 @@ export function checkWorld(w: World): Finding[] {
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 keyAt = (i: number) => beats[i]?.key ?? `b${i}`;
const planted = new Map<string, number>();
const paid = new Set<string>();
for (const { key, beat, index } of beats) {
@@ -50,7 +51,7 @@ export function checkWorld(w: World): Finding[] {
}
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 [s, at] of planted) if (!paid.has(s)) add("setup", "warn", keyAt(at), `${keyAt(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`);
diff --git a/sdk/story/src/compile.ts b/sdk/story/src/compile.ts
index 7783447d..05b1b955 100644
--- a/sdk/story/src/compile.ts
+++ b/sdk/story/src/compile.ts
@@ -23,7 +23,7 @@ export function compileScript(s: AnyStory, telling?: string, seed = 0): Script &
const b: ScriptBeat = { onScreen: onScreenOf(s, beat, seed), ...(lines.length ? { lines } : {}), ...(beat.seconds ? { seconds: beat.seconds } : {}) };
const pays = listOf(beat.pays), answered = a.answered;
const payoff = [...pays.map((p) => `pays off ${p}`), ...answered.map((f) => `answers ${f}`)].join("; ");
- return { heading: `${key.toUpperCase()}${beat.feel ? ` · ${beat.feel}` : ""}`, beats: [b], ...(payoff ? { payoff } : {}) };
+ return { heading: `${key.toUpperCase()}${beat.feel ? ` · ${beat.feel}` : ""}`, beats: [b], ...(payoff ? { payoff } : {}), beat: key };
});
return { title: info.title ?? "Untitled", ...(info.premise ? { logline: info.premise } : {}), scenes, beats: beatsOf(w).map((b) => b.key) };
}
diff --git a/sdk/story/src/data.ts b/sdk/story/src/data.ts
new file mode 100644
index 00000000..1c0bf6a9
--- /dev/null
+++ b/sdk/story/src/data.ts
@@ -0,0 +1,149 @@
+// A story as plain JSON, for anything outside TypeScript: a model that writes or reads stories, a file, the wire
+// (docs/story.feature ST6a). fromData() reads JSON into a story and says what's wrong with it: a reference to a key that
+// isn't declared, a field of the wrong shape. tsc checks a story written in code; this checks one that wasn't.
+//
+// The schemas are where the story models are schema-native: storySchema() is the shape of a whole story, and
+// beatSchema(story) is the shape of one more beat *for that story*, its references enums of the story's own keys, so a
+// generator decoding under it can't name an event, a fact or a setup the story doesn't have.
+import type { AnyStory } from "./model.ts";
+import { resolved, type RStory } from "./load.ts";
+
+type Json = Record<string, unknown>;
+export type DataError = { at: string; says: string };
+
+/** A story as plain JSON: every choice point picked (with the seed), `kind` dropped. */
+export function toData(s: AnyStory, seed = 0): Json {
+ const { kind: _kind, ...rest } = resolved(s, seed) as RStory & { kind?: string };
+ return JSON.parse(JSON.stringify(rest));
+}
+
+const str = { type: "string" };
+const strs = { type: "array", items: str };
+const enumOf = (keys: string[]) => (keys.length ? { type: "string", enum: keys } : str);
+const listOf = (s: Json) => ({ type: "array", items: s });
+const oneOrMany = (s: Json) => ({ anyOf: [s, listOf(s)] });
+
+const MASKS = ["hero", "mentor", "ally", "herald", "threshold", "shapeshifter", "shadow", "trickster", "gift"];
+
+/** One beat's shape; with keys, its references are enums of them. */
+export function beatShape(k: { events?: string[]; facts?: string[]; agents?: string[]; setups?: string[] } = {}): Json {
+ const ev = enumOf(k.events ?? []), fact = enumOf(k.facts ?? []), who = k.agents?.length ? { type: "string", enum: [...k.agents, "narrator"] } : str;
+ return {
+ type: "object",
+ additionalProperties: false,
+ required: ["shows"],
+ properties: {
+ id: str,
+ shows: listOf(ev),
+ reveals: listOf(fact),
+ hides: listOf(fact),
+ asks: listOf(fact),
+ feel: str,
+ setup: oneOrMany(str),
+ pays: oneOrMany(k.setups?.length ? enumOf(k.setups) : str),
+ stage: { type: "object", additionalProperties: str },
+ surprise: { type: "string", enum: ["meant"] },
+ says: listOf({ type: "object", additionalProperties: false, required: ["who", "says"], properties: { who, says: str, means: str, how: str } }),
+ onScreen: str,
+ seconds: { type: "number" },
+ },
+ };
+}
+
+/** The keys a story declares, by kind (setups are the ones its beats plant). */
+export function keysIn(s: Json): { values: string[]; facts: string[]; agents: string[]; events: string[]; setups: string[] } {
+ const keys = (o: unknown) => (o && typeof o === "object" ? Object.keys(o) : []);
+ const tellings = Object.values((s.tellings ?? {}) as Record<string, Json[]>);
+ const setups = [...new Set(tellings.flat().flatMap((b) => (b?.setup === undefined ? [] : ([] as unknown[]).concat(b.setup))).map(String))];
+ return { values: keys(s.values), facts: keys(s.facts), agents: keys(s.agents), events: keys(s.world), setups };
+}
+
+/** The shape of one more beat for this story: what a generator decodes under. */
+export const beatSchema = (s: AnyStory | Json, seed = 0): Json => {
+ const k = keysIn((s as AnyStory).kind === "story" ? toData(s as AnyStory, seed) : (s as Json));
+ return beatShape(k);
+};
+
+/** The shape of a whole story (keys free; fromData checks the references). */
+export function storySchema(): Json {
+ const turns = { type: "object", additionalProperties: { type: "integer", minimum: -3, maximum: 3 } };
+ const event = {
+ type: "object",
+ additionalProperties: false,
+ required: ["who", "does"],
+ properties: {
+ who: str, with: strs, does: str, because: oneOrMany(str), needs: strs, sets: strs, unsets: strs, learns: strs, turns,
+ ends: { type: "object", additionalProperties: { type: "string", enum: ["want", "need", "lie", "want-refused"] } },
+ dilemma: strs, claim: str, proof: strs, routine: { type: "boolean" },
+ },
+ };
+ const agent = {
+ type: "object",
+ additionalProperties: false,
+ properties: { want: str, need: str, lie: str, mask: { type: "string", enum: MASKS }, believes: strs, arc: { type: "string", enum: ["positive", "negative", "flat"] }, role: str },
+ };
+ return {
+ type: "object",
+ additionalProperties: false,
+ required: ["values", "agents", "world", "tellings"],
+ properties: {
+ title: str,
+ premise: str,
+ idea: { type: "object", additionalProperties: false, required: ["side"], properties: { value: str, side: str, counter: str } },
+ values: { type: "object", additionalProperties: { type: "object", additionalProperties: false, required: ["neg", "pos"], properties: { neg: str, pos: str } } },
+ facts: { type: "object", additionalProperties: str },
+ agents: { type: "object", additionalProperties: agent },
+ world: { type: "object", additionalProperties: event },
+ tellings: { type: "object", additionalProperties: listOf(beatShape()) },
+ lenses: strs,
+ },
+ };
+}
+
+/** JSON read as a story, with everything wrong in it. A story with errors is still returned, for a critic to read. */
+export function fromData(j: unknown): { story: AnyStory | null; errors: DataError[] } {
+ const errors: DataError[] = [];
+ const err = (at: string, says: string) => errors.push({ at, says });
+ if (!j || typeof j !== "object" || Array.isArray(j)) return { story: null, errors: [{ at: "", says: "a story is a JSON object" }] };
+ const s = j as Json;
+ for (const f of ["values", "agents", "world", "tellings"]) if (!s[f] || typeof s[f] !== "object" || Array.isArray(s[f])) err(f, `a story needs ${f}, an object`);
+ if (errors.length) return { story: null, errors };
+ const k = keysIn(s);
+ const has = (kind: keyof typeof k, at: string, x: unknown) => {
+ if (typeof x !== "string") return err(at, `expected a ${kind.slice(0, -1)} key, got ${JSON.stringify(x)}`);
+ if (!k[kind].includes(x)) err(at, `"${x}" isn't one of the story's ${kind} (${k[kind].join(", ") || "none"})`);
+ };
+ const many = (kind: keyof typeof k, at: string, x: unknown) => ([] as unknown[]).concat(x ?? []).forEach((y, i) => has(kind, `${at}[${i}]`, y));
+ for (const [a, ag] of Object.entries(s.agents as Record<string, Json>)) many("facts", `agents.${a}.believes`, ag?.believes);
+ const order = k.events;
+ for (const [e, ev] of Object.entries(s.world as Record<string, Json>)) {
+ if (!ev || typeof ev !== "object") { err(`world.${e}`, "an event is an object"); continue; }
+ has("agents", `world.${e}.who`, ev.who);
+ if (typeof ev.does !== "string" || !ev.does) err(`world.${e}.does`, "an event says what happens (does)");
+ many("agents", `world.${e}.with`, ev.with);
+ many("events", `world.${e}.because`, ev.because);
+ for (const c of ([] as unknown[]).concat(ev.because ?? [])) if (typeof c === "string" && order.indexOf(c) >= order.indexOf(e)) err(`world.${e}.because`, `"${c}" comes after ${e} in story order`);
+ for (const f of ["needs", "sets", "unsets", "learns", "proof"]) many("facts", `world.${e}.${f}`, ev[f]);
+ for (const [v, d] of Object.entries((ev.turns ?? {}) as Json)) {
+ has("values", `world.${e}.turns`, v);
+ if (typeof d !== "number" || !Number.isInteger(d) || Math.abs(d) > 3) err(`world.${e}.turns.${v}`, "a turn is a whole number of steps, -3 to 3");
+ }
+ for (const a of Object.keys((ev.ends ?? {}) as Json)) has("agents", `world.${e}.ends`, a);
+ }
+ for (const [t, beats] of Object.entries(s.tellings as Record<string, unknown>)) {
+ if (!Array.isArray(beats)) { err(`tellings.${t}`, "a telling is a list of beats"); continue; }
+ beats.forEach((b: Json, i) => {
+ const at = `tellings.${t}[${i}]`;
+ if (!b || typeof b !== "object") return err(at, "a beat is an object");
+ if (!Array.isArray(b.shows)) err(`${at}.shows`, "a beat lists the events it shows (shows: [] for none)");
+ many("events", `${at}.shows`, b.shows);
+ for (const f of ["reveals", "hides", "asks"]) many("facts", `${at}.${f}`, b[f]);
+ many("setups", `${at}.pays`, b.pays);
+ ([] as Json[]).concat((b.says as Json[]) ?? []).forEach((l, j) => {
+ if (l?.who !== "narrator") has("agents", `${at}.says[${j}].who`, l?.who);
+ });
+ });
+ }
+ if (s.idea && (s.idea as Json).value !== undefined) has("values", "idea.value", (s.idea as Json).value);
+ return { story: { ...(s as object), kind: "story" } as AnyStory, errors };
+}
diff --git a/sdk/story/src/index.ts b/sdk/story/src/index.ts
index 06d4804e..8d9e2ab8 100644
--- a/sdk/story/src/index.ts
+++ b/sdk/story/src/index.ts
@@ -15,3 +15,4 @@ export { LENSES, mckee, pas, pixar, storynomics } from "./lenses/index.ts";
export { sample, samples, matrix, judge, type Sampled, type SampleOptions, type MatrixResult, type MatrixRow } from "./sample.ts";
export { compileScript, compileStorylets, dramaManager, toInk, toYarn, onScreenOf, type Storylet } from "./compile.ts";
export { resolved, type RStory } from "./load.ts";
+export { toData, fromData, storySchema, beatSchema, beatShape, keysIn, type DataError } from "./data.ts";
diff --git a/sdk/story/src/load.ts b/sdk/story/src/load.ts
index 14bfcaa7..70a7c5d8 100644
--- a/sdk/story/src/load.ts
+++ b/sdk/story/src/load.ts
@@ -2,7 +2,7 @@
// 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" ...)
+// beats { Key, Beat, Index } (Index: its place in the telling; Key its id, else "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";
@@ -32,7 +32,7 @@ export function load(s: AnyStory, telling?: string, seed = 0): World {
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 })));
+ (beats as RBeat[]).forEach((b, i) => keys.beats.push(w.spawn({ Key: b.id ?? `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;
diff --git a/sdk/story/src/model.ts b/sdk/story/src/model.ts
index 91e6d74c..ffa9428c 100644
--- a/sdk/story/src/model.ts
+++ b/sdk/story/src/model.ts
@@ -78,6 +78,8 @@ export type Line<A extends string> = {
};
export type Beat<F extends string, A extends string, E extends string, S extends string> = {
+ /** its name: what a composition's Sequence and raea check call it (default b0, b1 ... by place) */
+ id?: 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 */
diff --git a/sdk/story/src/mutate.ts b/sdk/story/src/mutate.ts
index ed9bc616..cd36e1c1 100644
--- a/sdk/story/src/mutate.ts
+++ b/sdk/story/src/mutate.ts
@@ -23,26 +23,27 @@ export function mutants(s: AnyStory, telling?: string, seed = 0): Mutant[] {
const beats = (): Tell => clone(base.tellings[t]);
const withTelling = (b: Tell, world = base.world): AnyStory => ({ ...clone(base), world: clone(world), tellings: { ...clone(base.tellings), [t]: b } }) as unknown as AnyStory;
const keys = Object.keys(base.world);
+ const bk = (i: number, b: Tell = base.tellings[t]) => b[i]?.id ?? `b${i}`;
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" } });
+ out.push({ story: withTelling(b), telling: t, label: { kind: "drop-setup", at: bk(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" } });
+ out.push({ story: withTelling(b), telling: t, label: { kind: "drop-payoff", at: bk(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" } });
+ out.push({ story: withTelling(beats(), world), telling: t, label: { kind: "flatten-beat", at: bk(i), says: `${bk(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` } });
+ out.push({ story: withTelling(b), telling: t, label: { kind: "swap-beats", at: bk(i), says: `${bk(i)} and ${bk(i + 1)} were swapped` } });
}
});
@@ -69,7 +70,7 @@ export function mutants(s: AnyStory, telling?: string, seed = 0): Mutant[] {
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" } });
+ out.push({ story: withTelling(b), telling: t, label: { kind: "drop-cause-beat", at: bk(i), says: `${bk(i)}, the only sight of a cause, was cut`, expect: "and-then" } });
});
const world = clone(base.world);
@@ -78,7 +79,7 @@ export function mutants(s: AnyStory, telling?: string, seed = 0): Mutant[] {
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" } });
+ out.push({ story: withTelling(b, world), telling: t, label: { kind: "orphan-event", at: bk(at, b), says: "an uncaused event that turns nothing was inserted", expect: "cause" } });
return out;
}
diff --git a/sdk/story/src/raea/checks.ts b/sdk/story/src/raea/checks.ts
new file mode 100644
index 00000000..5c024bf9
--- /dev/null
+++ b/sdk/story/src/raea/checks.ts
@@ -0,0 +1,65 @@
+// A story's checks as one raea/check check (docs/story.feature ST5a). A project uses it explicitly, with a three-line
+// check of its own that imports its story:
+//
+// // checks/story.ts
+// import { storyCheck } from "raea/story/raea/checks";
+// import launch from "../launch.story";
+// export default storyCheck(launch, { telling: "30s", lenses: ["mckee", "pas", "storynomics"] });
+//
+// and a taste line that names it: { text: "The story holds and is on screen", check: "checks/story.ts" }.
+// On every frame it keeps the shots (a Sequence's name and frames) and the spoken lines; after the last frame it reports
+// the story's own findings (exact checks and lenses), then each beat with no shot named for it, a beat whose shot comes
+// out of the telling's order, and a beat line that's never spoken inside its shot. It's `over: "both"`: `raea check
+// launch.story.ts` runs it with no frames, before anything is drawn, and then only the story's own findings speak.
+import { check, found, type Line, type Shot } from "raea/check";
+import { judge } from "../sample.ts";
+import { LENSES } from "../lenses/index.ts";
+import { resolved } from "../load.ts";
+import type { Lens } from "../lens.ts";
+import type { AnyStory } from "../model.ts";
+
+export type StoryCheckOptions = { telling?: string; seed?: number; lenses?: (string | Lens)[]; onScreen?: boolean; id?: string };
+
+const words = (s: string) => s.toLowerCase().replace(/[^a-z0-9' ]+/g, " ").split(/\s+/).filter(Boolean);
+
+export function storyCheck(s: AnyStory, o: StoryCheckOptions = {}) {
+ const lenses = (o.lenses ?? s.lenses ?? []).map((l) => (typeof l === "string" ? LENSES[l] : l)).filter((l): l is Lens => !!l);
+ const tellingName = o.telling ?? Object.keys(s.tellings)[0];
+ return check(
+ { id: o.id ?? "story", text: "the story holds together, and every beat is on screen in order", over: "both" },
+ (world, frame, _values, memo) => {
+ memo.shots ??= {};
+ memo.lines ??= [];
+ for (const e of world.find({ with: ["Shot"] })) {
+ const sh = world.component<Shot>(e, "Shot")!;
+ if (!sh.name) continue;
+ const m = (memo.shots[sh.name] ??= { from: sh.from, to: sh.to ?? frame + 1 });
+ m.to = Math.max(m.to, sh.to ?? frame + 1);
+ }
+ for (const e of world.find({ with: ["Line"] })) {
+ const l = world.component<Line>(e, "Line")!;
+ if (!memo.lines.some((x: Line) => x.from === l.from && x.text === l.text)) memo.lines.push({ text: l.text, from: l.from, to: l.to ?? l.from });
+ }
+ },
+ (_values, memo) => {
+ for (const f of judge(s, o.seed ?? 0, tellingName, lenses)) found({ about: [f.about], says: f.says, level: f.level, ...(f.fix ? { fix: f.fix } : {}) });
+ // with no frames (raea check NAME.story.ts), the story alone: nothing was drawn to look for
+ if (o.onScreen === false || memo.shots === undefined) return;
+ const beats = resolved(s, o.seed ?? 0).tellings[tellingName] ?? [];
+ let last = -1;
+ beats.forEach((b, i) => {
+ const key = b.id ?? `b${i}`;
+ const shot = memo.shots?.[key] as { from: number; to: number } | undefined;
+ if (!shot) return found({ about: [key], says: `the beat ${key} has no shot named for it`, fix: `name the beat's Sequence "${key}" (or use <Beat> from raea/story/raea/compose)` });
+ if (shot.from < last) found({ about: [key], frames: [shot.from, shot.to], says: `${key} comes before the beat it follows in the telling`, level: "warn" });
+ last = shot.from;
+ for (const l of b.says ?? []) {
+ const want = words(String(l.says));
+ const said = (memo.lines as Line[]).filter((x) => x.from < shot.to && (x.to ?? x.from) >= shot.from).flatMap((x) => words(x.text));
+ const heard = want.filter((w) => said.includes(w)).length;
+ if (want.length && heard / want.length < 0.6) found({ about: [key], frames: [shot.from, shot.to], says: `${key}'s line "${l.says}" isn't spoken inside its shot`, level: "warn" });
+ }
+ });
+ },
+ );
+}
diff --git a/sdk/story/src/raea/compose.tsx b/sdk/story/src/raea/compose.tsx
new file mode 100644
index 00000000..f20d972f
--- /dev/null
+++ b/sdk/story/src/raea/compose.tsx
@@ -0,0 +1,37 @@
+// A composition using a story explicitly (docs/story.feature ST5a): each beat's frames from the telling (a beat's
+// `seconds`, else `each`), and <Beat>, a Sequence named by the beat's id so raea check's story check finds it.
+import { Sequence } from "raea";
+import type { ReactNode } from "react";
+import { resolved } from "../load.ts";
+import type { AnyStory } from "../model.ts";
+
+export type BeatTime = { key: string; from: number; durationInFrames: number };
+
+/** Every beat of a telling with its first frame and length, laid end to end. */
+export function beatTimes(s: AnyStory, telling: string | undefined, fps: number, each = 3, seed = 0): BeatTime[] {
+ const name = telling ?? Object.keys(s.tellings)[0];
+ let from = 0;
+ return (resolved(s, seed).tellings[name] ?? []).map((b, i) => {
+ const durationInFrames = Math.round((b.seconds ?? each) * fps);
+ const t = { key: b.id ?? `b${i}`, from, durationInFrames };
+ from += durationInFrames;
+ return t;
+ });
+}
+
+/** One beat's frames, by its key. */
+export function beatTime(times: BeatTime[], key: string): BeatTime {
+ const t = times.find((x) => x.key === key);
+ if (!t) throw new Error(`no beat ${key} in this telling (it has ${times.map((x) => x.key).join(", ")})`);
+ return t;
+}
+
+/** A beat on screen: a Sequence named by its key, at its frames. */
+export function Beat({ times, id, children }: { times: BeatTime[]; id: string; children?: ReactNode }) {
+ const t = beatTime(times, id);
+ return (
+ <Sequence name={t.key} from={t.from} durationInFrames={t.durationInFrames}>
+ {children}
+ </Sequence>
+ );
+}
diff --git a/sdk/story/test/data.test.ts b/sdk/story/test/data.test.ts
new file mode 100644
index 00000000..67783344
--- /dev/null
+++ b/sdk/story/test/data.test.ts
@@ -0,0 +1,25 @@
+import { expect, test } from "bun:test";
+import { beatSchema, checkStory, fromData, toData } from "../src/index.ts";
+import { launch } from "./fixture.ts";
+
+test("a story round-trips through JSON and reads back clean", () => {
+ const j = toData(launch);
+ const { story, errors } = fromData(j);
+ expect(errors).toEqual([]);
+ expect(checkStory(story!, "30s").filter((f) => f.level === "error")).toEqual(checkStory(launch, "30s").filter((f) => f.level === "error"));
+});
+
+test("fromData names a bad reference and a cause out of order", () => {
+ const j = toData(launch) as any;
+ j.tellings["30s"][1].shows.push("nope");
+ j.world.week.because = "ships";
+ const msgs = fromData(j).errors.map((e) => e.at);
+ expect(msgs).toContain("tellings.30s[1].shows[2]");
+ expect(msgs).toContain("world.week.because");
+});
+
+test("a beat's schema holds the story's own keys", () => {
+ const s = beatSchema(launch) as any;
+ expect(s.properties.shows.items.enum).toEqual(["week", "doubles", "tries", "ships"]);
+ expect(s.properties.pays.anyOf[0].enum).toEqual(["how"]);
+});
diff --git a/sdk/story/test/sample.test.ts b/sdk/story/test/sample.test.ts
index 38c33195..cfb6c452 100644
--- a/sdk/story/test/sample.test.ts
+++ b/sdk/story/test/sample.test.ts
@@ -44,6 +44,7 @@ test("a telling compiles to a Script, the world to storylets a drama manager pla
expect(sc.scenes.length).toBe(4);
expect(sc.scenes[0].heading).toBe("B0 · curiosity");
expect(sc.scenes[3].payoff).toBe("pays off how; answers recipeRuns");
+ expect(sc.scenes.map((x) => x.beat)).toEqual(["b0", "b1", "b2", "b3"]);
const played = dramaManager(compileStorylets(launch), [0.2, 0.6, 0.4, 1]);
expect(played).toEqual(["week", "doubles", "tries", "ships"]);
const withLines = { ...launch, tellings: { "30s": [{ shows: ["tries" as const], says: [{ who: "team" as const, says: "Fine. One recipe.", means: "I don't believe it" }] }] } };
diff --git a/sdk/story/tsconfig.json b/sdk/story/tsconfig.json
index ea8e00e9..d8489e2e 100644
--- a/sdk/story/tsconfig.json
+++ b/sdk/story/tsconfig.json
@@ -1,11 +1,5 @@
{
"extends": "../tsconfig.base.json",
- "compilerOptions": {
- "allowImportingTsExtensions": true,
- "verbatimModuleSyntax": true,
- "erasableSyntaxOnly": true,
- "noUnusedLocals": true,
- "lib": ["ES2023"]
- },
+ "compilerOptions": { "allowImportingTsExtensions": true },
"include": ["src", "test/types.ts", "test/fixture.ts"]
}