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
ST3b: field-tested on a 55-shot film. A beat's stage label pins its lens's stage before the lens reads (and any lens's inciting or climax label pins the anchors every lens reads); stages nobody labelled are held between the labelled ones; the inciting incident is the first shown, non-routine event that changes anything; the crisis is the last dilemma after it; a refusal can be a dilemma; shots that continue the beat before's event count its turn once (no false rhythm or no-turn findings); McKee doesn't call danger rising on another value easing off; resolution events aren't dead ends. ST6b: speech-only extractor rows, scored apart; ONNX int4 export and prediction under the same schema.
shinyobjectzcaabca1d90be
diff --git a/sdk/story/models/rows.ts b/sdk/story/models/rows.tsindex f2be8bb9..54649352 100644--- a/sdk/story/models/rows.ts+++ b/sdk/story/models/rows.ts@@ -64,7 +64,10 @@ for (const { i, s } of stories) {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)) });+ push("extract", sp, { i, kind: "script", prompt: p, answer: JSON.stringify(bare(s)) });+ // a transcript has the words alone: the same story from its lines, as a launch film's speech reads+ const spoken = beats.flatMap((b) => (b.says ?? []).map((l: J) => `${name(l.who)}: ${l.says}`));+ if (spoken.length >= 2) push("extract", sp, { i, kind: "lines", prompt: spoken.join("\n"), 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);diff --git a/sdk/story/models/score.ts b/sdk/story/models/score.tsindex 5bf90a9f..f96e57bb 100644--- a/sdk/story/models/score.ts+++ b/sdk/story/models/score.ts@@ -75,8 +75,13 @@ function scoreCritic(row: J, pred: J | null): J {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 who0 = f.slice(5, -(`-${SPLIT}.jsonl`.length));+ const all = read(join(ROWS, TASK, f));+ // the extractor's scripts and its transcripts (lines only) are scored apart+ const kinds = TASK === "extract" ? [...new Set(all.map((p) => p.kind ?? "script"))] : [undefined];+ for (const kind of kinds) {+ const who = kind ? `${who0}/${kind}` : who0;+ const preds = kind ? all.filter((p) => (p.kind ?? "script") === kind) : all;const per: J[] = [];for (const p of preds) {const row = byKey.get(p.key);@@ -97,6 +102,7 @@ for (const f of files) {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)))];diff --git a/sdk/story/models/story_models.py b/sdk/story/models/story_models.pyindex 5d7bf0d5..c1938517 100644--- a/sdk/story/models/story_models.py+++ b/sdk/story/models/story_models.py@@ -5,6 +5,8 @@ The generator's schema is the story's own (data.ts beatSchema): it can't name anpython 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]+ python story_models.py export TASK --adapter DIR (LoRA fused, then ONNX int4 for ort: DIR/onnx)+ python story_models.py onnx TASK --split test --adapter DIR (predictions from the ONNX model, under the schema)Predictions go to ROWS/TASK/pred-<who>-<split>.jsonl; models/score.ts scores them with raea/story's exact checks."""@@ -265,9 +267,57 @@ def frontier(a):print(f"frontier {a.model}: {len(todo)} rows, ${spent:.3f} -> {out}", flush=True)+def export(a):+ import shutil+ import subprocess++ ad = Path(os.path.expanduser(a.adapter))+ fused, out = ad / "fused", ad / "onnx"+ py = sys.executable+ subprocess.run([py, "-m", "mlx_lm", "fuse", "--model", a.base, "--adapter-path", str(ad), "--save-path", str(fused), "--dequantize"], check=True, capture_output=True)+ subprocess.run([py, "-m", "onnxruntime_genai.models.builder", "-m", str(fused), "-o", str(out), "-p", "int4", "-e", "cpu"], check=True, capture_output=True)+ shutil.rmtree(fused) # the fused weights are 1.2 GB and rebuilt from the adapter in seconds+ size = sum(f.stat().st_size for f in out.iterdir())+ print(f"exported {a.task} -> {out} ({size / 1e6:.0f} MB, int4, CPU)", flush=True)+++def onnx_predict(a):+ import onnxruntime_genai as og+ from transformers import AutoTokenizer++ 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]+ d = Path(os.path.expanduser(a.adapter)) / "onnx"+ tok = AutoTokenizer.from_pretrained(str(d))+ model = og.Model(str(d))+ otok = og.Tokenizer(model)+ out = rd / a.task / f"pred-{Path(a.adapter).name}-onnx-{a.split}.jsonl"+ done = {json.loads(l)["key"] for l in open(out)} if out.exists() else set()+ 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+ p = tok.apply_chat_template([{"role": "system", "content": SYSTEM[a.task]}, {"role": "user", "content": r["prompt"]}], tokenize=False, add_generation_prompt=True, enable_thinking=False)+ ids = otok.encode(p)+ params = og.GeneratorParams(model)+ params.set_search_options(max_length=len(ids) + a.max_new, do_sample=False)+ params.set_guidance("json_schema", json.dumps(schema_for(a.task, r, schemas)))+ g = og.Generator(model, params)+ g.append_tokens(ids)+ toks, t = [], time.time()+ while not g.is_done():+ g.generate_next_token()+ toks.append(g.get_next_tokens()[0])+ f.write(json.dumps({"key": key, "i": r["i"], "at": r.get("at"), "kind": r.get("kind"), "pred": otok.decode(toks), "secs": round(time.time() - t, 2)}) + "\n")+ f.flush()+ print(f"onnx predictions -> {out}", flush=True)++def main():ap = argparse.ArgumentParser()- ap.add_argument("cmd", choices=["train", "predict", "frontier"])+ ap.add_argument("cmd", choices=["train", "predict", "frontier", "export", "onnx"])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")@@ -285,7 +335,7 @@ def main():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)+ {"train": train, "predict": predict, "frontier": frontier, "export": export, "onnx": onnx_predict}[a.cmd](a)if __name__ == "__main__":diff --git a/sdk/story/src/checks.ts b/sdk/story/src/checks.tsindex 4e81d9c9..4322d82b 100644--- a/sdk/story/src/checks.ts+++ b/sdk/story/src/checks.ts@@ -28,7 +28,8 @@ export function checkWorld(w: World): Finding[] {for (const { e, key, beat } of beats) {const turns = w.must<Record<string, number>>(e, "Turns");- if (beat.shows.length && !Object.values(turns).some((d) => d !== 0))+ const continues = w.get<string[]>(e, "Continues") ?? [];+ if (beat.shows.length && continues.length < beat.shows.length && !Object.values(turns).some((d) => d !== 0))add("turns", "warn", key, `${key} shows ${beat.shows.join(", ")} but turns no value: nothing changes`, "give a shown event a turn, or cut the beat");if (!w.must<boolean>(e, "Linked"))add("and-then", "warn", key, `${key} isn't caused by anything the audience has seen: an "and then", not a "therefore" or a "but"`, "show its cause earlier, or name a cause the audience saw");@@ -57,7 +58,9 @@ export function checkWorld(w: World): Finding[] {add("belief", "error", b.event, `${b.who} acts on "${b.fact}" in ${b.event} without knowing it yet`, `let ${b.who} learn it earlier (an event that sets or learns it), or drop it from needs`);let run = 0, sign = 0;- beats.forEach(({ e, key }) => {+ beats.forEach(({ e, key, beat }) => {+ // a shot that only continues the event before it is part of that beat's turn, not a new one+ if (beat.shows.length && (w.get<string[]>(e, "Continues") ?? []).length === beat.shows.length) return;const net = Object.values(w.must<Record<string, number>>(e, "Turns")).reduce((x, y) => x + y, 0);const s = Math.sign(net);run = s !== 0 && s === sign ? run + 1 : s !== 0 ? 1 : 0;diff --git a/sdk/story/src/lens.ts b/sdk/story/src/lens.tsindex 72ae4547..f6dc732c 100644--- a/sdk/story/src/lens.ts+++ b/sdk/story/src/lens.ts@@ -35,10 +35,16 @@ export type Structure = {focusLevel: (key: string | undefined) => number;/** the beats from one key to another, both left out */between: (from: string | undefined, to: string | undefined) => string[];+ /** the first beat a lens's stage is labelled on (`stage: { campbell: "call" }`), which wins over inference */+ label: (lens: string, stage: string) => string | undefined;};const size = (t: Partial<Record<string, number>> | undefined) => Object.values(t ?? {}).reduce<number>((a, d) => a + Math.abs(d ?? 0), 0);+/** Stage names, in any lens, that pin an anchor when a beat carries them. */+const INCITING = ["inciting", "one-day", "call", "catalyst", "need"];+const CLIMAX = ["climax", "finally", "resurrection", "finale"];+export function structure(w: World): Structure {const beats = beatsOf(w).map((b) => ({ key: b.key, beat: b.beat, index: b.index, turns: w.must<Record<string, number>>(b.e, "Turns"), level: w.must<Record<string, number>>(b.e, "Level"), tension: w.must<number>(b.e, "Tension"), linked: w.must<boolean>(b.e, "Linked") }));const events = eventsOf(w).sort((a, b) => a.order - b.order).map(({ key, ev, order }) => ({ key, ev, order }));@@ -47,18 +53,24 @@ export function structure(w: World): Structure {const brand = Object.keys(agents).find((a) => agents[a].role === "brand" || agents[a].mask === "mentor" || agents[a].mask === "gift");const focus = infoOf(w).idea?.value ?? Object.keys(keysOf(w).values)[0];const focusTurn = (t: Record<string, number>) => (focus ? t[focus] ?? 0 : Object.values(t).reduce((a, b) => a + b, 0));- const inciting = events.find((x) => size(x.ev.turns) >= 2 && !x.ev.routine)?.key;+ // labels on beats (any lens's) pin the anchors every lens reads: the event a labelled beat shows first+ const pinned = (names: string[]) => { const b = beats.find((x) => Object.values(x.beat.stage ?? {}).some((v) => names.includes(v))); return b?.beat.shows[0]; };+ const shownEv = new Set(beats.flatMap((b) => b.beat.shows));+ // the inciting incident: the first event on screen, not routine, that changes anything+ const inciting = pinned(INCITING) ?? events.find((x) => shownEv.has(x.key) && size(x.ev.turns) >= 1 && !x.ev.routine)?.key ?? events.find((x) => size(x.ev.turns) >= 2 && !x.ev.routine)?.key;const incOrder = events.find((x) => x.key === inciting)?.order ?? 0;- const crisis = events.find((x) => x.order >= incOrder && (x.ev.dilemma?.length ?? 0) >= 2)?.key;+ // the crisis: the last dilemma after the inciting incident (an early one is a refusal or a debate, not the crisis)+ const crisis = pinned(["crisis"]) ?? [...events].reverse().find((x) => x.order >= incOrder && (x.ev.dilemma?.length ?? 0) >= 2)?.key;const crisisOrder = events.find((x) => x.key === crisis)?.order ?? incOrder;const after = events.filter((x) => x.order > crisisOrder);- const climax = after.length ? after.reduce((best, x) => (Math.abs(focusTurn(x.ev.turns as Record<string, number> ?? {})) > Math.abs(focusTurn(best.ev.turns as Record<string, number> ?? {})) ? x : best)).key : undefined;+ const climax = pinned(CLIMAX) ?? (after.length ? after.reduce((best, x) => (Math.abs(focusTurn(x.ev.turns as Record<string, number> ?? {})) > Math.abs(focusTurn(best.ev.turns as Record<string, number> ?? {})) ? x : best)).key : undefined);const firstShowing = (ev: string | undefined) => (ev ? beats.find((b) => b.beat.shows.includes(ev))?.key : undefined);const lastShowing = (ev: string | undefined) => (ev ? [...beats].reverse().find((b) => b.beat.shows.includes(ev))?.key : undefined);const focusLevel = (k: string | undefined) => { const b = beats.find((x) => x.key === k); return b ? focusTurn(b.level) : 0; };const idx = (k: string | undefined) => beats.find((x) => x.key === k)?.index;const between = (a: string | undefined, b: string | undefined) => beats.filter((x) => x.index > (idx(a) ?? -1) && x.index < (idx(b) ?? beats.length)).map((x) => x.key);- return { beats, events, focus, hero, brand, agents, inciting, crisis, climax, firstShowing, lastShowing, focusTurn, focusLevel, between };+ const label = (l: string, st: string) => beats.find((b) => b.beat.stage?.[l] === st)?.key;+ return { beats, events, focus, hero, brand, agents, inciting, crisis, climax, firstShowing, lastShowing, focusTurn, focusLevel, between, label };}/** A beat's own label for this lens's stage, when it has one. */@@ -73,6 +85,26 @@ export function labelled(s: Structure, lensName: string): StageMap {export const finding = (check: string, level: Level, about: string, says: string, fix?: string): Finding => ({ check, level, about, says, fix });+/** A lens's map with the beats' own labels winning, and every stage nobody labelled held between the labelled stages+ * around it: an inferred beat out of that order is dropped, and a stretch (inferred as several beats) left empty is+ * filled with the beats between its labelled neighbours. */+export function ordered(stages: string[], inferred: StageMap, own: StageMap, s: Structure): StageMap {+ const idx = (k: string) => s.beats.find((b) => b.key === k)?.index ?? -1;+ const out: StageMap = { ...inferred, ...own };+ if (!Object.keys(own).length) return out;+ const labelledAt = new Set(Object.values(own).flat());+ stages.forEach((st, i) => {+ if (own[st]) return;+ const before = stages.slice(0, i).flatMap((x) => own[x] ?? []).map(idx);+ const after = stages.slice(i + 1).flatMap((x) => own[x] ?? []).map(idx);+ const lo = before.length ? Math.max(...before) : -1, hi = after.length ? Math.min(...after) : s.beats.length;+ const had = inferred[st] ?? [];+ const kept = had.filter((k) => idx(k) > lo && idx(k) < hi);+ out[st] = kept.length || had.length < 2 || !before.length || !after.length ? kept : s.beats.filter((b) => b.index > lo && b.index < hi && !labelledAt.has(b.key)).map((b) => b.key);+ });+ return out;+}+/** Read a story told one way through lenses (the story's own `lenses`, else all given). */export function readThrough(s: AnyStory, lenses: Lens[], telling?: string, seed = 0): LensResult[] {const w = analyze(s, telling, seed);@@ -80,7 +112,7 @@ export function readThrough(s: AnyStory, lenses: Lens[], telling?: string, seedreturn lenses.map((l) => {const r = l.read(w, st);const own = labelled(st, l.name);- const map = { ...r.map, ...own };+ const map = ordered(l.stages, r.map, own, st);return { lens: l.name, ...r, map, passes: !r.findings.some((f) => f.level === "error") };});}diff --git a/sdk/story/src/lenses/campbell.ts b/sdk/story/src/lenses/campbell.tsindex 7a8f8aea..f025b10d 100644--- a/sdk/story/src/lenses/campbell.ts+++ b/sdk/story/src/lenses/campbell.ts@@ -13,16 +13,18 @@ export const campbell = lens({read: (_w, s) => {const f: Finding[] = [];const p: Proposal[] = [];- const call = s.firstShowing(s.inciting);+ const L = (st: string) => s.label("campbell", st);+ const call = L("call") ?? s.firstShowing(s.inciting);const mentor = mentorOf(s);- const aid = beatsWith(s, mentor).find((b) => b.index >= at(s, call))?.key ?? beatsWith(s, mentor)[0]?.key;+ const aid = L("aid") ?? beatsWith(s, mentor).find((b) => b.index >= at(s, call))?.key ?? beatsWith(s, mentor)[0]?.key;const heroActs = beatsWith(s, s.hero).filter((b) => b.index > Math.max(at(s, call), at(s, aid)));- const threshold = heroActs.find((b) => b.linked)?.key;- const boon = s.lastShowing(s.climax);+ const threshold = L("threshold") ?? heroActs.find((b) => b.linked)?.key;+ const boon = L("boon") ?? s.lastShowing(s.climax);// the abyss: the lowest beat before the boon, from the threshold when it comes first, else from the callconst from = threshold && at(s, threshold) < at(s, boon) ? threshold : call;- const ordeal = lowest(s, (from ? [from] : []).concat(s.between(from, boon)));- const refusal = s.between(call, aid ?? threshold).filter((k) => s.focusTurn(s.beats.find((b) => b.key === k)!.turns) < 0);+ const ordeal = L("ordeal") ?? lowest(s, (from ? [from] : []).concat(s.between(from, boon)));+ // a refusal: the hero turning down, or weighing a dilemma, between the call and the help+ const refusal = s.between(call, aid ?? threshold).filter((k) => { const b = s.beats.find((x) => x.key === k)!; return s.focusTurn(b.turns) < 0 || b.beat.shows.some((e) => (s.events.find((x) => x.key === e)?.ev.dilemma?.length ?? 0) >= 2); });const map = {call: call ? [call] : [], refusal, aid: aid ? [aid] : [], threshold: threshold ? [threshold] : [],trials: s.between(threshold, ordeal), ordeal: ordeal && ordeal !== threshold && ordeal !== call ? [ordeal] : [], boon: boon ? [boon] : [],diff --git a/sdk/story/src/lenses/mckee.ts b/sdk/story/src/lenses/mckee.tsindex 25c3e2e8..3c3b6c74 100644--- a/sdk/story/src/lenses/mckee.ts+++ b/sdk/story/src/lenses/mckee.ts@@ -12,7 +12,8 @@ export const mckee = lens({const f: Finding[] = [];const p: Proposal[] = [];const at = (k: string | undefined) => s.beats.find((b) => b.key === k)?.index ?? -1;- const inc = s.firstShowing(s.inciting), cri = s.lastShowing(s.crisis), cli = s.lastShowing(s.climax);+ const L = (st: string) => s.label("mckee", st);+ const inc = L("inciting") ?? s.firstShowing(s.inciting), cri = L("crisis") ?? s.lastShowing(s.crisis), cli = L("climax") ?? s.lastShowing(s.climax);const map = {inciting: inc ? [inc] : [],complications: s.beats.filter((b) => b.index > at(inc) && b.index < (cri ? at(cri) : at(cli))).map((b) => b.key),@@ -25,7 +26,7 @@ export const mckee = lens({f.push(finding("mckee:inciting", "error", "story", "nothing upsets the balance: no event turns a value by 2 or more", "give the protagonist's world a big turn early"));p.push({ stage: "inciting", after: s.beats[0]?.key, onScreen: `something happens to ${s.hero ?? "the protagonist"} that they can't ignore`, feel: "concern", why: "a story starts when the balance is upset" });} else if (at(inc) > Math.ceil(n / 3)) f.push(finding("mckee:inciting", "warn", inc, `the inciting incident comes at beat ${at(inc) + 1} of ${n}, past the first third`, "bring it earlier, or open on a flash-forward"));- if (!s.crisis) {+ if (!cri) {f.push(finding("mckee:crisis", "error", "story", "there's no crisis: the protagonist never chooses between two goods or two evils", "give the event before the climax a dilemma"));const hero = s.hero ? s.agents[s.hero] : undefined;p.push({ stage: "crisis", after: map.complications.at(-1) ?? inc, onScreen: `${s.hero ?? "the protagonist"} must choose: ${hero?.want ?? "what they want"}, or ${hero?.need ?? "what they need"}`, feel: "dread", why: "the climax only means something if it was a choice" });@@ -39,7 +40,8 @@ export const mckee = lens({}const comp = map.complications.map((k) => s.beats.find((b) => b.key === k)!.tension);for (let i = 1; i < comp.length; i++)- if (comp[i] < comp[i - 1] - 0.05) f.push(finding("mckee:complications", "warn", map.complications[i], "the complications ease off instead of escalating", "make each complication cost more than the last"));+ // easing off: tension falls and no value turns down (danger rising on another value still escalates)+ if (comp[i] < comp[i - 1] - 0.05 && !Object.values(s.beats.find((b) => b.key === map.complications[i])!.turns).some((d) => d < 0)) f.push(finding("mckee:complications", "warn", map.complications[i], "the complications ease off instead of escalating", "make each complication cost more than the last"));return { map, findings: f, proposals: p };},});diff --git a/sdk/story/src/lenses/pixar.ts b/sdk/story/src/lenses/pixar.tsindex b679953c..eefb4b35 100644--- a/sdk/story/src/lenses/pixar.ts+++ b/sdk/story/src/lenses/pixar.ts@@ -13,7 +13,7 @@ export const pixar = lens({const f: Finding[] = [];const p: Proposal[] = [];const idx = (k: string | undefined) => s.beats.find((b) => b.key === k)?.index ?? -1;- const one = s.firstShowing(s.inciting), fin = s.lastShowing(s.climax);+ const one = s.label("pixar", "one-day") ?? s.firstShowing(s.inciting), fin = s.label("pixar", "finally") ?? s.lastShowing(s.climax);const routine = s.beats.filter((b) => b.beat.shows.some((e) => s.events.find((x) => x.key === e)?.ev.routine)).map((b) => b.key);const because = s.beats.filter((b) => b.index > idx(one) && (fin === undefined || b.index < idx(fin)) && b.linked).map((b) => b.key);const ever = fin ? s.beats.filter((b) => b.index > idx(fin)).map((b) => b.key) : [];diff --git a/sdk/story/src/lenses/vogler.ts b/sdk/story/src/lenses/vogler.tsindex a159d0dd..c9ca60f3 100644--- a/sdk/story/src/lenses/vogler.ts+++ b/sdk/story/src/lenses/vogler.ts@@ -12,14 +12,15 @@ export const vogler = lens({stages: ["ordinary-world", "call", "refusal", "mentor", "threshold", "tests", "approach", "ordeal", "reward", "road-back", "resurrection", "return"],read: (_w, s) => {const f: Finding[] = [];- const call = s.firstShowing(s.inciting);+ const L = (st: string) => s.label("vogler", st);+ const call = L("call") ?? s.firstShowing(s.inciting);const mentor = mentorOf(s);- const meet = beatsWith(s, mentor).find((b) => b.index >= at(s, call))?.key;- const threshold = beatsWith(s, s.hero).find((b) => b.index > Math.max(at(s, call), at(s, meet)) && b.linked)?.key;- const climax = s.lastShowing(s.climax);+ const meet = L("mentor") ?? beatsWith(s, mentor).find((b) => b.index >= at(s, call))?.key;+ const threshold = L("threshold") ?? beatsWith(s, s.hero).find((b) => b.index > Math.max(at(s, call), at(s, meet)) && b.linked)?.key;+ const climax = L("resurrection") ?? s.lastShowing(s.climax);const from = threshold ?? call;- const ordeal = lowest(s, s.between(from, climax));- const reward = s.beats.find((b) => b.index > at(s, ordeal) && b.index < at(s, climax) && s.focusTurn(b.turns) > 0)?.key;+ const ordeal = L("ordeal") ?? lowest(s, s.between(from, climax));+ const reward = L("reward") ?? s.beats.find((b) => b.index > at(s, ordeal) && b.index < at(s, climax) && s.focusTurn(b.turns) > 0)?.key;const map = {"ordinary-world": s.between(undefined, call), call: call ? [call] : [],refusal: s.between(call, meet ?? threshold).filter((k) => s.focusTurn(s.beats.find((b) => b.key === k)!.turns) < 0),diff --git a/sdk/story/src/systems/cause.ts b/sdk/story/src/systems/cause.tsindex 3a598b64..3cf3d696 100644--- a/sdk/story/src/systems/cause.ts+++ b/sdk/story/src/systems/cause.ts@@ -24,8 +24,10 @@ export function causes(w: World): void {if ((order[c] ?? -1) >= o) out.later.push({ event: key, cause: c });}}- const last = events[events.length - 1]?.key;- for (const { key, ev } of events) if (key !== last && !causesSomething.has(key) && !ev.routine) out.deadEnds.push(key);+ // the resolution needn't cause anything: events after the last one that settles a want or need (else the last event)+ const settles = events.filter((x) => Object.keys(x.ev.ends ?? {}).length).map((x) => order[x.key] ?? -1);+ const resolved = settles.length ? Math.max(...settles) : (order[events[events.length - 1]?.key] ?? 0) - 1;+ for (const { key, ev } of events) if ((order[key] ?? 0) <= resolved && !causesSomething.has(key) && !ev.routine && !Object.keys(ev.ends ?? {}).length) out.deadEnds.push(key);w.setResource<Causes>("Causes", out);const byKey = Object.fromEntries(events.map((x) => [x.key, x.ev]));diff --git a/sdk/story/src/systems/values.ts b/sdk/story/src/systems/values.tsindex 251ebad4..84a058c5 100644--- a/sdk/story/src/systems/values.ts+++ b/sdk/story/src/systems/values.ts@@ -1,7 +1,7 @@// Value curves (docs/story.feature ST1a). In the world, each event moves the values it turns, in story order, so every// event has the world's level after it. In a telling, a beat's level is the world's level after the latest event it// shows (a flash-forward shows a later level, a flashback an earlier one), and its turn is the sum of what its events-// turn. Beats get "Turns" and "Level"; the world gets "Curves", each value's levels over the telling and its shape.+// turn. Beats get "Turns", "Level" and "Continues" (events the beat before showed too, counted once); the world gets "Curves", each value's levels over the telling and its shape.import type { World } from "../ecs.ts";import { beatsOf, eventsOf, keysOf, type REvent } from "../load.ts";@@ -35,9 +35,15 @@ export function values(w: World): void {let last = start;const series: Record<string, number[]> = Object.fromEntries(names.map((n) => [n, [0]]));const order = Object.fromEntries(eventsOf(w).map((x) => [x.key, x.order]));+ // a film tells one event over several shots: an event the beat before also showed continues there, and its turn+ // counts once, at the first shot of the run (a hook that shows the ending and a return to it later both count)+ let prev = new Set<string>();for (const { e, beat } of beatsOf(w)) {const turns: Record<string, number> = {};- for (const k of beat.shows) for (const [v, d] of Object.entries(eventsOf(w).find((x) => x.key === k)?.ev.turns ?? {})) turns[v] = (turns[v] ?? 0) + (d ?? 0);+ const continued = beat.shows.filter((k) => prev.has(k));+ prev = new Set(beat.shows);+ w.insert(e, "Continues", continued);+ for (const k of beat.shows.filter((x) => !continued.includes(x))) for (const [v, d] of Object.entries(eventsOf(w).find((x) => x.key === k)?.ev.turns ?? {})) turns[v] = (turns[v] ?? 0) + (d ?? 0);const latest = [...beat.shows].sort((a, b) => (order[b] ?? -1) - (order[a] ?? -1))[0];const lvl = latest !== undefined && after[latest] ? after[latest] : last;w.insert(e, "Turns", turns);diff --git a/sdk/story/test/lenses.test.ts b/sdk/story/test/lenses.test.tsindex 6999fcf5..ca7c2f03 100644--- a/sdk/story/test/lenses.test.ts+++ b/sdk/story/test/lenses.test.ts@@ -1,5 +1,5 @@import { expect, test } from "bun:test";-import { LENSES, readThrough, story, value } from "../src/index.ts";+import { LENSES, checkStory, readThrough, story, value } from "../src/index.ts";import { launch } from "./fixture.ts";test("the launch story passes McKee, Pixar, Storynomics and PAS, mapped as expected", () => {@@ -50,3 +50,23 @@ test("bernays refuses invented proof", () => {expect(r.findings.map((f) => f.check)).toContain("bernays:invented");expect(r.passes).toBe(false);});++test("labels pin a lens's stages and hold the unlabelled ones in order", () => {+ const t = launch.tellings["30s"] as any[];+ const labelled = { ...launch, tellings: { "30s": [t[0], { ...t[1], stage: { campbell: "call" } }, t[2], { ...t[3], stage: { campbell: "boon" } }] } };+ const r = readThrough(labelled as typeof launch, [LENSES.campbell, LENSES.mckee], "30s");+ expect(r[0].map.call).toEqual(["b1"]);+ expect(r[0].map.boon).toEqual(["b3"]);+ // nothing inferred for a stage lands outside its labelled neighbours+ for (const k of r[0].map.trials ?? []) expect(["b2"]).toContain(k);+ // campbell's boon is campbell's: mckee still finds its own climax+ expect(r[1].map.climax).toEqual(["b3"]);+});++test("shots of one event count its turn once", () => {+ const t = launch.tellings["30s"] as any[];+ const shots = { ...launch, tellings: { "30s": [t[0], t[1], { ...t[2], id: "tries-a" }, { ...t[2], id: "tries-b" }, { ...t[2], id: "tries-c" }, t[3]] } };+ const found = checkStory(shots as typeof launch, "30s");+ expect(found.filter((f) => f.check === "turns")).toEqual([]);+ expect(found.filter((f) => f.check === "rhythm")).toEqual([]);+});