sovkora 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +9 -0
  3. package/README.md +67 -2
  4. package/dist/commands/agent.command.js +267 -0
  5. package/dist/commands/chat.command.js +214 -0
  6. package/dist/commands/chat.handlers.js +150 -0
  7. package/dist/commands/chat.types.js +44 -0
  8. package/dist/commands/cinema.command.js +643 -0
  9. package/dist/commands/config.command.js +228 -0
  10. package/dist/commands/db.command.js +114 -0
  11. package/dist/commands/demo.command.js +55 -0
  12. package/dist/commands/dev.command.js +462 -0
  13. package/dist/commands/docs.command.js +135 -0
  14. package/dist/commands/doctor.command.js +119 -0
  15. package/dist/commands/forgot.command.js +57 -0
  16. package/dist/commands/generate.command.js +376 -0
  17. package/dist/commands/graph.command.js +54 -0
  18. package/dist/commands/init.command.js +380 -0
  19. package/dist/commands/init.steps.js +115 -0
  20. package/dist/commands/install.command.js +459 -0
  21. package/dist/commands/login.command.js +110 -0
  22. package/dist/commands/logs.command.js +215 -0
  23. package/dist/commands/logs.steps.js +130 -0
  24. package/dist/commands/mcp.command.js +104 -0
  25. package/dist/commands/models.command.js +164 -0
  26. package/dist/commands/onboard.command.js +236 -0
  27. package/dist/commands/pack.command.js +255 -0
  28. package/dist/commands/profile.command.js +51 -0
  29. package/dist/commands/recover.command.js +489 -0
  30. package/dist/commands/register.command.js +94 -0
  31. package/dist/commands/release.command.js +99 -0
  32. package/dist/commands/reset.command.js +79 -0
  33. package/dist/commands/runs.command.js +201 -0
  34. package/dist/commands/settings.command.js +85 -0
  35. package/dist/commands/start.command.js +590 -0
  36. package/dist/commands/status.command.js +167 -0
  37. package/dist/commands/stop.command.js +313 -0
  38. package/dist/commands/studio.command.js +266 -0
  39. package/dist/commands/test.command.js +134 -0
  40. package/dist/commands/verify.command.js +52 -0
  41. package/dist/commands/video.command.js +73 -0
  42. package/dist/commands/workspace-guard.js +72 -0
  43. package/dist/index.js +207 -0
  44. package/dist/renderers.js +250 -0
  45. package/dist/services/api-client.js +150 -0
  46. package/dist/services/auth.api.js +87 -0
  47. package/dist/services/chat.api.js +117 -0
  48. package/dist/services/cinema-estimate.json +42 -0
  49. package/dist/services/cinema.childsafe.js +52 -0
  50. package/dist/services/cinema.director.js +285 -0
  51. package/dist/services/cinema.production.js +417 -0
  52. package/dist/services/cinema.staging.js +323 -0
  53. package/dist/services/cinema.story.js +758 -0
  54. package/dist/services/cinema.treatment.js +393 -0
  55. package/dist/services/composer.run.js +94 -0
  56. package/dist/services/demo/demo.documents.js +108 -0
  57. package/dist/services/demo/demo.guard.js +49 -0
  58. package/dist/services/demo/demo.persona.js +114 -0
  59. package/dist/services/demo/demo.seed.js +281 -0
  60. package/dist/services/diagnostics.js +327 -0
  61. package/dist/services/image-model-recipes.json +93 -0
  62. package/dist/services/image-models.js +152 -0
  63. package/dist/services/local-store.js +145 -0
  64. package/dist/services/mcp.api.js +38 -0
  65. package/dist/services/model-catalog.js +70 -0
  66. package/dist/services/notify.js +55 -0
  67. package/dist/services/pack.api.js +23 -0
  68. package/dist/services/pack.bundle.js +241 -0
  69. package/dist/services/pack.sources.js +101 -0
  70. package/dist/services/release-manifest.js +266 -0
  71. package/dist/services/runs.view.js +80 -0
  72. package/dist/services/runs.wait.js +38 -0
  73. package/dist/services/semver.js +55 -0
  74. package/dist/services/settings.api.js +108 -0
  75. package/dist/services/string-utils.js +70 -0
  76. package/dist/services/studio.api.js +120 -0
  77. package/dist/services/templates.js +893 -0
  78. package/dist/services/tool-installer.js +353 -0
  79. package/dist/services/tool-path.js +72 -0
  80. package/dist/services/version-manager.js +253 -0
  81. package/dist/services/workspace-bootstrap.js +68 -0
  82. package/dist/threads.js +202 -0
  83. package/dist/types/api.types.js +6 -0
  84. package/dist/types/local.types.js +6 -0
  85. package/dist/ui/box.js +46 -0
  86. package/dist/ui/logger.js +28 -0
  87. package/dist/ui/platform.js +32 -0
  88. package/dist/ui/prompts.js +130 -0
  89. package/dist/ui/table.js +33 -0
  90. package/dist/utils/config.js +150 -0
  91. package/dist/utils/development-status.js +22 -0
  92. package/dist/utils/endpoints.js +41 -0
  93. package/dist/utils/health.js +94 -0
  94. package/dist/utils/pid.js +83 -0
  95. package/dist/utils/platform.js +358 -0
  96. package/dist/utils/process.js +139 -0
  97. package/dist/utils/state-dir.js +105 -0
  98. package/package.json +95 -4
@@ -0,0 +1,758 @@
1
+ "use strict";
2
+ /**
3
+ * @file cinema.story.ts
4
+ * @description The treatment stage of a cinematic short (orazaka#289, ADR-080 addendum v2): a short brief becomes a
5
+ * **story** before it becomes a shot list — an arc (hook → journey → turn → payoff), each character's intention, a theme,
6
+ * and for every shot a purpose, an action that serves its beat, a gaze and the physics that make a character alive; the
7
+ * narrator's lines with their direction (emotion, pace, emphasis) and the shots they land on; music cues that follow the
8
+ * arc; a sound list per shot.
9
+ *
10
+ * Everything here is pure: the **rubric** that rejects flat beats, off-topic action, a story without a turn or a line
11
+ * that cannot fit its shots (`critiqueStory`), the prompt and the parser of the language-model judge that reads the
12
+ * same rubric (`judgePrompt`, `parseJudge`), their verdict together (`verdict`), the timeline that aligns every line,
13
+ * music cue and sound to the cut (`timeline`), and the directed motion prompt of a shot (`directedMotion`).
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.LINE_SPILL = exports.LINE_LEAD = exports.JUDGE_THRESHOLD = exports.JUDGE_AXES = exports.MAX_MUSIC_INTENSITY = exports.MAX_WORDS_PER_SECOND = exports.RUBRIC_THRESHOLD = exports.NEVER_NAMED = exports.QUICK_SHOT = exports.MIN_LENGTH_SPREAD = exports.MIN_INTERACTION_SHARE = exports.MIN_INTERACTION_KINDS = exports.StoryError = exports.PACES = exports.INTERACTIONS = exports.SOUND_KINDS = exports.SOUND_EVENTS = exports.SOUND_BEDS = exports.BEATS = void 0;
17
+ exports.parseStory = parseStory;
18
+ exports.legalFindings = legalFindings;
19
+ exports.critiqueStory = critiqueStory;
20
+ exports.judgePrompt = judgePrompt;
21
+ exports.parseJudge = parseJudge;
22
+ exports.verdict = verdict;
23
+ exports.timeline = timeline;
24
+ exports.directedMotion = directedMotion;
25
+ /** The four beats of a short's arc, in the order a story must meet them. */
26
+ exports.BEATS = ["hook", "journey", "turn", "payoff"];
27
+ /** The sounds the foley step can lay (orazaka-worker-media app/foley.py): beds, then events placed at a second of the shot. */
28
+ exports.SOUND_BEDS = [
29
+ "rain",
30
+ "storm",
31
+ "wind",
32
+ "wind-soft",
33
+ "lake",
34
+ "waves",
35
+ "drizzle",
36
+ "room",
37
+ "dawn",
38
+ "city",
39
+ "rain-window",
40
+ "drips",
41
+ "tunnel",
42
+ "crowd",
43
+ "neon",
44
+ ];
45
+ exports.SOUND_EVENTS = [
46
+ "thunder",
47
+ "gust",
48
+ "flap",
49
+ "whoosh",
50
+ "steps",
51
+ "rustle",
52
+ "shake",
53
+ "paper",
54
+ "block",
55
+ "hum",
56
+ "ignite",
57
+ "chime",
58
+ "call",
59
+ "chirp",
60
+ "splash",
61
+ "splash-small",
62
+ "coin",
63
+ "parcel",
64
+ "tap",
65
+ "swell",
66
+ "train",
67
+ "skate",
68
+ "sparks",
69
+ "impact",
70
+ "slide",
71
+ "riser",
72
+ ];
73
+ exports.SOUND_KINDS = [...exports.SOUND_BEDS, ...exports.SOUND_EVENTS];
74
+ /**
75
+ * What characters do to each other in a shot (orazaka#289, Oussama's review: « they look presented, not part of a story »):
76
+ * a story where they meet, help, argue and hand off is told by these.
77
+ */
78
+ exports.INTERACTIONS = ["meet", "help", "argue", "handoff", "tease", "celebrate", "compete", "rescue"];
79
+ /** Pace of a line: what the voice step turns into a speaking rate. */
80
+ exports.PACES = ["slow", "measured", "rhythmic", "lively"];
81
+ class StoryError extends Error {
82
+ }
83
+ exports.StoryError = StoryError;
84
+ const str = (value) => (typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "");
85
+ const num = (value, fallback) => Number.isFinite(Number(value)) && value !== null && value !== "" ? Number(value) : fallback;
86
+ const list = (value) => (Array.isArray(value) ? value : []);
87
+ function oneOf(value, allowed, what) {
88
+ if (!allowed.includes(String(value)))
89
+ throw new StoryError(`${what} '${String(value)}' is not one of ${allowed.join(", ")}`);
90
+ return value;
91
+ }
92
+ /**
93
+ * A treatment's story, read once (parse, don't validate): what cannot be a story is refused by name — an unknown beat,
94
+ * a line on a shot that does not exist, a sound the foley step cannot make. What makes a story *good* is the rubric's
95
+ * job (`critiqueStory`), not the parser's.
96
+ */
97
+ function parseStory(raw) {
98
+ if (!raw || typeof raw !== "object")
99
+ throw new StoryError("a treatment is a JSON object");
100
+ const t = raw;
101
+ const arc = list(t.arc).map((a, i) => ({
102
+ beat: oneOf(a.beat, exports.BEATS, `arc[${i}].beat`),
103
+ purpose: str(a.purpose),
104
+ emotion: str(a.emotion),
105
+ intensity: Math.min(1, Math.max(0, num(a.intensity, 0.5))),
106
+ }));
107
+ const characters = list(t.characters).map((c) => ({
108
+ id: str(c.id),
109
+ description: str(c.description),
110
+ promise: str(c.promise),
111
+ intention: str(c.intention),
112
+ }));
113
+ const cast = new Set(characters.map((c) => c.id));
114
+ const shots = list(t.shots).map((s, i) => {
115
+ const id = i + 1;
116
+ if (Number(s.id ?? id) !== id)
117
+ throw new StoryError(`shots are numbered 1 to n in order (shot ${i + 1} says ${String(s.id)})`);
118
+ const characterIds = list(s.characters).map(String);
119
+ for (const c of characterIds)
120
+ if (!cast.has(c))
121
+ throw new StoryError(`shot ${id}: character '${c}' is not in the cast`);
122
+ const chain = s.chainFrom;
123
+ if (chain && !(Number(chain.shot) >= 1 && Number(chain.shot) < id))
124
+ throw new StoryError(`shot ${id}: chainFrom names a shot before it`);
125
+ return {
126
+ id,
127
+ slug: str(s.slug) || `shot-${id}`,
128
+ seconds: num(s.seconds, 3),
129
+ speed: num(s.speed, 1),
130
+ beat: oneOf(s.beat ?? "journey", exports.BEATS, `shot ${id}: beat`),
131
+ purpose: str(s.purpose),
132
+ characters: characterIds,
133
+ action: str(s.action),
134
+ intent: str(s.intent),
135
+ gaze: str(s.gaze),
136
+ physics: str(s.physics),
137
+ interaction: str(s.interaction),
138
+ ...(s.interactionKind
139
+ ? { interactionKind: oneOf(s.interactionKind, exports.INTERACTIONS, `shot ${id}: interactionKind`) }
140
+ : {}),
141
+ place: str(s.place),
142
+ framing: str(s.framing),
143
+ camera: str(s.camera),
144
+ lens: str(s.lens),
145
+ lighting: str(s.lighting),
146
+ atmosphere: str(s.atmosphere),
147
+ motion: str(s.motion),
148
+ transition: str(s.transition) || "cut",
149
+ ...(str(s.reuse) ? { reuse: str(s.reuse) } : {}),
150
+ ...(chain
151
+ ? { chainFrom: { shot: Number(chain.shot), ...(chain.at !== undefined ? { at: Number(chain.at) } : {}) } }
152
+ : {}),
153
+ sound: list(s.sound).map((c, k) => ({
154
+ kind: oneOf(c.kind, exports.SOUND_KINDS, `shot ${id}: sound[${k}].kind`),
155
+ ...(c.at !== undefined && c.at !== null ? { at: num(c.at, 0) } : {}),
156
+ gain: num(c.gain, -12),
157
+ })),
158
+ };
159
+ });
160
+ const ids = new Set(shots.map((s) => s.id));
161
+ const lines = list(t.lines).map((l, i) => {
162
+ const lineId = str(l.id) || `line-${i + 1}`;
163
+ const on = list(l.shots).map(Number);
164
+ if (on.length === 0 || on.some((s) => !ids.has(s)))
165
+ throw new StoryError(`line ${lineId}: its shots must exist`);
166
+ const d = (l.direction ?? {});
167
+ const textByLanguage = {};
168
+ for (const [k, v] of Object.entries(l))
169
+ if (/^[a-z]{2}$/.test(k) && typeof v === "string")
170
+ textByLanguage[k] = str(v);
171
+ return {
172
+ id: lineId,
173
+ shots: on,
174
+ text: textByLanguage,
175
+ direction: {
176
+ emotion: str(d.emotion),
177
+ pace: oneOf(d.pace ?? "measured", exports.PACES, `line ${lineId}: pace`),
178
+ emphasis: list(d.emphasis).map(String),
179
+ pauseAfter: Math.max(0, num(d.pauseAfter, 0.3)),
180
+ },
181
+ };
182
+ });
183
+ const music = (t.music && typeof t.music === "object" ? t.music : { prompt: str(t.music) });
184
+ const legal = (t.legal && typeof t.legal === "object" ? t.legal : {});
185
+ return {
186
+ title: str(t.title),
187
+ references: list(t.references ?? legal.references).map((r) => ({ evokes: str(r.evokes), how: str(r.how) })),
188
+ never: list(legal.never).map(String),
189
+ logline: str(t.logline),
190
+ theme: str(t.theme),
191
+ arc,
192
+ characters,
193
+ lines,
194
+ music: {
195
+ prompt: str(music.prompt),
196
+ cues: list(music.cues).map((c, i) => {
197
+ const span = list(c.shots).map(Number);
198
+ if (span.length && !(span.length === 2 && ids.has(span[0]) && ids.has(span[1]) && span[0] <= span[1])) {
199
+ throw new StoryError(`music cue ${i + 1}: shots is [first, last] of existing shots`);
200
+ }
201
+ const beat = c.beat ?? (span.length ? shots[span[0] - 1].beat : undefined);
202
+ return {
203
+ beat: oneOf(beat, exports.BEATS, `music cue ${i + 1}: beat`),
204
+ ...(span.length ? { shots: [span[0], span[1]] } : {}),
205
+ ...(str(c.genre) ? { genre: str(c.genre) } : {}),
206
+ intensity: Math.min(1, Math.max(0, num(c.intensity, 0.5))),
207
+ prompt: str(c.prompt),
208
+ };
209
+ }),
210
+ },
211
+ shots,
212
+ };
213
+ }
214
+ // ── The rubric ──────────────────────────────────────────────────────────────────────────────────────────────────────
215
+ /** Verbs that say nothing about a character (the v1 film's failure): an action made only of these is flat. */
216
+ const GENERIC = new RegExp("\\b(" +
217
+ [
218
+ "moves?|moving|stands?|standing",
219
+ "looks? around|walks? around|scanning",
220
+ "turns? (?:its|his|her) head (?:left|right)",
221
+ "flies around|is shown|appears?|idles?|poses?",
222
+ ].join("|") +
223
+ ")\\b", "gi");
224
+ /** Physical verbs of a living body: a character shot names at least one. */
225
+ const LIVING = new RegExp("\\b(" +
226
+ [
227
+ "breath\\w*|lean\\w*|crouch\\w*|leap\\w*|launch\\w*|beat\\w*|flap\\w*|land\\w*",
228
+ "fold\\w*|grip\\w*|tighten\\w*|shuffl\\w*|step\\w*|nod\\w*|bow\\w*|nudg\\w*",
229
+ "shak\\w*|lift\\w*|rais\\w*|set\\w*|tap\\w*|push\\w*|brac\\w*|tumbl\\w*",
230
+ "climb\\w*|glanc\\w*|snap\\w*|puff\\w*|smooth\\w*|carr\\w*|hold\\w*|answer\\w*",
231
+ "read\\w*|recogn\\w*|spread\\w*|ruffl\\w*|blink\\w*|widen\\w*|bump\\w*|twirl\\w*",
232
+ "hop\\w*|spin\\w*|wav(?:e|es|ing)|slid\\w*|danc\\w*|jump\\w*|cheer\\w*|scoop\\w*",
233
+ "wrap\\w*|flick\\w*|sink\\w*|shiver\\w*|curl\\w*|dive\\w*|snatch\\w*|catch\\w*",
234
+ "bob\\w*|bank\\w*",
235
+ ].join("|") +
236
+ ")\\b", "i");
237
+ /** Words too common to tie an action to a promise. */
238
+ const STOP = new Set([
239
+ "the",
240
+ "and",
241
+ "with",
242
+ "that",
243
+ "this",
244
+ "from",
245
+ "into",
246
+ "every",
247
+ "each",
248
+ "comes",
249
+ "first",
250
+ "time",
251
+ "line",
252
+ "open",
253
+ "its",
254
+ "their",
255
+ "then",
256
+ "they",
257
+ "when",
258
+ "what",
259
+ "keeps",
260
+ "keep",
261
+ "follows",
262
+ ]);
263
+ const stems = (value) => new Set(value
264
+ .toLowerCase()
265
+ .normalize("NFD")
266
+ .replace(/[̀-ͯ]/g, "")
267
+ .split(/[^a-z]+/)
268
+ .filter((w) => w.length >= 4 && !STOP.has(w))
269
+ .map((w) => w.slice(0, 5)));
270
+ /** A story with a cast shows at least this many kinds of interaction, in at least this share of its character shots. */
271
+ exports.MIN_INTERACTION_KINDS = 3;
272
+ exports.MIN_INTERACTION_SHARE = 1 / 3;
273
+ /** Rhythm: the spread of shot lengths (coefficient of variation), and what a quick shot is. */
274
+ exports.MIN_LENGTH_SPREAD = 0.15;
275
+ exports.QUICK_SHOT = 3;
276
+ const LINEUP = new RegExp("\\b(" +
277
+ [
278
+ "in a row|line[sd]? up|lineup",
279
+ "turns? (?:their|its) heads? (?:to|toward) the (?:camera|lens)",
280
+ "looks? (?:in)?to the (?:camera|lens)",
281
+ "pose[sd]? for",
282
+ ].join("|") +
283
+ ")\\b", "i");
284
+ /**
285
+ * Names a film must never say or show (the hard legal rule of orazaka#289): real people, songs, games, shows and brands
286
+ * a brief may evoke. A treatment adds its own (`legal.never`); a reference is evoked through original or generic means,
287
+ * never named. Matched as whole words, case-insensitive.
288
+ */
289
+ exports.NEVER_NAMED = [
290
+ "snoop",
291
+ "dr. dre",
292
+ "kendrick",
293
+ "drake",
294
+ "sugar sammy",
295
+ "bougon",
296
+ "not like us",
297
+ "gta",
298
+ "grand theft auto",
299
+ "rockstar games",
300
+ "disney",
301
+ "pixar",
302
+ "marvel",
303
+ "nintendo",
304
+ "pokemon",
305
+ "taylor swift",
306
+ "beyonce",
307
+ "eminem",
308
+ ];
309
+ function textsOf(story) {
310
+ const out = [
311
+ ["title", story.title],
312
+ ["logline", story.logline],
313
+ ["theme", story.theme],
314
+ ];
315
+ for (const l of story.lines)
316
+ for (const [lang, t] of Object.entries(l.text))
317
+ out.push([`line ${l.id} ${lang}`, t]);
318
+ for (const s of story.shots) {
319
+ for (const k of [
320
+ "action",
321
+ "motion",
322
+ "purpose",
323
+ "intent",
324
+ "interaction",
325
+ "place",
326
+ "camera",
327
+ "lighting",
328
+ "atmosphere",
329
+ ])
330
+ out.push([`shot ${s.id} ${k}`, s[k]]);
331
+ }
332
+ out.push(["music", story.music.prompt], ...story.music.cues.map((c, i) => [`cue ${i + 1}`, c.prompt]));
333
+ for (const r of story.references)
334
+ out.push([`reference ${r.evokes}`, `${r.evokes} ${r.how}`]);
335
+ return out;
336
+ }
337
+ /** What a story names that it must not (pure): the built-in list and the treatment's own, as whole words. */
338
+ function legalFindings(story) {
339
+ const banned = [...exports.NEVER_NAMED, ...story.never].map((n) => n.toLowerCase().trim()).filter(Boolean);
340
+ const findings = [];
341
+ for (const [where, text] of textsOf(story)) {
342
+ const lower = ` ${text.toLowerCase()} `;
343
+ for (const name of banned) {
344
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, String.raw `\$&`);
345
+ const at = lower.search(new RegExp(`[^a-z0-9]${escaped}[^a-z0-9]`));
346
+ if (at >= 0)
347
+ findings.push({
348
+ rule: "legal",
349
+ message: `${where} names « ${name} »: evoke it through an original or generic means instead`,
350
+ });
351
+ }
352
+ }
353
+ for (const r of story.references) {
354
+ if (r.how.split(/\s+/).length < 3)
355
+ findings.push({ rule: "legal", message: `the reference « ${r.evokes} » does not say how it is evoked legally` });
356
+ }
357
+ return findings;
358
+ }
359
+ /** Each criterion must reach this score; any finding of an arc, flat or off-topic beat fails the story outright. */
360
+ exports.RUBRIC_THRESHOLD = 0.85;
361
+ /** A narrator speaks at most this many words a second of the shots a line is said over (calm, cinematic pace). */
362
+ exports.MAX_WORDS_PER_SECOND = 2.6;
363
+ /** The score may never reach full loudness: a cue's intensity is at most this (« far too aggressive », orazaka#289). */
364
+ exports.MAX_MUSIC_INTENSITY = 0.85;
365
+ const screen = (s) => s.seconds / (s.speed || 1);
366
+ /** The rubric over a story (pure): the same rules the LLM judge reads, decided without one. */
367
+ function critiqueStory(story, language = "en") {
368
+ const findings = [];
369
+ const ratio = (passed, total) => (total === 0 ? 1 : Number((passed / total).toFixed(3)));
370
+ // Arc: every beat, in order, with a turn after the first third; the film ends on its payoff.
371
+ const order = story.shots.map((s) => exports.BEATS.indexOf(s.beat));
372
+ const runtime = story.shots.reduce((sum, s) => sum + screen(s), 0);
373
+ let arcOk = 0;
374
+ for (const beat of exports.BEATS) {
375
+ if (story.shots.some((s) => s.beat === beat))
376
+ arcOk += 1;
377
+ else
378
+ findings.push({ rule: "arc", message: `the story has no ${beat}` });
379
+ }
380
+ if (order.some((b, i) => i > 0 && b < order[i - 1]))
381
+ findings.push({ rule: "arc", message: "the beats go back in time (hook → journey → turn → payoff)" });
382
+ const turnAt = story.shots.findIndex((s) => s.beat === "turn");
383
+ if (turnAt >= 0) {
384
+ const before = story.shots.slice(0, turnAt).reduce((sum, s) => sum + screen(s), 0);
385
+ if (before < runtime / 3)
386
+ findings.push({ rule: "arc", message: "the turn comes before the story has started its journey (first third)" });
387
+ }
388
+ if (!story.theme)
389
+ findings.push({ rule: "arc", message: "the story names no theme" });
390
+ // Purpose: every shot says why it is in the film.
391
+ const purposeful = story.shots.filter((s) => {
392
+ if (s.purpose.split(" ").length >= 4)
393
+ return true;
394
+ findings.push({ rule: "purpose", shot: s.id, message: "the shot has no purpose (why is it in the film?)" });
395
+ return false;
396
+ }).length;
397
+ // Alive, flat and on-topic: what a character shot must have.
398
+ const characterShots = story.shots.filter((s) => s.characters.length > 0 && !s.reuse);
399
+ let alive = 0;
400
+ let onTopic = 0;
401
+ for (const s of characterShots) {
402
+ const beats = s.action.split(/[,;]| then | and then /).filter((p) => p.trim().length > 3).length;
403
+ const generic = (s.action.match(GENERIC) ?? []).length;
404
+ const living = LIVING.test(`${s.action} ${s.physics}`);
405
+ const problems = [];
406
+ if (!s.intent)
407
+ problems.push("no intention");
408
+ if (!s.gaze)
409
+ problems.push("no gaze");
410
+ if (!s.physics)
411
+ problems.push("no physics (weight, wings, breath)");
412
+ if (!living)
413
+ problems.push("no physical verb of a living body");
414
+ if (beats < 2)
415
+ problems.push("one action only (a beat needs a change)");
416
+ if (problems.length === 0)
417
+ alive += 1;
418
+ else
419
+ findings.push({ rule: "alive", shot: s.id, message: problems.join(", ") });
420
+ if (generic > 0 && beats - generic < 2)
421
+ findings.push({
422
+ rule: "flat",
423
+ shot: s.id,
424
+ message: `the action is generic motion (${(s.action.match(GENERIC) ?? []).join(", ")})`,
425
+ });
426
+ // On topic: the action carries the promise or the intention of at least one character in it, or the purpose names it.
427
+ const doing = stems(`${s.action} ${s.intent}`);
428
+ const tied = s.characters.some((id) => {
429
+ const c = story.characters.find((x) => x.id === id);
430
+ if (!c)
431
+ return false;
432
+ const promise = stems(`${c.promise} ${c.intention}`);
433
+ return ([...promise].some((w) => doing.has(w)) ||
434
+ (c.promise && s.purpose.toLowerCase().includes(c.promise.split(/[:,]/)[0].toLowerCase())));
435
+ });
436
+ if (tied)
437
+ onTopic += 1;
438
+ else
439
+ findings.push({
440
+ rule: "off-topic",
441
+ shot: s.id,
442
+ message: "the action serves no character's promise or intention",
443
+ });
444
+ }
445
+ // Continuity: a chained shot keeps one of the characters of the shot it starts from.
446
+ let chained = 0;
447
+ let chainOk = 0;
448
+ for (const s of story.shots) {
449
+ if (!s.chainFrom)
450
+ continue;
451
+ chained += 1;
452
+ const from = story.shots.find((x) => x.id === s.chainFrom?.shot);
453
+ if (from && s.characters.some((c) => from.characters.includes(c)))
454
+ chainOk += 1;
455
+ else
456
+ findings.push({
457
+ rule: "continuity",
458
+ shot: s.id,
459
+ message: `chained from shot ${s.chainFrom.shot} but shares no character with it`,
460
+ });
461
+ }
462
+ // Voice: every line has a direction, fits its shots, and lines never overlap.
463
+ let voiceOk = 0;
464
+ let lastShot = 0;
465
+ for (const l of story.lines) {
466
+ const words = (l.text[language] ?? Object.values(l.text)[0] ?? "").split(/\s+/).filter(Boolean).length;
467
+ const seconds = l.shots.reduce((sum, id) => sum + screen(story.shots[id - 1]), 0);
468
+ const problems = [];
469
+ if (!l.direction.emotion)
470
+ problems.push("no emotion");
471
+ if (words / Math.max(seconds, 0.1) > exports.MAX_WORDS_PER_SECOND)
472
+ problems.push(`${words} words over ${seconds.toFixed(1)} s is rushed`);
473
+ if (l.shots.some((id, k) => k > 0 && id !== l.shots[k - 1] + 1))
474
+ problems.push("its shots are not consecutive");
475
+ if (l.shots[0] <= lastShot)
476
+ problems.push("it overlaps the line before it");
477
+ lastShot = l.shots.at(-1);
478
+ if (problems.length === 0)
479
+ voiceOk += 1;
480
+ else
481
+ findings.push({ rule: "voice", line: l.id, message: problems.join(", ") });
482
+ }
483
+ // Music: a cue per beat present, never at full loudness, quiet in, the turn its peak, a resolve after it.
484
+ const cue = (b) => story.music.cues.find((c) => c.beat === b);
485
+ let musicOk = 0;
486
+ const musicChecks = 4;
487
+ const byShots = story.music.cues.some((c) => c.shots);
488
+ const covered = byShots
489
+ ? story.shots.every((s) => story.music.cues.some((c) => c.shots && c.shots[0] <= s.id && s.id <= c.shots[1]))
490
+ : exports.BEATS.every((b) => !story.shots.some((s) => s.beat === b) || cue(b));
491
+ if (covered)
492
+ musicOk += 1;
493
+ else
494
+ findings.push({
495
+ rule: "music",
496
+ message: byShots ? "a shot of the story has no music cue" : "a beat of the story has no music cue",
497
+ });
498
+ if (story.music.cues.every((c) => c.intensity <= exports.MAX_MUSIC_INTENSITY))
499
+ musicOk += 1;
500
+ else
501
+ findings.push({
502
+ rule: "music",
503
+ message: `a cue is louder than ${exports.MAX_MUSIC_INTENSITY} (the score sits under the story)`,
504
+ });
505
+ const hook = cue("hook");
506
+ if (!hook || story.music.cues.every((c) => c.intensity >= hook.intensity))
507
+ musicOk += 1;
508
+ else
509
+ findings.push({ rule: "music", message: "the hook's cue is not the quietest (an intro starts low)" });
510
+ // A score resolves: its last cue sits under its peak (a finale may peak — a DJ moment — then an outro brings it down).
511
+ const peak = Math.max(...story.music.cues.map((c) => c.intensity), 0);
512
+ const last = story.music.cues.at(-1);
513
+ if (!last || story.music.cues.length < 2 || last.intensity <= peak - 0.1)
514
+ musicOk += 1;
515
+ else
516
+ findings.push({ rule: "music", message: "the score ends at its peak (a score resolves after its peak)" });
517
+ // Sound: every shot has a sound; a character shot has at least one event (its action is heard, not just a bed).
518
+ const soundOk = story.shots.filter((s) => {
519
+ const events = s.sound.filter((c) => c.at !== undefined).length;
520
+ if (s.sound.length === 0)
521
+ findings.push({ rule: "sound", shot: s.id, message: "the shot is silent (no sound list)" });
522
+ else if (s.characters.length > 0 && !s.reuse && events === 0)
523
+ findings.push({ rule: "sound", shot: s.id, message: "the character's action is not heard (no foley event)" });
524
+ else
525
+ return true;
526
+ return false;
527
+ }).length;
528
+ // Interaction (orazaka#289: « they look presented, not part of a story »): characters meet, help, argue, hand off.
529
+ const multi = characterShots.filter((s) => s.characters.length >= 2);
530
+ const interacting = characterShots.filter((s) => s.characters.length >= 2 && s.interactionKind);
531
+ const kinds = new Set(interacting.map((s) => s.interactionKind));
532
+ const castSize = new Set(story.shots.flatMap((s) => s.characters)).size;
533
+ let interactionScore = 1;
534
+ if (castSize >= 2) {
535
+ const share = characterShots.length ? interacting.length / characterShots.length : 0;
536
+ interactionScore = Number((Math.min(1, kinds.size / exports.MIN_INTERACTION_KINDS) * Math.min(1, share / exports.MIN_INTERACTION_SHARE)).toFixed(3));
537
+ if (kinds.size < exports.MIN_INTERACTION_KINDS) {
538
+ findings.push({
539
+ rule: "interaction",
540
+ message: `the characters only ${[...kinds].join(", ") || "stand side by side"}: they should meet, help, argue, hand off (${exports.MIN_INTERACTION_KINDS} kinds at least)`,
541
+ });
542
+ }
543
+ if (share < exports.MIN_INTERACTION_SHARE) {
544
+ findings.push({
545
+ rule: "interaction",
546
+ message: `${interacting.length} of ${characterShots.length} character shots show characters acting on each other (a third at least)`,
547
+ });
548
+ }
549
+ for (const s of multi)
550
+ if (!s.interactionKind)
551
+ findings.push({
552
+ rule: "interaction",
553
+ shot: s.id,
554
+ message: "several characters share the frame but do nothing to each other",
555
+ });
556
+ }
557
+ // A lineup: characters presented to the camera instead of acting (v1's « five on the ridge turn their heads to us »).
558
+ for (const s of story.shots.filter((x) => x.characters.length >= 3 && !x.reuse)) {
559
+ if (LINEUP.test(s.action) && !s.interactionKind)
560
+ findings.push({ rule: "lineup", shot: s.id, message: "the characters are lined up for the camera, not acting" });
561
+ }
562
+ // Rhythm: shot lengths that vary, and somewhere a run of quick cuts (dynamism).
563
+ const lengths = story.shots.map(screen);
564
+ const mean = lengths.reduce((a, b) => a + b, 0) / Math.max(1, lengths.length);
565
+ const spread = Math.sqrt(lengths.reduce((a, b) => a + (b - mean) ** 2, 0) / Math.max(1, lengths.length)) / Math.max(mean, 1e-6);
566
+ const quickRun = lengths.some((_, i) => i + 2 < lengths.length && lengths.slice(i, i + 3).every((x) => x <= exports.QUICK_SHOT));
567
+ let rhythmOk = 0;
568
+ if (spread >= exports.MIN_LENGTH_SPREAD)
569
+ rhythmOk += 1;
570
+ else
571
+ findings.push({
572
+ rule: "rhythm",
573
+ message: `every shot lasts about the same (spread ${spread.toFixed(2)}): change the rhythm`,
574
+ });
575
+ if (quickRun || story.shots.length < 6)
576
+ rhythmOk += 1;
577
+ else
578
+ findings.push({
579
+ rule: "rhythm",
580
+ message: `no run of quick cuts (three shots of ${exports.QUICK_SHOT} s or less): nothing has momentum`,
581
+ });
582
+ // Legal (the hard rule): no real person, song, game, show or brand named anywhere; every reference says how it is evoked.
583
+ const named = legalFindings(story);
584
+ findings.push(...named);
585
+ const scores = {
586
+ arc: ratio(arcOk, exports.BEATS.length) * (findings.some((f) => f.rule === "arc") ? 0.5 : 1),
587
+ purpose: ratio(purposeful, story.shots.length),
588
+ alive: ratio(alive, characterShots.length),
589
+ onTopic: ratio(onTopic, characterShots.length),
590
+ continuity: ratio(chainOk, chained),
591
+ voice: ratio(voiceOk, story.lines.length),
592
+ music: ratio(musicOk, musicChecks),
593
+ sound: ratio(soundOk, story.shots.length),
594
+ interaction: interactionScore,
595
+ rhythm: ratio(rhythmOk, 2),
596
+ legal: named.length ? 0 : 1,
597
+ };
598
+ const blocking = findings.some((f) => ["arc", "flat", "off-topic", "lineup", "legal"].includes(f.rule));
599
+ return { scores, findings, pass: !blocking && Object.values(scores).every((v) => v >= exports.RUBRIC_THRESHOLD) };
600
+ }
601
+ // ── The language-model judge ────────────────────────────────────────────────────────────────────────────────────────
602
+ /** The axes the judge scores, 1 to 5: what a director would ask of a story before a GPU second is paid. */
603
+ exports.JUDGE_AXES = ["transport", "arc", "characters", "alive", "onTopic", "continuity"];
604
+ /** The judge must give each axis at least this (out of 5) for the story to be filmed. */
605
+ exports.JUDGE_THRESHOLD = 3.5;
606
+ /** The prompt of the critique Studio (pure): the story, compact, and the rubric it is scored against. */
607
+ function judgePrompt(story, language = "en") {
608
+ const shots = story.shots
609
+ .map((s) => `${s.id}. [${s.beat}] ${s.characters.join("+") || "landscape"} — purpose: ${s.purpose} — action: ${s.action}${s.gaze ? " — gaze: " + s.gaze : ""}${s.physics ? " — body: " + s.physics : ""}${s.interactionKind ? " — they " + s.interactionKind : ""}`)
610
+ .join("\n");
611
+ const cast = story.characters.map((c) => `${c.id}: promise «${c.promise}», intention «${c.intention}»`).join("\n");
612
+ const lines = story.lines
613
+ .map((l) => `(${l.shots.join(",")}) ${l.text[language] ?? ""} [${l.direction.emotion}, ${l.direction.pace}]`)
614
+ .join("\n");
615
+ return [
616
+ "You are a demanding film director reviewing a short film's treatment before it is shot. Judge it against this rubric.",
617
+ "transport: does the story carry the viewer (a hook that raises a question, stakes, an emotional turn, a payoff that answers the hook)?",
618
+ "arc: hook → journey → turn → payoff, in that order, each beat earned.",
619
+ "characters: does each character want something that comes from its promise, and do the characters act on each other (meet, help, argue, hand off) instead of being presented in a lineup? Is each role clear from what it does?",
620
+ "rhythm and emotion (part of transport): do the pace and the music change with the places and the beats, with real emotional moments?",
621
+ "alive: does every character shot direct a living performance (gesture, gaze, breath, weight, wings, interaction), not generic motion?",
622
+ "onTopic: does every action serve the beat and the character's promise (no decorative or unrelated action)?",
623
+ "continuity: do shots follow each other in space and time (screen direction, the same props, the same weather)?",
624
+ "Reject every shot whose action is flat (generic motion, nothing changes) or off-topic.",
625
+ 'Answer with ONE JSON object and nothing else: {"scores": {"transport": 1-5, "arc": 1-5, "characters": 1-5, "alive": 1-5, "onTopic": 1-5, "continuity": 1-5}, "rejects": [{"shot": n, "why": "…"}], "notes": "the two changes that would most improve it"}',
626
+ "",
627
+ `TITLE: ${story.title}`,
628
+ `LOGLINE: ${story.logline}`,
629
+ `THEME: ${story.theme}`,
630
+ `CAST:\n${cast}`,
631
+ `SHOTS:\n${shots}`,
632
+ `NARRATION:\n${lines}`,
633
+ ].join("\n");
634
+ }
635
+ /** The judge's answer, read once (pure): scores clamped to 1..5, rejects kept only for shots that exist. */
636
+ function parseJudge(raw, shotCount) {
637
+ const start = raw.indexOf("{");
638
+ const end = raw.lastIndexOf("}");
639
+ if (start < 0 || end <= start)
640
+ throw new StoryError("the judge's answer holds no JSON object");
641
+ let data;
642
+ try {
643
+ data = JSON.parse(raw.slice(start, end + 1));
644
+ }
645
+ catch (error) {
646
+ throw new StoryError(`the judge's answer is not JSON (${error instanceof Error ? error.message : "parse error"})`);
647
+ }
648
+ const given = (data.scores ?? {});
649
+ const scores = Object.fromEntries(exports.JUDGE_AXES.map((a) => [a, Math.min(5, Math.max(1, num(given[a], 1)))]));
650
+ const rejects = list(data.rejects)
651
+ .map((r) => ({ shot: Number(r.shot), why: str(r.why) }))
652
+ .filter((r) => Number.isInteger(r.shot) && r.shot >= 1 && r.shot <= shotCount);
653
+ return { scores, rejects, notes: str(data.notes) };
654
+ }
655
+ function findingLocation(f) {
656
+ if (f.shot)
657
+ return " (shot " + f.shot + ")";
658
+ return f.line ? " (line " + f.line + ")" : "";
659
+ }
660
+ /** The rubric and the judge together: a story is filmed only when both accept it (pure). */
661
+ function verdict(rubric, judge) {
662
+ const reasons = rubric.findings.map((f) => `${f.rule}${findingLocation(f)}: ${f.message}`);
663
+ if (judge) {
664
+ for (const axis of exports.JUDGE_AXES)
665
+ if (judge.scores[axis] < exports.JUDGE_THRESHOLD)
666
+ reasons.push(`judge: ${axis} ${judge.scores[axis]}/5`);
667
+ for (const r of judge.rejects)
668
+ reasons.push(`judge rejects shot ${r.shot}: ${r.why}`);
669
+ }
670
+ const judged = !judge || (exports.JUDGE_AXES.every((a) => judge.scores[a] >= exports.JUDGE_THRESHOLD) && judge.rejects.length === 0);
671
+ return { pass: rubric.pass && judged, reasons, notes: [...reasons, judge?.notes ?? ""].filter(Boolean).join("\n") };
672
+ }
673
+ // ── The timeline: lines, music and sound placed on the cut ─────────────────────────────────────────────────────────
674
+ /** When a line starts after its first shot's cut (a beat to let the picture land), in seconds. */
675
+ exports.LINE_LEAD = 0.35;
676
+ /** A line may run over its last shot's cut by at most this (the voice can carry across a cut, briefly). */
677
+ exports.LINE_SPILL = 0.4;
678
+ /**
679
+ * The film's timeline (pure). `spans` are the shots' places in the cut when the edit is known (after snapping to the
680
+ * music); otherwise each shot's screen time back to back. `voice` is each line's measured length in seconds (from the
681
+ * voice step); a line without one is given the time its words take at the pace asked.
682
+ */
683
+ function timeline(story, language = "en", voice = {}, spans) {
684
+ let t = 0;
685
+ const shots = story.shots.map((s, i) => {
686
+ const [start, end] = spans?.[i] ?? [t, t + screen(s)];
687
+ t = end;
688
+ return { id: s.id, start: round(start), end: round(end), beat: s.beat };
689
+ });
690
+ const seconds = shots.length ? shots.at(-1).end : 0;
691
+ const wps = { slow: 1.9, measured: 2.3, rhythmic: 2.4, lively: 2.7 };
692
+ const lines = story.lines.map((l) => {
693
+ const first = shots[l.shots[0] - 1];
694
+ const last = shots[l.shots.at(-1) - 1];
695
+ const words = (l.text[language] ?? "").split(/\s+/).filter(Boolean).length;
696
+ const length = voice[l.id] ?? words / wps[l.direction.pace];
697
+ const start = first.start + exports.LINE_LEAD;
698
+ const end = start + length;
699
+ const room = last.end + exports.LINE_SPILL - end;
700
+ return { id: l.id, start: round(start), end: round(end), fits: room >= 0, room: round(room) };
701
+ });
702
+ // Cues that name their shots follow the place (a genre per city); the others follow their beat.
703
+ const music = story.music.cues.some((c) => c.shots)
704
+ ? story.music.cues
705
+ .filter((c) => c.shots)
706
+ .map((c, i) => ({
707
+ id: c.genre ? `${i + 1}-${c.genre}` : `${i + 1}-${c.beat}`,
708
+ start: shots[c.shots[0] - 1].start,
709
+ end: shots[c.shots[1] - 1].end,
710
+ intensity: c.intensity,
711
+ }))
712
+ : exports.BEATS.flatMap((b) => {
713
+ const inBeat = shots.filter((s) => s.beat === b);
714
+ const cue = story.music.cues.find((c) => c.beat === b);
715
+ if (!inBeat.length || !cue)
716
+ return [];
717
+ return [{ id: b, start: inBeat[0].start, end: inBeat.at(-1).end, intensity: cue.intensity }];
718
+ });
719
+ const sound = story.shots.flatMap((s, i) => s.sound.map((c) => {
720
+ const shot = shots[i];
721
+ const start = c.at === undefined ? shot.start : Math.min(shot.end, shot.start + c.at / (s.speed || 1));
722
+ return {
723
+ shot: s.id,
724
+ kind: c.kind,
725
+ start: round(start),
726
+ end: c.at === undefined ? shot.end : round(start),
727
+ gain: c.gain,
728
+ };
729
+ }));
730
+ return { shots, lines, music, sound, seconds: round(seconds) };
731
+ }
732
+ const round = (v) => Number(v.toFixed(3));
733
+ // ── The directed motion of a shot ───────────────────────────────────────────────────────────────────────────────────
734
+ /**
735
+ * The motion prompt of a shot written from its parts when the treatment gives none (pure): who, what they want, the
736
+ * action as a sequence, where they look, the physics of the body, the camera and the light — said positively (a
737
+ * distilled video model ignores negatives). A living performance is directed, never left to « the bird moves ».
738
+ */
739
+ function directedMotion(story, shot) {
740
+ if (shot.motion)
741
+ return shot.motion;
742
+ const who = shot.characters
743
+ .map((id) => story.characters.find((c) => c.id === id)?.description)
744
+ .filter(Boolean)
745
+ .join(" and ");
746
+ const parts = [
747
+ who ? `${capital(who)}.` : "",
748
+ shot.intent ? `Intention: ${shot.intent}.` : "",
749
+ shot.action ? `${capital(shot.action.replace(/;\s*/g, ", then "))}.` : "",
750
+ shot.gaze ? `Gaze: ${shot.gaze}.` : "",
751
+ shot.physics ? `Physical detail: ${shot.physics}.` : "",
752
+ shot.interaction ? `Together: ${shot.interaction}.` : "",
753
+ [shot.camera, shot.lens].filter(Boolean).join(", ") + (shot.camera || shot.lens ? "." : ""),
754
+ [shot.lighting, shot.atmosphere].filter(Boolean).join(", ") + (shot.lighting || shot.atmosphere ? "." : ""),
755
+ ];
756
+ return parts.filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
757
+ }
758
+ const capital = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);