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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
ST10a: raea/story under edge cases, fuzzing and an A/B against plain prompts. Fixes what they found: fromData holds a story to storySchema() (shapeErrors), so a wrong-typed field or one in the wrong place is refused with where (a beat's turns, believes as text: 270 of 1,572 corpus stories carried one, silently dropped before) instead of crashing a reader (21 crash sites fuzzed to 0); unsets takes a fact back from those in the event and from the audience, and a claim can't rest on an undone fact; two beats with one id are an error (fromData and checks); seconds can't be negative; a telling that shows nothing is a finding; asker says when a beat isn't there. bench/: edges.ts (29 cases), fuzz.ts, ab.ts + ab-report.ts. direction: file_index without the closure cargo-dupes matched (293 exact again).
shinyobjectz69c631b66263
diff --git a/apps/direction/src/check.rs b/apps/direction/src/check.rsindex ffc95948..0b1ab601 100644--- a/apps/direction/src/check.rs+++ b/apps/direction/src/check.rs@@ -271,10 +271,11 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh/// Where `f` is in `files`, added at the end when it isn't yet: the one run's checks, each file once.fn file_index(files: &mut Vec<PathBuf>, f: &Path) -> usize {- files.iter().position(|x| x == f).unwrap_or_else(|| {- files.push(f.to_path_buf());- files.len() - 1- })+ if let Some(at) = files.iter().position(|x| x == f) {+ return at;+ }+ files.push(f.to_path_buf());+ files.len() - 1}/// Whether `r` runs on the composition `tsx` (`id` where its file registers several) of `project`: a rule a note's askdiff --git a/sdk/story/bench/ab-report.ts b/sdk/story/bench/ab-report.tsnew file mode 100644index 00000000..60cc841d--- /dev/null+++ b/sdk/story/bench/ab-report.ts@@ -0,0 +1,110 @@+// Reads an A/B run (bench/ab.ts) and says what it found: judges' ranks and scores by arm, blind-extracted findings per+// beat, B's repair rounds, cost and time, per-prompt winners, judge agreement, and B against C pair by pair.+// bun bench/ab-report.ts ~/.vd/story/ab/run1 [--json]+import { readFileSync } from "node:fs";+import { join } from "node:path";++type J = Record<string, any>;+const dir = process.argv[2];+const rows: J[] = readFileSync(join(dir, "rows.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));+const ARMS = ["A", "C", "B", "D", "E"];+const NAME: Record<string, string> = { A: "plain", C: "plain+edit", B: "raea/story", D: "plain+checks", E: "story+write" };+const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : NaN);+const f2 = (x: number) => (Number.isFinite(x) ? x.toFixed(2) : "-");+const binom = (k: number, n: number) => { // two-sided sign test+ const c = (n: number, k: number) => { let r = 1; for (let i = 1; i <= k; i++) r = (r * (n - k + i)) / i; return r; };+ const lo = Math.min(k, n - k); let p = 0; for (let i = 0; i <= lo; i++) p += c(n, i); return Math.min(1, (2 * p) / 2 ** n);+};+const out: J = { rows: rows.length };++console.log(`${rows.length} prompt samples, ${new Set(rows.map((r) => r.id)).size} prompts\n`);+// judges+const crit = ["cause", "setups", "clarity", "brief", "feeling", "overall"];+console.log("JUDGES (rank 1 = best; scores 1-10)");+console.log(`${"arm".padEnd(12)} ${"rank".padStart(5)} ${"firsts".padStart(7)} ${crit.map((c) => c.padStart(8)).join("")}`);+out.judges = {};+for (const a of ARMS) {+ const ranks: number[] = [], firsts: number[] = [], sc: Record<string, number[]> = Object.fromEntries(crit.map((c) => [c, []]));+ for (const r of rows) for (const j of r.judged) {+ const i = j.rank.indexOf(a); if (i < 0) continue;+ ranks.push(i + 1); firsts.push(i === 0 ? 1 : 0);+ for (const c of crit) { const v = Number(j.scores?.[a]?.[c]); if (Number.isFinite(v)) sc[c].push(v); }+ }+ out.judges[a] = { rank: mean(ranks), firsts: mean(firsts), n: ranks.length, ...Object.fromEntries(crit.map((c) => [c, mean(sc[c])])) };+ console.log(`${NAME[a].padEnd(12)} ${f2(mean(ranks)).padStart(5)} ${(Math.round(mean(firsts) * 100) + "%").padStart(7)} ${crit.map((c) => f2(mean(sc[c])).padStart(8)).join("")}`);+}+for (const m of [...new Set(rows.flatMap((r) => r.judged.map((j: J) => j.judge)))]) {+ console.log(` ${m}: ${ARMS.map((a) => `${NAME[a]} ${f2(mean(rows.flatMap((r) => r.judged.filter((j: J) => j.judge === m).map((j: J) => j.rank.indexOf(a) + 1).filter((x: number) => x > 0))))}`).join(", ")}`);+}+// agreement: the two judges pick the same first+const both = rows.filter((r) => r.judged.length === 2 && r.judged.every((j: J) => j.rank.length));+const agree = both.filter((r) => r.judged[0].rank[0] === r.judged[1].rank[0]).length;+console.log(` judges pick the same best in ${agree} of ${both.length}`);+out.agree = { same: agree, of: both.length };++// pair by pair: B vs C, B vs A, C vs A on each judge's rank+console.log("\nPAIRS (each judge's ranking of a sample is one vote)");+out.pairs = {};+for (const [x, y] of [["D", "C"], ["D", "A"], ["E", "A"], ["E", "C"], ["E", "B"], ["C", "A"], ["B", "A"], ["B", "C"]]) {+ let w = 0, n = 0;+ for (const r of rows) for (const j of r.judged) { const i = j.rank.indexOf(x), k = j.rank.indexOf(y); if (i < 0 || k < 0) continue; n++; if (i < k) w++; }+ out.pairs[`${x}>${y}`] = { wins: w, of: n, p: binom(w, n) };+ console.log(` ${NAME[x]} over ${NAME[y]}: ${w} of ${n} (sign test p = ${binom(w, n).toFixed(3)})`);+}++// extraction+console.log("\nBLIND EXTRACTION (the script alone read back into story data; findings from checkStory)");+out.extract = {};+for (const a of ARMS) {+ const per: number[] = [], errs: number[] = [], byCheck: Record<string, number> = {};+ let failed = 0, beats = 0;+ for (const r of rows) { const x = r.arms.find((y: J) => y.arm === a); if (!x?.extract) continue; if (!x.extract.checks) { failed++; continue; }+ const f = x.extract.checks.filter((c: J) => c.level !== "note"); const nb = Math.max(1, x.extract.beats || x.beats);+ per.push(f.length / nb); errs.push(f.filter((c: J) => c.level === "error").length / nb); beats += nb;+ for (const c of f) byCheck[c.check] = (byCheck[c.check] ?? 0) + 1; }+ const top = Object.entries(byCheck).sort((p, q) => q[1] - p[1]).slice(0, 6).map(([k, v]) => `${k} ${(v / beats).toFixed(2)}`).join(", ");+ out.extract[a] = { perBeat: mean(per), errorsPerBeat: mean(errs), failed, byCheck };+ console.log(` ${NAME[a].padEnd(12)} errors+warns a beat ${f2(mean(per))}, errors a beat ${f2(mean(errs))}${failed ? `, ${failed} unreadable` : ""}; per beat: ${top}`);+}++// the noise floor: a B story whose own data passed every check, read back blind from its script. What the extraction+// finds there is the gap between the data and the screen (or the extractor's own noise), not a hole in the story.+{+ const passed = rows.map((r) => r.arms.find((y: J) => y.arm === "B")).filter((b) => b?.extract?.checks && (() => { const l = [...b.log].reverse().find((x: J) => x.blocking); return l && !l.blocking.length; })());+ const per = passed.map((b) => b.extract.checks.filter((c: J) => c.level !== "note").length / Math.max(1, b.extract.beats || b.beats));+ out.noiseFloor = { perBeat: mean(per), n: passed.length };+ console.log(` floor: B stories that passed their own checks still get ${f2(mean(per))} a beat read back from the screen (n = ${passed.length})`);+}++// B's own loop+console.log("\nRAEA/STORY'S OWN LOOP");+const B = rows.map((r) => r.arms.find((y: J) => y.arm === "B")).filter(Boolean);+const first = B.filter((b) => b.log[0]?.blocking && !b.log[0].blocking.length).length;+const last = B.filter((b) => { const l = [...b.log].reverse().find((x: J) => x.blocking); return l && !l.blocking.length; }).length;+const crashes = B.filter((b) => b.log.some((x: J) => x.crash)).length;+const fixed: Record<string, number> = {};+for (const b of B) for (const l of b.log) for (const s of l.blocking ?? []) { const k = String(s).split(" ").slice(0, 2).join(" "); fixed[k] = (fixed[k] ?? 0) + 1; }+console.log(` passed on the first draft ${first} of ${B.length}; passed by the last round ${last} of ${B.length}; mean calls ${f2(mean(B.map((b) => b.calls)))}; SDK crashes ${crashes}`);+console.log(` findings it raised over all rounds: ${Object.entries(fixed).sort((p, q) => q[1] - p[1]).slice(0, 10).map(([k, v]) => `${k} x${v}`).join(", ")}`);+out.loop = { first, last, of: B.length, calls: mean(B.map((b) => b.calls)), crashes, raised: fixed };++// cost and shape+console.log("\nCOST AND SHAPE (writer only)");+out.cost = {};+for (const a of ARMS) {+ const xs = rows.map((r) => r.arms.find((y: J) => y.arm === a)).filter((x) => x?.final);+ out.cost[a] = { usd: mean(xs.map((x) => x.usd)), secs: mean(xs.map((x) => x.ms / 1000)), beats: mean(xs.map((x) => x.beats)), seconds: mean(xs.map((x) => x.seconds)) };+ console.log(` ${NAME[a].padEnd(12)} $${mean(xs.map((x) => x.usd)).toFixed(3)} a story, ${f2(mean(xs.map((x) => x.ms / 1000)))} s, ${f2(mean(xs.map((x) => x.beats)))} beats, ${f2(mean(xs.map((x) => x.seconds)))} s of film`);+}++// per prompt+console.log("\nBY PROMPT (mean rank over both judges and samples; best first)");+out.byPrompt = {};+for (const id of [...new Set(rows.map((r) => r.id))]) {+ const rs = rows.filter((r) => r.id === id);+ const m = ARMS.map((a) => [a, mean(rs.flatMap((r) => r.judged.map((j: J) => j.rank.indexOf(a) + 1).filter((x: number) => x > 0)))] as [string, number]).sort((p, q) => p[1] - q[1]);+ out.byPrompt[id] = Object.fromEntries(m);+ const ex = ARMS.map((a) => `${a} ${f2(mean(rs.map((r) => { const x = r.arms.find((y: J) => y.arm === a); return x?.extract?.checks ? x.extract.checks.filter((c: J) => c.level !== "note").length / Math.max(1, x.extract.beats || x.beats) : NaN; }).filter(Number.isFinite)))}`).join(" ");+ console.log(` ${id.padEnd(16)} ${m.map(([a, v]) => `${NAME[a]} ${f2(v)}`).join(" > ")} extract/beat: ${ex}`);+}+if (process.argv.includes("--json")) console.log(JSON.stringify(out));diff --git a/sdk/story/bench/ab.ts b/sdk/story/bench/ab.tsnew file mode 100644index 00000000..25ae8e8c--- /dev/null+++ b/sdk/story/bench/ab.ts@@ -0,0 +1,281 @@+// The same prompts with and without raea/story (docs/story.md). Three arms, one writer model:+// A plain the prompt, a beat script back, one call+// C plain+edit A, then a story editor's critique and rewrite in the writer's own head: the same knowledge the+// checks and the brief's lenses hold, said in words, with no machinery (one more call)+// B raea/story the story as data under the guide; checkStory and the lenses find what's wrong; the writer+// repairs from the findings, up to two rounds; its beats become the same beat script+// Every arm ends in the same format (numbered beats: what's on screen, who says what), scored the same blind ways:+// 1. extract: another model reads the script (nothing else) back into story data, recording only what's shown,+// and checkStory reads that: structure measured from the screen alone, not from the arm's own claims+// 2. judges: two models of other families rank the three scripts for a prompt, letters shuffled+// D raea/story as editor A's script read back blind into story data; checkStory and the lenses find its holes,+// handed to the writer by beat number; the writer rewrites the script (C's round, with the+// editor's eye replaced by the exact checks)+// E raea/story, then write B's checked story as story lines; the writer writes the script from it as a screenwriter+// bun bench/ab.ts [--samples 2] [--only id,id] [--out DIR] [--writer M] [--jobs 8] [--reuse RUN_DIR] [--arms A,C,B,D,E]+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { checkStory, fromData, LENSES, readThrough, resolved, rng, scriptOf, toData, toLines, 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 SAMPLES = Number(arg("--samples", "2"));+const ONLY = arg("--only", "").split(",").filter(Boolean);+const OUT = arg("--out", join(homedir(), ".vd/story/ab", new Date().toISOString().slice(0, 16).replace(/[:T]/g, "-")));+const WRITER = arg("--writer", "anthropic/claude-sonnet-5.5");+const EXTRACTOR = arg("--extractor", "google/gemini-3.7-flash");+const JUDGES = arg("--judges", "openai/gpt-5.4,google/gemini-3.1-pro-preview").split(",");+const JOBS = Number(arg("--jobs", "8"));+const REUSE = arg("--reuse", "");+const ARMS = arg("--arms", "A,C,B,D,E").split(",");+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 });++type J = Record<string, any>;+type Prompt = { id: string; brief: string; lenses: string[]; editor: string };+// made-up brands only. Each prompt names the frameworks it's held to; arm C's editor is told the same in words.+const PROMPTS: Prompt[] = [+ { id: "tent-launch", lenses: ["launch", "storynomics"], editor: "a launch film: the viewer's trouble first, the product named, the product doing its job, a proof, how to start; the customer is the hero, the product the mentor",+ brief: "A 30-second launch film for Halden Outdoor's new one-pull tent, for people who've never camped because setting up a tent scares them." },+ { id: "coffee-brand", lenses: ["storynomics", "pas"], editor: "a brand film: the customer is the hero with a problem; the brand is the mentor; a problem made to hurt, then solved, with proof",+ brief: "A 45-second brand film for Northwind Coffee, a small roaster whose beans are roasted the day they ship. Audience: people who drink bad office coffee." },+ { id: "whodunit", lenses: ["mckee"], editor: "a mystery in McKee's terms: an inciting incident, complications that progress, a crisis with a real dilemma, a climax; fair play: the detective may act only on clues the audience was shown",+ brief: "A 3-minute whodunit short in a seaside hotel. Fair play: an attentive viewer can name the culprit before the detective does." },+ { id: "kishotenketsu", lenses: ["kishotenketsu"], editor: "kishotenketsu: introduction, development, a twist that is a new point of view rather than a conflict, a reconciliation; no villain, no fight",+ brief: "A 1-minute wordless story with no conflict and no villain: a quiet turn of perspective in a city apartment block." },+ { id: "lighthouse-long", lenses: ["mckee", "campbell"], editor: "a short film in McKee's and Campbell's terms: an ordinary world, a call, a threshold, an ordeal, a reward, a return; a want against a need; a dilemma late; every setup paid",+ brief: "A 15-minute short film told in about 40 shots: a lighthouse keeper's daughter must decide whether to leave the island when the light is automated." },+ { id: "liar-quest", lenses: ["propp", "campbell"], editor: "a game quest in Propp's and Campbell's terms: a lack, a dispatcher, a departure, a test, a helper or magical agent, a struggle, a return; setups paid; a betrayal set up before it lands",+ brief: "A side quest for a fantasy RPG, 8 to 12 beats, where the quest giver is lying to the player from the start." },+ { id: "tragedy", lenses: ["mckee"], editor: "a tragedy: the hero gets what they want and loses what they need; a negative arc that is chosen, not accidental; every big turn set up",+ brief: "A 2-minute story where an ambitious young chef gets the restaurant review she wanted and loses the thing that mattered more." },+ { id: "skincare-15", lenses: ["pas", "launch"], editor: "a 15-second ad: problem, agitate, solve, proof; the product shown working on the viewer's problem",+ brief: "A 15-second ad for Lumen Skincare's mineral sunscreen that leaves no white cast, for people with dark skin who've given up on sunscreen." },+];++const PLAIN = `You are a screenwriter. Write the piece the brief asks for as a beat script: one JSON object+{"title": string, "beats": [{"onScreen": string, "says": [{"who": string, "says": string}], "seconds": number}]}.+Each beat is a shot or a short run of shots. "onScreen" is one or two concrete sentences of what the viewer sees; "says" is+any spoken lines (who is a character's name, or "narrator"); "seconds" is how long the beat runs. onScreen and says are all+the viewer gets, so they carry the story alone. Answer with the JSON object only.`;++const EDIT = (p: Prompt) => `Now read your script as a hard story editor would, then rewrite it. Hold it to ${p.editor}. Check, beat by beat:+- does each beat happen because of what came before ("therefore") or turn it ("but"), never just "and then"?+- does every beat change something (a value moves, the audience learns something)?+- does any character act on something they couldn't know yet?+- is every big turn set up, and every setup paid off?+- is the hero's want or need settled by the end, and does the main value end somewhere different from where it began?+- is every claim backed by proof the viewer sees?+List what you find in a sentence each under "critique", then fix all of it. Answer with one JSON object:+{"critique": [string], "title": string, "beats": [...same shape as before]}.`;++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, arc}. 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. arc "negative" for a tragedy's hero.+- 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. "turns" moves values in whole steps from -3 to 3; 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 or an earlier one sets). "unsets" undoes a fact (a lie exposed).+- tellings: one telling named "main": the beats in the order the audience sees them. Each beat: {id, shows: [event keys], feel, reveals, hides, asks, setup, pays, onScreen, says, seconds, surprise, meant}. 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), "seconds", and usually "says": [{who, says}] (who is an agent key or "narrator"). onScreen and says are the only words a viewer gets, so they carry the story alone. surprise: "meant" on a beat whose shock is the point; meant: ["check"] on a beat where a finding is deliberate (a breather a journey wants).+- idea: {value, side, counter}: the value the story is about and what it argues.+- lenses: the framework names it's held to.+Facts are KEYS: believes, needs, sets, unsets, learns, proof, reveals, hides and asks hold fact keys you declared in "facts", never sentences. 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.+A checker reads it: every beat turns a value or reveals something; each beat follows from what was seen; a big turn (2 or more) is set up; every setup is paid; a want or need is settled; a claim has proof shown by then; the focus value moves; and each named lens finds its stages. Keys are short camelCase words. Use only the keys you declare.+One valid story, a 30-second launch film:+${JSON.stringify(toData(launch as AnyStory))}+Answer with the JSON object only.`;++const EXTRACT = `You read a script and record, as story data, ONLY what the script shows. Never add a cause, a setup, a fact or a+feeling the script doesn't show on screen or in its lines: if a beat happens with no shown reason, leave "because" out;+if nothing in a beat moves a value, give its event no turn. The format:+- values: what's at stake, each {neg, pos}. facts: named facts, each a sentence. agents: each {want, need, role} as far as the script shows.+- world: events in the order they happen in the story, each {who, with, does, because (an earlier event the script shows causing it), needs, sets, learns, turns (value: -3..3), ends ({agent: "want"|"need"}), claim, proof, routine}.+- tellings: {"main": one beat per numbered beat of the script, in order, each {shows: [event keys], reveals, asks, setup, pays}}: exactly as many beats as the script has.+Facts are keys. A character "needs" a fact only when the script shows them acting on it. Answer with the JSON object only.`;++const JUDGE = (brief: string, scripts: [string, string][]) => `${["", "One writer", "Two writers", "Three writers", "Four writers", "Five writers"][scripts.length]} answered the same brief. Read each script as the+viewer gets it, then rank them. The brief: ${brief}++${scripts.map(([l, s]) => `SCRIPT ${l}\n${s}`).join("\n\n")}++Score each from 1 to 10 on: cause (each beat follows from the last, no "and then"), setups (what's planted pays off;+nothing comes from nowhere), clarity (a viewer follows what happens from the screen and lines alone), brief (it does+what the brief asks, at its length), feeling (it moves the viewer), overall. Then rank all of them, best first.+Answer with one JSON object: {"scores": {"${scripts.map(([l]) => l).join('": {...}, "')}": {...}} with each {cause, setups, clarity, brief, feeling, overall},+"rank": [letters best first], "why": one or two sentences}.`;++// ---- the model ----+let spent = 0;+async function ask(model: string, messages: J[], o: { tokens?: number; reasoning?: J } = {}): Promise<{ text: string; usd: number; ms: number; finish?: string }> {+ const t = performance.now();+ for (let attempt = 0; attempt < 4; 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-ab" },+ body: JSON.stringify({ model, messages, temperature: 1, max_tokens: o.tokens ?? 40000, ...(o.reasoning ? { reasoning: o.reasoning } : {}), response_format: { type: "json_object" }, usage: { include: true } }),+ }).catch((e) => ({ status: 599, json: async () => ({ error: String(e) }), ok: false }) as unknown as Response);+ if (res.status === 429 || res.status >= 500) { await new Promise((r) => setTimeout(r, 3000 * (attempt + 1))); continue; }+ const j: J = await res.json();+ if (!res.ok) throw new Error(`${model} ${res.status} ${JSON.stringify(j).slice(0, 300)}`);+ const usd = j.usage?.cost ?? 0;+ spent += usd;+ return { text: j.choices?.[0]?.message?.content ?? "", usd, ms: performance.now() - t, finish: j.choices?.[0]?.finish_reason };+ }+ throw new Error(`${model} kept refusing`);+}+const parse = (t: string): J | null => { try { return JSON.parse(t.replace(/^\s*```(json)?/, "").replace(/```\s*$/, "").trim()); } catch { const m = t.match(/\{[\s\S]*\}/); try { return m ? JSON.parse(m[0]) : null; } catch { return null; } } };+const beatsOk = (j: J | null) => !!j && Array.isArray(j.beats) && j.beats.length > 0;+const script = (j: J) => `${j.title ?? ""}\n${scriptOf(j.beats)}`;+const seconds = (j: J) => j.beats.reduce((a: number, b: J) => a + (typeof b.seconds === "number" ? b.seconds : 0), 0);++// ---- the arms ----+type Arm = { arm: string; final: J | null; calls: number; usd: number; ms: number; log: J[] };+async function plain(p: Prompt): Promise<Arm> {+ const msgs = [{ role: "system", content: PLAIN }, { role: "user", content: p.brief }];+ const r = await ask(WRITER, msgs);+ return { arm: "A", final: parse(r.text), calls: 1, usd: r.usd, ms: r.ms, log: [{ text: r.text }] };+}+async function edited(p: Prompt, a: Arm): Promise<Arm> {+ if (!beatsOk(a.final)) return { arm: "C", final: null, calls: 0, usd: 0, ms: 0, log: [] };+ const msgs = [{ role: "system", content: PLAIN }, { role: "user", content: p.brief }, { role: "assistant", content: JSON.stringify(a.final) }, { role: "user", content: EDIT(p) }];+ const r = await ask(WRITER, msgs);+ const j = parse(r.text);+ return { arm: "C", final: j, calls: 2, usd: a.usd + r.usd, ms: a.ms + r.ms, log: [{ critique: j?.critique, finish: r.finish }] };+}+function findingsOf(j: J, lenses: string[]): { blocking: string[]; all: J[]; story: AnyStory | null } {+ const { story, errors } = fromData(j);+ if (!story) return { blocking: errors.map((e) => `${e.at}: ${e.says}`), all: [], story: null };+ const found = [...checkStory(story, "main"), ...readThrough(story, lenses.map((l) => LENSES[l]).filter(Boolean), "main").flatMap((r) => r.findings)];+ return { blocking: found.filter((f) => f.level !== "note").map((f) => `${f.level} ${f.check} at ${f.about}: ${f.says}${f.fix ? ` (fix: ${f.fix})` : ""}`), all: found, story };+}+async function sdk(p: Prompt): Promise<Arm> {+ const msgs: J[] = [{ role: "system", content: GUIDE }, { role: "user", content: `${p.brief}\nHold it to these lenses: ${p.lenses.join(", ")}.` }];+ let usd = 0, ms = 0, calls = 0, j: J | null = null;+ const log: J[] = [];+ for (let round = 0; round < 3; round++) {+ const r = await ask(WRITER, msgs);+ usd += r.usd; ms += r.ms; calls++;+ j = parse(r.text);+ if (!j) { log.push({ round, parse: "failed", finish: r.finish, chars: r.text.length }); msgs.push({ role: "assistant", content: r.text }, { role: "user", content: "That wasn't one JSON object. Answer with the whole story as one JSON object only." }); continue; }+ let f: ReturnType<typeof findingsOf>;+ try { f = findingsOf(j, p.lenses); }+ catch (e) { log.push({ round, crash: String((e as Error).stack).slice(0, 1200) }); writeFileSync(join(OUT, `crash-${p.id}-${Date.now()}.json`), JSON.stringify({ story: j, stack: String((e as Error).stack) })); break; }+ log.push({ round, blocking: f.blocking, notes: f.all.filter((x) => x.level === "note").length });+ if (!f.blocking.length || round === 2) break;+ msgs.push({ role: "assistant", content: r.text }, { role: "user", content: `The checker found:\n${f.blocking.map((x) => `- ${x}`).join("\n")}\nFix each one (or, where a finding is a choice you mean, mark the beat with meant: ["check"]) and answer with the whole corrected story as one JSON object.` });+ }+ let final: J | null = null;+ if (j) {+ const { story } = fromData(j);+ const tell: J[] = j.tellings?.main ?? [];+ const res = story ? resolved(story, 0) : null;+ final = { title: j.title, beats: tell.map((b) => ({ onScreen: b.onScreen ?? (b.shows ?? []).map((k: string) => res?.world?.[k]?.does ?? j.world?.[k]?.does).filter(Boolean).join(". "), says: b.says ?? [], seconds: b.seconds })), data: j };+ }+ return { arm: "B", final, calls, usd, ms, log };+}++/** A finding about an extracted story, said by the beat it's about (the script's numbering). */+function byBeat(data: J, f: J): string {+ const tell: J[] = data.tellings?.main ?? [];+ let k = tell.findIndex((b, i) => b.id === f.about || `b${i}` === f.about);+ if (k < 0) k = tell.findIndex((b) => (b.shows ?? []).includes(f.about));+ const where = k >= 0 ? `beat ${k + 1}` : data.agents?.[f.about] ? `${f.about}'s arc` : "the whole script";+ return `${where}: ${f.says}`;+}+async function checkedEdit(p: Prompt, a: Arm): Promise<Arm> {+ if (!beatsOk(a.final)) return { arm: "D", final: null, calls: 0, usd: 0, ms: 0, log: [] };+ const ex = await extract(script(a.final!));+ if (!ex.data) return { arm: "D", final: null, calls: 0, usd: a.usd, ms: a.ms, log: [{ extract: ex.errors }] };+ const { story } = fromData(ex.data);+ const lens = story ? readThrough(story, p.lenses.map((l) => LENSES[l]).filter(Boolean), "main").flatMap((r) => r.findings) : [];+ const found = [...(ex.checks ?? []), ...lens.map((f) => ({ check: f.check, level: f.level, about: f.about, says: f.says }))].filter((f) => f.level !== "note");+ if (!found.length) return { arm: "D", final: a.final, calls: 1, usd: a.usd, ms: a.ms, log: [{ found: [] }] };+ const list = [...new Set(found.map((f) => `- ${byBeat(ex.data!, f)}`))].join("\n");+ const msgs = [{ role: "system", content: PLAIN }, { role: "user", content: p.brief }, { role: "assistant", content: JSON.stringify(a.final) },+ { role: "user", content: `A story checker read your script back as story data, from the screen and the lines alone, and found:\n${list}\nEach is what a viewer can't see on screen: a beat with no shown reason, a turn nothing set up, a setup never paid, an arc never settled. Fix each one so the screen shows it (or leave it where it's a choice you mean), then rewrite. Answer with one JSON object {"title": string, "beats": [...same shape as before]}.` }];+ const r = await ask(WRITER, msgs);+ return { arm: "D", final: parse(r.text), calls: 2, usd: a.usd + r.usd + ex.usd, ms: a.ms + r.ms, log: [{ found: found.map((f) => `${f.level} ${f.check}`), finish: r.finish }] };+}+async function written(p: Prompt, b: Arm): Promise<Arm> {+ const data = b.final?.data;+ if (!data) return { arm: "E", final: null, calls: 0, usd: 0, ms: 0, log: [] };+ const { story } = fromData(data);+ if (!story) return { arm: "E", final: null, calls: 0, usd: b.usd, ms: b.ms, log: [{ refused: true }] };+ const msgs = [{ role: "system", content: PLAIN }, { role: "user", content: `${p.brief}\n\nThe story is already worked out and checked, as story lines (VALUE, FACT, AGENT, EVENT in story order with its causes, then the telling's BEATs in the order the viewer sees them, each with what it shows, reveals, plants and pays):\n\n${toLines(story)}\n\nWrite it as the beat script, as a screenwriter would: keep every event, cause, setup and payoff, and make what's on screen and what's said carry each one so a viewer gets it without the notes. Use as many beats as the film needs.` }];+ const r = await ask(WRITER, msgs);+ return { arm: "E", final: parse(r.text), calls: b.calls + 1, usd: b.usd + r.usd, ms: b.ms + r.ms, log: [{ finish: r.finish }] };+}++// ---- scoring ----+type Extracted = { checks: J[] | null; errors: string[]; usd: number; beats: number; data?: J };+async function extract(s: string): Promise<Extracted> {+ let usd = 0;+ const msgs: J[] = [{ role: "system", content: EXTRACT }, { role: "user", content: s }];+ for (let t = 0; t < 2; t++) {+ const r = await ask(EXTRACTOR, msgs, { tokens: 30000 });+ usd += r.usd;+ const j = parse(r.text);+ const d = j ? fromData(j) : { story: null, errors: [{ at: "", says: "not JSON" }] };+ if (d.story && !d.errors.length) {+ try { return { checks: checkStory(d.story, "main").map((f) => ({ check: f.check, level: f.level, about: f.about, says: f.says })), errors: [], usd, beats: (j!.tellings?.main ?? []).length, data: j! }; }+ catch (e) { writeFileSync(join(OUT, `crash-extract-${Date.now()}.json`), JSON.stringify({ story: j, stack: String((e as Error).stack) })); return { checks: null, errors: [`crash: ${(e as Error).message}`], usd, beats: 0 }; }+ }+ msgs.push({ role: "assistant", content: r.text }, { role: "user", content: `Fix these and answer with the whole JSON object:\n${d.errors.slice(0, 20).map((e) => `- ${e.at}: ${e.says}`).join("\n")}` });+ if (t === 1) return { checks: null, errors: d.errors.slice(0, 5).map((e) => `${e.at}: ${e.says}`), usd, beats: 0 };+ }+ return { checks: null, errors: ["unreachable"], usd, beats: 0 };+}++async function pool<T, R>(xs: T[], n: number, fn: (x: T) => Promise<R>): Promise<R[]> {+ const out: R[] = new Array(xs.length);+ let i = 0;+ await Promise.all(Array.from({ length: Math.min(n, xs.length) }, async () => { while (i < xs.length) { const k = i++; out[k] = await fn(xs[k]); } }));+ return out;+}++const prompts = PROMPTS.filter((p) => !ONLY.length || ONLY.includes(p.id));+const units = prompts.flatMap((p) => Array.from({ length: SAMPLES }, (_, s) => ({ p, s })));+const prior = new Map<string, J>();+if (REUSE) for (const l of readFileSync(join(REUSE, "rows.jsonl"), "utf8").split("\n").filter(Boolean)) { const r = JSON.parse(l); prior.set(`${r.id}#${r.sample}`, r); }+const reused = (id: string, s: number, arm: string): Arm | null => {+ const x = prior.get(`${id}#${s}`)?.arms?.find((y: J) => y.arm === arm);+ return x && beatsOk(x.final) ? { arm, final: x.final, calls: x.calls, usd: x.usd, ms: x.ms, log: [...x.log, { reused: REUSE }] } : null;+};+console.log(`ab: ${units.length} prompt samples x ${ARMS.join(",")}${REUSE ? ` (reusing ${REUSE})` : ""}, writer ${WRITER}, extractor ${EXTRACTOR}, judges ${JUDGES.join(" + ")} -> ${OUT}`);+const rowsPath = join(OUT, "rows.jsonl");++await pool(units, JOBS, async ({ p, s }) => {+ try {+ const [a, b] = await Promise.all([reused(p.id, s, "A") ?? plain(p), reused(p.id, s, "B") ?? sdk(p)]);+ const [c, d, e] = await Promise.all([+ ARMS.includes("C") ? reused(p.id, s, "C") ?? edited(p, a) : null,+ ARMS.includes("D") ? checkedEdit(p, a) : null,+ ARMS.includes("E") ? written(p, b) : null,+ ]);+ const arms = [a, c, b, d, e].filter((x): x is Arm => !!x && ARMS.includes(x.arm));+ const scored = await Promise.all(arms.map(async (x) => {+ if (!beatsOk(x.final)) return { ...x, script: null, extract: null };+ const sc = script(x.final!);+ return { ...x, script: sc, extract: await extract(sc) };+ }));+ const ready = scored.filter((x) => x.script);+ const r = rng(s * 7919 + p.id.length);+ const order = ready.map((x) => x.arm).sort(() => r() - 0.5);+ const letters = ["V", "W", "X", "Y", "Z"].slice(0, order.length);+ const key = Object.fromEntries(letters.map((l, i) => [l, order[i]]));+ const judged = await Promise.all(JUDGES.map(async (m) => {+ const res = await ask(m, [{ role: "user", content: JUDGE(p.brief, letters.map((l) => [l, ready.find((x) => x.arm === key[l])!.script!])) }], { tokens: 12000, reasoning: { max_tokens: 4000 } }).catch((e) => ({ text: "", usd: 0, ms: 0, err: String(e) }));+ const j = parse(res.text);+ const byArm = j?.scores ? Object.fromEntries(Object.entries(j.scores as J).map(([l, v]) => [key[l], v])) : null;+ return { judge: m, rank: (j?.rank ?? []).map((l: string) => key[l]), scores: byArm, why: j?.why, usd: res.usd };+ }));+ const row = { id: p.id, sample: s, brief: p.brief, lenses: p.lenses, key, arms: scored.map((x) => ({ arm: x.arm, calls: x.calls, usd: x.usd, ms: Math.round(x.ms), log: x.log, final: x.final, script: x.script, beats: x.final?.beats?.length ?? 0, seconds: x.final?.beats ? seconds(x.final) : 0, extract: x.extract ? { ...x.extract, data: undefined } : null })), judged };+ appendFileSync(rowsPath, JSON.stringify(row) + "\n");+ console.log(`${p.id}#${s} ${judged.map((j) => `${j.judge.split("/")[1]}: ${j.rank.join(">")}`).join(" ")} $${spent.toFixed(2)}`);+ } catch (e) {+ console.log(`${p.id}#${s} FAILED ${String((e as Error).stack).slice(0, 900)}`);+ appendFileSync(join(OUT, "failed.jsonl"), JSON.stringify({ id: p.id, sample: s, err: String(e) }) + "\n");+ }+});+writeFileSync(join(OUT, "spent.txt"), `${spent.toFixed(4)}\n`);+console.log(`done: $${spent.toFixed(2)} -> ${rowsPath}`);diff --git a/sdk/story/bench/edges.ts b/sdk/story/bench/edges.tsnew file mode 100644index 00000000..06c7fd9a--- /dev/null+++ b/sdk/story/bench/edges.ts@@ -0,0 +1,200 @@+// Edge cases for raea/story: broken, extreme and odd stories, each with what the SDK should do, run, and what it did.+// Not a test suite (a case can fail and the run goes on); the cases that hold become tests.+// bun bench/edges.ts [--json out.json]+import { writeFileSync } from "node:fs";+import {+ asker, checkStory, choose, compileScript, compileStorylets, dramaManager, fromData, fromLines, LENSES, mutants, readThrough,+ samples, stateAt, story, toInk, toLines, value, windowAt, type AnyStory,+} from "../src/index.ts";++type J = Record<string, any>;+type Result = { name: string; expect: string; got: string; ok: boolean | null; ms: number };+const out: Result[] = [];+const S = (j: J) => ({ ...j, kind: "story" }) as unknown as AnyStory;+const brief = (fs: { check: string; level: string; about: string }[]) => fs.filter((f) => f.level !== "note").map((f) => `${f.level}:${f.check}@${f.about}`).join(" ") || "clean";+function run(name: string, expect: string, fn: () => { got: string; ok: boolean | null }) {+ const t = performance.now();+ try { const r = fn(); out.push({ name, expect, ...r, ms: Math.round(performance.now() - t) }); }+ catch (e) { out.push({ name, expect, got: `CRASH ${String((e as Error).message ?? e).slice(0, 140)}`, ok: false, ms: Math.round(performance.now() - t) }); }+}+const base = { values: { v: value("low", "high") }, agents: { a: { want: "x", need: "y" } } };++// ---- shape edges ----+run("empty story", "no crash; says there's nothing", () => {+ const f = checkStory(S({ values: {}, agents: {}, world: {}, tellings: { t: [] } }), "t");+ return { got: brief(f), ok: true };+});+run("telling with zero beats, real world", "no crash", () => {+ const f = checkStory(S({ ...base, world: { e: { who: "a", does: "x", turns: { v: 1 } } }, tellings: { t: [] } }), "t");+ return { got: brief(f), ok: true };+});+run("all narration (every beat shows nothing)", "turns warnings, no crash", () => {+ const f = checkStory(S({ ...base, world: { e: { who: "a", does: "x" } }, tellings: { t: [{ shows: [] }, { shows: [] }] } }), "t");+ return { got: brief(f), ok: f.some((x) => x.check === "turns") };+});+run("fromData: beat shows an event that doesn't exist", "refused with where", () => {+ const r = fromData({ ...base, world: { e: { who: "a", does: "x" } }, tellings: { t: [{ shows: ["ghost"] }] } });+ return { got: r.errors.map((e) => `${e.at}: ${e.says}`).join("; "), ok: r.errors.some((e) => e.at.includes("shows")) };+});+run("bypassing fromData: beat shows a missing event", "a finding or a clear error, not a silent pass", () => {+ const f = checkStory(S({ ...base, world: { e: { who: "a", does: "x", turns: { v: 1 } } }, tellings: { t: [{ shows: ["ghost"] }] } }), "t");+ return { got: brief(f), ok: f.length > 0 };+});+run("cause cycle (a because b, b because a)", "fromData refuses (cause after effect)", () => {+ const r = fromData({ ...base, world: { a1: { who: "a", does: "x", because: "b1" }, b1: { who: "a", does: "y", because: "a1" } }, tellings: { t: [{ shows: ["a1", "b1"] }] } });+ return { got: r.errors.map((e) => e.says).join("; ") || "accepted", ok: r.errors.length > 0 };+});+run("self-cause (a because a)", "refused", () => {+ const r = fromData({ ...base, world: { a1: { who: "a", does: "x", because: "a1" } }, tellings: { t: [{ shows: ["a1"] }] } });+ return { got: r.errors.map((e) => e.says).join("; ") || "accepted", ok: r.errors.length > 0 };+});+run("bypassing fromData: cycle straight into checkStory", "no hang, no crash", () => {+ const f = checkStory(S({ ...base, world: { a1: { who: "a", does: "x", because: "b1", turns: { v: 1 } }, b1: { who: "a", does: "y", because: "a1", turns: { v: -1 } } }, tellings: { t: [{ shows: ["a1"] }, { shows: ["b1"] }] } }), "t");+ return { got: brief(f), ok: f.some((x) => x.check === "cause") };+});+run("turn out of range (+9)", "fromData refuses", () => {+ const r = fromData({ ...base, world: { e: { who: "a", does: "x", turns: { v: 9 } } }, tellings: { t: [{ shows: ["e"] }] } });+ return { got: r.errors.map((e) => e.says).join("; ") || "accepted", ok: r.errors.length > 0 };+});+run("duplicate beat ids", "flagged (raea check finds Sequences by id)", () => {+ const r = fromData({ ...base, world: { e: { who: "a", does: "x", turns: { v: 1 } }, f: { who: "a", does: "y", because: "e", turns: { v: 1 } } }, tellings: { t: [{ id: "x", shows: ["e"] }, { id: "x", shows: ["f"] }] } });+ const f = r.story ? checkStory(r.story, "t") : [];+ return { got: (r.errors.map((e) => e.says).join("; ") || "accepted") + " | " + brief(f), ok: r.errors.length > 0 || f.some((x) => x.about === "x") };+});+run("an agent named 'narrator'", "no confusion with the narrator", () => {+ const r = fromData({ values: base.values, agents: { narrator: {} }, world: { e: { who: "narrator", does: "x", turns: { v: 1 } } }, tellings: { t: [{ shows: ["e"], says: [{ who: "narrator", says: "hi" }] }] } });+ return { got: (r.errors.map((e) => e.says).join("; ") || "accepted") + " | " + (r.story ? brief(checkStory(r.story, "t")) : ""), ok: null };+});+run("unicode keys and Japanese text", "works; lines round-trip", () => {+ const j = { values: { 勇気: { neg: "怖い", pos: "勇敢" } }, agents: { 花子: {} }, world: { 登る: { who: "花子", does: "山に登る 🏔️ | 一人で", turns: { 勇気: 2 } } }, tellings: { t: [{ shows: ["登る"], onScreen: "雪の中\nもう一歩" }] } };+ const r = fromData(j), back = fromLines(toLines(r.story!));+ return { got: `${brief(checkStory(r.story!, "t"))} | roundtrip errors ${back.errors.length}, does="${(back.story as any)?.world?.["登る"]?.does}"`, ok: back.errors.length === 0 && (back.story as any).world["登る"].does === j.world["登る"].does };+});+run("negative seconds on a beat", "flagged", () => {+ const r = fromData({ ...base, world: { e: { who: "a", does: "x", turns: { v: 1 } } }, tellings: { t: [{ shows: ["e"], seconds: -3 }] } });+ return { got: r.errors.map((e) => e.says).join("; ") || "accepted", ok: r.errors.length > 0 };+});++// ---- story edges ----+const mystery = (learnsEarly: boolean) => S({+ values: { truth: value("hidden", "known") },+ facts: { poison: "the tea was poisoned" },+ agents: { det: { want: "the killer", need: "to trust a stranger" }, maid: {} },+ world: {+ pour: { who: "maid", does: "pours the tea", sets: ["poison"], turns: { truth: -1 } },+ ...(learnsEarly ? { smell: { who: "det", does: "smells bitter almonds", because: "pour", learns: ["poison"], turns: { truth: 1 } } } : {}),+ accuse: { who: "det", does: "accuses the maid of poisoning", because: learnsEarly ? "smell" : "pour", needs: ["poison"], turns: { truth: 2 } },+ },+ tellings: { t: [{ shows: ["pour"], hides: ["poison"], asks: ["poison"] }, ...(learnsEarly ? [{ shows: ["smell"] }] : []), { shows: ["accuse"], reveals: ["poison"] }] },+});+run("mystery: detective acts on what he can't know", "belief error", () => { const f = checkStory(mystery(false), "t"); return { got: brief(f), ok: f.some((x) => x.check === "belief") }; });+run("mystery: fair-play clue added", "belief error gone", () => { const f = checkStory(mystery(true), "t"); return { got: brief(f), ok: !f.some((x) => x.check === "belief") }; });++const twoCuts = S({+ ...base,+ world: {+ work: { who: "a", does: "works late again", routine: true, turns: { v: -1 } },+ quit: { who: "a", does: "quits", because: "work", turns: { v: 2 }, ends: { a: "want" } },+ open: { who: "a", does: "opens a bakery", because: "quit", turns: { v: 2 }, ends: { a: "need" } },+ },+ tellings: { long: [{ id: "w", shows: ["work"] }, { id: "q", shows: ["quit"] }, { id: "o", shows: ["open"] }], short: [{ id: "w", shows: ["work"] }] },+});+run("two cuts of one world: a cut that stops early", "the short cut's unsettled arc shows only in it", () => {+ const L = checkStory(twoCuts, "long"), Sh = checkStory(twoCuts, "short");+ return { got: `long: ${brief(L)} || short: ${brief(Sh)}`, ok: brief(L) !== brief(Sh) };+});+run("flashback: show the ending first as a hook", "passes when the ending's fact is hidden and paid", () => {+ const s = S({ ...base, facts: { done: "the bakery is open" }, world: { ...twoCuts.world, open: { ...twoCuts.world.open, sets: ["done"] } },+ tellings: { t: [{ id: "hook", shows: ["open"], hides: ["done"], asks: ["done"], setup: "how" }, { id: "w", shows: ["work"] }, { id: "q", shows: ["quit"] }, { id: "o", shows: ["open"], reveals: ["done"], pays: "how" }] } });+ const f = checkStory(s, "t");+ return { got: brief(f), ok: !f.some((x) => x.level === "error") };+});+run("tragedy: negative arc, need never met", "no arc error for a meant negative arc", () => {+ const s = S({ values: { hope: value("despair", "hope") }, agents: { k: { want: "the crown", need: "to let go", arc: "negative" } },+ world: { take: { who: "k", does: "takes the crown", turns: { hope: 1 }, ends: { k: "want" } }, lose: { who: "k", does: "loses everyone", because: "take", turns: { hope: -3 } } },+ tellings: { t: [{ shows: ["take"] }, { shows: ["lose"] }] } });+ const f = checkStory(s, "t");+ return { got: brief(f), ok: !f.some((x) => x.check === "arc" && x.level !== "note") };+});+run("kishotenketsu: no conflict, a turn of view", "kishotenketsu passes; mckee may complain", () => {+ const s = S({ values: { view: value("ordinary", "wonder") }, agents: { girl: {}, old: {} },+ world: { ki: { who: "girl", does: "waters a plant on a balcony", routine: true }, sho: { who: "girl", does: "waters it every day as it grows", because: "ki", turns: { view: 1 } },+ ten: { who: "old", does: "across the street, an old man has drawn the plant every day for a year", turns: { view: 2 } }, ketsu: { who: "girl", does: "waves; he holds up the drawings", because: "ten", turns: { view: 1 } } },+ tellings: { t: [{ shows: ["ki"] }, { shows: ["sho"] }, { shows: ["ten"], surprise: "meant" }, { shows: ["ketsu"] }] } });+ const r = readThrough(s, [LENSES.kishotenketsu, LENSES.mckee], "t");+ return { got: r.map((x) => `${x.lens}:${x.passes ? "pass" : "FAIL"} ${brief(x.findings)}`).join(" || "), ok: r[0].passes };+});+run("claim before its proof", "claim error", () => {+ const s = S({ ...base, facts: { fast: "it ships in a day" }, agents: { a: {}, brand: { role: "brand" } },+ world: { claim: { who: "brand", does: "says it ships in a day", claim: "ships in a day", proof: ["fast"], turns: { v: 1 } }, ship: { who: "brand", does: "ships the order in a day", because: "claim", sets: ["fast"], turns: { v: 1 } } },+ tellings: { t: [{ shows: ["claim"] }, { shows: ["ship"] }] } });+ const f = checkStory(s, "t");+ return { got: brief(f), ok: f.some((x) => x.check === "claim") };+});+run("unreliable narrator: the audience is told something false, then it's undone", "a way to say it (unsets)", () => {+ const s = S({ values: { trust: value("doubt", "trust") }, facts: { alibi: "he was home all night" }, agents: { him: {} },+ world: { claims: { who: "him", does: "says he was home", sets: ["alibi"], turns: { trust: 1 } }, cam: { who: "him", does: "a camera shows him leaving at midnight", because: "claims", unsets: ["alibi"], turns: { trust: -3 } } },+ tellings: { t: [{ shows: ["claims"] }, { shows: ["cam"] }] } });+ const st = stateAt(s, "t", 2);+ return { got: `${brief(checkStory(s, "t"))} | audience knows at the end: [${st.knows}]`, ok: !st.knows.includes("alibi") };+});+run("surprise not meant vs meant", "warn, then nothing", () => {+ const mk = (meant: boolean) => S({ ...base, world: { a1: { who: "a", does: "x", turns: { v: 1 } }, hidden: { who: "a", does: "unseen" }, z: { who: "a", does: "a meteor", because: "hidden", turns: { v: -3 } } },+ tellings: { t: [{ shows: ["a1"] }, { shows: ["z"], ...(meant ? { surprise: "meant" } : {}) }] } });+ return { got: `${brief(checkStory(mk(false), "t"))} || ${brief(checkStory(mk(true), "t"))}`, ok: null };+});++// ---- generation edges ----+run("choice points: 20 seeds", "several distinct stories, the failing ones refused", () => {+ const s = story({+ values: { v: value("low", "high") },+ agents: { a: { want: choose(["the job", "the girl", "the boat"]), need: "y" } },+ world: { e: { who: "a", does: choose(["runs", "hides", "lies"]), turns: { v: choose([-2, 1, 2]) } }, f: { who: "a", does: "comes back", because: "e", turns: { v: 2 } } },+ tellings: { t: [{ shows: ["e"] }, choose([{ shows: ["f"] }, null])] },+ } as any);+ const xs = samples(s, 20, { telling: "t" });+ const distinct = new Set(xs.map((x) => JSON.stringify(x.story))).size;+ return { got: `${xs.length} sampled, ${distinct} distinct, ${xs.filter((x) => x.passes).length} pass`, ok: distinct > 1 };+});+run("mutants of the mystery", "every mutant is a story the checks can read", () => {+ const ms = mutants(mystery(true), "t");+ let found = 0, crash = 0;+ for (const m of ms) { try { if (checkStory(m.story, m.telling).length) found++; } catch { crash++; } }+ return { got: `${ms.length} mutants (${[...new Set(ms.map((m) => m.label.kind))].join(",")}), ${found} raise a finding, ${crash} crash`, ok: crash === 0 };+});+run("compile a branching story to a game", "storylets, a drama-manager path, ink", () => {+ const sl = compileStorylets(twoCuts);+ const path = dramaManager(sl, [0.2, 0.5, 0.9], 1);+ const ink = toInk(twoCuts, "long");+ const sc = compileScript(twoCuts, "long");+ return { got: `${sl.length} storylets, path ${path.join(">")}, ink ${ink.split("\n").length} lines, script ${sc.beats.length} beats`, ok: sl.length === 3 && ink.length > 0 };+});++// ---- scale ----+function big(n: number, beatsPer: number): AnyStory {+ const world: J = {}, tell: J[] = [];+ for (let i = 0; i < n; i++) world[`e${i}`] = { who: i % 2 ? "a" : "b", does: `step ${i}`, ...(i ? { because: `e${i - 1}` } : {}), turns: { v: i % 3 === 0 ? -1 : 1 } };+ for (let i = 0; i < n; i++) for (let k = 0; k < beatsPer; k++) tell.push({ id: `s${i}_${k}`, shows: [`e${i}`], scene: `sc${Math.floor(i / 10)}` });+ return S({ values: base.values, agents: { a: {}, b: {} }, world, tellings: { t: tell } });+}+for (const [n, per] of [[200, 1], [500, 4], [2000, 1]] as const) {+ run(`scale: ${n} events, ${n * per} beats`, "checks, lenses, a window and lines in seconds", () => {+ const s = big(n, per);+ const t0 = performance.now(); const f = checkStory(s, "t"); const t1 = performance.now();+ readThrough(s, [LENSES.mckee], "t"); const t2 = performance.now();+ const w = windowAt(s, "t", Math.floor((n * per) / 2)); const t3 = performance.now();+ const l = toLines(s); const t4 = performance.now();+ return { got: `checks ${(t1 - t0).toFixed(0)} ms (${f.length} findings), mckee ${(t2 - t1).toFixed(0)} ms, window ${(t3 - t2).toFixed(0)} ms (${w.length} chars), lines ${(t4 - t3).toFixed(0)} ms`, ok: t4 - t0 < 30000 };+ });+}+run("questions on a 2,000-beat telling", "a beat's questions without reading the whole telling each time", () => {+ const s = big(2000, 1);+ const t0 = performance.now(); const ask = asker(s, "t"); const t1 = performance.now(); const q = ask(1000, "lines"); const t2 = performance.now();+ return { got: `setup ${(t1 - t0).toFixed(0)} ms, one beat ${(t2 - t1).toFixed(0)} ms, ${Object.keys(q.questions).length} questions, state ${q.state.length} chars`, ok: t2 - t1 < 2000 };+});++const pad = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s.padEnd(n));+for (const r of out) console.log(`${r.ok === true ? "ok " : r.ok === false ? "FAIL" : " ? "} ${pad(r.name, 52)} ${String(r.ms).padStart(6)} ms ${r.got.slice(0, 260)}`);+console.log(`\n${out.filter((r) => r.ok === true).length} ok, ${out.filter((r) => r.ok === false).length} fail, ${out.filter((r) => r.ok === null).length} to read`);+const j = process.argv.indexOf("--json");+if (j > 0) writeFileSync(process.argv[j + 1], JSON.stringify(out, null, 1));diff --git a/sdk/story/bench/fuzz.ts b/sdk/story/bench/fuzz.tsnew file mode 100644index 00000000..e1e11b0c--- /dev/null+++ b/sdk/story/bench/fuzz.ts@@ -0,0 +1,62 @@+// Fuzz the contract "anything fromData accepts, every reader can read": take valid stories, put a wrong-typed value in+// one field at a time, and run every reader on what fromData lets through. A crash is a hole in fromData or a reader.+// bun bench/fuzz.ts [N]+import { asker, checkStory, compileScript, fromData, LENSES, readThrough, rng, toData, toLines, windowAt, type AnyStory } from "../src/index.ts";+import { launch } from "../test/fixture.ts";++type J = Record<string, any>;+const N = Number(process.argv[2] ?? 3000);+const seeds: J[] = [toData(launch as AnyStory) as J];+const WEIRD: unknown[] = [{}, [], "", 0, 5, null, true, "x", [{}], [null], { a: 1 }, -1, 1.5, ["nope"]];+const r = rng(7);+const paths = (o: unknown, at: (string | number)[] = []): (string | number)[][] =>+ o && typeof o === "object" ? [at, ...Object.entries(o).flatMap(([k, v]) => paths(v, [...at, Array.isArray(o) ? Number(k) : k]))] : [at];+const crashes = new Map<string, { path: string; value: string; reader: string; n: number }>();+let accepted = 0;+for (let i = 0; i < N; i++) {+ const d = structuredClone(seeds[0]);+ // half the time an existing field, half a field the story could have but doesn't (every optional field gets a turn)+ const EV = ["who", "with", "does", "because", "needs", "sets", "unsets", "learns", "turns", "ends", "dilemma", "claim", "proof", "routine", "surprise"];+ const BEAT = ["id", "shows", "reveals", "hides", "asks", "feel", "setup", "pays", "stage", "surprise", "meant", "says", "onScreen", "seconds", "scene"];+ const AG = ["want", "need", "lie", "mask", "role", "believes", "arc"];+ const TOP = ["idea", "facts", "lenses", "title", "premise"];+ const pick = <T,>(xs: T[]) => xs[Math.floor(r() * xs.length)];+ const ps = paths(d).filter((p) => p.length > 0);+ const t0 = Object.keys(d.tellings)[0];+ const p = r() < 0.5 ? ps[Math.floor(r() * ps.length)]+ : pick([+ () => ["world", pick(Object.keys(d.world)), pick(EV)],+ () => ["tellings", t0, Math.floor(r() * d.tellings[t0].length), pick(BEAT)],+ () => ["tellings", t0, Math.floor(r() * d.tellings[t0].length), "says", 0, pick(["who", "says", "means", "how"])],+ () => ["agents", pick(Object.keys(d.agents)), pick(AG)],+ () => [pick(TOP)],+ () => ["idea", pick(["value", "side", "counter"])],+ ])();+ if (p[p.length - 2] === 0 && p[p.length - 3] === "says") { let o: any = d; for (const k of p.slice(0, -3)) o = o[k]; o.says ??= [{ who: "narrator", says: "hi" }]; }+ const v = WEIRD[Math.floor(r() * WEIRD.length)];+ let o: any = d;+ for (const k of p.slice(0, -1)) o = o[k];+ o[p[p.length - 1]] = structuredClone(v);+ const { story, errors } = fromData(d);+ if (!story || errors.length) continue;+ accepted++;+ const t = Object.keys((story as J).tellings)[0];+ const readers: [string, () => unknown][] = [+ ["checkStory", () => checkStory(story, t)],+ ["lenses", () => readThrough(story, Object.values(LENSES), t)],+ ["toLines", () => toLines(story)],+ ["windowAt", () => windowAt(story, t, 1)],+ ["asker", () => asker(story, t)(0)],+ ["compileScript", () => compileScript(story, t)],+ ];+ for (const [name, fn] of readers) {+ try { fn(); } catch (e) {+ const where = p.map((k) => (typeof k === "number" ? "[]" : k)).join(".").replace(/world\.\w+/, "world.E").replace(/agents\.\w+/, "agents.A").replace(/tellings\.\w+/, "tellings.T");+ const key = `${where} = ${JSON.stringify(v)} | ${name} | ${String((e as Error).message).slice(0, 60)}`;+ const c = crashes.get(key);+ if (c) c.n++; else crashes.set(key, { path: where, value: JSON.stringify(v), reader: name, n: 1 });+ }+ }+}+console.log(`${N} mutations, ${accepted} accepted by fromData, ${crashes.size} distinct crashes`);+for (const k of [...crashes.keys()].sort()) console.log(` ${k} (x${crashes.get(k)!.n})`);diff --git a/sdk/story/src/checks.ts b/sdk/story/src/checks.tsindex d9ab8b6a..36bb8d67 100644--- a/sdk/story/src/checks.ts+++ b/sdk/story/src/checks.ts@@ -74,7 +74,11 @@ export function checkWorld(w: World): Finding[] {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 ids = new Map<string, number>();+ for (const { beat } of beats) if (beat.id !== undefined) ids.set(beat.id, (ids.get(beat.id) ?? 0) + 1);+ for (const [id, n] of ids) if (n > 1) add("id", "error", id, `${n} beats share the id "${id}", so a composition can't name its Sequence`, "give each beat its own id");const shown = new Set(beats.flatMap((b) => b.beat.shows));+ if (beats.length && !shown.size) add("turns", "warn", "story", "no beat shows an event: the telling is all narration", "show the events the beats are about");for (const [a, ent] of Object.entries(keysOf(w).agents)) {const ag = w.must<RAgent>(ent, "Agent");if (!ag.want && !ag.need) continue;@@ -90,6 +94,7 @@ export function checkWorld(w: World): Finding[] {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");}+ for (const f of x.ev.unsets ?? []) set.delete(f);}const focus = infoOf(w).idea?.value;diff --git a/sdk/story/src/data.ts b/sdk/story/src/data.tsindex dd221ffc..c39e091e 100644--- a/sdk/story/src/data.ts+++ b/sdk/story/src/data.ts@@ -46,7 +46,7 @@ export function beatShape(k: { events?: string[]; facts?: string[]; agents?: strmeant: oneOrMany(str),says: listOf({ type: "object", additionalProperties: false, required: ["who", "says"], properties: { who, says: str, means: str, how: str } }),onScreen: str,- seconds: { type: "number" },+ seconds: { type: "number", minimum: 0 },scene: str,},};@@ -102,6 +102,42 @@ export function storySchema(): Json {};}+/**+ * Where a value doesn't fit a schema, as errors: the few JSON Schema words storySchema() uses (type, enum, anyOf,+ * properties, required, additionalProperties, items, minimum, maximum). The one schema that tells a model a story's+ * shape is the one that holds the story to it, so a field of the wrong type never reaches a reader.+ */+export function shapeErrors(x: unknown, schema: Json, at = ""): DataError[] {+ const out: DataError[] = [];+ const here = at || "the story";+ const kind = (v: unknown) => (v === null ? "null" : Array.isArray(v) ? "a list" : typeof v === "object" ? "an object" : typeof v === "string" ? "text" : typeof v);+ if (schema.anyOf) {+ const tries = (schema.anyOf as Json[]).map((s2) => shapeErrors(x, s2, at));+ return tries.some((t) => !t.length) ? [] : tries.sort((p, q) => p.length - q.length)[0];+ }+ const t = schema.type as string | undefined;+ const fits = t === undefined || (t === "object" ? !!x && typeof x === "object" && !Array.isArray(x) : t === "array" ? Array.isArray(x) : t === "integer" ? Number.isInteger(x) : t === "number" ? typeof x === "number" && Number.isFinite(x) : typeof x === t);+ if (!fits) return [{ at: here, says: `expected ${t === "array" ? "a list" : t === "object" ? "an object" : t === "string" ? "text" : t === "integer" ? "a whole number" : t === "boolean" ? "true or false" : `a ${t}`}, got ${kind(x)}${typeof x === "string" || typeof x === "number" ? ` (${JSON.stringify(x).slice(0, 30)})` : ""}` }];+ if (schema.enum && !(schema.enum as unknown[]).includes(x)) out.push({ at: here, says: `${JSON.stringify(x)} isn't one of ${(schema.enum as unknown[]).map((e) => JSON.stringify(e)).join(", ")}` });+ if (typeof x === "number") {+ if (typeof schema.minimum === "number" && x < schema.minimum) out.push({ at: here, says: `${x} is under ${schema.minimum}` });+ if (typeof schema.maximum === "number" && x > schema.maximum) out.push({ at: here, says: `${x} is over ${schema.maximum}` });+ }+ if (t === "array" && schema.items) (x as unknown[]).forEach((v, i) => out.push(...shapeErrors(v, schema.items as Json, `${at}[${i}]`)));+ if (t === "object") {+ const o = x as Json, props = (schema.properties ?? {}) as Record<string, Json>;+ for (const r of (schema.required ?? []) as string[]) if (o[r] === undefined) out.push({ at: here, says: `needs ${r}` });+ for (const [k, v] of Object.entries(o)) {+ if (v === undefined) continue;+ const sub = props[k] ?? (typeof schema.additionalProperties === "object" ? (schema.additionalProperties as Json) : undefined);+ const path = at ? `${at}.${k}` : k;+ if (sub) out.push(...shapeErrors(v, sub, path));+ else if (schema.additionalProperties === false) out.push({ at: path, says: `isn't a field here (${Object.keys(props).join(", ")})` });+ }+ }+ return out;+}+/** 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[] = [];@@ -110,6 +146,10 @@ export function fromData(j: unknown): { story: AnyStory | null; errors: DataErroconst 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 };+ // the shape first: a field of the wrong type is refused here, before any reader trips on it+ errors.push(...shapeErrors(s, storySchema()));+ if (!Object.keys(s.tellings as Json).length) err("tellings", "a story needs at least one telling");+ 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)}`);@@ -134,9 +174,12 @@ export function fromData(j: unknown): { story: AnyStory | null; errors: DataErro}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; }+ const ids = new Set<string>();beats.forEach((b: Json, i) => {const at = `tellings.${t}[${i}]`;if (!b || typeof b !== "object") return err(at, "a beat is an object");+ if (typeof b.id === "string") { if (ids.has(b.id)) err(`${at}.id`, `another beat in ${t} is already "${b.id}"`); ids.add(b.id); }+ if (b.seconds !== undefined && (typeof b.seconds !== "number" || !(b.seconds >= 0))) err(`${at}.seconds`, "seconds is a length, 0 or more");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]);diff --git a/sdk/story/src/index.ts b/sdk/story/src/index.tsindex 456803e3..522cfbd1 100644--- a/sdk/story/src/index.ts+++ b/sdk/story/src/index.ts@@ -15,7 +15,7 @@ export { LENSES, LAUNCH_PRIORS, bernays, campbell, harmon, kishotenketsu, launchexport { 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";+export { toData, fromData, shapeErrors, storySchema, beatSchema, beatShape, keysIn, type DataError } from "./data.ts";export { toLines, fromLines, scriptOf } from "./lines.ts";export { stateAt, stateIn, stateLines, windowAt, type State } from "./state.ts";export { asker, questionsAt, findingsByBeat, CHECK_QUESTIONS, type Question, type Answer, type Asked, type AskOptions } from "./questions.ts";diff --git a/sdk/story/src/questions.ts b/sdk/story/src/questions.tsindex 48b9468b..88ee5f97 100644--- a/sdk/story/src/questions.ts+++ b/sdk/story/src/questions.ts@@ -86,6 +86,7 @@ export function asker(s: AnyStory | Record<string, any>, telling: string, o: Askconst events = eventsOf(w).sort((a, b) => a.order - b.order);return (k: number, as: "lines" | "script" = o.as ?? "lines"): Asked => {+ if (!Number.isInteger(k) || k < 0 || k >= beats.length) throw new RangeError(`no beat ${k + 1} in telling "${telling}": it has ${beats.length}`);const before = o.before ?? 3, after = o.after ?? 2;const from = Math.max(0, k - before), near = raw.slice(from, k + after + 1);const st = stateIn(w, k);diff --git a/sdk/story/src/systems/know.ts b/sdk/story/src/systems/know.tsindex 21a28e51..ed28353c 100644--- a/sdk/story/src/systems/know.ts+++ b/sdk/story/src/systems/know.ts@@ -26,6 +26,7 @@ export function knowledge(w: World): void {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);+ for (const who of [ev.who, ...(ev.with ?? [])]) for (const f of ev.unsets ?? []) known[who]?.delete(f);w.insert(e, "KnowsBefore", knowsBefore[key]);}w.setResource<Break[]>("BeliefBreaks", breaks);@@ -39,6 +40,8 @@ export function knowledge(w: World): void {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);+ // an event the audience sees undo a fact takes it back (a lie exposed, an alibi broken), unless the beat hides that+ for (const s of beat.shows) for (const f of byKey[s]?.ev.unsets ?? []) if (!(beat.hides ?? []).includes(f)) audience.delete(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);diff --git a/sdk/story/test/checks.test.ts b/sdk/story/test/checks.test.tsindex f7967920..9aff3b64 100644--- a/sdk/story/test/checks.test.ts+++ b/sdk/story/test/checks.test.ts@@ -1,5 +1,5 @@import { expect, test } from "bun:test";-import { analyze, checkStory, type Curve, type Audience, beatsOf } from "../src/index.ts";+import { analyze, asker, checkStory, stateAt, type Curve, type Audience, beatsOf } from "../src/index.ts";import { launch } from "./fixture.ts";test("the launch story passes every exact check", () => {@@ -22,3 +22,27 @@ 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);});++const tiny = (world: Record<string, any>, beats: any[], extra: Record<string, any> = {}) =>+ ({ kind: "story", values: { v: { neg: "low", pos: "high" } }, agents: { a: {} }, world, tellings: { t: beats }, ...extra }) as any;++test("an event that unsets a fact takes it back from the audience and from a claim (bench/edges.ts)", () => {+ const s = tiny(+ { says: { who: "a", does: "says he was home", sets: ["alibi"], turns: { v: 1 } }, cam: { who: "a", does: "a camera shows him leaving", because: "says", unsets: ["alibi"], turns: { v: -2 } },+ claim: { who: "a", does: "swears to it again", because: "cam", claim: "he was home", proof: ["alibi"], turns: { v: 1 } } },+ [{ shows: ["says"] }, { shows: ["cam"] }, { shows: ["claim"] }],+ { facts: { alibi: "he was home all night" } },+ );+ expect(stateAt(s, "t", 2).knows).not.toContain("alibi");+ expect(checkStory(s, "t").some((f) => f.check === "claim" && f.about === "claim")).toBe(true);+});++test("two beats sharing an id, and a telling that shows nothing, are findings", () => {+ const e = { x: { who: "a", does: "x", turns: { v: 1 } }, y: { who: "a", does: "y", because: "x", turns: { v: 1 } } };+ expect(checkStory(tiny(e, [{ id: "k", shows: ["x"] }, { id: "k", shows: ["y"] }]), "t").some((f) => f.check === "id" && f.level === "error")).toBe(true);+ expect(checkStory(tiny(e, [{ shows: [] }, { shows: [] }]), "t").some((f) => f.check === "turns" && f.about === "story")).toBe(true);+});++test("asking about a beat the telling doesn't have says so", () => {+ expect(() => asker(tiny({ x: { who: "a", does: "x" } }, []), "t")(0)).toThrow(/no beat 1/);+});diff --git a/sdk/story/test/data.test.ts b/sdk/story/test/data.test.tsindex 67783344..e374b299 100644--- a/sdk/story/test/data.test.ts+++ b/sdk/story/test/data.test.ts@@ -23,3 +23,26 @@ test("a beat's schema holds the story's own keys", () => {expect(s.properties.shows.items.enum).toEqual(["week", "doubles", "tries", "ships"]);expect(s.properties.pays.anyOf[0].enum).toEqual(["how"]);});++test("fromData refuses a field of the wrong type before any reader sees it (bench/fuzz.ts)", () => {+ const bad = (f: (j: any) => void) => { const j = toData(launch) as any; f(j); return fromData(j); };+ for (const [what, f] of [+ ["an agent that isn't an object", (j: any) => { j.agents.maya = null; }],+ ["a value with no poles", (j: any) => { j.values.freedom = null; }],+ ["a dilemma as text", (j: any) => { j.world.week.dilemma = "stay or go"; }],+ ["a beat id that isn't text", (j: any) => { j.tellings["30s"][0].id = 3; }],+ ["turns written on a beat", (j: any) => { j.tellings["30s"][0].turns = { freedom: 1 }; }],+ ["negative seconds", (j: any) => { j.tellings["30s"][0].seconds = -2; }],+ ["no telling", (j: any) => { j.tellings = {}; }],+ ] as const) {+ const r = bad(f);+ expect(r.errors.length, what).toBeGreaterThan(0);+ expect(r.story, what).toBeNull();+ }+});++test("fromData refuses two beats with one id in a telling", () => {+ const j = toData(launch) as any;+ j.tellings["30s"][1].id = j.tellings["30s"][0].id = "same";+ expect(fromData(j).errors.map((e) => e.at)).toContain("tellings.30s[1].id");+});diff --git a/sdk/story/test/lines.test.ts b/sdk/story/test/lines.test.tsindex 358097db..d94d36ff 100644--- a/sdk/story/test/lines.test.ts+++ b/sdk/story/test/lines.test.ts@@ -36,7 +36,7 @@ test("the launch story reads back from its lines exactly", () => {test("a broken line says where", () => {const { errors } = fromLines("VALUE v: low / high\nEVENT a: no arrow here\nBEAT b0: shows a");- expect(errors.map((e) => e.at)).toEqual(["line 2", "line 3"]);+ expect(errors.map((e) => e.at)).toEqual(["line 2", "line 3", "tellings"]);});const corpus = `${homedir()}/.vd/story/stories.jsonl`;