@kriya-ai/harness 0.2.4 → 2.0.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 (134) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +49 -0
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +504 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +376 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +426 -0
  33. package/plugins/runstrip/index.js +301 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +82 -5
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +175 -3
  44. package/src/edit/core/plan.js +95 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/transitions.js +17 -0
  51. package/src/edit/core/type-kit.js +173 -0
  52. package/src/edit/director/ask.js +37 -3
  53. package/src/edit/director/assembly.js +829 -0
  54. package/src/edit/director/continuity.js +137 -0
  55. package/src/edit/director/custom-motion.js +88 -0
  56. package/src/edit/director/graphics.js +186 -0
  57. package/src/edit/director/intent.js +125 -0
  58. package/src/edit/director/mentions.js +52 -0
  59. package/src/edit/director/plan.js +89 -12
  60. package/src/edit/director/revise.js +172 -7
  61. package/src/edit/director/viewer.js +136 -0
  62. package/src/edit/director/watch-fix.js +119 -0
  63. package/src/edit/engine/captions.js +110 -5
  64. package/src/edit/engine/confine.js +81 -4
  65. package/src/edit/engine/custom.js +243 -0
  66. package/src/edit/engine/dna2.js +893 -0
  67. package/src/edit/engine/fonts.js +218 -0
  68. package/src/edit/engine/graphics.js +439 -0
  69. package/src/edit/engine/index.js +14 -5
  70. package/src/edit/engine/motion.js +153 -14
  71. package/src/edit/engine/music-bed.js +59 -1
  72. package/src/edit/engine/packs.js +11 -0
  73. package/src/edit/engine/reference2.js +26 -0
  74. package/src/edit/engine/sfx.js +56 -1
  75. package/src/edit/engine/tool.js +21 -5
  76. package/src/edit/gates/assembly.js +194 -0
  77. package/src/edit/gates/copy.js +7 -4
  78. package/src/edit/gates/index.js +76 -8
  79. package/src/edit/gates/picture.js +6 -3
  80. package/src/edit/gates/reference.js +115 -0
  81. package/src/edit/gates/tile.js +96 -0
  82. package/src/edit/host/client.js +4 -3
  83. package/src/edit/host/clips.js +33 -0
  84. package/src/edit/host/jobs.js +9 -3
  85. package/src/edit/host/layers.js +134 -0
  86. package/src/edit/host/main.js +17 -7
  87. package/src/edit/host/paths.js +34 -3
  88. package/src/edit/host/preview.js +108 -0
  89. package/src/edit/host/projects.js +494 -29
  90. package/src/edit/host/server.js +263 -19
  91. package/src/edit/host/tavi.js +77 -0
  92. package/src/edit/loop/make.js +44 -3
  93. package/src/edit/recipes/assembly.js +352 -0
  94. package/src/edit/recipes/graphic-clips.js +59 -0
  95. package/src/edit/recipes/openings.js +36 -0
  96. package/src/edit/recipes/reel.js +138 -17
  97. package/src/edit/recipes/reference-look.js +29 -0
  98. package/src/edit/recipes/short-from-long.js +3 -3
  99. package/src/edit/recipes/sound.js +71 -0
  100. package/src/edit/runtime/cli.js +26 -5
  101. package/src/edit/runtime/fetch.js +4 -3
  102. package/src/edit/runtime/licences.js +7 -1
  103. package/src/explore.js +103 -0
  104. package/src/failure.js +1 -1
  105. package/src/gate-commands.js +114 -0
  106. package/src/gates/api.js +127 -0
  107. package/src/gates/commands.js +111 -0
  108. package/src/gates/detectors.js +370 -0
  109. package/src/gates/http.js +62 -0
  110. package/src/gates/index.js +196 -0
  111. package/src/gates/page.js +264 -0
  112. package/src/gates/sast.js +64 -0
  113. package/src/gates/stack.js +110 -0
  114. package/src/gates/tenant.js +162 -0
  115. package/src/gates/three.js +407 -0
  116. package/src/gates/ui.js +111 -0
  117. package/src/launch.js +15 -3
  118. package/src/loop.js +199 -7
  119. package/src/mcp.js +126 -0
  120. package/src/milestones.js +188 -0
  121. package/src/modes.js +32 -0
  122. package/src/orchestra.js +43 -0
  123. package/src/outcomes.js +88 -0
  124. package/src/profiles.js +5 -0
  125. package/src/receipts.js +238 -0
  126. package/src/release.js +356 -0
  127. package/src/runstrip.js +122 -0
  128. package/src/stack.js +120 -0
  129. package/src/verify.js +67 -20
  130. package/studio/dist/fonts/fraunces.woff2 +0 -0
  131. package/studio/dist/fonts/geist.woff2 +0 -0
  132. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  133. package/studio/dist/studio.css +452 -3
  134. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,352 @@
1
+ // The assembly make (TP2, ASSEMBLY_AND_INTENT §6): many files in one film, in the order the
2
+ // person gave. It runs only when the make's own brief carries an assembly with two or more
3
+ // parts in the order, or a part over or under them (EH-63); one file with none is the reel
4
+ // it always was. It reuses the reel's steps: the same story slot per talking part, the same
5
+ // captions, look and music. Code does the editing; the model only chooses a story per part.
6
+
7
+ import { apply } from "../core/ops.js"
8
+ import { solve } from "../core/solver.js"
9
+ import { TRANSITION_DEFAULT, TRANSITIONS } from "../core/transitions.js"
10
+ import { clipList, stretchOf } from "../director/assembly.js"
11
+ import { ALL_LOOKS, pageLimits, pages, placeOf, readablePages } from "../engine/captions.js"
12
+ import { paperEdit } from "../index/views.js"
13
+ import { isSceneBlock } from "../core/layout.js"
14
+ import { graphicOps, isPlanGraphic } from "./graphic-clips.js"
15
+ import { candidateLines, deliverableFor, fitLines, GRADES, recipeFor, remadeClips, runsOf, STORY_SCHEMA, trimIndex } from "./reel.js"
16
+ import { sceneOps } from "./scene-clips.js"
17
+ import { referenceLook } from "./reference-look.js"
18
+
19
+ const FLICKS = 705_600_000
20
+ const SPINE = ["story", "whole"]
21
+ const LEVEL_MAX = 12 // dB a part's speech may be moved to meet the others
22
+ const LEVEL_MIN = 0.5 // under this the parts already sound alike
23
+ const OVER_MIN = FLICKS / 2
24
+ const MUTE = -60 // dB: a picture's own sound under a voice-over
25
+
26
+ /** A part's story is kept by what it plays, so a reorder (or new part ids) asks the model nothing (TG-08). */
27
+ export const storyKey = (part) => JSON.stringify([part.asset, part.from ?? null, part.to ?? null])
28
+
29
+ /**
30
+ * How a part's picture sits in the frame when nobody said (§6.2): the same shape fills it; a face
31
+ * is followed; anything else of another shape keeps its whole picture over a blurred copy.
32
+ * @returns {"fill" | "fit" | "blur" | "subject"}
33
+ */
34
+ export function frameFor(part, facts, canvas, hasSubject) {
35
+ if (part.fit) return part.fit
36
+ if (!facts?.width || !facts?.height) return "fill"
37
+ const [source, frame] = [facts.width / facts.height, canvas.width / canvas.height]
38
+ if (Math.abs(source - frame) / frame < 0.02) return "fill"
39
+ return hasSubject ? "subject" : "blur"
40
+ }
41
+
42
+ /**
43
+ * Each part's speech brought to the loudest-used part's level (§6.2): within 1 LU after, each
44
+ * move inside LEVEL_MAX. A part nobody measured is left as it is.
45
+ * @param {{ id: string, lufs: number | null | undefined }[]} measured the reference first
46
+ * @returns {Map<string, number>} part id → dB
47
+ */
48
+ export function levelsFor(measured) {
49
+ const out = new Map()
50
+ const reference = measured.find((m) => Number.isFinite(m.lufs))
51
+ if (!reference) return out
52
+ for (const m of measured) {
53
+ if (m === reference || !Number.isFinite(m.lufs)) continue
54
+ const db = Math.round((reference.lufs - m.lufs) * 10) / 10
55
+ if (Math.abs(db) >= LEVEL_MIN) out.set(m.id, Math.max(-LEVEL_MAX, Math.min(LEVEL_MAX, db)))
56
+ }
57
+ return out
58
+ }
59
+
60
+ /**
61
+ * @param {{
62
+ * project: object, index: object, brief: object, ask: Function, signal?: AbortSignal,
63
+ * loudness?: Record<string, number | null>, filters?: Set<string> | null, offline?: string[]
64
+ * }} input
65
+ * brief.assembly: `{ version, parts }`, already checked; loudness: each file's measured speech
66
+ * loudness in LUFS (the Host measures; none means nothing is levelled); filters: what this
67
+ * FFmpeg can draw (null: unknown, so nothing that needs a pack is asked for); offline: files gone
68
+ * @returns {Promise<{ ops: object[], project: object, notes: string[], calls: number, slots: Record<string, string>, story: object, order: string[] }>}
69
+ */
70
+ export async function planAssembly({ project, index: fullIndex, brief = {}, ask, signal, loudness = {}, filters = null, offline = [] }) {
71
+ const recipe = recipeFor(brief)
72
+ const notes = []
73
+ const slots = {}
74
+ let calls = 0
75
+ const clips = clipList(project, fullIndex)
76
+ const clipOf = (asset) => clips.find((c) => c.asset === asset)
77
+ const name = (part) => `clip ${clipOf(part.asset)?.n ?? "?"}`
78
+ const factsOf = (asset) => project.assets.find((a) => a.id === asset)?.facts ?? {}
79
+
80
+ // A file that has gone is left out, with a note (§8); the Host ends `needs_you` when it was asked for by name
81
+ const gone = new Set(offline)
82
+ const all = brief.assembly.parts.filter((part) => {
83
+ if (!gone.has(part.asset)) return true
84
+ notes.push(`Left out ${name(part)}: its file isn't where it was.`)
85
+ return false
86
+ })
87
+ const hosts = new Set(all.filter((p) => SPINE.includes(p.use)).map((p) => p.id))
88
+ const parts = all.filter((part) => SPINE.includes(part.use) || part.use === "sound" || hosts.has(part.at?.part) || (notes.push(`Left out ${name(part)}: the part it played over isn't in this film.`), false))
89
+ const spine = parts.filter((p) => SPINE.includes(p.use))
90
+ if (!spine.length) throw new Error("This film has no part left to show: every file in its order is missing.")
91
+ // A sound part with speech is a voice-over: it becomes the clock, and the pictures are laid over it in order
92
+ const sounds = parts.filter((p) => p.use === "sound")
93
+ const voice = sounds.find((p) => clipOf(p.asset)?.speech && clipOf(p.asset)?.kind === "audio") ?? null
94
+ for (const p of sounds.filter((p) => clipOf(p.asset)?.speech && clipOf(p.asset)?.kind !== "audio")) notes.push(`${name(p)} is a video, and only a sound file can be the voice-over yet, so it isn't heard.`)
95
+ const song = sounds.find((p) => p !== voice && !clipOf(p.asset)?.speech) ?? null
96
+ for (const p of sounds.filter((p) => p !== voice && p !== song && !clipOf(p.asset)?.speech)) notes.push(`${name(p)} isn't heard: a film has one song.`)
97
+
98
+ // 1. Story, per talking part, in the film's order: the reel's own slot, scoped to that part's stretch
99
+ const talking = voice ? [] : spine.filter((p) => p.use === "story" && clipOf(p.asset)?.speech)
100
+ const asked = brief.targetDuration
101
+ const lengthOfLine = (line) => runsOf(line).reduce((sum, run) => sum + (run.at(-1).end - run[0].start), 0)
102
+ const scopes = new Map()
103
+ for (const part of talking) {
104
+ const { from, to } = stretchOf(part, clipOf(part.asset), fullIndex)
105
+ const outside = [{ from: 0, to: from }, { from: to, to: Number.MAX_SAFE_INTEGER }].filter((c) => c.to > c.from)
106
+ const { index } = trimIndex(fullIndex, part.asset, outside)
107
+ const lines = candidateLines(index, part.asset, brief.picks)
108
+ scopes.set(part.id, { index, lines, speech: lines.reduce((sum, l) => sum + lengthOfLine(l), 0) })
109
+ }
110
+ const wholeLength = spine.filter((p) => !talking.includes(p)).reduce((sum, p) => sum + (stretchOf(p, clipOf(p.asset), fullIndex).to - stretchOf(p, clipOf(p.asset), fullIndex).from), 0)
111
+ const speechTotal = [...scopes.values()].reduce((sum, s) => sum + s.speech, 0)
112
+ const stories = {}
113
+ const chosenBy = new Map()
114
+ for (const part of talking) {
115
+ const { index, lines, speech } = scopes.get(part.id)
116
+ const ids = new Set(lines.map((l) => l.id))
117
+ if (!lines.length) {
118
+ chosenBy.set(part.id, [])
119
+ continue
120
+ }
121
+ // The share of the asked length this part may take, when a length was asked for
122
+ const share = asked && speechTotal > 0 ? Math.max(0, Math.round(((asked - wholeLength) * speech) / speechTotal)) : null
123
+ const mustKeep = (brief.mustKeep ?? []).filter((id) => ids.has(id))
124
+ const key = storyKey(part)
125
+ const was = brief.story?.parts?.[key]
126
+ const kept = was && typeof was === "object" ? { hook: ids.has(was.hook) ? was.hook : null, drop: (Array.isArray(was.drop) ? was.drop : []).filter((id) => ids.has(id)) } : null
127
+ const scoped = { ...index, sentences: lines, words: lines.flatMap((l) => l.words), takes: [] }
128
+ const story = kept
129
+ ? { value: kept, source: "kept", calls: 0 }
130
+ : await ask({
131
+ task: "story",
132
+ schema: STORY_SCHEMA,
133
+ recipe: recipe.notes,
134
+ view: paperEdit(scoped, { assets: [part.asset] }),
135
+ request: `This is part ${spine.indexOf(part) + 1} of ${spine.length} of one film made from several files. Choose this part's opening line (a sentence id from the list, or null to keep the order) and any lines to drop because they repeat or wander.${share ? ` This part should run about ${Math.round(share / FLICKS)} seconds.` : ""} Never drop: ${mustKeep.join(", ") || "(none)"}.`,
136
+ maxOutput: 300,
137
+ check: ({ hook, drop }) => [hook, ...drop].filter((id) => id !== null && !ids.has(id)).map((id) => `"${id}" isn't one of the sentences shown`),
138
+ fallback: () => ({ hook: null, drop: [] }),
139
+ signal,
140
+ })
141
+ calls += story.calls
142
+ slots.story = slots.story && slots.story !== story.source ? "mixed" : story.source
143
+ if (story.reason) notes.push(`Story of ${name(part)}: ${story.reason} Kept every line, in order.`)
144
+ stories[key] = { hook: story.value.hook ?? null, drop: story.value.drop ?? [] }
145
+ let chosen = lines.filter((l) => !story.value.drop.includes(l.id) || mustKeep.includes(l.id))
146
+ const hook = story.value.hook
147
+ if (share && chosen.reduce((sum, l) => sum + lengthOfLine(l), 0) > share) chosen = fitLines(chosen, share, new Set([...mustKeep, ...(hook ? [hook] : [])]))
148
+ if (hook && chosen.some((l) => l.id === hook)) chosen = [chosen.find((l) => l.id === hook), ...chosen.filter((l) => l.id !== hook)]
149
+ chosenBy.set(part.id, chosen)
150
+ }
151
+
152
+ // 2. The spine: what was there goes, then each part's ranges in the film's order. A join between two files is a real cut
153
+ const sequence = project.sequences.find((q) => q.id === project.active)
154
+ const rebuilt = new Set(sequence.tracks.filter((t) => ["base", "caption", "music", "ambience"].includes(t.role)).map((t) => t.id))
155
+ const ops = [
156
+ // What an earlier make placed goes too: its cutaways carry the mark, so none shows twice (EH-60)
157
+ ...remadeClips(sequence, (c) => rebuilt.has(c.track) || c.plan === true || c.effects?.some((e) => isSceneBlock(e) || isPlanGraphic(e))).map((c) => ({ op: "ripple_delete", clip: c.id })),
158
+ { op: "set_brief", format: "assembly", targetDuration: asked ?? FLICKS, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
159
+ { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
160
+ ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...deliverableFor(brief) }]),
161
+ ]
162
+ const counts = [] // how many clips each spine part laid, in order
163
+ const voiceLength = voice ? stretchOf(voice, clipOf(voice.asset), fullIndex).to - stretchOf(voice, clipOf(voice.asset), fullIndex).from : 0
164
+ const pictureTotal = spine.reduce((sum, p) => sum + (stretchOf(p, clipOf(p.asset), fullIndex).to - stretchOf(p, clipOf(p.asset), fullIndex).from), 0)
165
+ for (const part of spine) {
166
+ const before = ops.length
167
+ const stretch = stretchOf(part, clipOf(part.asset), fullIndex)
168
+ if (voice) {
169
+ // The voice-over is the clock: each picture gets its share of it, never more than it has
170
+ const length = Math.min(stretch.to - stretch.from, Math.round((voiceLength * (stretch.to - stretch.from)) / pictureTotal))
171
+ if (length > 0) ops.push({ op: "keep_range", asset: part.asset, from: stretch.from, to: stretch.from + length })
172
+ } else if (chosenBy.has(part.id)) {
173
+ for (const line of chosenBy.get(part.id)) for (const run of runsOf(line)) ops.push({ op: "keep_range", asset: part.asset, from: { word: run[0].id, edge: "start" }, to: { word: run.at(-1).id, edge: "end" } })
174
+ } else ops.push({ op: "keep_range", asset: part.asset, from: part.from ?? stretch.from, to: part.to ?? stretch.to })
175
+ counts.push(ops.length - before)
176
+ if (ops.length === before) notes.push(`${name(part)} has nothing left to play in this cut, so it's out.`)
177
+ }
178
+ let step = apply(project, ops, { index: fullIndex, author: "agent" })
179
+ if (!step.applied) throw new Error(`The film's order was refused: ${step.diagnostics[0].message}`)
180
+ const baseTracks = new Set(sequence.tracks.filter((t) => t.role === "base").map((t) => t.id))
181
+ const laid = step.project.sequences.find((q) => q.id === step.project.active).clips.filter((c) => baseTracks.has(c.track) || c.track === "t-base")
182
+ const clipsOf = new Map()
183
+ let at = 0
184
+ spine.forEach((part, i) => {
185
+ clipsOf.set(part.id, laid.slice(at, at + counts[i]))
186
+ at += counts[i]
187
+ })
188
+ const live = spine.filter((p) => clipsOf.get(p.id).length)
189
+
190
+ // 3. Conform each part to the film (§6.2): shape, level, colour, room sound. Each degrades with a note; none fails a make (EH-76)
191
+ const conform = []
192
+ const canvas = recipe.canvas
193
+ for (const part of live) {
194
+ const facts = factsOf(part.asset)
195
+ const subject = (fullIndex.subjects?.[part.asset]?.length ?? 0) > 0
196
+ const mode = frameFor(part, facts, canvas, subject)
197
+ const cropWidth = facts.height ? Math.round((facts.height * canvas.width) / canvas.height) : 0
198
+ for (const clip of clipsOf.get(part.id)) {
199
+ if (mode === "fit" || mode === "blur") conform.push({ op: "set_frame", clip: clip.id, mode })
200
+ // Fill is today's behaviour: follow the speaker where there is one, else hold the centre
201
+ else if (facts.width && cropWidth < facts.width) conform.push(subject ? { op: "reframe", clip: clip.id, mode: "subject" } : { op: "reframe", clip: clip.id, mode: "fixed", x: Math.max(0, Math.round((facts.width - cropWidth) / 2)) })
202
+ }
203
+ if (facts.vfr) notes.push(`${name(part)} was recorded at a changing frame rate; it plays at the film's ${canvas.fps?.n ?? recipe.deliverable.fps.n} frames a second.`)
204
+ }
205
+ // The reference is the longest talking part: the others meet its level and its colour
206
+ const lengthOf = (part) => solveLength(step.project, fullIndex, clipsOf.get(part.id))
207
+ const speaking = live.filter((p) => clipOf(p.asset)?.speech && !voice)
208
+ const reference = [...speaking].sort((a, b) => lengthOf(b) - lengthOf(a))[0] ?? null
209
+ if (reference) {
210
+ const heard = live.filter((p) => factsOf(p.asset).hasAudio !== false)
211
+ const levels = levelsFor([reference, ...heard.filter((p) => p !== reference)].map((p) => ({ id: p.id, lufs: loudness[p.asset] })))
212
+ for (const [id, db] of levels) for (const clip of clipsOf.get(id)) conform.push({ op: "set_level", clip: clip.id, db })
213
+ if (heard.length > 1 && !Number.isFinite(loudness[reference.asset])) notes.push("The parts' loudness wasn't measured here, so each keeps the level it was recorded at.")
214
+ const others = live.filter((p) => p.asset !== reference.asset && clipOf(p.asset)?.picture)
215
+ if (others.length) {
216
+ if (filters?.has("lut3d")) for (const p of others) for (const clip of clipsOf.get(p.id)) conform.push({ op: "match_color", clip: clip.id, reference: clipsOf.get(reference.id)[0].id })
217
+ else notes.push("This computer's FFmpeg can't match colour between files (it has no lut3d), so each part keeps the colour it was shot with.")
218
+ }
219
+ // Room sound under the joins: a quiet stretch of the reference file, looped under the film
220
+ const quiet = (fullIndex.silences ?? []).filter((s) => s.asset === reference.asset && s.end - s.start >= 0.4 * FLICKS).sort((a, b) => b.end - b.start - (a.end - a.start))[0]
221
+ if (quiet && live.length > 1) conform.push({ op: "room_tone", asset: reference.asset, from: quiet.start, to: quiet.end })
222
+ }
223
+ if (voice) for (const part of live) if (factsOf(part.asset).hasAudio !== false) for (const clip of clipsOf.get(part.id)) conform.push({ op: "set_level", clip: clip.id, db: MUTE })
224
+
225
+ // 4. Over parts: the picture plays over its host's voice, at the word or the place asked for
226
+ const over = []
227
+ const wordsById = new Map((fullIndex.words ?? []).map((w) => [w.id, w]))
228
+ const keptWords = new Set([...chosenBy.values()].flatMap((lines) => lines.flatMap((l) => runsOf(l).flat().map((w) => w.id))))
229
+ for (const part of parts.filter((p) => p.use === "over")) {
230
+ const clip = clipOf(part.asset)
231
+ const host = clipsOf.get(part.at.part) ?? []
232
+ if (!clip?.picture || !host.length) {
233
+ notes.push(`Left out ${name(part)} as a cutaway: ${clip?.picture ? "the part it plays over has nothing left in this cut" : "it has no picture"}.`)
234
+ continue
235
+ }
236
+ const stretch = stretchOf(part, clip, fullIndex)
237
+ const own = stretch.to - stretch.from
238
+ const hostLength = solveLength(step.project, fullIndex, host)
239
+ let anchor
240
+ let length = Math.min(own, hostLength)
241
+ const word = part.at.word === undefined ? null : wordsById.get(part.at.word)
242
+ if (word && keptWords.has(word.id)) {
243
+ anchor = { word: word.id, edge: "start" }
244
+ // Capped by the sentence it sits on, unless the part's own stretch was asked for
245
+ const sentence = (fullIndex.sentences ?? []).find((s) => s.asset === word.asset && word.start >= s.start && word.end <= s.end)
246
+ if (sentence && part.from === undefined) length = Math.min(length, Math.max(OVER_MIN, sentence.end - word.start))
247
+ } else {
248
+ if (part.at.word !== undefined) notes.push(`The word ${name(part)} was to play over isn't in this cut, so it starts with that part.`)
249
+ const where = part.at.where ?? "start"
250
+ if (part.at.t !== undefined) anchor = { clip: host[0].id, edge: "start", offset: Math.min(part.at.t, Math.max(0, hostLength - OVER_MIN)) }
251
+ else if (where === "end") anchor = { clip: host.at(-1).id, edge: "end", offset: -Math.min(length, hostLength) }
252
+ else if (where === "middle") anchor = { clip: host[0].id, edge: "start", offset: Math.max(0, Math.round((hostLength - length) / 2)) }
253
+ else anchor = { clip: host[0].id, edge: "start" }
254
+ }
255
+ if (length < OVER_MIN) {
256
+ notes.push(`Left out ${name(part)} as a cutaway: there's under half a second for it.`)
257
+ continue
258
+ }
259
+ over.push({ op: "place_over", asset: part.asset, at: anchor, in: stretch.from, duration: length })
260
+ }
261
+
262
+ // 5. Sound parts: a song is fitted and ducked as in a reel; a voice-over is heard at its own level
263
+ const music = []
264
+ const bed = song ? song.asset : brief.music && project.assets.some((a) => a.id === brief.music && a.kind === "audio") ? brief.music : null
265
+ if (brief.music && !bed) notes.push(`There is no sound "${brief.music}" in this project, so the film has no music.`)
266
+ if (bed) music.push({ op: "set_music", asset: bed }, { op: "music_shape", fit: true, fadeIn: Math.round(FLICKS * 0.3) }, { op: "duck" })
267
+ const narration = voice ? [{ op: "add_sfx", asset: voice.asset, peak_at: 0 }] : []
268
+
269
+ // 6. The dressing: look, voice cleanup, captions, transitions at the joins when asked
270
+ const look = GRADES[brief.grade] ?? (brief.customGrade && typeof brief.customGrade === "object" ? brief.customGrade : null)
271
+ const pictures = live.flatMap((p) => clipsOf.get(p.id))
272
+ // TP6: a reference's colour as a measured match (a LUT the Host wrote), only when this brief carries one
273
+ const grading = brief.lut ? pictures.map((c) => ({ op: "apply_lut", clip: c.id, asset: brief.lut })) : look ? pictures.map((c) => ({ op: "grade", clip: c.id, ...look })) : []
274
+ const cleaning = brief.cleanVoice && !voice ? live.filter((p) => clipOf(p.asset)?.speech).flatMap((p) => clipsOf.get(p.id)).map((c) => ({ op: "clean_voice", clip: c.id, strength: 0.6 })) : []
275
+ const runs = voice ? [wordsRun(fullIndex, voice, clipOf(voice.asset))] : live.flatMap((p) => (chosenBy.get(p.id) ?? []).flatMap((l) => runsOf(l)))
276
+ const captions = ALL_LOOKS[brief.captions] ? runs.filter((run) => run.length).flatMap((run) => readablePages(pages(run, pageLimits(brief.captions)), run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
277
+ const captionLook = { ...(brief.captionStyle ?? {}), ...(brief.holdCaptions ? { hold: true } : {}), ...(placeOf(brief.captions) ? { place: placeOf(brief.captions) } : {}) }
278
+ const style = ALL_LOOKS[brief.captions] && Object.keys(captionLook).length ? [{ op: "set_look", caption: captionLook }] : []
279
+ const joins = Object.hasOwn(TRANSITIONS, brief.transition ?? "") ? live.slice(1).map((p) => ({ op: "transition", clip: clipsOf.get(p.id)[0].id, kind: brief.transition, duration: TRANSITION_DEFAULT })) : []
280
+ if (brief.coldOpen || brief.punches || brief.angles || brief.titles || brief.ramps || brief.broll === "own") notes.push("A cold open, punch-ins, angles, title cards, speed ramps and automatic B-roll are a single take's; a film of several files doesn't use them yet.")
281
+
282
+ let allOps = [...ops, ...style, ...conform, ...grading, ...cleaning, ...over, ...captions, ...music, ...narration, ...joins]
283
+ step = apply(project, allOps, { index: fullIndex, author: "agent" })
284
+ if (!step.applied) throw new Error(`The film was refused: ${step.diagnostics[0].message}`)
285
+ // TP6: a reference's grain, corners and bars over the whole film, only when this brief carries them (EH-59)
286
+ if (brief.fx?.length) step = referenceLook({ project, all: allOps, step, fx: brief.fx, index: fullIndex, notes })
287
+ const placedNow = step.project.sequences.find((q) => q.id === step.project.active).clips
288
+ // The voice-over plays at its own level, not as an effect under a voice
289
+ if (voice) {
290
+ const heard = placedNow.find((c) => c.source?.asset === voice.asset && !baseTracks.has(c.track))
291
+ if (heard) allOps.push({ op: "set_level", clip: heard.id, db: 0 })
292
+ }
293
+ // A cutaway of another shape sits in the frame by the same rule as a part of the order
294
+ for (const clip of placedNow.filter((c) => c.plan === true)) {
295
+ const part = parts.find((p) => p.use === "over" && p.asset === clip.source.asset)
296
+ const mode = frameFor(part ?? {}, factsOf(clip.source.asset), canvas, false)
297
+ if (mode === "fit" || mode === "blur") allOps.push({ op: "set_frame", clip: clip.id, mode })
298
+ }
299
+ // Scenes and graphics from an approved plan, per talking file: each keys on its own words
300
+ const keptOf = (asset) => live.filter((p) => p.asset === asset).flatMap((p) => (chosenBy.get(p.id) ?? []).flatMap((l) => runsOf(l).flat()))
301
+ const files = [...new Set(live.filter((p) => chosenBy.has(p.id)).map((p) => p.asset))]
302
+ const fileOf = (id) => wordsById.get(id)?.asset
303
+ for (const asset of files) {
304
+ const scenes = (brief.scenes ?? []).filter((s) => fileOf(s.from) === asset)
305
+ const picturesHere = (brief.pictures ?? []).filter((s) => fileOf(s.from) === asset)
306
+ const terms = (brief.terms ?? []).filter((t) => fileOf(t.at) === asset)
307
+ if (scenes.length || picturesHere.length || terms.length) {
308
+ const made = sceneOps({ scenes, pictures: picturesHere, terms, project: apply(project, allOps, { index: fullIndex, author: "agent" }).project, index: fullIndex, asset, kept: keptOf(asset), captions: !!ALL_LOOKS[brief.captions], sound: { scene: brief.sfx?.scene, reveal: brief.sfx?.reveal } })
309
+ allOps.push(...made.ops)
310
+ notes.push(...made.notes)
311
+ }
312
+ // An opening title belongs to the first talking file and an end card to the last; the rest sit on their own words
313
+ const graphics = (brief.graphics ?? []).filter((g) => (g.kind === "intro" ? asset === files[0] : g.kind === "end" ? asset === files.at(-1) : fileOf(g.at) === asset))
314
+ if (graphics.length) {
315
+ const made = graphicOps({ graphics, project: apply(project, allOps, { index: fullIndex, author: "agent" }).project, index: fullIndex, asset, kept: keptOf(asset) })
316
+ allOps.push(...made.ops)
317
+ notes.push(...made.notes)
318
+ }
319
+ }
320
+ step = apply(project, allOps, { index: fullIndex, author: "agent" })
321
+ if (!step.applied) throw new Error(`The film was refused: ${step.diagnostics[0].message}`)
322
+ // With no length asked for, the film is as long as its parts: the brief says so, so QG-12 checks what was meant
323
+ if (!asked) {
324
+ const length = solve(step.project, fullIndex).duration
325
+ allOps = allOps.map((op) => (op.op === "set_brief" ? { ...op, targetDuration: Math.max(1, length) } : op))
326
+ step = apply(project, allOps, { index: fullIndex, author: "agent" })
327
+ }
328
+
329
+ // 7. What I did: the order as made, part by part
330
+ const seconds = (flicks) => `${(flicks / FLICKS).toFixed(1)} s`
331
+ const madeProject = step.project
332
+ const order = [
333
+ ...live.map((part, i) => `${i + 1}. ${name(part)}${clipOf(part.asset)?.label ? ` "${clipOf(part.asset).label}"` : ""}, ${voice ? "picture" : part.use}, ${seconds(lengthOf(part))}${part.why && part.why !== "person" && part.why !== "storyboard" ? ` (${part.why === "director" ? "the Director's choice" : "the order added"})` : ""}`),
334
+ ...over.map((op) => `${name({ asset: op.asset })} over the voice for ${seconds(op.duration)}`),
335
+ ...(bed ? [`Music under the film${song ? ` from ${name(song)}` : ""}`] : []),
336
+ ...(voice ? [`${name(voice)} as the voice-over, which sets the timing`] : []),
337
+ ]
338
+ notes.unshift(`The film's order: ${order.join("; ")}.`)
339
+ return { ops: allOps, project: madeProject, notes, calls, slots, story: { parts: stories }, order }
340
+ }
341
+
342
+ // The length a part's clips take on the timeline
343
+ function solveLength(project, index, clips) {
344
+ const ids = new Set(clips.map((c) => c.id))
345
+ return solve(project, index).picture.filter((p) => ids.has(p.clip)).reduce((sum, p) => sum + (p.end - p.at), 0)
346
+ }
347
+
348
+ // A voice-over's words, in its stretch, as one run for captions
349
+ function wordsRun(index, part, clip) {
350
+ const { from, to } = stretchOf(part, clip, index)
351
+ return (index.words ?? []).filter((w) => w.asset === part.asset && w.start >= from && w.end <= to && !(w.flags ?? []).some((f) => f === "filler" || f === "stutter"))
352
+ }
@@ -0,0 +1,59 @@
1
+ // Graphic clips (MOTION_GRAPHICS.md): an approved plan's motion graphics as operations on the
2
+ // cut as solved. Each is anchored to its word, so it moves with the speech; code checks again
3
+ // what the plan checked, since a re-cut can drop a line or put a scene where a graphic was.
4
+
5
+ import { solve } from "../core/solver.js"
6
+ import { ALL_GRAPHIC_KINDS, cleanGraphic, GRAPHIC_BLOCK, GRAPHIC_VERSION, graphicLength } from "../engine/graphics.js"
7
+ import { graphicLine } from "../director/graphics.js"
8
+
9
+ const FLICKS = 705_600_000
10
+ const MIN_LENGTH = 1.2 * FLICKS
11
+ const GAP = 0.5 * FLICKS
12
+
13
+ /** A graphic an approved plan put there, which a remake replaces (one added in chat stays). */
14
+ export const isPlanGraphic = (effect) => effect?.type === "block" && effect.blockId === GRAPHIC_BLOCK && effect.variables?.plan === true
15
+
16
+ /**
17
+ * @param {{ graphics: object[], project: object, index: object, asset: string, kept: { id: string }[] }} input
18
+ * project: with the cut and its scenes applied; kept: the words the cut keeps, in order
19
+ * @returns {{ ops: object[], notes: string[] }}
20
+ */
21
+ export function graphicOps({ graphics, project, index, asset, kept }) {
22
+ const ops = []
23
+ const notes = []
24
+ const timeline = solve(project, index)
25
+ const story = timeline.picture.filter((p) => !p.echo && !p.hold)
26
+ const outputOf = (word) => {
27
+ const piece = story.find((p) => p.asset === asset && word.start >= p.in && word.start <= p.out)
28
+ return piece ? piece.at + (word.start - piece.in) : null
29
+ }
30
+ // Whatever already takes over the frame: scenes, definitions, pictures laid over the story
31
+ const taken = timeline.overlays.map((o) => ({ at: o.at, end: o.end }))
32
+ const words = kept.map((w) => ({ ...w, out: outputOf(w) })).filter((w) => w.out !== null).sort((a, b) => a.out - b.out)
33
+ if (!words.length) return { ops, notes }
34
+ for (const raw of graphics) {
35
+ // The make route is the switch's gate (EH-92): it lets motion kit 2 through only with editing.typeKit on, and a
36
+ // callout round a drawn box only with editing.customMotion on. What reaches here was approved, so it is placed
37
+ const graphic = cleanGraphic(raw, ALL_GRAPHIC_KINDS)
38
+ if (!graphic) continue
39
+ const length = graphicLength(graphic)
40
+ const leave = (reason) => notes.push(`Left out the ${graphicLine(graphic)}: ${reason}.`)
41
+ // The end card starts on the last word that leaves it its full length; the opening title on the first
42
+ const word = graphic.kind === "intro" ? words[0] : graphic.kind === "end" ? (words.findLast((w) => w.out <= timeline.duration - length) ?? words[0]) : words.find((w) => w.id === graphic.at)
43
+ if (!word) {
44
+ leave("its line isn't in this cut")
45
+ continue
46
+ }
47
+ const at = word.out
48
+ const duration = Math.min(length, timeline.duration - at)
49
+ const end = at + duration
50
+ if (duration < MIN_LENGTH) leave("there isn't time for it before the cut ends")
51
+ else if (taken.some((t) => at < t.end + GAP && t.at < end + GAP)) leave("something else is on screen there")
52
+ else {
53
+ taken.push({ at, end })
54
+ const { at: _word, ...variables } = graphic
55
+ ops.push({ op: "add_motion", block: GRAPHIC_BLOCK, version: GRAPHIC_VERSION, variables: { ...variables, plan: true }, at: { word: word.id, edge: "start" }, duration })
56
+ }
57
+ }
58
+ return { ops, notes }
59
+ }
@@ -0,0 +1,36 @@
1
+ // "Give me three openings" (TP8, CRAFT_UPGRADE §6.5, editing.directorLoop): three short drafts of the
2
+ // first eight seconds, each opening on a different line, for the person to pick one on the Variations
3
+ // wall. The lines are chosen by code from the index's own scores, so it costs no model call; the
4
+ // pick goes back as the next make's hook, which the make route already takes.
5
+
6
+ import { candidateLines, planReel, recipeFor } from "./reel.js"
7
+
8
+ const FLICKS = 705_600_000
9
+ export const OPENING = 8 * FLICKS
10
+ export const OPENINGS = 3
11
+
12
+ // Every slot takes its code default: an opening is a sketch, not a story the model chose
13
+ const byCode = async (slot) => ({ value: slot.fallback(), source: "default", calls: 0 })
14
+
15
+ /** The three hooks: the best-scored distinct lines, at most one from any eight seconds of the take, in score order. */
16
+ export function hooksFor(index, asset) {
17
+ const lines = candidateLines(index, asset).filter((l) => l.words.length >= 3)
18
+ const picked = []
19
+ for (const line of [...lines].sort((a, b) => (b.score ?? 0) - (a.score ?? 0) || a.start - b.start)) {
20
+ if (picked.some((p) => Math.abs(p.start - line.start) < OPENING)) continue
21
+ picked.push(line)
22
+ if (picked.length === OPENINGS) break
23
+ }
24
+ return picked.map((l) => ({ id: l.id, words: l.words.filter((w) => !w.flags?.includes("filler")).slice(0, 8).map((w) => w.text).join(" ") }))
25
+ }
26
+
27
+ /** Each opening as a planned project: the hook first, fitted to eight seconds, the brief's look kept. */
28
+ export async function planOpenings({ project, index, asset, brief = {}, signal }) {
29
+ const out = []
30
+ for (const hook of hooksFor(index, asset)) {
31
+ signal?.throwIfAborted()
32
+ const made = await planReel({ project, index, asset, ask: byCode, brief: { ...brief, targetDuration: OPENING, hook: hook.id, mustKeep: [hook.id], effort: "fast" }, variant: { tighter: OPENING / recipeFor(brief).target.max }, signal })
33
+ out.push({ hook, project: made.project })
34
+ }
35
+ return out
36
+ }