@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
@@ -2,46 +2,73 @@
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, rmSync, writeSync } from "node:fs"
5
+ import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, 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
+ import { apply } from "../core/ops.js"
9
10
  import { canonical, newProject, parseProject, serialize, sha256 } from "../core/project.js"
10
11
  import { createEngine, ENGINE_VERSION, guardPath } from "../engine/index.js"
11
- import { blockComposition, motionRuntime } from "../engine/motion.js"
12
+ import { blockComposition, customDocument, motionRuntime } from "../engine/motion.js"
13
+ import { confinement as osConfinement } from "../engine/confine.js"
14
+ import { CUSTOM_BLOCK, CUSTOM_VERSION, partsProblems } from "../engine/custom.js"
15
+ import { motionLength, nearestKit, writeMotion } from "../director/custom-motion.js"
16
+ import { gateCustomTile } from "../gates/tile.js"
12
17
  import { cleanScene, SCENE_BLOCK, SCENE_KINDS, SCENE_THEMES, SCENE_VERSION, swapsFor } from "../engine/scenes.js"
13
18
  import { parseCube } from "../engine/color.js"
14
19
  import { fingerprint } from "../engine/media.js"
15
20
  import { probe } from "../engine/probe.js"
16
21
  import { EngineFailure, runTool } from "../engine/tool.js"
17
22
  import { openJournal } from "../graph/journal.js"
18
- import { DEFAULT_RULES, solve } from "../core/solver.js"
23
+ import { DEFAULT_RULES, markPixels, solve } from "../core/solver.js"
19
24
  import { safeZoneFor, sceneFrame } from "../core/layout.js"
20
25
  import { revealWords } from "../director/beats.js"
21
26
  import { termId } from "../director/lookups.js"
22
27
  import { allowedMediaUrl, downloadMedia, MEDIA_TYPES, stillClipArgs } from "../engine/found-media.js"
28
+ import { measureLoudness } from "../engine/loudness.js"
29
+ import { planAssembly } from "../recipes/assembly.js"
23
30
  import { planMontage } from "../recipes/montage.js"
24
31
  import { analyseMulticam, PODCAST_MULTICAM } from "../recipes/multicam.js"
25
32
  import { planProgramme, programmeRecipe } from "../recipes/programme.js"
26
33
  import { defineTerms, fetchFeatures, searchMedia } from "../runtime/fetch.js"
27
34
  import { readDevice } from "../../store.js"
35
+ import { models } from "../../api.js"
36
+ import { measureDraft, timelineOf, viewerReport } from "../director/viewer.js"
37
+ import { sayWatch } from "../director/watch-fix.js"
38
+ import { planOpenings } from "../recipes/openings.js"
28
39
  import { createAsk } from "../director/ask.js"
29
40
  import { LOOKS } from "../engine/captions.js"
30
41
  import { cleanSelection, cleanWord, describe, noteWord, revise } from "../director/revise.js"
42
+ import { clipList, decideAssembly, isAssembly } from "../director/assembly.js"
43
+ import { cleanMentions, mentionsView } from "../director/mentions.js"
31
44
  import { openIndexDb } from "../index/db.js"
32
45
  import { makeReel, rebase } from "../loop/make.js"
46
+ import { liveFeed } from "./layers.js"
33
47
  import { runGates } from "../gates/index.js"
34
48
  import { FORMATS, REEL_TALKING_HEAD } from "../recipes/reel.js"
35
49
  import { compareRuns, replayAsk } from "../loop/replay.js"
36
50
  import { verifiedRecogniser, writeDelivery, writeHandoff } from "./deliver.js"
37
51
  import { createIndexer, layersFor } from "../index/index.js"
38
- import { activeRuntime } from "../runtime/setup.js"
52
+ import { activeRuntime, childEnv } from "../runtime/setup.js"
53
+ import { readWords, recogniser, speechArgs, transcribeArgs } from "../index/layers/words.js"
39
54
  import { editHome } from "./paths.js"
40
55
  import { createTaste } from "./taste.js"
41
56
  import { ASPECTS, analyseReference, cleanRefs, takeFrom } from "../engine/reference.js"
57
+ import { checkDna2, extractDna2, readDna2 } from "../engine/dna2.js"
58
+ import { referenceMatch } from "../engine/reference2.js"
59
+ import { applyStyleBrief, cleanOff, styleBrief } from "../core/style-brief.js"
60
+ import { SAFE_ZONES } from "../core/layout.js"
61
+ import { ALL_LOOKS } from "../engine/captions.js"
42
62
  import { briefOf, planCut } from "../director/plan.js"
43
- import { MOODS, writeMusicBed } from "../engine/music-bed.js"
44
- import { SFX, writeSfx } from "../engine/sfx.js"
63
+ import { editsSince, planDiff, storyFor } from "../director/continuity.js"
64
+ import { ALL_GRAPHIC_KINDS, cleanGraphic, GRAPHIC_ACCENTS, GRAPHIC_BLOCK, GRAPHIC_FONTS, GRAPHIC_KINDS, GRAPHIC_TONES, GRAPHIC_VERSION, graphicLength, REGIONS, STYLE_LABELS, STYLE_LABELS_2 } from "../engine/graphics.js"
65
+ import { ALL_MOODS, MOODS, writeAccent, writeMusicBed } from "../engine/music-bed.js"
66
+ import { SFX, SOUNDS, writeSfx } from "../engine/sfx.js"
67
+
68
+ // "start over", "from scratch": the one way a request after a make isn't a change to that cut
69
+ // "callout this", "circle it", "put an arrow on this": a drawn box asked to be marked (TP9)
70
+ const CALLOUT_ASKED = /\b(?:call ?out|circle|ring|highlight|arrow|point (?:at|to)|mark (?:this|it|that|here))\b/i
71
+ const STARTS_OVER = /\b(?:start (?:over|again|afresh)|from scratch|fresh (?:cut|edit|start)|brand[- ]new (?:cut|edit))\b/i
45
72
 
46
73
  function atomicWrite(file, text) {
47
74
  const part = `${file}.${process.pid}.tmp`
@@ -93,9 +120,43 @@ const askServer = async () => {
93
120
  const device = readDevice()
94
121
  return device ? fetchFeatures(device) : { visuals: false, playbooks: false, mediaSearch: false }
95
122
  }
123
+ // The tiers this person's plan lists, exactly as Kriya says (GET /models): never a guess, so a slot is
124
+ // only ever sent on one of them (EH-65). Signed out or unanswered: none, and nothing escalates
125
+ const askTiers = async () => {
126
+ const device = readDevice()
127
+ if (!device) return null
128
+ const answer = await models(device.url, device.token)
129
+ return Array.isArray(answer?.data) ? answer.data.map((m) => m?.id).filter((id) => typeof id === "string") : null
130
+ }
96
131
  const NOTHING_FOUND = { items: {}, definitions: {} }
97
132
 
98
- export function createProjects({ home, roots, scheduler, tools, governor = null, features = askServer }) {
133
+ /** Where the Plan Card shows a motion kit 2 graphic (EH-92): its region's box, as core/layout.js shapes it, on an empty frame. */
134
+ function regionPlacement(graphic, { width, height }) {
135
+ const region = REGIONS[graphic.kind]
136
+ if (!region) return null
137
+ if (region.region === "full" || region.region === "frame") return { x: 0, y: 0, w: width, h: height }
138
+ const margin = Math.round(Math.min(width, height) * 0.05)
139
+ const w = Math.floor((region.region === "corner" ? width : width - 2 * margin) * region.w)
140
+ const h = Math.floor(height * region.h)
141
+ if (region.region === "third") return { x: Math.round((width - w) / 2), y: height - h - Math.round(height * 0.12), w, h }
142
+ if (region.region === "corner") {
143
+ const corner = graphic.corner ?? "tr"
144
+ return { x: corner.endsWith("l") ? margin : width - w - margin, y: corner.startsWith("t") ? margin : height - h - margin, w, h }
145
+ }
146
+ const side = Math.min(w, h)
147
+ const p = graphic.point ?? { x: Math.round(width / 2), y: Math.round(height / 2) }
148
+ return { x: Math.min(Math.max(0, Math.round(p.x - side / 2)), width - side), y: Math.min(Math.max(0, Math.round(p.y - side / 2)), height - side), w: side, h: side }
149
+ }
150
+
151
+ /** TP9: the custom animations a project holds, by clip, so chat can place one again with no model call. */
152
+ function customBlocksOf(project) {
153
+ return project.sequences.flatMap((q) => q.clips).flatMap((clip) => {
154
+ const block = clip.effects.find((e) => e.type === "block" && e.blockId === CUSTOM_BLOCK && e.version === CUSTOM_VERSION)
155
+ return block && !partsProblems(block.variables).problems.length ? [{ clip: clip.id, ...(block.variables.name ? { name: block.variables.name } : {}), variables: block.variables }] : []
156
+ })
157
+ }
158
+
159
+ export function createProjects({ home, roots, scheduler, tools, governor = null, features = askServer, tiers = askTiers, confinement = osConfinement, gateTile = gateCustomTile }) {
99
160
  const base = editHome(home)
100
161
  let known = null
101
162
  const taste = createTaste({ home })
@@ -136,7 +197,8 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
136
197
  const folder = dirname(file)
137
198
  const journaled = openOrSetAside(join(dir, "journal.sqlite"), openJournal)
138
199
  const journal = journaled.value
139
- const engine = createEngine({ folder, roots: [...roots, folder], cache: join(dir, "cache"), exports: join(folder, "exports"), journal, toolVersion: version, capabilities, scheduler, motion: () => motionRuntime(activeRuntime(home)) })
200
+ // TP9: a custom animation is drawn only while Kriya says editing.customMotion is on and the OS confines Chrome
201
+ const engine = createEngine({ folder, roots: [...roots, folder], cache: join(dir, "cache"), exports: join(folder, "exports"), journal, toolVersion: version, capabilities, scheduler, motion: () => motionRuntime(activeRuntime(home)), customMotion: () => known?.value?.customMotion === true && !!confinement().kind })
140
202
  engine.load(log.current, index)
141
203
  const state = { id, file, folder, log, journal, engine, indexDb, index, proposals: new Map(), damaged: [...(opened.damaged ? ["index"] : []), ...(journaled.damaged ? ["journal"] : [])] }
142
204
  open.set(id, state)
@@ -274,10 +336,11 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
274
336
  },
275
337
 
276
338
  /** The Director for one job: the Governor's queue, the job's call budget, the journal's record. */
277
- askFor(state, job = 0) {
339
+ askFor(state, job = 0, { tiers: listed = null } = {}) {
278
340
  if (!governor) throw new EngineFailure("environment", "no_director", "This Host has no Director.")
279
341
  let left = JOB_CALLS
280
- const ask = createAsk({ governor, record: (row) => state.journal.call({ job, ...row }), budget: { take: () => left-- > 0 } })
342
+ // listed: the plan's tiers, only with editing.directorLoop on (TP8); absent, no slot escalates
343
+ const ask = createAsk({ governor, record: (row) => state.journal.call({ job, ...row }), budget: { take: () => left-- > 0 }, ...(listed ? { tiers: listed } : {}) })
281
344
  // Each slot's final answer, so the job can be replayed with no model call
282
345
  return async (slot) => {
283
346
  const answer = await ask(slot)
@@ -286,18 +349,111 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
286
349
  }
287
350
  },
288
351
 
352
+ /** Whether this computer can turn speech into text locally: the Media Runtime's recogniser and its weights (EB-11). */
353
+ canDictate: () => !recogniser(activeRuntime(home)).missing,
354
+
355
+ /**
356
+ * Hold to talk (TP4, ASSEMBLY_AND_INTENT §7.4): a few seconds of the person's microphone to text, by the local
357
+ * recogniser only; no audio leaves the computer. It waits for the recogniser's slot behind an index job (EH-75).
358
+ * @param {Buffer} audio what the Studio recorded
359
+ */
360
+ async dictate(state, audio, { signal } = {}) {
361
+ const engine = recogniser(activeRuntime(home))
362
+ if (engine.missing) throw new EngineFailure("environment", "no_recogniser", engine.missing)
363
+ const dir = join(dirOf(state.id), "cache", "dictation", randomBytes(6).toString("hex"))
364
+ mkdirSync(dir, { recursive: true })
365
+ const release = scheduler ? await scheduler.acquire(["gpu"], { signal }) : () => {}
366
+ try {
367
+ const input = join(dir, "said.media")
368
+ writeFileSync(input, audio)
369
+ const wav = join(dir, "said.wav")
370
+ await runTool("ffmpeg", speechArgs(input, wav), { signal, timeoutMs: 60_000 })
371
+ const env = { ...childEnv(), HF_HUB_OFFLINE: "1", HF_HUB_DISABLE_TELEMETRY: "1" }
372
+ const words = readWords(await runTool(engine.python, transcribeArgs(engine, wav, state.log.current.brief?.language ?? "en"), { signal, env, timeoutMs: 120_000 }))
373
+ return { text: words.map((w) => w.text).join(" ").replace(/[\u0000-\u001f<>]/g, " ").slice(0, 2000) }
374
+ } finally {
375
+ release()
376
+ rmSync(dir, { recursive: true, force: true })
377
+ }
378
+ },
379
+
289
380
  /** The console: words → a proposal, applied to a copy, nothing landing yet (UX_SPEC §4, §5). */
290
- async ask(state, { text, selection, history = [], job = 0 }) {
381
+ async ask(state, { text, selection, history = [], mentions, mark, job = 0 }) {
291
382
  const chosen = cleanSelection(selection, state.log.current, state.index)
292
- const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen, history })
383
+ const { motion, intent, craft, typeKit, customMotion } = await this.features()
384
+ // TP9: a drawn box and custom motion only with editing.customMotion on; off, the request is asked as it always was
385
+ const pointing = customMotion === true ? { customMotion: true, ...(mark ? { mark } : {}), customBlocks: customBlocksOf(state.log.current) } : {}
386
+ const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen, history, motion: motion && !state.engine.motion().missing, pointed: await this.pointed(state, mentions, text), intent, craft, ...(typeKit ? { typeKit } : {}), ...pointing })
387
+ // A custom animation the console asked for: written by its own slot, gated on its rendered tile, then proposed
388
+ let motionOf = null
389
+ if (result.custom?.length) {
390
+ const made = await this.customMotionOp(state, result.custom[0], { text, history, job })
391
+ if (made.op) {
392
+ const tried = apply(state.log.current, [...result.ops, made.op], { index: state.index, author: "agent" })
393
+ if (tried.applied) {
394
+ result.ops = [...result.ops, made.op]
395
+ result.changes = [...result.changes, describe(made.op, state.index)]
396
+ result.project = tried.project
397
+ motionOf = { op: result.ops.length - 1, ...(made.gates ? { gates: made.gates } : {}) }
398
+ } else result.say = `${result.say ? `${result.say} ` : ""}The custom animation couldn't go there: ${tried.diagnostics[0].message}.`.trim()
399
+ } else result.say = `${result.say ? `${result.say} ` : ""}${made.say}`.trim()
400
+ }
401
+ // TP4: what the change couldn't do, in the person's words; only with editing.intent on
402
+ const cannot = result.cannot?.length ? { cannot: result.cannot } : {}
293
403
  // A request about the whole video goes to the Director's make job; the Studio offers it
294
404
  const direct = result.direct ? { brief: { ...(result.direct.seconds ? { seconds: result.direct.seconds } : {}), ...(result.direct.captions ? { captions: result.direct.captions } : {}) } } : null
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.") }
405
+ if (!result.ops.length && !result.corrections.length) return { proposal: null, direct, say: result.say, source: result.source, reason: direct || result.say || cannot.cannot ? null : (result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way."), ...cannot }
296
406
  const id = randomBytes(6).toString("hex")
297
407
  state.proposals.set(id, { ops: result.ops, corrections: result.corrections, head: state.log.head })
298
408
  const { picture, duration } = solve(result.project ?? state.log.current, state.index)
299
409
  // Changes in one list, operations first, then corrections: "Only this" counts across both
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 } : {}) }
410
+ return { proposal: { id, ops: result.ops, changes: [...result.changes, ...result.corrections.map((c) => c.change)], timeline: result.ops.length ? { picture, duration } : null, ...(motionOf ? { motion: motionOf } : {}) }, direct, say: result.say, source: result.source, ...(result.reason ? { reason: result.reason } : {}), ...cannot }
411
+ },
412
+
413
+ /**
414
+ * MG2 (TP9): one custom animation for a proposal. A saved one is placed again with no model call; a new
415
+ * one is written on `balanced` only when Kriya lists it (EH-65), at most two calls, then its tile is
416
+ * rendered confined and must pass QG-08…11 before the person sees it. Refused, it says why and names
417
+ * the nearest kit graphic; it never loops and never falls back to unchecked code.
418
+ * @returns {Promise<{ op: object, gates?: object[] } | { say: string }>}
419
+ */
420
+ async customMotionOp(state, request, { text, history = [], job = 0 }) {
421
+ const project = state.log.current
422
+ const duration = motionLength(request.duration)
423
+ if (request.reuse !== undefined) {
424
+ const saved = customBlocksOf(project).find((b) => b.clip === request.reuse)
425
+ if (!saved) return { say: "That saved animation isn't in this project any more." }
426
+ return { op: { op: "add_motion", block: CUSTOM_BLOCK, version: CUSTOM_VERSION, variables: saved.variables, at: request.at, duration } }
427
+ }
428
+ const person = [...history.filter((h) => h.who === "you").map((h) => h.text), text].join("\n")
429
+ const words = state.index.words ?? []
430
+ const runtime = state.engine.motion()
431
+ const which = confinement()
432
+ const nearestSay = (why, nearest) => `${why} The nearest the kit has is a ${nearest.label.toLowerCase()}: ask for one if it would do.`
433
+ if (runtime.missing) return { say: nearestSay("A custom animation needs the Media Runtime's Chrome to be checked before you see it.", nearestKit(person)) }
434
+ const canvas = { width: project.canvas.width, height: project.canvas.height }
435
+ const made = await writeMotion({ ask: this.askFor(state, job), tiers: await this.allowedTiers(), allowed: (await this.features()).customMotion === true, which, person, describe: request.text, spoken: words.map((w) => w.text).join(" "), canvas, duration })
436
+ if (!made.node) return { say: nearestSay(`I couldn't make that custom animation: ${made.reason.replace(/\.$/, "")}.`, made.nearest) }
437
+ const fps = project.canvas.fps
438
+ const zone = safeZoneFor(project)
439
+ const work = join(dirOf(state.id), "cache", "custom", randomBytes(6).toString("hex"))
440
+ try {
441
+ const gated = await gateTile({ node: made.node, output: { ...canvas, fps }, canvas, safe: { top: zone.top ?? 0, right: zone.right ?? 0, bottom: zone.bottom ?? 0, left: zone.left ?? 0 }, runtime, work, which, binDir: join(base, "bin") })
442
+ const failed = gated.results.find((r) => r.status === "failed")
443
+ if (failed) return { say: nearestSay(`I wrote a custom animation, but its check failed (${failed.id}: ${failed.failures[0]?.kind?.replaceAll("_", " ") ?? "failed"}), so it isn't offered.`, made.nearest) }
444
+ return { op: { op: "add_motion", block: CUSTOM_BLOCK, version: CUSTOM_VERSION, variables: made.node.variables, at: request.at, duration }, gates: gated.results.map(({ id, status }) => ({ id, status })).sort((a, b) => (a.id < b.id ? -1 : 1)) }
445
+ } finally {
446
+ rmSync(work, { recursive: true, force: true })
447
+ }
448
+ },
449
+
450
+ /** A proposal's custom animation as the render will draw it, for its sandboxed preview. @returns {string} a document */
451
+ customPreview(state, proposalId, n) {
452
+ const op = state.proposals.get(proposalId)?.ops?.[n]
453
+ if (!op || op.op !== "add_motion" || op.block !== CUSTOM_BLOCK) throw new EngineFailure("input", "no_preview", "That proposal has no custom animation to show.")
454
+ const canvas = { width: state.log.current.canvas.width, height: state.log.current.canvas.height }
455
+ const html = customDocument({ blockId: CUSTOM_BLOCK, version: CUSTOM_VERSION, variables: op.variables, duration: op.duration }, { output: canvas, canvas }, { allowed: true, which: confinement() })
456
+ return html.replace("html,body{margin:0;background:transparent", "html,body{margin:0;background:linear-gradient(160deg,#6b7b80,#2a3437)")
301
457
  },
302
458
 
303
459
  /** Accept all, accept some, or reject a proposal. Rebased onto HEAD; the person's own edits never move. */
@@ -319,10 +475,48 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
319
475
  return { applied: ops.length + fixes.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
320
476
  },
321
477
 
478
+ /**
479
+ * The clips a message points at, as the Director reads them (mentions.js). With
480
+ * editing.assembly off no mention resolves: the message is asked as it always was.
481
+ * @returns {Promise<string>} empty when there are none
482
+ */
483
+ async pointed(state, mentions, text) {
484
+ if (mentions === undefined || !(await this.features()).assembly) return ""
485
+ const clean = cleanMentions(state.log.current, mentions, text)
486
+ if (!clean) throw new EngineFailure("input", "bad_mention", "That message points at a clip that isn't in this project. Pick the clip again.")
487
+ return mentionsView(state.log.current, clean)
488
+ },
489
+
322
490
  /** What this Kriya allows now. A failed question means off. */
323
491
  async features() {
324
492
  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
493
+ // A server from before editing.motion, editing.assembly or editing.livePreview says nothing of it: off
494
+ return { motion: false, customMotion: false, assembly: false, livePreview: false, intent: false, craft: false, typeKit: false, referenceIntent: false, directorLoop: false, taviOrder: false, ...known.value }
495
+ },
496
+
497
+ /** The tiers Kriya lists for this person now, or null when it can't say: then nothing escalates. */
498
+ async allowedTiers() {
499
+ try {
500
+ return await tiers()
501
+ } catch {
502
+ return null
503
+ }
504
+ },
505
+
506
+ /** One motion graphic as the render will draw it, for the Plan Card. @returns {string} a complete document */
507
+ graphicPreview(state, raw, format, { typeKit = false, drawn = false } = {}) {
508
+ // EH-92: motion kit 2 with editing.typeKit on; TP9: a callout round a drawn box with editing.customMotion on. Else MG1's kinds
509
+ const graphic = cleanGraphic(raw, typeKit || (drawn && raw?.kind === "callout" && raw?.mark) ? ALL_GRAPHIC_KINDS : undefined)
510
+ if (!graphic) throw new EngineFailure("input", "bad_graphic", "That isn't a graphic from this project's plan.")
511
+ const shape = FORMATS[format] ?? FORMATS["9:16"]
512
+ const canvas = { width: shape.width, height: shape.height }
513
+ if (graphic.mark) return blockComposition({ blockId: GRAPHIC_BLOCK, version: GRAPHIC_VERSION, variables: graphic, placement: markPixels(graphic.mark, canvas), duration: graphicLength(graphic) }, { output: canvas, canvas }).replace("html,body{margin:0;background:transparent", "html,body{margin:0;background:linear-gradient(160deg,#6b7b80,#2a3437)")
514
+ // Where a strap or a title usually lands; the make places each clear of the face and the captions
515
+ const low = graphic.kind === "lower" || graphic.kind === "end"
516
+ // EH-92: a motion kit 2 graphic in the place its region gives it (the make's solver places it clear of the face)
517
+ const placement = regionPlacement(graphic, canvas) ?? { x: Math.round(canvas.width * 0.1), y: Math.round(canvas.height * (low ? 0.66 : 0.42)), w: Math.floor((canvas.width * DEFAULT_RULES.boxWidth) / 100), h: Math.floor((canvas.height * DEFAULT_RULES.boxHeight) / 100) }
518
+ // A graphic sits over footage; the card shows it on a plain backdrop so a light or dark plate both read
519
+ return blockComposition({ blockId: GRAPHIC_BLOCK, version: GRAPHIC_VERSION, variables: graphic, placement, duration: graphicLength(graphic) }, { output: canvas, canvas }).replace("html,body{margin:0;background:transparent", "html,body{margin:0;background:linear-gradient(160deg,#6b7b80,#2a3437)")
326
520
  },
327
521
 
328
522
  /**
@@ -417,8 +611,31 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
417
611
  return { pictures, terms }
418
612
  },
419
613
 
614
+ /**
615
+ * The last make this cut still descends from: its brief, story, approved plan and the
616
+ * person's edits it carried (continuity.js). Null once that make is undone or none was run.
617
+ */
618
+ lastMake(state) {
619
+ try {
620
+ const last = JSON.parse(readFileSync(join(dirOf(state.id), "last-make.json"), "utf8"))
621
+ const since = editsSince(state.log, last.head)
622
+ return since ? { ...last, edits: [...(Array.isArray(last.carried) ? last.carried : []), ...since] } : null
623
+ } catch {
624
+ return null
625
+ }
626
+ },
627
+
628
+ /** The story a make of this brief keeps from the last one; null when it's chosen again. */
629
+ keptStory(state, brief) {
630
+ return brief.fresh ? null : storyFor(this.lastMake(state), brief)
631
+ },
632
+
420
633
  /** 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 } = {}) {
634
+ async plan(state, { text, history = [], previous = null, choices = {}, mentions, mark, job = 0, signal } = {}) {
635
+ // With a cut already made, a request changes that cut: the plan it was made from is the one revised
636
+ const fresh = STARTS_OVER.test(text)
637
+ const last = fresh ? null : this.lastMake(state)
638
+ previous ??= last?.plan ?? null
422
639
  // The references in use, each only for what the person took it for; with none named, every reference, whole
423
640
  const named = cleanRefs(choices.references)
424
641
  const chosen = named.length ? named : state.log.current.assets.filter((a) => a.kind === "reference").map((a) => ({ id: a.id, aspect: "all" }))
@@ -429,23 +646,72 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
429
646
  if (!found) continue
430
647
  const taken = takeFrom(found, aspect)
431
648
  const name = `${ref.path.split(/[\\/]/).at(-1)}${aspect === "all" ? "" : ` (only for: ${ASPECTS[aspect]})`}`
649
+ // TP6: a reference whose style was read gives the plan its brief's lines (code's own sentences over numbers),
650
+ // less what the person unticked. The same one call as before: no slot, no extra call (EH-64)
651
+ const style = aspect === "all" && (await this.features()).referenceIntent === true ? await this.styleBriefFor(state, id, choices.format) : null
652
+ if (style) {
653
+ const off = choices.styleBrief?.ref === id ? cleanOff(choices.styleBrief.off) : []
654
+ references.push({ name, lines: style.lines.filter((line) => line.state !== "cannot" && !off.includes(line.id)).map((line) => `${line.text}${line.why ? ` (${line.why})` : ""}`) })
655
+ continue
656
+ }
432
657
  references.push({ name, lines: taken.lines.length ? taken.lines : [`nothing measured for ${ASPECTS[aspect].toLowerCase()}`] })
433
658
  }
434
- const { visuals, playbooks, mediaSearch } = await this.features()
659
+ const { visuals, playbooks, mediaSearch, motion, assembly, intent, craft, typeKit } = await this.features()
435
660
  const device = mediaSearch ? readDevice() : null
436
661
  // What was found is kept here, so an approval names an id and never carries a URL or a licence from the browser
437
662
  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 })
663
+ const plan = await planCut({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, history, previous, references, choices, motion: motion && !state.engine.motion().missing, visuals: visuals && !state.engine.motion().missing, playbooks, lookups, pointed: await this.pointed(state, mentions, text), intent, craft, ...(typeKit ? { typeKit } : {}), signal })
664
+ // The film's order (TP2, ASSEMBLY_AND_INTENT §4, §5), only with editing.assembly on: this message's mentions and
665
+ // words, then the storyboard, then earlier messages, then the plan being revised, then the Director, then the
666
+ // default. The Director's slot is asked only when something is open
667
+ const ordered = assembly ? await this.order(state, { text, history, previous, mentions, job, signal, targetDuration: plan.settings.seconds ? Math.round(plan.settings.seconds * FLICKS) : undefined }) : null
668
+ if (ordered?.assembly) plan.settings.assembly = ordered.assembly
669
+ else delete plan.settings.assembly
670
+ // TP9: a box drawn on the frame with a request to mark it becomes a callout among the plan's graphics, placed by
671
+ // code where it was drawn, on the word under it; only with editing.customMotion and editing.motion on
672
+ if (mark && motion && (await this.features()).customMotion === true && CALLOUT_ASKED.test(text)) {
673
+ const word = noteWord(state.log.current, state.index, mark.at)
674
+ const graphic = word ? cleanGraphic({ kind: "callout", style: mark.kind, mark: { x: mark.x, y: mark.y, w: mark.w, h: mark.h }, at: word }, ALL_GRAPHIC_KINDS) : null
675
+ if (graphic) plan.settings.graphics = [...(plan.settings.graphics ?? []).filter((g) => !g.mark), graphic]
676
+ }
439
677
  const scenes = plan.settings.scenes ?? []
678
+ const brief = briefOf(plan.settings)
440
679
  // The exact brief an approval makes, so the Studio sends back what was shown
441
680
  return {
442
681
  ...plan,
443
- brief: briefOf(plan.settings),
682
+ // The Order section of the card: each part as the person knows it, and each decision that wasn't theirs
683
+ ...(ordered?.assembly ? { order: { source: ordered.source, lines: ordered.lines, parts: this.orderView(state, ordered.assembly) } } : ordered?.lines.length ? { order: { source: null, lines: ordered.lines, parts: [] } } : {}),
684
+ brief: { ...brief, ...(fresh ? { fresh: true } : {}) },
685
+ // Said by code from the two briefs, so the card shows what an approval changes in the cut that's there,
686
+ // and whether its story stays (the same test the make route applies, in the make's own units)
687
+ ...(last ? { revises: true, differs: last.plan ? planDiff(briefOf(last.plan.settings ?? {}), brief) : [], keepsStory: !!storyFor(last, { ...(brief.seconds ? { targetDuration: Math.round(brief.seconds * FLICKS) } : {}), ...(brief.cuts ? { cuts: brief.cuts.map((c) => ({ from: Math.round(c.from * FLICKS), to: Math.round(c.to * FLICKS) })) } : {}) }) } : {}),
688
+ // What the card may restyle each graphic to: labels only, the colours and fonts stay in code
689
+ // EH-92: with editing.typeKit on, the card knows motion kit 2's kinds and styles too
690
+ ...(plan.settings.graphics?.length ? { graphicChoices: { kinds: Object.fromEntries(Object.entries(typeKit ? ALL_GRAPHIC_KINDS : GRAPHIC_KINDS).map(([id, kind]) => [id, { label: kind.label, styles: kind.styles }])), styles: typeKit ? { ...STYLE_LABELS, ...STYLE_LABELS_2 } : STYLE_LABELS, accents: Object.keys(GRAPHIC_ACCENTS), tones: Object.keys(GRAPHIC_TONES), fonts: Object.keys(GRAPHIC_FONTS) } } : {}),
444
691
  // What the card may swap each scene to; code says, so it can't offer what won't draw
445
692
  ...(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
693
  }
447
694
  },
448
695
 
696
+ /** The film's order for a plan (director/assembly.js). The storyboard stored on the project is the Studio's own to read here. */
697
+ async order(state, { text, history = [], previous = null, mentions, job = 0, signal, targetDuration }) {
698
+ const project = state.log.current
699
+ const pointed = mentions === undefined ? [] : (cleanMentions(project, mentions, text) ?? [])
700
+ const storyboard = project.sequences.find((q) => q.id === project.active)?.assembly ?? null
701
+ return decideAssembly({ project, index: state.index, text, mentions: pointed, storyboard, history, previous: previous?.settings?.assembly ?? null, ask: this.askFor(state, job), targetDuration, signal })
702
+ },
703
+
704
+ /** An assembly's parts as the card shows them: number, label, stretch in seconds, use, who decided. Labels are data. */
705
+ orderView(state, assembly) {
706
+ const clips = clipList(state.log.current, state.index)
707
+ const words = new Map(state.index.words.map((w) => [w.id, w]))
708
+ const edge = (ref, side) => (ref === undefined ? null : typeof ref === "number" ? ref : (words.get(ref.word)?.[ref.edge ?? side] ?? null))
709
+ return assembly.parts.map((part) => {
710
+ const clip = clips.find((c) => c.asset === part.asset)
711
+ return { id: part.id, asset: part.asset, number: clip?.n ?? null, label: clip?.label || clip?.name || "", from: edge(part.from, "start"), to: edge(part.to, "end"), duration: clip?.duration ?? null, use: part.use, why: part.why ?? null, ...(part.at ? { at: part.at } : {}), ...(part.fit ? { fit: part.fit } : {}) }
712
+ })
713
+ },
714
+
449
715
  /** A reference's classified analysis (reference.js), kept by its fingerprint so it's measured once. */
450
716
  async referenceAnalysis(state, assetId, { signal } = {}) {
451
717
  const asset = state.log.current.assets.find((a) => a.id === assetId && a.kind === "reference")
@@ -460,6 +726,56 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
460
726
  return found
461
727
  },
462
728
 
729
+ /* TP6 (CRAFT_UPGRADE §4, EDD-65), behind editing.referenceIntent: Edit DNA 2 and the style brief */
730
+
731
+ /** Where a reference's Edit DNA 2 is kept: its own name, so an older analysis is never read as this shape (EH-73). */
732
+ dna2File(state, asset) {
733
+ return join(dirOf(state.id), "cache", "refs", `${asset.fingerprint}.dna2.json`)
734
+ },
735
+
736
+ /**
737
+ * A reference's measured Edit DNA 2, or null when it hasn't been measured. Never measures: a plan
738
+ * and a make only read what the measuring job kept (EH-73). A file that isn't this version's
739
+ * shape, or isn't numbers and fixed words, counts as not measured.
740
+ */
741
+ referenceDna(state, assetId) {
742
+ const asset = state.log.current.assets.find((a) => a.id === assetId && a.kind === "reference")
743
+ if (!asset) return null
744
+ const file = this.dna2File(state, asset)
745
+ return existsSync(file) ? readDna2(readFileSync(file, "utf8")) : null
746
+ },
747
+
748
+ /**
749
+ * Measures a reference's Edit DNA 2 and keeps it. Only ever a job's work: it has progress and a
750
+ * cancel, and anything without a job number is refused, so a plan or a make can't start it (EH-73).
751
+ */
752
+ async measureReference(state, assetId, { job, signal, onStep = () => {}, measure = extractDna2 } = {}) {
753
+ if (!Number.isInteger(job) || job <= 0) throw new EngineFailure("input", "refused", "A reference is measured as its own job, never inside a plan or a make.")
754
+ const asset = state.log.current.assets.find((a) => a.id === assetId && a.kind === "reference")
755
+ if (!asset) throw new EngineFailure("input", "unknown_asset", "There is no such reference in this project.")
756
+ if (!asset.facts.width || !asset.facts.duration) throw new EngineFailure("input", "refused", "Only a video reference has a style to read: an image gives its colour, music its tempo.")
757
+ const dna = checkDna2(await measure(sourcesOf(state)(assetId), { signal, onStep }))
758
+ const file = this.dna2File(state, asset)
759
+ mkdirSync(dirname(file), { recursive: true })
760
+ atomicWrite(file, JSON.stringify(dna))
761
+ return { asset: assetId, traits: Object.values(dna).filter((v) => v?.read === "yes").length }
762
+ },
763
+
764
+ /** What this server and computer can do with a reference, for a cut of this shape. */
765
+ async styleCan(state, format) {
766
+ const { motion, craft, typeKit } = await this.features()
767
+ const { width, height } = FORMATS[format] ?? state.log.current.canvas
768
+ const tall = height > width
769
+ const looks = typeKit ? ALL_LOOKS : LOOKS
770
+ return { looks, lookLabels: Object.fromEntries(Object.keys(looks).map((id) => [id, `${id.charAt(0).toUpperCase()}${id.slice(1)}`])), moods: craft ? ALL_MOODS : MOODS, motion: motion && !state.engine.motion().missing, craft, tall, ...(tall ? { safe: { top: SAFE_ZONES["reel-9x16"].top, bottom: SAFE_ZONES["reel-9x16"].bottom } } : {}) }
771
+ },
772
+
773
+ /** A measured reference's style brief, or null when it hasn't been measured yet. */
774
+ async styleBriefFor(state, assetId, format) {
775
+ const dna = this.referenceDna(state, assetId)
776
+ return dna ? styleBrief(dna, await this.styleCan(state, format)) : null
777
+ },
778
+
463
779
  /** The person's fix of a misheard word; captions, the transcript and the Director read it from now on. */
464
780
  correctWord(state, word, text) {
465
781
  const clean = cleanWord(text)
@@ -475,23 +791,57 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
475
791
  * A make job. With `replay`, the Director's slots are answered from that job's
476
792
  * recording (no model call), and nothing lands on the project (EDIT_LOOP §10).
477
793
  */
478
- async make(state, request, { job = 0, signal, onStep = () => {}, replay, beforeStory } = {}) {
794
+ async make(state, request, { job = 0, signal, onStep = () => {}, replay, beforeStory, onLive } = {}) {
479
795
  const video = state.log.current.assets.filter((a) => a.kind === "video")
480
- const asset = request.asset ?? video[0]?.id
796
+ // The film's order, only from this make's own brief (EH-63): never the storyboard stored on the project
797
+ const order = isAssembly(request.brief?.assembly?.parts) ? request.brief.assembly : null
798
+ const asset = request.asset ?? order?.parts.find((p) => ["story", "whole"].includes(p.use) && video.some((a) => a.id === p.asset))?.asset ?? video[0]?.id
481
799
  if (!asset || !video.some((a) => a.id === asset)) throw new EngineFailure("input", "no_take", "Add a video first.")
482
800
  if (!state.index.words.some((w) => w.asset === asset)) await this.indexAsset(state, asset, { signal })
801
+ // An assembly's files: each is where it was, or it is left out; one asked for by name ends the make for the person (§8)
802
+ const there = (id) => {
803
+ try {
804
+ return existsSync(sourcesOf(state)(id))
805
+ } catch {
806
+ return false
807
+ }
808
+ }
809
+ const offline = order ? [...new Set(order.parts.map((p) => p.asset))].filter((id) => !there(id)) : []
810
+ if (order && !replay) {
811
+ const numbers = clipList(state.log.current, state.index)
812
+ const asked = order.parts.filter((p) => offline.includes(p.asset) && (p.why === "person" || p.why === "storyboard"))
813
+ if (asked.length) return { verdict: "needs_you", notes: [`${[...new Set(asked.map((p) => `Clip ${numbers.find((c) => c.asset === p.asset)?.n ?? "?"}`))].join(" and ")} ${asked.length === 1 ? "is" : "are"} in the order you gave, and ${asked.length === 1 ? "its file isn't" : "their files aren't"} where ${asked.length === 1 ? "it was" : "they were"}. Put ${asked.length === 1 ? "it" : "them"} back, or take ${asked.length === 1 ? "it" : "them"} out of the storyboard, and make it again.`], calls: 0, stop: "needs_you", changes: [], dropped: [], attempts: [], gates: [] }
814
+ // Each part's file is read once, so its words and shots are there to cut by
815
+ for (const id of new Set(order.parts.map((p) => p.asset))) if (!offline.includes(id) && !state.index.words.some((w) => w.asset === id) && !state.index.shots.some((s) => s.asset === id)) await this.indexAsset(state, id, { signal })
816
+ }
483
817
  // References, classified (reference.js), numbers only and never placed on a track
484
818
  // (EDD-23): a video's pace and captions, an image's or video's colour, music's tempo and mood
485
819
  const styled = []
820
+ // TP7: the type kit this make's own brief carries (the person's, or an approved plan's), stored as theirs;
821
+ // a brief without one leaves the project's look alone (EH-69, audit §6 rule 4)
822
+ const kit = request.brief?.typeKit
823
+ if (kit && JSON.stringify(state.log.current.look.brand?.type ?? null) !== JSON.stringify(kit)) {
824
+ const stored = change(state, { ops: [{ op: "set_type_kit", ...kit }], author: "person" })
825
+ if (!stored.ok) styled.push(`The type kit wasn't used: ${stored.diagnostics[0]?.message ?? "it doesn't fit this project"}.`)
826
+ }
827
+ styled.push(...(request.brief?.packNotes ?? []))
486
828
  let captionsFromReference = false
487
829
  const fromRefs = {}
488
830
  // Each reference gives only what the person took it for (editing, sound, colour, graphics, or
489
831
  // all); one taken for an aspect goes first, so it wins that aspect over one taken for everything
490
832
  const refs = cleanRefs([request.brief?.reference, ...(request.brief?.references ?? [])].filter(Boolean)).sort((a, b) => (a.aspect === "all") - (b.aspect === "all"))
491
833
  const aspectOf = new Map()
834
+ // TP6: the style brief this make's own brief carries (editing.referenceIntent; the Host drops the key without it).
835
+ // Read from what the measuring job kept, never measured here (EH-73); unmeasured, the reference works as it did
836
+ const styleOf = !replay && request.brief?.styleBrief ? { ...request.brief.styleBrief, dna: this.referenceDna(state, request.brief.styleBrief.ref) } : null
837
+ if (styleOf && !styleOf.dna) styled.push("That reference's style hasn't been read yet (Read its style, in References), so this cut took only what a quick look gives.")
838
+ // The key is the Host's own: no recipe, record or replay sees it
839
+ if (styleOf) request = { ...request, brief: (({ styleBrief: _brief, ...rest }) => rest)(request.brief) }
840
+ let fit = null
492
841
  for (const { id, aspect } of replay ? [] : refs) {
493
842
  const ref = state.log.current.assets.find((a) => a.id === id && a.kind === "reference")
494
843
  if (!ref) continue
844
+ if (styleOf?.dna && id === styleOf.ref) continue
495
845
  const name = ref.path.split(/[\\/]/).at(-1)
496
846
  try {
497
847
  const found = takeFrom(await this.referenceAnalysis(state, id, { signal }), aspect)
@@ -534,9 +884,37 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
534
884
  styled.push(`${name} couldn't be measured (${error.message}), so its style wasn't used.`)
535
885
  }
536
886
  }
887
+ if (styleOf?.dna) {
888
+ const seconds = (request.brief.targetDuration ?? REEL_TALKING_HEAD.target.default) / FLICKS
889
+ const style = styleBrief(styleOf.dna, await this.styleCan(state, request.brief.format))
890
+ const applied = applyStyleBrief(request.brief, style, styleOf.off, { seconds })
891
+ request = { ...request, brief: applied.brief }
892
+ styled.push(...applied.notes)
893
+ // Its colour, measured against this take and matched within limits: a LUT Kriya writes from two sets of numbers
894
+ const take = state.log.current.assets.find((a) => a.id === asset)
895
+ if (applied.colourMatch && (await tools()).capabilities.filters?.has("lut3d")) {
896
+ try {
897
+ const match = await referenceMatch(sourcesOf(state)(asset), (take.facts.duration ?? 0) / FLICKS, styleOf.dna.colour, { signal })
898
+ const media = join(state.folder, "media")
899
+ mkdirSync(media, { recursive: true })
900
+ const name = `kriya-look-${sha256(match.cube).slice(0, 12)}.cube`
901
+ const file = join(media, name)
902
+ if (!existsSync(file)) atomicWrite(file, match.cube)
903
+ const lut = state.log.current.assets.find((a) => a.kind === "lut" && a.path.endsWith(name)) ?? (await this.addAsset(state, file, { rights: "own", rightsNote: "A colour match Kriya computed from measurements: no one else's picture." }))
904
+ request = { ...request, brief: { ...request.brief, lut: lut.id } }
905
+ styled.push(`From your reference: its colour, matched to your footage by measurement${match.limited ? ". Your footage is further from it than a match may move, so it went part of the way" : ""}.`)
906
+ } catch (error) {
907
+ if (signal?.aborted) throw error
908
+ styled.push(`The reference's colour wasn't matched (${error.message}).`)
909
+ }
910
+ } else if (applied.colourMatch) styled.push("The reference's colour wasn't matched: this computer's FFmpeg has no lut3d.")
911
+ fit = { kept: applied.kept.map(({ id, text, target }) => ({ id, text, ...(target ? { target } : {}) })) }
912
+ }
537
913
  // "generated:<mood>": a bed Kriya writes itself (music-bed.js), so a cut can have music with no file to find
538
914
  const mood = /^generated:(\w+)$/.exec(request.brief?.music ?? "")?.[1]
539
- if (mood && Object.hasOwn(MOODS, mood) && !replay) {
915
+ // TP10: seven more moods and twenty sounds only with editing.craft on; off, the three moods and four sounds as before
916
+ const crafted = (await this.features()).craft === true
917
+ if (mood && Object.hasOwn(crafted ? ALL_MOODS : MOODS, mood) && !replay) {
540
918
  const seconds = Math.ceil((request.brief.targetDuration ?? REEL_TALKING_HEAD.target.default) / FLICKS) + 15
541
919
  const media = join(state.folder, "media")
542
920
  mkdirSync(media, { recursive: true })
@@ -547,7 +925,16 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
547
925
  if (!existsSync(file)) writeMusicBed(file, { mood, seconds, bpm })
548
926
  const bed = known ?? (await this.addAsset(state, file, { rights: "own", rightsNote: "Made by Kriya's music generator: no one else's recording." }))
549
927
  request = { ...request, brief: { ...request.brief, music: bed.id } }
550
- }
928
+ // An accent in the bed's own key for every join (TP10), written by code like the bed
929
+ if (crafted && request.brief.arrange) {
930
+ const name = `kriya-sfx-accent-${mood}.wav`
931
+ const accentFile = join(media, name)
932
+ const made = writeAccent(accentFile, mood, { fps: state.log.current.canvas.fps })
933
+ const had = state.log.current.assets.find((a) => a.kind === "audio" && a.path.endsWith(name))
934
+ const accent = had ?? (await this.addAsset(state, accentFile, { rights: "own", rightsNote: "Made by Kriya's sound generator: no one else's recording.", extraFacts: { peak: Math.round(made.peak * FLICKS) } }))
935
+ request = { ...request, brief: { ...request.brief, accent: accent.id } }
936
+ }
937
+ } else if (crafted && request.brief?.arrange && !replay) styled.push("No accents on the joins: they are written in the key of a bed Kriya makes, and this cut has none.")
551
938
  // The pictures the person approved, downloaded now and not before, and their definitions as found
552
939
  if (request.brief?.pictures?.length || request.brief?.terms?.length) {
553
940
  const resolved = replay ? { pictures: [], terms: [] } : await this.resolveFound(state, request.brief, { signal, say: (line) => styled.push(line) })
@@ -567,7 +954,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
567
954
  mkdirSync(media, { recursive: true })
568
955
  const sfx = {}
569
956
  for (const [slot, kind] of Object.entries(wanted)) {
570
- if (!kind || !Object.hasOwn(SFX, kind)) continue
957
+ if (!kind || !(crafted ? SOUNDS.includes(kind) : Object.hasOwn(SFX, kind))) continue
571
958
  const file = join(media, `kriya-sfx-${kind}.wav`)
572
959
  const made = writeSfx(file, kind)
573
960
  const known = state.log.current.assets.find((a) => a.kind === "audio" && a.path.endsWith(`kriya-sfx-${kind}.wav`))
@@ -618,16 +1005,44 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
618
1005
  } else if (!replay && direct.montage && direct.music) {
619
1006
  planner = () => planMontage({ project: state.log.current, index: state.index, brief: direct })
620
1007
  }
1008
+ // The assembly make (TP2): its own recipe, the same render and gates. A replay follows it too:
1009
+ // each part's story is answered from the recording, in the order it was asked
1010
+ if (order) {
1011
+ // shortcut: a file's speech is measured over the whole file, not only the stretch a part uses
1012
+ const loudness = {}
1013
+ for (const id of new Set(order.parts.filter((p) => ["story", "whole"].includes(p.use)).map((p) => p.asset))) {
1014
+ if (offline.includes(id) || state.log.current.assets.find((a) => a.id === id)?.facts.hasAudio === false) continue
1015
+ loudness[id] = (await measureLoudness(sourcePath(id), { run }).catch(() => ({ integrated: null }))).integrated
1016
+ }
1017
+ const { capabilities } = await tools()
1018
+ planner = () => planAssembly({ project: state.log.current, index: state.index, brief: direct, ask, signal, loudness, filters: capabilities.filters, offline })
1019
+ plannerRecipe = null
1020
+ }
621
1021
  const runtime = activeRuntime(home)
622
- const ask = replay ? replayAsk(replay.answers) : this.askFor(state, job)
1022
+ // TP8 (editing.directorLoop): escalation only to a tier the plan lists, the Director's watch-and-fix and B-roll by
1023
+ // meaning. Off, or a replay: the make as it was, with the same slots and calls (ET-DL-REG-01, EH-58)
1024
+ const directed = !replay && (await this.features()).directorLoop === true
1025
+ const ask = replay ? replayAsk(replay.answers) : this.askFor(state, job, directed ? { tiers: await this.allowedTiers() } : {})
1026
+ if (directed) stages.splice(2, 0, "watch")
1027
+ const genre = request.plan?.settings?.genre ?? null
1028
+ const watch = directed ? { view: async (attempt) => { const timeline = timelineOf(attempt.project, state.index); return { timeline, report: viewerReport({ timeline, measured: await measureDraft(attempt.file, { run, duration: attempt.plan.duration }), ...(genre ? { genre } : {}) }) } } } : null
623
1029
  const parent = state.log.head
1030
+ // The person's edits to the last cut go onto this one, unless they asked to start over
1031
+ const last = replay || request.brief?.fresh ? null : this.lastMake(state)
1032
+ // "Watch the Director edit" (editing.livePreview): the make's real state as previews, sent as it happens; never in history
1033
+ const watching = onLive && !replay && (await this.features()).livePreview === true
1034
+ const liveFonts = watching ? state.engine.motion().fonts : null
1035
+ const onLiveMake = watching ? liveFeed({ index: state.index, runtimeVersion: (await tools()).version, tiles: (state.previewTiles ??= new Map()), ...(liveFonts ? { fonts: [...liveFonts.keys()] } : {}), send: onLive }) : null
624
1036
  const result = await makeReel({
1037
+ ...(onLiveMake ? { onLive: onLiveMake } : {}),
1038
+ edits: last?.edits ?? [],
625
1039
  project: state.log.current,
626
1040
  head: state.log.head,
627
1041
  index: state.index,
628
1042
  asset,
629
- brief: { ...extra, ...request.brief },
1043
+ brief: { ...extra, ...request.brief, ...(directed && (extra.broll ?? request.brief?.broll) === "own" ? { brollByMeaning: true } : {}) },
630
1044
  ask,
1045
+ ...(watch ? { watch } : {}),
631
1046
  render: (project, deliverable, abort) => state.engine.render({ quality: "master", deliverable, project, job, signal: abort }),
632
1047
  sourcePath,
633
1048
  signal,
@@ -642,6 +1057,10 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
642
1057
  binDir: join(base, "bin"),
643
1058
  recognise: verifiedRecogniser(runtime, { run, work, language: state.log.current.brief?.language ?? "en" }),
644
1059
  ask,
1060
+ // QG-15 runs only on a make that followed an assembly (EH-70)
1061
+ ...(order ? { assembly: { ...order, left: order.parts.filter((p) => offline.includes(p.asset)).map((p) => p.id) } } : {}),
1062
+ // QG-16 runs only on a make that followed a reference's style brief (TP6)
1063
+ ...(fit ? { referenceFit: fit } : {}),
645
1064
  },
646
1065
  })
647
1066
  // Each attempt as ranked, for the report: never the model's words
@@ -651,14 +1070,23 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
651
1070
  const planHash = result.best.plan ? sha256(canonical(result.best.plan)) : null
652
1071
  const repairs = result.best.repairs ?? []
653
1072
  const person = result.best.person ?? []
654
- const notes = [...result.notes, ...person.map((p) => `${p.gate}: ${p.message} This is yours to decide.`)]
1073
+ const carried = result.best.carried ?? []
1074
+ const lost = result.best.dropped ?? []
1075
+ // What the Director's watch did: a kept fix as a change, a dropped one as a note with its reason
1076
+ const watched = result.best.watched ? sayWatch(result.best.watched.rounds) : []
1077
+ const notes = [...result.notes, ...watched.filter((line) => line.includes("kept the cut as it was")), ...(carried.length ? [`Kept ${carried.length} of your own edit${carried.length === 1 ? "" : "s"} to the last cut.`] : []), ...(lost.length ? [`${lost.length} of your edits no longer fit this cut and ${lost.length === 1 ? "was" : "were"} left out: ${lost.map((d) => describe(d.op, state.index)).join("; ")}.`] : []), ...person.map((p) => `${p.gate}: ${p.message} This is yours to decide.`), ...(gates?.gates.find((g) => g.id === "QG-16")?.message ? [gates.gates.find((g) => g.id === "QG-16").message] : [])]
655
1078
  if (replay) return { replayOf: replay.of, verdict: gates?.verdict ?? "not_checked", gates: gates?.gates ?? [], planHash, notes, repairs, calls: result.calls, stop: result.outcome.stop }
656
1079
  const { ops, dropped } = state.log.head === result.head ? { ops: result.best.ops, dropped: [] } : rebase(state.log.current, result.best.ops, state.index)
657
1080
  const landed = change(state, { ops, author: "agent" })
658
1081
  if (!landed.ok) throw new EngineFailure("plan", "refused", landed.diagnostics[0].message)
1082
+ // What the next change to this cut starts from
1083
+ atomicWrite(join(dirOf(state.id), "last-make.json"), JSON.stringify({ head: state.log.head, brief: request.brief ?? {}, story: result.best.story ?? null, carried, plan: request.plan ?? (request.brief?.fresh ? null : (last?.plan ?? null)) }))
659
1084
  // A caption per spoken line is one change to a person: said once, with the count
660
1085
  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})`] : [])]
1086
+ // A cutaway the Director's watch took out again isn't something this make did: only what is in the cut is listed
1087
+ const final = result.best.watched ? state.log.current.sequences.find((q) => q.id === state.log.current.active).clips : null
1088
+ const stays = (op) => op.op !== "place_broll" || !final || final.some((c) => c.source?.asset === op.asset && c.source.in === (op.in ?? 0) && JSON.stringify(c.at) === JSON.stringify(op.at))
1089
+ const changes = [...usedRules, ...watched.filter((line) => !line.includes("kept the cut as it was")), ...ops.filter((op) => stays(op) && (!["ripple_delete", "reframe", "caption_style", "apply_lut"].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})`] : [])]
662
1090
  const { version } = await tools()
663
1091
  const delivery = result.best.file
664
1092
  ? 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 })
@@ -680,10 +1108,47 @@ export function createProjects({ home, roots, scheduler, tools, governor = null,
680
1108
  slots: result.slots,
681
1109
  stop: result.outcome.stop,
682
1110
  attempts,
683
- dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })),
1111
+ dropped: [...dropped, ...lost].map((d) => ({ change: describe(d.op, state.index), reason: d.reason })),
1112
+ ...(result.best.watched ? { watch: { score: result.best.watched.score, rounds: result.best.watched.rounds.map(({ round, kept, was, score, reason, fixes }) => ({ round, kept, was: was ?? null, score: score ?? null, ...(reason ? { reason } : {}), fixes: fixes.map((f) => f.kind) })), left: result.best.watched.left.map((f) => f.kind) } } : {}),
684
1113
  }
685
1114
  },
686
1115
 
1116
+ /**
1117
+ * "Give me three openings" (TP8, editing.directorLoop): three low-fidelity drafts of the first eight seconds,
1118
+ * each opening on a different line, chosen by code. Nothing lands on the project: the person's pick becomes
1119
+ * the next make's hook. Each film is in the project's exports, named by what it shows.
1120
+ */
1121
+ async openings(state, request, { job = 0, signal, onStep = () => {} } = {}) {
1122
+ if ((await this.features()).directorLoop !== true) throw new EngineFailure("input", "refused", "Openings to choose from aren't switched on.")
1123
+ const video = state.log.current.assets.filter((a) => a.kind === "video")
1124
+ const asset = request.asset ?? video[0]?.id
1125
+ if (!asset || !video.some((a) => a.id === asset)) throw new EngineFailure("input", "no_take", "Add a video first.")
1126
+ if (!state.index.words.some((w) => w.asset === asset)) await this.indexAsset(state, asset, { signal })
1127
+ const planned = await planOpenings({ project: state.log.current, index: state.index, asset, brief: request.brief ?? {}, signal })
1128
+ if (!planned.length) throw new EngineFailure("input", "no_lines", "There aren't enough spoken lines in this take to open on.")
1129
+ const openings = []
1130
+ for (const [n, { hook, project }] of planned.entries()) {
1131
+ onStep(n, planned.length)
1132
+ const deliverable = project.deliverables.find((d) => d.preset === REEL_TALKING_HEAD.deliverable.preset) ?? project.deliverables[0]
1133
+ const { file, plan } = await state.engine.render({ quality: "draft", deliverable: deliverable.id, project, job, signal })
1134
+ openings.push({ n, hook: hook.id, words: hook.words, seconds: Math.round((plan.duration / FLICKS) * 10) / 10, file: file.split(/[\\/]/).at(-1) })
1135
+ }
1136
+ return { asset, openings }
1137
+ },
1138
+
1139
+ /** One opening's film, only by the job's own record and only from this project's exports: never a path the browser names. */
1140
+ openingFile(state, number, n) {
1141
+ const row = state.journal.job(number)
1142
+ if (row?.kind !== "openings" || row.status !== "done") return null
1143
+ let found = null
1144
+ try {
1145
+ found = JSON.parse(row.dispatch ?? "{}").openings?.[n]?.file ?? null
1146
+ } catch {}
1147
+ if (typeof found !== "string" || /[\\/]/.test(found)) return null
1148
+ const file = join(state.folder, "exports", found)
1149
+ return existsSync(file) ? file : null
1150
+ },
1151
+
687
1152
  /**
688
1153
  * A revision: each note or change, in the person's words, through the same validated
689
1154
  * console as the Studio (ES-20), then this cut rendered and gated. A note is pinned to