@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
@@ -5,10 +5,14 @@
5
5
 
6
6
  import { apply } from "../core/ops.js"
7
7
  import { solve } from "../core/solver.js"
8
- import { cleanGraphic, GRAPHIC_BLOCK, GRAPHIC_KINDS, GRAPHIC_VERSION, graphicLength, SUBTITLE_MAX, TEXT_MAX } from "../engine/graphics.js"
8
+ import { ALL_GRAPHIC_KINDS, cleanGraphic, GRAPHIC_BLOCK, GRAPHIC_KINDS, GRAPHIC_VERSION, graphicLength, STEP_MAX, STEPS_MAX, SUBTITLE_MAX, TEXT_MAX } from "../engine/graphics.js"
9
+ import { ALL_LOOKS } from "../engine/captions.js"
9
10
  import { paperEdit, shotDigest } from "../index/views.js"
10
11
  import { TRANSITION_LABELS, transitionLength, TRANSITIONS } from "../core/transitions.js"
11
12
  import { brandIn, graphicProblems } from "./graphics.js"
13
+ import { withoutPlaces } from "./mentions.js"
14
+ import { grounded, tidyIntent } from "./intent.js"
15
+ import { EFFECTS as FX, MOVES } from "../core/effects.js"
12
16
 
13
17
  const FLICKS = 705_600_000
14
18
 
@@ -106,6 +110,84 @@ const ITEMS = OPS_SCHEMA.properties.ops.items
106
110
  const MOTION_SCHEMA = { ...OPS_SCHEMA, properties: { ...OPS_SCHEMA.properties, ops: { ...OPS_SCHEMA.properties.ops, items: { ...ITEMS, properties: { ...ITEMS.properties, op: { type: "string", enum: [...CONSOLE_OPS, "add_graphic", "transition"] }, kind: { type: "string", enum: [...Object.keys(GRAPHIC_KINDS), ...Object.keys(TRANSITIONS)] }, style: { type: "string", maxLength: 16 }, subtitle: { type: "string", maxLength: SUBTITLE_MAX } } } } } }
107
111
  export const consoleSchema = (motion) => (motion ? MOTION_SCHEMA : OPS_SCHEMA)
108
112
 
113
+ /** With editing.craft on (TP5), chat may also add a registry effect or a named move; off, `base` is returned as it is. */
114
+ export function craftSchema(base, craft) {
115
+ if (!craft) return base
116
+ const items = base.properties.ops.items
117
+ return { ...base, properties: { ...base.properties, ops: { ...base.properties.ops, items: { ...items, properties: { ...items.properties, op: { type: "string", enum: [...items.properties.op.enum, "add_effect", "add_adjustment", "remove_effect"] }, effect: { type: "string", enum: Object.keys(FX) }, params: { type: "object", additionalProperties: { type: "number" } }, move: { type: "string", enum: Object.keys(MOVES) } } } } } }
118
+ }
119
+ /** With editing.typeKit on (TP7), chat may also use the fourteen caption looks and motion kit 2; off, `base` is returned as it is. */
120
+ export function typeKitSchema(base, typeKit) {
121
+ if (!typeKit) return base
122
+ const items = base.properties.ops.items
123
+ const kinds = items.properties.kind ? { kind: { type: "string", enum: Object.keys(ALL_GRAPHIC_KINDS) }, steps: { type: "array", maxItems: STEPS_MAX, items: { type: "string", maxLength: STEP_MAX } } } : {}
124
+ return { ...base, properties: { ...base.properties, ops: { ...base.properties.ops, items: { ...items, properties: { ...items.properties, look: { type: "string", enum: Object.keys(ALL_LOOKS) }, ...kinds } } } } }
125
+ }
126
+ /**
127
+ * TP9 (CRAFT_UPGRADE §7): with editing.customMotion on, chat may ask for a custom animation
128
+ * (`custom_motion`, written afterwards by code's own slot, director/custom-motion.js); with a box drawn
129
+ * on the frame, it may act on it (`use_mark`). Neither, and `base` is returned as it is.
130
+ */
131
+ export function pointingSchema(base, { customMotion = false, mark = false } = {}) {
132
+ if (!customMotion && !mark) return base
133
+ const items = base.properties.ops.items
134
+ const ops = [...items.properties.op.enum, ...(customMotion ? ["custom_motion"] : []), ...(mark ? ["use_mark"] : [])]
135
+ return { ...base, properties: { ...base.properties, ops: { ...base.properties.ops, items: { ...items, properties: { ...items.properties, op: { type: "string", enum: ops }, ...(customMotion ? { reuse: ID } : {}), ...(mark ? { use: { type: "string", enum: MARK_USES } } : {}) } } } } }
136
+ }
137
+ export const MARK_USES = ["callout", "blur", "zoom", "mask"]
138
+ export const CUSTOM_MOTION_PROMPT = "Only for an animation that no kit graphic and no operation above can make (a logo that spins, a shape that draws itself, an animated diagram), custom_motion with text: what to animate, in the person's words, at (a word anchor) and duration only if they said how long. Code has it written, checks it and shows it to the person to approve. To place a saved custom animation again, custom_motion with reuse: its clip id, and at. At most one custom_motion."
139
+ const MARK_KINDS = { box: "box", ring: "ring", arrow: "arrow" }
140
+
141
+ /** Where a drawn box is, in words a model reads (code alone knows its numbers). */
142
+ export function markView(mark) {
143
+ const across = mark.x + mark.w / 2 < 333 ? "left" : mark.x + mark.w / 2 > 667 ? "right" : "centre"
144
+ const down = mark.y + mark.h / 2 < 333 ? "top" : mark.y + mark.h / 2 > 667 ? "bottom" : "middle"
145
+ const share = Math.round((mark.w * mark.h) / 10_000)
146
+ return `The person drew a ${MARK_KINDS[mark.kind] ?? "box"} on the frame at ${clock(mark.at)}, in the ${down} ${across}, about ${share}% of the frame. "This", "here", "that" or "it" means what they drew. To act on it, use_mark with use: callout (mark it; an optional short label in text, the speaker's or the person's own words), blur (blur what is inside it), zoom (zoom in on it) or mask (darken everything else); duration in flicks only if they said how long. Code places it exactly where they drew: never give coordinates.`
147
+ }
148
+
149
+ /**
150
+ * `use_mark` as Edit Core operations, placed by code at the drawn box (TP9): a callout round it, a blur
151
+ * or a mask in it over the shot (from the moment drawn to the end of its piece), or a punch-in centred on
152
+ * it. The model chose what to do; the numbers are the person's drawing.
153
+ * @returns {{ ops: object[], problems: string[] }}
154
+ */
155
+ export function expandMark(ops, { mark, project, index, person }) {
156
+ const problems = []
157
+ if (!ops.some((op) => op?.op === "use_mark")) return { ops, problems }
158
+ const { picture, duration: length } = solve(project, index)
159
+ const piece = picture.find((p) => mark.at >= p.at && mark.at < p.end)
160
+ const spoken = (index.words ?? []).map((w) => w.text).join(" ")
161
+ const region = { x: mark.x, y: mark.y, w: mark.w, h: mark.h }
162
+ // How long: what was asked, else the rest of the shot (capped), never past the cut's end; half a second at least
163
+ const span = (op, fallback) => Math.max(FLICKS / 2, Math.min(Number.isInteger(op.duration) ? op.duration : fallback, length - mark.at))
164
+ const rest = piece ? piece.end - mark.at : 3 * FLICKS
165
+ const out = ops.map((op, i) => {
166
+ if (op?.op !== "use_mark") return op
167
+ if (!MARK_USES.includes(op.use)) return problems.push(`operation ${i + 1}: use is one of ${MARK_USES.join(", ")}`), op
168
+ if (mark.at >= length) return problems.push(`operation ${i + 1}: the box was drawn past the end of the cut`), op
169
+ if (op.use === "callout") {
170
+ const graphic = cleanGraphic({ kind: "callout", style: MARK_KINDS[mark.kind] ?? "box", text: op.text ?? "", mark: region, ...brandIn(person) }, ALL_GRAPHIC_KINDS)
171
+ if (!graphic) return problems.push(`operation ${i + 1}: that label can't be a callout's`), op
172
+ const said = graphic.text ? graphicProblems(graphic, { spoken, near: spoken, person }) : []
173
+ if (said.length) return problems.push(`operation ${i + 1}: ${said[0]}; a callout's label is the speaker's or the person's own words`), op
174
+ return { op: "add_motion", block: GRAPHIC_BLOCK, version: GRAPHIC_VERSION, variables: graphic, at: mark.at, duration: span(op, 3 * FLICKS) }
175
+ }
176
+ if (op.use === "zoom") {
177
+ // Fit the drawn box in the frame, a little room round it, between 1.1× and 3×
178
+ const scale = Math.round(Math.min(3, Math.max(1.1, 0.9 * Math.min(1000 / mark.w, 1000 / mark.h))) * 100) / 100
179
+ return { op: "punch_in", at: mark.at, duration: span(op, Math.min(rest, 3 * FLICKS)), scale, ease: "smooth", x: Math.round(mark.x + mark.w / 2), y: Math.round(mark.y + mark.h / 2) }
180
+ }
181
+ const effect = op.use === "blur" ? { effect: "blur", params: { amount: 20 } } : { effect: "mask" }
182
+ return { op: "add_adjustment", at: mark.at, duration: span(op, Math.min(rest, 30 * FLICKS)), ...effect, region }
183
+ })
184
+ return { ops: out, problems }
185
+ }
186
+
187
+ export const TYPE_KIT_PROMPT = `Caption looks for caption_style: ${Object.keys(ALL_LOOKS).join(", ")}. With add_graphic you may also use ${Object.entries(ALL_GRAPHIC_KINDS).filter(([id]) => !GRAPHIC_KINDS[id]).map(([id, kind]) => `${id}: ${kind.label.toLowerCase()}`).join("; ")}; a list's lines go in \`steps\`, each the speaker's own words; a handle or call to action only in words the person typed.`
188
+
189
+ export const CRAFT_PROMPT = `To put an effect on a clip, add_effect with clip, effect (${Object.entries(FX).map(([id, row]) => `${id}: ${row.label.toLowerCase()}`).join("; ")}) and only the values the person asks for in params; over a stretch of the cut, add_adjustment with at (a word anchor), until or duration, and effect; remove_effect with clip and effect. For a change over time, pick a named move instead of numbers: ${Object.entries(MOVES).map(([id, m]) => `${id} (${m.effect}: ${m.label})`).join("; ")}. Add an effect only when the person asks for it.`
190
+
109
191
  /**
110
192
  * `add_graphic` as the engine's own operation: the graphic cleaned, its words held to the
111
193
  * speaker's and the person's, its length set by code. Every other operation passes through.
@@ -113,14 +195,14 @@ export const consoleSchema = (motion) => (motion ? MOTION_SCHEMA : OPS_SCHEMA)
113
195
  * @param {{ index: object, person: string }} context person: the person's own messages
114
196
  * @returns {{ ops: object[], problems: string[] }}
115
197
  */
116
- export function expandGraphics(ops, { index, person }) {
198
+ export function expandGraphics(ops, { index, person, kinds = GRAPHIC_KINDS }) {
117
199
  const problems = []
118
200
  const spoken = (index.words ?? []).map((w) => w.text).join(" ")
119
201
  const out = ops.map((op, i) => {
120
202
  // A transition's length is code's: the default, or what was asked, inside the allowed range
121
203
  if (op?.op === "transition") return Object.hasOwn(TRANSITIONS, op.kind ?? "") ? { op: "transition", clip: op.clip, kind: op.kind, duration: transitionLength(op.duration) } : (problems.push(`operation ${i + 1}: a transition's kind is one of ${Object.keys(TRANSITIONS).join(", ")}`), op)
122
204
  if (op?.op !== "add_graphic") return op
123
- const graphic = cleanGraphic({ ...op, ...brandIn(person), at: undefined })
205
+ const graphic = cleanGraphic({ ...op, ...brandIn(person), at: undefined }, kinds)
124
206
  if (!graphic) return problems.push(`operation ${i + 1}: that isn't a graphic the kit draws (a "stat" is digits; text is up to ${TEXT_MAX} characters)`), op
125
207
  if (op.at === undefined) return problems.push(`operation ${i + 1}: add_graphic needs \`at\`, a word anchor or a clip edge`), op
126
208
  const said = graphicProblems(graphic, { spoken, near: spoken, person })
@@ -204,7 +286,9 @@ export function describe(op, index) {
204
286
  case "add_title":
205
287
  return `Added the title "${op.text}" at ${place(op.at)}`
206
288
  case "add_motion":
207
- if (op.block === GRAPHIC_BLOCK) return `Added ${/^[aeiou]/i.test(GRAPHIC_KINDS[op.variables?.kind]?.label ?? "g") ? "an" : "a"} ${(GRAPHIC_KINDS[op.variables?.kind]?.label ?? "graphic").toLowerCase()} "${op.variables?.text ?? ""}"${op.variables?.subtitle ? `, "${op.variables.subtitle}"` : ""} at ${place(op.at)}`
289
+ if (op.block === "custom") return `Added a custom animation${op.variables?.name ? ` "${op.variables.name}"` : ""} at ${place(op.at)}`
290
+ if (op.block === GRAPHIC_BLOCK && op.variables?.mark) return `Marked what you drew with a ${op.variables.style ?? "box"} callout${op.variables.text ? `, "${op.variables.text}"` : ""}, at ${place(op.at)} for ${seconds(op.duration ?? 0)}`
291
+ if (op.block === GRAPHIC_BLOCK) return `Added ${/^[aeiou]/i.test(ALL_GRAPHIC_KINDS[op.variables?.kind]?.label ?? "g") ? "an" : "a"} ${(ALL_GRAPHIC_KINDS[op.variables?.kind]?.label ?? "graphic").toLowerCase()} "${op.variables?.text ?? ""}"${op.variables?.subtitle ? `, "${op.variables.subtitle}"` : ""} at ${place(op.at)}`
208
292
  return op.block === "scene" ? `Added an animated ${op.variables?.kind ?? ""} scene, "${op.variables?.text ?? ""}", at ${place(op.at)}` : op.op
209
293
  case "grade":
210
294
  return `Graded ${op.clip}${op.saturation !== undefined ? `, saturation ${op.saturation}` : ""}${op.gain !== undefined ? `, contrast ${op.gain}` : ""}${op.gamma !== undefined ? `, gamma ${op.gamma}` : ""}${op.lift !== undefined ? `, lift ${op.lift}` : ""}`
@@ -220,6 +304,10 @@ export function describe(op, index) {
220
304
  return `Cleaned the background noise out of ${op.clip}'s voice`
221
305
  case "set_level":
222
306
  return `Set ${op.clip} to ${op.db} dB`
307
+ case "add_adjustment":
308
+ // TP9: only a drawn region has words here; any other adjustment reads as it always did
309
+ if (op.region) return `${op.effect === "mask" ? "Darkened everything but" : "Blurred"} what you drew, from ${place(op.at)} for ${seconds(op.duration ?? 0)}`
310
+ return op.op
223
311
  case "add_deliverable":
224
312
  return `Set up the export: ${op.size?.width ?? "?"}×${op.size?.height ?? "?"}${op.loudness ? `, mastered to ${op.loudness.lufs} LUFS` : ""}${op.burnCaptions ? ", captions burned in" : ""}`
225
313
  default:
@@ -291,7 +379,8 @@ const UNIT = "(?:s|sec\\w*|se?c?o?n?d?s?\\b)(?![a-z])"
291
379
  * @returns {{ at: number, to?: number }[]} in flicks
292
380
  */
293
381
  export function timesIn(text, { duration = null } = {}) {
294
- const said = String(text)
382
+ // A mention's place (⟦1⟧, TP1) is never a time; without one this is the text as it was
383
+ const said = withoutPlaces(text)
295
384
  // Relative stretches first: "the first 5 seconds", "the last 5 s" (needs the cut's length)
296
385
  const relative = []
297
386
  for (const m of said.matchAll(new RegExp(`\\b(first|last|final|opening)\\s+(\\d+(?:\\.\\d+)?)\\s*${UNIT}`, "gi"))) {
@@ -373,18 +462,22 @@ export function timesView(text, project, index) {
373
462
  * @param {{ ask: ReturnType<import("./ask.js").createAsk>, project: object, index: object, text: string, selection?: object, signal?: AbortSignal }} input
374
463
  * @returns {Promise<{ ops: object[], changes: string[], project: object | null, source: string, reason?: string, calls: number }>}
375
464
  */
376
- export async function revise({ ask, project, index, text, selection, history = [], motion = false, signal }) {
465
+ export async function revise({ ask, project, index, text, selection, history = [], motion = false, pointed = "", intent = false, craft = false, typeKit = false, customMotion = false, mark = null, customBlocks = [], signal }) {
377
466
  const assets = project.assets.map((a) => a.id)
378
467
  // A marked range reads like a typed one: code says what it points at
379
468
  const marked = Number.isInteger(selection?.from) && Number.isInteger(selection?.to) ? ` from ${clock(selection.from)} to ${clock(selection.to)}` : ""
380
469
  const times = timesView(`${text}${marked}`, project, index)
381
470
  const bin = `Footage in the project: ${project.assets.filter((a) => ["video", "audio"].includes(a.kind)).map((a) => `${a.id} (${a.kind}, ${seconds(a.facts.duration ?? 0)})`).join(", ")}`
382
- const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), clipsView(project, index), bin, selectionText(selection, index), times].filter(Boolean).join("\n\n")
471
+ // pointed: the clips the person mentioned (mentions.js), fenced as data; empty, the view is what it was
472
+ // TP9: a drawn box and the saved custom animations, only when there are any; else the view is what it was
473
+ const saved = customMotion && customBlocks.length ? `Saved custom animations: ${customBlocks.map((b) => `${b.clip}${b.name ? ` ${JSON.stringify(b.name)}` : ""}`).join(", ")}` : ""
474
+ const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), clipsView(project, index), bin, selectionText(selection, index), times, pointed, saved, mark ? markView(mark) : ""].filter(Boolean).join("\n\n")
383
475
  // The last turns of this chat, so "shorter" or "no, the other one" mean something. The
384
476
  // person's lines are theirs; Kriya's are what it said before, not instructions
385
477
  const earlier = history.length ? `Earlier in this chat:\n${history.map((h) => `${h.who === "you" ? "Person" : "Kriya"}: ${JSON.stringify(h.text)}`).join("\n")}\n\n` : ""
386
478
  const request = [
387
479
  `${earlier}The person asks (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
480
+ ...(pointed ? ["A place like ⟦1⟧ in their words is a clip they pointed at; the list above says which asset each is. Use that asset id."] : []),
388
481
  "Answer with JSON only. Put in `ops` the operations that do exactly what they ask, and nothing else.",
389
482
  "Times like 0:05 are on the cut's timeline; the lines above say which clip, words and captions each time points at. Use those ids, never compute flicks yourself. To take out a stretch the person names by time, use the exact remove_range given for it above, unchanged; for a stretch named by words, remove_range from its first word (edge start) to its last word (edge end). To change what a caption says, caption_edit with its caption id; to remove a caption, ripple_delete its caption id; to caption words, caption_style with their word ids and a look; to put a title on screen, add_title with text and a word anchor; to take background noise out of the voice, clean_voice on each picture clip; to warm or cool the picture, grade with temperature (lower is warmer, 6500 neutral), vibrance or vignette; for a speed ramp or slow motion, speed_ramp on the clip with from and to (source flicks from the lines above, or word anchors) and peak {n, d} (2/1 speeds up and back, 1/2 is eased slow motion); for a constant speed, speed; to lay other footage over a moment, place_broll with a video asset id from the project, at a word anchor or clip edge, and duration in flicks.",
390
483
  ...(motion ? [`To put a motion graphic on screen, add_graphic with kind (${Object.entries(GRAPHIC_KINDS).map(([id, kind]) => `${id}: ${kind.label.toLowerCase()}`).join("; ")}), text, subtitle where the kind has a second line, and at (a word anchor). Its words must be the speaker's or the person's own from their request, never yours; a stat's text is digits the speaker says.`, `To dress a cut, transition with the clip the picture arrives in (never the first clip) and kind (${Object.keys(TRANSITIONS).join(", ")}); the cut itself doesn't move.`] : []),
@@ -392,11 +485,32 @@ export async function revise({ ask, project, index, text, selection, history = [
392
485
  "If they ask to fix or correct the transcript (names, misheard words), put each wrong word in `corrections` as {word: its id, text: the right word}, only where you are confident from the context.",
393
486
  "If they ask for the whole video to be made, directed, edited or improved (not one part of it), set `direct` to an object (with `seconds` and a caption look if they say so) and leave `ops` empty: the Director makes the whole cut.",
394
487
  'If none of these can do it, answer {"ops": []}.',
488
+ // editing.intent (TP4): nothing they asked is lost; off, the request is the text it was
489
+ ...(craft ? [CRAFT_PROMPT] : []),
490
+ ...(typeKit ? [TYPE_KIT_PROMPT] : []),
491
+ ...(customMotion ? [CUSTOM_MOTION_PROMPT] : []),
492
+ ...(intent ? ["Also put in `cannot` every piece of their request these operations can't do: their exact words as `evidence`, copied as written, and the nearest thing you can do as `nearest` if there is one. Empty when everything is done."] : []),
395
493
  ].join("\n")
396
494
  const words = new Map((index.words ?? []).map((w) => [w.id, w]))
397
495
  // Operations must apply; a correction on an unknown word is only dropped, never worth a second call
398
496
  const person = [...history.filter((h) => h.who === "you").map((h) => h.text), text].join("\n")
399
- const expand = (ops) => (motion ? expandGraphics(ops, { index, person }) : { ops, problems: [] })
497
+ // TP9: custom_motion is answered afterwards by its own slot, so it is set aside here, checked for shape only
498
+ const customClips = new Set(customBlocks.map((b) => b.clip))
499
+ const customProblems = (ops) =>
500
+ ops.flatMap((op, i) => {
501
+ if (op?.op !== "custom_motion") return []
502
+ if (!customMotion) return [`operation ${i + 1}: custom_motion isn't available`]
503
+ if (op.at === undefined) return [`operation ${i + 1}: custom_motion needs \`at\`, a word anchor or a clip edge`]
504
+ if (op.reuse !== undefined) return customClips.has(op.reuse) ? [] : [`operation ${i + 1}: ${op.reuse} isn't a saved custom animation`]
505
+ return typeof op.text === "string" && op.text.trim() ? [] : [`operation ${i + 1}: custom_motion needs text: what to animate`]
506
+ })
507
+ const expand = (asked) => {
508
+ const graphics = motion ? expandGraphics(asked, { index, person, ...(typeKit ? { kinds: ALL_GRAPHIC_KINDS } : {}) }) : { ops: asked, problems: [] }
509
+ const marked = mark ? expandMark(graphics.ops, { mark, project, index, person }) : { ops: graphics.ops, problems: [] }
510
+ const custom = customProblems(marked.ops)
511
+ if (marked.ops.filter((op) => op?.op === "custom_motion").length > 1) custom.push("only one custom_motion at a time")
512
+ return { ops: marked.ops.filter((op) => op?.op !== "custom_motion"), custom: marked.ops.filter((op) => op?.op === "custom_motion"), problems: [...graphics.problems, ...marked.problems, ...custom] }
513
+ }
400
514
  const check = ({ ops: asked }) => {
401
515
  if (!asked.length) return []
402
516
  const { ops, problems } = expand(asked)
@@ -404,9 +518,14 @@ export async function revise({ ask, project, index, text, selection, history = [
404
518
  const tried = apply(project, ops, { index, author: "agent" })
405
519
  return tried.applied ? [] : tried.diagnostics.map((d) => `operation ${d.op + 1}: ${d.message}`)
406
520
  }
407
- const answer = await ask({ task: "console", tier: "budget", schema: consoleSchema(motion), view, request, maxOutput: 2000, check, clean: tidyConsole, fallback: () => ({ ops: [] }), signal, priority: 0 })
521
+ const base = pointingSchema(typeKitSchema(craftSchema(consoleSchema(motion), craft), typeKit), { customMotion, mark: !!mark })
522
+ const schema = intent ? { ...base, properties: { ...base.properties, cannot: { type: "array", maxItems: 8, items: { type: "object", properties: { evidence: { type: "string", maxLength: 300 }, nearest: { type: "string", maxLength: 160 } }, required: ["evidence"], additionalProperties: false } } } } : base
523
+ // The `cannot` list is tidied before the schema sees it, so it never costs a repair call (EH-64)
524
+ const tidy = intent ? (value) => ({ ...tidyConsole(value), cannot: tidyIntent({ cannot: value?.cannot }, {}).cannot }) : tidyConsole
525
+ const answer = await ask({ task: "console", tier: "budget", schema, view, request, maxOutput: 2000, check, clean: tidy, fallback: () => ({ ops: [] }), signal, priority: 0 })
408
526
  const expanded = expand(answer.value.ops)
409
527
  const ops = expanded.problems.length ? [] : expanded.ops
528
+ const custom = expanded.problems.length ? [] : expanded.custom.map((op) => ({ at: op.at, ...(Number.isInteger(op.duration) ? { duration: op.duration } : {}), ...(op.reuse !== undefined ? { reuse: op.reuse } : { text: String(op.text).replace(/[\u0000-\u001f<>]/g, " ").trim().slice(0, 300) }) }))
410
529
  const tried = ops.length ? apply(project, ops, { index, author: "agent" }) : null
411
530
  // A correction that changes nothing, or isn't a known word, isn't offered
412
531
  const corrections = (answer.value.corrections ?? []).map((c) => ({ word: c.word, text: cleanWord(c.text) })).filter((c) => words.has(c.word) && c.text && c.text !== words.get(c.word).text)
@@ -421,5 +540,9 @@ export async function revise({ ask, project, index, text, selection, history = [
421
540
  source: answer.source,
422
541
  reason: answer.reason,
423
542
  calls: answer.calls,
543
+ // TP9: a custom animation to write (or a saved one to place), for the Host's own slot; only with the switch on
544
+ ...(custom.length ? { custom } : {}),
545
+ // What it couldn't do, in the person's own words: only words that are in their message
546
+ ...(intent ? { cannot: (answer.value.cannot ?? []).filter((c) => grounded(c.evidence, text, "")).map((c) => ({ said: c.evidence.replace(/[\u0000-\u001f<>]/g, " ").trim(), ...(c.nearest ? { nearest: c.nearest.replace(/[\u0000-\u001f<>]/g, " ").trim() } : {}) })) } : {}),
424
547
  }
425
548
  }
@@ -0,0 +1,136 @@
1
+ // The Viewer's Report (TP8, CRAFT_UPGRADE §6.2, EDD-68): the Director watches its own draft
2
+ // by code, free and always, in five-second windows. Picture changes come from the timeline
3
+ // and from the rendered file's own cuts; loudness and pauses from the rendered sound; text on
4
+ // screen, cutaways and speech from the solved timeline. It names typed findings and one score,
5
+ // deterministic for the same draft. No model is asked: watching by model (§6.3) needs
6
+ // editing.frameVision and the project's frame consent (EDD-14), and even then sends nothing here.
7
+
8
+ import { solve } from "../core/solver.js"
9
+ import { metadataFrames, ptsFlicks } from "../index/layers/meta.js"
10
+ import { CUT_SCORE } from "../index/layers/shots.js"
11
+ import { readSound, soundArgs, STEP } from "../index/layers/sound.js"
12
+
13
+ const FLICKS = 705_600_000
14
+ export const WINDOW = 5 * FLICKS
15
+ // still: scdet's mean frame difference on the 160 px copy, under which a window with no change is dull.
16
+ // Measured 2026-11-11: still bars with light noise 0.10, testsrc 0.15, testsrc2 0.81, a mandelbrot zoom 1.03
17
+ export const LIMITS = { deadAir: Math.round(1.5 * FLICKS), levelJump: 6, crowded: 3, still: 1 }
18
+ // Picture changes a window needs for its playbook's pace: the slow genres are never dull
19
+ const SLOW = new Set(["documentary", "podcast", "montage"])
20
+ export const paceOf = (genre) => (SLOW.has(genre) ? 0 : 1)
21
+ // What each finding costs the score; a crowded frame or a dead pause is worse than a still one
22
+ export const WEIGHT = { dull: 4, crowded: 8, dead_air: 8, repeated_cutaway: 8, level_jump: 6 }
23
+
24
+ /** Whether the model may look at frames: only with the switch on and the project's own consent (EDD-14, ET-DL-06). */
25
+ export const mayWatchFrames = (features = {}, project = {}) => features.frameVision === true && project.consent?.frames === true
26
+
27
+ /**
28
+ * What the draft shows, from its solved timeline: where the picture changes, the text on screen,
29
+ * the cutaways and the spoken words, all in timeline flicks, with the clip each came from.
30
+ */
31
+ export function timelineOf(project, index = {}) {
32
+ const solved = solve(project, index)
33
+ const base = solved.picture.filter((p) => p.role !== "broll" && p.asset)
34
+ const cutaways = solved.overlays.filter((o) => o.role === "broll" && o.asset).map(({ clip, asset, at, end, in: from, out }) => ({ clip, asset, at, end, in: from, out }))
35
+ const blocks = solved.overlays.filter((o) => o.block).map(({ clip, at, end, block }) => ({ clip, at, end, kind: block.blockId === "scene" ? "scene" : "graphic", block }))
36
+ const texts = [...(solved.captions ?? []).map(({ clip, at, end }) => ({ clip, at, end, kind: "caption" })), ...blocks]
37
+ const zooms = (solved.zooms ?? []).map(({ clip, at, end }) => ({ clip, at, end }))
38
+ const changes = [...base.slice(1).map((p) => p.at), ...cutaways.flatMap((c) => [c.at, c.end]), ...zooms.flatMap((z) => [z.at, z.end])].filter((t) => t > 0 && t < solved.duration)
39
+ const words = []
40
+ for (const piece of base) for (const word of index.words ?? []) if (word.asset === piece.asset && word.start >= piece.in && word.end <= piece.out && !word.flags?.includes("trimmed")) words.push({ at: piece.at + (word.start - piece.in), end: piece.at + (word.end - piece.in) })
41
+ const faced = new Set(Object.entries(index.subjects ?? {}).filter(([, list]) => list?.length).map(([asset]) => asset))
42
+ return { duration: solved.duration, base: base.map(({ clip, asset, at, end, in: from, out }) => ({ clip, asset, at, end, in: from, out, face: faced.has(asset) })), cutaways, texts, zooms, changes, words }
43
+ }
44
+
45
+ export const drawnArgs = (file) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-i", file, "-an", "-sn", "-dn", "-vf", `scale=160:-2,settb=AVTB,scdet=threshold=${CUT_SCORE},metadata=mode=print:file=-`, "-f", "null", "-"]
46
+
47
+ /** Reads the rendered draft: its own cuts and motion per frame, and its sound every 100 ms. */
48
+ export async function measureDraft(file, { run, duration }) {
49
+ const frames = metadataFrames(await run("ffmpeg", drawnArgs(file), { timeoutMs: 600_000 })).map(({ pts, values }) => ({ t: ptsFlicks(pts, 1_000_000), mafd: Number(values["lavfi.scd.mafd"] ?? 0), score: Number(values["lavfi.scd.score"] ?? 0) }))
50
+ const sound = readSound(await run("ffmpeg", soundArgs(file), { timeoutMs: 600_000 }), duration)
51
+ return { frames, cuts: frames.filter((f) => f.score >= CUT_SCORE && f.t > 0).map((f) => f.t), loudness: sound.data.loudness, silences: sound.silences }
52
+ }
53
+
54
+ const energy = (values) => {
55
+ const live = values.filter((v) => v !== null && v !== undefined)
56
+ return live.length ? Math.round(10 * Math.log10(live.reduce((sum, v) => sum + 10 ** (v / 10), 0) / live.length) * 10) / 10 : null
57
+ }
58
+ const overlap = (a, b) => Math.max(0, Math.min(a.end, b.end) - Math.max(a.at, b.at))
59
+ const near = (list, t, within = FLICKS / 5) => list.some((x) => Math.abs(x - t) <= within)
60
+
61
+ /** The most text layers on screen at once inside [at, end), and the clips at that moment. */
62
+ function crowdIn(texts, at, end) {
63
+ let most = { count: 0, at, clips: [] }
64
+ for (const t of texts.filter((x) => x.at < end && x.end > at)) {
65
+ const moment = Math.max(t.at, at)
66
+ const on = texts.filter((x) => x.at <= moment && x.end > moment)
67
+ if (on.length > most.count) most = { count: on.length, at: moment, end: Math.min(...on.map((x) => x.end), end), clips: on.map((x) => x.clip) }
68
+ }
69
+ return most
70
+ }
71
+
72
+ /**
73
+ * The report: per window its measures, the findings against the playbook's pace, and one score
74
+ * (100 with nothing found, lower for each finding, never below 0). Pure: the same input, the same report.
75
+ * @param {{ timeline: ReturnType<typeof timelineOf>, measured?: Awaited<ReturnType<typeof measureDraft>> | null, genre?: string }} input
76
+ */
77
+ export function viewerReport({ timeline, measured = null, genre = "opinion" }) {
78
+ const { duration } = timeline
79
+ const pace = paceOf(genre)
80
+ const changes = [...timeline.changes]
81
+ for (const t of measured?.cuts ?? []) if (!near(changes, t)) changes.push(t)
82
+ const windows = []
83
+ for (let at = 0; at < duration; at += WINDOW) {
84
+ const end = Math.min(duration, at + WINDOW)
85
+ const span = { at, end }
86
+ const length = end - at
87
+ const shown = timeline.base.filter((p) => p.face).reduce((sum, p) => sum + overlap(p, span), 0) - timeline.cutaways.reduce((sum, c) => sum + overlap(c, span), 0)
88
+ const frames = measured?.frames?.filter((f) => f.t >= at && f.t < end) ?? []
89
+ windows.push({
90
+ at,
91
+ end,
92
+ changes: changes.filter((t) => t >= at && t < end).length,
93
+ face: Math.max(0, Math.round((shown / length) * 100) / 100),
94
+ text: crowdIn(timeline.texts, at, end).count,
95
+ loudness: measured ? energy(measured.loudness.slice(Math.floor(at / STEP), Math.ceil(end / STEP))) : null,
96
+ speech: Math.round((timeline.words.filter((w) => w.at >= at && w.at < end).length / (length / FLICKS)) * 10) / 10,
97
+ motion: frames.length ? Math.round((frames.reduce((sum, f) => sum + f.mafd, 0) / frames.length) * 100) / 100 : null,
98
+ })
99
+ }
100
+ const findings = []
101
+ for (const w of windows) {
102
+ // Dull: a whole window where the picture never changes and barely moves, for a pace that wants change
103
+ if (pace && w.end - w.at >= WINDOW * 0.8 && w.changes < pace && (w.motion === null || w.motion < LIMITS.still)) findings.push({ kind: "dull", at: w.at, end: w.end })
104
+ const crowd = crowdIn(timeline.texts, w.at, w.end)
105
+ if (crowd.count >= LIMITS.crowded) findings.push({ kind: "crowded", at: crowd.at, end: crowd.end, clips: crowd.clips })
106
+ }
107
+ // Dead air: a pause in the rendered sound (or, unrendered, between spoken words) longer than a breath
108
+ const pauses = measured ? measured.silences : timeline.words.slice(1).map((w, i) => ({ start: timeline.words[i].end, end: w.at }))
109
+ for (const p of pauses) if (p.end - p.start >= LIMITS.deadAir && p.start > 0 && p.end < duration) findings.push({ kind: "dead_air", at: p.start, end: p.end })
110
+ // The same B-roll twice: the same file back to back, or the same stretch of it again anywhere
111
+ const shown = [...timeline.cutaways].sort((a, b) => a.at - b.at)
112
+ shown.forEach((c, i) => {
113
+ const again = shown.slice(0, i).some((d) => d.asset === c.asset && (d === shown[i - 1] || (c.in < d.out && d.in < c.out)))
114
+ if (again) findings.push({ kind: "repeated_cutaway", at: c.at, end: c.end, clip: c.clip, asset: c.asset })
115
+ })
116
+ // A level jump: two voiced windows side by side whose loudness steps by more than the limit
117
+ for (let i = 1; i < windows.length; i++) {
118
+ const [a, b] = [windows[i - 1], windows[i]]
119
+ if (a.loudness === null || b.loudness === null) continue
120
+ const step = Math.round((b.loudness - a.loudness) * 10) / 10
121
+ if (Math.abs(step) >= LIMITS.levelJump) findings.push({ kind: "level_jump", at: b.at, end: b.end, db: step, louder: step > 0 ? { at: b.at, end: b.end } : { at: a.at, end: a.end } })
122
+ }
123
+ findings.sort((a, b) => a.at - b.at || a.kind.localeCompare(b.kind))
124
+ const penalty = findings.reduce((sum, f) => sum + WEIGHT[f.kind], 0)
125
+ // Never saturates: a fix that removes any finding raises it, however long the film
126
+ const score = windows.length ? Math.round((100 * windows.length) / (windows.length + penalty / 10) * 10) / 10 : 0
127
+ return { windows, findings, score }
128
+ }
129
+
130
+ const clock = (t) => {
131
+ const s = Math.round(t / (FLICKS / 10)) / 10
132
+ return `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`
133
+ }
134
+ const WORDS = { dull: "a still stretch", crowded: "too much text at once", dead_air: "a long pause", repeated_cutaway: "the same B-roll again", level_jump: "a jump in loudness" }
135
+ /** A finding in the person's words, with its time. */
136
+ export const sayFinding = (f) => `${WORDS[f.kind]} at ${clock(f.at)}`
@@ -0,0 +1,119 @@
1
+ // Watch and fix (TP8, CRAFT_UPGRADE §6.1, EDD-68): each finding of the Viewer's Report maps to
2
+ // one typed fix, made by code: a punch-in on a still stretch, a graphic moved off a crowded
3
+ // moment, a pause trimmed, a repeated cutaway swapped or removed, a jump in level evened. The
4
+ // draft is rendered and gated again, and a fix is kept only when the score rises and the gates
5
+ // are no worse; a cut that passes its gates is never replaced by one that doesn't (EH-74). The
6
+ // rounds are the repair ladder's own, not more on top of them.
7
+
8
+ import { apply } from "../core/ops.js"
9
+ import { better, rankOf, ROUNDS } from "../loop/repair.js"
10
+ import { sayFinding } from "./viewer.js"
11
+
12
+ const FLICKS = 705_600_000
13
+ const PUNCH = 1.12
14
+ const PAD = Math.round(0.25 * FLICKS)
15
+ export const FIX_ROUNDS = 2
16
+
17
+ /** The fix rounds a candidate has left: two at most, out of what its repair ladder didn't use. */
18
+ export const roundsLeft = (repairs = []) => Math.max(0, Math.min(FIX_ROUNDS, ROUNDS - repairs.length))
19
+
20
+ const levelOf = (clip) => clip?.effects.find((e) => e.type === "level")?.db ?? 0
21
+ const clipOf = (project, id) => project.sequences.find((q) => q.id === project.active).clips.find((c) => c.id === id)
22
+
23
+ /**
24
+ * The typed operations for a report's findings. A finding with no safe fix is left for the person.
25
+ * @param {{ findings: object[] }} report
26
+ * @param {ReturnType<import("./viewer.js").timelineOf>} timeline
27
+ * @returns {{ fixes: { kind: string, at: number, ops: object[], why: string }[], left: object[] }}
28
+ */
29
+ export function fixesFor(report, project, index, timeline) {
30
+ const fixes = []
31
+ const left = []
32
+ const indexWords = index.words ?? []
33
+ const pictures = project.assets.filter((a) => a.kind === "video" && a.facts?.width && (a.facts.duration ?? 0) > FLICKS)
34
+ for (const f of report.findings) {
35
+ if (f.kind === "dull") {
36
+ const at = f.at + Math.round((f.end - f.at) / 3)
37
+ const duration = Math.min(Math.round(1.5 * FLICKS), f.end - at)
38
+ if (duration > FLICKS / 2 && !timeline.zooms.some((z) => z.at < at + duration && z.end > at)) fixes.push({ kind: f.kind, at: f.at, ops: [{ op: "punch_in", at, duration, scale: PUNCH }], why: `Punched in on ${sayFinding(f)}.` })
39
+ else left.push(f)
40
+ } else if (f.kind === "crowded") {
41
+ // The latest graphic of the moment moves to where nothing else is on screen; a scene stays on its words
42
+ const graphic = timeline.texts.filter((t) => f.clips.includes(t.clip) && t.kind === "graphic").sort((a, b) => b.at - a.at)[0]
43
+ const length = graphic ? graphic.end - graphic.at : 0
44
+ const clear = graphic && [f.end, ...timeline.texts.map((t) => t.end)].sort((a, b) => a - b).find((t) => t >= f.end && t + length <= timeline.duration && timeline.texts.filter((x) => x.clip !== graphic.clip && x.at < t + length && x.end > t).length < 2)
45
+ if (graphic && clear !== undefined) fixes.push({ kind: f.kind, at: f.at, ops: [{ op: "ripple_delete", clip: graphic.clip }, { op: "add_motion", block: graphic.block.blockId, version: graphic.block.version, variables: graphic.block.variables, at: clear, duration: length }], why: `Moved a graphic off ${sayFinding(f)}.` })
46
+ else left.push(f)
47
+ } else if (f.kind === "dead_air") {
48
+ // Trimmed inside its own clip, a quarter second kept each side, never through a word
49
+ const piece = timeline.base.find((p) => p.at <= f.at && p.end >= f.end)
50
+ const from = piece && piece.in + (f.at - piece.at) + PAD
51
+ const to = piece && piece.in + (f.end - piece.at) - PAD
52
+ if (piece && to - from > FLICKS / 4 && !indexWords.some((w) => w.asset === piece.asset && w.start < to && w.end > from)) fixes.push({ kind: f.kind, at: f.at, ops: [{ op: "remove_range", asset: piece.asset, from, to }], why: `Trimmed ${sayFinding(f)}.` })
53
+ else left.push(f)
54
+ } else if (f.kind === "repeated_cutaway") {
55
+ // Another of the person's clips not already on screen nearby, from its start; else the repeat goes
56
+ const near = new Set(timeline.cutaways.filter((c) => Math.abs(c.at - f.at) < 10 * FLICKS).map((c) => c.asset))
57
+ const base = new Set(timeline.base.map((p) => p.asset))
58
+ const other = pictures.find((a) => !near.has(a.id) && !base.has(a.id) && a.facts.duration >= f.end - f.at)
59
+ fixes.push({ kind: f.kind, at: f.at, ops: [{ op: "ripple_delete", clip: f.clip }, ...(other ? [{ op: "place_broll", asset: other.id, at: f.at, in: 0, duration: f.end - f.at }] : [])], why: other ? `Swapped ${sayFinding(f)} for another of your clips.` : `Took out ${sayFinding(f)}.` })
60
+ } else if (f.kind === "level_jump") {
61
+ // The louder side's own clips come down toward the quieter, never past it
62
+ const louder = timeline.base.filter((p) => p.at < f.louder.end && p.end > f.louder.at)
63
+ const quieter = new Set(timeline.base.filter((p) => !louder.includes(p)).map((p) => p.clip))
64
+ const clips = [...new Set(louder.map((p) => p.clip))].filter((id) => !quieter.has(id))
65
+ const down = Math.round((Math.abs(f.db) - 2) * 10) / 10
66
+ if (clips.length) fixes.push({ kind: f.kind, at: f.at, ops: clips.map((id) => ({ op: "set_level", clip: id, db: Math.round((levelOf(clipOf(project, id)) - down) * 10) / 10 })), why: `Evened ${sayFinding(f)} (${down} dB).` })
67
+ else left.push(f)
68
+ }
69
+ }
70
+ return { fixes, left }
71
+ }
72
+
73
+ const passing = (checked) => checked.blocking === 0 && checked.briefMisses === 0
74
+
75
+ /** The keep rule (ET-DL-03, EH-74): a higher score, gates no worse, and never a passing cut swapped for a failing one. */
76
+ export function keepFix(before, after) {
77
+ if (passing(before.checked) && !passing(after.checked)) return { kept: false, reason: "it would fail a gate the cut passed" }
78
+ if (better(rankOf(before.checked), rankOf(after.checked))) return { kept: false, reason: "the gates were worse" }
79
+ if (!(after.report.score > before.report.score)) return { kept: false, reason: `the score didn't rise (${before.report.score} → ${after.report.score})` }
80
+ return { kept: true }
81
+ }
82
+
83
+ /**
84
+ * The loop over one checked attempt.
85
+ * @param {{ project: object, ops: object[], file: string, plan: object, checked: object }} start
86
+ * @param {{ index: object, view: (attempt: object) => Promise<{ report: object, timeline: object }>, render: (project: object) => Promise<{ file: string, plan: object }>, check: (file: string, plan: object, project: object) => Promise<object>, rounds?: number, fixes?: typeof fixesFor, signal?: AbortSignal }} io
87
+ * @returns {Promise<{ best: object, rounds: object[], left: object[] }>}
88
+ */
89
+ export async function watchAndFix(start, { index, view, render, check, rounds = FIX_ROUNDS, fixes = fixesFor, signal }) {
90
+ let best = { ...start, ...(await view(start)) }
91
+ const log = []
92
+ const tried = new Set()
93
+ for (let round = 1; round <= Math.min(rounds, FIX_ROUNDS); round++) {
94
+ if (signal?.aborted || !best.report.findings.length) break
95
+ const proposed = fixes(best.report, best.project, index, best.timeline).fixes.filter((fix) => !tried.has(JSON.stringify(fix.ops)))
96
+ if (!proposed.length) break
97
+ proposed.forEach((fix) => tried.add(JSON.stringify(fix.ops)))
98
+ const ops = proposed.flatMap((fix) => fix.ops)
99
+ const step = apply(best.project, ops, { index, author: "code" })
100
+ const said = proposed.map(({ ops: _, ...fix }) => fix)
101
+ if (!step.applied) {
102
+ log.push({ round, fixes: said, kept: false, reason: step.diagnostics[0].message })
103
+ continue
104
+ }
105
+ const { file, plan } = await render(step.project)
106
+ const checked = await check(file, plan, step.project)
107
+ const attempt = { project: step.project, ops: [...best.ops, ...ops], file, plan, checked }
108
+ Object.assign(attempt, await view(attempt))
109
+ const verdict = keepFix(best, attempt)
110
+ log.push({ round, fixes: said, was: best.report.score, score: attempt.report.score, ...verdict })
111
+ if (verdict.kept) best = attempt
112
+ }
113
+ return { best, rounds: log, left: best.report.findings }
114
+ }
115
+
116
+ /** What the loop did, in the person's words: each kept fix, and each dropped round with its reason. */
117
+ export function sayWatch(rounds) {
118
+ return rounds.map((r) => (r.kept ? `Director: ${r.fixes.map((f) => f.why).join(" ")} Score ${r.was} → ${r.score}.` : `Director: tried ${r.fixes.map((f) => f.why.replace(/\.$/, "").toLowerCase()).join("; ")}, and kept the cut as it was: ${r.reason}.`))
119
+ }