Skip to content

armgit / raea

Public Imported from GitHub
0

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

ST6b: models/validate.ts: a held-out story (another author's, for a film of their own) through the checks, every lens, and rows in the models' format for predict, frontier, onnx and score. ST3b: a beat's meant: [checks] takes those findings about it out of what checks and lenses report (a breather the journey wants, where McKee would flag it); models/lib.ts holds what rows.ts and validate.ts share.

shinyobjectz212186d90782
diff --git a/sdk/story/models/lib.ts b/sdk/story/models/lib.ts
new file mode 100644
index 00000000..8d83bc96
--- /dev/null
+++ b/sdk/story/models/lib.ts
@@ -0,0 +1,41 @@
+// 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, type AnyStory } from "../src/index.ts";
+
+type J = Record<string, any>;
+
+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 withTelling = (s: J, beats: J[]): J => ({ ...s, tellings: { main: beats } });
+export const breaks = (s: J, beats: J[]) => {
+ const st = fromData(withTelling(s, beats)).story as AnyStory;
+ const keys = beats.map((b, i) => b.id ?? `b${i}`);
+ const firstShowing = (ev: string) => beats.findIndex((b) => (b.shows ?? []).includes(ev));
+ return checkStory(st, "main")
+ .filter((f) => f.level !== "note")
+ .map((f) => {
+ let beat: number | null = keys.indexOf(f.about);
+ if (beat < 0) beat = s.world?.[f.about] ? firstShowing(f.about) : -1;
+ return { beat: beat >= 0 ? beat + 1 : null, check: f.check, level: f.level };
+ })
+ .sort((a, b) => (a.beat ?? 0) - (b.beat ?? 0) || a.check.localeCompare(b.check));
+};
+
+/** The story as the extractor answers it: everything but the words on screen. */
+export const bare = (s: J): J => ({
+ ...(s.title ? { title: s.title } : {}),
+ ...(s.idea ? { idea: s.idea } : {}),
+ values: s.values, facts: s.facts ?? {}, agents: s.agents, world: s.world,
+ tellings: { main: s.tellings.main.map(({ onScreen: _o, says: _s, id: _i, ...b }: J) => b) },
+});
+
+export const CHECKS = ["turns", "and-then", "surprise", "cause", "dead-end", "setup", "belief", "rhythm", "arc", "claim", "idea"];
+export const criticSchema = {
+ type: "object", additionalProperties: false, required: ["breaks"],
+ properties: { breaks: { type: "array", items: { type: "object", additionalProperties: false, required: ["beat", "check", "level"], properties: { beat: { anyOf: [{ type: "integer", minimum: 1 }, { type: "null" }] }, check: { type: "string", enum: CHECKS }, level: { type: "string", enum: ["error", "warn"] } } } } },
+};
diff --git a/sdk/story/models/rows.ts b/sdk/story/models/rows.ts
index 54649352..df0cce4d 100644
--- a/sdk/story/models/rows.ts
+++ b/sdk/story/models/rows.ts
@@ -11,7 +11,8 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
-import { beatSchema, checkStory, fromData, rng, storySchema, type AnyStory } from "../src/index.ts";
+import { beatSchema, rng, storySchema } from "../src/index.ts";
+import { bare, breaks, criticSchema, name, prose } 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,36 +25,6 @@ const stories: { i: number; s: J; premise: J }[] = readFileSync(join(IN, "storie
/** The split a story falls in, by its index. */
export const split = (i: number) => { const h = (Math.imul(i + 1, 2654435761) >>> 0) % 10; return h === 0 ? "test" : h === 1 ? "val" : "train"; };
-const name = (k: string) => (k === "narrator" ? "NARRATOR" : k.replace(/([a-z])([A-Z])/g, "$1 $2").toUpperCase());
-
-/** A telling as a script a person would write: numbered beats, what's seen, who says what. No keys, no annotations. */
-export function prose(beats: J[]): string {
- return beats.map((b, n) => [`${n + 1}. ${b.onScreen ?? ""}`.trimEnd(), ...(b.says ?? []).map((l: J) => ` ${name(l.who)}: ${l.says}`)].join("\n")).join("\n");
-}
-
-const withTelling = (s: J, beats: J[]): J => ({ ...s, tellings: { main: beats } });
-const breaks = (s: J, beats: J[]) => {
- const st = fromData(withTelling(s, beats)).story as AnyStory;
- const keys = beats.map((b, i) => b.id ?? `b${i}`);
- const firstShowing = (ev: string) => beats.findIndex((b) => (b.shows ?? []).includes(ev));
- return checkStory(st, "main")
- .filter((f) => f.level !== "note")
- .map((f) => {
- let beat: number | null = keys.indexOf(f.about);
- if (beat < 0) beat = s.world?.[f.about] ? firstShowing(f.about) : -1;
- return { beat: beat >= 0 ? beat + 1 : null, check: f.check, level: f.level };
- })
- .sort((a, b) => (a.beat ?? 0) - (b.beat ?? 0) || a.check.localeCompare(b.check));
-};
-
-/** The story as the extractor answers it: everything but the words on screen. */
-const bare = (s: J): J => ({
- ...(s.title ? { title: s.title } : {}),
- ...(s.idea ? { idea: s.idea } : {}),
- values: s.values, facts: s.facts ?? {}, agents: s.agents, world: s.world,
- tellings: { main: s.tellings.main.map(({ onScreen: _o, says: _s, id: _i, ...b }: J) => b) },
-});
-
const out: Record<string, Record<string, J[]>> = { extract: {}, generate: {}, critic: {} };
const push = (task: string, sp: string, row: J) => ((out[task][sp] ??= []).push(row));
let clean = 0, broken = 0;
@@ -100,11 +71,6 @@ for (const { i, s } of stories) {
}
}
-const CHECKS = ["turns", "and-then", "surprise", "cause", "dead-end", "setup", "belief", "rhythm", "arc", "claim", "idea"];
-const criticSchema = {
- type: "object", additionalProperties: false, required: ["breaks"],
- properties: { breaks: { type: "array", items: { type: "object", additionalProperties: false, required: ["beat", "check", "level"], properties: { beat: { anyOf: [{ type: "integer", minimum: 1 }, { type: "null" }] }, check: { type: "string", enum: CHECKS }, level: { type: "string", enum: ["error", "warn"] } } } } },
-};
writeFileSync(join(OUT, "schemas.json"), JSON.stringify({ extract: storySchema(), critic: criticSchema }, null, 1));
for (const [task, sps] of Object.entries(out)) {
mkdirSync(join(OUT, task), { recursive: true });
diff --git a/sdk/story/models/validate.ts b/sdk/story/models/validate.ts
new file mode 100644
index 00000000..0e62ae6a
--- /dev/null
+++ b/sdk/story/models/validate.ts
@@ -0,0 +1,53 @@
+// A held-out story through the whole stack (docs/story.feature ST6b): a story none of the models, lenses or checks were
+// built on, written by someone else for a film of their own. It prints what the exact checks and every lens find,
+// then writes rows in the models' own format so story_models.py (predict, frontier, onnx) and score.ts run on it as on
+// the corpus's test split:
+// extract the telling as prose -> the story (scored against the author's own story)
+// generate each beat cut in turn -> the beat the model writes (does the story still hold?)
+// critic the telling as written, then each beat cut and each pair of neighbours swapped, labelled exactly
+//
+// bun models/validate.ts FILE.story.ts [--telling NAME] [--name NAME] [--out ~/.vd/story/validate]
+// (a story module that imports raea/story by name needs a tsconfig mapping it: bun --tsconfig-override ...)
+import { copyFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { basename, join, resolve } from "node:path";
+import { beatSchema, checkStory, LENSES, readThrough, toData, type AnyStory } from "../src/index.ts";
+import { bare, breaks, prose } 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; };
+const FILE = resolve(process.argv[2] ?? "");
+const story: AnyStory = (await import(FILE)).default;
+const TELLING = arg("--telling") ?? Object.keys(story.tellings)[0];
+const NAME = arg("--name") ?? basename(FILE).replace(/\.story\.ts$/, "");
+const OUT = join(arg("--out", join(homedir(), ".vd/story/validate"))!.replace(/^~/, homedir()), NAME);
+
+// the story as data with its telling as "main", the corpus's shape
+const d = toData(story) as J;
+const beats: J[] = d.tellings[TELLING];
+const s: J = { ...d, tellings: { main: beats } };
+
+console.log(`${d.title ?? NAME}: ${Object.keys(d.world).length} events, ${beats.length} beats in "${TELLING}", ${Object.keys(d.agents).length} agents, ${Object.keys(d.values).length} values`);
+const exact = checkStory(story, TELLING);
+console.log(`exact checks: ${exact.length} (${exact.filter((f) => f.level === "error").length} errors)`);
+for (const f of exact) console.log(` ${f.level.padEnd(5)} ${f.check.padEnd(10)} ${f.about}: ${f.says}`);
+for (const r of readThrough(story, Object.values(LENSES), TELLING)) {
+ const bad = r.findings.filter((f) => f.level !== "note");
+ console.log(`lens ${r.lens.padEnd(14)} ${r.passes ? "passes" : "FAILS "} ${bad.map((f) => `${f.check}@${f.about}`).join(" ")}`);
+}
+
+mkdirSync(OUT, { recursive: true });
+for (const t of ["extract", "generate", "critic"]) mkdirSync(join(OUT, t), { recursive: true });
+const rowsDir = join(homedir(), ".vd/story/rows");
+if (existsSync(join(rowsDir, "schemas.json"))) copyFileSync(join(rowsDir, "schemas.json"), join(OUT, "schemas.json"));
+const write = (task: string, rows: J[]) => writeFileSync(join(OUT, task, `${NAME}.jsonl`), rows.map((r) => JSON.stringify(r)).join("\n") + "\n");
+
+write("extract", [{ i: 0, kind: "script", prompt: prose(beats), answer: JSON.stringify(bare(s)) }]);
+write("generate", beats.map((b, k) => ({ i: 0, at: k, prompt: JSON.stringify({ story: { ...s, tellings: { main: beats.filter((_, n) => n !== k) } }, write: `the beat that goes at place ${k + 1} of ${beats.length}` }), answer: JSON.stringify(b), schema: beatSchema(s) })));
+const critic: J[] = [{ i: 0, kind: "clean", prompt: prose(beats), answer: JSON.stringify({ breaks: breaks(s, beats) }) }];
+beats.forEach((_, k) => { const b2 = beats.filter((_, n) => n !== k); critic.push({ i: 0, kind: `cut${k + 1}`, prompt: prose(b2), answer: JSON.stringify({ breaks: breaks(s, b2) }) }); });
+beats.slice(0, -1).forEach((_, k) => { const b2 = [...beats]; [b2[k], b2[k + 1]] = [b2[k + 1], b2[k]]; critic.push({ i: 0, kind: `swap${k + 1}`, prompt: prose(b2), answer: JSON.stringify({ breaks: breaks(s, b2) }) }); });
+write("critic", critic);
+const broken = critic.filter((r) => JSON.parse(r.answer).breaks.length).length;
+console.log(`rows -> ${OUT}: extract 1, generate ${beats.length}, critic ${critic.length} (${broken} with a break, ${critic.length - broken} clean)`);
+console.log(`next: python story_models.py predict TASK --rows ${OUT} --split ${NAME} --adapter ...; bun models/score.ts TASK --rows ${OUT} --split ${NAME}`);
diff --git a/sdk/story/src/checks.ts b/sdk/story/src/checks.ts
index 4322d82b..d9ab8b6a 100644
--- a/sdk/story/src/checks.ts
+++ b/sdk/story/src/checks.ts
@@ -19,6 +19,12 @@ export const analyze = (s: AnyStory, telling?: string, seed = 0): World => deriv
const RUN = 4; // beats in a row all turning one way before it's worth a note
+/** Findings left once every beat's `meant` is taken out: a check a beat says it means, about that beat. */
+export function unmeant(w: World, found: Finding[]): Finding[] {
+ const meant = new Map(beatsOf(w).map(({ key, beat }) => [key, new Set(listOf(beat.meant))]));
+ return found.filter((f) => !meant.get(f.about)?.has(f.check));
+}
+
export function checkWorld(w: World): Finding[] {
const out: Finding[] = [];
const add = (check: string, level: Level, about: string, says: string, fix?: string) => out.push({ check, level, about, says, fix });
@@ -89,7 +95,7 @@ export function checkWorld(w: World): Finding[] {
const focus = infoOf(w).idea?.value;
const curves = w.resource<Record<string, Curve>>("Curves") ?? {};
if (focus && curves[focus]?.shape === "flat") add("idea", "warn", focus, `the story is about ${focus}, and ${focus} never moves`, "turn it in the beats that matter");
- return out;
+ return unmeant(w, out);
}
/** Check a story told one way: its findings, errors first. */
diff --git a/sdk/story/src/data.ts b/sdk/story/src/data.ts
index 1c0bf6a9..cafcdd3a 100644
--- a/sdk/story/src/data.ts
+++ b/sdk/story/src/data.ts
@@ -43,6 +43,7 @@ export function beatShape(k: { events?: string[]; facts?: string[]; agents?: str
pays: oneOrMany(k.setups?.length ? enumOf(k.setups) : str),
stage: { type: "object", additionalProperties: str },
surprise: { type: "string", enum: ["meant"] },
+ meant: oneOrMany(str),
says: listOf({ type: "object", additionalProperties: false, required: ["who", "says"], properties: { who, says: str, means: str, how: str } }),
onScreen: str,
seconds: { type: "number" },
diff --git a/sdk/story/src/index.ts b/sdk/story/src/index.ts
index 76c68079..ec0c4cc1 100644
--- a/sdk/story/src/index.ts
+++ b/sdk/story/src/index.ts
@@ -8,7 +8,7 @@ export { values, shapeOf, type Curve, type Shape } from "./systems/values.ts";
export { knowledge, type Audience, type Break } from "./systems/know.ts";
export { causes, type Causes } from "./systems/cause.ts";
export { tension } from "./systems/tension.ts";
-export { analyze, derive, checkStory, checkWorld, type Finding, type Level } from "./checks.ts";
+export { analyze, derive, checkStory, checkWorld, unmeant, type Finding, type Level } from "./checks.ts";
export { mutants, sampleMutants, type Mutant, type Label, type Kind } from "./mutate.ts";
export { lens, readThrough, structure, labelled, type Lens, type LensResult, type Proposal, type Reading, type StageMap, type Structure } from "./lens.ts";
export { LENSES, bernays, campbell, harmon, kishotenketsu, mckee, pas, pixar, propp, saveTheCat, storynomics, vogler } from "./lenses/index.ts";
diff --git a/sdk/story/src/lens.ts b/sdk/story/src/lens.ts
index f6dc732c..014c14d0 100644
--- a/sdk/story/src/lens.ts
+++ b/sdk/story/src/lens.ts
@@ -4,7 +4,7 @@
// The inference here is shared: the protagonist, the brand, the idea's value, the inciting event, the crisis, the
// climax. It reads only derived data and the story's own fields, never prose.
import type { World } from "./ecs.ts";
-import { analyze, type Finding, type Level } from "./checks.ts";
+import { analyze, unmeant, type Finding, type Level } from "./checks.ts";
import { beatsOf, eventsOf, infoOf, keysOf, type RAgent, type RBeat, type REvent } from "./load.ts";
import type { AnyStory } from "./model.ts";
@@ -110,7 +110,8 @@ export function readThrough(s: AnyStory, lenses: Lens[], telling?: string, seed
const w = analyze(s, telling, seed);
const st = structure(w);
return lenses.map((l) => {
- const r = l.read(w, st);
+ const r0 = l.read(w, st);
+ const r = { ...r0, findings: unmeant(w, r0.findings) };
const own = labelled(st, l.name);
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/model.ts b/sdk/story/src/model.ts
index ffa9428c..61a5e8cf 100644
--- a/sdk/story/src/model.ts
+++ b/sdk/story/src/model.ts
@@ -97,6 +97,9 @@ export type Beat<F extends string, A extends string, E extends string, S extends
stage?: Record<string, string>;
/** a surprise the story means (a reveal nothing set up) */
surprise?: "meant";
+ /** findings about this beat the story means, by check (\"rhythm\", \"mckee:complications\" for a breather the
+ * journey wants): they're left out of what checks and lenses report */
+ meant?: string | string[];
says?: Line<A>[];
/** what's on screen, when it says more than the events' `does` */
onScreen?: Maybe<string>;
diff --git a/sdk/story/src/sample.ts b/sdk/story/src/sample.ts
index 679d8f7d..3319af62 100644
--- a/sdk/story/src/sample.ts
+++ b/sdk/story/src/sample.ts
@@ -2,7 +2,7 @@
// picks one. sample() walks seeds from the one given until a story passes (no finding at the level refused, in the
// exact checks and in every lens given), so a sampled story is always one that holds together. samples() gives several
// different ones. matrix() runs one story pattern across many premises and says, per premise, how often it holds.
-import { checkWorld, analyze, type Finding, type Level } from "./checks.ts";
+import { checkWorld, analyze, unmeant, type Finding, type Level } from "./checks.ts";
import { structure, type Lens } from "./lens.ts";
import type { AnyStory } from "./model.ts";
import { resolve } from "./resolve.ts";
@@ -16,7 +16,7 @@ const ranks: Record<Level, number> = { error: 0, warn: 1, note: 2 };
export function judge(s: AnyStory, seed: number, telling?: string, lenses: Lens[] = []): Finding[] {
const w = analyze(s, telling, seed);
const st = structure(w);
- return [...checkWorld(w), ...lenses.flatMap((l) => l.read(w, st).findings)];
+ return [...checkWorld(w), ...unmeant(w, lenses.flatMap((l) => l.read(w, st).findings))];
}
/** One story from the space that passes, starting at `seed`; the best found when none passes in `tries`. */
diff --git a/sdk/story/test/lenses.test.ts b/sdk/story/test/lenses.test.ts
index ca7c2f03..c471ed90 100644
--- a/sdk/story/test/lenses.test.ts
+++ b/sdk/story/test/lenses.test.ts
@@ -70,3 +70,13 @@ test("shots of one event count its turn once", () => {
expect(found.filter((f) => f.check === "turns")).toEqual([]);
expect(found.filter((f) => f.check === "rhythm")).toEqual([]);
});
+
+test("a beat can mean a finding: a breather the journey wants", () => {
+ const t = launch.tellings["30s"] as any[];
+ const world = { ...launch.world, tries: { ...launch.world.tries, turns: {} } };
+ const noisy = { ...launch, world };
+ const before = checkStory(noisy as typeof launch, "30s").filter((f) => f.about === "b2");
+ expect(before.length).toBeGreaterThan(0);
+ const meant = { ...launch, world, tellings: { "30s": [t[0], t[1], { ...t[2], meant: before.map((f) => f.check) }, t[3]] } };
+ expect(checkStory(meant as typeof launch, "30s").filter((f) => f.about === "b2")).toEqual([]);
+});