@kriya-ai/harness 0.2.3 → 0.2.5

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 (41) hide show
  1. package/contract/SOURCE.md +3 -3
  2. package/contract/contract.json +194 -0
  3. package/package.json +1 -1
  4. package/src/edit/core/ffmpeg.js +19 -1
  5. package/src/edit/core/layout.js +24 -1
  6. package/src/edit/core/ops.js +9 -3
  7. package/src/edit/core/plan.js +36 -5
  8. package/src/edit/core/solver.js +39 -3
  9. package/src/edit/core/transitions.js +17 -0
  10. package/src/edit/director/beats.js +335 -0
  11. package/src/edit/director/continuity.js +129 -0
  12. package/src/edit/director/graphics.js +152 -0
  13. package/src/edit/director/lookups.js +133 -0
  14. package/src/edit/director/plan.js +118 -6
  15. package/src/edit/director/playbooks.js +131 -0
  16. package/src/edit/director/revise.js +49 -5
  17. package/src/edit/engine/captions.js +32 -0
  18. package/src/edit/engine/found-media.js +64 -0
  19. package/src/edit/engine/graphics.js +178 -0
  20. package/src/edit/engine/motion.js +24 -3
  21. package/src/edit/engine/scenes.js +480 -0
  22. package/src/edit/gates/copy.js +25 -5
  23. package/src/edit/gates/index.js +16 -5
  24. package/src/edit/gates/picture.js +11 -3
  25. package/src/edit/gates/text.js +20 -4
  26. package/src/edit/graph/scheduler.js +1 -1
  27. package/src/edit/host/deliver.js +8 -1
  28. package/src/edit/host/main.js +8 -5
  29. package/src/edit/host/paths.js +15 -2
  30. package/src/edit/host/projects.js +229 -12
  31. package/src/edit/host/server.js +72 -3
  32. package/src/edit/index/views.js +9 -0
  33. package/src/edit/loop/make.js +25 -6
  34. package/src/edit/recipes/graphic-clips.js +57 -0
  35. package/src/edit/recipes/montage.js +74 -0
  36. package/src/edit/recipes/programme.js +24 -0
  37. package/src/edit/recipes/reel.js +65 -14
  38. package/src/edit/recipes/scene-clips.js +127 -0
  39. package/src/edit/runtime/fetch.js +33 -0
  40. package/studio/dist/studio.css +15 -0
  41. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,335 @@
1
+ // Visual beats (VISUAL_SCENES.md, EDD-51): which moments of the speech become an explainer
2
+ // scene. One model slot proposes them as typed JSON; code decides everything that can be
3
+ // decided: the words must have been said, the numbers must have been said here, and each
4
+ // scene spans whole sentences of a sensible length. With no model, code's own patterns
5
+ // find what they can, and only what they are sure of.
6
+
7
+ import { cleanScene, FLOW_MODES, SCENE_KINDS, SCENE_THEMES } from "../engine/scenes.js"
8
+ import { phraseView } from "../index/views.js"
9
+
10
+ const FLICKS = 705_600_000
11
+ const MIN_SCENE = 2.5 * FLICKS
12
+ const MAX_SCENE = 14 * FLICKS
13
+ const MIN_GAP = 1.5 * FLICKS
14
+ export const MAX_SHARE = 0.65 // of the cut under scenes: the speaker stays part of the film
15
+ export const MAX_SCENES = 10
16
+
17
+ /* ─────────────────────────────── what was said ─────────────────────────────── */
18
+
19
+ const SMALL = new Set("a an the of to in on at by for from with and or but so if as is are was were be been it its this that these those your you we our their his her they he she i my me not no do does did has have had will would can could should then than very more most into out up down over under about how what why when where which who".split(" "))
20
+ const tokens = (text) => String(text).normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}.,%]+/u).map((t) => t.replace(/^[.,]+|[.,]+$/g, "")).filter(Boolean)
21
+ // shortcut: English endings only; a label in another language must match the transcript's word as it stands
22
+ const stem = (word) => (word.length > 4 ? word.replace(/(?:ing|ed|es|s)$/, "") : word)
23
+ const isNumber = (token) => /^\d[\d.,]*%?$/.test(token)
24
+ const bare = (token) => token.replace(/%$/, "").replace(/,/g, "")
25
+
26
+ const ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
27
+ const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
28
+
29
+ /** Numbers in spoken words, as digits: "seventy five" → "75", "two hundred" → "200", "a thousand" → "1000". */
30
+ export function numbersSaid(text) {
31
+ const out = new Set()
32
+ const words = tokens(text)
33
+ let current = null
34
+ const flush = () => {
35
+ if (current !== null) out.add(String(current))
36
+ current = null
37
+ }
38
+ for (const word of words) {
39
+ if (isNumber(word)) {
40
+ flush()
41
+ out.add(bare(word))
42
+ continue
43
+ }
44
+ const one = ONES.indexOf(word)
45
+ const ten = TENS.indexOf(word)
46
+ if (one >= 0) current = (current ?? 0) + one
47
+ else if (ten >= 2) current = (current ?? 0) + ten * 10
48
+ else if (word === "hundred" || word === "thousand") current = (current ?? 1) * (word === "hundred" ? 100 : 1000)
49
+ else if (!(word === "and" && current !== null)) flush()
50
+ }
51
+ flush()
52
+ return out
53
+ }
54
+
55
+ const UNITS = { "%": /percent|per cent|%/i, mg: /milligram|\bmg\b/i, g: /\bgrams?\b|\bg\b/i, kg: /kilo/i, km: /kilomet/i, m: /\bmet(?:er|re)s?\b/i, cm: /centimet/i, mm: /millimet/i, l: /lit(?:er|re)s?\b/i, ml: /millilit/i, s: /\bseconds?\b/i, min: /\bminutes?\b/i, h: /\bhours?\b/i, x: /\btimes\b/i, "₹": /rupee|₹/i, $: /dollar|\$/ }
56
+
57
+ /**
58
+ * Why a scene's words aren't the speaker's: every word on screen was said somewhere in the
59
+ * take, and every number was said in or next to this scene's own lines. Nothing else
60
+ * reaches the screen, so a model can't add a fact (a figure, a name) the person never said.
61
+ * @param {object} scene from cleanScene
62
+ * @param {{ all: string, near: string }} said the whole take's text, and this scene's lines with their neighbours
63
+ * @returns {string[]}
64
+ */
65
+ export function groundProblems(scene, { all, near }) {
66
+ const problems = []
67
+ const known = new Set(tokens(all).map(stem))
68
+ const numbers = numbersSaid(near)
69
+ const check = (text) => {
70
+ for (const token of tokens(text)) {
71
+ if (isNumber(token)) {
72
+ if (!numbers.has(bare(token))) problems.push(`the number "${token}" isn't said in this scene's lines`)
73
+ } else if (!SMALL.has(token) && !known.has(stem(token))) problems.push(`"${token}" isn't in the speaker's words`)
74
+ }
75
+ }
76
+ check(scene.title)
77
+ for (const item of scene.items) {
78
+ check(item.text)
79
+ if (item.value !== undefined && !numbers.has(item.value.replace(/,/g, ""))) problems.push(`the number "${item.value}" isn't said in this scene's lines`)
80
+ if (item.unit) {
81
+ const cue = UNITS[item.unit.toLowerCase()]
82
+ if (cue ? !cue.test(near) : !known.has(stem(item.unit.toLowerCase()))) problems.push(`the unit "${item.unit}" isn't said in this scene's lines`)
83
+ }
84
+ }
85
+ return problems
86
+ }
87
+
88
+ /* ─────────────────────────────── phrases ─────────────────────────────── */
89
+
90
+ const MAX_PHRASE = 8 * FLICKS
91
+ const MIN_PHRASE = 1.2 * FLICKS
92
+ const PAUSE = 0.35 * FLICKS
93
+ const CLAUSE = /^(?:so|but|because|where|which|as|then|when|while|resulting|despite|without|until|since|although)$/i
94
+
95
+ /**
96
+ * A take's phrases: what a scene can start and end on. Recognised speech has few sentence
97
+ * marks (found on a real take: one "sentence" of 29 s, another of 22 s), so a sentence is too
98
+ * coarse; a phrase ends at a sentence end, a pause or a new clause, and caps at 8 s.
99
+ * @returns {{ first: number, last: number, start: number, end: number, text: string }[]} first, last: positions in `words`
100
+ */
101
+ export function phrasesOf(index, asset) {
102
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
103
+ const ends = new Set((index.sentences ?? []).filter((s) => s.asset === asset).map((s) => s.lastWord))
104
+ const out = []
105
+ let first = 0
106
+ const close = (last) => {
107
+ out.push({ first, last, start: words[first].start, end: words[last].end, text: words.slice(first, last + 1).map((w) => w.text).join(" ") })
108
+ first = last + 1
109
+ }
110
+ for (let i = 0; i < words.length; i++) {
111
+ const next = words[i + 1]
112
+ if (!next || ends.has(words[i].id)) {
113
+ close(i)
114
+ continue
115
+ }
116
+ const length = words[i].end - words[first].start
117
+ if (next.start - words[i].end >= PAUSE && length >= MIN_PHRASE) close(i)
118
+ else if (CLAUSE.test(tokens(next.text)[0] ?? "") && length >= MIN_PHRASE) close(i)
119
+ else if (next.end - words[first].start > MAX_PHRASE) close(i)
120
+ }
121
+ return out
122
+ }
123
+
124
+ /* ─────────────────────────────── placing ─────────────────────────────── */
125
+
126
+ const out = (word, cuts) => cuts.some((c) => (word.start + word.end) / 2 >= c.from * FLICKS && (word.start + word.end) / 2 < c.to * FLICKS)
127
+ const OPENING = 3 * FLICKS // the speaker is seen first
128
+ const NEAR = 6 * FLICKS // "said in or next to this scene's lines"
129
+
130
+ /**
131
+ * Scenes that may be made, in order: real words, forward, on phrase edges, a sensible length,
132
+ * room between them, under the share, words grounded. Each dropped one says why.
133
+ * @param {object[]} raw a model's or a browser's scenes; from and to are word ids or sentence ids
134
+ * @param {{ index: object, asset: string, cuts?: { from: number, to: number }[], limit?: number }} input cuts in seconds of the take
135
+ */
136
+ export function arrangeScenes(raw, { index, asset, cuts = [], limit = MAX_SCENES }) {
137
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
138
+ const total = words.length ? words.at(-1).end - words[0].start : 0
139
+ const phrases = phrasesOf(index, asset)
140
+ const position = new Map(words.map((w, i) => [w.id, i]))
141
+ const sentence = new Map((index.sentences ?? []).filter((s) => s.asset === asset).map((s) => [s.id, s]))
142
+ const phraseAt = (i) => phrases.findIndex((p) => i >= p.first && i <= p.last)
143
+ const startOf = (id) => phraseAt(position.get(sentence.get(id)?.firstWord ?? id) ?? -1)
144
+ const endOf = (id) => phraseAt(position.get(sentence.get(id)?.lastWord ?? id) ?? -1)
145
+ const all = words.map((w) => w.text).join(" ")
146
+ const dropped = []
147
+ const placed = []
148
+ const spans = (Array.isArray(raw) ? raw : [])
149
+ .map(cleanScene)
150
+ .filter(Boolean)
151
+ .map((scene) => ({ scene, i: startOf(scene.from), k: endOf(scene.to) }))
152
+ .sort((a, b) => (a.i < 0 ? Infinity : a.i) - (b.i < 0 ? Infinity : b.i))
153
+ let used = 0
154
+ for (const { scene, i, k: asked } of spans) {
155
+ const drop = (reason) => dropped.push({ scene, reason })
156
+ if (i < 0 || asked < i) {
157
+ drop("its lines aren't in this take")
158
+ continue
159
+ }
160
+ let k = asked
161
+ // A short phrase takes the next one with it, so a scene is on screen long enough to read
162
+ while (k + 1 < phrases.length && phrases[k].end - phrases[i].start < MIN_SCENE) k++
163
+ const start = phrases[i].start
164
+ const end = phrases[k].end
165
+ const span = end - start
166
+ if (!words.length || start - words[0].start < OPENING) drop("the first line stays on the speaker, as the hook")
167
+ else if (span < MIN_SCENE) drop("its lines are too short to read a scene")
168
+ else if (span > MAX_SCENE) drop("its lines run too long for one scene")
169
+ else if (words.some((w) => w.start >= start && w.end <= end && out(w, cuts))) drop("it covers a stretch you asked to trim")
170
+ else if (placed.length && start - placed.at(-1).end < MIN_GAP) drop("it comes too soon after the last scene")
171
+ else if (placed.length >= limit) drop("there are already enough scenes")
172
+ else if (total && used + span > total * MAX_SHARE) drop("the speaker would hardly be seen")
173
+ else {
174
+ const near = words.filter((w) => w.end >= start - NEAR && w.start <= end + NEAR).map((w) => w.text).join(" ")
175
+ const wrong = groundProblems(scene, { all, near })
176
+ if (wrong.length) drop(wrong[0])
177
+ else {
178
+ used += span
179
+ placed.push({ start, end, scene: { ...scene, from: words[phrases[i].first].id, to: words[phrases[k].last].id } })
180
+ }
181
+ }
182
+ }
183
+ return { scenes: placed.map((p) => p.scene), dropped }
184
+ }
185
+
186
+ /**
187
+ * The word each label is spoken on, in order, so it lands as it's said; null where the
188
+ * label's words aren't in these words (it then comes in evenly).
189
+ * @param {object} scene
190
+ * @param {{ id: string, text: string }[]} spoken the scene's words, in order
191
+ */
192
+ export function revealWords(scene, spoken) {
193
+ let from = 0
194
+ return scene.items.map((item) => {
195
+ const wanted = new Set([...tokens(item.text), ...(item.value ? [item.value] : [])].filter((t) => !SMALL.has(t)).map(stem))
196
+ for (let i = from; i < spoken.length; i++) {
197
+ if (tokens(spoken[i].text).some((t) => wanted.has(stem(t)) || wanted.has(bare(t)))) {
198
+ from = i + 1
199
+ return spoken[i]
200
+ }
201
+ }
202
+ return null
203
+ })
204
+ }
205
+
206
+ /* ─────────────────────────────── code's own beats ─────────────────────────────── */
207
+
208
+ const LEAD = /^(?:(?:so|and|but|then|now|that|this|the|a|an|your|our|it|when|because|which|without)\s+)+/i
209
+ const HELPERS = /\s+(?:starts?|begins?|keeps?|tends?|continues?|is|are|was|were|will)(?:\s+to)?$/i
210
+ function phrase(text, words = 4) {
211
+ const cleaned = String(text).replace(/[^\p{L}\p{N}%' -]+/gu, " ").replace(/\s+/g, " ").trim().replace(LEAD, "").replace(HELPERS, "")
212
+ return cleaned.split(" ").slice(-words).join(" ").slice(0, 32).trim()
213
+ }
214
+ const CHAIN = /\s*(?:\bwhich (?:then )?(?:leads? to|causes?|makes?)\b|\bleads? to\b|\bcauses?\b|\bturns? into\b|\bresults? in\b|\band then\b|\bthen\b|→)\s*/i
215
+ const FLOW = /\b([\p{L}\p{N} '-]{3,30}?)\s+(flood|flow|mov|enter|travel|pass|go)(?:s|es|ing|ed)?\s+(?:in ?to|through|to)\s+(?:the\s+|your\s+|a\s+)?([\p{L}\p{N} '-]{3,30})/iu
216
+ const VERSUS = /\b([\p{L}\p{N} '-]{3,30}?)\s+(?:versus|vs\.?|compared (?:to|with)|unlike)\s+(?:the\s+|a\s+)?([\p{L}\p{N} '-]{3,30})/iu
217
+ const PERCENT = /\b(\d{1,3}(?:\.\d{1,2})?)\s*(?:%|percent\b|per cent\b)\s*(?:of\s+)?([\p{L}\p{N} '-]{3,40})?/iu
218
+
219
+ /**
220
+ * The beats code is sure of, from what the sentence says outright.
221
+ * shortcut: English patterns only; with no model, speech in another language gets no scene. A model reads any language.
222
+ */
223
+ export function codeBeats(index, asset) {
224
+ const out = []
225
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
226
+ for (const { first, last, text } of phrasesOf(index, asset)) {
227
+ const base = { from: words[first].id, to: words[last].id, title: "" }
228
+ const percent = PERCENT.exec(text)
229
+ const flow = FLOW.exec(text)
230
+ const versus = VERSUS.exec(text)
231
+ const chain = text.split(CHAIN).map((part) => phrase(part)).filter(Boolean)
232
+ if (percent && phrase(percent[2] ?? "")) out.push({ ...base, kind: "stat", items: [{ text: String(percent[2]).trim().split(" ").slice(0, 5).join(" ").slice(0, 32).trim(), value: percent[1], unit: "%" }] })
233
+ else if (versus && phrase(versus[1]) && phrase(versus[2])) out.push({ ...base, kind: "compare", items: [{ text: phrase(versus[1]) }, { text: String(versus[2]).trim().split(" ").slice(0, 4).join(" ").slice(0, 32).trim() }] })
234
+ else if (flow && phrase(flow[1]) && phrase(flow[3])) out.push({ ...base, kind: "flow", mode: /flood/i.test(flow[2]) ? "floods" : /\b(?:can't|cannot|can not|blocked|stops?)\b/i.test(text) ? "blocked" : "flows", items: [{ text: phrase(flow[1]) }, { text: String(flow[3]).trim().split(" ").slice(0, 4).join(" ").slice(0, 32).trim() }] })
235
+ else if (chain.length >= 3 && chain.length <= 5) out.push({ ...base, kind: "process", items: chain.map((text) => ({ text })) })
236
+ }
237
+ return out
238
+ }
239
+
240
+ /* ─────────────────────────────── the slot ─────────────────────────────── */
241
+
242
+ const SCENES_SCHEMA = {
243
+ type: "object",
244
+ properties: {
245
+ contentType: { type: "string", enum: ["explainer", "tutorial", "story", "opinion", "interview", "vlog", "promo", "other"] },
246
+ theme: { type: "string", enum: Object.keys(SCENE_THEMES) },
247
+ scenes: {
248
+ type: "array",
249
+ maxItems: MAX_SCENES,
250
+ items: {
251
+ type: "object",
252
+ properties: {
253
+ from: { type: "string", maxLength: 64 },
254
+ to: { type: "string", maxLength: 64 },
255
+ kind: { type: "string", enum: Object.keys(SCENE_KINDS) },
256
+ mode: { type: "string", enum: FLOW_MODES },
257
+ title: { type: "string", maxLength: 60 },
258
+ items: {
259
+ type: "array",
260
+ maxItems: 6,
261
+ items: { type: "object", properties: { text: { type: "string", maxLength: 32 }, value: { type: "string", maxLength: 12 }, unit: { type: "string", maxLength: 8 } }, required: ["text"], additionalProperties: false },
262
+ },
263
+ },
264
+ required: ["from", "to", "kind", "title", "items"],
265
+ additionalProperties: false,
266
+ },
267
+ },
268
+ },
269
+ required: ["contentType", "theme", "scenes"],
270
+ additionalProperties: false,
271
+ }
272
+
273
+ const SAID_OFF = /\b(?:no|without|skip|don't (?:want|add|use)|do not (?:want|add|use))\s+(?:any\s+|the\s+)?(?:animations?|diagrams?|visuals?|graphics|scenes|illustrations?)\b/i
274
+ const SAID_ON = /\b(?:animat\w*|diagrams?|visuals?|graphics|illustrat\w*|explainer|cutaways?)\b/i
275
+ const SAID_THEMES = [[/\bblue ?prints?\b/i, "blueprint"], [/\bchalk ?(?:board)?\b|\bblackboard\b/i, "chalk"], [/\bpaper\b|\bwhite ?board\b|\blight (?:look|theme|background)\b/i, "paper"], [/\blab\b|\bdark (?:look|theme|background)\b/i, "lab"]]
276
+ // Types of video where a diagram is usually what the viewer needs
277
+ const EXPLAINS = new Set(["explainer", "tutorial", "promo"])
278
+
279
+ /** What the person's words say about scenes: "off", "on", or null. */
280
+ export function visualsIn(text) {
281
+ return SAID_OFF.test(text) ? "off" : SAID_ON.test(text) ? "on" : null
282
+ }
283
+
284
+ const themeIn = (text) => SAID_THEMES.find(([cue]) => cue.test(text))?.[1] ?? null
285
+
286
+ /**
287
+ * The scenes for a plan. The person's words come first: "no animations" means none and no
288
+ * call. A revision that doesn't mention them keeps the ones on the card.
289
+ * @param {{ ask: Function, index: object, asset: string, text: string, history?: object[], previous?: object | null, cuts?: object[], signal?: AbortSignal }} input
290
+ * @returns {Promise<{ scenes: object[], contentType: string | null, source: string, dropped: object[] }>}
291
+ */
292
+ export async function planScenes({ ask, index, asset, text, history = [], previous = null, cuts = [], signal }) {
293
+ const said = [...history.filter((h) => h.who === "you").map((h) => h.text), text]
294
+ const verdict = said.map(visualsIn).filter(Boolean).at(-1) ?? null
295
+ if (verdict === "off") return { scenes: [], contentType: null, source: "person", dropped: [] }
296
+ const themeSaid = said.map(themeIn).filter(Boolean).at(-1) ?? null
297
+ const restyle = (scenes) => (themeSaid ? scenes.map((scene) => ({ ...scene, theme: themeSaid })) : scenes)
298
+ const kept = previous?.settings?.scenes
299
+ if (Array.isArray(kept) && !visualsIn(text)) {
300
+ const { scenes, dropped } = arrangeScenes(restyle(kept), { index, asset, cuts })
301
+ return { scenes, contentType: null, source: "kept", dropped }
302
+ }
303
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
304
+ const phrases = phrasesOf(index, asset)
305
+ const usable = words.length ? (words.at(-1).end - words[0].start) / FLICKS : 0
306
+ const limit = Math.max(1, Math.min(MAX_SCENES, Math.round(usable / 9)))
307
+ if (phrases.length < 2) return { scenes: [], contentType: null, source: "code", dropped: [] }
308
+ const hints = codeBeats(index, asset)
309
+ const kinds = Object.entries(SCENE_KINDS).map(([id, kind]) => `- ${id} (${kind.min === kind.max ? kind.min : `${kind.min} to ${kind.max}`} items): ${kind.when}`).join("\n")
310
+ const request = [
311
+ `The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 1200))}`,
312
+ "You are the Director choosing the moments where an animated explainer scene takes over the frame while the speaker's voice keeps playing, the way a top science channel cuts away from the presenter to show the idea. First decide the contentType of this video.",
313
+ verdict === "on" ? "The person asked for visuals, so propose them whatever the contentType." : "If this video isn't explaining something (a story, an opinion, a personal moment, a vlog), answer with no scenes: a diagram would get in the way.",
314
+ `Choose up to ${limit} scenes, the moments that are hard to picture from words alone: how something works, a cause and effect, a process, numbers. Keep the speaker on screen for the opening line, for anything personal or emotional and for calls to action. Let the film breathe: leave the speaker on screen between scenes.`,
315
+ `A scene covers whole phrases, about 3 to 12 seconds: \`from\` is the first word id of its first phrase, \`to\` the last word id of its last phrase. Choose lines where something can be shown, and start each scene as the idea starts. The kinds:\n${kinds}`,
316
+ "Hard rules, checked by code, which throws away a scene that breaks them: every word on the scene comes from what the speaker actually says, in the speaker's language, as short labels of 1 to 4 words; a number only if the speaker says it in those lines, as digits, in `value`, with `unit` only if they say the unit. Never add a fact, figure or name of your own, however true. List items in the order they are spoken. `title` is at most 6 of the speaker's words, or empty.",
317
+ "Use a variety of kinds, each right for its moment. Choose one theme for the whole film: lab (dark, scientific), blueprint (engineering), chalk (a lesson), paper (light).",
318
+ hints.length ? `Code found these candidates, which may help: ${JSON.stringify(hints.slice(0, 8).map((h) => ({ from: h.from, kind: h.kind })))}.` : "",
319
+ ].filter(Boolean).join("\n")
320
+ // A scene that fails is dropped below; only a whole answer with nothing usable goes back to the model
321
+ const check = ({ scenes }) => {
322
+ if (!scenes.length) return []
323
+ const tried = arrangeScenes(scenes, { index, asset, cuts, limit })
324
+ return tried.scenes.length ? [] : tried.dropped.slice(0, 3).map((d) => `scene on ${d.scene.from}: ${d.reason}`)
325
+ }
326
+ const slot = (tier) => ask({ task: "scenes", tier, schema: SCENES_SCHEMA, view: phraseView(phrases.map((p) => ({ ...p, from: words[p.first].id, to: words[p.last].id }))), request, maxOutput: 2200, check, fallback: () => ({ contentType: "other", theme: "lab", scenes: hints }), signal, priority: 0 })
327
+ let answer = await slot("balanced")
328
+ // Refused before it answered (a plan without that tier): the budget model can still do this
329
+ if (answer.source === "default" && answer.calls === 1) answer = await slot("budget")
330
+ const { value } = answer
331
+ if (answer.source !== "default" && verdict !== "on" && !EXPLAINS.has(value.contentType)) return { scenes: [], contentType: value.contentType, source: answer.source, dropped: [] }
332
+ const themed = restyle((value.scenes ?? []).map((scene) => ({ ...scene, theme: value.theme })))
333
+ const { scenes, dropped } = arrangeScenes(themed, { index, asset, cuts, limit })
334
+ return { scenes, contentType: value.contentType ?? null, source: answer.source, dropped }
335
+ }
@@ -0,0 +1,129 @@
1
+ // A change asked for after a cut exists is a change to that cut (2026-11-10): the Director
2
+ // revises the plan it made, the story stays unless the length or the trims change, and the
3
+ // person's own edits since are replayed on the remade cut. Pure: the Host keeps the record.
4
+
5
+ import { solve } from "../core/solver.js"
6
+
7
+ // The plan sets these on every make, so an older one isn't carried over it
8
+ const PLANS_OWN = new Set(["set_brief", "set_format", "add_deliverable", "name_version"])
9
+
10
+ /**
11
+ * The operations landed after a version, oldest first: what the person (or the console, on
12
+ * their accepting) did to the cut since it was made.
13
+ * @returns {object[] | null} null when HEAD doesn't descend from that version (the make was undone)
14
+ */
15
+ export function editsSince(log, head) {
16
+ const byId = new Map(log.entries.map((e) => [e.id, e]))
17
+ const chain = []
18
+ for (let at = log.head; at !== head; at = byId.get(at).parent) {
19
+ if (at === null || !byId.has(at)) return null
20
+ chain.unshift(byId.get(at))
21
+ }
22
+ return chain.flatMap((e) => e.ops).filter((op) => !PLANS_OWN.has(op.op))
23
+ }
24
+
25
+ /** The last make's story, when this brief cuts the same footage to the same length; else null and it's chosen again. */
26
+ export function storyFor(last, brief = {}) {
27
+ if (!last?.story || !last.brief) return null
28
+ const same = last.brief.targetDuration === brief.targetDuration && JSON.stringify(last.brief.cuts ?? []) === JSON.stringify(brief.cuts ?? [])
29
+ return same ? last.story : null
30
+ }
31
+
32
+ /**
33
+ * Where each clip of the cut before went in the remade one (a remake gives every clip a new
34
+ * id): a caption by its first word, footage by its track and the most source time it shares.
35
+ * A clip's own source is word anchors, so the times come from the solved timelines.
36
+ * @returns {Map<string, string>}
37
+ */
38
+ export function remapIds(before, after, index) {
39
+ const clipsOf = (project) => project.sequences.find((q) => q.id === project.active)?.clips ?? []
40
+ const caption = (clip) => clip.effects?.find((e) => e.type === "caption")
41
+ // Each footage clip's stretch of its source, as played: asset, first in, last out
42
+ const spans = (project) => {
43
+ const out = new Map()
44
+ for (const p of solve(project, index).picture) {
45
+ if (p.hold) continue
46
+ const span = out.get(p.clip)
47
+ if (span) Object.assign(span, { in: Math.min(span.in, p.in), out: Math.max(span.out, p.out) })
48
+ else out.set(p.clip, { asset: p.asset, in: p.in, out: p.out, echo: !!p.echo })
49
+ }
50
+ return out
51
+ }
52
+ const [was, now] = [spans(before), spans(after)]
53
+ const next = clipsOf(after)
54
+ const ids = new Map()
55
+ for (const old of clipsOf(before)) {
56
+ if (next.some((c) => c.id === old.id)) continue // it survived the remake as it is
57
+ const words = caption(old)?.words
58
+ let found = null
59
+ if (words?.length) found = next.find((c) => caption(c)?.words?.[0] === words[0])?.id ?? null
60
+ else if (was.has(old.id)) {
61
+ const a = was.get(old.id)
62
+ let most = 0
63
+ for (const [id, b] of now) {
64
+ if (b.asset !== a.asset || b.echo !== a.echo || clipsOf(after).find((c) => c.id === id)?.track !== old.track) continue
65
+ const shared = Math.min(a.out, b.out) - Math.max(a.in, b.in)
66
+ if (shared > most) ((most = shared), (found = id))
67
+ }
68
+ }
69
+ if (found) ids.set(old.id, found)
70
+ }
71
+ return ids
72
+ }
73
+
74
+ // What a remake undoes: edits to the picture, the captions and the voice, which it rebuilds.
75
+ // A title, a graphic, B-roll, a marker or a sound sits on its own track and is still there, so
76
+ // replaying it would put it on screen twice; the music and the opening are the plan's to set
77
+ const REMADE = new Set(["keep_range", "remove_range", "use_take", "reorder", "trim", "split", "ripple_delete", "punch_in", "reframe", "speed", "speed_ramp", "freeze", "stabilize", "set_camera", "caption_style", "caption_edit", "caption_emphasis", "text_behind", "transition", "clean_voice", "set_level", "grade", "match_color", "apply_lut", "fix_exposure"])
78
+
79
+ /**
80
+ * The edits worth replaying on a remade cut: those the remake undid. One aimed at a clip
81
+ * that was already gone before the remake has nothing left to do, and is left out quietly.
82
+ */
83
+ export function replayable(edits, before) {
84
+ const there = new Set((before.sequences.find((q) => q.id === before.active)?.clips ?? []).map((c) => c.id))
85
+ return edits.filter((op) => REMADE.has(op.op) && ["clip", "caption"].every((key) => typeof op[key] !== "string" || there.has(op[key])))
86
+ }
87
+
88
+ /** An operation pointed at the remade cut's clips. */
89
+ export function remapOp(op, ids) {
90
+ const out = { ...op }
91
+ for (const key of ["clip", "caption", "after"]) if (typeof out[key] === "string" && ids.has(out[key])) out[key] = ids.get(out[key])
92
+ return out
93
+ }
94
+
95
+ const count = (noun) => (list) => (list?.length ? `${list.length} ${noun}${list.length === 1 ? "" : "s"}` : "none")
96
+ const onOff = (value) => (value ? "on" : "off")
97
+ const plain = (value) => (value === undefined || value === null || value === false || value === "" ? "none" : String(value))
98
+ const LINES = [
99
+ ["format", "Format", plain],
100
+ ["seconds", "Length", (v) => (v ? `${v} s` : "the recipe's")],
101
+ ["captions", "Captions", plain],
102
+ ["grade", "Colour look", plain],
103
+ ["music", "Music", (v) => plain(v).replace(/^generated:/, "")],
104
+ ["cleanVoice", "Voice cleanup", onOff],
105
+ ["hook", "Hook line", (v) => (v ? "chosen" : "none")],
106
+ ["coldOpen", "Cold open", (v) => (v ? `${v.from} to ${v.to}` : "none")],
107
+ ["cutSound", "Sound on cuts", plain],
108
+ ["introSound", "Sound into the story", plain],
109
+ ["punches", "Punch-ins", plain],
110
+ ["angles", "Wide and tight angles", onOff],
111
+ ["broll", "B-roll", plain],
112
+ ["titles", "Title cards", onOff],
113
+ ["ramps", "Speed ramp", onOff],
114
+ ["cuts", "Trims", count("stretch")],
115
+ ["scenes", "Animated scenes", count("scene")],
116
+ ["graphics", "Motion graphics", count("graphic")],
117
+ ["transition", "Transitions", plain],
118
+ ["transitionAll", "Transitions on every cut", onOff],
119
+ ["pictures", "Pictures", count("picture")],
120
+ ["terms", "Definitions", count("definition")],
121
+ ]
122
+
123
+ /** What a revised plan changes, in words, from the two briefs alone: never from a model's pitch. */
124
+ export function planDiff(before = {}, after = {}) {
125
+ return LINES.flatMap(([key, label, show]) => {
126
+ const [was, now] = [show(before[key]), show(after[key])]
127
+ return was === now && JSON.stringify(before[key]) === JSON.stringify(after[key]) ? [] : was === now ? [`${label}: changed`] : [`${label}: ${was} → ${now}`]
128
+ })
129
+ }
@@ -0,0 +1,152 @@
1
+ // The Director's motion graphics (MOTION_GRAPHICS.md, EDD-58): it proposes titles, a name
2
+ // strap, an opening title, an end card, quotes and numbers from the motion kit; code decides
3
+ // what may be shown. Words on screen are the speaker's or the person's own typed words, never
4
+ // the model's; a number is one that was said. Nothing here writes code or draws: the kit does.
5
+
6
+ import { cleanGraphic, GRAPHIC_ACCENTS, GRAPHIC_FONTS, GRAPHIC_KINDS, GRAPHIC_TONES, graphicLength, SUBTITLE_MAX, TEXT_MAX } from "../engine/graphics.js"
7
+ import { paperEdit } from "../index/views.js"
8
+ import { groundProblems } from "./beats.js"
9
+
10
+ const FLICKS = 705_600_000
11
+ export const MAX_GRAPHICS = 8
12
+ const GAP = 1 * FLICKS // the frame rests between graphics
13
+ const NEAR = 6 * FLICKS // a number is "said here" within this of the graphic
14
+ const ONCE = new Set(["intro", "end", "lower"])
15
+ const ID = { type: "string", maxLength: 64 }
16
+
17
+ export const GRAPHICS_SCHEMA = {
18
+ type: "object",
19
+ properties: {
20
+ graphics: {
21
+ type: "array",
22
+ maxItems: 12,
23
+ items: {
24
+ type: "object",
25
+ properties: { kind: { type: "string", enum: Object.keys(GRAPHIC_KINDS) }, style: { type: "string", maxLength: 16 }, text: { type: "string", maxLength: TEXT_MAX }, subtitle: { type: "string", maxLength: SUBTITLE_MAX }, at: ID },
26
+ required: ["kind", "text"],
27
+ additionalProperties: false,
28
+ },
29
+ },
30
+ },
31
+ required: ["graphics"],
32
+ additionalProperties: false,
33
+ }
34
+
35
+ // "no graphics", "without titles" turn them off; naming one asks for them
36
+ const OFF = /\b(?:no|without|skip|remove (?:the|all)(?: the)?|drop the)\s+(?:any\s+)?(?:motion[- ])?(?:graphics?|titles?|text on screen|lower[- ]thirds?|name straps?)\b/i
37
+ const ON = /\b(?:motion[- ]graphics?|graphics|lower[- ]thirds?|name (?:strap|tag|card)|end ?card|outro|intro(?:duction)? (?:title|card)|opening title|title cards?|chapter (?:cards?|titles?)|animated (?:titles?|text)|kinetic)\b/i
38
+
39
+ /** What the person's words say about motion graphics: "on", "off" or null. */
40
+ export const graphicsIn = (text) => (OFF.test(String(text ?? "")) ? "off" : ON.test(String(text ?? "")) ? "on" : null)
41
+
42
+ /** The brand kit in the person's words: a colour, a tone, a font. Code reads it; hex stays in code. */
43
+ export function brandIn(text) {
44
+ const said = String(text ?? "")
45
+ const out = {}
46
+ const accent = Object.keys(GRAPHIC_ACCENTS).find((name) => new RegExp(`\\b${name}\\b[^.]{0,24}\\b(?:graphics?|titles?|accent|brand|colou?r)|\\b(?:accent|brand|colou?r)\\b[^.]{0,16}\\b${name}\\b`, "i").test(said))
47
+ if (accent) out.accent = accent
48
+ if (/\blight (?:graphics?|titles?|plates?|cards?)\b/i.test(said)) out.tone = "light"
49
+ else if (/\bdark (?:graphics?|titles?|plates?|cards?)\b/i.test(said)) out.tone = "dark"
50
+ const font = Object.keys(GRAPHIC_FONTS).find((name) => new RegExp(`\\b${name}(?:[- ]?serif)?\\b[^.]{0,12}\\b(?:font|type|titles?|text)\\b`, "i").test(said))
51
+ if (font) out.font = /\bsans\b/i.test(said) && font === "serif" ? "sans" : font
52
+ return out
53
+ }
54
+
55
+ /**
56
+ * Why a graphic's words can't be shown; empty when they can. Every word is the speaker's or
57
+ * one the person typed, and a number is said near the graphic or typed by the person.
58
+ * @param {object} graphic from cleanGraphic
59
+ * @param {{ spoken: string, near: string, person: string }} said the take's words, those around the graphic, and the person's own messages
60
+ */
61
+ export function graphicProblems(graphic, { spoken, near, person }) {
62
+ return groundProblems({ title: graphic.text, items: graphic.subtitle ? [{ text: graphic.subtitle }] : [] }, { all: `${spoken} ${person}`, near: `${near} ${person}` })
63
+ }
64
+
65
+ /**
66
+ * The graphics a cut can carry, in the order they play: each cleaned, grounded, on a word that
67
+ * is still in the take, clear of the scenes and of each other. The opening title sits on the
68
+ * first word and the end card on the end; one of each, and one name strap.
69
+ * @param {object[]} raw
70
+ * @param {{ index: object, asset: string, cuts?: { from: number, to: number }[], person?: string, scenes?: { from: string, to: string }[], brand?: object, limit?: number }} context cuts in seconds of the take
71
+ * @returns {{ graphics: object[], dropped: { graphic: object, reason: string }[] }}
72
+ */
73
+ export function arrangeGraphics(raw, { index, asset, cuts = [], person = "", scenes = [], brand = {}, limit = MAX_GRAPHICS }) {
74
+ const trimmed = (w) => cuts.some((c) => (w.start + w.end) / 2 >= c.from * FLICKS && (w.start + w.end) / 2 < c.to * FLICKS)
75
+ const words = (index.words ?? []).filter((w) => w.asset === asset && !trimmed(w))
76
+ const byId = new Map(words.map((w) => [w.id, w]))
77
+ const spoken = words.map((w) => w.text).join(" ")
78
+ const under = scenes.map((s) => [byId.get(s.from), byId.get(s.to)]).filter(([a, b]) => a && b).map(([a, b]) => ({ start: a.start, end: b.end }))
79
+ const graphics = []
80
+ const dropped = []
81
+ const once = new Set()
82
+ const candidates = (Array.isArray(raw) ? raw : []).map((item) => cleanGraphic({ ...item, ...brand })).filter(Boolean)
83
+ // Where each starts in the take: the opening title first, the end card last
84
+ const placed = candidates.map((graphic) => ({ graphic, word: graphic.kind === "intro" ? words[0] : graphic.kind === "end" ? words.at(-1) : byId.get(graphic.at) }))
85
+ const order = (p) => (p.graphic.kind === "intro" ? -Infinity : p.graphic.kind === "end" ? Infinity : (p.word?.start ?? 0))
86
+ let free = -Infinity
87
+ for (const { graphic, word } of placed.sort((a, b) => order(a) - order(b))) {
88
+ const drop = (reason) => dropped.push({ graphic, reason })
89
+ if (!word) drop("it isn't on a word of this take")
90
+ else if (ONCE.has(graphic.kind) && once.has(graphic.kind)) drop(`there is already ${graphic.kind === "end" ? "an end card" : graphic.kind === "intro" ? "an opening title" : "a name strap"}`)
91
+ else if (graphics.length >= limit) drop("that is more graphics than this cut can carry")
92
+ else {
93
+ const edge = graphic.kind === "intro" || graphic.kind === "end"
94
+ const near = edge ? spoken : words.filter((w) => w.end >= word.start - NEAR && w.start <= word.start + NEAR).map((w) => w.text).join(" ")
95
+ const problems = graphicProblems(graphic, { spoken, near, person })
96
+ if (problems.length) drop(problems[0])
97
+ else if (!edge && under.some((s) => word.start >= s.start && word.start < s.end)) drop("an animated scene is on screen there")
98
+ else if (!edge && word.start < free) drop("another graphic is still on screen there")
99
+ else {
100
+ once.add(graphic.kind)
101
+ if (!edge) free = word.start + graphicLength(graphic) + GAP
102
+ const { at: _from, ...rest } = graphic
103
+ graphics.push(edge ? rest : { ...rest, at: word.id })
104
+ }
105
+ }
106
+ }
107
+ return { graphics, dropped }
108
+ }
109
+
110
+ /**
111
+ * The graphics for a plan. The person's words come first: "no graphics" means none and no
112
+ * call. A revision that doesn't mention them keeps the ones on the card, restyled if a colour
113
+ * or font was asked for.
114
+ * @returns {Promise<{ graphics: object[], source: string, dropped: object[] }>}
115
+ */
116
+ export async function planGraphics({ ask, index, asset, text, history = [], previous = null, cuts = [], scenes = [], signal }) {
117
+ const said = [...history.filter((h) => h.who === "you").map((h) => h.text), text]
118
+ const person = said.join("\n")
119
+ const verdict = said.map(graphicsIn).filter(Boolean).at(-1) ?? null
120
+ if (verdict === "off") return { graphics: [], source: "person", dropped: [] }
121
+ const kept = previous?.settings?.graphics
122
+ const was = Array.isArray(kept) && kept[0] ? { accent: kept[0].accent, tone: kept[0].tone, font: kept[0].font } : {}
123
+ const brand = said.map(brandIn).reduce((all, one) => ({ ...all, ...one }), was)
124
+ const context = { index, asset, cuts, person, scenes, brand }
125
+ if (Array.isArray(kept) && !graphicsIn(text)) return { ...arrangeGraphics(kept, context), source: "kept" }
126
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
127
+ const usable = words.length ? (words.at(-1).end - words[0].start) / FLICKS : 0
128
+ if (words.length < 4) return { graphics: [], source: "code", dropped: [] }
129
+ // About one every eight seconds at most; a short clip still has room for a title and one more
130
+ const limit = Math.max(1, Math.min(MAX_GRAPHICS, Math.ceil(usable / 8)))
131
+ const kinds = Object.entries(GRAPHIC_KINDS).map(([id, kind]) => `- ${id} (styles: ${kind.styles.join(", ")}): ${kind.when}`).join("\n")
132
+ const request = [
133
+ `The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 1200))}`,
134
+ "You are the Director choosing the motion graphics for this cut, the way a top editor dresses a video: a few, each with a reason, never decoration. The speaker stays the film.",
135
+ `Choose up to ${limit}, fewer for a short or personal video. \`at\` is the word id where a graphic appears (the opening title and the end card need none: code places them on the first and last seconds). The kinds:\n${kinds}`,
136
+ `Hard rules, checked by code, which throws away a graphic that breaks them: every word on a graphic is either said by the speaker or typed by the person in their request, in that language, at most ${TEXT_MAX} characters (${SUBTITLE_MAX} for a subtitle); a number only if it is said near that word or the person typed it. Never write a title, name, handle or claim of your own, however good. A name strap, an opening title or an end card only if the person gave its words or the speaker says them.`,
137
+ verdict === "on" ? "The person asked for motion graphics, so use them where they fit." : "If nothing earns a graphic, answer with none.",
138
+ scenes.length ? "Animated scenes already cover some lines; code drops a graphic placed inside one." : "",
139
+ ].filter(Boolean).join("\n")
140
+ // A graphic that fails is dropped below; only an answer with nothing usable goes back to the model
141
+ const check = ({ graphics }) => {
142
+ if (!graphics.length) return []
143
+ const tried = arrangeGraphics(graphics, { ...context, limit })
144
+ return tried.graphics.length ? [] : tried.dropped.slice(0, 3).map((d) => `${d.graphic.kind} "${d.graphic.text}": ${d.reason}`)
145
+ }
146
+ const answer = await ask({ task: "graphics", tier: "budget", schema: GRAPHICS_SCHEMA, view: paperEdit(index, { assets: [asset] }), request, maxOutput: 1200, check, fallback: () => ({ graphics: [] }), signal, priority: 0 })
147
+ return { ...arrangeGraphics(answer.value.graphics ?? [], { ...context, limit }), source: answer.source }
148
+ }
149
+
150
+ /** One line a person reads for a graphic, built by code. */
151
+ export const graphicLine = (graphic) => `${GRAPHIC_KINDS[graphic.kind].label} "${graphic.text}"${graphic.subtitle ? `, "${graphic.subtitle}"` : ""}`
152
+ export { GRAPHIC_TONES }