@open-take/compositor 0.4.2 → 0.4.4
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.
- package/dist/index.d.ts +203 -132
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +611 -251
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/audit-cursor.ts +487 -0
- package/src/index.ts +15 -8
- package/src/render.ts +5 -1
- package/src/types.ts +7 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["DEFAULT_CAMERA: CameraConfig","mb: MotionBlurConfig | undefined","DEFAULT_FRAMING: FramingConfig","DEFAULT_MOTION_BLUR: MotionBlurConfig","DEFAULT_CURSOR: CursorConfig","scale: number","best: ZoomLevelName | null","MOTION: Record<\"calm\" | \"natural\" | \"brisk\", MotionPreset>","v: number | undefined","want: number","legacy: number","cursor: CursorConfig","DARK_SHADOW: LookPreset[\"shadow\"]","LOOKS: Record<string, LookPreset>","framing: FramingConfig","FINISH: Record<\"smooth\" | \"crisp\" | \"heavy\", MotionBlurConfig | undefined>","mb: MotionBlurConfig | undefined","cachedFfmpeg: string | undefined","cachedFfprobe: string | undefined","bin: string","pkg: string","path: string | null","encodersText: string","encoder: string","name: string","t: number","x1: number","y1: number","x2: number","y2: number","s: number","x: number","bounce: number","p: number","cursor: TakeComposition[\"cursor\"]","angleDeg: number | undefined","oW: number","oH: number","kfs: KF<number>[]","ease: (u: number) => number","bbox: BBox","outW: number","outH: number","fillFrac: number","maxScale: number","restScale: number","videoW: number","videoH: number","insetFrac: number","center: Pt","scale: number","kfs: KF<CamRect>[]","comp: TakeComposition","restC: Pt","anchors: CameraSchedule[\"anchors\"]","e: { inAtMs: number; tMs: number }","out: ({ startMs: number; landMs: number; pullOut: boolean } | null)[]","rf: { t: number; r: CamRect }[]","r: CamRect","frac: number","u: number","decay: (u: number) => number","cam: { T: number; rest: number; at: (t: number) => { scale: number } }","y: number","legs: Leg[]","cur: Pt","cam: ReturnType<typeof stageCamera> | undefined","track: ReturnType<typeof zoomFracTrack> | undefined","a: Pt","b: Pt","arriveSec: number","dist","ms: number","path: Pt[]","seg: number[]","e: { tMs: number; durationMs?: number }","n: number","files: { name: string; size?: number }[]","b: BBox","a: Pt","b: Pt","a: BBox","box: BBox","video: { w: number; h: number }","b: Beat","beats: Beat[]","idx: number[]","out: { w: number; h: number }","cam: CameraConfig","rest: number","endMs: number","restC: Pt","roi: BBox","nodes: Node[]","segs: Seg[]","framings: Framing[]","log: CaptureLog","opts: PlanOpts","framing: FramingConfig","cursor: CursorConfig","camera: CameraConfig","p: Pt","b: BBox","pts: Pt[]","scaffolds: Scaffold[]","durationMs","beat: Beat","ev: Omit<CompEvent, \"zoom\">","events: CompEvent[]","zoom: ZoomDecision","captions: Caption[]","b: Beat","rest: number","err: unknown","reqField: Record<string, string>","comp: TakeComposition","opts: ValidateOpts","issues: CompositionIssue[]","path: string","message: string","fix?: string","k: MsKnob","positive: boolean","required: boolean","v: number | undefined","l: (typeof travels)[number]","s: string","cmd: string","args: string[]","videoPath: string","outMp4: string","fps: number","codec: \"h264\" | \"vp9\"","inMov: string","baseFps: number","blur: MotionBlurConfig | null","vf: string[]","from: string","to: string","dir: string","composition: TakeComposition","renderQueue: Promise<unknown>","opts: RenderTakeOpts","run","warnings: CompositionIssue[]","issues: CompositionIssue[]","noProgressTimer: ReturnType<typeof setTimeout> | undefined","_worker: number","progress: number","produced: string"],"sources":["../src/types.ts","../src/presets.ts","../src/ffmpeg.ts","../src/math.ts","../src/camera.ts","../src/plan.ts","../src/decode-guard.ts","../src/validate.ts","../src/render.ts"],"sourcesContent":["// The editable take composition — the source of truth. The agent (or a\n// human) edits THIS, and the revideo scene renders it deterministically.\n// All spatial fields are in VIDEO-pixel space (capture coords mapped\n// through viewport→video scaling), so the scene works in one coordinate\n// system.\n\nexport type Pt = { x: number; y: number };\nexport type BBox = { x: number; y: number; w: number; h: number };\n\n// --- capture input (the ground-truth event log) -----------------------\n\n/** Editorial zoom intent for an action (set by the planner/agent). */\nexport type ZoomIntent = \"auto\" | \"never\" | \"always\";\n\n/** Fields common to every captured action. `x,y` is the anchor / start\n * point (cursor target), viewport CSS px. */\nexport type CaptureEventBase = {\n /** anchor point (click target / field / drag start), viewport CSS px */\n x: number;\n y: number;\n /** element bounding box, viewport CSS px — the ground-truth edge */\n box?: BBox;\n /** ms from recording start (when the cursor arrives / action begins) */\n tMs: number;\n /** selector / note, kept for editability */\n sel?: string;\n note?: string;\n /** One-line viewer-facing caption from the plan step (\"Applying the\n * filter re-prices every row\"). planComposition turns these into `captions`\n * windows — the beat explains itself to a viewer who has never seen the\n * app, which footage alone cannot do. */\n caption?: string;\n /** selective-zoom intent from the plan. Absent/\"auto\" ⇒ the camera director\n * decides from the ground-truth log; \"always\"/\"never\" hard-override it (and\n * cut the beat out of any cluster — an override is a segment boundary). */\n zoom?: ZoomIntent;\n /** CAPTURE-DERIVED (frame-diff / mutation pass — the `effectBox` seam): the\n * region that actually CHANGED after the action, viewport CSS px. The\n * director frames THIS over `box` when present — a `type`'s result region, or\n * a payoff that lands somewhere other than where you clicked. Absent ⇒ the\n * director shapes an ROI from `box`/kind instead. */\n effectBox?: BBox;\n /** CAPTURE-DERIVED (same pass): fraction of the frame that changed after the\n * action, 0..1. ≥ camera.pullOutCoverage ⇒ the action repainted most of the\n * frame (nav / global restyle) ⇒ pull out to full view. Absent ⇒ the pull-out\n * branch is skipped (the director can't tell nav from popover on bbox alone —\n * it says so in the beat's `reason`). */\n changeCoverage?: number;\n};\n\n/** A click (or a type's focus-click): an instantaneous action at a point. */\nexport type CaptureClick = CaptureEventBase & { kind?: \"click\" };\n\n/** Typing into a focused field: the cursor parks and the zoom holds for\n * `durationMs` while the text appears in the recording. */\nexport type CaptureType = CaptureEventBase & {\n kind: \"type\";\n /** what was typed (editability) */\n text: string;\n /** ms the typing occupies on screen (ground-truth wall time) */\n durationMs: number;\n};\n\n/** A drag: a path from the anchor (`x,y`) to `to`, optionally via `path`,\n * with the button held for `durationMs`. */\nexport type CaptureDrag = CaptureEventBase & {\n kind: \"drag\";\n /** drag end point, viewport CSS px */\n to: { x: number; y: number };\n /** full polyline incl. ends, viewport CSS px (freehand strokes) */\n path?: { x: number; y: number }[];\n /** ms the drag occupies on screen (ground-truth wall time) */\n durationMs: number;\n /** how the stroke was paced and BAKED into the ink: \"smooth\" (accel-in /\n * decel-out — a natural hand-draw) or \"linear\" (constant speed). The\n * compositor cursor must replay the SAME easing to stay locked to the ink.\n * Absent ⇒ linear (legacy captures). */\n ease?: \"linear\" | \"smooth\";\n};\n\n/** A scroll: the content pans for `durationMs`. The cursor holds (no travel),\n * full-view (no zoom). `dy` is the signed pixels scrolled (editability). */\nexport type CaptureScroll = CaptureEventBase & {\n kind: \"scroll\";\n /** signed pixels scrolled (positive = down) */\n dy: number;\n /** ms the scroll occupies on screen (ground-truth wall time) */\n durationMs: number;\n};\n\n/** A hover: the cursor travels to `x,y` and dwells for `durationMs` so a\n * tooltip / menu / hover-state reveals. Like a click that doesn't click. */\nexport type CaptureHover = CaptureEventBase & {\n kind: \"hover\";\n /** ms the dwell occupies on screen (ground-truth wall time) */\n durationMs: number;\n};\n\n/** A look: a CAMERA-only beat. Nothing is done to the page and the cursor\n * does not move — the camera frames the target element and holds for\n * `durationMs`. This is the honest spelling of \"show the viewer this\n * region\": before it existed, the only way to aim the camera was to hover\n * a control you never meant to activate, which reads on screen as a\n * promise (\"about to click\") the video then breaks. `x,y` is the target's\n * center (zoom anchor); the cursor rests at its previous anchor. */\nexport type CaptureLook = CaptureEventBase & {\n kind: \"look\";\n /** ms the framed hold occupies on screen */\n durationMs: number;\n};\n\n/** A key press / shortcut: keyboard-driven, so the cursor holds (no travel).\n * Holds for `durationMs` while the effect plays out; if a reveal element was\n * located, `box` carries its bbox so the zoom can frame it. */\nexport type CapturePress = CaptureEventBase & {\n kind: \"press\";\n /** the chord pressed, e.g. \"Enter\" / \"Meta+k\" (editability) */\n keys: string;\n /** ms the hold occupies on screen (ground-truth wall time) */\n durationMs: number;\n};\n\n/** A file drag-and-drop (OS-level, synthesized via CDP Input.dispatchDragEvent\n * with real file paths): the cursor carries the file(s) from the anchor\n * (`x,y`) along `path` to `to`, where the drop lands and the page receives\n * actual Files. The compositor draws a \"file ghost card\" riding the cursor\n * for this beat — the recording itself shows only the page's reaction. */\nexport type CaptureDropFiles = CaptureEventBase & {\n kind: \"dropFiles\";\n /** drop point, viewport CSS px */\n to: { x: number; y: number };\n /** full polyline incl. ends, viewport CSS px */\n path?: { x: number; y: number }[];\n /** ms the carry occupies on screen (ground-truth wall time) */\n durationMs: number;\n /** carry pacing baked into the dispatched dragOver march (see CaptureDrag) */\n ease?: \"linear\" | \"smooth\";\n /** dropped files' display metadata (basename + bytes) for the ghost card */\n files: { name: string; size?: number }[];\n};\n\nexport type CaptureEvent =\n | CaptureClick\n | CaptureType\n | CaptureDrag\n | CaptureScroll\n | CaptureHover\n | CaptureLook\n | CapturePress\n | CaptureDropFiles;\n\nexport type CaptureLog = {\n video: { width: number; height: number; fps?: number | string; durationS?: number };\n viewport: { w: number; h: number };\n /** the app this take was shot from (the plan's url). Written by makeTake into\n * the KEPT log; the composition never reads it. It exists so a take can say\n * which app it is of — `make` refuses to overwrite a take of a different\n * app, which is what stops a second demo in the same folder from destroying\n * the first. Absent on takes made before it was recorded. */\n url?: string;\n start?: { x: number; y: number };\n /** the ordered ground-truth actions (click / type / drag) */\n events: CaptureEvent[];\n tEndMs?: number;\n /** Steps the capture DROPPED (target not found / endpoint unresolved) — the\n * take still completes, but a missing beat must reach the end-of-run\n * summary and (with --strict) the exit code, not just an early stderr line\n * buried under render progress. `step` is the plan's 0-based step index. */\n skipped?: { step: number; action: string; target?: string; reason: string }[];\n /** Beats whose editorial hold ran out before the PAGE had finished — the\n * capture kept waiting (see runtime/src/settle.ts) and records how much\n * longer it needed. This is the measurement that replaces guessing\n * `settleMs`: `heldMs + waitedMs` is what that beat actually wanted, and\n * `reason: \"budget\"` means even the extra wait was not enough. Absent when\n * every hold was already long enough. */\n settleWaits?: {\n step: number;\n action: string;\n heldMs: number;\n waitedMs: number;\n reason: \"idle\" | \"budget\" | \"unavailable\";\n }[];\n /** Largest share of the frame a `<canvas>`/`<video>` held during the capture.\n * It matters because the settle probe reads the page's STRUCTURE, and a\n * paint surface never changes structurally no matter what is drawn inside\n * it — so on a canvas-driven app \"the page settled\" is not evidence the\n * beat's payoff had appeared, and `settleMs` is doing the whole job alone.\n * Absent on an ordinary DOM app. */\n paintedFrac?: number;\n};\n\n// --- the composition (editable) ----------------------------------------\n\nexport type ZoomDecision = {\n /** selective: not every action zooms. Edit this to tune/remove. */\n enabled: boolean;\n /** absolute stage scale to reach (bbox-fit, capped) */\n scale: number;\n /** video-px point to frame (bbox center), pre-clamp */\n center: Pt;\n /** when the zoom-in begins (ms) */\n inAtMs: number;\n /** Optional \"glide\": a slow camera drift WHILE the zoom is held, as a velocity\n * in video-px per second {x,y}. The held centre pans from `center` by\n * `glide · holdSeconds` across the hold window (then the next beat ramps from\n * there / it zooms out from there). Adds life vs a dead-static hold (Screen\n * Studio's glide). Absent/0 ⇒ a still hold. Clamped to the video at read time,\n * so a drift just stops at the edge. Keep it gentle (tens of px/s). */\n glide?: Pt;\n /** why this decision (for the human/agent reading the composition) */\n reason: string;\n};\n\n/** Ghost-card knobs for a dropFiles beat (editable): the macOS-style file\n * card riding the cursor during the carry. */\nexport type GhostCardConfig = {\n enabled: boolean;\n /** card offset from the cursor tip, video-px (default ~{x:26,y:30}) */\n offset?: Pt;\n /** ms of the release pop after the drop (fade + settle; default 280) */\n releaseMs?: number;\n};\n\nexport type CompEvent = {\n kind: \"click\" | \"type\" | \"drag\" | \"scroll\" | \"hover\" | \"look\" | \"press\" | \"dropFiles\";\n tMs: number;\n /** anchor point (click / focus / drag start / hover) in video-px. For a\n * scroll/press the cursor does not move; this is its resting point. */\n point: Pt;\n /** element bbox in video-px (if known) */\n bbox?: BBox;\n label?: string;\n zoom: ZoomDecision;\n /** how long the action plays out after `tMs` (type/drag/scroll/hover/press);\n * 0 for a click. The cursor parks and the zoom holds for this long. */\n durationMs?: number;\n /** typed text (kind=type), for editability */\n text?: string;\n /** chord pressed (kind=press), for editability */\n keys?: string;\n /** drag end point, video-px (kind=drag) */\n to?: Pt;\n /** drag polyline incl. ends, video-px (kind=drag) — the cursor path */\n path?: Pt[];\n /** drag stroke easing baked into the ink (kind=drag): \"smooth\" or \"linear\".\n * The cursor replays it so it stays locked to the ink. Absent ⇒ linear. */\n ease?: \"linear\" | \"smooth\";\n /** dropped files' display metadata (kind=dropFiles), for the ghost card */\n files?: { name: string; size?: number }[];\n /** ghost-card rendering knobs (kind=dropFiles); absent ⇒ enabled defaults */\n ghostCard?: GhostCardConfig;\n};\n\nexport type FramingConfig = {\n /** video occupies this fraction of the frame at rest (inset for the backdrop) */\n insetFrac: number;\n cornerRadius: number;\n shadow: { color: string; blur: number; offset: Pt };\n /** backdrop behind the framed video. `type` defaults to \"gradient\" (from→to);\n * \"solid\" fills `from` only. `angle` (deg, CSS-like: 0 = upward) rotates the\n * gradient; absent ⇒ the legacy top-left→bottom-right diagonal (pixel-identical). */\n background: { from: string; to: string; type?: \"gradient\" | \"solid\"; angle?: number };\n};\n\nexport type CursorConfig = {\n /** Fallback travel duration (ms) when `travelWidthsPerSec` is unset/0. A FIXED\n * duration makes cursor speed scale with distance (short=slow, long=fast),\n * which reads inconsistent; prefer the distance-aware speed below. */\n travelMs: number;\n /** Distance-aware travel speed, as a fraction of the source video WIDTH per\n * second (resolution-independent). A travel leg's duration is\n * `distance / (widthsPerSec·videoWidth·zoomFrac)`, floored at `travelMinMs` and\n * then capped at `travelMaxMs` (in that order — an inverted band pins short hops\n * to the floor, not everything to the ceiling), so the cursor holds a roughly\n * CONSTANT on-screen speed regardless of distance —\n * the premium-recorder feel (measured ~0.30 widths/s on the reference). Set 0\n * to fall back to the fixed `travelMs`.\n *\n * `zoomFrac = restScale / camera scale` — exactly 1 for a full-view take, so a\n * zoom-less composition is unaffected. While the camera is punched in, the same\n * video-px move covers proportionally more of the DELIVERED frame, so without\n * this factor a 2× punch-in reads ~2× too fast precisely where the viewer is\n * looking closest. zoomFrac is INTEGRATED across the leg, not sampled at one\n * instant: a travel usually departs while the camera is still wide and lands\n * after it has closed in, and pricing all of it at the landing magnification\n * over-slows the departure by as much as a zoom-blind duration over-sped it.\n * A leg the camera holds a frame through degenerates to that one frame's\n * factor, which is the sampled model's only exactly-right case. */\n travelWidthsPerSec: number;\n /** Floor for a distance-aware travel (ms) so short hops aren't an instant snap.\n * NOTE both clamps are applied AFTER the speed model and neither is part of a\n * `pace` preset, so on the legs they bind THEY set the duration and re-pacing\n * the take does nothing. validate.ts says so once that stops being the\n * exception (see CLAMPED_LEGS_FRAC). */\n travelMinMs: number;\n /** Ceiling for a distance-aware travel (ms) so a full-width jump stays a glide,\n * not a multi-second crawl. Binds on any sweep past\n * `travelMaxMs · travelWidthsPerSec · videoWidth` — ~571px of a 1920 frame at\n * the shipped defaults — which is deliberate (it was eye-tuned on a reference\n * recorder's long moves), so it also bounds how much of the zoom correction\n * above a long zoomed sweep can actually receive. */\n travelMaxMs: number;\n scale: number;\n arcFrac: number;\n arcMax: number;\n rippleMs: number;\n /** ms to hold a zoom after the action settles, before zooming back out */\n holdMs: number;\n /** ms for a zoom-OUT / pull-out ramp (to rest OR to any wider framing).\n * Measured on a reference export: the pull-out is ~1.8× slower than the\n * punch-in (their zoom-out spring ω≈5.2 rad/s ⇒ ~1340ms of critically-damped\n * settle) — a slow, soft release reads premium; a fast one reads like a\n * flinch. */\n zoomOutMs: number;\n /** ms for the zoom-IN ramp (into a target). Decoupled from travelMs so the\n * zoom can be slower/gentler than the cursor. Measured reference punch-in spring\n * ω≈9.4 rad/s ⇒ ~730ms. */\n zoomInMs: number;\n /** Optional cubic-bezier easing for the camera-rect ramps (centre + size in\n * lockstep — see math.ts stageCamera). Absent ⇒ the default critically-\n * damped spring (the measured reference curve). Set this only to force a\n * bezier feel; `zoomSpring` wins over it when both are set. */\n zoomEase?: [number, number, number, number];\n /** Spring easing for the camera-rect ramps, as a `bounce` amount ∈ [0,~0.6):\n * 0 = critically damped (the measured reference zoom curve — also the\n * default when neither zoomSpring nor zoomEase is set), higher = more\n * overshoot/snap. The segment duration stays zoomInMs/zoomOutMs; bounce only\n * shapes the curve. Bounce > 0 overshoots the RECT (a touch past the target\n * frame, then settle) — keep it small. */\n zoomSpring?: number;\n /** Fraction of a camera ramp still UNfinished at its keyframe end (the action\n * instant), left to settle as an asymptotic overdamped tail that continues\n * INTO the hold — so a move tapers out like a physical camera instead of\n * stopping on a velocity cliff at the keyframe. Frame-tracked on the\n * reference export: its moves keep sub-threshold motion ~0.5s past the\n * visible end (tail τ ≈ 220ms in / ≈ 370ms out), while the cut spring's\n * τ = duration/6.9 ends 2-3× harder. ~0.04 (the shipped default) reproduces\n * the reference tails over the default zoomInMs/zoomOutMs. 0 = legacy\n * cut+normalized spring (absent falls back to the default on NEW plans; an\n * old composition without the field renders as it always did). Ignored when\n * zoomSpring or zoomEase is set (those keep their exact legacy curves). */\n zoomSettleFrac?: number;\n /** Minimum stay (ms) after the previous action's visible end before a\n * PULL-OUT ramp may begin. When the beat gap is too tight the pull-out now\n * departs late and LANDS late (after its own action instant) instead of\n * fleeing a frame the viewer is still reading — the reference recorder's\n * reactive pattern (payoff plays while the camera is still arriving).\n * ~800 (the shipped default) reads as a natural beat; pace presets scale it.\n * 0/absent = legacy (a squeezed pull-out departs the instant the previous\n * action ends and lands exactly on its action). Named pullOut- because\n * holdMs already covers the ordinary post-action dwell. */\n pullOutDwellMs?: number;\n /** ms to delay the synthetic cursor along a DRAG stroke, compensating for the\n * capture pipeline latency: the captured ink appears ~this long after the pen\n * actually moved, so without the delay the (exact-time) cursor leads the ink.\n * Tune so the cursor tip sits on the ink front mid-stroke. */\n dragLagMs: number;\n /** easing for a travel move, as cubic-bezier control points [x1,y1,x2,y2].\n * Default is a symmetric ease-in-out — measured from a reference recording, whose\n * cursor accelerates and decelerates evenly (a slow start, fast middle, soft\n * landing). Drag strokes ignore this (they ease the stroke in lockstep with\n * the captured ink — see math.ts). */\n travelEase: [number, number, number, number];\n};\n\n/** Camera motion blur (temporal supersampling — what a real shutter does). The\n * renderer samples the composition camera at `samples` sub-times within each\n * output frame and averages them, so a fast zoom/pan/cursor smears in the\n * motion direction (a camera/shutter motion blur). It smears the\n * backdrop-reveal on a zoom-OUT into a soft gradient instead of a hard\n * single-frame pop. The captured video's frames repeat across sub-samples, so\n * the recording's own content is NOT blurred — only the camera move + cursor. */\nexport type MotionBlurConfig = {\n /** sub-frames sampled per output frame. 1 ⇒ OFF (no supersampling, no cost). */\n samples: number;\n /** fraction of the frame interval the shutter is open (0..1). Blur strength;\n * 0 ⇒ OFF. ~0.5 = a 180° shutter, 1 = 360°. */\n shutter: number;\n};\n\n/** One caption window on a review copy: the pill reads `text` from `fromMs`\n * (inclusive) to `toMs` (exclusive) on the composition timeline. */\nexport type ReviewBadge = { fromMs: number; toMs: number; text: string };\n\n/** One viewer-facing caption window on the DELIVERED video: `text` shows\n * bottom-center from `fromMs` (inclusive) to `toMs` (exclusive) on the\n * composition timeline. Unlike ReviewBadge this is a first-class, persisted\n * composition field rendered on masters — footage alone shows WHAT happened;\n * the caption says what it MEANS, which is the difference between a demo a\n * stranger can follow and \"the screen moves around\". Absent ⇒ rendered\n * output is byte-identical to a caption-less composition. */\nexport type Caption = { fromMs: number; toMs: number; text: string };\n\n/** An opening title card: `title` (the app / the thesis) over a full-frame\n * scrim on top of the establishing hold, gone by `untilMs` (300ms fade).\n * Typographic and deterministic — rendered by the scene in the composition's\n * own look, in whatever language the author wrote, deletable like any field\n * — never generated imagery. The single cheapest \"produced, not captured\"\n * signal a demo can send. */\nexport type TitleCard = { title: string; subtitle?: string; untilMs?: number };\n\n/** Render-time decoration for review copies and A/B variant reels: burned-in\n * beat badges, a REVIEW watermark, and a per-variant corner label. Drawn by the\n * scene in SCREEN space (fixed, outside the composition camera) so the text is\n * legible at any zoom. This is a render input only — it is never written into\n * the editable `*.composition.json` artifact (render strips it) and the\n * validator ignores it. Text renders in the headless Chrome, so any script\n * (incl. CJK) works without ffmpeg font filters. */\nexport type ReviewDecor = {\n /** top-right watermark, e.g. \"REVIEW\" — marks a copy as not-for-posting */\n watermark?: string;\n /** bottom-left caption pill, swapping per timeline window */\n badges?: ReviewBadge[];\n /** constant bottom-left variant label for A/B reels, e.g. \"B · tight ×1.8\" */\n label?: string;\n};\n\n/** The auto-camera director's tuning. ON by default (a plan that specifies no\n * zoom must still come out with sensible framing — the whole point). The\n * numbers are the FEEL knobs; judge them by eye on a rendered clip, not on\n * paper. `enabled: false` is the clean escape hatch: the director doesn't run\n * and ONLY explicit `zoom: \"always\"/\"never\"` produce zoom (auto/absent hold\n * full view). There is no legacy per-event heuristic to fall back to. */\nexport type CameraConfig = {\n enabled: boolean;\n /** an ROI fills this fraction of the frame when framed (bigger ⇒ tighter). */\n fillFrac: number;\n /** hard ceiling on scale. NOT the main lever — ROI SIZE drives the actual\n * scale (a big type-ROI lands medium, a tiny icon lands tight); this just\n * stops a pinpoint ROI zooming past legibility. */\n maxScale: number;\n /** a punch that can't stay on screen this long is dropped to full view (a\n * sub-second punch reads as a flinch). Enforced AFTER hard breaks — the hold\n * extends into the gap before the next break, never merges across one. */\n minHoldMs: number;\n /** a scale below this isn't worth a distinct frame: a single beat that fits\n * under it holds full view, and a coalesced cluster whose UNION falls under\n * it splits instead (the two are \"different regions\" → chain/pull, not hold). */\n minZoomScale: number;\n /** gap between two actions greater than this ⇒ they cannot share a frame. */\n coalesceWindowMs: number;\n /** two ROIs whose centres are closer than this (fraction of video width) MAY\n * coalesce into one shared, held frame — the \"cluster\" (a thumbnail rail, a\n * toolbar). Farther apart ⇒ a re-frame (progressive/deeper), not a hold. */\n travelThreshold: number;\n /** changeCoverage ≥ this ⇒ the action repainted most of the frame (nav /\n * global) ⇒ pull out to full view. The nav-vs-popover divider — the one knob\n * to tune by eye on real captures (frame-diff pass populates the input). */\n pullOutCoverage: number;\n};\n\n// Defaults tuned as a STARTING point — every number here is meant to be judged\n// on a rendered clip and A/B'd one at a time, not signed off on paper.\nexport const DEFAULT_CAMERA: CameraConfig = {\n enabled: true,\n fillFrac: 0.6,\n maxScale: 2.4,\n minHoldMs: 1200,\n minZoomScale: 1.25,\n coalesceWindowMs: 900,\n travelThreshold: 0.18,\n pullOutCoverage: 0.55,\n};\n\nexport type TakeComposition = {\n output: { width: number; height: number; fps: number };\n source: {\n videoUrl: string;\n /** stage size the source video is DRAWN at (capture viewport CSS px) —\n * the coordinate space of every event/bbox below. A Retina capture's\n * file is denser (viewport × captureScale); the scene stretches it to\n * this size, so the extra pixels only sharpen sampling under zoom. */\n videoWidth: number;\n videoHeight: number;\n viewport: { w: number; h: number };\n };\n framing: FramingConfig;\n cursor: CursorConfig;\n /** camera motion blur; absent ⇒ off (renders exactly as before). */\n motionBlur?: MotionBlurConfig;\n /** cursor start, video-px */\n start: Pt;\n events: CompEvent[];\n durationMs: number;\n /** Head trim (ms of the composition timeline cut from the delivered mp4).\n * Capture starts at navigation, so the first frames show the app before it\n * painted (plus any cold-cache font swap) — trim them here instead of\n * post-processing with ffmpeg, so the refine loop keeps applying to the file\n * actually shipped. Event tMs values stay on the untrimmed timeline (the\n * capture is the ground truth); only the delivered head moves. 0/absent =\n * no trim. */\n startMs?: number;\n /** Viewer-facing captions, drawn bottom-center in SCREEN space (outside the\n * camera — legible at any zoom) on EVERY render including the master.\n * Persisted and hand-editable like any composition field; times are on the\n * untrimmed composition timeline (same convention as zoom.inAtMs — a\n * caption entirely inside the startMs head trim is never seen, and the\n * validator says so). Seeded from the plan steps' `caption` fields by\n * planComposition. */\n captions?: Caption[];\n /** optional opening title card over the establishing hold (see TitleCard) */\n titleCard?: TitleCard;\n /** render-time review decoration (badges/watermark/label); never persisted\n * (render strips exactly this field — `captions` above deliberately IS\n * persisted; it is content, not review scaffolding) */\n review?: ReviewDecor;\n};\n\n/** True when motion blur is configured to actually do something — whether the\n * delivery encode folds in the tmix shutter average (render.ts deliverMp4;\n * OFF skips tmix but still runs the same single delivery encode). */\nexport function motionBlurActive(mb: MotionBlurConfig | undefined): mb is MotionBlurConfig {\n return !!mb && mb.samples > 1 && mb.shutter > 0;\n}\n\nexport const DEFAULT_FRAMING: FramingConfig = {\n insetFrac: 0.92,\n cornerRadius: 28,\n shadow: { color: \"rgba(0,0,0,0.55)\", blur: 60, offset: { x: 0, y: 28 } },\n background: { from: \"#1e1b3a\", to: \"#0a0e1c\" },\n};\n\n// Camera motion blur, ON by default — it smooths the zoom\n// motion and softens the zoom-OUT backdrop reveal (the model-C hitch). 6\n// sub-frames is a good smoothness/speed balance; ~0.7 shutter is a strong-ish\n// blur without ghosting. EXPORT render cost scales with `samples` (renders at\n// fps·samples then averages), so `samples` is the quality⇄speed knob — drop it\n// to render faster, raise (≤~12) for silkier fast pans.\nexport const DEFAULT_MOTION_BLUR: MotionBlurConfig = {\n samples: 6,\n shutter: 0.7,\n};\n\nexport const DEFAULT_CURSOR: CursorConfig = {\n travelMs: 560,\n // Distance-aware cursor speed — the dominant \"silky\" lever. A fixed duration\n // makes velocity scale with distance (short=slow, long=fast); holding a roughly\n // constant on-screen speed reads consistent/premium. ~0.35 widths/s with the\n // big-move cap (travelMaxMs 850) was tuned by eye to a notch slower than a\n // premium reference recording (svgl.mp4) on this app's long toolbar→canvas\n // moves. Tune up for snappier, down for slower/grander.\n // NOTE on the cap (subtle): travel ENDS at the action's instant, so a LONGER\n // duration starts EARLIER, not later. With the front-loaded ease (below) a\n // longer move therefore reaches the target SOONER — i.e. raising travelMaxMs\n // can read as *faster*. Judge speed by how fast the cursor SWEEPS, not by when\n // it arrives; lower the cap for a more deliberate sweep.\n travelWidthsPerSec: 0.35,\n travelMinMs: 300,\n travelMaxMs: 850,\n scale: 2.0,\n // Near-straight glide. The reference cursor barely bows (measured: a\n // full-width move deviated <2% off the straight line), so the arc is small —\n // just enough to avoid a robotic ruler-straight path, not a visible curve.\n arcFrac: 0.05,\n arcMax: 24,\n rippleMs: 450,\n holdMs: 1100,\n // Camera ramp durations, measured off a reference export by frame-\n // tracking (see math.ts springEase): punch-in spring ω≈9.4 rad/s ≈ 730ms,\n // pull-out ω≈5.2 ≈ 1340ms. The slow soft release is half the premium feel.\n // No zoomEase/zoomSpring set ⇒ stageEasing falls to springEase(0), the\n // critically-damped spring that IS the measured SS curve over these windows.\n zoomOutMs: 1340,\n zoomInMs: 730,\n // Asymptotic settle + pull-out dwell — the A/B \"C variant\" Pascal signed off\n // (2026-07-26): each camera move keeps a ~4% residual settling INTO the hold\n // (no velocity cliff at the keyframe — the frame-tracked reference tail), and\n // a squeezed pull-out stays ≥800ms on the payoff, landing late instead of\n // fleeing a frame the viewer is still reading. Old compositions without the\n // fields keep the legacy cut/squeeze schedule byte-identically.\n zoomSettleFrac: 0.04,\n pullOutDwellMs: 800,\n // The captured ink trails the pen by the screencast/encode pipeline latency τ;\n // delay the cursor by τ so its tip rides the ink front. Set to τ EXACTLY and\n // the cursor locks to the ink at ALL stroke speeds (both are the same time-\n // delay of the same path), which is what makes a SMOOTH (eased) drag work —\n // its fast mid-section amplifies any τ mismatch into a visible lead. Measured\n // τ≈190ms on this pipeline (swept dragLagMs, picked where the tip sits on the\n // ink front mid-stroke); the old 110ms left even linear strokes ~40px ahead.\n // Re-tune if a different machine's encode latency differs.\n dragLagMs: 190,\n // Soft launch + soft landing (gentle accel from rest, peak ~t0.24, decelerate\n // into the target). Chosen over a symmetric ease-in-out (which felt less silky)\n // and over a pure ease-out [.33,1,.68,1] (instant-max launch + a 46%-of-duration\n // creep tail that makes the speed knob lie — see travelMaxMs). This keeps the\n // soft landing (the silk) while trimming the tail to 38% and removing the abrupt\n // launch. Tune toward [0.42,0,0.58,1] for a more uniform sweep.\n travelEase: [0.3, 0.0, 0.2, 1.0],\n};\n","// Curated preset vocabulary — the presets move (named levels, not raw\n// numbers) applied to the conversational refine loop. The composition schema\n// stays raw numbers; presets are a dictionary the CLI/agent speak: the agent\n// writes numbers into composition.json, and `beats`/`ab` reverse-map numbers\n// back to names for display. A value matching no preset displays as \"custom\"\n// and must never be silently rounded to a named level (bbox-derived precision\n// is ground truth).\n\nimport { DEFAULT_MOTION_BLUR } from \"./types\";\nimport type { CursorConfig, FramingConfig, MotionBlurConfig } from \"./types\";\n\n// --- zoom levels (absolute stage scale; rest ≈ 0.92 at same-size output) ----\n// medium matches the planner's default cap (1.5), so agent-planned zooms land\n// on a named level; close stays under the validator's 2.5 soft cap.\nexport const ZOOM_LEVELS = {\n light: 1.25,\n medium: 1.5,\n tight: 1.8,\n close: 2.2,\n} as const;\nexport type ZoomLevelName = keyof typeof ZOOM_LEVELS;\n\n/** Name a scale if it sits within tolerance of a preset; else null (custom). */\nexport function zoomLevelName(scale: number, tol = 0.07): ZoomLevelName | null {\n let best: ZoomLevelName | null = null;\n let bestD = tol;\n for (const [name, v] of Object.entries(ZOOM_LEVELS) as [ZoomLevelName, number][]) {\n const d = Math.abs(scale - v);\n if (d <= bestD) {\n best = name;\n bestD = d;\n }\n }\n return best;\n}\n\n// --- motion (pace) bundles ---------------------------------------------------\n// One name moves the whole feel together: cursor speed + hold + zoom ramps.\n// \"natural\" IS the shipped default (DEFAULT_CURSOR) — naming it makes the\n// default state speakable.\nexport type MotionPreset = Pick<\n CursorConfig,\n | \"travelWidthsPerSec\"\n | \"travelMinMs\"\n | \"travelMaxMs\"\n | \"holdMs\"\n | \"zoomInMs\"\n | \"zoomOutMs\"\n | \"pullOutDwellMs\"\n> & { zoomEase?: undefined };\n// zoomIn/zoomOut anchored to the measured reference springs (730/1340 —\n// see DEFAULT_CURSOR); calm/brisk scale both while keeping out ≈ 1.8× in.\n// pullOutDwellMs (the minimum stay on a payoff before a squeezed pull-out may\n// flee) scales with the same feel: a calm cut breathes longer, a brisk one\n// tolerates a shorter beat. Each preset also CLEARS a legacy zoomEase (spread\n// leaves the key undefined; JSON drops it) so applying a pace migrates an old\n// composition onto the default measured-SS spring curve instead of silently\n// keeping the old bezier.\n//\n// The TRAVEL CLAMPS ride along too, and they have to. They are applied AFTER\n// travelWidthsPerSec, so a preset that moved only the speed left every clamped\n// leg exactly where it was: below ~202px and above ~571px of a 1920 frame,\n// \"calm\" and \"brisk\" rendered IDENTICALLY and nothing said so. Each clamp\n// scales by the pace's own speed ratio against natural (300·0.35/0.28 = 375,\n// 850·0.35/0.45 = 661…), so a leg on a clamp keeps the same relationship to\n// the legs that aren't.\nexport const MOTION: Record<\"calm\" | \"natural\" | \"brisk\", MotionPreset> = {\n calm: {\n travelWidthsPerSec: 0.28,\n travelMinMs: 375,\n travelMaxMs: 1060,\n holdMs: 1500,\n zoomInMs: 900,\n zoomOutMs: 1650,\n pullOutDwellMs: 1000,\n zoomEase: undefined,\n },\n natural: {\n travelWidthsPerSec: 0.35,\n travelMinMs: 300,\n travelMaxMs: 850,\n holdMs: 1100,\n zoomInMs: 730,\n zoomOutMs: 1340,\n pullOutDwellMs: 800,\n zoomEase: undefined,\n },\n brisk: {\n travelWidthsPerSec: 0.45,\n travelMinMs: 235,\n travelMaxMs: 660,\n holdMs: 750,\n zoomInMs: 550,\n zoomOutMs: 1000,\n pullOutDwellMs: 600,\n zoomEase: undefined,\n },\n};\nexport type MotionName = keyof typeof MOTION;\n\n/** A clamp matches its preset — or the LEGACY value every composition carried\n * before the clamps joined the presets. Without that second door, applying\n * \"brisk\" to an old take and re-reading it would report \"custom\" purely\n * because the take predates clamp-aware presets. Same escape hatch\n * pullOutDwellMs already has. */\nexport const CLAMP_TOL_MS = 20;\nconst clampMatches = (v: number | undefined, want: number, legacy: number): boolean =>\n v == null || Math.abs(v - want) < CLAMP_TOL_MS || Math.abs(v - legacy) < 1;\n\nexport function motionName(cursor: CursorConfig): MotionName | null {\n for (const [name, m] of Object.entries(MOTION) as [MotionName, MotionPreset][]) {\n if (\n Math.abs(cursor.travelWidthsPerSec - m.travelWidthsPerSec) < 0.015 &&\n Math.abs(cursor.holdMs - m.holdMs) < 60 &&\n Math.abs(cursor.zoomInMs - m.zoomInMs) < 60 &&\n Math.abs(cursor.zoomOutMs - m.zoomOutMs) < 60 &&\n clampMatches(cursor.travelMinMs, m.travelMinMs, MOTION.natural.travelMinMs) &&\n clampMatches(cursor.travelMaxMs, m.travelMaxMs, MOTION.natural.travelMaxMs) &&\n // absent = a pre-dwell composition — still nameable by its four legacy\n // knobs; only an explicit different value makes the pace \"custom\".\n (cursor.pullOutDwellMs == null ||\n Math.abs(cursor.pullOutDwellMs - (m.pullOutDwellMs ?? 0)) < 60)\n )\n return name;\n }\n return null;\n}\n\n// --- looks (backdrop bundles) ------------------------------------------------\n// A look is the WHOLE backdrop treatment as one coherent bundle — background\n// gradient + corner radius + shadow — so \"paper\" doesn't produce a light\n// backdrop with dark-tuned corners/shadow.\nexport type LookPreset = Pick<FramingConfig, \"background\" | \"cornerRadius\" | \"shadow\">;\nconst DARK_SHADOW: LookPreset[\"shadow\"] = {\n color: \"rgba(0,0,0,0.55)\",\n blur: 60,\n offset: { x: 0, y: 28 },\n};\nexport const LOOKS: Record<string, LookPreset> = {\n midnight: {\n background: { from: \"#1e1b3a\", to: \"#0a0e1c\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n ink: {\n background: { from: \"#16181d\", to: \"#07080a\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n slate: {\n background: { from: \"#232733\", to: \"#0e1116\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n ocean: {\n background: { from: \"#0c2b36\", to: \"#071019\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n plum: {\n background: { from: \"#2a1e3a\", to: \"#140a1c\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n ember: {\n background: { from: \"#38231d\", to: \"#1a0d09\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n paper: {\n background: { from: \"#f6f4ef\", to: \"#ddd8cd\" },\n cornerRadius: 22,\n shadow: { color: \"rgba(31,27,20,0.30)\", blur: 45, offset: { x: 0, y: 20 } },\n },\n plain: {\n background: { from: \"#101014\", to: \"#101014\", type: \"solid\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n};\nexport type LookName = keyof typeof LOOKS;\n\nexport function lookName(framing: FramingConfig): string | null {\n const bg = framing.background;\n for (const [name, l] of Object.entries(LOOKS)) {\n if (\n l.background.from.toLowerCase() === bg.from.toLowerCase() &&\n l.background.to.toLowerCase() === bg.to.toLowerCase() &&\n (l.background.type ?? \"gradient\") === (bg.type ?? \"gradient\")\n )\n return name;\n }\n return null;\n}\n\n// --- finish (motion blur) ----------------------------------------------------\nexport const FINISH: Record<\"smooth\" | \"crisp\" | \"heavy\", MotionBlurConfig | undefined> = {\n smooth: DEFAULT_MOTION_BLUR, // {samples: 6, shutter: 0.7}\n crisp: undefined, // blur off — exports ~6× faster\n heavy: { samples: 8, shutter: 0.85 },\n};\nexport type FinishName = keyof typeof FINISH;\n\nexport function finishName(mb: MotionBlurConfig | undefined): FinishName | null {\n const active = !!mb && mb.samples > 1 && mb.shutter > 0;\n if (!active) return \"crisp\";\n for (const [name, f] of Object.entries(FINISH) as [FinishName, MotionBlurConfig | undefined][]) {\n if (f && mb && f.samples === mb.samples && Math.abs(f.shutter - mb.shutter) < 0.03) return name;\n }\n return null;\n}\n","// ffmpeg/ffprobe resolution — zero-config for npm consumers. Prefer the\n// system binaries on PATH (often newer/faster, and what the repo has always\n// used); fall back to the platform binaries from @ffmpeg-installer/ffmpeg and\n// @ffprobe-installer/ffprobe (direct deps here, and already in the tree via\n// @revideo/ffmpeg — so the fallback costs consumers no extra download). Throw\n// with an install hint only when neither exists.\n\nimport { spawn, spawnSync } from \"node:child_process\";\nimport { chmod, stat } from \"node:fs/promises\";\n\nlet cachedFfmpeg: string | undefined;\nlet cachedFfprobe: string | undefined;\n\nfunction runsOk(bin: string): boolean {\n try {\n return spawnSync(bin, [\"-version\"], { stdio: \"ignore\" }).status === 0;\n } catch {\n return false;\n }\n}\n\nasync function installerPath(pkg: string): Promise<string | null> {\n try {\n const m = (await import(pkg)) as { default?: { path?: string }; path?: string };\n return m.default?.path ?? m.path ?? null;\n } catch {\n return null;\n }\n}\n\n/** Some pnpm installs leave the platform packages' media binaries without an\n * executable bit. Repair the resolved target at the point of use as well as\n * in the repo postinstall: published consumers do not run this monorepo's\n * root lifecycle script. Windows does not use POSIX execute bits. */\nasync function ensureExecutable(path: string | null): Promise<void> {\n if (!path || process.platform === \"win32\") return;\n try {\n const info = await stat(path);\n if ((info.mode & 0o111) === 0) await chmod(path, info.mode | 0o111);\n } catch {\n // Best effort. The normal spawn below still returns the useful failure.\n }\n}\n\n/** Revideo resolves its own bundled ffprobe rather than calling\n * resolveFfprobe(), so repair both installer targets before invoking it. */\nexport async function repairBundledMediaPermissions(): Promise<void> {\n const paths = await Promise.all([\n installerPath(\"@ffmpeg-installer/ffmpeg\"),\n installerPath(\"@ffprobe-installer/ffprobe\"),\n ]);\n await Promise.all(paths.map(ensureExecutable));\n}\n\nexport async function resolveFfmpeg(): Promise<string> {\n if (cachedFfmpeg) return cachedFfmpeg;\n if (runsOk(\"ffmpeg\")) {\n cachedFfmpeg = \"ffmpeg\";\n return cachedFfmpeg;\n }\n const p = await installerPath(\"@ffmpeg-installer/ffmpeg\");\n await ensureExecutable(p);\n if (p && runsOk(p)) {\n cachedFfmpeg = p;\n return p;\n }\n throw new Error(\n \"ffmpeg not found — install it (e.g. `brew install ffmpeg`) or `npm install` so the bundled @ffmpeg-installer binary resolves for this platform\",\n );\n}\n\n/** True when an `ffmpeg -encoders` table has a video-encoder ROW named\n * `encoder` (\" V....D libx264 ...\"), not merely the name as a substring\n * somewhere — descriptions repeat encoder names constantly. */\nexport function parseEncoders(encodersText: string, encoder: string): boolean {\n const escaped = encoder.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`^\\\\s*V\\\\S{5}\\\\s+${escaped}(?:\\\\s|$)`, \"m\").test(encodersText);\n}\n\nconst encoderCache = new Map<string, Promise<boolean>>();\n\n/** True when the RESOLVED ffmpeg (resolveFfmpeg — which may be a system\n * binary lacking libvpx-vp9) offers the named video encoder. Cached per\n * name; any failure is false, never a throw. */\nexport function ffmpegHasEncoder(name: string): Promise<boolean> {\n let cached = encoderCache.get(name);\n if (!cached) {\n cached = hasEncoderOnce(name).catch(() => false);\n encoderCache.set(name, cached);\n }\n return cached;\n}\n\nasync function hasEncoderOnce(name: string): Promise<boolean> {\n const ffmpeg = await resolveFfmpeg();\n const text = await new Promise<string>((res, rej) => {\n const child = spawn(ffmpeg, [\"-hide_banner\", \"-encoders\"], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n let out = \"\";\n child.stdout.on(\"data\", (d) => {\n out += d;\n });\n child.on(\"error\", rej);\n child.on(\"close\", (code) =>\n code === 0 ? res(out) : rej(new Error(`ffmpeg -encoders exited ${code}`)),\n );\n });\n return parseEncoders(text, name);\n}\n\nexport async function resolveFfprobe(): Promise<string> {\n if (cachedFfprobe) return cachedFfprobe;\n if (runsOk(\"ffprobe\")) {\n cachedFfprobe = \"ffprobe\";\n return cachedFfprobe;\n }\n const p = await installerPath(\"@ffprobe-installer/ffprobe\");\n await ensureExecutable(p);\n if (p && runsOk(p)) {\n cachedFfprobe = p;\n return p;\n }\n throw new Error(\n \"ffprobe not found — install ffmpeg (e.g. `brew install ffmpeg`) or `npm install` so the bundled @ffprobe-installer binary resolves for this platform\",\n );\n}\n","// Pure, isomorphic math — imported by both the node-side planner and the\n// revideo scene (compiled fresh by vite at render time). No node/browser\n// APIs in here.\n\nimport type { BBox, Pt, TakeComposition } from \"./types\";\n\n// smootherstep 6t^5-15t^4+10t^3\nexport function smoother(t: number): number {\n const clamped = Math.max(0, Math.min(1, t));\n return clamped * clamped * clamped * (clamped * (clamped * 6 - 15) + 10);\n}\n\n// Cubic-bezier easing y(x) with endpoints (0,0),(1,1) and control points\n// (x1,y1),(x2,y2) — the same model CSS easing uses. Solves x(s)=x by\n// bisection (cheap, monotone) then returns y(s). Lets the travel cursor use a\n// decelerate-biased curve (long, gentle settle) instead of symmetric easing.\nexport function cubicBezier(x1: number, y1: number, x2: number, y2: number): (x: number) => number {\n const bx = (s: number) => {\n const u = 1 - s;\n return 3 * u * u * s * x1 + 3 * u * s * s * x2 + s * s * s;\n };\n const by = (s: number) => {\n const u = 1 - s;\n return 3 * u * u * s * y1 + 3 * u * s * s * y2 + s * s * s;\n };\n return (x: number) => {\n if (x <= 0) return 0;\n if (x >= 1) return 1;\n let lo = 0,\n hi = 1,\n s = x;\n for (let i = 0; i < 24; i++) {\n const xt = bx(s);\n if (Math.abs(xt - x) < 1e-4) break;\n if (xt < x) lo = s;\n else hi = s;\n s = (lo + hi) / 2;\n }\n return by(s);\n };\n}\n\n// Spring-shaped easing y(p) over [0,1]: the unit step response of a damped\n// spring, time-normalised so it rises (and, for bounce>0, slightly overshoots)\n// then settles within the segment. `bounce` ∈ [0, ~0.6): 0 = critically damped\n// (no overshoot — a soft, physical ease-out); higher = more overshoot/snap.\n//\n// bounce 0 over the default zoom durations IS the measured reference zoom\n// feel: frame-tracking a reference export gave a critically-damped spring on the\n// camera rect, ω≈9.4 rad/s in / ω≈5.2 out (which also matches the spring\n// preset numbers from the reference teardown) —\n// i.e. this exact curve over ~730ms in / ~1340ms out.\n//\n// Under time-normalisation the curve depends ONLY on the damping ratio ζ=1−bounce\n// (the natural frequency cancels), so a single `bounce` knob is the whole shape —\n// the segment DURATION stays whatever the keyframes say (zoomInMs/zoomOutMs).\n// The response is normalised by its end value so the segment lands on exactly 1\n// (no end-of-segment snap from the finite settle band).\nexport function springEase(bounce: number): (p: number) => number {\n const zeta = Math.max(0.4, Math.min(1, 1 - bounce));\n const Ts = -Math.log(1e-3) / zeta; // settling time to the 0.1% band (ω0 = 1)\n const step = (t: number): number => {\n if (zeta >= 1) return 1 - Math.exp(-t) * (1 + t); // critically damped\n const wd = Math.sqrt(1 - zeta * zeta); // damped natural frequency (ω0 = 1)\n return 1 - Math.exp(-zeta * t) * (Math.cos(wd * t) + (zeta / wd) * Math.sin(wd * t));\n };\n const end = step(Ts);\n return (p: number) => {\n if (p <= 0) return 0;\n if (p >= 1) return 1;\n return step(p * Ts) / end;\n };\n}\n\n// The stage (camera rect) easing, selected from the cursor config. ONE curve\n// eases the whole rect — centre and size together (see stageCamera). The single\n// source the revideo scene (scene.tsx) AND the editor preview consume — any\n// other renderer must use it identically so renderers can never drift.\n// Precedence: spring (zoomSpring) → cubic-bezier (zoomEase) → the default\n// critically-damped spring (the measured reference curve).\nexport function stageEasing(cursor: TakeComposition[\"cursor\"]): (u: number) => number {\n if (cursor.zoomSpring != null) return springEase(cursor.zoomSpring);\n if (cursor.zoomEase) return cubicBezier(...cursor.zoomEase);\n return springEase(0);\n}\n\n// Backdrop gradient endpoints in TOP-LEFT origin (0..oW, 0..oH), shared by the\n// preview canvas and the revideo scene so the backdrop can't drift. `angle` is\n// CSS-like degrees (0 = upward); absent ⇒ the legacy (0,0)→(oW,oH) diagonal, so\n// existing compositions render pixel-identically. (Scene maps to centred coords\n// by subtracting oW/2, oH/2.)\nexport function gradientEndpoints(\n angleDeg: number | undefined,\n oW: number,\n oH: number,\n): { x0: number; y0: number; x1: number; y1: number } {\n if (angleDeg == null) return { x0: 0, y0: 0, x1: oW, y1: oH };\n const th = (angleDeg * Math.PI) / 180;\n const dx = Math.sin(th);\n const dy = -Math.cos(th);\n const L = Math.abs(oW * dx) + Math.abs(oH * dy); // CSS gradient line length\n const cx = oW / 2;\n const cy = oH / 2;\n return {\n x0: cx - (dx * L) / 2,\n y0: cy - (dy * L) / 2,\n x1: cx + (dx * L) / 2,\n y1: cy + (dy * L) / 2,\n };\n}\n\ntype KF<T> = [number, T];\n\nexport function keyvalN(\n t: number,\n kfs: KF<number>[],\n ease: (u: number) => number = smoother,\n): number {\n if (t <= kfs[0]![0]) return kfs[0]![1];\n if (t >= kfs[kfs.length - 1]![0]) return kfs[kfs.length - 1]![1];\n for (let i = 0; i < kfs.length - 1; i++) {\n const [t0, v0] = kfs[i]!;\n const [t1, v1] = kfs[i + 1]!;\n if (t0 <= t && t <= t1) {\n return v0 + (v1 - v0) * ease((t - t0) / (t1 - t0));\n }\n }\n return kfs[kfs.length - 1]![1];\n}\n\n// --- bbox-fit zoom (Finding 1) -----------------------------------------\n\n/**\n * Scale (absolute, video-px → output-px) that fits `bbox` into `fillFrac`\n * of the output frame, capped at `maxScale` and floored at `restScale`.\n * Wide/long elements naturally get a gentler scale because the limiting\n * dimension dominates min().\n */\nexport function bboxFitScale(\n bbox: BBox,\n outW: number,\n outH: number,\n fillFrac: number,\n maxScale: number,\n restScale: number,\n): number {\n const fitW = (outW * fillFrac) / Math.max(1, bbox.w);\n const fitH = (outH * fillFrac) / Math.max(1, bbox.h);\n return Math.min(maxScale, Math.max(restScale, Math.min(fitW, fitH)));\n}\n\n/** Stage scale at rest: video inset into the frame (leaves backdrop margin). */\nexport function restStageScale(\n videoW: number,\n videoH: number,\n outW: number,\n outH: number,\n insetFrac: number,\n): number {\n return insetFrac * Math.min(outW / videoW, outH / videoH);\n}\n\n/**\n * Clamp a desired video-px center so the scaled video still covers the output\n * frame (the viewport crop stays inside the source video) when zoomed in. When\n * the content does not cover an axis (zoomed out / inset), centre that axis.\n *\n * In the composition-camera model the whole composition\n * (backdrop + inset screen) is zoomed by one camera; this keeps the camera crop\n * within the screen so a zoom fills the frame (no backdrop margin) without ever\n * panning past the recording's edge.\n */\nexport function clampCenter(\n center: Pt,\n scale: number,\n videoW: number,\n videoH: number,\n outW: number,\n outH: number,\n): Pt {\n const halfW = outW / (2 * scale);\n const halfH = outH / (2 * scale);\n const cx =\n videoW * scale >= outW ? Math.min(Math.max(center.x, halfW), videoW - halfW) : videoW / 2;\n const cy =\n videoH * scale >= outH ? Math.min(Math.max(center.y, halfH), videoH - halfH) : videoH / 2;\n return { x: cx, y: cy };\n}\n\n// --- stage (camera rect) keyframes from the composition ----------------\n\n/** The camera as a viewport RECT in video-px: centre + full viewport width\n * (height is implied by the output aspect: h = w·oH/oW). scale = oW / w. */\nexport type CamRect = { cx: number; cy: number; w: number };\n\nexport type StageKeyframes = {\n r: KF<CamRect>[]; // viewport rect over time (seconds)\n T: number; // total duration (s)\n};\n\n/** Interpolate the rect track: centre AND size move under the SAME eased\n * parameter. This is the whole trick (verified\n * by frame-tracking a reference export: its pan curve overlays its viewport-WIDTH\n * curve exactly, not its scale curve): lerping the rect keeps every corner on\n * a straight line, so the screen-space path of the zoom target is strictly\n * monotone toward frame centre — no wrong-way \"bounce\" for ANY scale pair,\n * which scale+centre lerp can't guarantee (it hooks when scale > 2×rest). */\nexport function keyvalR(t: number, kfs: KF<CamRect>[], ease: (u: number) => number): CamRect {\n if (t <= kfs[0]![0]) return kfs[0]![1];\n if (t >= kfs[kfs.length - 1]![0]) return kfs[kfs.length - 1]![1];\n for (let i = 0; i < kfs.length - 1; i++) {\n const [t0, v0] = kfs[i]!;\n const [t1, v1] = kfs[i + 1]!;\n if (t0 <= t && t <= t1) {\n const p = ease((t - t0) / (t1 - t0));\n // A spring ease (zoomSpring > 0) overshoots p past 1, extrapolating the\n // rect beyond its target — that's the wanted \"snap\", but on a deep punch\n // with a large bounce the extrapolated width could collapse through 0\n // (scale sign-flip = garbage frames). Floor the width against the\n // segment's own endpoints so overshoot can tighten at most 2× past the\n // tighter one; monotone eases (p ∈ [0,1]) never hit the floor.\n return {\n cx: v0.cx + (v1.cx - v0.cx) * p,\n cy: v0.cy + (v1.cy - v0.cy) * p,\n w: Math.max(v0.w + (v1.w - v0.w) * p, Math.min(v0.w, v1.w) * 0.5),\n };\n }\n }\n return kfs[kfs.length - 1]![1];\n}\n\n// The camera schedule shared by buildStageKeyframes (the render path) and\n// cameraRampSchedule (the refine surfaces — A/B windows, review badges): which\n// events anchor a camera move, when each ramp departs, and when it lands.\n// One computation so the badge/window timing can never drift from the render.\ntype CameraSchedule = {\n anchors: {\n evIdx: number;\n tMs: number;\n durationMs: number;\n inAtMs: number;\n scale: number;\n center: Pt;\n glide?: Pt;\n }[];\n targets: CamRect[];\n restR: CamRect;\n /** per-anchor ramp window, SECONDS */\n ramps: { start: number; end: number }[];\n /** per-anchor landing time, SECONDS (≥ ramp start + a minimal real ramp;\n * == tMs for every on-time ramp, later for a dwell-delayed pull-out or a\n * reveal-timed press whose ramp departs AT the action) */\n landTs: number[];\n rectFor: (center: Pt, scale: number) => CamRect;\n};\n\nfunction buildCameraSchedule(comp: TakeComposition): CameraSchedule {\n const { videoWidth: vW, videoHeight: vH } = comp.source;\n const { width: oW, height: oH } = comp.output;\n const rest = restStageScale(vW, vH, oW, oH, comp.framing.insetFrac);\n const restC: Pt = { x: vW / 2, y: vH / 2 };\n const ZOUT_MS = comp.cursor.zoomOutMs;\n\n // A framing target is clamped ONCE, here at build time (the viewport crop\n // stays inside the recording; an axis it doesn't cover centres). Every\n // keyframe rect is therefore valid — and for a monotone ease (p ∈ [0,1];\n // every default) lerped rect corners stay between the endpoints' corners, so\n // every IN-BETWEEN rect is valid too. No per-frame clamp, so the clamp can\n // never bend a path mid-flight (the old model's per-frame clamp force-\n // centred the pan while the video under-covered the frame, then released it\n // mid-zoom — a visible lurch; and its zoom-out \"land the centre early\"\n // repair made pull-outs pan-then-zoom two-phase). A zoomSpring bounce > 0\n // deliberately overshoots PAST the target rect (edge-flush targets can\n // flash a sliver of backdrop during the settle — the physical cost of\n // bounce; keyvalR floors only the width collapse).\n const rectFor = (center: Pt, scale: number): CamRect => {\n const c = clampCenter(center, scale, vW, vH, oW, oH);\n return { cx: c.x, cy: c.y, w: oW / scale };\n };\n const restR = rectFor(restC, rest);\n\n // Framing anchors over time. A zoom-enabled beat ramps to its target; a\n // scroll (content pans) and a zoom-less press (Escape/Enter whose effect is\n // global) ramp back to REST so the frame is full-view through them — without\n // these, a prior zoom would persist across the scroll/keypress. Every OTHER\n // disabled beat (a \"never\" click/hover/type/drag) means the same thing —\n // the director only ever disables a beat to show it FULL-VIEW — so it too\n // anchors to rest, but only while the camera is actually away from rest: a\n // disabled beat over an already-resting camera adds no anchor, keeping\n // legacy compositions (and their badge/A/B windows) byte-identical. The old\n // hold-prior-framing behavior left a `zoom:\"never\"` GLOBAL payoff cropped\n // inside the previous beat's punch (the 2026-07-27 interlinear field run).\n const anchors: CameraSchedule[\"anchors\"] = [];\n const awayFromRest = (): boolean => {\n const a = anchors[anchors.length - 1];\n if (!a) return false;\n return (\n Math.abs(a.scale - rest) > 1e-6 ||\n Math.abs(a.center.x - restC.x) > 0.5 ||\n Math.abs(a.center.y - restC.y) > 0.5\n );\n };\n comp.events.forEach((e, evIdx) => {\n const base = { evIdx, tMs: e.tMs, durationMs: e.durationMs ?? 0, inAtMs: e.zoom.inAtMs };\n if (e.kind === \"scroll\" || (!e.zoom.enabled && (e.kind === \"press\" || awayFromRest()))) {\n anchors.push({ ...base, scale: rest, center: restC });\n } else if (e.zoom.enabled) {\n anchors.push({ ...base, scale: e.zoom.scale, center: e.zoom.center, glide: e.zoom.glide });\n }\n });\n\n const targets = anchors.map((e) => rectFor(e.center, e.scale));\n\n // Effective ramp start per anchor. A PULL-OUT (wider viewport than the rect\n // it leaves) paces with zoomOutMs — measured on the reference export,\n // the pull-out is ~1.8× slower than the punch-in. The stored inAtMs keeps\n // governing punch-ins/same-size travels, and a HAND-SET inAtMs (≠ the\n // planner default tMs − zoomInMs) wins even for a pull-out, so the per-beat\n // timing knob stays live. When the zoomOutMs window would start before the\n // previous action's end, shorten it toward the punch-in window rather than\n // cut the payoff — but NEVER squeeze below min(zoomOutMs, zoomInMs) of real\n // ramp: a pull-out with no window is a jump cut, which is strictly worse\n // than leaving a payoff a little early.\n const ZIN_MS = comp.cursor.zoomInMs;\n const DWELL_MS = comp.cursor.pullOutDwellMs ?? 0;\n // A ramp whose departure sits AT/after its own action is REVEAL-timed: the\n // planner pins a zoom-enabled press there (its payoff exists only after the\n // keypress — a lead-in would punch into empty space), and a hand-set late\n // inAtMs means the same thing. Landing at tMs would make start === end (a\n // jump cut), so these get a full ramp window AFTER the departure instead.\n const revealTimed = (e: { inAtMs: number; tMs: number }): boolean => e.inAtMs >= e.tMs;\n const ramps = anchors.map((e, i) => {\n const from = i > 0 ? targets[i - 1]! : restR;\n const pullOut = targets[i]!.w > from.w + 1e-6;\n if (revealTimed(e))\n return { start: e.inAtMs / 1000, end: (e.inAtMs + (pullOut ? ZOUT_MS : ZIN_MS)) / 1000 };\n const isDefaultInAt = Math.abs(e.inAtMs - Math.max(0, e.tMs - ZIN_MS)) < 1;\n if (!pullOut || !isDefaultInAt) return { start: e.inAtMs / 1000, end: e.tMs / 1000 };\n const desired = e.tMs - ZOUT_MS;\n const prevEndMs = i > 0 ? anchors[i - 1]!.tMs + anchors[i - 1]!.durationMs : 0;\n const floor = prevEndMs + DWELL_MS;\n if (desired >= floor) return { start: Math.max(desired, 0) / 1000, end: e.tMs / 1000 };\n if (DWELL_MS > 0) {\n // The dwell floor pushes the departure past the on-time window: keep the\n // full pull-out ramp and LAND LATE (after the action instant) rather than\n // flee a frame the viewer is still reading. The landing is capped at the\n // next anchor's ramp start at push time.\n return { start: floor / 1000, end: (floor + ZOUT_MS) / 1000 };\n }\n const start = Math.min(prevEndMs, e.tMs - Math.min(ZOUT_MS, ZIN_MS));\n return { start: Math.max(start, 0) / 1000, end: e.tMs / 1000 };\n });\n // Second pass: a dwell-floored ramp must still FIT a real ramp before the\n // next anchor departs — otherwise the landT cap would invert it into a\n // 1ms jump cut (push()'s monotone clamp collapses it). Give up dwell time\n // before ramp time: shrink the dwell so at least min(zoomOutMs, zoomInMs)\n // of real ramp survives, and when even zero dwell has no room fall back to\n // the exact legacy squeeze. (Anchor starts never depend on earlier ramps'\n // ends, so one forward pass over pass-1 values is complete.)\n if (DWELL_MS > 0) {\n const minRamp = Math.min(ZOUT_MS, ZIN_MS);\n for (let i = 0; i < ramps.length - 1; i++) {\n const r = ramps[i]!;\n const e = anchors[i]!;\n if (revealTimed(e)) continue; // fitted in the reveal pass below (departure is pinned)\n if (r.end <= e.tMs / 1000 + 1e-9) continue; // on-time ramp — not dwell-late\n const latestStart = ramps[i + 1]!.start - 0.01 - minRamp / 1000;\n if (r.start <= latestStart) continue; // the late landing fits\n const prevEndMs = i > 0 ? anchors[i - 1]!.tMs + anchors[i - 1]!.durationMs : 0;\n if (latestStart * 1000 >= prevEndMs) {\n r.start = latestStart;\n r.end = Math.min(r.start + ZOUT_MS / 1000, ramps[i + 1]!.start - 0.01);\n } else {\n const start = Math.min(prevEndMs, e.tMs - minRamp);\n r.start = Math.max(start, 0) / 1000;\n r.end = e.tMs / 1000;\n }\n }\n }\n\n // Reveal fit pass: a reveal-timed ramp's departure is PINNED at the action —\n // moving it earlier would re-create the exact artifact this timing removes\n // (zooming into a reveal that doesn't exist yet). When the full window would\n // run into the next anchor's departure, shrink the ramp (a faster punch)\n // instead, floored at half a window so it still reads as a move; anything\n // tighter falls to push()'s monotone clamp like any other crowding.\n const REVEAL_MIN_S = Math.min(ZOUT_MS, ZIN_MS) / 2000;\n for (let i = 0; i < ramps.length; i++) {\n if (!revealTimed(anchors[i]!)) continue;\n const r = ramps[i]!;\n const nextStart = i + 1 < ramps.length ? ramps[i + 1]!.start : Number.POSITIVE_INFINITY;\n r.end = Math.max(r.start + REVEAL_MIN_S, Math.min(r.end, nextStart - 0.01));\n }\n\n // A dwell-delayed pull-out lands after its own action instant; cap the\n // landing so it can never run into the next anchor's ramp (floored at a\n // minimal real ramp — the fits-check in the dwell pass guarantees room).\n // An on-time ramp (end === tMs, every legacy entry) keeps the exact old\n // landing; a pass-2-shrunk ramp may deliberately land BEFORE its tMs. A\n // reveal-timed ramp was already fitted above — it lands exactly at its end.\n const landTs = anchors.map((e, i) => {\n const nextStart = anchors[i + 1] ? ramps[i + 1]!.start : Number.POSITIVE_INFINITY;\n const rampEnd = ramps[i]!.end;\n if (revealTimed(e)) return rampEnd;\n return rampEnd === e.tMs / 1000\n ? rampEnd\n : Math.max(\n ramps[i]!.start + Math.min(ZOUT_MS, ZIN_MS) / 1000,\n Math.min(rampEnd, nextStart - 0.01),\n );\n });\n\n return { anchors, targets, restR, ramps, landTs, rectFor };\n}\n\n/** Per-EVENT camera ramp timing (ms), for the refine surfaces (A/B windows,\n * review badges): when the camera actually departs toward a beat and when it\n * lands. `null` for a beat the camera holds through (no anchor). Derived from\n * the same schedule the render uses, so a dwell-delayed pull-out (which\n * departs after the stored inAtMs and can land after its own tMs) is\n * reflected instead of approximated from inAtMs. `pullOut` says which pace\n * knob the window belongs to (zoomOutMs vs zoomInMs) — the same test the\n * schedule itself makes, so a reader can't drift from it. */\nexport function cameraRampSchedule(\n comp: TakeComposition,\n): ({ startMs: number; landMs: number; pullOut: boolean } | null)[] {\n const { anchors, targets, restR, ramps, landTs } = buildCameraSchedule(comp);\n const out: ({ startMs: number; landMs: number; pullOut: boolean } | null)[] = comp.events.map(\n () => null,\n );\n anchors.forEach((a, i) => {\n const from = i > 0 ? targets[i - 1]! : restR;\n out[a.evIdx] = {\n startMs: ramps[i]!.start * 1000,\n landMs: landTs[i]! * 1000,\n pullOut: targets[i]!.w > from.w + 1e-6,\n };\n });\n return out;\n}\n\nexport function buildStageKeyframes(comp: TakeComposition): StageKeyframes {\n const { anchors, targets, restR, ramps, landTs, rectFor } = buildCameraSchedule(comp);\n const HOLD = comp.cursor.holdMs / 1000;\n const ZOUT_MS = comp.cursor.zoomOutMs;\n\n const rf: { t: number; r: CamRect }[] = [{ t: 0, r: restR }];\n const push = (t: number, r: CamRect) => {\n rf.push({ t: Math.max(t, rf[rf.length - 1]!.t + 1e-3), r });\n };\n\n let cur = restR;\n anchors.forEach((e, i) => {\n // the action plays out (typing/drawing/scrolling) for durationMs after tMs\n // — hold the target framing through it (a point click has duration 0).\n const actionEnd = (e.tMs + e.durationMs) / 1000;\n const next = anchors[i + 1];\n const nextStart = next ? ramps[i + 1]!.start : Number.POSITIVE_INFINITY;\n const landT = landTs[i]!;\n const holdEndT = Math.max(next ? nextStart : actionEnd + HOLD, landT);\n push(ramps[i]!.start, cur); // hold current until ramp begins\n push(landT, targets[i]!); // ONE eased rect segment lands at the action\n cur = targets[i]!;\n // glide: drift the held centre across the hold window (velocity px/s ·\n // holdSeconds), so a held zoom slowly pans instead of sitting dead-static.\n // Clamped like any target so the drift can't leave the recording.\n let holdR = cur;\n if (e.glide && (e.glide.x !== 0 || e.glide.y !== 0)) {\n const holdDur = Math.max(0, holdEndT - landT);\n holdR = rectFor(\n { x: e.center.x + e.glide.x * holdDur, y: e.center.y + e.glide.y * holdDur },\n e.scale,\n );\n }\n push(holdEndT, holdR); // hold (or glide) until the next ramp / the tail\n cur = holdR;\n if (!next) {\n push(holdEndT + ZOUT_MS / 1000, restR); // final zoom-out, one rect segment\n cur = restR;\n }\n });\n\n const lastT = rf[rf.length - 1]!.t;\n const T = Math.max(comp.durationMs / 1000, lastT) + 0.3;\n push(T, restR);\n\n return { r: rf.map((f) => [f.t, f.r]), T };\n}\n\n// --- asymptotic settle (zoomSettleFrac) --------------------------------\n\n/** Residual (1 − progress) of an overdamped spring's unit step response, on\n * NORMALISED segment time u = (t − t0)/(t1 − t0). ω0 is solved so the\n * residual at u=1 (the action instant) equals `frac`; past u=1 the same\n * curve keeps decaying — the tail that replaces the legacy cut. ζ=1.2 gives\n * the reference-measured shape: a fast main ramp (peak velocity ~14% in)\n * plus a slow settle pole; at frac 0.04 the tail τ ≈ duration/3.6 (730ms →\n * ~205ms, 1340ms → ~375ms — the frame-tracked reference tails; a different\n * frac shifts ω0 and with it τ). */\nfunction settleDecay(frac: number): (u: number) => number {\n const zeta = 1.2;\n const s = Math.sqrt(zeta * zeta - 1);\n const l1 = zeta + s;\n const l2 = zeta - s;\n const resid = (x: number) => (l1 * Math.exp(-l2 * x) - l2 * Math.exp(-l1 * x)) / (l1 - l2);\n let lo = 0.1;\n let hi = 60;\n for (let i = 0; i < 60; i++) {\n const mid = (lo + hi) / 2;\n if (resid(mid) > frac) lo = mid;\n else hi = mid;\n }\n const w0T = (lo + hi) / 2;\n return (u: number) => (u <= 0 ? 1 : resid(w0T * u));\n}\n\n/** Evaluate the rect track with moves that settle ASYMPTOTICALLY: each ramp\n * covers 1−frac of its distance by its keyframe end, then keeps creeping\n * toward the target through the following hold (never a velocity cliff). A\n * ramp launches from wherever the previous tail actually is (position-\n * continuous chaining); every emitted rect is a convex combination of\n * build-time-clamped rects, and the valid-rect set is convex (linear\n * half-plane bounds in cx,cy,w), so in-between rects stay valid exactly as\n * in the lerped path. */\nfunction settleRectAt(kfs: KF<CamRect>[], decay: (u: number) => number, t: number): CamRect {\n let from = kfs[0]![1];\n for (let i = 0; i < kfs.length - 1; i++) {\n const [t0, r0] = kfs[i]!;\n const [t1, r1] = kfs[i + 1]!;\n if (r0.cx === r1.cx && r0.cy === r1.cy && r0.w === r1.w) continue; // hold — the active tail keeps running\n if (t < t0) break;\n // find when the NEXT move begins — this move's tail runs until then\n let handoff = Number.POSITIVE_INFINITY;\n for (let j = i + 1; j < kfs.length - 1; j++) {\n const [ta, ra] = kfs[j]!;\n const [, rb] = kfs[j + 1]!;\n if (ra.cx !== rb.cx || ra.cy !== rb.cy || ra.w !== rb.w) {\n handoff = ta;\n break;\n }\n }\n const evalT = Math.min(t, handoff);\n const d = decay((evalT - t0) / Math.max(t1 - t0, 1e-6));\n from = {\n cx: r1.cx + (from.cx - r1.cx) * d,\n cy: r1.cy + (from.cy - r1.cy) * d,\n w: r1.w + (from.w - r1.w) * d,\n };\n if (t < handoff) return from;\n }\n return from;\n}\n\n/** The one camera evaluator — scene.tsx (render) and the editor preview both\n * consume THIS, so preview and export can never drift. */\nexport function stageCamera(comp: TakeComposition): {\n T: number;\n rest: number;\n peakScale: number;\n at: (t: number) => { scale: number; center: Pt };\n} {\n const stage = buildStageKeyframes(comp);\n const ease = stageEasing(comp.cursor);\n const oW = comp.output.width;\n const rest = restStageScale(\n comp.source.videoWidth,\n comp.source.videoHeight,\n oW,\n comp.output.height,\n comp.framing.insetFrac,\n );\n // zoomSettleFrac swaps the segment-lerped track for the asymptotic-settle\n // evaluator; explicit zoomSpring/zoomEase keep their exact legacy curves.\n const frac = comp.cursor.zoomSettleFrac ?? 0;\n const useSettle = frac > 0 && comp.cursor.zoomSpring == null && !comp.cursor.zoomEase;\n const decay = useSettle ? settleDecay(frac) : undefined;\n const at = (t: number) => {\n const r = decay ? settleRectAt(stage.r, decay, t) : keyvalR(t, stage.r, ease);\n return { scale: oW / r.w, center: { x: r.cx, y: r.cy } };\n };\n // Peak by sampling (not just keyframe extremes): a spring ease overshoots\n // mid-segment, so the true peak can sit above every keyframe.\n let peakScale = stage.r.reduce((m, [, r]) => Math.max(m, oW / r.w), rest);\n for (let i = 0; i <= 720; i++) peakScale = Math.max(peakScale, at((i / 720) * stage.T).scale);\n return { T: stage.T, rest, peakScale, at };\n}\n\n// --- cursor path (eased, with gentle arc) ------------------------------\n\n// A `drag` leg carries the polyline the cursor follows with the button held\n// (no perpendicular arc — it traces the real stroke). A normal travel leg has\n// no path and gets the gentle arc.\ntype Leg = {\n t0: number;\n t1: number;\n a: Pt;\n b: Pt;\n drag?: boolean;\n path?: Pt[];\n ease?: \"linear\" | \"smooth\";\n /** Diagnostics only (never read by the render): which travel clamp, if\n * either, set this leg's duration instead of the speed law. The clamps run\n * AFTER the speed model, so a clamped leg is one where `travelWidthsPerSec`\n * — and therefore the whole `pace` preset — has no say. validate.ts reports\n * it when it stops being the exception and becomes the rule. */\n clamped?: \"min\" | \"max\";\n /** Diagnostics only: the duration (s) the clamped speed law asked for. When\n * the delivered `t1 - t0` is shorter, the previous beat's action ran too\n * late to leave room and the move is being rushed — a CAPTURE-side gap no\n * cursor knob can fix. `evIdx` is the event this leg travels to. */\n wantSec?: number;\n evIdx?: number;\n};\n\n/** Cumulative ∫ (rest / cameraScale) dt over the take, on a uniform grid.\n *\n * The integrand is how much of the DELIVERED frame one video-px of movement\n * buys, normalised so a camera at rest integrates to 1 — so this converts a\n * video-px path into the distance the VIEWER actually sees it cross, and\n * INVERTING it answers \"when must this move depart to hold a constant\n * on-screen speed\". Strictly increasing (the integrand is > 0), so the\n * inverse is single-valued and a binary search finds it. Outside the sampled\n * window the end value extrapolates linearly at the end slope.\n *\n * This is a function of the camera schedule alone (which reads comp.events /\n * comp.cursor, never the legs), so pricing a leg with it introduces no cycle. */\nfunction zoomFracTrack(cam: { T: number; rest: number; at: (t: number) => { scale: number } }) {\n const STEP = 0.005; // 5ms — ~150× finer than the shortest shipped camera ramp\n const n = Math.max(2, Math.min(20000, Math.ceil(cam.T / STEP) + 1));\n const step = cam.T > 0 ? cam.T / (n - 1) : STEP;\n const zf = (t: number) => cam.rest / Math.max(cam.at(t).scale, 1e-6);\n const cum = new Float64Array(n);\n const zf0 = zf(0);\n let prev = zf0;\n for (let i = 1; i < n; i++) {\n const v = zf(i * step);\n cum[i] = cum[i - 1]! + ((prev + v) / 2) * step; // trapezoid\n prev = v;\n }\n const zfT = prev;\n const tEnd = (n - 1) * step;\n const last = cum[n - 1]!;\n return {\n at(t: number): number {\n if (t <= 0) return t * zf0;\n if (t >= tEnd) return last + (t - tEnd) * zfT;\n const i = Math.floor(t / step);\n const f = t / step - i;\n return cum[i]! + (cum[i + 1]! - cum[i]!) * f;\n },\n /** the t at which the cumulative integral equals `y` */\n invert(y: number): number {\n if (y <= 0) return zf0 > 0 ? y / zf0 : 0;\n if (y >= last) return tEnd + (zfT > 0 ? (y - last) / zfT : 0);\n let lo = 0;\n let hi = n - 1;\n while (hi - lo > 1) {\n const mid = (lo + hi) >> 1;\n if (cum[mid]! <= y) lo = mid;\n else hi = mid;\n }\n const span = cum[hi]! - cum[lo]!;\n return (lo + (span > 0 ? (y - cum[lo]!) / span : 0)) * step;\n },\n };\n}\n\nexport function buildLegs(comp: TakeComposition): Leg[] {\n const legs: Leg[] = [];\n let cur: Pt = comp.start;\n // When the previous beat's ACTION finishes (tMs + durationMs) — not when its\n // travel leg landed. See the prevEnd comment below.\n let freeAt = 0;\n // Distance-aware travel: hold a roughly constant on-screen speed (premium\n // feel) instead of a fixed duration (which makes short moves slow + long\n // moves fast). Falls back to the fixed travelMs when speed is unset/0.\n const { travelWidthsPerSec, travelMinMs, travelMaxMs, travelMs } = comp.cursor;\n // ON-SCREEN means the DELIVERED frame, not the raw recording. While the\n // camera is zoomed in, a video-px move covers proportionally more of the\n // frame — so a zoom-blind duration makes every zoomed move read that many\n // times too fast, precisely where the viewer is looking closest (a 2x punch\n // -in doubles the apparent speed).\n // The magnification is not constant ACROSS a leg, though: a travel typically\n // departs while the camera is still wide and lands after it has closed in, so\n // pricing the whole leg at the ARRIVAL magnification (the most punched-in\n // instant it ever sees) over-slows the departure by as much as it was\n // previously over-fast. Solve the honest thing instead — depart at the\n // instant from which the INTEGRATED on-screen distance to the target equals\n // one leg's worth of travel at the reference speed — which is exactly what\n // inverting the zoomFrac track does. A camera that never leaves rest\n // integrates to the identity, so a full-view take keeps its measured-by-eye\n // calibration bit-for-bit (short-circuited below to keep that exact).\n // Built lazily: only a composition that actually travels needs the camera,\n // and a zoom-less take must not pay for the track.\n let cam: ReturnType<typeof stageCamera> | undefined;\n let track: ReturnType<typeof zoomFracTrack> | undefined;\n const travelDur = (a: Pt, b: Pt, arriveSec: number): { sec: number; clamped?: \"min\" | \"max\" } => {\n if (!travelWidthsPerSec) return { sec: travelMs / 1000 };\n const speedPxPerSec = travelWidthsPerSec * comp.source.videoWidth;\n if (speedPxPerSec <= 0) return { sec: travelMs / 1000 };\n const dist = Math.hypot(b.x - a.x, b.y - a.y);\n cam ??= stageCamera(comp);\n let ms: number;\n if (cam.peakScale <= cam.rest + 1e-9) {\n ms = (dist / speedPxPerSec) * 1000; // camera never leaves rest — closed form\n } else {\n track ??= zoomFracTrack(cam);\n ms = (arriveSec - track.invert(track.at(arriveSec) - dist / speedPxPerSec)) * 1000;\n }\n if (ms < travelMinMs) return { sec: travelMinMs / 1000, clamped: \"min\" };\n if (ms > travelMaxMs) return { sec: travelMaxMs / 1000, clamped: \"max\" };\n return { sec: ms / 1000 };\n };\n for (const [evIdx, e] of comp.events.entries()) {\n // scroll/press/look are not pointer-driven — the cursor holds where it was\n // (the content pans / the keyboard acts / the CAMERA does the moving). No\n // travel leg; `cur` is untouched, so the between-legs parking logic keeps\n // the cursor at its last anchor. For a look this parking IS the feature:\n // cursor movement promises an action, and a look makes none — the camera\n // frames the target while the cursor honestly stays put.\n // They still OCCUPY the frame for durationMs, though: a scroll's duration IS\n // the pan, a press's is the reveal animating in, a look's is the framed\n // hold. A travel that departs into any of them puts two motions on screen\n // at once — content sliding under a cursor crossing it — so they push\n // `freeAt` exactly like a pointer beat even though they contribute no leg.\n if (e.kind === \"scroll\" || e.kind === \"press\" || e.kind === \"look\") {\n freeAt = Math.max(freeAt, (e.tMs + (e.durationMs ?? 0)) / 1000);\n continue;\n }\n const arrive = e.tMs / 1000;\n // Start travelDur before arrival, but never before the previous leg ended\n // (a long glide into a quick succession would otherwise overlap it — then\n // the move just runs in the available window, a touch faster than target)\n // and never before the previous beat's ACTION finished. A travel leg ends\n // at its tMs, but a `type` keeps emitting keystrokes for durationMs after\n // that — so the leg end alone would let a long enough glide drag the\n // pointer off the field mid-word.\n // …and never AFTER the arrival: overlapping action windows (only reachable\n // by hand — a capture always leaves a settle gap) would otherwise build an\n // INVERTED leg, which matches no instant at all in cursorPos, so the cursor\n // would silently jump-cut instead of degrading to a hard landing.\n const prevEnd = Math.max(legs.length ? legs[legs.length - 1]!.t1 : 0, freeAt);\n const d = travelDur(cur, e.point, arrive);\n const t0 = Math.min(arrive, Math.max(arrive - d.sec, prevEnd, 0));\n legs.push({\n t0,\n t1: arrive,\n a: cur,\n b: e.point,\n evIdx,\n wantSec: d.sec,\n ...(d.clamped ? { clamped: d.clamped } : {}),\n });\n cur = e.point;\n freeAt = Math.max(freeAt, (e.tMs + (e.durationMs ?? 0)) / 1000);\n if ((e.kind === \"drag\" || e.kind === \"dropFiles\") && e.to) {\n // Delay the stroke by dragLagMs so the cursor rides the captured ink front\n // (the ink trails the pen by the capture-pipeline latency). The cursor\n // holds at the start point during the gap [arrive, arrive+lag], then traces\n // — matching when the ink actually appears on screen. A dropFiles carry\n // has no ink, but the page's dragover reaction rode the same capture\n // pipeline, so the same lag keeps cursor and reaction in step.\n const lag = comp.cursor.dragLagMs / 1000;\n const start = arrive + lag;\n const dEnd = (e.tMs + (e.durationMs ?? 0)) / 1000 + lag;\n const path = e.path && e.path.length >= 2 ? e.path : [e.point, e.to];\n if (dEnd > start)\n legs.push({ t0: start, t1: dEnd, a: e.point, b: e.to, drag: true, path, ease: e.ease });\n cur = e.to;\n }\n }\n return legs;\n}\n\n/** Point a fraction `u` (0..1) along a polyline, parameterised by arc length. */\nfunction alongPath(path: Pt[], u: number): Pt {\n if (path.length === 1) return path[0]!;\n const seg: number[] = [];\n let total = 0;\n for (let i = 0; i < path.length - 1; i++) {\n const d = Math.hypot(path[i + 1]!.x - path[i]!.x, path[i + 1]!.y - path[i]!.y);\n seg.push(d);\n total += d;\n }\n if (total === 0) return path[0]!;\n let target = u * total;\n for (let i = 0; i < seg.length; i++) {\n if (target <= seg[i]! || i === seg.length - 1) {\n const f = seg[i]! > 0 ? target / seg[i]! : 0;\n return {\n x: path[i]!.x + (path[i + 1]!.x - path[i]!.x) * f,\n y: path[i]!.y + (path[i + 1]!.y - path[i]!.y) * f,\n };\n }\n target -= seg[i]!;\n }\n return path[path.length - 1]!;\n}\n\nexport function cursorPos(t: number, legs: Leg[], comp: TakeComposition): Pt {\n for (const lg of legs) {\n if (lg.t0 <= t && t <= lg.t1) {\n // A ZERO-span leg (a departure clamped all the way to its own arrival —\n // see buildLegs) has landed by definition; without the guard the 0/0\n // would put NaN through the ease and blank the cursor for that frame.\n const span = lg.t1 - lg.t0;\n const raw = span > 0 ? Math.max(0, Math.min(1, (t - lg.t0) / span)) : 1;\n // A drag replays the captured stroke's pacing so the cursor stays locked\n // to the ink: \"smooth\" (accel-in / decel-out — a natural hand-draw) or\n // \"linear\" (constant speed). The capture bakes the SAME curve into the ink\n // (cdp-capture.ts) and records it on the event; absent ⇒ linear (legacy).\n // (Held-button moves are fire-and-forget there, so the slow eased ends —\n // sub-pixel, no paint — no longer stall the stroke; cursor and ink are\n // both ~stationary at the ends, so they stay locked.)\n if (lg.drag && lg.path) return alongPath(lg.path, lg.ease === \"smooth\" ? smoother(raw) : raw);\n const e = comp.cursor.travelEase;\n const p = e ? cubicBezier(e[0], e[1], e[2], e[3])(raw) : smoother(raw);\n const base = { x: lg.a.x + (lg.b.x - lg.a.x) * p, y: lg.a.y + (lg.b.y - lg.a.y) * p };\n const dx = lg.b.x - lg.a.x,\n dy = lg.b.y - lg.a.y;\n const L = Math.hypot(dx, dy) || 1;\n const arc = Math.min(comp.cursor.arcFrac * L, comp.cursor.arcMax) * Math.sin(Math.PI * p);\n return { x: base.x + (-dy / L) * arc, y: base.y + (dx / L) * arc };\n }\n }\n if (legs.length === 0 || t < legs[0]!.t0) return comp.start;\n for (let i = 0; i < legs.length - 1; i++)\n if (legs[i]!.t1 < t && t < legs[i + 1]!.t0) return legs[i]!.b;\n return legs[legs.length - 1]!.b;\n}\n\n/** True while a drag is mid-stroke (button held) — for the pressed cursor. */\nexport function isDragging(t: number, legs: Leg[]): boolean {\n return legs.some((lg) => lg.drag === true && lg.t0 <= t && t <= lg.t1);\n}\n\n// --- file ghost card (dropFiles) ----------------------------------------\n\n/** A dropFiles carry's on-screen window [start, end] in SECONDS — when the\n * ghost card rides the cursor. Same dragLagMs shift as the carry leg in\n * buildLegs, so card and cursor cannot drift apart. Shared by the Revideo\n * scene and the editor preview (the no-drift invariant). */\nexport function carryWindow(\n e: { tMs: number; durationMs?: number },\n comp: TakeComposition,\n): { t0: number; t1: number } {\n const lag = comp.cursor.dragLagMs / 1000;\n const t0 = e.tMs / 1000 + lag;\n return { t0, t1: t0 + (e.durationMs ?? 0) / 1000 };\n}\n\n/** \"1.2 MB\" / \"412 KB\" — the ghost card's size caption (scene + preview). */\nexport function fmtBytes(n: number): string {\n return n >= 1024 * 1024\n ? `${(n / 1024 / 1024).toFixed(1)} MB`\n : `${Math.max(1, Math.round(n / 1024))} KB`;\n}\n\n/** The ghost card's two text lines for a dropFiles beat: the (first) filename,\n * and a meta caption (\"3 files · 1.8 MB\" / \"1.2 MB\"). Shared scene/preview.\n * Long filenames middle-ellipse (extension kept) so the card can't outgrow\n * the frame — neither render surface clamps its width. */\nexport function ghostCardLines(files: { name: string; size?: number }[]): {\n title: string;\n meta: string;\n} {\n const raw = files[0]?.name ?? \"file\";\n const MAX = 34;\n const title = raw.length <= MAX ? raw : `${raw.slice(0, MAX - 12)}…${raw.slice(raw.length - 11)}`;\n const total = files.reduce((s, f) => s + (f.size ?? 0), 0);\n const size = total > 0 ? fmtBytes(total) : \"\";\n const count = files.length > 1 ? `${files.length} files` : \"\";\n return { title, meta: [count, size].filter(Boolean).join(\" · \") };\n}\n","// camera.ts — the auto-camera DIRECTOR.\n//\n// Zoom is DECIDED here, deterministically, from the ground-truth event log — NOT\n// by the authoring agent (which decides pre-capture, blind, and every model has\n// its own bias), and NOT per-event in isolation. The director runs over the\n// WHOLE beat sequence so it can do the three things a per-event heuristic can't:\n//\n// 1. shape the region-of-interest PER KIND — a `type`'s payoff grows DOWN out\n// of the thin field, so the ROI (and thus the scale) is result-sized, not\n// strip-sized;\n// 2. COALESCE a burst of nearby small interactions into ONE sustained frame\n// (a thumbnail rail / toolbar), instead of punch-pull flicker per beat;\n// 3. PULL OUT for a global repaint (nav / restyle) — read off the capture's\n// changed-area, not guessed from a bbox that looks identical to a popover's.\n//\n// Output stays in the editable representation: one framing decision per beat\n// (enabled / scale / center + a human-readable reason). A \"cluster\" is just\n// every beat in it sharing the SAME scale+center — buildStageKeyframes then\n// holds the camera across them for free (no new schema, no new keyframe code).\n//\n// Pure & synchronous: it reads only fields already on the beats, including the\n// capture-derived effectBox / changeCoverage seam. The frame-diff (or, later,\n// mutation) pass that POPULATES those fields lives in the runtime (node) layer;\n// the director itself never does I/O, so it stays snapshot-testable.\n\nimport { bboxFitScale } from \"./math\";\nimport type { BBox, CameraConfig, Pt, ZoomIntent } from \"./types\";\n\n/** One action, already mapped into video-px, handed to the director. */\nexport type Beat = {\n kind: \"click\" | \"type\" | \"drag\" | \"scroll\" | \"hover\" | \"look\" | \"press\" | \"dropFiles\";\n tMs: number;\n durationMs: number;\n /** element bbox (for a drag: the path's bbox), video-px — or undefined for a\n * bare press (no located element). */\n box?: BBox;\n /** the region that actually changed after the action (frame-diff seam),\n * video-px. Framed over `box` when present. */\n effectBox?: BBox;\n /** fraction of the frame that changed after the action, 0..1. */\n changeCoverage?: number;\n /** anchor / cursor rest point, video-px (for the reason only). */\n point: Pt;\n /** plan override; absent ⇒ \"auto\" (the director decides). */\n intent: ZoomIntent;\n /** short label (sel / note) for the cluster tag in the reason. */\n label?: string;\n /** press only: the key chord (for the Escape-dismissal rule). */\n keys?: string;\n};\n\n/** The director's per-beat verdict. plan.ts adds `inAtMs` to make a full\n * ZoomDecision. */\nexport type Framing = {\n enabled: boolean;\n scale: number;\n center: Pt;\n reason: string;\n};\n\nconst centerOf = (b: BBox): Pt => ({ x: b.x + b.w / 2, y: b.y + b.h / 2 });\nconst dist = (a: Pt, b: Pt): number => Math.hypot(a.x - b.x, a.y - b.y);\nconst union = (a: BBox, b: BBox): BBox => {\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n return { x, y, w: Math.max(a.x + a.w, b.x + b.w) - x, h: Math.max(a.y + a.h, b.y + b.h) - y };\n};\n\n// A `type` field is a thin strip; its payoff (search results, an AI answer)\n// grows DOWNWARD out of it. Framing the strip alone puts dead header above and\n// crops the result below. Grow the ROI down (never up) so the frame sits over\n// field + result: a taller ROI ⇒ lower scale AND a centre that drops below the\n// field — both correct. For a type this also CAPS the effectBox height: a\n// search/filter result list is open-ended, so the raw frame-diff region can\n// span the whole viewport and flatten the punch to ~1× — growDown bounds how far\n// down the frame reaches while the effectBox still supplies the real reveal width.\nfunction growDown(box: BBox, video: { w: number; h: number }): BBox {\n const grownH = Math.max(box.h, Math.min(video.h * 0.42, box.w * 0.55));\n const h = Math.min(grownH, video.h - box.y); // never spill past the video edge\n return { x: box.x, y: box.y, w: box.w, h };\n}\n\n/** The region a beat is \"about\" — what the camera should frame. A type is\n * field-anchored and height-capped (its reveal is open-ended); every other\n * kind trusts the captured effect region, else shapes one from the bbox. */\nfunction roiForBeat(b: Beat, video: { w: number; h: number }): BBox | undefined {\n // A press with an EXPLICIT zoom=always + a located reveal element: the\n // author named exactly what to frame — that box outranks the frame-diff\n // effectBox. A press payoff behind a scrim (modal / command palette) diffs\n // as a full-frame repaint, which would flatten the punch to ~1× (issue #3);\n // and a tiny incidental effectBox (a save indicator) would yank the frame\n // somewhere else entirely (issue #8). click/hover keep effectBox preference:\n // there the payoff usually lands AWAY from the element, which is the whole\n // point of the frame-diff seam.\n if (b.kind === \"press\" && b.intent === \"always\" && b.box) return b.box;\n // A look names exactly what to frame — that IS the beat. Nothing happened on\n // the page, so any effectBox is neighbouring noise (an animation, a ticking\n // number), and preferring it would aim the \"show the viewer this\" camera at\n // something else entirely.\n if (b.kind === \"look\" && b.box) return b.box;\n if (b.kind === \"type\" && b.box) {\n // Bound the frame to \"field + top of results\": keep the effectBox's real\n // reveal WIDTH, but cap the HEIGHT to growDown's result-sized window so an\n // open-ended result list can't flatten the punch to ~1× (see growDown).\n const capH = growDown(b.box, video).h;\n if (b.effectBox) {\n const x = Math.min(b.box.x, b.effectBox.x);\n const right = Math.max(b.box.x + b.box.w, b.effectBox.x + b.effectBox.w);\n const bottom = b.effectBox.y + b.effectBox.h;\n // Floor at the field height so a reveal that lands at/above the field top\n // (a rare upward-opening autocomplete) can't yield a zero/negative ROI —\n // we then simply frame the field, never punch into the vacated space above.\n const h = Math.max(b.box.h, Math.min(capH, bottom - b.box.y));\n return { x, y: b.box.y, w: right - x, h };\n }\n return growDown(b.box, video);\n }\n if (b.effectBox) return b.effectBox;\n if (!b.box) return undefined;\n return b.box;\n}\n\nfunction clusterLabel(beats: Beat[], idx: number[]): string {\n const raw = beats[idx[0]!]?.label ?? \"\";\n const cleaned = raw.replace(/\\s+/g, \" \").trim().slice(0, 18);\n return cleaned || \"region\";\n}\n\ntype Node = {\n roi?: BBox;\n scale: number; // fit of its OWN roi (rest if none)\n forceFull: boolean; // must show full view (scroll / never / global repaint / no-roi / orienting)\n forcePunch: boolean; // its own isolated punch (intent === \"always\")\n boundary: boolean; // starts a new segment regardless of similarity\n reason: string;\n};\n\ntype Seg = {\n idx: number[];\n kind: \"rest\" | \"punch\";\n roi?: BBox;\n scale: number;\n center: Pt;\n dropped?: boolean; // a punch demoted to rest by min-hold\n};\n\n/**\n * Decide framing for every beat. `endMs` is when the last frame can hold until\n * (for the min-hold check on the final segment). `rest` is the stage scale at\n * full view.\n */\nexport function directCamera(\n beats: Beat[],\n video: { w: number; h: number },\n out: { w: number; h: number },\n cam: CameraConfig,\n rest: number,\n endMs: number,\n): Framing[] {\n const restC: Pt = { x: video.w / 2, y: video.h / 2 };\n const fit = (roi: BBox) => bboxFitScale(roi, out.w, out.h, cam.fillFrac, cam.maxScale, rest);\n\n // --- phase 1: per-beat ROI + hard-break classification ---------------------\n const nodes: Node[] = beats.map((b, i) => {\n const roi = roiForBeat(b, video);\n const scale = roi ? fit(roi) : rest;\n const gapBreak =\n i > 0 && b.tMs - (beats[i - 1]!.tMs + beats[i - 1]!.durationMs) > cam.coalesceWindowMs;\n\n // explicit overrides win, and are segment boundaries (Q2 / point 3).\n if (b.intent === \"never\")\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"plan: zoom=never → full view\",\n };\n if (b.intent === \"always\") {\n // An explicit \"always\" must never ship a no-op: a wide ROI can fit-scale\n // into the imperceptible band (rest…~1.1×) and render an enabled zoom\n // the eye can't see (issue #1). Floor at minZoomScale — the author asked\n // for a punch, so give the smallest one that reads as one.\n const floored = roi ? Math.max(scale, cam.minZoomScale) : scale;\n return {\n roi,\n scale: floored,\n forceFull: false,\n forcePunch: true,\n boundary: true,\n reason: roi\n ? floored > scale\n ? `plan: zoom=always → ROI fit ${scale.toFixed(2)}× is imperceptible — floored to ${floored.toFixed(2)}× (fits ≠ legible: raise zoom.scale if the payoff is fine text)`\n : `plan: zoom=always → ${floored.toFixed(2)}× (framing from ROI)`\n : \"plan: zoom=always but no bbox to frame → full view\",\n };\n }\n\n // a scroll is a pan beat: content moves, the frame stays full-view.\n if (b.kind === \"scroll\")\n return {\n roi: undefined,\n scale: rest,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"scroll — full view (content pans)\",\n };\n\n // Escape DISMISSES: its visual change is something VANISHING, so the\n // frame-diff effectBox is the vacated region — framing it would punch into\n // blank space. The editorial payoff of a dismissal is the restored page.\n if (b.kind === \"press\" && b.keys && /(^|\\+)esc(ape)?$/i.test(b.keys.trim()))\n return {\n roi: undefined,\n scale: rest,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"Escape (dismissal) — full view\",\n };\n\n // global repaint (nav / restyle): the payoff is the whole page → pull out.\n // Needs the frame-diff annotation; without it this branch is skipped (the\n // director can't tell nav from popover on a bbox alone — say so).\n if (b.changeCoverage != null && b.changeCoverage >= cam.pullOutCoverage)\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: `changeCoverage ${b.changeCoverage.toFixed(2)} ≥ ${cam.pullOutCoverage} (global repaint) → full view`,\n };\n\n // the opening beat orients: open on the whole app (Q3 — falls out of \"the\n // camera opens full\", no zoomFirst flag). A cold-open uses zoom=always.\n // Only when the beat actually opens the video, though: a first action ≥2s\n // in (a leading `wait`, a slow warmup) already gave the viewer the full\n // view — forcing it wide again just robs the hero moment (issue #2; the\n // default warmup alone puts an immediate first action at ~1s).\n if (i === 0 && b.tMs < 2000)\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"opening beat — full view (orienting)\",\n };\n\n // nothing locatable to frame (a bare Escape/Enter with no reveal).\n if (!roi)\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"no bbox to frame → full view\",\n };\n\n // not tight enough to earn a distinct frame (a big element fills it already).\n if (scale < cam.minZoomScale)\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: gapBreak,\n reason: `ROI fills the frame already (fit ${scale.toFixed(2)}× < ${cam.minZoomScale}×) — full view`,\n };\n\n // an ordinary punchable beat — eligible to coalesce with its neighbours.\n return {\n roi,\n scale,\n forceFull: false,\n forcePunch: false,\n boundary: gapBreak,\n reason: `punch ${scale.toFixed(2)}× (ROI-fit)`,\n };\n });\n\n // --- phase 2: coalesce adjacent punchable beats into shared-frame clusters --\n const segs: Seg[] = [];\n for (let i = 0; i < nodes.length; i++) {\n const n = nodes[i]!;\n if (n.forceFull) {\n segs.push({ idx: [i], kind: \"rest\", scale: rest, center: restC });\n continue;\n }\n const last = segs[segs.length - 1];\n const lastLastIdx = last ? last.idx[last.idx.length - 1]! : -1;\n const canExtend =\n !!last &&\n last.kind === \"punch\" &&\n !!last.roi &&\n !n.forcePunch &&\n !nodes[lastLastIdx]!.forcePunch &&\n !n.boundary &&\n !!n.roi &&\n dist(centerOf(n.roi), centerOf(last.roi)) < cam.travelThreshold * video.w &&\n fit(union(last.roi, n.roi)) >= cam.minZoomScale; // union must stay tight enough\n\n if (canExtend && last?.roi && n.roi) {\n const roi = union(last.roi, n.roi);\n last.idx.push(i);\n last.roi = roi;\n last.scale = fit(roi);\n last.center = centerOf(roi);\n } else {\n segs.push({\n idx: [i],\n kind: \"punch\",\n roi: n.roi,\n scale: n.scale,\n center: n.roi ? centerOf(n.roi) : restC,\n });\n }\n }\n\n // --- phase 3: min-hold — extend into the gap before the next break; a punch\n // that still can't clear minHoldMs is a flinch → drop it to full view. NEVER\n // merges across a break (order: hard break → coalesce → min-hold).\n segs.forEach((s, si) => {\n if (s.kind !== \"punch\") return;\n // A look segment is exempt: its hold length is the AUTHOR'S statement\n // (\"show the viewer this for durationMs\"), not a derived gap — demoting it\n // to full view would delete the beat's entire content. A tight look reads\n // brisk, not flinchy, because nothing else competes for the frame.\n if (s.idx.some((i) => beats[i]!.kind === \"look\")) return;\n const firstT = beats[s.idx[0]!]!.tMs;\n const next = segs[si + 1];\n const heldUntil = next ? beats[next.idx[0]!]!.tMs : endMs;\n if (heldUntil - firstT < cam.minHoldMs) {\n s.kind = \"rest\";\n s.scale = rest;\n s.center = restC;\n s.dropped = true;\n }\n });\n\n // --- assemble per-beat framing --------------------------------------------\n const framings: Framing[] = new Array(beats.length);\n for (const s of segs) {\n if (s.kind === \"rest\") {\n for (const i of s.idx)\n framings[i] = {\n enabled: false,\n scale: rest,\n center: restC,\n reason: s.dropped\n ? `punch dropped — held < ${cam.minHoldMs}ms (would flinch) → full view`\n : nodes[i]!.reason,\n };\n continue;\n }\n const N = s.idx.length;\n const tag = N > 1 ? `cluster[${clusterLabel(beats, s.idx)}]` : null;\n s.idx.forEach((i, k) => {\n framings[i] = {\n enabled: true,\n scale: s.scale,\n center: s.center,\n reason: tag\n ? `${tag} ${k + 1}/${N} · hold shared framing (union of ${N}) → ${s.scale.toFixed(2)}×`\n : nodes[i]!.reason,\n };\n });\n }\n return framings;\n}\n","// planComposition: capture event log -> default editable TakeComposition.\n//\n// Coordinate mapping (capture viewport px -> video px) and the per-beat\n// scaffolding live here; the ZOOM decision is delegated to the camera DIRECTOR\n// (camera.ts), which runs over the whole beat sequence with the real bbox /\n// timing / changed-area from the ground-truth log. Every decision it makes is\n// still written per-beat into the composition (enabled/scale/center + reason)\n// so a human/agent can read and tune it.\n\nimport { type Beat, directCamera } from \"./camera\";\nimport { restStageScale } from \"./math\";\nimport {\n type BBox,\n type CameraConfig,\n type Caption,\n type CaptureLog,\n type CompEvent,\n type CursorConfig,\n DEFAULT_CAMERA,\n DEFAULT_CURSOR,\n DEFAULT_FRAMING,\n DEFAULT_MOTION_BLUR,\n type FramingConfig,\n type Pt,\n type TakeComposition,\n type ZoomDecision,\n} from \"./types\";\n\nexport type PlanOpts = {\n output?: { width?: number; height?: number; fps?: number };\n framing?: Partial<FramingConfig>;\n cursor?: Partial<CursorConfig>;\n /** auto-camera director tuning (default DEFAULT_CAMERA — ON). The director\n * decides zoom from the ground-truth log; these are its feel knobs. Set\n * `camera.enabled = false` for the manual escape hatch (only explicit\n * event `zoom: \"always\"/\"never\"` produce zoom then). */\n camera?: Partial<CameraConfig>;\n};\n\nexport function planComposition(log: CaptureLog, opts: PlanOpts = {}): TakeComposition {\n // Stage space = the capture VIEWPORT (CSS px), NOT the video file's pixel\n // size. A Retina capture (captureScale 2) records a 2×-dense bitmap of the\n // same viewport; the scene draws it at viewport size, so the denser bitmap\n // only sharpens sampling under zoom. Keying the stage to the viewport keeps\n // every calibrated quantity — camera scales (rest/minZoomScale/maxScale),\n // cursor/ripple sizes, framing radius/shadow — meaning the same thing at\n // any capture density. (Pre-Retina logs have video == viewport, so this is\n // byte-identical for them.)\n const vW = log.viewport.w,\n vH = log.viewport.h;\n const oW = opts.output?.width ?? vW;\n const oH = opts.output?.height ?? vH;\n const fps = opts.output?.fps ?? 30;\n\n const framing: FramingConfig = { ...DEFAULT_FRAMING, ...opts.framing };\n const cursor: CursorConfig = { ...DEFAULT_CURSOR, ...opts.cursor };\n const camera: CameraConfig = { ...DEFAULT_CAMERA, ...opts.camera };\n\n // log coords (viewport CSS px) -> stage px. Identity today (stage IS the\n // viewport); kept as an explicit mapping seam.\n const sx = vW / log.viewport.w;\n const sy = vH / log.viewport.h;\n const mapPt = (p: Pt): Pt => ({ x: p.x * sx, y: p.y * sy });\n const mapBox = (b: BBox): BBox => ({ x: b.x * sx, y: b.y * sy, w: b.w * sx, h: b.h * sy });\n\n const rest = restStageScale(vW, vH, oW, oH, framing.insetFrac);\n\n // Axis-aligned bbox of a polyline (video-px), so a drag frames the WHOLE\n // stroke (a path, not a point): a big cross-canvas drag fits ≈ rest → no zoom.\n const pathBBox = (pts: Pt[]): BBox => {\n const xs = pts.map((p) => p.x),\n ys = pts.map((p) => p.y);\n const x = Math.min(...xs),\n y = Math.min(...ys);\n return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y };\n };\n\n // --- map every event into video-px scaffolding (kind-agnostic zoom yet) -----\n type Scaffold = {\n beat: Beat;\n ev: Omit<CompEvent, \"zoom\">;\n };\n\n const scaffolds: Scaffold[] = log.events.map((c) => {\n const kind = c.kind ?? \"click\";\n const point = mapPt({ x: c.x, y: c.y });\n const intent = c.zoom ?? \"auto\";\n const durationMs = \"durationMs\" in c ? c.durationMs : 0;\n\n // drag / dropFiles: cursor path + the region we frame is the path's bbox\n const carries = kind === \"drag\" || kind === \"dropFiles\";\n const to = carries ? mapPt((c as { to: Pt }).to) : undefined;\n const rawPath = carries\n ? ((c as { path?: Pt[] }).path ?? [{ x: c.x, y: c.y }, (c as { to: Pt }).to])\n : undefined;\n const path = rawPath?.map(mapPt);\n const ease = carries ? (c as { ease?: \"linear\" | \"smooth\" }).ease : undefined;\n\n // the element bbox (ground truth): a carry → path bbox, else the captured box\n const bbox = carries && path ? pathBBox(path) : c.box ? mapBox(c.box) : undefined;\n const effectBox = c.effectBox ? mapBox(c.effectBox) : undefined;\n const label = c.sel ?? c.note;\n\n const beat: Beat = {\n kind,\n tMs: c.tMs,\n durationMs,\n box: bbox,\n effectBox,\n changeCoverage: c.changeCoverage,\n point,\n intent,\n label,\n ...(kind === \"press\" ? { keys: (c as { keys?: string }).keys } : {}),\n };\n\n const ev: Omit<CompEvent, \"zoom\"> = {\n kind,\n tMs: c.tMs,\n point,\n bbox,\n label,\n ...(durationMs ? { durationMs } : {}),\n ...(kind === \"type\" ? { text: (c as { text: string }).text } : {}),\n ...(kind === \"press\" ? { keys: (c as { keys: string }).keys } : {}),\n ...(to ? { to } : {}),\n ...(path ? { path } : {}),\n ...(ease ? { ease } : {}),\n ...(kind === \"dropFiles\"\n ? { files: (c as { files: { name: string; size?: number }[] }).files }\n : {}),\n };\n return { beat, ev };\n });\n\n const beats = scaffolds.map((s) => s.beat);\n\n // horizon for the min-hold check on the final segment\n const last = log.events.length ? log.events[log.events.length - 1]! : undefined;\n const lastEnd = last ? last.tMs + (\"durationMs\" in last ? last.durationMs : 0) : 0;\n const endMs = Math.max(log.tEndMs ?? 0, lastEnd + cursor.holdMs);\n\n // --- decide framing --------------------------------------------------------\n // director ON (default): decide from the log. OFF: the manual escape hatch —\n // only explicit always/never produce zoom, auto/absent hold full view.\n const framings = camera.enabled\n ? directCamera(beats, { w: vW, h: vH }, { w: oW, h: oH }, camera, rest, endMs)\n : beats.map((b) => manualFraming(b, rest));\n\n const events: CompEvent[] = scaffolds.map((s, i) => {\n const f = framings[i]!;\n const zoom: ZoomDecision = {\n enabled: f.enabled,\n scale: f.scale,\n center: f.center,\n // zoom-in ramp starts zoomInMs before the action (decoupled from cursor\n // travelMs so the zoom can be slower/gentler — a more cinematic feel).\n // EXCEPT a zoom-enabled press: its payoff (palette / modal / result)\n // exists only AFTER the keypress, and a keypress has no on-screen\n // antecedent to anticipate — a lead-in punches into empty space and the\n // reveal then pops inside an already-committed frame. The camera departs\n // AT the action and rides the reveal in (buildCameraSchedule gives a\n // late-departing ramp its full window after the departure).\n inAtMs:\n f.enabled && s.beat.kind === \"press\"\n ? s.beat.tMs\n : Math.max(0, s.beat.tMs - cursor.zoomInMs),\n reason: f.reason,\n };\n return { ...s.ev, zoom };\n });\n\n const start = log.start ? mapPt(log.start) : { x: vW * 0.25, y: vH * 0.9 };\n const durationMs = Math.max(log.tEndMs ?? 0, lastEnd + cursor.holdMs + cursor.zoomOutMs + 400);\n\n // --- captions: per-step caption strings → viewer-facing subtitle windows.\n // Deterministic tiling ANCHORED AT ACTION INSTANTS: a caption lands exactly\n // when its beat's action does — the camera has finished (or nearly finished)\n // its move by then, so the swap happens over a settled frame. Anchoring at\n // the zoom DEPARTURE (the first design) put every caption swap inside a\n // camera ramp, and two simultaneous motions read as \"the subtitle moves\n // with the zoom\" — the field complaint that moved the anchor here. A\n // caption holds until the next beat's action (never narrating someone\n // else's beat); the last one rides out to the end. All times\n // untrimmed-timeline, editable afterwards like any composition field.\n const captions: Caption[] = [];\n log.events.forEach((c, i) => {\n const text = c.caption?.trim();\n if (!text) return;\n const e = events[i]!;\n const prevEnd = captions.length ? captions[captions.length - 1]!.toMs : 0;\n const fromMs = Math.max(e.tMs, prevEnd);\n const next = events[i + 1];\n const toMs = Math.max(fromMs + 300, next ? next.tMs : durationMs);\n captions.push({ fromMs, toMs, text });\n });\n\n return {\n output: { width: oW, height: oH, fps },\n source: { videoUrl: \"/capture.mp4\", videoWidth: vW, videoHeight: vH, viewport: log.viewport },\n framing,\n cursor,\n motionBlur: DEFAULT_MOTION_BLUR,\n start,\n events,\n durationMs,\n ...(captions.length ? { captions } : {}),\n };\n}\n\n// Manual mode (camera.enabled === false): the director does not run. Only an\n// explicit plan intent produces zoom — \"always\" frames the element bbox, every-\n// thing else holds full view. Deliberately dumb: this is the fully-hand-driven\n// escape hatch, not a second heuristic.\nfunction manualFraming(\n b: Beat,\n rest: number,\n): {\n enabled: boolean;\n scale: number;\n center: Pt;\n reason: string;\n} {\n if (b.intent === \"always\" && b.box) {\n return {\n enabled: true,\n scale: rest, // manual mode leaves scale for the human to raise; frame the bbox\n center: { x: b.box.x + b.box.w / 2, y: b.box.y + b.box.h / 2 },\n reason: \"camera off · plan: zoom=always (raise scale by hand)\",\n };\n }\n return {\n enabled: false,\n scale: rest,\n center: b.point,\n reason: \"camera off · full view (no explicit zoom)\",\n };\n}\n","// The decode guard's shared vocabulary — imported by BOTH sides of the\n// browser/Node boundary. The scene (src/scene/scene.tsx, vite-compiled inside\n// the render browser) probes the capture with a throwaway <video> and rejects\n// with a message built here; render.ts (Node) recognises that rejection and\n// retries with a VP9 intermediate. Only the message STRING survives the\n// crossing — revideo forwards e.message through onRenderFailed — so the\n// contract is a sentinel substring, not an error class.\n//\n// Keep this module dependency-free: the scene tree is copied verbatim into\n// the render scratch and compiled for the browser, so a node:* import here\n// would break the scene build.\n\nexport const CAPTURE_UNDECODABLE_MARK = \"capture video is not decodable in the render browser\";\n\n/** Build the guard's rejection message. Both variants START with the mark so\n * isCaptureUndecodable can match the forwarded string. */\nexport function buildUndecodableMessage(\n kind: \"media-error\" | \"timeout\",\n detail: string,\n src: string,\n): string {\n const why =\n kind === \"media-error\"\n ? `decode failed (${detail}) — this Chromium likely lacks the capture's codec`\n : `no decode within 30s (${detail}) — the render browser may lack the capture's codec`;\n return `${CAPTURE_UNDECODABLE_MARK}: ${why}; src=${src}`;\n}\n\n/** Did this render rejection come from the scene's decode guard? Substring\n * match on the message — the Error identity does not survive the\n * browser→Node crossing. */\nexport function isCaptureUndecodable(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err);\n return message.includes(CAPTURE_UNDECODABLE_MARK);\n}\n","// validateComposition: a NON-MUTATING structural check on an edited\n// composition. The refine loop is \"edit the JSON, re-render\" — so the agent\n// (or a human) hand-edits `*.composition.json`, and this gives a\n// millisecond, field-specific verdict BEFORE paying for a render. It never\n// changes the composition; it only reports.\n//\n// Severity:\n// \"error\" — the render would be wrong/broken (or silently mis-framed).\n// renderTake refuses to render until these are fixed.\n// \"warn\" — suspect, but may be intentional. Rendered as-is.\n//\n// The single most important check is the capture-lock (see CAPTURE-LOCKED\n// below): an action beat's `tMs` is bound to the recording — the video frame\n// at time t shows the page AS IT WAS at capture-time t — so re-rendering with\n// a moved `tMs` desyncs the overlay from the on-screen action. Retiming an\n// action needs a re-capture, not a JSON edit. Pass the capture log to enforce\n// this; without it the check is skipped (we can't know the ground truth).\n\nimport { buildLegs, buildStageKeyframes, cameraRampSchedule, restStageScale } from \"./math\";\nimport { CLAMP_TOL_MS, MOTION, motionName } from \"./presets\";\nimport { DEFAULT_CURSOR } from \"./types\";\nimport type { CaptureLog, TakeComposition } from \"./types\";\n\n/** Tail past the last beat's settle that still reads as \"the shot breathing\".\n * Beyond it the delivered mp4 is a frozen screen — the padded-to-25s failure. */\nconst DEAD_TAIL_MS = 2500;\n/** A dwell-delayed pull-out lands a little after its own action BY DESIGN, and\n * a tail of a few frames is invisible (the spring has all but arrived). The\n * artifact is a camera that has barely LEFT when the action fires — so gate on\n * both an absolute floor and the fraction of the ramp still to run. */\nconst MOVING_AT_ACTION_MS = 150;\nconst MOVING_AT_ACTION_FRAC = 0.25;\n/** How far past the SLOWEST shipped pace a camera window may run before it is\n * worth a word. Anchored on the preset vocabulary rather than a number\n * invented here, so the ceiling tracks the presets if they are ever retuned. */\nconst RAMP_SLACK = 2;\n/** A travel clamp binding on the odd short hop is the point of having clamps;\n * binding on more than this share of the legs means the speed law (and the\n * whole `pace` preset) is not what paces the take. Under CLAMPED_LEGS_MIN legs\n * the share says nothing — two clamped legs out of two is a fixture, not a\n * finding. */\nconst CLAMPED_LEGS_FRAC = 0.5;\nconst CLAMPED_LEGS_MIN = 3;\n/** A travel squeezed under this share of what the speed law asked for reads as\n * a dart rather than a glide. Paired with an absolute floor so a few-frame\n * shortfall on an already-short hop stays quiet. */\nconst SQUEEZE_FRAC = 0.7;\nconst SQUEEZE_MIN_MS = 200;\n\nexport type CompositionIssue = {\n severity: \"error\" | \"warn\";\n /** dotted/indexed field path, e.g. \"events[3].zoom.scale\" */\n path: string;\n message: string;\n /** a concrete suggested correction the agent can apply */\n fix?: string;\n};\n\nexport type ValidateOpts = {\n /** soft ceiling on zoom scale — above it the pixels visibly soften (warn).\n * Default 2.5 (the planner caps auto-zoom at 1.5; manual edits get headroom). */\n maxScale?: number;\n /** the ground-truth capture log. When given, action `tMs` is checked against\n * it (capture-lock). Omit to skip that check. */\n captureLog?: CaptureLog;\n};\n\nconst reqField: Record<string, string> = {\n type: \"text\",\n press: \"keys\",\n drag: \"to\",\n dropFiles: \"to\",\n // a look IS its hold — without a duration there is no beat to render\n look: \"durationMs\",\n};\n\nexport function validateComposition(\n comp: TakeComposition,\n opts: ValidateOpts = {},\n): CompositionIssue[] {\n const issues: CompositionIssue[] = [];\n const err = (path: string, message: string, fix?: string) =>\n issues.push({ severity: \"error\", path, message, fix });\n const warn = (path: string, message: string, fix?: string) =>\n issues.push({ severity: \"warn\", path, message, fix });\n\n const maxScale = opts.maxScale ?? 2.5;\n\n // --- output / source sanity ---\n const { width: oW, height: oH, fps } = comp.output;\n if (!(oW > 0 && oH > 0))\n err(\"output\", `non-positive output size ${oW}x${oH}`, \"set positive width/height\");\n if (!(fps > 0)) err(\"output.fps\", `fps must be > 0 (got ${fps})`, \"set output.fps to 30 or 60\");\n const { videoWidth: vW, videoHeight: vH } = comp.source;\n if (!(vW > 0 && vH > 0)) err(\"source\", `non-positive source video size ${vW}x${vH}`);\n\n const rest = restStageScale(vW, vH, oW, oH, comp.framing.insetFrac);\n\n // --- motion blur (render cost scales with samples: frames = fps × samples) ---\n const mb = comp.motionBlur;\n if (mb) {\n if (!Number.isInteger(mb.samples) || mb.samples < 1 || mb.samples > 16)\n err(\n \"motionBlur.samples\",\n `samples must be an integer 1-16 (got ${mb.samples})`,\n \"6 is the balanced default; 1 turns blur off\",\n );\n else if (mb.samples > 9)\n warn(\n \"motionBlur.samples\",\n `samples ${mb.samples} renders ${mb.samples}× the frames for little extra smoothness`,\n \"9 is the practical ceiling\",\n );\n if (!(mb.shutter >= 0 && mb.shutter <= 1))\n err(\n \"motionBlur.shutter\",\n `shutter must be 0..1 (got ${mb.shutter})`,\n \"0.7 is the default; 0 turns blur off\",\n );\n }\n\n // --- duration / ordering ---\n const events = comp.events ?? [];\n let lastEnd = 0;\n let prevT = -1;\n for (let i = 0; i < events.length; i++) {\n const e = events[i]!;\n const p = `events[${i}]`;\n const dur = e.durationMs ?? 0;\n const endMs = e.tMs + dur;\n lastEnd = Math.max(lastEnd, endMs);\n\n // ordering: events must stay in temporal order (the video is temporal)\n if (e.tMs < prevT) {\n err(\n `${p}.tMs`,\n `tMs ${e.tMs} is before the previous beat (${prevT}) — events out of order`,\n \"events follow the recording; reordering needs a re-capture, not a swap here\",\n );\n }\n prevT = e.tMs;\n\n if (e.tMs < 0) err(`${p}.tMs`, `negative tMs ${e.tMs}`);\n if (e.tMs > comp.durationMs)\n err(\n `${p}.tMs`,\n `tMs ${e.tMs} exceeds composition durationMs ${comp.durationMs}`,\n \"raise durationMs or remove the beat\",\n );\n\n // kind-specific required fields (editability invariants)\n const need = reqField[e.kind];\n if (need && (e as Record<string, unknown>)[need] == null)\n err(\n `${p}.${need}`,\n `${e.kind} beat is missing \"${need}\"`,\n `restore ${need} from the capture`,\n );\n if (e.kind === \"dropFiles\" && !e.files?.length)\n warn(\n `${p}.files`,\n `dropFiles beat has no files metadata — the ghost card will show a generic \"file\"`,\n \"restore files [{name,size}] from the capture\",\n );\n if (e.kind === \"dropFiles\" && !dur)\n warn(\n `${p}.durationMs`,\n \"dropFiles beat has no carry duration — the cursor teleports to the drop point and the ghost card only flashes\",\n \"restore durationMs from the capture\",\n );\n\n // --- zoom decision ---\n const z = e.zoom;\n if (!z) {\n err(\n `${p}.zoom`,\n \"missing zoom decision\",\n \"every beat needs a zoom { enabled, scale, center, inAtMs }\",\n );\n continue;\n }\n // inAtMs must precede the action (the zoom-in ramps in before the beat\n // lands) — EXCEPT a press: its reveal exists only after the keypress, so\n // its zoom departs AT the action (inAtMs === tMs; the schedule then runs\n // the ramp after the departure instead of landing at tMs).\n if (z.inAtMs < 0) err(`${p}.zoom.inAtMs`, `negative inAtMs ${z.inAtMs}`, \"clamp to 0\");\n if (z.inAtMs > e.tMs && e.kind !== \"press\")\n err(\n `${p}.zoom.inAtMs`,\n `inAtMs ${z.inAtMs} is AFTER the action at tMs ${e.tMs} — the zoom would arrive late`,\n `set inAtMs = tMs − cursor.zoomInMs (= ${Math.max(0, e.tMs - comp.cursor.zoomInMs)})`,\n );\n if (e.kind === \"press\" && z.enabled && z.inAtMs < e.tMs)\n warn(\n `${p}.zoom.inAtMs`,\n `press zoom departs ${e.tMs - z.inAtMs}ms BEFORE the keypress — its reveal doesn't exist yet, so the camera punches into empty space`,\n `set inAtMs = tMs (${e.tMs}) so the zoom rides the reveal in`,\n );\n\n if (z.enabled) {\n // scale must zoom IN (≥ rest). Below rest shows MORE than the framed\n // video → backdrop dead-space; that's never what an enabled zoom wants.\n if (z.scale < rest - 1e-6)\n err(\n `${p}.zoom.scale`,\n `scale ${z.scale.toFixed(3)} is below rest ${rest.toFixed(3)} — that zooms OUT past the frame (dead space)`,\n `raise to ≥ ${rest.toFixed(2)}, or set zoom.enabled=false for a full-view beat`,\n );\n else if (z.scale < rest * 1.2)\n // the whole dead band, not just ≈rest exactly: a 1.03× \"zoom\" renders\n // an enabled move the eye can't see (issue #1 — it shipped silently).\n warn(\n `${p}.zoom.scale`,\n `scale ${z.scale.toFixed(3)} is within 20% of rest ${rest.toFixed(3)} — an imperceptible zoom (enabled but invisible)`,\n \"raise scale to ≥ ~1.25 to actually zoom, or set enabled=false\",\n );\n if (z.scale > maxScale)\n warn(\n `${p}.zoom.scale`,\n `scale ${z.scale.toFixed(2)} exceeds the soft cap ${maxScale} — pixels will soften`,\n `clamp toward ${maxScale.toFixed(1)} unless the detail truly needs it`,\n );\n // center inside the video (clampCenter will pull it in, but an off-video\n // center usually means a stale/hand-miscomputed value)\n if (z.center.x < 0 || z.center.x > vW || z.center.y < 0 || z.center.y > vH)\n warn(\n `${p}.zoom.center`,\n `center (${z.center.x.toFixed(0)},${z.center.y.toFixed(0)}) is outside the video ${vW}x${vH}`,\n e.bbox\n ? \"use the bbox center: { x: bbox.x+bbox.w/2, y: bbox.y+bbox.h/2 }\"\n : \"point at the on-screen target (video-px)\",\n );\n // enabling zoom on a no-bbox beat means an invented center/scale — fine,\n // but flag it so the refine loop knows it's not bbox-derived.\n if (!e.bbox)\n warn(\n `${p}.zoom`,\n \"zoom enabled on a beat with no bbox — center/scale are hand-set, not bbox-fit\",\n \"double-check the center frames the intended region\",\n );\n }\n }\n\n // --- cursor motion knobs ---------------------------------------------------\n // These are plain numbers in the schema and, until here, NOTHING bounded them:\n // a hand edit (or an agent reaching for \"start the zoom earlier\" and stretching\n // the wrong knob) could put the whole take on a crawl with every other check\n // still passing.\n //\n // PRESENT-but-nonsensical is an error: the schedule arithmetic turns it into\n // NaN keyframes. ABSENT is usually the LEGACY shape — compositions predate\n // travelWidthsPerSec / travelMin/MaxMs / zoomInMs and the schedule has a\n // documented fallback for each — so absence is an error only where nothing\n // can stand in. (A validator that refused to render yesterday's composition\n // would be a worse bug than the one it catches.)\n const cur = comp.cursor;\n type MsKnob =\n | \"travelMs\"\n | \"travelMinMs\"\n | \"travelMaxMs\"\n | \"holdMs\"\n | \"zoomInMs\"\n | \"zoomOutMs\"\n | \"travelWidthsPerSec\";\n const knob = (k: MsKnob, positive: boolean, required: boolean) => {\n const v: number | undefined = cur[k];\n if (v == null) {\n if (required)\n err(\n `cursor.${k}`,\n `${k} is missing and the schedule has no fallback for it`,\n `set cursor.${k} to the shipped default (${DEFAULT_CURSOR[k]})`,\n );\n return;\n }\n if (typeof v !== \"number\" || !Number.isFinite(v) || (positive ? v <= 0 : v < 0))\n err(\n `cursor.${k}`,\n `${k} must be a ${positive ? \"positive\" : \"non-negative\"} number (got ${JSON.stringify(v)})`,\n `restore the shipped default (${DEFAULT_CURSOR[k]})`,\n );\n };\n // The speed law is live only with a positive travelWidthsPerSec; without it\n // the cursor runs on the fixed travelMs and the clamps are never consulted.\n const speedLaw = typeof cur.travelWidthsPerSec === \"number\" && cur.travelWidthsPerSec > 0;\n knob(\"holdMs\", false, true);\n knob(\"zoomOutMs\", true, true);\n knob(\"zoomInMs\", true, false); // absent ⇒ the legacy inAtMs→tMs window\n knob(\"travelWidthsPerSec\", false, false); // absent/0 ⇒ the documented travelMs fallback\n knob(\"travelMs\", true, !speedLaw);\n knob(\"travelMinMs\", false, speedLaw);\n knob(\"travelMaxMs\", true, speedLaw);\n if (\n Number.isFinite(cur.travelMinMs) &&\n Number.isFinite(cur.travelMaxMs) &&\n cur.travelMaxMs < cur.travelMinMs\n )\n // An inverted band has no coherent answer, and the clamps are applied in\n // order (floor first — see math.ts travelDur), so every leg lands on one\n // bound or the other and the ordering INVERTS: a short hop takes the\n // 800ms floor while a full-frame sweep takes the 400ms ceiling.\n err(\n \"cursor.travelMaxMs\",\n `travelMaxMs ${cur.travelMaxMs} is below travelMinMs ${cur.travelMinMs} — an inverted band, so every leg is pinned to one bound or the other and SHORT hops (${cur.travelMinMs}ms) end up slower than full-frame sweeps (${cur.travelMaxMs}ms)`,\n `raise travelMaxMs above travelMinMs (defaults ${DEFAULT_CURSOR.travelMinMs}/${DEFAULT_CURSOR.travelMaxMs})`,\n );\n // A punch-in's ramp END is pinned to the action instant, so a LONGER window\n // means departing EARLIER and creeping — never landing later. Past roughly\n // twice the slowest shipped pace the settle curve reads as a drift, and\n // nothing else here catches it (the crowded-release check below only fires on\n // a ramp that lands LATE).\n if (cur.zoomInMs > MOTION.calm.zoomInMs * RAMP_SLACK)\n warn(\n \"cursor.zoomInMs\",\n `zoomInMs ${cur.zoomInMs} is over ${RAMP_SLACK}× the slowest shipped pace (calm = ${MOTION.calm.zoomInMs}) — a punch-in lands ON the action, so this departs that much earlier and creeps in`,\n `${DEFAULT_CURSOR.zoomInMs} is the frame-measured default; use pace \"calm\" (${MOTION.calm.zoomInMs}) for a gentler punch`,\n );\n if (cur.zoomOutMs > MOTION.calm.zoomOutMs * RAMP_SLACK)\n warn(\n \"cursor.zoomOutMs\",\n `zoomOutMs ${cur.zoomOutMs} is over ${RAMP_SLACK}× the slowest shipped pace (calm = ${MOTION.calm.zoomOutMs}) — every release drifts out for that long, and the tail must outlast it`,\n `${DEFAULT_CURSOR.zoomOutMs} is the frame-measured default; use pace \"calm\" (${MOTION.calm.zoomOutMs}) for a slower release`,\n );\n\n // camera-rect spring: bounce shapes the ONE ease driving centre+size, so an\n // out-of-range value corrupts every camera move (see math.ts springEase).\n const spring = comp.cursor.zoomSpring;\n if (spring != null) {\n if (!(spring >= 0 && spring < 0.6))\n err(\n \"cursor.zoomSpring\",\n `zoomSpring ${spring} outside [0, 0.6)`,\n \"0 = critically damped (the default feel); keep bounce ≤ 0.3\",\n );\n else if (spring > 0.3)\n warn(\n \"cursor.zoomSpring\",\n `zoomSpring ${spring} is a lot of bounce — the rect overshoot can flash backdrop at edge-flush targets and over-zoom tight punches`,\n \"keep ≤ 0.3 (the editor slider's max) unless the flash is wanted\",\n );\n }\n\n // asymptotic settle: the residual left to creep out after the action instant.\n // Beyond ~0.15 the camera visibly hasn't arrived when the action fires.\n const settleFrac = comp.cursor.zoomSettleFrac;\n if (settleFrac != null && !(settleFrac >= 0 && settleFrac <= 0.15))\n err(\n \"cursor.zoomSettleFrac\",\n `zoomSettleFrac ${settleFrac} outside [0, 0.15]`,\n \"~0.04 = the reference-measured tail; 0 = legacy cut spring\",\n );\n else if (settleFrac != null && settleFrac > 0 && (comp.cursor.zoomEase || spring != null))\n warn(\n \"cursor.zoomSettleFrac\",\n `zoomSettleFrac is IGNORED while cursor.${comp.cursor.zoomEase ? \"zoomEase\" : \"zoomSpring\"} is set — the render is byte-identical to not setting it`,\n \"delete cursor.zoomEase / cursor.zoomSpring (a pace preset clears zoomEase) to activate the settle tail\",\n );\n\n const dwell = comp.cursor.pullOutDwellMs;\n if (dwell != null && !(dwell >= 0 && dwell <= 5000))\n err(\n \"cursor.pullOutDwellMs\",\n `pullOutDwellMs ${dwell} outside [0, 5000]`,\n \"600-1000 reads as a natural beat; 0 = legacy (depart as soon as the action ends)\",\n );\n\n // SILENT PACE OVERRIDE: travelMinMs/travelMaxMs are applied AFTER the speed\n // law (math.ts buildLegs), so on the legs they bind it is the clamp — not\n // travelWidthsPerSec — that sets the duration. travelWidthsPerSec is what a\n // `pace` preset moves and travelMin/MaxMs are NOT in the preset, so a take\n // whose legs are mostly clamped answers a pace change with a shrug. Nothing\n // in the JSON shows this; only the legs do.\n if (cur.travelWidthsPerSec > 0 && issues.every((i) => i.severity !== \"error\")) {\n try {\n const travels = buildLegs(comp).filter((l) => !l.drag);\n const pace = motionName(cur);\n // RUSHED TRAVEL: a leg is bounded on the left by the previous beat's\n // action end, so a beat that runs late (or a settleMs too short to hold\n // the glide that follows it) squeezes the move into whatever is left and\n // the cursor darts. This is the cursor's twin of the crowded-release\n // check below, and like it the fix is in the RECORDING: nothing in the\n // composition can widen a gap the capture never left.\n const shortfall = (l: (typeof travels)[number]) => (l.wantSec ?? 0) - (l.t1 - l.t0);\n const squeezed = travels\n .filter(\n (l) =>\n l.wantSec != null &&\n l.t1 - l.t0 < l.wantSec * SQUEEZE_FRAC &&\n shortfall(l) > SQUEEZE_MIN_MS / 1000,\n )\n .sort((a, b) => shortfall(b) - shortfall(a));\n const worst = squeezed[0];\n if (worst) {\n const got = Math.round((worst.t1 - worst.t0) * 1000);\n const want = Math.round((worst.wantSec ?? 0) * 1000);\n const prev = worst.evIdx != null ? events[worst.evIdx - 1] : undefined;\n warn(\n `events[${worst.evIdx}]`,\n `${squeezed.length === 1 ? \"this beat's\" : `${squeezed.length} beats' travel is rushed; the worst`} approach gets ${got}ms of the ${want}ms the speed law asks for — the cursor darts in${prev ? ` because events[${worst.evIdx! - 1}] (${prev.kind}) is still running until ${prev.tMs + (prev.durationMs ?? 0)}ms` : \" because the take starts too close to it\"}`,\n prev\n ? `raise the previous step's settleMs by ≥ ${want - got}ms and re-\\`make\\` — the gap is in the CAPTURE, no cursor knob can widen it`\n : `add a leading \\`wait\\` (or move \\`start\\` closer) and re-\\`make\\` — the opening sweep has no room`,\n );\n }\n for (const which of [\"min\", \"max\"] as const) {\n const n = travels.filter((l) => l.clamped === which).length;\n if (travels.length < CLAMPED_LEGS_MIN || n <= travels.length * CLAMPED_LEGS_FRAC) continue;\n const field = which === \"min\" ? \"travelMinMs\" : \"travelMaxMs\";\n // A clamp at ITS PACE'S value is not an override — it IS the pace, it\n // was tuned with the rest of the bundle, and re-pacing moves those legs\n // like any other. Only a clamp somebody HAND-SET away from the pace\n // overrides it, and only then is there anything to say. (Before the\n // clamps joined MOTION every clamped leg really was deaf to the pace,\n // and this warning said so; saying it now would be false.)\n const shipped = pace ? MOTION[pace] : DEFAULT_CURSOR;\n // Same tolerance motionName uses, so the two can never disagree: a\n // value near enough to keep the pace's NAME is near enough to be the\n // pace, and must not be reported as overriding it.\n if (Math.abs(cur[field] - shipped[field]) < CLAMP_TOL_MS) continue;\n warn(\n `cursor.${field}`,\n `${n} of ${travels.length} travel legs are ${which === \"min\" ? \"floored at\" : \"capped at\"} a hand-set cursor.${field} of ${cur[field]}ms — on those the clamp sets the duration, not cursor.travelWidthsPerSec${pace ? `, so they no longer move with the \"${pace}\" pace (which ships ${shipped[field]}ms)` : \"\"}`,\n `restore cursor.${field} to ${shipped[field]}${pace ? ` (the \"${pace}\" pace's own value)` : \" (the shipped default)\"} to put those legs back under the speed law — or keep it, if they are meant to read as ${which === \"min\" ? \"darts\" : \"one steady sweep\"}`,\n );\n }\n } catch {\n /* never let a diagnostics pass throw */\n }\n }\n\n // tail: the composition must outlast the last action (+ a little settle)\n if (comp.durationMs < lastEnd)\n err(\n \"durationMs\",\n `durationMs ${comp.durationMs} ends before the last action (${lastEnd})`,\n `raise to ≥ ${Math.round(lastEnd + comp.cursor.holdMs + comp.cursor.zoomOutMs)}`,\n );\n else if (comp.durationMs < lastEnd + comp.cursor.zoomOutMs)\n warn(\n \"durationMs\",\n `only ${comp.durationMs - lastEnd}ms after the last action — the final zoom-out may be cut`,\n `allow ≥ ${comp.cursor.zoomOutMs}ms (cursor.zoomOutMs) of tail`,\n );\n // …and the mirror image: a tail so long the delivered mp4 ends on a frozen\n // screen. The classic cause is padding a plan with trailing `wait`s to hit a\n // \"~25s\" target — the capture keeps rolling long after the last payoff has\n // settled and nothing on screen changes again. Cheap to fix (durationMs is\n // render-only), invisible to an agent that never watches the tail.\n else if (events.length) {\n const settledEnd = lastEnd + comp.cursor.holdMs + comp.cursor.zoomOutMs;\n if (comp.durationMs > settledEnd + DEAD_TAIL_MS)\n warn(\n \"durationMs\",\n `${((comp.durationMs - settledEnd) / 1000).toFixed(1)}s of tail after the last beat settles — the delivered video ends on a frozen screen`,\n `trim durationMs to ≈ ${Math.round(settledEnd)}, or add a beat that earns the time`,\n );\n }\n\n // CROWDED RELEASE: the camera should be PARKED at the instant an action\n // fires. A release (a zoomed beat followed by a full-view one) needs\n // pullOutDwellMs + zoomOutMs of room after the previous beat's payoff\n // settles; when the gap is tighter the schedule keeps the ramp and lands it\n // LATE — deliberately, because fleeing a frame the viewer is still reading is\n // worse — and the frame slides out from under the next click. That trade is\n // right given the recording, but the recording is the thing to fix, so say\n // so. (A zoom-enabled `press` is reveal-timed by construction: it departs AT\n // the keypress and rides the reveal in, so its late landing is the design.)\n if (issues.every((i) => i.severity !== \"error\")) {\n try {\n const sched = cameraRampSchedule(comp);\n const room = (comp.cursor.pullOutDwellMs ?? 0) + comp.cursor.zoomOutMs;\n for (let i = 0; i < events.length; i++) {\n const e = events[i]!;\n const r = sched[i];\n if (!r) continue;\n const rampMs = r.landMs - r.startMs;\n // OVER-LONG WINDOW: the ramp a beat actually gets is inAtMs → its\n // landing, so a hand-set inAtMs — not cursor.zoomInMs — is what makes a\n // multi-second creep. The usual cause is reading \"start the zoom\n // earlier\" as \"start it much earlier\": the landing is pinned to the\n // action, so the only thing that moves is how slowly it gets there.\n // Only HAND-SET windows are flagged; the planner's own default is\n // clamped at 0 for an early first beat and that is by design.\n const nominal = r.pullOut ? comp.cursor.zoomOutMs : comp.cursor.zoomInMs;\n const handSet = Math.abs(e.zoom.inAtMs - Math.max(0, e.tMs - comp.cursor.zoomInMs)) >= 1;\n if (handSet && nominal > 0 && rampMs > nominal * RAMP_SLACK)\n warn(\n `events[${i}].zoom.inAtMs`,\n `this beat's camera window runs ${Math.round(rampMs)}ms — ${(rampMs / nominal).toFixed(1)}× cursor.${r.pullOut ? \"zoomOutMs\" : \"zoomInMs\"} (${nominal}ms) — so the camera departs at ${Math.round(r.startMs)}ms and creeps to the action instead of moving at the take's pace`,\n `set inAtMs = ${Math.max(0, e.tMs - comp.cursor.zoomInMs)} (tMs − cursor.zoomInMs) and change cursor.${r.pullOut ? \"zoomOutMs\" : \"zoomInMs\"} if the RAMP itself should be slower`,\n );\n // press: reveal-timed by construction. look: nothing fires at tMs —\n // the camera arriving early in the DWELL is the beat working as\n // designed, so \"the frame slides out from under it\" cannot happen.\n if (e.kind === \"press\" || e.kind === \"look\") continue;\n const lateMs = Math.round(r.landMs - e.tMs);\n if (lateMs <= MOVING_AT_ACTION_MS) continue;\n if (!(rampMs > 0) || lateMs / rampMs <= MOVING_AT_ACTION_FRAC) continue;\n const prev = events[i - 1];\n const prevEnd = prev ? prev.tMs + (prev.durationMs ?? 0) : 0;\n // The dwell floor can push the departure past the action entirely, and\n // then \"% of the move done\" is negative — a fraction that cannot\n // describe a camera which has not left yet. Say the stronger thing.\n const doneFrac = 1 - lateMs / rampMs;\n const progress =\n doneFrac > 0\n ? `has only ${Math.round(doneFrac * 100)}% of its move done`\n : \"has not even departed\";\n warn(\n `events[${i}].zoom`,\n `the camera ${progress} when this beat's action fires (departs ${Math.round(r.startMs)}ms, lands ${Math.round(r.landMs)}ms, action ${e.tMs}ms) — the frame slides out from under it${prev ? `; the previous beat settles only ${Math.round(e.tMs - prevEnd)}ms earlier` : \"\"}`,\n prev\n ? `hold the frame — copy events[${i - 1}].zoom onto this beat so the camera never moves at the action; or re-capture with ≥ ${room}ms of settle on events[${i - 1}] (cursor.pullOutDwellMs + cursor.zoomOutMs)`\n : `re-capture with more lead-in before this beat, or set zoom.enabled=false`,\n );\n }\n } catch {\n /* never let a diagnostics pass throw */\n }\n }\n\n // A dwell-delayed final pull-out can land LATER than the legacy tail math\n // above assumes — check the actual schedule, not the formula. (Guarded: the\n // schedule needs a structurally sound composition; earlier errors mean this\n // check would throw, and its absence is already explained by them.)\n if ((comp.cursor.pullOutDwellMs ?? 0) > 0 && issues.every((i) => i.severity !== \"error\")) {\n try {\n const kfs = buildStageKeyframes(comp).r;\n let motionEndS = 0;\n for (let i = 0; i < kfs.length - 1; i++) {\n const [, a] = kfs[i]!;\n const [t1, b] = kfs[i + 1]!;\n if (a.cx !== b.cx || a.cy !== b.cy || a.w !== b.w) motionEndS = t1;\n }\n if (motionEndS * 1000 > comp.durationMs + 1)\n warn(\n \"durationMs\",\n `the camera is still mid-motion at durationMs (dwell-delayed landing ends ~${Math.round(motionEndS * 1000)}ms)`,\n `raise durationMs to ≥ ${Math.round(motionEndS * 1000)}`,\n );\n } catch {\n /* never let a diagnostics pass throw */\n }\n }\n\n // Dead HEAD — the mirror of the dead-tail check. A capture that had to wait\n // out a cold load (map tiles, data fetch) ships that whole wait unless\n // startMs trims it, and \"8 seconds of nothing, then the cursor moves\" is\n // the first thing every viewer sees. The wait was necessary to SHOOT;\n // shipping it is a choice, and the default choice should be no.\n if (comp.events.length) {\n const firstVisible = comp.events[0]!.zoom.inAtMs;\n const deadHeadMs = firstVisible - (comp.startMs ?? 0);\n if (deadHeadMs > DEAD_TAIL_MS)\n warn(\n \"startMs\",\n `${(deadHeadMs / 1000).toFixed(1)}s of dead opening before the first beat's camera moves — the delivered video starts on a frozen screen`,\n `set startMs ≈ ${Math.max(0, firstVisible - 1200)} (leave ~1.2s of establishing hold, trim the rest of the load wait)`,\n );\n }\n\n // head trim: cut dead pre-paint frames, never a beat. The trim only moves\n // the delivered head — tMs values stay on the capture timeline.\n const startMs = comp.startMs;\n if (startMs != null) {\n if (!(startMs >= 0) || startMs >= comp.durationMs)\n err(\n \"startMs\",\n `startMs ${startMs} outside [0, durationMs ${comp.durationMs})`,\n \"the head trim must leave a video\",\n );\n else if (comp.events[0] && startMs > comp.events[0].zoom.inAtMs)\n warn(\n \"startMs\",\n `startMs ${startMs} cuts into the first beat (camera/cursor already moving at ${comp.events[0].zoom.inAtMs}ms)`,\n `keep the trim ≤ ${comp.events[0].zoom.inAtMs} so the delivered video opens at rest`,\n );\n }\n\n // --- captions: viewer-facing timeline overlays on the DELIVERED video ---\n // Times are on the untrimmed composition timeline, like zoom.inAtMs.\n for (const [i, cap] of (comp.captions ?? []).entries()) {\n if (!cap.text?.trim()) {\n err(`captions[${i}].text`, \"empty caption text\", \"give the caption a line, or delete it\");\n continue;\n }\n if (!(cap.toMs > cap.fromMs))\n err(\n `captions[${i}].toMs`,\n `toMs ${cap.toMs} is not after fromMs ${cap.fromMs} — an inverted/empty window shows nothing`,\n \"set toMs > fromMs (a readable line needs ~1500ms on screen)\",\n );\n if (!(cap.fromMs >= 0) || cap.fromMs >= comp.durationMs)\n err(\n `captions[${i}].fromMs`,\n `fromMs ${cap.fromMs} outside [0, durationMs ${comp.durationMs})`,\n \"captions live on the composition timeline\",\n );\n const prev = comp.captions?.[i - 1];\n if (prev && cap.fromMs < prev.toMs)\n warn(\n `captions[${i}].fromMs`,\n `window [${cap.fromMs}, ${cap.toMs}) overlaps captions[${i - 1}] [${prev.fromMs}, ${prev.toMs}) — two pills stack in the same slot`,\n `start this caption at ${prev.toMs}, or end the previous one at ${cap.fromMs}`,\n );\n if (comp.startMs != null && cap.toMs <= comp.startMs)\n warn(\n `captions[${i}]`,\n `window [${cap.fromMs}, ${cap.toMs}) sits entirely inside the startMs head trim (${comp.startMs}) — it is never seen`,\n \"move the window past the trim, or delete the caption\",\n );\n if (cap.text.trim().length > 120)\n warn(\n `captions[${i}].text`,\n `${cap.text.trim().length} chars — a caption is one explanatory sentence, not a paragraph`,\n \"cut to one sentence (~15-30 CJK chars / 8-14 words); move detail into the beat itself\",\n );\n }\n\n if (comp.titleCard && !comp.titleCard.title?.trim())\n err(\"titleCard.title\", \"empty title on a title card\", \"give it the app/thesis line, or delete titleCard\");\n\n // --- CAPTURE-LOCKED: action tMs must match the recording ---\n // The video is temporal: a beat's tMs is WHEN it is visible in the capture.\n // A render-only edit cannot move that, so a drifted tMs would fire the\n // overlay off the on-screen action. (Cinematic timing — inAtMs, holdMs,\n // zoom ramps, the intro travel and the tail — IS freely editable; only the\n // action anchor tMs is locked.)\n if (opts.captureLog) {\n const log = opts.captureLog;\n if (log.events.length !== events.length)\n warn(\n \"events\",\n `composition has ${events.length} beats but the capture log has ${log.events.length} — added/removed actions need a re-capture`,\n \"re-capture to change the choreography; edit only renders the existing recording\",\n );\n const n = Math.min(log.events.length, events.length);\n for (let i = 0; i < n; i++) {\n const lt = log.events[i]!.tMs;\n const ct = events[i]!.tMs;\n if (Math.abs(lt - ct) > 1)\n err(\n `events[${i}].tMs`,\n `tMs ${ct} drifted from the captured ${lt} — an action's tMs is capture-locked (the video shows it at ${lt}ms)`,\n `restore tMs to ${lt}; to retime the action itself, re-capture`,\n );\n }\n }\n\n return issues;\n}\n\n/** Format issues for a human/agent log. Errors first. */\nexport function formatIssues(issues: CompositionIssue[]): string {\n if (!issues.length) return \"composition OK (0 issues)\";\n const order = (s: string) => (s === \"error\" ? 0 : 1);\n return issues\n .slice()\n .sort((a, b) => order(a.severity) - order(b.severity))\n .map(\n (i) => ` [${i.severity}] ${i.path}: ${i.message}${i.fix ? `\\n fix: ${i.fix}` : \"\"}`,\n )\n .join(\"\\n\");\n}\n","// renderTake: composition (or capture log) + captured video -> polished\n// mp4 + the editable composition written alongside it.\n//\n// Runs revideo headless (vite + chromium + ffmpeg). The renderer resolves\n// everything relative to process.cwd(), and injects `projectFile` verbatim\n// as an import specifier — so the render runs from a directory laid out like\n// the package (src/ + public/) with the vite-root-absolute\n// \"/src/scene/project.ts\" (a bare specifier hangs the renderer forever; see\n// spike-revideo/VERDICT.md).\n//\n// That directory is a per-render SCRATCH COPY in the tmp dir, never the\n// installed package: a render used to write capture.mp4, .composition.json and\n// out-render/ into node_modules, which breaks read-only installs outright and\n// lets two renders read each other's composition. See prepareScratch.\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport {\n mkdir,\n mkdtemp,\n readdir,\n readFile,\n rm,\n symlink,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { renderVideo } from \"@open-take/revideo-renderer\";\nimport { isCaptureUndecodable } from \"./decode-guard\";\nimport { ffmpegHasEncoder, repairBundledMediaPermissions, resolveFfmpeg } from \"./ffmpeg\";\nimport { type PlanOpts, planComposition } from \"./plan\";\nimport {\n type CaptureLog,\n type MotionBlurConfig,\n motionBlurActive,\n type TakeComposition,\n} from \"./types\";\nimport { type CompositionIssue, formatIssues, validateComposition } from \"./validate\";\n\n// dist/index.js -> package root\nconst PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), \"..\");\nconst RENDER_OUT = \"out-render\"; // relative to cwd (= the scratch dir at render time)\n\nexport type RenderTakeOpts = {\n /** input capture video (webm or mp4) */\n videoPath: string;\n /** output polished mp4 path */\n outPath: string;\n /** provide a capture log (auto-planned) ... */\n log?: CaptureLog;\n /** ... or a ready-made composition (editable artifact) */\n composition?: TakeComposition;\n planOpts?: PlanOpts;\n logProgress?: boolean;\n /** Chrome binary for the headless render. Pass the same Chrome-for-Testing\n * the capture path uses so a single browser serves both stages. The\n * higher-level runtime resolves and supplies this to puppeteer-core. */\n chromePath: string;\n /** the capture log, for cross-checking that an edited composition didn't\n * drift an action's capture-locked tMs (see validateComposition). Optional —\n * the structural checks run regardless. */\n captureLog?: CaptureLog;\n /** skip the pre-render structural validation. Default false — we validate and\n * refuse to render an errored composition (a render is expensive; catch a bad\n * hand-edit in milliseconds instead). */\n skipValidate?: boolean;\n /** progress callback (0..1) forwarded from revideo's renderer. */\n onProgress?: (progress: number) => void;\n /** render only this window of the composition timeline, in SECONDS — the\n * windowed-render path behind A/B variant reels (a 4s window instead of the\n * whole take). With motion blur OFF, frames are identical to the same span\n * of a full render (the timeline is deterministic). With blur active the\n * content matches but not bit-exactly: the tmix shutter windows are phased\n * from the CLIP start, and the first frame's trailing window is truncated.\n * Forwarded to revideo's projectSettings.range. */\n rangeSec?: [number, number];\n /** write the editable composition (default true). Review copies and A/B reels\n * are disposable — they skip it. */\n writeCompositionSibling?: boolean;\n /** where to write it. Default `<out>.composition.json`; the runtime passes the\n * take's working dir instead. WHERE a take keeps its files is a take-layout\n * question — the compositor just writes where it is told. */\n compositionPath?: string;\n};\n\nexport type RenderTakeResult = {\n mp4Path: string;\n compositionPath: string;\n /** non-fatal validator findings for this composition. The render went ahead,\n * but each one is something the author has to look at — a zoom that punches\n * into empty space, a press whose zoom departs before the keypress, a tail\n * that delivers a frozen screen. Empty when `skipValidate` is set. */\n warnings: CompositionIssue[];\n};\n\nfunction run(cmd: string, args: string[]): Promise<void> {\n return new Promise((res, rej) => {\n const c = spawn(cmd, args, { stdio: [\"ignore\", \"ignore\", \"pipe\"] });\n let err = \"\";\n c.stderr.on(\"data\", (d) => {\n err += d;\n });\n c.on(\"error\", rej);\n c.on(\"close\", (code) => (code === 0 ? res() : rej(new Error(`${cmd} exited ${code}: ${err}`))));\n });\n}\n\n/** Normalise the capture to a constant-fps mp4 the web decoder can read.\n * fps follows the composition so a hi-fps capture can render at 60 (the\n * render grid must match — a 30-grid would throw away the extra frames).\n *\n * `codec` is normally h264; \"vp9\" is the retry arm for render browsers\n * WITHOUT H.264 decoding (Playwright-style Chromium builds ship no\n * proprietary codecs). The scene's decode guard rejects in seconds when the\n * capture can't decode there (see src/decode-guard.ts); renderTakeExclusive\n * catches that rejection and re-encodes the scratch capture with this arm\n * before one retry. The VP9 fallback must keep the .mp4 container AND the\n * capture.mp4 name: revideo routes video decoding by file extension, so a\n * .webm would take a different (and broken) decode path — VP9-in-MP4 (vp09\n * track) is the shape that works. */\nasync function toMp4(\n videoPath: string,\n outMp4: string,\n fps: number,\n codec: \"h264\" | \"vp9\",\n): Promise<void> {\n await mkdir(dirname(outMp4), { recursive: true });\n const codecArgs =\n codec === \"vp9\"\n ? [\"-c:v\", \"libvpx-vp9\", \"-b:v\", \"0\", \"-crf\", \"24\", \"-row-mt\", \"1\", \"-cpu-used\", \"4\"]\n : [\"-c:v\", \"libx264\", \"-crf\", \"18\"];\n await run(await resolveFfmpeg(), [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-i\",\n resolve(videoPath),\n ...codecArgs,\n \"-pix_fmt\",\n \"yuv420p\",\n \"-r\",\n String(fps),\n \"-an\",\n outMp4,\n ]);\n}\n\n/** Delivery encode: the visually-lossless ProRes intermediate -> the postable\n * H.264. The ONLY lossy generation in the pipeline, so its CRF is the\n * master's quality — overlay text (captions/title card) used to look soft\n * because it took TWO generations before this fix: revideo's default wasm\n * exporter (WebCodecs H.264 at the browser's default bitrate, no knob, at\n * fps·samples) and then this re-encode on top.\n *\n * Motion blur folds in here (temporal supersampling: the scene was rendered\n * at fps·samples, project.ts): `tmix=frames=M` averages M consecutive\n * sub-frames; `fps=baseFps` then decimates ≈every `samples`-th, so each\n * output frame = the mean of the last M sub-frames of its interval (a\n * trailing shutter).\n *\n * The scale step is a REAL conversion, not a re-tag: the ProRes encode\n * converts the scene's RGB frames with swscale's default bt601 matrix, so\n * the intermediate is 601-coded. Convert to bt709 and tag it — verified by\n * round-tripping primaries (601-coded red merely tagged 709 decodes to\n * rgb(255,24,0); converted it decodes to rgb(252,0,0)). */\nasync function deliverMp4(\n inMov: string,\n outMp4: string,\n baseFps: number,\n blur: MotionBlurConfig | null,\n): Promise<void> {\n const vf: string[] = [];\n if (blur) {\n const M = Math.max(1, Math.min(blur.samples, Math.round(blur.shutter * blur.samples)));\n vf.push(`tmix=frames=${M}`, `fps=${baseFps}`);\n }\n vf.push(\n \"scale=in_color_matrix=bt601:out_color_matrix=bt709\",\n \"format=yuv420p\",\n \"setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709\",\n );\n await run(await resolveFfmpeg(), [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-i\",\n resolve(inMov),\n \"-vf\",\n vf.join(\",\"),\n \"-c:v\",\n \"libx264\",\n \"-crf\",\n \"18\",\n \"-movflags\",\n \"+faststart\",\n \"-r\",\n String(baseFps),\n \"-an\",\n outMp4,\n ]);\n}\n\n// --- per-render scratch dir --------------------------------------------------\n\n/** The nearest node_modules above the installed package. Symlinked into the\n * scratch dir so the copied scene can still resolve `@revideo/*` — pnpm keeps\n * a node_modules beside the package, npm/yarn hoist it to the project root, so\n * walk up rather than assume either. */\nfunction hostNodeModules(): string | null {\n let dir = PKG_ROOT;\n for (;;) {\n const candidate = join(dir, \"node_modules\");\n if (existsSync(candidate)) return candidate;\n const up = dirname(dir);\n if (up === dir) return null;\n dir = up;\n }\n}\n\n/** The whole dependency tree in one directory, for vite's fs.allow. Vite serves\n * realpaths, and pnpm's are under `<root>/node_modules/.pnpm/…`, so the first\n * `node_modules` segment of a resolved dependency covers every layout. */\nfunction depsRoot(): string | null {\n try {\n const real = realpathSync(createRequire(import.meta.url).resolve(\"@revideo/core\"));\n const parts = real.split(sep);\n const i = parts.indexOf(\"node_modules\");\n return i === -1 ? null : parts.slice(0, i + 1).join(sep);\n } catch {\n return null;\n }\n}\n\n/** Copy a tree WITHOUT inheriting its permission bits. `fs.cp` preserves mode,\n * so copying out of a read-only install yields a read-only copy we then can't\n * write the composition into. Re-creating each file gives us the umask\n * default instead. The scene tree is a handful of small source files. */\nasync function copyWritable(from: string, to: string): Promise<void> {\n await mkdir(to, { recursive: true });\n for (const e of await readdir(from, { withFileTypes: true })) {\n const src = join(from, e.name);\n const dst = join(to, e.name);\n if (e.isDirectory()) await copyWritable(src, dst);\n else if (e.isFile()) await writeFile(dst, await readFile(src));\n }\n}\n\nasync function cleanupScratch(dir: string): Promise<void> {\n // Drop the node_modules LINK first and by name: recursive deletion around a\n // link to the real dependency tree deserves an explicit safety boundary.\n await unlink(join(dir, \"node_modules\")).catch(() => {});\n if (!process.env.OPEN_TAKE_KEEP_SCRATCH) {\n await rm(dir, { recursive: true, force: true });\n } else {\n process.stderr.write(`render scratch kept: ${dir}\\n`);\n }\n}\n\n/** Build the throwaway directory this render runs in: the package's `src/`\n * (the scene and everything it imports), this render's composition, the\n * normalised capture as vite's public asset, and a node_modules link. */\nasync function prepareScratch(composition: TakeComposition, videoPath: string): Promise<string> {\n const dir = await mkdtemp(join(tmpdir(), \"open-take-render-\"));\n try {\n await copyWritable(join(PKG_ROOT, \"src\"), join(dir, \"src\"));\n await writeFile(\n join(dir, \"src\", \"scene\", \".composition.json\"),\n JSON.stringify(composition, null, 2),\n );\n const nm = hostNodeModules();\n if (!nm) throw new Error(\"render: could not locate node_modules for the scene's imports\");\n // \"junction\" is the Windows directory link that doesn't need admin rights;\n // ignored on POSIX.\n await symlink(nm, join(dir, \"node_modules\"), \"junction\");\n // fps follows the composition: the render grid must match the source, or a\n // hi-fps capture is decimated before the scene ever sees it. Always H.264\n // here — the happy path — the decode-guard retry re-encodes as VP9 in\n // place when the render browser can't take it.\n await toMp4(videoPath, join(dir, \"public\", \"capture.mp4\"), composition.output.fps, \"h264\");\n return dir;\n } catch (error) {\n await cleanupScratch(dir);\n throw error;\n }\n}\n\n// process.chdir is process-global, so two renders in one process cannot run\n// concurrently no matter how isolated their directories are — the scratch dirs\n// remove the shared STATE, this removes the interleaving. (True parallelism\n// needs the renderer off cwd, or one child process per render.)\nlet renderQueue: Promise<unknown> = Promise.resolve();\n\nexport async function renderTake(opts: RenderTakeOpts): Promise<RenderTakeResult> {\n const run = renderQueue.then(\n () => renderTakeExclusive(opts),\n () => renderTakeExclusive(opts),\n );\n renderQueue = run.catch(() => {});\n return run;\n}\n\nasync function renderTakeExclusive(opts: RenderTakeOpts): Promise<RenderTakeResult> {\n if (!opts.chromePath) {\n throw new Error(\n \"renderTake: `chromePath` is required; use @open-take/runtime to resolve managed Chrome automatically\",\n );\n }\n const composition: TakeComposition =\n opts.composition ??\n planComposition(\n opts.log ??\n (() => {\n throw new Error(\"renderTake: provide `log` or `composition`\");\n })(),\n opts.planOpts,\n );\n\n // 0. validate BEFORE the expensive render. A hand-edited composition (the\n // refine loop) can carry a malformed zoom or a capture-locked tMs drift;\n // catch it in milliseconds rather than after a multi-second render.\n // Warnings are RETURNED as well as printed: this stderr line lands minutes\n // before the render finishes, so on its own it is scrolled past — the\n // caller re-prints them in the end-of-run summary, exactly as it already\n // does for skipped capture steps.\n const warnings: CompositionIssue[] = [];\n if (!opts.skipValidate) {\n const issues: CompositionIssue[] = validateComposition(composition, {\n captureLog: opts.captureLog ?? opts.log,\n });\n const errors = issues.filter((i) => i.severity === \"error\");\n warnings.push(...issues.filter((i) => i.severity === \"warn\"));\n if (opts.logProgress && warnings.length)\n process.stderr.write(`composition warnings:\\n${formatIssues(warnings)}\\n`);\n if (errors.length)\n throw new Error(\n `composition has ${errors.length} error(s) — refusing to render:\\n${formatIssues(errors)}`,\n );\n }\n\n // Head trim (composition.startMs): deliver the timeline from startMs on,\n // through the SAME range mechanism the A/B windows use — the composition\n // timeline (tMs, badges, keyframes) is untouched; only the delivered head\n // moves. An explicit rangeSec (an A/B clip window) wins: those windows are\n // authored on the composition timeline and already judged as clips.\n const rangeSec =\n opts.rangeSec ??\n (composition.startMs && composition.startMs > 0\n ? ([composition.startMs / 1000, composition.durationMs / 1000 + 120] as [number, number])\n : undefined);\n\n // Revideo spawns its bundled ffprobe directly. Repair installer permissions\n // here so published consumers are protected even though they do not run the\n // monorepo root's postinstall script.\n await repairBundledMediaPermissions();\n\n // 1. lay out this render's own directory (scene + composition + capture).\n // The intermediate starts as H.264; the decode-guard retry below swaps\n // it for VP9 when the render browser turns out not to decode it.\n const scratch = await prepareScratch(composition, opts.videoPath);\n const deps = depsRoot();\n // Resolved BEFORE the chdir below: the retry re-encode runs while cwd is\n // the scratch dir, where a relative videoPath would resolve wrongly.\n const videoAbs = resolve(opts.videoPath);\n try {\n // 2. render headless, with cwd pinned to the scratch dir.\n // revideo's @revideo/telemetry phones home to PostHog by default; this is an\n // all-local tool, so default it OFF (an explicit user-set value still wins).\n if (process.env.DISABLE_TELEMETRY === undefined) process.env.DISABLE_TELEMETRY = \"true\";\n\n // One attempt = one renderVideo call with its own no-progress hint timer.\n // A stuck render is SILENT: revideo's first progress tick fires only after\n // the first frame fully renders, and legitimate pre-roll can take tens of\n // seconds — so hint (never kill) when no tick has landed after 3 minutes.\n const renderOnce = async (): Promise<string> => {\n let noProgressTimer: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {\n process.stderr.write(\n \"open-take: no render progress after 3 minutes — if this never advances, the render browser may be stuck decoding the capture (see OPEN_TAKE_CHROME)\\n\",\n );\n }, 180_000);\n try {\n return await renderVideo({\n projectFile: \"/src/scene/project.ts\",\n settings: {\n outFile: \"take.mov\",\n outDir: RENDER_OUT,\n workers: 1,\n // ProRes 4444 intermediate, NOT revideo's default wasm exporter: the\n // wasm path encodes H.264 in-browser via WebCodecs at the browser's\n // default bitrate (mp4-wasm passes `bitrate: undefined`, and revideo\n // 0.11 exposes no knob) — at fps·samples that visibly softens fine\n // detail, screen-space caption/title text worst of all, before the\n // delivery encode ever runs. The ffmpeg exporter is fed lossless PNG\n // frames and prores_ks 4444 keeps them visually intact (4:4:4, no\n // DCT mush), leaving deliverMp4's CRF 18 as the single lossy\n // generation. Costs scratch disk (GBs at fps·samples for a long\n // take) and slower frame handoff — accepted for the master's text.\n projectSettings: {\n exporter: { name: \"@revideo/core/ffmpeg\", options: { format: \"proRes\" } },\n ...(rangeSec ? { range: rangeSec } : {}),\n },\n logProgress: opts.logProgress ?? false,\n // Wrapped even without opts.onProgress: the first tick proves the\n // browser is decoding frames, which disarms the no-progress hint.\n progressCallback: (_worker: number, progress: number) => {\n if (noProgressTimer !== undefined) {\n clearTimeout(noProgressTimer);\n noProgressTimer = undefined;\n }\n opts.onProgress?.(progress);\n },\n // vite's dev server refuses to serve outside its root, and its root is\n // now a tmp dir — so allow the dependency tree the scene imports\n // through the node_modules link (vite resolves it to the realpath).\n viteConfig: {\n server: { fs: { allow: [scratch, ...(deps ? [deps] : [])] } },\n },\n // Reuse the capture-managed Chrome-for-Testing for both stages.\n puppeteer: {\n // --password-store/--use-mock-keychain: never touch the OS keychain, so\n // macOS doesn't pop a \"Chrome wants to use Chromium Safe Storage\" prompt\n // mid-render (matches the capture launch in runtime/cdp.ts).\n args: [\n \"--no-sandbox\",\n \"--disable-setuid-sandbox\",\n \"--password-store=basic\",\n \"--use-mock-keychain\",\n ],\n executablePath: opts.chromePath,\n },\n },\n });\n } finally {\n if (noProgressTimer !== undefined) clearTimeout(noProgressTimer);\n }\n };\n\n const prevCwd = process.cwd();\n process.chdir(scratch);\n let produced: string;\n try {\n try {\n produced = await renderOnce();\n } catch (error) {\n // The scene's decode guard rejected: this browser cannot decode the\n // H.264 intermediate (Playwright-style Chromium ships no proprietary\n // codecs — before the guard, such a render hung forever; a real user\n // lost ~20 minutes to that silence). Re-encode the scratch capture as\n // VP9-in-MP4 and retry ONCE; without an ffmpeg that can, refuse with\n // the fix. Any other rejection rethrows untouched.\n if (!isCaptureUndecodable(error)) throw error;\n const detail = error instanceof Error ? error.message : String(error);\n if (!(await ffmpegHasEncoder(\"libvpx-vp9\"))) {\n throw new Error(\n `render: the browser at ${opts.chromePath} cannot decode the capture (${detail}) — ` +\n \"point OPEN_TAKE_CHROME at a full Chrome/Chrome-for-Testing build, or install an \" +\n \"ffmpeg with libvpx-vp9 to enable the VP9 fallback\",\n { cause: error },\n );\n }\n process.stderr.write(\n \"open-take: the render browser cannot decode the H.264 capture — retrying with a VP9 intermediate (output unchanged)\\n\",\n );\n await toMp4(\n videoAbs,\n join(scratch, \"public\", \"capture.mp4\"),\n composition.output.fps,\n \"vp9\",\n );\n try {\n produced = await renderOnce();\n } catch (retryError) {\n if (!isCaptureUndecodable(retryError)) throw retryError;\n const retryDetail = retryError instanceof Error ? retryError.message : String(retryError);\n throw new Error(\n `render: the browser at ${opts.chromePath} cannot decode the capture even as VP9 ` +\n `(${retryDetail}) — point OPEN_TAKE_CHROME at a full Chrome/Chrome-for-Testing build`,\n { cause: retryError },\n );\n }\n }\n } finally {\n process.chdir(prevCwd);\n }\n\n // 3. deliver the postable mp4 from the ProRes intermediate + the editable\n // composition. Motion blur (when configured) and the 601→709 colour\n // conversion both happen inside this single encode — see deliverMp4.\n await mkdir(dirname(resolve(opts.outPath)), { recursive: true });\n const producedAbs = resolve(scratch, produced);\n await deliverMp4(\n producedAbs,\n resolve(opts.outPath),\n composition.output.fps,\n motionBlurActive(composition.motionBlur) ? composition.motionBlur : null,\n );\n const compositionPath = opts.compositionPath\n ? resolve(opts.compositionPath)\n : `${resolve(opts.outPath).replace(/\\.mp4$/i, \"\")}.composition.json`;\n if (opts.writeCompositionSibling !== false) {\n // strip the render-time review decoration — the editable artifact is the\n // clean composition, never the badged/watermarked variant of it.\n const { review: _review, ...persisted } = composition;\n await mkdir(dirname(compositionPath), { recursive: true });\n await writeFile(compositionPath, JSON.stringify(persisted, null, 2));\n }\n\n return { mp4Path: resolve(opts.outPath), compositionPath, warnings };\n } finally {\n await cleanupScratch(scratch);\n }\n}\n"],"mappings":";;;;;;;;;;;AAqcA,MAAaA,iBAA+B;CAC1C,SAAS;CACT,UAAU;CACV,UAAU;CACV,WAAW;CACX,cAAc;CACd,kBAAkB;CAClB,iBAAiB;CACjB,iBAAiB;AAClB;;;;AAiDD,SAAgB,iBAAiBC,IAA0D;AACzF,UAAS,MAAM,GAAG,UAAU,KAAK,GAAG,UAAU;AAC/C;AAED,MAAaC,kBAAiC;CAC5C,WAAW;CACX,cAAc;CACd,QAAQ;EAAE,OAAO;EAAoB,MAAM;EAAI,QAAQ;GAAE,GAAG;GAAG,GAAG;EAAI;CAAE;CACxE,YAAY;EAAE,MAAM;EAAW,IAAI;CAAW;AAC/C;AAQD,MAAaC,sBAAwC;CACnD,SAAS;CACT,SAAS;AACV;AAED,MAAaC,iBAA+B;CAC1C,UAAU;CAYV,oBAAoB;CACpB,aAAa;CACb,aAAa;CACb,OAAO;CAIP,SAAS;CACT,QAAQ;CACR,UAAU;CACV,QAAQ;CAMR,WAAW;CACX,UAAU;CAOV,gBAAgB;CAChB,gBAAgB;CAShB,WAAW;CAOX,YAAY;EAAC;EAAK;EAAK;EAAK;CAAI;AACjC;;;;AC9jBD,MAAa,cAAc;CACzB,OAAO;CACP,QAAQ;CACR,OAAO;CACP,OAAO;AACR;;AAID,SAAgB,cAAcC,OAAe,MAAM,KAA4B;CAC7E,IAAIC,OAA6B;CACjC,IAAI,QAAQ;AACZ,MAAK,MAAM,CAAC,MAAM,EAAE,IAAI,OAAO,QAAQ,YAAY,EAA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path: string | null","encodersText: string","encoder: string","name: string","t: number","x1: number","y1: number","x2: number","y2: number","s: number","x: number","bounce: number","p: number","cursor: TakeComposition[\"cursor\"]","angleDeg: number | undefined","oW: number","oH: number","kfs: KF<number>[]","ease: (u: number) => number","bbox: BBox","outW: number","outH: number","fillFrac: number","maxScale: number","restScale: number","videoW: number","videoH: number","insetFrac: number","center: Pt","scale: number","kfs: KF<CamRect>[]","comp: TakeComposition","restC: Pt","anchors: CameraSchedule[\"anchors\"]","e: { inAtMs: number; tMs: number }","out: ({ startMs: number; landMs: number; pullOut: boolean } | null)[]","rf: { t: number; r: CamRect }[]","r: CamRect","frac: number","u: number","decay: (u: number) => number","cam: { T: number; rest: number; at: (t: number) => { scale: number } }","y: number","legs: Leg[]","cur: Pt","cam: ReturnType<typeof stageCamera> | undefined","track: ReturnType<typeof zoomFracTrack> | undefined","a: Pt","b: Pt","arriveSec: number","dist","ms: number","path: Pt[]","seg: number[]","e: { tMs: number; durationMs?: number }","n: number","files: { name: string; size?: number }[]","CURSOR_POLYGON: readonly (readonly [number, number])[]","scale: number","xs: number[]","src: Float32Array","s","frame: GrayFrame","expect: Pt","offs: number[]","b: number[]","found: Pt | undefined","comp: TakeComposition","out: PredictedTip[]","v: number","rows: AuditRow[]","issues: CompositionIssue[]","ffmpeg: string","mp4Path: string","tSec: number","width: number","height: number","chunks: Buffer[]","d: Buffer","opts: AuditCursorOpts","b: BBox","a: Pt","b: Pt","a: BBox","box: BBox","video: { w: number; h: number }","b: Beat","beats: Beat[]","idx: number[]","out: { w: number; h: number }","cam: CameraConfig","rest: number","endMs: number","restC: Pt","roi: BBox","nodes: Node[]","segs: Seg[]","framings: Framing[]","DEFAULT_CAMERA: CameraConfig","mb: MotionBlurConfig | undefined","DEFAULT_FRAMING: FramingConfig","DEFAULT_MOTION_BLUR: MotionBlurConfig","DEFAULT_CURSOR: CursorConfig","log: CaptureLog","opts: PlanOpts","framing: FramingConfig","cursor: CursorConfig","camera: CameraConfig","p: Pt","b: BBox","pts: Pt[]","scaffolds: Scaffold[]","durationMs","beat: Beat","ev: Omit<CompEvent, \"zoom\">","events: CompEvent[]","zoom: ZoomDecision","captions: Caption[]","b: Beat","rest: number","scale: number","best: ZoomLevelName | null","MOTION: Record<\"calm\" | \"natural\" | \"brisk\", MotionPreset>","v: number | undefined","want: number","legacy: number","cursor: CursorConfig","DARK_SHADOW: LookPreset[\"shadow\"]","LOOKS: Record<string, LookPreset>","framing: FramingConfig","FINISH: Record<\"smooth\" | \"crisp\" | \"heavy\", MotionBlurConfig | undefined>","mb: MotionBlurConfig | undefined","err: unknown","reqField: Record<string, string>","comp: TakeComposition","opts: ValidateOpts","issues: CompositionIssue[]","path: string","message: string","fix?: string","k: MsKnob","positive: boolean","required: boolean","v: number | undefined","l: (typeof travels)[number]","s: string","cmd: string","args: string[]","videoPath: string","outMp4: string","fps: number","codec: \"h264\" | \"vp9\"","inMov: string","baseFps: number","blur: MotionBlurConfig | null","vf: string[]","from: string","to: string","dir: string","composition: TakeComposition","renderQueue: Promise<unknown>","opts: RenderTakeOpts","run","warnings: CompositionIssue[]","issues: CompositionIssue[]","noProgressTimer: ReturnType<typeof setTimeout> | undefined","_worker: number","progress: number","produced: string"],"sources":["../src/ffmpeg.ts","../src/math.ts","../src/audit-cursor.ts","../src/camera.ts","../src/types.ts","../src/plan.ts","../src/presets.ts","../src/decode-guard.ts","../src/validate.ts","../src/render.ts"],"sourcesContent":["// ffmpeg/ffprobe resolution — zero-config for npm consumers. Prefer the\n// system binaries on PATH (often newer/faster, and what the repo has always\n// used); fall back to the platform binaries from @ffmpeg-installer/ffmpeg and\n// @ffprobe-installer/ffprobe (direct deps here, and already in the tree via\n// @revideo/ffmpeg — so the fallback costs consumers no extra download). Throw\n// with an install hint only when neither exists.\n\nimport { spawn, spawnSync } from \"node:child_process\";\nimport { chmod, stat } from \"node:fs/promises\";\n\nlet cachedFfmpeg: string | undefined;\nlet cachedFfprobe: string | undefined;\n\nfunction runsOk(bin: string): boolean {\n try {\n return spawnSync(bin, [\"-version\"], { stdio: \"ignore\" }).status === 0;\n } catch {\n return false;\n }\n}\n\nasync function installerPath(pkg: string): Promise<string | null> {\n try {\n const m = (await import(pkg)) as { default?: { path?: string }; path?: string };\n return m.default?.path ?? m.path ?? null;\n } catch {\n return null;\n }\n}\n\n/** Some pnpm installs leave the platform packages' media binaries without an\n * executable bit. Repair the resolved target at the point of use as well as\n * in the repo postinstall: published consumers do not run this monorepo's\n * root lifecycle script. Windows does not use POSIX execute bits. */\nasync function ensureExecutable(path: string | null): Promise<void> {\n if (!path || process.platform === \"win32\") return;\n try {\n const info = await stat(path);\n if ((info.mode & 0o111) === 0) await chmod(path, info.mode | 0o111);\n } catch {\n // Best effort. The normal spawn below still returns the useful failure.\n }\n}\n\n/** Revideo resolves its own bundled ffprobe rather than calling\n * resolveFfprobe(), so repair both installer targets before invoking it. */\nexport async function repairBundledMediaPermissions(): Promise<void> {\n const paths = await Promise.all([\n installerPath(\"@ffmpeg-installer/ffmpeg\"),\n installerPath(\"@ffprobe-installer/ffprobe\"),\n ]);\n await Promise.all(paths.map(ensureExecutable));\n}\n\nexport async function resolveFfmpeg(): Promise<string> {\n if (cachedFfmpeg) return cachedFfmpeg;\n if (runsOk(\"ffmpeg\")) {\n cachedFfmpeg = \"ffmpeg\";\n return cachedFfmpeg;\n }\n const p = await installerPath(\"@ffmpeg-installer/ffmpeg\");\n await ensureExecutable(p);\n if (p && runsOk(p)) {\n cachedFfmpeg = p;\n return p;\n }\n throw new Error(\n \"ffmpeg not found — install it (e.g. `brew install ffmpeg`) or `npm install` so the bundled @ffmpeg-installer binary resolves for this platform\",\n );\n}\n\n/** True when an `ffmpeg -encoders` table has a video-encoder ROW named\n * `encoder` (\" V....D libx264 ...\"), not merely the name as a substring\n * somewhere — descriptions repeat encoder names constantly. */\nexport function parseEncoders(encodersText: string, encoder: string): boolean {\n const escaped = encoder.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`^\\\\s*V\\\\S{5}\\\\s+${escaped}(?:\\\\s|$)`, \"m\").test(encodersText);\n}\n\nconst encoderCache = new Map<string, Promise<boolean>>();\n\n/** True when the RESOLVED ffmpeg (resolveFfmpeg — which may be a system\n * binary lacking libvpx-vp9) offers the named video encoder. Cached per\n * name; any failure is false, never a throw. */\nexport function ffmpegHasEncoder(name: string): Promise<boolean> {\n let cached = encoderCache.get(name);\n if (!cached) {\n cached = hasEncoderOnce(name).catch(() => false);\n encoderCache.set(name, cached);\n }\n return cached;\n}\n\nasync function hasEncoderOnce(name: string): Promise<boolean> {\n const ffmpeg = await resolveFfmpeg();\n const text = await new Promise<string>((res, rej) => {\n const child = spawn(ffmpeg, [\"-hide_banner\", \"-encoders\"], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n let out = \"\";\n child.stdout.on(\"data\", (d) => {\n out += d;\n });\n child.on(\"error\", rej);\n child.on(\"close\", (code) =>\n code === 0 ? res(out) : rej(new Error(`ffmpeg -encoders exited ${code}`)),\n );\n });\n return parseEncoders(text, name);\n}\n\nexport async function resolveFfprobe(): Promise<string> {\n if (cachedFfprobe) return cachedFfprobe;\n if (runsOk(\"ffprobe\")) {\n cachedFfprobe = \"ffprobe\";\n return cachedFfprobe;\n }\n const p = await installerPath(\"@ffprobe-installer/ffprobe\");\n await ensureExecutable(p);\n if (p && runsOk(p)) {\n cachedFfprobe = p;\n return p;\n }\n throw new Error(\n \"ffprobe not found — install ffmpeg (e.g. `brew install ffmpeg`) or `npm install` so the bundled @ffprobe-installer binary resolves for this platform\",\n );\n}\n","// Pure, isomorphic math — imported by both the node-side planner and the\n// revideo scene (compiled fresh by vite at render time). No node/browser\n// APIs in here.\n\nimport type { BBox, Pt, TakeComposition } from \"./types\";\n\n// smootherstep 6t^5-15t^4+10t^3\nexport function smoother(t: number): number {\n const clamped = Math.max(0, Math.min(1, t));\n return clamped * clamped * clamped * (clamped * (clamped * 6 - 15) + 10);\n}\n\n// Cubic-bezier easing y(x) with endpoints (0,0),(1,1) and control points\n// (x1,y1),(x2,y2) — the same model CSS easing uses. Solves x(s)=x by\n// bisection (cheap, monotone) then returns y(s). Lets the travel cursor use a\n// decelerate-biased curve (long, gentle settle) instead of symmetric easing.\nexport function cubicBezier(x1: number, y1: number, x2: number, y2: number): (x: number) => number {\n const bx = (s: number) => {\n const u = 1 - s;\n return 3 * u * u * s * x1 + 3 * u * s * s * x2 + s * s * s;\n };\n const by = (s: number) => {\n const u = 1 - s;\n return 3 * u * u * s * y1 + 3 * u * s * s * y2 + s * s * s;\n };\n return (x: number) => {\n if (x <= 0) return 0;\n if (x >= 1) return 1;\n let lo = 0,\n hi = 1,\n s = x;\n for (let i = 0; i < 24; i++) {\n const xt = bx(s);\n if (Math.abs(xt - x) < 1e-4) break;\n if (xt < x) lo = s;\n else hi = s;\n s = (lo + hi) / 2;\n }\n return by(s);\n };\n}\n\n// Spring-shaped easing y(p) over [0,1]: the unit step response of a damped\n// spring, time-normalised so it rises (and, for bounce>0, slightly overshoots)\n// then settles within the segment. `bounce` ∈ [0, ~0.6): 0 = critically damped\n// (no overshoot — a soft, physical ease-out); higher = more overshoot/snap.\n//\n// bounce 0 over the default zoom durations IS the measured reference zoom\n// feel: frame-tracking a reference export gave a critically-damped spring on the\n// camera rect, ω≈9.4 rad/s in / ω≈5.2 out (which also matches the spring\n// preset numbers from the reference teardown) —\n// i.e. this exact curve over ~730ms in / ~1340ms out.\n//\n// Under time-normalisation the curve depends ONLY on the damping ratio ζ=1−bounce\n// (the natural frequency cancels), so a single `bounce` knob is the whole shape —\n// the segment DURATION stays whatever the keyframes say (zoomInMs/zoomOutMs).\n// The response is normalised by its end value so the segment lands on exactly 1\n// (no end-of-segment snap from the finite settle band).\nexport function springEase(bounce: number): (p: number) => number {\n const zeta = Math.max(0.4, Math.min(1, 1 - bounce));\n const Ts = -Math.log(1e-3) / zeta; // settling time to the 0.1% band (ω0 = 1)\n const step = (t: number): number => {\n if (zeta >= 1) return 1 - Math.exp(-t) * (1 + t); // critically damped\n const wd = Math.sqrt(1 - zeta * zeta); // damped natural frequency (ω0 = 1)\n return 1 - Math.exp(-zeta * t) * (Math.cos(wd * t) + (zeta / wd) * Math.sin(wd * t));\n };\n const end = step(Ts);\n return (p: number) => {\n if (p <= 0) return 0;\n if (p >= 1) return 1;\n return step(p * Ts) / end;\n };\n}\n\n// The stage (camera rect) easing, selected from the cursor config. ONE curve\n// eases the whole rect — centre and size together (see stageCamera). The single\n// source the revideo scene (scene.tsx) AND the editor preview consume — any\n// other renderer must use it identically so renderers can never drift.\n// Precedence: spring (zoomSpring) → cubic-bezier (zoomEase) → the default\n// critically-damped spring (the measured reference curve).\nexport function stageEasing(cursor: TakeComposition[\"cursor\"]): (u: number) => number {\n if (cursor.zoomSpring != null) return springEase(cursor.zoomSpring);\n if (cursor.zoomEase) return cubicBezier(...cursor.zoomEase);\n return springEase(0);\n}\n\n// Backdrop gradient endpoints in TOP-LEFT origin (0..oW, 0..oH), shared by the\n// preview canvas and the revideo scene so the backdrop can't drift. `angle` is\n// CSS-like degrees (0 = upward); absent ⇒ the legacy (0,0)→(oW,oH) diagonal, so\n// existing compositions render pixel-identically. (Scene maps to centred coords\n// by subtracting oW/2, oH/2.)\nexport function gradientEndpoints(\n angleDeg: number | undefined,\n oW: number,\n oH: number,\n): { x0: number; y0: number; x1: number; y1: number } {\n if (angleDeg == null) return { x0: 0, y0: 0, x1: oW, y1: oH };\n const th = (angleDeg * Math.PI) / 180;\n const dx = Math.sin(th);\n const dy = -Math.cos(th);\n const L = Math.abs(oW * dx) + Math.abs(oH * dy); // CSS gradient line length\n const cx = oW / 2;\n const cy = oH / 2;\n return {\n x0: cx - (dx * L) / 2,\n y0: cy - (dy * L) / 2,\n x1: cx + (dx * L) / 2,\n y1: cy + (dy * L) / 2,\n };\n}\n\ntype KF<T> = [number, T];\n\nexport function keyvalN(\n t: number,\n kfs: KF<number>[],\n ease: (u: number) => number = smoother,\n): number {\n if (t <= kfs[0]![0]) return kfs[0]![1];\n if (t >= kfs[kfs.length - 1]![0]) return kfs[kfs.length - 1]![1];\n for (let i = 0; i < kfs.length - 1; i++) {\n const [t0, v0] = kfs[i]!;\n const [t1, v1] = kfs[i + 1]!;\n if (t0 <= t && t <= t1) {\n return v0 + (v1 - v0) * ease((t - t0) / (t1 - t0));\n }\n }\n return kfs[kfs.length - 1]![1];\n}\n\n// --- bbox-fit zoom (Finding 1) -----------------------------------------\n\n/**\n * Scale (absolute, video-px → output-px) that fits `bbox` into `fillFrac`\n * of the output frame, capped at `maxScale` and floored at `restScale`.\n * Wide/long elements naturally get a gentler scale because the limiting\n * dimension dominates min().\n */\nexport function bboxFitScale(\n bbox: BBox,\n outW: number,\n outH: number,\n fillFrac: number,\n maxScale: number,\n restScale: number,\n): number {\n const fitW = (outW * fillFrac) / Math.max(1, bbox.w);\n const fitH = (outH * fillFrac) / Math.max(1, bbox.h);\n return Math.min(maxScale, Math.max(restScale, Math.min(fitW, fitH)));\n}\n\n/** Stage scale at rest: video inset into the frame (leaves backdrop margin). */\nexport function restStageScale(\n videoW: number,\n videoH: number,\n outW: number,\n outH: number,\n insetFrac: number,\n): number {\n return insetFrac * Math.min(outW / videoW, outH / videoH);\n}\n\n/**\n * Clamp a desired video-px center so the scaled video still covers the output\n * frame (the viewport crop stays inside the source video) when zoomed in. When\n * the content does not cover an axis (zoomed out / inset), centre that axis.\n *\n * In the composition-camera model the whole composition\n * (backdrop + inset screen) is zoomed by one camera; this keeps the camera crop\n * within the screen so a zoom fills the frame (no backdrop margin) without ever\n * panning past the recording's edge.\n */\nexport function clampCenter(\n center: Pt,\n scale: number,\n videoW: number,\n videoH: number,\n outW: number,\n outH: number,\n): Pt {\n const halfW = outW / (2 * scale);\n const halfH = outH / (2 * scale);\n const cx =\n videoW * scale >= outW ? Math.min(Math.max(center.x, halfW), videoW - halfW) : videoW / 2;\n const cy =\n videoH * scale >= outH ? Math.min(Math.max(center.y, halfH), videoH - halfH) : videoH / 2;\n return { x: cx, y: cy };\n}\n\n// --- stage (camera rect) keyframes from the composition ----------------\n\n/** The camera as a viewport RECT in video-px: centre + full viewport width\n * (height is implied by the output aspect: h = w·oH/oW). scale = oW / w. */\nexport type CamRect = { cx: number; cy: number; w: number };\n\nexport type StageKeyframes = {\n r: KF<CamRect>[]; // viewport rect over time (seconds)\n T: number; // total duration (s)\n};\n\n/** Interpolate the rect track: centre AND size move under the SAME eased\n * parameter. This is the whole trick (verified\n * by frame-tracking a reference export: its pan curve overlays its viewport-WIDTH\n * curve exactly, not its scale curve): lerping the rect keeps every corner on\n * a straight line, so the screen-space path of the zoom target is strictly\n * monotone toward frame centre — no wrong-way \"bounce\" for ANY scale pair,\n * which scale+centre lerp can't guarantee (it hooks when scale > 2×rest). */\nexport function keyvalR(t: number, kfs: KF<CamRect>[], ease: (u: number) => number): CamRect {\n if (t <= kfs[0]![0]) return kfs[0]![1];\n if (t >= kfs[kfs.length - 1]![0]) return kfs[kfs.length - 1]![1];\n for (let i = 0; i < kfs.length - 1; i++) {\n const [t0, v0] = kfs[i]!;\n const [t1, v1] = kfs[i + 1]!;\n if (t0 <= t && t <= t1) {\n const p = ease((t - t0) / (t1 - t0));\n // A spring ease (zoomSpring > 0) overshoots p past 1, extrapolating the\n // rect beyond its target — that's the wanted \"snap\", but on a deep punch\n // with a large bounce the extrapolated width could collapse through 0\n // (scale sign-flip = garbage frames). Floor the width against the\n // segment's own endpoints so overshoot can tighten at most 2× past the\n // tighter one; monotone eases (p ∈ [0,1]) never hit the floor.\n return {\n cx: v0.cx + (v1.cx - v0.cx) * p,\n cy: v0.cy + (v1.cy - v0.cy) * p,\n w: Math.max(v0.w + (v1.w - v0.w) * p, Math.min(v0.w, v1.w) * 0.5),\n };\n }\n }\n return kfs[kfs.length - 1]![1];\n}\n\n// The camera schedule shared by buildStageKeyframes (the render path) and\n// cameraRampSchedule (the refine surfaces — A/B windows, review badges): which\n// events anchor a camera move, when each ramp departs, and when it lands.\n// One computation so the badge/window timing can never drift from the render.\ntype CameraSchedule = {\n anchors: {\n evIdx: number;\n tMs: number;\n durationMs: number;\n inAtMs: number;\n scale: number;\n center: Pt;\n glide?: Pt;\n }[];\n targets: CamRect[];\n restR: CamRect;\n /** per-anchor ramp window, SECONDS */\n ramps: { start: number; end: number }[];\n /** per-anchor landing time, SECONDS (≥ ramp start + a minimal real ramp;\n * == tMs for every on-time ramp, later for a dwell-delayed pull-out or a\n * reveal-timed press whose ramp departs AT the action) */\n landTs: number[];\n rectFor: (center: Pt, scale: number) => CamRect;\n};\n\nfunction buildCameraSchedule(comp: TakeComposition): CameraSchedule {\n const { videoWidth: vW, videoHeight: vH } = comp.source;\n const { width: oW, height: oH } = comp.output;\n const rest = restStageScale(vW, vH, oW, oH, comp.framing.insetFrac);\n const restC: Pt = { x: vW / 2, y: vH / 2 };\n const ZOUT_MS = comp.cursor.zoomOutMs;\n\n // A framing target is clamped ONCE, here at build time (the viewport crop\n // stays inside the recording; an axis it doesn't cover centres). Every\n // keyframe rect is therefore valid — and for a monotone ease (p ∈ [0,1];\n // every default) lerped rect corners stay between the endpoints' corners, so\n // every IN-BETWEEN rect is valid too. No per-frame clamp, so the clamp can\n // never bend a path mid-flight (the old model's per-frame clamp force-\n // centred the pan while the video under-covered the frame, then released it\n // mid-zoom — a visible lurch; and its zoom-out \"land the centre early\"\n // repair made pull-outs pan-then-zoom two-phase). A zoomSpring bounce > 0\n // deliberately overshoots PAST the target rect (edge-flush targets can\n // flash a sliver of backdrop during the settle — the physical cost of\n // bounce; keyvalR floors only the width collapse).\n const rectFor = (center: Pt, scale: number): CamRect => {\n const c = clampCenter(center, scale, vW, vH, oW, oH);\n return { cx: c.x, cy: c.y, w: oW / scale };\n };\n const restR = rectFor(restC, rest);\n\n // Framing anchors over time. A zoom-enabled beat ramps to its target; a\n // scroll (content pans) and a zoom-less press (Escape/Enter whose effect is\n // global) ramp back to REST so the frame is full-view through them — without\n // these, a prior zoom would persist across the scroll/keypress. Every OTHER\n // disabled beat (a \"never\" click/hover/type/drag) means the same thing —\n // the director only ever disables a beat to show it FULL-VIEW — so it too\n // anchors to rest, but only while the camera is actually away from rest: a\n // disabled beat over an already-resting camera adds no anchor, keeping\n // legacy compositions (and their badge/A/B windows) byte-identical. The old\n // hold-prior-framing behavior left a `zoom:\"never\"` GLOBAL payoff cropped\n // inside the previous beat's punch (the 2026-07-27 interlinear field run).\n const anchors: CameraSchedule[\"anchors\"] = [];\n const awayFromRest = (): boolean => {\n const a = anchors[anchors.length - 1];\n if (!a) return false;\n return (\n Math.abs(a.scale - rest) > 1e-6 ||\n Math.abs(a.center.x - restC.x) > 0.5 ||\n Math.abs(a.center.y - restC.y) > 0.5\n );\n };\n comp.events.forEach((e, evIdx) => {\n const base = { evIdx, tMs: e.tMs, durationMs: e.durationMs ?? 0, inAtMs: e.zoom.inAtMs };\n if (e.kind === \"scroll\" || (!e.zoom.enabled && (e.kind === \"press\" || awayFromRest()))) {\n anchors.push({ ...base, scale: rest, center: restC });\n } else if (e.zoom.enabled) {\n anchors.push({ ...base, scale: e.zoom.scale, center: e.zoom.center, glide: e.zoom.glide });\n }\n });\n\n const targets = anchors.map((e) => rectFor(e.center, e.scale));\n\n // Effective ramp start per anchor. A PULL-OUT (wider viewport than the rect\n // it leaves) paces with zoomOutMs — measured on the reference export,\n // the pull-out is ~1.8× slower than the punch-in. The stored inAtMs keeps\n // governing punch-ins/same-size travels, and a HAND-SET inAtMs (≠ the\n // planner default tMs − zoomInMs) wins even for a pull-out, so the per-beat\n // timing knob stays live. When the zoomOutMs window would start before the\n // previous action's end, shorten it toward the punch-in window rather than\n // cut the payoff — but NEVER squeeze below min(zoomOutMs, zoomInMs) of real\n // ramp: a pull-out with no window is a jump cut, which is strictly worse\n // than leaving a payoff a little early.\n const ZIN_MS = comp.cursor.zoomInMs;\n const DWELL_MS = comp.cursor.pullOutDwellMs ?? 0;\n // A ramp whose departure sits AT/after its own action is REVEAL-timed: the\n // planner pins a zoom-enabled press there (its payoff exists only after the\n // keypress — a lead-in would punch into empty space), and a hand-set late\n // inAtMs means the same thing. Landing at tMs would make start === end (a\n // jump cut), so these get a full ramp window AFTER the departure instead.\n const revealTimed = (e: { inAtMs: number; tMs: number }): boolean => e.inAtMs >= e.tMs;\n const ramps = anchors.map((e, i) => {\n const from = i > 0 ? targets[i - 1]! : restR;\n const pullOut = targets[i]!.w > from.w + 1e-6;\n if (revealTimed(e))\n return { start: e.inAtMs / 1000, end: (e.inAtMs + (pullOut ? ZOUT_MS : ZIN_MS)) / 1000 };\n const isDefaultInAt = Math.abs(e.inAtMs - Math.max(0, e.tMs - ZIN_MS)) < 1;\n if (!pullOut || !isDefaultInAt) return { start: e.inAtMs / 1000, end: e.tMs / 1000 };\n const desired = e.tMs - ZOUT_MS;\n const prevEndMs = i > 0 ? anchors[i - 1]!.tMs + anchors[i - 1]!.durationMs : 0;\n const floor = prevEndMs + DWELL_MS;\n if (desired >= floor) return { start: Math.max(desired, 0) / 1000, end: e.tMs / 1000 };\n if (DWELL_MS > 0) {\n // The dwell floor pushes the departure past the on-time window: keep the\n // full pull-out ramp and LAND LATE (after the action instant) rather than\n // flee a frame the viewer is still reading. The landing is capped at the\n // next anchor's ramp start at push time.\n return { start: floor / 1000, end: (floor + ZOUT_MS) / 1000 };\n }\n const start = Math.min(prevEndMs, e.tMs - Math.min(ZOUT_MS, ZIN_MS));\n return { start: Math.max(start, 0) / 1000, end: e.tMs / 1000 };\n });\n // Second pass: a dwell-floored ramp must still FIT a real ramp before the\n // next anchor departs — otherwise the landT cap would invert it into a\n // 1ms jump cut (push()'s monotone clamp collapses it). Give up dwell time\n // before ramp time: shrink the dwell so at least min(zoomOutMs, zoomInMs)\n // of real ramp survives, and when even zero dwell has no room fall back to\n // the exact legacy squeeze. (Anchor starts never depend on earlier ramps'\n // ends, so one forward pass over pass-1 values is complete.)\n if (DWELL_MS > 0) {\n const minRamp = Math.min(ZOUT_MS, ZIN_MS);\n for (let i = 0; i < ramps.length - 1; i++) {\n const r = ramps[i]!;\n const e = anchors[i]!;\n if (revealTimed(e)) continue; // fitted in the reveal pass below (departure is pinned)\n if (r.end <= e.tMs / 1000 + 1e-9) continue; // on-time ramp — not dwell-late\n const latestStart = ramps[i + 1]!.start - 0.01 - minRamp / 1000;\n if (r.start <= latestStart) continue; // the late landing fits\n const prevEndMs = i > 0 ? anchors[i - 1]!.tMs + anchors[i - 1]!.durationMs : 0;\n if (latestStart * 1000 >= prevEndMs) {\n r.start = latestStart;\n r.end = Math.min(r.start + ZOUT_MS / 1000, ramps[i + 1]!.start - 0.01);\n } else {\n const start = Math.min(prevEndMs, e.tMs - minRamp);\n r.start = Math.max(start, 0) / 1000;\n r.end = e.tMs / 1000;\n }\n }\n }\n\n // Reveal fit pass: a reveal-timed ramp's departure is PINNED at the action —\n // moving it earlier would re-create the exact artifact this timing removes\n // (zooming into a reveal that doesn't exist yet). When the full window would\n // run into the next anchor's departure, shrink the ramp (a faster punch)\n // instead, floored at half a window so it still reads as a move; anything\n // tighter falls to push()'s monotone clamp like any other crowding.\n const REVEAL_MIN_S = Math.min(ZOUT_MS, ZIN_MS) / 2000;\n for (let i = 0; i < ramps.length; i++) {\n if (!revealTimed(anchors[i]!)) continue;\n const r = ramps[i]!;\n const nextStart = i + 1 < ramps.length ? ramps[i + 1]!.start : Number.POSITIVE_INFINITY;\n r.end = Math.max(r.start + REVEAL_MIN_S, Math.min(r.end, nextStart - 0.01));\n }\n\n // A dwell-delayed pull-out lands after its own action instant; cap the\n // landing so it can never run into the next anchor's ramp (floored at a\n // minimal real ramp — the fits-check in the dwell pass guarantees room).\n // An on-time ramp (end === tMs, every legacy entry) keeps the exact old\n // landing; a pass-2-shrunk ramp may deliberately land BEFORE its tMs. A\n // reveal-timed ramp was already fitted above — it lands exactly at its end.\n const landTs = anchors.map((e, i) => {\n const nextStart = anchors[i + 1] ? ramps[i + 1]!.start : Number.POSITIVE_INFINITY;\n const rampEnd = ramps[i]!.end;\n if (revealTimed(e)) return rampEnd;\n return rampEnd === e.tMs / 1000\n ? rampEnd\n : Math.max(\n ramps[i]!.start + Math.min(ZOUT_MS, ZIN_MS) / 1000,\n Math.min(rampEnd, nextStart - 0.01),\n );\n });\n\n return { anchors, targets, restR, ramps, landTs, rectFor };\n}\n\n/** Per-EVENT camera ramp timing (ms), for the refine surfaces (A/B windows,\n * review badges): when the camera actually departs toward a beat and when it\n * lands. `null` for a beat the camera holds through (no anchor). Derived from\n * the same schedule the render uses, so a dwell-delayed pull-out (which\n * departs after the stored inAtMs and can land after its own tMs) is\n * reflected instead of approximated from inAtMs. `pullOut` says which pace\n * knob the window belongs to (zoomOutMs vs zoomInMs) — the same test the\n * schedule itself makes, so a reader can't drift from it. */\nexport function cameraRampSchedule(\n comp: TakeComposition,\n): ({ startMs: number; landMs: number; pullOut: boolean } | null)[] {\n const { anchors, targets, restR, ramps, landTs } = buildCameraSchedule(comp);\n const out: ({ startMs: number; landMs: number; pullOut: boolean } | null)[] = comp.events.map(\n () => null,\n );\n anchors.forEach((a, i) => {\n const from = i > 0 ? targets[i - 1]! : restR;\n out[a.evIdx] = {\n startMs: ramps[i]!.start * 1000,\n landMs: landTs[i]! * 1000,\n pullOut: targets[i]!.w > from.w + 1e-6,\n };\n });\n return out;\n}\n\nexport function buildStageKeyframes(comp: TakeComposition): StageKeyframes {\n const { anchors, targets, restR, ramps, landTs, rectFor } = buildCameraSchedule(comp);\n const HOLD = comp.cursor.holdMs / 1000;\n const ZOUT_MS = comp.cursor.zoomOutMs;\n\n const rf: { t: number; r: CamRect }[] = [{ t: 0, r: restR }];\n const push = (t: number, r: CamRect) => {\n rf.push({ t: Math.max(t, rf[rf.length - 1]!.t + 1e-3), r });\n };\n\n let cur = restR;\n anchors.forEach((e, i) => {\n // the action plays out (typing/drawing/scrolling) for durationMs after tMs\n // — hold the target framing through it (a point click has duration 0).\n const actionEnd = (e.tMs + e.durationMs) / 1000;\n const next = anchors[i + 1];\n const nextStart = next ? ramps[i + 1]!.start : Number.POSITIVE_INFINITY;\n const landT = landTs[i]!;\n const holdEndT = Math.max(next ? nextStart : actionEnd + HOLD, landT);\n push(ramps[i]!.start, cur); // hold current until ramp begins\n push(landT, targets[i]!); // ONE eased rect segment lands at the action\n cur = targets[i]!;\n // glide: drift the held centre across the hold window (velocity px/s ·\n // holdSeconds), so a held zoom slowly pans instead of sitting dead-static.\n // Clamped like any target so the drift can't leave the recording.\n let holdR = cur;\n if (e.glide && (e.glide.x !== 0 || e.glide.y !== 0)) {\n const holdDur = Math.max(0, holdEndT - landT);\n holdR = rectFor(\n { x: e.center.x + e.glide.x * holdDur, y: e.center.y + e.glide.y * holdDur },\n e.scale,\n );\n }\n push(holdEndT, holdR); // hold (or glide) until the next ramp / the tail\n cur = holdR;\n if (!next) {\n push(holdEndT + ZOUT_MS / 1000, restR); // final zoom-out, one rect segment\n cur = restR;\n }\n });\n\n const lastT = rf[rf.length - 1]!.t;\n const T = Math.max(comp.durationMs / 1000, lastT) + 0.3;\n push(T, restR);\n\n return { r: rf.map((f) => [f.t, f.r]), T };\n}\n\n// --- asymptotic settle (zoomSettleFrac) --------------------------------\n\n/** Residual (1 − progress) of an overdamped spring's unit step response, on\n * NORMALISED segment time u = (t − t0)/(t1 − t0). ω0 is solved so the\n * residual at u=1 (the action instant) equals `frac`; past u=1 the same\n * curve keeps decaying — the tail that replaces the legacy cut. ζ=1.2 gives\n * the reference-measured shape: a fast main ramp (peak velocity ~14% in)\n * plus a slow settle pole; at frac 0.04 the tail τ ≈ duration/3.6 (730ms →\n * ~205ms, 1340ms → ~375ms — the frame-tracked reference tails; a different\n * frac shifts ω0 and with it τ). */\nfunction settleDecay(frac: number): (u: number) => number {\n const zeta = 1.2;\n const s = Math.sqrt(zeta * zeta - 1);\n const l1 = zeta + s;\n const l2 = zeta - s;\n const resid = (x: number) => (l1 * Math.exp(-l2 * x) - l2 * Math.exp(-l1 * x)) / (l1 - l2);\n let lo = 0.1;\n let hi = 60;\n for (let i = 0; i < 60; i++) {\n const mid = (lo + hi) / 2;\n if (resid(mid) > frac) lo = mid;\n else hi = mid;\n }\n const w0T = (lo + hi) / 2;\n return (u: number) => (u <= 0 ? 1 : resid(w0T * u));\n}\n\n/** Evaluate the rect track with moves that settle ASYMPTOTICALLY: each ramp\n * covers 1−frac of its distance by its keyframe end, then keeps creeping\n * toward the target through the following hold (never a velocity cliff). A\n * ramp launches from wherever the previous tail actually is (position-\n * continuous chaining); every emitted rect is a convex combination of\n * build-time-clamped rects, and the valid-rect set is convex (linear\n * half-plane bounds in cx,cy,w), so in-between rects stay valid exactly as\n * in the lerped path. */\nfunction settleRectAt(kfs: KF<CamRect>[], decay: (u: number) => number, t: number): CamRect {\n let from = kfs[0]![1];\n for (let i = 0; i < kfs.length - 1; i++) {\n const [t0, r0] = kfs[i]!;\n const [t1, r1] = kfs[i + 1]!;\n if (r0.cx === r1.cx && r0.cy === r1.cy && r0.w === r1.w) continue; // hold — the active tail keeps running\n if (t < t0) break;\n // find when the NEXT move begins — this move's tail runs until then\n let handoff = Number.POSITIVE_INFINITY;\n for (let j = i + 1; j < kfs.length - 1; j++) {\n const [ta, ra] = kfs[j]!;\n const [, rb] = kfs[j + 1]!;\n if (ra.cx !== rb.cx || ra.cy !== rb.cy || ra.w !== rb.w) {\n handoff = ta;\n break;\n }\n }\n const evalT = Math.min(t, handoff);\n const d = decay((evalT - t0) / Math.max(t1 - t0, 1e-6));\n from = {\n cx: r1.cx + (from.cx - r1.cx) * d,\n cy: r1.cy + (from.cy - r1.cy) * d,\n w: r1.w + (from.w - r1.w) * d,\n };\n if (t < handoff) return from;\n }\n return from;\n}\n\n/** The one camera evaluator — scene.tsx (render) and the editor preview both\n * consume THIS, so preview and export can never drift. */\nexport function stageCamera(comp: TakeComposition): {\n T: number;\n rest: number;\n peakScale: number;\n at: (t: number) => { scale: number; center: Pt };\n} {\n const stage = buildStageKeyframes(comp);\n const ease = stageEasing(comp.cursor);\n const oW = comp.output.width;\n const rest = restStageScale(\n comp.source.videoWidth,\n comp.source.videoHeight,\n oW,\n comp.output.height,\n comp.framing.insetFrac,\n );\n // zoomSettleFrac swaps the segment-lerped track for the asymptotic-settle\n // evaluator; explicit zoomSpring/zoomEase keep their exact legacy curves.\n const frac = comp.cursor.zoomSettleFrac ?? 0;\n const useSettle = frac > 0 && comp.cursor.zoomSpring == null && !comp.cursor.zoomEase;\n const decay = useSettle ? settleDecay(frac) : undefined;\n const at = (t: number) => {\n const r = decay ? settleRectAt(stage.r, decay, t) : keyvalR(t, stage.r, ease);\n return { scale: oW / r.w, center: { x: r.cx, y: r.cy } };\n };\n // Peak by sampling (not just keyframe extremes): a spring ease overshoots\n // mid-segment, so the true peak can sit above every keyframe.\n let peakScale = stage.r.reduce((m, [, r]) => Math.max(m, oW / r.w), rest);\n for (let i = 0; i <= 720; i++) peakScale = Math.max(peakScale, at((i / 720) * stage.T).scale);\n return { T: stage.T, rest, peakScale, at };\n}\n\n// --- cursor path (eased, with gentle arc) ------------------------------\n\n// A `drag` leg carries the polyline the cursor follows with the button held\n// (no perpendicular arc — it traces the real stroke). A normal travel leg has\n// no path and gets the gentle arc.\ntype Leg = {\n t0: number;\n t1: number;\n a: Pt;\n b: Pt;\n drag?: boolean;\n path?: Pt[];\n ease?: \"linear\" | \"smooth\";\n /** Diagnostics only (never read by the render): which travel clamp, if\n * either, set this leg's duration instead of the speed law. The clamps run\n * AFTER the speed model, so a clamped leg is one where `travelWidthsPerSec`\n * — and therefore the whole `pace` preset — has no say. validate.ts reports\n * it when it stops being the exception and becomes the rule. */\n clamped?: \"min\" | \"max\";\n /** Diagnostics only: the duration (s) the clamped speed law asked for. When\n * the delivered `t1 - t0` is shorter, the previous beat's action ran too\n * late to leave room and the move is being rushed — a CAPTURE-side gap no\n * cursor knob can fix. `evIdx` is the event this leg travels to. */\n wantSec?: number;\n evIdx?: number;\n};\n\n/** Cumulative ∫ (rest / cameraScale) dt over the take, on a uniform grid.\n *\n * The integrand is how much of the DELIVERED frame one video-px of movement\n * buys, normalised so a camera at rest integrates to 1 — so this converts a\n * video-px path into the distance the VIEWER actually sees it cross, and\n * INVERTING it answers \"when must this move depart to hold a constant\n * on-screen speed\". Strictly increasing (the integrand is > 0), so the\n * inverse is single-valued and a binary search finds it. Outside the sampled\n * window the end value extrapolates linearly at the end slope.\n *\n * This is a function of the camera schedule alone (which reads comp.events /\n * comp.cursor, never the legs), so pricing a leg with it introduces no cycle. */\nfunction zoomFracTrack(cam: { T: number; rest: number; at: (t: number) => { scale: number } }) {\n const STEP = 0.005; // 5ms — ~150× finer than the shortest shipped camera ramp\n const n = Math.max(2, Math.min(20000, Math.ceil(cam.T / STEP) + 1));\n const step = cam.T > 0 ? cam.T / (n - 1) : STEP;\n const zf = (t: number) => cam.rest / Math.max(cam.at(t).scale, 1e-6);\n const cum = new Float64Array(n);\n const zf0 = zf(0);\n let prev = zf0;\n for (let i = 1; i < n; i++) {\n const v = zf(i * step);\n cum[i] = cum[i - 1]! + ((prev + v) / 2) * step; // trapezoid\n prev = v;\n }\n const zfT = prev;\n const tEnd = (n - 1) * step;\n const last = cum[n - 1]!;\n return {\n at(t: number): number {\n if (t <= 0) return t * zf0;\n if (t >= tEnd) return last + (t - tEnd) * zfT;\n const i = Math.floor(t / step);\n const f = t / step - i;\n return cum[i]! + (cum[i + 1]! - cum[i]!) * f;\n },\n /** the t at which the cumulative integral equals `y` */\n invert(y: number): number {\n if (y <= 0) return zf0 > 0 ? y / zf0 : 0;\n if (y >= last) return tEnd + (zfT > 0 ? (y - last) / zfT : 0);\n let lo = 0;\n let hi = n - 1;\n while (hi - lo > 1) {\n const mid = (lo + hi) >> 1;\n if (cum[mid]! <= y) lo = mid;\n else hi = mid;\n }\n const span = cum[hi]! - cum[lo]!;\n return (lo + (span > 0 ? (y - cum[lo]!) / span : 0)) * step;\n },\n };\n}\n\nexport function buildLegs(comp: TakeComposition): Leg[] {\n const legs: Leg[] = [];\n let cur: Pt = comp.start;\n // When the previous beat's ACTION finishes (tMs + durationMs) — not when its\n // travel leg landed. See the prevEnd comment below.\n let freeAt = 0;\n // Distance-aware travel: hold a roughly constant on-screen speed (premium\n // feel) instead of a fixed duration (which makes short moves slow + long\n // moves fast). Falls back to the fixed travelMs when speed is unset/0.\n const { travelWidthsPerSec, travelMinMs, travelMaxMs, travelMs } = comp.cursor;\n // ON-SCREEN means the DELIVERED frame, not the raw recording. While the\n // camera is zoomed in, a video-px move covers proportionally more of the\n // frame — so a zoom-blind duration makes every zoomed move read that many\n // times too fast, precisely where the viewer is looking closest (a 2x punch\n // -in doubles the apparent speed).\n // The magnification is not constant ACROSS a leg, though: a travel typically\n // departs while the camera is still wide and lands after it has closed in, so\n // pricing the whole leg at the ARRIVAL magnification (the most punched-in\n // instant it ever sees) over-slows the departure by as much as it was\n // previously over-fast. Solve the honest thing instead — depart at the\n // instant from which the INTEGRATED on-screen distance to the target equals\n // one leg's worth of travel at the reference speed — which is exactly what\n // inverting the zoomFrac track does. A camera that never leaves rest\n // integrates to the identity, so a full-view take keeps its measured-by-eye\n // calibration bit-for-bit (short-circuited below to keep that exact).\n // Built lazily: only a composition that actually travels needs the camera,\n // and a zoom-less take must not pay for the track.\n let cam: ReturnType<typeof stageCamera> | undefined;\n let track: ReturnType<typeof zoomFracTrack> | undefined;\n const travelDur = (a: Pt, b: Pt, arriveSec: number): { sec: number; clamped?: \"min\" | \"max\" } => {\n if (!travelWidthsPerSec) return { sec: travelMs / 1000 };\n const speedPxPerSec = travelWidthsPerSec * comp.source.videoWidth;\n if (speedPxPerSec <= 0) return { sec: travelMs / 1000 };\n const dist = Math.hypot(b.x - a.x, b.y - a.y);\n cam ??= stageCamera(comp);\n let ms: number;\n if (cam.peakScale <= cam.rest + 1e-9) {\n ms = (dist / speedPxPerSec) * 1000; // camera never leaves rest — closed form\n } else {\n track ??= zoomFracTrack(cam);\n ms = (arriveSec - track.invert(track.at(arriveSec) - dist / speedPxPerSec)) * 1000;\n }\n if (ms < travelMinMs) return { sec: travelMinMs / 1000, clamped: \"min\" };\n if (ms > travelMaxMs) return { sec: travelMaxMs / 1000, clamped: \"max\" };\n return { sec: ms / 1000 };\n };\n for (const [evIdx, e] of comp.events.entries()) {\n // scroll/press/look are not pointer-driven — the cursor holds where it was\n // (the content pans / the keyboard acts / the CAMERA does the moving). No\n // travel leg; `cur` is untouched, so the between-legs parking logic keeps\n // the cursor at its last anchor. For a look this parking IS the feature:\n // cursor movement promises an action, and a look makes none — the camera\n // frames the target while the cursor honestly stays put.\n // They still OCCUPY the frame for durationMs, though: a scroll's duration IS\n // the pan, a press's is the reveal animating in, a look's is the framed\n // hold. A travel that departs into any of them puts two motions on screen\n // at once — content sliding under a cursor crossing it — so they push\n // `freeAt` exactly like a pointer beat even though they contribute no leg.\n if (e.kind === \"scroll\" || e.kind === \"press\" || e.kind === \"look\") {\n freeAt = Math.max(freeAt, (e.tMs + (e.durationMs ?? 0)) / 1000);\n continue;\n }\n const arrive = e.tMs / 1000;\n // Start travelDur before arrival, but never before the previous leg ended\n // (a long glide into a quick succession would otherwise overlap it — then\n // the move just runs in the available window, a touch faster than target)\n // and never before the previous beat's ACTION finished. A travel leg ends\n // at its tMs, but a `type` keeps emitting keystrokes for durationMs after\n // that — so the leg end alone would let a long enough glide drag the\n // pointer off the field mid-word.\n // …and never AFTER the arrival: overlapping action windows (only reachable\n // by hand — a capture always leaves a settle gap) would otherwise build an\n // INVERTED leg, which matches no instant at all in cursorPos, so the cursor\n // would silently jump-cut instead of degrading to a hard landing.\n const prevEnd = Math.max(legs.length ? legs[legs.length - 1]!.t1 : 0, freeAt);\n const d = travelDur(cur, e.point, arrive);\n const t0 = Math.min(arrive, Math.max(arrive - d.sec, prevEnd, 0));\n legs.push({\n t0,\n t1: arrive,\n a: cur,\n b: e.point,\n evIdx,\n wantSec: d.sec,\n ...(d.clamped ? { clamped: d.clamped } : {}),\n });\n cur = e.point;\n freeAt = Math.max(freeAt, (e.tMs + (e.durationMs ?? 0)) / 1000);\n if ((e.kind === \"drag\" || e.kind === \"dropFiles\") && e.to) {\n // Delay the stroke by dragLagMs so the cursor rides the captured ink front\n // (the ink trails the pen by the capture-pipeline latency). The cursor\n // holds at the start point during the gap [arrive, arrive+lag], then traces\n // — matching when the ink actually appears on screen. A dropFiles carry\n // has no ink, but the page's dragover reaction rode the same capture\n // pipeline, so the same lag keeps cursor and reaction in step.\n const lag = comp.cursor.dragLagMs / 1000;\n const start = arrive + lag;\n const dEnd = (e.tMs + (e.durationMs ?? 0)) / 1000 + lag;\n const path = e.path && e.path.length >= 2 ? e.path : [e.point, e.to];\n if (dEnd > start)\n legs.push({ t0: start, t1: dEnd, a: e.point, b: e.to, drag: true, path, ease: e.ease });\n cur = e.to;\n }\n }\n return legs;\n}\n\n/** Point a fraction `u` (0..1) along a polyline, parameterised by arc length. */\nfunction alongPath(path: Pt[], u: number): Pt {\n if (path.length === 1) return path[0]!;\n const seg: number[] = [];\n let total = 0;\n for (let i = 0; i < path.length - 1; i++) {\n const d = Math.hypot(path[i + 1]!.x - path[i]!.x, path[i + 1]!.y - path[i]!.y);\n seg.push(d);\n total += d;\n }\n if (total === 0) return path[0]!;\n let target = u * total;\n for (let i = 0; i < seg.length; i++) {\n if (target <= seg[i]! || i === seg.length - 1) {\n const f = seg[i]! > 0 ? target / seg[i]! : 0;\n return {\n x: path[i]!.x + (path[i + 1]!.x - path[i]!.x) * f,\n y: path[i]!.y + (path[i + 1]!.y - path[i]!.y) * f,\n };\n }\n target -= seg[i]!;\n }\n return path[path.length - 1]!;\n}\n\nexport function cursorPos(t: number, legs: Leg[], comp: TakeComposition): Pt {\n for (const lg of legs) {\n if (lg.t0 <= t && t <= lg.t1) {\n // A ZERO-span leg (a departure clamped all the way to its own arrival —\n // see buildLegs) has landed by definition; without the guard the 0/0\n // would put NaN through the ease and blank the cursor for that frame.\n const span = lg.t1 - lg.t0;\n const raw = span > 0 ? Math.max(0, Math.min(1, (t - lg.t0) / span)) : 1;\n // A drag replays the captured stroke's pacing so the cursor stays locked\n // to the ink: \"smooth\" (accel-in / decel-out — a natural hand-draw) or\n // \"linear\" (constant speed). The capture bakes the SAME curve into the ink\n // (cdp-capture.ts) and records it on the event; absent ⇒ linear (legacy).\n // (Held-button moves are fire-and-forget there, so the slow eased ends —\n // sub-pixel, no paint — no longer stall the stroke; cursor and ink are\n // both ~stationary at the ends, so they stay locked.)\n if (lg.drag && lg.path) return alongPath(lg.path, lg.ease === \"smooth\" ? smoother(raw) : raw);\n const e = comp.cursor.travelEase;\n const p = e ? cubicBezier(e[0], e[1], e[2], e[3])(raw) : smoother(raw);\n const base = { x: lg.a.x + (lg.b.x - lg.a.x) * p, y: lg.a.y + (lg.b.y - lg.a.y) * p };\n const dx = lg.b.x - lg.a.x,\n dy = lg.b.y - lg.a.y;\n const L = Math.hypot(dx, dy) || 1;\n const arc = Math.min(comp.cursor.arcFrac * L, comp.cursor.arcMax) * Math.sin(Math.PI * p);\n return { x: base.x + (-dy / L) * arc, y: base.y + (dx / L) * arc };\n }\n }\n if (legs.length === 0 || t < legs[0]!.t0) return comp.start;\n for (let i = 0; i < legs.length - 1; i++)\n if (legs[i]!.t1 < t && t < legs[i + 1]!.t0) return legs[i]!.b;\n return legs[legs.length - 1]!.b;\n}\n\n/** True while a drag is mid-stroke (button held) — for the pressed cursor. */\nexport function isDragging(t: number, legs: Leg[]): boolean {\n return legs.some((lg) => lg.drag === true && lg.t0 <= t && t <= lg.t1);\n}\n\n// --- file ghost card (dropFiles) ----------------------------------------\n\n/** A dropFiles carry's on-screen window [start, end] in SECONDS — when the\n * ghost card rides the cursor. Same dragLagMs shift as the carry leg in\n * buildLegs, so card and cursor cannot drift apart. Shared by the Revideo\n * scene and the editor preview (the no-drift invariant). */\nexport function carryWindow(\n e: { tMs: number; durationMs?: number },\n comp: TakeComposition,\n): { t0: number; t1: number } {\n const lag = comp.cursor.dragLagMs / 1000;\n const t0 = e.tMs / 1000 + lag;\n return { t0, t1: t0 + (e.durationMs ?? 0) / 1000 };\n}\n\n/** \"1.2 MB\" / \"412 KB\" — the ghost card's size caption (scene + preview). */\nexport function fmtBytes(n: number): string {\n return n >= 1024 * 1024\n ? `${(n / 1024 / 1024).toFixed(1)} MB`\n : `${Math.max(1, Math.round(n / 1024))} KB`;\n}\n\n/** The ghost card's two text lines for a dropFiles beat: the (first) filename,\n * and a meta caption (\"3 files · 1.8 MB\" / \"1.2 MB\"). Shared scene/preview.\n * Long filenames middle-ellipse (extension kept) so the card can't outgrow\n * the frame — neither render surface clamps its width. */\nexport function ghostCardLines(files: { name: string; size?: number }[]): {\n title: string;\n meta: string;\n} {\n const raw = files[0]?.name ?? \"file\";\n const MAX = 34;\n const title = raw.length <= MAX ? raw : `${raw.slice(0, MAX - 12)}…${raw.slice(raw.length - 11)}`;\n const total = files.reduce((s, f) => s + (f.size ?? 0), 0);\n const size = total > 0 ? fmtBytes(total) : \"\";\n const count = files.length > 1 ? `${files.length} files` : \"\";\n return { title, meta: [count, size].filter(Boolean).join(\" · \") };\n}\n","// auditCursor: verify the DRAWN cursor in a finished mp4 against the\n// compositor's own INTENT. No vision model and no duplicated geometry — the\n// engine already knows where it meant to draw the pointer (math.buildLegs /\n// cursorPos / stageCamera give the tip in the finished frame), so the audit\n// only has to LOOK there: the cursor polygon is rasterised at that beat's\n// on-screen scale and matched by masked normalised cross-correlation in a\n// ±SEARCH_WIN_PX window around the expected tip. Field-validated: a 1% skew\n// is caught while 22/22 beats of good footage pass clean (median error\n// 0.21px, ncc ≈ 0.83).\n//\n// The pixel-independent parts (template, NCC search, tip prediction, issue\n// building) are pure and exported for tests; only auditCursor itself spawns\n// ffmpeg (one grayscale frame per beat, piped raw — no image decoder dep).\n\nimport { spawn } from \"node:child_process\";\nimport { resolveFfmpeg } from \"./ffmpeg\";\nimport { buildLegs, cursorPos, stageCamera } from \"./math\";\nimport type { Pt, TakeComposition } from \"./types\";\nimport type { CompositionIssue } from \"./validate\";\n\n/** The pointer polygon, tip at (0,0), stage units. Copied from\n * src/scene/scene.tsx (CURSOR) — the scene is compiled by revideo's vite and\n * exports nothing, so the vertex list is duplicated here ON PURPOSE: any\n * drift between the drawn cursor and the audited one shows up in review. */\nexport const CURSOR_POLYGON: readonly (readonly [number, number])[] = [\n [0, 0],\n [0, 17],\n [4.5, 13],\n [7.5, 19.5],\n [10, 18.3],\n [7, 11.7],\n [12, 11.7],\n];\n\n/** supersample factor for the template rasteriser */\nconst SS = 4;\n/** template pixels below this mask weight do not score */\nconst MASK_MIN = 0.15;\n/** search radius around the expected tip, output px */\nconst SEARCH_WIN_PX = 45;\n/** Below this the template never locked onto a cursor at all — a different\n * failure from \"matched but offset\". Measured with the Python prototype's\n * LANCZOS template: ncc 0.825 on a clean take, 0.611 at 8% skew, 0.421 at\n * 13% (the shipped-to-a-PR failure). Re-measured with THIS module's box\n * downsample on a real 10-beat draft render: all 9 pointer beats found at\n * 0.00px error, ncc 0.626–0.944 — the 0.5 floor holds for this template. */\nconst NCC_MATCH_MIN = 0.5;\n/** the scene's cursor body fill, rgb(20,20,24) ≈ 20/255 gray */\nconst BODY_GRAY = 20 / 255;\n\nconst DEFAULT_SAMPLE_AFTER_MS = 500;\nconst DEFAULT_TOL_PX = 6;\n\nexport type AuditCursorOpts = {\n /** ms after a beat's landing to sample (clamped inside the beat's hold) */\n sampleAfterMs?: number;\n /** max tolerated tip error, VIEWPORT px (default 6; good takes median 0.21) */\n tolPx?: number;\n};\n\nexport type AuditRow = {\n /** event index */\n beat: number;\n /** sample instant in the DELIVERED video (startMs head trim applied), s */\n tSec: number;\n /** expected cursor-tip position in the finished frame, output px */\n expect: Pt;\n /** best-match tip position, output px (absent when unverifiable) */\n found?: Pt;\n /** tip error in viewport px (output-px error / camera scale) */\n errViewportPx?: number;\n /** masked NCC score of the best match */\n ncc?: number;\n /** the expected tip is not in the delivered frame — unverifiable, never an error */\n offscreen?: boolean;\n};\n\nexport type GrayFrame = { data: Float32Array; width: number; height: number };\n\nexport type CursorTemplate = {\n width: number;\n height: number;\n /** grayscale sprite, 0..1 (dark body, white outline) */\n pixels: Float32Array;\n /** score only where the sprite is — the patch around it is page content */\n mask: Float32Array;\n /** local coords of the cursor TIP inside the template */\n tip: Pt;\n};\n\n/** Rasterise the cursor sprite at its on-screen scale (cursor.scale × camera\n * scale): supersampled scanline polygon fill + a distance-field outline\n * stroke, box-downsampled — matching how the scene draws it (dark body,\n * 2 stage-px white stroke) closely enough for NCC to lock on. */\nexport function makeCursorTemplate(scale: number): CursorTemplate {\n const pad = 3;\n const width = Math.ceil(12 * scale) + 6 + pad; // polygon extents 12 × 19.5\n const height = Math.ceil(19.5 * scale) + 6 + pad;\n const sW = width * SS;\n const sH = height * SS;\n const pts = CURSOR_POLYGON.map(\n ([x, y]) => [(x * scale + pad / 2) * SS, (y * scale + pad / 2) * SS] as const,\n );\n\n // even-odd scanline fill at supersample resolution\n const fill = new Float32Array(sW * sH);\n for (let y = 0; y < sH; y++) {\n const yc = y + 0.5;\n const xs: number[] = [];\n for (let i = 0; i < pts.length; i++) {\n const [x1, y1] = pts[i]!;\n const [x2, y2] = pts[(i + 1) % pts.length]!;\n if (y1 <= yc !== y2 <= yc) xs.push(x1 + ((yc - y1) * (x2 - x1)) / (y2 - y1));\n }\n xs.sort((a, b) => a - b);\n for (let k = 0; k + 1 < xs.length; k += 2) {\n const x0 = Math.max(0, Math.ceil(xs[k]! - 0.5));\n const x1 = Math.min(sW - 1, Math.floor(xs[k + 1]! - 0.5));\n for (let x = x0; x <= x1; x++) fill[y * sW + x] = 1;\n }\n }\n\n // outline stroke: the scene draws lineWidth 2 in stage units, so on screen\n // it is ~2·camScale ≈ `scale` px at the shipped cursor.scale of 2 — the\n // same approximation the field-validated prototype used.\n const half = Math.max(2, Math.round(scale * SS)) / 2;\n const strk = new Float32Array(sW * sH);\n for (let i = 0; i < pts.length; i++) {\n const [ax, ay] = pts[i]!;\n const [bx, by] = pts[(i + 1) % pts.length]!;\n const dx = bx - ax;\n const dy = by - ay;\n const len2 = dx * dx + dy * dy || 1;\n const x0 = Math.max(0, Math.floor(Math.min(ax, bx) - half - 1));\n const x1 = Math.min(sW - 1, Math.ceil(Math.max(ax, bx) + half + 1));\n const y0 = Math.max(0, Math.floor(Math.min(ay, by) - half - 1));\n const y1 = Math.min(sH - 1, Math.ceil(Math.max(ay, by) + half + 1));\n for (let y = y0; y <= y1; y++) {\n for (let x = x0; x <= x1; x++) {\n const px = x + 0.5 - ax;\n const py = y + 0.5 - ay;\n const u = Math.max(0, Math.min(1, (px * dx + py * dy) / len2));\n const ex = px - u * dx;\n const ey = py - u * dy;\n if (ex * ex + ey * ey <= half * half) strk[y * sW + x] = 1;\n }\n }\n }\n\n // box-downsample SS× to the final template\n const down = (src: Float32Array): Float32Array => {\n const out = new Float32Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n let s = 0;\n for (let sy = 0; sy < SS; sy++)\n for (let sx = 0; sx < SS; sx++) s += src[(y * SS + sy) * sW + x * SS + sx]!;\n out[y * width + x] = s / (SS * SS);\n }\n }\n return out;\n };\n const f = down(fill);\n const s = down(strk);\n const pixels = new Float32Array(width * height);\n const mask = new Float32Array(width * height);\n for (let i = 0; i < pixels.length; i++) {\n const interior = Math.min(1, Math.max(0, f[i]! - s[i]!));\n pixels[i] = interior * BODY_GRAY + s[i]!; // dark body, white outline\n mask[i] = Math.min(1, interior + s[i]!);\n }\n return { width, height, pixels, mask, tip: { x: pad / 2, y: pad / 2 } };\n}\n\n/** Masked-NCC search over a ±win px window around the expected tip. Returns\n * the best score and the tip position it was found at; `found` is absent\n * only when no template placement fits inside the frame at all. */\nexport function findCursor(\n frame: GrayFrame,\n expect: Pt,\n scale: number,\n win = SEARCH_WIN_PX,\n): { ncc: number; found?: Pt } {\n const tpl = makeCursorTemplate(scale);\n const { width: fw, height: fh, data } = frame;\n // The template vector is constant across placements: hoist the mask index\n // list (as frame-row offsets) and the zero-meaned template values.\n const offs: number[] = [];\n const b: number[] = [];\n for (let ty = 0; ty < tpl.height; ty++) {\n for (let tx = 0; tx < tpl.width; tx++) {\n const j = ty * tpl.width + tx;\n if (tpl.mask[j]! > MASK_MIN) {\n offs.push(ty * fw + tx);\n b.push(tpl.pixels[j]!);\n }\n }\n }\n const n = offs.length;\n if (n < 12) return { ncc: -1 };\n let bMean = 0;\n for (const v of b) bMean += v;\n bMean /= n;\n let db2 = 0;\n for (let j = 0; j < n; j++) {\n b[j] = b[j]! - bMean;\n db2 += b[j]! * b[j]!;\n }\n const db = Math.sqrt(db2);\n if (db < 1e-6) return { ncc: -1 };\n\n let best = -2;\n let found: Pt | undefined;\n for (let dy = -win; dy <= win; dy++) {\n for (let dx = -win; dx <= win; dx++) {\n const x0 = Math.round(expect.x + dx - tpl.tip.x);\n const y0 = Math.round(expect.y + dy - tpl.tip.y);\n if (x0 < 0 || y0 < 0 || x0 + tpl.width > fw || y0 + tpl.height > fh) continue;\n const base = y0 * fw + x0;\n // Σb = 0, so cov = Σab and var(a) = Σa² − (Σa)²/n — one pass per patch.\n let sa = 0;\n let saa = 0;\n let sab = 0;\n for (let j = 0; j < n; j++) {\n const a = data[base + offs[j]!]!;\n sa += a;\n saa += a * a;\n sab += a * b[j]!;\n }\n const da = Math.sqrt(Math.max(0, saa - (sa * sa) / n));\n const score = da < 1e-6 ? -1 : sab / (da * db);\n if (score > best) {\n best = score;\n found = { x: expect.x + dx, y: expect.y + dy };\n }\n }\n }\n return { ncc: best, found };\n}\n\nexport type PredictedTip = {\n /** event index */\n beat: number;\n /** sample instant on the composition (capture) timeline, ms */\n sampleMs: number;\n /** the same instant in the DELIVERED video (startMs head trim applied), s */\n tSec: number;\n /** expected cursor-tip position in the finished frame, output px */\n expect: Pt;\n /** camera scale at the sample instant (output px per video px) */\n camScale: number;\n /** the tip is not in the delivered frame (zoomed out of frame, or the head\n * trim cut the sample) — unverifiable, never an error */\n offscreen: boolean;\n};\n\n/** Where the compositor MEANT to draw the pointer tip, per pointer-landing\n * beat, in finished-frame px — via the engine's own public math, so there is\n * no second geometry to drift. */\nexport function predictCursorTips(\n comp: TakeComposition,\n sampleAfterMs = DEFAULT_SAMPLE_AFTER_MS,\n): PredictedTip[] {\n const legs = buildLegs(comp);\n const cam = stageCamera(comp);\n const { width: oW, height: oH, fps } = comp.output;\n const startMs = comp.startMs ?? 0;\n const frameMs = 1000 / fps;\n const out: PredictedTip[] = [];\n for (const [beat, e] of comp.events.entries()) {\n if (!e.point) continue; // hand-edited JSON can drop it; nothing to verify then\n if (e.kind === \"press\" && !e.bbox) continue; // bare press: cursor parked, no target\n // Sample inside the beat's HOLD: after the landing (the ripple has fired,\n // the camera settle is all but done) but before the cursor departs again —\n // the next travel leg, or this beat's own drag stroke. Legs are t0-ordered,\n // so the first departure past tMs is the binding one.\n let sampleMs = e.tMs + sampleAfterMs;\n for (const l of legs) {\n const departMs = l.t0 * 1000;\n // strict >: a rushed succession clamps the next leg's t0 to EXACTLY this\n // landing (math.ts buildLegs), and that departure is still binding — a\n // \"+1\" grace would sample mid-flight on the skipped leg, converting\n // cursor speed into ~17px of false position error at 60fps.\n if (departMs > e.tMs) {\n sampleMs = Math.min(sampleMs, departMs - frameMs);\n break;\n }\n }\n sampleMs = Math.max(Math.min(sampleMs, comp.durationMs - frameMs), e.tMs);\n const tS = sampleMs / 1000;\n const c = cursorPos(tS, legs, comp); // video px\n const k = cam.at(tS);\n // scene geometry: a video-px point lands at (p − camera center)·scale + out/2\n const expect: Pt = {\n x: (c.x - k.center.x) * k.scale + oW / 2,\n y: (c.y - k.center.y) * k.scale + oH / 2,\n };\n const tSec = (sampleMs - startMs) / 1000;\n const offscreen = tSec < 0 || expect.x < 0 || expect.x >= oW || expect.y < 0 || expect.y >= oH;\n out.push({ beat, sampleMs, tSec, expect, camScale: k.scale, offscreen });\n }\n return out;\n}\n\nconst median = (xs: number[]): number => {\n const s = xs.slice().sort((a, b) => a - b);\n const m = s.length >> 1;\n return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;\n};\n\nconst signed = (v: number): string => `${v >= 0 ? \"+\" : \"\"}${v.toFixed(1)}`;\n\n/** Turn measured rows into issues (pure — unit-testable without a video). */\nexport function auditIssues(rows: AuditRow[], tolPx = DEFAULT_TOL_PX): CompositionIssue[] {\n const issues: CompositionIssue[] = [];\n const offscreen = rows.filter((r) => r.offscreen);\n if (offscreen.length) {\n const names = offscreen\n .map((r) => `events[${r.beat}] (tip at ${r.expect.x.toFixed(0)},${r.expect.y.toFixed(0)})`)\n .join(\", \");\n issues.push({\n severity: \"warn\",\n path: \"events\",\n message: `${offscreen.length} beat${offscreen.length === 1 ? \"\" : \"s\"} cannot be audited — the zoom pushed the expected cursor tip out of the output frame: ${names}`,\n fix: \"check those beats by eye; to make them auditable, pull zoom.center toward the pointer or lower zoom.scale so the pointer stays in frame\",\n });\n }\n const checked = rows.filter((r) => !r.offscreen && r.ncc != null && r.found);\n const unmatched = checked.filter((r) => (r.ncc ?? -1) < NCC_MATCH_MIN);\n const offsetFails = checked.filter(\n (r) => (r.ncc ?? -1) >= NCC_MATCH_MIN && (r.errViewportPx ?? 0) > tolPx,\n );\n if (!unmatched.length && !offsetFails.length) return issues;\n const parts = [\n ...offsetFails.map(\n (r) =>\n `events[${r.beat}] drawn ${r.errViewportPx!.toFixed(1)}px off (ncc ${r.ncc!.toFixed(2)} — the cursor matched, at the wrong place)`,\n ),\n ...unmatched.map(\n (r) =>\n `events[${r.beat}] never matched (best ncc ${r.ncc!.toFixed(2)} < ${NCC_MATCH_MIN} — no cursor found near the expected tip, so its offset means nothing)`,\n ),\n ];\n // A shared offset across the failing beats is the classic failure (the\n // every-cursor-13%-off release): a renderer↔math transform skew, not\n // per-beat noise — say so, with the measured vector.\n let fix =\n \"re-render and re-audit; a repeat means the renderer disagrees with math.cursorPos/stageCamera — the fix is in the renderer, no composition edit moves the drawn cursor\";\n if (offsetFails.length >= 2) {\n const vecs = offsetFails.map((r) => {\n const dx = r.found!.x - r.expect.x;\n const dy = r.found!.y - r.expect.y;\n const errOut = Math.hypot(dx, dy);\n const k = errOut > 0 ? (r.errViewportPx ?? 0) / errOut : 0; // output px → viewport px\n return { x: dx * k, y: dy * k };\n });\n const mx = median(vecs.map((v) => v.x));\n const my = median(vecs.map((v) => v.y));\n const spread = Math.max(...vecs.map((v) => Math.hypot(v.x - mx, v.y - my)));\n if (spread <= 2)\n fix = `every failing beat shares one offset ≈ (${signed(mx)}, ${signed(my)}) viewport px — a systematic renderer↔math skew; fix the cursor transform in the renderer and re-render (no composition edit moves the drawn cursor)`;\n }\n issues.push({\n severity: \"error\",\n path: \"events\",\n message: `the drawn cursor misses the composition's own intent on ${offsetFails.length + unmatched.length} of ${checked.length} verifiable beats (tolerance ${tolPx}px): ${parts.join(\"; \")}`,\n fix,\n });\n return issues;\n}\n\n/** Decode ONE frame of the delivered mp4 at tSec to raw grayscale pixels,\n * piped straight from ffmpeg — no image-decoding dependency. */\nfunction extractGrayFrame(\n ffmpeg: string,\n mp4Path: string,\n tSec: number,\n width: number,\n height: number,\n): Promise<GrayFrame> {\n return new Promise((res, rej) => {\n const child = spawn(\n ffmpeg,\n [\n \"-hide_banner\",\n \"-v\",\n \"error\",\n \"-ss\",\n tSec.toFixed(4),\n \"-i\",\n mp4Path,\n \"-frames:v\",\n \"1\",\n \"-f\",\n \"rawvideo\",\n \"-pix_fmt\",\n \"gray\",\n \"pipe:1\",\n ],\n { stdio: [\"ignore\", \"pipe\", \"pipe\"] },\n );\n const chunks: Buffer[] = [];\n let errText = \"\";\n child.stdout.on(\"data\", (d: Buffer) => chunks.push(d));\n child.stderr.on(\"data\", (d) => {\n errText += d;\n });\n child.on(\"error\", rej);\n child.on(\"close\", (code) => {\n const bytes = Buffer.concat(chunks);\n const need = width * height;\n if (code !== 0)\n return rej(\n new Error(\n `ffmpeg exited ${code} extracting the ${tSec.toFixed(2)}s frame from ${mp4Path}${errText.trim() ? `: ${errText.trim()}` : \"\"}`,\n ),\n );\n // EXACTLY one gray frame: a longer payload means the mp4's true\n // dimensions exceed the composition's — reinterpreting its first\n // oW·oH bytes with the wrong row stride would garble the image and\n // turn every beat into a false \"never matched\" renderer defect.\n if (bytes.length !== need)\n return rej(\n new Error(\n `ffmpeg returned ${bytes.length} bytes for the ${tSec.toFixed(2)}s frame — expected one ${width}x${height} gray frame (${need} bytes); is ${mp4Path} the delivered render of this composition?`,\n ),\n );\n const data = new Float32Array(need);\n for (let i = 0; i < need; i++) data[i] = bytes[i]! / 255;\n res({ data, width, height });\n });\n });\n}\n\n/** Audit the drawn cursor of a delivered mp4 against the composition that\n * rendered it. One row per pointer-landing beat; issues in the\n * validateComposition shape (\"error\" = the render is wrong, \"warn\" = a beat\n * the audit cannot see). */\nexport async function auditCursor(\n comp: TakeComposition,\n mp4Path: string,\n opts: AuditCursorOpts = {},\n): Promise<{ rows: AuditRow[]; issues: CompositionIssue[] }> {\n const tolPx = opts.tolPx ?? DEFAULT_TOL_PX;\n const preds = predictCursorTips(comp, opts.sampleAfterMs ?? DEFAULT_SAMPLE_AFTER_MS);\n if (!preds.length)\n // an empty verdict must not read as \"audit clean\" — nothing was opened,\n // nothing was verified\n return {\n rows: [],\n issues: [\n {\n severity: \"warn\",\n path: \"events\",\n message:\n \"no pointer-landing beats to audit — the drawn cursor was never verified on this take\",\n },\n ],\n };\n const ffmpeg = await resolveFfmpeg();\n const { width: oW, height: oH } = comp.output;\n const rows: AuditRow[] = [];\n for (const p of preds) {\n if (p.offscreen) {\n rows.push({ beat: p.beat, tSec: p.tSec, expect: p.expect, offscreen: true });\n continue;\n }\n const frame = await extractGrayFrame(ffmpeg, mp4Path, p.tSec, oW, oH);\n const { ncc, found } = findCursor(frame, p.expect, comp.cursor.scale * p.camScale);\n if (!found) {\n // every placement in the search window fell off the frame edge — as\n // unverifiable as an offscreen tip, and reported with them\n rows.push({ beat: p.beat, tSec: p.tSec, expect: p.expect, offscreen: true });\n continue;\n }\n const errOutPx = Math.hypot(found.x - p.expect.x, found.y - p.expect.y);\n rows.push({\n beat: p.beat,\n tSec: p.tSec,\n expect: p.expect,\n found,\n errViewportPx: errOutPx / p.camScale,\n ncc,\n });\n }\n return { rows, issues: auditIssues(rows, tolPx) };\n}\n","// camera.ts — the auto-camera DIRECTOR.\n//\n// Zoom is DECIDED here, deterministically, from the ground-truth event log — NOT\n// by the authoring agent (which decides pre-capture, blind, and every model has\n// its own bias), and NOT per-event in isolation. The director runs over the\n// WHOLE beat sequence so it can do the three things a per-event heuristic can't:\n//\n// 1. shape the region-of-interest PER KIND — a `type`'s payoff grows DOWN out\n// of the thin field, so the ROI (and thus the scale) is result-sized, not\n// strip-sized;\n// 2. COALESCE a burst of nearby small interactions into ONE sustained frame\n// (a thumbnail rail / toolbar), instead of punch-pull flicker per beat;\n// 3. PULL OUT for a global repaint (nav / restyle) — read off the capture's\n// changed-area, not guessed from a bbox that looks identical to a popover's.\n//\n// Output stays in the editable representation: one framing decision per beat\n// (enabled / scale / center + a human-readable reason). A \"cluster\" is just\n// every beat in it sharing the SAME scale+center — buildStageKeyframes then\n// holds the camera across them for free (no new schema, no new keyframe code).\n//\n// Pure & synchronous: it reads only fields already on the beats, including the\n// capture-derived effectBox / changeCoverage seam. The frame-diff (or, later,\n// mutation) pass that POPULATES those fields lives in the runtime (node) layer;\n// the director itself never does I/O, so it stays snapshot-testable.\n\nimport { bboxFitScale } from \"./math\";\nimport type { BBox, CameraConfig, Pt, ZoomIntent } from \"./types\";\n\n/** One action, already mapped into video-px, handed to the director. */\nexport type Beat = {\n kind: \"click\" | \"type\" | \"drag\" | \"scroll\" | \"hover\" | \"look\" | \"press\" | \"dropFiles\";\n tMs: number;\n durationMs: number;\n /** element bbox (for a drag: the path's bbox), video-px — or undefined for a\n * bare press (no located element). */\n box?: BBox;\n /** the region that actually changed after the action (frame-diff seam),\n * video-px. Framed over `box` when present. */\n effectBox?: BBox;\n /** fraction of the frame that changed after the action, 0..1. */\n changeCoverage?: number;\n /** anchor / cursor rest point, video-px (for the reason only). */\n point: Pt;\n /** plan override; absent ⇒ \"auto\" (the director decides). */\n intent: ZoomIntent;\n /** short label (sel / note) for the cluster tag in the reason. */\n label?: string;\n /** press only: the key chord (for the Escape-dismissal rule). */\n keys?: string;\n};\n\n/** The director's per-beat verdict. plan.ts adds `inAtMs` to make a full\n * ZoomDecision. */\nexport type Framing = {\n enabled: boolean;\n scale: number;\n center: Pt;\n reason: string;\n};\n\nconst centerOf = (b: BBox): Pt => ({ x: b.x + b.w / 2, y: b.y + b.h / 2 });\nconst dist = (a: Pt, b: Pt): number => Math.hypot(a.x - b.x, a.y - b.y);\nconst union = (a: BBox, b: BBox): BBox => {\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n return { x, y, w: Math.max(a.x + a.w, b.x + b.w) - x, h: Math.max(a.y + a.h, b.y + b.h) - y };\n};\n\n// A `type` field is a thin strip; its payoff (search results, an AI answer)\n// grows DOWNWARD out of it. Framing the strip alone puts dead header above and\n// crops the result below. Grow the ROI down (never up) so the frame sits over\n// field + result: a taller ROI ⇒ lower scale AND a centre that drops below the\n// field — both correct. For a type this also CAPS the effectBox height: a\n// search/filter result list is open-ended, so the raw frame-diff region can\n// span the whole viewport and flatten the punch to ~1× — growDown bounds how far\n// down the frame reaches while the effectBox still supplies the real reveal width.\nfunction growDown(box: BBox, video: { w: number; h: number }): BBox {\n const grownH = Math.max(box.h, Math.min(video.h * 0.42, box.w * 0.55));\n const h = Math.min(grownH, video.h - box.y); // never spill past the video edge\n return { x: box.x, y: box.y, w: box.w, h };\n}\n\n/** The region a beat is \"about\" — what the camera should frame. A type is\n * field-anchored and height-capped (its reveal is open-ended); every other\n * kind trusts the captured effect region, else shapes one from the bbox. */\nfunction roiForBeat(b: Beat, video: { w: number; h: number }): BBox | undefined {\n // A press with an EXPLICIT zoom=always + a located reveal element: the\n // author named exactly what to frame — that box outranks the frame-diff\n // effectBox. A press payoff behind a scrim (modal / command palette) diffs\n // as a full-frame repaint, which would flatten the punch to ~1× (issue #3);\n // and a tiny incidental effectBox (a save indicator) would yank the frame\n // somewhere else entirely (issue #8). click/hover keep effectBox preference:\n // there the payoff usually lands AWAY from the element, which is the whole\n // point of the frame-diff seam.\n if (b.kind === \"press\" && b.intent === \"always\" && b.box) return b.box;\n // A look names exactly what to frame — that IS the beat. Nothing happened on\n // the page, so any effectBox is neighbouring noise (an animation, a ticking\n // number), and preferring it would aim the \"show the viewer this\" camera at\n // something else entirely.\n if (b.kind === \"look\" && b.box) return b.box;\n if (b.kind === \"type\" && b.box) {\n // Bound the frame to \"field + top of results\": keep the effectBox's real\n // reveal WIDTH, but cap the HEIGHT to growDown's result-sized window so an\n // open-ended result list can't flatten the punch to ~1× (see growDown).\n const capH = growDown(b.box, video).h;\n if (b.effectBox) {\n const x = Math.min(b.box.x, b.effectBox.x);\n const right = Math.max(b.box.x + b.box.w, b.effectBox.x + b.effectBox.w);\n const bottom = b.effectBox.y + b.effectBox.h;\n // Floor at the field height so a reveal that lands at/above the field top\n // (a rare upward-opening autocomplete) can't yield a zero/negative ROI —\n // we then simply frame the field, never punch into the vacated space above.\n const h = Math.max(b.box.h, Math.min(capH, bottom - b.box.y));\n return { x, y: b.box.y, w: right - x, h };\n }\n return growDown(b.box, video);\n }\n if (b.effectBox) return b.effectBox;\n if (!b.box) return undefined;\n return b.box;\n}\n\nfunction clusterLabel(beats: Beat[], idx: number[]): string {\n const raw = beats[idx[0]!]?.label ?? \"\";\n const cleaned = raw.replace(/\\s+/g, \" \").trim().slice(0, 18);\n return cleaned || \"region\";\n}\n\ntype Node = {\n roi?: BBox;\n scale: number; // fit of its OWN roi (rest if none)\n forceFull: boolean; // must show full view (scroll / never / global repaint / no-roi / orienting)\n forcePunch: boolean; // its own isolated punch (intent === \"always\")\n boundary: boolean; // starts a new segment regardless of similarity\n reason: string;\n};\n\ntype Seg = {\n idx: number[];\n kind: \"rest\" | \"punch\";\n roi?: BBox;\n scale: number;\n center: Pt;\n dropped?: boolean; // a punch demoted to rest by min-hold\n};\n\n/**\n * Decide framing for every beat. `endMs` is when the last frame can hold until\n * (for the min-hold check on the final segment). `rest` is the stage scale at\n * full view.\n */\nexport function directCamera(\n beats: Beat[],\n video: { w: number; h: number },\n out: { w: number; h: number },\n cam: CameraConfig,\n rest: number,\n endMs: number,\n): Framing[] {\n const restC: Pt = { x: video.w / 2, y: video.h / 2 };\n const fit = (roi: BBox) => bboxFitScale(roi, out.w, out.h, cam.fillFrac, cam.maxScale, rest);\n\n // --- phase 1: per-beat ROI + hard-break classification ---------------------\n const nodes: Node[] = beats.map((b, i) => {\n const roi = roiForBeat(b, video);\n const scale = roi ? fit(roi) : rest;\n const gapBreak =\n i > 0 && b.tMs - (beats[i - 1]!.tMs + beats[i - 1]!.durationMs) > cam.coalesceWindowMs;\n\n // explicit overrides win, and are segment boundaries (Q2 / point 3).\n if (b.intent === \"never\")\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"plan: zoom=never → full view\",\n };\n if (b.intent === \"always\") {\n // An explicit \"always\" must never ship a no-op: a wide ROI can fit-scale\n // into the imperceptible band (rest…~1.1×) and render an enabled zoom\n // the eye can't see (issue #1). Floor at minZoomScale — the author asked\n // for a punch, so give the smallest one that reads as one.\n const floored = roi ? Math.max(scale, cam.minZoomScale) : scale;\n return {\n roi,\n scale: floored,\n forceFull: false,\n forcePunch: true,\n boundary: true,\n reason: roi\n ? floored > scale\n ? `plan: zoom=always → ROI fit ${scale.toFixed(2)}× is imperceptible — floored to ${floored.toFixed(2)}× (fits ≠ legible: raise zoom.scale if the payoff is fine text)`\n : `plan: zoom=always → ${floored.toFixed(2)}× (framing from ROI)`\n : \"plan: zoom=always but no bbox to frame → full view\",\n };\n }\n\n // a scroll is a pan beat: content moves, the frame stays full-view.\n if (b.kind === \"scroll\")\n return {\n roi: undefined,\n scale: rest,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"scroll — full view (content pans)\",\n };\n\n // Escape DISMISSES: its visual change is something VANISHING, so the\n // frame-diff effectBox is the vacated region — framing it would punch into\n // blank space. The editorial payoff of a dismissal is the restored page.\n if (b.kind === \"press\" && b.keys && /(^|\\+)esc(ape)?$/i.test(b.keys.trim()))\n return {\n roi: undefined,\n scale: rest,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"Escape (dismissal) — full view\",\n };\n\n // global repaint (nav / restyle): the payoff is the whole page → pull out.\n // Needs the frame-diff annotation; without it this branch is skipped (the\n // director can't tell nav from popover on a bbox alone — say so).\n if (b.changeCoverage != null && b.changeCoverage >= cam.pullOutCoverage)\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: `changeCoverage ${b.changeCoverage.toFixed(2)} ≥ ${cam.pullOutCoverage} (global repaint) → full view`,\n };\n\n // the opening beat orients: open on the whole app (Q3 — falls out of \"the\n // camera opens full\", no zoomFirst flag). A cold-open uses zoom=always.\n // Only when the beat actually opens the video, though: a first action ≥2s\n // in (a leading `wait`, a slow warmup) already gave the viewer the full\n // view — forcing it wide again just robs the hero moment (issue #2; the\n // default warmup alone puts an immediate first action at ~1s).\n if (i === 0 && b.tMs < 2000)\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"opening beat — full view (orienting)\",\n };\n\n // nothing locatable to frame (a bare Escape/Enter with no reveal).\n if (!roi)\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: true,\n reason: \"no bbox to frame → full view\",\n };\n\n // not tight enough to earn a distinct frame (a big element fills it already).\n if (scale < cam.minZoomScale)\n return {\n roi,\n scale,\n forceFull: true,\n forcePunch: false,\n boundary: gapBreak,\n reason: `ROI fills the frame already (fit ${scale.toFixed(2)}× < ${cam.minZoomScale}×) — full view`,\n };\n\n // an ordinary punchable beat — eligible to coalesce with its neighbours.\n return {\n roi,\n scale,\n forceFull: false,\n forcePunch: false,\n boundary: gapBreak,\n reason: `punch ${scale.toFixed(2)}× (ROI-fit)`,\n };\n });\n\n // --- phase 2: coalesce adjacent punchable beats into shared-frame clusters --\n const segs: Seg[] = [];\n for (let i = 0; i < nodes.length; i++) {\n const n = nodes[i]!;\n if (n.forceFull) {\n segs.push({ idx: [i], kind: \"rest\", scale: rest, center: restC });\n continue;\n }\n const last = segs[segs.length - 1];\n const lastLastIdx = last ? last.idx[last.idx.length - 1]! : -1;\n const canExtend =\n !!last &&\n last.kind === \"punch\" &&\n !!last.roi &&\n !n.forcePunch &&\n !nodes[lastLastIdx]!.forcePunch &&\n !n.boundary &&\n !!n.roi &&\n dist(centerOf(n.roi), centerOf(last.roi)) < cam.travelThreshold * video.w &&\n fit(union(last.roi, n.roi)) >= cam.minZoomScale; // union must stay tight enough\n\n if (canExtend && last?.roi && n.roi) {\n const roi = union(last.roi, n.roi);\n last.idx.push(i);\n last.roi = roi;\n last.scale = fit(roi);\n last.center = centerOf(roi);\n } else {\n segs.push({\n idx: [i],\n kind: \"punch\",\n roi: n.roi,\n scale: n.scale,\n center: n.roi ? centerOf(n.roi) : restC,\n });\n }\n }\n\n // --- phase 3: min-hold — extend into the gap before the next break; a punch\n // that still can't clear minHoldMs is a flinch → drop it to full view. NEVER\n // merges across a break (order: hard break → coalesce → min-hold).\n segs.forEach((s, si) => {\n if (s.kind !== \"punch\") return;\n // A look segment is exempt: its hold length is the AUTHOR'S statement\n // (\"show the viewer this for durationMs\"), not a derived gap — demoting it\n // to full view would delete the beat's entire content. A tight look reads\n // brisk, not flinchy, because nothing else competes for the frame.\n if (s.idx.some((i) => beats[i]!.kind === \"look\")) return;\n const firstT = beats[s.idx[0]!]!.tMs;\n const next = segs[si + 1];\n const heldUntil = next ? beats[next.idx[0]!]!.tMs : endMs;\n if (heldUntil - firstT < cam.minHoldMs) {\n s.kind = \"rest\";\n s.scale = rest;\n s.center = restC;\n s.dropped = true;\n }\n });\n\n // --- assemble per-beat framing --------------------------------------------\n const framings: Framing[] = new Array(beats.length);\n for (const s of segs) {\n if (s.kind === \"rest\") {\n for (const i of s.idx)\n framings[i] = {\n enabled: false,\n scale: rest,\n center: restC,\n reason: s.dropped\n ? `punch dropped — held < ${cam.minHoldMs}ms (would flinch) → full view`\n : nodes[i]!.reason,\n };\n continue;\n }\n const N = s.idx.length;\n const tag = N > 1 ? `cluster[${clusterLabel(beats, s.idx)}]` : null;\n s.idx.forEach((i, k) => {\n framings[i] = {\n enabled: true,\n scale: s.scale,\n center: s.center,\n reason: tag\n ? `${tag} ${k + 1}/${N} · hold shared framing (union of ${N}) → ${s.scale.toFixed(2)}×`\n : nodes[i]!.reason,\n };\n });\n }\n return framings;\n}\n","// The editable take composition — the source of truth. The agent (or a\n// human) edits THIS, and the revideo scene renders it deterministically.\n// All spatial fields are in VIDEO-pixel space (capture coords mapped\n// through viewport→video scaling), so the scene works in one coordinate\n// system.\n\nexport type Pt = { x: number; y: number };\nexport type BBox = { x: number; y: number; w: number; h: number };\n\n// --- capture input (the ground-truth event log) -----------------------\n\n/** Editorial zoom intent for an action (set by the planner/agent). */\nexport type ZoomIntent = \"auto\" | \"never\" | \"always\";\n\n/** Fields common to every captured action. `x,y` is the anchor / start\n * point (cursor target), viewport CSS px. */\nexport type CaptureEventBase = {\n /** anchor point (click target / field / drag start), viewport CSS px */\n x: number;\n y: number;\n /** element bounding box, viewport CSS px — the ground-truth edge */\n box?: BBox;\n /** ms from recording start (when the cursor arrives / action begins) */\n tMs: number;\n /** selector / note, kept for editability */\n sel?: string;\n note?: string;\n /** One-line viewer-facing caption from the plan step (\"Applying the\n * filter re-prices every row\"). planComposition turns these into `captions`\n * windows — the beat explains itself to a viewer who has never seen the\n * app, which footage alone cannot do. */\n caption?: string;\n /** selective-zoom intent from the plan. Absent/\"auto\" ⇒ the camera director\n * decides from the ground-truth log; \"always\"/\"never\" hard-override it (and\n * cut the beat out of any cluster — an override is a segment boundary). */\n zoom?: ZoomIntent;\n /** CAPTURE-DERIVED (frame-diff / mutation pass — the `effectBox` seam): the\n * region that actually CHANGED after the action, viewport CSS px. The\n * director frames THIS over `box` when present — a `type`'s result region, or\n * a payoff that lands somewhere other than where you clicked. Absent ⇒ the\n * director shapes an ROI from `box`/kind instead. */\n effectBox?: BBox;\n /** CAPTURE-DERIVED (same pass): fraction of the frame that changed after the\n * action, 0..1. ≥ camera.pullOutCoverage ⇒ the action repainted most of the\n * frame (nav / global restyle) ⇒ pull out to full view. Absent ⇒ the pull-out\n * branch is skipped (the director can't tell nav from popover on bbox alone —\n * it says so in the beat's `reason`). */\n changeCoverage?: number;\n};\n\n/** A click (or a type's focus-click): an instantaneous action at a point. */\nexport type CaptureClick = CaptureEventBase & { kind?: \"click\" };\n\n/** Typing into a focused field: the cursor parks and the zoom holds for\n * `durationMs` while the text appears in the recording. */\nexport type CaptureType = CaptureEventBase & {\n kind: \"type\";\n /** what was typed (editability) */\n text: string;\n /** ms the typing occupies on screen (ground-truth wall time) */\n durationMs: number;\n};\n\n/** A drag: a path from the anchor (`x,y`) to `to`, optionally via `path`,\n * with the button held for `durationMs`. */\nexport type CaptureDrag = CaptureEventBase & {\n kind: \"drag\";\n /** drag end point, viewport CSS px */\n to: { x: number; y: number };\n /** full polyline incl. ends, viewport CSS px (freehand strokes) */\n path?: { x: number; y: number }[];\n /** ms the drag occupies on screen (ground-truth wall time) */\n durationMs: number;\n /** how the stroke was paced and BAKED into the ink: \"smooth\" (accel-in /\n * decel-out — a natural hand-draw) or \"linear\" (constant speed). The\n * compositor cursor must replay the SAME easing to stay locked to the ink.\n * Absent ⇒ linear (legacy captures). */\n ease?: \"linear\" | \"smooth\";\n};\n\n/** A scroll: the content pans for `durationMs`. The cursor holds (no travel),\n * full-view (no zoom). `dy` is the signed pixels scrolled (editability). */\nexport type CaptureScroll = CaptureEventBase & {\n kind: \"scroll\";\n /** signed pixels scrolled (positive = down) */\n dy: number;\n /** ms the scroll occupies on screen (ground-truth wall time) */\n durationMs: number;\n};\n\n/** A hover: the cursor travels to `x,y` and dwells for `durationMs` so a\n * tooltip / menu / hover-state reveals. Like a click that doesn't click. */\nexport type CaptureHover = CaptureEventBase & {\n kind: \"hover\";\n /** ms the dwell occupies on screen (ground-truth wall time) */\n durationMs: number;\n};\n\n/** A look: a CAMERA-only beat. Nothing is done to the page and the cursor\n * does not move — the camera frames the target element and holds for\n * `durationMs`. This is the honest spelling of \"show the viewer this\n * region\": before it existed, the only way to aim the camera was to hover\n * a control you never meant to activate, which reads on screen as a\n * promise (\"about to click\") the video then breaks. `x,y` is the target's\n * center (zoom anchor); the cursor rests at its previous anchor. */\nexport type CaptureLook = CaptureEventBase & {\n kind: \"look\";\n /** ms the framed hold occupies on screen */\n durationMs: number;\n};\n\n/** A key press / shortcut: keyboard-driven, so the cursor holds (no travel).\n * Holds for `durationMs` while the effect plays out; if a reveal element was\n * located, `box` carries its bbox so the zoom can frame it. */\nexport type CapturePress = CaptureEventBase & {\n kind: \"press\";\n /** the chord pressed, e.g. \"Enter\" / \"Meta+k\" (editability) */\n keys: string;\n /** ms the hold occupies on screen (ground-truth wall time) */\n durationMs: number;\n};\n\n/** A file drag-and-drop (OS-level, synthesized via CDP Input.dispatchDragEvent\n * with real file paths): the cursor carries the file(s) from the anchor\n * (`x,y`) along `path` to `to`, where the drop lands and the page receives\n * actual Files. The compositor draws a \"file ghost card\" riding the cursor\n * for this beat — the recording itself shows only the page's reaction. */\nexport type CaptureDropFiles = CaptureEventBase & {\n kind: \"dropFiles\";\n /** drop point, viewport CSS px */\n to: { x: number; y: number };\n /** full polyline incl. ends, viewport CSS px */\n path?: { x: number; y: number }[];\n /** ms the carry occupies on screen (ground-truth wall time) */\n durationMs: number;\n /** carry pacing baked into the dispatched dragOver march (see CaptureDrag) */\n ease?: \"linear\" | \"smooth\";\n /** dropped files' display metadata (basename + bytes) for the ghost card */\n files: { name: string; size?: number }[];\n};\n\nexport type CaptureEvent =\n | CaptureClick\n | CaptureType\n | CaptureDrag\n | CaptureScroll\n | CaptureHover\n | CaptureLook\n | CapturePress\n | CaptureDropFiles;\n\nexport type CaptureLog = {\n video: { width: number; height: number; fps?: number | string; durationS?: number };\n viewport: { w: number; h: number };\n /** the app this take was shot from (the plan's url). Written by makeTake into\n * the KEPT log; the composition never reads it. It exists so a take can say\n * which app it is of — `make` refuses to overwrite a take of a different\n * app, which is what stops a second demo in the same folder from destroying\n * the first. Absent on takes made before it was recorded. */\n url?: string;\n start?: { x: number; y: number };\n /** the ordered ground-truth actions (click / type / drag) */\n events: CaptureEvent[];\n tEndMs?: number;\n /** Steps the capture DROPPED (target not found / endpoint unresolved) — the\n * take still completes, but a missing beat must reach the end-of-run\n * summary and (strict by default) the exit code, not just an early stderr line\n * buried under render progress. `step` is the plan's 0-based step index. */\n skipped?: { step: number; action: string; target?: string; reason: string }[];\n /** Pre-capture target-resolution findings (runtime/src/precheck.ts): every\n * plan target resolved against the page as loaded, with the capture's own\n * locator semantics, BEFORE the screencast started. Errors abort the\n * capture, so only warnings ever reach a written log — kept here so a take\n * on disk records what the gate already said about its plan. */\n precheck?: { severity: \"error\" | \"warn\"; path: string; message: string; fix?: string }[];\n /** Beats whose editorial hold ran out before the PAGE had finished — the\n * capture kept waiting (see runtime/src/settle.ts) and records how much\n * longer it needed. This is the measurement that replaces guessing\n * `settleMs`: `heldMs + waitedMs` is what that beat actually wanted, and\n * `reason: \"budget\"` means even the extra wait was not enough. Absent when\n * every hold was already long enough. */\n settleWaits?: {\n step: number;\n action: string;\n heldMs: number;\n waitedMs: number;\n reason: \"idle\" | \"budget\" | \"unavailable\";\n }[];\n /** Largest share of the frame a `<canvas>`/`<video>` held during the capture.\n * It matters because the settle probe reads the page's STRUCTURE, and a\n * paint surface never changes structurally no matter what is drawn inside\n * it — so on a canvas-driven app \"the page settled\" is not evidence the\n * beat's payoff had appeared, and `settleMs` is doing the whole job alone.\n * Absent on an ordinary DOM app. */\n paintedFrac?: number;\n};\n\n// --- the composition (editable) ----------------------------------------\n\nexport type ZoomDecision = {\n /** selective: not every action zooms. Edit this to tune/remove. */\n enabled: boolean;\n /** absolute stage scale to reach (bbox-fit, capped) */\n scale: number;\n /** video-px point to frame (bbox center), pre-clamp */\n center: Pt;\n /** when the zoom-in begins (ms) */\n inAtMs: number;\n /** Optional \"glide\": a slow camera drift WHILE the zoom is held, as a velocity\n * in video-px per second {x,y}. The held centre pans from `center` by\n * `glide · holdSeconds` across the hold window (then the next beat ramps from\n * there / it zooms out from there). Adds life vs a dead-static hold (Screen\n * Studio's glide). Absent/0 ⇒ a still hold. Clamped to the video at read time,\n * so a drift just stops at the edge. Keep it gentle (tens of px/s). */\n glide?: Pt;\n /** why this decision (for the human/agent reading the composition) */\n reason: string;\n};\n\n/** Ghost-card knobs for a dropFiles beat (editable): the macOS-style file\n * card riding the cursor during the carry. */\nexport type GhostCardConfig = {\n enabled: boolean;\n /** card offset from the cursor tip, video-px (default ~{x:26,y:30}) */\n offset?: Pt;\n /** ms of the release pop after the drop (fade + settle; default 280) */\n releaseMs?: number;\n};\n\nexport type CompEvent = {\n kind: \"click\" | \"type\" | \"drag\" | \"scroll\" | \"hover\" | \"look\" | \"press\" | \"dropFiles\";\n tMs: number;\n /** anchor point (click / focus / drag start / hover) in video-px. For a\n * scroll/press the cursor does not move; this is its resting point. */\n point: Pt;\n /** element bbox in video-px (if known) */\n bbox?: BBox;\n label?: string;\n zoom: ZoomDecision;\n /** how long the action plays out after `tMs` (type/drag/scroll/hover/press);\n * 0 for a click. The cursor parks and the zoom holds for this long. */\n durationMs?: number;\n /** typed text (kind=type), for editability */\n text?: string;\n /** chord pressed (kind=press), for editability */\n keys?: string;\n /** drag end point, video-px (kind=drag) */\n to?: Pt;\n /** drag polyline incl. ends, video-px (kind=drag) — the cursor path */\n path?: Pt[];\n /** drag stroke easing baked into the ink (kind=drag): \"smooth\" or \"linear\".\n * The cursor replays it so it stays locked to the ink. Absent ⇒ linear. */\n ease?: \"linear\" | \"smooth\";\n /** dropped files' display metadata (kind=dropFiles), for the ghost card */\n files?: { name: string; size?: number }[];\n /** ghost-card rendering knobs (kind=dropFiles); absent ⇒ enabled defaults */\n ghostCard?: GhostCardConfig;\n};\n\nexport type FramingConfig = {\n /** video occupies this fraction of the frame at rest (inset for the backdrop) */\n insetFrac: number;\n cornerRadius: number;\n shadow: { color: string; blur: number; offset: Pt };\n /** backdrop behind the framed video. `type` defaults to \"gradient\" (from→to);\n * \"solid\" fills `from` only. `angle` (deg, CSS-like: 0 = upward) rotates the\n * gradient; absent ⇒ the legacy top-left→bottom-right diagonal (pixel-identical). */\n background: { from: string; to: string; type?: \"gradient\" | \"solid\"; angle?: number };\n};\n\nexport type CursorConfig = {\n /** Fallback travel duration (ms) when `travelWidthsPerSec` is unset/0. A FIXED\n * duration makes cursor speed scale with distance (short=slow, long=fast),\n * which reads inconsistent; prefer the distance-aware speed below. */\n travelMs: number;\n /** Distance-aware travel speed, as a fraction of the source video WIDTH per\n * second (resolution-independent). A travel leg's duration is\n * `distance / (widthsPerSec·videoWidth·zoomFrac)`, floored at `travelMinMs` and\n * then capped at `travelMaxMs` (in that order — an inverted band pins short hops\n * to the floor, not everything to the ceiling), so the cursor holds a roughly\n * CONSTANT on-screen speed regardless of distance —\n * the premium-recorder feel (measured ~0.30 widths/s on the reference). Set 0\n * to fall back to the fixed `travelMs`.\n *\n * `zoomFrac = restScale / camera scale` — exactly 1 for a full-view take, so a\n * zoom-less composition is unaffected. While the camera is punched in, the same\n * video-px move covers proportionally more of the DELIVERED frame, so without\n * this factor a 2× punch-in reads ~2× too fast precisely where the viewer is\n * looking closest. zoomFrac is INTEGRATED across the leg, not sampled at one\n * instant: a travel usually departs while the camera is still wide and lands\n * after it has closed in, and pricing all of it at the landing magnification\n * over-slows the departure by as much as a zoom-blind duration over-sped it.\n * A leg the camera holds a frame through degenerates to that one frame's\n * factor, which is the sampled model's only exactly-right case. */\n travelWidthsPerSec: number;\n /** Floor for a distance-aware travel (ms) so short hops aren't an instant snap.\n * NOTE both clamps are applied AFTER the speed model and neither is part of a\n * `pace` preset, so on the legs they bind THEY set the duration and re-pacing\n * the take does nothing. validate.ts says so once that stops being the\n * exception (see CLAMPED_LEGS_FRAC). */\n travelMinMs: number;\n /** Ceiling for a distance-aware travel (ms) so a full-width jump stays a glide,\n * not a multi-second crawl. Binds on any sweep past\n * `travelMaxMs · travelWidthsPerSec · videoWidth` — ~571px of a 1920 frame at\n * the shipped defaults — which is deliberate (it was eye-tuned on a reference\n * recorder's long moves), so it also bounds how much of the zoom correction\n * above a long zoomed sweep can actually receive. */\n travelMaxMs: number;\n scale: number;\n arcFrac: number;\n arcMax: number;\n rippleMs: number;\n /** ms to hold a zoom after the action settles, before zooming back out */\n holdMs: number;\n /** ms for a zoom-OUT / pull-out ramp (to rest OR to any wider framing).\n * Measured on a reference export: the pull-out is ~1.8× slower than the\n * punch-in (their zoom-out spring ω≈5.2 rad/s ⇒ ~1340ms of critically-damped\n * settle) — a slow, soft release reads premium; a fast one reads like a\n * flinch. */\n zoomOutMs: number;\n /** ms for the zoom-IN ramp (into a target). Decoupled from travelMs so the\n * zoom can be slower/gentler than the cursor. Measured reference punch-in spring\n * ω≈9.4 rad/s ⇒ ~730ms. */\n zoomInMs: number;\n /** Optional cubic-bezier easing for the camera-rect ramps (centre + size in\n * lockstep — see math.ts stageCamera). Absent ⇒ the default critically-\n * damped spring (the measured reference curve). Set this only to force a\n * bezier feel; `zoomSpring` wins over it when both are set. */\n zoomEase?: [number, number, number, number];\n /** Spring easing for the camera-rect ramps, as a `bounce` amount ∈ [0,~0.6):\n * 0 = critically damped (the measured reference zoom curve — also the\n * default when neither zoomSpring nor zoomEase is set), higher = more\n * overshoot/snap. The segment duration stays zoomInMs/zoomOutMs; bounce only\n * shapes the curve. Bounce > 0 overshoots the RECT (a touch past the target\n * frame, then settle) — keep it small. */\n zoomSpring?: number;\n /** Fraction of a camera ramp still UNfinished at its keyframe end (the action\n * instant), left to settle as an asymptotic overdamped tail that continues\n * INTO the hold — so a move tapers out like a physical camera instead of\n * stopping on a velocity cliff at the keyframe. Frame-tracked on the\n * reference export: its moves keep sub-threshold motion ~0.5s past the\n * visible end (tail τ ≈ 220ms in / ≈ 370ms out), while the cut spring's\n * τ = duration/6.9 ends 2-3× harder. ~0.04 (the shipped default) reproduces\n * the reference tails over the default zoomInMs/zoomOutMs. 0 = legacy\n * cut+normalized spring (absent falls back to the default on NEW plans; an\n * old composition without the field renders as it always did). Ignored when\n * zoomSpring or zoomEase is set (those keep their exact legacy curves). */\n zoomSettleFrac?: number;\n /** Minimum stay (ms) after the previous action's visible end before a\n * PULL-OUT ramp may begin. When the beat gap is too tight the pull-out now\n * departs late and LANDS late (after its own action instant) instead of\n * fleeing a frame the viewer is still reading — the reference recorder's\n * reactive pattern (payoff plays while the camera is still arriving).\n * ~800 (the shipped default) reads as a natural beat; pace presets scale it.\n * 0/absent = legacy (a squeezed pull-out departs the instant the previous\n * action ends and lands exactly on its action). Named pullOut- because\n * holdMs already covers the ordinary post-action dwell. */\n pullOutDwellMs?: number;\n /** ms to delay the synthetic cursor along a DRAG stroke, compensating for the\n * capture pipeline latency: the captured ink appears ~this long after the pen\n * actually moved, so without the delay the (exact-time) cursor leads the ink.\n * Tune so the cursor tip sits on the ink front mid-stroke. */\n dragLagMs: number;\n /** easing for a travel move, as cubic-bezier control points [x1,y1,x2,y2].\n * Default is a symmetric ease-in-out — measured from a reference recording, whose\n * cursor accelerates and decelerates evenly (a slow start, fast middle, soft\n * landing). Drag strokes ignore this (they ease the stroke in lockstep with\n * the captured ink — see math.ts). */\n travelEase: [number, number, number, number];\n};\n\n/** Camera motion blur (temporal supersampling — what a real shutter does). The\n * renderer samples the composition camera at `samples` sub-times within each\n * output frame and averages them, so a fast zoom/pan/cursor smears in the\n * motion direction (a camera/shutter motion blur). It smears the\n * backdrop-reveal on a zoom-OUT into a soft gradient instead of a hard\n * single-frame pop. The captured video's frames repeat across sub-samples, so\n * the recording's own content is NOT blurred — only the camera move + cursor. */\nexport type MotionBlurConfig = {\n /** sub-frames sampled per output frame. 1 ⇒ OFF (no supersampling, no cost). */\n samples: number;\n /** fraction of the frame interval the shutter is open (0..1). Blur strength;\n * 0 ⇒ OFF. ~0.5 = a 180° shutter, 1 = 360°. */\n shutter: number;\n};\n\n/** One caption window on a review copy: the pill reads `text` from `fromMs`\n * (inclusive) to `toMs` (exclusive) on the composition timeline. */\nexport type ReviewBadge = { fromMs: number; toMs: number; text: string };\n\n/** One viewer-facing caption window on the DELIVERED video: `text` shows\n * bottom-center from `fromMs` (inclusive) to `toMs` (exclusive) on the\n * composition timeline. Unlike ReviewBadge this is a first-class, persisted\n * composition field rendered on masters — footage alone shows WHAT happened;\n * the caption says what it MEANS, which is the difference between a demo a\n * stranger can follow and \"the screen moves around\". Absent ⇒ rendered\n * output is byte-identical to a caption-less composition. */\nexport type Caption = { fromMs: number; toMs: number; text: string };\n\n/** An opening title card: `title` (the app / the thesis) over a full-frame\n * scrim on top of the establishing hold, gone by `untilMs` (300ms fade).\n * Typographic and deterministic — rendered by the scene in the composition's\n * own look, in whatever language the author wrote, deletable like any field\n * — never generated imagery. The single cheapest \"produced, not captured\"\n * signal a demo can send. */\nexport type TitleCard = { title: string; subtitle?: string; untilMs?: number };\n\n/** Render-time decoration for review copies and A/B variant reels: burned-in\n * beat badges, a REVIEW watermark, and a per-variant corner label. Drawn by the\n * scene in SCREEN space (fixed, outside the composition camera) so the text is\n * legible at any zoom. This is a render input only — it is never written into\n * the editable `*.composition.json` artifact (render strips it) and the\n * validator ignores it. Text renders in the headless Chrome, so any script\n * (incl. CJK) works without ffmpeg font filters. */\nexport type ReviewDecor = {\n /** top-right watermark, e.g. \"REVIEW\" — marks a copy as not-for-posting */\n watermark?: string;\n /** bottom-left caption pill, swapping per timeline window */\n badges?: ReviewBadge[];\n /** constant bottom-left variant label for A/B reels, e.g. \"B · tight ×1.8\" */\n label?: string;\n};\n\n/** The auto-camera director's tuning. ON by default (a plan that specifies no\n * zoom must still come out with sensible framing — the whole point). The\n * numbers are the FEEL knobs; judge them by eye on a rendered clip, not on\n * paper. `enabled: false` is the clean escape hatch: the director doesn't run\n * and ONLY explicit `zoom: \"always\"/\"never\"` produce zoom (auto/absent hold\n * full view). There is no legacy per-event heuristic to fall back to. */\nexport type CameraConfig = {\n enabled: boolean;\n /** an ROI fills this fraction of the frame when framed (bigger ⇒ tighter). */\n fillFrac: number;\n /** hard ceiling on scale. NOT the main lever — ROI SIZE drives the actual\n * scale (a big type-ROI lands medium, a tiny icon lands tight); this just\n * stops a pinpoint ROI zooming past legibility. */\n maxScale: number;\n /** a punch that can't stay on screen this long is dropped to full view (a\n * sub-second punch reads as a flinch). Enforced AFTER hard breaks — the hold\n * extends into the gap before the next break, never merges across one. */\n minHoldMs: number;\n /** a scale below this isn't worth a distinct frame: a single beat that fits\n * under it holds full view, and a coalesced cluster whose UNION falls under\n * it splits instead (the two are \"different regions\" → chain/pull, not hold). */\n minZoomScale: number;\n /** gap between two actions greater than this ⇒ they cannot share a frame. */\n coalesceWindowMs: number;\n /** two ROIs whose centres are closer than this (fraction of video width) MAY\n * coalesce into one shared, held frame — the \"cluster\" (a thumbnail rail, a\n * toolbar). Farther apart ⇒ a re-frame (progressive/deeper), not a hold. */\n travelThreshold: number;\n /** changeCoverage ≥ this ⇒ the action repainted most of the frame (nav /\n * global) ⇒ pull out to full view. The nav-vs-popover divider — the one knob\n * to tune by eye on real captures (frame-diff pass populates the input). */\n pullOutCoverage: number;\n};\n\n// Defaults tuned as a STARTING point — every number here is meant to be judged\n// on a rendered clip and A/B'd one at a time, not signed off on paper.\nexport const DEFAULT_CAMERA: CameraConfig = {\n enabled: true,\n fillFrac: 0.6,\n maxScale: 2.4,\n minHoldMs: 1200,\n minZoomScale: 1.25,\n coalesceWindowMs: 900,\n travelThreshold: 0.18,\n pullOutCoverage: 0.55,\n};\n\nexport type TakeComposition = {\n output: { width: number; height: number; fps: number };\n source: {\n videoUrl: string;\n /** stage size the source video is DRAWN at (capture viewport CSS px) —\n * the coordinate space of every event/bbox below. A Retina capture's\n * file is denser (viewport × captureScale); the scene stretches it to\n * this size, so the extra pixels only sharpen sampling under zoom. */\n videoWidth: number;\n videoHeight: number;\n viewport: { w: number; h: number };\n };\n framing: FramingConfig;\n cursor: CursorConfig;\n /** camera motion blur; absent ⇒ off (renders exactly as before). */\n motionBlur?: MotionBlurConfig;\n /** cursor start, video-px */\n start: Pt;\n events: CompEvent[];\n durationMs: number;\n /** Head trim (ms of the composition timeline cut from the delivered mp4).\n * Capture starts at navigation, so the first frames show the app before it\n * painted (plus any cold-cache font swap) — trim them here instead of\n * post-processing with ffmpeg, so the refine loop keeps applying to the file\n * actually shipped. Event tMs values stay on the untrimmed timeline (the\n * capture is the ground truth); only the delivered head moves. 0/absent =\n * no trim. */\n startMs?: number;\n /** Viewer-facing captions, drawn bottom-center in SCREEN space (outside the\n * camera — legible at any zoom) on EVERY render including the master.\n * Persisted and hand-editable like any composition field; times are on the\n * untrimmed composition timeline (same convention as zoom.inAtMs — a\n * caption entirely inside the startMs head trim is never seen, and the\n * validator says so). Seeded from the plan steps' `caption` fields by\n * planComposition. */\n captions?: Caption[];\n /** optional opening title card over the establishing hold (see TitleCard) */\n titleCard?: TitleCard;\n /** render-time review decoration (badges/watermark/label); never persisted\n * (render strips exactly this field — `captions` above deliberately IS\n * persisted; it is content, not review scaffolding) */\n review?: ReviewDecor;\n};\n\n/** True when motion blur is configured to actually do something — whether the\n * delivery encode folds in the tmix shutter average (render.ts deliverMp4;\n * OFF skips tmix but still runs the same single delivery encode). */\nexport function motionBlurActive(mb: MotionBlurConfig | undefined): mb is MotionBlurConfig {\n return !!mb && mb.samples > 1 && mb.shutter > 0;\n}\n\nexport const DEFAULT_FRAMING: FramingConfig = {\n insetFrac: 0.92,\n cornerRadius: 28,\n shadow: { color: \"rgba(0,0,0,0.55)\", blur: 60, offset: { x: 0, y: 28 } },\n background: { from: \"#1e1b3a\", to: \"#0a0e1c\" },\n};\n\n// Camera motion blur, ON by default — it smooths the zoom\n// motion and softens the zoom-OUT backdrop reveal (the model-C hitch). 6\n// sub-frames is a good smoothness/speed balance; ~0.7 shutter is a strong-ish\n// blur without ghosting. EXPORT render cost scales with `samples` (renders at\n// fps·samples then averages), so `samples` is the quality⇄speed knob — drop it\n// to render faster, raise (≤~12) for silkier fast pans.\nexport const DEFAULT_MOTION_BLUR: MotionBlurConfig = {\n samples: 6,\n shutter: 0.7,\n};\n\nexport const DEFAULT_CURSOR: CursorConfig = {\n travelMs: 560,\n // Distance-aware cursor speed — the dominant \"silky\" lever. A fixed duration\n // makes velocity scale with distance (short=slow, long=fast); holding a roughly\n // constant on-screen speed reads consistent/premium. ~0.35 widths/s with the\n // big-move cap (travelMaxMs 850) was tuned by eye to a notch slower than a\n // premium reference recording (svgl.mp4) on this app's long toolbar→canvas\n // moves. Tune up for snappier, down for slower/grander.\n // NOTE on the cap (subtle): travel ENDS at the action's instant, so a LONGER\n // duration starts EARLIER, not later. With the front-loaded ease (below) a\n // longer move therefore reaches the target SOONER — i.e. raising travelMaxMs\n // can read as *faster*. Judge speed by how fast the cursor SWEEPS, not by when\n // it arrives; lower the cap for a more deliberate sweep.\n travelWidthsPerSec: 0.35,\n travelMinMs: 300,\n travelMaxMs: 850,\n scale: 2.0,\n // Near-straight glide. The reference cursor barely bows (measured: a\n // full-width move deviated <2% off the straight line), so the arc is small —\n // just enough to avoid a robotic ruler-straight path, not a visible curve.\n arcFrac: 0.05,\n arcMax: 24,\n rippleMs: 450,\n holdMs: 1100,\n // Camera ramp durations, measured off a reference export by frame-\n // tracking (see math.ts springEase): punch-in spring ω≈9.4 rad/s ≈ 730ms,\n // pull-out ω≈5.2 ≈ 1340ms. The slow soft release is half the premium feel.\n // No zoomEase/zoomSpring set ⇒ stageEasing falls to springEase(0), the\n // critically-damped spring that IS the measured SS curve over these windows.\n zoomOutMs: 1340,\n zoomInMs: 730,\n // Asymptotic settle + pull-out dwell — the A/B \"C variant\" Pascal signed off\n // (2026-07-26): each camera move keeps a ~4% residual settling INTO the hold\n // (no velocity cliff at the keyframe — the frame-tracked reference tail), and\n // a squeezed pull-out stays ≥800ms on the payoff, landing late instead of\n // fleeing a frame the viewer is still reading. Old compositions without the\n // fields keep the legacy cut/squeeze schedule byte-identically.\n zoomSettleFrac: 0.04,\n pullOutDwellMs: 800,\n // The captured ink trails the pen by the screencast/encode pipeline latency τ;\n // delay the cursor by τ so its tip rides the ink front. Set to τ EXACTLY and\n // the cursor locks to the ink at ALL stroke speeds (both are the same time-\n // delay of the same path), which is what makes a SMOOTH (eased) drag work —\n // its fast mid-section amplifies any τ mismatch into a visible lead. Measured\n // τ≈190ms on this pipeline (swept dragLagMs, picked where the tip sits on the\n // ink front mid-stroke); the old 110ms left even linear strokes ~40px ahead.\n // Re-tune if a different machine's encode latency differs.\n dragLagMs: 190,\n // Soft launch + soft landing (gentle accel from rest, peak ~t0.24, decelerate\n // into the target). Chosen over a symmetric ease-in-out (which felt less silky)\n // and over a pure ease-out [.33,1,.68,1] (instant-max launch + a 46%-of-duration\n // creep tail that makes the speed knob lie — see travelMaxMs). This keeps the\n // soft landing (the silk) while trimming the tail to 38% and removing the abrupt\n // launch. Tune toward [0.42,0,0.58,1] for a more uniform sweep.\n travelEase: [0.3, 0.0, 0.2, 1.0],\n};\n","// planComposition: capture event log -> default editable TakeComposition.\n//\n// Coordinate mapping (capture viewport px -> video px) and the per-beat\n// scaffolding live here; the ZOOM decision is delegated to the camera DIRECTOR\n// (camera.ts), which runs over the whole beat sequence with the real bbox /\n// timing / changed-area from the ground-truth log. Every decision it makes is\n// still written per-beat into the composition (enabled/scale/center + reason)\n// so a human/agent can read and tune it.\n\nimport { type Beat, directCamera } from \"./camera\";\nimport { restStageScale } from \"./math\";\nimport {\n type BBox,\n type CameraConfig,\n type Caption,\n type CaptureLog,\n type CompEvent,\n type CursorConfig,\n DEFAULT_CAMERA,\n DEFAULT_CURSOR,\n DEFAULT_FRAMING,\n DEFAULT_MOTION_BLUR,\n type FramingConfig,\n type Pt,\n type TakeComposition,\n type ZoomDecision,\n} from \"./types\";\n\nexport type PlanOpts = {\n output?: { width?: number; height?: number; fps?: number };\n framing?: Partial<FramingConfig>;\n cursor?: Partial<CursorConfig>;\n /** auto-camera director tuning (default DEFAULT_CAMERA — ON). The director\n * decides zoom from the ground-truth log; these are its feel knobs. Set\n * `camera.enabled = false` for the manual escape hatch (only explicit\n * event `zoom: \"always\"/\"never\"` produce zoom then). */\n camera?: Partial<CameraConfig>;\n};\n\nexport function planComposition(log: CaptureLog, opts: PlanOpts = {}): TakeComposition {\n // Stage space = the capture VIEWPORT (CSS px), NOT the video file's pixel\n // size. A Retina capture (captureScale 2) records a 2×-dense bitmap of the\n // same viewport; the scene draws it at viewport size, so the denser bitmap\n // only sharpens sampling under zoom. Keying the stage to the viewport keeps\n // every calibrated quantity — camera scales (rest/minZoomScale/maxScale),\n // cursor/ripple sizes, framing radius/shadow — meaning the same thing at\n // any capture density. (Pre-Retina logs have video == viewport, so this is\n // byte-identical for them.)\n const vW = log.viewport.w,\n vH = log.viewport.h;\n const oW = opts.output?.width ?? vW;\n const oH = opts.output?.height ?? vH;\n const fps = opts.output?.fps ?? 30;\n\n const framing: FramingConfig = { ...DEFAULT_FRAMING, ...opts.framing };\n const cursor: CursorConfig = { ...DEFAULT_CURSOR, ...opts.cursor };\n const camera: CameraConfig = { ...DEFAULT_CAMERA, ...opts.camera };\n\n // log coords (viewport CSS px) -> stage px. Identity today (stage IS the\n // viewport); kept as an explicit mapping seam.\n const sx = vW / log.viewport.w;\n const sy = vH / log.viewport.h;\n const mapPt = (p: Pt): Pt => ({ x: p.x * sx, y: p.y * sy });\n const mapBox = (b: BBox): BBox => ({ x: b.x * sx, y: b.y * sy, w: b.w * sx, h: b.h * sy });\n\n const rest = restStageScale(vW, vH, oW, oH, framing.insetFrac);\n\n // Axis-aligned bbox of a polyline (video-px), so a drag frames the WHOLE\n // stroke (a path, not a point): a big cross-canvas drag fits ≈ rest → no zoom.\n const pathBBox = (pts: Pt[]): BBox => {\n const xs = pts.map((p) => p.x),\n ys = pts.map((p) => p.y);\n const x = Math.min(...xs),\n y = Math.min(...ys);\n return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y };\n };\n\n // --- map every event into video-px scaffolding (kind-agnostic zoom yet) -----\n type Scaffold = {\n beat: Beat;\n ev: Omit<CompEvent, \"zoom\">;\n };\n\n const scaffolds: Scaffold[] = log.events.map((c) => {\n const kind = c.kind ?? \"click\";\n const point = mapPt({ x: c.x, y: c.y });\n const intent = c.zoom ?? \"auto\";\n const durationMs = \"durationMs\" in c ? c.durationMs : 0;\n\n // drag / dropFiles: cursor path + the region we frame is the path's bbox\n const carries = kind === \"drag\" || kind === \"dropFiles\";\n const to = carries ? mapPt((c as { to: Pt }).to) : undefined;\n const rawPath = carries\n ? ((c as { path?: Pt[] }).path ?? [{ x: c.x, y: c.y }, (c as { to: Pt }).to])\n : undefined;\n const path = rawPath?.map(mapPt);\n const ease = carries ? (c as { ease?: \"linear\" | \"smooth\" }).ease : undefined;\n\n // the element bbox (ground truth): a carry → path bbox, else the captured box\n const bbox = carries && path ? pathBBox(path) : c.box ? mapBox(c.box) : undefined;\n const effectBox = c.effectBox ? mapBox(c.effectBox) : undefined;\n const label = c.sel ?? c.note;\n\n const beat: Beat = {\n kind,\n tMs: c.tMs,\n durationMs,\n box: bbox,\n effectBox,\n changeCoverage: c.changeCoverage,\n point,\n intent,\n label,\n ...(kind === \"press\" ? { keys: (c as { keys?: string }).keys } : {}),\n };\n\n const ev: Omit<CompEvent, \"zoom\"> = {\n kind,\n tMs: c.tMs,\n point,\n bbox,\n label,\n ...(durationMs ? { durationMs } : {}),\n ...(kind === \"type\" ? { text: (c as { text: string }).text } : {}),\n ...(kind === \"press\" ? { keys: (c as { keys: string }).keys } : {}),\n ...(to ? { to } : {}),\n ...(path ? { path } : {}),\n ...(ease ? { ease } : {}),\n ...(kind === \"dropFiles\"\n ? { files: (c as { files: { name: string; size?: number }[] }).files }\n : {}),\n };\n return { beat, ev };\n });\n\n const beats = scaffolds.map((s) => s.beat);\n\n // horizon for the min-hold check on the final segment\n const last = log.events.length ? log.events[log.events.length - 1]! : undefined;\n const lastEnd = last ? last.tMs + (\"durationMs\" in last ? last.durationMs : 0) : 0;\n const endMs = Math.max(log.tEndMs ?? 0, lastEnd + cursor.holdMs);\n\n // --- decide framing --------------------------------------------------------\n // director ON (default): decide from the log. OFF: the manual escape hatch —\n // only explicit always/never produce zoom, auto/absent hold full view.\n const framings = camera.enabled\n ? directCamera(beats, { w: vW, h: vH }, { w: oW, h: oH }, camera, rest, endMs)\n : beats.map((b) => manualFraming(b, rest));\n\n const events: CompEvent[] = scaffolds.map((s, i) => {\n const f = framings[i]!;\n const zoom: ZoomDecision = {\n enabled: f.enabled,\n scale: f.scale,\n center: f.center,\n // zoom-in ramp starts zoomInMs before the action (decoupled from cursor\n // travelMs so the zoom can be slower/gentler — a more cinematic feel).\n // EXCEPT a zoom-enabled press: its payoff (palette / modal / result)\n // exists only AFTER the keypress, and a keypress has no on-screen\n // antecedent to anticipate — a lead-in punches into empty space and the\n // reveal then pops inside an already-committed frame. The camera departs\n // AT the action and rides the reveal in (buildCameraSchedule gives a\n // late-departing ramp its full window after the departure).\n inAtMs:\n f.enabled && s.beat.kind === \"press\"\n ? s.beat.tMs\n : Math.max(0, s.beat.tMs - cursor.zoomInMs),\n reason: f.reason,\n };\n return { ...s.ev, zoom };\n });\n\n const start = log.start ? mapPt(log.start) : { x: vW * 0.25, y: vH * 0.9 };\n const durationMs = Math.max(log.tEndMs ?? 0, lastEnd + cursor.holdMs + cursor.zoomOutMs + 400);\n\n // --- captions: per-step caption strings → viewer-facing subtitle windows.\n // Deterministic tiling ANCHORED AT ACTION INSTANTS: a caption lands exactly\n // when its beat's action does — the camera has finished (or nearly finished)\n // its move by then, so the swap happens over a settled frame. Anchoring at\n // the zoom DEPARTURE (the first design) put every caption swap inside a\n // camera ramp, and two simultaneous motions read as \"the subtitle moves\n // with the zoom\" — the field complaint that moved the anchor here. A\n // caption holds until the next beat's action (never narrating someone\n // else's beat); the last one rides out to the end. All times\n // untrimmed-timeline, editable afterwards like any composition field.\n const captions: Caption[] = [];\n log.events.forEach((c, i) => {\n const text = c.caption?.trim();\n if (!text) return;\n const e = events[i]!;\n const prevEnd = captions.length ? captions[captions.length - 1]!.toMs : 0;\n const fromMs = Math.max(e.tMs, prevEnd);\n const next = events[i + 1];\n const toMs = Math.max(fromMs + 300, next ? next.tMs : durationMs);\n captions.push({ fromMs, toMs, text });\n });\n\n return {\n output: { width: oW, height: oH, fps },\n source: { videoUrl: \"/capture.mp4\", videoWidth: vW, videoHeight: vH, viewport: log.viewport },\n framing,\n cursor,\n motionBlur: DEFAULT_MOTION_BLUR,\n start,\n events,\n durationMs,\n ...(captions.length ? { captions } : {}),\n };\n}\n\n// Manual mode (camera.enabled === false): the director does not run. Only an\n// explicit plan intent produces zoom — \"always\" frames the element bbox, every-\n// thing else holds full view. Deliberately dumb: this is the fully-hand-driven\n// escape hatch, not a second heuristic.\nfunction manualFraming(\n b: Beat,\n rest: number,\n): {\n enabled: boolean;\n scale: number;\n center: Pt;\n reason: string;\n} {\n if (b.intent === \"always\" && b.box) {\n return {\n enabled: true,\n scale: rest, // manual mode leaves scale for the human to raise; frame the bbox\n center: { x: b.box.x + b.box.w / 2, y: b.box.y + b.box.h / 2 },\n reason: \"camera off · plan: zoom=always (raise scale by hand)\",\n };\n }\n return {\n enabled: false,\n scale: rest,\n center: b.point,\n reason: \"camera off · full view (no explicit zoom)\",\n };\n}\n","// Curated preset vocabulary — the presets move (named levels, not raw\n// numbers) applied to the conversational refine loop. The composition schema\n// stays raw numbers; presets are a dictionary the CLI/agent speak: the agent\n// writes numbers into composition.json, and `beats`/`ab` reverse-map numbers\n// back to names for display. A value matching no preset displays as \"custom\"\n// and must never be silently rounded to a named level (bbox-derived precision\n// is ground truth).\n\nimport { DEFAULT_MOTION_BLUR } from \"./types\";\nimport type { CursorConfig, FramingConfig, MotionBlurConfig } from \"./types\";\n\n// --- zoom levels (absolute stage scale; rest ≈ 0.92 at same-size output) ----\n// medium matches the planner's default cap (1.5), so agent-planned zooms land\n// on a named level; close stays under the validator's 2.5 soft cap.\nexport const ZOOM_LEVELS = {\n light: 1.25,\n medium: 1.5,\n tight: 1.8,\n close: 2.2,\n} as const;\nexport type ZoomLevelName = keyof typeof ZOOM_LEVELS;\n\n/** Name a scale if it sits within tolerance of a preset; else null (custom). */\nexport function zoomLevelName(scale: number, tol = 0.07): ZoomLevelName | null {\n let best: ZoomLevelName | null = null;\n let bestD = tol;\n for (const [name, v] of Object.entries(ZOOM_LEVELS) as [ZoomLevelName, number][]) {\n const d = Math.abs(scale - v);\n if (d <= bestD) {\n best = name;\n bestD = d;\n }\n }\n return best;\n}\n\n// --- motion (pace) bundles ---------------------------------------------------\n// One name moves the whole feel together: cursor speed + hold + zoom ramps.\n// \"natural\" IS the shipped default (DEFAULT_CURSOR) — naming it makes the\n// default state speakable.\nexport type MotionPreset = Pick<\n CursorConfig,\n | \"travelWidthsPerSec\"\n | \"travelMinMs\"\n | \"travelMaxMs\"\n | \"holdMs\"\n | \"zoomInMs\"\n | \"zoomOutMs\"\n | \"pullOutDwellMs\"\n> & { zoomEase?: undefined };\n// zoomIn/zoomOut anchored to the measured reference springs (730/1340 —\n// see DEFAULT_CURSOR); calm/brisk scale both while keeping out ≈ 1.8× in.\n// pullOutDwellMs (the minimum stay on a payoff before a squeezed pull-out may\n// flee) scales with the same feel: a calm cut breathes longer, a brisk one\n// tolerates a shorter beat. Each preset also CLEARS a legacy zoomEase (spread\n// leaves the key undefined; JSON drops it) so applying a pace migrates an old\n// composition onto the default measured-SS spring curve instead of silently\n// keeping the old bezier.\n//\n// The TRAVEL CLAMPS ride along too, and they have to. They are applied AFTER\n// travelWidthsPerSec, so a preset that moved only the speed left every clamped\n// leg exactly where it was: below ~202px and above ~571px of a 1920 frame,\n// \"calm\" and \"brisk\" rendered IDENTICALLY and nothing said so. Each clamp\n// scales by the pace's own speed ratio against natural (300·0.35/0.28 = 375,\n// 850·0.35/0.45 = 661…), so a leg on a clamp keeps the same relationship to\n// the legs that aren't.\nexport const MOTION: Record<\"calm\" | \"natural\" | \"brisk\", MotionPreset> = {\n calm: {\n travelWidthsPerSec: 0.28,\n travelMinMs: 375,\n travelMaxMs: 1060,\n holdMs: 1500,\n zoomInMs: 900,\n zoomOutMs: 1650,\n pullOutDwellMs: 1000,\n zoomEase: undefined,\n },\n natural: {\n travelWidthsPerSec: 0.35,\n travelMinMs: 300,\n travelMaxMs: 850,\n holdMs: 1100,\n zoomInMs: 730,\n zoomOutMs: 1340,\n pullOutDwellMs: 800,\n zoomEase: undefined,\n },\n brisk: {\n travelWidthsPerSec: 0.45,\n travelMinMs: 235,\n travelMaxMs: 660,\n holdMs: 750,\n zoomInMs: 550,\n zoomOutMs: 1000,\n pullOutDwellMs: 600,\n zoomEase: undefined,\n },\n};\nexport type MotionName = keyof typeof MOTION;\n\n/** A clamp matches its preset — or the LEGACY value every composition carried\n * before the clamps joined the presets. Without that second door, applying\n * \"brisk\" to an old take and re-reading it would report \"custom\" purely\n * because the take predates clamp-aware presets. Same escape hatch\n * pullOutDwellMs already has. */\nexport const CLAMP_TOL_MS = 20;\nconst clampMatches = (v: number | undefined, want: number, legacy: number): boolean =>\n v == null || Math.abs(v - want) < CLAMP_TOL_MS || Math.abs(v - legacy) < 1;\n\nexport function motionName(cursor: CursorConfig): MotionName | null {\n for (const [name, m] of Object.entries(MOTION) as [MotionName, MotionPreset][]) {\n if (\n Math.abs(cursor.travelWidthsPerSec - m.travelWidthsPerSec) < 0.015 &&\n Math.abs(cursor.holdMs - m.holdMs) < 60 &&\n Math.abs(cursor.zoomInMs - m.zoomInMs) < 60 &&\n Math.abs(cursor.zoomOutMs - m.zoomOutMs) < 60 &&\n clampMatches(cursor.travelMinMs, m.travelMinMs, MOTION.natural.travelMinMs) &&\n clampMatches(cursor.travelMaxMs, m.travelMaxMs, MOTION.natural.travelMaxMs) &&\n // absent = a pre-dwell composition — still nameable by its four legacy\n // knobs; only an explicit different value makes the pace \"custom\".\n (cursor.pullOutDwellMs == null ||\n Math.abs(cursor.pullOutDwellMs - (m.pullOutDwellMs ?? 0)) < 60)\n )\n return name;\n }\n return null;\n}\n\n// --- looks (backdrop bundles) ------------------------------------------------\n// A look is the WHOLE backdrop treatment as one coherent bundle — background\n// gradient + corner radius + shadow — so \"paper\" doesn't produce a light\n// backdrop with dark-tuned corners/shadow.\nexport type LookPreset = Pick<FramingConfig, \"background\" | \"cornerRadius\" | \"shadow\">;\nconst DARK_SHADOW: LookPreset[\"shadow\"] = {\n color: \"rgba(0,0,0,0.55)\",\n blur: 60,\n offset: { x: 0, y: 28 },\n};\nexport const LOOKS: Record<string, LookPreset> = {\n midnight: {\n background: { from: \"#1e1b3a\", to: \"#0a0e1c\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n ink: {\n background: { from: \"#16181d\", to: \"#07080a\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n slate: {\n background: { from: \"#232733\", to: \"#0e1116\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n ocean: {\n background: { from: \"#0c2b36\", to: \"#071019\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n plum: {\n background: { from: \"#2a1e3a\", to: \"#140a1c\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n ember: {\n background: { from: \"#38231d\", to: \"#1a0d09\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n paper: {\n background: { from: \"#f6f4ef\", to: \"#ddd8cd\" },\n cornerRadius: 22,\n shadow: { color: \"rgba(31,27,20,0.30)\", blur: 45, offset: { x: 0, y: 20 } },\n },\n plain: {\n background: { from: \"#101014\", to: \"#101014\", type: \"solid\" },\n cornerRadius: 28,\n shadow: DARK_SHADOW,\n },\n};\nexport type LookName = keyof typeof LOOKS;\n\nexport function lookName(framing: FramingConfig): string | null {\n const bg = framing.background;\n for (const [name, l] of Object.entries(LOOKS)) {\n if (\n l.background.from.toLowerCase() === bg.from.toLowerCase() &&\n l.background.to.toLowerCase() === bg.to.toLowerCase() &&\n (l.background.type ?? \"gradient\") === (bg.type ?? \"gradient\")\n )\n return name;\n }\n return null;\n}\n\n// --- finish (motion blur) ----------------------------------------------------\nexport const FINISH: Record<\"smooth\" | \"crisp\" | \"heavy\", MotionBlurConfig | undefined> = {\n smooth: DEFAULT_MOTION_BLUR, // {samples: 6, shutter: 0.7}\n crisp: undefined, // blur off — exports ~6× faster\n heavy: { samples: 8, shutter: 0.85 },\n};\nexport type FinishName = keyof typeof FINISH;\n\nexport function finishName(mb: MotionBlurConfig | undefined): FinishName | null {\n const active = !!mb && mb.samples > 1 && mb.shutter > 0;\n if (!active) return \"crisp\";\n for (const [name, f] of Object.entries(FINISH) as [FinishName, MotionBlurConfig | undefined][]) {\n if (f && mb && f.samples === mb.samples && Math.abs(f.shutter - mb.shutter) < 0.03) return name;\n }\n return null;\n}\n","// The decode guard's shared vocabulary — imported by BOTH sides of the\n// browser/Node boundary. The scene (src/scene/scene.tsx, vite-compiled inside\n// the render browser) probes the capture with a throwaway <video> and rejects\n// with a message built here; render.ts (Node) recognises that rejection and\n// retries with a VP9 intermediate. Only the message STRING survives the\n// crossing — revideo forwards e.message through onRenderFailed — so the\n// contract is a sentinel substring, not an error class.\n//\n// Keep this module dependency-free: the scene tree is copied verbatim into\n// the render scratch and compiled for the browser, so a node:* import here\n// would break the scene build.\n\nexport const CAPTURE_UNDECODABLE_MARK = \"capture video is not decodable in the render browser\";\n\n/** Build the guard's rejection message. Both variants START with the mark so\n * isCaptureUndecodable can match the forwarded string. */\nexport function buildUndecodableMessage(\n kind: \"media-error\" | \"timeout\",\n detail: string,\n src: string,\n): string {\n const why =\n kind === \"media-error\"\n ? `decode failed (${detail}) — this Chromium likely lacks the capture's codec`\n : `no decode within 30s (${detail}) — the render browser may lack the capture's codec`;\n return `${CAPTURE_UNDECODABLE_MARK}: ${why}; src=${src}`;\n}\n\n/** Did this render rejection come from the scene's decode guard? Substring\n * match on the message — the Error identity does not survive the\n * browser→Node crossing. */\nexport function isCaptureUndecodable(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err);\n return message.includes(CAPTURE_UNDECODABLE_MARK);\n}\n","// validateComposition: a NON-MUTATING structural check on an edited\n// composition. The refine loop is \"edit the JSON, re-render\" — so the agent\n// (or a human) hand-edits `*.composition.json`, and this gives a\n// millisecond, field-specific verdict BEFORE paying for a render. It never\n// changes the composition; it only reports.\n//\n// Severity:\n// \"error\" — the render would be wrong/broken (or silently mis-framed).\n// renderTake refuses to render until these are fixed.\n// \"warn\" — suspect, but may be intentional. Rendered as-is.\n//\n// The single most important check is the capture-lock (see CAPTURE-LOCKED\n// below): an action beat's `tMs` is bound to the recording — the video frame\n// at time t shows the page AS IT WAS at capture-time t — so re-rendering with\n// a moved `tMs` desyncs the overlay from the on-screen action. Retiming an\n// action needs a re-capture, not a JSON edit. Pass the capture log to enforce\n// this; without it the check is skipped (we can't know the ground truth).\n\nimport { buildLegs, buildStageKeyframes, cameraRampSchedule, restStageScale } from \"./math\";\nimport { CLAMP_TOL_MS, MOTION, motionName } from \"./presets\";\nimport { DEFAULT_CURSOR } from \"./types\";\nimport type { CaptureLog, TakeComposition } from \"./types\";\n\n/** Tail past the last beat's settle that still reads as \"the shot breathing\".\n * Beyond it the delivered mp4 is a frozen screen — the padded-to-25s failure. */\nconst DEAD_TAIL_MS = 2500;\n/** A dwell-delayed pull-out lands a little after its own action BY DESIGN, and\n * a tail of a few frames is invisible (the spring has all but arrived). The\n * artifact is a camera that has barely LEFT when the action fires — so gate on\n * both an absolute floor and the fraction of the ramp still to run. */\nconst MOVING_AT_ACTION_MS = 150;\nconst MOVING_AT_ACTION_FRAC = 0.25;\n/** How far past the SLOWEST shipped pace a camera window may run before it is\n * worth a word. Anchored on the preset vocabulary rather than a number\n * invented here, so the ceiling tracks the presets if they are ever retuned. */\nconst RAMP_SLACK = 2;\n/** A travel clamp binding on the odd short hop is the point of having clamps;\n * binding on more than this share of the legs means the speed law (and the\n * whole `pace` preset) is not what paces the take. Under CLAMPED_LEGS_MIN legs\n * the share says nothing — two clamped legs out of two is a fixture, not a\n * finding. */\nconst CLAMPED_LEGS_FRAC = 0.5;\nconst CLAMPED_LEGS_MIN = 3;\n/** A travel squeezed under this share of what the speed law asked for reads as\n * a dart rather than a glide. Paired with an absolute floor so a few-frame\n * shortfall on an already-short hop stays quiet. */\nconst SQUEEZE_FRAC = 0.7;\nconst SQUEEZE_MIN_MS = 200;\n\nexport type CompositionIssue = {\n severity: \"error\" | \"warn\";\n /** dotted/indexed field path, e.g. \"events[3].zoom.scale\" */\n path: string;\n message: string;\n /** a concrete suggested correction the agent can apply */\n fix?: string;\n};\n\nexport type ValidateOpts = {\n /** soft ceiling on zoom scale — above it the pixels visibly soften (warn).\n * Default 2.5 (the planner caps auto-zoom at 1.5; manual edits get headroom). */\n maxScale?: number;\n /** the ground-truth capture log. When given, action `tMs` is checked against\n * it (capture-lock). Omit to skip that check. */\n captureLog?: CaptureLog;\n};\n\nconst reqField: Record<string, string> = {\n type: \"text\",\n press: \"keys\",\n drag: \"to\",\n dropFiles: \"to\",\n // a look IS its hold — without a duration there is no beat to render\n look: \"durationMs\",\n};\n\nexport function validateComposition(\n comp: TakeComposition,\n opts: ValidateOpts = {},\n): CompositionIssue[] {\n const issues: CompositionIssue[] = [];\n const err = (path: string, message: string, fix?: string) =>\n issues.push({ severity: \"error\", path, message, fix });\n const warn = (path: string, message: string, fix?: string) =>\n issues.push({ severity: \"warn\", path, message, fix });\n\n const maxScale = opts.maxScale ?? 2.5;\n\n // --- output / source sanity ---\n const { width: oW, height: oH, fps } = comp.output;\n if (!(oW > 0 && oH > 0))\n err(\"output\", `non-positive output size ${oW}x${oH}`, \"set positive width/height\");\n if (!(fps > 0)) err(\"output.fps\", `fps must be > 0 (got ${fps})`, \"set output.fps to 30 or 60\");\n const { videoWidth: vW, videoHeight: vH } = comp.source;\n if (!(vW > 0 && vH > 0)) err(\"source\", `non-positive source video size ${vW}x${vH}`);\n\n const rest = restStageScale(vW, vH, oW, oH, comp.framing.insetFrac);\n\n // --- motion blur (render cost scales with samples: frames = fps × samples) ---\n const mb = comp.motionBlur;\n if (mb) {\n if (!Number.isInteger(mb.samples) || mb.samples < 1 || mb.samples > 16)\n err(\n \"motionBlur.samples\",\n `samples must be an integer 1-16 (got ${mb.samples})`,\n \"6 is the balanced default; 1 turns blur off\",\n );\n else if (mb.samples > 9)\n warn(\n \"motionBlur.samples\",\n `samples ${mb.samples} renders ${mb.samples}× the frames for little extra smoothness`,\n \"9 is the practical ceiling\",\n );\n if (!(mb.shutter >= 0 && mb.shutter <= 1))\n err(\n \"motionBlur.shutter\",\n `shutter must be 0..1 (got ${mb.shutter})`,\n \"0.7 is the default; 0 turns blur off\",\n );\n }\n\n // --- duration / ordering ---\n const events = comp.events ?? [];\n let lastEnd = 0;\n let prevT = -1;\n for (let i = 0; i < events.length; i++) {\n const e = events[i]!;\n const p = `events[${i}]`;\n const dur = e.durationMs ?? 0;\n const endMs = e.tMs + dur;\n lastEnd = Math.max(lastEnd, endMs);\n\n // ordering: events must stay in temporal order (the video is temporal)\n if (e.tMs < prevT) {\n err(\n `${p}.tMs`,\n `tMs ${e.tMs} is before the previous beat (${prevT}) — events out of order`,\n \"events follow the recording; reordering needs a re-capture, not a swap here\",\n );\n }\n prevT = e.tMs;\n\n if (e.tMs < 0) err(`${p}.tMs`, `negative tMs ${e.tMs}`);\n if (e.tMs > comp.durationMs)\n err(\n `${p}.tMs`,\n `tMs ${e.tMs} exceeds composition durationMs ${comp.durationMs}`,\n \"raise durationMs or remove the beat\",\n );\n\n // kind-specific required fields (editability invariants)\n const need = reqField[e.kind];\n if (need && (e as Record<string, unknown>)[need] == null)\n err(\n `${p}.${need}`,\n `${e.kind} beat is missing \"${need}\"`,\n `restore ${need} from the capture`,\n );\n if (e.kind === \"dropFiles\" && !e.files?.length)\n warn(\n `${p}.files`,\n `dropFiles beat has no files metadata — the ghost card will show a generic \"file\"`,\n \"restore files [{name,size}] from the capture\",\n );\n if (e.kind === \"dropFiles\" && !dur)\n warn(\n `${p}.durationMs`,\n \"dropFiles beat has no carry duration — the cursor teleports to the drop point and the ghost card only flashes\",\n \"restore durationMs from the capture\",\n );\n\n // --- zoom decision ---\n const z = e.zoom;\n if (!z) {\n err(\n `${p}.zoom`,\n \"missing zoom decision\",\n \"every beat needs a zoom { enabled, scale, center, inAtMs }\",\n );\n continue;\n }\n // inAtMs must precede the action (the zoom-in ramps in before the beat\n // lands) — EXCEPT a press: its reveal exists only after the keypress, so\n // its zoom departs AT the action (inAtMs === tMs; the schedule then runs\n // the ramp after the departure instead of landing at tMs).\n if (z.inAtMs < 0) err(`${p}.zoom.inAtMs`, `negative inAtMs ${z.inAtMs}`, \"clamp to 0\");\n if (z.inAtMs > e.tMs && e.kind !== \"press\")\n err(\n `${p}.zoom.inAtMs`,\n `inAtMs ${z.inAtMs} is AFTER the action at tMs ${e.tMs} — the zoom would arrive late`,\n `set inAtMs = tMs − cursor.zoomInMs (= ${Math.max(0, e.tMs - comp.cursor.zoomInMs)})`,\n );\n if (e.kind === \"press\" && z.enabled && z.inAtMs < e.tMs)\n warn(\n `${p}.zoom.inAtMs`,\n `press zoom departs ${e.tMs - z.inAtMs}ms BEFORE the keypress — its reveal doesn't exist yet, so the camera punches into empty space`,\n `set inAtMs = tMs (${e.tMs}) so the zoom rides the reveal in`,\n );\n\n if (z.enabled) {\n // scale must zoom IN (≥ rest). Below rest shows MORE than the framed\n // video → backdrop dead-space; that's never what an enabled zoom wants.\n if (z.scale < rest - 1e-6)\n err(\n `${p}.zoom.scale`,\n `scale ${z.scale.toFixed(3)} is below rest ${rest.toFixed(3)} — that zooms OUT past the frame (dead space)`,\n `raise to ≥ ${rest.toFixed(2)}, or set zoom.enabled=false for a full-view beat`,\n );\n else if (z.scale < rest * 1.2)\n // the whole dead band, not just ≈rest exactly: a 1.03× \"zoom\" renders\n // an enabled move the eye can't see (issue #1 — it shipped silently).\n warn(\n `${p}.zoom.scale`,\n `scale ${z.scale.toFixed(3)} is within 20% of rest ${rest.toFixed(3)} — an imperceptible zoom (enabled but invisible)`,\n \"raise scale to ≥ ~1.25 to actually zoom, or set enabled=false\",\n );\n if (z.scale > maxScale)\n warn(\n `${p}.zoom.scale`,\n `scale ${z.scale.toFixed(2)} exceeds the soft cap ${maxScale} — pixels will soften`,\n `clamp toward ${maxScale.toFixed(1)} unless the detail truly needs it`,\n );\n // center inside the video (clampCenter will pull it in, but an off-video\n // center usually means a stale/hand-miscomputed value)\n if (z.center.x < 0 || z.center.x > vW || z.center.y < 0 || z.center.y > vH)\n warn(\n `${p}.zoom.center`,\n `center (${z.center.x.toFixed(0)},${z.center.y.toFixed(0)}) is outside the video ${vW}x${vH}`,\n e.bbox\n ? \"use the bbox center: { x: bbox.x+bbox.w/2, y: bbox.y+bbox.h/2 }\"\n : \"point at the on-screen target (video-px)\",\n );\n // enabling zoom on a no-bbox beat means an invented center/scale — fine,\n // but flag it so the refine loop knows it's not bbox-derived.\n if (!e.bbox)\n warn(\n `${p}.zoom`,\n \"zoom enabled on a beat with no bbox — center/scale are hand-set, not bbox-fit\",\n \"double-check the center frames the intended region\",\n );\n }\n }\n\n // --- cursor motion knobs ---------------------------------------------------\n // These are plain numbers in the schema and, until here, NOTHING bounded them:\n // a hand edit (or an agent reaching for \"start the zoom earlier\" and stretching\n // the wrong knob) could put the whole take on a crawl with every other check\n // still passing.\n //\n // PRESENT-but-nonsensical is an error: the schedule arithmetic turns it into\n // NaN keyframes. ABSENT is usually the LEGACY shape — compositions predate\n // travelWidthsPerSec / travelMin/MaxMs / zoomInMs and the schedule has a\n // documented fallback for each — so absence is an error only where nothing\n // can stand in. (A validator that refused to render yesterday's composition\n // would be a worse bug than the one it catches.)\n const cur = comp.cursor;\n type MsKnob =\n | \"travelMs\"\n | \"travelMinMs\"\n | \"travelMaxMs\"\n | \"holdMs\"\n | \"zoomInMs\"\n | \"zoomOutMs\"\n | \"travelWidthsPerSec\";\n const knob = (k: MsKnob, positive: boolean, required: boolean) => {\n const v: number | undefined = cur[k];\n if (v == null) {\n if (required)\n err(\n `cursor.${k}`,\n `${k} is missing and the schedule has no fallback for it`,\n `set cursor.${k} to the shipped default (${DEFAULT_CURSOR[k]})`,\n );\n return;\n }\n if (typeof v !== \"number\" || !Number.isFinite(v) || (positive ? v <= 0 : v < 0))\n err(\n `cursor.${k}`,\n `${k} must be a ${positive ? \"positive\" : \"non-negative\"} number (got ${JSON.stringify(v)})`,\n `restore the shipped default (${DEFAULT_CURSOR[k]})`,\n );\n };\n // The speed law is live only with a positive travelWidthsPerSec; without it\n // the cursor runs on the fixed travelMs and the clamps are never consulted.\n const speedLaw = typeof cur.travelWidthsPerSec === \"number\" && cur.travelWidthsPerSec > 0;\n knob(\"holdMs\", false, true);\n knob(\"zoomOutMs\", true, true);\n knob(\"zoomInMs\", true, false); // absent ⇒ the legacy inAtMs→tMs window\n knob(\"travelWidthsPerSec\", false, false); // absent/0 ⇒ the documented travelMs fallback\n knob(\"travelMs\", true, !speedLaw);\n knob(\"travelMinMs\", false, speedLaw);\n knob(\"travelMaxMs\", true, speedLaw);\n if (\n Number.isFinite(cur.travelMinMs) &&\n Number.isFinite(cur.travelMaxMs) &&\n cur.travelMaxMs < cur.travelMinMs\n )\n // An inverted band has no coherent answer, and the clamps are applied in\n // order (floor first — see math.ts travelDur), so every leg lands on one\n // bound or the other and the ordering INVERTS: a short hop takes the\n // 800ms floor while a full-frame sweep takes the 400ms ceiling.\n err(\n \"cursor.travelMaxMs\",\n `travelMaxMs ${cur.travelMaxMs} is below travelMinMs ${cur.travelMinMs} — an inverted band, so every leg is pinned to one bound or the other and SHORT hops (${cur.travelMinMs}ms) end up slower than full-frame sweeps (${cur.travelMaxMs}ms)`,\n `raise travelMaxMs above travelMinMs (defaults ${DEFAULT_CURSOR.travelMinMs}/${DEFAULT_CURSOR.travelMaxMs})`,\n );\n // A punch-in's ramp END is pinned to the action instant, so a LONGER window\n // means departing EARLIER and creeping — never landing later. Past roughly\n // twice the slowest shipped pace the settle curve reads as a drift, and\n // nothing else here catches it (the crowded-release check below only fires on\n // a ramp that lands LATE).\n if (cur.zoomInMs > MOTION.calm.zoomInMs * RAMP_SLACK)\n warn(\n \"cursor.zoomInMs\",\n `zoomInMs ${cur.zoomInMs} is over ${RAMP_SLACK}× the slowest shipped pace (calm = ${MOTION.calm.zoomInMs}) — a punch-in lands ON the action, so this departs that much earlier and creeps in`,\n `${DEFAULT_CURSOR.zoomInMs} is the frame-measured default; use pace \"calm\" (${MOTION.calm.zoomInMs}) for a gentler punch`,\n );\n if (cur.zoomOutMs > MOTION.calm.zoomOutMs * RAMP_SLACK)\n warn(\n \"cursor.zoomOutMs\",\n `zoomOutMs ${cur.zoomOutMs} is over ${RAMP_SLACK}× the slowest shipped pace (calm = ${MOTION.calm.zoomOutMs}) — every release drifts out for that long, and the tail must outlast it`,\n `${DEFAULT_CURSOR.zoomOutMs} is the frame-measured default; use pace \"calm\" (${MOTION.calm.zoomOutMs}) for a slower release`,\n );\n\n // camera-rect spring: bounce shapes the ONE ease driving centre+size, so an\n // out-of-range value corrupts every camera move (see math.ts springEase).\n const spring = comp.cursor.zoomSpring;\n if (spring != null) {\n if (!(spring >= 0 && spring < 0.6))\n err(\n \"cursor.zoomSpring\",\n `zoomSpring ${spring} outside [0, 0.6)`,\n \"0 = critically damped (the default feel); keep bounce ≤ 0.3\",\n );\n else if (spring > 0.3)\n warn(\n \"cursor.zoomSpring\",\n `zoomSpring ${spring} is a lot of bounce — the rect overshoot can flash backdrop at edge-flush targets and over-zoom tight punches`,\n \"keep ≤ 0.3 (the editor slider's max) unless the flash is wanted\",\n );\n }\n\n // asymptotic settle: the residual left to creep out after the action instant.\n // Beyond ~0.15 the camera visibly hasn't arrived when the action fires.\n const settleFrac = comp.cursor.zoomSettleFrac;\n if (settleFrac != null && !(settleFrac >= 0 && settleFrac <= 0.15))\n err(\n \"cursor.zoomSettleFrac\",\n `zoomSettleFrac ${settleFrac} outside [0, 0.15]`,\n \"~0.04 = the reference-measured tail; 0 = legacy cut spring\",\n );\n else if (settleFrac != null && settleFrac > 0 && (comp.cursor.zoomEase || spring != null))\n warn(\n \"cursor.zoomSettleFrac\",\n `zoomSettleFrac is IGNORED while cursor.${comp.cursor.zoomEase ? \"zoomEase\" : \"zoomSpring\"} is set — the render is byte-identical to not setting it`,\n \"delete cursor.zoomEase / cursor.zoomSpring (a pace preset clears zoomEase) to activate the settle tail\",\n );\n\n const dwell = comp.cursor.pullOutDwellMs;\n if (dwell != null && !(dwell >= 0 && dwell <= 5000))\n err(\n \"cursor.pullOutDwellMs\",\n `pullOutDwellMs ${dwell} outside [0, 5000]`,\n \"600-1000 reads as a natural beat; 0 = legacy (depart as soon as the action ends)\",\n );\n\n // SILENT PACE OVERRIDE: travelMinMs/travelMaxMs are applied AFTER the speed\n // law (math.ts buildLegs), so on the legs they bind it is the clamp — not\n // travelWidthsPerSec — that sets the duration. travelWidthsPerSec is what a\n // `pace` preset moves and travelMin/MaxMs are NOT in the preset, so a take\n // whose legs are mostly clamped answers a pace change with a shrug. Nothing\n // in the JSON shows this; only the legs do.\n if (cur.travelWidthsPerSec > 0 && issues.every((i) => i.severity !== \"error\")) {\n try {\n const travels = buildLegs(comp).filter((l) => !l.drag);\n const pace = motionName(cur);\n // RUSHED TRAVEL: a leg is bounded on the left by the previous beat's\n // action end, so a beat that runs late (or a settleMs too short to hold\n // the glide that follows it) squeezes the move into whatever is left and\n // the cursor darts. This is the cursor's twin of the crowded-release\n // check below, and like it the fix is in the RECORDING: nothing in the\n // composition can widen a gap the capture never left.\n const shortfall = (l: (typeof travels)[number]) => (l.wantSec ?? 0) - (l.t1 - l.t0);\n const squeezed = travels\n .filter(\n (l) =>\n l.wantSec != null &&\n l.t1 - l.t0 < l.wantSec * SQUEEZE_FRAC &&\n shortfall(l) > SQUEEZE_MIN_MS / 1000,\n )\n .sort((a, b) => shortfall(b) - shortfall(a));\n const worst = squeezed[0];\n if (worst) {\n const got = Math.round((worst.t1 - worst.t0) * 1000);\n const want = Math.round((worst.wantSec ?? 0) * 1000);\n const prev = worst.evIdx != null ? events[worst.evIdx - 1] : undefined;\n warn(\n `events[${worst.evIdx}]`,\n `${squeezed.length === 1 ? \"this beat's\" : `${squeezed.length} beats' travel is rushed; the worst`} approach gets ${got}ms of the ${want}ms the speed law asks for — the cursor darts in${prev ? ` because events[${worst.evIdx! - 1}] (${prev.kind}) is still running until ${prev.tMs + (prev.durationMs ?? 0)}ms` : \" because the take starts too close to it\"}`,\n prev\n ? `raise the previous step's settleMs by ≥ ${want - got}ms and re-\\`make\\` — the gap is in the CAPTURE, no cursor knob can widen it`\n : `add a leading \\`wait\\` (or move \\`start\\` closer) and re-\\`make\\` — the opening sweep has no room`,\n );\n }\n for (const which of [\"min\", \"max\"] as const) {\n const n = travels.filter((l) => l.clamped === which).length;\n if (travels.length < CLAMPED_LEGS_MIN || n <= travels.length * CLAMPED_LEGS_FRAC) continue;\n const field = which === \"min\" ? \"travelMinMs\" : \"travelMaxMs\";\n // A clamp at ITS PACE'S value is not an override — it IS the pace, it\n // was tuned with the rest of the bundle, and re-pacing moves those legs\n // like any other. Only a clamp somebody HAND-SET away from the pace\n // overrides it, and only then is there anything to say. (Before the\n // clamps joined MOTION every clamped leg really was deaf to the pace,\n // and this warning said so; saying it now would be false.)\n const shipped = pace ? MOTION[pace] : DEFAULT_CURSOR;\n // Same tolerance motionName uses, so the two can never disagree: a\n // value near enough to keep the pace's NAME is near enough to be the\n // pace, and must not be reported as overriding it.\n if (Math.abs(cur[field] - shipped[field]) < CLAMP_TOL_MS) continue;\n warn(\n `cursor.${field}`,\n `${n} of ${travels.length} travel legs are ${which === \"min\" ? \"floored at\" : \"capped at\"} a hand-set cursor.${field} of ${cur[field]}ms — on those the clamp sets the duration, not cursor.travelWidthsPerSec${pace ? `, so they no longer move with the \"${pace}\" pace (which ships ${shipped[field]}ms)` : \"\"}`,\n `restore cursor.${field} to ${shipped[field]}${pace ? ` (the \"${pace}\" pace's own value)` : \" (the shipped default)\"} to put those legs back under the speed law — or keep it, if they are meant to read as ${which === \"min\" ? \"darts\" : \"one steady sweep\"}`,\n );\n }\n } catch {\n /* never let a diagnostics pass throw */\n }\n }\n\n // tail: the composition must outlast the last action (+ a little settle)\n if (comp.durationMs < lastEnd)\n err(\n \"durationMs\",\n `durationMs ${comp.durationMs} ends before the last action (${lastEnd})`,\n `raise to ≥ ${Math.round(lastEnd + comp.cursor.holdMs + comp.cursor.zoomOutMs)}`,\n );\n else if (comp.durationMs < lastEnd + comp.cursor.zoomOutMs)\n warn(\n \"durationMs\",\n `only ${comp.durationMs - lastEnd}ms after the last action — the final zoom-out may be cut`,\n `allow ≥ ${comp.cursor.zoomOutMs}ms (cursor.zoomOutMs) of tail`,\n );\n // …and the mirror image: a tail so long the delivered mp4 ends on a frozen\n // screen. The classic cause is padding a plan with trailing `wait`s to hit a\n // \"~25s\" target — the capture keeps rolling long after the last payoff has\n // settled and nothing on screen changes again. Cheap to fix (durationMs is\n // render-only), invisible to an agent that never watches the tail.\n else if (events.length) {\n const settledEnd = lastEnd + comp.cursor.holdMs + comp.cursor.zoomOutMs;\n if (comp.durationMs > settledEnd + DEAD_TAIL_MS)\n warn(\n \"durationMs\",\n `${((comp.durationMs - settledEnd) / 1000).toFixed(1)}s of tail after the last beat settles — the delivered video ends on a frozen screen`,\n `trim durationMs to ≈ ${Math.round(settledEnd)}, or add a beat that earns the time`,\n );\n }\n\n // CROWDED RELEASE: the camera should be PARKED at the instant an action\n // fires. A release (a zoomed beat followed by a full-view one) needs\n // pullOutDwellMs + zoomOutMs of room after the previous beat's payoff\n // settles; when the gap is tighter the schedule keeps the ramp and lands it\n // LATE — deliberately, because fleeing a frame the viewer is still reading is\n // worse — and the frame slides out from under the next click. That trade is\n // right given the recording, but the recording is the thing to fix, so say\n // so. (A zoom-enabled `press` is reveal-timed by construction: it departs AT\n // the keypress and rides the reveal in, so its late landing is the design.)\n if (issues.every((i) => i.severity !== \"error\")) {\n try {\n const sched = cameraRampSchedule(comp);\n const room = (comp.cursor.pullOutDwellMs ?? 0) + comp.cursor.zoomOutMs;\n for (let i = 0; i < events.length; i++) {\n const e = events[i]!;\n const r = sched[i];\n if (!r) continue;\n const rampMs = r.landMs - r.startMs;\n // OVER-LONG WINDOW: the ramp a beat actually gets is inAtMs → its\n // landing, so a hand-set inAtMs — not cursor.zoomInMs — is what makes a\n // multi-second creep. The usual cause is reading \"start the zoom\n // earlier\" as \"start it much earlier\": the landing is pinned to the\n // action, so the only thing that moves is how slowly it gets there.\n // Only HAND-SET windows are flagged; the planner's own default is\n // clamped at 0 for an early first beat and that is by design.\n const nominal = r.pullOut ? comp.cursor.zoomOutMs : comp.cursor.zoomInMs;\n const handSet = Math.abs(e.zoom.inAtMs - Math.max(0, e.tMs - comp.cursor.zoomInMs)) >= 1;\n if (handSet && nominal > 0 && rampMs > nominal * RAMP_SLACK)\n warn(\n `events[${i}].zoom.inAtMs`,\n `this beat's camera window runs ${Math.round(rampMs)}ms — ${(rampMs / nominal).toFixed(1)}× cursor.${r.pullOut ? \"zoomOutMs\" : \"zoomInMs\"} (${nominal}ms) — so the camera departs at ${Math.round(r.startMs)}ms and creeps to the action instead of moving at the take's pace`,\n `set inAtMs = ${Math.max(0, e.tMs - comp.cursor.zoomInMs)} (tMs − cursor.zoomInMs) and change cursor.${r.pullOut ? \"zoomOutMs\" : \"zoomInMs\"} if the RAMP itself should be slower`,\n );\n // press: reveal-timed by construction. look: nothing fires at tMs —\n // the camera arriving early in the DWELL is the beat working as\n // designed, so \"the frame slides out from under it\" cannot happen.\n if (e.kind === \"press\" || e.kind === \"look\") continue;\n const lateMs = Math.round(r.landMs - e.tMs);\n if (lateMs <= MOVING_AT_ACTION_MS) continue;\n if (!(rampMs > 0) || lateMs / rampMs <= MOVING_AT_ACTION_FRAC) continue;\n const prev = events[i - 1];\n const prevEnd = prev ? prev.tMs + (prev.durationMs ?? 0) : 0;\n // The dwell floor can push the departure past the action entirely, and\n // then \"% of the move done\" is negative — a fraction that cannot\n // describe a camera which has not left yet. Say the stronger thing.\n const doneFrac = 1 - lateMs / rampMs;\n const progress =\n doneFrac > 0\n ? `has only ${Math.round(doneFrac * 100)}% of its move done`\n : \"has not even departed\";\n warn(\n `events[${i}].zoom`,\n `the camera ${progress} when this beat's action fires (departs ${Math.round(r.startMs)}ms, lands ${Math.round(r.landMs)}ms, action ${e.tMs}ms) — the frame slides out from under it${prev ? `; the previous beat settles only ${Math.round(e.tMs - prevEnd)}ms earlier` : \"\"}`,\n prev\n ? `hold the frame — copy events[${i - 1}].zoom onto this beat so the camera never moves at the action; or re-capture with ≥ ${room}ms of settle on events[${i - 1}] (cursor.pullOutDwellMs + cursor.zoomOutMs)`\n : `re-capture with more lead-in before this beat, or set zoom.enabled=false`,\n );\n }\n } catch {\n /* never let a diagnostics pass throw */\n }\n }\n\n // A dwell-delayed final pull-out can land LATER than the legacy tail math\n // above assumes — check the actual schedule, not the formula. (Guarded: the\n // schedule needs a structurally sound composition; earlier errors mean this\n // check would throw, and its absence is already explained by them.)\n if ((comp.cursor.pullOutDwellMs ?? 0) > 0 && issues.every((i) => i.severity !== \"error\")) {\n try {\n const kfs = buildStageKeyframes(comp).r;\n let motionEndS = 0;\n for (let i = 0; i < kfs.length - 1; i++) {\n const [, a] = kfs[i]!;\n const [t1, b] = kfs[i + 1]!;\n if (a.cx !== b.cx || a.cy !== b.cy || a.w !== b.w) motionEndS = t1;\n }\n if (motionEndS * 1000 > comp.durationMs + 1)\n warn(\n \"durationMs\",\n `the camera is still mid-motion at durationMs (dwell-delayed landing ends ~${Math.round(motionEndS * 1000)}ms)`,\n `raise durationMs to ≥ ${Math.round(motionEndS * 1000)}`,\n );\n } catch {\n /* never let a diagnostics pass throw */\n }\n }\n\n // Dead HEAD — the mirror of the dead-tail check. A capture that had to wait\n // out a cold load (map tiles, data fetch) ships that whole wait unless\n // startMs trims it, and \"8 seconds of nothing, then the cursor moves\" is\n // the first thing every viewer sees. The wait was necessary to SHOOT;\n // shipping it is a choice, and the default choice should be no.\n if (comp.events.length) {\n const firstVisible = comp.events[0]!.zoom.inAtMs;\n const deadHeadMs = firstVisible - (comp.startMs ?? 0);\n if (deadHeadMs > DEAD_TAIL_MS)\n warn(\n \"startMs\",\n `${(deadHeadMs / 1000).toFixed(1)}s of dead opening before the first beat's camera moves — the delivered video starts on a frozen screen`,\n `set startMs ≈ ${Math.max(0, firstVisible - 1200)} (leave ~1.2s of establishing hold, trim the rest of the load wait)`,\n );\n }\n\n // head trim: cut dead pre-paint frames, never a beat. The trim only moves\n // the delivered head — tMs values stay on the capture timeline.\n const startMs = comp.startMs;\n if (startMs != null) {\n if (!(startMs >= 0) || startMs >= comp.durationMs)\n err(\n \"startMs\",\n `startMs ${startMs} outside [0, durationMs ${comp.durationMs})`,\n \"the head trim must leave a video\",\n );\n else if (comp.events[0] && startMs > comp.events[0].zoom.inAtMs)\n warn(\n \"startMs\",\n `startMs ${startMs} cuts into the first beat (camera/cursor already moving at ${comp.events[0].zoom.inAtMs}ms)`,\n `keep the trim ≤ ${comp.events[0].zoom.inAtMs} so the delivered video opens at rest`,\n );\n }\n\n // --- captions: viewer-facing timeline overlays on the DELIVERED video ---\n // Times are on the untrimmed composition timeline, like zoom.inAtMs.\n for (const [i, cap] of (comp.captions ?? []).entries()) {\n if (!cap.text?.trim()) {\n err(`captions[${i}].text`, \"empty caption text\", \"give the caption a line, or delete it\");\n continue;\n }\n if (!(cap.toMs > cap.fromMs))\n err(\n `captions[${i}].toMs`,\n `toMs ${cap.toMs} is not after fromMs ${cap.fromMs} — an inverted/empty window shows nothing`,\n \"set toMs > fromMs (a readable line needs ~1500ms on screen)\",\n );\n if (!(cap.fromMs >= 0) || cap.fromMs >= comp.durationMs)\n err(\n `captions[${i}].fromMs`,\n `fromMs ${cap.fromMs} outside [0, durationMs ${comp.durationMs})`,\n \"captions live on the composition timeline\",\n );\n const prev = comp.captions?.[i - 1];\n if (prev && cap.fromMs < prev.toMs)\n warn(\n `captions[${i}].fromMs`,\n `window [${cap.fromMs}, ${cap.toMs}) overlaps captions[${i - 1}] [${prev.fromMs}, ${prev.toMs}) — two pills stack in the same slot`,\n `start this caption at ${prev.toMs}, or end the previous one at ${cap.fromMs}`,\n );\n if (comp.startMs != null && cap.toMs <= comp.startMs)\n warn(\n `captions[${i}]`,\n `window [${cap.fromMs}, ${cap.toMs}) sits entirely inside the startMs head trim (${comp.startMs}) — it is never seen`,\n \"move the window past the trim, or delete the caption\",\n );\n if (cap.text.trim().length > 120)\n warn(\n `captions[${i}].text`,\n `${cap.text.trim().length} chars — a caption is one explanatory sentence, not a paragraph`,\n \"cut to one sentence (~15-30 CJK chars / 8-14 words); move detail into the beat itself\",\n );\n }\n\n if (comp.titleCard && !comp.titleCard.title?.trim())\n err(\"titleCard.title\", \"empty title on a title card\", \"give it the app/thesis line, or delete titleCard\");\n\n // --- CAPTURE-LOCKED: action tMs must match the recording ---\n // The video is temporal: a beat's tMs is WHEN it is visible in the capture.\n // A render-only edit cannot move that, so a drifted tMs would fire the\n // overlay off the on-screen action. (Cinematic timing — inAtMs, holdMs,\n // zoom ramps, the intro travel and the tail — IS freely editable; only the\n // action anchor tMs is locked.)\n if (opts.captureLog) {\n const log = opts.captureLog;\n if (log.events.length !== events.length)\n warn(\n \"events\",\n `composition has ${events.length} beats but the capture log has ${log.events.length} — added/removed actions need a re-capture`,\n \"re-capture to change the choreography; edit only renders the existing recording\",\n );\n const n = Math.min(log.events.length, events.length);\n for (let i = 0; i < n; i++) {\n const lt = log.events[i]!.tMs;\n const ct = events[i]!.tMs;\n if (Math.abs(lt - ct) > 1)\n err(\n `events[${i}].tMs`,\n `tMs ${ct} drifted from the captured ${lt} — an action's tMs is capture-locked (the video shows it at ${lt}ms)`,\n `restore tMs to ${lt}; to retime the action itself, re-capture`,\n );\n }\n }\n\n return issues;\n}\n\n/** Format issues for a human/agent log. Errors first. */\nexport function formatIssues(issues: CompositionIssue[]): string {\n if (!issues.length) return \"composition OK (0 issues)\";\n const order = (s: string) => (s === \"error\" ? 0 : 1);\n return issues\n .slice()\n .sort((a, b) => order(a.severity) - order(b.severity))\n .map(\n (i) => ` [${i.severity}] ${i.path}: ${i.message}${i.fix ? `\\n fix: ${i.fix}` : \"\"}`,\n )\n .join(\"\\n\");\n}\n","// renderTake: composition (or capture log) + captured video -> polished\n// mp4 + the editable composition written alongside it.\n//\n// Runs revideo headless (vite + chromium + ffmpeg). The renderer resolves\n// everything relative to process.cwd(), and injects `projectFile` verbatim\n// as an import specifier — so the render runs from a directory laid out like\n// the package (src/ + public/) with the vite-root-absolute\n// \"/src/scene/project.ts\" (a bare specifier hangs the renderer forever; see\n// spike-revideo/VERDICT.md).\n//\n// That directory is a per-render SCRATCH COPY in the tmp dir, never the\n// installed package: a render used to write capture.mp4, .composition.json and\n// out-render/ into node_modules, which breaks read-only installs outright and\n// lets two renders read each other's composition. See prepareScratch.\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport {\n mkdir,\n mkdtemp,\n readdir,\n readFile,\n rm,\n symlink,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { renderVideo } from \"@open-take/revideo-renderer\";\nimport { isCaptureUndecodable } from \"./decode-guard\";\nimport { ffmpegHasEncoder, repairBundledMediaPermissions, resolveFfmpeg } from \"./ffmpeg\";\nimport { type PlanOpts, planComposition } from \"./plan\";\nimport {\n type CaptureLog,\n type MotionBlurConfig,\n motionBlurActive,\n type TakeComposition,\n} from \"./types\";\nimport { type CompositionIssue, formatIssues, validateComposition } from \"./validate\";\n\n// dist/index.js -> package root\nconst PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), \"..\");\nconst RENDER_OUT = \"out-render\"; // relative to cwd (= the scratch dir at render time)\n\nexport type RenderTakeOpts = {\n /** input capture video (webm or mp4) */\n videoPath: string;\n /** output polished mp4 path */\n outPath: string;\n /** provide a capture log (auto-planned) ... */\n log?: CaptureLog;\n /** ... or a ready-made composition (editable artifact) */\n composition?: TakeComposition;\n planOpts?: PlanOpts;\n logProgress?: boolean;\n /** Chrome binary for the headless render. Pass the same Chrome-for-Testing\n * the capture path uses so a single browser serves both stages. The\n * higher-level runtime resolves and supplies this to puppeteer-core. */\n chromePath: string;\n /** the capture log, for cross-checking that an edited composition didn't\n * drift an action's capture-locked tMs (see validateComposition). Optional —\n * the structural checks run regardless. */\n captureLog?: CaptureLog;\n /** skip the pre-render structural validation. Default false — we validate and\n * refuse to render an errored composition (a render is expensive; catch a bad\n * hand-edit in milliseconds instead). */\n skipValidate?: boolean;\n /** progress callback (0..1) forwarded from revideo's renderer. */\n onProgress?: (progress: number) => void;\n /** render only this window of the composition timeline, in SECONDS — the\n * windowed-render path behind A/B variant reels (a 4s window instead of the\n * whole take). With motion blur OFF, frames are identical to the same span\n * of a full render (the timeline is deterministic). With blur active the\n * content matches but not bit-exactly: the tmix shutter windows are phased\n * from the CLIP start, and the first frame's trailing window is truncated.\n * Forwarded to revideo's projectSettings.range. */\n rangeSec?: [number, number];\n /** write the editable composition (default true). Review copies and A/B reels\n * are disposable — they skip it. */\n writeCompositionSibling?: boolean;\n /** where to write it. Default `<out>.composition.json`; the runtime passes the\n * take's working dir instead. WHERE a take keeps its files is a take-layout\n * question — the compositor just writes where it is told. */\n compositionPath?: string;\n};\n\nexport type RenderTakeResult = {\n mp4Path: string;\n compositionPath: string;\n /** non-fatal validator findings for this composition. The render went ahead,\n * but each one is something the author has to look at — a zoom that punches\n * into empty space, a press whose zoom departs before the keypress, a tail\n * that delivers a frozen screen. Empty when `skipValidate` is set. */\n warnings: CompositionIssue[];\n /** the composition this render actually used — callers that judge the\n * output (post-shoot gates) must judge THIS object, not a re-read of\n * composition.json, which a concurrent editor save may have moved on. */\n composition: TakeComposition;\n};\n\nfunction run(cmd: string, args: string[]): Promise<void> {\n return new Promise((res, rej) => {\n const c = spawn(cmd, args, { stdio: [\"ignore\", \"ignore\", \"pipe\"] });\n let err = \"\";\n c.stderr.on(\"data\", (d) => {\n err += d;\n });\n c.on(\"error\", rej);\n c.on(\"close\", (code) => (code === 0 ? res() : rej(new Error(`${cmd} exited ${code}: ${err}`))));\n });\n}\n\n/** Normalise the capture to a constant-fps mp4 the web decoder can read.\n * fps follows the composition so a hi-fps capture can render at 60 (the\n * render grid must match — a 30-grid would throw away the extra frames).\n *\n * `codec` is normally h264; \"vp9\" is the retry arm for render browsers\n * WITHOUT H.264 decoding (Playwright-style Chromium builds ship no\n * proprietary codecs). The scene's decode guard rejects in seconds when the\n * capture can't decode there (see src/decode-guard.ts); renderTakeExclusive\n * catches that rejection and re-encodes the scratch capture with this arm\n * before one retry. The VP9 fallback must keep the .mp4 container AND the\n * capture.mp4 name: revideo routes video decoding by file extension, so a\n * .webm would take a different (and broken) decode path — VP9-in-MP4 (vp09\n * track) is the shape that works. */\nasync function toMp4(\n videoPath: string,\n outMp4: string,\n fps: number,\n codec: \"h264\" | \"vp9\",\n): Promise<void> {\n await mkdir(dirname(outMp4), { recursive: true });\n const codecArgs =\n codec === \"vp9\"\n ? [\"-c:v\", \"libvpx-vp9\", \"-b:v\", \"0\", \"-crf\", \"24\", \"-row-mt\", \"1\", \"-cpu-used\", \"4\"]\n : [\"-c:v\", \"libx264\", \"-crf\", \"18\"];\n await run(await resolveFfmpeg(), [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-i\",\n resolve(videoPath),\n ...codecArgs,\n \"-pix_fmt\",\n \"yuv420p\",\n \"-r\",\n String(fps),\n \"-an\",\n outMp4,\n ]);\n}\n\n/** Delivery encode: the visually-lossless ProRes intermediate -> the postable\n * H.264. The ONLY lossy generation in the pipeline, so its CRF is the\n * master's quality — overlay text (captions/title card) used to look soft\n * because it took TWO generations before this fix: revideo's default wasm\n * exporter (WebCodecs H.264 at the browser's default bitrate, no knob, at\n * fps·samples) and then this re-encode on top.\n *\n * Motion blur folds in here (temporal supersampling: the scene was rendered\n * at fps·samples, project.ts): `tmix=frames=M` averages M consecutive\n * sub-frames; `fps=baseFps` then decimates ≈every `samples`-th, so each\n * output frame = the mean of the last M sub-frames of its interval (a\n * trailing shutter).\n *\n * The scale step is a REAL conversion, not a re-tag: the ProRes encode\n * converts the scene's RGB frames with swscale's default bt601 matrix, so\n * the intermediate is 601-coded. Convert to bt709 and tag it — verified by\n * round-tripping primaries (601-coded red merely tagged 709 decodes to\n * rgb(255,24,0); converted it decodes to rgb(252,0,0)). */\nasync function deliverMp4(\n inMov: string,\n outMp4: string,\n baseFps: number,\n blur: MotionBlurConfig | null,\n): Promise<void> {\n const vf: string[] = [];\n if (blur) {\n const M = Math.max(1, Math.min(blur.samples, Math.round(blur.shutter * blur.samples)));\n vf.push(`tmix=frames=${M}`, `fps=${baseFps}`);\n }\n vf.push(\n \"scale=in_color_matrix=bt601:out_color_matrix=bt709\",\n \"format=yuv420p\",\n \"setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709\",\n );\n await run(await resolveFfmpeg(), [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-i\",\n resolve(inMov),\n \"-vf\",\n vf.join(\",\"),\n \"-c:v\",\n \"libx264\",\n \"-crf\",\n \"18\",\n \"-movflags\",\n \"+faststart\",\n \"-r\",\n String(baseFps),\n \"-an\",\n outMp4,\n ]);\n}\n\n// --- per-render scratch dir --------------------------------------------------\n\n/** The nearest node_modules above the installed package. Symlinked into the\n * scratch dir so the copied scene can still resolve `@revideo/*` — pnpm keeps\n * a node_modules beside the package, npm/yarn hoist it to the project root, so\n * walk up rather than assume either. */\nfunction hostNodeModules(): string | null {\n let dir = PKG_ROOT;\n for (;;) {\n const candidate = join(dir, \"node_modules\");\n if (existsSync(candidate)) return candidate;\n const up = dirname(dir);\n if (up === dir) return null;\n dir = up;\n }\n}\n\n/** The whole dependency tree in one directory, for vite's fs.allow. Vite serves\n * realpaths, and pnpm's are under `<root>/node_modules/.pnpm/…`, so the first\n * `node_modules` segment of a resolved dependency covers every layout. */\nfunction depsRoot(): string | null {\n try {\n const real = realpathSync(createRequire(import.meta.url).resolve(\"@revideo/core\"));\n const parts = real.split(sep);\n const i = parts.indexOf(\"node_modules\");\n return i === -1 ? null : parts.slice(0, i + 1).join(sep);\n } catch {\n return null;\n }\n}\n\n/** Copy a tree WITHOUT inheriting its permission bits. `fs.cp` preserves mode,\n * so copying out of a read-only install yields a read-only copy we then can't\n * write the composition into. Re-creating each file gives us the umask\n * default instead. The scene tree is a handful of small source files. */\nasync function copyWritable(from: string, to: string): Promise<void> {\n await mkdir(to, { recursive: true });\n for (const e of await readdir(from, { withFileTypes: true })) {\n const src = join(from, e.name);\n const dst = join(to, e.name);\n if (e.isDirectory()) await copyWritable(src, dst);\n else if (e.isFile()) await writeFile(dst, await readFile(src));\n }\n}\n\nasync function cleanupScratch(dir: string): Promise<void> {\n // Drop the node_modules LINK first and by name: recursive deletion around a\n // link to the real dependency tree deserves an explicit safety boundary.\n await unlink(join(dir, \"node_modules\")).catch(() => {});\n if (!process.env.OPEN_TAKE_KEEP_SCRATCH) {\n await rm(dir, { recursive: true, force: true });\n } else {\n process.stderr.write(`render scratch kept: ${dir}\\n`);\n }\n}\n\n/** Build the throwaway directory this render runs in: the package's `src/`\n * (the scene and everything it imports), this render's composition, the\n * normalised capture as vite's public asset, and a node_modules link. */\nasync function prepareScratch(composition: TakeComposition, videoPath: string): Promise<string> {\n const dir = await mkdtemp(join(tmpdir(), \"open-take-render-\"));\n try {\n await copyWritable(join(PKG_ROOT, \"src\"), join(dir, \"src\"));\n await writeFile(\n join(dir, \"src\", \"scene\", \".composition.json\"),\n JSON.stringify(composition, null, 2),\n );\n const nm = hostNodeModules();\n if (!nm) throw new Error(\"render: could not locate node_modules for the scene's imports\");\n // \"junction\" is the Windows directory link that doesn't need admin rights;\n // ignored on POSIX.\n await symlink(nm, join(dir, \"node_modules\"), \"junction\");\n // fps follows the composition: the render grid must match the source, or a\n // hi-fps capture is decimated before the scene ever sees it. Always H.264\n // here — the happy path — the decode-guard retry re-encodes as VP9 in\n // place when the render browser can't take it.\n await toMp4(videoPath, join(dir, \"public\", \"capture.mp4\"), composition.output.fps, \"h264\");\n return dir;\n } catch (error) {\n await cleanupScratch(dir);\n throw error;\n }\n}\n\n// process.chdir is process-global, so two renders in one process cannot run\n// concurrently no matter how isolated their directories are — the scratch dirs\n// remove the shared STATE, this removes the interleaving. (True parallelism\n// needs the renderer off cwd, or one child process per render.)\nlet renderQueue: Promise<unknown> = Promise.resolve();\n\nexport async function renderTake(opts: RenderTakeOpts): Promise<RenderTakeResult> {\n const run = renderQueue.then(\n () => renderTakeExclusive(opts),\n () => renderTakeExclusive(opts),\n );\n renderQueue = run.catch(() => {});\n return run;\n}\n\nasync function renderTakeExclusive(opts: RenderTakeOpts): Promise<RenderTakeResult> {\n if (!opts.chromePath) {\n throw new Error(\n \"renderTake: `chromePath` is required; use @open-take/runtime to resolve managed Chrome automatically\",\n );\n }\n const composition: TakeComposition =\n opts.composition ??\n planComposition(\n opts.log ??\n (() => {\n throw new Error(\"renderTake: provide `log` or `composition`\");\n })(),\n opts.planOpts,\n );\n\n // 0. validate BEFORE the expensive render. A hand-edited composition (the\n // refine loop) can carry a malformed zoom or a capture-locked tMs drift;\n // catch it in milliseconds rather than after a multi-second render.\n // Warnings are RETURNED as well as printed: this stderr line lands minutes\n // before the render finishes, so on its own it is scrolled past — the\n // caller re-prints them in the end-of-run summary, exactly as it already\n // does for skipped capture steps.\n const warnings: CompositionIssue[] = [];\n if (!opts.skipValidate) {\n const issues: CompositionIssue[] = validateComposition(composition, {\n captureLog: opts.captureLog ?? opts.log,\n });\n const errors = issues.filter((i) => i.severity === \"error\");\n warnings.push(...issues.filter((i) => i.severity === \"warn\"));\n if (opts.logProgress && warnings.length)\n process.stderr.write(`composition warnings:\\n${formatIssues(warnings)}\\n`);\n if (errors.length)\n throw new Error(\n `composition has ${errors.length} error(s) — refusing to render:\\n${formatIssues(errors)}`,\n );\n }\n\n // Head trim (composition.startMs): deliver the timeline from startMs on,\n // through the SAME range mechanism the A/B windows use — the composition\n // timeline (tMs, badges, keyframes) is untouched; only the delivered head\n // moves. An explicit rangeSec (an A/B clip window) wins: those windows are\n // authored on the composition timeline and already judged as clips.\n const rangeSec =\n opts.rangeSec ??\n (composition.startMs && composition.startMs > 0\n ? ([composition.startMs / 1000, composition.durationMs / 1000 + 120] as [number, number])\n : undefined);\n\n // Revideo spawns its bundled ffprobe directly. Repair installer permissions\n // here so published consumers are protected even though they do not run the\n // monorepo root's postinstall script.\n await repairBundledMediaPermissions();\n\n // 1. lay out this render's own directory (scene + composition + capture).\n // The intermediate starts as H.264; the decode-guard retry below swaps\n // it for VP9 when the render browser turns out not to decode it.\n const scratch = await prepareScratch(composition, opts.videoPath);\n const deps = depsRoot();\n // Resolved BEFORE the chdir below: the retry re-encode runs while cwd is\n // the scratch dir, where a relative videoPath would resolve wrongly.\n const videoAbs = resolve(opts.videoPath);\n try {\n // 2. render headless, with cwd pinned to the scratch dir.\n // revideo's @revideo/telemetry phones home to PostHog by default; this is an\n // all-local tool, so default it OFF (an explicit user-set value still wins).\n if (process.env.DISABLE_TELEMETRY === undefined) process.env.DISABLE_TELEMETRY = \"true\";\n\n // One attempt = one renderVideo call with its own no-progress hint timer.\n // A stuck render is SILENT: revideo's first progress tick fires only after\n // the first frame fully renders, and legitimate pre-roll can take tens of\n // seconds — so hint (never kill) when no tick has landed after 3 minutes.\n const renderOnce = async (): Promise<string> => {\n let noProgressTimer: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {\n process.stderr.write(\n \"open-take: no render progress after 3 minutes — if this never advances, the render browser may be stuck decoding the capture (see OPEN_TAKE_CHROME)\\n\",\n );\n }, 180_000);\n try {\n return await renderVideo({\n projectFile: \"/src/scene/project.ts\",\n settings: {\n outFile: \"take.mov\",\n outDir: RENDER_OUT,\n workers: 1,\n // ProRes 4444 intermediate, NOT revideo's default wasm exporter: the\n // wasm path encodes H.264 in-browser via WebCodecs at the browser's\n // default bitrate (mp4-wasm passes `bitrate: undefined`, and revideo\n // 0.11 exposes no knob) — at fps·samples that visibly softens fine\n // detail, screen-space caption/title text worst of all, before the\n // delivery encode ever runs. The ffmpeg exporter is fed lossless PNG\n // frames and prores_ks 4444 keeps them visually intact (4:4:4, no\n // DCT mush), leaving deliverMp4's CRF 18 as the single lossy\n // generation. Costs scratch disk (GBs at fps·samples for a long\n // take) and slower frame handoff — accepted for the master's text.\n projectSettings: {\n exporter: { name: \"@revideo/core/ffmpeg\", options: { format: \"proRes\" } },\n ...(rangeSec ? { range: rangeSec } : {}),\n },\n logProgress: opts.logProgress ?? false,\n // Wrapped even without opts.onProgress: the first tick proves the\n // browser is decoding frames, which disarms the no-progress hint.\n progressCallback: (_worker: number, progress: number) => {\n if (noProgressTimer !== undefined) {\n clearTimeout(noProgressTimer);\n noProgressTimer = undefined;\n }\n opts.onProgress?.(progress);\n },\n // vite's dev server refuses to serve outside its root, and its root is\n // now a tmp dir — so allow the dependency tree the scene imports\n // through the node_modules link (vite resolves it to the realpath).\n viteConfig: {\n server: { fs: { allow: [scratch, ...(deps ? [deps] : [])] } },\n },\n // Reuse the capture-managed Chrome-for-Testing for both stages.\n puppeteer: {\n // --password-store/--use-mock-keychain: never touch the OS keychain, so\n // macOS doesn't pop a \"Chrome wants to use Chromium Safe Storage\" prompt\n // mid-render (matches the capture launch in runtime/cdp.ts).\n args: [\n \"--no-sandbox\",\n \"--disable-setuid-sandbox\",\n \"--password-store=basic\",\n \"--use-mock-keychain\",\n ],\n executablePath: opts.chromePath,\n },\n },\n });\n } finally {\n if (noProgressTimer !== undefined) clearTimeout(noProgressTimer);\n }\n };\n\n const prevCwd = process.cwd();\n process.chdir(scratch);\n let produced: string;\n try {\n try {\n produced = await renderOnce();\n } catch (error) {\n // The scene's decode guard rejected: this browser cannot decode the\n // H.264 intermediate (Playwright-style Chromium ships no proprietary\n // codecs — before the guard, such a render hung forever; a real user\n // lost ~20 minutes to that silence). Re-encode the scratch capture as\n // VP9-in-MP4 and retry ONCE; without an ffmpeg that can, refuse with\n // the fix. Any other rejection rethrows untouched.\n if (!isCaptureUndecodable(error)) throw error;\n const detail = error instanceof Error ? error.message : String(error);\n if (!(await ffmpegHasEncoder(\"libvpx-vp9\"))) {\n throw new Error(\n `render: the browser at ${opts.chromePath} cannot decode the capture (${detail}) — ` +\n \"point OPEN_TAKE_CHROME at a full Chrome/Chrome-for-Testing build, or install an \" +\n \"ffmpeg with libvpx-vp9 to enable the VP9 fallback\",\n { cause: error },\n );\n }\n process.stderr.write(\n \"open-take: the render browser cannot decode the H.264 capture — retrying with a VP9 intermediate (output unchanged)\\n\",\n );\n await toMp4(\n videoAbs,\n join(scratch, \"public\", \"capture.mp4\"),\n composition.output.fps,\n \"vp9\",\n );\n try {\n produced = await renderOnce();\n } catch (retryError) {\n if (!isCaptureUndecodable(retryError)) throw retryError;\n const retryDetail = retryError instanceof Error ? retryError.message : String(retryError);\n throw new Error(\n `render: the browser at ${opts.chromePath} cannot decode the capture even as VP9 ` +\n `(${retryDetail}) — point OPEN_TAKE_CHROME at a full Chrome/Chrome-for-Testing build`,\n { cause: retryError },\n );\n }\n }\n } finally {\n process.chdir(prevCwd);\n }\n\n // 3. deliver the postable mp4 from the ProRes intermediate + the editable\n // composition. Motion blur (when configured) and the 601→709 colour\n // conversion both happen inside this single encode — see deliverMp4.\n await mkdir(dirname(resolve(opts.outPath)), { recursive: true });\n const producedAbs = resolve(scratch, produced);\n await deliverMp4(\n producedAbs,\n resolve(opts.outPath),\n composition.output.fps,\n motionBlurActive(composition.motionBlur) ? composition.motionBlur : null,\n );\n const compositionPath = opts.compositionPath\n ? resolve(opts.compositionPath)\n : `${resolve(opts.outPath).replace(/\\.mp4$/i, \"\")}.composition.json`;\n if (opts.writeCompositionSibling !== false) {\n // strip the render-time review decoration — the editable artifact is the\n // clean composition, never the badged/watermarked variant of it.\n const { review: _review, ...persisted } = composition;\n await mkdir(dirname(compositionPath), { recursive: true });\n await writeFile(compositionPath, JSON.stringify(persisted, null, 2));\n }\n\n return { mp4Path: resolve(opts.outPath), compositionPath, warnings, composition };\n } finally {\n await cleanupScratch(scratch);\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,IAAIA;AACJ,IAAIC;AAEJ,SAAS,OAAOC,KAAsB;AACpC,KAAI;AACF,SAAO,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