@kriya-ai/harness 0.2.5 → 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 (132) 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 +498 -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 +65 -6
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +169 -2
  44. package/src/edit/core/plan.js +65 -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/type-kit.js +173 -0
  51. package/src/edit/director/ask.js +37 -3
  52. package/src/edit/director/assembly.js +829 -0
  53. package/src/edit/director/continuity.js +9 -1
  54. package/src/edit/director/custom-motion.js +88 -0
  55. package/src/edit/director/graphics.js +44 -10
  56. package/src/edit/director/intent.js +125 -0
  57. package/src/edit/director/mentions.js +52 -0
  58. package/src/edit/director/plan.js +43 -11
  59. package/src/edit/director/revise.js +132 -9
  60. package/src/edit/director/viewer.js +136 -0
  61. package/src/edit/director/watch-fix.js +119 -0
  62. package/src/edit/engine/captions.js +110 -5
  63. package/src/edit/engine/confine.js +81 -4
  64. package/src/edit/engine/custom.js +243 -0
  65. package/src/edit/engine/dna2.js +893 -0
  66. package/src/edit/engine/fonts.js +218 -0
  67. package/src/edit/engine/graphics.js +271 -10
  68. package/src/edit/engine/index.js +14 -5
  69. package/src/edit/engine/motion.js +148 -13
  70. package/src/edit/engine/music-bed.js +59 -1
  71. package/src/edit/engine/packs.js +11 -0
  72. package/src/edit/engine/reference2.js +26 -0
  73. package/src/edit/engine/sfx.js +56 -1
  74. package/src/edit/engine/tool.js +21 -5
  75. package/src/edit/gates/assembly.js +194 -0
  76. package/src/edit/gates/copy.js +7 -4
  77. package/src/edit/gates/index.js +72 -7
  78. package/src/edit/gates/reference.js +115 -0
  79. package/src/edit/gates/tile.js +96 -0
  80. package/src/edit/host/client.js +4 -3
  81. package/src/edit/host/clips.js +33 -0
  82. package/src/edit/host/jobs.js +9 -3
  83. package/src/edit/host/layers.js +134 -0
  84. package/src/edit/host/main.js +10 -3
  85. package/src/edit/host/paths.js +21 -3
  86. package/src/edit/host/preview.js +108 -0
  87. package/src/edit/host/projects.js +443 -34
  88. package/src/edit/host/server.js +235 -20
  89. package/src/edit/host/tavi.js +77 -0
  90. package/src/edit/loop/make.js +28 -3
  91. package/src/edit/recipes/assembly.js +352 -0
  92. package/src/edit/recipes/graphic-clips.js +4 -2
  93. package/src/edit/recipes/openings.js +36 -0
  94. package/src/edit/recipes/reel.js +104 -14
  95. package/src/edit/recipes/reference-look.js +29 -0
  96. package/src/edit/recipes/short-from-long.js +3 -3
  97. package/src/edit/recipes/sound.js +71 -0
  98. package/src/edit/runtime/cli.js +26 -5
  99. package/src/edit/runtime/fetch.js +4 -4
  100. package/src/edit/runtime/licences.js +7 -1
  101. package/src/explore.js +103 -0
  102. package/src/failure.js +1 -1
  103. package/src/gate-commands.js +114 -0
  104. package/src/gates/api.js +127 -0
  105. package/src/gates/commands.js +111 -0
  106. package/src/gates/detectors.js +370 -0
  107. package/src/gates/http.js +62 -0
  108. package/src/gates/index.js +196 -0
  109. package/src/gates/page.js +264 -0
  110. package/src/gates/sast.js +64 -0
  111. package/src/gates/stack.js +110 -0
  112. package/src/gates/tenant.js +162 -0
  113. package/src/gates/three.js +407 -0
  114. package/src/gates/ui.js +111 -0
  115. package/src/launch.js +15 -3
  116. package/src/loop.js +199 -7
  117. package/src/mcp.js +126 -0
  118. package/src/milestones.js +188 -0
  119. package/src/modes.js +32 -0
  120. package/src/orchestra.js +43 -0
  121. package/src/outcomes.js +88 -0
  122. package/src/profiles.js +5 -0
  123. package/src/receipts.js +238 -0
  124. package/src/release.js +356 -0
  125. package/src/runstrip.js +122 -0
  126. package/src/stack.js +120 -0
  127. package/src/verify.js +67 -20
  128. package/studio/dist/fonts/fraunces.woff2 +0 -0
  129. package/studio/dist/fonts/geist.woff2 +0 -0
  130. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  131. package/studio/dist/studio.css +449 -1
  132. package/studio/dist/studio.js +3 -3
@@ -2,23 +2,37 @@
2
2
  // every request, and an owner-only socket with the same routes. Typed requests only:
3
3
  // no route runs a command, and every path passes guardPath.
4
4
 
5
- import { createHash, createHmac, randomBytes } from "node:crypto"
5
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"
6
6
  import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs"
7
7
  import { basename, dirname, extname, isAbsolute, join } from "node:path"
8
8
  import { pipeline } from "node:stream/promises"
9
9
 
10
+ import { apply, CRAFT_OP_NAMES, TYPE_OP_NAMES } from "../core/ops.js"
10
11
  import { compile } from "../core/plan.js"
12
+ import { clipNumbers } from "../core/project.js"
11
13
  import { solve } from "../core/solver.js"
12
- import { LOOKS } from "../engine/captions.js"
14
+ import { ALL_LOOKS, LOOKS, MORE_CAPTION_LOOKS } from "../engine/captions.js"
13
15
  import { ENGINE_VERSION, guardPath } from "../engine/index.js"
14
16
  import { cleanRefs } from "../engine/reference.js"
17
+ import { cleanOff } from "../core/style-brief.js"
15
18
  import { cleanScene } from "../engine/scenes.js"
16
- import { cleanGraphic } from "../engine/graphics.js"
19
+ import { ALL_GRAPHIC_KINDS, cleanGraphic, GRAPHIC_BLOCK, GRAPHIC_KINDS } from "../engine/graphics.js"
17
20
  import { TRANSITIONS } from "../core/transitions.js"
21
+ import { regionOf } from "../core/effects.js"
18
22
  import { EngineFailure } from "../engine/tool.js"
19
23
  import { activeRuntime } from "../runtime/setup.js"
20
24
  import { recogniser } from "../index/layers/words.js"
25
+ import { assemblyProblems, isAssembly } from "../director/assembly.js"
21
26
  import { FORMATS, GRADES } from "../recipes/reel.js"
27
+ import { previewOf, tileDocument } from "./preview.js"
28
+ import { lastMadeEntry, layersOf, viewOf } from "./layers.js"
29
+ import { projectAt } from "../core/history.js"
30
+ import { TOKEN_HEADER } from "./paths.js"
31
+ import { withFonts } from "../engine/fonts.js"
32
+ import { applyStylePack, STYLE_PACKS } from "../core/style-packs.js"
33
+ import { cleanTypeKit, PAIRS } from "../core/type-kit.js"
34
+ import { ALL_MOODS, MOODS } from "../engine/music-bed.js"
35
+ import { CUT_SOUNDS, INTRO_SOUNDS } from "../engine/sfx.js"
22
36
 
23
37
  const HEADERS = {
24
38
  "cross-origin-opener-policy": "same-origin",
@@ -31,7 +45,8 @@ const COOKIE = "kriya_edit"
31
45
  const MAX_BODY = 4 * 1024 * 1024
32
46
  // The Studio app, built by `npm run build:studio` (ED6)
33
47
  const STUDIO = join(import.meta.dirname, "..", "..", "..", "studio", "dist")
34
- const STUDIO_FILES = { "/": ["index.html", "text/html; charset=utf-8"], "/studio.js": ["studio.js", "text/javascript"], "/studio.css": ["studio.css", "text/css"] }
48
+ // The Studio's three type faces (OFL-1.1, the harness's own: THIRD_PARTY_NOTICES.md), from this origin, so its policy stays 'self'
49
+ const STUDIO_FILES = { "/": ["index.html", "text/html; charset=utf-8"], "/studio.js": ["studio.js", "text/javascript"], "/studio.css": ["studio.css", "text/css"], "/fonts/geist.woff2": ["fonts/geist.woff2", "font/woff2"], "/fonts/fraunces.woff2": ["fonts/fraunces.woff2", "font/woff2"], "/fonts/jetbrains-mono.woff2": ["fonts/jetbrains-mono.woff2", "font/woff2"] }
35
50
  const TYPES = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".m4a": "audio/mp4", ".wav": "audio/wav", ".mp3": "audio/mpeg", ".jpg": "image/jpeg", ".json": "application/json" }
36
51
 
37
52
  // An inline icon, so the browser doesn't ask for /favicon.ico (a 404 in the console)
@@ -59,6 +74,30 @@ const backOf = (value, port) => {
59
74
  }
60
75
  }
61
76
 
77
+ // TP9: the longest cut a drawn box can point into (a day, in flicks); the Host checks it against the cut itself
78
+ const MARK_AT_MAX = 24 * 3600 * 705_600_000
79
+ const MARK_KINDS = ["box", "ring", "arrow"]
80
+
81
+ /**
82
+ * A box, ring or arrow drawn on the monitor (TP9, CRAFT_UPGRADE §7): never trusted as sent. Whole thousandths
83
+ * of the frame, inside it, each side at least 10; `at` whole flicks on the cut. @returns {object | null | undefined}
84
+ * undefined: none sent; null: sent and refused
85
+ */
86
+ export function cleanMark(raw) {
87
+ if (raw === undefined || raw === null) return undefined
88
+ if (typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).some((key) => !["kind", "x", "y", "w", "h", "at"].includes(key))) return null
89
+ if (!MARK_KINDS.includes(raw.kind) || !Number.isSafeInteger(raw.at) || raw.at < 0 || raw.at > MARK_AT_MAX) return null
90
+ const box = regionOf({ x: raw.x, y: raw.y, w: raw.w, h: raw.h })
91
+ return box ? { kind: raw.kind, ...box, at: raw.at } : null
92
+ }
93
+
94
+ /** A secret compared in constant time; anything but one string of the same length is no. */
95
+ export function sameSecret(given, secret) {
96
+ if (typeof given !== "string" || typeof secret !== "string") return false
97
+ const [a, b] = [Buffer.from(given), Buffer.from(secret)]
98
+ return a.length === b.length && timingSafeEqual(a, b)
99
+ }
100
+
62
101
  function studioFile(res, pathname) {
63
102
  const [name, type] = STUDIO_FILES[pathname]
64
103
  const file = join(STUDIO, name)
@@ -80,7 +119,21 @@ function page(res, type, body) {
80
119
 
81
120
  const refuse = (res, status, message) => json(res, status, { error: status, message })
82
121
  /** A plan as the Studio sends it back (one being revised, or the one just approved): bounded text and a settings object the Director re-checks. */
83
- const cleanPlan = (plan) => (plan && typeof plan === "object" ? { say: String(plan.say ?? "").slice(0, 900), steps: Array.isArray(plan.steps) ? plan.steps.slice(0, 10).map((s) => String(s).slice(0, 240)) : [], settings: plan.settings && typeof plan.settings === "object" && !Array.isArray(plan.settings) && JSON.stringify(plan.settings).length <= 20_000 ? plan.settings : {} } : null)
122
+ // A plan's answered questions (TP4), so a revision doesn't ask again: up to 8 plain values, each checked again by readIntent
123
+ const cleanAnswers = (answers) => (answers && typeof answers === "object" && !Array.isArray(answers) ? Object.fromEntries(Object.entries(answers).filter(([key, value]) => /^[A-Za-z]{1,32}$/.test(key) && ["string", "number", "boolean"].includes(typeof value) && String(value).length <= 64).slice(0, 8)) : null)
124
+ const cleanPlan = (plan) => (plan && typeof plan === "object" ? { say: String(plan.say ?? "").slice(0, 900), steps: Array.isArray(plan.steps) ? plan.steps.slice(0, 10).map((s) => String(s).slice(0, 240)) : [], settings: plan.settings && typeof plan.settings === "object" && !Array.isArray(plan.settings) && JSON.stringify(plan.settings).length <= 20_000 ? plan.settings : {}, ...(cleanAnswers(plan.intent?.answers) ? { intent: { answers: cleanAnswers(plan.intent.answers) } } : {}) } : null)
125
+
126
+ /** A request's raw bytes, up to MAX_BODY. */
127
+ async function readBody(req) {
128
+ const chunks = []
129
+ let size = 0
130
+ for await (const chunk of req) {
131
+ size += chunk.length
132
+ if (size > MAX_BODY) throw new EngineFailure("input", "too_large", "That request is too large.")
133
+ chunks.push(chunk)
134
+ }
135
+ return Buffer.concat(chunks)
136
+ }
84
137
 
85
138
  async function readJson(req) {
86
139
  const chunks = []
@@ -126,7 +179,7 @@ const statusOf = (error) => ({ outside_project: 403, missing_file: 404, exists:
126
179
  */
127
180
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
128
181
 
129
- export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid, stamp = null, busy = () => 0 }) {
182
+ export function createHandler({ home, ipcToken = null, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid, stamp = null, busy = () => 0 }) {
130
183
  const tokens = new Map() // sha256 of a launch token → { expires, back }
131
184
  const sessions = new Set()
132
185
  const mediaSecret = randomBytes(32)
@@ -140,8 +193,23 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
140
193
 
141
194
  // offline: the file isn't where the project says, so the Studio asks to relink it (EG-3)
142
195
  const withMedia = (state, asset) => ({ ...asset, media: mediaId(state.id, asset.id), ...(existsSync(isAbsolute(asset.path) ? asset.path : join(state.folder, asset.path)) ? {} : { offline: true }) })
196
+ // TP1, only with editing.assembly on: each clip's computed number (never stored, EH-54) and the
197
+ // day its file was last written, for the bin's sort and groups. Off, the view is what it was
198
+ // shortcut: the file's own date stands in for "recorded" (a copied file gets the day it was copied); read the container's creation time when that matters
199
+ const withHandle = (state, numbers) => (asset) => {
200
+ const view = withMedia(state, asset)
201
+ if (!numbers.has(asset.id)) return view
202
+ const recorded = view.offline ? null : statSync(isAbsolute(asset.path) ? asset.path : join(state.folder, asset.path)).mtime.toISOString()
203
+ return { ...view, number: numbers.get(asset.id), ...(recorded ? { recorded } : {}) }
204
+ }
205
+ const assemblyOn = async () => (await projects.features()).assembly === true
206
+ const livePreviewOn = async () => (await projects.features()).livePreview === true
207
+ // Hold to talk (TP4): editing.intent on and the local recogniser's weights installed; otherwise no button and no route
208
+ const dictationOn = async () => (await projects.features()).intent === true && projects.canDictate()
143
209
  const NOTICES = { index: "This project's index was damaged and set aside. Index the footage again.", journal: "This project's job record was damaged and set aside. Finished renders will be made again." }
144
- const projectView = (state) => ({ project: state.log.current, head: state.log.head, assets: state.log.current.assets.map((asset) => withMedia(state, asset)), ...(state.damaged?.length ? { notices: state.damaged.map((part) => ({ kind: part === "index" ? "reindex" : "rerender", message: NOTICES[part] })) } : {}) })
210
+ // TP7: the type kit's choices, only with editing.typeKit on (labels only: fonts and colours stay in code), and whether this computer has the fonts
211
+ const typeKitView = async (state) => ((await projects.features()).typeKit === true ? { typeKit: { packs: Object.fromEntries(Object.entries(STYLE_PACKS).map(([id, pack]) => [id, { label: pack.label, does: pack.does }])), pairs: Object.fromEntries(Object.entries(PAIRS).map(([id, pair]) => [id, pair.label])), looks: Object.keys(MORE_CAPTION_LOOKS), shipped: (state.engine.motion().fonts?.size ?? 0) > 0, chosen: state.log.current.look.brand?.type ?? null } } : {})
212
+ const projectView = async (state) => ({ project: state.log.current, head: state.log.head, ...(await typeKitView(state)), ...((await livePreviewOn()) ? { livePreview: true } : {}), ...((await projects.features()).referenceIntent === true ? { referenceIntent: true } : {}), ...((await projects.features()).directorLoop === true ? { directorLoop: true } : {}), ...((await projects.features()).customMotion === true ? { customMotion: true } : {}), ...((await projects.features()).intent === true ? { intent: true, ...(projects.canDictate() ? { dictation: true } : {}) } : {}), ...((await assemblyOn()) ? { assembly: true, assets: state.log.current.assets.map(withHandle(state, clipNumbers(state.log.current))) } : { assets: state.log.current.assets.map((asset) => withMedia(state, asset)) }), ...(state.damaged?.length ? { notices: state.damaged.map((part) => ({ kind: part === "index" ? "reindex" : "rerender", message: NOTICES[part] })) } : {}) })
145
213
 
146
214
  // The Media Runtime, installed from the Studio with its progress shown (the same signed
147
215
  // manifest and checks as `kriya edit setup`): a first Index no longer looks like nothing happening
@@ -313,16 +381,25 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
313
381
  }
314
382
  const state = await needProject(res, parts[1])
315
383
  if (!state) return
316
- if (parts.length === 2 && method === "GET") return say(200, projectView(state))
384
+ if (parts.length === 2 && method === "GET") return say(200, await projectView(state))
317
385
  if (parts.length === 2 && method === "DELETE") return say(200, projects.remove(state.id, { running: (id) => jobs.runningIn(id) }))
318
386
  if (parts.length === 2 && method === "PATCH") {
319
387
  const { ops, undo } = await readJson(req)
320
388
  if (undo === true) {
321
389
  projects.undo(state)
322
- return say(200, { ...projectView(state), diagnostics: [] })
390
+ return say(200, { ...(await projectView(state)), diagnostics: [] })
391
+ }
392
+ // Labels and the storyboard are behind editing.assembly: off, the Host takes neither (ET-ASM-REG-01)
393
+ // Effects from the registry are behind editing.craft (TP5): off, the Host takes none
394
+ if (Array.isArray(ops) && ops.some((op) => CRAFT_OP_NAMES.includes(op?.op)) && (await projects.features()).craft !== true) return say(422, { ...(await projectView(state)), diagnostics: [{ code: "switched_off", message: "Effects aren't switched on.", op: 0 }] })
395
+ if (Array.isArray(ops) && ops.some((op) => ["describe_asset", "set_assembly", "place_over", "set_frame"].includes(op?.op)) && !(await assemblyOn())) return say(422, { ...(await projectView(state)), diagnostics: [{ code: "switched_off", message: "Clip labels and the storyboard aren't switched on.", op: 0 }] })
396
+ // The type kit, more caption looks and motion kit 2 are behind editing.typeKit (TP7): off, the Host takes none of them
397
+ if (Array.isArray(ops) && (await projects.features()).typeKit !== true) {
398
+ const typed = ops.findIndex((op) => TYPE_OP_NAMES.includes(op?.op) || (op?.op === "caption_style" && !Object.hasOwn(LOOKS, op.look ?? "") && Object.hasOwn(ALL_LOOKS, op.look ?? "")) || (op?.op === "add_motion" && op.block === GRAPHIC_BLOCK && (!Object.hasOwn(GRAPHIC_KINDS, op.variables?.kind ?? "") || !GRAPHIC_KINDS[op.variables.kind].styles.includes(op.variables?.style ?? GRAPHIC_KINDS[op.variables.kind].styles[0]))))
399
+ if (typed >= 0) return say(422, { ...(await projectView(state)), diagnostics: [{ code: "switched_off", message: "The type kit, the new caption looks and motion kit 2 aren't switched on.", op: typed }] })
323
400
  }
324
401
  const result = projects.change(state, { ops, author: "person" })
325
- return say(result.ok ? 200 : 422, { ...projectView(state), diagnostics: result.diagnostics })
402
+ return say(result.ok ? 200 : 422, { ...(await projectView(state)), diagnostics: result.diagnostics })
326
403
  }
327
404
  if (parts[2] === "assets" && method === "POST") {
328
405
  const { path } = await readJson(req)
@@ -343,18 +420,85 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
343
420
  const { picture, audio, overlays, captions, duration } = solve(state.log.current, state.index)
344
421
  return say(200, { ...compile(state.log.current, state.index, { engineVersion: ENGINE_VERSION, runtimeVersion: version }), timeline: { picture, audio, overlays, captions, duration } })
345
422
  }
423
+ // The live preview (TP3, editing.livePreview): what the monitor draws, from the draft's own plan;
424
+ // with ?proposal=, the cut as it would be if that proposal were accepted. Off, neither route exists
425
+ if (parts[2] === "preview" && parts.length === 3 && method === "GET") {
426
+ if (!(await livePreviewOn())) return refuse(res, 404, "The live preview isn't on.")
427
+ const proposalId = url.searchParams.get("proposal")
428
+ let project = state.log.current
429
+ if (proposalId !== null) {
430
+ const proposal = state.proposals.get(proposalId)
431
+ if (!proposal) return refuse(res, 404, "That proposal isn't there any more.")
432
+ const applied = apply(project, proposal.ops, { index: state.index })
433
+ if (applied.diagnostics.length) return refuse(res, 409, "That proposal no longer fits the cut.")
434
+ project = applied.project
435
+ }
436
+ const { version } = await tools()
437
+ state.previewTiles ??= new Map()
438
+ const fonts = state.engine.motion().fonts
439
+ return say(200, previewOf(project, state.index, { runtimeVersion: version, tiles: state.previewTiles, ...(fonts ? { fonts: [...fonts.keys()] } : {}) }))
440
+ }
441
+ // "Replay how it was edited" (editing.livePreview): the latest make's own operations, layer by layer,
442
+ // from the cut it started on, as previews to draw. Nothing renders and nothing is written
443
+ if (parts[2] === "layers" && parts.length === 3 && method === "GET") {
444
+ if (!(await livePreviewOn())) return refuse(res, 404, "The live preview isn't on.")
445
+ const { entry, job } = lastMadeEntry(state.journal.jobs("done"), state.log)
446
+ if (!entry) return refuse(res, 404, "There's no make to replay yet: make one first.")
447
+ const { version } = await tools()
448
+ state.previewTiles ??= new Map()
449
+ const fonts = state.engine.motion().fonts
450
+ const before = projectAt(state.log, entry.parent, { index: state.index })
451
+ const layers = layersOf(before, entry.ops, state.index).map(({ project, ...layer }) => ({ ...layer, ...viewOf(project, state.index, { runtimeVersion: version, tiles: state.previewTiles, ...(fonts ? { fonts: [...fonts.keys()] } : {}) }) }))
452
+ return say(200, { job, current: entry.id === state.log.head, layers })
453
+ }
454
+ // One tile of a preview: its own sandboxed document, no network, as the render draws it
455
+ if (parts[2] === "tile-preview" && parts.length === 3 && method === "GET") {
456
+ if (!(await livePreviewOn())) return refuse(res, 404, "The live preview isn't on.")
457
+ const found = tileDocument(state.previewTiles ?? new Map(), url.searchParams.get("key"))
458
+ if (found === null) return refuse(res, 404, "That tile isn't in this preview.")
459
+ // TP7: a type kit's fonts go in as data, as the render puts them; a tile without one is unchanged
460
+ const html = withFonts(found, state.engine.motion().fonts)
461
+ res.writeHead(200, { ...HEADERS, "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:; frame-ancestors 'self'; sandbox allow-scripts" })
462
+ return res.end(html)
463
+ }
464
+ // A few seconds of the person's voice to text, on this computer only (TP4, §7.4)
465
+ if (parts[2] === "dictate" && parts.length === 3 && method === "POST") {
466
+ if (!(await dictationOn())) return refuse(res, 404, "Hold to talk isn't available.")
467
+ if (!/^(?:audio|video)\/(?:webm|ogg|mp4)\b/.test(req.headers["content-type"] ?? "")) return refuse(res, 415, "Send the recording as WebM, Ogg or MP4 audio.")
468
+ const audio = await readBody(req)
469
+ if (!audio.length) return refuse(res, 400, "Nothing was recorded.")
470
+ return say(200, await projects.dictate(state, audio))
471
+ }
346
472
  if (parts[2] === "ask" && parts.length === 3 && method === "POST") {
347
- const { text, selection, history } = await readJson(req)
473
+ const { text, selection, history, mentions, mark: drawn } = await readJson(req)
348
474
  if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want changed, in up to 2,000 characters.")
475
+ // TP9: a drawn box, checked here; with editing.customMotion off it isn't read at all
476
+ const mark = (await projects.features()).customMotion === true ? cleanMark(drawn) : undefined
477
+ if (mark === null) return refuse(res, 400, "That drawing isn't a box, ring or arrow inside the frame. Draw it again.")
349
478
  // The chat's last turns, short and text only: nothing else of the browser's reaches the model
350
479
  const turns = Array.isArray(history) ? history.filter((h) => h && (h.who === "you" || h.who === "kriya") && typeof h.text === "string").slice(-6).map((h) => ({ who: h.who, text: h.text.slice(0, 400) })) : []
351
- return say(200, await projects.ask(state, { text, selection, history: turns }))
480
+ return say(200, await projects.ask(state, { text, selection, history: turns, mentions, ...(mark ? { mark } : {}) }))
481
+ }
482
+ // TP9 (editing.customMotion): a proposal's custom animation, as the render draws it: its own sandboxed document, no network
483
+ if (parts[2] === "custom-preview" && parts.length === 3 && method === "GET") {
484
+ if ((await projects.features()).customMotion !== true) return refuse(res, 404, "Custom motion isn't on.")
485
+ const n = Number(url.searchParams.get("op"))
486
+ if (!Number.isInteger(n) || n < 0) return refuse(res, 404, "That proposal has no custom animation to show.")
487
+ let html
488
+ try {
489
+ html = projects.customPreview(state, url.searchParams.get("proposal") ?? "", n)
490
+ } catch (error) {
491
+ if (error instanceof EngineFailure && error.reason === "no_preview") return refuse(res, 404, error.message)
492
+ throw error
493
+ }
494
+ res.writeHead(200, { ...HEADERS, "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; frame-ancestors 'self'; sandbox allow-scripts" })
495
+ return res.end(html)
352
496
  }
353
497
  if (parts[2] === "proposals" && parts.length === 4 && method === "POST") {
354
498
  const { accept, only } = await readJson(req)
355
499
  if (typeof accept !== "boolean" || (only !== undefined && !(Array.isArray(only) && only.every(Number.isInteger)))) return refuse(res, 400, "Accept or reject the proposal.")
356
500
  const result = projects.decide(state, parts[3], { accept, only })
357
- return say(200, { ...result, ...projectView(state) })
501
+ return say(200, { ...result, ...(await projectView(state)) })
358
502
  }
359
503
  if (parts[2] === "make" && parts.length === 3 && method === "POST") {
360
504
  const { asset, brief, plan } = await readJson(req)
@@ -363,7 +507,8 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
363
507
  if (Number.isFinite(brief.seconds) && brief.seconds >= 5 && brief.seconds <= 600) clean.targetDuration = Math.round(brief.seconds * 705_600_000)
364
508
  if (Array.isArray(brief.mustKeep) && brief.mustKeep.every((id) => typeof id === "string" && id.length < 64)) clean.mustKeep = brief.mustKeep.slice(0, 20)
365
509
  if (brief.effort === "fast" || brief.effort === "best") clean.effort = brief.effort
366
- if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
510
+ const typeKitOn = (await projects.features()).typeKit === true
511
+ if (typeof brief.captions === "string" && Object.hasOwn(typeKitOn ? ALL_LOOKS : LOOKS, brief.captions)) clean.captions = brief.captions
367
512
  if (typeof brief.music === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.music)) clean.music = brief.music
368
513
  if (typeof brief.reference === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.reference)) clean.reference = brief.reference
369
514
  if (Object.hasOwn(FORMATS, brief.format)) clean.format = brief.format
@@ -375,8 +520,11 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
375
520
  if (Array.isArray(brief.references)) clean.references = cleanRefs(brief.references)
376
521
  if (safeId(brief.hook)) clean.hook = brief.hook
377
522
  if (brief.coldOpen && safeId(brief.coldOpen.from) && safeId(brief.coldOpen.to)) clean.coldOpen = { from: brief.coldOpen.from, to: brief.coldOpen.to, mono: brief.coldOpen.mono !== false }
378
- if (["whoosh", "pop"].includes(brief.cutSound)) clean.cutSound = brief.cutSound
379
- if (["riser", "hit"].includes(brief.introSound)) clean.introSound = brief.introSound
523
+ // TP10: with editing.craft on, the sounds Kriya writes are more, and the make may arrange its sound to the cut
524
+ const crafted = (await projects.features()).craft === true
525
+ if ((crafted ? CUT_SOUNDS : ["whoosh", "pop"]).includes(brief.cutSound)) clean.cutSound = brief.cutSound
526
+ if ((crafted ? INTRO_SOUNDS : ["riser", "hit"]).includes(brief.introSound)) clean.introSound = brief.introSound
527
+ if (crafted) for (const flag of ["arrange", "ambience", "splits", "beatJoins"]) if (brief[flag] === true) clean[flag] = true
380
528
  if (Number.isInteger(brief.punches) && brief.punches >= 0 && brief.punches <= 8) clean.punches = brief.punches
381
529
  for (const flag of ["angles", "titles", "ramps"]) if (brief[flag] === true) clean[flag] = true
382
530
  if (brief.broll === "own") clean.broll = "own"
@@ -403,13 +551,42 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
403
551
  if (brief.transitionAll === true) clean.transitionAll = true
404
552
  }
405
553
  // Motion graphics from an approved plan, only while the server's switch is on; each cleaned to the kit's shape
406
- if (Array.isArray(brief.graphics) && brief.graphics.length && allowed.motion) clean.graphics = brief.graphics.slice(0, 12).map(cleanGraphic).filter(Boolean)
554
+ // TP9: a callout round a drawn box also, with editing.customMotion on
555
+ if (Array.isArray(brief.graphics) && brief.graphics.length && allowed.motion) clean.graphics = brief.graphics.slice(0, 12).map((g) => cleanGraphic(g, typeKitOn || (allowed.customMotion === true && g?.kind === "callout" && g?.mark) ? ALL_GRAPHIC_KINDS : GRAPHIC_KINDS)).filter(Boolean)
556
+ // TP7: a type kit or a style pack, from the person's brief or an approved plan, only with editing.typeKit on.
557
+ // The pack fills only what the brief leaves open; the kit is stored on the project by the make (EH-69)
558
+ if (typeKitOn && (brief.typeKit !== undefined || typeof brief.stylePack === "string")) {
559
+ let raw = brief.typeKit ?? null
560
+ if (typeof brief.stylePack === "string") {
561
+ if (!Object.hasOwn(STYLE_PACKS, brief.stylePack)) return refuse(res, 400, "There is no style pack by that name.")
562
+ const packed = applyStylePack(brief.stylePack, clean, { moods: allowed.craft ? ALL_MOODS : MOODS, grades: GRADES, transitions: TRANSITIONS, looks: ALL_LOOKS, motion: allowed.motion })
563
+ Object.assign(clean, packed.brief)
564
+ if (packed.notes.length) clean.packNotes = packed.notes
565
+ // The person's own pair, colours, logo and bar over the pack's
566
+ raw = { ...packed.kit, ...(raw && typeof raw === "object" ? raw : {}), pack: brief.stylePack }
567
+ }
568
+ const { kit, problem } = cleanTypeKit(raw, { packs: STYLE_PACKS })
569
+ if (problem) return refuse(res, 400, `That type kit can't be used: ${problem}.`)
570
+ if (kit) clean.typeKit = kit
571
+ }
572
+ // TP6: the style brief the person kept, only with editing.referenceIntent on: a reference's id and the trait ids
573
+ // they unticked. Nothing else of it comes from the browser: the Host builds the lines again from the measured numbers
574
+ if (allowed.referenceIntent === true && brief.styleBrief && safeId(brief.styleBrief.ref)) clean.styleBrief = { ref: brief.styleBrief.ref, off: cleanOff(brief.styleBrief.off) }
407
575
  // Animated scenes from an approved plan, only while the server's switch is on; the recipe checks each again against the speech
408
576
  if (Array.isArray(brief.scenes) && brief.scenes.length && (await projects.features()).visuals) {
409
577
  clean.scenes = brief.scenes.slice(0, 12).map(cleanScene).filter(Boolean)
410
578
  clean.sceneSound = brief.sceneSound !== false
411
579
  }
412
580
  }
581
+ // The film's order (TP2), only from this make's own brief and only with editing.assembly on: the storyboard
582
+ // the Studio sent, or an approved plan's. Checked as set_assembly checks it; one file with none is the reel
583
+ // it always was, and with the switch off the key is dropped (ET-ASM-REG-01, EH-63)
584
+ if (brief && typeof brief === "object" && brief.assembly !== undefined && (await projects.features()).assembly === true) {
585
+ const assembly = { version: 1, parts: Array.isArray(brief.assembly?.parts) ? brief.assembly.parts : [] }
586
+ const problems = assemblyProblems(assembly, { project: state.log.current, index: state.index })
587
+ if (problems.length) return refuse(res, 400, `That order can't be made: ${problems[0]}`)
588
+ if (isAssembly(assembly.parts)) clean.assembly = assembly
589
+ }
413
590
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
414
591
  if (brief?.fresh === true) clean.fresh = true
415
592
  // The last make's story, set here by the Host (never taken from the browser) so a replay of this job has it too
@@ -418,6 +595,27 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
418
595
  const approved = cleanPlan(plan)
419
596
  return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean, ...(approved ? { plan: approved } : {}) }))
420
597
  }
598
+ // Three openings to choose from (TP8, editing.directorLoop): started as a job, each film streamed by the job's own
599
+ // record. Off, neither route exists
600
+ if (parts[2] === "openings" && (await projects.features()).directorLoop === true) {
601
+ if (parts.length === 3 && method === "POST") {
602
+ const { asset, brief } = await readJson(req)
603
+ if (asset !== undefined && (typeof asset !== "string" || !state.log.current.assets.some((a) => a.id === asset && a.kind === "video"))) return refuse(res, 400, "Name the take.")
604
+ // Only the look of the openings comes from the browser, each value from its fixed list
605
+ const clean = {}
606
+ if (brief && typeof brief === "object") {
607
+ if (Object.hasOwn(FORMATS, brief.format)) clean.format = brief.format
608
+ if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
609
+ if (Object.hasOwn(GRADES, brief.grade)) clean.grade = brief.grade
610
+ }
611
+ return say(200, jobs.start(state, { kind: "openings", ...(asset ? { asset } : {}), brief: clean }))
612
+ }
613
+ if (parts.length === 5 && method === "GET") {
614
+ const file = /^\d{1,9}$/.test(parts[3]) && /^[0-2]$/.test(parts[4]) ? projects.openingFile(state, Number(parts[3]), Number(parts[4])) : null
615
+ if (!file) return refuse(res, 404, "That opening isn't there any more.")
616
+ return sendFile(req, res, file)
617
+ }
618
+ }
421
619
  // The person fixes a word the recogniser misheard (UX_SPEC §5)
422
620
  if (parts[2] === "words" && parts.length === 4 && method === "POST") {
423
621
  const { text } = await readJson(req)
@@ -452,17 +650,31 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
452
650
  } catch {
453
651
  return refuse(res, 400, "That isn't a graphic.")
454
652
  }
455
- const html = projects.graphicPreview(state, graphic, url.searchParams.get("format"))
653
+ const html = projects.graphicPreview(state, graphic, url.searchParams.get("format"), { typeKit: (await projects.features()).typeKit === true, drawn: (await projects.features()).customMotion === true })
456
654
  res.writeHead(200, { ...HEADERS, "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; frame-ancestors 'self'; sandbox allow-scripts" })
457
655
  return res.end(html)
458
656
  }
459
657
  // The Director's plan: proposed in words with its settings; nothing is made here
460
658
  if (parts[2] === "plan" && parts.length === 3 && method === "POST") {
461
- const { text, history, previous, choices } = await readJson(req)
659
+ const { text, history, previous, choices, mentions, mark: drawn } = await readJson(req)
462
660
  if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want, in up to 2,000 characters.")
661
+ const mark = (await projects.features()).customMotion === true ? cleanMark(drawn) : undefined
662
+ if (mark === null) return refuse(res, 400, "That drawing isn't a box, ring or arrow inside the frame. Draw it again.")
463
663
  const turns = Array.isArray(history) ? history.filter((h) => h && (h.who === "you" || h.who === "kriya") && typeof h.text === "string").slice(-6).map((h) => ({ who: h.who, text: h.text.slice(0, 400) })) : []
464
664
  const prior = cleanPlan(previous)
465
- return say(200, await projects.plan(state, { text, history: turns, previous: prior, choices: choices && typeof choices === "object" ? choices : {} }))
665
+ return say(200, await projects.plan(state, { text, history: turns, previous: prior, choices: choices && typeof choices === "object" ? choices : {}, mentions, ...(mark ? { mark } : {}) }))
666
+ }
667
+ // TP6 (editing.referenceIntent): a reference's style is read as a job (progress, cancel) and its brief is built from
668
+ // what the job kept; asking for a brief never measures. Off, neither route exists
669
+ if (parts[2] === "references" && parts.length === 5 && (parts[4] === "measure" || parts[4] === "brief") && (await projects.features()).referenceIntent === true) {
670
+ const ref = decodeURIComponent(parts[3])
671
+ if (!state.log.current.assets.some((a) => a.id === ref && a.kind === "reference")) return refuse(res, 404, "There is no such reference in this project.")
672
+ if (parts[4] === "measure" && method === "POST") return say(200, jobs.start(state, { kind: "reference", asset: ref }))
673
+ if (parts[4] === "brief" && method === "GET") {
674
+ const format = url.searchParams.get("format")
675
+ const brief = await projects.styleBriefFor(state, ref, Object.hasOwn(FORMATS, format ?? "") ? format : undefined)
676
+ return say(200, brief ? { status: "ready", brief } : { status: "none" })
677
+ }
466
678
  }
467
679
  // A reference's classified analysis, measured once and kept
468
680
  if (parts[2] === "references" && parts.length === 4 && method === "GET") return say(200, await projects.referenceAnalysis(state, decodeURIComponent(parts[3])))
@@ -512,6 +724,9 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
512
724
  const url = new URL(req.url, "http://host")
513
725
  try {
514
726
  if (overSocket) {
727
+ // TP11: the channel's own secret on every command, so another account on a shared Windows computer
728
+ // (whose pipe Node can't make owner-only) gets nothing. A Host made without one (tests) is as before
729
+ if (ipcToken !== null && !sameSecret(req.headers[TOKEN_HEADER], ipcToken)) return refuse(res, 401, "This command didn't come from this account's Kriya.")
515
730
  if (url.pathname === "/internal/info") return json(res, 200, { pid, port: port(), stamp, busy: busy() })
516
731
  if (url.pathname === "/internal/launch" && req.method === "POST") {
517
732
  const token = mintToken((await readJson(req)).back)
@@ -16,6 +16,8 @@ import { encoderFor } from "../engine/capabilities.js"
16
16
  import { probe } from "../engine/probe.js"
17
17
  import { runTool } from "../engine/tool.js"
18
18
  import { editHome } from "./paths.js"
19
+ import { clipList, decideAssembly, resolveRefs } from "../director/assembly.js"
20
+ import { cleanLabel } from "../core/project.js"
19
21
 
20
22
  const VIDEO = new Set([".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi"])
21
23
  const REPORT_MS = 10_000 // At most this often (TOOLS_AND_CONTRACTS §5)
@@ -29,6 +31,8 @@ const FLICKS = 705_600_000
29
31
  const FILE_QUESTION_S = 600
30
32
  const TAKE_QUESTION_S = 300
31
33
  const TASTE_QUESTION_S = 3600
34
+ const ORDER_QUESTION_S = 600
35
+ const ORDER_OPTIONS = 4
32
36
  const TAKE_MARGIN = 0.1
33
37
  const CLIP_SECONDS = 5
34
38
  const WAIT_S = 25
@@ -82,6 +86,48 @@ export function secondsIn(brief) {
82
86
  return seconds >= 5 && seconds <= 600 ? seconds : undefined
83
87
  }
84
88
 
89
+ const SPINE = ["story", "whole"]
90
+ /** One order as the person reads it on a card: "Clip 2 (Intro), then clip 1". Numbers and their own labels, no file names. */
91
+ export function orderLine(assembly, project) {
92
+ const numbered = new Map(clipList(project).map((c) => [c.asset, c.n]))
93
+ const label = (asset) => cleanLabel(project.assets.find((a) => a.id === asset)?.label)
94
+ const line = assembly.parts
95
+ .filter((p) => SPINE.includes(p.use))
96
+ .map((p, i) => `${i ? "clip" : "Clip"} ${numbered.get(p.asset) ?? "?"}${label(p.asset) ? ` (${label(p.asset)})` : ""}`)
97
+ .join(", then ")
98
+ return line.length > 200 ? `${line.slice(0, 199)}…` : line
99
+ }
100
+
101
+ /**
102
+ * The order a Tavi brief names across the folder's clips (TP11), by code only: no model call, never the
103
+ * storyboard stored on the project (EH-63), only the project's own numbered clips (no reference, no path).
104
+ * @returns {Promise<{ assembly: object } | { options: { label: string, assembly: object }[] } | null>}
105
+ * null: the brief names no order (one file, or one clip), and the job is the reel it always was
106
+ */
107
+ export async function orderIn(brief, state) {
108
+ const project = state.log.current
109
+ const index = state.index ?? {}
110
+ const clips = clipList(project, index)
111
+ if (clips.filter((c) => c.picture && c.duration > 0).length < 2) return null
112
+ const said = resolveRefs(brief, clips, { index })
113
+ if (said.refs.length < 2) return null
114
+ const decided = await decideAssembly({ project, index, text: brief })
115
+ if (decided.assembly && !decided.open.length) return { assembly: decided.assembly }
116
+ // What code couldn't settle: each clip that fits the first open place, as its own order, for the person to pick
117
+ const open = decided.open.find((item) => item.candidates?.length >= 2)
118
+ if (!open) return null
119
+ const options = []
120
+ for (const asset of open.candidates.slice(0, ORDER_OPTIONS)) {
121
+ const n = clips.find((c) => c.asset === asset)?.n
122
+ // The place said ("the beach clip") becomes that clip's number, its own "clip" or "file" word with it
123
+ const place = new RegExp(`${open.said.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s+(?:clip|file|video|one))?`, "i")
124
+ const tried = await decideAssembly({ project, index, text: brief.replace(place, `clip ${n}`) })
125
+ if (tried.assembly && !tried.open.length && !options.some((o) => JSON.stringify(o.assembly.parts) === JSON.stringify(tried.assembly.parts))) options.push({ label: orderLine(tried.assembly, project), assembly: tried.assembly })
126
+ }
127
+ if (options.length === 1) return { assembly: options[0].assembly }
128
+ return options.length >= 2 ? { options } : null
129
+ }
130
+
85
131
  /**
86
132
  * A file small enough to upload: the master when it fits, else a lower bitrate that
87
133
  * does. @returns {Promise<string | null>} null when even that won't fit
@@ -310,6 +356,37 @@ export function createTavi({ home, projects, taste = projects.taste, jobs, tools
310
356
  }
311
357
  // Only this recipe reaches a make job so far (ED11, ED12)
312
358
  if (recipe && recipe !== "reel-talking-head") return refuse("not_allowed")
359
+ // TP11: an order across the folder's clips, only with editing.assembly on and Kriya's taviOrder (rule 17);
360
+ // otherwise, and for a brief that names one file, everything below is as it was (ET-TP-REG-04)
361
+ const ordered = (state, assembly) => {
362
+ const seconds = secondsIn(brief)
363
+ const started = jobs().start(state, { kind: "make", brief: { effort, ...(seconds && { targetDuration: seconds * FLICKS }), assembly }, dispatch, dispatchJob: job })
364
+ entry.hostJob = started.id
365
+ return { accepted: true }
366
+ }
367
+ try {
368
+ const features = revisionOf ? null : await projects.features?.().catch(() => null)
369
+ const known = features?.assembly === true && features?.taviOrder === true ? projects.list().find((p) => dirname(p.file) === folder) : null
370
+ if (known) {
371
+ const state = await projects.get(known.id)
372
+ const order = await orderIn(brief, state)
373
+ if (order?.assembly) return ordered(state, order.assembly)
374
+ if (order?.options) {
375
+ void askPerson(dispatch, entry, job, {
376
+ kind: "order",
377
+ prompt: "Which order did you mean?",
378
+ options: order.options.map((o) => ({ label: o.label })),
379
+ defaultOption: 0,
380
+ timeoutSeconds: ORDER_QUESTION_S,
381
+ })
382
+ .then((option) => (entry.abort.signal.aborted ? final(dispatch, "canceled", { code: "canceled" }) : ordered(state, order.options[option].assembly)))
383
+ .catch((error) => (entry.abort.signal.aborted ? final(dispatch, "canceled", { code: "canceled" }) : failed(error)))
384
+ return { accepted: true }
385
+ }
386
+ }
387
+ } catch (error) {
388
+ return failed(error)
389
+ }
313
390
  try {
314
391
  const files = rankFiles(folder, brief)
315
392
  if (!files.length && !revisionOf) return await refuse("no_media")
@@ -12,6 +12,7 @@ import { remapIds, remapOp, replayable } from "../director/continuity.js"
12
12
  import { planReel, recipeFor } from "../recipes/reel.js"
13
13
  import { search } from "./loop.js"
14
14
  import { repairLadder } from "./repair.js"
15
+ import { roundsLeft, watchAndFix } from "../director/watch-fix.js"
15
16
 
16
17
  const FLICKS = 705_600_000
17
18
  const TEXT_GATES = new Set(["QG-08", "QG-09", "QG-10", "QG-11"])
@@ -38,15 +39,23 @@ export function planVerdict(project, index, recipe, { engineVersion = "f0", runt
38
39
  * ask: Function, render: (project: object, deliverable: string, signal?: AbortSignal) => Promise<{ file: string, plan: object }>,
39
40
  * sourcePath: (asset: string) => string, signal?: AbortSignal, onStage?: (stage: string) => void, run?: Function,
40
41
  * gateKit?: { tilePath?: Function, motion?: object, work?: string }, the Engine's tiles and Chrome, for QG-08 and QG-09
42
+ * watch?: { view: (attempt: object) => Promise<{ report: object, timeline: object }> } | null, the Director's watch-and-fix (TP8, editing.directorLoop); absent, the make as before
43
+ * onLive?: (event: object) => void, the make's real state as it happens (editing.livePreview): each planned candidate, each render, gate results, repairs and watch rounds. Never written to history; a throw here is ignored
41
44
  * }} input
42
45
  */
43
- export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {}, planner = null, plannerRecipe = null, edits = [] }) {
46
+ export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {}, planner = null, plannerRecipe = null, edits = [], watch = null, onLive = null }) {
44
47
  // edits: what the person did to the last cut, replayed on each candidate before it is rendered and gated
45
48
  // planner: a recipe with no variants to try (a programme, a montage), instead of the reel
46
49
  const recipe = plannerRecipe ?? recipeFor(brief)
47
50
  let calls = 0
48
51
  const notes = []
49
52
  const slots = {}
53
+ const live = (event) => {
54
+ if (!onLive) return
55
+ try {
56
+ onLive(event)
57
+ } catch {}
58
+ }
50
59
 
51
60
  const variantOf = async (variant) => {
52
61
  onStage("story")
@@ -54,7 +63,9 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
54
63
  calls += made.calls
55
64
  Object.assign(slots, made.slots)
56
65
  for (const note of made.notes) if (!notes.includes(note)) notes.push(note)
57
- return { ...carryEdits(made, edits, { before: project, index }), variant }
66
+ const candidate = { ...carryEdits(made, edits, { before: project, index }), variant }
67
+ live({ stage: "plan", before: project, ops: candidate.ops, round: variant.tighter ? 2 : variant.noHook ? 3 : 1 })
68
+ return candidate
58
69
  }
59
70
 
60
71
  const evaluate = async (candidate) => {
@@ -64,17 +75,31 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
64
75
  onStage("check")
65
76
  const deliverable = candidate.project.deliverables.find((d) => d.preset === recipe.deliverable.preset)
66
77
  const check = (file, plan, project) => runGates({ file, plan, project, index, sourcePath, thresholds: recipe.thresholds, ...gateKit, ...(run ? { run } : {}) })
78
+ live({ stage: "render", project: candidate.project })
67
79
  const { file, plan } = await render(candidate.project, deliverable.id, signal)
68
80
  let attempt = { project: candidate.project, ops: candidate.ops, file, plan, checked: await check(file, plan, candidate.project) }
81
+ live({ stage: "check", gates: attempt.checked.gates })
69
82
  // The repair ladder (QUALITY_GATES §4): code's fixes first, never a looser threshold, never a must-keep cut
70
83
  if (attempt.checked.blocking > 0 || attempt.checked.briefMisses > 0) {
71
84
  onStage("repair")
72
85
  const mustKeeps = (project) => planVerdict({ ...project, brief: { ...project.brief, targetDuration: undefined } }, index, recipe).briefMisses === 0
73
- const ladder = await repairLadder(attempt, { index, render: (project) => render(project, deliverable.id, signal), check, keepsMustKeeps: mustKeeps, signal })
86
+ const ladder = await repairLadder(attempt, { index, render: (project) => (live({ stage: "render", repair: true, project }), render(project, deliverable.id, signal)), check, keepsMustKeeps: mustKeeps, signal })
74
87
  attempt = ladder.best
88
+ live({ stage: "repair", attempts: ladder.attempts, project: attempt.project })
89
+ live({ stage: "check", gates: attempt.checked.gates })
75
90
  candidate.repairs = ladder.attempts
76
91
  candidate.person = ladder.person
77
92
  }
93
+ // TP8: the Director watches what was rendered and fixes it, in the rounds the ladder left (EH-74)
94
+ const left = watch ? roundsLeft(candidate.repairs) : 0
95
+ if (left > 0) {
96
+ onStage("watch")
97
+ const watched = await watchAndFix(attempt, { index, view: watch.view, render: (project) => render(project, deliverable.id, signal), check, rounds: left, signal })
98
+ attempt = watched.best
99
+ live({ stage: "watch", rounds: watched.rounds, project: attempt.project })
100
+ live({ stage: "check", gates: attempt.checked.gates })
101
+ candidate.watched = { rounds: watched.rounds, left: watched.left, score: watched.best.report?.score ?? null }
102
+ }
78
103
  Object.assign(candidate, { project: attempt.project, ops: attempt.ops, file: attempt.file, plan: attempt.plan, gates: attempt.checked })
79
104
  const checked = attempt.checked
80
105
  return { level: "F5", blocking: checked.blocking, briefMisses: checked.briefMisses, notes: checked.notes, quality: f0.quality, verdict: checked.verdict, failed: checked.gates?.filter((g) => g.status === "failed" && g.severity !== "note").map((g) => g.id) ?? [] }