@kriya-ai/harness 0.0.0-stage → 0.2.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 (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,461 @@
1
+ // `podcast-multicam` (EDITOR_WORKFLOWS §3.2, §9): N cameras of one conversation become
2
+ // one programme. Code does all of it, with no model call:
3
+ // 1. Sync (ET-IDX-07): each camera's sound against the master's, coarse by cross-
4
+ // correlating 10 ms loudness envelopes, then fine by GCC-PHAT on the samples in a
5
+ // few windows; a straight line through the windows gives the offset and clock drift.
6
+ // Each pairing has a confidence; below the floor the person is asked.
7
+ // 2. Who speaks: each speaker's own source (a dedicated mic, or the camera nearest
8
+ // them) against its own noise floor; a voice that is only the other's bleed is not.
9
+ // 3. Switch: a path search over the angles with a minimum shot length (2.5 s), a cost
10
+ // per switch, the speaker's camera for one voice, the wide for cross-talk and
11
+ // laughter; then a cutaway to the listener inside long monologues.
12
+ // The master's sound is the programme's: angles are picture only, so no cut is heard.
13
+
14
+ import { apply } from "../core/ops.js"
15
+ import { runTool } from "../engine/tool.js"
16
+
17
+ const FLICKS = 705_600_000
18
+
19
+ /** The recipe is data (ET-RCP-01): no command, path, URL, model or price. */
20
+ export const PODCAST_MULTICAM = {
21
+ id: "podcast-multicam",
22
+ canvas: { width: 1920, height: 1080 },
23
+ deliverable: { preset: "podcast-16x9", size: { width: 1920, height: 1080 }, fps: { n: 30, d: 1 }, codec: "h264", audio: "aac", loudness: { lufs: -14, tp: -1 }, burnCaptions: false, gates: ["QG-01", "QG-02", "QG-03", "QG-04", "QG-05", "QG-06", "QG-07", "QG-11", "QG-12", "QG-13", "QG-14"] },
24
+ thresholds: { lengthTolerance: 0.05 },
25
+ step: FLICKS / 10, // the switcher decides every 100 ms
26
+ minShot: 2.5 * FLICKS,
27
+ switchCost: 4,
28
+ voiceAbove: 12, // dB over the source's own floor
29
+ dominance: 6, // dB: a quieter voice this far under the loudest is bleed
30
+ hangover: 5, // steps a voice stays on after its last loud step
31
+ reaction: { after: 12 * FLICKS, length: 3 * FLICKS },
32
+ syncFloor: 0.3,
33
+ notes: "Recipe: a multi-camera conversation. The speaker's camera while one person talks, the wide shot when they talk over each other, a look at the listener in a long answer.",
34
+ }
35
+
36
+ export const SYNC_RATE = 8000
37
+ const ENVELOPE = 80 // samples: 10 ms at 8 kHz
38
+
39
+ // ---- Signals ----
40
+
41
+ /** A file's sound, mono at `rate`, as 16-bit samples. Long files: two hours is 115 MB at 8 kHz. */
42
+ export async function decodePcm(file, { rate = SYNC_RATE, run = runTool, signal } = {}) {
43
+ const chunks = []
44
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", file, "-vn", "-sn", "-dn", "-ac", "1", "-ar", String(rate), "-f", "s16le", "-"], { onStdout: (chunk) => chunks.push(chunk), signal, stallMs: 60_000 })
45
+ const bytes = Buffer.concat(chunks)
46
+ return new Int16Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + (bytes.length & ~1)))
47
+ }
48
+
49
+ const nextPow2 = (n) => 2 ** Math.ceil(Math.log2(Math.max(2, n)))
50
+
51
+ /** In-place radix-2 FFT; `inverse` scales by 1/n. */
52
+ export function fft(re, im, inverse = false) {
53
+ const n = re.length
54
+ for (let i = 1, j = 0; i < n; i++) {
55
+ let bit = n >> 1
56
+ for (; j & bit; bit >>= 1) j ^= bit
57
+ j ^= bit
58
+ if (i < j) {
59
+ ;[re[i], re[j]] = [re[j], re[i]]
60
+ ;[im[i], im[j]] = [im[j], im[i]]
61
+ }
62
+ }
63
+ for (let len = 2; len <= n; len <<= 1) {
64
+ const angle = ((inverse ? 2 : -2) * Math.PI) / len
65
+ const [wr, wi] = [Math.cos(angle), Math.sin(angle)]
66
+ for (let i = 0; i < n; i += len) {
67
+ let [cr, ci] = [1, 0]
68
+ for (let k = 0; k < len / 2; k++) {
69
+ const [a, b] = [i + k, i + k + len / 2]
70
+ const tr = re[b] * cr - im[b] * ci
71
+ const ti = re[b] * ci + im[b] * cr
72
+ re[b] = re[a] - tr
73
+ im[b] = im[a] - ti
74
+ re[a] += tr
75
+ im[a] += ti
76
+ ;[cr, ci] = [cr * wr - ci * wi, cr * wi + ci * wr]
77
+ }
78
+ }
79
+ }
80
+ if (inverse) for (let i = 0; i < n; i++) (re[i] /= n), (im[i] /= n)
81
+ }
82
+
83
+ /**
84
+ * c[k] = Σ a[n]·b[n+k], for k from -(a.length-1) to b.length-1, by FFT. With `phat`,
85
+ * each frequency is weighted to unit size (GCC-PHAT), which sharpens the peak.
86
+ * @returns {(k: number) => number}
87
+ */
88
+ function correlate(a, b, { phat = false } = {}) {
89
+ const size = nextPow2(a.length + b.length)
90
+ const [ar, ai, br, bi] = [new Float64Array(size), new Float64Array(size), new Float64Array(size), new Float64Array(size)]
91
+ ar.set(a)
92
+ br.set(b)
93
+ fft(ar, ai)
94
+ fft(br, bi)
95
+ for (let i = 0; i < size; i++) {
96
+ // conj(A)·B
97
+ const re = ar[i] * br[i] + ai[i] * bi[i]
98
+ const im = ar[i] * bi[i] - ai[i] * br[i]
99
+ const norm = phat ? Math.hypot(re, im) || 1 : 1
100
+ ar[i] = re / norm
101
+ ai[i] = im / norm
102
+ }
103
+ fft(ar, ai, true)
104
+ return (k) => ar[((k % size) + size) % size]
105
+ }
106
+
107
+ /** Loudness in dB per `step` samples (10 ms at 8 kHz). */
108
+ export function levels(pcm, step = ENVELOPE) {
109
+ const out = new Float32Array(Math.floor(pcm.length / step))
110
+ for (let i = 0; i < out.length; i++) {
111
+ let sum = 0
112
+ for (let j = i * step; j < (i + 1) * step; j++) sum += (pcm[j] / 32768) ** 2
113
+ out[i] = 10 * Math.log10(sum / step + 1e-10)
114
+ }
115
+ return out
116
+ }
117
+
118
+ // ---- Sync ----
119
+
120
+ const peakOf = (c, from, to) => {
121
+ let best = from
122
+ for (let k = from + 1; k <= to; k++) if (c(k) > c(best)) best = k
123
+ return best
124
+ }
125
+
126
+ /** The fine offset in one window, in samples, by GCC-PHAT within ±margin of `coarse`. */
127
+ function fineOffset(ref, other, at, length, coarse, margin) {
128
+ const start = at + coarse - margin
129
+ if (at < 0 || at + length > ref.length || start < 0 || start + length + 2 * margin > other.length) return null
130
+ const a = Float64Array.from(ref.subarray(at, at + length), (x) => x / 32768)
131
+ const b = Float64Array.from(other.subarray(start, start + length + 2 * margin), (x) => x / 32768)
132
+ const c = correlate(a, b, { phat: true })
133
+ const k = peakOf(c, 0, 2 * margin)
134
+ // Sharpness: the peak against the best value more than 1.5 ms away (drift smears a peak over a few samples)
135
+ const apart = Math.ceil(margin / 20) // 1.5 ms at the default 30 ms margin
136
+ let second = -Infinity
137
+ for (let j = 0; j <= 2 * margin; j++) if (Math.abs(j - k) > apart) second = Math.max(second, c(j))
138
+ const confidence = c(k) > 0 ? Math.max(0, 1 - Math.max(0, second) / c(k)) : 0
139
+ // Parabolic interpolation between samples
140
+ const [y0, y1, y2] = [c(k - 1), c(k), c(k + 1)]
141
+ const denominator = y0 - 2 * y1 + y2
142
+ const sub = k > 0 && k < 2 * margin && denominator !== 0 ? (0.5 * (y0 - y2)) / denominator : 0
143
+ return { offset: k + sub + coarse - margin, confidence }
144
+ }
145
+
146
+ // The envelope lag near step `at`, within ±2 s of `lag`, over 20 s either side
147
+ function localLag(ea, eb, at, lag, span = 2000, reach = 200) {
148
+ const from = Math.max(0, at - span)
149
+ const to = Math.min(ea.length, at + span)
150
+ if (to - from < span || from + lag - reach < 0 || to + lag + reach > eb.length) return lag
151
+ const c = correlate(ea.subarray(from, to), eb.subarray(from + lag - reach, to + lag + reach))
152
+ return lag - reach + peakOf(c, 0, 2 * reach)
153
+ }
154
+
155
+ /**
156
+ * Where `other` sits against `ref`: an event at ref time t is at other time
157
+ * t + offset + drift·t. Both are mono 16-bit at `rate`.
158
+ * @returns {{ offset: number, drift: number, confidence: number, windows: number }} offset in flicks; drift as a ratio (1e-4 is 100 ppm)
159
+ */
160
+ export function syncPair(ref, other, { rate = SYNC_RATE, maxLag = 60 * rate, windows = 6, window = 4 * rate, margin = Math.round(0.03 * rate) } = {}) {
161
+ // Coarse: envelopes in dB, floored and centred, so loudness differences don't matter
162
+ const envelope = (pcm) => {
163
+ const db = levels(pcm).map((x) => Math.max(x, -60))
164
+ const mean = db.reduce((s, x) => s + x, 0) / Math.max(1, db.length)
165
+ return db.map((x) => x - mean)
166
+ }
167
+ const [ea, eb] = [envelope(ref), envelope(other)]
168
+ const c = correlate(ea, eb)
169
+ const reach = Math.min(Math.round(maxLag / ENVELOPE), Math.max(ea.length, eb.length) - 1)
170
+ // Normalised by overlap, so a lag that overlaps little doesn't win by size; under half the shorter recording, a sliver could match by chance
171
+ const least = Math.min(ea.length, eb.length) / 2
172
+ const score = (k) => {
173
+ const overlap = Math.min(ea.length, eb.length - k) - Math.max(0, -k)
174
+ return overlap >= least ? c(k) / overlap : -Infinity
175
+ }
176
+ let lag = -reach
177
+ for (let k = -reach + 1; k <= reach; k++) if (score(k) > score(lag)) lag = k
178
+ const coarse = lag * ENVELOPE
179
+
180
+ // Fine: windows spread over the overlap, each placed where the reference is loudest
181
+ const first = Math.max(0, -coarse) + margin
182
+ const last = Math.min(ref.length, other.length - coarse) - window - margin
183
+ const found = []
184
+ if (last > first) {
185
+ const part = (last - first) / windows
186
+ for (let w = 0; w < windows; w++) {
187
+ let [best, energy] = [null, -1]
188
+ for (let at = Math.round(first + w * part); at <= first + (w + 1) * part - window / 2 && at <= last; at += rate / 4) {
189
+ let e = 0
190
+ for (let j = at; j < at + window; j += 8) e += ref[j] * ref[j]
191
+ if (e > energy) [best, energy] = [at, e]
192
+ }
193
+ // Drift moves the offset along the file, so each window re-finds its lag on the envelopes nearby
194
+ const fine = best === null ? null : fineOffset(ref, other, best, window, localLag(ea, eb, Math.round((best + window / 2) / ENVELOPE), lag) * ENVELOPE, margin)
195
+ if (fine) found.push({ t: best + window / 2, ...fine })
196
+ }
197
+ }
198
+ const good = found.filter((f) => f.confidence >= 0.1)
199
+ if (!good.length) return { offset: Math.round((coarse / rate) * FLICKS), drift: 0, confidence: 0, windows: 0 }
200
+ // A robust line first (Theil–Sen), so a window that locked onto an echo, more than 2 ms off it, is left out
201
+ const middle = (list) => [...list].sort((x, y) => x - y)[Math.floor(list.length / 2)]
202
+ const slopes = good.flatMap((f, i) => good.slice(i + 1).filter((g) => g.t !== f.t).map((g) => (g.offset - f.offset) / (g.t - f.t)))
203
+ const slope = slopes.length ? middle(slopes) : 0
204
+ const intercept = middle(good.map((f) => f.offset - slope * f.t))
205
+ const kept = good.filter((f) => Math.abs(f.offset - (intercept + slope * f.t)) <= 0.002 * rate)
206
+ let [offset, drift] = [intercept, slope]
207
+ if (kept.length >= 2) {
208
+ const n = kept.length
209
+ const mt = kept.reduce((s, f) => s + f.t, 0) / n
210
+ const mo = kept.reduce((s, f) => s + f.offset, 0) / n
211
+ const stt = kept.reduce((s, f) => s + (f.t - mt) ** 2, 0)
212
+ drift = stt > 0 ? kept.reduce((s, f) => s + (f.t - mt) * (f.offset - mo), 0) / stt : 0
213
+ offset = mo - drift * mt
214
+ }
215
+ const confidence = kept.length ? kept.map((f) => f.confidence).sort((a, b) => a - b)[Math.floor(kept.length / 2)] * (kept.length / found.length) : 0
216
+ return { offset: Math.round((offset / rate) * FLICKS), drift, confidence, windows: kept.length }
217
+ }
218
+
219
+ // ---- Who speaks ----
220
+
221
+ /**
222
+ * Each speaker's loudness on the master's clock, one value per decision step (the
223
+ * loudest 10 ms inside it); NaN where that source wasn't recording. `sources[i]` is
224
+ * speaker i's sound and its sync.
225
+ * @param {{ pcm: Int16Array, sync: { offset: number, drift: number } }[]} sources
226
+ */
227
+ export function speakerLevels(sources, steps, { rate = SYNC_RATE, step = PODCAST_MULTICAM.step } = {}) {
228
+ return sources.map(({ pcm, sync }) => {
229
+ const db = levels(pcm)
230
+ const out = new Float32Array(steps).fill(NaN)
231
+ const span = step / (FLICKS / (rate / ENVELOPE))
232
+ for (let i = 0; i < steps; i++) {
233
+ const t = i * step
234
+ const from = Math.floor(((t + sync.offset + sync.drift * t) / FLICKS) * (rate / ENVELOPE))
235
+ if (from < 0 || from + span > db.length) continue
236
+ out[i] = -100
237
+ for (let j = from; j < from + span; j++) out[i] = Math.max(out[i], db[j])
238
+ }
239
+ return out
240
+ })
241
+ }
242
+
243
+ /**
244
+ * Who is talking at each step, as a list of speaker numbers: a voice above its own
245
+ * floor, held through short gaps, and not more than `dominance` dB under the loudest
246
+ * over that same stretch (so bleed between one person's words isn't the other person).
247
+ * null where a speaker's source wasn't recording: who speaks isn't known there.
248
+ */
249
+ export function activity(speakers, rules = PODCAST_MULTICAM) {
250
+ const recent = speakers.map((db) => Array.from(db, (_, i) => Math.max(...db.slice(Math.max(0, i - rules.hangover), i + 1).filter((x) => !Number.isNaN(x)), -100)))
251
+ const loud = speakers.map((db) => {
252
+ // The floor: the quietest 5 % (pauses between words), so a voice that bleeds all the time isn't the floor
253
+ const heard = [...db].filter((x) => x > -100).sort((a, b) => a - b)
254
+ const floor = heard[Math.floor(heard.length / 20)] ?? -100
255
+ return Array.from(db, (x) => x > floor + rules.voiceAbove)
256
+ })
257
+ const on = loud.map((list) => list.map((_, i) => list.slice(Math.max(0, i - rules.hangover), i + 1).some(Boolean)))
258
+ return Array.from({ length: speakers[0]?.length ?? 0 }, (_, i) => {
259
+ if (speakers.some((db) => Number.isNaN(db[i]))) return null
260
+ const active = speakers.map((_, s) => s).filter((s) => on[s][i])
261
+ const top = Math.max(...active.map((s) => recent[s][i]))
262
+ const kept = active.filter((s) => recent[s][i] >= top - rules.dominance)
263
+ // A voice held only by the hangover (or only loud with the other's bleed) gives way to one heard now, so a change of turn isn't read as cross-talk
264
+ const peak = Math.max(...kept.map((s) => speakers[s][i]))
265
+ const now = kept.filter((s) => loud[s][i] && speakers[s][i] >= peak - rules.dominance)
266
+ return now.length ? now : kept
267
+ })
268
+ }
269
+
270
+ // ---- Switching ----
271
+
272
+ // Cost of showing `angle` while `active` speak: the speaker's own camera for one voice,
273
+ // the wide for several; silence costs nothing, so the picture holds. The listener's camera
274
+ // costs a little more than the wide, so a one-second reply holds the shot, not cuts away
275
+ function costOf(angle, active) {
276
+ if (active === null) return angle.speaker === null ? 0 : 1 // not known: the wide is safe
277
+ if (!active.length) return 0
278
+ if (active.length === 1) return angle.speaker === active[0] ? 0 : angle.speaker === null ? 1 : 1.5
279
+ return angle.speaker === null ? 0 : active.includes(angle.speaker) ? 2 : 3
280
+ }
281
+
282
+ /**
283
+ * The path search: states are (angle, steps on it, capped at the minimum shot), so a
284
+ * switch is only allowed off a shot at least `minShot` long. Angle 0 is the wide.
285
+ * @param {number[][]} labels who speaks at each step
286
+ * @param {{ speaker: number | null, available?: (step: number) => boolean }[]} angles
287
+ * @returns {{ angle: number, from: number, to: number }[]} shots in steps, end-exclusive
288
+ */
289
+ export function switchShots(labels, angles, rules = PODCAST_MULTICAM) {
290
+ const T = labels.length
291
+ if (!T) return []
292
+ const R = Math.max(1, Math.round(rules.minShot / rules.step))
293
+ const A = angles.length
294
+ const S = A * R
295
+ const emit = (a, i) => (angles[a].available && !angles[a].available(i) ? Infinity : costOf(angles[a], labels[i]))
296
+ let cost = new Float64Array(S).fill(Infinity)
297
+ for (let a = 0; a < A; a++) cost[a * R] = emit(a, 0)
298
+ const back = new Int32Array(T * S).fill(-1)
299
+ for (let i = 1; i < T; i++) {
300
+ const next = new Float64Array(S).fill(Infinity)
301
+ for (let a = 0; a < A; a++) {
302
+ const e = emit(a, i)
303
+ if (e === Infinity) continue
304
+ // Stay: (a, r) → (a, min(r + 1, R))
305
+ for (let r = 0; r < R; r++) {
306
+ const from = a * R + r
307
+ const to = a * R + Math.min(r + 1, R - 1)
308
+ if (cost[from] + e < next[to]) [next[to], back[i * S + to]] = [cost[from] + e, from]
309
+ }
310
+ // Switch: (b, R) → (a, 1)
311
+ for (let b = 0; b < A; b++) {
312
+ const from = b * R + R - 1
313
+ if (b === a || cost[from] === Infinity) continue
314
+ const value = cost[from] + rules.switchCost + e
315
+ if (value < next[a * R]) [next[a * R], back[i * S + a * R]] = [value, from]
316
+ }
317
+ }
318
+ cost = next
319
+ }
320
+ // The last shot must be long enough too, when the whole is
321
+ const cheapest = (allowed) => {
322
+ let best = -1
323
+ for (let s = 0; s < S; s++) if (allowed(s) && cost[s] < Infinity && (best < 0 || cost[s] < cost[best])) best = s
324
+ return best
325
+ }
326
+ let end = cheapest((s) => T < R || s % R === R - 1)
327
+ if (end < 0) end = cheapest(() => true)
328
+ const path = new Int32Array(T)
329
+ for (let i = T - 1, s = end; i >= 0; i--) {
330
+ path[i] = Math.floor(s / R)
331
+ s = back[i * S + s]
332
+ }
333
+ const shots = []
334
+ for (let i = 0; i < T; i++) {
335
+ if (shots.length && shots.at(-1).angle === path[i]) shots.at(-1).to = i + 1
336
+ else shots.push({ angle: path[i], from: i, to: i + 1 })
337
+ }
338
+ return shots
339
+ }
340
+
341
+ /**
342
+ * Cutaways to the listener inside long single-speaker shots: one every `after`, at the
343
+ * listener's loudest moment near it (a laugh, an "mm"), never leaving a shot under
344
+ * `minShot` either side.
345
+ */
346
+ export function reactionCuts(shots, angles, labels, speakers, rules = PODCAST_MULTICAM) {
347
+ const [after, length, min, half] = [rules.reaction.after, rules.reaction.length, rules.minShot, FLICKS / 2].map((t) => Math.round(t / rules.step))
348
+ const out = []
349
+ for (const shot of shots) {
350
+ const speaker = angles[shot.angle].speaker
351
+ if (speaker === null || shot.to - shot.from < after + length + min) {
352
+ out.push(shot)
353
+ continue
354
+ }
355
+ // The listener: the last other voice heard before this shot, else anyone else with a camera
356
+ const heard = labels.slice(0, shot.from).findLast((l) => l?.some((s) => s !== speaker))?.find((s) => s !== speaker)
357
+ const others = angles.map((_, i) => i).filter((i) => angles[i].speaker !== null && angles[i].speaker !== speaker)
358
+ const listener = others.find((i) => angles[i].speaker === heard) ?? others[0]
359
+ if (listener === undefined) {
360
+ out.push(shot)
361
+ continue
362
+ }
363
+ let cursor = shot.from
364
+ for (let target = shot.from + after; target + length + min <= shot.to; target += after) {
365
+ const [lo, hi] = [Math.max(cursor + min, target - Math.floor(after / 3)), Math.min(shot.to - length - min, target + Math.floor(after / 3))]
366
+ if (lo > hi) continue
367
+ const db = speakers[angles[listener].speaker]
368
+ // A reaction is heard over the speaker (a laugh, an "mm"); the listener alone for half a second is a reply, and isn't cut to
369
+ const replies = (i) => labels.slice(i, i + length).some((l) => l === null) || labels.slice(i, i + length).filter((l) => l.length && !l.includes(speaker)).length >= half
370
+ const fits = (i) => labels[i]?.includes(speaker) && !replies(i) && (!angles[listener].available || angles[listener].available(i))
371
+ // The listener's loudest moment; with none louder than another, the target itself
372
+ let at = Math.min(hi, Math.max(lo, target))
373
+ if (!fits(at)) at = -1
374
+ for (let i = lo; i <= hi; i++) if (fits(i) && (at < 0 || db[i] > db[at] + 1)) at = i
375
+ if (at < 0) continue
376
+ out.push({ ...shot, from: cursor, to: at }, { angle: listener, from: at, to: at + length, reaction: true })
377
+ cursor = at + length
378
+ }
379
+ out.push({ ...shot, from: cursor })
380
+ }
381
+ return out
382
+ }
383
+
384
+ // ---- The recipe ----
385
+
386
+ /**
387
+ * Reads, syncs and labels the sources. `master` is the wide camera, whose sound is the
388
+ * programme's; each angle is a camera on one speaker, its voice from its own `mic` file
389
+ * when there is one, else from the camera's sound.
390
+ * @param {{ master: { asset: string, file: string, duration: number }, angles: { asset: string, file: string, speaker: number, mic?: string }[] }} input
391
+ */
392
+ export async function analyseMulticam({ master, angles }, { run = runTool, signal, rules = PODCAST_MULTICAM } = {}) {
393
+ if (angles.map((a) => a.speaker).sort((a, b) => a - b).some((s, i) => s !== i)) throw new Error("Give each camera its own speaker, numbered from 0.")
394
+ const ref = await decodePcm(master.file, { run, signal })
395
+ const sync = {}
396
+ const voices = []
397
+ for (const angle of angles) {
398
+ const pcm = await decodePcm(angle.file, { run, signal })
399
+ sync[angle.asset] = syncPair(ref, pcm)
400
+ const mic = angle.mic ? await decodePcm(angle.mic, { run, signal }) : null
401
+ voices[angle.speaker] = mic ? { pcm: mic, sync: syncPair(ref, mic) } : { pcm, sync: sync[angle.asset] }
402
+ }
403
+ const steps = Math.floor(master.duration / rules.step)
404
+ const speakers = speakerLevels(voices, steps, { step: rules.step })
405
+ return { sync, speakers, labels: activity(speakers, rules) }
406
+ }
407
+
408
+ const WHY = (shot, angles, labels) => {
409
+ if (shot.reaction) return "the listener's reaction"
410
+ if (angles[shot.angle].speaker === null) return labels.slice(shot.from, shot.to).some((l) => l?.length > 1) ? "both talking" : "the room"
411
+ return `speaker ${angles[shot.angle].speaker + 1}`
412
+ }
413
+
414
+ /**
415
+ * Plans the programme as operations: the master whole on the base track, each angle's
416
+ * shot as picture over it, in sync, with the master's sound throughout.
417
+ * @param {{ project: object, index: object, master: string, angles: { asset: string, speaker: number }[], analysis: { sync: Record<string, { offset: number, drift: number, confidence: number }>, speakers: Float32Array[], labels: number[][] }, brief?: object }} input
418
+ */
419
+ export function planMulticam({ project, index, master, angles, analysis, brief = {}, rules = PODCAST_MULTICAM }) {
420
+ const notes = []
421
+ const facts = (id) => project.assets.find((a) => a.id === id).facts
422
+ const low = angles.filter((a) => analysis.sync[a.asset].confidence < rules.syncFloor)
423
+ if (low.length) throw Object.assign(new Error(`The sound of ${low.map((a) => a.asset).join(", ")} doesn't match the master's well enough to sync (confidence under ${rules.syncFloor}). Check it's the same conversation, or line it up by hand.`), { needsYou: true })
424
+
425
+ const duration = facts(master).duration
426
+ // A camera is usable while its own recording covers the moment
427
+ const sourceTime = (asset, t) => Math.round(t + analysis.sync[asset].offset + analysis.sync[asset].drift * t)
428
+ const view = [{ speaker: null }, ...angles.map((a) => ({ speaker: a.speaker, asset: a.asset, available: (i) => sourceTime(a.asset, i * rules.step) >= 0 && sourceTime(a.asset, (i + 1) * rules.step) <= facts(a.asset).duration }))]
429
+ const shots = reactionCuts(switchShots(analysis.labels, view, rules), view, analysis.labels, analysis.speakers, rules)
430
+
431
+ const sequence = project.sequences.find((q) => q.id === project.active)
432
+ const base = new Set(sequence.tracks.filter((t) => t.role === "base").map((t) => t.id))
433
+ const ops = [
434
+ ...sequence.clips.filter((c) => base.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
435
+ { op: "set_brief", format: rules.id, targetDuration: duration, mustKeep: [], mustCut: [], effort: brief.effort ?? "best" },
436
+ { op: "set_format", width: rules.canvas.width, height: rules.canvas.height, fps: rules.deliverable.fps },
437
+ ...(project.deliverables.some((d) => d.preset === rules.deliverable.preset) ? [] : [{ op: "add_deliverable", ...rules.deliverable }]),
438
+ { op: "keep_range", asset: master, from: 0, to: duration },
439
+ ]
440
+ const cut = apply(project, ops, { index, author: "agent" })
441
+ if (!cut.applied) throw new Error(`The programme was refused: ${cut.diagnostics[0].message}`)
442
+ const after = cut.project.sequences.find((q) => q.id === cut.project.active)
443
+ const baseTracks = new Set(after.tracks.filter((t) => t.role === "base").map((t) => t.id))
444
+ const programme = after.clips.findLast((c) => baseTracks.has(c.track)).id
445
+
446
+ for (const shot of shots) {
447
+ if (view[shot.angle].speaker === null) continue
448
+ const [from, to] = [shot.from * rules.step, Math.min(duration, shot.to * rules.step)]
449
+ const asset = view[shot.angle].asset
450
+ const start = sourceTime(asset, from)
451
+ ops.push({ op: "place_broll", asset, at: { clip: programme, edge: "start", offset: from }, in: start, out: start + (to - from) })
452
+ }
453
+ const done = apply(project, ops, { index, author: "agent" })
454
+ if (!done.applied) throw new Error(`The switch was refused: ${done.diagnostics[0].message}`)
455
+
456
+ const plan = shots.map((s) => ({ asset: view[s.angle].asset ?? master, at: s.from * rules.step, end: Math.min(duration, s.to * rules.step), why: WHY(s, view, analysis.labels) }))
457
+ const reactions = shots.filter((s) => s.reaction).length
458
+ notes.push(`Synced ${angles.length} camera${angles.length === 1 ? "" : "s"} to the master: ${angles.map((a) => `${a.asset} ${(analysis.sync[a.asset].offset / FLICKS).toFixed(3)} s, drift ${Math.round(analysis.sync[a.asset].drift * 1e6)} ppm, confidence ${analysis.sync[a.asset].confidence.toFixed(2)}`).join("; ")}.`)
459
+ notes.push(`${shots.length} shots, none under ${rules.minShot / FLICKS} s; the wide for talking over each other${reactions ? `, and ${reactions} look${reactions === 1 ? "" : "s"} at the listener` : ""}. The sound is the master's throughout.`)
460
+ return { ops, project: done.project, notes, calls: 0, shots: plan }
461
+ }
@@ -0,0 +1,202 @@
1
+ // `reel-talking-head` (EDITOR_WORKFLOWS §3.1): one raw take becomes a vertical reel.
2
+ // Best take per line, restarts, fillers and stutters out, hook first, fitted to
3
+ // the length, punch-ins on a few emphasis words, reframed to 9:16, mastered to
4
+ // −14 LUFS. Code does the editing; the model makes two small choices (the hook and
5
+ // the lines to drop; the emphasis words), each with a default that needs no model.
6
+
7
+ import { apply } from "../core/ops.js"
8
+ import { LOOKS, pages } from "../engine/captions.js"
9
+ import { paperEdit } from "../index/views.js"
10
+
11
+ const FLICKS = 705_600_000
12
+
13
+ /** The recipe is data (ET-RCP-01): no command, path, URL, model or price. */
14
+ export const REEL_TALKING_HEAD = {
15
+ id: "reel-talking-head",
16
+ target: { min: 30 * FLICKS, max: 60 * FLICKS, default: 45 * FLICKS },
17
+ canvas: { width: 1080, height: 1920 },
18
+ deliverable: { preset: "reel-9x16", size: { width: 1080, height: 1920 }, fps: { n: 30, d: 1 }, codec: "h264", audio: "aac", loudness: { lufs: -14, tp: -1 }, burnCaptions: false, gates: ["QG-01", "QG-02", "QG-03", "QG-04", "QG-05", "QG-06", "QG-07", "QG-11", "QG-12", "QG-13", "QG-14"] },
19
+ thresholds: { lengthTolerance: 1 / 3 }, // 30 to 60 s around 45
20
+ punch: { scale: 1.15, max: 3 },
21
+ joinGap: Math.round(0.7 * FLICKS), // a pause longer than this inside a line is cut out
22
+ notes: "Recipe: a talking-head reel for phones. The first sentence must work on its own as a hook. Keep the speaker's meaning; drop only lines that repeat or wander.",
23
+ }
24
+
25
+ const STRUCK = new Set(["filler", "stutter", "restart"])
26
+
27
+ /** The recipe's deliverable; with captions asked for, they burn in and the text gates run (ED8). */
28
+ export function deliverableFor(brief = {}) {
29
+ const base = REEL_TALKING_HEAD.deliverable
30
+ return LOOKS[brief.captions] ? { ...base, burnCaptions: true, gates: [...base.gates, "QG-08", "QG-09", "QG-10"].sort() } : base
31
+ }
32
+
33
+ /** Lines worth keeping: each take group's best, with restarts and abandoned attempts out. */
34
+ export function candidateLines(index, asset, picks = {}) {
35
+ const takes = new Map(index.takes.map((t) => [t.sentence, t]))
36
+ const words = index.words.filter((w) => w.asset === asset)
37
+ const byId = new Map(words.map((w, i) => [w.id, i]))
38
+ return index.sentences
39
+ .filter((s) => s.asset === asset)
40
+ .map((s) => ({ ...s, words: words.slice(byId.get(s.firstWord), byId.get(s.lastWord) + 1) }))
41
+ .filter((s) => {
42
+ const take = takes.get(s.id)
43
+ // The person's choice of take, if a decision card asked them (ED15); else the best
44
+ if (take && (picks[take.group] ? picks[take.group] !== s.id : take.rank !== 1)) return false
45
+ if (s.score === 0) return false
46
+ return !s.words.every((w) => w.flags.some((f) => STRUCK.has(f)))
47
+ })
48
+ }
49
+
50
+ /** A line's spoken runs: its words minus fillers and stutters, split at long pauses. */
51
+ export function runsOf(line, joinGap = REEL_TALKING_HEAD.joinGap) {
52
+ const runs = []
53
+ let run = null
54
+ for (const word of line.words) {
55
+ if (word.flags.some((f) => STRUCK.has(f))) {
56
+ run = null
57
+ continue
58
+ }
59
+ if (run && word.start - run.at(-1).end <= joinGap) run.push(word)
60
+ else runs.push((run = [word]))
61
+ }
62
+ return runs
63
+ }
64
+
65
+ const lengthOf = (line) => runsOf(line).reduce((sum, run) => sum + (run.at(-1).end - run[0].start), 0)
66
+
67
+ /**
68
+ * Picks lines to fit `max` by dynamic programming over 100 ms steps: as many seconds
69
+ * of the best lines as fit, in their order, with the required ones always in.
70
+ * `valueOf(line, cost)` weighs a line (ED11's short-from-long: closeness to the topic × density).
71
+ */
72
+ export function fitLines(lines, max, required = new Set(), valueOf = (line, cost) => cost * (line.score || 1)) {
73
+ const unit = FLICKS / 10
74
+ const cost = lines.map((l) => Math.ceil(lengthOf(l) / unit))
75
+ const fixed = lines.reduce((sum, l, i) => sum + (required.has(l.id) ? cost[i] : 0), 0)
76
+ const capacity = Math.floor(max / unit) - fixed
77
+ if (capacity < 0) return lines.filter((l) => required.has(l.id))
78
+ // value: by default speech kept, weighted by the line's take score
79
+ const free = lines.map((l, i) => ({ i, cost: cost[i], value: valueOf(l, cost[i]) })).filter(({ i }) => !required.has(lines[i].id))
80
+ const best = new Float64Array(capacity + 1)
81
+ const pick = free.map(() => new Uint8Array(capacity + 1))
82
+ free.forEach((item, k) => {
83
+ for (let c = capacity; c >= item.cost; c--) {
84
+ const value = best[c - item.cost] + item.value
85
+ if (value > best[c]) {
86
+ best[c] = value
87
+ pick[k][c] = 1
88
+ }
89
+ }
90
+ })
91
+ const chosen = new Set([...required])
92
+ let c = capacity
93
+ for (let k = free.length - 1; k >= 0; k--) {
94
+ if (pick[k][c]) {
95
+ chosen.add(lines[free[k].i].id)
96
+ c -= free[k].cost
97
+ }
98
+ }
99
+ return lines.filter((l) => chosen.has(l.id))
100
+ }
101
+
102
+ const STORY_SCHEMA = {
103
+ type: "object",
104
+ properties: { hook: { anyOf: [{ type: "string", maxLength: 64 }, { type: "null" }] }, drop: { type: "array", maxItems: 40, items: { type: "string", maxLength: 64 } } },
105
+ required: ["hook", "drop"],
106
+ additionalProperties: false,
107
+ }
108
+ const EMPHASIS_SCHEMA = { type: "object", properties: { emphasis: { type: "array", maxItems: 3, items: { type: "string", maxLength: 64 } } }, required: ["emphasis"], additionalProperties: false }
109
+
110
+ /**
111
+ * Plans the reel as operations on `project` (which keeps its assets; its cut is replaced).
112
+ * @param {{ project: object, index: object, asset: string, ask: Function, brief?: object, variant?: { tighter?: number, noHook?: boolean }, signal?: AbortSignal }} input
113
+ * @returns {Promise<{ ops: object[], project: object, notes: string[], calls: number, slots: Record<string, string> }>}
114
+ */
115
+ export async function planReel({ project, index, asset, ask, brief = {}, variant = {}, signal }) {
116
+ const recipe = REEL_TALKING_HEAD
117
+ const notes = []
118
+ const slots = {}
119
+ let calls = 0
120
+ const lines = candidateLines(index, asset, brief.picks)
121
+ const ids = new Set(lines.map((l) => l.id))
122
+ const mustKeep = (brief.mustKeep ?? []).filter((id) => ids.has(id))
123
+ const scoped = { ...index, sentences: lines, words: lines.flatMap((l) => l.words), takes: [] }
124
+
125
+ // Story: the hook, and the lines that add nothing (sentence ids only)
126
+ const story = await ask({
127
+ task: "story",
128
+ schema: STORY_SCHEMA,
129
+ recipe: recipe.notes,
130
+ view: paperEdit(scoped, { assets: [asset] }),
131
+ request: `Choose the opening line (a sentence id from the list, or null to keep the order) and any lines to drop because they repeat or wander. The reel should run ${recipe.target.min / FLICKS} to ${recipe.target.max / FLICKS} seconds. Never drop: ${mustKeep.join(", ") || "(none)"}.`,
132
+ maxOutput: 300,
133
+ check: ({ hook, drop }) => [hook, ...drop].filter((id) => id !== null && !ids.has(id)).map((id) => `"${id}" isn't one of the sentences shown`),
134
+ fallback: () => ({ hook: null, drop: [] }),
135
+ signal,
136
+ })
137
+ calls += story.calls
138
+ slots.story = story.source
139
+ if (story.reason) notes.push(`Story: ${story.reason} Kept every line, in order.`)
140
+ const hook = variant.noHook ? null : story.value.hook
141
+ let chosen = lines.filter((l) => !story.value.drop.includes(l.id) || mustKeep.includes(l.id))
142
+
143
+ // Length: fit under the maximum, the hook and must-keeps always in
144
+ const max = Math.round(recipe.target.max * (variant.tighter ?? 1))
145
+ const required = new Set([...mustKeep, ...(hook ? [hook] : [])])
146
+ if (chosen.reduce((sum, l) => sum + lengthOf(l), 0) > max) chosen = fitLines(chosen, max, required)
147
+ const total = chosen.reduce((sum, l) => sum + lengthOf(l), 0)
148
+ if (total < recipe.target.min) notes.push(`The footage gives ${(total / FLICKS).toFixed(1)} s of usable speech, under the ${recipe.target.min / FLICKS} s the recipe aims for.`)
149
+ if (hook && chosen.some((l) => l.id === hook)) chosen = [chosen.find((l) => l.id === hook), ...chosen.filter((l) => l.id !== hook)]
150
+ if (hook && chosen[0]?.id === hook && lines[0]?.id !== hook) notes.push(`Moved "${hook}" to the front as the hook.`)
151
+
152
+ // The cut: replace whatever is there with the kept runs
153
+ const sequence = project.sequences.find((q) => q.id === project.active)
154
+ const base = new Set(sequence.tracks.filter((t) => t.role === "base").map((t) => t.id))
155
+ const ops = [
156
+ ...sequence.clips.filter((c) => base.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
157
+ { op: "set_brief", format: recipe.id, targetDuration: brief.targetDuration ?? recipe.target.default, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
158
+ { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
159
+ ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...deliverableFor(brief) }]),
160
+ ]
161
+ for (const line of chosen) for (const run of runsOf(line)) ops.push({ op: "keep_range", asset, from: { word: run[0].id, edge: "start" }, to: { word: run.at(-1).id, edge: "end" } })
162
+ let step = apply(project, ops, { index, author: "agent" })
163
+ if (!step.applied) throw new Error(`The reel's cut was refused: ${step.diagnostics[0].message}`)
164
+
165
+ // Emphasis: a few words worth a punch-in
166
+ const kept = chosen.flatMap((l) => runsOf(l).flat())
167
+ const keptIds = new Set(kept.map((w) => w.id))
168
+ const emphasis = await ask({
169
+ task: "emphasis",
170
+ schema: EMPHASIS_SCHEMA,
171
+ recipe: recipe.notes,
172
+ view: paperEdit({ ...scoped, sentences: chosen }, { assets: [asset] }),
173
+ request: `Pick up to ${recipe.punch.max} single words to emphasise with a quick zoom: numbers, names, the point of a line. Word ids only.`,
174
+ maxOutput: 200,
175
+ check: ({ emphasis: picked }) => picked.filter((id) => !keptIds.has(id)).map((id) => `"${id}" isn't a kept word`),
176
+ fallback: () => ({ emphasis: kept.filter((w) => /\d/.test(w.text)).slice(0, recipe.punch.max).map((w) => w.id) }),
177
+ signal,
178
+ })
179
+ calls += emphasis.calls
180
+ slots.emphasis = emphasis.source
181
+ if (emphasis.reason) notes.push(`Emphasis: ${emphasis.reason}`)
182
+ const punches = [...new Set(emphasis.value.emphasis)].slice(0, recipe.punch.max).map((id) => ({ op: "punch_in", at: { word: id, edge: "start" }, until: { word: id, edge: "end" }, scale: brief.zoom ?? recipe.punch.scale }))
183
+
184
+ // Reframe to 9:16: follow the speaker where the index has one, else hold the centre
185
+ const facts = project.assets.find((a) => a.id === asset).facts
186
+ const cropWidth = Math.round((facts.height * recipe.canvas.width) / recipe.canvas.height)
187
+ const subject = (index.subjects?.[asset]?.length ?? 0) > 0
188
+ if (!subject) notes.push("No face track for this take, so the frame holds the centre.")
189
+ const clips = step.project.sequences.find((q) => q.id === step.project.active).clips.filter((c) => base.has(c.track))
190
+ const framing = clips.map((c) => (subject ? { op: "reframe", clip: c.id, mode: "subject" } : { op: "reframe", clip: c.id, mode: "fixed", x: Math.max(0, Math.round((facts.width - cropWidth) / 2)) }))
191
+
192
+ // Captions, when the brief asks for a look: pages of the kept words, timed to the speech
193
+ const captions = LOOKS[brief.captions] ? chosen.flatMap((l) => runsOf(l)).flatMap((run) => pages(run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
194
+ // Music, when the brief names a sound in the project: fitted on its downbeats, ducked under the speech (ED9)
195
+ const song = brief.music ? project.assets.find((a) => a.id === brief.music && a.kind === "audio") : null
196
+ if (brief.music && !song) notes.push(`There is no sound "${brief.music}" in this project, so the reel has no music.`)
197
+ const music = song ? [{ op: "set_music", asset: song.id }, { op: "music_shape", fit: true, fadeIn: Math.round(FLICKS * 0.3) }, { op: "duck" }] : []
198
+ const all = [...ops, ...punches, ...framing, ...captions, ...music]
199
+ step = apply(project, all, { index, author: "agent" })
200
+ if (!step.applied) throw new Error(`The reel was refused: ${step.diagnostics[0].message}`)
201
+ return { ops: all, project: step.project, notes, calls, slots }
202
+ }