@kriya-ai/harness 0.2.2 → 0.2.4

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 (45) hide show
  1. package/contract/SOURCE.md +3 -3
  2. package/contract/contract.json +188 -0
  3. package/package.json +1 -1
  4. package/src/edit/core/ffmpeg.js +5 -1
  5. package/src/edit/core/layout.js +26 -1
  6. package/src/edit/core/ops.js +74 -6
  7. package/src/edit/core/plan.js +2 -1
  8. package/src/edit/core/project.js +6 -1
  9. package/src/edit/core/solver.js +66 -15
  10. package/src/edit/director/ask.js +42 -27
  11. package/src/edit/director/beats.js +335 -0
  12. package/src/edit/director/lookups.js +133 -0
  13. package/src/edit/director/plan.js +365 -0
  14. package/src/edit/director/playbooks.js +131 -0
  15. package/src/edit/director/revise.js +171 -12
  16. package/src/edit/engine/captions.js +32 -0
  17. package/src/edit/engine/found-media.js +64 -0
  18. package/src/edit/engine/motion.js +78 -18
  19. package/src/edit/engine/music-bed.js +110 -0
  20. package/src/edit/engine/reference.js +134 -0
  21. package/src/edit/engine/scenes.js +480 -0
  22. package/src/edit/engine/sfx.js +63 -0
  23. package/src/edit/gates/copy.js +25 -5
  24. package/src/edit/gates/index.js +12 -4
  25. package/src/edit/gates/picture.js +5 -0
  26. package/src/edit/gates/text.js +20 -4
  27. package/src/edit/graph/scheduler.js +1 -1
  28. package/src/edit/host/client.js +28 -4
  29. package/src/edit/host/deliver.js +8 -1
  30. package/src/edit/host/jobs.js +43 -0
  31. package/src/edit/host/main.js +4 -2
  32. package/src/edit/host/paths.js +25 -0
  33. package/src/edit/host/projects.js +328 -38
  34. package/src/edit/host/server.js +106 -8
  35. package/src/edit/index/db.js +5 -0
  36. package/src/edit/index/layers/retakes.js +7 -1
  37. package/src/edit/index/views.js +9 -0
  38. package/src/edit/loop/make.js +9 -6
  39. package/src/edit/recipes/montage.js +74 -0
  40. package/src/edit/recipes/programme.js +24 -0
  41. package/src/edit/recipes/reel.js +149 -20
  42. package/src/edit/recipes/scene-clips.js +127 -0
  43. package/src/edit/runtime/fetch.js +32 -0
  44. package/studio/dist/studio.css +62 -4
  45. package/studio/dist/studio.js +4 -2
@@ -2,33 +2,46 @@
2
2
  // person's folder; its history and cache stay in ~/.kriya/edit/<id>/, never synced.
3
3
 
4
4
  import { randomBytes } from "node:crypto"
5
- import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeSync } from "node:fs"
5
+ import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs"
6
6
  import { dirname, extname, isAbsolute, join, relative, sep } from "node:path"
7
7
 
8
8
  import { checkout, commit, createLog, parseEntry, undo, versions } from "../core/history.js"
9
9
  import { canonical, newProject, parseProject, serialize, sha256 } from "../core/project.js"
10
10
  import { createEngine, ENGINE_VERSION, guardPath } from "../engine/index.js"
11
- import { motionRuntime } from "../engine/motion.js"
11
+ import { blockComposition, motionRuntime } from "../engine/motion.js"
12
+ import { cleanScene, SCENE_BLOCK, SCENE_KINDS, SCENE_THEMES, SCENE_VERSION, swapsFor } from "../engine/scenes.js"
12
13
  import { parseCube } from "../engine/color.js"
13
14
  import { fingerprint } from "../engine/media.js"
14
15
  import { probe } from "../engine/probe.js"
15
16
  import { EngineFailure, runTool } from "../engine/tool.js"
16
17
  import { openJournal } from "../graph/journal.js"
17
- import { solve } from "../core/solver.js"
18
+ import { DEFAULT_RULES, solve } from "../core/solver.js"
19
+ import { safeZoneFor, sceneFrame } from "../core/layout.js"
20
+ import { revealWords } from "../director/beats.js"
21
+ import { termId } from "../director/lookups.js"
22
+ import { allowedMediaUrl, downloadMedia, MEDIA_TYPES, stillClipArgs } from "../engine/found-media.js"
23
+ import { planMontage } from "../recipes/montage.js"
24
+ import { analyseMulticam, PODCAST_MULTICAM } from "../recipes/multicam.js"
25
+ import { planProgramme, programmeRecipe } from "../recipes/programme.js"
26
+ import { defineTerms, fetchFeatures, searchMedia } from "../runtime/fetch.js"
27
+ import { readDevice } from "../../store.js"
18
28
  import { createAsk } from "../director/ask.js"
19
29
  import { LOOKS } from "../engine/captions.js"
20
30
  import { cleanSelection, cleanWord, describe, noteWord, revise } from "../director/revise.js"
21
31
  import { openIndexDb } from "../index/db.js"
22
32
  import { makeReel, rebase } from "../loop/make.js"
23
33
  import { runGates } from "../gates/index.js"
24
- import { REEL_TALKING_HEAD } from "../recipes/reel.js"
34
+ import { FORMATS, REEL_TALKING_HEAD } from "../recipes/reel.js"
25
35
  import { compareRuns, replayAsk } from "../loop/replay.js"
26
36
  import { verifiedRecogniser, writeDelivery, writeHandoff } from "./deliver.js"
27
37
  import { createIndexer, layersFor } from "../index/index.js"
28
38
  import { activeRuntime } from "../runtime/setup.js"
29
39
  import { editHome } from "./paths.js"
30
40
  import { createTaste } from "./taste.js"
31
- import { extractDna } from "../engine/dna.js"
41
+ import { ASPECTS, analyseReference, cleanRefs, takeFrom } from "../engine/reference.js"
42
+ import { briefOf, planCut } from "../director/plan.js"
43
+ import { MOODS, writeMusicBed } from "../engine/music-bed.js"
44
+ import { SFX, writeSfx } from "../engine/sfx.js"
32
45
 
33
46
  function atomicWrite(file, text) {
34
47
  const part = `${file}.${process.pid}.tmp`
@@ -74,8 +87,17 @@ const FLICKS = 705_600_000
74
87
  // Director model calls a job may make (DIRECTOR_AND_AGENT §13, short form)
75
88
  const JOB_CALLS = 40
76
89
 
77
- export function createProjects({ home, roots, scheduler, tools, governor = null }) {
90
+ // What the server has switched on, asked for at most once a minute, so turning a switch off takes effect soon
91
+ const FEATURES_MS = 60_000
92
+ const askServer = async () => {
93
+ const device = readDevice()
94
+ return device ? fetchFeatures(device) : { visuals: false, playbooks: false, mediaSearch: false }
95
+ }
96
+ const NOTHING_FOUND = { items: {}, definitions: {} }
97
+
98
+ export function createProjects({ home, roots, scheduler, tools, governor = null, features = askServer }) {
78
99
  const base = editHome(home)
100
+ let known = null
79
101
  const taste = createTaste({ home })
80
102
  const registry = join(base, "projects.json")
81
103
  const open = new Map()
@@ -170,6 +192,26 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
170
192
  persist(state)
171
193
  },
172
194
 
195
+ /**
196
+ * Removes a project from the Studio: its history, cache, index and journal in
197
+ * ~/.kriya/edit/<id>/ go. The person's folder (the project file, footage, exports)
198
+ * is theirs and is never touched. A project with work running is refused.
199
+ */
200
+ remove(id, { running = () => false } = {}) {
201
+ const known = entry(id)
202
+ if (!known) throw new EngineFailure("input", "no_project", "There is no such project.")
203
+ if (running(id)) throw new EngineFailure("input", "busy", "This project has work running. Let it finish or stop it first.")
204
+ const state = open.get(id)
205
+ if (state) {
206
+ state.journal.close()
207
+ state.indexDb.close()
208
+ open.delete(id)
209
+ }
210
+ atomicWrite(registry, JSON.stringify(list().filter((item) => item.id !== id)))
211
+ rmSync(dirOf(id), { recursive: true, force: true })
212
+ return { removed: id, kept: dirname(known.file) }
213
+ },
214
+
173
215
  /** @param {{ name: string, folder: string, offered?: boolean }} input offered: the person offered this folder on this computer (CC-D2) */
174
216
  async create({ name, folder, offered = false }) {
175
217
  const real = guardPath(folder, offered ? [folder] : roots)
@@ -186,7 +228,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
186
228
  },
187
229
 
188
230
  /** Brings a file in by reference: probed, fingerprinted, never copied or written. */
189
- async addAsset(state, path, { reference = false } = {}) {
231
+ async addAsset(state, path, { reference = false, rights = "unknown", rightsNote, extraFacts = {} } = {}) {
190
232
  const real = guardPath(path, [...roots, state.folder])
191
233
  // A .cube is a LUT (ED13): read and checked here, before FFmpeg ever sees it, never probed as media
192
234
  const lut = extname(real).toLowerCase() === ".cube"
@@ -197,13 +239,14 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
197
239
  throw new EngineFailure("input", "refused", error.message)
198
240
  }
199
241
  }
200
- const { facts } = lut ? { facts: {} } : await probe(real)
242
+ const { facts: probed } = lut ? { facts: {} } : await probe(real)
243
+ const facts = { ...probed, ...extraFacts }
201
244
  const id = `a${state.log.current.assets.length + 1}`
202
245
  const within = relative(state.folder, real)
203
246
  const stored = within.startsWith("..") || isAbsolute(within) ? real : within.split(sep).join("/")
204
247
  // A reference is measured for its style only (EDD-23); the person confirmed they may use it
205
- if (reference && !facts.width) throw new EngineFailure("input", "refused", "A reference needs to be a video.")
206
- const op = { op: "add_asset", id, kind: reference ? "reference" : lut ? "lut" : kindOf(facts), fingerprint: await fingerprint(real), path: stored, linked: true, rights: "unknown", ...(reference ? { rightsNote: "The person confirmed they may use it as a style reference." } : {}), facts }
248
+ if (reference && !facts.width && !facts.hasAudio) throw new EngineFailure("input", "refused", "A reference needs to be a video, an image or a piece of music.")
249
+ const op = { op: "add_asset", id, kind: reference ? "reference" : lut ? "lut" : kindOf(facts), fingerprint: await fingerprint(real), path: stored, linked: true, rights: reference ? "unknown" : rights, ...(reference ? { rightsNote: "The person confirmed they may use it as a style reference." } : rightsNote ? { rightsNote } : {}), facts }
207
250
  const result = change(state, { ops: [op], author: "code" })
208
251
  if (!result.ok) throw new EngineFailure("input", "refused", result.diagnostics[0].message)
209
252
  return state.log.current.assets.at(-1)
@@ -244,17 +287,17 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
244
287
  },
245
288
 
246
289
  /** The console: words → a proposal, applied to a copy, nothing landing yet (UX_SPEC §4, §5). */
247
- async ask(state, { text, selection, job = 0 }) {
290
+ async ask(state, { text, selection, history = [], job = 0 }) {
248
291
  const chosen = cleanSelection(selection, state.log.current, state.index)
249
- const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen })
292
+ const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen, history })
250
293
  // A request about the whole video goes to the Director's make job; the Studio offers it
251
294
  const direct = result.direct ? { brief: { ...(result.direct.seconds ? { seconds: result.direct.seconds } : {}), ...(result.direct.captions ? { captions: result.direct.captions } : {}) } } : null
252
- if (!result.ops.length && !result.corrections.length) return { proposal: null, direct, source: result.source, reason: direct ? null : (result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way.") }
295
+ if (!result.ops.length && !result.corrections.length) return { proposal: null, direct, say: result.say, source: result.source, reason: direct || result.say ? null : (result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way.") }
253
296
  const id = randomBytes(6).toString("hex")
254
297
  state.proposals.set(id, { ops: result.ops, corrections: result.corrections, head: state.log.head })
255
298
  const { picture, duration } = solve(result.project ?? state.log.current, state.index)
256
299
  // Changes in one list, operations first, then corrections: "Only this" counts across both
257
- return { proposal: { id, ops: result.ops, changes: [...result.changes, ...result.corrections.map((c) => c.change)], timeline: result.ops.length ? { picture, duration } : null }, direct, source: result.source, ...(result.reason ? { reason: result.reason } : {}) }
300
+ return { proposal: { id, ops: result.ops, changes: [...result.changes, ...result.corrections.map((c) => c.change)], timeline: result.ops.length ? { picture, duration } : null }, direct, say: result.say, source: result.source, ...(result.reason ? { reason: result.reason } : {}) }
258
301
  },
259
302
 
260
303
  /** Accept all, accept some, or reject a proposal. Rebased onto HEAD; the person's own edits never move. */
@@ -276,6 +319,147 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
276
319
  return { applied: ops.length + fixes.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
277
320
  },
278
321
 
322
+ /** What this Kriya allows now. A failed question means off. */
323
+ async features() {
324
+ if (!known || Date.now() - known.at > FEATURES_MS) known = { at: Date.now(), value: await features().catch(() => ({ visuals: false, playbooks: false, mediaSearch: false })) }
325
+ return known.value
326
+ },
327
+
328
+ /**
329
+ * One scene as the render will draw it, for the Plan Card: the words fall where they will,
330
+ * so the person sees the real thing before anything is rendered.
331
+ * @returns {string} a complete document
332
+ */
333
+ scenePreview(state, raw, format) {
334
+ const scene = cleanScene(raw)
335
+ const words = new Map(state.index.words.map((w) => [w.id, w]))
336
+ const from = words.get(scene?.from)
337
+ const to = words.get(scene?.to)
338
+ if (!from || !to || to.end <= from.start) throw new EngineFailure("input", "bad_scene", "That isn't a scene from this project's plan.")
339
+ const shape = FORMATS[format] ?? FORMATS["9:16"]
340
+ const canvas = { width: shape.width, height: shape.height }
341
+ const safe = safeZoneFor({ canvas, deliverables: [{ preset: shape.preset, size: canvas }] })
342
+ const { content } = sceneFrame(canvas, safe, { w: Math.floor((canvas.width * DEFAULT_RULES.boxWidth) / 100), h: Math.floor((canvas.height * DEFAULT_RULES.boxHeight) / 100) })
343
+ const duration = to.end - from.start
344
+ const landing = revealWords(scene, state.index.words.filter((w) => w.asset === from.asset && w.start >= from.start && w.end <= to.end))
345
+ const items = scene.items.map((item, i) => ({ ...item, ...(landing[i] ? { reveal: Math.round(((landing[i].start - from.start) / FLICKS) * 1000) } : {}) }))
346
+ return blockComposition({ blockId: SCENE_BLOCK, version: SCENE_VERSION, variables: { ...scene, items }, placement: content, duration }, { output: canvas, canvas })
347
+ },
348
+
349
+ foundOf(state) {
350
+ const file = join(dirOf(state.id), "cache", "found.json")
351
+ return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : NOTHING_FOUND
352
+ },
353
+
354
+ keepFound(state, { items = [], definitions = [] }) {
355
+ const dir = join(dirOf(state.id), "cache")
356
+ mkdirSync(dir, { recursive: true })
357
+ const known = this.foundOf(state)
358
+ const next = { items: { ...known.items, ...Object.fromEntries(items.map((item) => [item.id, item])) }, definitions: { ...known.definitions, ...Object.fromEntries(definitions.map((d) => [termId(d.term), d])) } }
359
+ atomicWrite(join(dir, "found.json"), JSON.stringify(next))
360
+ },
361
+
362
+ /** A found picture's small version for the Plan Card, fetched once. Only ids this project's plan found. */
363
+ async foundThumb(state, id, { signal } = {}) {
364
+ const item = this.foundOf(state).items[id]
365
+ if (!item || !allowedMediaUrl(item.thumb)) throw new EngineFailure("input", "unknown_media", "That picture isn't from this project's plan.")
366
+ const dir = join(dirOf(state.id), "cache", "found-thumbs")
367
+ mkdirSync(dir, { recursive: true })
368
+ const base = join(dir, sha256(id).slice(0, 24))
369
+ for (const [type, extension] of Object.entries(MEDIA_TYPES)) if (existsSync(`${base}${extension}`)) return { file: `${base}${extension}`, type }
370
+ return downloadMedia(item.thumb, base, { signal, maxBytes: 12 * 1024 * 1024 })
371
+ },
372
+
373
+ /**
374
+ * The approved pictures on disk, as assets with their credit, and the approved definitions as
375
+ * kept. A still becomes a clip with a slow move. One that can't be had is left out with a note.
376
+ */
377
+ async resolveFound(state, brief, { signal, say }) {
378
+ const found = this.foundOf(state)
379
+ const words = new Map(state.index.words.map((w) => [w.id, w]))
380
+ const shape = FORMATS[brief.format] ?? FORMATS["9:16"]
381
+ const media = join(state.folder, "media")
382
+ const pictures = []
383
+ for (const { from, to, id } of brief.pictures ?? []) {
384
+ const item = found.items[id]
385
+ const first = words.get(from)
386
+ const last = words.get(to)
387
+ if (!item || !first || !last || !allowedMediaUrl(item.url)) {
388
+ say("Left out a picture that isn't from this project's plan.")
389
+ continue
390
+ }
391
+ try {
392
+ mkdirSync(media, { recursive: true })
393
+ const tag = `found-${sha256(id).slice(0, 16)}`
394
+ const seconds = Math.min(16, Math.ceil((last.end - first.start) / FLICKS) + 2)
395
+ const clipName = `${tag}-${shape.width}x${shape.height}-${seconds}s.mp4`
396
+ const note = `${item.title} by ${item.creator}, ${item.licence}, ${item.page}`
397
+ let known = state.log.current.assets.find((a) => a.path.endsWith(item.kind === "video" ? tag : clipName) || a.path.includes(`${tag}.`))
398
+ if (!known) {
399
+ const { file } = await downloadMedia(item.url, join(media, tag), { signal })
400
+ let path = file
401
+ if (item.kind === "image") {
402
+ path = join(media, clipName)
403
+ await runTool("ffmpeg", stillClipArgs({ image: file, output: path, width: shape.width, height: shape.height, seconds, inward: pictures.length % 2 === 0 }), { signal, timeoutMs: 180_000 })
404
+ }
405
+ known = await this.addAsset(state, path, { rights: item.rights, rightsNote: note })
406
+ }
407
+ pictures.push({ asset: known.id, from, to })
408
+ } catch (error) {
409
+ if (signal?.aborted) throw error
410
+ say(`Left out the picture "${item.title}": ${error.message}`)
411
+ }
412
+ }
413
+ const terms = (brief.terms ?? []).flatMap(({ at, id }) => {
414
+ const d = found.definitions[id]
415
+ return d && words.has(at) ? [{ at, term: d.term, quote: d.quote, source: d.source, page: d.page }] : []
416
+ })
417
+ return { pictures, terms }
418
+ },
419
+
420
+ /** The Director's plan for the whole cut: proposed, never made until the person approves it. */
421
+ async plan(state, { text, history = [], previous = null, choices = {}, job = 0, signal } = {}) {
422
+ // The references in use, each only for what the person took it for; with none named, every reference, whole
423
+ const named = cleanRefs(choices.references)
424
+ const chosen = named.length ? named : state.log.current.assets.filter((a) => a.kind === "reference").map((a) => ({ id: a.id, aspect: "all" }))
425
+ const references = []
426
+ for (const { id, aspect } of chosen) {
427
+ const ref = state.log.current.assets.find((a) => a.id === id && a.kind === "reference")
428
+ const found = ref && (await this.referenceAnalysis(state, ref.id, { signal }).catch(() => null))
429
+ if (!found) continue
430
+ const taken = takeFrom(found, aspect)
431
+ const name = `${ref.path.split(/[\\/]/).at(-1)}${aspect === "all" ? "" : ` (only for: ${ASPECTS[aspect]})`}`
432
+ references.push({ name, lines: taken.lines.length ? taken.lines : [`nothing measured for ${ASPECTS[aspect].toLowerCase()}`] })
433
+ }
434
+ const { visuals, playbooks, mediaSearch } = await this.features()
435
+ const device = mediaSearch ? readDevice() : null
436
+ // What was found is kept here, so an approval names an id and never carries a URL or a licence from the browser
437
+ const lookups = device ? { search: (queries) => searchMedia(device, queries), define: (terms) => defineTerms(device, terms), keep: (found) => this.keepFound(state, found) } : null
438
+ const plan = await planCut({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, history, previous, references, choices, visuals: visuals && !state.engine.motion().missing, playbooks, lookups, signal })
439
+ const scenes = plan.settings.scenes ?? []
440
+ // The exact brief an approval makes, so the Studio sends back what was shown
441
+ return {
442
+ ...plan,
443
+ brief: briefOf(plan.settings),
444
+ // What the card may swap each scene to; code says, so it can't offer what won't draw
445
+ ...(scenes.length ? { sceneChoices: { kinds: Object.fromEntries(Object.entries(SCENE_KINDS).map(([id, kind]) => [id, kind.label])), themes: Object.fromEntries(Object.entries(SCENE_THEMES).map(([id, theme]) => [id, theme.label])), swaps: scenes.map(swapsFor) } } : {}),
446
+ }
447
+ },
448
+
449
+ /** A reference's classified analysis (reference.js), kept by its fingerprint so it's measured once. */
450
+ async referenceAnalysis(state, assetId, { signal } = {}) {
451
+ const asset = state.log.current.assets.find((a) => a.id === assetId && a.kind === "reference")
452
+ if (!asset) throw new EngineFailure("input", "unknown_asset", "There is no such reference in this project.")
453
+ const dir = join(dirOf(state.id), "cache", "refs")
454
+ // .2: a video's soundtrack is measured too, and each line is kept under its aspect
455
+ const file = join(dir, `${asset.fingerprint}.2.json`)
456
+ if (existsSync(file)) return JSON.parse(readFileSync(file, "utf8"))
457
+ const found = await analyseReference(sourcesOf(state)(assetId), asset.facts, { signal })
458
+ mkdirSync(dir, { recursive: true })
459
+ atomicWrite(file, JSON.stringify(found))
460
+ return found
461
+ },
462
+
279
463
  /** The person's fix of a misheard word; captions, the transcript and the Director read it from now on. */
280
464
  correctWord(state, word, text) {
281
465
  const clean = cleanWord(text)
@@ -296,45 +480,144 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
296
480
  const asset = request.asset ?? video[0]?.id
297
481
  if (!asset || !video.some((a) => a.id === asset)) throw new EngineFailure("input", "no_take", "Add a video first.")
298
482
  if (!state.index.words.some((w) => w.asset === asset)) await this.indexAsset(state, asset, { signal })
299
- // The song's beats, so the music can be fitted on its downbeats
300
- const song = request.brief?.music && state.log.current.assets.find((a) => a.id === request.brief.music && a.kind === "audio")
301
- if (song && !state.index.beats?.some((b) => b.asset === song.id)) await this.indexAsset(state, song.id, { signal })
302
- // A real choice goes to the person before the story is planned (TAVI_INTEGRATION §5)
303
- const picks = !replay && beforeStory ? await beforeStory(state, asset, { signal, sourcePath: sourcesOf(state) }) : null
304
- // The person's confirmed rules, under anything the brief says, and their choices. A
305
- // replay uses what the job really used. Captions only where they can render
306
- const recorded = replay?.answers.find((a) => a.task === "brief_extra")
307
- const extra = recorded ? JSON.parse(recorded.value) : { ...taste.defaults(), ...(picks && { picks }) }
308
- // A style reference (EDD-23): measured to numbers only, never placed on a track. Its
309
- // pace sets how often the picture changes (punch-ins), and its captions turn ours on
483
+ // References, classified (reference.js), numbers only and never placed on a track
484
+ // (EDD-23): a video's pace and captions, an image's or video's colour, music's tempo and mood
310
485
  const styled = []
311
486
  let captionsFromReference = false
312
- const reference = request.brief?.reference && state.log.current.assets.find((a) => a.id === request.brief.reference && a.kind === "reference")
313
- if (reference && !replay) {
487
+ const fromRefs = {}
488
+ // Each reference gives only what the person took it for (editing, sound, colour, graphics, or
489
+ // all); one taken for an aspect goes first, so it wins that aspect over one taken for everything
490
+ const refs = cleanRefs([request.brief?.reference, ...(request.brief?.references ?? [])].filter(Boolean)).sort((a, b) => (a.aspect === "all") - (b.aspect === "all"))
491
+ const aspectOf = new Map()
492
+ for (const { id, aspect } of replay ? [] : refs) {
493
+ const ref = state.log.current.assets.find((a) => a.id === id && a.kind === "reference")
494
+ if (!ref) continue
495
+ const name = ref.path.split(/[\\/]/).at(-1)
314
496
  try {
315
- const dna = await extractDna(sourcesOf(state)(reference.id), { signal })
497
+ const found = takeFrom(await this.referenceAnalysis(state, id, { signal }), aspect)
498
+ if (aspect !== "all" && !found.lines.length) styled.push(`${name} has nothing Kriya can measure for ${ASPECTS[aspect].toLowerCase()}, so it wasn't used.`)
316
499
  const seconds = (request.brief.targetDuration ?? REEL_TALKING_HEAD.target.default) / FLICKS
317
- if (dna.pace.median) {
318
- extra.punches = Math.min(8, Math.max(1, Math.round(seconds / dna.pace.median / 2)))
319
- styled.push(`Took the pace of your reference: its picture changes every ${dna.pace.median.toFixed(1)} s, so ${extra.punches} punch-ins`)
500
+ // The first reference to give an aspect sets it. One the person took for that aspect
501
+ // is their explicit choice, so it outranks the brief's own setting there; one taken
502
+ // for everything sits under the brief, as before
503
+ const claim = (key) => !aspectOf.has(key) && (aspectOf.set(key, aspect), true)
504
+ const explicit = aspect !== "all"
505
+ if (found.pace?.every && claim("pace")) {
506
+ const punches = Math.min(8, Math.max(1, Math.round(seconds / found.pace.every / 2)))
507
+ if (explicit) request = { ...request, brief: { ...request.brief, punches } }
508
+ else fromRefs.punches = punches
509
+ styled.push(`Took the pace of ${name}: its picture changes every ${found.pace.every.toFixed(1)} s, so ${punches} punch-ins`)
320
510
  }
321
- if (dna.captions.present && !request.brief.captions && !extra.captions && state.engine.motion()) {
322
- extra.captions = "clean"
511
+ if (found.captions && !request.brief.captions && !state.engine.motion().missing && claim("captions")) {
512
+ fromRefs.captions = "clean"
323
513
  captionsFromReference = true
324
- styled.push("Your reference has captions, so this cut has them too")
514
+ styled.push(`${name} has captions, so this cut has them too`)
515
+ }
516
+ // An image says the most about colour, so it wins over a video's taken the same way
517
+ const colourBy = aspectOf.get("colour")
518
+ const colourFree = explicit ? colourBy === undefined || (colourBy !== "all" && found.kind === "image" && fromRefs.colourKind !== "image") : !request.brief.grade && (colourBy === undefined || (colourBy === "all" && found.kind === "image" && fromRefs.colourKind !== "image"))
519
+ if (found.colour && colourFree) {
520
+ aspectOf.set("colour", aspect)
521
+ fromRefs.customGrade = found.colour.grade
522
+ fromRefs.colourKind = found.kind
523
+ if (explicit && request.brief.grade) request = { ...request, brief: { ...request.brief, grade: undefined } }
524
+ styled.push(`Took the colour of ${name}: ${found.colour.words.join(", ")}`)
525
+ }
526
+ // A song the person chose stays; a reference taken for its sound replaces a generated bed
527
+ const musicFree = explicit ? !request.brief.music || /^generated:/.test(request.brief.music) : !request.brief.music
528
+ if (found.music && musicFree && claim("music")) {
529
+ request = { ...request, brief: { ...request.brief, music: `generated:${found.music.mood}`, musicBpm: found.music.bpm ?? undefined } }
530
+ styled.push(`Music follows ${name}: ${/^[aeiou]/.test(found.music.mood) ? "an" : "a"} ${found.music.mood} bed${found.music.bpm ? ` at ${found.music.bpm} bpm` : ""}`)
325
531
  }
326
532
  } catch (error) {
327
533
  if (signal?.aborted) throw error
328
- styled.push(`Your reference couldn't be measured (${error.message}), so its style wasn't used.`)
534
+ styled.push(`${name} couldn't be measured (${error.message}), so its style wasn't used.`)
329
535
  }
330
536
  }
331
- if (extra.captions && (!Object.hasOwn(LOOKS, extra.captions) || !state.engine.motion())) delete extra.captions
537
+ // "generated:<mood>": a bed Kriya writes itself (music-bed.js), so a cut can have music with no file to find
538
+ const mood = /^generated:(\w+)$/.exec(request.brief?.music ?? "")?.[1]
539
+ if (mood && Object.hasOwn(MOODS, mood) && !replay) {
540
+ const seconds = Math.ceil((request.brief.targetDuration ?? REEL_TALKING_HEAD.target.default) / FLICKS) + 15
541
+ const media = join(state.folder, "media")
542
+ mkdirSync(media, { recursive: true })
543
+ const bpm = request.brief.musicBpm
544
+ const tag = `kriya-music-${mood}${bpm ? `-${bpm}bpm` : ""}-${seconds}s.wav`
545
+ const file = join(media, tag)
546
+ const known = state.log.current.assets.find((a) => a.kind === "audio" && a.path.endsWith(tag))
547
+ if (!existsSync(file)) writeMusicBed(file, { mood, seconds, bpm })
548
+ const bed = known ?? (await this.addAsset(state, file, { rights: "own", rightsNote: "Made by Kriya's music generator: no one else's recording." }))
549
+ request = { ...request, brief: { ...request.brief, music: bed.id } }
550
+ }
551
+ // The pictures the person approved, downloaded now and not before, and their definitions as found
552
+ if (request.brief?.pictures?.length || request.brief?.terms?.length) {
553
+ const resolved = replay ? { pictures: [], terms: [] } : await this.resolveFound(state, request.brief, { signal, say: (line) => styled.push(line) })
554
+ request = { ...request, brief: { ...request.brief, ...resolved } }
555
+ }
556
+ // Scenes are drawn by the motion layer: without it they go, with a note, rather than fail the cut
557
+ if ((request.brief?.scenes?.length || request.brief?.terms?.length) && state.engine.motion().missing) {
558
+ request = { ...request, brief: { ...request.brief, scenes: undefined, terms: undefined } }
559
+ styled.push(`No animated scenes or definitions this time: ${state.engine.motion().missing}`)
560
+ }
561
+ // Sound design Kriya writes itself (sfx.js): a cut sound and an intro sound, each knowing its peak;
562
+ // a whoosh as a scene arrives and a pop as each of its labels lands
563
+ const sceneSound = (request.brief?.scenes?.length || request.brief?.pictures?.length) && request.brief.sceneSound !== false
564
+ const wanted = { cut: request.brief?.cutSound, intro: request.brief?.introSound, scene: sceneSound ? "whoosh" : undefined, reveal: sceneSound ? "pop" : undefined }
565
+ if (!replay && (wanted.cut || wanted.intro || wanted.scene)) {
566
+ const media = join(state.folder, "media")
567
+ mkdirSync(media, { recursive: true })
568
+ const sfx = {}
569
+ for (const [slot, kind] of Object.entries(wanted)) {
570
+ if (!kind || !Object.hasOwn(SFX, kind)) continue
571
+ const file = join(media, `kriya-sfx-${kind}.wav`)
572
+ const made = writeSfx(file, kind)
573
+ const known = state.log.current.assets.find((a) => a.kind === "audio" && a.path.endsWith(`kriya-sfx-${kind}.wav`))
574
+ sfx[slot] = (known ?? (await this.addAsset(state, file, { rights: "own", rightsNote: "Made by Kriya's sound generator: no one else's recording.", extraFacts: { peak: made.peak } }))).id
575
+ }
576
+ request = { ...request, brief: { ...request.brief, sfx } }
577
+ }
578
+ // The song's beats, so the music can be fitted on its downbeats
579
+ const song = request.brief?.music && state.log.current.assets.find((a) => a.id === request.brief.music && a.kind === "audio")
580
+ if (song && !state.index.beats?.some((b) => b.asset === song.id)) await this.indexAsset(state, song.id, { signal })
581
+ // A real choice goes to the person before the story is planned (TAVI_INTEGRATION §5)
582
+ const picks = !replay && beforeStory ? await beforeStory(state, asset, { signal, sourcePath: sourcesOf(state) }) : null
583
+ // The person's confirmed rules, under anything the brief says, and their choices. A
584
+ // replay uses what the job really used. Captions only where they can render
585
+ const recorded = replay?.answers.find((a) => a.task === "brief_extra")
586
+ const extra = recorded ? JSON.parse(recorded.value) : { ...taste.defaults(), ...(picks && { picks }) }
587
+ const { colourKind: _kind, ...fromRefBrief } = fromRefs
588
+ Object.assign(extra, fromRefBrief)
589
+ // Captions only where they can render: a missing runtime or Chrome drops them with a note,
590
+ // rather than failing the whole cut at render (found in use: every render failed)
591
+ const motionMissing = state.engine.motion().missing
592
+ if (extra.captions && (!Object.hasOwn(LOOKS, extra.captions) || motionMissing)) delete extra.captions
593
+ if (motionMissing && request.brief?.captions) {
594
+ request = { ...request, brief: { ...request.brief, captions: undefined } }
595
+ styled.push(`No captions this time: ${motionMissing}`)
596
+ }
332
597
  if (!replay && Object.keys(extra).length) state.journal.answer({ job, task: "brief_extra", source: "person", value: extra })
333
598
  const usedRules = [...styled, ...(extra.captions && !request.brief?.captions && !captionsFromReference ? [`Used your rule: ${extra.captions} captions`] : []), ...(extra.zoom && !request.brief?.zoom ? [`Used your rule: ${extra.zoom.toFixed(2)}× zoom`] : [])]
334
599
  const stages = ["story", "check", "repair"]
335
600
  const run = runTool
336
601
  const work = join(dirOf(state.id), "cache", "gates")
337
602
  const sourcePath = sourcesOf(state)
603
+ // A podcast's cameras or a montage's song: their own recipes, with the same render and gates.
604
+ // Cameras that won't sync fall back to the reel, and it says so
605
+ let planner = null
606
+ let plannerRecipe = null
607
+ const direct = { ...extra, ...request.brief }
608
+ if (!replay && direct.multicam) {
609
+ const { master, angles } = direct.multicam
610
+ const facts = (id) => state.log.current.assets.find((a) => a.id === id)?.facts
611
+ if (facts(master)?.duration && angles.every((a) => facts(a.asset))) {
612
+ const analysis = await analyseMulticam({ master: { asset: master, file: sourcePath(master), duration: facts(master).duration }, angles: angles.map((a) => ({ ...a, file: sourcePath(a.asset) })) }, { signal })
613
+ if (angles.every((a) => analysis.sync[a.asset].confidence >= PODCAST_MULTICAM.syncFloor)) {
614
+ planner = () => planProgramme({ project: state.log.current, index: state.index, brief: direct, multicam: { master, angles, analysis } })
615
+ plannerRecipe = programmeRecipe
616
+ } else styled.push("The cameras' sound didn't match well enough to sync them, so this is cut from one camera.")
617
+ }
618
+ } else if (!replay && direct.montage && direct.music) {
619
+ planner = () => planMontage({ project: state.log.current, index: state.index, brief: direct })
620
+ }
338
621
  const runtime = activeRuntime(home)
339
622
  const ask = replay ? replayAsk(replay.answers) : this.askFor(state, job)
340
623
  const parent = state.log.head
@@ -348,6 +631,8 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
348
631
  render: (project, deliverable, abort) => state.engine.render({ quality: "master", deliverable, project, job, signal: abort }),
349
632
  sourcePath,
350
633
  signal,
634
+ planner,
635
+ plannerRecipe,
351
636
  onStage: (stage) => onStep(stages.indexOf(stage) + 1, stages.length + 1),
352
637
  gateKit: {
353
638
  tilePath: state.engine.tilePath,
@@ -371,14 +656,19 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
371
656
  const { ops, dropped } = state.log.head === result.head ? { ops: result.best.ops, dropped: [] } : rebase(state.log.current, result.best.ops, state.index)
372
657
  const landed = change(state, { ops, author: "agent" })
373
658
  if (!landed.ok) throw new EngineFailure("plan", "refused", landed.diagnostics[0].message)
374
- const changes = [...usedRules, ...ops.filter((op) => !["ripple_delete", "reframe"].includes(op.op)).map((op) => describe(op, state.index))]
659
+ // A caption per spoken line is one change to a person: said once, with the count
660
+ const captioned = ops.filter((op) => op.op === "caption_style" && op.words?.length)
661
+ const changes = [...usedRules, ...ops.filter((op) => !["ripple_delete", "reframe", "caption_style"].includes(op.op) || (op.op === "caption_style" && !op.words?.length)).map((op) => describe(op, state.index)), ...(captioned.length ? [`Captioned ${captioned.length} line${captioned.length === 1 ? "" : "s"} (${captioned[0].look})`] : [])]
375
662
  const { version } = await tools()
376
663
  const delivery = result.best.file
377
664
  ? await writeDelivery({ file: result.best.file, title: state.log.current.name, project: result.best.project, parent, plan: result.best.plan, sourcePath, tools: { engine: ENGINE_VERSION, ffmpeg: version, runtime: runtime?.version ?? null }, gates: gates?.gates ?? [], verdict: gates?.verdict ?? "not_checked", calls: state.journal.calls(job), changes, notes, repairs, beforeFrom: sourcePath(asset), run, work })
378
665
  : null
666
+ if (delivery?.credits) changes.push(`Credits for your description are in ${delivery.credits.split(/[\\/]/).at(-1)}`)
379
667
  return {
380
668
  verdict: gates?.verdict ?? "not_checked",
669
+ credits: delivery?.credits ?? null,
381
670
  file: result.best.file ?? null,
671
+ head: state.log.head, // the version this file shows, so the Studio can say when it's out of date
382
672
  receipt: delivery?.receipt ?? null,
383
673
  report: delivery?.report ?? null,
384
674
  planHash,
@@ -431,7 +721,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
431
721
  const { version } = await tools()
432
722
  const mentions = gates.gates.filter((g) => g.status === "not_checked" || (g.status === "failed" && g.severity === "note")).map((g) => g.id)
433
723
  const delivery = await writeDelivery({ file, title: project.name, project, parent, plan, sourcePath, tools: { engine: ENGINE_VERSION, ffmpeg: version, runtime: runtime?.version ?? null }, gates: gates.gates, verdict: gates.verdict, calls: state.journal.calls(job), changes: [], notes: mentions, repairs: [], beforeFrom: null, run, work })
434
- return { verdict: gates.verdict, file, receipt: delivery?.receipt ?? null, report: delivery?.report ?? null, planHash: sha256(canonical(plan)), gates: gates.gates, notes: mentions, applied, skipped }
724
+ return { verdict: gates.verdict, file, head: state.log.head, receipt: delivery?.receipt ?? null, report: delivery?.report ?? null, planHash: sha256(canonical(plan)), gates: gates.gates, notes: mentions, applied, skipped }
435
725
  },
436
726
 
437
727
  /** `kriya edit replay`: a make job again from its recording; it compares, and lands nothing. */