@open-take/runtime 0.2.6 → 0.2.8

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["a: Uint8Array","b: Uint8Array","w: number","h: number","before: Uint8Array","after: Uint8Array","ambient?: Uint8Array","cx: number","cy: number","bin: string","videoPath: string","tSec: number","aw: number","ah: number","chunks: Buffer[]","b: Buffer","log: CaptureLog","opts: AnnotateOpts","p: string","input: string","base","take: TakePaths","opts: { capture?: boolean }","mp4Path: string","prevPath: string","capturePath: string","KIND_LABEL: Record<CompEvent[\"kind\"], string>","e: CompEvent","s: string","n: number","ms: number","comp: TakeComposition","name: string","lines: string[]","badges: ReviewBadge[]","take: TakePaths","opts: ReviewOpts","decorated: TakeComposition","set: string","beat?: number","path: string","raw: string","value: unknown","node: Record<string, unknown>","knob: AbKnob","node: unknown","value: string","comps: TakeComposition[]","beat: number | undefined","full: boolean","nextStart: number | undefined","opts: AbOpts","variants: AbVariant[]","clips: string[]","opts: { beat?: number; full?: boolean }","src: string","out: string","args: string[]","outPath: string","v: { width: number; height: number; fps: number }","seq: string[]","spec: OpenerCommand","fallbackLine: string","target: string","platform: NodeJS.Platform","absolutePath: string","p: string","CONTENT_TYPE: Record<string, string>","dir: string","path: string","res: ServerResponse","status: number","obj: unknown","req: IncomingMessage","chunks: Buffer[]","filePath: string","url: string","opts: EditServerOpts","deps: EditServerDeps","job: RenderJob | null","writeLock: Promise<unknown>","fn: () => Promise<T>","run","comp: TakeComposition","baseMtime: number | undefined","parsed: unknown","url","i: CompositionIssue","j: RenderJob","captureLog: CaptureLog | undefined","event: string","data: unknown","server: ReturnType<typeof createServer>","startPort: number","e: NodeJS.ErrnoException","comp: TakeComposition","from: number","to: number","n: number","opts: { beat?: number }","notes: string[]","t: number","rows: FrameRow[]","cells: FrameCell[]","cmd: string","args: string[]","path: string","ms: number","plan: FramePlan","framesPath: string","trimMs: number","tileW?: number","take: TakePaths","opts: FramesOpts","ffmpeg","outPath: string","capturePath: string","plan: TakePlan","opts: MakeTakeOpts","opts: RenderCompositionOpts","opts: {\n compositionPath: string;\n capturePath: string;\n outPath: string;\n /** explicit capture-log path; default = the sibling of capturePath; null skips */\n captureLogPath?: string | null;\n logProgress?: boolean;\n chromePath?: string;\n onProgress?: (progress: number) => void;\n}"],"sources":["../src/frame-diff.ts","../src/take.ts","../src/review.ts","../src/edit-server.ts","../src/frames.ts","../src/index.ts"],"sourcesContent":["// Tier-2 capture annotation: AFTER a capture, diff the recording's frames\n// around each action to record what the action actually CHANGED on screen —\n// `effectBox` (the changed region, viewport px) and `changeCoverage` (fraction\n// of the frame affected). The camera director (compositor/src/camera.ts)\n// consumes these to (a) frame the PAYOFF instead of the clicked control when\n// the result lands somewhere else, and (b) tell a global repaint (nav /\n// restyle → pull out to full view) from a local popover — a bbox alone can't.\n//\n// This is the pass camera.ts's header defers to \"the runtime (node) layer\":\n// pixels, not DOM. Frame-diff over the kept capture needs no browser hooks,\n// works for canvas apps a MutationObserver can't see, and is deterministic\n// over the recording (re-runnable on old takes).\n//\n// Failure-tolerant BY CONTRACT: annotation must never fail a take. Any ffmpeg\n// error / short read / degenerate window skips that event (fields stay absent\n// — the director falls back to its bbox heuristics, exactly the pre-tier-2\n// behaviour) and `annotateCaptureLog` never throws.\n\nimport { spawn } from \"node:child_process\";\nimport { resolveFfmpeg } from \"@open-take/compositor\";\nimport type { BBox, CaptureLog } from \"@open-take/compositor\";\n\n// Analysis raster: frames are decoded grayscale at ~ANALYSIS_W wide. 16px cells\n// on that raster (≈32px at 1080p) are the change unit — coarse enough that\n// h264 noise and a blinking caret vanish, fine enough to frame a suggestion\n// panel. Bumping ANALYSIS_W raises precision and cost together.\nconst ANALYSIS_W = 960;\nconst CELL = 16;\n/** min |gray delta| for a pixel to count as changed (h264 noise is ~2–6) */\nconst PIXEL_DELTA = 16;\n/** a cell is \"changed\" when > this fraction of its pixels changed */\nconst CELL_FRAC = 0.08;\n\n/** sample the \"before\" state this long before the action (ms). Kept TIGHT so\n * everything that happens on the approach — the capture's own\n * scrollIntoView, hover styles, the previous action's tail — is already\n * painted and therefore NOT attributed to this action; a click's own effect\n * can't land within one 60fps frame of the input, so this still precedes it.\n * (Also < NEXT_CLEARANCE_MS, so adjacent events' windows can never overlap —\n * no double attribution.) */\nconst BEFORE_MS = 30;\n/** sample the \"after\" state this long after the action (+durationMs) settles —\n * catches popover/reveal animations (ms; the capture itself sleeps ~1s\n * between actions, so there is normally room). */\nconst SETTLE_MS = 500;\n/** third sample this long after the \"after\" frame: cells STILL changing\n * between the two are ambient motion (hero video, carousel, streaming text)\n * — masked out of the action's diff so they can't poison effectBox (ms). */\nconst AMBIENT_MS = 250;\n/** keep this much clearance before the NEXT action so its changes are never\n * attributed to this one (ms). */\nconst NEXT_CLEARANCE_MS = 60;\n/** a box-less event (bare press) only gets an effectBox when the change is at\n * least this big — a blinking terminal cursor must not become a phantom\n * punch target on an event that used to mean \"full view\". */\nconst MIN_NO_BOX_COVERAGE = 0.015;\n\nexport type FrameDiffResult = {\n /** fraction of the frame's cells that changed (0..1) */\n coverage: number;\n /** bbox of the changed region in ANALYSIS-raster px, or undefined when\n * nothing beyond isolated specks changed */\n box?: BBox;\n};\n\n/** per-cell changed-pixel counts of |before−after| > PIXEL_DELTA (symmetric —\n * appearing light-on-dark content matters as much as dark-on-light). */\nfunction cellCounts(a: Uint8Array, b: Uint8Array, w: number, h: number): Uint16Array {\n const cw = Math.ceil(w / CELL);\n const counts = new Uint16Array(cw * Math.ceil(h / CELL));\n for (let y = 0; y < h; y++) {\n const row = y * w;\n const crow = Math.floor(y / CELL) * cw;\n for (let x = 0; x < w; x++) {\n const d = a[row + x]! - b[row + x]!;\n if (d > PIXEL_DELTA || d < -PIXEL_DELTA) counts[crow + Math.floor(x / CELL)]!++;\n }\n }\n return counts;\n}\n\n/**\n * Pure diff of two grayscale frames (same w×h). Cell-based: a cell counts as\n * changed when enough of its pixels moved. An isolated changed cell (no\n * changed 8-neighbour) is kept only when it changed OVERWHELMINGLY (≥ half its\n * pixels — a real single-cell payoff like a cart badge), else it's a speck\n * (caret blink, cursor sliver) and is dropped.\n *\n * `ambient` (optional) is a THIRD frame sampled shortly after `after`: any\n * cell still changing between `after` and `ambient` is ambient motion (hero\n * video, carousel, streaming text) and is excluded — without this, one\n * animating region would poison every event's effectBox with its union.\n *\n * `coverage` is the changed-CELL area fraction — the region the action\n * affected — deliberately not the changed-PIXEL fraction: a nav swap between\n * two white-ish pages repaints most of the frame while leaving most PIXELS\n * white-on-white, and it's the affected region the director's pull-out\n * threshold reasons about.\n */\nexport function diffFrames(\n before: Uint8Array,\n after: Uint8Array,\n w: number,\n h: number,\n ambient?: Uint8Array,\n): FrameDiffResult {\n const cw = Math.ceil(w / CELL);\n const ch = Math.ceil(h / CELL);\n const counts = cellCounts(before, after, w, h);\n const minCount = Math.max(1, Math.floor(CELL * CELL * CELL_FRAC));\n const strongCount = Math.floor(CELL * CELL * 0.5);\n const ambientCounts = ambient ? cellCounts(after, ambient, w, h) : undefined;\n const changed = (cx: number, cy: number): boolean =>\n cx >= 0 &&\n cy >= 0 &&\n cx < cw &&\n cy < ch &&\n counts[cy * cw + cx]! >= minCount &&\n (!ambientCounts || ambientCounts[cy * cw + cx]! < minCount);\n\n let kept = 0;\n let x0 = cw;\n let y0 = ch;\n let x1 = -1;\n let y1 = -1;\n for (let cy = 0; cy < ch; cy++) {\n for (let cx = 0; cx < cw; cx++) {\n if (!changed(cx, cy)) continue;\n let neighbour = counts[cy * cw + cx]! >= strongCount; // strong cells stand alone\n for (let dy = -1; dy <= 1 && !neighbour; dy++)\n for (let dx = -1; dx <= 1; dx++) {\n if (dx === 0 && dy === 0) continue;\n if (changed(cx + dx, cy + dy)) {\n neighbour = true;\n break;\n }\n }\n if (!neighbour) continue; // isolated speck\n kept++;\n if (cx < x0) x0 = cx;\n if (cy < y0) y0 = cy;\n if (cx > x1) x1 = cx;\n if (cy > y1) y1 = cy;\n }\n }\n if (kept === 0) return { coverage: 0 };\n return {\n coverage: kept / (cw * ch),\n box: {\n x: x0 * CELL,\n y: y0 * CELL,\n w: Math.min((x1 + 1) * CELL, w) - x0 * CELL,\n h: Math.min((y1 + 1) * CELL, h) - y0 * CELL,\n },\n };\n}\n\n/** Decode ONE grayscale frame at time `tSec` from `videoPath`, scaled to\n * aw×ah. Resolves undefined on any failure (missing frame near EOF, etc.). */\nfunction grabFrame(\n bin: string,\n videoPath: string,\n tSec: number,\n aw: number,\n ah: number,\n): Promise<Uint8Array | undefined> {\n return new Promise((res) => {\n const args = [\n \"-v\",\n \"error\",\n \"-ss\",\n tSec.toFixed(3),\n \"-i\",\n videoPath,\n \"-frames:v\",\n \"1\",\n \"-vf\",\n `scale=${aw}:${ah}`,\n \"-f\",\n \"rawvideo\",\n \"-pix_fmt\",\n \"gray\",\n \"-\",\n ];\n const c = spawn(bin, args, { stdio: [\"ignore\", \"pipe\", \"ignore\"] });\n const chunks: Buffer[] = [];\n c.stdout.on(\"data\", (b: Buffer) => chunks.push(b));\n c.on(\"error\", () => res(undefined));\n c.on(\"close\", () => {\n const buf = Buffer.concat(chunks);\n res(buf.length === aw * ah ? new Uint8Array(buf) : undefined);\n });\n });\n}\n\nexport type AnnotateOpts = {\n /** explicit ffmpeg binary; resolved via the compositor's resolver if omitted */\n ffmpegBin?: string;\n logProgress?: boolean;\n};\n\n/**\n * Annotate a capture log with per-event `effectBox` + `changeCoverage` by\n * diffing the capture video around each action. Returns a NEW log (input\n * untouched); events whose diff fails or whose sample window is degenerate are\n * returned unchanged. Never throws.\n */\nexport async function annotateCaptureLog(\n log: CaptureLog,\n videoPath: string,\n opts: AnnotateOpts = {},\n): Promise<CaptureLog> {\n try {\n const bin = opts.ffmpegBin ?? (await resolveFfmpeg());\n const vW = log.video.width;\n const vH = log.video.height;\n if (!(vW > 0) || !(vH > 0)) return log;\n const aw = Math.min(ANALYSIS_W, vW);\n const ah = Math.max(CELL, Math.round((vH * aw) / vW));\n // map analysis-raster px → viewport CSS px (what effectBox is declared in)\n const mx = log.viewport.w / aw;\n const my = log.viewport.h / ah;\n const durS = log.video.durationS ?? (log.tEndMs != null ? log.tEndMs / 1000 : undefined);\n\n const events = [...log.events];\n for (let i = 0; i < events.length; i++) {\n const e = events[i]!;\n const durationMs = \"durationMs\" in e && e.durationMs != null ? e.durationMs : 0;\n const before = Math.max(0, (e.tMs - BEFORE_MS) / 1000);\n let after = (e.tMs + durationMs + SETTLE_MS) / 1000;\n const next = events[i + 1];\n const ceil = Math.min(\n next ? (next.tMs - NEXT_CLEARANCE_MS) / 1000 : Number.POSITIVE_INFINITY,\n // never sample past the recording's end (the last frame would repeat —\n // fine — but a seek past EOF returns nothing)\n durS != null ? Math.max(0, durS - 0.05) : Number.POSITIVE_INFINITY,\n );\n after = Math.min(after, ceil);\n if (after <= before + 0.05) continue; // degenerate window — skip\n // ambient sample: only when it fits before the next action / EOF —\n // without room we go unmasked rather than sample another event's effect\n const ambientT = after + AMBIENT_MS / 1000;\n const wantAmbient = ambientT <= ceil;\n const [fa, fb, fc] = await Promise.all([\n grabFrame(bin, videoPath, before, aw, ah),\n grabFrame(bin, videoPath, after, aw, ah),\n wantAmbient ? grabFrame(bin, videoPath, ambientT, aw, ah) : Promise.resolve(undefined),\n ]);\n if (!fa || !fb) continue;\n const d = diffFrames(fa, fb, aw, ah, fc);\n // a box-less event (bare press) only gets an effectBox for a substantial\n // change — else a blinking cursor becomes a phantom punch target\n const hasBox = \"box\" in e && e.box != null;\n const attachBox = d.box && (hasBox || d.coverage >= MIN_NO_BOX_COVERAGE);\n events[i] = {\n ...e,\n changeCoverage: Math.round(d.coverage * 1000) / 1000,\n ...(attachBox && d.box\n ? {\n effectBox: {\n x: Math.round(d.box.x * mx),\n y: Math.round(d.box.y * my),\n w: Math.round(d.box.w * mx),\n h: Math.round(d.box.h * my),\n },\n }\n : {}),\n };\n if (opts.logProgress) {\n const eb = events[i]!.effectBox;\n // coverage 0 is sub-THRESHOLD, not proof of a dead beat: a 1px outline\n // or low-opacity highlight diffs below the noise floor and is often\n // visually fine — point the reader at the frames, not the number.\n const subThreshold =\n events[i]!.changeCoverage === 0 && !eb\n ? \" (sub-threshold — a subtle effect can score 0; judge by frames)\"\n : \"\";\n process.stderr.write(\n `frame-diff [${i}] ${e.kind ?? \"click\"}@${e.tMs}ms coverage=${events[i]!.changeCoverage}${\n eb ? ` effect=(${eb.x},${eb.y} ${eb.w}x${eb.h})` : \"\"\n }${subThreshold}\\n`,\n );\n }\n }\n return { ...log, events };\n } catch {\n return log; // annotation must never fail a take\n }\n}\n","// Take path resolution + prev snapshot — the file conventions behind the\n// conversational refine loop. A \"take\" is the artifact family makeTake writes\n// beside `<base>.mp4`; every CLI verb accepts any member of the family (or the\n// directory holding one) and resolves the rest by convention.\n\nimport { copyFile, readdir, rename, rm, stat } from \"node:fs/promises\";\nimport { basename, join, resolve } from \"node:path\";\n\nexport type TakePaths = {\n /** shared path prefix (no extension) */\n base: string;\n name: string;\n /** `<base>.mp4` — the polished, postable master */\n mp4Path: string;\n compositionPath: string;\n capturePath: string;\n captureLogPath: string;\n /** `<base>.review.mp4` — draft copy with burned beat badges (disposable) */\n reviewPath: string;\n /** `<base>.draft.mp4` — clean draft-quality re-render (disposable; never\n * clobbers the postable master) */\n draftPath: string;\n /** `<base>.ab.mp4` — the A/B variant reel (disposable) */\n abPath: string;\n /** `<base>.prev.mp4` — the previous master, kept so \"A\" can mean revert */\n prevPath: string;\n /** `<base>.dossier.md` — the agent's persisted exploration harvest (app\n * thesis, hero candidates tried/rejected, selector map, content answers,\n * hazards). Read it before re-exploring; it survives re-makes. */\n dossierPath: string;\n};\n\nasync function isFile(p: string): Promise<boolean> {\n return (await stat(p).catch(() => null))?.isFile() ?? false;\n}\n\n/** Strip any known take suffix to get the shared base, then derive the family.\n * A directory picks the `*.composition.json` that has a sibling capture. */\nexport async function resolveTakePaths(input: string): Promise<TakePaths> {\n let p = resolve(input);\n const s = await stat(p).catch(() => null);\n if (s?.isDirectory()) {\n // `<base>.prev.composition.json` is a pre-re-make snapshot, never a take.\n const comps = (await readdir(p)).filter(\n (e) => /\\.composition\\.json$/i.test(e) && !/\\.prev\\.composition\\.json$/i.test(e),\n );\n if (comps.length === 0) throw new Error(`no *.composition.json found in ${p}`);\n let pick = comps[0]!;\n for (const c of comps) {\n const base = join(p, c.replace(/\\.composition\\.json$/i, \"\"));\n if (await isFile(`${base}.capture.mp4`)) {\n pick = c;\n break;\n }\n }\n p = join(p, pick);\n }\n const base = p\n .replace(/\\.dossier\\.md$/i, \"\")\n .replace(/\\.prev\\.composition\\.json$/i, \"\")\n .replace(/\\.composition\\.json$/i, \"\")\n .replace(/\\.capture\\.json$/i, \"\")\n .replace(/\\.capture\\.mp4$/i, \"\")\n .replace(/\\.review\\.mp4$/i, \"\")\n .replace(/\\.draft\\.mp4$/i, \"\")\n .replace(/\\.ab\\.mp4$/i, \"\")\n .replace(/\\.prev\\.mp4$/i, \"\")\n .replace(/\\.mp4$/i, \"\");\n return {\n base,\n name: basename(base),\n mp4Path: `${base}.mp4`,\n compositionPath: `${base}.composition.json`,\n capturePath: `${base}.capture.mp4`,\n captureLogPath: `${base}.capture.json`,\n reviewPath: `${base}.review.mp4`,\n draftPath: `${base}.draft.mp4`,\n abPath: `${base}.ab.mp4`,\n prevPath: `${base}.prev.mp4`,\n dossierPath: `${base}.dossier.md`,\n };\n}\n\n/** Friendly preflight: verbs die with a clear message instead of a raw ffmpeg\n * ENOENT when a take is missing the files they need. Old takes (or cleaned\n * ones) may have a composition + mp4 but no kept capture — those can be\n * watched but not re-rendered. */\nexport async function requireTakeFiles(\n take: TakePaths,\n opts: { capture?: boolean } = {},\n): Promise<void> {\n if (!(await isFile(take.compositionPath)))\n throw new Error(\n `missing ${take.compositionPath} — not a take produced by \\`make\\` (or the wrong path)`,\n );\n if (opts.capture && !(await isFile(take.capturePath)))\n throw new Error(\n `this take has no kept capture (${take.capturePath}) — re-rendering needs the frozen recording.\\n` +\n `Takes made before capture-keeping (or cleaned up) can't be re-rendered; run \\`make\\` again for a refinable take.`,\n );\n}\n\nexport type StagedPrev = {\n /** call after the render SUCCEEDS: the staged copy becomes `<base>.prev.mp4` */\n commit: () => Promise<void>;\n /** call when the render fails/refuses: discard the staged copy, keeping the\n * existing prev intact */\n abort: () => Promise<void>;\n};\n\n/** Stage a copy of the current master so it becomes `<base>.prev.mp4` only\n * AFTER the next render succeeds. A refused (validator) or crashed render\n * must NOT clobber the existing revert point — that would make \"keep the old\n * one\" replay the wrong version. No-op when there is no master yet. This is\n * what makes \"A\" (keep the old one) a mechanical revert instead of a memory. */\nexport async function stagePrev(mp4Path: string, prevPath: string): Promise<StagedPrev> {\n if (!(await isFile(mp4Path))) return { commit: async () => {}, abort: async () => {} };\n const pending = `${prevPath}.pending`;\n await copyFile(mp4Path, pending);\n return {\n commit: () => rename(pending, prevPath),\n abort: () => rm(pending, { force: true }),\n };\n}\n","// The conversational refine surface: beat sheets, badged review copies, and\n// A/B variant reels. No GUI — the system video player shows purpose-built\n// artifacts and the terminal (agent) is the only input channel.\n//\n// beats — a numbered stdout table: the shared map for \"beat 3: no zoom\"\n// review — `<base>.review.mp4`: fast draft with beat badges burned in\n// (the video itself teaches the referring vocabulary) + watermark\n// ab — `<base>.ab.mp4`: ONE knob, 2-4 labeled variants, each played\n// twice — a taste question answered with one letter\n//\n// Badges/labels are drawn by the revideo scene in Chrome (composition.review),\n// NOT by ffmpeg drawtext — slim ffmpeg builds ship without font filters.\n\nimport { spawn } from \"node:child_process\";\nimport { readFile, rm, stat } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport {\n type CaptureLog,\n type CompEvent,\n FINISH,\n type FinishName,\n LOOKS,\n type LookName,\n MOTION,\n type MotionName,\n type ReviewBadge,\n type TakeComposition,\n ZOOM_LEVELS,\n type ZoomLevelName,\n finishName,\n formatIssues,\n lookName,\n math,\n motionName,\n renderTake,\n resolveFfmpeg,\n validateComposition,\n zoomLevelName,\n} from \"@open-take/compositor\";\nimport { ensureChrome } from \"./cdp\";\nimport { type TakePaths, requireTakeFiles } from \"./take\";\n\n/** Sibling capture log (`<capture>.json`), if present — enables the\n * capture-lock check; silently absent otherwise (matches index.ts). */\nasync function loadLogSibling(capturePath: string): Promise<CaptureLog | undefined> {\n try {\n return JSON.parse(\n await readFile(resolve(capturePath).replace(/\\.mp4$/i, \".json\"), \"utf8\"),\n ) as CaptureLog;\n } catch {\n return undefined;\n }\n}\n\n// --- shared formatting -------------------------------------------------------\n\nconst KIND_LABEL: Record<CompEvent[\"kind\"], string> = {\n click: \"click\",\n type: \"type\",\n drag: \"drag\",\n scroll: \"scroll\",\n hover: \"hover\",\n press: \"key\",\n};\n\nfunction beatTitle(e: CompEvent): string {\n if (e.label) return e.label;\n if (e.kind === \"type\" && e.text) return `\"${e.text}\"`;\n if (e.kind === \"press\" && e.keys) return e.keys;\n return e.kind;\n}\n\nconst trunc = (s: string, n: number): string => (s.length > n ? `${s.slice(0, n - 1)}…` : s);\n\n/** \"click Open menu\" — the shared beat vocabulary (beat sheet rows, frames rows). */\nexport function beatLabel(e: CompEvent): string {\n return `${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)}`;\n}\n\nfunction fmtTime(ms: number): string {\n const s = Math.max(0, Math.round(ms / 1000));\n return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, \"0\")}`;\n}\n\n/** \"zoom medium (×1.5)\" | \"zoom ×1.85 (custom)\" | \"wide\" */\nfunction zoomText(e: CompEvent): string {\n if (!e.zoom.enabled) return \"wide\";\n const name = zoomLevelName(e.zoom.scale);\n const x = `×${Number(e.zoom.scale.toFixed(2))}`;\n return name ? `zoom ${name} (${x})` : `zoom ${x} (custom)`;\n}\n\n// --- the beat sheet ----------------------------------------------------------\n\nexport function buildBeatSheet(comp: TakeComposition, name: string): string {\n const n = comp.events.length;\n const look = lookName(comp.framing) ?? \"custom\";\n const pace = motionName(comp.cursor) ?? \"custom\";\n const finish = finishName(comp.motionBlur) ?? \"custom\";\n const trim = comp.startMs ?? 0;\n const lines: string[] = [\n `${name} · ${((comp.durationMs - trim) / 1000).toFixed(1)}s · ${n} beat${n === 1 ? \"\" : \"s\"} · look ${look} · pace ${pace} · finish ${finish}${trim ? ` · head −${(trim / 1000).toFixed(1)}s` : \"\"}`,\n ];\n const first = comp.events[0];\n if (!first || first.zoom.inAtMs > 400) lines.push(` in 0:00 full view, cursor glides in`);\n comp.events.forEach((e, i) => {\n const num = String(i + 1).padStart(2, \" \");\n const kind = KIND_LABEL[e.kind].padEnd(6, \" \");\n const title = trunc(beatTitle(e), 24).padEnd(25, \" \");\n lines.push(` ${num} ${fmtTime(e.tMs)} ${kind} ${title} ${zoomText(e)}`);\n });\n const last = comp.events[n - 1];\n if (last) {\n const endMs = last.tMs + (last.durationMs ?? 0) + comp.cursor.holdMs;\n lines.push(` out ${fmtTime(endMs)} zoom releases, holds to ${fmtTime(comp.durationMs)}`);\n }\n lines.push(\n `say it like: \"beat 2: no zoom\" · \"tighter on beat 3\" · \"look: slate\" · \"pace: brisk\"`,\n );\n return lines.join(\"\\n\");\n}\n\nexport const SAY_IT_CARD = `SAY IT, I'LL CUT IT\n instant (~10s) zoom off / tighter / looser on a beat · re-center a beat (name the\n element) · hold longer · pace: calm / natural / brisk · look:\n midnight / ink / slate / ocean / plum / ember / paper / plain ·\n finish: smooth / crisp / heavy · quicker intro · shorter tail\n re-shoot (~1m) change what's clicked or typed · add / cut / reorder beats ·\n retime an action\n compare taste questions come back as an A/B reel — answer with a letter\n (\"B\"), or \"between A and B\", or \"none, go darker\"`;\n\n// --- review copy -------------------------------------------------------------\n\n/** Badge windows: each beat owns [its camera-ramp start, the next beat's) —\n * the pill swaps as the camera actually starts moving toward the beat.\n * Timing comes from the REAL schedule (cameraRampSchedule), so a\n * dwell-delayed pull-out (departing after its stored inAtMs) badges when it\n * moves, not when the formula guessed; beats the camera holds through fall\n * back to inAtMs. INTRO/TAIL bracket them. */\nexport function buildBadges(comp: TakeComposition): ReviewBadge[] {\n const n = comp.events.length;\n const badges: ReviewBadge[] = [];\n const ramps = math.cameraRampSchedule(comp);\n let prevStart = 0;\n const starts = comp.events.map((e, i) => {\n const s = Math.max(ramps[i]?.startMs ?? e.zoom.inAtMs, prevStart + 1);\n prevStart = s;\n return s;\n });\n if (n === 0 || starts[0]! > 400)\n badges.push({ fromMs: 0, toMs: starts[0] ?? comp.durationMs, text: \"INTRO\" });\n comp.events.forEach((e, i) => {\n const last = i === n - 1;\n // a dwell-delayed landing can put the arrival after tMs — own the badge\n // window until the action AND the camera have both settled.\n const arrived = Math.max(e.tMs, ramps[i]?.landMs ?? e.tMs);\n const endOwn = arrived + (e.durationMs ?? 0) + comp.cursor.holdMs;\n const to = last ? Math.min(endOwn, comp.durationMs) : starts[i + 1]!;\n badges.push({\n fromMs: starts[i]!,\n toMs: to,\n text: `BEAT ${i + 1}/${n} · ${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)} · ${zoomText(e)}`,\n });\n if (last && to < comp.durationMs + 1000)\n badges.push({ fromMs: to, toMs: comp.durationMs + 1500, text: \"TAIL\" });\n });\n return badges;\n}\n\n/** Draft-quality transform: 30fps cap + motion blur OFF — up to ~12× faster\n * than a blurred 60fps master, close enough for composition-level notes.\n * (2 blur samples would render 2× the frames for a tmix window that rounds to\n * 1 — all cost, zero blur.) FEEL questions (blur, pace, zoom silkiness) must\n * be judged on full quality — use `ab`. */\nexport function toDraft(comp: TakeComposition): TakeComposition {\n const { motionBlur: _mb, ...rest } = comp;\n return { ...rest, output: { ...comp.output, fps: Math.min(30, comp.output.fps) } };\n}\n\nexport type ReviewOpts = {\n chromePath?: string;\n logProgress?: boolean;\n};\n\nexport async function renderReview(\n take: TakePaths,\n opts: ReviewOpts = {},\n): Promise<{ reviewPath: string; sheet: string }> {\n await requireTakeFiles(take, { capture: true });\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const captureLog = await loadLogSibling(take.capturePath);\n const chromePath = await ensureChrome(opts.chromePath);\n const decorated: TakeComposition = {\n ...toDraft(comp),\n review: { watermark: \"REVIEW\", badges: buildBadges(comp) },\n };\n await renderTake({\n composition: decorated,\n videoPath: take.capturePath,\n outPath: take.reviewPath,\n captureLog,\n logProgress: opts.logProgress ?? true,\n chromePath,\n writeCompositionSibling: false,\n });\n return { reviewPath: take.reviewPath, sheet: buildBeatSheet(comp, take.name) };\n}\n\n/** Draft-quality re-render of the CURRENT composition to `<base>.draft.mp4` —\n * no badges, no watermark, and never the master's path, so a mid-refine\n * frame-check (edit → draft → `frames`) costs seconds without downgrading or\n * clobbering the postable mp4. Disposable like the review copy. */\nexport async function renderDraft(\n take: TakePaths,\n opts: ReviewOpts = {},\n): Promise<{ draftPath: string }> {\n await requireTakeFiles(take, { capture: true });\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const captureLog = await loadLogSibling(take.capturePath);\n const chromePath = await ensureChrome(opts.chromePath);\n await renderTake({\n composition: toDraft(comp),\n videoPath: take.capturePath,\n outPath: take.draftPath,\n captureLog,\n logProgress: opts.logProgress ?? true,\n chromePath,\n writeCompositionSibling: false,\n });\n return { draftPath: take.draftPath };\n}\n\n// --- A/B variant reels -------------------------------------------------------\n\nexport type AbKnob =\n | { kind: \"zoom\"; beat: number } // 1-based beat number\n | { kind: \"look\" }\n | { kind: \"pace\" }\n | { kind: \"finish\" }\n | { kind: \"path\"; path: string }; // raw dot-path escape hatch (agent use)\n\nexport type AbVariant = { letter: string; desc: string; comp: TakeComposition };\n\nexport function parseSetFlag(set: string, beat?: number): { knob: AbKnob; values: string[] } {\n const eq = set.indexOf(\"=\");\n if (eq < 1) throw new Error(`ab: --set expects <knob>=<v1>,<v2>[,<v3>] (got \"${set}\")`);\n const key = set.slice(0, eq).trim();\n const values = set\n .slice(eq + 1)\n .split(\",\")\n .map((v) => v.trim())\n .filter(Boolean);\n if (values.length < 1) throw new Error(`ab: --set ${key}= needs at least one value`);\n if (values.length > 3) throw new Error(`ab: at most 3 requested values (plus current) per reel`);\n if (key === \"zoom\") {\n if (!beat) throw new Error(`ab: --set zoom=… needs --beat <n> (which beat to reframe)`);\n return { knob: { kind: \"zoom\", beat }, values };\n }\n if (key === \"look\" || key === \"pace\" || key === \"finish\") return { knob: { kind: key }, values };\n if (key.includes(\".\")) return { knob: { kind: \"path\", path: key }, values };\n throw new Error(\n `ab: unknown knob \"${key}\" — use zoom (with --beat), look, pace, finish, or a raw dot-path like cursor.holdMs`,\n );\n}\n\nfunction setPath(comp: TakeComposition, path: string, raw: string): TakeComposition {\n // coerce booleans/null BEFORE the number check — a string \"false\" is truthy,\n // which would silently leave e.g. zoom.enabled ON while the variant label\n // claims otherwise (a reel comparing two identical clips).\n const t = raw.trim();\n const value: unknown =\n t === \"true\"\n ? true\n : t === \"false\"\n ? false\n : t === \"null\"\n ? null\n : Number.isFinite(Number(raw)) && t !== \"\"\n ? Number(raw)\n : raw;\n const parts = path.split(\".\");\n const next = structuredClone(comp) as unknown as Record<string, unknown>;\n let node: Record<string, unknown> = next;\n for (const p of parts.slice(0, -1)) {\n const child = node[p];\n if (typeof child !== \"object\" || child == null)\n throw new Error(`ab: path \"${path}\" — \"${p}\" is not an object`);\n node = child as Record<string, unknown>;\n }\n node[parts[parts.length - 1]!] = value;\n return next as unknown as TakeComposition;\n}\n\n/** Current-state description for a knob (the implicit \"keep it\" variant). */\nfunction currentDesc(comp: TakeComposition, knob: AbKnob): string {\n if (knob.kind === \"zoom\") {\n const e = comp.events[knob.beat - 1];\n return e ? zoomText(e) : \"?\";\n }\n if (knob.kind === \"look\") return lookName(comp.framing) ?? \"custom look\";\n if (knob.kind === \"pace\") return motionName(comp.cursor) ?? \"custom pace\";\n if (knob.kind === \"finish\") return finishName(comp.motionBlur) ?? \"custom finish\";\n const parts = knob.path.split(\".\");\n let node: unknown = comp;\n for (const p of parts) node = (node as Record<string, unknown> | undefined)?.[p];\n return `${knob.path}=${JSON.stringify(node)}`;\n}\n\nfunction applyKnob(comp: TakeComposition, knob: AbKnob, value: string): TakeComposition {\n if (knob.kind === \"zoom\") {\n const i = knob.beat - 1;\n const e = comp.events[i];\n if (!e) throw new Error(`ab: --beat ${knob.beat} out of range (1-${comp.events.length})`);\n const events = comp.events.slice();\n if (value === \"off\" || value === \"wide\") {\n events[i] = { ...e, zoom: { ...e.zoom, enabled: false } };\n } else {\n const scale = value in ZOOM_LEVELS ? ZOOM_LEVELS[value as ZoomLevelName] : Number(value);\n if (!Number.isFinite(scale))\n throw new Error(`ab: zoom value \"${value}\" — use off/light/medium/tight/close or a number`);\n events[i] = { ...e, zoom: { ...e.zoom, enabled: true, scale } };\n }\n return { ...comp, events };\n }\n if (knob.kind === \"look\") {\n const look = LOOKS[value as LookName];\n if (!look)\n throw new Error(`ab: unknown look \"${value}\" — one of ${Object.keys(LOOKS).join(\"/\")}`);\n return { ...comp, framing: { ...comp.framing, ...structuredClone(look) } };\n }\n if (knob.kind === \"pace\") {\n const pace = MOTION[value as MotionName];\n if (!pace)\n throw new Error(`ab: unknown pace \"${value}\" — one of ${Object.keys(MOTION).join(\"/\")}`);\n // zoomInMs only affects rendering through each beat's zoom.inAtMs (derived\n // at plan time as tMs − zoomInMs). Rebase events still sitting on the OLD\n // derivation so the new pace actually changes the zoom ramps; hand-tuned\n // inAtMs values are left alone.\n const oldZoomInMs = comp.cursor.zoomInMs;\n const events = comp.events.map((e) =>\n e.zoom.inAtMs === Math.max(0, e.tMs - oldZoomInMs)\n ? { ...e, zoom: { ...e.zoom, inAtMs: Math.max(0, e.tMs - pace.zoomInMs) } }\n : e,\n );\n return { ...comp, events, cursor: { ...comp.cursor, ...pace } };\n }\n if (knob.kind === \"finish\") {\n if (!(value in FINISH))\n throw new Error(`ab: unknown finish \"${value}\" — one of ${Object.keys(FINISH).join(\"/\")}`);\n const mb = FINISH[value as FinishName];\n const { motionBlur: _mb, ...rest } = comp;\n return mb ? { ...rest, motionBlur: { ...mb } } : rest;\n }\n return setPath(comp, knob.path, value);\n}\n\nfunction variantDesc(knob: AbKnob, value: string, comp: TakeComposition): string {\n if (knob.kind === \"zoom\") {\n const e = comp.events[knob.beat - 1];\n return e ? zoomText(e) : value;\n }\n if (knob.kind === \"path\") return `${knob.path}=${value}`;\n return value;\n}\n\n/** The reel's time window (ms): a beat's zoom arc with lead-in/out padding, so\n * a taste question costs a ~4s render per variant, not the whole take. The\n * window is the UNION across all variant compositions — a variant with a\n * longer hold/zoom-out (or a rebased inAtMs) must not be cut mid-settle, since\n * the settle is exactly what the reel exists to judge. */\nexport function abWindow(\n comps: TakeComposition[],\n beat: number | undefined,\n full: boolean,\n): [number, number] | undefined {\n if (full) return undefined;\n const base = comps[0];\n if (!base || base.events.length === 0) return undefined;\n if (beat != null && (beat < 1 || beat > base.events.length))\n throw new Error(`ab: --beat ${beat} out of range (1-${base.events.length})`);\n let i = beat != null ? beat - 1 : base.events.findIndex((e) => e.zoom.enabled);\n if (i < 0) i = 0;\n let from = Number.POSITIVE_INFINITY;\n let to = 0;\n for (const c of comps) {\n const e = c.events[i];\n if (!e) continue;\n // The REAL camera schedule (cameraRampSchedule): a pull-out ramp can start\n // up to zoomOutMs before its tMs, or — dwell-delayed — depart later and\n // LAND after its own tMs. Open on the actual departure so the clip keeps a\n // static lead-in, and close when the framing is actually released (the\n // next anchor's actual departure), so a late landing is never cut\n // mid-settle — the settle is exactly what the reel exists to judge.\n const ramps = math.cameraRampSchedule(c);\n const ramp = ramps[i];\n const rampFrom = ramp ? ramp.startMs : Math.min(e.zoom.inAtMs, e.tMs - c.cursor.zoomOutMs);\n from = Math.min(from, Math.max(0, rampFrom - 1200));\n let nextStart: number | undefined;\n for (let j = i + 1; j < c.events.length; j++) {\n const r = ramps[j];\n if (r) {\n nextStart = r.startMs;\n break;\n }\n }\n const landMs = Math.max(e.tMs, ramp?.landMs ?? e.tMs);\n const ownEnd = landMs + (e.durationMs ?? 0) + c.cursor.holdMs + c.cursor.zoomOutMs;\n // no durationMs clamp: the scene runs to its last keyframe + tail, and a\n // range end past the scene's end just stops at the end.\n to = Math.max(to, (nextStart ?? ownEnd) + 400);\n }\n if (!Number.isFinite(from)) return undefined;\n return [from, Math.max(to, from + 1500)];\n}\n\nexport type AbOpts = {\n set: string;\n beat?: number;\n full?: boolean;\n draft?: boolean;\n chromePath?: string;\n logProgress?: boolean;\n};\n\nconst LETTERS = [\"A\", \"B\", \"C\", \"D\"];\n\nexport async function renderAbReel(\n take: TakePaths,\n opts: AbOpts,\n): Promise<{ abPath: string; legend: string }> {\n await requireTakeFiles(take, { capture: true });\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const captureLog = await loadLogSibling(take.capturePath);\n const chromePath = await ensureChrome(opts.chromePath);\n const { knob, values } = parseSetFlag(opts.set, opts.beat);\n\n // variants: the CURRENT state first (so \"A\" always means \"keep it\"), then the\n // requested values — skipping a request that just re-states the current state.\n const cur = currentDesc(comp, knob);\n const variants: AbVariant[] = [{ letter: \"A\", desc: `current (${cur})`, comp }];\n for (const v of values) {\n const applied = applyKnob(comp, knob, v);\n const desc = variantDesc(knob, v, applied);\n if (desc === cur || variants.some((x) => x.desc === desc)) continue;\n variants.push({ letter: LETTERS[variants.length]!, desc, comp: applied });\n }\n if (variants.length < 2)\n throw new Error(`ab: every requested value matches the current state — nothing to compare`);\n\n // validate EVERY variant up front (milliseconds) — one bad value must not\n // waste the minutes already spent rendering the variants before it.\n for (const v of variants) {\n const issues = validateComposition(v.comp, captureLog ? { captureLog } : {});\n const errors = issues.filter((i) => i.severity === \"error\");\n if (errors.length)\n throw new Error(`ab: variant ${v.letter} (${v.desc}) is invalid:\\n${formatIssues(errors)}`);\n }\n\n const windowMs = abWindow(\n variants.map((v) => v.comp),\n opts.beat,\n opts.full ?? false,\n );\n const rangeSec = windowMs\n ? ([windowMs[0] / 1000, windowMs[1] / 1000] as [number, number])\n : undefined;\n\n // FEEL knobs are judged at FULL quality (blur by eye); --draft opts down.\n const clips: string[] = [];\n try {\n for (const v of variants) {\n const base = opts.draft ? toDraft(v.comp) : v.comp;\n const decorated: TakeComposition = {\n ...base,\n review: { label: `${v.letter} · ${v.desc}` },\n };\n const clip = `${take.base}.ab.${v.letter}.mp4`;\n if (opts.logProgress !== false)\n process.stderr.write(\n `variant ${v.letter} · ${v.desc}${rangeSec ? ` · window ${rangeSec[0].toFixed(1)}–${rangeSec[1].toFixed(1)}s` : \"\"}\\n`,\n );\n await renderTake({\n composition: decorated,\n videoPath: take.capturePath,\n outPath: clip,\n captureLog,\n logProgress: opts.logProgress ?? true,\n chromePath,\n rangeSec,\n writeCompositionSibling: false,\n });\n clips.push(clip);\n }\n\n // reel = A B C A B C with short black gaps; each variant seen twice so the\n // eye can confirm on the second pass.\n await concatWithGaps([...clips, ...clips], take.abPath, {\n width: comp.output.width,\n height: comp.output.height,\n fps: opts.draft ? Math.min(30, comp.output.fps) : comp.output.fps,\n });\n } finally {\n await Promise.all(clips.map((c) => rm(c, { force: true })));\n }\n\n const legend = [\n `A/B reel: ${take.abPath} (${knobLabel(knob)})`,\n ...variants.map((v) => ` ${v.letter} ${v.desc}`),\n `answer with a letter — or \"between A and B\" / \"none, try …\"`,\n ].join(\"\\n\");\n return { abPath: take.abPath, legend };\n}\n\nfunction knobLabel(knob: AbKnob): string {\n if (knob.kind === \"zoom\") return `beat ${knob.beat} · zoom`;\n if (knob.kind === \"path\") return knob.path;\n return knob.kind;\n}\n\n/** before/after reel from the existing prev + current masters — no render at\n * all, pure ffmpeg trims. Order convention: BEFORE then AFTER, twice. */\nexport async function renderBeforeAfter(\n take: TakePaths,\n opts: { beat?: number; full?: boolean } = {},\n): Promise<{ abPath: string; legend: string }> {\n await requireTakeFiles(take);\n if (!(await stat(take.prevPath).catch(() => null)))\n throw new Error(`ab --before-after: no ${take.prevPath} yet (it appears after a re-render)`);\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const winComp = abWindow([comp], opts.beat, opts.full ?? false);\n // the masters are delivered files: a composition startMs head-trim already\n // removed their head, so composition-timeline windows shift back by it.\n const trim = comp.startMs ?? 0;\n const win = winComp\n ? ([Math.max(0, winComp[0] - trim), Math.max(0, winComp[1] - trim)] as [number, number])\n : undefined;\n const cut = async (src: string, out: string) => {\n const args = [\"-y\", \"-loglevel\", \"error\", \"-i\", src];\n if (win) args.push(\"-ss\", String(win[0] / 1000), \"-t\", String((win[1] - win[0]) / 1000));\n args.push(\"-c:v\", \"libx264\", \"-crf\", \"18\", \"-pix_fmt\", \"yuv420p\", \"-an\", out);\n await ffmpeg(args);\n };\n const before = `${take.base}.ab.before.mp4`;\n const after = `${take.base}.ab.after.mp4`;\n await cut(take.prevPath, before);\n await cut(take.mp4Path, after);\n await concatWithGaps([before, after, before, after], take.abPath, {\n width: comp.output.width,\n height: comp.output.height,\n fps: comp.output.fps,\n });\n await Promise.all([rm(before, { force: true }), rm(after, { force: true })]);\n const legend = [\n `before/after reel: ${take.abPath}`,\n ` plays BEFORE then AFTER, twice — say \"keep the old one\" to revert`,\n ].join(\"\\n\");\n return { abPath: take.abPath, legend };\n}\n\n// --- ffmpeg helpers ----------------------------------------------------------\n\nasync function ffmpeg(args: string[]): Promise<void> {\n const bin = await resolveFfmpeg();\n return new Promise((res, rej) => {\n const c = spawn(bin, 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(`ffmpeg exited ${code}: ${err}`))));\n });\n}\n\n/** Concat clips with a 0.35s black gap between each, re-encoding via the concat\n * FILTER (robust to per-clip encoder variance; everything shares WxH/fps). The\n * gap comes from a lavfi color source — no font/text filters needed. */\nasync function concatWithGaps(\n clips: string[],\n outPath: string,\n v: { width: number; height: number; fps: number },\n): Promise<void> {\n const args = [\"-y\", \"-loglevel\", \"error\"];\n for (const c of clips) args.push(\"-i\", resolve(c));\n args.push(\"-f\", \"lavfi\", \"-t\", \"0.35\", \"-i\", `color=c=black:s=${v.width}x${v.height}:r=${v.fps}`);\n const gapIdx = clips.length;\n // A gap after every clip except the last: [0][gap][1][gap]…[n-1]\n const seq: string[] = [];\n const gapUses = clips.length - 1;\n const split =\n gapUses > 1\n ? `[${gapIdx}:v]split=${gapUses}${Array.from({ length: gapUses }, (_, i) => `[g${i}]`).join(\"\")};`\n : \"\";\n clips.forEach((_, i) => {\n seq.push(`[${i}:v]`);\n if (i < clips.length - 1) seq.push(gapUses > 1 ? `[g${i}]` : `[${gapIdx}:v]`);\n });\n const filter = `${split}${seq.join(\"\")}concat=n=${seq.length}:v=1:a=0[v]`;\n args.push(\n \"-filter_complex\",\n filter,\n \"-map\",\n \"[v]\",\n \"-c:v\",\n \"libx264\",\n \"-crf\",\n \"18\",\n \"-pix_fmt\",\n \"yuv420p\",\n \"-r\",\n String(v.fps),\n \"-an\",\n resolve(outPath),\n );\n await ffmpeg(args);\n}\n\n// --- open / reveal -----------------------------------------------------------\n\n/** Spawn a fire-and-forget opener. spawn ENOENT arrives ASYNCHRONOUSLY on the\n * child's \"error\" event (a try/catch around spawn never sees it and the\n * process would die with an unhandled error) — so degrade via the listener.\n *\n * `windowsVerbatimArguments` hands argv to Windows unmodified: cmd.exe and explorer.exe\n * re-parse the raw command line by rules node's own quoting doesn't match, so\n * the command builders below quote for them (see winQuote). */\nexport type OpenerCommand = {\n command: string;\n args: string[];\n windowsVerbatimArguments: boolean;\n};\n\nfunction spawnOpener(spec: OpenerCommand, fallbackLine: string): void {\n try {\n const c = spawn(spec.command, spec.args, {\n stdio: \"ignore\",\n detached: true,\n windowsVerbatimArguments: spec.windowsVerbatimArguments,\n });\n c.on(\"error\", () => process.stdout.write(fallbackLine));\n c.unref();\n } catch {\n process.stdout.write(fallbackLine);\n }\n}\n\n/** Wrap a path/URL for a verbatim Windows command line. Safe unquoted-inside:\n * `\"` is illegal in Windows filenames, and cmd stops treating `&` `^` `|` as\n * metacharacters once quoted. */\nconst winQuote = (s: string) => `\"${s}\"`;\n\n/** Pure command specs keep platform quoting independently testable on every\n * CI runner, including the Windows-only `start` title argument rule. */\nexport function getOpenCommand(\n target: string,\n platform: NodeJS.Platform = process.platform,\n): OpenerCommand {\n if (platform === \"darwin\") {\n return { command: \"open\", args: [target], windowsVerbatimArguments: false };\n }\n if (platform === \"win32\") {\n return {\n command: \"cmd\",\n args: [\"/c\", \"start\", '\"\"', winQuote(target)],\n windowsVerbatimArguments: true,\n };\n }\n return { command: \"xdg-open\", args: [target], windowsVerbatimArguments: false };\n}\n\nexport function getRevealCommand(\n absolutePath: string,\n platform: NodeJS.Platform = process.platform,\n): OpenerCommand {\n if (platform === \"darwin\") {\n return { command: \"open\", args: [\"-R\", absolutePath], windowsVerbatimArguments: false };\n }\n if (platform === \"win32\") {\n return {\n command: \"explorer\",\n // explorer takes ONE argument: `/select,` glued to a quoted path.\n args: [`/select,${winQuote(absolutePath)}`],\n windowsVerbatimArguments: true,\n };\n }\n return {\n command: \"xdg-open\",\n args: [dirname(absolutePath)],\n windowsVerbatimArguments: false,\n };\n}\n\n/** Open a file with the OS default player; degrade to printing the path. */\nexport function openPath(p: string): void {\n const abs = resolve(p);\n openWithOs(abs, `open: ${abs}\\n`);\n}\n\n/** Hand a path or URL to the OS default handler. Windows needs `cmd /c start`\n * with an EMPTY first argument: `start` reads a lone quoted argument as the\n * window TITLE, so `start \"<file>\"` opens a blank console instead of the file. */\nexport function openWithOs(target: string, fallbackLine: string): void {\n spawnOpener(getOpenCommand(target), fallbackLine);\n}\n\n/** Reveal a file in Finder/Explorer; degrade to printing the path. */\nexport function revealPath(p: string): void {\n const abs = resolve(p);\n spawnOpener(getRevealCommand(abs), `at: ${abs}\\n`);\n}\n","// edit-server — the local bridge that powers `open-take edit <take>`. It serves\n// the built editor SPA AND a tiny JSON/stream API over the take's files, so the\n// browser editor can load a take, save edits, and trigger a real (Node-only)\n// revideo render with live progress — all on 127.0.0.1, no external services.\n//\n// Endpoints (all under /api):\n// GET /api/take → { composition, captureLog, source, videoUrl, mp4Url, mtime }\n// GET /api/take/video → the kept capture mp4 (HTTP Range, for <video> seeking)\n// GET /api/take/output[?v=tok] → the latest rendered mp4 (HTTP Range)\n// POST /api/composition → guarded validate + persist (428 without base, 400 invalid)\n// POST /api/render → guarded persist + start → { jobId, mtime } (409 conflict/busy)\n// GET /api/render/:id/events → SSE: progress* → done {mp4Url} | failed {message}\n// Everything else is static from the editor dist (SPA fallback to index.html).\n//\n// Two writers share composition.json: this editor and the agent (the Dailies\n// loop re-writes it between renders). Writes here are optimistically\n// concurrency-controlled — the client echoes back the mtime it last saw and a\n// write over a file that moved since is REFUSED with 409, rather than silently\n// winning. See persistGuarded.\n\nimport { createReadStream, statSync } from \"node:fs\";\nimport { appendFile, readFile, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { type IncomingMessage, type ServerResponse, createServer } from \"node:http\";\nimport { extname, join, normalize, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n type CaptureLog,\n type CompositionIssue,\n type TakeComposition,\n validateComposition,\n} from \"@open-take/compositor\";\nimport { renderComposition } from \"./index\";\nimport { openWithOs } from \"./review\";\n\nexport type EditServerOpts = {\n /** path to the take: its .mp4 / .composition.json / a dir containing them. */\n takePath: string;\n port?: number;\n /** open the browser at the served URL (default true). */\n open?: boolean;\n chromePath?: string;\n};\n\nimport { resolveTakePaths } from \"./take\";\n\ntype TakePaths = Awaited<ReturnType<typeof resolveTakePaths>>;\n\ntype RenderJob = {\n id: string;\n progress: number;\n status: \"running\" | \"done\" | \"error\";\n error?: string;\n mp4Url?: string;\n clients: Set<ServerResponse>;\n};\n\ntype EditServerDeps = {\n /** Test seam for the long-running renderer. Production uses the real one. */\n renderComposition?: typeof renderComposition;\n /** Test seam immediately after the temp composition is written. */\n beforeCompositionCommit?: () => Promise<void>;\n};\n\nconst CONTENT_TYPE: Record<string, string> = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".ico\": \"image/x-icon\",\n \".woff2\": \"font/woff2\",\n \".woff\": \"font/woff\",\n \".map\": \"application/json; charset=utf-8\",\n};\n\n/** Locate the built editor SPA: prefer the live monorepo build during\n * development, then fall back to the bundled copy used by the published\n * package. */\nfunction resolveEditorDist(): string | null {\n const here = fileURLToPath(import.meta.url);\n const pkgRoot = resolve(here, \"..\", \"..\"); // dist/edit-server.js → packages/runtime\n // In the monorepo the live editor build wins: editor-dist/ is a prepack COPY\n // and goes stale the moment you rebuild the editor, which silently serves old\n // JS to anyone testing a change. Published, that path doesn't exist (it would\n // resolve under node_modules/apps/editor/…), so the copy is the only candidate.\n const candidates = [\n resolve(pkgRoot, \"..\", \"..\", \"apps\", \"editor\", \"dist\"),\n resolve(pkgRoot, \"editor-dist\"),\n ];\n return candidates.find((c) => existsHtml(c)) ?? null;\n}\nfunction existsHtml(dir: string): boolean {\n return existsFile(join(dir, \"index.html\"));\n}\nfunction existsFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\nconst sendJson = (res: ServerResponse, status: number, obj: unknown) => {\n const body = JSON.stringify(obj);\n res.writeHead(status, {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Content-Length\": Buffer.byteLength(body),\n });\n res.end(body);\n};\n\nasync function readBody(req: IncomingMessage, capBytes = 32 * 1024 * 1024): Promise<string> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const c of req) {\n size += (c as Buffer).length;\n if (size > capBytes) throw new Error(\"request body too large\");\n chunks.push(c as Buffer);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\n/** Stream a file with HTTP Range support (206) — required for <video> seeking. */\nasync function serveFile(req: IncomingMessage, res: ServerResponse, filePath: string) {\n const st = await stat(filePath).catch(() => null);\n if (!st?.isFile()) {\n sendJson(res, 404, { error: \"not found\" });\n return;\n }\n const type = CONTENT_TYPE[extname(filePath).toLowerCase()] ?? \"application/octet-stream\";\n const range = req.headers.range;\n if (range) {\n const m = /bytes=(\\d*)-(\\d*)/.exec(range);\n const start = m?.[1] ? Number(m[1]) : 0;\n const end = m?.[2] ? Number(m[2]) : st.size - 1;\n if (start >= st.size || end >= st.size || start > end) {\n res.writeHead(416, { \"Content-Range\": `bytes */${st.size}` });\n res.end();\n return;\n }\n res.writeHead(206, {\n \"Content-Range\": `bytes ${start}-${end}/${st.size}`,\n \"Accept-Ranges\": \"bytes\",\n \"Content-Length\": end - start + 1,\n \"Content-Type\": type,\n });\n createReadStream(filePath, { start, end }).pipe(res);\n } else {\n res.writeHead(200, {\n \"Content-Length\": st.size,\n \"Accept-Ranges\": \"bytes\",\n \"Content-Type\": type,\n });\n createReadStream(filePath).pipe(res);\n }\n}\n\n/** Open the editor in the default browser. Shares the OS-opener with review.ts\n * — a private copy here is how the Windows `start`-eats-the-first-quoted-arg\n * bug survived in one place after being noticed in the other. */\nfunction openBrowser(url: string) {\n openWithOs(url, `open: ${url}\\n`);\n}\n\nexport async function startEditServer(\n opts: EditServerOpts,\n deps: EditServerDeps = {},\n): Promise<{ url: string; close: () => Promise<void> }> {\n const take = await resolveTakePaths(opts.takePath);\n // the two essentials must exist; the capture log is optional (skips the lock).\n for (const f of [take.compositionPath, take.capturePath]) {\n if (!(await stat(f).catch(() => null))?.isFile()) throw new Error(`missing take file: ${f}`);\n }\n const dist = resolveEditorDist();\n if (!dist)\n throw new Error(\"editor build not found — run `pnpm --filter @open-take/editor build` first\");\n\n const loadCaptureLog = async (): Promise<CaptureLog | null> => {\n try {\n return JSON.parse(await readFile(take.captureLogPath, \"utf8\")) as CaptureLog;\n } catch {\n return null;\n }\n };\n\n let job: RenderJob | null = null;\n let jobSeq = 0;\n // Set synchronously before the render endpoint's first await. Without this,\n // two simultaneous POSTs can both observe `job === null`, persist, and\n // replace each other's job before either request reaches the assignment.\n let renderStarting = false;\n\n const compositionMtime = async (): Promise<number> =>\n (await stat(take.compositionPath).catch(() => null))?.mtimeMs ?? 0;\n\n // Every write runs alone: check-then-write is only meaningful if nothing\n // interleaves between the two, and this server can have an autosave and an\n // export in flight at once.\n let writeLock: Promise<unknown> = Promise.resolve();\n const exclusive = <T>(fn: () => Promise<T>): Promise<T> => {\n const run = writeLock.then(fn, fn);\n writeLock = run.catch(() => {});\n return run;\n };\n\n /** Persist unless someone else wrote first. `baseMtime` is the mtime the\n * client last read. Every API write must provide it; 保留我的 re-bases to\n * the 409's mtime and remains guarded against an even newer write.\n *\n * We check once before writing the temp file and again immediately before\n * rename, so an agent write during serialization/I/O is refused too. No\n * portable filesystem API provides compare-and-swap by mtime: a different\n * process writing in the final stat→rename window can still be overwritten\n * unless every writer honors the same lock. */\n const persistGuarded = async (\n comp: TakeComposition,\n baseMtime: number | undefined,\n ): Promise<{ ok: true; mtime: number } | { ok: false; mtime: number }> =>\n exclusive(async () => {\n const onDisk = await compositionMtime();\n if (baseMtime !== undefined && onDisk !== baseMtime) return { ok: false, mtime: onDisk };\n const tmp = `${take.compositionPath}.tmp`;\n let committed = false;\n try {\n await writeFile(tmp, JSON.stringify(comp, null, 2));\n await deps.beforeCompositionCommit?.();\n if (baseMtime !== undefined) {\n const beforeRename = await compositionMtime();\n if (beforeRename !== onDisk) return { ok: false, mtime: beforeRename };\n }\n await rename(tmp, take.compositionPath);\n committed = true;\n return { ok: true, mtime: await compositionMtime() };\n } finally {\n if (!committed) await unlink(tmp).catch(() => {});\n }\n });\n\n type WritePayload = { composition: TakeComposition; baseMtime: number };\n\n /** The write guard is mandatory. A missing base used to mean \"force write\",\n * which made a bare JSON body an invisible escape hatch around conflict\n * protection. Callers must first GET /api/take and echo its mtime. */\n const readWrite = async (\n req: IncomingMessage,\n res: ServerResponse,\n ): Promise<WritePayload | null> => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readBody(req));\n } catch {\n sendJson(res, 400, { error: \"invalid JSON request body\" });\n return null;\n }\n const candidate =\n parsed && typeof parsed === \"object\"\n ? (parsed as { composition?: unknown; baseMtime?: unknown })\n : null;\n if (\n !candidate?.composition ||\n typeof candidate.baseMtime !== \"number\" ||\n !Number.isFinite(candidate.baseMtime)\n ) {\n sendJson(res, 428, {\n error:\n \"write precondition required: send { composition, baseMtime } using the mtime from GET /api/take\",\n });\n return null;\n }\n return {\n composition: candidate.composition as TakeComposition,\n baseMtime: candidate.baseMtime,\n };\n };\n\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? \"/\", \"http://localhost\");\n const path = url.pathname;\n const method = req.method ?? \"GET\";\n\n // same-origin guard: this is a loopback server, but a hostile web page\n // could still fire cross-site requests at it — refuse foreign Origins\n // and non-JSON bodies on state-changing endpoints.\n if (method === \"POST\") {\n const host = req.headers.host ?? \"\";\n const origin = req.headers.origin;\n const sameOrigin = !origin || origin === `http://${host}`;\n const isJson = (req.headers[\"content-type\"] ?? \"\").includes(\"application/json\");\n if (!/^(127\\.0\\.0\\.1|localhost)(:\\d+)?$/.test(host) || !sameOrigin || !isJson) {\n sendJson(res, 403, { error: \"forbidden\" });\n return;\n }\n }\n\n // ---- API ----\n if (path === \"/api/take\" && method === \"GET\") {\n // read the mtime BEFORE the contents: if a write lands in between, the\n // client's base is older than what it holds and its next save 409s —\n // the safe direction. (Reading it after could hand out a base newer\n // than the composition we returned, which would silently clobber.)\n const mtime = await compositionMtime();\n const composition = JSON.parse(\n await readFile(take.compositionPath, \"utf8\"),\n ) as TakeComposition;\n const captureLog = await loadCaptureLog();\n sendJson(res, 200, {\n composition,\n captureLog,\n source: { name: take.name },\n videoUrl: \"/api/take/video\",\n mp4Url: \"/api/take/output\",\n mtime,\n });\n return;\n }\n if (path === \"/api/take/video\" && method === \"GET\") {\n await serveFile(req, res, take.capturePath);\n return;\n }\n if (path === \"/api/take/mtime\" && method === \"GET\") {\n sendJson(res, 200, { mtime: await compositionMtime() });\n return;\n }\n if (path === \"/api/notes\" && method === \"POST\") {\n const { text } = JSON.parse(await readBody(req)) as { text?: string };\n if (!text?.trim()) {\n sendJson(res, 400, { error: \"empty note\" });\n return;\n }\n const line = text.trim().replace(/\\s+/g, \" \").slice(0, 2000);\n // durable for the agent to pick up later + live on stdout for an agent\n // watching this process\n await appendFile(`${take.base}.notes.md`, `- ${line}\\n`);\n process.stdout.write(`NOTE ${JSON.stringify({ take: take.name, text: line })}\\n`);\n sendJson(res, 200, { ok: true });\n return;\n }\n if (path === \"/api/take/output\" && method === \"GET\") {\n await serveFile(req, res, take.mp4Path);\n return;\n }\n\n if (path === \"/api/composition\" && method === \"POST\") {\n const payload = await readWrite(req, res);\n if (!payload) return;\n const { composition: comp, baseMtime } = payload;\n const captureLog = await loadCaptureLog();\n const issues = validateComposition(comp, captureLog ? { captureLog } : {});\n const errors = issues.filter((i) => i.severity === \"error\");\n if (errors.length) {\n sendJson(res, 400, { issues });\n return;\n }\n const saved = await persistGuarded(comp, baseMtime);\n if (!saved.ok) {\n sendJson(res, 409, { conflict: true, mtime: saved.mtime });\n return;\n }\n sendJson(res, 200, { ok: true, issues, mtime: saved.mtime });\n return;\n }\n\n if (path === \"/api/render\" && method === \"POST\") {\n if (renderStarting || job?.status === \"running\") {\n sendJson(res, 409, { error: \"a render is already in progress\" });\n return;\n }\n renderStarting = true;\n try {\n const payload = await readWrite(req, res);\n if (!payload) return;\n const { composition: comp, baseMtime } = payload;\n const captureLog = (await loadCaptureLog()) ?? undefined;\n const issues = validateComposition(comp, captureLog ? { captureLog } : {});\n const errors = issues.filter((i: CompositionIssue) => i.severity === \"error\");\n if (errors.length) {\n sendJson(res, 400, { issues });\n return;\n }\n const saved = await persistGuarded(comp, baseMtime);\n if (!saved.ok) {\n // Same status as \"render already running\" above — the `conflict`\n // flag is what tells the two apart on the client.\n sendJson(res, 409, { conflict: true, mtime: saved.mtime });\n return;\n }\n const id = `${Date.now().toString(36)}-${++jobSeq}`;\n job = { id, progress: 0, status: \"running\", clients: new Set() };\n // Re-base immediately: the guarded write already happened. Waiting\n // for SSE `done` leaves the client stale when rendering fails or\n // disconnects.\n sendJson(res, 200, { jobId: id, mtime: saved.mtime });\n // Run the render in the background; stream progress to SSE clients.\n void runRender(job, comp, captureLog);\n } finally {\n renderStarting = false;\n }\n return;\n }\n\n const ev = /^\\/api\\/render\\/([^/]+)\\/events$/.exec(path);\n if (ev && method === \"GET\") {\n const id = ev[1];\n if (!job || job.id !== id) {\n sendJson(res, 404, { error: \"unknown job\" });\n return;\n }\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n emit(res, \"progress\", { progress: job.progress });\n if (job.status === \"done\") {\n emit(res, \"done\", { mp4Url: job.mp4Url });\n res.end();\n return;\n }\n if (job.status === \"error\") {\n emit(res, \"failed\", { message: job.error });\n res.end();\n return;\n }\n job.clients.add(res);\n req.on(\"close\", () => job?.clients.delete(res));\n return;\n }\n\n if (path.startsWith(\"/api/\")) {\n sendJson(res, 404, { error: \"no such endpoint\" });\n return;\n }\n\n // ---- static editor SPA ----\n if (method !== \"GET\") {\n sendJson(res, 405, { error: \"method not allowed\" });\n return;\n }\n const rel = normalize(decodeURIComponent(path)).replace(/^(\\.\\.[/\\\\])+/, \"\");\n let filePath = join(dist, rel === \"/\" ? \"index.html\" : rel);\n if (!filePath.startsWith(dist)) {\n sendJson(res, 403, { error: \"forbidden\" });\n return;\n }\n const fst = await stat(filePath).catch(() => null);\n if (!fst?.isFile()) filePath = join(dist, \"index.html\"); // SPA fallback\n await serveFile(req, res, filePath);\n } catch (err) {\n sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });\n }\n });\n\n async function runRender(\n j: RenderJob,\n comp: TakeComposition,\n captureLog: CaptureLog | undefined,\n ) {\n try {\n await (deps.renderComposition ?? renderComposition)({\n composition: comp,\n capturePath: take.capturePath,\n outPath: take.mp4Path,\n captureLog,\n chromePath: opts.chromePath,\n // POST /api/render already persisted `comp` under persistGuarded. A\n // second write after a long render would overwrite any agent edit that\n // landed while rendering.\n writeCompositionSibling: false,\n onProgress: (p) => {\n j.progress = p;\n for (const c of j.clients) emit(c, \"progress\", { progress: p });\n },\n });\n j.status = \"done\";\n j.progress = 1;\n j.mp4Url = `/api/take/output?v=${Date.now().toString(36)}`;\n for (const c of j.clients) {\n emit(c, \"done\", { mp4Url: j.mp4Url });\n c.end();\n }\n } catch (err) {\n j.status = \"error\";\n j.error = err instanceof Error ? err.message : String(err);\n for (const c of j.clients) {\n emit(c, \"failed\", { message: j.error });\n c.end();\n }\n } finally {\n j.clients.clear();\n }\n }\n\n const port = await listen(server, opts.port ?? 4178);\n const url = `http://127.0.0.1:${port}/`;\n process.stdout.write(\n `open-take editor → ${url}\\n(serving take \"${take.name}\"; Ctrl-C to stop)\\n`,\n );\n if (opts.open !== false) openBrowser(url);\n\n return {\n url,\n close: () => new Promise<void>((r) => server.close(() => r())),\n };\n}\n\nfunction emit(res: ServerResponse, event: string, data: unknown) {\n res.write(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n}\n\n/** Bind to 127.0.0.1 only; if the port is taken, try the next few. Resolves the\n * port actually BOUND, which differs from the requested one when port 0 asks\n * the OS to choose (how the tests get an isolated server). */\nfunction listen(server: ReturnType<typeof createServer>, startPort: number): Promise<number> {\n return new Promise((res, rej) => {\n let port = startPort;\n const tryOne = () => {\n server.once(\"error\", (e: NodeJS.ErrnoException) => {\n if (e.code === \"EADDRINUSE\" && port < startPort + 20) {\n port++;\n tryOne();\n } else rej(e);\n });\n server.listen(port, \"127.0.0.1\", () => {\n const addr = server.address();\n res(addr && typeof addr === \"object\" ? addr.port : port);\n });\n };\n tryOne();\n });\n}\n","// frames — beat-aware verification sheets: one tiled contact sheet whose\n// sample times come from the REAL camera schedule (cameraRampSchedule), so a\n// verifier looks at the HOLD of each beat — never accidentally inside a ramp\n// or settle tail and misreads motion as a framing bug. Rows tell the story:\n// an intro row (dead-opening check), one row per beat (travel + 4 hold\n// samples), a tail row (lingering-ending check). `--beat N` densifies one\n// beat into a 10-cell strip with per-cell phase labels instead.\n//\n// Pure planning (buildFramePlan) is separated from the ffmpeg I/O\n// (renderFrames) so the schedule math stays snapshot-testable.\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtemp, readFile, rm, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport {\n type TakeComposition,\n math,\n resolveFfmpeg,\n resolveFfprobe,\n} from \"@open-take/compositor\";\nimport { beatLabel } from \"./review\";\nimport { type TakePaths, requireTakeFiles } from \"./take\";\n\nexport type FramePhase = \"intro\" | \"travel\" | \"hold\" | \"tail\";\nexport type FrameCell = {\n /** sample time on the COMPOSITION timeline, ms (the `beats` vocabulary). */\n tMs: number;\n phase: FramePhase;\n};\nexport type FrameRow = { label: string; cells: FrameCell[] };\nexport type FramePlan = { rows: FrameRow[]; cols: number; notes: string[] };\n\nconst COLS = 5;\n\n/** Per-beat camera windows on the composition timeline, buildBadges-style:\n * monotone starts (the ramp departure toward the beat), the actual landing,\n * and where the framing is released (the next beat's departure, or the own\n * hold's end). */\nfunction beatWindows(comp: TakeComposition): {\n startMs: number;\n arrivedMs: number;\n releaseMs: number;\n}[] {\n const ramps = math.cameraRampSchedule(comp);\n let prevStart = 0;\n const starts = comp.events.map((e, i) => {\n const s = Math.max(ramps[i]?.startMs ?? e.zoom.inAtMs, prevStart + 1);\n prevStart = s;\n return s;\n });\n return comp.events.map((e, i) => {\n const arrived = Math.max(e.tMs, ramps[i]?.landMs ?? e.tMs);\n const endOwn = arrived + (e.durationMs ?? 0) + comp.cursor.holdMs;\n const release =\n i < comp.events.length - 1 ? starts[i + 1]! : Math.min(endOwn, comp.durationMs);\n return { startMs: starts[i]!, arrivedMs: arrived, releaseMs: release };\n });\n}\n\nconst spread = (from: number, to: number, n: number): number[] =>\n Array.from({ length: n }, (_, k) => (n === 1 ? from : from + ((to - from) * k) / (n - 1)));\n\nexport function buildFramePlan(comp: TakeComposition, opts: { beat?: number } = {}): FramePlan {\n const wins = beatWindows(comp);\n const notes: string[] = [];\n const endCap = comp.durationMs - 60;\n\n if (opts.beat != null) {\n const i = opts.beat - 1;\n const e = comp.events[i];\n const w = wins[i];\n if (!e || !w)\n throw new Error(`frames: --beat ${opts.beat} out of range (1-${comp.events.length})`);\n const from = Math.max(comp.startMs ?? 0, w.startMs - 400);\n const to = Math.min(endCap, w.releaseMs + 400);\n const phase = (t: number): FramePhase =>\n t < w.arrivedMs ? \"travel\" : t <= w.releaseMs ? \"hold\" : \"tail\";\n const cells = spread(from, to, COLS * 2).map((t) => ({ tMs: t, phase: phase(t) }));\n const label = `beat ${opts.beat} · ${beatLabel(e)}`;\n return {\n rows: [\n { label: `${label} 1/2`, cells: cells.slice(0, COLS) },\n { label: `${label} 2/2`, cells: cells.slice(COLS) },\n ],\n cols: COLS,\n notes,\n };\n }\n\n const rows: FrameRow[] = [];\n const trim = comp.startMs ?? 0;\n const introEnd = wins.length ? wins[0]!.startMs - 100 : endCap;\n if (introEnd - trim > 800) {\n rows.push({\n label: \"in\",\n cells: spread(trim, introEnd, COLS).map((tMs) => ({ tMs, phase: \"intro\" as const })),\n });\n }\n comp.events.forEach((e, i) => {\n const w = wins[i]!;\n // beats already trimmed off by startMs can't be sampled from the delivered\n // file — say so instead of tiling frame 0 five times.\n if (w.releaseMs <= trim) {\n notes.push(`beat ${i + 1} ends before the startMs head trim — not sampled`);\n return;\n }\n const holdFrom = Math.max(trim, Math.min(w.arrivedMs + 80, endCap));\n const holdTo = Math.max(holdFrom, Math.min(w.releaseMs - 120, endCap));\n const cells: FrameCell[] = [];\n if (w.arrivedMs - w.startMs > 200 && w.startMs >= trim) {\n cells.push({ tMs: (w.startMs + w.arrivedMs) / 2, phase: \"travel\" });\n }\n const holdN = COLS - cells.length;\n for (const tMs of spread(holdFrom, holdTo, holdN)) cells.push({ tMs, phase: \"hold\" });\n rows.push({ label: `beat ${i + 1} · ${beatLabel(e)}`, cells });\n });\n const lastRelease = wins.length ? wins[wins.length - 1]!.releaseMs : trim;\n if (comp.durationMs - lastRelease > 800) {\n rows.push({\n label: \"out\",\n cells: spread(Math.max(trim, lastRelease), endCap, COLS).map((tMs) => ({\n tMs,\n phase: \"tail\" as const,\n })),\n });\n }\n return { rows, cols: COLS, notes };\n}\n\n// --- rendering (ffmpeg I/O) --------------------------------------------------\n\nfunction run(cmd: string, args: string[]): Promise<string> {\n return new Promise((res, rej) => {\n const c = spawn(cmd, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let out = \"\";\n let err = \"\";\n c.stdout.on(\"data\", (d) => {\n out += d;\n });\n c.stderr.on(\"data\", (d) => {\n err += d;\n });\n c.on(\"error\", rej);\n c.on(\"close\", (code) => (code === 0 ? res(out) : rej(new Error(`${cmd} exited ${code}: ${err}`))));\n });\n}\n\nasync function mp4Duration(path: string): Promise<number> {\n const out = await run(await resolveFfprobe(), [\n \"-v\",\n \"error\",\n \"-show_entries\",\n \"format=duration\",\n \"-of\",\n \"csv=p=0\",\n resolve(path),\n ]);\n const s = Number.parseFloat(out.trim());\n if (!Number.isFinite(s) || s <= 0) throw new Error(`frames: could not read duration of ${path}`);\n return s * 1000;\n}\n\nconst fmtS = (ms: number): string => `${(ms / 1000).toFixed(1)}s`;\n\nexport function buildFrameSheet(\n plan: FramePlan,\n framesPath: string,\n trimMs: number,\n tileW?: number,\n): string {\n const lines = [\n `frames: ${framesPath} · ${plan.cols} cols × ${plan.rows.length} rows${tileW ? ` · ${tileW}px tiles` : \"\"} · times on the composition timeline${trimMs ? ` (head −${(trimMs / 1000).toFixed(1)}s already cut from the mp4)` : \"\"}`,\n ];\n plan.rows.forEach((r, i) => {\n const cells = r.cells\n .map((c) => (c.phase === \"hold\" || c.phase === \"intro\" ? fmtS(c.tMs) : `${fmtS(c.tMs)}(${c.phase})`))\n .join(\" · \");\n lines.push(` row ${i + 1} ${r.label.padEnd(34, \" \")} ${cells}`);\n });\n for (const n of plan.notes) lines.push(` ⚠ ${n}`);\n lines.push(\n `judge framing/payoff on HOLD cells only — travel cells are mid-motion by design (ramps + blur live there).`,\n );\n return lines.join(\"\\n\");\n}\n\nexport type FramesOpts = {\n /** densify one beat (1-based) into a 10-cell strip */\n beat?: number;\n /** which delivered file to sample (default the master mp4) */\n sourcePath?: string;\n /** tile width in px. Defaults: 480 for the overview, 720 for a --beat strip\n * (diagnosis wants detail — a 480px tile of a Retina capture is a 1/8-scale\n * thumbnail: enough to suspect a framing bug, not enough to confirm it). */\n tileWidth?: number;\n};\n\n/** Extract the plan's frames from a delivered take mp4 and tile them into\n * `<base>.frames[.beatN].png`. No Chrome, no render — a handful of ffmpeg\n * seeks; seconds, not minutes. */\nexport async function renderFrames(\n take: TakePaths,\n opts: FramesOpts = {},\n): Promise<{ framesPath: string; sheet: string; plan: FramePlan }> {\n await requireTakeFiles(take);\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const src = resolve(opts.sourcePath ?? take.mp4Path);\n if (!(await stat(src).catch(() => null))?.isFile())\n throw new Error(`frames: ${src} not found — render the take first`);\n const plan = buildFramePlan(comp, { beat: opts.beat });\n if (plan.rows.length === 0) throw new Error(\"frames: nothing to sample (no beats, no intro/tail)\");\n\n const trim = comp.startMs ?? 0;\n const durMs = await mp4Duration(src);\n const ffmpeg = await resolveFfmpeg();\n const framesPath = opts.beat != null ? `${take.base}.frames.beat${opts.beat}.png` : `${take.base}.frames.png`;\n const tileW = Math.round(opts.tileWidth ?? (opts.beat != null ? 720 : 480));\n if (!Number.isFinite(tileW) || tileW < 120 || tileW > 1920)\n throw new Error(`frames: tile width ${tileW} out of range (120-1920)`);\n const tileH = Math.round((tileW * comp.output.height) / comp.output.width);\n\n const work = await mkdtemp(join(tmpdir(), \"open-take-frames-\"));\n try {\n const cells = plan.rows.flatMap((r) => r.cells);\n for (let i = 0; i < cells.length; i++) {\n // composition time → delivered-file time; clamp inside the real file so\n // encoder rounding at the tail can't yield an empty extraction.\n const fileMs = Math.min(Math.max(cells[i]!.tMs - trim, 0), durMs - 50);\n await run(ffmpeg, [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-ss\",\n String(fileMs / 1000),\n \"-i\",\n src,\n \"-frames:v\",\n \"1\",\n \"-vf\",\n `scale=${tileW}:${tileH}`,\n join(work, `f${String(i).padStart(3, \"0\")}.png`),\n ]);\n }\n await run(ffmpeg, [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-framerate\",\n \"1\",\n \"-i\",\n join(work, \"f%03d.png\"),\n \"-frames:v\",\n \"1\",\n \"-vf\",\n `tile=${plan.cols}x${plan.rows.length}`,\n framesPath,\n ]);\n } finally {\n await rm(work, { recursive: true, force: true });\n }\n return { framesPath, sheet: buildFrameSheet(plan, framesPath, trim, tileW), plan };\n}\n","// @open-take/runtime — the thin pipeline: agent plan -> capture (event\n// log) -> compositor -> polished mp4 + editable composition.\n//\n// await makeTake(plan, { outPath: \"demo.mp4\" }) // capture + render\n// await renderComposition({ composition, capturePath, outPath }) // refine\n//\n// Keep it thin. The agent does the planning; this just runs the pipeline.\n//\n// The two entry points mirror the two costs. makeTake DRIVES the app in\n// real-time (expensive, the ground-truth recording) and KEEPS the capture\n// alongside the output. renderComposition re-renders an EDITED composition\n// over that saved capture — no browser drive — which is the refinement loop:\n// the agent tweaks the editable composition.json (zoom/pacing/framing) and\n// re-renders deterministically. Only the *cinematic* layer is editable this\n// way; changing the choreography (what's clicked/typed, beat order) needs a\n// fresh makeTake (the video is temporal — see validateComposition).\n\nimport { copyFile, mkdir, mkdtemp, readFile, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n type CaptureLog,\n type PlanOpts,\n type TakeComposition,\n planComposition,\n renderTake,\n} from \"@open-take/compositor\";\nimport { type CaptureOpts, captureTake } from \"./capture\";\nimport { ensureChrome } from \"./cdp\";\nimport { annotateCaptureLog } from \"./frame-diff\";\nimport { toDraft } from \"./review\";\nimport type { TakePlan } from \"./types\";\n\nexport type { TakePlan, TakeStep } from \"./types\";\nexport {\n captureTake,\n type CaptureOpts,\n inspectPage,\n type InspectOpts,\n type InspectResult,\n type InspectElement,\n} from \"./capture\";\nexport { captureTakeCDP } from \"./cdp-capture\";\nexport {\n annotateCaptureLog,\n diffFrames,\n type AnnotateOpts,\n type FrameDiffResult,\n} from \"./frame-diff\";\nexport { ensureChrome, resolveChrome } from \"./cdp\";\nexport { startEditServer, type EditServerOpts } from \"./edit-server\";\nexport {\n requireTakeFiles,\n resolveTakePaths,\n stagePrev,\n type StagedPrev,\n type TakePaths,\n} from \"./take\";\nexport {\n buildBeatSheet,\n buildBadges,\n beatLabel,\n renderReview,\n renderDraft,\n renderAbReel,\n renderBeforeAfter,\n toDraft,\n openPath,\n revealPath,\n SAY_IT_CARD,\n type AbOpts,\n type ReviewOpts,\n} from \"./review\";\nexport {\n buildFramePlan,\n buildFrameSheet,\n renderFrames,\n type FramePlan,\n type FrameRow,\n type FrameCell,\n type FramePhase,\n type FramesOpts,\n} from \"./frames\";\nexport { validateComposition, formatIssues, type CompositionIssue } from \"@open-take/compositor\";\n\nexport type MakeTakeOpts = {\n /** output polished mp4 path */\n outPath: string;\n /** tune the default composition (zoom fill/cap, framing, cursor) */\n planOpts?: PlanOpts;\n capture?: Omit<CaptureOpts, \"videoPath\">;\n /** frame-diff the capture to annotate each event with what it actually\n * changed on screen (effectBox/changeCoverage — the camera director's\n * nav-vs-popover + payoff-framing inputs). Default true; annotation\n * failures never fail the take. */\n frameDiff?: boolean;\n logProgress?: boolean;\n /** print per-event diagnostics (the frame-diff lines). Default false — they\n * are useful when debugging framing, but on a normal run they bury the\n * warnings an author must act on (a skipped step). */\n verbose?: boolean;\n /** render the INITIAL mp4 at draft quality (30fps cap + motion blur off,\n * ~6-12× faster) for the iterate loop; the capture still records at the\n * full fps and the composition sibling keeps the full-quality settings, so\n * the closing `render` produces the real master from the same take. */\n draft?: boolean;\n /** called the moment the raw capture lands beside the output — BEFORE the\n * frame-diff + render minutes. The progressive-reveal hook: the CLI prints\n * and auto-opens the raw footage so the user watches it while the polish\n * renders. A throwing callback never fails the take. */\n onCaptureReady?: (capturePath: string) => void;\n};\n\nexport type MakeTakeResult = {\n mp4Path: string;\n compositionPath: string;\n /** the KEPT raw capture (next to the mp4) — feed this back to\n * renderComposition to refine without re-driving the app. */\n capturePath: string;\n /** the KEPT capture log (`<out>.capture.json`) — the ground-truth action\n * timing. `render` auto-loads it so the capture-lock check (a refine must not\n * move an action's tMs) is enforced in the real refine loop, not just inside\n * makeTake. */\n captureLogPath: string;\n composition: TakeComposition;\n /** steps the capture dropped (target not found) — surface these in the\n * end-of-run summary; `--strict` turns them into a non-zero exit. */\n skipped: NonNullable<CaptureLog[\"skipped\"]>;\n};\n\n/** `<out>.mp4` → `<out>.capture.mp4` — the raw recording kept beside the\n * polished output so the composition can be re-rendered (refined) later. */\nconst capturePathFor = (outPath: string): string =>\n `${resolve(outPath).replace(/\\.mp4$/i, \"\")}.capture.mp4`;\n\n/** `<x>.capture.mp4` → `<x>.capture.json` — the capture log sits beside the\n * video. Deriving it by convention lets `render` find the ground-truth timing\n * from just the `--video` path. */\nexport const captureLogPathFor = (capturePath: string): string =>\n resolve(capturePath).replace(/\\.mp4$/i, \".json\");\n\n/** Load the capture log that sits beside a capture video, if present. Returns\n * undefined when there's no sibling (e.g. an old capture, or a hand-supplied\n * video) — the capture-lock check is then skipped, not an error. */\nexport async function loadCaptureLogSibling(capturePath: string): Promise<CaptureLog | undefined> {\n const p = captureLogPathFor(capturePath);\n try {\n return JSON.parse(await readFile(p, \"utf8\")) as CaptureLog;\n } catch {\n return undefined;\n }\n}\n\nexport async function makeTake(plan: TakePlan, opts: MakeTakeOpts): Promise<MakeTakeResult> {\n const work = await mkdtemp(join(tmpdir(), \"open-take-\"));\n const tmpVideo = join(work, \"capture.mp4\"); // CDP screencast → h264 mp4\n\n // Resolve (and, first run, download) Chrome ONCE, then hand the same binary\n // to both capture and render. One browser serves the whole pipeline; the\n // renderer uses puppeteer-core and never downloads another one.\n const chromePath = await ensureChrome(opts.capture?.chromePath);\n\n const raw = await captureTake(plan, { ...opts.capture, chromePath, videoPath: tmpVideo });\n\n // KEEP the capture beside the output the moment it exists — BEFORE the\n // frame-diff + render minutes — so the caller can reveal the raw footage\n // while the polish is still cooking (perceived latency: the user sees\n // nothing for ~10 minutes otherwise). Refinement re-renders over this copy\n // without re-driving the app (the refine loop's whole point).\n const capturePath = capturePathFor(opts.outPath);\n const captureLogPath = captureLogPathFor(capturePath);\n await mkdir(dirname(capturePath), { recursive: true });\n await copyFile(tmpVideo, capturePath);\n try {\n opts.onCaptureReady?.(capturePath);\n } catch {\n // a reveal hook must never fail the take\n }\n\n // Tier-2 annotation: diff the recording around each action so the log\n // carries what each action actually changed (effectBox/changeCoverage) —\n // the director's ground truth for payoff-framing and nav pull-outs. The\n // annotated log is what gets KEPT, so later re-plans keep the signal.\n const log =\n opts.frameDiff === false\n ? raw\n : await annotateCaptureLog(raw, tmpVideo, { logProgress: opts.verbose === true });\n\n // Keep the LOG too — it's the ground-truth action timing the capture-lock\n // check needs in the refine loop (the composition is editable; the log is not).\n await writeFile(captureLogPath, JSON.stringify(log, null, 2));\n\n // One knob: the render grid follows the capture fps (default 60) unless the\n // caller pinned an explicit render fps. (A 30fps\n // render of a 60fps capture would discard half the frames; matching them is\n // what makes 60fps real.)\n const captureFps = opts.capture?.fps ?? 60;\n const planOpts =\n opts.planOpts?.output?.fps == null\n ? { ...opts.planOpts, output: { ...opts.planOpts?.output, fps: captureFps } }\n : opts.planOpts;\n const composition = planComposition(log, planOpts);\n const { mp4Path, compositionPath } = await renderTake({\n // A draft take renders fast (30fps cap + no blur) but PLANS at full\n // quality: the sibling written below keeps the real settings, so the\n // closing `render` masters this same take without a re-make.\n composition: opts.draft ? toDraft(composition) : composition,\n videoPath: capturePath,\n outPath: resolve(opts.outPath),\n logProgress: opts.logProgress ?? false,\n chromePath,\n captureLog: log,\n ...(opts.draft ? { writeCompositionSibling: false } : {}),\n });\n if (opts.draft) await writeFile(compositionPath, JSON.stringify(composition, null, 2));\n\n return {\n mp4Path,\n compositionPath,\n capturePath,\n captureLogPath,\n composition,\n skipped: log.skipped ?? [],\n };\n}\n\nexport type RenderCompositionOpts = {\n /** the edited composition (or its parsed JSON) */\n composition: TakeComposition;\n /** the kept raw capture from makeTake (`<out>.capture.mp4`) */\n capturePath: string;\n /** output polished mp4 path */\n outPath: string;\n /** the ground-truth capture log, for the capture-lock check (an edit must not\n * move an action's tMs). Pass it to enforce the lock; omit to skip it. */\n captureLog?: CaptureLog;\n logProgress?: boolean;\n /** Chrome binary; resolved once if omitted */\n chromePath?: string;\n /** render progress (0..1), forwarded from revideo — for a progress UI. */\n onProgress?: (progress: number) => void;\n /** Write the editable `<out>.composition.json` sibling (default true).\n * Callers that already persisted the composition under their own\n * concurrency guard can disable the second, unguarded write. */\n writeCompositionSibling?: boolean;\n};\n\n/** Refine: re-render an EDITED composition over a saved capture — no app\n * drive. This is the talk-to-edit loop's render step. Deterministic: the\n * capture is frozen, so only your edits change the output. Validation runs at\n * the render boundary (renderTake) and throws on a malformed edit — including a\n * capture-locked tMs drift when `captureLog` is supplied. */\nexport async function renderComposition(\n opts: RenderCompositionOpts,\n): Promise<{ mp4Path: string; compositionPath: string }> {\n const chromePath = await ensureChrome(opts.chromePath);\n return renderTake({\n composition: opts.composition,\n videoPath: resolve(opts.capturePath),\n outPath: resolve(opts.outPath),\n logProgress: opts.logProgress ?? false,\n chromePath,\n captureLog: opts.captureLog,\n onProgress: opts.onProgress,\n writeCompositionSibling: opts.writeCompositionSibling,\n });\n}\n\n/** Convenience: load a `*.composition.json` and re-render over a saved capture.\n * Auto-loads the sibling capture log (`<video>`.json) so the capture-lock check\n * is enforced in the CLI refine loop — pass `captureLogPath` to override, or\n * set it to `null` to skip. Validation (incl. the lock) runs at the renderTake\n * boundary, which throws on any error BEFORE the expensive render. */\nexport async function renderCompositionFile(opts: {\n compositionPath: string;\n capturePath: string;\n outPath: string;\n /** explicit capture-log path; default = the sibling of capturePath; null skips */\n captureLogPath?: string | null;\n logProgress?: boolean;\n chromePath?: string;\n onProgress?: (progress: number) => void;\n}): Promise<{ mp4Path: string; compositionPath: string }> {\n const composition = JSON.parse(\n await readFile(resolve(opts.compositionPath), \"utf8\"),\n ) as TakeComposition;\n const captureLog =\n opts.captureLogPath === null\n ? undefined\n : opts.captureLogPath\n ? (JSON.parse(await readFile(resolve(opts.captureLogPath), \"utf8\")) as CaptureLog)\n : await loadCaptureLogSibling(opts.capturePath);\n if (opts.logProgress)\n process.stderr.write(\n captureLog\n ? \"capture-lock: on (loaded capture log)\\n\"\n : \"capture-lock: off (no capture log)\\n\",\n );\n return renderComposition({\n composition,\n capturePath: opts.capturePath,\n outPath: opts.outPath,\n captureLog,\n logProgress: opts.logProgress,\n chromePath: opts.chromePath,\n onProgress: opts.onProgress,\n });\n}\n"],"mappings":";;;;;;;;;;;AA0BA,MAAM,aAAa;AACnB,MAAM,OAAO;;AAEb,MAAM,cAAc;;AAEpB,MAAM,YAAY;;;;;;;;AASlB,MAAM,YAAY;;;;AAIlB,MAAM,YAAY;;;;AAIlB,MAAM,aAAa;;;AAGnB,MAAM,oBAAoB;;;;AAI1B,MAAM,sBAAsB;;;AAY5B,SAAS,WAAWA,GAAeC,GAAeC,GAAWC,GAAwB;CACnF,MAAM,KAAK,KAAK,KAAK,IAAI,KAAK;CAC9B,MAAM,SAAS,IAAI,YAAY,KAAK,KAAK,KAAK,IAAI,KAAK;AACvD,MAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;EAC1B,MAAM,MAAM,IAAI;EAChB,MAAM,OAAO,KAAK,MAAM,IAAI,KAAK,GAAG;AACpC,OAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;GAC1B,MAAM,IAAI,EAAE,MAAM,KAAM,EAAE,MAAM;AAChC,OAAI,IAAI,eAAe,KA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AAO,MACb,aACI,4CACA,uCACL;AACH,QAAO,kBAAkB;EACvB;EACA,aAAa,KAAK;EAClB,SAAS,KAAK;EACd;EACA,aAAa,KAAK;EAClB,YAAY,KAAK;EACjB,YAAY,KAAK;CAClB,EAAC;AACH"}
1
+ {"version":3,"file":"index.js","names":["a: Uint8Array","b: Uint8Array","w: number","h: number","before: Uint8Array","after: Uint8Array","ambient?: Uint8Array","cx: number","cy: number","bin: string","videoPath: string","tSec: number","aw: number","ah: number","chunks: Buffer[]","b: Buffer","log: CaptureLog","opts: AnnotateOpts","p: string","input: string","base","take: TakePaths","opts: { capture?: boolean }","mp4Path: string","prevPath: string","capturePath: string","KIND_LABEL: Record<CompEvent[\"kind\"], string>","e: CompEvent","s: string","n: number","ms: number","comp: TakeComposition","name: string","lines: string[]","badges: ReviewBadge[]","take: TakePaths","opts: ReviewOpts","decorated: TakeComposition","set: string","beat?: number","path: string","raw: string","value: unknown","node: Record<string, unknown>","knob: AbKnob","node: unknown","value: string","comps: TakeComposition[]","beat: number | undefined","full: boolean","nextStart: number | undefined","opts: AbOpts","variants: AbVariant[]","clips: string[]","opts: { beat?: number; full?: boolean }","src: string","out: string","args: string[]","outPath: string","v: { width: number; height: number; fps: number }","seq: string[]","spec: OpenerCommand","fallbackLine: string","target: string","platform: NodeJS.Platform","absolutePath: string","p: string","name: string","opts: AuthOpts","proc: ChildProcess","spawnErr: Error | undefined","CONTENT_TYPE: Record<string, string>","dir: string","path: string","res: ServerResponse","status: number","obj: unknown","req: IncomingMessage","chunks: Buffer[]","filePath: string","url: string","opts: EditServerOpts","deps: EditServerDeps","job: RenderJob | null","writeLock: Promise<unknown>","fn: () => Promise<T>","run","comp: TakeComposition","baseMtime: number | undefined","parsed: unknown","url","i: CompositionIssue","rel","j: RenderJob","captureLog: CaptureLog | undefined","event: string","data: unknown","server: ReturnType<typeof createServer>","startPort: number","e: NodeJS.ErrnoException","ms: number","p: string","buf: Buffer","take: TakePaths","opts: ReadNotesOpts","opts: WaitNotesOpts","res: NotesRead & { timedOut?: boolean }","opts: { waited?: boolean }","comp: TakeComposition","from: number","to: number","n: number","opts: { beat?: number }","notes: string[]","t: number","rows: FrameRow[]","cells: FrameCell[]","cmd: string","args: string[]","path: string","ms: number","plan: FramePlan","framesPath: string","trimMs: number","tileW?: number","take: TakePaths","opts: FramesOpts","ffmpeg","outPath: string","capturePath: string","plan: TakePlan","opts: MakeTakeOpts","opts: RenderCompositionOpts","opts: {\n compositionPath: string;\n capturePath: string;\n outPath: string;\n /** explicit capture-log path; default = the sibling of capturePath; null skips */\n captureLogPath?: string | null;\n logProgress?: boolean;\n chromePath?: string;\n onProgress?: (progress: number) => void;\n}"],"sources":["../src/frame-diff.ts","../src/take.ts","../src/review.ts","../src/auth.ts","../src/edit-server.ts","../src/notes.ts","../src/frames.ts","../src/index.ts"],"sourcesContent":["// Tier-2 capture annotation: AFTER a capture, diff the recording's frames\n// around each action to record what the action actually CHANGED on screen —\n// `effectBox` (the changed region, viewport px) and `changeCoverage` (fraction\n// of the frame affected). The camera director (compositor/src/camera.ts)\n// consumes these to (a) frame the PAYOFF instead of the clicked control when\n// the result lands somewhere else, and (b) tell a global repaint (nav /\n// restyle → pull out to full view) from a local popover — a bbox alone can't.\n//\n// This is the pass camera.ts's header defers to \"the runtime (node) layer\":\n// pixels, not DOM. Frame-diff over the kept capture needs no browser hooks,\n// works for canvas apps a MutationObserver can't see, and is deterministic\n// over the recording (re-runnable on old takes).\n//\n// Failure-tolerant BY CONTRACT: annotation must never fail a take. Any ffmpeg\n// error / short read / degenerate window skips that event (fields stay absent\n// — the director falls back to its bbox heuristics, exactly the pre-tier-2\n// behaviour) and `annotateCaptureLog` never throws.\n\nimport { spawn } from \"node:child_process\";\nimport { resolveFfmpeg } from \"@open-take/compositor\";\nimport type { BBox, CaptureLog } from \"@open-take/compositor\";\n\n// Analysis raster: frames are decoded grayscale at ~ANALYSIS_W wide. 16px cells\n// on that raster (≈32px at 1080p) are the change unit — coarse enough that\n// h264 noise and a blinking caret vanish, fine enough to frame a suggestion\n// panel. Bumping ANALYSIS_W raises precision and cost together.\nconst ANALYSIS_W = 960;\nconst CELL = 16;\n/** min |gray delta| for a pixel to count as changed (h264 noise is ~2–6) */\nconst PIXEL_DELTA = 16;\n/** a cell is \"changed\" when > this fraction of its pixels changed */\nconst CELL_FRAC = 0.08;\n\n/** sample the \"before\" state this long before the action (ms). Kept TIGHT so\n * everything that happens on the approach — the capture's own\n * scrollIntoView, hover styles, the previous action's tail — is already\n * painted and therefore NOT attributed to this action; a click's own effect\n * can't land within one 60fps frame of the input, so this still precedes it.\n * (Also < NEXT_CLEARANCE_MS, so adjacent events' windows can never overlap —\n * no double attribution.) */\nconst BEFORE_MS = 30;\n/** sample the \"after\" state this long after the action (+durationMs) settles —\n * catches popover/reveal animations (ms; the capture itself sleeps ~1s\n * between actions, so there is normally room). */\nconst SETTLE_MS = 500;\n/** third sample this long after the \"after\" frame: cells STILL changing\n * between the two are ambient motion (hero video, carousel, streaming text)\n * — masked out of the action's diff so they can't poison effectBox (ms). */\nconst AMBIENT_MS = 250;\n/** keep this much clearance before the NEXT action so its changes are never\n * attributed to this one (ms). */\nconst NEXT_CLEARANCE_MS = 60;\n/** a box-less event (bare press) only gets an effectBox when the change is at\n * least this big — a blinking terminal cursor must not become a phantom\n * punch target on an event that used to mean \"full view\". */\nconst MIN_NO_BOX_COVERAGE = 0.015;\n\nexport type FrameDiffResult = {\n /** fraction of the frame's cells that changed (0..1) */\n coverage: number;\n /** bbox of the changed region in ANALYSIS-raster px, or undefined when\n * nothing beyond isolated specks changed */\n box?: BBox;\n};\n\n/** per-cell changed-pixel counts of |before−after| > PIXEL_DELTA (symmetric —\n * appearing light-on-dark content matters as much as dark-on-light). */\nfunction cellCounts(a: Uint8Array, b: Uint8Array, w: number, h: number): Uint16Array {\n const cw = Math.ceil(w / CELL);\n const counts = new Uint16Array(cw * Math.ceil(h / CELL));\n for (let y = 0; y < h; y++) {\n const row = y * w;\n const crow = Math.floor(y / CELL) * cw;\n for (let x = 0; x < w; x++) {\n const d = a[row + x]! - b[row + x]!;\n if (d > PIXEL_DELTA || d < -PIXEL_DELTA) counts[crow + Math.floor(x / CELL)]!++;\n }\n }\n return counts;\n}\n\n/**\n * Pure diff of two grayscale frames (same w×h). Cell-based: a cell counts as\n * changed when enough of its pixels moved. An isolated changed cell (no\n * changed 8-neighbour) is kept only when it changed OVERWHELMINGLY (≥ half its\n * pixels — a real single-cell payoff like a cart badge), else it's a speck\n * (caret blink, cursor sliver) and is dropped.\n *\n * `ambient` (optional) is a THIRD frame sampled shortly after `after`: any\n * cell still changing between `after` and `ambient` is ambient motion (hero\n * video, carousel, streaming text) and is excluded — without this, one\n * animating region would poison every event's effectBox with its union.\n *\n * `coverage` is the changed-CELL area fraction — the region the action\n * affected — deliberately not the changed-PIXEL fraction: a nav swap between\n * two white-ish pages repaints most of the frame while leaving most PIXELS\n * white-on-white, and it's the affected region the director's pull-out\n * threshold reasons about.\n */\nexport function diffFrames(\n before: Uint8Array,\n after: Uint8Array,\n w: number,\n h: number,\n ambient?: Uint8Array,\n): FrameDiffResult {\n const cw = Math.ceil(w / CELL);\n const ch = Math.ceil(h / CELL);\n const counts = cellCounts(before, after, w, h);\n const minCount = Math.max(1, Math.floor(CELL * CELL * CELL_FRAC));\n const strongCount = Math.floor(CELL * CELL * 0.5);\n const ambientCounts = ambient ? cellCounts(after, ambient, w, h) : undefined;\n const changed = (cx: number, cy: number): boolean =>\n cx >= 0 &&\n cy >= 0 &&\n cx < cw &&\n cy < ch &&\n counts[cy * cw + cx]! >= minCount &&\n (!ambientCounts || ambientCounts[cy * cw + cx]! < minCount);\n\n let kept = 0;\n let x0 = cw;\n let y0 = ch;\n let x1 = -1;\n let y1 = -1;\n for (let cy = 0; cy < ch; cy++) {\n for (let cx = 0; cx < cw; cx++) {\n if (!changed(cx, cy)) continue;\n let neighbour = counts[cy * cw + cx]! >= strongCount; // strong cells stand alone\n for (let dy = -1; dy <= 1 && !neighbour; dy++)\n for (let dx = -1; dx <= 1; dx++) {\n if (dx === 0 && dy === 0) continue;\n if (changed(cx + dx, cy + dy)) {\n neighbour = true;\n break;\n }\n }\n if (!neighbour) continue; // isolated speck\n kept++;\n if (cx < x0) x0 = cx;\n if (cy < y0) y0 = cy;\n if (cx > x1) x1 = cx;\n if (cy > y1) y1 = cy;\n }\n }\n if (kept === 0) return { coverage: 0 };\n return {\n coverage: kept / (cw * ch),\n box: {\n x: x0 * CELL,\n y: y0 * CELL,\n w: Math.min((x1 + 1) * CELL, w) - x0 * CELL,\n h: Math.min((y1 + 1) * CELL, h) - y0 * CELL,\n },\n };\n}\n\n/** Decode ONE grayscale frame at time `tSec` from `videoPath`, scaled to\n * aw×ah. Resolves undefined on any failure (missing frame near EOF, etc.). */\nfunction grabFrame(\n bin: string,\n videoPath: string,\n tSec: number,\n aw: number,\n ah: number,\n): Promise<Uint8Array | undefined> {\n return new Promise((res) => {\n const args = [\n \"-v\",\n \"error\",\n \"-ss\",\n tSec.toFixed(3),\n \"-i\",\n videoPath,\n \"-frames:v\",\n \"1\",\n \"-vf\",\n `scale=${aw}:${ah}`,\n \"-f\",\n \"rawvideo\",\n \"-pix_fmt\",\n \"gray\",\n \"-\",\n ];\n const c = spawn(bin, args, { stdio: [\"ignore\", \"pipe\", \"ignore\"] });\n const chunks: Buffer[] = [];\n c.stdout.on(\"data\", (b: Buffer) => chunks.push(b));\n c.on(\"error\", () => res(undefined));\n c.on(\"close\", () => {\n const buf = Buffer.concat(chunks);\n res(buf.length === aw * ah ? new Uint8Array(buf) : undefined);\n });\n });\n}\n\nexport type AnnotateOpts = {\n /** explicit ffmpeg binary; resolved via the compositor's resolver if omitted */\n ffmpegBin?: string;\n logProgress?: boolean;\n};\n\n/**\n * Annotate a capture log with per-event `effectBox` + `changeCoverage` by\n * diffing the capture video around each action. Returns a NEW log (input\n * untouched); events whose diff fails or whose sample window is degenerate are\n * returned unchanged. Never throws.\n */\nexport async function annotateCaptureLog(\n log: CaptureLog,\n videoPath: string,\n opts: AnnotateOpts = {},\n): Promise<CaptureLog> {\n try {\n const bin = opts.ffmpegBin ?? (await resolveFfmpeg());\n const vW = log.video.width;\n const vH = log.video.height;\n if (!(vW > 0) || !(vH > 0)) return log;\n const aw = Math.min(ANALYSIS_W, vW);\n const ah = Math.max(CELL, Math.round((vH * aw) / vW));\n // map analysis-raster px → viewport CSS px (what effectBox is declared in)\n const mx = log.viewport.w / aw;\n const my = log.viewport.h / ah;\n const durS = log.video.durationS ?? (log.tEndMs != null ? log.tEndMs / 1000 : undefined);\n\n const events = [...log.events];\n for (let i = 0; i < events.length; i++) {\n const e = events[i]!;\n const durationMs = \"durationMs\" in e && e.durationMs != null ? e.durationMs : 0;\n const before = Math.max(0, (e.tMs - BEFORE_MS) / 1000);\n let after = (e.tMs + durationMs + SETTLE_MS) / 1000;\n const next = events[i + 1];\n const ceil = Math.min(\n next ? (next.tMs - NEXT_CLEARANCE_MS) / 1000 : Number.POSITIVE_INFINITY,\n // never sample past the recording's end (the last frame would repeat —\n // fine — but a seek past EOF returns nothing)\n durS != null ? Math.max(0, durS - 0.05) : Number.POSITIVE_INFINITY,\n );\n after = Math.min(after, ceil);\n if (after <= before + 0.05) continue; // degenerate window — skip\n // ambient sample: only when it fits before the next action / EOF —\n // without room we go unmasked rather than sample another event's effect\n const ambientT = after + AMBIENT_MS / 1000;\n const wantAmbient = ambientT <= ceil;\n const [fa, fb, fc] = await Promise.all([\n grabFrame(bin, videoPath, before, aw, ah),\n grabFrame(bin, videoPath, after, aw, ah),\n wantAmbient ? grabFrame(bin, videoPath, ambientT, aw, ah) : Promise.resolve(undefined),\n ]);\n if (!fa || !fb) continue;\n const d = diffFrames(fa, fb, aw, ah, fc);\n // a box-less event (bare press) only gets an effectBox for a substantial\n // change — else a blinking cursor becomes a phantom punch target\n const hasBox = \"box\" in e && e.box != null;\n const attachBox = d.box && (hasBox || d.coverage >= MIN_NO_BOX_COVERAGE);\n events[i] = {\n ...e,\n changeCoverage: Math.round(d.coverage * 1000) / 1000,\n ...(attachBox && d.box\n ? {\n effectBox: {\n x: Math.round(d.box.x * mx),\n y: Math.round(d.box.y * my),\n w: Math.round(d.box.w * mx),\n h: Math.round(d.box.h * my),\n },\n }\n : {}),\n };\n if (opts.logProgress) {\n const eb = events[i]!.effectBox;\n // coverage 0 is sub-THRESHOLD, not proof of a dead beat: a 1px outline\n // or low-opacity highlight diffs below the noise floor and is often\n // visually fine — point the reader at the frames, not the number.\n const subThreshold =\n events[i]!.changeCoverage === 0 && !eb\n ? \" (sub-threshold — a subtle effect can score 0; judge by frames)\"\n : \"\";\n process.stderr.write(\n `frame-diff [${i}] ${e.kind ?? \"click\"}@${e.tMs}ms coverage=${events[i]!.changeCoverage}${\n eb ? ` effect=(${eb.x},${eb.y} ${eb.w}x${eb.h})` : \"\"\n }${subThreshold}\\n`,\n );\n }\n }\n return { ...log, events };\n } catch {\n return log; // annotation must never fail a take\n }\n}\n","// Take path resolution + prev snapshot — the file conventions behind the\n// conversational refine loop. A \"take\" is the artifact family makeTake writes\n// beside `<base>.mp4`; every CLI verb accepts any member of the family (or the\n// directory holding one) and resolves the rest by convention.\n\nimport { copyFile, readdir, rename, rm, stat } from \"node:fs/promises\";\nimport { basename, join, resolve } from \"node:path\";\n\nexport type TakePaths = {\n /** shared path prefix (no extension) */\n base: string;\n name: string;\n /** `<base>.mp4` — the polished, postable master */\n mp4Path: string;\n compositionPath: string;\n capturePath: string;\n captureLogPath: string;\n /** `<base>.review.mp4` — draft copy with burned beat badges (disposable) */\n reviewPath: string;\n /** `<base>.draft.mp4` — clean draft-quality re-render (disposable; never\n * clobbers the postable master) */\n draftPath: string;\n /** `<base>.ab.mp4` — the A/B variant reel (disposable) */\n abPath: string;\n /** `<base>.prev.mp4` — the previous master, kept so \"A\" can mean revert */\n prevPath: string;\n /** `<base>.dossier.md` — the agent's persisted exploration harvest (app\n * thesis, hero candidates tried/rejected, selector map, content answers,\n * hazards). Read it before re-exploring; it survives re-makes. */\n dossierPath: string;\n /** `<base>.notes.md` — the director's notes, appended one line per note by\n * the editor's Agent panel. The user→agent channel; see notes.ts. */\n notesPath: string;\n /** `<base>.notes.cursor` — byte offset of the last note the agent consumed.\n * Written ONLY by the reader, so it never races the server's append. */\n notesCursorPath: string;\n};\n\nasync function isFile(p: string): Promise<boolean> {\n return (await stat(p).catch(() => null))?.isFile() ?? false;\n}\n\n/** Strip any known take suffix to get the shared base, then derive the family.\n * A directory picks the `*.composition.json` that has a sibling capture. */\nexport async function resolveTakePaths(input: string): Promise<TakePaths> {\n let p = resolve(input);\n const s = await stat(p).catch(() => null);\n if (s?.isDirectory()) {\n // `<base>.prev.composition.json` is a pre-re-make snapshot, never a take.\n const comps = (await readdir(p)).filter(\n (e) => /\\.composition\\.json$/i.test(e) && !/\\.prev\\.composition\\.json$/i.test(e),\n );\n if (comps.length === 0) throw new Error(`no *.composition.json found in ${p}`);\n let pick = comps[0]!;\n for (const c of comps) {\n const base = join(p, c.replace(/\\.composition\\.json$/i, \"\"));\n if (await isFile(`${base}.capture.mp4`)) {\n pick = c;\n break;\n }\n }\n p = join(p, pick);\n }\n const base = p\n .replace(/\\.dossier\\.md$/i, \"\")\n .replace(/\\.notes\\.cursor$/i, \"\")\n .replace(/\\.notes\\.md$/i, \"\")\n .replace(/\\.prev\\.composition\\.json$/i, \"\")\n .replace(/\\.composition\\.json$/i, \"\")\n .replace(/\\.capture\\.json$/i, \"\")\n .replace(/\\.capture\\.mp4$/i, \"\")\n .replace(/\\.review\\.mp4$/i, \"\")\n .replace(/\\.draft\\.mp4$/i, \"\")\n .replace(/\\.ab\\.mp4$/i, \"\")\n .replace(/\\.prev\\.mp4$/i, \"\")\n .replace(/\\.mp4$/i, \"\");\n return {\n base,\n name: basename(base),\n mp4Path: `${base}.mp4`,\n compositionPath: `${base}.composition.json`,\n capturePath: `${base}.capture.mp4`,\n captureLogPath: `${base}.capture.json`,\n reviewPath: `${base}.review.mp4`,\n draftPath: `${base}.draft.mp4`,\n abPath: `${base}.ab.mp4`,\n prevPath: `${base}.prev.mp4`,\n dossierPath: `${base}.dossier.md`,\n notesPath: `${base}.notes.md`,\n notesCursorPath: `${base}.notes.cursor`,\n };\n}\n\n/** Friendly preflight: verbs die with a clear message instead of a raw ffmpeg\n * ENOENT when a take is missing the files they need. Old takes (or cleaned\n * ones) may have a composition + mp4 but no kept capture — those can be\n * watched but not re-rendered. */\nexport async function requireTakeFiles(\n take: TakePaths,\n opts: { capture?: boolean } = {},\n): Promise<void> {\n if (!(await isFile(take.compositionPath)))\n throw new Error(\n `missing ${take.compositionPath} — not a take produced by \\`make\\` (or the wrong path)`,\n );\n if (opts.capture && !(await isFile(take.capturePath)))\n throw new Error(\n `this take has no kept capture (${take.capturePath}) — re-rendering needs the frozen recording.\\n` +\n `Takes made before capture-keeping (or cleaned up) can't be re-rendered; run \\`make\\` again for a refinable take.`,\n );\n}\n\nexport type StagedPrev = {\n /** call after the render SUCCEEDS: the staged copy becomes `<base>.prev.mp4` */\n commit: () => Promise<void>;\n /** call when the render fails/refuses: discard the staged copy, keeping the\n * existing prev intact */\n abort: () => Promise<void>;\n};\n\n/** Stage a copy of the current master so it becomes `<base>.prev.mp4` only\n * AFTER the next render succeeds. A refused (validator) or crashed render\n * must NOT clobber the existing revert point — that would make \"keep the old\n * one\" replay the wrong version. No-op when there is no master yet. This is\n * what makes \"A\" (keep the old one) a mechanical revert instead of a memory. */\nexport async function stagePrev(mp4Path: string, prevPath: string): Promise<StagedPrev> {\n if (!(await isFile(mp4Path))) return { commit: async () => {}, abort: async () => {} };\n const pending = `${prevPath}.pending`;\n await copyFile(mp4Path, pending);\n return {\n commit: () => rename(pending, prevPath),\n abort: () => rm(pending, { force: true }),\n };\n}\n","// The conversational refine surface: beat sheets, badged review copies, and\n// A/B variant reels. No GUI — the system video player shows purpose-built\n// artifacts and the terminal (agent) is the only input channel.\n//\n// beats — a numbered stdout table: the shared map for \"beat 3: no zoom\"\n// review — `<base>.review.mp4`: fast draft with beat badges burned in\n// (the video itself teaches the referring vocabulary) + watermark\n// ab — `<base>.ab.mp4`: ONE knob, 2-4 labeled variants, each played\n// twice — a taste question answered with one letter\n//\n// Badges/labels are drawn by the revideo scene in Chrome (composition.review),\n// NOT by ffmpeg drawtext — slim ffmpeg builds ship without font filters.\n\nimport { spawn } from \"node:child_process\";\nimport { readFile, rm, stat } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport {\n type CaptureLog,\n type CompEvent,\n type CompositionIssue,\n FINISH,\n type FinishName,\n LOOKS,\n type LookName,\n MOTION,\n type MotionName,\n type ReviewBadge,\n type TakeComposition,\n ZOOM_LEVELS,\n type ZoomLevelName,\n finishName,\n formatIssues,\n lookName,\n math,\n motionName,\n renderTake,\n resolveFfmpeg,\n validateComposition,\n zoomLevelName,\n} from \"@open-take/compositor\";\nimport { ensureChrome } from \"./cdp\";\nimport { type TakePaths, requireTakeFiles } from \"./take\";\n\n/** Sibling capture log (`<capture>.json`), if present — enables the\n * capture-lock check; silently absent otherwise (matches index.ts). */\nasync function loadLogSibling(capturePath: string): Promise<CaptureLog | undefined> {\n try {\n return JSON.parse(\n await readFile(resolve(capturePath).replace(/\\.mp4$/i, \".json\"), \"utf8\"),\n ) as CaptureLog;\n } catch {\n return undefined;\n }\n}\n\n// --- shared formatting -------------------------------------------------------\n\nconst KIND_LABEL: Record<CompEvent[\"kind\"], string> = {\n click: \"click\",\n type: \"type\",\n drag: \"drag\",\n dropFiles: \"drop\",\n scroll: \"scroll\",\n hover: \"hover\",\n press: \"key\",\n};\n\nfunction beatTitle(e: CompEvent): string {\n if (e.label) return e.label;\n if (e.kind === \"type\" && e.text) return `\"${e.text}\"`;\n if (e.kind === \"press\" && e.keys) return e.keys;\n return e.kind;\n}\n\nconst trunc = (s: string, n: number): string => (s.length > n ? `${s.slice(0, n - 1)}…` : s);\n\n/** \"click Open menu\" — the shared beat vocabulary (beat sheet rows, frames rows). */\nexport function beatLabel(e: CompEvent): string {\n return `${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)}`;\n}\n\nfunction fmtTime(ms: number): string {\n const s = Math.max(0, Math.round(ms / 1000));\n return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, \"0\")}`;\n}\n\n/** \"zoom medium (×1.5)\" | \"zoom ×1.85 (custom)\" | \"wide\" */\nfunction zoomText(e: CompEvent): string {\n if (!e.zoom.enabled) return \"wide\";\n const name = zoomLevelName(e.zoom.scale);\n const x = `×${Number(e.zoom.scale.toFixed(2))}`;\n return name ? `zoom ${name} (${x})` : `zoom ${x} (custom)`;\n}\n\n// --- the beat sheet ----------------------------------------------------------\n\nexport function buildBeatSheet(comp: TakeComposition, name: string): string {\n const n = comp.events.length;\n const look = lookName(comp.framing) ?? \"custom\";\n const pace = motionName(comp.cursor) ?? \"custom\";\n const finish = finishName(comp.motionBlur) ?? \"custom\";\n const trim = comp.startMs ?? 0;\n const lines: string[] = [\n `${name} · ${((comp.durationMs - trim) / 1000).toFixed(1)}s · ${n} beat${n === 1 ? \"\" : \"s\"} · look ${look} · pace ${pace} · finish ${finish}${trim ? ` · head −${(trim / 1000).toFixed(1)}s` : \"\"}`,\n ];\n const first = comp.events[0];\n if (!first || first.zoom.inAtMs > 400) lines.push(` in 0:00 full view, cursor glides in`);\n comp.events.forEach((e, i) => {\n const num = String(i + 1).padStart(2, \" \");\n const kind = KIND_LABEL[e.kind].padEnd(6, \" \");\n const title = trunc(beatTitle(e), 24).padEnd(25, \" \");\n lines.push(` ${num} ${fmtTime(e.tMs)} ${kind} ${title} ${zoomText(e)}`);\n });\n const last = comp.events[n - 1];\n if (last) {\n const endMs = last.tMs + (last.durationMs ?? 0) + comp.cursor.holdMs;\n lines.push(` out ${fmtTime(endMs)} zoom releases, holds to ${fmtTime(comp.durationMs)}`);\n }\n lines.push(\n `say it like: \"beat 2: no zoom\" · \"tighter on beat 3\" · \"look: slate\" · \"pace: brisk\"`,\n );\n return lines.join(\"\\n\");\n}\n\nexport const SAY_IT_CARD = `SAY IT, I'LL CUT IT\n instant (~10s) zoom off / tighter / looser on a beat · re-center a beat (name the\n element) · hold longer · pace: calm / natural / brisk · look:\n midnight / ink / slate / ocean / plum / ember / paper / plain ·\n finish: smooth / crisp / heavy · quicker intro · shorter tail\n re-shoot (~1m) change what's clicked or typed · add / cut / reorder beats ·\n retime an action\n compare taste questions come back as an A/B reel — answer with a letter\n (\"B\"), or \"between A and B\", or \"none, go darker\"`;\n\n// --- review copy -------------------------------------------------------------\n\n/** Badge windows: each beat owns [its camera-ramp start, the next beat's) —\n * the pill swaps as the camera actually starts moving toward the beat.\n * Timing comes from the REAL schedule (cameraRampSchedule), so a\n * dwell-delayed pull-out (departing after its stored inAtMs) badges when it\n * moves, not when the formula guessed; beats the camera holds through fall\n * back to inAtMs. INTRO/TAIL bracket them. */\nexport function buildBadges(comp: TakeComposition): ReviewBadge[] {\n const n = comp.events.length;\n const badges: ReviewBadge[] = [];\n const ramps = math.cameraRampSchedule(comp);\n let prevStart = 0;\n const starts = comp.events.map((e, i) => {\n const s = Math.max(ramps[i]?.startMs ?? e.zoom.inAtMs, prevStart + 1);\n prevStart = s;\n return s;\n });\n if (n === 0 || starts[0]! > 400)\n badges.push({ fromMs: 0, toMs: starts[0] ?? comp.durationMs, text: \"INTRO\" });\n comp.events.forEach((e, i) => {\n const last = i === n - 1;\n // a dwell-delayed landing can put the arrival after tMs — own the badge\n // window until the action AND the camera have both settled.\n const arrived = Math.max(e.tMs, ramps[i]?.landMs ?? e.tMs);\n const endOwn = arrived + (e.durationMs ?? 0) + comp.cursor.holdMs;\n const to = last ? Math.min(endOwn, comp.durationMs) : starts[i + 1]!;\n badges.push({\n fromMs: starts[i]!,\n toMs: to,\n text: `BEAT ${i + 1}/${n} · ${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)} · ${zoomText(e)}`,\n });\n if (last && to < comp.durationMs + 1000)\n badges.push({ fromMs: to, toMs: comp.durationMs + 1500, text: \"TAIL\" });\n });\n return badges;\n}\n\n/** Draft-quality transform: 30fps cap + motion blur OFF — up to ~12× faster\n * than a blurred 60fps master, close enough for composition-level notes.\n * (2 blur samples would render 2× the frames for a tmix window that rounds to\n * 1 — all cost, zero blur.) FEEL questions (blur, pace, zoom silkiness) must\n * be judged on full quality — use `ab`. */\nexport function toDraft(comp: TakeComposition): TakeComposition {\n const { motionBlur: _mb, ...rest } = comp;\n return { ...rest, output: { ...comp.output, fps: Math.min(30, comp.output.fps) } };\n}\n\nexport type ReviewOpts = {\n chromePath?: string;\n logProgress?: boolean;\n};\n\nexport async function renderReview(\n take: TakePaths,\n opts: ReviewOpts = {},\n): Promise<{ reviewPath: string; sheet: string; warnings: CompositionIssue[] }> {\n await requireTakeFiles(take, { capture: true });\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const captureLog = await loadLogSibling(take.capturePath);\n const chromePath = await ensureChrome(opts.chromePath);\n const decorated: TakeComposition = {\n ...toDraft(comp),\n review: { watermark: \"REVIEW\", badges: buildBadges(comp) },\n };\n const { warnings } = await renderTake({\n composition: decorated,\n videoPath: take.capturePath,\n outPath: take.reviewPath,\n captureLog,\n logProgress: opts.logProgress ?? true,\n chromePath,\n writeCompositionSibling: false,\n });\n return { reviewPath: take.reviewPath, sheet: buildBeatSheet(comp, take.name), warnings };\n}\n\n/** Draft-quality re-render of the CURRENT composition to `<base>.draft.mp4` —\n * no badges, no watermark, and never the master's path, so a mid-refine\n * frame-check (edit → draft → `frames`) costs seconds without downgrading or\n * clobbering the postable mp4. Disposable like the review copy. */\nexport async function renderDraft(\n take: TakePaths,\n opts: ReviewOpts = {},\n): Promise<{ draftPath: string; warnings: CompositionIssue[] }> {\n await requireTakeFiles(take, { capture: true });\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const captureLog = await loadLogSibling(take.capturePath);\n const chromePath = await ensureChrome(opts.chromePath);\n const { warnings } = await renderTake({\n composition: toDraft(comp),\n videoPath: take.capturePath,\n outPath: take.draftPath,\n captureLog,\n logProgress: opts.logProgress ?? true,\n chromePath,\n writeCompositionSibling: false,\n });\n return { draftPath: take.draftPath, warnings };\n}\n\n// --- A/B variant reels -------------------------------------------------------\n\nexport type AbKnob =\n | { kind: \"zoom\"; beat: number } // 1-based beat number\n | { kind: \"look\" }\n | { kind: \"pace\" }\n | { kind: \"finish\" }\n | { kind: \"path\"; path: string }; // raw dot-path escape hatch (agent use)\n\nexport type AbVariant = { letter: string; desc: string; comp: TakeComposition };\n\nexport function parseSetFlag(set: string, beat?: number): { knob: AbKnob; values: string[] } {\n const eq = set.indexOf(\"=\");\n if (eq < 1) throw new Error(`ab: --set expects <knob>=<v1>,<v2>[,<v3>] (got \"${set}\")`);\n const key = set.slice(0, eq).trim();\n const values = set\n .slice(eq + 1)\n .split(\",\")\n .map((v) => v.trim())\n .filter(Boolean);\n if (values.length < 1) throw new Error(`ab: --set ${key}= needs at least one value`);\n if (values.length > 3) throw new Error(`ab: at most 3 requested values (plus current) per reel`);\n if (key === \"zoom\") {\n if (!beat) throw new Error(`ab: --set zoom=… needs --beat <n> (which beat to reframe)`);\n return { knob: { kind: \"zoom\", beat }, values };\n }\n if (key === \"look\" || key === \"pace\" || key === \"finish\") return { knob: { kind: key }, values };\n if (key.includes(\".\")) return { knob: { kind: \"path\", path: key }, values };\n throw new Error(\n `ab: unknown knob \"${key}\" — use zoom (with --beat), look, pace, finish, or a raw dot-path like cursor.holdMs`,\n );\n}\n\nfunction setPath(comp: TakeComposition, path: string, raw: string): TakeComposition {\n // coerce booleans/null BEFORE the number check — a string \"false\" is truthy,\n // which would silently leave e.g. zoom.enabled ON while the variant label\n // claims otherwise (a reel comparing two identical clips).\n const t = raw.trim();\n const value: unknown =\n t === \"true\"\n ? true\n : t === \"false\"\n ? false\n : t === \"null\"\n ? null\n : Number.isFinite(Number(raw)) && t !== \"\"\n ? Number(raw)\n : raw;\n const parts = path.split(\".\");\n const next = structuredClone(comp) as unknown as Record<string, unknown>;\n let node: Record<string, unknown> = next;\n for (const p of parts.slice(0, -1)) {\n const child = node[p];\n if (typeof child !== \"object\" || child == null)\n throw new Error(`ab: path \"${path}\" — \"${p}\" is not an object`);\n node = child as Record<string, unknown>;\n }\n node[parts[parts.length - 1]!] = value;\n return next as unknown as TakeComposition;\n}\n\n/** Current-state description for a knob (the implicit \"keep it\" variant). */\nfunction currentDesc(comp: TakeComposition, knob: AbKnob): string {\n if (knob.kind === \"zoom\") {\n const e = comp.events[knob.beat - 1];\n return e ? zoomText(e) : \"?\";\n }\n if (knob.kind === \"look\") return lookName(comp.framing) ?? \"custom look\";\n if (knob.kind === \"pace\") return motionName(comp.cursor) ?? \"custom pace\";\n if (knob.kind === \"finish\") return finishName(comp.motionBlur) ?? \"custom finish\";\n const parts = knob.path.split(\".\");\n let node: unknown = comp;\n for (const p of parts) node = (node as Record<string, unknown> | undefined)?.[p];\n return `${knob.path}=${JSON.stringify(node)}`;\n}\n\nfunction applyKnob(comp: TakeComposition, knob: AbKnob, value: string): TakeComposition {\n if (knob.kind === \"zoom\") {\n const i = knob.beat - 1;\n const e = comp.events[i];\n if (!e) throw new Error(`ab: --beat ${knob.beat} out of range (1-${comp.events.length})`);\n const events = comp.events.slice();\n if (value === \"off\" || value === \"wide\") {\n events[i] = { ...e, zoom: { ...e.zoom, enabled: false } };\n } else {\n const scale = value in ZOOM_LEVELS ? ZOOM_LEVELS[value as ZoomLevelName] : Number(value);\n if (!Number.isFinite(scale))\n throw new Error(`ab: zoom value \"${value}\" — use off/light/medium/tight/close or a number`);\n events[i] = { ...e, zoom: { ...e.zoom, enabled: true, scale } };\n }\n return { ...comp, events };\n }\n if (knob.kind === \"look\") {\n const look = LOOKS[value as LookName];\n if (!look)\n throw new Error(`ab: unknown look \"${value}\" — one of ${Object.keys(LOOKS).join(\"/\")}`);\n return { ...comp, framing: { ...comp.framing, ...structuredClone(look) } };\n }\n if (knob.kind === \"pace\") {\n const pace = MOTION[value as MotionName];\n if (!pace)\n throw new Error(`ab: unknown pace \"${value}\" — one of ${Object.keys(MOTION).join(\"/\")}`);\n // zoomInMs only affects rendering through each beat's zoom.inAtMs (derived\n // at plan time as tMs − zoomInMs). Rebase events still sitting on the OLD\n // derivation so the new pace actually changes the zoom ramps; hand-tuned\n // inAtMs values are left alone.\n const oldZoomInMs = comp.cursor.zoomInMs;\n const events = comp.events.map((e) =>\n e.zoom.inAtMs === Math.max(0, e.tMs - oldZoomInMs)\n ? { ...e, zoom: { ...e.zoom, inAtMs: Math.max(0, e.tMs - pace.zoomInMs) } }\n : e,\n );\n return { ...comp, events, cursor: { ...comp.cursor, ...pace } };\n }\n if (knob.kind === \"finish\") {\n if (!(value in FINISH))\n throw new Error(`ab: unknown finish \"${value}\" — one of ${Object.keys(FINISH).join(\"/\")}`);\n const mb = FINISH[value as FinishName];\n const { motionBlur: _mb, ...rest } = comp;\n return mb ? { ...rest, motionBlur: { ...mb } } : rest;\n }\n return setPath(comp, knob.path, value);\n}\n\nfunction variantDesc(knob: AbKnob, value: string, comp: TakeComposition): string {\n if (knob.kind === \"zoom\") {\n const e = comp.events[knob.beat - 1];\n return e ? zoomText(e) : value;\n }\n if (knob.kind === \"path\") return `${knob.path}=${value}`;\n return value;\n}\n\n/** The reel's time window (ms): a beat's zoom arc with lead-in/out padding, so\n * a taste question costs a ~4s render per variant, not the whole take. The\n * window is the UNION across all variant compositions — a variant with a\n * longer hold/zoom-out (or a rebased inAtMs) must not be cut mid-settle, since\n * the settle is exactly what the reel exists to judge. */\nexport function abWindow(\n comps: TakeComposition[],\n beat: number | undefined,\n full: boolean,\n): [number, number] | undefined {\n if (full) return undefined;\n const base = comps[0];\n if (!base || base.events.length === 0) return undefined;\n if (beat != null && (beat < 1 || beat > base.events.length))\n throw new Error(`ab: --beat ${beat} out of range (1-${base.events.length})`);\n let i = beat != null ? beat - 1 : base.events.findIndex((e) => e.zoom.enabled);\n if (i < 0) i = 0;\n let from = Number.POSITIVE_INFINITY;\n let to = 0;\n for (const c of comps) {\n const e = c.events[i];\n if (!e) continue;\n // The REAL camera schedule (cameraRampSchedule): a pull-out ramp can start\n // up to zoomOutMs before its tMs, or — dwell-delayed — depart later and\n // LAND after its own tMs. Open on the actual departure so the clip keeps a\n // static lead-in, and close when the framing is actually released (the\n // next anchor's actual departure), so a late landing is never cut\n // mid-settle — the settle is exactly what the reel exists to judge.\n const ramps = math.cameraRampSchedule(c);\n const ramp = ramps[i];\n const rampFrom = ramp ? ramp.startMs : Math.min(e.zoom.inAtMs, e.tMs - c.cursor.zoomOutMs);\n from = Math.min(from, Math.max(0, rampFrom - 1200));\n let nextStart: number | undefined;\n for (let j = i + 1; j < c.events.length; j++) {\n const r = ramps[j];\n if (r) {\n nextStart = r.startMs;\n break;\n }\n }\n const landMs = Math.max(e.tMs, ramp?.landMs ?? e.tMs);\n const ownEnd = landMs + (e.durationMs ?? 0) + c.cursor.holdMs + c.cursor.zoomOutMs;\n // no durationMs clamp: the scene runs to its last keyframe + tail, and a\n // range end past the scene's end just stops at the end.\n to = Math.max(to, (nextStart ?? ownEnd) + 400);\n }\n if (!Number.isFinite(from)) return undefined;\n return [from, Math.max(to, from + 1500)];\n}\n\nexport type AbOpts = {\n set: string;\n beat?: number;\n full?: boolean;\n draft?: boolean;\n chromePath?: string;\n logProgress?: boolean;\n};\n\nconst LETTERS = [\"A\", \"B\", \"C\", \"D\"];\n\nexport async function renderAbReel(\n take: TakePaths,\n opts: AbOpts,\n): Promise<{ abPath: string; legend: string }> {\n await requireTakeFiles(take, { capture: true });\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const captureLog = await loadLogSibling(take.capturePath);\n const chromePath = await ensureChrome(opts.chromePath);\n const { knob, values } = parseSetFlag(opts.set, opts.beat);\n\n // variants: the CURRENT state first (so \"A\" always means \"keep it\"), then the\n // requested values — skipping a request that just re-states the current state.\n const cur = currentDesc(comp, knob);\n const variants: AbVariant[] = [{ letter: \"A\", desc: `current (${cur})`, comp }];\n for (const v of values) {\n const applied = applyKnob(comp, knob, v);\n const desc = variantDesc(knob, v, applied);\n if (desc === cur || variants.some((x) => x.desc === desc)) continue;\n variants.push({ letter: LETTERS[variants.length]!, desc, comp: applied });\n }\n if (variants.length < 2)\n throw new Error(`ab: every requested value matches the current state — nothing to compare`);\n\n // validate EVERY variant up front (milliseconds) — one bad value must not\n // waste the minutes already spent rendering the variants before it.\n for (const v of variants) {\n const issues = validateComposition(v.comp, captureLog ? { captureLog } : {});\n const errors = issues.filter((i) => i.severity === \"error\");\n if (errors.length)\n throw new Error(`ab: variant ${v.letter} (${v.desc}) is invalid:\\n${formatIssues(errors)}`);\n }\n\n const windowMs = abWindow(\n variants.map((v) => v.comp),\n opts.beat,\n opts.full ?? false,\n );\n const rangeSec = windowMs\n ? ([windowMs[0] / 1000, windowMs[1] / 1000] as [number, number])\n : undefined;\n\n // FEEL knobs are judged at FULL quality (blur by eye); --draft opts down.\n const clips: string[] = [];\n try {\n for (const v of variants) {\n const base = opts.draft ? toDraft(v.comp) : v.comp;\n const decorated: TakeComposition = {\n ...base,\n review: { label: `${v.letter} · ${v.desc}` },\n };\n const clip = `${take.base}.ab.${v.letter}.mp4`;\n if (opts.logProgress !== false)\n process.stderr.write(\n `variant ${v.letter} · ${v.desc}${rangeSec ? ` · window ${rangeSec[0].toFixed(1)}–${rangeSec[1].toFixed(1)}s` : \"\"}\\n`,\n );\n await renderTake({\n composition: decorated,\n videoPath: take.capturePath,\n outPath: clip,\n captureLog,\n logProgress: opts.logProgress ?? true,\n chromePath,\n rangeSec,\n writeCompositionSibling: false,\n });\n clips.push(clip);\n }\n\n // reel = A B C A B C with short black gaps; each variant seen twice so the\n // eye can confirm on the second pass.\n await concatWithGaps([...clips, ...clips], take.abPath, {\n width: comp.output.width,\n height: comp.output.height,\n fps: opts.draft ? Math.min(30, comp.output.fps) : comp.output.fps,\n });\n } finally {\n await Promise.all(clips.map((c) => rm(c, { force: true })));\n }\n\n const legend = [\n `A/B reel: ${take.abPath} (${knobLabel(knob)})`,\n ...variants.map((v) => ` ${v.letter} ${v.desc}`),\n `answer with a letter — or \"between A and B\" / \"none, try …\"`,\n ].join(\"\\n\");\n return { abPath: take.abPath, legend };\n}\n\nfunction knobLabel(knob: AbKnob): string {\n if (knob.kind === \"zoom\") return `beat ${knob.beat} · zoom`;\n if (knob.kind === \"path\") return knob.path;\n return knob.kind;\n}\n\n/** before/after reel from the existing prev + current masters — no render at\n * all, pure ffmpeg trims. Order convention: BEFORE then AFTER, twice. */\nexport async function renderBeforeAfter(\n take: TakePaths,\n opts: { beat?: number; full?: boolean } = {},\n): Promise<{ abPath: string; legend: string }> {\n await requireTakeFiles(take);\n if (!(await stat(take.prevPath).catch(() => null)))\n throw new Error(`ab --before-after: no ${take.prevPath} yet (it appears after a re-render)`);\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const winComp = abWindow([comp], opts.beat, opts.full ?? false);\n // the masters are delivered files: a composition startMs head-trim already\n // removed their head, so composition-timeline windows shift back by it.\n const trim = comp.startMs ?? 0;\n const win = winComp\n ? ([Math.max(0, winComp[0] - trim), Math.max(0, winComp[1] - trim)] as [number, number])\n : undefined;\n const cut = async (src: string, out: string) => {\n const args = [\"-y\", \"-loglevel\", \"error\", \"-i\", src];\n if (win) args.push(\"-ss\", String(win[0] / 1000), \"-t\", String((win[1] - win[0]) / 1000));\n args.push(\"-c:v\", \"libx264\", \"-crf\", \"18\", \"-pix_fmt\", \"yuv420p\", \"-an\", out);\n await ffmpeg(args);\n };\n const before = `${take.base}.ab.before.mp4`;\n const after = `${take.base}.ab.after.mp4`;\n await cut(take.prevPath, before);\n await cut(take.mp4Path, after);\n await concatWithGaps([before, after, before, after], take.abPath, {\n width: comp.output.width,\n height: comp.output.height,\n fps: comp.output.fps,\n });\n await Promise.all([rm(before, { force: true }), rm(after, { force: true })]);\n const legend = [\n `before/after reel: ${take.abPath}`,\n ` plays BEFORE then AFTER, twice — say \"keep the old one\" to revert`,\n ].join(\"\\n\");\n return { abPath: take.abPath, legend };\n}\n\n// --- ffmpeg helpers ----------------------------------------------------------\n\nasync function ffmpeg(args: string[]): Promise<void> {\n const bin = await resolveFfmpeg();\n return new Promise((res, rej) => {\n const c = spawn(bin, 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(`ffmpeg exited ${code}: ${err}`))));\n });\n}\n\n/** Concat clips with a 0.35s black gap between each, re-encoding via the concat\n * FILTER (robust to per-clip encoder variance; everything shares WxH/fps). The\n * gap comes from a lavfi color source — no font/text filters needed. */\nasync function concatWithGaps(\n clips: string[],\n outPath: string,\n v: { width: number; height: number; fps: number },\n): Promise<void> {\n const args = [\"-y\", \"-loglevel\", \"error\"];\n for (const c of clips) args.push(\"-i\", resolve(c));\n args.push(\"-f\", \"lavfi\", \"-t\", \"0.35\", \"-i\", `color=c=black:s=${v.width}x${v.height}:r=${v.fps}`);\n const gapIdx = clips.length;\n // A gap after every clip except the last: [0][gap][1][gap]…[n-1]\n const seq: string[] = [];\n const gapUses = clips.length - 1;\n const split =\n gapUses > 1\n ? `[${gapIdx}:v]split=${gapUses}${Array.from({ length: gapUses }, (_, i) => `[g${i}]`).join(\"\")};`\n : \"\";\n clips.forEach((_, i) => {\n seq.push(`[${i}:v]`);\n if (i < clips.length - 1) seq.push(gapUses > 1 ? `[g${i}]` : `[${gapIdx}:v]`);\n });\n const filter = `${split}${seq.join(\"\")}concat=n=${seq.length}:v=1:a=0[v]`;\n args.push(\n \"-filter_complex\",\n filter,\n \"-map\",\n \"[v]\",\n \"-c:v\",\n \"libx264\",\n \"-crf\",\n \"18\",\n \"-pix_fmt\",\n \"yuv420p\",\n \"-r\",\n String(v.fps),\n \"-an\",\n resolve(outPath),\n );\n await ffmpeg(args);\n}\n\n// --- open / reveal -----------------------------------------------------------\n\n/** Spawn a fire-and-forget opener. spawn ENOENT arrives ASYNCHRONOUSLY on the\n * child's \"error\" event (a try/catch around spawn never sees it and the\n * process would die with an unhandled error) — so degrade via the listener.\n *\n * `windowsVerbatimArguments` hands argv to Windows unmodified: cmd.exe and explorer.exe\n * re-parse the raw command line by rules node's own quoting doesn't match, so\n * the command builders below quote for them (see winQuote). */\nexport type OpenerCommand = {\n command: string;\n args: string[];\n windowsVerbatimArguments: boolean;\n};\n\nfunction spawnOpener(spec: OpenerCommand, fallbackLine: string): void {\n try {\n const c = spawn(spec.command, spec.args, {\n stdio: \"ignore\",\n detached: true,\n windowsVerbatimArguments: spec.windowsVerbatimArguments,\n });\n c.on(\"error\", () => process.stdout.write(fallbackLine));\n c.unref();\n } catch {\n process.stdout.write(fallbackLine);\n }\n}\n\n/** Wrap a path/URL for a verbatim Windows command line. Safe unquoted-inside:\n * `\"` is illegal in Windows filenames, and cmd stops treating `&` `^` `|` as\n * metacharacters once quoted. */\nconst winQuote = (s: string) => `\"${s}\"`;\n\n/** Pure command specs keep platform quoting independently testable on every\n * CI runner, including the Windows-only `start` title argument rule. */\nexport function getOpenCommand(\n target: string,\n platform: NodeJS.Platform = process.platform,\n): OpenerCommand {\n if (platform === \"darwin\") {\n return { command: \"open\", args: [target], windowsVerbatimArguments: false };\n }\n if (platform === \"win32\") {\n return {\n command: \"cmd\",\n args: [\"/c\", \"start\", '\"\"', winQuote(target)],\n windowsVerbatimArguments: true,\n };\n }\n return { command: \"xdg-open\", args: [target], windowsVerbatimArguments: false };\n}\n\nexport function getRevealCommand(\n absolutePath: string,\n platform: NodeJS.Platform = process.platform,\n): OpenerCommand {\n if (platform === \"darwin\") {\n return { command: \"open\", args: [\"-R\", absolutePath], windowsVerbatimArguments: false };\n }\n if (platform === \"win32\") {\n return {\n command: \"explorer\",\n // explorer takes ONE argument: `/select,` glued to a quoted path.\n args: [`/select,${winQuote(absolutePath)}`],\n windowsVerbatimArguments: true,\n };\n }\n return {\n command: \"xdg-open\",\n args: [dirname(absolutePath)],\n windowsVerbatimArguments: false,\n };\n}\n\n/** Open a file with the OS default player; degrade to printing the path. */\nexport function openPath(p: string): void {\n const abs = resolve(p);\n openWithOs(abs, `open: ${abs}\\n`);\n}\n\n/** Hand a path or URL to the OS default handler. Windows needs `cmd /c start`\n * with an EMPTY first argument: `start` reads a lone quoted argument as the\n * window TITLE, so `start \"<file>\"` opens a blank console instead of the file. */\nexport function openWithOs(target: string, fallbackLine: string): void {\n spawnOpener(getOpenCommand(target), fallbackLine);\n}\n\n/** Reveal a file in Finder/Explorer; degrade to printing the path. */\nexport function revealPath(p: string): void {\n const abs = resolve(p);\n spawnOpener(getRevealCommand(abs), `at: ${abs}\\n`);\n}\n","// open-take auth — one-time interactive login on a PERSISTENT profile.\n//\n// Launches a HEADED Chrome on ~/.open-take/profiles/<name> (or an explicit\n// dir), navigates to the login URL, and waits for the human to finish (press\n// Enter in the terminal, or quit Chrome). Later captures reuse the same\n// profile via `make --profile <name>` — still headless — so the recording is\n// authenticated without ever typing credentials into a TakePlan.\n//\n// Deliberately NOT launchBrowser: no CDP, no debug port, no automation flags\n// beyond the keychain ones — as close to a normal browsing session as an\n// isolated profile gets. The keychain flags (--password-store=basic /\n// --use-mock-keychain) MUST match the capture launch exactly: Chrome encrypts\n// cookies with the active keychain, so a mismatch would write cookies the\n// headless capture can't decrypt.\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { mkdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { ensureChrome } from \"./cdp\";\n\n/** The canonical profile dir for a named auth profile. Names are a single\n * path segment — anything else (\"../\", \"/\", spaces-only) would escape or\n * collide with other open-take state under ~/.open-take. */\nexport function profileDir(name: string): string {\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || name.includes(\"..\"))\n throw new Error(\n `invalid profile name ${JSON.stringify(name)} — use letters/digits/dots/dashes/underscores`,\n );\n return join(homedir(), \".open-take\", \"profiles\", name);\n}\n\nexport type AuthOpts = {\n /** profile name (dir under ~/.open-take/profiles/) — or pass `dir` */\n name: string;\n /** explicit profile dir (overrides `name`) */\n dir?: string;\n /** where to send the user to log in (default about:blank) */\n url?: string;\n /** explicit Chrome binary (else auto-resolved / auto-downloaded) */\n chromePath?: string;\n};\n\nexport type AuthResult = { dir: string };\n\n/**\n * Open a headed Chrome on the persistent profile and resolve when the user is\n * done (Enter on stdin, or the browser quits). The profile dir is returned so\n * callers can print how to use it.\n */\nexport async function authProfile(opts: AuthOpts): Promise<AuthResult> {\n const dir = opts.dir ?? profileDir(opts.name);\n mkdirSync(dir, { recursive: true });\n const chrome = await ensureChrome(opts.chromePath);\n const proc: ChildProcess = spawn(\n chrome,\n [\n `--user-data-dir=${dir}`,\n \"--no-first-run\",\n \"--no-default-browser-check\",\n // keychain parity with launchBrowser (see header)\n \"--password-store=basic\",\n \"--use-mock-keychain\",\n \"--window-size=1280,900\",\n opts.url ?? \"about:blank\",\n ],\n { stdio: [\"ignore\", \"ignore\", \"ignore\"], detached: false },\n );\n\n let spawnErr: Error | undefined;\n await new Promise<void>((resolveWait) => {\n let settled = false;\n const done = () => {\n if (settled) return;\n settled = true;\n process.stdin.off(\"data\", onEnter);\n if (process.stdin.isTTY) process.stdin.pause();\n resolveWait();\n };\n const onEnter = () => done();\n proc.once(\"exit\", done);\n proc.once(\"error\", (e) => {\n // spawn failure (bad chromePath, EACCES): 'exit' never fires — surface\n // the real error instead of crashing on an unhandled 'error' event.\n spawnErr = e;\n done();\n });\n if (process.stdin.isTTY) {\n process.stdin.resume();\n process.stdin.on(\"data\", onEnter);\n }\n });\n if (spawnErr) throw new Error(`auth: failed to launch Chrome: ${spawnErr.message}`);\n\n // If the user pressed Enter with Chrome still open, close it gracefully so\n // the profile (cookies, local storage) flushes to disk — and WAIT for the\n // exit (cleared timer, SIGKILL fallback) so we never print \"profile saved\"\n // while Chrome still holds the SingletonLock mid-flush.\n if (proc.exitCode == null) {\n proc.kill(\"SIGTERM\");\n await new Promise<void>((r) => {\n const tm = setTimeout(() => {\n try {\n proc.kill(\"SIGKILL\");\n } catch {\n /* already gone */\n }\n r();\n }, 4000);\n proc.once(\"exit\", () => {\n clearTimeout(tm);\n r();\n });\n });\n }\n // give Chrome a beat to finish flushing profile files\n await new Promise((r) => setTimeout(r, 500));\n return { dir };\n}\n","// edit-server — the local bridge that powers `open-take edit <take>`. It serves\n// the built editor SPA AND a tiny JSON/stream API over the take's files, so the\n// browser editor can load a take, save edits, and trigger a real (Node-only)\n// revideo render with live progress — all on 127.0.0.1, no external services.\n//\n// Endpoints (all under /api):\n// GET /api/take → { composition, captureLog, source, videoUrl, mp4Url, mtime }\n// GET /api/take/video → the kept capture mp4 (HTTP Range, for <video> seeking)\n// GET /api/take/output[?v=tok] → the latest rendered mp4 (HTTP Range)\n// POST /api/composition → guarded validate + persist (428 without base, 400 invalid)\n// POST /api/render → guarded persist + start → { jobId, mtime } (409 conflict/busy)\n// GET /api/render/:id/events → SSE: progress* → done {mp4Url} | failed {message}\n// Everything else is static from the editor dist (SPA fallback to index.html).\n//\n// Two writers share composition.json: this editor and the agent (the Dailies\n// loop re-writes it between renders). Writes here are optimistically\n// concurrency-controlled — the client echoes back the mtime it last saw and a\n// write over a file that moved since is REFUSED with 409, rather than silently\n// winning. See persistGuarded.\n\nimport { createReadStream, statSync } from \"node:fs\";\nimport { appendFile, readFile, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { type IncomingMessage, type ServerResponse, createServer } from \"node:http\";\nimport { extname, join, normalize, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n type CaptureLog,\n type CompositionIssue,\n type TakeComposition,\n validateComposition,\n} from \"@open-take/compositor\";\nimport { renderComposition } from \"./index\";\nimport { openWithOs } from \"./review\";\n\nexport type EditServerOpts = {\n /** path to the take: its .mp4 / .composition.json / a dir containing them. */\n takePath: string;\n port?: number;\n /** open the browser at the served URL (default true). */\n open?: boolean;\n chromePath?: string;\n};\n\nimport { resolveTakePaths } from \"./take\";\n\ntype TakePaths = Awaited<ReturnType<typeof resolveTakePaths>>;\n\ntype RenderJob = {\n id: string;\n progress: number;\n status: \"running\" | \"done\" | \"error\";\n error?: string;\n mp4Url?: string;\n clients: Set<ServerResponse>;\n};\n\ntype EditServerDeps = {\n /** Test seam for the long-running renderer. Production uses the real one. */\n renderComposition?: typeof renderComposition;\n /** Test seam immediately after the temp composition is written. */\n beforeCompositionCommit?: () => Promise<void>;\n};\n\nconst CONTENT_TYPE: Record<string, string> = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".ico\": \"image/x-icon\",\n \".woff2\": \"font/woff2\",\n \".woff\": \"font/woff\",\n \".map\": \"application/json; charset=utf-8\",\n};\n\n/** Locate the built editor SPA: prefer the live monorepo build during\n * development, then fall back to the bundled copy used by the published\n * package. */\nfunction resolveEditorDist(): string | null {\n const here = fileURLToPath(import.meta.url);\n const pkgRoot = resolve(here, \"..\", \"..\"); // dist/edit-server.js → packages/runtime\n // In the monorepo the live editor build wins: editor-dist/ is a prepack COPY\n // and goes stale the moment you rebuild the editor, which silently serves old\n // JS to anyone testing a change. Published, that path doesn't exist (it would\n // resolve under node_modules/apps/editor/…), so the copy is the only candidate.\n const candidates = [\n resolve(pkgRoot, \"..\", \"..\", \"apps\", \"editor\", \"dist\"),\n resolve(pkgRoot, \"editor-dist\"),\n ];\n return candidates.find((c) => existsHtml(c)) ?? null;\n}\nfunction existsHtml(dir: string): boolean {\n return existsFile(join(dir, \"index.html\"));\n}\nfunction existsFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\nconst sendJson = (res: ServerResponse, status: number, obj: unknown) => {\n const body = JSON.stringify(obj);\n res.writeHead(status, {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Content-Length\": Buffer.byteLength(body),\n });\n res.end(body);\n};\n\nasync function readBody(req: IncomingMessage, capBytes = 32 * 1024 * 1024): Promise<string> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const c of req) {\n size += (c as Buffer).length;\n if (size > capBytes) throw new Error(\"request body too large\");\n chunks.push(c as Buffer);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\n/** Stream a file with HTTP Range support (206) — required for <video> seeking. */\nasync function serveFile(req: IncomingMessage, res: ServerResponse, filePath: string) {\n const st = await stat(filePath).catch(() => null);\n if (!st?.isFile()) {\n sendJson(res, 404, { error: \"not found\" });\n return;\n }\n const type = CONTENT_TYPE[extname(filePath).toLowerCase()] ?? \"application/octet-stream\";\n const range = req.headers.range;\n if (range) {\n const m = /bytes=(\\d*)-(\\d*)/.exec(range);\n const start = m?.[1] ? Number(m[1]) : 0;\n const end = m?.[2] ? Number(m[2]) : st.size - 1;\n if (start >= st.size || end >= st.size || start > end) {\n res.writeHead(416, { \"Content-Range\": `bytes */${st.size}` });\n res.end();\n return;\n }\n res.writeHead(206, {\n \"Content-Range\": `bytes ${start}-${end}/${st.size}`,\n \"Accept-Ranges\": \"bytes\",\n \"Content-Length\": end - start + 1,\n \"Content-Type\": type,\n });\n createReadStream(filePath, { start, end }).pipe(res);\n } else {\n res.writeHead(200, {\n \"Content-Length\": st.size,\n \"Accept-Ranges\": \"bytes\",\n \"Content-Type\": type,\n });\n createReadStream(filePath).pipe(res);\n }\n}\n\n/** Open the editor in the default browser. Shares the OS-opener with review.ts\n * — a private copy here is how the Windows `start`-eats-the-first-quoted-arg\n * bug survived in one place after being noticed in the other. */\nfunction openBrowser(url: string) {\n openWithOs(url, `open: ${url}\\n`);\n}\n\nexport async function startEditServer(\n opts: EditServerOpts,\n deps: EditServerDeps = {},\n): Promise<{ url: string; close: () => Promise<void> }> {\n const take = await resolveTakePaths(opts.takePath);\n // the two essentials must exist; the capture log is optional (skips the lock).\n for (const f of [take.compositionPath, take.capturePath]) {\n if (!(await stat(f).catch(() => null))?.isFile()) throw new Error(`missing take file: ${f}`);\n }\n const dist = resolveEditorDist();\n if (!dist)\n throw new Error(\"editor build not found — run `pnpm --filter @open-take/editor build` first\");\n\n const loadCaptureLog = async (): Promise<CaptureLog | null> => {\n try {\n return JSON.parse(await readFile(take.captureLogPath, \"utf8\")) as CaptureLog;\n } catch {\n return null;\n }\n };\n\n let job: RenderJob | null = null;\n let jobSeq = 0;\n // Set synchronously before the render endpoint's first await. Without this,\n // two simultaneous POSTs can both observe `job === null`, persist, and\n // replace each other's job before either request reaches the assignment.\n let renderStarting = false;\n\n const compositionMtime = async (): Promise<number> =>\n (await stat(take.compositionPath).catch(() => null))?.mtimeMs ?? 0;\n\n // Every write runs alone: check-then-write is only meaningful if nothing\n // interleaves between the two, and this server can have an autosave and an\n // export in flight at once.\n let writeLock: Promise<unknown> = Promise.resolve();\n const exclusive = <T>(fn: () => Promise<T>): Promise<T> => {\n const run = writeLock.then(fn, fn);\n writeLock = run.catch(() => {});\n return run;\n };\n\n /** Persist unless someone else wrote first. `baseMtime` is the mtime the\n * client last read. Every API write must provide it; \"Keep mine\" re-bases to\n * the 409's mtime and remains guarded against an even newer write.\n *\n * We check once before writing the temp file and again immediately before\n * rename, so an agent write during serialization/I/O is refused too. No\n * portable filesystem API provides compare-and-swap by mtime: a different\n * process writing in the final stat→rename window can still be overwritten\n * unless every writer honors the same lock. */\n const persistGuarded = async (\n comp: TakeComposition,\n baseMtime: number | undefined,\n ): Promise<{ ok: true; mtime: number } | { ok: false; mtime: number }> =>\n exclusive(async () => {\n const onDisk = await compositionMtime();\n if (baseMtime !== undefined && onDisk !== baseMtime) return { ok: false, mtime: onDisk };\n const tmp = `${take.compositionPath}.tmp`;\n let committed = false;\n try {\n await writeFile(tmp, JSON.stringify(comp, null, 2));\n await deps.beforeCompositionCommit?.();\n if (baseMtime !== undefined) {\n const beforeRename = await compositionMtime();\n if (beforeRename !== onDisk) return { ok: false, mtime: beforeRename };\n }\n await rename(tmp, take.compositionPath);\n committed = true;\n return { ok: true, mtime: await compositionMtime() };\n } finally {\n if (!committed) await unlink(tmp).catch(() => {});\n }\n });\n\n type WritePayload = { composition: TakeComposition; baseMtime: number };\n\n /** The write guard is mandatory. A missing base used to mean \"force write\",\n * which made a bare JSON body an invisible escape hatch around conflict\n * protection. Callers must first GET /api/take and echo its mtime. */\n const readWrite = async (\n req: IncomingMessage,\n res: ServerResponse,\n ): Promise<WritePayload | null> => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readBody(req));\n } catch {\n sendJson(res, 400, { error: \"invalid JSON request body\" });\n return null;\n }\n const candidate =\n parsed && typeof parsed === \"object\"\n ? (parsed as { composition?: unknown; baseMtime?: unknown })\n : null;\n if (\n !candidate?.composition ||\n typeof candidate.baseMtime !== \"number\" ||\n !Number.isFinite(candidate.baseMtime)\n ) {\n sendJson(res, 428, {\n error:\n \"write precondition required: send { composition, baseMtime } using the mtime from GET /api/take\",\n });\n return null;\n }\n return {\n composition: candidate.composition as TakeComposition,\n baseMtime: candidate.baseMtime,\n };\n };\n\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? \"/\", \"http://localhost\");\n const path = url.pathname;\n const method = req.method ?? \"GET\";\n\n // same-origin guard: this is a loopback server, but a hostile web page\n // could still fire cross-site requests at it — refuse foreign Origins\n // and non-JSON bodies on state-changing endpoints.\n if (method === \"POST\") {\n const host = req.headers.host ?? \"\";\n const origin = req.headers.origin;\n const sameOrigin = !origin || origin === `http://${host}`;\n const isJson = (req.headers[\"content-type\"] ?? \"\").includes(\"application/json\");\n if (!/^(127\\.0\\.0\\.1|localhost)(:\\d+)?$/.test(host) || !sameOrigin || !isJson) {\n sendJson(res, 403, { error: \"forbidden\" });\n return;\n }\n }\n\n // ---- API ----\n if (path === \"/api/take\" && method === \"GET\") {\n // read the mtime BEFORE the contents: if a write lands in between, the\n // client's base is older than what it holds and its next save 409s —\n // the safe direction. (Reading it after could hand out a base newer\n // than the composition we returned, which would silently clobber.)\n const mtime = await compositionMtime();\n const composition = JSON.parse(\n await readFile(take.compositionPath, \"utf8\"),\n ) as TakeComposition;\n const captureLog = await loadCaptureLog();\n sendJson(res, 200, {\n composition,\n captureLog,\n source: { name: take.name },\n videoUrl: \"/api/take/video\",\n mp4Url: \"/api/take/output\",\n mtime,\n });\n return;\n }\n if (path === \"/api/take/video\" && method === \"GET\") {\n await serveFile(req, res, take.capturePath);\n return;\n }\n if (path === \"/api/take/mtime\" && method === \"GET\") {\n sendJson(res, 200, { mtime: await compositionMtime() });\n return;\n }\n if (path === \"/api/notes\" && method === \"POST\") {\n const { text } = JSON.parse(await readBody(req)) as { text?: string };\n if (!text?.trim()) {\n sendJson(res, 400, { error: \"empty note\" });\n return;\n }\n const line = text.trim().replace(/\\s+/g, \" \").slice(0, 2000);\n // durable for the agent to pick up later (`open-take notes --wait`\n // blocks on exactly this append) + live on stdout for an agent\n // watching this process\n await appendFile(take.notesPath, `- ${line}\\n`);\n process.stdout.write(`NOTE ${JSON.stringify({ take: take.name, text: line })}\\n`);\n sendJson(res, 200, { ok: true });\n return;\n }\n if (path === \"/api/take/output\" && method === \"GET\") {\n await serveFile(req, res, take.mp4Path);\n return;\n }\n\n if (path === \"/api/composition\" && method === \"POST\") {\n const payload = await readWrite(req, res);\n if (!payload) return;\n const { composition: comp, baseMtime } = payload;\n const captureLog = await loadCaptureLog();\n const issues = validateComposition(comp, captureLog ? { captureLog } : {});\n const errors = issues.filter((i) => i.severity === \"error\");\n if (errors.length) {\n sendJson(res, 400, { issues });\n return;\n }\n const saved = await persistGuarded(comp, baseMtime);\n if (!saved.ok) {\n sendJson(res, 409, { conflict: true, mtime: saved.mtime });\n return;\n }\n sendJson(res, 200, { ok: true, issues, mtime: saved.mtime });\n return;\n }\n\n if (path === \"/api/render\" && method === \"POST\") {\n if (renderStarting || job?.status === \"running\") {\n sendJson(res, 409, { error: \"a render is already in progress\" });\n return;\n }\n renderStarting = true;\n try {\n const payload = await readWrite(req, res);\n if (!payload) return;\n const { composition: comp, baseMtime } = payload;\n const captureLog = (await loadCaptureLog()) ?? undefined;\n const issues = validateComposition(comp, captureLog ? { captureLog } : {});\n const errors = issues.filter((i: CompositionIssue) => i.severity === \"error\");\n if (errors.length) {\n sendJson(res, 400, { issues });\n return;\n }\n const saved = await persistGuarded(comp, baseMtime);\n if (!saved.ok) {\n // Same status as \"render already running\" above — the `conflict`\n // flag is what tells the two apart on the client.\n sendJson(res, 409, { conflict: true, mtime: saved.mtime });\n return;\n }\n const id = `${Date.now().toString(36)}-${++jobSeq}`;\n job = { id, progress: 0, status: \"running\", clients: new Set() };\n // Re-base immediately: the guarded write already happened. Waiting\n // for SSE `done` leaves the client stale when rendering fails or\n // disconnects.\n sendJson(res, 200, { jobId: id, mtime: saved.mtime });\n // Run the render in the background; stream progress to SSE clients.\n void runRender(job, comp, captureLog);\n } finally {\n renderStarting = false;\n }\n return;\n }\n\n const ev = /^\\/api\\/render\\/([^/]+)\\/events$/.exec(path);\n if (ev && method === \"GET\") {\n const id = ev[1];\n if (!job || job.id !== id) {\n sendJson(res, 404, { error: \"unknown job\" });\n return;\n }\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n emit(res, \"progress\", { progress: job.progress });\n if (job.status === \"done\") {\n emit(res, \"done\", { mp4Url: job.mp4Url });\n res.end();\n return;\n }\n if (job.status === \"error\") {\n emit(res, \"failed\", { message: job.error });\n res.end();\n return;\n }\n job.clients.add(res);\n req.on(\"close\", () => job?.clients.delete(res));\n return;\n }\n\n if (path.startsWith(\"/api/\")) {\n sendJson(res, 404, { error: \"no such endpoint\" });\n return;\n }\n\n // ---- static editor SPA ----\n if (method !== \"GET\") {\n sendJson(res, 405, { error: \"method not allowed\" });\n return;\n }\n const rel = normalize(decodeURIComponent(path)).replace(/^(\\.\\.[/\\\\])+/, \"\");\n let filePath = join(dist, rel === \"/\" ? \"index.html\" : rel);\n if (!filePath.startsWith(dist)) {\n sendJson(res, 403, { error: \"forbidden\" });\n return;\n }\n const fst = await stat(filePath).catch(() => null);\n if (!fst?.isFile()) filePath = join(dist, \"index.html\"); // SPA fallback\n await serveFile(req, res, filePath);\n } catch (err) {\n sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });\n }\n });\n\n async function runRender(\n j: RenderJob,\n comp: TakeComposition,\n captureLog: CaptureLog | undefined,\n ) {\n try {\n await (deps.renderComposition ?? renderComposition)({\n composition: comp,\n capturePath: take.capturePath,\n outPath: take.mp4Path,\n captureLog,\n chromePath: opts.chromePath,\n // POST /api/render already persisted `comp` under persistGuarded. A\n // second write after a long render would overwrite any agent edit that\n // landed while rendering.\n writeCompositionSibling: false,\n onProgress: (p) => {\n j.progress = p;\n for (const c of j.clients) emit(c, \"progress\", { progress: p });\n },\n });\n j.status = \"done\";\n j.progress = 1;\n j.mp4Url = `/api/take/output?v=${Date.now().toString(36)}`;\n for (const c of j.clients) {\n emit(c, \"done\", { mp4Url: j.mp4Url });\n c.end();\n }\n } catch (err) {\n j.status = \"error\";\n j.error = err instanceof Error ? err.message : String(err);\n for (const c of j.clients) {\n emit(c, \"failed\", { message: j.error });\n c.end();\n }\n } finally {\n j.clients.clear();\n }\n }\n\n const port = await listen(server, opts.port ?? 4178);\n const url = `http://127.0.0.1:${port}/`;\n process.stdout.write(\n `open-take editor → ${url}\\n(serving take \"${take.name}\"; Ctrl-C to stop)\\n`,\n );\n if (opts.open !== false) openBrowser(url);\n\n return {\n url,\n close: () => new Promise<void>((r) => server.close(() => r())),\n };\n}\n\nfunction emit(res: ServerResponse, event: string, data: unknown) {\n res.write(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n}\n\n/** Bind to 127.0.0.1 only; if the port is taken, try the next few. Resolves the\n * port actually BOUND, which differs from the requested one when port 0 asks\n * the OS to choose (how the tests get an isolated server). */\nfunction listen(server: ReturnType<typeof createServer>, startPort: number): Promise<number> {\n return new Promise((res, rej) => {\n let port = startPort;\n const tryOne = () => {\n server.once(\"error\", (e: NodeJS.ErrnoException) => {\n if (e.code === \"EADDRINUSE\" && port < startPort + 20) {\n port++;\n tryOne();\n } else rej(e);\n });\n server.listen(port, \"127.0.0.1\", () => {\n const addr = server.address();\n res(addr && typeof addr === \"object\" ? addr.port : port);\n });\n };\n tryOne();\n });\n}\n","// notes — the editor→agent channel, and the only part of the dailies loop the\n// agent can't see by looking at files it already knows about.\n//\n// The editor's Agent panel POSTs a note; edit-server appends one line to\n// `<base>.notes.md`. That file is durable but PASSIVE: nothing tells a running\n// agent it grew, so a note left in the browser sat unread until the user went\n// back to the terminal and said so. This module is the active half:\n//\n// readNotes(take) → the notes appended since you last looked\n// waitForNotes(take, …) → BLOCKS until a new one lands, then returns it\n//\n// `waitForNotes` is what makes `open-take notes <take> --wait` a wake-up: an\n// agent starts it as a background process when it hands the editor over, and\n// the process EXITS the moment the user leaves a note — which is exactly the\n// signal every agent harness already understands (a finished command with\n// output). No watcher daemon, no harness-specific hook.\n//\n// Read position is a byte offset in a sidecar (`<base>.notes.cursor`) rather\n// than a mark inside the log, because only the reader writes the sidecar. A\n// read-modify-write of notes.md itself would race the server's append and could\n// silently swallow a note — the one failure this channel must never have.\n\nimport { readFile, stat, writeFile } from \"node:fs/promises\";\nimport type { TakePaths } from \"./take\";\n\nexport type NotesRead = {\n /** notes appended since the cursor, oldest first */\n notes: string[];\n /** how many notes the whole log holds */\n total: number;\n /** the byte offset now consumed */\n cursor: number;\n};\n\nexport type WaitNotesResult = NotesRead & {\n /** true when the deadline passed with nothing new (`notes` is then empty) */\n timedOut: boolean;\n};\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\nconst fileSize = async (p: string): Promise<number> => (await stat(p).catch(() => null))?.size ?? 0;\n\nconst readBytes = async (p: string): Promise<Buffer> =>\n await readFile(p).catch(() => Buffer.alloc(0));\n\nconst readCursor = async (p: string): Promise<number> => {\n const n = Number((await readFile(p, \"utf8\").catch(() => \"\")).trim());\n return Number.isFinite(n) && n >= 0 ? n : 0;\n};\n\n/** `- opening is too slow` → `opening is too slow`; blank lines and stray text\n * are tolerated. Notes are free text in any language — never parsed for meaning. */\nconst parseNotes = (buf: Buffer): string[] =>\n buf\n .toString(\"utf8\")\n .split(\"\\n\")\n .map((l) => l.replace(/^-\\s*/, \"\").trim())\n .filter((l) => l.length > 0);\n\nexport type ReadNotesOpts = {\n /** ignore the cursor and return every note in the log (still advances it) */\n all?: boolean;\n /** report without advancing the cursor — the next read sees them again */\n peek?: boolean;\n};\n\n/** The notes appended since the last read, and how many the log holds.\n * Advances the cursor unless `peek`, so a note is delivered exactly once. */\nexport async function readNotes(take: TakePaths, opts: ReadNotesOpts = {}): Promise<NotesRead> {\n const buf = await readBytes(take.notesPath);\n const saved = await readCursor(take.notesCursorPath);\n // A cursor past EOF means the log was truncated or replaced — start over\n // rather than sit silently past the end of a file that has notes in it.\n const from = opts.all || saved > buf.length ? 0 : saved;\n // Only consume WHOLE lines: an append that lands mid-read would otherwise\n // leave half a note consumed and the rest orphaned behind the cursor.\n const end = buf.lastIndexOf(0x0a) + 1;\n const slice = end > from ? buf.subarray(from, end) : Buffer.alloc(0);\n const cursor = Math.max(from, end);\n if (!opts.peek && cursor !== saved) {\n await writeFile(take.notesCursorPath, `${cursor}\\n`).catch(() => {});\n }\n return { notes: parseNotes(slice), total: parseNotes(buf).length, cursor };\n}\n\nexport type WaitNotesOpts = ReadNotesOpts & {\n /** give up after this long and return `timedOut` (default 30 min) */\n timeoutMs?: number;\n /** how often to stat the log (default 500ms) */\n pollMs?: number;\n /** after the log grows, wait this long before reading so a burst of notes\n * arrives as ONE batch instead of waking the agent once per line\n * (default 800ms) */\n settleMs?: number;\n /** stop waiting early (returns timedOut with no notes) */\n signal?: AbortSignal;\n};\n\n/** Block until at least one unread note exists, then return it (and consume\n * it). Returns immediately when the log already has unread notes — a waiter\n * started after the user typed still delivers, which is what makes restarting\n * one between rounds lossless. */\nexport async function waitForNotes(\n take: TakePaths,\n opts: WaitNotesOpts = {},\n): Promise<WaitNotesResult> {\n const timeoutMs = opts.timeoutMs ?? 30 * 60_000;\n const pollMs = opts.pollMs ?? 500;\n const settleMs = opts.settleMs ?? 800;\n const deadline = Date.now() + timeoutMs;\n\n let last = await readNotes(take, opts);\n if (last.notes.length) return { ...last, timedOut: false };\n // Watch the SIZE we last observed, not the cursor: a log whose final line\n // has no newline yet leaves cursor < size, and polling against the cursor\n // would then re-read on every tick forever.\n let seen = await fileSize(take.notesPath);\n\n while (!opts.signal?.aborted && Date.now() < deadline) {\n await sleep(Math.min(pollMs, Math.max(0, deadline - Date.now())));\n if (opts.signal?.aborted) break;\n // `!==` not `>`: a truncated/rewritten log is a change too, and readNotes\n // knows how to restart from 0 when the cursor no longer fits.\n if ((await fileSize(take.notesPath)) === seen) continue;\n if (settleMs > 0) await sleep(settleMs);\n last = await readNotes(take, { ...opts, all: false });\n seen = await fileSize(take.notesPath); // the settle window may have grown it\n if (last.notes.length) return { ...last, timedOut: false };\n }\n return { ...last, notes: [], timedOut: true };\n}\n\nconst rel = (p: string): string => p.replace(`${process.cwd()}/`, \"\");\n\n/** The wake-up message. Written for an agent reading a finished background\n * command: what came in, and the one thing it must re-read before editing. */\nexport function formatNotes(\n take: TakePaths,\n res: NotesRead & { timedOut?: boolean },\n opts: { waited?: boolean } = {},\n): string {\n if (!res.notes.length) {\n if (opts.waited && res.timedOut) return `no notes · ${take.name} (waited out)\\n`;\n return res.total\n ? `no new notes · ${take.name} (${res.total} already read in ${rel(take.notesPath)})\\n`\n : `no notes yet · ${take.name} (${rel(take.notesPath)})\\n`;\n }\n const head = `${res.notes.length} new note${res.notes.length > 1 ? \"s\" : \"\"} from the editor · ${take.name}`;\n return [\n head,\n ...res.notes.map((n) => `- ${n}`),\n `(re-read ${rel(take.compositionPath)} before editing it — the editor may have changed it too)`,\n \"\",\n ].join(\"\\n\");\n}\n","// frames — beat-aware verification sheets: one tiled contact sheet whose\n// sample times come from the REAL camera schedule (cameraRampSchedule), so a\n// verifier looks at the HOLD of each beat — never accidentally inside a ramp\n// or settle tail and misreads motion as a framing bug. Rows tell the story:\n// an intro row (dead-opening check), one row per beat (travel + 4 hold\n// samples), a tail row (lingering-ending check). `--beat N` densifies one\n// beat into a 10-cell strip with per-cell phase labels instead.\n//\n// Pure planning (buildFramePlan) is separated from the ffmpeg I/O\n// (renderFrames) so the schedule math stays snapshot-testable.\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtemp, readFile, rm, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport {\n type TakeComposition,\n math,\n resolveFfmpeg,\n resolveFfprobe,\n} from \"@open-take/compositor\";\nimport { beatLabel } from \"./review\";\nimport { type TakePaths, requireTakeFiles } from \"./take\";\n\nexport type FramePhase = \"intro\" | \"travel\" | \"hold\" | \"tail\";\nexport type FrameCell = {\n /** sample time on the COMPOSITION timeline, ms (the `beats` vocabulary). */\n tMs: number;\n phase: FramePhase;\n};\nexport type FrameRow = { label: string; cells: FrameCell[] };\nexport type FramePlan = { rows: FrameRow[]; cols: number; notes: string[] };\n\nconst COLS = 5;\n\n/** Per-beat camera windows on the composition timeline, buildBadges-style:\n * monotone starts (the ramp departure toward the beat), the actual landing,\n * and where the framing is released (the next beat's departure, or the own\n * hold's end). */\nfunction beatWindows(comp: TakeComposition): {\n startMs: number;\n arrivedMs: number;\n releaseMs: number;\n}[] {\n const ramps = math.cameraRampSchedule(comp);\n let prevStart = 0;\n const starts = comp.events.map((e, i) => {\n const s = Math.max(ramps[i]?.startMs ?? e.zoom.inAtMs, prevStart + 1);\n prevStart = s;\n return s;\n });\n return comp.events.map((e, i) => {\n const arrived = Math.max(e.tMs, ramps[i]?.landMs ?? e.tMs);\n const endOwn = arrived + (e.durationMs ?? 0) + comp.cursor.holdMs;\n const release =\n i < comp.events.length - 1 ? starts[i + 1]! : Math.min(endOwn, comp.durationMs);\n return { startMs: starts[i]!, arrivedMs: arrived, releaseMs: release };\n });\n}\n\nconst spread = (from: number, to: number, n: number): number[] =>\n Array.from({ length: n }, (_, k) => (n === 1 ? from : from + ((to - from) * k) / (n - 1)));\n\nexport function buildFramePlan(comp: TakeComposition, opts: { beat?: number } = {}): FramePlan {\n const wins = beatWindows(comp);\n const notes: string[] = [];\n const endCap = comp.durationMs - 60;\n\n if (opts.beat != null) {\n const i = opts.beat - 1;\n const e = comp.events[i];\n const w = wins[i];\n if (!e || !w)\n throw new Error(`frames: --beat ${opts.beat} out of range (1-${comp.events.length})`);\n const from = Math.max(comp.startMs ?? 0, w.startMs - 400);\n const to = Math.min(endCap, w.releaseMs + 400);\n const phase = (t: number): FramePhase =>\n t < w.arrivedMs ? \"travel\" : t <= w.releaseMs ? \"hold\" : \"tail\";\n const cells = spread(from, to, COLS * 2).map((t) => ({ tMs: t, phase: phase(t) }));\n const label = `beat ${opts.beat} · ${beatLabel(e)}`;\n return {\n rows: [\n { label: `${label} 1/2`, cells: cells.slice(0, COLS) },\n { label: `${label} 2/2`, cells: cells.slice(COLS) },\n ],\n cols: COLS,\n notes,\n };\n }\n\n const rows: FrameRow[] = [];\n const trim = comp.startMs ?? 0;\n const introEnd = wins.length ? wins[0]!.startMs - 100 : endCap;\n if (introEnd - trim > 800) {\n rows.push({\n label: \"in\",\n cells: spread(trim, introEnd, COLS).map((tMs) => ({ tMs, phase: \"intro\" as const })),\n });\n }\n comp.events.forEach((e, i) => {\n const w = wins[i]!;\n // beats already trimmed off by startMs can't be sampled from the delivered\n // file — say so instead of tiling frame 0 five times.\n if (w.releaseMs <= trim) {\n notes.push(`beat ${i + 1} ends before the startMs head trim — not sampled`);\n return;\n }\n const holdFrom = Math.max(trim, Math.min(w.arrivedMs + 80, endCap));\n const holdTo = Math.max(holdFrom, Math.min(w.releaseMs - 120, endCap));\n const cells: FrameCell[] = [];\n if (w.arrivedMs - w.startMs > 200 && w.startMs >= trim) {\n cells.push({ tMs: (w.startMs + w.arrivedMs) / 2, phase: \"travel\" });\n }\n const holdN = COLS - cells.length;\n for (const tMs of spread(holdFrom, holdTo, holdN)) cells.push({ tMs, phase: \"hold\" });\n rows.push({ label: `beat ${i + 1} · ${beatLabel(e)}`, cells });\n });\n const lastRelease = wins.length ? wins[wins.length - 1]!.releaseMs : trim;\n if (comp.durationMs - lastRelease > 800) {\n rows.push({\n label: \"out\",\n cells: spread(Math.max(trim, lastRelease), endCap, COLS).map((tMs) => ({\n tMs,\n phase: \"tail\" as const,\n })),\n });\n }\n return { rows, cols: COLS, notes };\n}\n\n// --- rendering (ffmpeg I/O) --------------------------------------------------\n\nfunction run(cmd: string, args: string[]): Promise<string> {\n return new Promise((res, rej) => {\n const c = spawn(cmd, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let out = \"\";\n let err = \"\";\n c.stdout.on(\"data\", (d) => {\n out += d;\n });\n c.stderr.on(\"data\", (d) => {\n err += d;\n });\n c.on(\"error\", rej);\n c.on(\"close\", (code) => (code === 0 ? res(out) : rej(new Error(`${cmd} exited ${code}: ${err}`))));\n });\n}\n\nasync function mp4Duration(path: string): Promise<number> {\n const out = await run(await resolveFfprobe(), [\n \"-v\",\n \"error\",\n \"-show_entries\",\n \"format=duration\",\n \"-of\",\n \"csv=p=0\",\n resolve(path),\n ]);\n const s = Number.parseFloat(out.trim());\n if (!Number.isFinite(s) || s <= 0) throw new Error(`frames: could not read duration of ${path}`);\n return s * 1000;\n}\n\nconst fmtS = (ms: number): string => `${(ms / 1000).toFixed(1)}s`;\n\nexport function buildFrameSheet(\n plan: FramePlan,\n framesPath: string,\n trimMs: number,\n tileW?: number,\n): string {\n const lines = [\n `frames: ${framesPath} · ${plan.cols} cols × ${plan.rows.length} rows${tileW ? ` · ${tileW}px tiles` : \"\"} · times on the composition timeline${trimMs ? ` (head −${(trimMs / 1000).toFixed(1)}s already cut from the mp4)` : \"\"}`,\n ];\n plan.rows.forEach((r, i) => {\n const cells = r.cells\n .map((c) => (c.phase === \"hold\" || c.phase === \"intro\" ? fmtS(c.tMs) : `${fmtS(c.tMs)}(${c.phase})`))\n .join(\" · \");\n lines.push(` row ${i + 1} ${r.label.padEnd(34, \" \")} ${cells}`);\n });\n for (const n of plan.notes) lines.push(` ⚠ ${n}`);\n lines.push(\n `judge framing/payoff on HOLD cells only — travel cells are mid-motion by design (ramps + blur live there).`,\n );\n return lines.join(\"\\n\");\n}\n\nexport type FramesOpts = {\n /** densify one beat (1-based) into a 10-cell strip */\n beat?: number;\n /** which delivered file to sample (default the master mp4) */\n sourcePath?: string;\n /** tile width in px. Defaults: 480 for the overview, 720 for a --beat strip\n * (diagnosis wants detail — a 480px tile of a Retina capture is a 1/8-scale\n * thumbnail: enough to suspect a framing bug, not enough to confirm it). */\n tileWidth?: number;\n};\n\n/** Extract the plan's frames from a delivered take mp4 and tile them into\n * `<base>.frames[.beatN].png`. No Chrome, no render — a handful of ffmpeg\n * seeks; seconds, not minutes. */\nexport async function renderFrames(\n take: TakePaths,\n opts: FramesOpts = {},\n): Promise<{ framesPath: string; sheet: string; plan: FramePlan }> {\n await requireTakeFiles(take);\n const comp = JSON.parse(await readFile(take.compositionPath, \"utf8\")) as TakeComposition;\n const src = resolve(opts.sourcePath ?? take.mp4Path);\n if (!(await stat(src).catch(() => null))?.isFile())\n throw new Error(`frames: ${src} not found — render the take first`);\n const plan = buildFramePlan(comp, { beat: opts.beat });\n if (plan.rows.length === 0) throw new Error(\"frames: nothing to sample (no beats, no intro/tail)\");\n\n const trim = comp.startMs ?? 0;\n const durMs = await mp4Duration(src);\n const ffmpeg = await resolveFfmpeg();\n const framesPath = opts.beat != null ? `${take.base}.frames.beat${opts.beat}.png` : `${take.base}.frames.png`;\n const tileW = Math.round(opts.tileWidth ?? (opts.beat != null ? 720 : 480));\n if (!Number.isFinite(tileW) || tileW < 120 || tileW > 1920)\n throw new Error(`frames: tile width ${tileW} out of range (120-1920)`);\n const tileH = Math.round((tileW * comp.output.height) / comp.output.width);\n\n const work = await mkdtemp(join(tmpdir(), \"open-take-frames-\"));\n try {\n const cells = plan.rows.flatMap((r) => r.cells);\n for (let i = 0; i < cells.length; i++) {\n // composition time → delivered-file time; clamp inside the real file so\n // encoder rounding at the tail can't yield an empty extraction.\n const fileMs = Math.min(Math.max(cells[i]!.tMs - trim, 0), durMs - 50);\n await run(ffmpeg, [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-ss\",\n String(fileMs / 1000),\n \"-i\",\n src,\n \"-frames:v\",\n \"1\",\n \"-vf\",\n `scale=${tileW}:${tileH}`,\n join(work, `f${String(i).padStart(3, \"0\")}.png`),\n ]);\n }\n await run(ffmpeg, [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-framerate\",\n \"1\",\n \"-i\",\n join(work, \"f%03d.png\"),\n \"-frames:v\",\n \"1\",\n \"-vf\",\n `tile=${plan.cols}x${plan.rows.length}`,\n framesPath,\n ]);\n } finally {\n await rm(work, { recursive: true, force: true });\n }\n return { framesPath, sheet: buildFrameSheet(plan, framesPath, trim, tileW), plan };\n}\n","// @open-take/runtime — the thin pipeline: agent plan -> capture (event\n// log) -> compositor -> polished mp4 + editable composition.\n//\n// await makeTake(plan, { outPath: \"demo.mp4\" }) // capture + render\n// await renderComposition({ composition, capturePath, outPath }) // refine\n//\n// Keep it thin. The agent does the planning; this just runs the pipeline.\n//\n// The two entry points mirror the two costs. makeTake DRIVES the app in\n// real-time (expensive, the ground-truth recording) and KEEPS the capture\n// alongside the output. renderComposition re-renders an EDITED composition\n// over that saved capture — no browser drive — which is the refinement loop:\n// the agent tweaks the editable composition.json (zoom/pacing/framing) and\n// re-renders deterministically. Only the *cinematic* layer is editable this\n// way; changing the choreography (what's clicked/typed, beat order) needs a\n// fresh makeTake (the video is temporal — see validateComposition).\n\nimport { copyFile, mkdir, mkdtemp, readFile, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n type CaptureLog,\n type CompositionIssue,\n type PlanOpts,\n type TakeComposition,\n planComposition,\n renderTake,\n} from \"@open-take/compositor\";\nimport { type CaptureOpts, captureTake } from \"./capture\";\nimport { ensureChrome } from \"./cdp\";\nimport { annotateCaptureLog } from \"./frame-diff\";\nimport { toDraft } from \"./review\";\nimport type { TakePlan } from \"./types\";\n\nexport type { TakePlan, TakeStep } from \"./types\";\nexport {\n captureTake,\n type CaptureOpts,\n inspectPage,\n type InspectOpts,\n type InspectResult,\n type InspectElement,\n} from \"./capture\";\nexport { captureTakeCDP } from \"./cdp-capture\";\nexport { resolveNavigateUrl, type NavigateTarget } from \"./nav\";\nexport { authProfile, profileDir, type AuthOpts, type AuthResult } from \"./auth\";\nexport {\n annotateCaptureLog,\n diffFrames,\n type AnnotateOpts,\n type FrameDiffResult,\n} from \"./frame-diff\";\nexport { ensureChrome, resolveChrome } from \"./cdp\";\nexport { startEditServer, type EditServerOpts } from \"./edit-server\";\nexport {\n requireTakeFiles,\n resolveTakePaths,\n stagePrev,\n type StagedPrev,\n type TakePaths,\n} from \"./take\";\nexport {\n formatNotes,\n readNotes,\n waitForNotes,\n type NotesRead,\n type ReadNotesOpts,\n type WaitNotesOpts,\n type WaitNotesResult,\n} from \"./notes\";\nexport {\n buildBeatSheet,\n buildBadges,\n beatLabel,\n renderReview,\n renderDraft,\n renderAbReel,\n renderBeforeAfter,\n toDraft,\n openPath,\n revealPath,\n SAY_IT_CARD,\n type AbOpts,\n type ReviewOpts,\n} from \"./review\";\nexport {\n buildFramePlan,\n buildFrameSheet,\n renderFrames,\n type FramePlan,\n type FrameRow,\n type FrameCell,\n type FramePhase,\n type FramesOpts,\n} from \"./frames\";\nexport { validateComposition, formatIssues, type CompositionIssue } from \"@open-take/compositor\";\n\nexport type MakeTakeOpts = {\n /** output polished mp4 path */\n outPath: string;\n /** tune the default composition (zoom fill/cap, framing, cursor) */\n planOpts?: PlanOpts;\n capture?: Omit<CaptureOpts, \"videoPath\">;\n /** frame-diff the capture to annotate each event with what it actually\n * changed on screen (effectBox/changeCoverage — the camera director's\n * nav-vs-popover + payoff-framing inputs). Default true; annotation\n * failures never fail the take. */\n frameDiff?: boolean;\n logProgress?: boolean;\n /** print per-event diagnostics (the frame-diff lines). Default false — they\n * are useful when debugging framing, but on a normal run they bury the\n * warnings an author must act on (a skipped step). */\n verbose?: boolean;\n /** render the INITIAL mp4 at draft quality (30fps cap + motion blur off,\n * ~6-12× faster) for the iterate loop; the capture still records at the\n * full fps and the composition sibling keeps the full-quality settings, so\n * the closing `render` produces the real master from the same take. */\n draft?: boolean;\n /** called the moment the raw capture lands beside the output — BEFORE the\n * frame-diff + render minutes. The progressive-reveal hook: the CLI prints\n * and auto-opens the raw footage so the user watches it while the polish\n * renders. A throwing callback never fails the take. */\n onCaptureReady?: (capturePath: string) => void;\n};\n\nexport type MakeTakeResult = {\n mp4Path: string;\n compositionPath: string;\n /** the KEPT raw capture (next to the mp4) — feed this back to\n * renderComposition to refine without re-driving the app. */\n capturePath: string;\n /** the KEPT capture log (`<out>.capture.json`) — the ground-truth action\n * timing. `render` auto-loads it so the capture-lock check (a refine must not\n * move an action's tMs) is enforced in the real refine loop, not just inside\n * makeTake. */\n captureLogPath: string;\n composition: TakeComposition;\n /** steps the capture dropped (target not found) — surface these in the\n * end-of-run summary; `--strict` turns them into a non-zero exit. */\n skipped: NonNullable<CaptureLog[\"skipped\"]>;\n /** beats whose `settleMs` ran out before the PAGE was done. The capture\n * waited (see runtime/src/settle.ts) so the take is still correct, but the\n * plan is now known to under-budget those beats — the summary prints the\n * number to write into `settleMs`, which is the whole point: it stops being\n * a guess after the first run. */\n settleWaits: NonNullable<CaptureLog[\"settleWaits\"]>;\n /** set when a `<canvas>`/`<video>` dominated the frame — the settle probe\n * is blind inside one, so a quiet run proves nothing about those beats. */\n paintedFrac?: number;\n /** non-fatal validator findings on the rendered composition. Printed at the\n * render boundary too, but that line is minutes deep in the progress output\n * by the time the run ends — surface these in the end-of-run summary the\n * same way `skipped` is, or they get scrolled past and ship. */\n warnings: CompositionIssue[];\n};\n\n/** `<out>.mp4` → `<out>.capture.mp4` — the raw recording kept beside the\n * polished output so the composition can be re-rendered (refined) later. */\nconst capturePathFor = (outPath: string): string =>\n `${resolve(outPath).replace(/\\.mp4$/i, \"\")}.capture.mp4`;\n\n/** `<x>.capture.mp4` → `<x>.capture.json` — the capture log sits beside the\n * video. Deriving it by convention lets `render` find the ground-truth timing\n * from just the `--video` path. */\nexport const captureLogPathFor = (capturePath: string): string =>\n resolve(capturePath).replace(/\\.mp4$/i, \".json\");\n\n/** Load the capture log that sits beside a capture video, if present. Returns\n * undefined when there's no sibling (e.g. an old capture, or a hand-supplied\n * video) — the capture-lock check is then skipped, not an error. */\nexport async function loadCaptureLogSibling(capturePath: string): Promise<CaptureLog | undefined> {\n const p = captureLogPathFor(capturePath);\n try {\n return JSON.parse(await readFile(p, \"utf8\")) as CaptureLog;\n } catch {\n return undefined;\n }\n}\n\nexport async function makeTake(plan: TakePlan, opts: MakeTakeOpts): Promise<MakeTakeResult> {\n const work = await mkdtemp(join(tmpdir(), \"open-take-\"));\n const tmpVideo = join(work, \"capture.mp4\"); // CDP screencast → h264 mp4\n\n // Resolve (and, first run, download) Chrome ONCE, then hand the same binary\n // to both capture and render. One browser serves the whole pipeline; the\n // renderer uses puppeteer-core and never downloads another one.\n const chromePath = await ensureChrome(opts.capture?.chromePath);\n\n const raw = await captureTake(plan, { ...opts.capture, chromePath, videoPath: tmpVideo });\n\n // KEEP the capture beside the output the moment it exists — BEFORE the\n // frame-diff + render minutes — so the caller can reveal the raw footage\n // while the polish is still cooking (perceived latency: the user sees\n // nothing for ~10 minutes otherwise). Refinement re-renders over this copy\n // without re-driving the app (the refine loop's whole point).\n const capturePath = capturePathFor(opts.outPath);\n const captureLogPath = captureLogPathFor(capturePath);\n await mkdir(dirname(capturePath), { recursive: true });\n await copyFile(tmpVideo, capturePath);\n try {\n opts.onCaptureReady?.(capturePath);\n } catch {\n // a reveal hook must never fail the take\n }\n\n // Tier-2 annotation: diff the recording around each action so the log\n // carries what each action actually changed (effectBox/changeCoverage) —\n // the director's ground truth for payoff-framing and nav pull-outs. The\n // annotated log is what gets KEPT, so later re-plans keep the signal.\n const log =\n opts.frameDiff === false\n ? raw\n : await annotateCaptureLog(raw, tmpVideo, { logProgress: opts.verbose === true });\n\n // Keep the LOG too — it's the ground-truth action timing the capture-lock\n // check needs in the refine loop (the composition is editable; the log is not).\n await writeFile(captureLogPath, JSON.stringify(log, null, 2));\n\n // One knob: the render grid follows the capture fps (default 60) unless the\n // caller pinned an explicit render fps. (A 30fps\n // render of a 60fps capture would discard half the frames; matching them is\n // what makes 60fps real.)\n const captureFps = opts.capture?.fps ?? 60;\n const planOpts =\n opts.planOpts?.output?.fps == null\n ? { ...opts.planOpts, output: { ...opts.planOpts?.output, fps: captureFps } }\n : opts.planOpts;\n const composition = planComposition(log, planOpts);\n const { mp4Path, compositionPath, warnings } = await renderTake({\n // A draft take renders fast (30fps cap + no blur) but PLANS at full\n // quality: the sibling written below keeps the real settings, so the\n // closing `render` masters this same take without a re-make.\n composition: opts.draft ? toDraft(composition) : composition,\n videoPath: capturePath,\n outPath: resolve(opts.outPath),\n logProgress: opts.logProgress ?? false,\n chromePath,\n captureLog: log,\n ...(opts.draft ? { writeCompositionSibling: false } : {}),\n });\n if (opts.draft) await writeFile(compositionPath, JSON.stringify(composition, null, 2));\n\n return {\n mp4Path,\n compositionPath,\n capturePath,\n captureLogPath,\n composition,\n skipped: log.skipped ?? [],\n settleWaits: log.settleWaits ?? [],\n ...(log.paintedFrac != null ? { paintedFrac: log.paintedFrac } : {}),\n warnings,\n };\n}\n\nexport type RenderCompositionOpts = {\n /** the edited composition (or its parsed JSON) */\n composition: TakeComposition;\n /** the kept raw capture from makeTake (`<out>.capture.mp4`) */\n capturePath: string;\n /** output polished mp4 path */\n outPath: string;\n /** the ground-truth capture log, for the capture-lock check (an edit must not\n * move an action's tMs). Pass it to enforce the lock; omit to skip it. */\n captureLog?: CaptureLog;\n logProgress?: boolean;\n /** Chrome binary; resolved once if omitted */\n chromePath?: string;\n /** render progress (0..1), forwarded from revideo — for a progress UI. */\n onProgress?: (progress: number) => void;\n /** Write the editable `<out>.composition.json` sibling (default true).\n * Callers that already persisted the composition under their own\n * concurrency guard can disable the second, unguarded write. */\n writeCompositionSibling?: boolean;\n};\n\n/** Refine: re-render an EDITED composition over a saved capture — no app\n * drive. This is the talk-to-edit loop's render step. Deterministic: the\n * capture is frozen, so only your edits change the output. Validation runs at\n * the render boundary (renderTake) and throws on a malformed edit — including a\n * capture-locked tMs drift when `captureLog` is supplied. */\nexport async function renderComposition(\n opts: RenderCompositionOpts,\n): Promise<{ mp4Path: string; compositionPath: string; warnings: CompositionIssue[] }> {\n const chromePath = await ensureChrome(opts.chromePath);\n return renderTake({\n composition: opts.composition,\n videoPath: resolve(opts.capturePath),\n outPath: resolve(opts.outPath),\n logProgress: opts.logProgress ?? false,\n chromePath,\n captureLog: opts.captureLog,\n onProgress: opts.onProgress,\n writeCompositionSibling: opts.writeCompositionSibling,\n });\n}\n\n/** Convenience: load a `*.composition.json` and re-render over a saved capture.\n * Auto-loads the sibling capture log (`<video>`.json) so the capture-lock check\n * is enforced in the CLI refine loop — pass `captureLogPath` to override, or\n * set it to `null` to skip. Validation (incl. the lock) runs at the renderTake\n * boundary, which throws on any error BEFORE the expensive render. */\nexport async function renderCompositionFile(opts: {\n compositionPath: string;\n capturePath: string;\n outPath: string;\n /** explicit capture-log path; default = the sibling of capturePath; null skips */\n captureLogPath?: string | null;\n logProgress?: boolean;\n chromePath?: string;\n onProgress?: (progress: number) => void;\n}): Promise<{ mp4Path: string; compositionPath: string; warnings: CompositionIssue[] }> {\n const composition = JSON.parse(\n await readFile(resolve(opts.compositionPath), \"utf8\"),\n ) as TakeComposition;\n const captureLog =\n opts.captureLogPath === null\n ? undefined\n : opts.captureLogPath\n ? (JSON.parse(await readFile(resolve(opts.captureLogPath), \"utf8\")) as CaptureLog)\n : await loadCaptureLogSibling(opts.capturePath);\n if (opts.logProgress)\n process.stderr.write(\n captureLog\n ? \"capture-lock: on (loaded capture log)\\n\"\n : \"capture-lock: off (no capture log)\\n\",\n );\n return renderComposition({\n composition,\n capturePath: opts.capturePath,\n outPath: opts.outPath,\n captureLog,\n logProgress: opts.logProgress,\n chromePath: opts.chromePath,\n onProgress: opts.onProgress,\n });\n}\n"],"mappings":";;;;;;;;;;;AA0BA,MAAM,aAAa;AACnB,MAAM,OAAO;;AAEb,MAAM,cAAc;;AAEpB,MAAM,YAAY;;;;;;;;AASlB,MAAM,YAAY;;;;AAIlB,MAAM,YAAY;;;;AAIlB,MAAM,aAAa;;;AAGnB,MAAM,oBAAoB;;;;AAI1B,MAAM,sBAAsB;;;AAY5B,SAAS,WAAWA,GAAeC,GAAeC,GAAWC,GAAwB;CACnF,MAAM,KAAK,KAAK,KAAK,IAAI,KAAK;CAC9B,MAAM,SAAS,IAAI,YAAY,KAAK,KAAK,KAAK,IAAI,KAAK;AACvD,MAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;EAC1B,MAAM,MAAM,IAAI;EAChB,MAAM,OAAO,KAAK,MAAM,IAAI,KAAK,GAAG;AACpC,OAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;GAC1B,MAAM,IAAI,EAAE,MAAM,KAAM,EAAE,MAAM;AAChC,OAAI,IAAI,eAAe,KAAK,YAAa,QAAO,OAAO,KAAK,MAAM,IAAI,KAAK;EAC5E;CACF;AACD,QAAO;AACR;;;;;;;;;;;;;;;;;;;AAoBD,SAAgB,WACdC,QACAC,OACAH,GACAC,GACAG,SACiB;CACjB,MAAM,KAAK,KAAK,KAAK,IAAI,KAAK;CAC9B,MAAM,KAAK,KAAK,KAAK,IAAI,KAAK;CAC9B,MAAM,SAAS,WAAW,QAAQ,OAAO,GAAG,EAAE;CAC9C,MAAM,WAAW,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,OAAO,UAAU,CAAC;CACjE,MAAM,cAAc,KAAK,MAAM,OAAO,OAAO,GAAI;CACjD,MAAM,gBAAgB,UAAU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