@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
@@ -59,6 +59,15 @@ export function paperEdit(raw, { assets, budget = BUDGETS.paper } = {}) {
59
59
  return fence("Paper edit: one sentence a line, [sentence id, word ids, seconds, flags] then the words as heard.", lines, budget, (left) => `[${left} more sentences not shown: ask for a slice]`)
60
60
  }
61
61
 
62
+ /**
63
+ * The phrases a scene can start and end on, for the visual beats slot. `[a1:w12-a1:w19 2.4s] "…"`
64
+ * @param {{ from: string, to: string, start: number, end: number, text: string }[]} phrases
65
+ */
66
+ export function phraseView(phrases, budget = BUDGETS.paper) {
67
+ const lines = phrases.map((p) => `[${p.from}-${p.to} ${seconds(p.end - p.start)}s] ${quote(p.text)}`)
68
+ return fence("The speech in phrases: [first word id-last word id, seconds] then the words as heard.", lines, budget, (left) => `[${left} more phrases not shown]`)
69
+ }
70
+
62
71
  /** The shot digest: ids, exact flicks, length, faces, movement and picture flags. */
63
72
  export function shotDigest(raw, { assets, budget = BUDGETS.shots } = {}) {
64
73
  const faces = new Map()
@@ -8,11 +8,13 @@
8
8
  import { apply } from "../core/ops.js"
9
9
  import { compile } from "../core/plan.js"
10
10
  import { runGates } from "../gates/index.js"
11
+ import { remapIds, remapOp, replayable } from "../director/continuity.js"
11
12
  import { planReel, recipeFor } from "../recipes/reel.js"
12
13
  import { search } from "./loop.js"
13
14
  import { repairLadder } from "./repair.js"
14
15
 
15
16
  const FLICKS = 705_600_000
17
+ const TEXT_GATES = new Set(["QG-08", "QG-09", "QG-10", "QG-11"])
16
18
 
17
19
  /** F0: what the plan alone shows. Nothing renders for an attempt that fails here (ET-LOOP-04). */
18
20
  export function planVerdict(project, index, recipe, { engineVersion = "f0", runtimeVersion = "f0" } = {}) {
@@ -38,19 +40,21 @@ export function planVerdict(project, index, recipe, { engineVersion = "f0", runt
38
40
  * gateKit?: { tilePath?: Function, motion?: object, work?: string }, the Engine's tiles and Chrome, for QG-08 and QG-09
39
41
  * }} input
40
42
  */
41
- export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {} }) {
42
- const recipe = recipeFor(brief)
43
+ export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {}, planner = null, plannerRecipe = null, edits = [] }) {
44
+ // edits: what the person did to the last cut, replayed on each candidate before it is rendered and gated
45
+ // planner: a recipe with no variants to try (a programme, a montage), instead of the reel
46
+ const recipe = plannerRecipe ?? recipeFor(brief)
43
47
  let calls = 0
44
48
  const notes = []
45
49
  const slots = {}
46
50
 
47
51
  const variantOf = async (variant) => {
48
52
  onStage("story")
49
- const made = await planReel({ project, index, asset, ask, brief, variant, signal })
53
+ const made = planner ? await planner() : await planReel({ project, index, asset, ask, brief, variant, signal })
50
54
  calls += made.calls
51
55
  Object.assign(slots, made.slots)
52
56
  for (const note of made.notes) if (!notes.includes(note)) notes.push(note)
53
- return { ...made, variant }
57
+ return { ...carryEdits(made, edits, { before: project, index }), variant }
54
58
  }
55
59
 
56
60
  const evaluate = async (candidate) => {
@@ -73,13 +77,14 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
73
77
  }
74
78
  Object.assign(candidate, { project: attempt.project, ops: attempt.ops, file: attempt.file, plan: attempt.plan, gates: attempt.checked })
75
79
  const checked = attempt.checked
76
- return { level: "F5", blocking: checked.blocking, briefMisses: checked.briefMisses, notes: checked.notes, quality: f0.quality, verdict: checked.verdict }
80
+ return { level: "F5", blocking: checked.blocking, briefMisses: checked.briefMisses, notes: checked.notes, quality: f0.quality, verdict: checked.verdict, failed: checked.gates?.filter((g) => g.status === "failed" && g.severity !== "note").map((g) => g.id) ?? [] }
77
81
  }
78
82
 
79
83
  const outcome = await search({
80
84
  start: { start: true, project },
81
85
  // Round 1: the recipe as planned. Later rounds: a tighter cut, then the original order
82
- propose: async (best, round) => [await variantOf(round === 1 ? {} : round === 2 ? { tighter: 0.85 } : { noHook: true })],
86
+ // Another length or order can't fix what's wrong with how text is drawn: those rounds only cost time
87
+ propose: async (best, round) => (round > 1 && (planner || (best.verdict.briefMisses === 0 && best.verdict.failed?.length && best.verdict.failed.every((id) => TEXT_GATES.has(id)))) ? [] : [await variantOf(round === 1 ? {} : round === 2 ? { tighter: 0.85 } : { noHook: true })]),
83
88
  evaluate,
84
89
  signal,
85
90
  rounds: 3,
@@ -91,6 +96,20 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
91
96
  return { best: best.start ? null : best, outcome, notes, calls, slots, head }
92
97
  }
93
98
 
99
+ /**
100
+ * The person's edits since the last make, replayed on a remade cut: each pointed at the clip
101
+ * that replaced its own, applied if it still fits and listed if it doesn't, never forced.
102
+ * @returns the candidate with those operations after its own, and `dropped`
103
+ */
104
+ export function carryEdits(made, edits, { before, index }) {
105
+ const worth = replayable(edits, before)
106
+ if (!worth.length) return made
107
+ const ids = remapIds(before, made.project, index)
108
+ const { ops, dropped } = rebase(made.project, worth.map((op) => remapOp(op, ids)), index)
109
+ const landed = ops.length ? apply(made.project, ops, { index, author: "agent" }) : null
110
+ return { ...made, ops: [...made.ops, ...ops], project: landed?.applied ? landed.project : made.project, carried: landed?.applied ? ops : [], dropped }
111
+ }
112
+
94
113
  /**
95
114
  * Lands the winner on HEAD. Unchanged HEAD: one entry. Changed: each operation is tried
96
115
  * on the new HEAD, and one that conflicts is dropped and listed, never forced.
@@ -0,0 +1,57 @@
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 { 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
+ const graphic = cleanGraphic(raw)
36
+ if (!graphic) continue
37
+ const length = graphicLength(graphic)
38
+ const leave = (reason) => notes.push(`Left out the ${graphicLine(graphic)}: ${reason}.`)
39
+ // The end card starts on the last word that leaves it its full length; the opening title on the first
40
+ 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)
41
+ if (!word) {
42
+ leave("its line isn't in this cut")
43
+ continue
44
+ }
45
+ const at = word.out
46
+ const duration = Math.min(length, timeline.duration - at)
47
+ const end = at + duration
48
+ if (duration < MIN_LENGTH) leave("there isn't time for it before the cut ends")
49
+ else if (taken.some((t) => at < t.end + GAP && t.at < end + GAP)) leave("something else is on screen there")
50
+ else {
51
+ taken.push({ at, end })
52
+ const { at: _word, ...variables } = graphic
53
+ ops.push({ op: "add_motion", block: GRAPHIC_BLOCK, version: GRAPHIC_VERSION, variables: { ...variables, plan: true }, at: { word: word.id, edge: "start" }, duration })
54
+ }
55
+ }
56
+ return { ops, notes }
57
+ }
@@ -0,0 +1,74 @@
1
+ // A music-led montage (DP5): the person's song leads, and their clips cut on its beats. Each cut lands
2
+ // on a beat of the song's own grid, each clip moves through new parts of its source, and the clips'
3
+ // own sound goes, so what's heard is the song.
4
+
5
+ import { apply } from "../core/ops.js"
6
+ import { solve } from "../core/solver.js"
7
+ import { recipeFor } from "./reel.js"
8
+
9
+ const FLICKS = 705_600_000
10
+ const MIN_SHOT = 0.8 * FLICKS
11
+ const MAX_SHOT = 5 * FLICKS
12
+
13
+ /** Shot lengths from the song's beats: every beat that's at least MIN_SHOT on from the last cut, up to `total`. */
14
+ export function beatCuts(beats, total) {
15
+ const times = [...new Set(beats.map((b) => b.t))].filter((t) => t > 0 && t <= total).sort((a, b) => a - b)
16
+ const cuts = []
17
+ let last = 0
18
+ for (const t of times) {
19
+ if (t - last < MIN_SHOT) continue
20
+ // A long gap in the beat grid still gets a picture change
21
+ while (t - last > MAX_SHOT) {
22
+ last += MAX_SHOT
23
+ cuts.push(last)
24
+ }
25
+ cuts.push(t)
26
+ last = t
27
+ }
28
+ return cuts
29
+ }
30
+
31
+ /** @param {{ project: object, index: object, brief: object }} input brief.music: the song's asset id */
32
+ export function planMontage({ project, index, brief = {} }) {
33
+ const recipe = recipeFor(brief)
34
+ const song = project.assets.find((a) => a.id === brief.music && a.kind === "audio")
35
+ const clips = project.assets.filter((a) => a.kind === "video" && (a.facts.duration ?? 0) >= MIN_SHOT)
36
+ if (!song) throw new Error("A montage needs a song in the project.")
37
+ if (!clips.length) throw new Error("A montage needs at least one video in the project.")
38
+ const footage = clips.reduce((sum, a) => sum + a.facts.duration, 0)
39
+ const total = Math.min(brief.targetDuration ?? song.facts.duration, song.facts.duration, footage)
40
+ const beats = (index.beats ?? []).filter((b) => b.asset === song.id)
41
+ const notes = []
42
+ if (!beats.length) notes.push("This song has no beat grid, so the cuts follow an even rhythm instead of its beats.")
43
+ const cuts = beats.length ? beatCuts(beats, total) : Array.from({ length: Math.floor(total / (2 * FLICKS)) }, (_, i) => (i + 1) * 2 * FLICKS)
44
+ const edges = [0, ...cuts.filter((c) => c < total - MIN_SHOT), total]
45
+ const sequence = project.sequences.find((q) => q.id === project.active)
46
+ const rebuilt = new Set(sequence.tracks.filter((t) => ["base", "caption", "music"].includes(t.role)).map((t) => t.id))
47
+ const ops = [
48
+ ...sequence.clips.filter((c) => rebuilt.has(c.track) || c.effects?.some((e) => e.blockId === "scene")).map((c) => ({ op: "ripple_delete", clip: c.id })),
49
+ { op: "set_brief", format: recipe.id, targetDuration: total, mustKeep: [], mustCut: [], effort: brief.effort ?? "best" },
50
+ { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
51
+ ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...recipe.deliverable }]),
52
+ ]
53
+ // Round the clips, each from where it last stopped, wrapping when one runs out
54
+ const played = new Map(clips.map((a) => [a.id, 0]))
55
+ for (let i = 0; i + 1 < edges.length; i++) {
56
+ const length = edges[i + 1] - edges[i]
57
+ const clip = clips[i % clips.length]
58
+ let from = played.get(clip.id)
59
+ if (from + length > clip.facts.duration) from = 0
60
+ const to = Math.min(from + length, clip.facts.duration)
61
+ played.set(clip.id, to)
62
+ ops.push({ op: "keep_range", asset: clip.id, from, to, exact: true })
63
+ }
64
+ const cut = apply(project, ops, { index, author: "agent" })
65
+ if (!cut.applied) throw new Error(`The montage was refused: ${cut.diagnostics[0].message}`)
66
+ const after = cut.project.sequences.find((q) => q.id === cut.project.active)
67
+ const base = new Set(after.tracks.filter((t) => t.role === "base").map((t) => t.id))
68
+ const placed = after.clips.filter((c) => base.has(c.track))
69
+ const all = [...ops, ...placed.map((c) => ({ op: "set_level", clip: c.id, db: -60 })), { op: "set_music", asset: song.id }, { op: "music_shape", fit: true, fadeIn: Math.round(FLICKS * 0.1) }]
70
+ const step = apply(project, all, { index, author: "agent" })
71
+ if (!step.applied) throw new Error(`The montage was refused: ${step.diagnostics[0].message}`)
72
+ notes.push(`Cut ${placed.length} shots to the song's beats over ${(solve(step.project, index).duration / FLICKS).toFixed(1)} s.`)
73
+ return { ops: all, project: step.project, notes, calls: 0, slots: {} }
74
+ }
@@ -0,0 +1,24 @@
1
+ // A podcast from a plan (DP2): `planMulticam` makes the switching, this dresses it with what the
2
+ // brief asked for. Captions read the master's words, so they follow the talk through every switch.
3
+
4
+ import { apply } from "../core/ops.js"
5
+ import { LOOKS, pages, readablePages } from "../engine/captions.js"
6
+ import { planMulticam, PODCAST_MULTICAM } from "./multicam.js"
7
+
8
+ export const programmeRecipe = { ...PODCAST_MULTICAM }
9
+
10
+ /** @param {{ project: object, index: object, brief: object, multicam: { master: string, angles: object[], analysis: object } }} input */
11
+ export function planProgramme({ project, index, brief = {}, multicam }) {
12
+ const made = planMulticam({ project, index, ...multicam, brief })
13
+ const words = (index.words ?? []).filter((w) => w.asset === multicam.master && !w.flags?.includes("trimmed"))
14
+ const captions = LOOKS[brief.captions] ? (index.sentences ?? []).filter((s) => s.asset === multicam.master).flatMap((s) => {
15
+ const run = words.filter((w) => w.start >= s.start && w.end <= s.end)
16
+ return readablePages(pages(run), run)
17
+ }).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
18
+ const captionLook = { ...(brief.captionStyle ?? {}), ...(brief.holdCaptions ? { hold: true } : {}) }
19
+ const style = Object.keys(captionLook).length ? [{ op: "set_look", caption: captionLook }] : []
20
+ const ops = [...made.ops, ...style, ...captions]
21
+ const step = apply(project, ops, { index, author: "agent" })
22
+ if (!step.applied) throw new Error(`The programme was refused: ${step.diagnostics[0].message}`)
23
+ return { ops, project: step.project, notes: made.notes, calls: 0, slots: {} }
24
+ }
@@ -4,10 +4,14 @@
4
4
  // −14 LUFS. Code does the editing; the model makes two small choices (the hook and
5
5
  // the lines to drop; the emphasis words), each with a default that needs no model.
6
6
 
7
+ import { isSceneBlock } from "../core/layout.js"
8
+ import { graphicOps, isPlanGraphic } from "./graphic-clips.js"
9
+ import { TRANSITION_DEFAULT, TRANSITIONS } from "../core/transitions.js"
7
10
  import { apply } from "../core/ops.js"
8
11
  import { solve } from "../core/solver.js"
9
- import { LOOKS, pages } from "../engine/captions.js"
12
+ import { LOOKS, pages, readablePages } from "../engine/captions.js"
10
13
  import { paperEdit } from "../index/views.js"
14
+ import { sceneOps } from "./scene-clips.js"
11
15
 
12
16
  const FLICKS = 705_600_000
13
17
 
@@ -166,7 +170,10 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
166
170
  const scoped = { ...index, sentences: lines, words: lines.flatMap((l) => l.words), takes: [] }
167
171
 
168
172
  // Story: the hook, and the lines that add nothing (sentence ids only)
169
- const story = await ask({
173
+ // A change to a cut that's already made keeps its story (continuity.js): the Host passes the
174
+ // last make's choice, checked here against this footage, and no model is asked
175
+ const keptStory = brief.story && typeof brief.story === "object" ? { hook: ids.has(brief.story.hook) ? brief.story.hook : null, drop: (Array.isArray(brief.story.drop) ? brief.story.drop : []).filter((id) => ids.has(id)) } : null
176
+ const story = keptStory ? { value: keptStory, source: "kept", calls: 0 } : await ask({
170
177
  task: "story",
171
178
  schema: STORY_SCHEMA,
172
179
  recipe: recipe.notes,
@@ -183,11 +190,20 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
183
190
  // A hook the person approved in the Director's plan wins over the model's pick
184
191
  const planned = typeof brief.hook === "string" && lines.some((l) => l.id === brief.hook) ? brief.hook : null
185
192
  const hook = variant.noHook ? null : (planned ?? story.value.hook)
186
- let chosen = lines.filter((l) => !story.value.drop.includes(l.id) || mustKeep.includes(l.id))
193
+ // The lines under an approved scene stay: fitting the length mustn't take a scene the person approved (found on real footage)
194
+ const wordsById = new Map(index.words.map((w) => [w.id, w]))
195
+ const sceneLines = [...(brief.scenes ?? []), ...(brief.pictures ?? [])].flatMap((scene) => {
196
+ const from = wordsById.get(scene.from)
197
+ const to = wordsById.get(scene.to)
198
+ return from && to ? lines.filter((l) => l.start < to.end && from.start < l.end).map((l) => l.id) : []
199
+ })
200
+ let chosen = lines.filter((l) => !story.value.drop.includes(l.id) || mustKeep.includes(l.id) || sceneLines.includes(l.id))
187
201
 
188
202
  // Length: fit under the maximum, the hook and must-keeps always in
189
- const max = Math.round(recipe.target.max * (variant.tighter ?? 1))
190
- const required = new Set([...mustKeep, ...(hook ? [hook] : [])])
203
+ // With scenes, the length the person asked for is the limit, even past the reel's 60 s
204
+ const longest = brief.scenes?.length || brief.pictures?.length ? Math.max(recipe.target.max, brief.targetDuration ?? 0) : recipe.target.max
205
+ const max = Math.round(longest * (variant.tighter ?? 1))
206
+ const required = new Set([...mustKeep, ...sceneLines, ...(hook ? [hook] : [])])
191
207
  if (chosen.reduce((sum, l) => sum + lengthOf(l), 0) > max) chosen = fitLines(chosen, max, required)
192
208
  const total = chosen.reduce((sum, l) => sum + lengthOf(l), 0)
193
209
  // Short footage sets the length: a 29 s take makes a 29 s cut, not a cut that "needs you"
@@ -205,7 +221,8 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
205
221
  // make left them all on screen twice (found in use, 2026-11-09)
206
222
  const rebuilt = new Set(sequence.tracks.filter((t) => ["base", "caption", "music"].includes(t.role)).map((t) => t.id))
207
223
  const ops = [
208
- ...sequence.clips.filter((c) => rebuilt.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
224
+ // Scenes too: an earlier make's scenes hang on the words of that cut
225
+ ...sequence.clips.filter((c) => rebuilt.has(c.track) || c.effects?.some((e) => isSceneBlock(e) || isPlanGraphic(e))).map((c) => ({ op: "ripple_delete", clip: c.id })),
209
226
  { op: "set_brief", format: recipe.id, targetDuration: target, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
210
227
  { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
211
228
  ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...deliverableFor(brief) }]),
@@ -227,16 +244,27 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
227
244
  // Emphasis: a few words worth a punch-in; a reference's pace can ask for more (EDD-23)
228
245
  const most = Number.isInteger(brief.punches) && brief.punches > 0 ? Math.min(brief.punches, 8) : recipe.punch.max
229
246
  const kept = chosen.flatMap((l) => runsOf(l).flat())
230
- const keptIds = new Set(kept.map((w) => w.id))
231
- const emphasis = await ask({
247
+ // The approved plan's scenes, on the cut as solved. A zoom or title under one would never be seen
248
+ const scenes = brief.scenes?.length || brief.pictures?.length || brief.terms?.length ? sceneOps({ scenes: brief.scenes ?? [], pictures: brief.pictures ?? [], terms: brief.terms ?? [], project: step.project, index, asset, kept, captions: !!LOOKS[brief.captions], sound: { scene: brief.sfx?.scene, reveal: brief.sfx?.reveal } }) : { ops: [], covered: new Set(), notes: [] }
249
+ notes.push(...scenes.notes)
250
+ // The approved plan's motion graphics (MOTION_GRAPHICS.md), placed on the cut with its scenes in, so none lands on one
251
+ const withScenes = scenes.ops.length ? apply(step.project, scenes.ops, { index, author: "agent" }) : null
252
+ const graphics = brief.graphics?.length ? graphicOps({ graphics: brief.graphics, project: withScenes?.applied ? withScenes.project : step.project, index, asset, kept }) : { ops: [], notes: [] }
253
+ notes.push(...graphics.notes)
254
+ const visible = kept.filter((w) => !scenes.covered.has(w.id))
255
+ const keptIds = new Set(visible.map((w) => w.id))
256
+ // The same words stay punched in while the plan asks for as many as before
257
+ const was = keptStory && brief.story.emphasis
258
+ const keptWords = was && was.most === most && Array.isArray(was.ids) ? was.ids.filter((id) => keptIds.has(id)) : null
259
+ const emphasis = keptWords ? { value: { emphasis: keptWords }, source: "kept", calls: 0 } : await ask({
232
260
  task: "emphasis",
233
261
  schema: EMPHASIS_SCHEMA,
234
262
  recipe: recipe.notes,
235
- view: paperEdit({ ...scoped, sentences: chosen }, { assets: [asset] }),
263
+ view: paperEdit({ ...scoped, sentences: chosen.filter((l) => l.words.some((w) => keptIds.has(w.id))) }, { assets: [asset] }),
236
264
  request: `Pick up to ${most} single words to emphasise with a quick zoom: numbers, names, the point of a line. Word ids only.`,
237
265
  maxOutput: 200,
238
266
  check: ({ emphasis: picked }) => picked.filter((id) => !keptIds.has(id)).map((id) => `"${id}" isn't a kept word`),
239
- fallback: () => ({ emphasis: kept.filter((w) => /\d/.test(w.text)).slice(0, most).map((w) => w.id) }),
267
+ fallback: () => ({ emphasis: visible.filter((w) => /\d/.test(w.text)).slice(0, most).map((w) => w.id) }),
240
268
  signal,
241
269
  })
242
270
  calls += emphasis.calls
@@ -260,7 +288,9 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
260
288
  // Sound design: an effect on every cut of the story, a riser into it after a cold open.
261
289
  // Each is placed by its peak, so the loudest moment lands on the cut
262
290
  const storyClips = clips.filter((c) => !c.echo)
263
- const cutSounds = brief.sfx?.cut ? storyClips.slice(1).map((c) => ({ op: "add_sfx", asset: brief.sfx.cut, peak_at: { clip: c.id, edge: "start" } })) : []
291
+ // A playbook's restraint: a sound on every nth cut, not on all of them
292
+ const every = Number.isInteger(brief.soundEvery) && brief.soundEvery > 1 ? brief.soundEvery : 1
293
+ const cutSounds = brief.sfx?.cut ? storyClips.slice(1).filter((_, i) => i % every === 0).map((c) => ({ op: "add_sfx", asset: brief.sfx.cut, peak_at: { clip: c.id, edge: "start" } })) : []
264
294
  const introSound = brief.sfx?.intro && cold && storyClips[0] ? [{ op: "add_sfx", asset: brief.sfx.intro, peak_at: { clip: storyClips[0].id, edge: "start" } }] : []
265
295
  const sounds = [...cutSounds, ...introSound]
266
296
 
@@ -300,13 +330,34 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
300
330
  const cleaning = brief.cleanVoice ? clips.map((c) => ({ op: "clean_voice", clip: c.id, strength: 0.6 })) : []
301
331
 
302
332
  // Captions, when the brief asks for a look: pages of the kept words, timed to the speech
303
- const captions = LOOKS[brief.captions] ? chosen.flatMap((l) => runsOf(l)).flatMap((run) => pages(run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
333
+ const captions = LOOKS[brief.captions] ? chosen.flatMap((l) => runsOf(l)).flatMap((run) => readablePages(pages(run), run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
304
334
  // Music, when the brief names a sound in the project: fitted on its downbeats, ducked under the speech (ED9)
305
335
  const song = brief.music ? project.assets.find((a) => a.id === brief.music && a.kind === "audio") : null
306
336
  if (brief.music && !song) notes.push(`There is no sound "${brief.music}" in this project, so the reel has no music.`)
307
337
  const music = song ? [{ op: "set_music", asset: song.id }, { op: "music_shape", fit: true, fadeIn: Math.round(FLICKS * 0.3) }, { op: "duck" }] : []
308
- const all = [...ops, ...angles, ...punches, ...framing, ...grading, ...cleaning, ...broll, ...titles, ...captions, ...music, ...sounds, ...ramps]
338
+ const captionLook = { ...(brief.captionStyle ?? {}), ...(brief.holdCaptions ? { hold: true } : {}) }
339
+ const style = LOOKS[brief.captions] && Object.keys(captionLook).length ? [{ op: "set_look", caption: captionLook }] : []
340
+ // Transitions (transitions.js): where the story changes moment (out of the cold open, a line moved
341
+ // up, a jump of seconds in the take), or on every cut when the person asked. A filler cut stays a cut
342
+ const joins = []
343
+ if (Object.hasOwn(TRANSITIONS, brief.transition ?? "")) {
344
+ const SECTION = 3 * FLICKS
345
+ // The story as it plays: each clip's stretch of the take, in order (a clip's own source is word anchors)
346
+ const played = []
347
+ for (const p of solve(step.project, index).picture) {
348
+ if (p.hold) continue
349
+ if (played.at(-1)?.clip === p.clip) played.at(-1).out = p.out
350
+ else played.push({ clip: p.clip, asset: p.asset, in: p.in, out: p.out, echo: !!p.echo })
351
+ }
352
+ for (let i = 1; i < played.length; i++) {
353
+ const [a, b] = [played[i - 1], played[i]]
354
+ const moment = a.echo !== b.echo || a.asset !== b.asset || b.in < a.out || b.in - a.out > SECTION
355
+ if (brief.transitionAll || moment) joins.push({ op: "transition", clip: b.clip, kind: brief.transition, duration: TRANSITION_DEFAULT })
356
+ }
357
+ if (!joins.length) notes.push(`No ${brief.transition} transition: this cut runs straight through, with no change of moment to dress.`)
358
+ }
359
+ const all = [...ops, ...style, ...angles, ...punches, ...framing, ...grading, ...cleaning, ...broll, ...titles, ...scenes.ops, ...graphics.ops, ...captions, ...music, ...sounds, ...ramps, ...joins]
309
360
  step = apply(project, all, { index, author: "agent" })
310
361
  if (!step.applied) throw new Error(`The reel was refused: ${step.diagnostics[0].message}`)
311
- return { ops: all, project: step.project, notes, calls, slots }
362
+ return { ops: all, project: step.project, notes, calls, slots, story: { hook: story.value.hook ?? null, drop: story.value.drop ?? [], emphasis: { most, ids: [...new Set(emphasis.value.emphasis)].slice(0, most) } } }
312
363
  }
@@ -0,0 +1,127 @@
1
+ // Scene clips (VISUAL_SCENES.md §3.2): an approved plan's scenes as operations on the cut as
2
+ // solved. The words anchor them, so a scene moves with its speech; each label is timed to the
3
+ // word it's said on; code checks again what the plan checked, since a re-cut can drop a line.
4
+
5
+ import { arrangeScenes, MAX_SHARE, revealWords } from "../director/beats.js"
6
+ import { cleanScene, SCENE_BLOCK, SCENE_THEMES, SCENE_VERSION } from "../engine/scenes.js"
7
+ import { solve } from "../core/solver.js"
8
+
9
+ const FLICKS = 705_600_000
10
+ const OPENING = 2 * FLICKS // the speaker is seen first
11
+ // Removing pauses can tighten an approved gap: closer than this, the first scene holds until the next starts, so the speaker doesn't flash between them
12
+ const MIN_GAP = 1 * FLICKS
13
+ const MIN_LENGTH = 2 * FLICKS
14
+ const MAX_LENGTH = 15 * FLICKS
15
+ const REVEAL_GAP = 0.6 * FLICKS // pops closer than this blur together
16
+
17
+ /**
18
+ * pictures: approved licensed clips, resolved to assets; terms: quoted definitions to show on their words.
19
+ * @param {{ scenes: object[], pictures?: { asset: string, from: string, to: string }[], terms?: { at: string, term: string, quote: string, source: string }[], project: object, index: object, asset: string, kept: { id: string }[], captions?: boolean, sound?: { scene?: string, reveal?: string } }} input
20
+ * project: with the cut applied; kept: the words the cut keeps
21
+ * @returns {{ ops: object[], covered: Set<string>, notes: string[] }} covered: the words under a scene
22
+ */
23
+ export function sceneOps({ scenes, pictures = [], terms = [], project, index, asset, kept, captions = false, sound = {} }) {
24
+ const notes = []
25
+ const covered = new Set()
26
+ const ops = []
27
+ const { scenes: arranged, dropped } = arrangeScenes(scenes, { index, asset })
28
+ for (const { scene, reason } of dropped) notes.push(`Left out the ${scene.kind} scene: ${reason}.`)
29
+ const timeline = solve(project, index)
30
+ const story = timeline.picture.filter((p) => !p.echo && !p.hold)
31
+ const start = story[0]?.at ?? 0
32
+ const outputOf = (word, edge) => {
33
+ const t = edge === "start" ? word.start : word.end
34
+ const piece = story.find((p) => p.asset === asset && t >= p.in && t <= p.out)
35
+ return piece ? piece.at + (t - piece.in) : null
36
+ }
37
+ const keptIds = new Set(kept.map((w) => w.id))
38
+ const words = index.words.filter((w) => w.asset === asset)
39
+ const byId = new Map(words.map((w) => [w.id, w]))
40
+ let last = -Infinity
41
+ let previous = null
42
+ let used = 0
43
+ for (const raw of arranged) {
44
+ const scene = cleanScene(raw)
45
+ const from = byId.get(scene.from)
46
+ const to = byId.get(scene.to)
47
+ const name = `"${scene.title || scene.items[0].text}"`
48
+ const spoken = words.filter((w) => w.start >= from.start && w.end <= to.end && keptIds.has(w.id))
49
+ if (!spoken.length) {
50
+ notes.push(`Left out the scene ${name}: its lines aren't in this cut.`)
51
+ continue
52
+ }
53
+ const at = outputOf(spoken[0], "start")
54
+ const end = outputOf(spoken.at(-1), "end")
55
+ const length = end - at
56
+ const refuse = at === null || end === null || !(length > 0) ? "its lines aren't together in this cut" : at < start + OPENING ? "the speaker is seen first" : length < MIN_LENGTH ? "its lines are too short in this cut" : length > MAX_LENGTH ? "its lines are apart in this cut" : at < last ? "its lines come before the last scene in this cut" : used + length > timeline.duration * MAX_SHARE ? "the speaker would hardly be seen" : null
57
+ if (refuse) {
58
+ notes.push(`Left out the scene ${name}: ${refuse}.`)
59
+ continue
60
+ }
61
+ if (previous && at - last < MIN_GAP) previous.until = { word: spoken[0].id, edge: "start" }
62
+ const landing = revealWords(scene, spoken)
63
+ const items = scene.items.map((item, i) => {
64
+ const t = landing[i] && outputOf(landing[i], "start")
65
+ return { ...item, ...(t === null || t === undefined ? {} : { reveal: Math.round(((t - at) / FLICKS) * 1000) }) }
66
+ })
67
+ last = end
68
+ used += length
69
+ for (const word of spoken) covered.add(word.id)
70
+ previous = {
71
+ op: "add_motion",
72
+ block: SCENE_BLOCK,
73
+ version: SCENE_VERSION,
74
+ variables: { kind: scene.kind, theme: scene.theme, title: scene.title, text: scene.title || scene.items[0].text, items, ...(scene.mode ? { mode: scene.mode } : {}), ...(captions && SCENE_THEMES[scene.theme].band ? { band: true } : {}) },
75
+ at: { word: spoken[0].id, edge: "start" },
76
+ until: { word: spoken.at(-1).id, edge: "end" },
77
+ }
78
+ ops.push(previous)
79
+ if (sound.scene) ops.push({ op: "add_sfx", asset: sound.scene, peak_at: { word: spoken[0].id, edge: "start" } })
80
+ if (sound.reveal) {
81
+ let lastPop = at
82
+ for (const word of landing) {
83
+ const t = word && outputOf(word, "start")
84
+ if (t === null || t === undefined || t - lastPop < REVEAL_GAP) continue
85
+ lastPop = t
86
+ ops.push({ op: "add_sfx", asset: sound.reveal, peak_at: { word: word.id, edge: "start" } })
87
+ }
88
+ }
89
+ }
90
+ const taken = ops.filter((o) => o.op === "add_motion").map((o) => ({ at: outputOf(byId.get(o.at.word), "start"), end: outputOf(byId.get(o.until.word), "end") }))
91
+ for (const picture of pictures) {
92
+ const from = byId.get(picture.from)
93
+ const to = byId.get(picture.to)
94
+ const asset_ = project.assets.find((a) => a.id === picture.asset)
95
+ const spoken = from && to ? words.filter((w) => w.start >= from.start && w.end <= to.end && keptIds.has(w.id)) : []
96
+ if (!spoken.length || !asset_) {
97
+ notes.push("Left out a picture: its lines aren't in this cut.")
98
+ continue
99
+ }
100
+ const at = outputOf(spoken[0], "start")
101
+ const end = outputOf(spoken.at(-1), "end")
102
+ const length = end - at
103
+ const refuse = at === null || end === null || !(length > 0) ? "its lines aren't together in this cut" : at < start + OPENING ? "the speaker is seen first" : length < MIN_LENGTH || length > MAX_LENGTH ? "its lines don't fit it in this cut" : taken.some((t) => at < t.end && t.at < end) ? "a scene is already there" : length > (asset_.facts.duration ?? 0) ? "the clip is too short for its lines" : used + length > timeline.duration * MAX_SHARE ? "the speaker would hardly be seen" : null
104
+ if (refuse) {
105
+ notes.push(`Left out a picture: ${refuse}.`)
106
+ continue
107
+ }
108
+ used += length
109
+ taken.push({ at, end })
110
+ for (const word of spoken) covered.add(word.id)
111
+ ops.push({ op: "place_broll", asset: asset_.id, at: { word: spoken[0].id, edge: "start" }, until: { word: spoken.at(-1).id, edge: "end" } })
112
+ if (sound.scene) ops.push({ op: "add_sfx", asset: sound.scene, peak_at: { word: spoken[0].id, edge: "start" } })
113
+ }
114
+ for (const term of terms) {
115
+ const word = byId.get(term.at)
116
+ const at = word && keptIds.has(word.id) ? outputOf(word, "start") : null
117
+ if (at === null || taken.some((t) => at >= t.at && at < t.end)) {
118
+ notes.push(`Left out the definition of "${term.term}": something else is on screen there, or the line isn't in this cut.`)
119
+ continue
120
+ }
121
+ // Long enough to read: letters over 15 a second, plus a second and a half
122
+ const seconds = Math.min(7, (term.term.length + term.quote.length + term.source.length) / 15 + 1.5)
123
+ const duration = Math.round(Math.min(seconds * FLICKS, Math.max(FLICKS, timeline.duration - at)))
124
+ ops.push({ op: "add_motion", block: "term", version: 1, variables: { text: term.term, quote: term.quote, source: term.source, ...(term.page ? { page: term.page } : {}) }, at: { word: word.id, edge: "start" }, duration })
125
+ }
126
+ return { ops, covered, notes }
127
+ }
@@ -4,6 +4,39 @@
4
4
  import { call, KriyaError } from "../../api.js"
5
5
  import { openManifest, RuntimeError, TRUSTED_KEYS } from "./manifest.js"
6
6
 
7
+ /**
8
+ * What this Kriya has switched on for editing (EH-01). Any failure, a server with no such
9
+ * route among them, means off: the server ships first, and a client never assumes (track E rule 17).
10
+ * @returns {Promise<{ visuals: boolean, playbooks: boolean, mediaSearch: boolean, motion: boolean, customMotion: boolean }>}
11
+ */
12
+ export async function fetchFeatures(device) {
13
+ try {
14
+ const found = await call(device.url, "GET", "/editing/features", { token: device.token })
15
+ // motion, customMotion: a server from before them says nothing, which is off
16
+ return { visuals: found?.visuals === true, playbooks: found?.playbooks === true, mediaSearch: found?.mediaSearch === true, motion: found?.motion === true, customMotion: found?.customMotion === true }
17
+ } catch {
18
+ return { visuals: false, playbooks: false, mediaSearch: false, motion: false, customMotion: false }
19
+ }
20
+ }
21
+
22
+ /** Licensed pictures for these words; nothing found on any failure, so a plan never fails on a search. */
23
+ export async function searchMedia(device, queries) {
24
+ try {
25
+ return (await call(device.url, "POST", "/editing/media", { token: device.token, body: { queries } }))?.results ?? []
26
+ } catch {
27
+ return []
28
+ }
29
+ }
30
+
31
+ /** Cited definitions for these terms; none on any failure. */
32
+ export async function defineTerms(device, terms) {
33
+ try {
34
+ return (await call(device.url, "POST", "/editing/define", { token: device.token, body: { terms } }))?.definitions ?? []
35
+ } catch {
36
+ return []
37
+ }
38
+ }
39
+
7
40
  /** The manifest for this device. A 404 is how a client learns this Kriya has no editing (EH-01). */
8
41
  export async function fetchManifest(device, trusted = TRUSTED_KEYS) {
9
42
  try {
@@ -227,6 +227,21 @@ a { color: var(--teal); }
227
227
  .send { display: grid; gap: 6px; }
228
228
  .extras { display: flex; flex-wrap: wrap; gap: 0 14px; }
229
229
  .plan .steps { margin: 4px 0; padding-left: 20px; display: grid; gap: 4px; }
230
+ .scenes { display: grid; gap: 8px; }
231
+ .scene-head { justify-content: space-between; align-items: center; }
232
+ .scene-head .field { width: auto; }
233
+ .scene-info .field { width: auto; flex: 1 1 140px; min-width: 0; }
234
+ .scene-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 12px; }
235
+ /* A wide (16:9) preview and its controls don't fit side by side on a phone: the controls drop under it */
236
+ .proposal .scene-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-start; justify-content: flex-start; }
237
+ .found-thumb { flex: none; width: 120px; height: 90px; object-fit: cover; border-radius: 6px; background: #000; }
238
+ .scenes .row .field { width: auto; flex: 1 1 120px; min-width: 0; }
239
+ .scene-picture { flex: none; overflow: hidden; border-radius: 6px; background: #000; }
240
+ .scene-picture iframe { border: 0; display: block; transform-origin: 0 0; pointer-events: none; }
241
+ .scene-info { min-width: 0; flex: 1 1 140px; display: grid; gap: 4px; }
242
+ .scene-info p { margin: 0; overflow-wrap: anywhere; }
243
+ .scene-info .row { flex-wrap: wrap; gap: 6px; }
244
+ .scene-time { font-family: ui-monospace, "JetBrains Mono", monospace; color: var(--teal); }
230
245
  .refs-direct { margin: 0; }
231
246
  .refs-direct:empty { display: none; }
232
247
  .ref .ref-lines { list-style: none; padding: 0; margin: 2px 0; font-size: 13px; color: var(--ink-2); display: grid; gap: 2px; }