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
ST6c: story as decisions. src/questions.ts: a beat's window (story lines or a plain script) as a decision model's state and typed questions about it in the Jev / Clef format (11 checks as noul, the event shown, the turn, continues, learns, opens, tension, three lens stages), each answered exactly by the checks, systems and lenses. models/decide-rows.ts (corpus, cuts, swaps and mutants: 15,154 train windows), models/clef.ts (Clef and Clef-flash zero-shot), models/decide.py (Qwen3-0.6B frozen, LoRA, an option head, one prefill pass, cross-entropy plus Brier), models/decide-score.ts. scriptOf moves into raea/story; split into models/lib.ts.
shinyobjectz23220fa00288
diff --git a/sdk/story/models/clef.ts b/sdk/story/models/clef.tsnew file mode 100644index 00000000..f4d5f879--- /dev/null+++ b/sdk/story/models/clef.ts@@ -0,0 +1,46 @@+// Clef as the zero-shot baseline for the story decision model: the same states and typed questions+// (models/decide-rows.ts), answered by Cloudflare's decision models on Workers AI, normalised to per-option+// probabilities like every other model's predictions (decide-score.ts reads them alike).+// bun models/clef.ts [--model clef-flash|clef] [--split test] [--limit 200] [--jobs 8]+// Needs CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN (environment or ~/.raea/env). $0.15 per million input tokens.+import { appendFileSync, existsSync, readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++type J = Record<string, any>;+const arg = (k: string, d: string) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };+const MODEL = arg("--model", "clef-flash"), SPLIT = arg("--split", "test"), LIMIT = +arg("--limit", "200"), JOBS = +arg("--jobs", "8");+const DIR = arg("--rows", join(homedir(), ".vd/story/rows/decide")).replace(/^~/, homedir());+const env = (k: string) => process.env[k] ?? (existsSync(join(homedir(), ".raea/env")) ? readFileSync(join(homedir(), ".raea/env"), "utf8").match(new RegExp(`^${k}=(.*)$`, "m"))?.[1]?.replace(/^["']|["']$/g, "") : undefined);+const ACCT = env("CLOUDFLARE_ACCOUNT_ID"), TOKEN = env("CLOUDFLARE_API_TOKEN");+if (!ACCT || !TOKEN) throw new Error("set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN");++export const keyOf = (r: J) => `${r.i}:${r.kind}:${r.at}:${r.as}`;+/** Clef's answer to one question as {option: probability}. */+export function probsOf(q: J, a: J): Record<string, number> {+ if (!a) return {};+ if (q.type === "noul") { const p = typeof a.noul === "number" ? a.noul : 0.5; return { no: 1 - p, yes: p }; }+ return a.probabilities ?? {};+}++const rows: J[] = readFileSync(join(DIR, `${SPLIT}.jsonl`), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)).filter((_, j, all) => j % Math.max(1, Math.floor(all.length / LIMIT)) === 0).slice(0, LIMIT);+const out = join(DIR, `pred-${MODEL}-${SPLIT}.jsonl`);+const done = new Set(existsSync(out) ? readFileSync(out, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l).key) : []);+let tokens = 0, n = 0, failed = 0;+const queue = rows.filter((r) => !done.has(keyOf(r)));+async function one(r: J) {+ for (let attempt = 0; attempt < 3; attempt++) {+ const t = Date.now();+ const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${ACCT}/ai/run/@cf/cloudflare/${MODEL}`, { method: "POST", headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/json" }, body: JSON.stringify({ state: r.state, questions: r.questions }) });+ const j: J = await res.json().catch(() => ({}));+ if (!j.success) { if (attempt === 2) { failed++; console.error("failed", keyOf(r), JSON.stringify(j.errors ?? res.status).slice(0, 200)); } continue; }+ tokens += j.result?.usage?.input_tokens ?? 0;+ const probs = Object.fromEntries(Object.entries(r.questions as J).map(([id, q]) => [id, probsOf(q, j.result.answers?.[id])]));+ appendFileSync(out, JSON.stringify({ key: keyOf(r), probs, secs: (Date.now() - t) / 1000 }) + "\n");+ if (++n % 25 === 0) console.log(`${n}/${queue.length}, ${tokens} tokens ($${(tokens * 0.15e-6).toFixed(3)})`);+ return;+ }+}+const it = queue[Symbol.iterator]();+await Promise.all(Array.from({ length: JOBS }, async () => { for (let x = it.next(); !x.done; x = it.next()) await one(x.value); }));+console.log(`done: ${n} answered, ${failed} failed, ${tokens} input tokens, spent $${(tokens * 0.15e-6).toFixed(3)} -> ${out}`);diff --git a/sdk/story/models/decide-rows.ts b/sdk/story/models/decide-rows.tsnew file mode 100644index 00000000..fcf3795f--- /dev/null+++ b/sdk/story/models/decide-rows.ts@@ -0,0 +1,46 @@+// Rows for the story decision model (docs/story.md, "Story as decisions"): a beat's window as the state, typed+// questions about that beat (src/questions.ts), and their exact answers. Each corpus story is read as written and with+// one beat cut and one pair swapped (where the checks find breaks); windows are story lines or a plain script.+// train: three beats of each telling, lines or script at random; val, test: up to eight beats, both forms+// bun models/decide-rows.ts [--in ~/.vd/story] [--out ~/.vd/story/rows/decide]+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { asker, fromData, rng, sampleMutants } from "../src/index.ts";+import { split } from "./lib.ts";++type J = Record<string, any>;+const arg = (k: string, d: string) => { const i = process.argv.indexOf(k); return (i > 0 ? process.argv[i + 1] : d).replace(/^~/, homedir()); };+const IN = arg("--in", join(homedir(), ".vd/story")), OUT = arg("--out", join(homedir(), ".vd/story/rows/decide"));+const stories = readFileSync(join(IN, "stories.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));+const out: Record<string, J[]> = {};+const yes: Record<string, number> = {};+for (const { i, story } of stories) {+ if (fromData(story).errors.length) continue;+ const sp = split(i), r = rng(i * 7919 + 3);+ const beats: J[] = story.tellings.main;+ const variants: [string, J[]][] = [["clean", beats]];+ if (beats.length > 3) {+ const c = Math.floor(r() * beats.length); variants.push([`cut${c + 1}`, beats.filter((_, n) => n !== c)]);+ const w = Math.floor(r() * (beats.length - 1)); const b2 = [...beats]; [b2[w], b2[w + 1]] = [b2[w + 1], b2[w]]; variants.push([`swap${w + 1}`, b2]);+ }+ // and two mutants (src/mutate.ts): a cause broken, a fact known early, a setup dropped ... where cuts can't reach+ const muts = (() => { try { return sampleMutants(fromData(story).story!, 2, i, "main"); } catch { return []; } })();+ const all: [string, J][] = [...variants.map(([k, bs]) => [k, { ...story, tellings: { main: bs } }] as [string, J]), ...muts.map((m) => [`mut-${m.label.kind}`, m.story as unknown as J] as [string, J])];+ for (const [kind, st] of all) {+ const bs: J[] = (st.tellings as J).main;+ let ask;+ try { ask = asker(st, "main"); } catch { continue; }+ const ks = bs.map((_, k) => k);+ const pick = sp === "train" ? [...new Set([0, 1, 2].map(() => ks[Math.floor(r() * ks.length)]))] : ks.slice(0, 8);+ for (const k of pick) for (const as of sp === "train" ? [r() < 0.5 ? "lines" : "script"] : ["lines", "script"]) {+ const q = ask(k, as as "lines" | "script");+ (out[sp] ??= []).push({ i, kind, at: k, as, ...q });+ if (sp === "train") for (const [id, v] of Object.entries(q.answers)) if (v === true) yes[id] = (yes[id] ?? 0) + 1;+ }+ }+}+mkdirSync(OUT, { recursive: true });+for (const [sp, rows] of Object.entries(out)) writeFileSync(join(OUT, `${sp}.jsonl`), rows.map((x) => JSON.stringify(x)).join("\n") + "\n");+console.log(Object.entries(out).map(([sp, rows]) => `${sp} ${rows.length}`).join(", "), "->", OUT);+console.log("yes answers on train:", JSON.stringify(yes));diff --git a/sdk/story/models/decide-score.ts b/sdk/story/models/decide-score.tsnew file mode 100644index 00000000..d9546bd0--- /dev/null+++ b/sdk/story/models/decide-score.ts@@ -0,0 +1,77 @@+// Scores the story decision model's predictions against the exact answers (docs/story.md, "Story as decisions"),+// every model on the windows all of them answered: Clef and Clef-flash (zero-shot), the local model, and "prior" (the+// training set's base rates, the floor any model has to clear).+// noul Brier (lower is better), AUC, accuracy at 0.5 breaks.* pooled as "breaks", and each on its own+// choice accuracy (the most likely option), Brier over the options+// score accuracy (the most likely level), mean error of the expected level+// bun models/decide-score.ts [--split test] [--rows ~/.vd/story/rows/decide] [--by as]+import { readdirSync, readFileSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++type J = Record<string, any>;+const arg = (k: string, d: string) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };+const SPLIT = arg("--split", "test"), DIR = arg("--rows", join(homedir(), ".vd/story/rows/decide")).replace(/^~/, homedir());+const read = (f: string): J[] => readFileSync(join(DIR, f), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));+const keyOf = (r: J) => `${r.i}:${r.kind}:${r.at}:${r.as}`;+const rows = new Map(read(`${SPLIT}.jsonl`).map((r) => [keyOf(r), r]));++// the prior: base rates on train, by question id (choices whose options change per story fall back to uniform)+const train = read("train.jsonl");+const freq: Record<string, Record<string, number>> = {};+for (const r of train) for (const [id, v] of Object.entries(r.answers)) { const o = (freq[id] ??= {}); const k = String(v === true ? "yes" : v === false ? "no" : v); o[k] = (o[k] ?? 0) + 1; }+const priorFor = (id: string, q: J): Record<string, number> => {+ const opts = q.type === "noul" ? ["no", "yes"] : q.type === "choice" ? Object.keys(q.criteria) : q.criteria.map((_: string, i: number) => String(i));+ const f = id === "shows" ? {} : freq[id] ?? {};+ const tot = opts.reduce((a: number, o: string) => a + (f[o] ?? 0) + 0.5, 0);+ return Object.fromEntries(opts.map((o: string) => [o, ((f[o] ?? 0) + 0.5) / tot]));+};++const preds: Record<string, Map<string, J>> = {};+for (const f of readdirSync(DIR).filter((f) => f.startsWith("pred-") && f.endsWith(`-${SPLIT}.jsonl`))) preds[f.slice(5, -(`-${SPLIT}.jsonl`.length))] = new Map(read(f).map((p) => [p.key, p.probs]));+const common = [...rows.keys()].filter((k) => Object.values(preds).every((m) => m.has(k)));+preds.prior = new Map(common.map((k) => [k, Object.fromEntries(Object.entries(rows.get(k)!.questions as J).map(([id, q]) => [id, priorFor(id, q)]))]));++const truth = (q: J, v: unknown) => (q.type === "noul" ? (v ? "yes" : "no") : String(v));+function auc(ps: number[], ys: boolean[]): number | null {+ const pos = ps.filter((_, i) => ys[i]), neg = ps.filter((_, i) => !ys[i]);+ if (!pos.length || !neg.length) return null;+ let s = 0; for (const p of pos) for (const n of neg) s += p > n ? 1 : p === n ? 0.5 : 0;+ return s / (pos.length * neg.length);+}+function score(who: string, keys: string[]): J {+ const groups: Record<string, { p: number[]; y: boolean[]; acc: number[]; brier: number[]; err: number[] }> = {};+ const g = (k: string) => (groups[k] ??= { p: [], y: [], acc: [], brier: [], err: [] });+ for (const key of keys) {+ const r = rows.get(key)!, pr = preds[who].get(key)!;+ for (const [id, q] of Object.entries(r.questions as J)) {+ const probs: Record<string, number> = pr[id] ?? {};+ const t = truth(q, r.answers[id]);+ const opts = Object.keys(probs).length ? Object.keys(probs) : Object.keys(priorFor(id, q));+ const best = opts.reduce((a, b) => ((probs[b] ?? 0) > (probs[a] ?? 0) ? b : a), opts[0]);+ const brier = opts.reduce((a, o) => a + ((probs[o] ?? 0) - (o === t ? 1 : 0)) ** 2, 0);+ const names = id.startsWith("breaks.") ? ["breaks", id] : id.startsWith("stage.") ? ["stage", id] : [id];+ for (const name of names) {+ const x = g(name);+ x.acc.push(best === t ? 1 : 0); x.brier.push(brier);+ if (q.type === "noul") { x.p.push(probs.yes ?? 0); x.y.push(t === "yes"); }+ if (q.type === "score") x.err.push(Math.abs(opts.reduce((a, o) => a + Number(o) * (probs[o] ?? 0), 0) - Number(t)));+ }+ }+ }+ const mean = (a: number[]) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : null);+ return Object.fromEntries(Object.entries(groups).map(([k, x]) => [k, { n: x.acc.length, acc: mean(x.acc), brier: mean(x.brier), auc: x.p.length ? auc(x.p, x.y) : null, err: mean(x.err), pos: x.y.filter(Boolean).length || undefined }]));+}+const by = process.argv.includes("--by") ? arg("--by", "as") : null;+const slices: [string, string[]][] = by ? [...new Set(common.map((k) => rows.get(k)![by]))].map((v) => [`${by}=${v}`, common.filter((k) => rows.get(k)![by] === v)]) : [["all", common]];+const result: J = {};+for (const [slice, keys] of slices) {+ console.log(`\n== ${slice}: ${keys.length} windows`);+ const all = Object.fromEntries(Object.keys(preds).map((who) => [who, score(who, keys)]));+ result[slice] = all;+ const names = Object.keys(all.prior).sort((a, b) => (a.includes(".") ? 1 : 0) - (b.includes(".") ? 1 : 0) || a.localeCompare(b));+ const f = (x: number | null | undefined) => (x == null ? " - " : x.toFixed(3));+ console.log(["question".padEnd(22), "pos", ...Object.keys(all).map((w) => `${w}: acc brier auc`.padEnd(26))].join(" "));+ for (const nm of names) console.log([nm.padEnd(22), String(all.prior[nm].pos ?? "").padStart(3), ...Object.keys(all).map((w) => `${f(all[w][nm]?.acc)} ${f(all[w][nm]?.brier)} ${f(all[w][nm]?.auc ?? all[w][nm]?.err)}`.padEnd(26))].join(" "));+}+writeFileSync(join(DIR, `scores-${SPLIT}.json`), JSON.stringify(result, null, 1));diff --git a/sdk/story/models/decide.py b/sdk/story/models/decide.pynew file mode 100644index 00000000..45d869ff--- /dev/null+++ b/sdk/story/models/decide.py@@ -0,0 +1,240 @@+"""The story decision model (docs/story.md, "Story as decisions"): System 1 for raea/story.++A small base (Qwen3-0.6B by default) reads a beat's window and every typed question about it in ONE prefill pass, with+no text generated. A small head scores each option of each question from the hidden state at that option's last+token, and a softmax over a question's options gives its probabilities. Trained as Clef is: the base frozen, LoRA on+its layers, the head; label-smoothed cross-entropy plus a Brier term so the probabilities are calibrated. The answers+are exact (models/decide-rows.ts, from the checks, systems and lenses), so this is consolidation: the slow, exact+reading (System 2) turned into a one-pass instinct, measured against it and against Clef (models/clef.ts).++ python decide.py train [--rows ~/.vd/story/rows/decide] [--iters 3000] [--name q06]+ python decide.py predict [--split test] [--limit 300] [--name q06] -> pred-decide-NAME-SPLIT.jsonl+Predictions take the same evenly spread windows clef.ts does, so decide-score.ts compares them on the same ones.+"""+import argparse+import json+import math+import random+import time+from pathlib import Path++import mlx.core as mx+import mlx.nn as nn+import mlx.optimizers as optim+from mlx.utils import tree_flatten++SYSTEM = (+ "You read a story window and answer typed questions about one beat of it. Each question lists its options; "+ "the most fitting option is the answer."+)+++def rows_dir(a):+ return Path(a.rows).expanduser()+++def read_jsonl(p):+ return [json.loads(l) for l in open(p) if l.strip()]+++def options(q):+ if q["type"] == "noul":+ return [("no", ""), ("yes", "")]+ if q["type"] == "choice":+ return list(q["criteria"].items())+ return [(str(i), lvl) for i, lvl in enumerate(q["criteria"])]+++def truth(q, v):+ return ("yes" if v else "no") if q["type"] == "noul" else str(v)+++def encode(tok, row, max_state_chars):+ """Token ids for the window and its questions, and per question its option names and their last-token positions."""+ enc = lambda s: tok.encode(s, add_special_tokens=False)+ state = row["state"]+ if len(state) > max_state_chars: # keep the end (the beats and LOOK AT) and as much of the head as fits+ state = state[: max_state_chars // 3] + "\n...\n" + state[-(2 * max_state_chars) // 3 :]+ ids = enc(f"<|im_start|>system\n{SYSTEM}<|im_end|>\n<|im_start|>user\nSTATE\n{state}\nQUESTIONS\n")+ qs = []+ for qid, q in row["questions"].items():+ ids += enc(f"\n[{qid}] {q['instructions']}\n")+ names, pos = [], []+ for name, desc in options(q):+ ids += enc(f"- {name}{': ' + desc if desc and desc != name else ''}\n")+ names.append(name)+ pos.append(len(ids) - 1)+ qs.append((qid, names, pos))+ return ids, qs+++class Head(nn.Module):+ def __init__(self, dims, hidden=256):+ super().__init__()+ self.l1 = nn.Linear(dims, hidden)+ self.l2 = nn.Linear(hidden, 1)++ def __call__(self, h):+ return self.l2(nn.gelu(self.l1(h))).squeeze(-1)+++class Decider(nn.Module):+ def __init__(self, lm, dims):+ super().__init__()+ self.lm = lm+ self.head = Head(dims)++ def __call__(self, ids, pos):+ h = self.lm.model(ids[None])[0] # hidden states after the final norm+ return self.head(h[pos])+++def build(a, train=True):+ from mlx_lm import load+ from mlx_lm.tuner.utils import linear_to_lora_layers++ lm, tok = load(a.base)+ lm.freeze()+ linear_to_lora_layers(lm, a.layers, {"rank": a.rank, "scale": 20.0, "dropout": 0.05 if train else 0.0})+ dims = lm.model.embed_tokens.weight.shape[1]+ dec = Decider(lm, dims)+ return dec, tok+++def loss_fn(dec, ids, pos, groups, targets, smooth=0.05):+ logits = dec(ids, pos)+ total = mx.array(0.0)+ for (s, e), t in zip(groups, targets):+ lg = logits[s:e]+ n = e - s+ lp = lg - mx.logsumexp(lg)+ onehot = mx.zeros((n,)).at[t].add(1.0)+ soft = onehot * (1 - smooth) + smooth / n+ p = mx.exp(lp)+ total = total + (-(soft * lp).sum()) + ((p - onehot) ** 2).sum()+ return total / len(groups)+++def prep(tok, row, max_state_chars):+ ids, qs = encode(tok, row, max_state_chars)+ pos, groups, targets, names = [], [], [], []+ for qid, opts, p in qs:+ t = truth(row["questions"][qid], row["answers"][qid])+ if t not in opts:+ continue+ groups.append((len(pos), len(pos) + len(p)))+ targets.append(opts.index(t))+ pos += p+ names.append((qid, opts))+ return mx.array(ids), mx.array(pos), groups, targets, names+++def train(a):+ from mlx_lm.tuner.trainer import grad_checkpoint++ rd = rows_dir(a)+ rows = read_jsonl(rd / "train.jsonl")+ allval = read_jsonl(rd / "val.jsonl")+ val = allval[:: max(1, len(allval) // a.val)][: a.val]+ dec, tok = build(a)+ grad_checkpoint(dec.lm.model.layers[0])+ n_train = sum(v.size for _, v in tree_flatten(dec.trainable_parameters()))+ print(f"decide: {len(rows)} train windows, {len(val)} val; trainable {n_train / 1e6:.2f}M", flush=True)+ sched = optim.join_schedules([optim.linear_schedule(1e-6, a.lr, 100), optim.cosine_decay(a.lr, a.iters, a.lr * 0.05)], [100])+ opt = optim.AdamW(learning_rate=sched, weight_decay=0.01)+ vg = nn.value_and_grad(dec, loss_fn)+ rng = random.Random(0)+ out = rd / f"decide-{a.name}"+ out.mkdir(exist_ok=True)++ def val_loss():+ dec.eval()+ ls = [loss_fn(dec, *prep(tok, r, a.max_state)[:4]).item() for r in val]+ dec.train()+ return sum(ls) / len(ls)++ print(f" 0 val {val_loss():.3f}", flush=True)+ t0, acc, grads = time.time(), [], None+ for it in range(1, a.iters + 1):+ r = rows[rng.randrange(len(rows))]+ ids, pos, groups, targets, _ = prep(tok, r, a.max_state)+ if not groups:+ continue+ l, g = vg(dec, ids, pos, groups, targets)+ grads = g if grads is None else tree_map_add(grads, g)+ acc.append(l.item())+ if it % a.accum == 0:+ grads = tree_scale(grads, 1 / a.accum)+ opt.update(dec, grads)+ mx.eval(dec.parameters(), opt.state)+ grads = None+ if it % 50 == 0:+ print(f"{it:6d} {sum(acc) / len(acc):.3f} {time.time() - t0:.0f}s", flush=True)+ acc = []+ if it % 500 == 0 or it == a.iters:+ print(f"{it:6d} val {val_loss():.3f}", flush=True)+ mx.save_safetensors(str(out / "weights.safetensors"), dict(tree_flatten(dec.trainable_parameters())))+ json.dump(vars(a), open(out / "config.json", "w"), indent=1)+ print(f"trained -> {out}", flush=True)+++def tree_map_add(a, b):+ from mlx.utils import tree_map+ return tree_map(lambda x, y: x + y, a, b)+++def tree_scale(a, s):+ from mlx.utils import tree_map+ return tree_map(lambda x: x * s, a)+++def predict(a):+ rd = rows_dir(a)+ allrows = read_jsonl(rd / f"{a.split}.jsonl")+ stride = max(1, len(allrows) // a.limit) if a.limit else 1+ rows = [r for j, r in enumerate(allrows) if j % stride == 0][: a.limit or None]+ dec, tok = build(a, train=False)+ dec.load_weights(str(rd / f"decide-{a.name}" / "weights.safetensors"), strict=False)+ dec.eval()+ out = rd / f"pred-decide-{a.name}-{a.split}.jsonl"+ with open(out, "w") as f:+ for n, r in enumerate(rows):+ t = time.time()+ ids, qs = encode(tok, r, a.max_state)+ pos = [p for _, _, ps in qs for p in ps]+ logits = dec(mx.array(ids), mx.array(pos))+ mx.eval(logits)+ probs, i = {}, 0+ for qid, names, ps in qs:+ lg = logits[i : i + len(ps)]+ p = mx.softmax(lg).tolist()+ probs[qid] = dict(zip(names, p))+ i += len(ps)+ key = f"{r['i']}:{r['kind']}:{r['at']}:{r['as']}"+ f.write(json.dumps({"key": key, "probs": probs, "secs": round(time.time() - t, 3), "tokens": len(ids)}) + "\n")+ if (n + 1) % 50 == 0:+ print(f"{n + 1}/{len(rows)}", flush=True)+ print(f"predicted {len(rows)} -> {out}", flush=True)+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("cmd", choices=["train", "predict"])+ ap.add_argument("--rows", default="~/.vd/story/rows/decide")+ ap.add_argument("--base", default="Qwen/Qwen3-0.6B")+ ap.add_argument("--name", default="q06")+ ap.add_argument("--iters", type=int, default=3000)+ ap.add_argument("--accum", type=int, default=4)+ ap.add_argument("--lr", type=float, default=2e-4)+ ap.add_argument("--rank", type=int, default=16)+ ap.add_argument("--layers", type=int, default=28)+ ap.add_argument("--max-state", dest="max_state", type=int, default=9000)+ ap.add_argument("--val", type=int, default=60)+ ap.add_argument("--split", default="test")+ ap.add_argument("--limit", type=int, default=300)+ a = ap.parse_args()+ {"train": train, "predict": predict}[a.cmd](a)+++if __name__ == "__main__":+ main()diff --git a/sdk/story/models/lib.ts b/sdk/story/models/lib.tsindex 9bcfa40a..fc811db6 100644--- a/sdk/story/models/lib.ts+++ b/sdk/story/models/lib.ts@@ -1,15 +1,16 @@// What the corpus rows (rows.ts) and a held-out story's rows (validate.ts) share: a telling as prose, the story as the// extractor answers it, and exact labels for a telling a viewer could see.-import { checkStory, fromData, toLines, type AnyStory } from "../src/index.ts";+import { checkStory, fromData, scriptOf, toLines, type AnyStory } from "../src/index.ts";type J = Record<string, any>;+/** A story's split by its index: one in ten test, one in ten val, the rest train. */+export const split = (i: number) => { const h = (Math.imul(i + 1, 2654435761) >>> 0) % 10; return h === 0 ? "test" : h === 1 ? "val" : "train"; };+export const name = (k: string) => (k === "narrator" ? "NARRATOR" : k.replace(/([a-z])([A-Z])/g, "$1 $2").toUpperCase());/** A telling as a script a person would write: numbered beats, what's seen, who says what. No keys, no annotations. */-export function prose(beats: J[]): string {- return beats.map((b, n) => [`${n + 1}. ${b.onScreen ?? ""}`.trimEnd(), ...(b.says ?? []).map((l: J) => ` ${name(l.who)}: ${l.says}`)].join("\n")).join("\n");-}+export const prose = (beats: J[]): string => scriptOf(beats);export const withTelling = (s: J, beats: J[]): J => ({ ...s, tellings: { main: beats } });export const breaks = (s: J, beats: J[]) => {diff --git a/sdk/story/models/rows.ts b/sdk/story/models/rows.tsindex 3cd27ee5..e82f503d 100644--- a/sdk/story/models/rows.ts+++ b/sdk/story/models/rows.ts@@ -13,7 +13,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";import { beatSchema, rng, storySchema, windowAt } from "../src/index.ts";-import { bare, breaks, CHUNK, chunkSteps, criticSchema, name, prose, stepSchema } from "./lib.ts";+import { bare, breaks, CHUNK, split, chunkSteps, criticSchema, name, prose, stepSchema } from "./lib.ts";const arg = (k: string, d: string) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };const IN = arg("--in", join(homedir(), ".vd/story"));@@ -24,7 +24,6 @@ type J = Record<string, any>;const stories: { i: number; s: J; premise: J }[] = readFileSync(join(IN, "stories.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)).map((d) => ({ i: d.i, s: d.story, premise: d.premise }));/** The split a story falls in, by its index. */-export const split = (i: number) => { const h = (Math.imul(i + 1, 2654435761) >>> 0) % 10; return h === 0 ? "test" : h === 1 ? "val" : "train"; };const out: Record<string, Record<string, J[]>> = { extract: {}, steps: {}, generate: {}, critic: {} };const push = (task: string, sp: string, row: J) => ((out[task][sp] ??= []).push(row));diff --git a/sdk/story/src/index.ts b/sdk/story/src/index.tsindex 5103ce4f..e18dfec0 100644--- a/sdk/story/src/index.ts+++ b/sdk/story/src/index.ts@@ -16,5 +16,6 @@ export { sample, samples, matrix, judge, type Sampled, type SampleOptions, typeexport { 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 { toLines, fromLines } from "./lines.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/lines.ts b/sdk/story/src/lines.tsindex 036b1034..2c5fb34b 100644--- a/sdk/story/src/lines.ts+++ b/sdk/story/src/lines.ts@@ -76,6 +76,12 @@ export function toLines(s: AnyStory | J, seed = 0): string {}const listOf = (x: unknown) => ([] as unknown[]).concat(x ?? []);+const speaker = (k: string) => (k === "narrator" ? "NARRATOR" : k.replace(/([a-z])([A-Z])/g, "$1 $2").toUpperCase());+/** Beats as a script a person would write: numbered (from `from`), what's seen, who says what; no keys. */+export function scriptOf(beats: J[], from = 0): string {+ return beats.map((b, n) => [`${from + n + 1}. ${b.onScreen ?? ""}`.trimEnd(), ...(b.says ?? []).filter((l: J) => l?.says).map((l: J) => ` ${speaker(l.who)}: ${l.says}`)].join("\n")).join("\n");+}+/** Lines read back into a story, with everything wrong in them: a line that doesn't parse, then fromData's errors. */export function fromLines(text: string): { story: AnyStory | null; errors: DataError[] } {const d: J = { values: {}, facts: {}, agents: {}, world: {}, tellings: {} };diff --git a/sdk/story/src/questions.ts b/sdk/story/src/questions.tsnew file mode 100644index 00000000..48b9468b--- /dev/null+++ b/sdk/story/src/questions.ts@@ -0,0 +1,141 @@+// Story as decisions (docs/story.md, "Story as decisions"): a beat's window as a decision model's state, and typed+// questions about that beat in the Jev / Clef request format (noul: yes or no; choice: one of named options; score:+// an ordered scale), each with its exact answer from the checks, the systems and the lenses. The answers are free+// and exact, so a small model can be trained to give them in one pass with calibrated probabilities (System 1),+// and measured against the slow, exact reading that made them (System 2) and against Clef itself.+//+// questionsAt(story, telling, k, { as: "lines" }) the window as story lines: the world, the state, the beats+// questionsAt(story, telling, k, { as: "script" }) the window as a script a person would write: no structure+import type { World } from "./ecs.ts";+import { analyze, checkWorld, type Finding } from "./checks.ts";+import { beatsOf, eventsOf } from "./load.ts";+import { LENSES } from "./lenses/index.ts";+import { readThrough } from "./lens.ts";+import { scriptOf, toLines } from "./lines.ts";+import type { AnyStory } from "./model.ts";+import { toData } from "./data.ts";+import { stateIn, stateLines } from "./state.ts";+import type { Audience } from "./systems/know.ts";++export type Question =+ | { type: "noul"; instructions: string }+ | { type: "choice"; instructions: string; criteria: Record<string, string> }+ | { type: "score"; instructions: string; criteria: string[] };+export type Answer = boolean | string | number;+export type Asked = { state: string; questions: Record<string, Question>; answers: Record<string, Answer> };++/** What each check means, as a question a reader of one beat can answer. */+export const CHECK_QUESTIONS: Record<string, string> = {+ turns: "Does this beat change nothing: no value moves, nothing is learned (a non-event)?",+ "and-then": "Does this beat only follow the one before ('and then') instead of being caused by it ('therefore') or turning it ('but')?",+ surprise: "Is this beat a big turn whose causes the audience never saw, with nothing set up for it?",+ cause: "Does something happen here whose cause the story never shows?",+ "dead-end": "Is this an event that leads nowhere: nothing later follows from it?",+ setup: "Is something set up here that is never paid off, or paid off here without having been set up?",+ belief: "Does a character act here on something they can't know yet?",+ rhythm: "Is this beat the end of a long run of beats that all turn the same way?",+ arc: "Does a character's arc break here (a need met with no change, a lie never faced)?",+ claim: "Is a claim made here that the story never shows proof of?",+ idea: "Does the story's controlling idea go unargued here (no beat on its value, or the counter-idea unvoiced)?",+};+const TENSION = ["none", "low", "some", "high", "peak"];++/** The beat a finding is about: a beat key, or the first beat to show the event it names. */+function beatOfFinding(w: World, f: Finding): number {+ const beats = beatsOf(w);+ const at = beats.findIndex((b) => b.key === f.about);+ return at >= 0 ? at : beats.findIndex((b) => b.beat.shows.includes(f.about));+}++/** Every finding (error or warn) by beat index: computed once per telling, read by every window. */+export function findingsByBeat(w: World): Map<number, Set<string>> {+ const out = new Map<number, Set<string>>();+ for (const f of checkWorld(w)) {+ if (f.level === "note") continue;+ const k = beatOfFinding(w, f);+ if (k >= 0) (out.get(k) ?? out.set(k, new Set()).get(k)!).add(f.check);+ }+ return out;+}++/** Each lens's stage for each beat index (the first stage whose map holds it). */+function stagesByBeat(s: AnyStory, telling: string, lenses: string[], seed: number): Record<string, Record<number, string>> {+ const known = lenses.map((n) => LENSES[n]).filter(Boolean);+ const w = analyze(s, telling, seed);+ const idx = new Map(beatsOf(w).map((b) => [b.key, b.index]));+ return Object.fromEntries(readThrough(s, known, telling, seed).map((r) => {+ const by: Record<number, string> = {};+ for (const [stage, keys] of Object.entries(r.map)) for (const key of keys) { const i = idx.get(key); if (i !== undefined && by[i] === undefined) by[i] = stage; }+ return [r.lens, by];+ }));+}++export type AskOptions = { as?: "lines" | "script"; before?: number; after?: number; lenses?: string[]; seed?: number; maxEvents?: number };++/** A reusable reader for one telling: the analysis, findings and lens stages computed once, then any beat's window. */+export function asker(s: AnyStory | Record<string, any>, telling: string, o: AskOptions = {}) {+ const story = ((s as AnyStory).kind === "story" ? s : { ...s, kind: "story" }) as AnyStory;+ const seed = o.seed ?? 0;+ const d = toData(story, seed) as Record<string, any>;+ const w = analyze(story, telling, seed);+ const found = findingsByBeat(w);+ const lenses = o.lenses ?? ["mckee", "pixar", "campbell"];+ const stages = stagesByBeat(story, telling, lenses, seed);+ const beats = beatsOf(w);+ const raw: any[] = d.tellings[telling];+ const events = eventsOf(w).sort((a, b) => a.order - b.order);++ return (k: number, as: "lines" | "script" = o.as ?? "lines"): Asked => {+ 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);+ // events a reader could name: the ones still ahead and the ones the window shows, in story order+ const inWindow = new Set(near.flatMap((b) => b.shows ?? []));+ const usable = events.filter((e) => inWindow.has(e.key) || st.ahead.includes(e.key)).slice(0, o.maxEvents ?? 40);+ let state: string;+ if (as === "lines") {+ const world = Object.fromEntries(usable.map((e) => [e.key, d.world[e.key]]));+ const head = toLines({ ...d, world, tellings: {} }).split("\n").filter((l) => !l.startsWith("TELLING"));+ const beatLines = toLines({ values: {}, agents: {}, world: {}, tellings: { t: near } }).split("\n").filter((l) => !l.startsWith("TELLING"));+ state = [...head, stateLines(st), `BEATS ${from + 1} to ${from + near.length} of ${raw.length}`, ...beatLines, `LOOK AT beat ${k + 1}`].join("\n");+ } else {+ state = [`A script, beats ${from + 1} to ${from + near.length} of ${raw.length}.`, scriptOf(near, from), `LOOK AT beat ${k + 1}`].join("\n");+ }+ const b = beats[k], beat = b.beat;+ const n = k + 1;+ const questions: Record<string, Question> = {};+ const answers: Record<string, Answer> = {};+ const has = found.get(k) ?? new Set<string>();+ for (const [check, q] of Object.entries(CHECK_QUESTIONS)) { questions[`breaks.${check}`] = { type: "noul", instructions: `Beat ${n}: ${q}` }; answers[`breaks.${check}`] = has.has(check); }++ const criteria: Record<string, string> = { none: "no event: a title, a breath, a beat of narration" };+ for (const e of usable) criteria[e.key] = `${e.ev.who}: ${e.ev.does}`;+ questions.shows = { type: "choice", instructions: `Which event does beat ${n} show first?`, criteria };+ answers.shows = beat.shows[0] && criteria[beat.shows[0]] ? beat.shows[0] : "none";++ const turns = Object.values(w.get<Record<string, number>>(b.e, "Turns") ?? {}).reduce((a, x) => a + x, 0);+ questions.turn = { type: "choice", instructions: `Taken together, which way does beat ${n} turn the story's values?`, criteria: { down: "worse for the hero: a loss, a threat, a no", none: "neither way", up: "better for the hero: a gain, a yes, relief" } };+ answers.turn = turns < 0 ? "down" : turns > 0 ? "up" : "none";+ questions.continues = { type: "noul", instructions: `Does beat ${n} continue the very event the beat before it showed (another shot of the same moment)?` };+ answers.continues = (w.get<string[]>(b.e, "Continues") ?? []).length > 0;+ const a = w.must<Audience>(b.e, "Audience");+ questions.learns = { type: "noul", instructions: `Does the audience learn a new fact in beat ${n}?` };+ answers.learns = a.learned.length > 0;+ questions.opens = { type: "noul", instructions: `Does beat ${n} open a question the audience now waits to have answered?` };+ answers.opens = (beat.asks ?? []).some((f: string) => a.open.includes(f));+ questions.tension = { type: "score", instructions: `How much tension does the audience feel at beat ${n}?`, criteria: TENSION };+ answers.tension = Math.min(4, Math.round((w.get<number>(b.e, "Tension") ?? 0) * 4));+ for (const l of lenses) {+ const lens = LENSES[l];+ if (!lens) continue;+ const crit: Record<string, string> = { none: "no stage of this framework" };+ for (const st2 of lens.stages) crit[st2] = st2;+ questions[`stage.${l}`] = { type: "choice", instructions: `Read as ${l} (${lens.about.replace(/\.$/, "")}): which stage is beat ${n}?`, criteria: crit };+ answers[`stage.${l}`] = stages[l]?.[k] ?? "none";+ }+ return { state, questions, answers };+ };+}++export const questionsAt = (s: AnyStory, telling: string, k: number, o: AskOptions = {}): Asked => asker(s, telling, o)(k, o.as);+