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.

ST3a: lenses (McKee, the Pixar spine, Storynomics, PAS), seeded sampling with a theme matrix, and compilers to Script, storylets, Ink and Yarn

shinyobjectz79e8ac7af913
diff --git a/docs/story.feature b/docs/story.feature
index 0d159bed..666f2a66 100644
--- a/docs/story.feature
+++ b/docs/story.feature
@@ -91,6 +91,15 @@ Feature: Story: a story as ECS data, read through many frameworks, generated wit
When a story is read through each
Then each says which beats play its stages, what's missing or out of order, and proposes beats for what's missing
And a story read through every lens says which it passes
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/lens.ts | 200 | the lens shape, the shared structure (hero, brand, inciting, crisis, climax), readThrough |
+ | sdk | sdk/story/src/lenses/index.ts | 40 | the shipped lenses by name |
+ | sdk | sdk/story/src/lenses/mckee.ts | 120 | inciting, complications, crisis, climax, resolution |
+ | sdk | sdk/story/src/lenses/pixar.ts | 120 | the story spine |
+ | sdk | sdk/story/src/lenses/storynomics.ts | 120 | the customer as hero, the brand as mentor or gift |
+ | sdk | sdk/story/src/lenses/pas.ts | 120 | problem, agitate, solve |
+ | sdk | sdk/story/test/lenses.test.ts | 150 | the launch story passes; a brand-hero fails; a crisis proposed |
Scenario: ST3b. The rest of the frameworks
Given campbell, vogler, harmon, save-the-cat, kishotenketsu, propp and bernays as lenses
@@ -104,6 +113,10 @@ Feature: Story: a story as ECS data, read through many frameworks, generated wit
When it's sampled with a seed
Then the same seed gives the same story, a new seed may give another, and no sampled story fails an exact check
And a theme matrix runs one story pattern across many premises and says where it breaks
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/sample.ts | 160 | sample, samples, matrix, judge |
+ | sdk | sdk/story/test/sample.test.ts | 150 | sampled stories pass; the matrix; compilers |
Rule: ST5. Into raea check, scripts and games
@@ -118,6 +131,9 @@ Feature: Story: a story as ECS data, read through many frameworks, generated wit
And compileStorylets gives preconditions and effects over facts, with a drama manager that picks the next storylet
to keep a target tension curve
And dialogue lines carry what's said, what's meant, and the value they turn
+ And the plan:
+ | crate | file | lines | job |
+ | sdk | sdk/story/src/compile.ts | 200 | Script, storylets and a drama manager, Ink and Yarn |
Rule: ST6. Story models: small, on-device, schema-native
diff --git a/sdk/story/src/compile.ts b/sdk/story/src/compile.ts
new file mode 100644
index 00000000..7783447d
--- /dev/null
+++ b/sdk/story/src/compile.ts
@@ -0,0 +1,86 @@
+// Compilers (docs/story.feature ST5b): a telling into raea/brief's Script (the screenplay and A/V table the feed shows),
+// the world into storylets with a drama manager for a game, and a telling's lines into Ink and Yarn Spinner.
+import type { Script } from "raea/brief";
+import { analyze } from "./checks.ts";
+import { beatsOf, infoOf, resolved, type RBeat } from "./load.ts";
+import { causesOf, listOf, type AnyStory } from "./model.ts";
+import { rng } from "./resolve.ts";
+import type { Audience } from "./systems/know.ts";
+
+type ScriptBeat = Script["scenes"][number]["beats"][number];
+
+/** What a beat shows, in words: its own onScreen, else its events' `does`. */
+export const onScreenOf = (s: AnyStory, b: RBeat, seed = 0): string =>
+ (b.onScreen as string | undefined) ?? b.shows.map((k) => resolved(s, seed).world[k]?.does as string).filter(Boolean).join(". ");
+
+/** A telling as a Script: a scene a beat, its heading the beat's place and feeling, its payoff what it pays or answers. */
+export function compileScript(s: AnyStory, telling?: string, seed = 0): Script & { beats: string[] } {
+ const w = analyze(s, telling, seed);
+ const info = infoOf(w);
+ const scenes = beatsOf(w).map(({ e, key, beat }) => {
+ const a = w.must<Audience>(e, "Audience");
+ const lines = (beat.says ?? []).map((l) => ({ who: l.who, says: l.says as string, ...(l.how ? { how: l.how } : {}) }));
+ const b: ScriptBeat = { onScreen: onScreenOf(s, beat, seed), ...(lines.length ? { lines } : {}), ...(beat.seconds ? { seconds: beat.seconds } : {}) };
+ const pays = listOf(beat.pays), answered = a.answered;
+ const payoff = [...pays.map((p) => `pays off ${p}`), ...answered.map((f) => `answers ${f}`)].join("; ");
+ return { heading: `${key.toUpperCase()}${beat.feel ? ` · ${beat.feel}` : ""}`, beats: [b], ...(payoff ? { payoff } : {}) };
+ });
+ return { title: info.title ?? "Untitled", ...(info.premise ? { logline: info.premise } : {}), scenes, beats: beatsOf(w).map((b) => b.key) };
+}
+
+export type Storylet = { id: string; who: string; does: string; after: string[]; needs: string[]; sets: string[]; unsets: string[]; weight: number };
+
+/** The world as storylets: each event playable once its causes have played and its agent holds what it needs. */
+export function compileStorylets(s: AnyStory, seed = 0): Storylet[] {
+ const r = resolved(s, seed);
+ return Object.entries(r.world).map(([id, ev]) => ({
+ id, who: ev.who, does: ev.does as string, after: causesOf(ev), needs: ev.needs ?? [], sets: ev.sets ?? [], unsets: ev.unsets ?? [],
+ weight: Object.values(ev.turns ?? {}).reduce<number>((a, d) => a + Math.abs(d ?? 0), 0),
+ }));
+}
+
+/** A drama manager: plays storylets one at a time, each step choosing among those available the one whose weight is
+ * nearest the target curve's next point (a target of 0 to 1 against the heaviest storylet), ties broken by the seed. */
+export function dramaManager(storylets: Storylet[], target: number[], seed = 0): string[] {
+ const done = new Set<string>(), facts = new Set<string>();
+ const heaviest = Math.max(1, ...storylets.map((x) => x.weight));
+ const r = rng(seed);
+ const played: string[] = [];
+ for (let step = 0; played.length < storylets.length; step++) {
+ const open = storylets.filter((x) => !done.has(x.id) && x.after.every((a) => done.has(a)) && x.needs.every((f) => facts.has(f)));
+ if (!open.length) break;
+ const want = (target[Math.min(step, target.length - 1)] ?? 0.5) * heaviest;
+ const best = open.map((x) => ({ x, d: Math.abs(x.weight - want) + r() * 1e-6 })).sort((a, b) => a.d - b.d)[0].x;
+ done.add(best.id); played.push(best.id);
+ for (const f of best.sets) facts.add(f);
+ for (const f of best.unsets) facts.delete(f);
+ }
+ return played;
+}
+
+/** A telling's lines as Ink: a knot a beat, each line `who: says`, subtext as a comment. */
+export function toInk(s: AnyStory, telling?: string, seed = 0): string {
+ const w = analyze(s, telling, seed);
+ const out: string[] = [];
+ const bs = beatsOf(w);
+ bs.forEach(({ key, beat }, i) => {
+ out.push(`=== ${key} ===`);
+ if (beat.feel) out.push(`// feel: ${beat.feel}`);
+ out.push(onScreenOf(s, beat, seed) ? `// ${onScreenOf(s, beat, seed)}` : "");
+ for (const l of beat.says ?? []) out.push(`${l.who}: ${l.says as string}${l.means ? ` // means: ${l.means}` : ""}`);
+ out.push(i + 1 < bs.length ? `-> ${bs[i + 1].key}` : "-> END", "");
+ });
+ return out.filter((l, i, a) => !(l === "" && a[i - 1] === "")).join("\n");
+}
+
+/** A telling's lines as Yarn Spinner nodes. */
+export function toYarn(s: AnyStory, telling?: string, seed = 0): string {
+ const w = analyze(s, telling, seed);
+ const bs = beatsOf(w);
+ return bs.map(({ key, beat }, i) => [
+ `title: ${key}`, ...(beat.feel ? [`tags: ${String(beat.feel).replace(/\s+/g, "-")}`] : []), "---",
+ ...(beat.says ?? []).map((l) => `${l.who}: ${l.says as string}${l.means ? ` // means: ${l.means}` : ""}`),
+ ...(i + 1 < bs.length ? [`<<jump ${bs[i + 1].key}>>`] : []), "===",
+ ].join("\n")).join("\n");
+}
+
diff --git a/sdk/story/src/index.ts b/sdk/story/src/index.ts
index 98f27a9e..06d4804e 100644
--- a/sdk/story/src/index.ts
+++ b/sdk/story/src/index.ts
@@ -10,3 +10,8 @@ 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 { 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, mckee, pas, pixar, storynomics } from "./lenses/index.ts";
+export { sample, samples, matrix, judge, type Sampled, type SampleOptions, type MatrixResult, type MatrixRow } from "./sample.ts";
+export { compileScript, compileStorylets, dramaManager, toInk, toYarn, onScreenOf, type Storylet } from "./compile.ts";
+export { resolved, type RStory } from "./load.ts";
diff --git a/sdk/story/src/lens.ts b/sdk/story/src/lens.ts
new file mode 100644
index 00000000..4e172f5a
--- /dev/null
+++ b/sdk/story/src/lens.ts
@@ -0,0 +1,79 @@
+// Lenses (docs/story.feature ST3a): a framework as code. A lens reads a derived world: it maps its stages onto beats (a
+// beat's own `stage` label wins over inference), checks what its framework asks, and proposes beats for stages that are
+// missing. Every lens has the same shape, so a person's or an agency's own format is one more module.
+// 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 { beatsOf, eventsOf, infoOf, keysOf, type RAgent, type RBeat, type REvent } from "./load.ts";
+import type { AnyStory } from "./model.ts";
+
+export type StageMap = Record<string, string[]>;
+export type Proposal = { stage: string; after?: string; onScreen: string; feel?: string; why: string };
+export type Reading = { map: StageMap; findings: Finding[]; proposals: Proposal[] };
+export type Lens = { name: string; about: string; stages: string[]; read: (w: World, s: Structure) => Reading };
+export type LensResult = Reading & { lens: string; passes: boolean };
+
+export const lens = (l: Lens): Lens => l;
+
+/** What every lens reads: the structure inferred once per world. */
+export type Structure = {
+ beats: { key: string; beat: RBeat; index: number; turns: Record<string, number>; tension: number; linked: boolean }[];
+ events: { key: string; ev: REvent; order: number }[];
+ focus: string | undefined;
+ hero: string | undefined;
+ brand: string | undefined;
+ agents: Record<string, RAgent>;
+ inciting: string | undefined;
+ crisis: string | undefined;
+ climax: string | undefined;
+ /** the first beat showing an event, and the last */
+ firstShowing: (event: string | undefined) => string | undefined;
+ lastShowing: (event: string | undefined) => string | undefined;
+ focusTurn: (turns: Record<string, number>) => number;
+};
+
+const size = (t: Partial<Record<string, number>> | undefined) => Object.values(t ?? {}).reduce<number>((a, d) => a + Math.abs(d ?? 0), 0);
+
+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"), 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 }));
+ const agents = Object.fromEntries(Object.entries(keysOf(w).agents).map(([k, e]) => [k, w.must<RAgent>(e, "Agent")]));
+ const hero = Object.keys(agents).find((a) => agents[a].role === "customer" || agents[a].mask === "hero") ?? events[0]?.ev.who;
+ 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;
+ 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;
+ 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 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);
+ return { beats, events, focus, hero, brand, agents, inciting, crisis, climax, firstShowing, lastShowing, focusTurn };
+}
+
+/** A beat's own label for this lens's stage, when it has one. */
+export function labelled(s: Structure, lensName: string): StageMap {
+ const map: StageMap = {};
+ for (const b of s.beats) {
+ const st = b.beat.stage?.[lensName];
+ if (st) (map[st] ??= []).push(b.key);
+ }
+ return map;
+}
+
+export const finding = (check: string, level: Level, about: string, says: string, fix?: string): Finding => ({ check, level, about, says, fix });
+
+/** 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);
+ const st = structure(w);
+ return lenses.map((l) => {
+ const r = l.read(w, st);
+ const own = labelled(st, l.name);
+ const map = { ...r.map, ...own };
+ return { lens: l.name, ...r, map, passes: !r.findings.some((f) => f.level === "error") };
+ });
+}
diff --git a/sdk/story/src/lenses/index.ts b/sdk/story/src/lenses/index.ts
new file mode 100644
index 00000000..0f87ba93
--- /dev/null
+++ b/sdk/story/src/lenses/index.ts
@@ -0,0 +1,9 @@
+// The lenses raea ships, by name (docs/story.feature ST3a, ST3b).
+import type { Lens } from "../lens.ts";
+import { mckee } from "./mckee.ts";
+import { pas } from "./pas.ts";
+import { pixar } from "./pixar.ts";
+import { storynomics } from "./storynomics.ts";
+
+export { mckee, pas, pixar, storynomics };
+export const LENSES: Record<string, Lens> = { mckee, pixar, storynomics, pas };
diff --git a/sdk/story/src/lenses/mckee.ts b/sdk/story/src/lenses/mckee.ts
new file mode 100644
index 00000000..25c3e2e8
--- /dev/null
+++ b/sdk/story/src/lenses/mckee.ts
@@ -0,0 +1,45 @@
+// McKee's lens (Story, 1997): the five parts of a story's design (inciting incident, progressive complications, crisis,
+// climax, resolution), each scene a turn of a value, the crisis a true dilemma, the climax answering what the inciting
+// incident opened. In our words; the stages' names are the book's.
+import { finding, lens, type Proposal } from "../lens.ts";
+import type { Finding } from "../checks.ts";
+
+export const mckee = lens({
+ name: "mckee",
+ about: "Inciting incident, complications that escalate, a crisis that's a real dilemma, a climax that answers it, a resolution.",
+ stages: ["inciting", "complications", "crisis", "climax", "resolution"],
+ read: (_w, s) => {
+ 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 map = {
+ inciting: inc ? [inc] : [],
+ complications: s.beats.filter((b) => b.index > at(inc) && b.index < (cri ? at(cri) : at(cli))).map((b) => b.key),
+ crisis: cri ? [cri] : [],
+ climax: cli ? [cli] : [],
+ resolution: cli ? s.beats.filter((b) => b.index > at(cli)).map((b) => b.key) : [],
+ };
+ const n = s.beats.length;
+ if (!inc) {
+ 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) {
+ 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" });
+ }
+ if (!cli) f.push(finding("mckee:climax", "error", "story", "nothing after the crisis answers it", "show the event the crisis leads to, turning the story's value"));
+ else {
+ const cliBeat = s.beats.find((b) => b.key === cli)!;
+ if (s.focusTurn(cliBeat.turns) === 0) f.push(finding("mckee:climax", "warn", cli, `the climax doesn't turn ${s.focus}, the value the story is about`, `turn ${s.focus} in the climax`));
+ const ev = s.events.find((x) => x.key === s.climax)?.ev;
+ if (ev && s.hero && ev.who !== s.hero && !(ev.with ?? []).includes(s.hero)) f.push(finding("mckee:climax", "warn", cli, `${s.hero} doesn't act in the climax: ${ev.who} does`, `let ${s.hero} make the decisive move`));
+ }
+ 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"));
+ return { map, findings: f, proposals: p };
+ },
+});
diff --git a/sdk/story/src/lenses/pas.ts b/sdk/story/src/lenses/pas.ts
new file mode 100644
index 00000000..b23c6c1c
--- /dev/null
+++ b/sdk/story/src/lenses/pas.ts
@@ -0,0 +1,37 @@
+// Problem, agitate, solve: the ad and launch-video form. The problem is the audience's own, stated early; agitating it
+// makes it cost more; the solve shows the product doing the job, with proof. Its priors (how early, how long) are what
+// the launch lens learns from real outcomes (docs/story.feature ST7a); these are the form's own rules of thumb.
+import { finding, lens, type Proposal } from "../lens.ts";
+import type { Finding } from "../checks.ts";
+
+export const pas = lens({
+ name: "pas",
+ about: "Problem (the audience's own, early), agitate (it costs more), solve (the product doing the job, with proof).",
+ stages: ["problem", "agitate", "solve"],
+ read: (_w, s) => {
+ const f: Finding[] = [];
+ const p: Proposal[] = [];
+ const neg = (t: Record<string, number>) => Object.values(t).some((d) => d < 0);
+ const involves = (b: (typeof s.beats)[number], who: string | undefined) => !!who && b.beat.shows.some((e) => { const ev = s.events.find((x) => x.key === e)?.ev; return ev?.who === who || (ev?.with ?? []).includes(who); });
+ const problemB = s.beats.find((b) => neg(b.turns) && !involves(b, s.brand));
+ const solveB = problemB ? s.beats.find((b) => b.index > problemB.index && s.focusTurn(b.turns) > 0) : undefined;
+ const agitate = problemB ? s.beats.filter((b) => b.index > problemB.index && (!solveB || b.index < solveB.index) && neg(b.turns)) : [];
+ const map = { problem: problemB ? [problemB.key] : [], agitate: agitate.map((b) => b.key), solve: solveB ? [solveB.key] : [] };
+ const n = s.beats.length;
+ if (!problemB) {
+ f.push(finding("pas:problem", "error", "story", "no problem: no beat turns anything down before the product", "open on the cost the audience pays today"));
+ p.push({ stage: "problem", onScreen: `${s.hero ?? "the audience"} paying the cost today: ${s.hero ? s.agents[s.hero]?.want ?? "" : ""}`.trim(), feel: "recognition", why: "the audience has to see their own problem before they want a fix" });
+ } else if (problemB.index > Math.floor(n * 0.4)) f.push(finding("pas:problem", "warn", problemB.key, `the problem arrives at beat ${problemB.index + 1} of ${n}, late for an ad`, "state it in the first beats"));
+ if (problemB && !agitate.length) {
+ f.push(finding("pas:agitate", "note", "story", "the problem is stated but never gets worse", "show what it costs next"));
+ p.push({ stage: "agitate", after: problemB.key, onScreen: "what the problem costs next, if nothing changes", feel: "concern", why: "agitation makes the solve feel earned" });
+ }
+ if (!solveB) f.push(finding("pas:solve", "error", "story", "no solve: nothing turns the problem around", "show the product doing the job"));
+ else {
+ if (!involves(solveB, s.brand)) f.push(finding("pas:solve", "warn", solveB.key, "the solve doesn't show the product", "put the product in the beat that turns things around"));
+ const proven = solveB.beat.shows.some((e) => (s.events.find((x) => x.key === e)?.ev.proof ?? []).length > 0);
+ if (!proven) f.push(finding("pas:proof", "note", solveB.key, "the solve makes no claim backed by a fact", "show proof: a fact the story makes true"));
+ }
+ return { map, findings: f, proposals: p };
+ },
+});
diff --git a/sdk/story/src/lenses/pixar.ts b/sdk/story/src/lenses/pixar.ts
new file mode 100644
index 00000000..b679953c
--- /dev/null
+++ b/sdk/story/src/lenses/pixar.ts
@@ -0,0 +1,35 @@
+// The story spine (Kenn Adams' improv form, which Pixar's story artists use and Emma Coats' rules of storytelling pass
+// on): Once upon a time... Every day... Until one day... Because of that... Because of that... Until finally... And ever
+// since. Its test is a causal chain with no gaps. Pixar's Braintrust (Catmull, Creativity, Inc.) is a review practice,
+// not a structure: candid notes on the problem, never the fix; raea's readers and fingerprint notes play that part.
+import { finding, lens, type Proposal } from "../lens.ts";
+import type { Finding } from "../checks.ts";
+
+export const pixar = lens({
+ name: "pixar",
+ about: "The story spine: once upon a time, every day, until one day, because of that (twice or more), until finally, and ever since.",
+ stages: ["once", "every-day", "one-day", "because", "finally", "ever-since"],
+ read: (_w, s) => {
+ 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 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) : [];
+ const map = { once: s.beats[0] ? [s.beats[0].key] : [], "every-day": routine, "one-day": one ? [one] : [], because, finally: fin ? [fin] : [], "ever-since": ever };
+ if (!routine.length) {
+ f.push(finding("pixar:every-day", "warn", "story", "no 'every day': the audience never sees how things are before they change", "show a routine event (routine: true) before the change"));
+ p.push({ stage: "every-day", after: undefined, onScreen: `${s.hero ?? "the protagonist"}'s ordinary day: ${s.hero ? s.agents[s.hero]?.want ?? "" : ""}`.trim(), feel: "recognition", why: "a change only reads against the normal it breaks" });
+ }
+ if (!one) f.push(finding("pixar:one-day", "error", "story", "no 'until one day': nothing breaks the routine", "add the event that changes everything"));
+ if (because.length < 2) {
+ f.push(finding("pixar:because", "warn", "story", `only ${because.length} 'because of that' between the change and the end`, "add a consequence that leads to the next"));
+ p.push({ stage: "because", after: one, onScreen: "a consequence of the change that forces the next move", feel: "concern", why: "the spine needs a chain of consequences, not one jump" });
+ }
+ for (const b of s.beats) if (b.index > idx(one) && !b.linked) f.push(finding("pixar:because", "error", b.key, `${b.key} breaks the spine: it isn't a consequence of what came before`, "make it follow from an earlier beat"));
+ if (!fin) f.push(finding("pixar:finally", "error", "story", "no 'until finally': the chain never resolves", "show the event the chain leads to"));
+ if (!ever.length) f.push(finding("pixar:ever-since", "note", "story", "no 'and ever since': the new normal isn't shown", "end on how things are now"));
+ return { map, findings: f, proposals: p };
+ },
+});
diff --git a/sdk/story/src/lenses/storynomics.ts b/sdk/story/src/lenses/storynomics.ts
new file mode 100644
index 00000000..05229f2c
--- /dev/null
+++ b/sdk/story/src/lenses/storynomics.ts
@@ -0,0 +1,30 @@
+// Storynomics (McKee and Gerace, 2018): stories told for a brand. The customer is the protagonist; the brand is the
+// mentor or the gift that helps them act, never the hero of its own ad. The story turns a core value of the customer's
+// life from negative to positive, and the customer, not the brand, makes the decisive move. In our words.
+import { finding, lens, type Proposal } from "../lens.ts";
+import type { Finding } from "../checks.ts";
+
+export const storynomics = lens({
+ name: "storynomics",
+ about: "The customer is the hero, the brand the mentor or the gift; a core value of the customer's life turns from negative to positive.",
+ stages: ["at-stake", "the-gift", "the-act", "restored"],
+ read: (w, s) => {
+ const f: Finding[] = [];
+ const p: Proposal[] = [];
+ const customer = Object.keys(s.agents).find((a) => s.agents[a].role === "customer") ?? s.hero;
+ const gift = s.brand ? s.beats.find((b) => b.beat.shows.some((e) => { const ev = s.events.find((x) => x.key === e)?.ev; return ev?.who === s.brand || (ev?.with ?? []).includes(s.brand!); }))?.key : undefined;
+ const act = s.lastShowing(s.climax);
+ const map = { "at-stake": [s.firstShowing(s.inciting)].filter(Boolean) as string[], "the-gift": gift ? [gift] : [], "the-act": act ? [act] : [], restored: s.beats.length ? [s.beats[s.beats.length - 1].key] : [] };
+ if (!customer) f.push(finding("storynomics:customer", "error", "story", "there's no customer: the story is about the brand", "make a customer the protagonist (role: \"customer\")"));
+ if (!s.brand) {
+ f.push(finding("storynomics:brand", "warn", "story", "the brand never appears as mentor or gift", "give the brand an agent (role: \"brand\") that helps the customer act"));
+ p.push({ stage: "the-gift", after: map["at-stake"][0], onScreen: `the brand puts something in ${customer ?? "the customer"}'s hands`, feel: "hope", why: "the brand's role is what it gives, not what it is" });
+ }
+ const climax = s.events.find((x) => x.key === s.climax)?.ev;
+ if (climax && s.brand && climax.who === s.brand) f.push(finding("storynomics:hero", "error", act ?? "story", `the brand (${s.brand}) makes the decisive move, stealing ${customer ?? "the customer"}'s climax`, `let ${customer ?? "the customer"} act, with the brand alongside (with: ["${s.brand}"])`));
+ const curves = w.resource<Record<string, { levels: number[] }>>("Curves") ?? {};
+ const lv = s.focus ? curves[s.focus]?.levels.slice(1) ?? [] : [];
+ if (lv.length && !(lv[lv.length - 1] > Math.min(...lv))) f.push(finding("storynomics:value", "error", "story", `${s.focus} doesn't end better than its lowest point`, `end with ${s.focus} turned toward its positive pole`));
+ return { map, findings: f, proposals: p };
+ },
+});
diff --git a/sdk/story/src/load.ts b/sdk/story/src/load.ts
index 98e8d270..14bfcaa7 100644
--- a/sdk/story/src/load.ts
+++ b/sdk/story/src/load.ts
@@ -12,13 +12,17 @@ export type Resolved<T> = T extends { choice: readonly (infer U)[] } ? U : T ext
export type REvent = Resolved<Event<string, string, string, string>>;
export type RBeat = Resolved<Beat<string, string, string, string>>;
export type RAgent = Agent<string>;
+/** A story with every choice point picked: plain beats and events throughout. */
+export type RStory = Omit<AnyStory, "tellings" | "world"> & { tellings: Record<string, RBeat[]>; world: Record<string, REvent> };
+/** The story resolved for this seed, typed as plain data. */
+export const resolved = (s: AnyStory, seed = 0): RStory => resolve(s, seed) as unknown as RStory;
export type Keys = { values: Record<string, Entity>; facts: Record<string, Entity>; agents: Record<string, Entity>; events: Record<string, Entity>; beats: Entity[] };
export type StoryInfo = { title?: string; premise?: string; idea?: AnyStory["idea"]; lenses: string[]; telling: string };
/** The world of a story told one way. `telling` defaults to the story's first. */
export function load(s: AnyStory, telling?: string, seed = 0): World {
- const r = resolve(s, seed);
+ const r = resolved(s, seed);
const name = telling ?? Object.keys(r.tellings)[0];
const beats = r.tellings[name];
if (!beats) throw new Error(`the story has no telling named ${name} (it has ${Object.keys(r.tellings).join(", ")})`);
diff --git a/sdk/story/src/model.ts b/sdk/story/src/model.ts
index ca6c3fc3..91e6d74c 100644
--- a/sdk/story/src/model.ts
+++ b/sdk/story/src/model.ts
@@ -101,7 +101,9 @@ export type Beat<F extends string, A extends string, E extends string, S extends
seconds?: number;
};
-export type Telling<F extends string, A extends string, E extends string, S extends string> = Beat<F, A, E, S>[];
+/** A telling's beats. A beat may be a choice point over beats, `null` among the options meaning "leave it out", so a
+ * telling can sample optional and alternative beats; a whole telling may be a choice too (alternative orders). */
+export type Telling<F extends string, A extends string, E extends string, S extends string> = (Beat<F, A, E, S> | Choice<Beat<F, A, E, S> | null>)[];
export type StorySpec<
V extends string, F extends string, A extends string, E extends string, S extends string, T extends string,
@@ -116,7 +118,7 @@ export type StorySpec<
/** events in story order (the order things happen in the world) */
world: Record<E, Event<V, F, A, E>>;
/** each telling: one cut of the film, a trailer, a game's critical path */
- tellings: Record<T, Telling<F, A, E, S>>;
+ tellings: Record<T, Telling<F, A, E, S> | Choice<Telling<F, A, E, S>>>;
/** the lenses it's read and checked through by default (lens.ts) */
lenses?: string[];
};
diff --git a/sdk/story/src/mutate.ts b/sdk/story/src/mutate.ts
index 0557114a..ed9bc616 100644
--- a/sdk/story/src/mutate.ts
+++ b/sdk/story/src/mutate.ts
@@ -3,24 +3,25 @@
// breaks the exact checks find by construction (a dropped setup); others they can't (two beats swapped so the story
// drags), and those are what a learned critic is for. `expect` names the check that should find it, when one should.
import { listOf, type AnyStory } from "./model.ts";
-import { resolve, rng } from "./resolve.ts";
+import { rng } from "./resolve.ts";
+import { resolved, type RBeat, type REvent, type RStory } from "./load.ts";
export type Kind =
| "drop-setup" | "drop-payoff" | "drop-cause" | "early-need" | "flatten-beat" | "drop-proof" | "swap-beats" | "drop-cause-beat" | "orphan-event";
export type Label = { kind: Kind; at: string; says: string; expect?: string };
export type Mutant = { story: AnyStory; telling: string; label: Label };
-type Tell = AnyStory["tellings"][string];
-type Ev = AnyStory["world"][string];
+type Tell = RBeat[];
+type Ev = REvent;
const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x)) as T;
/** Every way this story told this way can be broken, each as one mutant. */
export function mutants(s: AnyStory, telling?: string, seed = 0): Mutant[] {
- const base = resolve(s, seed);
+ const base: RStory = resolved(s, seed);
const t = telling ?? Object.keys(base.tellings)[0];
const out: Mutant[] = [];
- const beats = (): Tell => out.length >= 0 ? (clone(base.tellings[t]) as Tell) : [];
- const withTelling = (b: Tell, world = base.world): AnyStory => ({ ...clone(base), world: clone(world), tellings: { ...clone(base.tellings), [t]: b } });
+ const beats = (): Tell => clone(base.tellings[t]);
+ const withTelling = (b: Tell, world = base.world): AnyStory => ({ ...clone(base), world: clone(world), tellings: { ...clone(base.tellings), [t]: b } }) as unknown as AnyStory;
const keys = Object.keys(base.world);
base.tellings[t].forEach((beat, i) => {
diff --git a/sdk/story/src/resolve.ts b/sdk/story/src/resolve.ts
index 6cf9e7b9..3ac71fff 100644
--- a/sdk/story/src/resolve.ts
+++ b/sdk/story/src/resolve.ts
@@ -27,7 +27,7 @@ export function pick<T>(options: readonly T[], weights: readonly number[] | unde
function walk(x: unknown, r: () => number): unknown {
if (isChoice(x)) return walk(pick(x.choice, x.weights, r), r);
- if (Array.isArray(x)) return x.map((v) => walk(v, r));
+ if (Array.isArray(x)) return x.map((v) => walk(v, r)).filter((v) => v !== null); // a choice of null drops the item
if (x && typeof x === "object") return Object.fromEntries(Object.entries(x).map(([k, v]) => [k, walk(v, r)]));
return x;
}
diff --git a/sdk/story/src/sample.ts b/sdk/story/src/sample.ts
new file mode 100644
index 00000000..679d8f7d
--- /dev/null
+++ b/sdk/story/src/sample.ts
@@ -0,0 +1,74 @@
+// Generation without a fixed answer (docs/story.feature ST4a). A story with choice points is a space of stories; a seed
+// 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 { structure, type Lens } from "./lens.ts";
+import type { AnyStory } from "./model.ts";
+import { resolve } from "./resolve.ts";
+
+export type SampleOptions = { seed?: number; telling?: string; lenses?: Lens[]; refuse?: Level; tries?: number };
+export type Sampled = { story: AnyStory; seed: number; findings: Finding[]; passes: boolean };
+
+const ranks: Record<Level, number> = { error: 0, warn: 1, note: 2 };
+
+/** Every finding for one seed: the exact checks and each lens's. */
+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)];
+}
+
+/** One story from the space that passes, starting at `seed`; the best found when none passes in `tries`. */
+export function sample(s: AnyStory, o: SampleOptions = {}): Sampled {
+ const { seed = 0, telling, lenses = [], refuse = "error", tries = 64 } = o;
+ let best: Sampled | undefined;
+ for (let i = 0; i < tries; i++) {
+ const sd = seed + i;
+ const findings = judge(s, sd, telling, lenses);
+ const bad = findings.filter((f) => ranks[f.level] <= ranks[refuse]).length;
+ const got: Sampled = { story: resolve(s, sd), seed: sd, findings, passes: bad === 0 };
+ if (got.passes) return got;
+ if (!best || bad < best.findings.filter((f) => ranks[f.level] <= ranks[refuse]).length) best = got;
+ }
+ return best!;
+}
+
+/** Up to n different passing stories (different once resolved), from seeds counted up from `seed`. */
+export function samples(s: AnyStory, n: number, o: SampleOptions = {}): Sampled[] {
+ const out: Sampled[] = [];
+ const seen = new Set<string>();
+ let seed = o.seed ?? 0;
+ for (let guard = 0; out.length < n && guard < n * 32; guard++) {
+ const got = sample(s, { ...o, seed });
+ seed = got.seed + 1;
+ if (!got.passes) break;
+ const key = JSON.stringify(got.story);
+ if (!seen.has(key)) { seen.add(key); out.push(got); }
+ }
+ return out;
+}
+
+export type MatrixRow = { theme: string; seed: number; passes: boolean; findings: Finding[] };
+export type MatrixResult = { rows: MatrixRow[]; byTheme: Record<string, { passed: number; of: number; checks: Record<string, number> }> };
+
+/** One story pattern across many premises: how often it holds for each, and which checks fail where. */
+export function matrix<T>(pattern: (theme: T) => AnyStory, themes: Record<string, T>, o: SampleOptions & { seeds?: number[] } = {}): MatrixResult {
+ const seeds = o.seeds ?? [0, 1, 2, 3, 4];
+ const refuse = o.refuse ?? "error";
+ const rows: MatrixRow[] = [];
+ const byTheme: MatrixResult["byTheme"] = {};
+ for (const [name, theme] of Object.entries(themes)) {
+ const s = pattern(theme);
+ const agg = (byTheme[name] = { passed: 0, of: 0, checks: {} as Record<string, number> });
+ for (const seed of seeds) {
+ const findings = judge(s, seed, o.telling, o.lenses ?? []);
+ const bad = findings.filter((f) => ranks[f.level] <= ranks[refuse]);
+ rows.push({ theme: name, seed, passes: bad.length === 0, findings });
+ agg.of++;
+ if (!bad.length) agg.passed++;
+ for (const f of bad) agg.checks[f.check] = (agg.checks[f.check] ?? 0) + 1;
+ }
+ }
+ return { rows, byTheme };
+}
diff --git a/sdk/story/test/lenses.test.ts b/sdk/story/test/lenses.test.ts
new file mode 100644
index 00000000..891cdd9e
--- /dev/null
+++ b/sdk/story/test/lenses.test.ts
@@ -0,0 +1,32 @@
+import { expect, test } from "bun:test";
+import { LENSES, 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", () => {
+ const r = readThrough(launch, Object.values(LENSES), "30s");
+ for (const x of r) expect([x.lens, x.findings.filter((f) => f.level === "error")]).toEqual([x.lens, []]);
+ const by = Object.fromEntries(r.map((x) => [x.lens, x.map]));
+ expect(by.mckee.inciting).toEqual(["b1"]);
+ expect(by.mckee.crisis).toEqual(["b2"]);
+ expect(by.mckee.climax).toEqual(["b3"]);
+ expect(by.pas).toEqual({ problem: ["b1"], agitate: ["b2"], solve: ["b3"] });
+});
+
+test("a brand that saves the day itself fails Storynomics", () => {
+ const brandHero = { ...launch, world: { ...launch.world, ships: { ...launch.world.ships, who: "raea" as const, with: ["team" as const] } } };
+ const r = readThrough(brandHero, [LENSES.storynomics], "30s")[0];
+ expect(r.passes).toBe(false);
+ expect(r.findings.some((f) => f.check === "storynomics:hero")).toBe(true);
+});
+
+test("a story with no dilemma gets a crisis proposed from the hero's want and need", () => {
+ const flat = story({
+ values: { v: value("low", "high") },
+ agents: { kid: { want: "win the race", need: "learn to lose", mask: "hero" } },
+ world: { a: { who: "kid", does: "trains", routine: true }, b: { who: "kid", does: "falls at the start", because: "a", turns: { v: -2 } }, c: { who: "kid", does: "finishes last, laughing", because: "b", turns: { v: 2 }, ends: { kid: "need" } } },
+ tellings: { t: [{ shows: ["a"] }, { shows: ["b"] }, { shows: ["c"] }] },
+ });
+ const r = readThrough(flat, [LENSES.mckee], "t")[0];
+ expect(r.findings.some((f) => f.check === "mckee:crisis" && f.level === "error")).toBe(true);
+ expect(r.proposals.find((p) => p.stage === "crisis")?.onScreen).toBe("kid must choose: win the race, or learn to lose");
+});
diff --git a/sdk/story/test/sample.test.ts b/sdk/story/test/sample.test.ts
new file mode 100644
index 00000000..38c33195
--- /dev/null
+++ b/sdk/story/test/sample.test.ts
@@ -0,0 +1,51 @@
+import { expect, test } from "bun:test";
+import { choose, compileScript, compileStorylets, dramaManager, LENSES, matrix, sample, samples, story, toInk, value } from "../src/index.ts";
+import { launch } from "./fixture.ts";
+
+// a pattern: one launch shape over any product, with optional and alternative beats
+const pattern = (t: { who: string; pain: string; win: string }) => story({
+ title: t.who, idea: { value: "time", side: `${t.win}` },
+ values: { time: value("lost", "won") },
+ facts: { works: "it works" },
+ agents: { them: { want: t.win, role: "customer", mask: "hero" }, product: { role: "brand", mask: "mentor" } },
+ world: {
+ day: { who: "them", does: `every week, ${t.pain}`, routine: true, turns: { time: -1 } },
+ worse: { who: "them", does: choose([`${t.pain} doubles`, `a deadline makes ${t.pain} worse`]), because: "day", turns: { time: -2 } },
+ choice: { who: "them", does: "decides to try something new", because: "worse", dilemma: ["keep going", "try it"] },
+ win: { who: "them", with: ["product"], does: t.win, because: "choice", sets: ["works"], turns: { time: 3 }, ends: { them: "want" }, claim: t.win, proof: ["works"] },
+ },
+ tellings: {
+ ad: choose([
+ [{ shows: ["day"] }, { shows: ["worse"] }, { shows: ["choice"] }, { shows: ["win"] }],
+ [{ shows: ["win"], hides: ["works"], asks: ["works"] }, { shows: ["day"] }, { shows: ["worse"] }, choose([{ shows: ["choice"] }, null]), { shows: ["win"], reveals: ["works"] }],
+ ]),
+ },
+});
+
+test("a sampled story always passes, and seeds give different ones", () => {
+ const s = pattern({ who: "Northwind Coffee", pain: "the roast log is done by hand", win: "the log fills itself" });
+ const got = samples(s, 4, { lenses: [LENSES.mckee, LENSES.pas, LENSES.storynomics] });
+ expect(got.length).toBeGreaterThan(1);
+ for (const g of got) expect(g.passes).toBe(true);
+ expect(sample(s, { seed: 3 }).story).toEqual(sample(s, { seed: 3 }).story);
+});
+
+test("the theme matrix says where a pattern breaks", () => {
+ const m = matrix(pattern, {
+ coffee: { who: "Northwind Coffee", pain: "the roast log is done by hand", win: "the log fills itself" },
+ skincare: { who: "Lumen Skincare", pain: "every shade is shot again", win: "every shade from one shoot" },
+ }, { lenses: [LENSES.mckee, LENSES.pas] });
+ expect(Object.keys(m.byTheme)).toEqual(["coffee", "skincare"]);
+ expect(m.rows.length).toBe(10);
+});
+
+test("a telling compiles to a Script, the world to storylets a drama manager plays in causal order, lines to Ink", () => {
+ const sc = compileScript(launch, "30s");
+ expect(sc.scenes.length).toBe(4);
+ expect(sc.scenes[0].heading).toBe("B0 · curiosity");
+ expect(sc.scenes[3].payoff).toBe("pays off how; answers recipeRuns");
+ const played = dramaManager(compileStorylets(launch), [0.2, 0.6, 0.4, 1]);
+ expect(played).toEqual(["week", "doubles", "tries", "ships"]);
+ const withLines = { ...launch, tellings: { "30s": [{ shows: ["tries" as const], says: [{ who: "team" as const, says: "Fine. One recipe.", means: "I don't believe it" }] }] } };
+ expect(toInk(withLines, "30s")).toContain("team: Fine. One recipe. // means: I don't believe it");
+});