@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,237 @@
1
+ // `short-from-long` (EDITOR_WORKFLOWS §3.1): a long recording (30 to 60+ minutes)
2
+ // becomes a standalone 30–60 s vertical short. Code does all of it, with no model call:
3
+ // story search over the cleaned lines (EDIT_LOOP §6 step 2), three candidates ranked by
4
+ // a pairwise tournament at F0 (the compiled plan) and F1 (the text), never rendered;
5
+ // the winner reframed to 9:16 on the L8 face track (EDIT_ENGINE §5.2).
6
+ // EDD-16: the rubric orders candidates for this one video. Nothing here forecasts views.
7
+
8
+ import { apply } from "../core/ops.js"
9
+ import { compile } from "../core/plan.js"
10
+ import { LOOKS, pages } from "../engine/captions.js"
11
+ import { candidateLines, fitLines, runsOf } from "./reel.js"
12
+
13
+ const FLICKS = 705_600_000
14
+
15
+ /** The recipe is data (ET-RCP-01): no command, path, URL, model or price. */
16
+ export const SHORT_FROM_LONG = {
17
+ id: "short-from-long",
18
+ target: { min: 30 * FLICKS, max: 60 * FLICKS, default: 45 * FLICKS },
19
+ canvas: { width: 1080, height: 1920 },
20
+ deliverable: { preset: "short-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"] },
21
+ thresholds: { lengthTolerance: 1 / 3 },
22
+ candidates: 3,
23
+ joinGap: Math.round(0.7 * FLICKS),
24
+ topicGap: 4 * FLICKS, // a pause this long between lines ends a story (PERCEPTION §8: split at pauses and embedding distance)
25
+ minCohesion: 0.08, // a line this far from the story's centroid starts a new topic
26
+ notes: "Recipe: a standalone short cut from a long recording. It opens on a line that works alone and ends on a finished thought.",
27
+ }
28
+
29
+ /** With captions asked for, they burn in and the text gates run, as for the reel (ED8). */
30
+ export function deliverableFor(brief = {}) {
31
+ const base = SHORT_FROM_LONG.deliverable
32
+ return LOOKS[brief.captions] ? { ...base, burnCaptions: true, gates: [...base.gates, "QG-08", "QG-09", "QG-10"].sort() } : base
33
+ }
34
+
35
+ // Openers that lean on something said before: a short that starts here starts mid-thought
36
+ const DANGLING = new Set(["and", "but", "so", "because", "also", "then", "or", "which", "it", "this", "that", "these", "those", "they", "he", "she", "him", "her", "them", "there", "yeah", "right", "anyway"])
37
+ const STOP = new Set([...DANGLING, "a", "an", "the", "i", "you", "we", "to", "of", "in", "on", "for", "is", "was", "are", "be", "with", "as", "at", "my", "our", "your", "me", "us", "do", "did", "have", "has", "had", "not", "just", "if", "what", "how", "why", "when", "all", "about", "from", "by", "one", "can", "will", "would", "now", "here", "its", "it's", "i'm", "let", "let's", "like", "um", "uh", "okay", "ok"])
38
+ const DIMS = 256
39
+
40
+ const tokensOf = (text) => text.toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? []
41
+
42
+ /**
43
+ * A sentence vector: content words hashed into 256 dims, L2-normalised.
44
+ * shortcut: lexical, so synonyms don't meet; L11's embeddings replace it when that layer is built
45
+ */
46
+ export function embed(text) {
47
+ const v = new Float64Array(DIMS)
48
+ for (const word of tokensOf(text)) {
49
+ if (STOP.has(word) || word.length < 3) continue
50
+ let h = 2166136261
51
+ for (const c of word.replace(/(ing|ed|es|s)$/, "")) h = Math.imul(h ^ c.charCodeAt(0), 16777619)
52
+ v[(h >>> 0) % DIMS] += 1
53
+ }
54
+ const norm = Math.hypot(...v)
55
+ return norm ? v.map((x) => x / norm) : v
56
+ }
57
+
58
+ const dot = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0)
59
+ const textOf = (line) => line.words.map((w) => w.text).join(" ")
60
+ const spoken = (line, joinGap) => runsOf(line, joinGap).reduce((sum, run) => sum + (run.at(-1).end - run[0].start), 0)
61
+
62
+ function centroid(vectors) {
63
+ const c = new Float64Array(DIMS)
64
+ for (const v of vectors) for (let i = 0; i < DIMS; i++) c[i] += v[i]
65
+ const norm = Math.hypot(...c)
66
+ return norm ? c.map((x) => x / norm) : c
67
+ }
68
+
69
+ /** How well a line opens a short on its own, 0 to 1 (F1, text only). */
70
+ export function openingStrength(line) {
71
+ const words = tokensOf(textOf(line))
72
+ if (!words.length || DANGLING.has(words[0])) return 0
73
+ let score = 0.5
74
+ if (words.some((w) => /\d/.test(w)) || /\?$/.test(textOf(line).trim())) score += 0.25
75
+ if (words.length >= 5 && words.length <= 16) score += 0.25
76
+ return score
77
+ }
78
+
79
+ const finished = (line) => /[.!?]["')]?$/.test(textOf(line).trim())
80
+
81
+ /**
82
+ * The rubric (EDD-16): numbers that order candidates, each 0 to 1, higher better.
83
+ * hook: the opening line stands alone; cohesion: lines stay on one topic; density:
84
+ * words a second against the recording's own pace; fit: length against the target;
85
+ * ending: it ends on a finished sentence; references: no line leans on a cut one.
86
+ */
87
+ function rubricOf(story, { target, pace }) {
88
+ const vectors = story.lines.map((l) => l.vector)
89
+ const c = centroid(vectors)
90
+ const words = story.lines.reduce((sum, l) => sum + l.words.length, 0)
91
+ const seconds = story.duration / FLICKS
92
+ const cut = story.lines.slice(1).filter((l, i) => l.n !== story.lines[i].n + 1)
93
+ return {
94
+ hook: openingStrength(story.lines[0]),
95
+ cohesion: vectors.length ? vectors.reduce((sum, v) => sum + dot(v, c), 0) / vectors.length : 0,
96
+ density: Math.min(1, words / seconds / (pace * 1.25)),
97
+ fit: Math.max(0, 1 - Math.abs(story.duration - target) / target),
98
+ ending: finished(story.lines.at(-1)) ? 1 : 0,
99
+ references: cut.length ? 1 - cut.filter((l) => openingStrength(l) === 0).length / cut.length : 1,
100
+ }
101
+ }
102
+
103
+ const total = (rubric) => Object.values(rubric).reduce((a, b) => a + b, 0)
104
+
105
+ /**
106
+ * Story search: each line that opens well starts a window that grows until a topic
107
+ * shift or 1.5× the maximum; a knapsack (dynamic programming over 100 ms steps, reel.js)
108
+ * keeps the lines worth most, by length × closeness to the story's topic × density,
109
+ * under the maximum with the opener always in. Windows are scored by the rubric and the
110
+ * best that don't overlap become candidates.
111
+ * @returns {{ lines: object[], duration: number, rubric: object, score: number }[]}
112
+ */
113
+ export function storySearch(index, asset, { recipe = SHORT_FROM_LONG, max = recipe.target.max, count = recipe.candidates, target = recipe.target.default } = {}) {
114
+ const lines = candidateLines(index, asset).map((line, n) => {
115
+ const duration = spoken(line, recipe.joinGap)
116
+ return { ...line, n, duration, vector: embed(textOf(line)), density: line.words.length / Math.max(duration / FLICKS, 0.1) }
117
+ })
118
+ if (!lines.length) return []
119
+ const pace = lines.reduce((sum, l) => sum + l.words.length, 0) / (lines.reduce((sum, l) => sum + l.duration, 0) / FLICKS)
120
+ const windows = []
121
+ for (let i = 0; i < lines.length; i++) {
122
+ if (openingStrength(lines[i]) < 0.5) continue
123
+ const window = [lines[i]]
124
+ let length = lines[i].duration
125
+ for (let j = i + 1; j < lines.length && length < max * 1.5; j++) {
126
+ const gap = lines[j].start - lines[j - 1].end
127
+ if (gap > recipe.topicGap || dot(lines[j].vector, centroid(window.map((l) => l.vector))) < recipe.minCohesion) break
128
+ window.push(lines[j])
129
+ length += lines[j].duration
130
+ }
131
+ if (length < recipe.target.min) continue
132
+ const c = centroid(window.map((l) => l.vector))
133
+ const valueOf = (line, cost) => cost * (0.5 + Math.max(0, dot(line.vector, c))) * Math.min(1.5, line.density / pace)
134
+ const kept = length > max ? fitLines(window, max, new Set([lines[i].id]), valueOf) : window
135
+ // A knapsack can drop the ending; trim back to the last finished sentence when there is one
136
+ const end = kept.findLastIndex(finished)
137
+ const story = end > 0 ? kept.slice(0, end + 1) : kept
138
+ const storyLength = story.reduce((sum, l) => sum + l.duration, 0)
139
+ if (storyLength < recipe.target.min || storyLength > max) continue
140
+ const candidate = { lines: story, duration: storyLength }
141
+ candidate.rubric = rubricOf(candidate, { target, pace })
142
+ candidate.score = total(candidate.rubric)
143
+ windows.push(candidate)
144
+ }
145
+ windows.sort((a, b) => b.score - a.score || a.lines[0].start - b.lines[0].start)
146
+ const chosen = []
147
+ const overlaps = (a, b) => a.lines[0].start <= b.lines.at(-1).end && b.lines[0].start <= a.lines.at(-1).end
148
+ for (const w of windows) {
149
+ if (chosen.length === count) break
150
+ if (!chosen.some((c) => overlaps(c, w))) chosen.push(w)
151
+ }
152
+ return chosen
153
+ }
154
+
155
+ /**
156
+ * The tournament (EDIT_LOOP §6 step 2): every pair meets once; a candidate takes the
157
+ * pair when it is ahead on more rubric criteria, then on the sum. Ranked by wins
158
+ * (Copeland), ties by the sum. F0 adds the compiled plan's own facts: a plan that
159
+ * doesn't compile, or has issues, gives up the criterion to one that does.
160
+ * @param {{ rubric: object, f0?: { issues: number, duration: number } }[]} candidates
161
+ * @returns {{ order: number[], wins: number[], pairs: { a: number, b: number, winner: number, ahead: string[] }[] }}
162
+ */
163
+ export function tournament(candidates) {
164
+ const criteria = (c) => ({ ...c.rubric, plan: c.f0 ? 1 / (1 + c.f0.issues) : 0 })
165
+ const wins = candidates.map(() => 0)
166
+ const pairs = []
167
+ for (let a = 0; a < candidates.length; a++) {
168
+ for (let b = a + 1; b < candidates.length; b++) {
169
+ const [x, y] = [criteria(candidates[a]), criteria(candidates[b])]
170
+ const aheadA = Object.keys(x).filter((k) => x[k] > y[k] + 1e-9)
171
+ const aheadB = Object.keys(x).filter((k) => y[k] > x[k] + 1e-9)
172
+ const winner = aheadA.length !== aheadB.length ? (aheadA.length > aheadB.length ? a : b) : total(x) >= total(y) ? a : b
173
+ wins[winner]++
174
+ pairs.push({ a, b, winner, ahead: winner === a ? aheadA : aheadB })
175
+ }
176
+ }
177
+ const order = candidates.map((_, i) => i).sort((i, j) => wins[j] - wins[i] || total(criteria(candidates[j])) - total(criteria(candidates[i])) || i - j)
178
+ return { order, wins, pairs }
179
+ }
180
+
181
+ /** The operations that cut `lines` into a 9:16 short on `project`. */
182
+ function cutOps(project, index, asset, lines, brief, recipe) {
183
+ const sequence = project.sequences.find((q) => q.id === project.active)
184
+ const base = new Set(sequence.tracks.filter((t) => t.role === "base").map((t) => t.id))
185
+ const ops = [
186
+ ...sequence.clips.filter((c) => base.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
187
+ { 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 } : {}) },
188
+ { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
189
+ ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...deliverableFor(brief) }]),
190
+ ]
191
+ for (const line of lines) for (const run of runsOf(line, recipe.joinGap)) ops.push({ op: "keep_range", asset, from: { word: run[0].id, edge: "start" }, to: { word: run.at(-1).id, edge: "end" } })
192
+ const step = apply(project, ops, { index, author: "agent" })
193
+ return { ops, step, base }
194
+ }
195
+
196
+ /**
197
+ * Plans the short as operations on `project`. The three candidates are compiled (F0)
198
+ * but never rendered; the tournament picks the one that is cut, reframed and dressed.
199
+ * @param {{ project: object, index: object, asset: string, brief?: object, variant?: { tighter?: number } }} input
200
+ * @returns {{ ops: object[], project: object, notes: string[], calls: number, slots: Record<string, string>, candidates: object[] }}
201
+ */
202
+ export function planShort({ project, index, asset, brief = {}, variant = {} }) {
203
+ const recipe = SHORT_FROM_LONG
204
+ const notes = []
205
+ const max = Math.round(recipe.target.max * (variant.tighter ?? 1))
206
+ const found = storySearch(index, asset, { max, target: brief.targetDuration ?? recipe.target.default })
207
+ if (!found.length) throw new Error(`No standalone story of ${recipe.target.min / FLICKS} to ${max / FLICKS} s was found in this recording.`)
208
+
209
+ // F0: each candidate's plan, compiled; nothing is rendered
210
+ for (const candidate of found) {
211
+ const { step } = cutOps(project, index, asset, candidate.lines, brief, recipe)
212
+ const plan = step.applied ? compile(step.project, index, { engineVersion: "f0", runtimeVersion: "f0" }) : null
213
+ candidate.f0 = plan ? { issues: plan.issues.length, duration: plan.duration } : undefined
214
+ }
215
+ const ranked = tournament(found)
216
+ const best = found[ranked.order[0]]
217
+ const summary = ranked.order.map((i, rank) => ({ rank: rank + 1, wins: ranked.wins[i], from: found[i].lines[0].id, to: found[i].lines.at(-1).id, seconds: Math.round(found[i].duration / FLICKS), plan: found[i].f0 ? { issues: found[i].f0.issues, seconds: Math.round(found[i].f0.duration / FLICKS) } : null, rubric: Object.fromEntries(Object.entries(found[i].rubric).map(([k, v]) => [k, Math.round(v * 100) / 100])) }))
218
+ notes.push(`Compared ${found.length} candidate stories in pairs on the rubric and picked the one from ${best.lines[0].id} to ${best.lines.at(-1).id}. The rubric ranks them for this video; it doesn't predict views.`)
219
+ const dropped = best.lines.slice(1).filter((l, i) => l.n !== best.lines[i].n + 1).length
220
+ if (dropped) notes.push(`Left out ${dropped === 1 ? "a line" : `${dropped} places`} inside the story to fit the length.`)
221
+
222
+ const { ops, step, base } = cutOps(project, index, asset, best.lines, brief, recipe)
223
+ if (!step.applied) throw new Error(`The short's cut was refused: ${step.diagnostics[0].message}`)
224
+
225
+ // Reframe to 9:16 on the face track (L8); the solver keeps the face box in and moves without whips (ET-SOL-03)
226
+ const facts = project.assets.find((a) => a.id === asset).facts
227
+ const cropWidth = Math.round((facts.height * recipe.canvas.width) / recipe.canvas.height)
228
+ const subject = (index.subjects?.[asset]?.length ?? 0) > 0
229
+ if (!subject) notes.push("No face track for this recording, so the frame holds the centre.")
230
+ const clips = step.project.sequences.find((q) => q.id === step.project.active).clips.filter((c) => base.has(c.track))
231
+ 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)) }))
232
+ const captions = LOOKS[brief.captions] ? best.lines.flatMap((l) => runsOf(l, recipe.joinGap)).flatMap((run) => pages(run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
233
+ const all = [...ops, ...framing, ...captions]
234
+ const done = apply(project, all, { index, author: "agent" })
235
+ if (!done.applied) throw new Error(`The short was refused: ${done.diagnostics[0].message}`)
236
+ return { ops: all, project: done.project, notes, calls: 0, slots: { story: "code" }, candidates: summary }
237
+ }
@@ -0,0 +1,137 @@
1
+ // `tutorial` (EDITOR_WORKFLOWS §3.2, §12 "zoom-to-click"): a screen recording becomes
2
+ // a tight 16:9 lesson. From the L9 screen track, code finds the actions (typing, a
3
+ // click that opens something), zooms smoothly into each, and shortens stretches where
4
+ // nothing moves and nobody speaks. "Thinking" stays when something happens on screen.
5
+ // No model call: every choice here is measured.
6
+
7
+ import { apply } from "../core/ops.js"
8
+
9
+ const FLICKS = 705_600_000
10
+
11
+ /** The recipe is data (ET-RCP-01): no command, path, URL, model or price. */
12
+ export const TUTORIAL = {
13
+ id: "tutorial",
14
+ canvas: { width: 1920, height: 1080 },
15
+ deliverable: { preset: "youtube-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"] },
16
+ thresholds: { lengthTolerance: 0.5 },
17
+ still: { longest: Math.round(1.5 * FLICKS), keep: Math.round(0.5 * FLICKS) }, // a still stretch over 1.5 s keeps 0.5 s
18
+ wordPad: Math.round(0.24 * FLICKS), // silence this close to a word is speech
19
+ zoom: { min: 1.25, max: 2, room: 1.8, lead: Math.round(0.4 * FLICKS), tail: Math.round(0.8 * FLICKS), merge: FLICKS, shortest: Math.round(1.2 * FLICKS), widest: 0.5, ease: "smooth" },
20
+ notes: "Recipe: a screen tutorial. Zoom where the action is; cut waiting, keep thinking while the screen moves.",
21
+ }
22
+
23
+ const union = (a, b) => {
24
+ const [x0, y0] = [Math.min(a.x, b.x), Math.min(a.y, b.y)]
25
+ return { x: x0, y: y0, w: Math.max(a.x + a.w, b.x + b.w) - x0, h: Math.max(a.y + a.h, b.y + b.h) - y0 }
26
+ }
27
+
28
+ /**
29
+ * Actions: runs of samples where a region changed, joined across short gaps while the
30
+ * region stays compact. A change wider than half the screen (a page load, a scroll)
31
+ * isn't an action to zoom into.
32
+ * @returns {{ start: number, end: number, box: object }[]} source flicks and pixels
33
+ */
34
+ export function findActions(track, { width, height }, recipe = TUTORIAL) {
35
+ const actions = []
36
+ const step = track.length > 1 ? track[1].t - track[0].t : FLICKS / 5
37
+ for (const sample of track) {
38
+ if (!sample.change) continue
39
+ const last = actions.at(-1)
40
+ const joined = last && sample.t - last.end <= recipe.zoom.merge ? union(last.box, sample.change) : null
41
+ if (joined && joined.w <= width * recipe.zoom.widest && joined.h <= height * recipe.zoom.widest) Object.assign(last, { end: sample.t, box: joined })
42
+ else actions.push({ start: sample.t - step, end: sample.t, box: sample.change })
43
+ }
44
+ return actions.filter((a) => a.box.w <= width * recipe.zoom.widest && a.box.h <= height * recipe.zoom.widest)
45
+ }
46
+
47
+ /**
48
+ * The ranges to keep: everything but the middle of still stretches. A sample is still
49
+ * when nothing changed and the cursor didn't move; a word (with its pad) is never still.
50
+ * @returns {{ from: number, to: number }[]} source flicks, in order
51
+ */
52
+ export function keptRanges(track, words, duration, recipe = TUTORIAL) {
53
+ const speaking = (from, to) => words.some((w) => w.start - recipe.wordPad < to && from < w.end + recipe.wordPad)
54
+ const step = track.length > 1 ? track[1].t - track[0].t : FLICKS / 5
55
+ const stills = []
56
+ let run = null
57
+ for (const sample of track) {
58
+ const still = !sample.change && !sample.cursor && !speaking(sample.t - step, sample.t)
59
+ if (still && run) run.to = sample.t
60
+ else if (still) run = { from: sample.t - step, to: sample.t }
61
+ else if (run) {
62
+ stills.push(run)
63
+ run = null
64
+ }
65
+ }
66
+ if (run) stills.push(run)
67
+ const ranges = []
68
+ let from = 0
69
+ for (const s of stills) {
70
+ if (s.to - s.from <= recipe.still.longest) continue
71
+ // keep half the allowance at each side, so the cut lands in the middle of the stillness
72
+ const [cutFrom, cutTo] = [s.from + recipe.still.keep / 2, s.to - recipe.still.keep / 2]
73
+ if (cutFrom > from) ranges.push({ from, to: cutFrom })
74
+ from = cutTo
75
+ }
76
+ if (duration > from) ranges.push({ from, to: duration })
77
+ return ranges
78
+ }
79
+
80
+ /** A zoom into `box`: scale so the box fills the frame with room, centre in thousandths. */
81
+ export function zoomFor(box, { width, height }, recipe = TUTORIAL) {
82
+ const scale = Math.min(recipe.zoom.max, width / (box.w * recipe.zoom.room), height / (box.h * recipe.zoom.room))
83
+ if (scale < recipe.zoom.min) return null
84
+ const at = (v, size) => Math.max(0, Math.min(1000, Math.round((v / size) * 1000)))
85
+ return { scale: Math.round(scale * 100) / 100, x: at(box.x + box.w / 2, width), y: at(box.y + box.h / 2, height) }
86
+ }
87
+
88
+ /**
89
+ * Plans the tutorial as operations on `project`.
90
+ * @param {{ project: object, index: object, asset: string, track: object[], brief?: object }} input
91
+ * track: L9 samples (index/layers/screen.js) for the asset
92
+ * @returns {{ ops: object[], project: object, notes: string[], calls: number, slots: Record<string, string>, zooms: object[] }}
93
+ */
94
+ export function planTutorial({ project, index, asset, track, brief = {} }) {
95
+ const recipe = TUTORIAL
96
+ const notes = []
97
+ const facts = project.assets.find((a) => a.id === asset).facts
98
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
99
+ const ranges = keptRanges(track, words, facts.duration, recipe)
100
+ const saved = facts.duration - ranges.reduce((sum, r) => sum + r.to - r.from, 0)
101
+ if (saved > 0) notes.push(`Shortened ${track.length ? "still stretches" : "nothing"}: ${(saved / FLICKS).toFixed(1)} s of waiting cut, ${(recipe.still.keep / FLICKS).toFixed(1)} s kept at each.`)
102
+
103
+ const sequence = project.sequences.find((q) => q.id === project.active)
104
+ const base = new Set(sequence.tracks.filter((t) => t.role === "base").map((t) => t.id))
105
+ const ops = [
106
+ ...sequence.clips.filter((c) => base.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
107
+ { op: "set_brief", format: recipe.id, targetDuration: brief.targetDuration ?? ranges.reduce((sum, r) => sum + r.to - r.from, 0), mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
108
+ { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
109
+ ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...recipe.deliverable }]),
110
+ ...ranges.map((r) => ({ op: "keep_range", asset, from: r.from, to: r.to })),
111
+ ]
112
+ const cut = apply(project, ops, { index, author: "agent" })
113
+ if (!cut.applied) throw new Error(`The tutorial's cut was refused: ${cut.diagnostics[0].message}`)
114
+
115
+ // Zooms: anchored to the clip that plays the action, so they follow later edits
116
+ const clips = cut.project.sequences.find((q) => q.id === cut.project.active).clips.filter((c) => base.has(c.track) && c.source?.asset === asset)
117
+ const zooms = []
118
+ const frame = { width: facts.width, height: facts.height }
119
+ for (const action of findActions(track, frame, recipe)) {
120
+ const zoom = zoomFor(action.box, frame, recipe)
121
+ const clip = clips.find((c) => c.source.in <= action.start + recipe.zoom.lead && action.start < c.source.out)
122
+ if (!zoom || !clip) continue
123
+ const from = Math.max(clip.source.in, action.start - recipe.zoom.lead)
124
+ const to = Math.min(clip.source.out, Math.max(action.end + recipe.zoom.tail, from + recipe.zoom.shortest))
125
+ if (to - from < recipe.zoom.shortest / 2) continue
126
+ const last = zooms.at(-1)
127
+ if (last && last.clip === clip.id && from <= last.to) continue // one zoom at a time
128
+ zooms.push({ clip: clip.id, from, to, ...zoom, box: action.box })
129
+ }
130
+ const punches = zooms.map((z) => ({ op: "punch_in", at: { clip: z.clip, edge: "start", offset: z.from - clips.find((c) => c.id === z.clip).source.in }, duration: z.to - z.from, scale: z.scale, x: z.x, y: z.y, ease: recipe.zoom.ease }))
131
+ if (zooms.length) notes.push(`Zoomed in on ${zooms.length} action${zooms.length === 1 ? "" : "s"} on screen.`)
132
+ else notes.push("Found no compact action on screen to zoom into.")
133
+ const all = [...ops, ...punches]
134
+ const done = apply(project, all, { index, author: "agent" })
135
+ if (!done.applied) throw new Error(`The tutorial was refused: ${done.diagnostics[0].message}`)
136
+ return { ops: all, project: done.project, notes, calls: 0, slots: {}, zooms }
137
+ }
@@ -0,0 +1,155 @@
1
+ // `youtube-longform` (EDITOR_WORKFLOWS §3.2, §10): an A-roll talk of 8 to 20+ minutes
2
+ // becomes a paced, chaptered YouTube cut. Code does all of it, with no model call:
3
+ // the story tree (PERCEPTION_AND_INDEX §8) gives scenes; each scene keeps its best
4
+ // takes with fillers and long pauses out; retention pacing changes the picture at the
5
+ // recipe's rate (faster in the intro), with punch-ins and B-roll; chapters come from
6
+ // the scenes; captions go out as a sidecar (SRT), not burned. Other tracks (music,
7
+ // effects) are left as they are, so the audio layout stays on its buses.
8
+
9
+ import { apply } from "../core/ops.js"
10
+ import { solve } from "../core/solver.js"
11
+ import { LOOKS, pages } from "../engine/captions.js"
12
+ import { chapterList, chapters, storyTree } from "../index/story.js"
13
+ import { candidateLines, fitLines, runsOf } from "./reel.js"
14
+
15
+ const FLICKS = 705_600_000
16
+ const MINUTE = 60 * FLICKS
17
+
18
+ /** The recipe is data (ET-RCP-01): no command, path, URL, model or price. */
19
+ export const YOUTUBE_LONGFORM = {
20
+ id: "youtube-longform",
21
+ target: { min: 8 * MINUTE, max: 40 * MINUTE, default: 15 * MINUTE },
22
+ canvas: { width: 1920, height: 1080 },
23
+ deliverable: { preset: "youtube-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.1 },
25
+ pace: { every: 12 * FLICKS, intro: 0.5, close: 0.8 }, // the longest a picture holds; the intro twice as fast, the close a little faster
26
+ punch: { scale: 1.12 },
27
+ broll: { length: 4 * FLICKS },
28
+ endScreen: 20 * FLICKS,
29
+ joinGap: Math.round(0.7 * FLICKS),
30
+ captions: "clean",
31
+ notes: "Recipe: a long YouTube video from a talk. Every scene keeps its point; the picture changes often enough to hold attention; chapters follow the story.",
32
+ }
33
+
34
+ /** Where each kept word plays on the timeline (pieces at their own speed). */
35
+ function wordTimes(timeline, index, asset) {
36
+ const words = index.words.filter((w) => w.asset === asset)
37
+ const times = new Map()
38
+ for (const piece of timeline.picture) {
39
+ if (piece.asset !== asset || piece.hold) continue
40
+ const rate = piece.speed.d / piece.speed.n
41
+ for (const w of words) if (w.start >= piece.in && w.start < piece.out && !times.has(w.id)) times.set(w.id, Math.round(piece.at + (w.start - piece.in) * rate))
42
+ }
43
+ return times
44
+ }
45
+
46
+ /** Times on the timeline where the picture changes: cuts, punch-ins, B-roll. */
47
+ export function pictureChanges(timeline) {
48
+ return [...new Set([0, ...timeline.picture.map((p) => p.at), ...timeline.zooms.flatMap((z) => [z.at, z.end]), ...timeline.overlays.flatMap((o) => [o.at, o.end]), timeline.duration])].sort((a, b) => a - b)
49
+ }
50
+
51
+ // Words in groups no longer than `every`, for a punch-in on every other group
52
+ function chunks(words, every) {
53
+ const out = [[]]
54
+ for (const w of words) {
55
+ if (out.at(-1).length && w.end - out.at(-1)[0].start > every) out.push([])
56
+ out.at(-1).push(w)
57
+ }
58
+ return out
59
+ }
60
+
61
+ /**
62
+ * Plans the long cut as operations on `project` (its assets and other tracks stay; the
63
+ * base cut is replaced).
64
+ * @param {{ project: object, index: object, asset: string, broll?: string[], brief?: object, cache?: Map<string, any> }} input
65
+ * @returns {{ ops: object[], project: object, notes: string[], calls: number, tree: object, chapters: object[], chapterList: string, endScreen: { at: number, end: number } | null, pace: { every: number, longest: number, flat: { at: number, end: number }[] } }}
66
+ */
67
+ export function planLongform({ project, index, asset, broll = [], brief = {}, cache, recipe = YOUTUBE_LONGFORM }) {
68
+ const notes = []
69
+ const tree = storyTree(index, asset, { cache })
70
+ if (!tree.scenes.length) throw new Error("This recording has no transcript to cut from.")
71
+ const sceneOf = new Map(tree.scenes.flatMap((scene, n) => scene.children.flatMap((id) => tree.beats.find((b) => b.id === id).sentences.map((s) => [s, n]))))
72
+
73
+ // Every scene keeps its best takes; over the limit, the lines worth least go, never a scene's opener
74
+ const all = candidateLines(index, asset).filter((l) => sceneOf.has(l.id))
75
+ const lengthOf = (list) => list.reduce((sum, l) => sum + runsOf(l, recipe.joinGap).reduce((s, run) => s + run.at(-1).end - run[0].start, 0), 0)
76
+ const limit = brief.targetDuration ?? recipe.target.max
77
+ // Each scene's share of the length stays as it was, so no scene is cut to nothing
78
+ const total = lengthOf(all)
79
+ const lines = total <= limit ? all : tree.scenes.flatMap((_, n) => {
80
+ const own = all.filter((l) => sceneOf.get(l.id) === n)
81
+ return own.length ? fitLines(own, Math.floor((limit * lengthOf(own)) / total), new Set([own[0].id])) : []
82
+ })
83
+ if (lines.length < all.length) notes.push(`Left out ${all.length - lines.length} of ${all.length} lines to fit ${Math.round(limit / MINUTE)} minutes; every scene keeps its opening.`)
84
+ const kept = lengthOf(lines)
85
+ if (kept < recipe.target.min) notes.push(`The talk has ${(kept / MINUTE).toFixed(1)} minutes worth keeping, under this recipe's ${recipe.target.min / MINUTE}; nothing is padded.`)
86
+
87
+ const sequence = project.sequences.find((q) => q.id === project.active)
88
+ const base = new Set(sequence.tracks.filter((t) => t.role === "base").map((t) => t.id))
89
+ const runs = lines.flatMap((line) => runsOf(line, recipe.joinGap).map((words) => ({ words, scene: sceneOf.get(line.id) })))
90
+ const ops = [
91
+ ...sequence.clips.filter((c) => base.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
92
+ { op: "set_brief", format: recipe.id, targetDuration: brief.targetDuration ?? kept, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
93
+ { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
94
+ ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...recipe.deliverable }]),
95
+ ...runs.map(({ words }) => ({ op: "keep_range", asset, from: { word: words[0].id, edge: "start" }, to: { word: words.at(-1).id, edge: "end" } })),
96
+ ]
97
+ const cut = apply(project, ops, { index, author: "agent" })
98
+ if (!cut.applied) throw new Error(`The long cut was refused: ${cut.diagnostics[0].message}`)
99
+
100
+ // Chapters from the scenes, at the first word each scene plays
101
+ const cutTimeline = solve(cut.project, index)
102
+ // With no length asked for, the target is the cut itself, pads included
103
+ if (brief.targetDuration === undefined) ops.find((op) => op.op === "set_brief").targetDuration = cutTimeline.duration
104
+ const times = wordTimes(cutTimeline, index, asset)
105
+ const sentences = new Map(index.sentences.map((s) => [s.id, s]))
106
+ const words = index.words.filter((w) => w.asset === asset)
107
+ const position = new Map(words.map((w, i) => [w.id, i]))
108
+ const firstPlayed = (id) => {
109
+ const s = sentences.get(id)
110
+ return words.slice(position.get(s.firstWord), position.get(s.lastWord) + 1).find((w) => times.has(w.id)) ?? null
111
+ }
112
+ const found = chapters(tree, (id) => times.get(firstPlayed(id)?.id) ?? null, { duration: cutTimeline.duration })
113
+ if (found.note) notes.push(found.note)
114
+ const atWord = new Map([...times].map(([id, t]) => [t, id]))
115
+ for (const chapter of found.chapters) {
116
+ // On the scene's first played word, so it follows a later trim; 00:00 is the start itself
117
+ ops.push({ op: "mark", name: chapter.title, at: chapter.at === 0 ? 0 : { word: atWord.get(chapter.at), edge: "start" } })
118
+ }
119
+
120
+ // Retention pacing: every cut is a change; inside a long run, a punch-in on every other stretch
121
+ const every = (scene) => recipe.pace.every * (scene === 0 ? recipe.pace.intro : scene === tree.scenes.length - 1 ? recipe.pace.close : 1)
122
+ for (const run of runs) {
123
+ chunks(run.words, every(run.scene)).forEach((group, i) => {
124
+ if (i % 2 === 1) ops.push({ op: "punch_in", at: { word: group[0].id, edge: "start" }, until: { word: group.at(-1).id, edge: "end" }, scale: recipe.punch.scale })
125
+ })
126
+ }
127
+ // B-roll on each scene's second line, after its opener has set the scene
128
+ if (broll.length) {
129
+ let next = 0
130
+ for (let scene = 1; scene < tree.scenes.length; scene++) {
131
+ const second = runs.filter((r) => r.scene === scene)[1]
132
+ if (!second) continue
133
+ const id = broll[next++ % broll.length]
134
+ const length = Math.min(recipe.broll.length, project.assets.find((a) => a.id === id).facts.duration ?? recipe.broll.length)
135
+ ops.push({ op: "place_broll", asset: id, at: { word: second.words[0].id, edge: "start" }, in: 0, out: length })
136
+ }
137
+ }
138
+ // Captions as a sidecar: YouTube takes the SRT; nothing is burned in
139
+ const look = brief.captions === false ? null : LOOKS[brief.captions] ? brief.captions : recipe.captions
140
+ if (look) for (const run of runs) for (const ids of pages(run.words)) ops.push({ op: "caption_style", look, words: ids })
141
+
142
+ const done = apply(project, ops, { index, author: "agent" })
143
+ if (!done.applied) throw new Error(`The long cut was refused: ${done.diagnostics[0].message}`)
144
+ const timeline = solve(done.project, index)
145
+
146
+ const changes = pictureChanges(timeline)
147
+ const gaps = changes.slice(1).map((t, i) => ({ at: changes[i], end: t }))
148
+ const longest = Math.max(0, ...gaps.map((g) => g.end - g.at))
149
+ const flat = gaps.filter((g) => g.end - g.at > recipe.pace.every * 1.5)
150
+ notes.push(`${tree.scenes.length} scenes from the story tree; ${runs.length} cuts; the picture changes at least every ${Math.round(longest / FLICKS)} s${flat.length ? `, except ${flat.length} flat stretch${flat.length === 1 ? "" : "es"}` : ""}.`)
151
+ if (found.chapters.length) notes.push(`Chapters for the description:\n${chapterList(found.chapters)}`)
152
+ const endScreen = timeline.duration >= recipe.endScreen + 5 * FLICKS ? { at: timeline.duration - recipe.endScreen, end: timeline.duration } : null
153
+ if (endScreen) notes.push(`The last ${recipe.endScreen / FLICKS} s are the end-screen slot; keep cards clear of it.`)
154
+ return { ops, project: done.project, notes, calls: 0, tree, chapters: found.chapters, chapterList: chapterList(found.chapters), endScreen, pace: { every: recipe.pace.every, longest, flat } }
155
+ }