Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Move VideoStudio compose QA into native runtime

wyt0f7483d35781
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json b/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json
index b975e857..bba7e965 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json
@@ -1,13 +1,13 @@
{
"agent_id": "79df9cc89f5f",
- "version": "1.0.12",
+ "version": "1.0.15",
"min_app_version": "1.5.1",
"name": "VideoStudio",
"description_zh": "做视频、也剪视频:解说/动画、AI 口播数字人、给已有视频加字幕/配音旁白、剪辑切片、高光、本地化、混音降噪——凡是“做一段视频”或“对已有视频做处理”的需求都路由到它,而不是 commander 自己拿命令行/ffmpeg 硬拼。三条产线:①解说/动画(脚本→分镜→HTML 合成渲染 mp4);②AI 生成实拍(口播/数字人);③剪辑你上传的真实视频——加旁白/配音、加/烧字幕、剪辑切片、做高光、本地化配音、混音降噪。适合“做个 60 秒讲解 X 的动画”“竖屏短视频介绍产品”“把文案做成带字幕解说”“给这段视频加中文旁白/配音”“给我的视频加字幕/剪一下/做高光/做本地化”。触发词:做视频、解说视频、动画、短视频、视频制作、配音、旁白、加字幕、剪辑、剪视频、给视频加…、给这段视频…、高光切片、本地化配音、竖屏视频",
"description_en": "Makes and edits videos. Routes video requests into three production lines: explainers/animations, AI-generated footage or talking-head/avatar clips, and edits to uploaded real footage. Use it for short videos, captioned explainers, vertical product clips, narration or voiceover, subtitles, trimming, highlights, localization, dubbing, mixing, denoise, or any request to change an existing video. Triggers: make video, explainer, animation, short video, edit video, voiceover, narration, add captions, trim, highlights, localize, dubbing, vertical video",
- "workflow": "You are Video Studio, an in-app video production agent for short videos. Your job is to route the request into one locked production line, produce reviewable artifacts, and stop only at named user gates. Keep model turns lean: load the minimum line-specific skills and project files for the current stage.\n\n### Operating model\n- Route first, then lock one line. Do not silently switch lines after a gate; if the promise changes, ask the user.\n- User-facing gates are only: GATE A concept/brief, GATE B script/storyboard or EDL, optional GATE C billable/sensitive generation, and GATE D draft review.\n- Internal states do not ask the user: brief normalization, narration fit, design contract, HTML authoring, scene-map timing, QA lint/inspect, repair, render, plan/checkpoint updates, loudness/caption checks.\n- After a line is locked, read only the skills needed by that line. Do not carry AUTO/EDIT/GENERATE details into a COMPOSE-only task, or COMPOSE implementation details into EDIT/GENERATE tasks.\n- Use built-in tools and skill scripts as stable production interfaces. Do not inspect platform runtime/source code to discover how a tool/script works; failures are blockers or artifact issues to fix at the VideoStudio layer.\n\n### Gate protocol\nAt every named gate:\n1. Show the artifact in chat: script/plan as concise markdown, images as ![](path), draft video as [video](chat-media://local/<absolute path>).\n2. Add one line describing the next action and any cost/QA note.\n3. Emit one <agent-input-form> with a select and free-text adjustments field, then <plan-interaction status=\"open\" /> and stop. Do not call another tool after opening a gate.\n4. On resume: approve continues; revise changes only the gated artifact; change direction routes back to the appropriate earlier gate.\n\n### Route and lock\nRead video-router for routing. If a line is clear, lock it in the Gate A proposal.\n- COMPOSE: designed explainers, product promos, typography, diagrams, motion graphics, captions/lower-thirds, deterministic HTML/SVG composition.\n- GENERATE: AI-generated cinematic footage, talking-head/avatar, character or scene generation. Billable generation requires Gate C.\n- EDIT: user supplied real footage to cut, subtitle, dub, localize, mix, denoise, or make highlights.\n- AUTO: a true cross-line deliverable where supplied media, generated clips, composed overlays, narration, or editing must be woven into one EDL.\n\n### GATE A - Proposal\nShow inferred brief: line, aspect ratio, duration, language, and 1-3 concepts. Each concept includes hook, visual approach, rough length, and cost note if billable generation may be involved. When the user supplied brand assets, footage, or a site, inspect them before writing concepts and make at least one concept use a supplied asset as the opening hook. Options: pick concept, revise brief/mix, new direction. Stop.\n\n### Shared craft\nFor the locked line, apply video-craft before authoring the gated artifact. Keep it practical: hook, one idea per beat, readable safe-zone text, restrained motion, muted-friendly captions, and audio fit. Do not repeatedly reload the full craft skill inside the same production stage; keep a short checklist in the stage artifact.\n\n### COMPOSE line\nAfter Gate A locks COMPOSE, read stage-compose and frontend-design; read other line skills only if the approved concept explicitly needs them.\n1. Script + storyboard: write project/script.md and project/shotlist.json in one step.\n2. GATE B: show the script plus a compact shotlist summary. Options: approve, revise, change direction. Stop.\n3. On approval, run the COMPOSE production runbook from stage-compose: optional generate_speech once, write project/composition/design-contract.json, then model-author project/composition/index.html directly. For narrated/tightly timed work, also write project/composition/scene-map.json from the approved script/shotlist. Call `video_studio` with op `composition.draft` to prepare declared local vendor assets, check contract/scene-map/HTML consistency, block remote runtime resources, verify local assets, check shotlist/source alignment, verify narration-to-scene mapping, lint, inspect, render, probe final media/audio streams, sample video frames, check for frozen sampled runs, write evidence frames/contact sheet, and write the QA report. Repair at most two localized design-contract/scene-map/HTML issues only when draft fails with blocking errors. If the draft report blocks on source_alignment, narration mapping, media_qa, or audio timing, fix the mapped source/content before rendering again. When draft returns ok:true, freeze index.html/design-contract/scene-map/assets/audio and open Gate D; visual warnings are Gate D advisories, not permission for another self-repair. Do not write or compile spec.json.\n4. GATE D: only after the draft command returns ok with zero blocking QA errors and any triggered composition-design-review has no concrete blockers, show project/render/draft.mp4 and the QA headline/report. Product, promo, version-update, portfolio, style_source, or visibly risky drafts trigger composition-design-review after draft ok and before Gate D; if it reports only advisory/craft findings, list them at Gate D without rerendering. Options: approve high export, revise. Stop.\n5. Final: render high once after approval.\n\n### AUTO line\nRead stage-plan then stage-assemble. Probe/transcribe/OCR supplied media before planning. Write and validate project/plan.json, then Gate B on the EDL summary. Gate C appears only for billable generation. Assemble idempotently: never regenerate produced billable segments; mix narration once; keep compose segments silent when the assembler owns narration. Before Gate D, run stage-plan video_plan --op promise_check --probe-produced; any fail blocks delivery. Gate D shows draft plus QA report.\n\n### GENERATE line\nRead stage-generate; add stage-consistency for recurring characters or story continuity. Plan shots, Gate B on shotlist/script, Gate C before billable generation, then generate/assemble. Preserve built-in lip-synced audio for talking-head clips; do not synthesize over a speaking mouth.\n\n### EDIT line\nRead stage-edit and use actual media evidence before planning: probe every clip, transcribe spoken media, OCR silent/screen/slideshow media. Write project/plan.json, Gate B on the edit plan, then execute trims/concat/mix/subtitles/loudness. Gate D shows the draft and loudness/QA headline.\n\n### Follow-up edits\nIf a draft/final and project/plan.json exist and the user asks for one local change, edit only the affected segment, narration line, caption, trim, volume, speed, or shot. Reproduce only what changed and then re-assemble. Re-plan only when the request genuinely restructures the timeline.\n\n### Deliver\nEvery final response must include the produced media link or a clear blocker. Keep gate and delivery messages short; the artifact is the message.",
+ "workflow": "You are Video Studio, an in-app video production agent for short videos. Your job is to route the request into one locked production line, produce reviewable artifacts, and stop only at named user gates. Keep model turns lean: load the minimum line-specific skills and project files for the current stage.\n\n### Operating model\n- Route first, then lock one line. Do not silently switch lines after a gate; if the promise changes, ask the user.\n- User-facing gates are only: GATE A concept/brief, GATE B script/storyboard or EDL, optional GATE C billable/sensitive generation, and GATE D draft review.\n- Internal states do not ask the user: brief normalization, narration fit, design contract, HTML authoring, scene-map timing, QA lint/inspect, repair, render, plan/checkpoint updates, loudness/caption checks.\n- After a line is locked, read only the skills needed by that line. Do not carry AUTO/EDIT/GENERATE details into a COMPOSE-only task, or COMPOSE implementation details into EDIT/GENERATE tasks.\n- Use built-in tools and skill scripts as stable production interfaces. Do not inspect platform runtime/source code to discover how a tool/script works; failures are blockers or artifact issues to fix at the VideoStudio layer.\n\n### Gate protocol\nAt every named gate:\n1. Show the artifact in chat: script/plan as concise markdown, images as ![](path), draft video as [video](chat-media://local/<absolute path>).\n2. Add one line describing the next action and any cost/QA note.\n3. Emit one <agent-input-form> with a select and free-text adjustments field, then <plan-interaction status=\"open\" /> and stop. Do not call another tool after opening a gate.\n4. On resume: approve continues; revise changes only the gated artifact; change direction routes back to the appropriate earlier gate.\n\n### Route and lock\nRead video-router for routing. If a line is clear, lock it in the Gate A proposal.\n- COMPOSE: designed explainers, product promos, typography, diagrams, motion graphics, captions/lower-thirds, deterministic HTML/SVG composition.\n- GENERATE: AI-generated cinematic footage, talking-head/avatar, character or scene generation. Billable generation requires Gate C.\n- EDIT: user supplied real footage to cut, subtitle, dub, localize, mix, denoise, or make highlights.\n- AUTO: a true cross-line deliverable where supplied media, generated clips, composed overlays, narration, or editing must be woven into one EDL.\n\n### GATE A - Proposal\nShow inferred brief: line, aspect ratio, duration, language, and 1-3 concepts. Each concept includes hook, visual approach, rough length, and cost note if billable generation may be involved. When the user supplied brand assets, footage, or a site, inspect them before writing concepts and make at least one concept use a supplied asset as the opening hook. Options: pick concept, revise brief/mix, new direction. Stop.\n\n### Shared craft\nFor the locked line, apply video-craft before authoring the gated artifact. Keep it practical: hook, one idea per beat, readable safe-zone text, restrained motion, muted-friendly captions, and audio fit. Do not repeatedly reload the full craft skill inside the same production stage; keep a short checklist in the stage artifact.\n\n### COMPOSE line\nAfter Gate A locks COMPOSE, read stage-compose and frontend-design; read other line skills only if the approved concept explicitly needs them.\n1. Script + storyboard: write project/script.md and project/shotlist.json in one step.\n2. GATE B: show the script plus a compact shotlist summary. Options: approve, revise, change direction. Stop.\n3. On approval, run the COMPOSE production runbook from stage-compose: optional generate_speech once, write project/composition/design-contract.json, then model-author project/composition/index.html directly. For narrated/tightly timed work, also write project/composition/scene-map.json from the approved script/shotlist; if scenes use narration_ref or lack inline narration text with numeric windows, write project/composition/narration-map.json before draft. Call `video_studio` with op `composition.draft` to prepare declared local vendor assets, check contract/scene-map/HTML consistency, block remote runtime resources, verify local assets, check shotlist/source alignment, verify narration-to-scene mapping, lint, inspect, render, probe final media/audio streams, sample video frames, check for frozen sampled runs, write evidence frames/contact sheet, and write the QA report. Repair at most two localized design-contract/scene-map/HTML issues only when draft fails with blocking errors. If the draft report blocks on source_alignment, narration mapping, media_qa, or audio timing, fix the mapped source/content before rendering again. When draft returns ok:true, freeze index.html/design-contract/scene-map/assets/audio and open Gate D; visual warnings are Gate D advisories, not permission for another self-repair. Do not write or compile spec.json.\n4. GATE D: only after the draft command returns ok with zero blocking QA errors and any triggered composition-design-review has no concrete blockers, show project/render/draft.mp4 and the QA headline/report. Product, promo, version-update, portfolio, style_source, or visibly risky drafts trigger composition-design-review after draft ok and before Gate D; if it reports only advisory/craft findings, list them at Gate D without rerendering. Options: approve high export, revise. Stop.\n5. Final: render high once after approval.\n\n### AUTO line\nRead stage-plan then stage-assemble. Probe/transcribe/OCR supplied media before planning. Write and validate project/plan.json, then Gate B on the EDL summary. Gate C appears only for billable generation. Assemble idempotently: never regenerate produced billable segments; mix narration once; keep compose segments silent when the assembler owns narration. Before Gate D, run stage-plan video_plan --op promise_check --probe-produced; any fail blocks delivery. Gate D shows draft plus QA report.\n\n### GENERATE line\nRead stage-generate; add stage-consistency for recurring characters or story continuity. Plan shots, Gate B on shotlist/script, Gate C before billable generation, then generate/assemble. Preserve built-in lip-synced audio for talking-head clips; do not synthesize over a speaking mouth.\n\n### EDIT line\nRead stage-edit and use actual media evidence before planning: probe every clip, transcribe spoken media, OCR silent/screen/slideshow media. Write project/plan.json, Gate B on the edit plan, then execute trims/concat/mix/subtitles/loudness. Gate D shows the draft and loudness/QA headline.\n\n### Follow-up edits\nIf a draft/final and project/plan.json exist and the user asks for one local change, edit only the affected segment, narration line, caption, trim, volume, speed, or shot. Reproduce only what changed and then re-assemble. Re-plan only when the request genuinely restructures the timeline.\n\n### Deliver\nEvery final response must include the produced media link or a clear blocker. Keep gate and delivery messages short; the artifact is the message.",
"created_at": "2026-06-23T19:35:00",
- "updated_at": "2026-07-08T17:10:00.000Z",
+ "updated_at": "2026-07-09T07:19:53.000Z",
"knowhow": [
"Routes video requests into COMPOSE, GENERATE, EDIT, or AUTO production lines and loads only the skills needed by the locked line.",
"Separates user-visible gates from internal production states so technical work proceeds without extra approval loops.",
@@ -47,11 +47,11 @@
"Narrated COMPOSE drafts must include project/composition/scene-map.json so source and voiceover alignment can be audited before Gate D.",
"COMPOSE drafts must pass contract_html QA before rendering: design-contract exists, canvas/timing match, approved scene copy appears in HTML, and local assets resolve.",
"COMPOSE index.html must not depend on http/https runtime resources; scripts, fonts, images, CSS, audio, and video must be vendored or produced inside the composition directory.",
- "Narrated COMPOSE drafts should use narration-map.json when line timing is available so narration_ref scene alignment is checked before Gate D.",
+ "Narrated COMPOSE drafts with scene narration_ref or missing inline narration text/timing must include narration-map.json so narration-to-scene alignment is checked before Gate D.",
"COMPOSE Gate D design review should use draft contact_sheet and frame_paths as primary evidence for first-frame, scene-midpoint, and payoff-frame judgment.",
"COMPOSE may open an HTML Preview Gate before Gate D when target duration is at least 45 seconds, scene count is at least 7, a 20-45 second piece has dense/complex visuals, or a prior draft failed; use composition.inspect plus composition.snapshot and do not render mp4 while preview revisions are still being decided.",
"COMPOSE visuals should be SVG-first; use GSAP only for purposeful timed reveals, transitions, or emphasis that improve comprehension.",
- "When COMPOSE HTML uses GSAP, it must load ./assets/vendor/gsap.min.js; the render script owns that offline vendor file, may replace old managed shims, and blocks incompatible user-provided vendor files. Do not manually patch assets/vendor/gsap.min.js inside a composition.",
+ "When COMPOSE HTML uses GSAP, it must load ./assets/vendor/gsap.min.js; the native video_studio draft/render path owns that offline vendor file and blocks missing or incompatible vendor files. Do not manually patch assets/vendor/gsap.min.js inside a composition.",
"COMPOSE draft repair is script-budgeted: the initial failed draft may be followed by two repair passes; if the second repair still fails, the real failing check is returned with repair_budget.budget_exhausted=true, and any later draft attempt returns E_REPAIR_BUDGET_EXCEEDED.",
"Once composition.draft returns ok:true, COMPOSE must freeze index.html, design-contract.json, scene-map.json, assets, and narration until Gate D user feedback; visual inspect and design-review findings are advisory unless a blocking tool check failed.",
"Narrated COMPOSE Gate D requires media_qa evidence for the final mp4: container/video duration near composition duration, a present audio stream, and audio coverage that is not materially shorter than the mapped narration source."
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/bundled-runtime.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/bundled-runtime.ts
index 050302f4..585bd8ae 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/bundled-runtime.ts
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/bundled-runtime.ts
@@ -117,12 +117,9 @@ function resolveFfmpegBinary(kind: 'ffmpeg' | 'ffprobe'): string | undefined {
/**
* Bundled ffmpeg/ffprobe absolute paths, or undefined when not vendored for
- * this platform. HyperFrames render REQUIRES system ffmpeg+ffprobe and ships
- * neither; pointing it at these via `HYPERFRAMES_FFMPEG_PATH` /
- * `HYPERFRAMES_FFPROBE_PATH` makes rendering deterministic instead of relying
- * on whatever the user's machine happens to have. When undefined (e.g. a dev
- * checkout before the vendor step), callers should leave the override unset so
- * HyperFrames falls back to scanning common install dirs.
+ * this platform. VideoStudio skill scripts use these paths for deterministic
+ * local media probing and ffmpeg operations instead of relying on whatever the
+ * user's machine happens to have.
*/
export function bundledFfmpegPaths(): { ffmpeg?: string; ffprobe?: string } {
const result: { ffmpeg?: string; ffprobe?: string } = {};
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/hyperframes_runtime.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/hyperframes_runtime.ts
deleted file mode 100644
index 130cd0f7..00000000
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/hyperframes_runtime.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * Shared runtime for the HyperFrames-backed video tools (render_composition /
- * analyze_media / generate_speech). Centralizes: resolving the bundled Node +
- * npx, building the spawn env (PATH prepend, bundled ffmpeg lock, npm cache +
- * offline/retry hardening, shared Python venv on PATH for tts), and a generic
- * capture-spawn for `--json` ops. hyperframes itself is a runtime npx download
- * (deliberately not bundled — see the design plan §6.2); these knobs make that
- * download reliable.
- */
-
-import { spawn } from 'node:child_process';
-import * as fs from 'node:fs';
-
-import {
- bundledNodeExecutable,
- bundledNpxCli,
- bundledRuntimePathEntries,
- bundledFfmpegPaths,
-} from './bundled-runtime';
-import * as paths from './paths';
-
-/** Pinned HyperFrames version. Bump deliberately (reproducible + known flags). */
-export const HYPERFRAMES_SPEC = '[email protected]';
-
-/** Resolve the bundled Node + npm `npx-cli.js` to run hyperframes as
- * `node <npx-cli.js> ...` — robust cross-platform (no shebang/.cmd/shell). */
-export function resolveHyperframesRunner(): { node: string; npxCli: string } | null {
- const node = bundledNodeExecutable();
- const npxCli = bundledNpxCli();
- if (!node || !npxCli) return null;
- return { node, npxCli };
-}
-
-/** Env for any hyperframes npx invocation. */
-export function buildHyperframesEnv(): NodeJS.ProcessEnv {
- const env: NodeJS.ProcessEnv = { ...process.env };
- const sep = process.platform === 'win32' ? ';' : ':';
-
- const prepend = [...bundledRuntimePathEntries()];
- // Shared Python venv bin → `hyperframes tts` resolves the venv `python` that
- // carries kokoro-onnx. Harmless for render/transcribe (no python shell-out);
- // a non-existent dir is simply ignored by PATH resolution.
- prepend.push(paths.PYTHON_VENV_BIN_DIR);
- if (prepend.length) env.PATH = [...prepend, env.PATH || ''].filter(Boolean).join(sep);
-
- const ff = bundledFfmpegPaths();
- if (ff.ffmpeg) env.HYPERFRAMES_FFMPEG_PATH = ff.ffmpeg;
- if (ff.ffprobe) env.HYPERFRAMES_FFPROBE_PATH = ff.ffprobe;
-
- for (const dir of [paths.NODE_NPM_CACHE_DIR, paths.NODE_NPM_PREFIX_DIR, paths.NODE_NPM_GLOBAL_BIN_DIR]) {
- try { fs.mkdirSync(dir, { recursive: true }); } catch { /* npm will surface a clearer error later */ }
- }
- env.NPM_CONFIG_CACHE = paths.NODE_NPM_CACHE_DIR;
- env.NPM_CONFIG_PREFIX = paths.NODE_NPM_PREFIX_DIR;
- env.NPM_CONFIG_FUND = 'false';
- env.NPM_CONFIG_AUDIT = 'false';
- env.NPM_CONFIG_UPDATE_NOTIFIER = 'false';
- // Warm cache → zero network; bump retries so a cold-download network blip self-heals.
- env.NPM_CONFIG_PREFER_OFFLINE = 'true';
- env.NPM_CONFIG_FETCH_RETRIES = '4';
- return env;
-}
-
-export interface CaptureResult {
- code: number | null;
- stdout: string;
- stderr: string;
- timedOut: boolean;
- aborted: boolean;
-}
-
-const CAPTURE_HEARTBEAT_MS = 15_000;
-
-/**
- * Run `npx hyperframes <args>` and capture stdout/stderr. For `--json` ops
- * (inspect / lint / transcribe) where the output is the product. Never rejects.
- * `onLine` receives complete output lines as they stream (for progress
- * surfacing); `onHeartbeat` fires periodically while the child is alive so
- * long silent phases (e.g. a first-run model download) stay observable.
- */
-export function runHyperframesCapture(
- args: string[],
- opts: {
- cwd?: string;
- signal?: AbortSignal;
- timeoutMs?: number;
- onLine?: (line: string, stream: 'stdout' | 'stderr') => void;
- onHeartbeat?: (elapsedSec: number) => void;
- },
-): Promise<CaptureResult> {
- const runner = resolveHyperframesRunner();
- if (!runner) {
- return Promise.resolve({ code: -1, stdout: '', stderr: 'E_RUNTIME_MISSING: bundled Node not found', timedOut: false, aborted: false });
- }
- const env = buildHyperframesEnv();
- const fullArgs = [runner.npxCli, '--yes', HYPERFRAMES_SPEC, ...args];
- const timeoutMs = opts.timeoutMs ?? 10 * 60 * 1000;
-
- return new Promise<CaptureResult>((resolve) => {
- let child: ReturnType<typeof spawn>;
- try {
- child = spawn(runner.node, fullArgs, { ...(opts.cwd ? { cwd: opts.cwd } : {}), env, ...(opts.signal ? { signal: opts.signal } : {}) });
- } catch (err) {
- resolve({ code: -1, stdout: '', stderr: (err as Error).message, timedOut: false, aborted: false });
- return;
- }
- const out: string[] = [];
- const errChunks: string[] = [];
- let timedOut = false;
- const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeoutMs);
- const startedAtMs = Date.now();
- const heartbeat = opts.onHeartbeat
- ? setInterval(() => opts.onHeartbeat?.(Math.round((Date.now() - startedAtMs) / 1000)), CAPTURE_HEARTBEAT_MS)
- : null;
- (heartbeat as { unref?: () => void } | null)?.unref?.();
- const lineBufs: Record<'stdout' | 'stderr', string> = { stdout: '', stderr: '' };
- const pumpLines = (stream: 'stdout' | 'stderr', chunk: string) => {
- if (!opts.onLine) return;
- lineBufs[stream] += chunk;
- let nl: number;
- while ((nl = lineBufs[stream].indexOf('\n')) !== -1) {
- const line = lineBufs[stream].slice(0, nl);
- lineBufs[stream] = lineBufs[stream].slice(nl + 1);
- try { opts.onLine(line, stream); } catch { /* progress is best-effort */ }
- }
- if (lineBufs[stream].length > 64 * 1024) lineBufs[stream] = lineBufs[stream].slice(-8 * 1024);
- };
- child.stdout?.on('data', (c: Buffer) => {
- const s = c.toString('utf8');
- out.push(s);
- pumpLines('stdout', s);
- });
- child.stderr?.on('data', (c: Buffer) => {
- const s = c.toString('utf8');
- errChunks.push(s);
- pumpLines('stderr', s);
- });
- child.stdin?.end();
- child.on('error', (err) => {
- clearTimeout(timer);
- if (heartbeat) clearInterval(heartbeat);
- resolve({ code: -1, stdout: out.join(''), stderr: err.message, timedOut, aborted: !!opts.signal?.aborted });
- });
- child.on('close', (code) => {
- clearTimeout(timer);
- if (heartbeat) clearInterval(heartbeat);
- resolve({ code, stdout: out.join(''), stderr: errChunks.join(''), timedOut, aborted: !!opts.signal?.aborted });
- });
- });
-}
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/redact.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/redact.ts
index 99131055..badcbeed 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/redact.ts
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/redact.ts
@@ -1,6 +1,6 @@
/**
* Redaction helpers for log/telemetry text. Subprocess stderr (ffmpeg /
- * hyperframes / whisper) can contain absolute filesystem paths, which CLAUDE.md
+ * OCR / whisper) can contain absolute filesystem paths, which CLAUDE.md
* forbids writing to logs. Use `redactPaths` on any captured stderr/stdout tail
* before logging it.
*/
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze.ts
index 190ed3c1..4a4bcd7c 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze.ts
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze.ts
@@ -1,9 +1,8 @@
/**
- * video_analyze — local backend for the `analyze_media` tool. Transcription
- * (and later scene/silence analysis) over real footage. Runs `hyperframes
- * transcribe`, which uses a self-managed whisper.cpp binary + model (NOT Python
- * / torch — spike-verified), so this adds ZERO new dependencies, same runtime
- * pattern as render_composition.
+ * video_analyze — local backend for the `analyze_media` tool. Handles
+ * frame/text/quality analysis over real footage. Spoken transcription is owned
+ * by the built-in `video_studio` tool (`op: "speech.transcribe"`) so this
+ * script stays independent from external render/transcription CLIs.
*
* Multi-op (room to grow: scenes / silence / highlights later). The tool layer
* owns path-sandbox validation.
@@ -13,7 +12,6 @@ import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
-import { runHyperframesCapture } from './hyperframes_runtime';
import {
measureSilenceCoverage,
assessVoiceoverCoverage,
@@ -24,16 +22,9 @@ import {
} from './video_edit';
import type { QualityThresholds } from './video_decide';
import { ocrImageText, ocrImagesText } from './ocr_runtime';
-import { redactPaths } from './redact';
-import { createLogger } from './logger-shim';
-
-const log = createLogger('video-analyze');
const round2 = (n: number): number => Math.round((Number.isFinite(n) ? n : 0) * 100) / 100;
-/** Minimum interval between forwarded transcribe output lines. */
-const TRANSCRIBE_LINE_EMIT_MIN_MS = 3_000;
-
/** Best-effort progress JSONL on stderr (same protocol as video_edit); the
* direct-CLI runner forwards these lines to the user-facing tool progress. */
function emitAnalyzeProgress(op: AnalyzeOp, event: Record<string, unknown>): void {
@@ -45,15 +36,11 @@ function emitAnalyzeProgress(op: AnalyzeOp, event: Record<string, unknown>): voi
}
}
-export type AnalyzeOp = 'transcribe' | 'silence' | 'ocr' | 'scenes' | 'quality';
+export type AnalyzeOp = 'silence' | 'ocr' | 'scenes' | 'quality';
export interface AnalyzeParams {
op: AnalyzeOp;
inputAbsPath: string;
- /** whisper.cpp model: tiny.en / base.en / small.en / medium.en / large-v3.
- * `.en` variants are English-only; large-v3 is multilingual (use it for
- * non-English / Chinese audio). */
- model?: string;
/** op:"ocr" only — seconds between sampled frames (default 2.5). */
intervalSec?: number;
/** op:"ocr" only — cap on sampled frames (default 16). */
@@ -182,51 +169,6 @@ export async function analyzeMedia(p: AnalyzeParams): Promise<AnalyzeResult> {
return { ok: true, op: 'quality', summary: { op: 'quality', ...r.report } };
}
- if (p.op === 'transcribe') {
- const args = ['transcribe', p.inputAbsPath, '--json'];
- if (p.model) args.push('--model', p.model);
- // Run in the input's dir so the emitted transcript.json lands in scope.
- let lastLineEmitMs = 0;
- const r = await runHyperframesCapture(args, {
- cwd: path.dirname(p.inputAbsPath),
- ...(p.signal ? { signal: p.signal } : {}),
- // Generous: the first non-English transcribe downloads the large-v3 model
- // (~3GB) before processing; a tight timeout would fail mid-download.
- timeoutMs: 45 * 60 * 1000,
- onHeartbeat: (elapsedSec) => emitAnalyzeProgress('transcribe', { status: 'heartbeat', elapsed_sec: elapsedSec }),
- // Surface hyperframes' own progress lines (model download, transcribe
- // stages) — stderr only; stdout is the JSON product.
- onLine: (line, stream) => {
- if (stream !== 'stderr') return;
- const text = line.trim();
- if (!text) return;
- const now = Date.now();
- if (now - lastLineEmitMs < TRANSCRIBE_LINE_EMIT_MIN_MS) return;
- lastLineEmitMs = now;
- emitAnalyzeProgress('transcribe', { status: 'output', detail: redactPaths(text).slice(0, 200) });
- },
- });
- if (r.aborted) return { ok: false, errorCode: 'E_ANALYZE_ABORTED', message: 'transcribe aborted.' };
- if (r.timedOut) return { ok: false, errorCode: 'E_ANALYZE_TIMEOUT', message: 'transcribe timed out.' };
-
- const out = r.stdout.trim();
- if (out) {
- try {
- const parsed = JSON.parse(out) as { ok?: boolean; error?: unknown };
- if (parsed && parsed.ok === false) {
- return { ok: false, errorCode: 'E_ANALYZE_FAILED', message: String(parsed.error ?? 'transcribe failed') };
- }
- return { ok: true, op: 'transcribe', summary: parsed };
- } catch { /* fall through to exit-code handling */ }
- }
- if (r.code !== 0) {
- const tail = r.stderr.trim().slice(-1000);
- log.warn(`hyperframes transcribe exited ${r.code}: ${redactPaths(tail.slice(-300))}`);
- return { ok: false, errorCode: 'E_ANALYZE_FAILED', message: `transcribe failed (exit ${r.code}). ${tail || 'No diagnostic output.'}` };
- }
- return { ok: false, errorCode: 'E_ANALYZE_NO_OUTPUT', message: 'transcribe produced no parseable output.' };
- }
-
if (p.op === 'ocr') {
const kind = ocrInputKind(p.inputAbsPath);
if (kind === 'unsupported') {
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint.ts
deleted file mode 100644
index 43b4f74c..00000000
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * video_craft_lint — pure, static craft checks over a HyperFrames composition's
- * index.html. Operationalizes the two deterministically-checkable thresholds
- * from the video-craft skill (legible font size, restrained palette) so the
- * agent gets concrete warnings alongside the structural/visual QA, instead of
- * relying on the model to remember the numbers while it authors HTML.
- *
- * Advisory only — these never block a render; they feed the pre-render review.
- * Layout-dependent craft (text safe zones, overflow) is intentionally left to
- * the headless `inspect` pass, which actually lays the composition out; a static
- * scan can't know rendered geometry.
- */
-
-export interface CraftFinding {
- /** Advisory severity — informs the review, never blocks. */
- level: 'warn';
- code: 'FONT_TOO_SMALL' | 'PALETTE_LARGE';
- message: string;
-}
-
-/** video-craft §4: at 1080p, body text "never below ~40 px". Scales with canvas. */
-const FONT_FLOOR_AT_1080 = 40;
-/** Distinct chromatic colors across the whole file above which we nudge the
- * author to re-check per-scene palette (video-craft §4: ≤ 3–5 on screen). High
- * enough that a normal multi-scene composition doesn't trip it. */
-const PALETTE_SOFT_MAX = 8;
-
-/** Legibility floor scales the 1080p number to the real canvas height. Read it
- * from the root `data-height`; fall back to 1080 when absent/unparseable. */
-function readCanvasHeight(html: string, override?: number): number {
- if (typeof override === 'number' && Number.isFinite(override) && override > 0) return override;
- const m = html.match(/data-height\s*=\s*["']?(\d{2,5})/i);
- const h = m ? Number(m[1]) : NaN;
- return Number.isFinite(h) && h > 0 ? h : 1080;
-}
-
-function fontFloor(height: number): number {
- return Math.max(1, Math.round((FONT_FLOOR_AT_1080 * height) / 1080));
-}
-
-/** Explicit px font-sizes below the floor. Only `px` is judged — em/rem/vw/%/
- * clamp() are not a hard pixel commitment and are skipped on purpose. */
-function smallFontSizesPx(html: string, floor: number): number[] {
- const out = new Set<number>();
- const re = /font-size\s*:\s*([\d.]+)px\b/gi;
- let m: RegExpExecArray | null;
- while ((m = re.exec(html)) !== null) {
- const px = Number(m[1]);
- if (Number.isFinite(px) && px > 0 && px < floor) out.add(px);
- }
- return [...out].sort((a, b) => a - b);
-}
-
-/** Expand a hex body (no '#', lowercased, len 3/4/6/8) to 6 rrggbb digits. */
-function expandHex(h: string): string {
- if (h.length === 3) return h.split('').map((c) => c + c).join('');
- if (h.length === 4) return h.slice(0, 3).split('').map((c) => c + c).join('');
- return h.slice(0, 6); // 6 or 8 (drop alpha)
-}
-
-/** Pure grays (incl. black/white) aren't part of the "≤3–5 colors" budget. */
-function isNeutralHex6(h: string): boolean {
- return h.slice(0, 2) === h.slice(2, 4) && h.slice(2, 4) === h.slice(4, 6);
-}
-
-/** Whitespace-stripped lowercased rgb()/rgba()/hsl()/hsla()/transparent → is it
- * a structural neutral (gray, or fully transparent) rather than a real color? */
-function isNeutralColorFn(s: string): boolean {
- if (s.includes('transparent')) return true;
- const rgb = s.match(/^rgba?\((\d+),(\d+),(\d+)/);
- if (rgb) return rgb[1] === rgb[2] && rgb[2] === rgb[3];
- const hsl = s.match(/^hsla?\(\d+(?:deg)?,(\d+(?:\.\d+)?)%/);
- if (hsl) return Number(hsl[1]) === 0; // 0% saturation = gray
- return false;
-}
-
-/** Distinct chromatic colors used anywhere in the composition. */
-function chromaticColors(html: string): Set<string> {
- const colors = new Set<string>();
- const hexRe = /#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})\b/gi;
- let m: RegExpExecArray | null;
- while ((m = hexRe.exec(html)) !== null) {
- const six = expandHex(m[1].toLowerCase());
- if (!isNeutralHex6(six)) colors.add(`#${six}`);
- }
- const fnRe = /\b(?:rgb|rgba|hsl|hsla)\([^)]*\)/gi;
- while ((m = fnRe.exec(html)) !== null) {
- const key = m[0].toLowerCase().replace(/\s+/g, '');
- if (!isNeutralColorFn(key)) colors.add(key);
- }
- return colors;
-}
-
-/**
- * Static craft lint of a composition's index.html. Returns advisory findings;
- * an empty array means nothing tripped (it does NOT mean the composition is
- * good — only that these two mechanical thresholds passed).
- */
-export function lintCompositionCraft(html: string, opts?: { canvasHeight?: number }): CraftFinding[] {
- const findings: CraftFinding[] = [];
- if (!html) return findings;
-
- const height = readCanvasHeight(html, opts?.canvasHeight);
- const floor = fontFloor(height);
- const small = smallFontSizesPx(html, floor);
- if (small.length) {
- const shown = small.slice(0, 6).map((n) => `${n}px`).join(', ');
- const more = small.length > 6 ? `, +${small.length - 6} more` : '';
- findings.push({
- level: 'warn',
- code: 'FONT_TOO_SMALL',
- message:
- `Font sizes below the legibility floor (~${floor}px for a ${height}px-tall canvas): ${shown}${more}. `
- + `Raise body text to ≥ the floor and titles well above it, or it won't read at phone size.`,
- });
- }
-
- const colors = chromaticColors(html);
- if (colors.size > PALETTE_SOFT_MAX) {
- findings.push({
- level: 'warn',
- code: 'PALETTE_LARGE',
- message:
- `${colors.size} distinct chromatic colors in the composition — aim for ≤ 3–5 on screen at once. `
- + `Re-check each scene: background least-saturated, one accent that reads first.`,
- });
- }
-
- return findings;
-}
-
-/** Render findings as a short text block to append to the QA findings the model
- * reads. Empty string when there are none (so callers can concatenate freely). */
-export function formatCraftFindings(findings: CraftFinding[], opts?: { strict?: boolean }): string {
- if (!findings.length) return '';
- return [
- opts?.strict
- ? '[craft] static threshold checks (FONT_TOO_SMALL blocks under --strict-craft; PALETTE_LARGE is advisory):'
- : '[craft] static threshold checks (advisory, from the video-craft skill):',
- ...findings.map((f) => ` - ${f.code}: ${f.message}`),
- ].join('\n');
-}
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts
index 8937a641..dacfedd6 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts
@@ -2,7 +2,8 @@
* video_edit — local backend for the `edit_video` tool (deterministic real-
* footage editing). Runs the bundled ffmpeg/ffprobe (see util/bundled-runtime
* `bundledFfmpegPaths`) — zero new dependencies, no network, no npx. This is
- * the "C 剪辑" capability axis; render_composition (HyperFrames) stays separate.
+ * the "C 剪辑" capability axis; COMPOSE rendering is owned by the native
+ * `video_studio` tool.
*
* Multi-op (per the design decision that edit_video is one multi-sub-op tool):
* probe | trim | concat | burnsubs | overlay | extract_frame
@@ -153,7 +154,7 @@ export interface EditParams {
* for silence) and the smallest kept sliver (default 0.3s). */
padSec?: number;
minKeepSec?: number;
- /** remove_fillers: the analyze_media transcribe JSON (word-level timings) and the
+ /** remove_fillers: the video_studio speech.transcribe JSON (word-level timings) and the
* filler tokens to drop (default um/uh/...). */
transcriptAbsPath?: string;
fillers?: string[];
@@ -931,12 +932,12 @@ export async function editVideo(p: EditParams): Promise<EditResult> {
if (p.op === 'remove_fillers') {
if (!p.inputAbsPath) return fail('E_EDIT_ARG', 'remove_fillers requires input_path');
- if (!p.transcriptAbsPath) return fail('E_EDIT_ARG', 'remove_fillers requires transcript_path (the analyze_media transcribe JSON with word timings)');
+ if (!p.transcriptAbsPath) return fail('E_EDIT_ARG', 'remove_fillers requires transcript_path (the video_studio speech.transcribe JSON with word timings)');
let json: unknown;
try { json = JSON.parse(await fs.readFile(p.transcriptAbsPath, 'utf8')); }
catch (err) { return fail('E_EDIT_TRANSCRIPT_PARSE', `could not read/parse transcript_path: ${(err as Error).message}`); }
const words = normalizeTranscriptWords(json);
- if (!words.length) return fail('E_EDIT_NO_WORDS', 'transcript had no word-level timings — re-run analyze_media transcribe (--json) on this clip.');
+ if (!words.length) return fail('E_EDIT_NO_WORDS', 'transcript had no word-level timings — re-run video_studio op:"speech.transcribe" with timestamps:"word" on this clip.');
const padSec = finiteNum(p.padSec);
const minKeepSec = finiteNum(p.minKeepSec);
const removeSpans = fillerSpansFromWords(
@@ -988,7 +989,7 @@ export async function editVideo(p: EditParams): Promise<EditResult> {
return fail(
'E_EDIT_BASE_HAS_AUDIO',
'The base video already has an audio track, so mixing narration onto it would STACK a second voice (the "two voices" defect). '
- + 'Render the base SILENT first — for a compose segment, remove the narration <audio> from its index.html so render_composition produces no audio, then re-mix. '
+ + 'Render the base SILENT first — for a compose segment, remove the narration <audio> from its index.html so the native composition draft has no audio, then re-mix. '
+ "If layering is intended (e.g. music under a talking-head's built-in lip-synced voice) pass on_existing_audio='mix'; "
+ "to drop the base audio and keep only this narration pass on_existing_audio='replace'.",
);
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render.ts
deleted file mode 100644
index e35d2051..00000000
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render.ts
+++ /dev/null
@@ -1,530 +0,0 @@
-/**
- * video_render — local backend for the `render_composition` tool.
- *
- * Renders a HyperFrames HTML composition directory to an mp4/webm by running
- * the upstream `hyperframes` CLI on Orkas's bundled Node runtime. This is the
- * "方案 A (local)" backend; a future hosted backend (方案 B) plugs in behind the
- * same `renderComposition()` signature without touching the tool or skills.
- *
- * Spike-verified facts (see PC/docs/plans/video-agents-design-plan.md §12.1):
- * - HyperFrames render REQUIRES system ffmpeg + ffprobe and bundles NEITHER.
- * We point it at the bundled ffmpeg-static via HYPERFRAMES_FFMPEG_PATH /
- * HYPERFRAMES_FFPROBE_PATH. When those aren't vendored yet (dev checkout),
- * we leave the override unset so HyperFrames falls back to scanning common
- * install dirs (the dev machine's system ffmpeg).
- * - It uses puppeteer-core + @puppeteer/browsers and prefers system Chrome;
- * only machines without Chrome download a managed Chromium (~180MB).
- * - Child Chrome/worker processes do NOT inherit env automatically, so we pass
- * a fully-composed env to the top spawn and let it propagate down.
- */
-
-import * as fs from 'node:fs/promises';
-import * as os from 'node:os';
-import * as path from 'node:path';
-import { spawn } from 'node:child_process';
-
-// Single source of truth for the bundled-node + npx + env (incl. the pinned
-// HYPERFRAMES_SPEC). render/inspect, transcribe, and tts all share it so the
-// hyperframes version can never drift between them.
-import { HYPERFRAMES_SPEC, resolveHyperframesRunner, buildHyperframesEnv } from './hyperframes_runtime';
-import { lintCompositionCraft, formatCraftFindings, type CraftFinding } from './video_craft_lint';
-import { redactPaths } from './redact';
-import { createLogger } from './logger-shim';
-
-const log = createLogger('video-render');
-
-/** Backstop kill for a wedged render that emits nothing. Long renders are
- * legitimate, so this is generous; normal completion / user abort happen far
- * sooner via ctx.signal. */
-const RENDER_TIMEOUT_MS = 20 * 60 * 1000;
-/** Constrained machines software-render frame-by-frame — far slower — so the
- * outer watchdog and HyperFrames' own timeouts must not preempt a legitimately
- * slow (but progressing) render. */
-const CONSTRAINED_RENDER_TIMEOUT_MS = 40 * 60 * 1000;
-const CONSTRAINED_PROTOCOL_TIMEOUT_MS = 15 * 60 * 1000; // vs hyperframes 5min default
-const CONSTRAINED_PLAYER_READY_TIMEOUT_MS = 3 * 60 * 1000; // vs 45s default
-const CONSTRAINED_BROWSER_TIMEOUT_MS = 3 * 60 * 1000; // vs 60s default
-/** inspect/lint only expose --timeout (runtime init); bump it on slow machines. */
-const CONSTRAINED_QA_INIT_TIMEOUT_MS = 30 * 1000; // vs 5s default
-
-/** RAM at or below this (GB) trips the constrained render profile — matches
- * HyperFrames' own low-memory auto-threshold so the two agree. */
-export const LOW_RAM_GB = 8;
-/** Cost heuristic marking a render infeasible under software rendering on a
- * constrained machine within a reasonable budget. ~1080x1920@30s@30fps (~1863)
- * is fine; 60s@60fps (~7452) is heavy. Keep the knobs here; log the decision. */
-export const HEAVY_RENDER_COST = 3000;
-
-/** True when this machine should use the low-memory render profile. `gpuMode`
- * (from a prior attempt's output) forces it even on a high-RAM box. */
-export function isConstrainedMachine(totalRamGB: number, observedGpuMode?: string): boolean {
- return totalRamGB <= LOW_RAM_GB || observedGpuMode === 'software';
-}
-
-/** Coarse render cost = frames × megapixels. Pure, unit-tested. */
-export function estimateRenderCost(width: number, height: number, durationSec: number, fps: number): number {
- const frames = Math.max(1, durationSec) * Math.max(1, fps);
- const megapixels = Math.max(1, (width * height) / 1_000_000);
- return Math.round(frames * megapixels);
-}
-
-/** What to do with a heavy render on a constrained machine: a draft degrades
- * (cheaper, still reviewable); a final never silently degrades — it fails fast
- * with an actionable message instead of a long hang. */
-export function renderCostDecision(opts: { constrained: boolean; costUnits: number; isFinal: boolean }): 'proceed' | 'degrade' | 'fail_fast' {
- if (!opts.constrained || opts.costUnits <= HEAVY_RENDER_COST) return 'proceed';
- return opts.isFinal ? 'fail_fast' : 'degrade';
-}
-
-/** Lower fps first (product decision). Returns a reduced fps, or the same value
- * when it is already at/below the floor (caller then proceeds as-is). */
-export function degradedFps(fps: number): number {
- if (fps > 30) return 30;
- return fps; // already ≤30; fps degrade exhausted
-}
-
-/** Error/crash tails were truncated to ~1000 chars, which hides the native V8
- * crash backtrace weak/no-GPU machines produce. Keep a generous tail in the
- * result; the full stdout+stderr is persisted to `logPath` when given. */
-const RENDER_LOG_TAIL_CHARS = 8000;
-
-/** HyperFrames QA emits no trace of its own; a heartbeat is the only liveness
- * signal while headless Chrome seeks the timeline. */
-const QA_PROGRESS_HEARTBEAT_MS = 15_000;
-
-/** Machine + HyperFrames render facts parsed from the child's own output, so a
- * failed/slow render is self-explaining (was it software-rendering? how much
- * RAM? a native worker crash or a timeout?). */
-export interface RenderDiagnostics {
- gpuMode?: 'hardware' | 'software' | 'unknown';
- workers?: string;
- protocolTimeoutMs?: number;
- playerReadyTimeoutMs?: number;
- browserTimeoutMs?: number;
- totalRamGB?: number;
- crashSignature?: 'native_worker_crash' | 'timeout' | null;
-}
-
-export function machineRamGB(): number {
- return Math.round((os.totalmem() / 1024 ** 3) * 10) / 10;
-}
-
-/** Parse HyperFrames' own `Pipeline started {...}` JSON and the gpu-probe line
- * from the combined child output. Pure — unit-tested against real log lines. */
-export function parseRenderDiagnostics(output: string): RenderDiagnostics {
- const d: RenderDiagnostics = {};
- const s = String(output || '');
- // The `Pipeline started {...}` line carries nested objects (e.g. "fps":{...}),
- // so take the whole line's first `{` .. last `}` rather than a lazy match.
- const line = s.split(/\r?\n/).find((l) => l.includes('Pipeline started') && l.includes('{'));
- if (line) {
- const start = line.indexOf('{');
- const end = line.lastIndexOf('}');
- if (start !== -1 && end > start) {
- try {
- const j = JSON.parse(line.slice(start, end + 1)) as Record<string, unknown>;
- const gm = j.browserGpuMode;
- if (gm === 'hardware' || gm === 'software') d.gpuMode = gm;
- if (j.requestedWorkers != null) d.workers = String(j.requestedWorkers);
- const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
- d.protocolTimeoutMs = num(j.protocolTimeoutMs) ?? num(j.protocolTimeout);
- d.playerReadyTimeoutMs = num(j.playerReadyTimeoutMs) ?? num(j.playerReadyTimeout);
- d.browserTimeoutMs = num(j.browserTimeoutMs) ?? num(j.browserTimeout);
- } catch { /* not the line we wanted */ }
- }
- }
- if (!d.gpuMode) {
- const m = s.match(/browserGpuMode\s*(?:auto\s*(?:→|->)\s*)?["']?(hardware|software)["']?/i);
- if (m) d.gpuMode = m[1].toLowerCase() as 'hardware' | 'software';
- }
- return d;
-}
-
-/** Classify a native crash vs a timeout from the child's stderr + exit code.
- * `exit null` + V8 isolate/snapshot symbols is the weak-machine crash we saw. */
-export function classifyRenderCrash(
- stderr: string,
- code: number | null,
- timedOut: boolean,
-): 'native_worker_crash' | 'timeout' | null {
- if (timedOut) return 'timeout';
- const s = String(stderr || '');
- if (
- /NewIsolate|SnapshotData|MultiIsolatePlatform|v8::internal|Segmentation fault|SIGSEGV|SIGABRT|Fatal error/i.test(s)
- && code !== 0
- ) return 'native_worker_crash';
- return null;
-}
-
-/** Best-effort: persist the full combined child log to `logPath`. Never throws
- * (a diagnostics write must not fail the render). Returns the path or null. */
-async function writeRenderLog(logPath: string | undefined, combined: string): Promise<string | null> {
- if (!logPath) return null;
- try {
- await fs.mkdir(path.dirname(logPath), { recursive: true }).catch(() => {});
- await fs.writeFile(logPath, combined, 'utf8');
- return logPath;
- } catch {
- return null;
- }
-}
-
-/** Compact human line for a failure message / report, from parsed diagnostics. */
-function diagnosticsSummary(d: RenderDiagnostics): string {
- const parts: string[] = [];
- if (d.gpuMode) parts.push(`gpu=${d.gpuMode}`);
- if (typeof d.totalRamGB === 'number') parts.push(`ram=${d.totalRamGB}GB`);
- if (d.workers) parts.push(`workers=${d.workers}`);
- if (d.crashSignature) parts.push(`crash=${d.crashSignature}`);
- return parts.join(' ');
-}
-
-export type RenderQuality = 'draft' | 'standard' | 'high';
-export type RenderFormat = 'mp4' | 'webm';
-
-export interface RenderCompositionParams {
- /** Absolute path to the composition project dir (holds index.html). */
- projectDirAbs: string;
- /** Absolute path for the rendered output (.mp4 / .webm). */
- outputAbsPath: string;
- quality?: RenderQuality;
- fps?: number;
- format?: RenderFormat;
- /** Optional `data-composition-variables` overrides (object keyed by id). */
- variables?: Record<string, unknown>;
- signal?: AbortSignal;
- onProgress?: (event: { phase: string; message: string }) => void;
- /** When set, the full combined child stdout+stderr is written here for
- * diagnosis (path-sandboxed by the caller). */
- logPath?: string;
- /** Low-memory / no-GPU render profile: pin 1 worker + bump timeouts so a slow
- * software render finishes instead of crashing/timing out. */
- constrained?: boolean;
-}
-
-export type RenderCompositionResult =
- | { ok: true; path: string; bytes: number; diagnostics?: RenderDiagnostics; logPath?: string }
- | { ok: false; errorCode: string; message: string; diagnostics?: RenderDiagnostics; logPath?: string };
-
-function buildRenderArgs(p: RenderCompositionParams): string[] {
- const args = ['render', '--output', p.outputAbsPath];
- if (p.quality) args.push('--quality', p.quality);
- if (typeof p.fps === 'number') args.push('--fps', String(p.fps));
- if (p.format) args.push('--format', p.format);
- if (p.constrained) {
- args.push(
- '--low-memory-mode',
- '--workers', '1',
- '--protocol-timeout', String(CONSTRAINED_PROTOCOL_TIMEOUT_MS),
- '--player-ready-timeout', String(CONSTRAINED_PLAYER_READY_TIMEOUT_MS),
- '--browser-timeout', String(CONSTRAINED_BROWSER_TIMEOUT_MS),
- );
- }
- if (p.variables && Object.keys(p.variables).length) {
- args.push('--variables', JSON.stringify(p.variables));
- }
- return args;
-}
-
-/** Parse a HyperFrames `[Render:trace]` JSON line into a coarse progress event. */
-function parseTraceLine(line: string): { phase: string; message: string } | null {
- const idx = line.indexOf('[Render:trace]');
- if (idx === -1) return null;
- const jsonStart = line.indexOf('{', idx);
- if (jsonStart === -1) return null;
- try {
- const trace = JSON.parse(line.slice(jsonStart)) as { phase?: unknown; status?: unknown };
- const phase = typeof trace.phase === 'string' ? trace.phase : 'render';
- const status = typeof trace.status === 'string' ? trace.status : '';
- return { phase: `render.${phase}`, message: status ? `${phase} ${status}` : phase };
- } catch {
- return null;
- }
-}
-
-/**
- * Render `projectDirAbs` to `outputAbsPath`. Path-sandbox validation is the
- * caller's (the tool's) responsibility — this backend trusts the absolute
- * paths it receives.
- */
-export async function renderComposition(p: RenderCompositionParams): Promise<RenderCompositionResult> {
- const runner = resolveHyperframesRunner();
- if (!runner) {
- return {
- ok: false,
- errorCode: 'E_RENDER_RUNTIME_MISSING',
- message: 'Bundled Node runtime not found; cannot run the HyperFrames renderer.',
- };
- }
-
- // Confirm the project dir has a composition entry before spawning.
- const indexHtml = path.join(p.projectDirAbs, 'index.html');
- try {
- const st = await fs.stat(indexHtml);
- if (!st.isFile()) throw new Error('not a file');
- } catch {
- return {
- ok: false,
- errorCode: 'E_RENDER_NO_COMPOSITION',
- message: `No index.html found in composition dir: ${p.projectDirAbs}`,
- };
- }
-
- await fs.mkdir(path.dirname(p.outputAbsPath), { recursive: true }).catch(() => {});
-
- const env = buildHyperframesEnv();
- const args = [runner.npxCli, '--yes', HYPERFRAMES_SPEC, ...buildRenderArgs(p)];
-
- return new Promise<RenderCompositionResult>((resolve) => {
- let child: ReturnType<typeof spawn>;
- try {
- child = spawn(runner.node, args, {
- cwd: p.projectDirAbs,
- env,
- ...(p.signal ? { signal: p.signal } : {}),
- });
- } catch (err) {
- resolve({ ok: false, errorCode: 'E_RENDER_SPAWN', message: (err as Error).message });
- return;
- }
-
- const errChunks: string[] = [];
- const outChunks: string[] = [];
- let stdoutBuf = '';
- let settled = false;
- let timedOut = false;
-
- const renderTimeoutMs = p.constrained ? CONSTRAINED_RENDER_TIMEOUT_MS : RENDER_TIMEOUT_MS;
- const timer = setTimeout(() => {
- timedOut = true;
- child.kill('SIGKILL');
- }, renderTimeoutMs);
-
- const pumpProgress = (chunk: string) => {
- stdoutBuf += chunk;
- let nl: number;
- while ((nl = stdoutBuf.indexOf('\n')) !== -1) {
- const line = stdoutBuf.slice(0, nl);
- stdoutBuf = stdoutBuf.slice(nl + 1);
- const ev = parseTraceLine(line);
- if (ev) p.onProgress?.(ev);
- }
- };
-
- child.stdout?.on('data', (c: Buffer) => {
- const s = c.toString('utf8');
- outChunks.push(s);
- pumpProgress(s);
- });
- child.stderr?.on('data', (c: Buffer) => {
- const s = c.toString('utf8');
- errChunks.push(s);
- pumpProgress(s); // hyperframes routes some [Render:trace] lines to stderr
- });
- child.stdin?.end();
-
- const finish = (r: RenderCompositionResult) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(r);
- };
-
- child.on('error', (err: Error) => {
- // Abort surfaces here as an AbortError; report it as such, not a crash.
- if (p.signal?.aborted) {
- finish({ ok: false, errorCode: 'E_RENDER_ABORTED', message: 'Render aborted.' });
- return;
- }
- finish({ ok: false, errorCode: 'E_RENDER_SPAWN', message: err.message });
- });
-
- child.on('close', async (code: number | null) => {
- const stdout = outChunks.join('');
- const stderr = errChunks.join('').trim();
- const combined = stdout + (stderr ? `\n--- stderr ---\n${stderr}` : '');
- const diagnostics: RenderDiagnostics = {
- ...parseRenderDiagnostics(combined),
- totalRamGB: machineRamGB(),
- crashSignature: classifyRenderCrash(stderr, code, timedOut),
- };
- const logPath = (await writeRenderLog(p.logPath, combined)) ?? undefined;
- const withDiag = (r: RenderCompositionResult): RenderCompositionResult =>
- ({ ...r, diagnostics, ...(logPath ? { logPath } : {}) });
- const summary = diagnosticsSummary(diagnostics);
-
- if (timedOut) {
- finish(withDiag({ ok: false, errorCode: 'E_RENDER_TIMEOUT', message: `Render timed out after ${renderTimeoutMs}ms.${summary ? ` [${summary}]` : ''}` }));
- return;
- }
- if (p.signal?.aborted) {
- finish(withDiag({ ok: false, errorCode: 'E_RENDER_ABORTED', message: 'Render aborted.' }));
- return;
- }
- if (code !== 0) {
- const tail = stderr.slice(-RENDER_LOG_TAIL_CHARS);
- log.warn(`hyperframes render exited ${code}: ${redactPaths(tail.slice(-300))}${summary ? ` [${summary}]` : ''}`);
- return finish(withDiag({
- ok: false,
- errorCode: 'E_RENDER_FAILED',
- message: `HyperFrames render failed (exit ${code}).${summary ? ` [${summary}]` : ''}${logPath ? ` Full log: ${logPath}.` : ''} ${tail || 'No diagnostic output.'}`,
- }));
- }
- const st = await fs.stat(p.outputAbsPath).catch(() => null);
- if (!st || !st.isFile() || st.size === 0) {
- return finish(withDiag({
- ok: false,
- errorCode: 'E_RENDER_NO_OUTPUT',
- message: `Render reported success but no output file was produced at ${p.outputAbsPath}.`,
- }));
- }
- finish(withDiag({ ok: true, path: p.outputAbsPath, bytes: st.size }));
- });
- });
-}
-
-export type QaOp = 'lint' | 'inspect';
-
-export type QaResult =
- | { ok: true; op: QaOp; findings: string; diagnostics?: RenderDiagnostics; logPath?: string }
- | { ok: false; errorCode: string; message: string; diagnostics?: RenderDiagnostics; logPath?: string };
-
-/** Backstop for a wedged QA pass. `inspect` spawns headless Chrome to seek the
- * timeline; a few minutes is generous. */
-const QA_TIMEOUT_MS = 5 * 60 * 1000;
-
-function withStrictCraftFindings(findings: string, craftFindings: CraftFinding[]): string {
- const blockingFindings = craftFindings.filter((f) => f.code === 'FONT_TOO_SMALL');
- if (!blockingFindings.length) return findings;
- try {
- const parsed = JSON.parse(findings) as Record<string, unknown>;
- const existingIssues = Array.isArray(parsed.issues) ? parsed.issues : [];
- const craftIssues = blockingFindings.map((f) => ({
- code: f.code,
- severity: 'error',
- selector: 'document',
- message: f.message,
- fixHint: 'Raise all readable text to the video-craft legibility floor before rendering.',
- source: 'video-craft',
- }));
- const add = craftIssues.length;
- const numberField = (key: string) => (typeof parsed[key] === 'number' ? parsed[key] as number : 0);
- parsed.ok = false;
- parsed.errorCount = numberField('errorCount') + add;
- parsed.issueCount = numberField('issueCount') + add;
- parsed.totalIssueCount = numberField('totalIssueCount') + add;
- parsed.issues = [...existingIssues, ...craftIssues];
- return JSON.stringify(parsed, null, 2);
- } catch {
- return `${findings}\n\n[craft] BLOCKING strict checks:\n${blockingFindings.map((f) => ` - ${f.code}: ${f.message}`).join('\n')}`;
- }
-}
-
-/**
- * Run a HyperFrames QA pass (`lint` structural / `inspect` visual) over the
- * composition dir and return its `--json` findings. `inspect` seeks the rendered
- * layout in headless Chrome and reports text overflow / off-canvas / clipping —
- * a real visual check the model can act on, unlike re-reading its own HTML. No
- * ffmpeg needed. The findings are the product, so they are returned regardless
- * of exit code (a non-zero exit just means issues were found).
- */
-export async function qaComposition(
- op: QaOp,
- p: {
- projectDirAbs: string;
- signal?: AbortSignal;
- strictCraft?: boolean;
- onProgress?: (event: { phase: string; message: string }) => void;
- logPath?: string;
- constrained?: boolean;
- },
-): Promise<QaResult> {
- const runner = resolveHyperframesRunner();
- if (!runner) {
- return { ok: false, errorCode: 'E_RENDER_RUNTIME_MISSING', message: 'Bundled Node runtime not found.' };
- }
- const indexHtml = path.join(p.projectDirAbs, 'index.html');
- const st = await fs.stat(indexHtml).catch(() => null);
- if (!st || !st.isFile()) {
- return { ok: false, errorCode: 'E_RENDER_NO_COMPOSITION', message: `No index.html in: ${p.projectDirAbs}` };
- }
-
- const env = buildHyperframesEnv();
- const args = [runner.npxCli, '--yes', HYPERFRAMES_SPEC, op, '--json'];
- // inspect/lint only expose --timeout (runtime init); a slow machine needs longer.
- if (p.constrained) args.push('--timeout', String(CONSTRAINED_QA_INIT_TIMEOUT_MS));
-
- return new Promise<QaResult>((resolve) => {
- let child: ReturnType<typeof spawn>;
- try {
- child = spawn(runner.node, args, { cwd: p.projectDirAbs, env, ...(p.signal ? { signal: p.signal } : {}) });
- } catch (err) {
- resolve({ ok: false, errorCode: 'E_QA_SPAWN', message: (err as Error).message });
- return;
- }
- const out: string[] = [];
- const errOut: string[] = [];
- let settled = false;
- let timedOut = false;
- const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, QA_TIMEOUT_MS);
- const startedAtMs = Date.now();
- const heartbeat = p.onProgress
- ? setInterval(() => p.onProgress?.({ phase: `qa.${op}`, message: `${op} running (${Math.round((Date.now() - startedAtMs) / 1000)}s elapsed)` }), QA_PROGRESS_HEARTBEAT_MS)
- : null;
- (heartbeat as { unref?: () => void } | null)?.unref?.();
- let traceBuf = '';
- const pumpTrace = (chunk: string) => {
- if (!p.onProgress) return;
- traceBuf += chunk;
- let nl: number;
- while ((nl = traceBuf.indexOf('\n')) !== -1) {
- const line = traceBuf.slice(0, nl);
- traceBuf = traceBuf.slice(nl + 1);
- const ev = parseTraceLine(line);
- if (ev) p.onProgress?.(ev);
- }
- };
- child.stdout?.on('data', (c: Buffer) => out.push(c.toString('utf8')));
- child.stderr?.on('data', (c: Buffer) => { const s = c.toString('utf8'); errOut.push(s); pumpTrace(s); });
- child.stdin?.end();
- const finish = (r: QaResult) => { if (settled) return; settled = true; clearTimeout(timer); if (heartbeat) clearInterval(heartbeat); resolve(r); };
- child.on('error', (err: Error) => {
- if (p.signal?.aborted) return finish({ ok: false, errorCode: 'E_QA_ABORTED', message: `${op} aborted.` });
- finish({ ok: false, errorCode: 'E_QA_SPAWN', message: err.message });
- });
- child.on('close', async (code: number | null) => {
- if (timedOut) return finish({ ok: false, errorCode: 'E_QA_TIMEOUT', message: `${op} timed out.` });
- if (p.signal?.aborted) return finish({ ok: false, errorCode: 'E_QA_ABORTED', message: `${op} aborted.` });
- const findings = out.join('').trim();
- if (!findings) {
- const stderrFull = errOut.join('').trim();
- const combined = out.join('') + (stderrFull ? `\n--- stderr ---\n${stderrFull}` : '');
- const diagnostics: RenderDiagnostics = {
- ...parseRenderDiagnostics(combined),
- totalRamGB: machineRamGB(),
- crashSignature: classifyRenderCrash(stderrFull, code, false),
- };
- const logPath = (await writeRenderLog(p.logPath, combined)) ?? undefined;
- const summary = diagnosticsSummary(diagnostics);
- return finish({
- ok: false,
- errorCode: 'E_QA_NO_OUTPUT',
- message: `${op} produced no findings.${summary ? ` [${summary}]` : ''}${logPath ? ` Full log: ${logPath}.` : ''} ${stderrFull.slice(-RENDER_LOG_TAIL_CHARS) || 'No diagnostic output.'}`,
- diagnostics,
- ...(logPath ? { logPath } : {}),
- });
- }
- // Append advisory craft-threshold findings (pure static scan of the HTML).
- // Best-effort: a read failure must never fail the QA pass.
- let craft = '';
- let finalFindings = findings;
- try {
- const html = await fs.readFile(indexHtml, 'utf8');
- const craftFindings = lintCompositionCraft(html);
- if (p.strictCraft) finalFindings = withStrictCraftFindings(findings, craftFindings);
- craft = formatCraftFindings(craftFindings, { strict: !!p.strictCraft });
- } catch { /* advisory only; ignore */ }
- finish({ ok: true, op, findings: craft ? `${finalFindings}\n\n${craft}` : finalFindings });
- });
- });
-}
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/SKILL.md
index 3a4b7ff4..47b12c9e 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/SKILL.md
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/SKILL.md
@@ -19,7 +19,7 @@ After Gate B approves the script/storyboard, keep the production turn narrow:
1. Read only the approved `project/script.md`, `project/shotlist.json`, and this skill if not already loaded for the current turn. Also read `frontend-design`; read `design-system-importer` only when a concrete style source or explicit named reference exists. Do not read `composition-design-review` until the draft returns `ok: true` and its trigger applies.
2. If standalone narration is needed, call `generate_speech` once to `project/composition/assets/narration.mp3`.
-3. Write `project/composition/design-contract.json`, then model-author `project/composition/index.html` directly. For narrated work, also write `project/composition/scene-map.json` from the approved script/shotlist so timing QA can verify voiceover-to-visual alignment. If narration line timing is known, write `project/composition/narration-map.json`.
+3. Write `project/composition/design-contract.json`, then model-author `project/composition/index.html` directly. For narrated work, also write `project/composition/scene-map.json` from the approved script/shotlist so timing QA can verify voiceover-to-visual alignment. If scenes use `narration_ref` or lack inline narration text with numeric windows, write `project/composition/narration-map.json` before draft.
4. Decide whether to open the optional HTML Preview Gate before rendering mp4. Use the preview gate when expected render rework is expensive: target duration >= 45s, scene count >= 7, render cost is likely slow, or the composition has dense text, complex SVG/GSAP, many branded/supplied assets, or a prior draft failure. Skip it for short/simple work: target duration < 20s, scene count <= 4, no narration/timing complexity, and no obvious visual-risk signal. The subject category alone never forces the preview gate.
5. If the HTML Preview Gate is needed, run `video_studio` `op: "composition.inspect"` and `op: "composition.snapshot"` to `project/composition/preview/first-frame.png`, then show the first-frame image, inspect headline, `index.html` path, and why preview was inserted. Options: approve HTML preview, revise HTML/design, or render draft anyway. Stop. On approval, continue to the draft command. On revise, modify only `design-contract.json`, `scene-map.json`, or `index.html`, then rerun inspect/snapshot and reopen the same preview gate.
6. Run the draft command with `video_studio` `op: "composition.draft"`. Before rendering, the production path prepares declared local vendor assets, checks `contract_html` design-contract/scene-map/HTML consistency, blocks remote runtime resources, verifies local assets, checks shotlist/source alignment, and checks narration mapping. Then it runs lint, inspect, render, audio/media QA, sampled-frame QA, and writes one QA report.
@@ -99,17 +99,17 @@ For narrated or tightly timed work, write `project/composition/scene-map.json` b
If the approved shotlist beat is intentionally merged into a longer visual scene, add `source_alignment.merge_reason` or per-scene `source_shots`. When audio exists, every scene must include either concise `narration` text or a `narration_ref`/`source_shots` mapping to the approved script/shotlist.
-When TTS or a transcription step gives line timing, add `project/composition/narration-map.json`:
+When scenes use `narration_ref`, add `project/composition/narration-map.json` before draft:
```json
{
"lines": [
- { "id": "n01", "start": 0.0, "duration": 3.2, "text": "Meet Orkas 1.5.0." }
+ { "id": "n01", "scene_id": "hook", "start": 0.0, "end": 3.2, "text": "Meet Orkas 1.5.0." }
]
}
```
-Then use `"narration_ref": "n01"` or a comma-separated list on the matching scene. Draft QA uses this map before falling back to coarse text-length timing, so voiceover/visual drift is caught earlier.
+Then use `"narration_ref": "n01"` or a comma-separated list on the matching scene. Timed media refs such as `"assets/narration.mp3#t=0.0,3.2"` are also valid when the map line includes `scene_id` or matching start/end. If no map is present, every narrated scene must include inline `narration`/`narration_text` plus numeric start/duration or start/end; otherwise draft QA blocks Gate D.
## Composition contract (the minimum that renders)
@@ -162,7 +162,7 @@ Canonical minimal `index.html` (16:9, 10s):
- **SVG-first visual layer**: prefer inline SVG for non-text motion graphics such as diagrams, connectors, nodes, progress paths, charts, orbit lines, icon-like marks, and background geometry. Keep readable prose in normal HTML text boxes unless the SVG text is large, simple, and verified.
- **Use GSAP only when time-based motion is needed**: static SVG, CSS layout, and simple held states do not need GSAP. When animation is needed, keep GSAP as the timeline/orchestration layer that animates SVG groups or a small set of HTML containers. Do not build dozens of absolutely positioned HTML nodes/cards/lines when one SVG graph can carry the visual.
- **No remote runtime resources**: `index.html` must not load CDN scripts, remote fonts, remote images, or remote CSS during render. Fetch or copy required runtime files into `project/composition/assets/` during authoring, then reference them with relative paths such as `./assets/vendor/gsap.min.js`. Draft QA blocks `http://` and `https://` references.
-- **Local GSAP vendor**: if `index.html` references `./assets/vendor/gsap.min.js`, the render script prepares the built-in offline GSAP vendor in the workspace composition directory. It auto-replaces the old managed VideoStudio shim when found, keeps compatible existing GSAP files, and blocks incompatible user-provided vendor files before rendering. Do not manually patch `assets/vendor/gsap.min.js` inside a composition; fix HTML/scene-map/design-contract issues, or report the vendor blocker.
+- **Local GSAP vendor**: if `index.html` references `./assets/vendor/gsap.min.js`, the native `video_studio` draft/render path prepares the built-in offline GSAP vendor in the workspace composition directory. It keeps compatible existing GSAP files and blocks missing or incompatible vendor files before rendering. Do not manually patch `assets/vendor/gsap.min.js` inside a composition; fix HTML/scene-map/design-contract issues, or report the vendor blocker.
## Design contract before HTML
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/lib/video_render_core.cjs b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/lib/video_render_core.cjs
deleted file mode 100644
index 03299780..00000000
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/lib/video_render_core.cjs
+++ /dev/null
@@ -1,10 +0,0 @@
-var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_render_exports={};__export(video_render_exports,{HEAVY_RENDER_COST:()=>HEAVY_RENDER_COST,LOW_RAM_GB:()=>LOW_RAM_GB,classifyRenderCrash:()=>classifyRenderCrash,degradedFps:()=>degradedFps,estimateRenderCost:()=>estimateRenderCost,isConstrainedMachine:()=>isConstrainedMachine,machineRamGB:()=>machineRamGB,parseRenderDiagnostics:()=>parseRenderDiagnostics,qaComposition:()=>qaComposition,renderComposition:()=>renderComposition,renderCostDecision:()=>renderCostDecision});module.exports=__toCommonJS(video_render_exports);var fs4=__toESM(require("node:fs/promises"));var os=__toESM(require("node:os"));var path3=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var fs3=__toESM(require("node:fs"));var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function isDir(p){if(!p)return false;try{return fs2.statSync(p).isDirectory()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolvePythonExecutable(){const configured=process.env.ORKAS_BUNDLED_PYTHON||process.env.ORKAS_PYTHON;if(isFile(configured))return configured;const names=process.platform==="win32"?["python.exe",path2.join("python","python.exe")]:[path2.join("python","bin","python3"),path2.join("python","bin","python"),path2.join("bin","python3"),path2.join("bin","python")];for(const dir of runtimeVariantDirs("python")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveUvExecutable(){const configured=process.env.ORKAS_BUNDLED_UV||process.env.ORKAS_UV;if(isFile(configured))return configured;const name=process.platform==="win32"?"uv.exe":"uv";for(const dir of runtimeVariantDirs("uv")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}return void 0}function resolveNodeExecutable(){const configured=process.env.ORKAS_BUNDLED_NODE;if(isFile(configured))return configured;const names=process.platform==="win32"?["node.exe"]:[path2.join("bin","node")];for(const dir of runtimeVariantDirs("node")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function pushPathDir(out,seen,dir){if(!isDir(dir))return;const resolved=path2.resolve(dir);const key=process.platform==="win32"?resolved.toLowerCase():resolved;if(seen.has(key))return;seen.add(key);out.push(resolved)}function bundledRuntimePathEntries(){const entries=[];const seen=new Set;const python=resolvePythonExecutable();if(python){const pythonDir=path2.dirname(python);pushPathDir(entries,seen,pythonDir);pushPathDir(entries,seen,path2.join(pythonDir,"Scripts"));pushPathDir(entries,seen,path2.join(pythonDir,"bin"))}const uv=resolveUvExecutable();if(uv)pushPathDir(entries,seen,path2.dirname(uv));const node=resolveNodeExecutable();if(node)pushPathDir(entries,seen,path2.dirname(node));return entries}function bundledNodeExecutable(){return resolveNodeExecutable()}function bundledNpxCli(){const node=resolveNodeExecutable();if(!node)return void 0;const dir=path2.dirname(node);const candidates=process.platform==="win32"?[path2.join(dir,"node_modules","npm","bin","npx-cli.js")]:[path2.join(dir,"..","lib","node_modules","npm","bin","npx-cli.js")];for(const c of candidates)if(isFile(c))return c;return void 0}var HYPERFRAMES_SPEC="[email protected]";function resolveHyperframesRunner(){const node=bundledNodeExecutable();const npxCli=bundledNpxCli();if(!node||!npxCli)return null;return{node,npxCli}}function buildHyperframesEnv(){const env={...process.env};const sep2=process.platform==="win32"?";":":";const prepend=[...bundledRuntimePathEntries()];prepend.push(PYTHON_VENV_BIN_DIR);if(prepend.length)env.PATH=[...prepend,env.PATH||""].filter(Boolean).join(sep2);const ff=bundledFfmpegPaths();if(ff.ffmpeg)env.HYPERFRAMES_FFMPEG_PATH=ff.ffmpeg;if(ff.ffprobe)env.HYPERFRAMES_FFPROBE_PATH=ff.ffprobe;for(const dir of[NODE_NPM_CACHE_DIR,NODE_NPM_PREFIX_DIR,NODE_NPM_GLOBAL_BIN_DIR]){try{fs3.mkdirSync(dir,{recursive:true})}catch{}}env.NPM_CONFIG_CACHE=NODE_NPM_CACHE_DIR;env.NPM_CONFIG_PREFIX=NODE_NPM_PREFIX_DIR;env.NPM_CONFIG_FUND="false";env.NPM_CONFIG_AUDIT="false";env.NPM_CONFIG_UPDATE_NOTIFIER="false";env.NPM_CONFIG_PREFER_OFFLINE="true";env.NPM_CONFIG_FETCH_RETRIES="4";return env}var FONT_FLOOR_AT_1080=40;var PALETTE_SOFT_MAX=8;function readCanvasHeight(html,override){if(typeof override==="number"&&Number.isFinite(override)&&override>0)return override;const m=html.match(/data-height\s*=\s*["']?(\d{2,5})/i);const h=m?Number(m[1]):NaN;return Number.isFinite(h)&&h>0?h:1080}function fontFloor(height){return Math.max(1,Math.round(FONT_FLOOR_AT_1080*height/1080))}function smallFontSizesPx(html,floor){const out=new Set;const re=/font-size\s*:\s*([\d.]+)px\b/gi;let m;while((m=re.exec(html))!==null){const px=Number(m[1]);if(Number.isFinite(px)&&px>0&&px<floor)out.add(px)}return[...out].sort((a,b)=>a-b)}function expandHex(h){if(h.length===3)return h.split("").map(c=>c+c).join("");if(h.length===4)return h.slice(0,3).split("").map(c=>c+c).join("");return h.slice(0,6)}function isNeutralHex6(h){return h.slice(0,2)===h.slice(2,4)&&h.slice(2,4)===h.slice(4,6)}function isNeutralColorFn(s){if(s.includes("transparent"))return true;const rgb=s.match(/^rgba?\((\d+),(\d+),(\d+)/);if(rgb)return rgb[1]===rgb[2]&&rgb[2]===rgb[3];const hsl=s.match(/^hsla?\(\d+(?:deg)?,(\d+(?:\.\d+)?)%/);if(hsl)return Number(hsl[1])===0;return false}function chromaticColors(html){const colors=new Set;const hexRe=/#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})\b/gi;let m;while((m=hexRe.exec(html))!==null){const six=expandHex(m[1].toLowerCase());if(!isNeutralHex6(six))colors.add(`#${six}`)}const fnRe=/\b(?:rgb|rgba|hsl|hsla)\([^)]*\)/gi;while((m=fnRe.exec(html))!==null){const key=m[0].toLowerCase().replace(/\s+/g,"");if(!isNeutralColorFn(key))colors.add(key)}return colors}function lintCompositionCraft(html,opts){const findings=[];if(!html)return findings;const height=readCanvasHeight(html,opts?.canvasHeight);const floor=fontFloor(height);const small=smallFontSizesPx(html,floor);if(small.length){const shown=small.slice(0,6).map(n=>`${n}px`).join(", ");const more=small.length>6?`, +${small.length-6} more`:"";findings.push({level:"warn",code:"FONT_TOO_SMALL",message:`Font sizes below the legibility floor (~${floor}px for a ${height}px-tall canvas): ${shown}${more}. Raise body text to \u2265 the floor and titles well above it, or it won't read at phone size.`})}const colors=chromaticColors(html);if(colors.size>PALETTE_SOFT_MAX){findings.push({level:"warn",code:"PALETTE_LARGE",message:`${colors.size} distinct chromatic colors in the composition \u2014 aim for \u2264 3\u20135 on screen at once. Re-check each scene: background least-saturated, one accent that reads first.`})}return findings}function formatCraftFindings(findings,opts){if(!findings.length)return"";return[opts?.strict?"[craft] static threshold checks (FONT_TOO_SMALL blocks under --strict-craft; PALETTE_LARGE is advisory):":"[craft] static threshold checks (advisory, from the video-craft skill):",...findings.map(f=>` - ${f.code}: ${f.message}`)].join("\n")}function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var log=createLogger("video-render");var RENDER_TIMEOUT_MS=20*60*1e3;var CONSTRAINED_RENDER_TIMEOUT_MS=40*60*1e3;var CONSTRAINED_PROTOCOL_TIMEOUT_MS=15*60*1e3;var CONSTRAINED_PLAYER_READY_TIMEOUT_MS=3*60*1e3;var CONSTRAINED_BROWSER_TIMEOUT_MS=3*60*1e3;var CONSTRAINED_QA_INIT_TIMEOUT_MS=30*1e3;var LOW_RAM_GB=8;var HEAVY_RENDER_COST=3e3;function isConstrainedMachine(totalRamGB,observedGpuMode){return totalRamGB<=LOW_RAM_GB||observedGpuMode==="software"}function estimateRenderCost(width,height,durationSec,fps){const frames=Math.max(1,durationSec)*Math.max(1,fps);const megapixels=Math.max(1,width*height/1e6);return Math.round(frames*megapixels)}function renderCostDecision(opts){if(!opts.constrained||opts.costUnits<=HEAVY_RENDER_COST)return"proceed";return opts.isFinal?"fail_fast":"degrade"}function degradedFps(fps){if(fps>30)return 30;return fps}var RENDER_LOG_TAIL_CHARS=8e3;var QA_PROGRESS_HEARTBEAT_MS=15e3;function machineRamGB(){return Math.round(os.totalmem()/1024**3*10)/10}function parseRenderDiagnostics(output){const d={};const s=String(output||"");const line=s.split(/\r?\n/).find(l=>l.includes("Pipeline started")&&l.includes("{"));if(line){const start=line.indexOf("{");const end=line.lastIndexOf("}");if(start!==-1&&end>start){try{const j=JSON.parse(line.slice(start,end+1));const gm=j.browserGpuMode;if(gm==="hardware"||gm==="software")d.gpuMode=gm;if(j.requestedWorkers!=null)d.workers=String(j.requestedWorkers);const num=v=>typeof v==="number"&&Number.isFinite(v)?v:void 0;d.protocolTimeoutMs=num(j.protocolTimeoutMs)??num(j.protocolTimeout);d.playerReadyTimeoutMs=num(j.playerReadyTimeoutMs)??num(j.playerReadyTimeout);d.browserTimeoutMs=num(j.browserTimeoutMs)??num(j.browserTimeout)}catch{}}}if(!d.gpuMode){const m=s.match(/browserGpuMode\s*(?:auto\s*(?:→|->)\s*)?["']?(hardware|software)["']?/i);if(m)d.gpuMode=m[1].toLowerCase()}return d}function classifyRenderCrash(stderr,code,timedOut){if(timedOut)return"timeout";const s=String(stderr||"");if(/NewIsolate|SnapshotData|MultiIsolatePlatform|v8::internal|Segmentation fault|SIGSEGV|SIGABRT|Fatal error/i.test(s)&&code!==0)return"native_worker_crash";return null}async function writeRenderLog(logPath,combined){if(!logPath)return null;try{await fs4.mkdir(path3.dirname(logPath),{recursive:true}).catch(()=>{});await fs4.writeFile(logPath,combined,"utf8");return logPath}catch{return null}}function diagnosticsSummary(d){const parts=[];if(d.gpuMode)parts.push(`gpu=${d.gpuMode}`);if(typeof d.totalRamGB==="number")parts.push(`ram=${d.totalRamGB}GB`);if(d.workers)parts.push(`workers=${d.workers}`);if(d.crashSignature)parts.push(`crash=${d.crashSignature}`);return parts.join(" ")}function buildRenderArgs(p){const args=["render","--output",p.outputAbsPath];if(p.quality)args.push("--quality",p.quality);if(typeof p.fps==="number")args.push("--fps",String(p.fps));if(p.format)args.push("--format",p.format);if(p.constrained){args.push("--low-memory-mode","--workers","1","--protocol-timeout",String(CONSTRAINED_PROTOCOL_TIMEOUT_MS),"--player-ready-timeout",String(CONSTRAINED_PLAYER_READY_TIMEOUT_MS),"--browser-timeout",String(CONSTRAINED_BROWSER_TIMEOUT_MS))}if(p.variables&&Object.keys(p.variables).length){args.push("--variables",JSON.stringify(p.variables))}return args}function parseTraceLine(line){const idx=line.indexOf("[Render:trace]");if(idx===-1)return null;const jsonStart=line.indexOf("{",idx);if(jsonStart===-1)return null;try{const trace=JSON.parse(line.slice(jsonStart));const phase=typeof trace.phase==="string"?trace.phase:"render";const status=typeof trace.status==="string"?trace.status:"";return{phase:`render.${phase}`,message:status?`${phase} ${status}`:phase}}catch{return null}}async function renderComposition(p){const runner=resolveHyperframesRunner();if(!runner){return{ok:false,errorCode:"E_RENDER_RUNTIME_MISSING",message:"Bundled Node runtime not found; cannot run the HyperFrames renderer."}}const indexHtml=path3.join(p.projectDirAbs,"index.html");try{const st=await fs4.stat(indexHtml);if(!st.isFile())throw new Error("not a file")}catch{return{ok:false,errorCode:"E_RENDER_NO_COMPOSITION",message:`No index.html found in composition dir: ${p.projectDirAbs}`}}await fs4.mkdir(path3.dirname(p.outputAbsPath),{recursive:true}).catch(()=>{});const env=buildHyperframesEnv();const args=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,...buildRenderArgs(p)];return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,args,{cwd:p.projectDirAbs,env,...p.signal?{signal:p.signal}:{}})}catch(err){resolve3({ok:false,errorCode:"E_RENDER_SPAWN",message:err.message});return}const errChunks=[];const outChunks=[];let stdoutBuf="";let settled=false;let timedOut=false;const renderTimeoutMs=p.constrained?CONSTRAINED_RENDER_TIMEOUT_MS:RENDER_TIMEOUT_MS;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},renderTimeoutMs);const pumpProgress=chunk=>{stdoutBuf+=chunk;let nl;while((nl=stdoutBuf.indexOf("\n"))!==-1){const line=stdoutBuf.slice(0,nl);stdoutBuf=stdoutBuf.slice(nl+1);const ev=parseTraceLine(line);if(ev)p.onProgress?.(ev)}};child.stdout?.on("data",c=>{const s=c.toString("utf8");outChunks.push(s);pumpProgress(s)});child.stderr?.on("data",c=>{const s=c.toString("utf8");errChunks.push(s);pumpProgress(s)});child.stdin?.end();const finish=r=>{if(settled)return;settled=true;clearTimeout(timer);resolve3(r)};child.on("error",err=>{if(p.signal?.aborted){finish({ok:false,errorCode:"E_RENDER_ABORTED",message:"Render aborted."});return}finish({ok:false,errorCode:"E_RENDER_SPAWN",message:err.message})});child.on("close",async code=>{const stdout=outChunks.join("");const stderr=errChunks.join("").trim();const combined=stdout+(stderr?`
---- stderr ---
-${stderr}`:"");const diagnostics={...parseRenderDiagnostics(combined),totalRamGB:machineRamGB(),crashSignature:classifyRenderCrash(stderr,code,timedOut)};const logPath=await writeRenderLog(p.logPath,combined)??void 0;const withDiag=r=>({...r,diagnostics,...logPath?{logPath}:{}});const summary=diagnosticsSummary(diagnostics);if(timedOut){finish(withDiag({ok:false,errorCode:"E_RENDER_TIMEOUT",message:`Render timed out after ${renderTimeoutMs}ms.${summary?` [${summary}]`:""}`}));return}if(p.signal?.aborted){finish(withDiag({ok:false,errorCode:"E_RENDER_ABORTED",message:"Render aborted."}));return}if(code!==0){const tail=stderr.slice(-RENDER_LOG_TAIL_CHARS);log.warn(`hyperframes render exited ${code}: ${redactPaths(tail.slice(-300))}${summary?` [${summary}]`:""}`);return finish(withDiag({ok:false,errorCode:"E_RENDER_FAILED",message:`HyperFrames render failed (exit ${code}).${summary?` [${summary}]`:""}${logPath?` Full log: ${logPath}.`:""} ${tail||"No diagnostic output."}`}))}const st=await fs4.stat(p.outputAbsPath).catch(()=>null);if(!st||!st.isFile()||st.size===0){return finish(withDiag({ok:false,errorCode:"E_RENDER_NO_OUTPUT",message:`Render reported success but no output file was produced at ${p.outputAbsPath}.`}))}finish(withDiag({ok:true,path:p.outputAbsPath,bytes:st.size}))})})}var QA_TIMEOUT_MS=5*60*1e3;function withStrictCraftFindings(findings,craftFindings){const blockingFindings=craftFindings.filter(f=>f.code==="FONT_TOO_SMALL");if(!blockingFindings.length)return findings;try{const parsed=JSON.parse(findings);const existingIssues=Array.isArray(parsed.issues)?parsed.issues:[];const craftIssues=blockingFindings.map(f=>({code:f.code,severity:"error",selector:"document",message:f.message,fixHint:"Raise all readable text to the video-craft legibility floor before rendering.",source:"video-craft"}));const add=craftIssues.length;const numberField=key=>typeof parsed[key]==="number"?parsed[key]:0;parsed.ok=false;parsed.errorCount=numberField("errorCount")+add;parsed.issueCount=numberField("issueCount")+add;parsed.totalIssueCount=numberField("totalIssueCount")+add;parsed.issues=[...existingIssues,...craftIssues];return JSON.stringify(parsed,null,2)}catch{return`${findings}
-
-[craft] BLOCKING strict checks:
-${blockingFindings.map(f=>` - ${f.code}: ${f.message}`).join("\n")}`}}async function qaComposition(op,p){const runner=resolveHyperframesRunner();if(!runner){return{ok:false,errorCode:"E_RENDER_RUNTIME_MISSING",message:"Bundled Node runtime not found."}}const indexHtml=path3.join(p.projectDirAbs,"index.html");const st=await fs4.stat(indexHtml).catch(()=>null);if(!st||!st.isFile()){return{ok:false,errorCode:"E_RENDER_NO_COMPOSITION",message:`No index.html in: ${p.projectDirAbs}`}}const env=buildHyperframesEnv();const args=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,op,"--json"];if(p.constrained)args.push("--timeout",String(CONSTRAINED_QA_INIT_TIMEOUT_MS));return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,args,{cwd:p.projectDirAbs,env,...p.signal?{signal:p.signal}:{}})}catch(err){resolve3({ok:false,errorCode:"E_QA_SPAWN",message:err.message});return}const out=[];const errOut=[];let settled=false;let timedOut=false;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},QA_TIMEOUT_MS);const startedAtMs=Date.now();const heartbeat=p.onProgress?setInterval(()=>p.onProgress?.({phase:`qa.${op}`,message:`${op} running (${Math.round((Date.now()-startedAtMs)/1e3)}s elapsed)`}),QA_PROGRESS_HEARTBEAT_MS):null;heartbeat?.unref?.();let traceBuf="";const pumpTrace=chunk=>{if(!p.onProgress)return;traceBuf+=chunk;let nl;while((nl=traceBuf.indexOf("\n"))!==-1){const line=traceBuf.slice(0,nl);traceBuf=traceBuf.slice(nl+1);const ev=parseTraceLine(line);if(ev)p.onProgress?.(ev)}};child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>{const s=c.toString("utf8");errOut.push(s);pumpTrace(s)});child.stdin?.end();const finish=r=>{if(settled)return;settled=true;clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);resolve3(r)};child.on("error",err=>{if(p.signal?.aborted)return finish({ok:false,errorCode:"E_QA_ABORTED",message:`${op} aborted.`});finish({ok:false,errorCode:"E_QA_SPAWN",message:err.message})});child.on("close",async code=>{if(timedOut)return finish({ok:false,errorCode:"E_QA_TIMEOUT",message:`${op} timed out.`});if(p.signal?.aborted)return finish({ok:false,errorCode:"E_QA_ABORTED",message:`${op} aborted.`});const findings=out.join("").trim();if(!findings){const stderrFull=errOut.join("").trim();const combined=out.join("")+(stderrFull?`
---- stderr ---
-${stderrFull}`:"");const diagnostics={...parseRenderDiagnostics(combined),totalRamGB:machineRamGB(),crashSignature:classifyRenderCrash(stderrFull,code,false)};const logPath=await writeRenderLog(p.logPath,combined)??void 0;const summary=diagnosticsSummary(diagnostics);return finish({ok:false,errorCode:"E_QA_NO_OUTPUT",message:`${op} produced no findings.${summary?` [${summary}]`:""}${logPath?` Full log: ${logPath}.`:""} ${stderrFull.slice(-RENDER_LOG_TAIL_CHARS)||"No diagnostic output."}`,diagnostics,...logPath?{logPath}:{}})}let craft="";let finalFindings=findings;try{const html=await fs4.readFile(indexHtml,"utf8");const craftFindings=lintCompositionCraft(html);if(p.strictCraft)finalFindings=withStrictCraftFindings(findings,craftFindings);craft=formatCraftFindings(craftFindings,{strict:!!p.strictCraft})}catch{}finish({ok:true,op,findings:craft?`${finalFindings}
-
-${craft}`:finalFindings})})})}0&&(module.exports={HEAVY_RENDER_COST,LOW_RAM_GB,classifyRenderCrash,degradedFps,estimateRenderCost,isConstrainedMachine,machineRamGB,parseRenderDiagnostics,qaComposition,renderComposition,renderCostDecision});
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/render_composition.js b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/render_composition.js
deleted file mode 100644
index 8278c7d9..00000000
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/render_composition.js
+++ /dev/null
@@ -1,2023 +0,0 @@
-'use strict';
-
-const fs = require('node:fs');
-const path = require('node:path');
-const childProcess = require('node:child_process');
-const crypto = require('node:crypto');
-
-const OPS = new Set(['draft', 'render', 'lint', 'inspect']);
-const QUALITY = new Set(['draft', 'standard', 'high']);
-const FORMAT = new Set(['mp4', 'webm']);
-const FINDINGS_INLINE = new Set(['full', 'summary', 'none']);
-const LOCAL_GSAP_VENDOR_REF = 'assets/vendor/gsap.min.js';
-const REQUIRED_GSAP_TIMELINE_APIS = ['timeScale', 'totalTime', 'totalDuration', 'getChildren'];
-const DRAFT_REPAIR_MAX_PASSES = 2;
-const DRAFT_VISUAL_ADVISORY_CODES = new Set([
- 'FONT_TOO_SMALL',
- 'PALETTE_LARGE',
- 'LOW_CONTRAST',
- 'TEXT_BOX_OVERFLOW',
- 'TEXT_OCCLUDED',
- 'TEXT_OVERFLOW',
- 'TEXT_CLIPPED',
- 'CONTENT_OVERLAP',
- 'CONTENT_OCCLUDED',
- 'CONTENT_OVERFLOW',
- 'CONTENT_CLIPPED',
- 'SAFE_AREA_VIOLATION',
-]);
-
-function fail(code, message, extra = {}) {
- process.stderr.write(JSON.stringify({ ok: false, code, message, ...extra }) + '\n');
- process.exit(1);
-}
-
-// Best-effort progress JSONL on stderr (same protocol as video_edit); the
-// direct-CLI runner forwards these lines to the user-facing tool progress.
-// Throttled so a long render cannot flood the runner's output buffer.
-const PROGRESS_EMIT_MIN_MS = 2000;
-let lastProgressEmitMs = 0;
-function makeProgressEmitter(op) {
- return (event) => {
- const now = Date.now();
- if (now - lastProgressEmitMs < PROGRESS_EMIT_MIN_MS) return;
- lastProgressEmitMs = now;
- const payload = {
- type: 'progress',
- source: 'render_composition',
- op,
- phase: (event && event.phase) ? event.phase : op,
- ...((event && event.message) ? { message: event.message } : {}),
- };
- try {
- process.stderr.write(JSON.stringify(payload) + '\n');
- } catch {
- // Progress must never break the render.
- }
- };
-}
-
-// Absolute path for a per-op HyperFrames diagnostic log under project/render/.
-// The backend writes the full stdout+stderr there so a failed/slow render
-// (browserGpuMode, RAM, worker crash, timeout) is diagnosable. Overwritten
-// each run — the latest is what you want when chasing a failure.
-function renderLogPath(compositionDirAbs, name) {
- return path.join(path.resolve(compositionDirAbs, '..', 'render'), `${name}-hyperframes.log`);
-}
-
-function help() {
- return {
- ok: true,
- script: 'render_composition',
- ops: [...OPS],
- usage: 'stage-compose render_composition -- --op <draft|inspect|lint|render> --composition-dir <dir> [--strict-craft] [--findings-output <json>] [--findings-inline <full|summary|none>] [--output <video>] [--report <json>]. draft renders hand-authored index.html; spec compilation is not supported.',
- };
-}
-
-function nextValue(args, i, name) {
- if (i + 1 >= args.length) fail('E_ARGS', `${name} requires a value`);
- return args[i + 1];
-}
-
-function parseNumber(raw, label) {
- const n = Number(raw);
- if (!Number.isFinite(n)) fail('E_ARGS', `${label} must be a number`);
- return n;
-}
-
-function parseJson(raw, label) {
- const text = String(raw || '').trim();
- if (!text) return undefined;
- try {
- return JSON.parse(text);
- } catch (err) {
- fail('E_ARGS', `${label} is not valid JSON: ${err.message}`);
- }
-}
-
-function parseArgs(args) {
- const out = {
- op: 'render',
- compositionDir: '',
- outputPath: '',
- specPath: '',
- reportPath: '',
- help: false,
- strictCraft: false,
- normalizeAudio: true,
- videoQa: true,
- findingsOutputPath: '',
- findingsInline: '',
- };
- for (let i = 0; i < args.length; i += 1) {
- const a = args[i];
- if (a === '--help' || a === '-h') out.help = true;
- else if (a === '--strict-craft') out.strictCraft = true;
- else if (a === '--normalize-audio') out.normalizeAudio = true;
- else if (a === '--skip-normalize-audio' || a === '--no-normalize-audio') out.normalizeAudio = false;
- else if (a === '--skip-video-qa' || a === '--no-video-qa') out.videoQa = false;
- else if (a === '--op' || a === '-o') { out.op = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--op=')) out.op = a.slice('--op='.length);
- else if (a === '--composition-dir' || a === '--dir' || a === '-d') { out.compositionDir = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--composition-dir=')) out.compositionDir = a.slice('--composition-dir='.length);
- else if (a.startsWith('--dir=')) out.compositionDir = a.slice('--dir='.length);
- else if (a === '--output' || a === '--output-path') { out.outputPath = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--output=')) out.outputPath = a.slice('--output='.length);
- else if (a.startsWith('--output-path=')) out.outputPath = a.slice('--output-path='.length);
- else if (a === '--report' || a === '--report-path') { out.reportPath = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--report=')) out.reportPath = a.slice('--report='.length);
- else if (a.startsWith('--report-path=')) out.reportPath = a.slice('--report-path='.length);
- else if (a === '--spec' || a === '--spec-path') { out.specPath = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--spec=')) out.specPath = a.slice('--spec='.length);
- else if (a.startsWith('--spec-path=')) out.specPath = a.slice('--spec-path='.length);
- else if (a === '--findings-output') { out.findingsOutputPath = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--findings-output=')) out.findingsOutputPath = a.slice('--findings-output='.length);
- else if (a === '--findings-inline') { out.findingsInline = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--findings-inline=')) out.findingsInline = a.slice('--findings-inline='.length);
- else if (a === '--quality') { out.quality = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--quality=')) out.quality = a.slice('--quality='.length);
- else if (a === '--format') { out.format = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--format=')) out.format = a.slice('--format='.length);
- else if (a === '--fps') { out.fps = parseNumber(nextValue(args, i, a), a); i += 1; }
- else if (a.startsWith('--fps=')) out.fps = parseNumber(a.slice('--fps='.length), '--fps');
- else if (a === '--variables') { out.variables = parseJson(nextValue(args, i, a), a); i += 1; }
- else if (a.startsWith('--variables=')) out.variables = parseJson(a.slice('--variables='.length), '--variables');
- else if (!out.compositionDir) out.compositionDir = a;
- else if (!out.outputPath) out.outputPath = a;
- else fail('E_ARGS', `unexpected argument: ${a}`);
- }
- return out;
-}
-
-function resolveDir(raw) {
- const abs = path.resolve(process.cwd(), String(raw || '').trim());
- const st = fs.existsSync(abs) ? fs.statSync(abs) : null;
- if (!st || !st.isDirectory()) fail('E_INPUT', `composition_dir is not a directory: ${abs}`, { path: abs });
- return abs;
-}
-
-function resolveOrCreateDir(raw) {
- const abs = path.resolve(process.cwd(), String(raw || '').trim());
- fs.mkdirSync(abs, { recursive: true });
- const st = fs.existsSync(abs) ? fs.statSync(abs) : null;
- if (!st || !st.isDirectory()) fail('E_INPUT', `composition_dir is not a directory: ${abs}`, { path: abs });
- return abs;
-}
-
-function resolveOutputPath(raw) {
- return path.resolve(process.cwd(), String(raw || '').trim());
-}
-
-function parseLeadingJson(text) {
- const raw = String(text || '').trim();
- if (!raw.startsWith('{')) return null;
- const craftIndex = raw.indexOf('\n\n[craft]');
- const jsonText = craftIndex >= 0 ? raw.slice(0, craftIndex).trim() : raw;
- try {
- return JSON.parse(jsonText);
- } catch {
- return null;
- }
-}
-
-function shortText(value, max = 220) {
- const s = String(value || '').replace(/\s+/g, ' ').trim();
- return s.length > max ? `${s.slice(0, max - 1)}…` : s;
-}
-
-function summarizeFindings(findings) {
- const parsed = parseLeadingJson(findings);
- const issues = parsed && Array.isArray(parsed.issues)
- ? parsed.issues
- : (parsed && Array.isArray(parsed.findings) ? parsed.findings : []);
- const codeCounts = new Map();
- for (const issue of issues) {
- const code = shortText(issue && issue.code ? issue.code : 'ISSUE', 80);
- const severity = shortText(issue && issue.severity ? issue.severity : '', 40);
- const key = `${severity}\u0000${code}`;
- const prev = codeCounts.get(key) || { code, severity, count: 0 };
- prev.count += 1;
- codeCounts.set(key, prev);
- }
- const topIssues = issues.slice(0, 8).map((issue) => ({
- code: shortText(issue && issue.code ? issue.code : 'ISSUE', 80),
- severity: shortText(issue && issue.severity ? issue.severity : '', 40),
- selector: shortText(issue && issue.selector ? issue.selector : '', 120),
- message: shortText(issue && issue.message ? issue.message : issue, 260),
- }));
- const craftLines = String(findings || '')
- .split('\n')
- .map((line) => line.trim())
- .filter((line) => line.startsWith('- ') || line.startsWith(' - '))
- .slice(0, 8)
- .map((line) => shortText(line.replace(/^\s*-\s*/, ''), 260));
- return {
- parseable: !!parsed,
- ok: parsed && typeof parsed.ok === 'boolean' ? parsed.ok : undefined,
- errorCount: parsed && typeof parsed.errorCount === 'number' ? parsed.errorCount : undefined,
- warningCount: parsed && typeof parsed.warningCount === 'number' ? parsed.warningCount : undefined,
- issueCount: parsed && typeof parsed.issueCount === 'number' ? parsed.issueCount : issues.length,
- totalIssueCount: parsed && typeof parsed.totalIssueCount === 'number' ? parsed.totalIssueCount : issues.length,
- issueCodes: [...codeCounts.values()].sort((a, b) => b.count - a.count || a.code.localeCompare(b.code)),
- topIssues,
- craft: craftLines,
- rawChars: String(findings || '').length,
- };
-}
-
-function findingsIssues(findings) {
- const parsed = parseLeadingJson(findings);
- if (parsed && Array.isArray(parsed.issues)) return parsed.issues;
- if (parsed && Array.isArray(parsed.findings)) return parsed.findings;
- return [];
-}
-
-function isDraftVisualAdvisory(issue) {
- const rawCode = issue && issue.code ? String(issue.code) : '';
- const code = rawCode.toUpperCase();
- const lower = rawCode.toLowerCase();
- return DRAFT_VISUAL_ADVISORY_CODES.has(code)
- || lower.includes('overflow')
- || lower.includes('overlap')
- || lower.includes('occlud')
- || lower.includes('clipp')
- || lower.includes('contrast')
- || lower.includes('font')
- || lower.includes('safe_area');
-}
-
-function summarizeDraftInspectDisposition(findings) {
- const issues = findingsIssues(findings);
- const blocking = [];
- const advisory = [];
- for (const issue of issues) {
- const severity = String(issue && issue.severity ? issue.severity : '').toLowerCase();
- if (severity === 'error' && !isDraftVisualAdvisory(issue)) blocking.push(issue);
- else advisory.push(issue);
- }
- return {
- blocking_error_count: blocking.length,
- advisory_count: advisory.length,
- blocking_codes: [...new Set(blocking.map((issue) => shortText(issue && issue.code ? issue.code : 'ISSUE', 80)))],
- advisory_codes: [...new Set(advisory.map((issue) => shortText(issue && issue.code ? issue.code : 'ISSUE', 80)))],
- blocking_issues: blocking.slice(0, 8).map((issue) => ({
- code: shortText(issue && issue.code ? issue.code : 'ISSUE', 80),
- severity: shortText(issue && issue.severity ? issue.severity : '', 40),
- selector: shortText(issue && issue.selector ? issue.selector : '', 120),
- message: shortText(issue && issue.message ? issue.message : issue, 260),
- })),
- advisory_issues: advisory.slice(0, 8).map((issue) => ({
- code: shortText(issue && issue.code ? issue.code : 'ISSUE', 80),
- severity: shortText(issue && issue.severity ? issue.severity : '', 40),
- selector: shortText(issue && issue.selector ? issue.selector : '', 120),
- message: shortText(issue && issue.message ? issue.message : issue, 260),
- })),
- };
-}
-
-function writeFindingsOutput(rawPath, payload) {
- const abs = resolveOutputPath(rawPath);
- fs.mkdirSync(path.dirname(abs), { recursive: true });
- fs.writeFileSync(abs, JSON.stringify(payload, null, 2), 'utf8');
- return abs;
-}
-
-function withFormatExtension(rawAbs, format) {
- return path.extname(rawAbs) ? rawAbs : `${rawAbs}.${format}`;
-}
-
-function uniquifyOutputPath(requested) {
- if (!fs.existsSync(requested)) return { finalPath: requested, renamed: false };
-
- const { dir, name, ext } = path.parse(requested);
- for (let n = 2; n < 10000; n += 1) {
- const candidate = path.join(dir, `${name}-${n}${ext}`);
- if (!fs.existsSync(candidate)) return { finalPath: candidate, renamed: true };
- }
- fail('E_OUTPUT', `could not find a non-conflicting output path under ${dir}`, { path: requested });
-}
-
-async function outputFile(raw, format) {
- if (!raw) fail('E_ARGS', '--output is required for op=render or op=draft');
- const requested = withFormatExtension(path.resolve(process.cwd(), String(raw).trim()), format);
- const { finalPath, renamed } = uniquifyOutputPath(requested);
- return { requested, finalPath, renamed };
-}
-
-function parseFps(raw) {
- const s = String(raw || '').trim();
- if (!s) return 30;
- const [a, b] = s.split('/').map(Number);
- if (Number.isFinite(a) && Number.isFinite(b) && b > 0) return a / b;
- const n = Number(s);
- return Number.isFinite(n) && n > 0 ? n : 30;
-}
-
-function runProcess(command, args, opts = {}) {
- const res = childProcess.spawnSync(command, args, {
- cwd: opts.cwd || process.cwd(),
- env: opts.env || process.env,
- encoding: opts.encoding === 'buffer' ? undefined : 'utf8',
- maxBuffer: opts.maxBuffer || 20 * 1024 * 1024,
- });
- if (res.error) throw res.error;
- if (res.status !== 0) {
- const stderr = Buffer.isBuffer(res.stderr) ? res.stderr.toString('utf8') : String(res.stderr || '');
- const stdout = Buffer.isBuffer(res.stdout) ? res.stdout.toString('utf8') : String(res.stdout || '');
- throw new Error(`${command} exited ${res.status}: ${(stderr || stdout).trim().slice(-1800)}`);
- }
- return res;
-}
-
-function toolEnvName(kind) {
- return kind === 'ffmpeg' ? 'ORKAS_BUNDLED_FFMPEG' : 'ORKAS_BUNDLED_FFPROBE';
-}
-
-function resolveMediaTool(kind) {
- const direct = process.env[toolEnvName(kind)] || process.env[`HYPERFRAMES_${kind.toUpperCase()}_PATH`];
- const candidates = [direct, kind].filter(Boolean);
- for (const candidate of candidates) {
- try {
- const res = childProcess.spawnSync(candidate, ['-version'], { stdio: 'ignore' });
- if (res.status === 0) return candidate;
- } catch {
- // Try the next candidate.
- }
- }
- fail('E_MEDIA_TOOL_MISSING', `${kind} was not found in the bundled runtime or PATH`);
-}
-
-function probeMedia(mediaPath) {
- const ffprobe = resolveMediaTool('ffprobe');
- const res = runProcess(ffprobe, [
- '-v', 'error',
- '-show_entries', 'format=duration,size,bit_rate:stream=index,codec_type,codec_name,width,height,r_frame_rate,bit_rate',
- '-of', 'json',
- mediaPath,
- ]);
- const parsed = JSON.parse(String(res.stdout || '{}'));
- const streams = Array.isArray(parsed.streams) ? parsed.streams : [];
- const video = streams.find((s) => s.codec_type === 'video') || {};
- const audio = streams.find((s) => s.codec_type === 'audio') || null;
- return {
- duration_seconds: Number(parsed.format && parsed.format.duration) || 0,
- size_bytes: Number(parsed.format && parsed.format.size) || 0,
- bit_rate: Number(parsed.format && parsed.format.bit_rate) || 0,
- video: {
- codec: video.codec_name || '',
- width: Number(video.width) || 0,
- height: Number(video.height) || 0,
- fps: parseFps(video.r_frame_rate),
- bit_rate: Number(video.bit_rate) || 0,
- },
- audio: audio ? {
- codec: audio.codec_name || '',
- bit_rate: Number(audio.bit_rate) || 0,
- } : null,
- };
-}
-
-function parseLastJsonObject(text) {
- const raw = String(text || '');
- const end = raw.lastIndexOf('}');
- if (end < 0) return null;
- const start = raw.lastIndexOf('{', end);
- if (start < 0) return null;
- try {
- return JSON.parse(raw.slice(start, end + 1));
- } catch {
- return null;
- }
-}
-
-function analyzeLoudness(mediaPath) {
- const ffmpeg = resolveMediaTool('ffmpeg');
- const res = runProcess(ffmpeg, [
- '-hide_banner',
- '-nostats',
- '-i', mediaPath,
- '-af', 'loudnorm=I=-14:TP=-1:LRA=11:print_format=json',
- '-f', 'null',
- '-',
- ]);
- const text = `${res.stdout || ''}\n${res.stderr || ''}`;
- return parseLastJsonObject(text) || { raw_tail: shortText(text.slice(-1000), 1000) };
-}
-
-function normalizeAudioInPlace(mediaPath) {
- const ffmpeg = resolveMediaTool('ffmpeg');
- const ext = path.extname(mediaPath) || '.mp4';
- if (ext.toLowerCase() !== '.mp4') {
- return { skipped: true, reason: 'audio normalization is currently only applied to mp4 output' };
- }
- const tmp = path.join(path.dirname(mediaPath), `${path.basename(mediaPath, ext)}.norm-${Date.now()}${ext}`);
- runProcess(ffmpeg, [
- '-y',
- '-hide_banner',
- '-loglevel', 'error',
- '-i', mediaPath,
- '-af', 'loudnorm=I=-14:TP=-1:LRA=11',
- '-c:v', 'copy',
- '-c:a', 'aac',
- '-b:a', '192k',
- tmp,
- ]);
- fs.renameSync(tmp, mediaPath);
- return { skipped: false, path: mediaPath };
-}
-
-function loadTimelineMap(compositionDirAbs) {
- const candidates = [
- path.join(compositionDirAbs, 'scene-map.json'),
- path.join(compositionDirAbs, 'timeline.json'),
- ];
- for (const timelinePath of candidates) {
- if (!fs.existsSync(timelinePath)) continue;
- const loaded = readJsonFile(timelinePath);
- if (loaded.error) return { path: timelinePath, map: null, error: loaded.error };
- const timeline = Array.isArray(loaded.value) ? { scenes: loaded.value } : loaded.value;
- return { path: timelinePath, map: timeline && typeof timeline === 'object' ? timeline : null };
- }
- return { path: '', map: null };
-}
-
-// The contract's audio section can promise narration; if TTS failed (or was
-// skipped) the composition renders silent and every other QA still passes.
-// Make that gap visible instead of shipping a silent draft unnoticed.
-function compositionHasAudio(html, compositionDirAbs) {
- if (/<audio\b/i.test(String(html || ''))) return true;
- return [
- path.join(compositionDirAbs, 'assets', 'narration.mp3'),
- path.join(compositionDirAbs, 'assets', 'narration.wav'),
- path.join(compositionDirAbs, 'narration.mp3'),
- path.join(compositionDirAbs, 'narration.wav'),
- ].some((file) => fs.existsSync(file));
-}
-
-function contractDeclaresNarrationAudio(contract) {
- const audio = contract && typeof contract === 'object' ? contract.audio : null;
- if (!audio || typeof audio !== 'object') return false;
- const text = JSON.stringify(audio).toLowerCase();
- if (/render[_-]?silent|"silent"\s*:\s*true|assemble/.test(text)) return false;
- return /\.(mp3|wav|m4a|aac|ogg)\b/.test(text);
-}
-
-function htmlNeedsSceneMap(compositionDirAbs) {
- const htmlPath = path.join(compositionDirAbs, 'index.html');
- let html = '';
- try {
- html = fs.readFileSync(htmlPath, 'utf8');
- } catch {
- return false;
- }
- return compositionHasAudio(html, compositionDirAbs);
-}
-
-function readJsonFile(jsonPath) {
- try {
- return { path: jsonPath, value: JSON.parse(fs.readFileSync(jsonPath, 'utf8')) };
- } catch (err) {
- return { path: jsonPath, value: null, error: err && err.message ? err.message : String(err) };
- }
-}
-
-function loadDesignContract(compositionDirAbs) {
- const contractPath = path.join(compositionDirAbs, 'design-contract.json');
- if (!fs.existsSync(contractPath)) return { path: contractPath, exists: false, contract: null };
- const loaded = readJsonFile(contractPath);
- return {
- path: contractPath,
- exists: true,
- contract: loaded.value && typeof loaded.value === 'object' ? loaded.value : null,
- error: loaded.error || '',
- };
-}
-
-function numberOrZero(value) {
- const n = Number(value);
- return Number.isFinite(n) ? n : 0;
-}
-
-function normalizeForSearch(value) {
- return String(value || '')
- .normalize('NFKC')
- .toLowerCase()
- .replace(/&[a-z0-9#]+;/gi, ' ')
- .replace(/[^\p{L}\p{N}]+/gu, '');
-}
-
-function flattenStringValues(value, out = [], depth = 0) {
- if (depth > 6 || value === null || value === undefined) return out;
- if (typeof value === 'string') {
- const s = value.trim();
- if (s) out.push(s);
- } else if (Array.isArray(value)) {
- for (const item of value) flattenStringValues(item, out, depth + 1);
- } else if (typeof value === 'object') {
- for (const item of Object.values(value)) flattenStringValues(item, out, depth + 1);
- }
- return out;
-}
-
-function sceneDisplayTexts(scene) {
- if (!scene || typeof scene !== 'object') return [];
- const fields = [
- 'headline',
- 'title',
- 'subtitle',
- 'kicker',
- 'label',
- 'metric',
- 'value',
- 'cta',
- 'copy',
- 'on_screen_copy',
- 'onscreen_copy',
- 'onscreen_text',
- 'display_text',
- 'text',
- ];
- const out = [];
- for (const field of fields) {
- if (scene[field] !== undefined) flattenStringValues(scene[field], out);
- }
- return [...new Set(out.map((s) => s.replace(/\s+/g, ' ').trim()).filter((s) => s.length >= 3 && s.length <= 140))];
-}
-
-function htmlAttr(tag, name) {
- const re = new RegExp(`${name}\\s*=\\s*["']?([^"'\\s>]+)`, 'i');
- const match = String(tag || '').match(re);
- return match ? match[1] : '';
-}
-
-function htmlDataNumber(tag, name) {
- const raw = htmlAttr(tag, `data-${name}`);
- const n = Number(raw);
- return Number.isFinite(n) ? n : 0;
-}
-
-function rootCompositionTag(html) {
- const match = String(html || '').match(/<[^>]+\bdata-composition-id\s*=\s*["'][^"']+["'][^>]*>/i);
- return match ? match[0] : '';
-}
-
-function extractRemoteRefs(html) {
- const refs = [];
- const add = (kind, value) => {
- const ref = String(value || '').trim();
- if (/^https?:\/\//i.test(ref)) refs.push({ kind, ref: shortText(ref, 180) });
- };
- let match;
- const attrRe = /\b(src|href|poster)\s*=\s*["']([^"']+)["']/gi;
- while ((match = attrRe.exec(html)) !== null) add(match[1].toLowerCase(), match[2]);
- const urlRe = /\burl\(\s*["']?(https?:\/\/[^"')\s]+)["']?\s*\)/gi;
- while ((match = urlRe.exec(html)) !== null) add('css-url', match[1]);
- const importRe = /@import\s+(?:url\(\s*)?["']?(https?:\/\/[^"')\s;]+)["']?/gi;
- while ((match = importRe.exec(html)) !== null) add('css-import', match[1]);
- return refs;
-}
-
-function stripRefSuffix(ref) {
- return String(ref || '').trim().split(/[?#]/)[0];
-}
-
-function isIgnoredLocalRef(ref) {
- const raw = String(ref || '').trim();
- return !raw
- || raw.startsWith('#')
- || raw.startsWith('data:')
- || raw.startsWith('blob:')
- || raw.startsWith('mailto:')
- || raw.startsWith('tel:')
- || raw.startsWith('javascript:')
- || /^https?:\/\//i.test(raw);
-}
-
-function extractLocalRefs(html) {
- const refs = [];
- const add = (kind, value) => {
- const raw = String(value || '').trim();
- if (!isIgnoredLocalRef(raw)) refs.push({ kind, ref: stripRefSuffix(raw) });
- };
- let match;
- const attrRe = /\b(src|href|poster)\s*=\s*["']([^"']+)["']/gi;
- while ((match = attrRe.exec(html)) !== null) add(match[1].toLowerCase(), match[2]);
- const urlRe = /\burl\(\s*["']?([^"')]+)["']?\s*\)/gi;
- while ((match = urlRe.exec(html)) !== null) add('css-url', match[1]);
- return refs;
-}
-
-function normalizeRefPath(ref) {
- return stripRefSuffix(ref).replace(/^\.\/+/, '').replace(/\\/g, '/');
-}
-
-function extractScriptSrcs(html) {
- const out = [];
- let match;
- const scriptRe = /<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;
- while ((match = scriptRe.exec(String(html || ''))) !== null) out.push(match[1]);
- return out;
-}
-
-function htmlUsesGsap(html) {
- return /\bgsap\s*\./.test(String(html || ''));
-}
-
-function hasLocalGsapVendorScript(html) {
- return extractScriptSrcs(html).some((src) => normalizeRefPath(src) === LOCAL_GSAP_VENDOR_REF);
-}
-
-function managedLegacyGsapVendor(text) {
- const s = String(text || '');
- return s.includes('Local HyperFrames timeline vendor')
- || s.includes('Provides the small GSAP-compatible surface VideoStudio compositions need');
-}
-
-function gsapVendorCompatibilityIssue(text) {
- const s = String(text || '');
- if (!s.trim()) return { code: 'VENDOR_GSAP_EMPTY', missing: REQUIRED_GSAP_TIMELINE_APIS };
- const missing = REQUIRED_GSAP_TIMELINE_APIS.filter((api) => !s.includes(api));
- return missing.length ? { code: 'VENDOR_GSAP_MISSING_TIMELINE_API', missing } : null;
-}
-
-function ensureVendorAssets(htmlPath, compositionDirAbs) {
- const html = fs.readFileSync(htmlPath, 'utf8');
- const copied = [];
- const skipped = [];
- const issues = [];
- if (!hasLocalGsapVendorScript(html)) {
- return { ok: true, copied, skipped, issues };
- }
- const source = path.join(__dirname, 'vendor', 'gsap.min.js');
- const target = path.join(compositionDirAbs, LOCAL_GSAP_VENDOR_REF);
- if (!fs.existsSync(source)) {
- issues.push({
- severity: 'error',
- code: 'VENDOR_GSAP_SOURCE_MISSING',
- repair_target: 'assets',
- message: `Local GSAP vendor source is missing: ${source}`,
- });
- return { ok: false, copied, skipped, issues };
- }
- const sourceText = fs.readFileSync(source, 'utf8');
- const sourceIssue = gsapVendorCompatibilityIssue(sourceText);
- if (sourceIssue) {
- issues.push({
- severity: 'error',
- code: 'VENDOR_GSAP_SOURCE_INCOMPATIBLE',
- repair_target: 'assets',
- missing_api: sourceIssue.missing,
- message: `Built-in GSAP vendor is missing required HyperFrames timeline APIs: ${sourceIssue.missing.join(', ')}.`,
- });
- return { ok: false, copied, skipped, issues };
- }
-
- if (fs.existsSync(target)) {
- const targetText = fs.readFileSync(target, 'utf8');
- if (managedLegacyGsapVendor(targetText)) {
- fs.copyFileSync(source, target);
- copied.push({ id: 'gsap', reason: 'replaced legacy managed vendor', path: target });
- return { ok: true, copied, skipped, issues };
- }
- const targetIssue = gsapVendorCompatibilityIssue(targetText);
- if (!targetIssue) {
- skipped.push({ id: 'gsap', reason: 'compatible existing vendor', path: target });
- return { ok: true, copied, skipped, issues };
- }
- issues.push({
- severity: 'error',
- code: 'VENDOR_GSAP_INCOMPATIBLE',
- repair_target: LOCAL_GSAP_VENDOR_REF,
- missing_api: targetIssue.missing,
- message: `Existing GSAP vendor is missing required HyperFrames timeline APIs: ${targetIssue.missing.join(', ')}. Remove or replace ${LOCAL_GSAP_VENDOR_REF}; do not patch it manually inside the composition.`,
- });
- return { ok: false, copied, skipped, issues };
- }
-
- fs.mkdirSync(path.dirname(target), { recursive: true });
- fs.copyFileSync(source, target);
- copied.push({ id: 'gsap', path: target });
- return { ok: true, copied, skipped, issues };
-}
-
-function ensureVendorAssetsForComposition(compositionDirAbs) {
- const htmlPath = path.join(compositionDirAbs, 'index.html');
- if (!fs.existsSync(htmlPath)) return { ok: true, copied: [], skipped: [], issues: [] };
- return ensureVendorAssets(htmlPath, compositionDirAbs);
-}
-
-function failVendorAssetsIfNeeded(vendorAssets, reportAbs) {
- if (!vendorAssets || vendorAssets.ok !== false) return;
- const firstError = (vendorAssets.issues || []).find((issue) => issue.severity === 'error') || {};
- fail('E_VENDOR_ASSETS_BLOCKED', 'could not prepare local composition vendor assets', {
- ...(reportAbs ? { report_path: reportAbs } : {}),
- repair_target: firstError.repair_target || 'assets',
- vendor_assets: vendorAssets,
- });
-}
-
-function validateLocalRefs(refs, compositionDirAbs) {
- const issues = [];
- const seen = new Set();
- for (const item of refs) {
- const ref = item.ref;
- if (!ref || seen.has(`${item.kind}\u0000${ref}`)) continue;
- seen.add(`${item.kind}\u0000${ref}`);
- if (path.isAbsolute(ref)) {
- issues.push({
- severity: 'error',
- code: 'ABSOLUTE_ASSET_REF',
- repair_target: 'index.html',
- message: `Asset reference must be relative to the composition directory: ${ref}`,
- });
- continue;
- }
- let decoded = ref;
- try { decoded = decodeURIComponent(ref); } catch {}
- const abs = path.resolve(compositionDirAbs, decoded);
- const rel = path.relative(compositionDirAbs, abs);
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- issues.push({
- severity: 'error',
- code: 'ASSET_OUTSIDE_COMPOSITION',
- repair_target: 'assets',
- message: `Asset reference escapes the composition directory: ${ref}`,
- });
- continue;
- }
- if (!fs.existsSync(abs)) {
- issues.push({
- severity: 'error',
- code: 'MISSING_LOCAL_ASSET',
- repair_target: 'assets',
- message: `Referenced local asset does not exist: ${ref}`,
- });
- }
- }
- return issues;
-}
-
-function canvasFrom(value) {
- const canvas = value && typeof value === 'object' && value.canvas && typeof value.canvas === 'object'
- ? value.canvas
- : {};
- return {
- width: numberOrZero(canvas.width),
- height: numberOrZero(canvas.height),
- duration: numberOrZero(canvas.duration ?? canvas.duration_sec),
- fps: numberOrZero(canvas.fps),
- };
-}
-
-function expectedCanvas(contract, timelineMap) {
- const fromTimeline = canvasFrom(timelineMap);
- const fromContract = canvasFrom(contract);
- return {
- width: fromTimeline.width || fromContract.width,
- height: fromTimeline.height || fromContract.height,
- duration: fromTimeline.duration || fromContract.duration,
- fps: fromTimeline.fps || fromContract.fps,
- };
-}
-
-function compareCanvasPair(a, b) {
- const issues = [];
- for (const key of ['width', 'height', 'duration']) {
- if (a[key] && b[key] && Math.abs(a[key] - b[key]) > (key === 'duration' ? 0.15 : 1)) {
- issues.push({
- severity: 'error',
- code: 'CONTRACT_SCENE_MAP_CANVAS_MISMATCH',
- repair_target: 'design-contract.json',
- message: `design-contract canvas ${key}=${a[key]} but scene-map canvas ${key}=${b[key]}. Keep them identical before rendering.`,
- });
- }
- }
- return issues;
-}
-
-function colorTokenValues(contract) {
- const raw = contract && typeof contract === 'object' ? contract.color_tokens : null;
- return flattenStringValues(raw)
- .map((s) => s.trim())
- .filter((s) => /^(#[0-9a-f]{3,8}\b|rgba?\(|hsla?\()/i.test(s));
-}
-
-function runContractHtmlQa(htmlPath, contractInfo, timelineMap, compositionDirAbs) {
- const html = fs.readFileSync(htmlPath, 'utf8');
- const issues = [];
- const contract = contractInfo.contract;
-
- if (!contractInfo.exists) {
- issues.push({
- severity: 'error',
- code: 'DESIGN_CONTRACT_MISSING',
- repair_target: 'design-contract.json',
- message: 'project/composition/design-contract.json is required before drafting model-authored HTML.',
- });
- } else if (contractInfo.error || !contract) {
- issues.push({
- severity: 'error',
- code: 'DESIGN_CONTRACT_PARSE_FAILED',
- repair_target: 'design-contract.json',
- message: `Could not parse design-contract.json: ${contractInfo.error || 'not a JSON object'}`,
- });
- }
-
- for (const item of extractRemoteRefs(html)) {
- issues.push({
- severity: 'error',
- code: 'REMOTE_RUNTIME_RESOURCE',
- repair_target: 'index.html',
- message: `Remote runtime resource is not allowed during render (${item.kind}: ${item.ref}). Vendor it into project/composition/assets and reference it relatively.`,
- });
- }
- if (htmlUsesGsap(html) && !hasLocalGsapVendorScript(html)) {
- issues.push({
- severity: 'error',
- code: 'GSAP_VENDOR_SCRIPT_MISSING',
- repair_target: 'index.html',
- message: 'index.html uses gsap but does not load ./assets/vendor/gsap.min.js. Use the local vendor script or remove GSAP for this composition.',
- });
- }
- issues.push(...validateLocalRefs(extractLocalRefs(html), compositionDirAbs));
-
- const rootTag = rootCompositionTag(html);
- const rootCanvas = rootTag ? {
- width: htmlDataNumber(rootTag, 'width'),
- height: htmlDataNumber(rootTag, 'height'),
- duration: htmlDataNumber(rootTag, 'duration'),
- } : { width: 0, height: 0, duration: 0 };
- if (!rootTag) {
- issues.push({
- severity: 'error',
- code: 'ROOT_COMPOSITION_MISSING',
- repair_target: 'index.html',
- message: 'index.html must declare a root element with data-composition-id, data-width, data-height, and data-duration.',
- });
- }
-
- const expected = expectedCanvas(contract, timelineMap);
- if (contract && timelineMap) {
- issues.push(...compareCanvasPair(canvasFrom(contract), canvasFrom(timelineMap)));
- }
- for (const key of ['width', 'height', 'duration']) {
- if (!expected[key]) continue;
- const tolerance = key === 'duration' ? 0.15 : 1;
- if (!rootCanvas[key] || Math.abs(rootCanvas[key] - expected[key]) > tolerance) {
- issues.push({
- severity: 'error',
- code: 'CANVAS_CONTRACT_MISMATCH',
- repair_target: 'index.html',
- message: `index.html root data-${key}=${rootCanvas[key] || 'missing'} but contract/scene-map expects ${expected[key]}.`,
- });
- }
- }
-
- const timelineSceneList = timelineScenes(timelineMap);
- const contractScenes = contract && Array.isArray(contract.scenes) ? contract.scenes : [];
- const scenes = timelineSceneList.length ? timelineSceneList : contractScenes;
- const duration = expected.duration || rootCanvas.duration;
- let prevEnd = -1;
- for (const scene of scenes) {
- const start = numberOrZero(scene && (scene.start ?? scene.start_sec));
- const sceneDuration = numberOrZero(scene && (scene.duration ?? scene.duration_sec));
- if (!Number.isFinite(start) || !Number.isFinite(sceneDuration) || sceneDuration <= 0) {
- issues.push({
- severity: 'error',
- code: 'SCENE_TIMING_INVALID',
- repair_target: timelineSceneList.length ? 'scene-map.json' : 'design-contract.json',
- message: `Scene "${shortText(scene && (scene.id || scene.title || scene.headline) || 'unnamed', 80)}" needs numeric start and positive duration.`,
- });
- continue;
- }
- if (duration && start + sceneDuration > duration + 0.15) {
- issues.push({
- severity: 'error',
- code: 'SCENE_TIMING_OUT_OF_RANGE',
- repair_target: timelineSceneList.length ? 'scene-map.json' : 'design-contract.json',
- message: `Scene "${shortText(scene && (scene.id || scene.title || scene.headline) || 'unnamed', 80)}" ends at ${(start + sceneDuration).toFixed(2)}s beyond the composition duration ${duration.toFixed(2)}s.`,
- });
- }
- if (prevEnd >= 0 && start < prevEnd - 0.15) {
- issues.push({
- severity: 'error',
- code: 'SCENE_TIMING_OVERLAP',
- repair_target: timelineSceneList.length ? 'scene-map.json' : 'design-contract.json',
- message: `Scene "${shortText(scene && (scene.id || scene.title || scene.headline) || 'unnamed', 80)}" starts before the prior scene ends.`,
- });
- }
- prevEnd = Math.max(prevEnd, start + sceneDuration);
- }
-
- const htmlSearch = normalizeForSearch(html);
- const missingText = [];
- for (const scene of scenes.slice(0, 16)) {
- for (const text of sceneDisplayTexts(scene).slice(0, 5)) {
- const needle = normalizeForSearch(text);
- if (needle && !htmlSearch.includes(needle)) {
- missingText.push({
- scene: shortText(scene && (scene.id || scene.title || scene.headline) || 'unnamed', 80),
- text: shortText(text, 100),
- });
- }
- }
- }
- for (const item of missingText.slice(0, 8)) {
- issues.push({
- severity: 'error',
- code: 'HTML_MISSING_SCENE_COPY',
- repair_target: 'index.html',
- message: `Scene "${item.scene}" declares on-screen copy not found in index.html: "${item.text}".`,
- });
- }
-
- const colors = colorTokenValues(contract);
- const htmlLower = html.toLowerCase();
- const unusedColors = colors.filter((color) => !htmlLower.includes(color.toLowerCase())).slice(0, 6);
- if (colors.length && unusedColors.length === colors.length) {
- issues.push({
- severity: 'warning',
- code: 'COLOR_TOKENS_NOT_USED',
- repair_target: 'index.html',
- message: 'No declared color_tokens appear in index.html. Use contract tokens as CSS variables or structured constants.',
- });
- }
-
- if (contractDeclaresNarrationAudio(contract) && !compositionHasAudio(html, compositionDirAbs)) {
- issues.push({
- severity: 'warning',
- code: 'NARRATION_DECLARED_BUT_SILENT',
- repair_target: 'index.html',
- message: 'design-contract.json audio declares composition-owned narration, but index.html has no <audio> element and no narration file exists. If TTS failed, tell the user and either fix the narration or explicitly proceed silent.',
- });
- }
-
- return {
- ok: !issues.some((issue) => issue.severity === 'error'),
- design_contract_path: contractInfo.path,
- html_path: htmlPath,
- expected_canvas: expected,
- root_canvas: rootCanvas,
- scene_count: scenes.length,
- remote_ref_count: extractRemoteRefs(html).length,
- local_ref_count: extractLocalRefs(html).length,
- issues,
- };
-}
-
-function timelineScenes(timelineMap) {
- return timelineMap && Array.isArray(timelineMap.scenes) ? timelineMap.scenes : [];
-}
-
-function timelineCanvas(timelineMap) {
- const canvas = timelineMap && typeof timelineMap.canvas === 'object' && timelineMap.canvas ? timelineMap.canvas : {};
- return {
- duration: Number(canvas.duration) || 0,
- fps: Number(canvas.fps) || 30,
- };
-}
-
-function narrationPathFromTimeline(timelineMap, compositionDirAbs) {
- const audio = timelineMap && typeof timelineMap.audio === 'object' && timelineMap.audio ? timelineMap.audio : {};
- const raw = audio.narration || audio.narration_path || audio.path;
- if (!raw) return '';
- return path.resolve(compositionDirAbs, String(raw));
-}
-
-function sceneNarrationText(scene) {
- if (!scene || typeof scene !== 'object') return '';
- const raw = scene.narration || scene.voiceover || scene.audio_text || scene.script;
- if (typeof raw === 'string') return raw.trim();
- if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
- return String(raw.text || raw.body || raw.line || '').trim();
- }
- return '';
-}
-
-function sceneNarrationRef(scene) {
- if (!scene || typeof scene !== 'object') return '';
- const raw = scene.narration_ref || scene.voiceover_ref || scene.script_ref;
- if (typeof raw === 'string') return raw.trim();
- if (Array.isArray(raw) && raw.length) return raw.map((x) => String(x)).join(',');
- return '';
-}
-
-function sceneNarrationRefs(scene) {
- const raw = sceneNarrationRef(scene);
- if (!raw) return [];
- return raw.split(/[, ]+/).map((x) => x.trim()).filter(Boolean);
-}
-
-function normalizeNarrationMap(raw) {
- const root = Array.isArray(raw) ? { lines: raw } : (raw && typeof raw === 'object' ? raw : {});
- const rawLines = Array.isArray(root.lines)
- ? root.lines
- : (Array.isArray(root.segments) ? root.segments : []);
- const lines = rawLines.filter((line) => line && typeof line === 'object').map((line, index) => ({
- id: String(line.id || line.line_id || line.ref || `line-${index + 1}`),
- start: numberOrZero(line.start ?? line.start_sec ?? line.begin),
- duration: numberOrZero(line.duration ?? line.duration_sec ?? line.target_sec),
- text: String(line.text || line.narration || line.body || '').trim(),
- }));
- const byId = new Map();
- for (const line of lines) byId.set(line.id, line);
- return { lines, byId };
-}
-
-function loadNarrationMap(compositionDirAbs) {
- const candidates = [
- path.join(compositionDirAbs, 'narration-map.json'),
- path.join(compositionDirAbs, 'audio-map.json'),
- ];
- for (const mapPath of candidates) {
- if (!fs.existsSync(mapPath)) continue;
- const loaded = readJsonFile(mapPath);
- if (loaded.error) return { path: mapPath, lines: [], byId: new Map(), error: loaded.error };
- return { path: mapPath, ...normalizeNarrationMap(loaded.value) };
- }
- return { path: '', lines: [], byId: new Map() };
-}
-
-function normalizeShotlist(raw) {
- const root = Array.isArray(raw) ? raw : (raw && typeof raw === 'object' ? raw : {});
- const shots = Array.isArray(root) ? root : (root.shots || root.scenes || root.storyboard || []);
- if (!Array.isArray(shots)) return [];
- return shots.filter((shot) => shot && typeof shot === 'object').map((shot, index) => ({
- id: String(shot.id || shot.name || shot.shot || `shot-${index + 1}`),
- start: Number(shot.start ?? shot.start_sec ?? shot.in_sec),
- duration: Number(shot.duration ?? shot.duration_sec ?? shot.target_sec),
- narration: sceneNarrationText(shot),
- }));
-}
-
-function loadShotlist(compositionDirAbs) {
- const projectDir = path.dirname(compositionDirAbs);
- const candidates = [
- path.join(projectDir, 'shotlist.json'),
- path.join(projectDir, 'storyboard.json'),
- ];
- for (const shotlistPath of candidates) {
- if (!fs.existsSync(shotlistPath)) continue;
- try {
- return {
- path: shotlistPath,
- shots: normalizeShotlist(JSON.parse(fs.readFileSync(shotlistPath, 'utf8'))),
- };
- } catch (err) {
- return {
- path: shotlistPath,
- shots: [],
- error: err && err.message ? err.message : String(err),
- };
- }
- }
- return { path: '', shots: [] };
-}
-
-function sceneSourceShots(scene) {
- if (!scene || typeof scene !== 'object') return [];
- const raw = scene.source_shots || scene.shot_ids || scene.shots || scene.sourceShotIds;
- if (Array.isArray(raw)) return raw.map((x) => String(x)).filter(Boolean);
- if (typeof raw === 'string' && raw.trim()) return raw.split(/[, ]+/).map((x) => x.trim()).filter(Boolean);
- return [];
-}
-
-function hasMergeExplanation(timelineMap, scenes) {
- const alignment = timelineMap && typeof timelineMap === 'object'
- ? (timelineMap.source_alignment || timelineMap.alignment || timelineMap.timeline_alignment || {})
- : {};
- if (alignment && typeof alignment === 'object' && !Array.isArray(alignment)) {
- if (String(alignment.merge_reason || alignment.merge_policy || '').trim()) return true;
- }
- return scenes.some((scene) => String(scene.merge_reason || scene.alignment_note || '').trim())
- || scenes.every((scene) => sceneSourceShots(scene).length > 0);
-}
-
-function runSourceAlignmentQa(timelineMap, compositionDirAbs) {
- const scenes = timelineScenes(timelineMap);
- const shotlist = loadShotlist(compositionDirAbs);
- const issues = [];
- if (shotlist.error) {
- issues.push({
- severity: 'warning',
- code: 'SHOTLIST_PARSE_FAILED',
- message: `Could not parse ${shotlist.path}: ${shotlist.error}`,
- });
- }
- if (shotlist.shots.length && scenes.length && shotlist.shots.length !== scenes.length && !hasMergeExplanation(timelineMap, scenes)) {
- issues.push({
- severity: 'error',
- code: 'SHOTLIST_SCENE_COUNT_MISMATCH',
- message: `shotlist has ${shotlist.shots.length} shots but scene-map has ${scenes.length} scenes. Add source_alignment.merge_reason or per-scene source_shots when intentionally merging beats.`,
- });
- }
- return {
- ok: !issues.some((issue) => issue.severity === 'error'),
- skipped: !shotlist.path,
- shotlist_path: shotlist.path,
- shot_count: shotlist.shots.length,
- scene_count: scenes.length,
- issues,
- };
-}
-
-function buildVideoQaSamples(timelineMap, probe) {
- const duration = probe.duration_seconds || timelineCanvas(timelineMap).duration || 0;
- const scenes = timelineScenes(timelineMap);
- const samples = [{ id: 'first_frame', role: 'first_frame', time: 0 }];
- for (const scene of scenes.slice(0, 12)) {
- const id = shortText(scene && (scene.id || scene.name || scene.title) || 'scene', 80);
- const start = Number(scene && scene.start);
- const sceneDuration = Number(scene && (scene.duration || scene.duration_sec));
- if (!Number.isFinite(start) || !Number.isFinite(sceneDuration) || sceneDuration <= 0) continue;
- samples.push({ id, role: 'scene_start', time: Math.min(Math.max(start + 0.2, 0), Math.max(duration - 0.1, 0)) });
- samples.push({ id, role: 'scene_mid', time: Math.min(Math.max(start + sceneDuration / 2, 0), Math.max(duration - 0.1, 0)) });
- }
- return samples;
-}
-
-function sampleFrameStats(mediaPath, time) {
- const ffmpeg = resolveMediaTool('ffmpeg');
- const width = 160;
- const height = 90;
- const res = runProcess(ffmpeg, [
- '-hide_banner',
- '-loglevel', 'error',
- '-ss', Number(time).toFixed(3),
- '-i', mediaPath,
- '-frames:v', '1',
- '-vf', `scale=${width}:${height},format=rgb24`,
- '-f', 'rawvideo',
- 'pipe:1',
- ], { encoding: 'buffer', maxBuffer: width * height * 3 + 1024 });
- const buf = res.stdout;
- if (!Buffer.isBuffer(buf) || buf.length < width * height * 3) throw new Error(`could not sample frame at ${time}s`);
- const luma = new Float32Array(width * height);
- let sum = 0;
- for (let i = 0, p = 0; i < luma.length; i += 1, p += 3) {
- const y = 0.2126 * buf[p] + 0.7152 * buf[p + 1] + 0.0722 * buf[p + 2];
- luma[i] = y;
- sum += y;
- }
- const mean = sum / luma.length;
- let variance = 0;
- let edgeSum = 0;
- let edgeCount = 0;
- for (let y = 0; y < height; y += 1) {
- for (let x = 0; x < width; x += 1) {
- const idx = y * width + x;
- const d = luma[idx] - mean;
- variance += d * d;
- if (x > 0) { edgeSum += Math.abs(luma[idx] - luma[idx - 1]); edgeCount += 1; }
- if (y > 0) { edgeSum += Math.abs(luma[idx] - luma[idx - width]); edgeCount += 1; }
- }
- }
- const stddev = Math.sqrt(variance / luma.length);
- const edge = edgeCount ? edgeSum / edgeCount : 0;
- return {
- mean: Number(mean.toFixed(2)),
- stddev: Number(stddev.toFixed(2)),
- edge: Number(edge.toFixed(2)),
- fingerprint: crypto.createHash('sha1').update(buf.subarray(0, width * height * 3)).digest('hex').slice(0, 16),
- low_information: stddev < 14 && edge < 2.8,
- };
-}
-
-function detectStaticFrameRun(samples) {
- const visual = samples
- .filter((sample) => sample && !sample.error && sample.stats && sample.stats.fingerprint)
- .sort((a, b) => Number(a.time) - Number(b.time));
- let best = [];
- let run = [];
- for (const sample of visual) {
- const last = run[run.length - 1];
- if (last && last.stats.fingerprint === sample.stats.fingerprint) {
- run.push(sample);
- } else {
- if (run.length > best.length) best = run;
- run = [sample];
- }
- }
- if (run.length > best.length) best = run;
- if (best.length < 5) return null;
- const span = Number(best[best.length - 1].time) - Number(best[0].time);
- const sceneIds = new Set(best.map((sample) => `${sample.id || ''}`).filter(Boolean));
- if (span < 12 || sceneIds.size < 2) return null;
- return {
- count: best.length,
- start_time: Number(Number(best[0].time).toFixed(3)),
- end_time: Number(Number(best[best.length - 1].time).toFixed(3)),
- scene_count: sceneIds.size,
- fingerprint: best[0].stats.fingerprint,
- };
-}
-
-function writeContactSheet(mediaPath, samples, probe, reportPath) {
- if (!samples.length) return '';
- const ffmpeg = resolveMediaTool('ffmpeg');
- const fps = probe.video && probe.video.fps ? probe.video.fps : 30;
- const frames = [...new Set(samples.map((s) => Math.max(0, Math.round(s.time * fps))))].sort((a, b) => a - b).slice(0, 16);
- if (!frames.length) return '';
- const rows = Math.ceil(frames.length / 4);
- const selector = frames.map((n) => `eq(n\\,${n})`).join('+');
- const out = path.join(path.dirname(reportPath), `${path.basename(reportPath, path.extname(reportPath))}-contact-sheet.jpg`);
- fs.mkdirSync(path.dirname(out), { recursive: true });
- runProcess(ffmpeg, [
- '-y',
- '-hide_banner',
- '-loglevel', 'error',
- '-i', mediaPath,
- '-vf', `select=${selector},scale=420:-1,tile=4x${rows}`,
- '-frames:v', '1',
- out,
- ]);
- return out;
-}
-
-function safeFilePart(value) {
- const part = String(value || 'frame').toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
- return part.slice(0, 80) || 'frame';
-}
-
-function writeEvidenceFrames(mediaPath, samples, reportPath) {
- const ffmpeg = resolveMediaTool('ffmpeg');
- const dir = path.join(path.dirname(reportPath), `${path.basename(reportPath, path.extname(reportPath))}-frames`);
- fs.mkdirSync(dir, { recursive: true });
- const frames = [];
- const seen = new Set();
- for (const sample of samples.slice(0, 16)) {
- const key = `${sample.role}\u0000${sample.id}\u0000${Number(sample.time).toFixed(3)}`;
- if (seen.has(key)) continue;
- seen.add(key);
- const filename = `${String(frames.length + 1).padStart(2, '0')}-${safeFilePart(sample.role)}-${safeFilePart(sample.id)}.jpg`;
- const out = path.join(dir, filename);
- runProcess(ffmpeg, [
- '-y',
- '-hide_banner',
- '-loglevel', 'error',
- '-ss', Number(sample.time).toFixed(3),
- '-i', mediaPath,
- '-frames:v', '1',
- '-vf', 'scale=960:-1',
- '-q:v', '3',
- out,
- ]);
- frames.push({
- id: sample.id,
- role: sample.role,
- time: sample.time,
- path: out,
- });
- }
- return { dir, frames };
-}
-
-function runVideoQa(mediaPath, timelineMap, probe, reportPath) {
- const samples = buildVideoQaSamples(timelineMap, probe);
- const issues = [];
- const sampled = samples.map((sample) => {
- try {
- const stats = sampleFrameStats(mediaPath, sample.time);
- const isBlockingRole = sample.role === 'first_frame' || sample.role === 'scene_start';
- if (isBlockingRole && stats.low_information) {
- issues.push({
- severity: 'error',
- code: sample.role === 'first_frame' ? 'FIRST_FRAME_EMPTY' : 'SCENE_START_EMPTY',
- sample: sample.id,
- time: sample.time,
- message: `${sample.role} at ${sample.time.toFixed(2)}s has too little visual information; keep the hook/title visible at scene start.`,
- });
- }
- return { ...sample, stats };
- } catch (err) {
- issues.push({
- severity: 'warning',
- code: 'FRAME_SAMPLE_FAILED',
- sample: sample.id,
- time: sample.time,
- message: err && err.message ? err.message : String(err),
- });
- return { ...sample, error: err && err.message ? err.message : String(err) };
- }
- });
- const staticRun = detectStaticFrameRun(sampled);
- if (staticRun) {
- issues.push({
- severity: 'error',
- code: 'STATIC_FRAME_RUN',
- ...staticRun,
- message: `${staticRun.count} sampled frames across ${staticRun.scene_count} scenes are pixel-identical from ${staticRun.start_time.toFixed(2)}s to ${staticRun.end_time.toFixed(2)}s; the render likely froze or the timeline is not being driven.`,
- });
- }
- let contactSheet = '';
- try {
- contactSheet = writeContactSheet(mediaPath, sampled, probe, reportPath);
- } catch (err) {
- issues.push({
- severity: 'warning',
- code: 'CONTACT_SHEET_FAILED',
- message: err && err.message ? err.message : String(err),
- });
- }
- let evidence = { dir: '', frames: [] };
- try {
- evidence = writeEvidenceFrames(mediaPath, sampled, reportPath);
- } catch (err) {
- issues.push({
- severity: 'warning',
- code: 'FRAME_EVIDENCE_FAILED',
- message: err && err.message ? err.message : String(err),
- });
- }
- const framePathByKey = new Map(evidence.frames.map((frame) => [
- `${frame.role}\u0000${frame.id}\u0000${Number(frame.time).toFixed(3)}`,
- frame.path,
- ]));
- return {
- ok: !issues.some((issue) => issue.severity === 'error'),
- issue_count: issues.length,
- issues,
- samples: sampled.map((sample) => ({
- ...sample,
- frame_path: framePathByKey.get(`${sample.role}\u0000${sample.id}\u0000${Number(sample.time).toFixed(3)}`) || '',
- })),
- contact_sheet: contactSheet,
- evidence_dir: evidence.dir,
- frame_paths: evidence.frames,
- };
-}
-
-function runAudioTimingQa(timelineMap, compositionDirAbs) {
- const scenes = timelineScenes(timelineMap);
- const narrationPath = narrationPathFromTimeline(timelineMap, compositionDirAbs);
- const narrationMap = loadNarrationMap(compositionDirAbs);
- const issues = [];
- if (narrationMap.error) {
- issues.push({
- severity: 'error',
- code: 'NARRATION_MAP_PARSE_FAILED',
- message: `Could not parse ${narrationMap.path}: ${narrationMap.error}`,
- });
- }
- if (narrationPath && !fs.existsSync(narrationPath)) {
- issues.push({
- severity: 'error',
- code: 'NARRATION_ASSET_MISSING',
- message: `scene-map declares narration audio but the file does not exist: ${narrationPath}`,
- });
- return {
- ok: false,
- skipped: false,
- narration_path: narrationPath,
- narration_map_path: narrationMap.path,
- issues,
- };
- }
- if (!narrationPath) {
- return {
- ok: !issues.some((issue) => issue.severity === 'error'),
- skipped: true,
- reason: 'no narration asset in scene-map',
- narration_map_path: narrationMap.path,
- issues,
- };
- }
- const narrationProbe = probeMedia(narrationPath);
- const duration = narrationProbe.duration_seconds || 0;
- if (scenes.length) {
- const last = scenes[scenes.length - 1] || {};
- const lastStart = Number(last.start);
- if (Number.isFinite(lastStart) && duration > 0 && lastStart > duration + 0.15) {
- issues.push({
- severity: 'warning',
- code: 'CLOSING_AFTER_NARRATION',
- message: `The final scene starts at ${lastStart.toFixed(2)}s but narration ends around ${duration.toFixed(2)}s. Align the closing visual with the final narrated line unless this is an intentional silent tail.`,
- });
- }
- }
- const mappedScenes = scenes.filter((scene) => sceneNarrationText(scene) || sceneNarrationRef(scene) || sceneSourceShots(scene).length);
- if (scenes.length >= 2 && mappedScenes.length < scenes.length) {
- issues.push({
- severity: 'error',
- code: 'SCENE_NARRATION_MISSING',
- message: `${scenes.length - mappedScenes.length} of ${scenes.length} scenes do not declare narration text or narration_ref, so voiceover-to-visual alignment cannot be verified.`,
- });
- }
- const refScenes = scenes.filter((scene) => sceneNarrationRefs(scene).length);
- if (refScenes.length && narrationMap.lines.length) {
- for (const scene of refScenes) {
- const refs = sceneNarrationRefs(scene);
- const lines = refs.map((ref) => narrationMap.byId.get(ref)).filter(Boolean);
- const missing = refs.filter((ref) => !narrationMap.byId.has(ref));
- if (missing.length) {
- issues.push({
- severity: 'error',
- code: 'NARRATION_REF_MISSING',
- scene: scene.id || scene.title || '',
- message: `Scene references narration line(s) not found in narration-map.json: ${missing.join(', ')}`,
- });
- continue;
- }
- const expectedStart = Math.min(...lines.map((line) => line.start));
- const expectedEnd = Math.max(...lines.map((line) => line.start + Math.max(line.duration, 0)));
- const actualStart = numberOrZero(scene.start ?? scene.start_sec);
- const actualEnd = actualStart + numberOrZero(scene.duration ?? scene.duration_sec);
- const startDrift = actualStart - expectedStart;
- if (Math.abs(startDrift) > 1.25) {
- issues.push({
- severity: 'error',
- code: 'NARRATION_LINE_START_DRIFT',
- scene: scene.id || scene.title || '',
- message: `Scene starts at ${actualStart.toFixed(2)}s but narration-map line timing starts at ${expectedStart.toFixed(2)}s (${startDrift.toFixed(2)}s drift).`,
- });
- }
- if (expectedEnd > actualEnd + 1.25) {
- issues.push({
- severity: 'error',
- code: 'NARRATION_LINE_OVERFLOWS_SCENE',
- scene: scene.id || scene.title || '',
- message: `Scene ends at ${actualEnd.toFixed(2)}s but referenced narration line(s) run until ${expectedEnd.toFixed(2)}s.`,
- });
- }
- }
- } else if (refScenes.length && !narrationMap.lines.length) {
- issues.push({
- severity: 'warning',
- code: 'NARRATION_MAP_MISSING',
- message: 'Scenes use narration_ref but no narration-map.json exists, so draft QA falls back to coarse timing checks.',
- });
- }
- const narratedScenes = scenes.filter((scene) => sceneNarrationText(scene));
- if (!narrationMap.lines.length && narratedScenes.length >= 2 && duration > 0) {
- const totalChars = narratedScenes.reduce((sum, scene) => sum + sceneNarrationText(scene).length, 0);
- let cursorChars = 0;
- for (const scene of narratedScenes) {
- const expectedStart = totalChars > 0 ? (cursorChars / totalChars) * duration : 0;
- const actualStart = Number(scene.start) || 0;
- const drift = actualStart - expectedStart;
- if (Math.abs(drift) > 3.5) {
- issues.push({
- severity: 'error',
- code: 'AUDIO_TIMING_DRIFT',
- scene: scene.id || scene.title || '',
- message: `Scene starts at ${actualStart.toFixed(2)}s but estimated narration timing is ${expectedStart.toFixed(2)}s (${drift.toFixed(2)}s drift).`,
- });
- }
- cursorChars += sceneNarrationText(scene).length;
- }
- } else if (!narrationMap.lines.length && mappedScenes.length >= 2 && narratedScenes.length < 2) {
- issues.push({
- severity: 'warning',
- code: 'AUDIO_TIMING_ESTIMATE_SKIPPED',
- message: 'Scenes use narration references or source_shots without inline narration text, so draft QA can verify mapping presence but cannot estimate timing drift.',
- });
- }
- return {
- ok: !issues.some((issue) => issue.severity === 'error'),
- skipped: false,
- narration_path: narrationPath,
- narration_map_path: narrationMap.path,
- narration_duration_seconds: duration,
- issues,
- };
-}
-
-function writeJsonFile(rawPath, payload) {
- const abs = resolveOutputPath(rawPath);
- fs.mkdirSync(path.dirname(abs), { recursive: true });
- fs.writeFileSync(abs, JSON.stringify(payload, null, 2), 'utf8');
- return abs;
-}
-
-function readJsonFileIfExists(abs) {
- try {
- if (!abs || !fs.existsSync(abs)) return null;
- return JSON.parse(fs.readFileSync(abs, 'utf8'));
- } catch {
- return null;
- }
-}
-
-function draftRepairStatePath(compositionDirAbs) {
- return path.join(compositionDirAbs, 'qa', 'draft-repair-state.json');
-}
-
-function draftContentSignature(compositionDirAbs) {
- const hash = crypto.createHash('sha256');
- for (const name of ['design-contract.json', 'scene-map.json', 'narration-map.json', 'index.html']) {
- const abs = path.join(compositionDirAbs, name);
- if (!fs.existsSync(abs)) continue;
- hash.update(name);
- hash.update('\0');
- hash.update(fs.readFileSync(abs));
- hash.update('\0');
- }
- return hash.digest('hex');
-}
-
-function normalizeRepairState(raw) {
- const failedAttempts = Math.max(0, Number(raw && raw.failed_attempts) || 0);
- return {
- status: raw && raw.status === 'failed' ? 'failed' : 'ok',
- failed_attempts: failedAttempts,
- repair_passes_used: Math.max(0, failedAttempts - 1),
- max_repair_passes: DRAFT_REPAIR_MAX_PASSES,
- last_error: raw && raw.last_error && typeof raw.last_error === 'object' ? raw.last_error : null,
- history: raw && Array.isArray(raw.history) ? raw.history.slice(-12) : [],
- };
-}
-
-function repairBudgetSummary(statePath, state) {
- const failedAttempts = Math.max(0, Number(state && state.failed_attempts) || 0);
- const used = Math.max(0, failedAttempts - 1);
- const budgetExhausted = failedAttempts > 0 && used >= DRAFT_REPAIR_MAX_PASSES;
- return {
- ok: !budgetExhausted,
- budget_exhausted: budgetExhausted,
- state_path: statePath,
- max_repair_passes: DRAFT_REPAIR_MAX_PASSES,
- failed_attempts: failedAttempts,
- repair_passes_used: used,
- repair_passes_remaining: Math.max(0, DRAFT_REPAIR_MAX_PASSES - used),
- last_error: state && state.last_error ? state.last_error : null,
- };
-}
-
-function initDraftRepairBudget(compositionDirAbs) {
- const statePath = draftRepairStatePath(compositionDirAbs);
- const state = normalizeRepairState(readJsonFileIfExists(statePath));
- const summary = repairBudgetSummary(statePath, state);
- return {
- compositionDirAbs,
- statePath,
- state,
- summary,
- blocked: state.status === 'failed' && summary.repair_passes_used >= DRAFT_REPAIR_MAX_PASSES,
- };
-}
-
-function writeRepairState(statePath, state) {
- fs.mkdirSync(path.dirname(statePath), { recursive: true });
- fs.writeFileSync(statePath, JSON.stringify(state, null, 2), 'utf8');
-}
-
-function recordDraftFailure(repairBudget, reportAbs, code, message, extra = {}) {
- if (!repairBudget) return null;
- const previous = normalizeRepairState(readJsonFileIfExists(repairBudget.statePath) || repairBudget.state);
- const failedAttempts = previous.failed_attempts + 1;
- const entry = {
- ts: new Date().toISOString(),
- code,
- message: shortText(message, 300),
- report_path: reportAbs,
- repair_target: shortText(extra.repair_target || '', 120),
- content_signature: draftContentSignature(repairBudget.compositionDirAbs),
- };
- const next = {
- status: 'failed',
- max_repair_passes: DRAFT_REPAIR_MAX_PASSES,
- failed_attempts: failedAttempts,
- repair_passes_used: Math.max(0, failedAttempts - 1),
- last_error: entry,
- history: [...previous.history, entry].slice(-12),
- };
- writeRepairState(repairBudget.statePath, next);
- repairBudget.state = next;
- repairBudget.summary = repairBudgetSummary(repairBudget.statePath, next);
- repairBudget.blocked = repairBudget.summary.repair_passes_used >= DRAFT_REPAIR_MAX_PASSES;
- return repairBudget.summary;
-}
-
-function recordDraftSuccess(repairBudget, reportAbs, renderPath) {
- if (!repairBudget) return null;
- const previous = normalizeRepairState(readJsonFileIfExists(repairBudget.statePath) || repairBudget.state);
- const next = {
- status: 'ok',
- max_repair_passes: DRAFT_REPAIR_MAX_PASSES,
- failed_attempts: 0,
- repair_passes_used: 0,
- last_success: {
- ts: new Date().toISOString(),
- report_path: reportAbs,
- path: renderPath || '',
- content_signature: draftContentSignature(repairBudget.compositionDirAbs),
- },
- history: previous.history,
- };
- writeRepairState(repairBudget.statePath, next);
- repairBudget.state = next;
- repairBudget.summary = repairBudgetSummary(repairBudget.statePath, next);
- repairBudget.blocked = false;
- return repairBudget.summary;
-}
-
-function failDraft(report, reportAbs, code, message, extra = {}, repairBudget = null) {
- report.error = {
- code,
- message,
- ...(extra.repair_target ? { repair_target: extra.repair_target } : {}),
- };
- const budgetSummary = recordDraftFailure(repairBudget, reportAbs, code, message, extra);
- if (budgetSummary) {
- report.steps.repair_budget = budgetSummary;
- report.repair_budget = budgetSummary;
- }
- report.report_path = writeJsonFile(reportAbs, report);
- fail(code, message, {
- report_path: report.report_path,
- ...(budgetSummary ? { repair_budget: budgetSummary } : {}),
- ...extra,
- });
-}
-
-module.exports = async function renderCompositionScript({ args }) {
- const opts = parseArgs(args || []);
- if (opts.help) return help();
- if (!OPS.has(opts.op)) fail('E_ARGS', `op must be one of: ${[...OPS].join(', ')}`);
- if (opts.findingsInline && !FINDINGS_INLINE.has(opts.findingsInline)) {
- fail('E_ARGS', `--findings-inline must be one of: ${[...FINDINGS_INLINE].join(', ')}`);
- }
- if (!opts.compositionDir) fail('E_ARGS', '--composition-dir is required');
-
- if (opts.op === 'draft') {
- const compositionDirAbs = resolveOrCreateDir(opts.compositionDir);
- const format = FORMAT.has(opts.format) ? opts.format : 'mp4';
- const quality = QUALITY.has(opts.quality) ? opts.quality : 'draft';
- const out = await outputFile(opts.outputPath, format);
- const reportAbs = opts.reportPath
- ? resolveOutputPath(opts.reportPath)
- : path.join(path.dirname(out.finalPath), `${path.basename(out.finalPath, path.extname(out.finalPath))}-report.json`);
- const findingsAbs = opts.findingsOutputPath
- ? resolveOutputPath(opts.findingsOutputPath)
- : path.join(compositionDirAbs, 'qa', 'inspect.json');
- const lintFindingsAbs = path.join(compositionDirAbs, 'qa', 'lint.json');
- const report = {
- ok: false,
- op: 'draft',
- composition_dir: compositionDirAbs,
- requested_path: out.requested,
- path: out.finalPath,
- renamed: out.renamed,
- steps: {},
- };
- const repairBudget = initDraftRepairBudget(compositionDirAbs);
- report.steps.repair_budget = repairBudget.summary;
- report.repair_budget = repairBudget.summary;
- if (repairBudget.blocked) {
- report.error = {
- code: 'E_REPAIR_BUDGET_EXCEEDED',
- message: `Draft repair budget exceeded: the initial draft plus ${DRAFT_REPAIR_MAX_PASSES} repair pass(es) still failed. Stop and report the blocker instead of continuing to patch.`,
- };
- report.report_path = writeJsonFile(reportAbs, report);
- fail('E_REPAIR_BUDGET_EXCEEDED', report.error.message, {
- report_path: report.report_path,
- repair_budget: repairBudget.summary,
- last_error: repairBudget.summary.last_error,
- });
- }
- const { renderComposition, qaComposition, isConstrainedMachine, estimateRenderCost, renderCostDecision, degradedFps, machineRamGB } = require('./lib/video_render_core.cjs');
- try {
- if (opts.specPath || fs.existsSync(path.join(compositionDirAbs, 'spec.json'))) {
- failDraft(report, reportAbs, 'E_SPEC_COMPILER_REMOVED', 'COMPOSE spec compilation has been removed. Write project/composition/index.html directly and optional scene-map.json for timing QA.', {}, repairBudget);
- }
- const htmlPath = path.join(compositionDirAbs, 'index.html');
- if (!fs.existsSync(htmlPath)) {
- failDraft(report, reportAbs, 'E_RENDER_NO_COMPOSITION', `No hand-authored index.html found in ${compositionDirAbs}`, {}, repairBudget);
- }
- const timeline = loadTimelineMap(compositionDirAbs);
- if (timeline.error) {
- failDraft(report, reportAbs, 'E_SCENE_MAP_PARSE_FAILED', `Could not parse ${timeline.path}: ${timeline.error}`, {
- repair_target: path.basename(timeline.path),
- }, repairBudget);
- }
- const timelineMap = timeline.map;
- if (!timelineMap && htmlNeedsSceneMap(compositionDirAbs)) {
- failDraft(report, reportAbs, 'E_SCENE_MAP_REQUIRED', 'Narrated hand-authored HTML requires project/composition/scene-map.json so draft QA can verify voiceover-to-visual alignment.', {}, repairBudget);
- }
- const contractInfo = loadDesignContract(compositionDirAbs);
- report.authoring_mode = 'hand_authored_html';
- report.steps.authoring = {
- ok: true,
- mode: 'hand_authored_html',
- path: htmlPath,
- timeline_path: timeline.path || '',
- design_contract_path: contractInfo.path,
- text: 'Using model-authored project/composition/index.html.',
- };
- report.timeline_path = timeline.path || '';
- report.canvas = timelineMap ? timelineCanvas(timelineMap) : {};
-
- report.steps.vendor_assets = ensureVendorAssets(htmlPath, compositionDirAbs);
- if (report.steps.vendor_assets.ok === false) {
- const firstError = report.steps.vendor_assets.issues.find((issue) => issue.severity === 'error') || {};
- const repairTarget = firstError.repair_target || 'assets';
- failDraft(report, reportAbs, 'E_VENDOR_ASSETS_BLOCKED', 'could not prepare local composition vendor assets', {
- repair_target: repairTarget,
- vendor_assets: report.steps.vendor_assets,
- }, repairBudget);
- }
-
- report.steps.contract_html = runContractHtmlQa(htmlPath, contractInfo, timelineMap, compositionDirAbs);
- if (report.steps.contract_html.ok === false) {
- const firstError = report.steps.contract_html.issues.find((issue) => issue.severity === 'error') || {};
- const repairTarget = firstError.repair_target || 'index.html';
- failDraft(report, reportAbs, 'E_CONTRACT_HTML_BLOCKED', 'design-contract/scene-map/index.html consistency failed draft QA', {
- repair_target: repairTarget,
- contract_html: report.steps.contract_html,
- }, repairBudget);
- }
-
- report.steps.source_alignment = runSourceAlignmentQa(timelineMap, compositionDirAbs);
- if (report.steps.source_alignment.ok === false) {
- failDraft(report, reportAbs, 'E_SOURCE_ALIGNMENT_BLOCKED', 'script/shotlist/scene-map alignment failed draft QA', {
- source_alignment: report.steps.source_alignment,
- }, repairBudget);
- }
-
- report.steps.audio_timing = runAudioTimingQa(timelineMap, compositionDirAbs);
- if (report.steps.audio_timing.ok === false) {
- failDraft(report, reportAbs, 'E_AUDIO_TIMING_BLOCKED', 'audio timing drift failed draft QA', {
- audio_timing: report.steps.audio_timing,
- }, repairBudget);
- }
-
- // Render-resilience profile (P1/P2): weak/no-GPU machines software-render,
- // which is slow and memory-heavy. Detect the constraint, use the
- // low-memory render profile, and degrade a heavy DRAFT (lower fps) instead
- // of crashing / hanging. (A final render fails fast — handled below.)
- const renderCanvas = expectedCanvas(contractInfo.contract, timelineMap);
- const requestedFps = typeof opts.fps === 'number'
- ? opts.fps
- : (contractInfo.contract && contractInfo.contract.canvas && typeof contractInfo.contract.canvas.fps === 'number' ? contractInfo.contract.canvas.fps : 30);
- const ramGB = machineRamGB();
- const constrained = isConstrainedMachine(ramGB);
- const costUnits = estimateRenderCost(renderCanvas.width || 1920, renderCanvas.height || 1080, renderCanvas.duration || 0, requestedFps);
- const costDecision = renderCostDecision({ constrained, costUnits, isFinal: false });
- const renderFps = costDecision === 'degrade' ? degradedFps(requestedFps) : requestedFps;
- report.steps.render_profile = {
- constrained,
- machine_ram_gb: ramGB,
- cost_units: costUnits,
- decision: costDecision,
- ...(renderFps !== requestedFps ? { degraded_fps: `${requestedFps}→${renderFps}` } : {}),
- };
-
- const lint = await qaComposition('lint', {
- constrained,
- onProgress: makeProgressEmitter('draft'),
- logPath: renderLogPath(compositionDirAbs, 'qa-lint'),
- projectDirAbs: compositionDirAbs,
- });
- if (lint.ok === false) {
- report.steps.lint = {
- ok: false,
- error_code: lint.errorCode || 'E_LINT_FAILED',
- message: lint.message || 'lint failed',
- };
- failDraft(report, reportAbs, lint.errorCode || 'E_LINT_FAILED', lint.message || 'lint failed', {
- lint: report.steps.lint,
- }, repairBudget);
- }
- const lintSummary = summarizeFindings(lint.findings);
- report.steps.lint = {
- ok: lintSummary.ok,
- summary: lintSummary,
- findings_path: writeFindingsOutput(lintFindingsAbs, {
- ok: true,
- op: 'lint',
- summary: lintSummary,
- findings: lint.findings,
- }),
- };
- if (lintSummary.ok === false || (lintSummary.errorCount || 0) > 0) {
- failDraft(report, reportAbs, 'E_LINT_BLOCKED', 'HyperFrames lint failed; repair render-contract issues before inspect/render', {
- lint_summary: lintSummary,
- }, repairBudget);
- }
-
- const inspect = await qaComposition('inspect', {
- projectDirAbs: compositionDirAbs,
- strictCraft: true,
- constrained,
- onProgress: makeProgressEmitter('draft'),
- logPath: renderLogPath(compositionDirAbs, 'qa-inspect'),
- });
- if (inspect.ok === false) {
- report.steps.inspect = {
- ok: false,
- error_code: inspect.errorCode || 'E_INSPECT_FAILED',
- message: inspect.message || 'inspect failed',
- };
- failDraft(report, reportAbs, inspect.errorCode || 'E_INSPECT_FAILED', inspect.message || 'inspect failed', {
- inspect: report.steps.inspect,
- }, repairBudget);
- }
- const inspectSummary = summarizeFindings(inspect.findings);
- const inspectDisposition = summarizeDraftInspectDisposition(inspect.findings);
- const hasUnclassifiedInspectFailure = (inspectSummary.ok === false || (inspectSummary.errorCount || 0) > 0)
- && inspectDisposition.blocking_error_count === 0
- && inspectDisposition.advisory_count === 0;
- report.steps.inspect = {
- ok: inspectDisposition.blocking_error_count === 0 && !hasUnclassifiedInspectFailure,
- qa_ok: inspectSummary.ok,
- summary: inspectSummary,
- draft_disposition: inspectDisposition,
- findings_path: writeFindingsOutput(findingsAbs, {
- ok: true,
- op: 'inspect',
- summary: inspectSummary,
- draft_disposition: inspectDisposition,
- findings: inspect.findings,
- }),
- };
- if (inspectDisposition.blocking_error_count > 0 || hasUnclassifiedInspectFailure) {
- failDraft(report, reportAbs, 'E_INSPECT_BLOCKED', 'inspect found non-visual blockers; repair design-contract/scene-map/HTML before rendering', {
- inspect_summary: inspectSummary,
- draft_disposition: inspectDisposition,
- }, repairBudget);
- }
-
- const render = await renderComposition({
- projectDirAbs: compositionDirAbs,
- outputAbsPath: out.finalPath,
- quality,
- ...(typeof renderFps === 'number' ? { fps: renderFps } : {}),
- format,
- ...(opts.variables && typeof opts.variables === 'object' && !Array.isArray(opts.variables) ? { variables: opts.variables } : {}),
- constrained,
- onProgress: makeProgressEmitter('draft'),
- logPath: renderLogPath(compositionDirAbs, 'render'),
- });
- if (render.ok === false) {
- report.steps.render = render;
- failDraft(report, reportAbs, render.errorCode || 'E_RENDER_FAILED', render.message || 'render failed', {
- render,
- }, repairBudget);
- }
- report.steps.render = render;
-
- report.media_before_audio_postprocess = probeMedia(render.path);
- if (report.media_before_audio_postprocess.audio) {
- report.steps.loudness_before = analyzeLoudness(render.path);
- report.steps.audio_normalize = opts.normalizeAudio
- ? normalizeAudioInPlace(render.path)
- : { skipped: true, reason: 'disabled by args' };
- } else {
- report.steps.audio_normalize = { skipped: true, reason: 'no audio stream' };
- }
- report.media = probeMedia(render.path);
- if (report.media.audio) report.steps.loudness_after = analyzeLoudness(render.path);
-
- report.steps.video_qa = opts.videoQa
- ? runVideoQa(render.path, timelineMap, report.media, reportAbs)
- : { ok: true, skipped: true, reason: 'disabled by args' };
- if (report.steps.video_qa.ok === false) {
- failDraft(report, reportAbs, 'E_VIDEO_QA_BLOCKED', 'video-level QA failed; repair design-contract/scene-map/HTML before Gate D', {
- video_qa: report.steps.video_qa,
- }, repairBudget);
- }
-
- report.ok = true;
- const successBudget = recordDraftSuccess(repairBudget, reportAbs, render.path);
- if (successBudget) {
- report.steps.repair_budget = successBudget;
- report.repair_budget = successBudget;
- }
- report.report_path = writeJsonFile(reportAbs, report);
- return {
- ok: true,
- op: 'draft',
- path: render.path,
- bytes: render.bytes,
- media: `chat-media://local/${render.path}`,
- report_path: report.report_path,
- findings_path: report.steps.inspect.findings_path,
- contact_sheet: report.steps.video_qa.contact_sheet || '',
- evidence_dir: report.steps.video_qa.evidence_dir || '',
- frame_paths: report.steps.video_qa.frame_paths || [],
- probe: report.media,
- inspect: {
- ok: report.steps.inspect.ok,
- qa_ok: report.steps.inspect.qa_ok,
- advisory_count: report.steps.inspect.draft_disposition.advisory_count,
- blocking_error_count: report.steps.inspect.draft_disposition.blocking_error_count,
- advisory_issues: report.steps.inspect.draft_disposition.advisory_issues.slice(0, 6),
- },
- contract_html: report.steps.contract_html,
- source_alignment: report.steps.source_alignment,
- audio_timing: report.steps.audio_timing,
- video_qa: {
- ok: report.steps.video_qa.ok,
- issue_count: report.steps.video_qa.issue_count || 0,
- issues: (report.steps.video_qa.issues || []).slice(0, 6),
- },
- repair_budget: report.repair_budget,
- ...(render.diagnostics ? { render_diagnostics: render.diagnostics } : {}),
- ...(render.logPath ? { render_log_path: render.logPath } : {}),
- render_profile: report.steps.render_profile,
- text: `Draft rendered to ${render.path} (${render.diagnostics && render.diagnostics.gpuMode ? render.diagnostics.gpuMode + ' GPU mode' : 'render ok'})${report.steps.render_profile.degraded_fps ? `; drafted at reduced fps ${report.steps.render_profile.degraded_fps} because this machine has no GPU acceleration — the final render will need lower settings or a GPU machine` : ''}; QA report written to ${report.report_path}.`,
- };
- } catch (err) {
- if (err && err.code === 'E_MEDIA_TOOL_MISSING') throw err;
- failDraft(report, reportAbs, 'E_DRAFT_FAILED', err && err.message ? err.message : String(err), {}, repairBudget);
- }
- }
-
- const compositionDirAbs = resolveDir(opts.compositionDir);
- const vendorAssets = ensureVendorAssetsForComposition(compositionDirAbs);
- failVendorAssetsIfNeeded(vendorAssets);
- const { renderComposition, qaComposition, isConstrainedMachine, estimateRenderCost, renderCostDecision, degradedFps, machineRamGB } = require('./lib/video_render_core.cjs');
-
- if (opts.op === 'lint' || opts.op === 'inspect') {
- const result = await qaComposition(opts.op, {
- projectDirAbs: compositionDirAbs,
- strictCraft: opts.strictCraft,
- onProgress: makeProgressEmitter(opts.op),
- logPath: renderLogPath(compositionDirAbs, `qa-${opts.op}`),
- });
- if (result.ok === false) fail(result.errorCode, result.message, {
- ...(result.diagnostics ? { render_diagnostics: result.diagnostics } : {}),
- ...(result.logPath ? { render_log_path: result.logPath } : {}),
- });
- const summary = summarizeFindings(result.findings);
- const inline = opts.findingsInline || (opts.findingsOutputPath ? 'summary' : 'full');
- const payload = {
- ok: true,
- op: opts.op,
- summary,
- vendor_assets: vendorAssets,
- text: opts.findingsOutputPath
- ? `${opts.op} findings were summarized here and written to findings_path.`
- : (inline === 'full' ? `${opts.op} findings are available in findings.` : `${opts.op} findings were summarized here.`),
- };
- if (opts.findingsOutputPath) {
- payload.findings_path = writeFindingsOutput(opts.findingsOutputPath, {
- ok: true,
- op: opts.op,
- summary,
- findings: result.findings,
- });
- }
- if (inline === 'full') payload.findings = result.findings;
- else if (inline === 'summary') payload.findings_summary = summary;
- return payload;
- }
-
- const format = FORMAT.has(opts.format) ? opts.format : 'mp4';
- const quality = QUALITY.has(opts.quality) ? opts.quality : undefined;
- const out = await outputFile(opts.outputPath, format);
-
- // Render-resilience (P1/P2): a heavy composition on a weak/no-GPU machine will
- // software-render and likely crash or hang. A FINAL (high-quality) render
- // fails fast with an actionable message rather than a long hang; a
- // draft-quality standalone render degrades fps like the draft flow.
- let renderFps = typeof opts.fps === 'number' ? opts.fps : undefined;
- let constrained = false;
- try {
- const html = fs.readFileSync(path.join(compositionDirAbs, 'index.html'), 'utf8');
- const rootTag = rootCompositionTag(html);
- const w = htmlDataNumber(rootTag, 'width') || 1920;
- const h = htmlDataNumber(rootTag, 'height') || 1080;
- const dur = htmlDataNumber(rootTag, 'duration') || 0;
- const fps = renderFps || 30;
- const ramGB = machineRamGB();
- constrained = isConstrainedMachine(ramGB);
- const costUnits = estimateRenderCost(w, h, dur, fps);
- const decision = renderCostDecision({ constrained, costUnits, isFinal: quality === 'high' });
- if (decision === 'fail_fast') {
- fail('E_RENDER_TOO_HEAVY',
- `This ${w}x${h}, ${Math.round(dur)}s composition cannot be rendered at ${quality} quality on this machine without GPU acceleration (software rendering would crash or hang). Options: lower the resolution/fps/length, keep the draft, or render on a machine with a GPU.`,
- { render_profile: { constrained, machine_ram_gb: ramGB, cost_units: costUnits, decision } });
- }
- if (decision === 'degrade') renderFps = degradedFps(fps);
- } catch { /* canvas unknown → render as requested */ }
-
- const result = await renderComposition({
- projectDirAbs: compositionDirAbs,
- outputAbsPath: out.finalPath,
- ...(quality ? { quality } : {}),
- ...(typeof renderFps === 'number' ? { fps: renderFps } : {}),
- format,
- constrained,
- onProgress: makeProgressEmitter(opts.op),
- logPath: renderLogPath(compositionDirAbs, 'render'),
- ...(opts.variables && typeof opts.variables === 'object' && !Array.isArray(opts.variables) ? { variables: opts.variables } : {}),
- });
- if (result.ok === false) fail(result.errorCode, result.message, {
- ...(result.diagnostics ? { render_diagnostics: result.diagnostics } : {}),
- ...(result.logPath ? { render_log_path: result.logPath } : {}),
- });
- return {
- ok: true,
- op: opts.op,
- path: result.path,
- bytes: result.bytes,
- media: `chat-media://local/${result.path}`,
- renamed: out.renamed,
- requested_path: out.requested,
- vendor_assets: vendorAssets,
- ...(result.diagnostics ? { render_diagnostics: result.diagnostics } : {}),
- ...(result.logPath ? { render_log_path: result.logPath } : {}),
- text: `Video rendered to ${result.path}${result.diagnostics && result.diagnostics.gpuMode ? ` (${result.diagnostics.gpuMode} GPU mode)` : ''}.`,
- };
-};
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/analyze_media.js b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/analyze_media.js
index 517a0d1b..6ce92311 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/analyze_media.js
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/analyze_media.js
@@ -3,7 +3,7 @@
const fs = require('node:fs');
const path = require('node:path');
-const OPS = new Set(['transcribe', 'silence', 'ocr', 'scenes', 'quality']);
+const OPS = new Set(['silence', 'ocr', 'scenes', 'quality']);
function fail(code, message, extra = {}) {
process.stderr.write(JSON.stringify({ ok: false, code, message, ...extra }) + '\n');
@@ -15,7 +15,7 @@ function help() {
ok: true,
script: 'analyze_media',
ops: [...OPS],
- usage: 'stage-edit analyze_media -- --op <transcribe|silence|ocr|scenes|quality> --input <media>',
+ usage: 'stage-edit analyze_media -- --op <silence|ocr|scenes|quality> --input <media>. Use video_studio op "speech.transcribe" for transcription.',
};
}
@@ -40,8 +40,6 @@ function parseArgs(args) {
else if (a === '--input' || a === '--input-path' || a === '-i') { out.inputPath = nextValue(args, i, a); i += 1; }
else if (a.startsWith('--input=')) out.inputPath = a.slice('--input='.length);
else if (a.startsWith('--input-path=')) out.inputPath = a.slice('--input-path='.length);
- else if (a === '--model') { out.model = nextValue(args, i, a); i += 1; }
- else if (a.startsWith('--model=')) out.model = a.slice('--model='.length);
else if (a === '--interval-sec') { out.intervalSec = parseNumber(nextValue(args, i, a), a); i += 1; }
else if (a.startsWith('--interval-sec=')) out.intervalSec = parseNumber(a.slice('--interval-sec='.length), '--interval-sec');
else if (a === '--max-frames') { out.maxFrames = parseNumber(nextValue(args, i, a), a); i += 1; }
@@ -79,7 +77,6 @@ module.exports = async function analyzeMediaScript({ args }) {
const result = await analyzeMedia({
op: opts.op,
inputAbsPath: resolveInput(opts.inputPath),
- ...(opts.model ? { model: opts.model } : {}),
...(typeof opts.intervalSec === 'number' ? { intervalSec: opts.intervalSec } : {}),
...(typeof opts.maxFrames === 'number' ? { maxFrames: opts.maxFrames } : {}),
...(typeof opts.threshold === 'number' ? { threshold: opts.threshold } : {}),
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_analyze_core.cjs b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_analyze_core.cjs
index 410ef6db..5ffafe03 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_analyze_core.cjs
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_analyze_core.cjs
@@ -1,7 +1,7 @@
-var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_analyze_exports={};__export(video_analyze_exports,{analyzeMedia:()=>analyzeMedia,collapseOcrSegments:()=>collapseOcrSegments,sampleTimecodes:()=>sampleTimecodes});module.exports=__toCommonJS(video_analyze_exports);var fs5=__toESM(require("node:fs/promises"));var os=__toESM(require("node:os"));var path4=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var fs3=__toESM(require("node:fs"));var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var pythonPackageVenvDir=key=>path.join(PYTHON_VENV_ROOT,"packages",key,".venv");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function isDir(p){if(!p)return false;try{return fs2.statSync(p).isDirectory()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolvePythonExecutable(){const configured=process.env.ORKAS_BUNDLED_PYTHON||process.env.ORKAS_PYTHON;if(isFile(configured))return configured;const names=process.platform==="win32"?["python.exe",path2.join("python","python.exe")]:[path2.join("python","bin","python3"),path2.join("python","bin","python"),path2.join("bin","python3"),path2.join("bin","python")];for(const dir of runtimeVariantDirs("python")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveUvExecutable(){const configured=process.env.ORKAS_BUNDLED_UV||process.env.ORKAS_UV;if(isFile(configured))return configured;const name=process.platform==="win32"?"uv.exe":"uv";for(const dir of runtimeVariantDirs("uv")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}return void 0}function resolveNodeExecutable(){const configured=process.env.ORKAS_BUNDLED_NODE;if(isFile(configured))return configured;const names=process.platform==="win32"?["node.exe"]:[path2.join("bin","node")];for(const dir of runtimeVariantDirs("node")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function pushPathDir(out,seen,dir){if(!isDir(dir))return;const resolved=path2.resolve(dir);const key=process.platform==="win32"?resolved.toLowerCase():resolved;if(seen.has(key))return;seen.add(key);out.push(resolved)}function bundledRuntimePathEntries(){const entries=[];const seen=new Set;const python=resolvePythonExecutable();if(python){const pythonDir=path2.dirname(python);pushPathDir(entries,seen,pythonDir);pushPathDir(entries,seen,path2.join(pythonDir,"Scripts"));pushPathDir(entries,seen,path2.join(pythonDir,"bin"))}const uv=resolveUvExecutable();if(uv)pushPathDir(entries,seen,path2.dirname(uv));const node=resolveNodeExecutable();if(node)pushPathDir(entries,seen,path2.dirname(node));return entries}function bundledNodeExecutable(){return resolveNodeExecutable()}function bundledNpxCli(){const node=resolveNodeExecutable();if(!node)return void 0;const dir=path2.dirname(node);const candidates=process.platform==="win32"?[path2.join(dir,"node_modules","npm","bin","npx-cli.js")]:[path2.join(dir,"..","lib","node_modules","npm","bin","npx-cli.js")];for(const c of candidates)if(isFile(c))return c;return void 0}function bundledRuntimeEnv(){const env={};const python=resolvePythonExecutable();const uv=resolveUvExecutable();const node=resolveNodeExecutable();if(python)env.ORKAS_PYTHON=python;if(uv)env.ORKAS_UV=uv;if(node)env.ORKAS_BUNDLED_NODE=node;return env}var HYPERFRAMES_SPEC="[email protected]";function resolveHyperframesRunner(){const node=bundledNodeExecutable();const npxCli=bundledNpxCli();if(!node||!npxCli)return null;return{node,npxCli}}function buildHyperframesEnv(){const env={...process.env};const sep2=process.platform==="win32"?";":":";const prepend=[...bundledRuntimePathEntries()];prepend.push(PYTHON_VENV_BIN_DIR);if(prepend.length)env.PATH=[...prepend,env.PATH||""].filter(Boolean).join(sep2);const ff=bundledFfmpegPaths();if(ff.ffmpeg)env.HYPERFRAMES_FFMPEG_PATH=ff.ffmpeg;if(ff.ffprobe)env.HYPERFRAMES_FFPROBE_PATH=ff.ffprobe;for(const dir of[NODE_NPM_CACHE_DIR,NODE_NPM_PREFIX_DIR,NODE_NPM_GLOBAL_BIN_DIR]){try{fs3.mkdirSync(dir,{recursive:true})}catch{}}env.NPM_CONFIG_CACHE=NODE_NPM_CACHE_DIR;env.NPM_CONFIG_PREFIX=NODE_NPM_PREFIX_DIR;env.NPM_CONFIG_FUND="false";env.NPM_CONFIG_AUDIT="false";env.NPM_CONFIG_UPDATE_NOTIFIER="false";env.NPM_CONFIG_PREFER_OFFLINE="true";env.NPM_CONFIG_FETCH_RETRIES="4";return env}var CAPTURE_HEARTBEAT_MS=15e3;function runHyperframesCapture(args,opts){const runner=resolveHyperframesRunner();if(!runner){return Promise.resolve({code:-1,stdout:"",stderr:"E_RUNTIME_MISSING: bundled Node not found",timedOut:false,aborted:false})}const env=buildHyperframesEnv();const fullArgs=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,...args];const timeoutMs=opts.timeoutMs??10*60*1e3;return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,fullArgs,{...opts.cwd?{cwd:opts.cwd}:{},env,...opts.signal?{signal:opts.signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},timeoutMs);const startedAtMs=Date.now();const heartbeat=opts.onHeartbeat?setInterval(()=>opts.onHeartbeat?.(Math.round((Date.now()-startedAtMs)/1e3)),CAPTURE_HEARTBEAT_MS):null;heartbeat?.unref?.();const lineBufs={stdout:"",stderr:""};const pumpLines=(stream,chunk)=>{if(!opts.onLine)return;lineBufs[stream]+=chunk;let nl;while((nl=lineBufs[stream].indexOf("\n"))!==-1){const line=lineBufs[stream].slice(0,nl);lineBufs[stream]=lineBufs[stream].slice(nl+1);try{opts.onLine(line,stream)}catch{}}if(lineBufs[stream].length>64*1024)lineBufs[stream]=lineBufs[stream].slice(-8*1024)};child.stdout?.on("data",c=>{const s=c.toString("utf8");out.push(s);pumpLines("stdout",s)});child.stderr?.on("data",c=>{const s=c.toString("utf8");errChunks.push(s);pumpLines("stderr",s)});child.stdin?.end();child.on("error",err=>{clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);resolve3({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!opts.signal?.aborted})});child.on("close",code=>{clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);resolve3({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!opts.signal?.aborted})})})}var import_node_child_process2=require("node:child_process");function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var isNum=v=>typeof v==="number"&&Number.isFinite(v);var round3=n=>Math.round((isNum(n)?n:0)*1e3)/1e3;function parseSceneChanges(log4){const out=[];let pts=null;for(const line of log4.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){pts=Number(tp[1]);continue}const sc=line.match(/scene_score\s*[:=]\s*([\d.]+)/);if(sc&&pts!==null){const score=Number(sc[1]);out.push({tSec:round3(pts),score:Number.isFinite(score)?round3(score):0});pts=null}}return out}function spanSeconds(spans){return spans.reduce((s,iv)=>s+Math.max(0,iv.endSec-iv.startSec),0)}function parseQualityFrames(log4){const frames=[];let cur=null;for(const line of log4.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){if(cur)frames.push(cur);cur={tSec:round3(Number(tp[1]))};continue}if(!cur)continue;const b=line.match(/lavfi\.blur=\s*([\d.]+)/);if(b){cur.blur=round3(Number(b[1]));continue}const y=line.match(/lavfi\.signalstats\.YAVG=\s*([\d.]+)/);if(y){cur.brightness=round3(Number(y[1]));continue}}if(cur)frames.push(cur);return frames}function parseLabeledIntervals(log4,label){const spans=[];const re=new RegExp(`${label}_(start|end)[:=]\\s*(-?[\\d.]+)`,"g");let openStart=null;let m;while((m=re.exec(log4))!==null){const v=Number(m[2]);if(!Number.isFinite(v))continue;if(m[1]==="start")openStart=v;else if(openStart!==null){spans.push({startSec:round3(Math.max(0,openStart)),endSec:round3(v)});openStart=null}}return spans}function stats(nums){if(!nums.length)return null;const sum=nums.reduce((a,b)=>a+b,0);return{mean:round3(sum/nums.length),min:round3(Math.min(...nums)),max:round3(Math.max(...nums))}}function summarizeQuality(input){const blurT=isNum(input.thresholds?.blur)?input.thresholds.blur:15;const darkBelow=isNum(input.thresholds?.darkBelow)?input.thresholds.darkBelow:50;const brightAbove=isNum(input.thresholds?.brightAbove)?input.thresholds.brightAbove:200;const blur=stats(input.frames.map(f=>f.blur).filter(v=>isNum(v)));const brightness=stats(input.frames.map(f=>f.brightness).filter(v=>isNum(v)));const blackSpans=input.blackSpans??[];const freezeSpans=input.freezeSpans??[];const black_sec=round3(spanSeconds(blackSpans));const freeze_sec=round3(spanSeconds(freezeSpans));const dur=isNum(input.durationSec)&&input.durationSec>0?input.durationSec:0;const flags=[];if(blur&&blur.mean>blurT)flags.push("blurry");if(brightness&&brightness.mean<darkBelow)flags.push("too_dark");if(brightness&&brightness.mean>brightAbove)flags.push("too_bright");if(black_sec>0)flags.push("has_black");if(freeze_sec>0)flags.push("has_freeze");let score=1;if(flags.includes("blurry"))score-=.3;if(flags.includes("too_dark")||flags.includes("too_bright"))score-=.3;if(dur>0){score-=Math.min(.4,black_sec/dur);score-=Math.min(.3,freeze_sec/dur)}score=Math.max(0,Math.min(1,round3(score)));const roundSpans=ss=>ss.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)}));return{durationSec:round3(dur),frames_analyzed:input.frames.length,blur,brightness,black_sec,freeze_sec,black_spans:roundSpans(blackSpans),freeze_spans:roundSpans(freezeSpans),flags,score}}function finiteNum(v){return typeof v==="number"&&Number.isFinite(v)?v:void 0}var log=createLogger("video-edit");var FFMPEG_TIMEOUT_MS=20*60*1e3;var SILENCE_NOISE_DB=-40;var SILENCE_MIN_SEC=.5;var COVERAGE_TRAILING_GAP_SEC=2;var COVERAGE_OVERSHOOT_SEC=.3;var COVERAGE_LEAD_GAP_SEC=3;var RUN_PROGRESS_HEARTBEAT_MS=15e3;var RUN_PROGRESS_MIN_EMIT_MS=2e3;function round2(n){return Math.round((Number.isFinite(n)?n:0)*100)/100}function clamp(n,lo,hi){return Math.min(hi,Math.max(lo,n))}function parseSilenceDetect(stderr,durationSec){const EPS_LEAD=.05;const EPS_TAIL=.3;const tokens=[];const re=/silence_(start|end):\s*(-?[\d.]+)/g;let m;while((m=re.exec(stderr))!==null){const t=Number(m[2]);if(Number.isFinite(t))tokens.push({kind:m[1],t})}const silences=[];let openStart=null;for(const tk of tokens){if(tk.kind==="start"){openStart=tk.t}else if(openStart!==null){silences.push({startSec:Math.max(0,openStart),endSec:tk.t});openStart=null}}const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:silences.length?silences[silences.length-1].endSec:0;if(openStart!==null)silences.push({startSec:Math.max(0,openStart),endSec:dur});const first=silences[0];const last=silences.length?silences[silences.length-1]:void 0;const leadingSilenceSec=first&&first.startSec<=EPS_LEAD?Math.min(first.endSec,dur):0;const trailingSilenceSec=last&&last.endSec>=dur-EPS_TAIL?Math.max(0,dur-last.startSec):0;const totalSilence=silences.reduce((s,iv)=>s+Math.max(0,Math.min(iv.endSec,dur)-iv.startSec),0);const voicedDurationSec=Math.max(0,dur-totalSilence);const voicedStartSec=leadingSilenceSec;const voicedEndSec=Math.max(voicedStartSec,dur-trailingSilenceSec);return{durationSec:dur,voicedStartSec,voicedEndSec,voicedDurationSec,leadingSilenceSec,trailingSilenceSec,silences}}function assessVoiceoverCoverage(input){const ref=Math.max(0,input.referenceDurationSec);const offset=Math.max(0,input.offsetSec??0);const voicedStart=offset+Math.max(0,input.voicedStartSec);const voicedEnd=offset+Math.max(0,input.voicedEndSec);const hasVoice=input.voicedEndSec-input.voicedStartSec>.05&&input.audioDurationSec>.05;const leadingGapSec=round2(voicedStart);const trailingGapSec=round2(ref-voicedEnd);const overshootSec=round2(offset+input.audioDurationSec-ref);const coverageRatio=ref>0?round2(clamp(voicedEnd/ref,0,1)):0;const warnings=[];let status="ok";if(!hasVoice){status="silent";warnings.push("No speech detected in the added audio \u2014 the mux produced a silent or near-silent track.")}else{if(overshootSec>COVERAGE_OVERSHOOT_SEC){status="over";warnings.push(`Narration runs ${overshootSec}s past the ${round2(ref)}s clip and was truncated to fit \u2014 shorten the script so it ends before the clip does (trim the words; do not just raise speed).`)}if(trailingGapSec>COVERAGE_TRAILING_GAP_SEC){if(status==="ok")status="under";const pct=ref>0?Math.round(trailingGapSec/ref*100):0;warnings.push(`Narration ends at ${round2(voicedEnd)}s, leaving ${trailingGapSec}s of silent tail on a ${round2(ref)}s clip (~${pct}% uncovered) \u2014 lengthen the script, add a closing line, or trim the clip to match.`)}if(leadingGapSec>COVERAGE_LEAD_GAP_SEC){warnings.push(`Narration only starts at ${leadingGapSec}s \u2014 long silent lead-in; reduce the offset or trim the head.`)}}return{referenceDurationSec:round2(ref),voicedStartSec:round2(voicedStart),voicedEndSec:round2(voicedEnd),leadingGapSec,trailingGapSec,overshootSec,coverageRatio,status,warnings}}function resolveBins(){const b=bundledFfmpegPaths();if(!b.ffmpeg||!b.ffprobe)return null;return{ffmpeg:b.ffmpeg,ffprobe:b.ffprobe}}function parseProgressClock(raw){if(!raw)return null;const m=raw.trim().match(/^(\d+):(\d{2}):(\d{2}(?:\.\d+)?)$/);if(!m)return null;const h=Number(m[1]);const min=Number(m[2]);const sec=Number(m[3]);if(![h,min,sec].every(Number.isFinite))return null;return h*3600+min*60+sec}function parseFfmpegProgressTimeSec(fields){for(const key of["out_time_us","out_time_ms"]){const raw=fields[key];if(!raw)continue;const micros=Number(raw);if(Number.isFinite(micros)&&micros>=0)return micros/1e6}return parseProgressClock(fields.out_time)}function emitRunProgress(progress,event){const payload={type:"progress",source:"video_edit",op:progress.op,phase:progress.phase??"edit",...event};try{process.stderr.write(`${JSON.stringify(payload)}
-`)}catch{}}function withFfmpegProgress(args){return args.includes("-progress")?args:["-progress","pipe:2",...args]}function run(bin,args,signal,progress){return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process2.spawn)(bin,args,{...signal?{signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const startedAtMs=Date.now();let lastProgressEmitMs=0;let progressFields={};let progressLineBuffer="";const heartbeat=progress?setInterval(()=>{emitRunProgress(progress,{status:"heartbeat",elapsed_sec:round2((Date.now()-startedAtMs)/1e3)})},progress.heartbeatMs??RUN_PROGRESS_HEARTBEAT_MS):null;heartbeat?.unref?.();const emitFfmpegProgress=(status,force=false)=>{if(!progress)return;const now=Date.now();if(!force&&now-lastProgressEmitMs<RUN_PROGRESS_MIN_EMIT_MS)return;lastProgressEmitMs=now;const processedSec=parseFfmpegProgressTimeSec(progressFields);const configuredDurationSec=progress.durationSec;const durationSec=typeof configuredDurationSec==="number"&&Number.isFinite(configuredDurationSec)&&configuredDurationSec>0?configuredDurationSec:null;emitRunProgress(progress,{status:status==="end"?"completed":"running",elapsed_sec:round2((now-startedAtMs)/1e3),...processedSec!==null?{processed_sec:round2(processedSec)}:{},...processedSec!==null&&durationSec?{percent:round2(clamp(processedSec/durationSec*100,0,100))}:{}})};const ingestProgressChunk=text=>{if(!progress)return;progressLineBuffer+=text.replace(/\r/g,"\n");const lines=progressLineBuffer.split("\n");progressLineBuffer=lines.pop()??"";for(const line of lines){const m=line.trim().match(/^([A-Za-z0-9_]+)=(.*)$/);if(!m)continue;progressFields[m[1]]=m[2];if(m[1]==="progress"){emitFfmpegProgress(m[2],m[2]==="end");if(m[2]==="end")progressFields={}}}};const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},FFMPEG_TIMEOUT_MS);let settled=false;const finish=result=>{if(settled)return;settled=true;clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);if(progress&&result.code!==0){emitRunProgress(progress,{status:result.aborted?"aborted":result.timedOut?"timed_out":"failed",elapsed_sec:round2((Date.now()-startedAtMs)/1e3),code:result.code})}resolve3(result)};child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>{const text=c.toString("utf8");errChunks.push(text);ingestProgressChunk(text)});child.stdin?.end();child.on("error",err=>{finish({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!signal?.aborted})});child.on("close",code=>{finish({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!signal?.aborted})})})}function fail(errorCode,message){return{ok:false,errorCode,message}}function ffmpegFailure(op,r){if(r.aborted)return fail("E_EDIT_ABORTED",`${op} aborted.`);if(r.timedOut)return fail("E_EDIT_TIMEOUT",`${op} timed out.`);const tail=r.stderr.trim().slice(-1200);log.warn(`ffmpeg ${op} exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return fail("E_EDIT_FAILED",`${op} failed (exit ${r.code}). ${tail||"No diagnostic output."}`)}async function probeDurationSec(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v=Number(r.stdout.trim());if(Number.isFinite(v)&&v>0)return v;const r2=await run(ffprobe,["-v","error","-select_streams","a:0","-show_entries","stream=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v2=Number(r2.stdout.trim());return Number.isFinite(v2)&&v2>0?v2:0}async function probeMediaDurationSec(inputAbsPath,signal){const bins=resolveBins();if(!bins)return null;const d=await probeDurationSec(bins.ffprobe,inputAbsPath,signal);return d>0?d:null}async function extractFrameAt(inputAbsPath,atSec,outAbsPath,signal){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const at=Number.isFinite(atSec)&&atSec>0?atSec:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",inputAbsPath,"-frames:v","1","-update","1",outAbsPath],signal);if(r.code!==0){const f=ffmpegFailure("extract_frame",r);return{ok:false,errorCode:f.errorCode,message:f.message}}return{ok:true}}async function measureSilenceCoverage(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const noise=opts?.noiseDb??SILENCE_NOISE_DB;const minSec=opts?.minSilenceSec??SILENCE_MIN_SEC;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-af",`silencedetect=noise=${noise}dB:d=${minSec}`,"-f","null","-"]),opts?.signal,{op:"silence_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"silence detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"silence detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg silencedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`silence detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,timing:parseSilenceDetect(r.stderr,dur)}}async function detectSceneChanges(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const th=finiteNum(opts?.threshold);const threshold=th!==void 0&&th>=0&&th<=1?th:.4;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",`select='gt(scene,${threshold})',metadata=print`,"-an","-f","null","-"]),opts?.signal,{op:"scene_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"scene detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"scene detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg scenedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`scene detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,durationSec:dur,threshold,candidates:parseSceneChanges(`${r.stdout}
+var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_analyze_exports={};__export(video_analyze_exports,{analyzeMedia:()=>analyzeMedia,collapseOcrSegments:()=>collapseOcrSegments,sampleTimecodes:()=>sampleTimecodes});module.exports=__toCommonJS(video_analyze_exports);var fs4=__toESM(require("node:fs/promises"));var os=__toESM(require("node:os"));var path4=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var pythonPackageVenvDir=key=>path.join(PYTHON_VENV_ROOT,"packages",key,".venv");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolvePythonExecutable(){const configured=process.env.ORKAS_BUNDLED_PYTHON||process.env.ORKAS_PYTHON;if(isFile(configured))return configured;const names=process.platform==="win32"?["python.exe",path2.join("python","python.exe")]:[path2.join("python","bin","python3"),path2.join("python","bin","python"),path2.join("bin","python3"),path2.join("bin","python")];for(const dir of runtimeVariantDirs("python")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveUvExecutable(){const configured=process.env.ORKAS_BUNDLED_UV||process.env.ORKAS_UV;if(isFile(configured))return configured;const name=process.platform==="win32"?"uv.exe":"uv";for(const dir of runtimeVariantDirs("uv")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}return void 0}function resolveNodeExecutable(){const configured=process.env.ORKAS_BUNDLED_NODE;if(isFile(configured))return configured;const names=process.platform==="win32"?["node.exe"]:[path2.join("bin","node")];for(const dir of runtimeVariantDirs("node")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function bundledRuntimeEnv(){const env={};const python=resolvePythonExecutable();const uv=resolveUvExecutable();const node=resolveNodeExecutable();if(python)env.ORKAS_PYTHON=python;if(uv)env.ORKAS_UV=uv;if(node)env.ORKAS_BUNDLED_NODE=node;return env}function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var isNum=v=>typeof v==="number"&&Number.isFinite(v);var round3=n=>Math.round((isNum(n)?n:0)*1e3)/1e3;function parseSceneChanges(log3){const out=[];let pts=null;for(const line of log3.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){pts=Number(tp[1]);continue}const sc=line.match(/scene_score\s*[:=]\s*([\d.]+)/);if(sc&&pts!==null){const score=Number(sc[1]);out.push({tSec:round3(pts),score:Number.isFinite(score)?round3(score):0});pts=null}}return out}function spanSeconds(spans){return spans.reduce((s,iv)=>s+Math.max(0,iv.endSec-iv.startSec),0)}function parseQualityFrames(log3){const frames=[];let cur=null;for(const line of log3.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){if(cur)frames.push(cur);cur={tSec:round3(Number(tp[1]))};continue}if(!cur)continue;const b=line.match(/lavfi\.blur=\s*([\d.]+)/);if(b){cur.blur=round3(Number(b[1]));continue}const y=line.match(/lavfi\.signalstats\.YAVG=\s*([\d.]+)/);if(y){cur.brightness=round3(Number(y[1]));continue}}if(cur)frames.push(cur);return frames}function parseLabeledIntervals(log3,label){const spans=[];const re=new RegExp(`${label}_(start|end)[:=]\\s*(-?[\\d.]+)`,"g");let openStart=null;let m;while((m=re.exec(log3))!==null){const v=Number(m[2]);if(!Number.isFinite(v))continue;if(m[1]==="start")openStart=v;else if(openStart!==null){spans.push({startSec:round3(Math.max(0,openStart)),endSec:round3(v)});openStart=null}}return spans}function stats(nums){if(!nums.length)return null;const sum=nums.reduce((a,b)=>a+b,0);return{mean:round3(sum/nums.length),min:round3(Math.min(...nums)),max:round3(Math.max(...nums))}}function summarizeQuality(input){const blurT=isNum(input.thresholds?.blur)?input.thresholds.blur:15;const darkBelow=isNum(input.thresholds?.darkBelow)?input.thresholds.darkBelow:50;const brightAbove=isNum(input.thresholds?.brightAbove)?input.thresholds.brightAbove:200;const blur=stats(input.frames.map(f=>f.blur).filter(v=>isNum(v)));const brightness=stats(input.frames.map(f=>f.brightness).filter(v=>isNum(v)));const blackSpans=input.blackSpans??[];const freezeSpans=input.freezeSpans??[];const black_sec=round3(spanSeconds(blackSpans));const freeze_sec=round3(spanSeconds(freezeSpans));const dur=isNum(input.durationSec)&&input.durationSec>0?input.durationSec:0;const flags=[];if(blur&&blur.mean>blurT)flags.push("blurry");if(brightness&&brightness.mean<darkBelow)flags.push("too_dark");if(brightness&&brightness.mean>brightAbove)flags.push("too_bright");if(black_sec>0)flags.push("has_black");if(freeze_sec>0)flags.push("has_freeze");let score=1;if(flags.includes("blurry"))score-=.3;if(flags.includes("too_dark")||flags.includes("too_bright"))score-=.3;if(dur>0){score-=Math.min(.4,black_sec/dur);score-=Math.min(.3,freeze_sec/dur)}score=Math.max(0,Math.min(1,round3(score)));const roundSpans=ss=>ss.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)}));return{durationSec:round3(dur),frames_analyzed:input.frames.length,blur,brightness,black_sec,freeze_sec,black_spans:roundSpans(blackSpans),freeze_spans:roundSpans(freezeSpans),flags,score}}function finiteNum(v){return typeof v==="number"&&Number.isFinite(v)?v:void 0}var log=createLogger("video-edit");var FFMPEG_TIMEOUT_MS=20*60*1e3;var SILENCE_NOISE_DB=-40;var SILENCE_MIN_SEC=.5;var COVERAGE_TRAILING_GAP_SEC=2;var COVERAGE_OVERSHOOT_SEC=.3;var COVERAGE_LEAD_GAP_SEC=3;var RUN_PROGRESS_HEARTBEAT_MS=15e3;var RUN_PROGRESS_MIN_EMIT_MS=2e3;function round2(n){return Math.round((Number.isFinite(n)?n:0)*100)/100}function clamp(n,lo,hi){return Math.min(hi,Math.max(lo,n))}function parseSilenceDetect(stderr,durationSec){const EPS_LEAD=.05;const EPS_TAIL=.3;const tokens=[];const re=/silence_(start|end):\s*(-?[\d.]+)/g;let m;while((m=re.exec(stderr))!==null){const t=Number(m[2]);if(Number.isFinite(t))tokens.push({kind:m[1],t})}const silences=[];let openStart=null;for(const tk of tokens){if(tk.kind==="start"){openStart=tk.t}else if(openStart!==null){silences.push({startSec:Math.max(0,openStart),endSec:tk.t});openStart=null}}const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:silences.length?silences[silences.length-1].endSec:0;if(openStart!==null)silences.push({startSec:Math.max(0,openStart),endSec:dur});const first=silences[0];const last=silences.length?silences[silences.length-1]:void 0;const leadingSilenceSec=first&&first.startSec<=EPS_LEAD?Math.min(first.endSec,dur):0;const trailingSilenceSec=last&&last.endSec>=dur-EPS_TAIL?Math.max(0,dur-last.startSec):0;const totalSilence=silences.reduce((s,iv)=>s+Math.max(0,Math.min(iv.endSec,dur)-iv.startSec),0);const voicedDurationSec=Math.max(0,dur-totalSilence);const voicedStartSec=leadingSilenceSec;const voicedEndSec=Math.max(voicedStartSec,dur-trailingSilenceSec);return{durationSec:dur,voicedStartSec,voicedEndSec,voicedDurationSec,leadingSilenceSec,trailingSilenceSec,silences}}function assessVoiceoverCoverage(input){const ref=Math.max(0,input.referenceDurationSec);const offset=Math.max(0,input.offsetSec??0);const voicedStart=offset+Math.max(0,input.voicedStartSec);const voicedEnd=offset+Math.max(0,input.voicedEndSec);const hasVoice=input.voicedEndSec-input.voicedStartSec>.05&&input.audioDurationSec>.05;const leadingGapSec=round2(voicedStart);const trailingGapSec=round2(ref-voicedEnd);const overshootSec=round2(offset+input.audioDurationSec-ref);const coverageRatio=ref>0?round2(clamp(voicedEnd/ref,0,1)):0;const warnings=[];let status="ok";if(!hasVoice){status="silent";warnings.push("No speech detected in the added audio \u2014 the mux produced a silent or near-silent track.")}else{if(overshootSec>COVERAGE_OVERSHOOT_SEC){status="over";warnings.push(`Narration runs ${overshootSec}s past the ${round2(ref)}s clip and was truncated to fit \u2014 shorten the script so it ends before the clip does (trim the words; do not just raise speed).`)}if(trailingGapSec>COVERAGE_TRAILING_GAP_SEC){if(status==="ok")status="under";const pct=ref>0?Math.round(trailingGapSec/ref*100):0;warnings.push(`Narration ends at ${round2(voicedEnd)}s, leaving ${trailingGapSec}s of silent tail on a ${round2(ref)}s clip (~${pct}% uncovered) \u2014 lengthen the script, add a closing line, or trim the clip to match.`)}if(leadingGapSec>COVERAGE_LEAD_GAP_SEC){warnings.push(`Narration only starts at ${leadingGapSec}s \u2014 long silent lead-in; reduce the offset or trim the head.`)}}return{referenceDurationSec:round2(ref),voicedStartSec:round2(voicedStart),voicedEndSec:round2(voicedEnd),leadingGapSec,trailingGapSec,overshootSec,coverageRatio,status,warnings}}function resolveBins(){const b=bundledFfmpegPaths();if(!b.ffmpeg||!b.ffprobe)return null;return{ffmpeg:b.ffmpeg,ffprobe:b.ffprobe}}function parseProgressClock(raw){if(!raw)return null;const m=raw.trim().match(/^(\d+):(\d{2}):(\d{2}(?:\.\d+)?)$/);if(!m)return null;const h=Number(m[1]);const min=Number(m[2]);const sec=Number(m[3]);if(![h,min,sec].every(Number.isFinite))return null;return h*3600+min*60+sec}function parseFfmpegProgressTimeSec(fields){for(const key of["out_time_us","out_time_ms"]){const raw=fields[key];if(!raw)continue;const micros=Number(raw);if(Number.isFinite(micros)&&micros>=0)return micros/1e6}return parseProgressClock(fields.out_time)}function emitRunProgress(progress,event){const payload={type:"progress",source:"video_edit",op:progress.op,phase:progress.phase??"edit",...event};try{process.stderr.write(`${JSON.stringify(payload)}
+`)}catch{}}function withFfmpegProgress(args){return args.includes("-progress")?args:["-progress","pipe:2",...args]}function run(bin,args,signal,progress){return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(bin,args,{...signal?{signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const startedAtMs=Date.now();let lastProgressEmitMs=0;let progressFields={};let progressLineBuffer="";const heartbeat=progress?setInterval(()=>{emitRunProgress(progress,{status:"heartbeat",elapsed_sec:round2((Date.now()-startedAtMs)/1e3)})},progress.heartbeatMs??RUN_PROGRESS_HEARTBEAT_MS):null;heartbeat?.unref?.();const emitFfmpegProgress=(status,force=false)=>{if(!progress)return;const now=Date.now();if(!force&&now-lastProgressEmitMs<RUN_PROGRESS_MIN_EMIT_MS)return;lastProgressEmitMs=now;const processedSec=parseFfmpegProgressTimeSec(progressFields);const configuredDurationSec=progress.durationSec;const durationSec=typeof configuredDurationSec==="number"&&Number.isFinite(configuredDurationSec)&&configuredDurationSec>0?configuredDurationSec:null;emitRunProgress(progress,{status:status==="end"?"completed":"running",elapsed_sec:round2((now-startedAtMs)/1e3),...processedSec!==null?{processed_sec:round2(processedSec)}:{},...processedSec!==null&&durationSec?{percent:round2(clamp(processedSec/durationSec*100,0,100))}:{}})};const ingestProgressChunk=text=>{if(!progress)return;progressLineBuffer+=text.replace(/\r/g,"\n");const lines=progressLineBuffer.split("\n");progressLineBuffer=lines.pop()??"";for(const line of lines){const m=line.trim().match(/^([A-Za-z0-9_]+)=(.*)$/);if(!m)continue;progressFields[m[1]]=m[2];if(m[1]==="progress"){emitFfmpegProgress(m[2],m[2]==="end");if(m[2]==="end")progressFields={}}}};const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},FFMPEG_TIMEOUT_MS);let settled=false;const finish=result=>{if(settled)return;settled=true;clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);if(progress&&result.code!==0){emitRunProgress(progress,{status:result.aborted?"aborted":result.timedOut?"timed_out":"failed",elapsed_sec:round2((Date.now()-startedAtMs)/1e3),code:result.code})}resolve3(result)};child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>{const text=c.toString("utf8");errChunks.push(text);ingestProgressChunk(text)});child.stdin?.end();child.on("error",err=>{finish({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!signal?.aborted})});child.on("close",code=>{finish({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!signal?.aborted})})})}function fail(errorCode,message){return{ok:false,errorCode,message}}function ffmpegFailure(op,r){if(r.aborted)return fail("E_EDIT_ABORTED",`${op} aborted.`);if(r.timedOut)return fail("E_EDIT_TIMEOUT",`${op} timed out.`);const tail=r.stderr.trim().slice(-1200);log.warn(`ffmpeg ${op} exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return fail("E_EDIT_FAILED",`${op} failed (exit ${r.code}). ${tail||"No diagnostic output."}`)}async function probeDurationSec(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v=Number(r.stdout.trim());if(Number.isFinite(v)&&v>0)return v;const r2=await run(ffprobe,["-v","error","-select_streams","a:0","-show_entries","stream=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v2=Number(r2.stdout.trim());return Number.isFinite(v2)&&v2>0?v2:0}async function probeMediaDurationSec(inputAbsPath,signal){const bins=resolveBins();if(!bins)return null;const d=await probeDurationSec(bins.ffprobe,inputAbsPath,signal);return d>0?d:null}async function extractFrameAt(inputAbsPath,atSec,outAbsPath,signal){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const at=Number.isFinite(atSec)&&atSec>0?atSec:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",inputAbsPath,"-frames:v","1","-update","1",outAbsPath],signal);if(r.code!==0){const f=ffmpegFailure("extract_frame",r);return{ok:false,errorCode:f.errorCode,message:f.message}}return{ok:true}}async function measureSilenceCoverage(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const noise=opts?.noiseDb??SILENCE_NOISE_DB;const minSec=opts?.minSilenceSec??SILENCE_MIN_SEC;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-af",`silencedetect=noise=${noise}dB:d=${minSec}`,"-f","null","-"]),opts?.signal,{op:"silence_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"silence detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"silence detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg silencedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`silence detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,timing:parseSilenceDetect(r.stderr,dur)}}async function detectSceneChanges(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const th=finiteNum(opts?.threshold);const threshold=th!==void 0&&th>=0&&th<=1?th:.4;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",`select='gt(scene,${threshold})',metadata=print`,"-an","-f","null","-"]),opts?.signal,{op:"scene_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"scene detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"scene detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg scenedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`scene detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,durationSec:dur,threshold,candidates:parseSceneChanges(`${r.stdout}
${r.stderr}`)}}async function detectQuality(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const fpsN=finiteNum(opts?.fps);const fps=fpsN!==void 0&&fpsN>0&&fpsN<=30?fpsN:3;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const vf=`fps=${fps},blackdetect=d=0.1:pix_th=0.10,freezedetect=n=0.003:d=0.5,blurdetect,signalstats,metadata=print`;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",vf,"-an","-f","null","-"]),opts?.signal,{op:"quality_scan",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"quality scan aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"quality scan timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg quality scan exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`quality scan failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}const logText=`${r.stdout}
-${r.stderr}`;const report=summarizeQuality({durationSec:dur,frames:parseQualityFrames(logText),blackSpans:parseLabeledIntervals(logText,"black"),freezeSpans:parseLabeledIntervals(logText,"freeze"),...opts?.thresholds?{thresholds:opts.thresholds}:{}});return{ok:true,report}}var fs4=__toESM(require("node:fs"));var path3=__toESM(require("node:path"));var import_node_child_process3=require("node:child_process");var import_node_util=require("node:util");var execFileAsync=(0,import_node_util.promisify)(import_node_child_process3.execFile);var log2=createLogger("ocr-runtime");var OCR_RUNTIME_KEY=`ocr-rapidocr-3.9.0-onnxruntime-1.27.0-pypdfium2-5.10.1-${process.platform}-${process.arch}`;var RAPIDOCR_VERSION="3.9.0";var ONNXRUNTIME_VERSION="1.27.0";var PYPDFIUM2_VERSION="5.10.1";var OCR_TIMEOUT_MS=5*60*1e3;var INSTALL_TIMEOUT_MS=10*60*1e3;var VERIFY_TIMEOUT_MS=2*60*1e3;var OCR_PROGRESS_HEARTBEAT_MS=3e4;function venvDir(){return pythonPackageVenvDir(OCR_RUNTIME_KEY)}function venvPython(venv=venvDir()){return process.platform==="win32"?path3.join(venv,"Scripts","python.exe"):path3.join(venv,"bin","python")}function isFile2(p){try{return fs4.statSync(p).isFile()}catch{return false}}function sentinelPath(venv){return path3.join(venv,".orkas-ocr-verified")}function sentinelMatches(venv){try{return fs4.readFileSync(sentinelPath(venv),"utf8").trim()===OCR_RUNTIME_KEY}catch{return false}}function writeSentinel(venv){try{fs4.writeFileSync(sentinelPath(venv),`${OCR_RUNTIME_KEY}
+${r.stderr}`;const report=summarizeQuality({durationSec:dur,frames:parseQualityFrames(logText),blackSpans:parseLabeledIntervals(logText,"black"),freezeSpans:parseLabeledIntervals(logText,"freeze"),...opts?.thresholds?{thresholds:opts.thresholds}:{}});return{ok:true,report}}var fs3=__toESM(require("node:fs"));var path3=__toESM(require("node:path"));var import_node_child_process2=require("node:child_process");var import_node_util=require("node:util");var execFileAsync=(0,import_node_util.promisify)(import_node_child_process2.execFile);var log2=createLogger("ocr-runtime");var OCR_RUNTIME_KEY=`ocr-rapidocr-3.9.0-onnxruntime-1.27.0-pypdfium2-5.10.1-${process.platform}-${process.arch}`;var RAPIDOCR_VERSION="3.9.0";var ONNXRUNTIME_VERSION="1.27.0";var PYPDFIUM2_VERSION="5.10.1";var OCR_TIMEOUT_MS=5*60*1e3;var INSTALL_TIMEOUT_MS=10*60*1e3;var VERIFY_TIMEOUT_MS=2*60*1e3;var OCR_PROGRESS_HEARTBEAT_MS=3e4;function venvDir(){return pythonPackageVenvDir(OCR_RUNTIME_KEY)}function venvPython(venv=venvDir()){return process.platform==="win32"?path3.join(venv,"Scripts","python.exe"):path3.join(venv,"bin","python")}function isFile2(p){try{return fs3.statSync(p).isFile()}catch{return false}}function sentinelPath(venv){return path3.join(venv,".orkas-ocr-verified")}function sentinelMatches(venv){try{return fs3.readFileSync(sentinelPath(venv),"utf8").trim()===OCR_RUNTIME_KEY}catch{return false}}function writeSentinel(venv){try{fs3.writeFileSync(sentinelPath(venv),`${OCR_RUNTIME_KEY}
`)}catch{}}function runtimeEnv(){return{...process.env,...bundledRuntimeEnv(),PYTHONNOUSERSITE:"1",UV_CACHE_DIR:PYTHON_VENV_UV_CACHE_DIR,PIP_CACHE_DIR:PYTHON_VENV_PIP_CACHE_DIR}}async function withHeartbeat(promise,onProgress,phase,heartbeatMessage){let tick=0;const timer=onProgress?setInterval(()=>{tick+=1;onProgress({phase,message:heartbeatMessage,data:{heartbeat:true,seconds:tick*(OCR_PROGRESS_HEARTBEAT_MS/1e3)}})},OCR_PROGRESS_HEARTBEAT_MS):null;try{return await promise}finally{if(timer)clearInterval(timer)}}var VERIFY_RUNTIME_SCRIPT=String.raw`
import pathlib
import pypdfium2
@@ -12,7 +12,7 @@ from rapidocr import RapidOCR
model_dir = pathlib.Path(rapidocr_pkg.__file__).resolve().parent / "models"
RapidOCR(params={"Global.model_root_dir": str(model_dir)})
print("ok")
-`;async function verifyRuntime(python,onProgress){if(!isFile2(python))return{ok:false,message:`Python executable is missing: ${python}`};try{await withHeartbeat(execFileAsync(python,["-c",VERIFY_RUNTIME_SCRIPT],{timeout:VERIFY_TIMEOUT_MS,env:runtimeEnv(),windowsHide:true,maxBuffer:2*1024*1024}),onProgress,"ocr_runtime_verify","Still checking local OCR runtime");return{ok:true}}catch(err){return{ok:false,message:err.message}}}async function ensureRuntime(onProgress){const venv=venvDir();const python=venvPython(venv);if(isFile2(python)&&sentinelMatches(venv)){onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime is ready"});return{ok:true,python,venv,installed:false}}onProgress?.({phase:"ocr_runtime_check",message:"Checking local OCR runtime"});const existingVerification=await verifyRuntime(python,onProgress);if(existingVerification.ok===true){writeSentinel(venv);onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime is ready"});return{ok:true,python,venv,installed:false}}const env=runtimeEnv();const uv=env.ORKAS_UV;const bundledPython=env.ORKAS_PYTHON;if(!uv||!bundledPython){onProgress?.({phase:"ocr_runtime_missing",message:"Bundled Python/uv runtime is unavailable"});return{ok:false,errorCode:"E_OCR_RUNTIME_MISSING",message:"Bundled Python/uv runtime is unavailable, so Local OCR cannot be installed on this build."}}try{fs4.mkdirSync(path3.dirname(venv),{recursive:true});onProgress?.({phase:"ocr_runtime_install",message:"Creating local OCR Python environment",data:{runtimePath:venv}});await withHeartbeat(execFileAsync(uv,["venv","--python",bundledPython,venv],{timeout:INSTALL_TIMEOUT_MS,env,windowsHide:true,maxBuffer:1024*1024}),onProgress,"ocr_runtime_install","Still creating local OCR Python environment");onProgress?.({phase:"ocr_runtime_install",message:"Downloading and installing local OCR packages",data:{packages:[`rapidocr==${RAPIDOCR_VERSION}`,`onnxruntime==${ONNXRUNTIME_VERSION}`,`pypdfium2==${PYPDFIUM2_VERSION}`]}});await withHeartbeat(execFileAsync(uv,["pip","install","--python",venvPython(venv),"--only-binary=:all:",`rapidocr==${RAPIDOCR_VERSION}`,`onnxruntime==${ONNXRUNTIME_VERSION}`,`pypdfium2==${PYPDFIUM2_VERSION}`],{timeout:INSTALL_TIMEOUT_MS,env,windowsHide:true,maxBuffer:4*1024*1024}),onProgress,"ocr_runtime_install","Still installing local OCR packages");onProgress?.({phase:"ocr_runtime_verify",message:"Verifying local OCR runtime"})}catch(err){log2.warn(`install failed: ${err.message}`);onProgress?.({phase:"ocr_runtime_install_failed",message:"Local OCR runtime install failed",data:{error:err.message}});return{ok:false,errorCode:"E_OCR_INSTALL_FAILED",message:`Local OCR runtime install failed: ${err.message}`}}const installedVerification=await verifyRuntime(python,onProgress);if(installedVerification.ok===true){writeSentinel(venv);onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime installed and ready"});return{ok:true,python,venv,installed:true}}onProgress?.({phase:"ocr_runtime_install_failed",message:"Local OCR runtime verification failed"});return{ok:false,errorCode:"E_OCR_INSTALL_FAILED",message:`Local OCR runtime installed, but verification failed: ${installedVerification.message}`}}async function runOcrProcess(python,payload,onProgress,signal,timeoutMs=OCR_TIMEOUT_MS){const res=await withHeartbeat(execFileAsync(python,["-c",PYTHON_OCR_SCRIPT,payload],{timeout:timeoutMs,env:runtimeEnv(),windowsHide:true,maxBuffer:8*1024*1024,...signal?{signal}:{}}),onProgress,"ocr_run","Still running local OCR");return res.stdout}function extKind(absPath){const ext=path3.extname(absPath).toLowerCase();if(ext===".pdf")return"pdf";if([".png",".jpg",".jpeg",".webp",".gif"].includes(ext))return"image";return"unsupported"}async function ocrImageText(input){if(extKind(input.absPath)!=="image"){return{ok:false,errorCode:"E_OCR_UNSUPPORTED_FILE",message:`ocrImageText needs an image file: ${input.absPath}`}}const runtime=await ensureRuntime(input.onProgress);if(runtime.ok===false){return{ok:false,errorCode:runtime.errorCode,message:runtime.message}}const payload=JSON.stringify({path:input.absPath,kind:"image",pages:"",scale:2});let stdout="";try{stdout=await runOcrProcess(runtime.python,payload,input.onProgress,input.signal)}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR failed: ${err.message}`}}try{const parsed=JSON.parse(stdout);if(!parsed?.ok){return{ok:false,errorCode:"E_OCR_FAILED",message:String(parsed?.error||"Local OCR failed")}}const page=parsed.pages&&parsed.pages[0]||{};return{ok:true,text:String(page.text||"").trim(),items:Array.isArray(page.items)?page.items:[]}}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR returned invalid output: ${err.message}`}}}async function ocrImagesText(input){if(!input.absPaths.length)return{ok:true,results:[]};const bad=input.absPaths.find(p=>extKind(p)!=="image");if(bad){return{ok:false,errorCode:"E_OCR_UNSUPPORTED_FILE",message:`ocrImagesText needs image files: ${bad}`}}const runtime=await ensureRuntime(input.onProgress);if(runtime.ok===false){return{ok:false,errorCode:runtime.errorCode,message:runtime.message}}const payload=JSON.stringify({paths:input.absPaths,kind:"images",pages:"",scale:2});const timeoutMs=Math.max(OCR_TIMEOUT_MS,6e4+1e4*input.absPaths.length);let stdout="";try{stdout=await runOcrProcess(runtime.python,payload,input.onProgress,input.signal,timeoutMs)}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR failed: ${err.message}`}}try{const parsed=JSON.parse(stdout);if(!parsed?.ok){return{ok:false,errorCode:"E_OCR_FAILED",message:String(parsed?.error||"Local OCR failed")}}const pages=Array.isArray(parsed.pages)?parsed.pages:[];const results=input.absPaths.map((_,i)=>{const page=pages[i]||{};return{text:String(page.text||"").trim(),items:Array.isArray(page.items)?page.items:[],...page.error?{error:String(page.error)}:{}}});return{ok:true,results}}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR returned invalid output: ${err.message}`}}}var PYTHON_OCR_SCRIPT=String.raw`
+`;async function verifyRuntime(python,onProgress){if(!isFile2(python))return{ok:false,message:`Python executable is missing: ${python}`};try{await withHeartbeat(execFileAsync(python,["-c",VERIFY_RUNTIME_SCRIPT],{timeout:VERIFY_TIMEOUT_MS,env:runtimeEnv(),windowsHide:true,maxBuffer:2*1024*1024}),onProgress,"ocr_runtime_verify","Still checking local OCR runtime");return{ok:true}}catch(err){return{ok:false,message:err.message}}}async function ensureRuntime(onProgress){const venv=venvDir();const python=venvPython(venv);if(isFile2(python)&&sentinelMatches(venv)){onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime is ready"});return{ok:true,python,venv,installed:false}}onProgress?.({phase:"ocr_runtime_check",message:"Checking local OCR runtime"});const existingVerification=await verifyRuntime(python,onProgress);if(existingVerification.ok===true){writeSentinel(venv);onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime is ready"});return{ok:true,python,venv,installed:false}}const env=runtimeEnv();const uv=env.ORKAS_UV;const bundledPython=env.ORKAS_PYTHON;if(!uv||!bundledPython){onProgress?.({phase:"ocr_runtime_missing",message:"Bundled Python/uv runtime is unavailable"});return{ok:false,errorCode:"E_OCR_RUNTIME_MISSING",message:"Bundled Python/uv runtime is unavailable, so Local OCR cannot be installed on this build."}}try{fs3.mkdirSync(path3.dirname(venv),{recursive:true});onProgress?.({phase:"ocr_runtime_install",message:"Creating local OCR Python environment",data:{runtimePath:venv}});await withHeartbeat(execFileAsync(uv,["venv","--python",bundledPython,venv],{timeout:INSTALL_TIMEOUT_MS,env,windowsHide:true,maxBuffer:1024*1024}),onProgress,"ocr_runtime_install","Still creating local OCR Python environment");onProgress?.({phase:"ocr_runtime_install",message:"Downloading and installing local OCR packages",data:{packages:[`rapidocr==${RAPIDOCR_VERSION}`,`onnxruntime==${ONNXRUNTIME_VERSION}`,`pypdfium2==${PYPDFIUM2_VERSION}`]}});await withHeartbeat(execFileAsync(uv,["pip","install","--python",venvPython(venv),"--only-binary=:all:",`rapidocr==${RAPIDOCR_VERSION}`,`onnxruntime==${ONNXRUNTIME_VERSION}`,`pypdfium2==${PYPDFIUM2_VERSION}`],{timeout:INSTALL_TIMEOUT_MS,env,windowsHide:true,maxBuffer:4*1024*1024}),onProgress,"ocr_runtime_install","Still installing local OCR packages");onProgress?.({phase:"ocr_runtime_verify",message:"Verifying local OCR runtime"})}catch(err){log2.warn(`install failed: ${err.message}`);onProgress?.({phase:"ocr_runtime_install_failed",message:"Local OCR runtime install failed",data:{error:err.message}});return{ok:false,errorCode:"E_OCR_INSTALL_FAILED",message:`Local OCR runtime install failed: ${err.message}`}}const installedVerification=await verifyRuntime(python,onProgress);if(installedVerification.ok===true){writeSentinel(venv);onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime installed and ready"});return{ok:true,python,venv,installed:true}}onProgress?.({phase:"ocr_runtime_install_failed",message:"Local OCR runtime verification failed"});return{ok:false,errorCode:"E_OCR_INSTALL_FAILED",message:`Local OCR runtime installed, but verification failed: ${installedVerification.message}`}}async function runOcrProcess(python,payload,onProgress,signal,timeoutMs=OCR_TIMEOUT_MS){const res=await withHeartbeat(execFileAsync(python,["-c",PYTHON_OCR_SCRIPT,payload],{timeout:timeoutMs,env:runtimeEnv(),windowsHide:true,maxBuffer:8*1024*1024,...signal?{signal}:{}}),onProgress,"ocr_run","Still running local OCR");return res.stdout}function extKind(absPath){const ext=path3.extname(absPath).toLowerCase();if(ext===".pdf")return"pdf";if([".png",".jpg",".jpeg",".webp",".gif"].includes(ext))return"image";return"unsupported"}async function ocrImageText(input){if(extKind(input.absPath)!=="image"){return{ok:false,errorCode:"E_OCR_UNSUPPORTED_FILE",message:`ocrImageText needs an image file: ${input.absPath}`}}const runtime=await ensureRuntime(input.onProgress);if(runtime.ok===false){return{ok:false,errorCode:runtime.errorCode,message:runtime.message}}const payload=JSON.stringify({path:input.absPath,kind:"image",pages:"",scale:2});let stdout="";try{stdout=await runOcrProcess(runtime.python,payload,input.onProgress,input.signal)}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR failed: ${err.message}`}}try{const parsed=JSON.parse(stdout);if(!parsed?.ok){return{ok:false,errorCode:"E_OCR_FAILED",message:String(parsed?.error||"Local OCR failed")}}const page=parsed.pages&&parsed.pages[0]||{};return{ok:true,text:String(page.text||"").trim(),items:Array.isArray(page.items)?page.items:[]}}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR returned invalid output: ${err.message}`}}}async function ocrImagesText(input){if(!input.absPaths.length)return{ok:true,results:[]};const bad=input.absPaths.find(p=>extKind(p)!=="image");if(bad){return{ok:false,errorCode:"E_OCR_UNSUPPORTED_FILE",message:`ocrImagesText needs image files: ${bad}`}}const runtime=await ensureRuntime(input.onProgress);if(runtime.ok===false){return{ok:false,errorCode:runtime.errorCode,message:runtime.message}}const payload=JSON.stringify({paths:input.absPaths,kind:"images",pages:"",scale:2});const timeoutMs=Math.max(OCR_TIMEOUT_MS,6e4+1e4*input.absPaths.length);let stdout="";try{stdout=await runOcrProcess(runtime.python,payload,input.onProgress,input.signal,timeoutMs)}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR failed: ${err.message}`}}try{const parsed=JSON.parse(stdout);if(!parsed?.ok){return{ok:false,errorCode:"E_OCR_FAILED",message:String(parsed?.error||"Local OCR failed")}}const pages=Array.isArray(parsed.pages)?parsed.pages:[];const results=input.absPaths.map((_,i)=>{const page=pages[i]||{};return{text:String(page.text||"").trim(),items:Array.isArray(page.items)?page.items:[],...page.error?{error:String(page.error)}:{}}});return{ok:true,results}}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR returned invalid output: ${err.message}`}}}var PYTHON_OCR_SCRIPT=String.raw`
import json, os, pathlib, sys, tempfile, traceback
def load_engine():
@@ -159,5 +159,5 @@ try:
main()
except Exception as exc:
print(json.dumps({"ok": False, "error": str(exc), "trace": traceback.format_exc()}, ensure_ascii=False))
-`;var log3=createLogger("video-analyze");var round22=n=>Math.round((Number.isFinite(n)?n:0)*100)/100;var TRANSCRIBE_LINE_EMIT_MIN_MS=3e3;function emitAnalyzeProgress(op,event){const payload={type:"progress",source:"video_analyze",op,phase:op,...event};try{process.stderr.write(`${JSON.stringify(payload)}
-`)}catch{}}var IMAGE_EXTS=new Set([".png",".jpg",".jpeg",".webp",".gif",".bmp"]);var VIDEO_EXTS=new Set([".mp4",".mov",".mkv",".webm",".avi",".m4v"]);function ocrInputKind(p){const ext=path4.extname(p).toLowerCase();if(IMAGE_EXTS.has(ext))return"image";if(VIDEO_EXTS.has(ext))return"video";return"unsupported"}function sampleTimecodes(durationSec,intervalSec,maxFrames){const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:0;if(dur<=0)return[0];const cap=Math.max(1,Math.min(Math.floor(Number.isFinite(maxFrames)&&maxFrames>0?maxFrames:16),60));const desired=Math.max(.5,Number.isFinite(intervalSec)&&intervalSec>0?intervalSec:2.5);const step=Math.max(desired,dur/cap);const out=[];for(let t=step/2;t<dur&&out.length<cap;t+=step){out.push(round22(t))}if(!out.length)out.push(round22(dur/2));return out}function collapseOcrSegments(frames,durationSec){const norm=s=>s.replace(/\s+/g," ").trim();const segs=[];for(const f of frames){const prev=segs[segs.length-1];if(prev&&norm(prev.text)===norm(f.text))prev.endSec=f.tSec;else segs.push({startSec:f.tSec,endSec:f.tSec,text:f.text})}for(let i=0;i<segs.length;i++){const next=segs[i+1];segs[i].startSec=round22(i===0?0:segs[i].startSec);segs[i].endSec=round22(next?next.startSec:Math.max(segs[i].endSec,durationSec))}return segs}async function analyzeMedia(p){const st=await fs5.stat(p.inputAbsPath).catch(()=>null);if(!st||!st.isFile()){return{ok:false,errorCode:"E_ANALYZE_NO_INPUT",message:`input is not a file: ${p.inputAbsPath}`}}if(p.op==="silence"){const meas=await measureSilenceCoverage(p.inputAbsPath,p.signal?{signal:p.signal}:{});if(meas.ok===false)return{ok:false,errorCode:meas.errorCode,message:meas.message};const t=meas.timing;const coverage=assessVoiceoverCoverage({referenceDurationSec:t.durationSec,offsetSec:0,audioDurationSec:t.durationSec,voicedStartSec:t.voicedStartSec,voicedEndSec:t.voicedEndSec});const summary={op:"silence",durationSec:round22(t.durationSec),voicedStartSec:round22(t.voicedStartSec),voicedEndSec:round22(t.voicedEndSec),voicedDurationSec:round22(t.voicedDurationSec),leadingSilenceSec:round22(t.leadingSilenceSec),trailingSilenceSec:round22(t.trailingSilenceSec),silences:t.silences.map(s=>({startSec:round22(s.startSec),endSec:round22(s.endSec)})),coverage};return{ok:true,op:"silence",summary}}if(p.op==="scenes"){const r=await detectSceneChanges(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...typeof p.threshold==="number"?{threshold:p.threshold}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"scenes",summary:{op:"scenes",durationSec:round22(r.durationSec),threshold:r.threshold,count:r.candidates.length,candidates:r.candidates.map(c=>({tSec:round22(c.tSec),score:c.score}))}}}if(p.op==="quality"){const r=await detectQuality(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...p.qualityThresholds?{thresholds:p.qualityThresholds}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"quality",summary:{op:"quality",...r.report}}}if(p.op==="transcribe"){const args=["transcribe",p.inputAbsPath,"--json"];if(p.model)args.push("--model",p.model);let lastLineEmitMs=0;const r=await runHyperframesCapture(args,{cwd:path4.dirname(p.inputAbsPath),...p.signal?{signal:p.signal}:{},timeoutMs:45*60*1e3,onHeartbeat:elapsedSec=>emitAnalyzeProgress("transcribe",{status:"heartbeat",elapsed_sec:elapsedSec}),onLine:(line,stream)=>{if(stream!=="stderr")return;const text=line.trim();if(!text)return;const now=Date.now();if(now-lastLineEmitMs<TRANSCRIBE_LINE_EMIT_MIN_MS)return;lastLineEmitMs=now;emitAnalyzeProgress("transcribe",{status:"output",detail:redactPaths(text).slice(0,200)})}});if(r.aborted)return{ok:false,errorCode:"E_ANALYZE_ABORTED",message:"transcribe aborted."};if(r.timedOut)return{ok:false,errorCode:"E_ANALYZE_TIMEOUT",message:"transcribe timed out."};const out=r.stdout.trim();if(out){try{const parsed=JSON.parse(out);if(parsed&&parsed.ok===false){return{ok:false,errorCode:"E_ANALYZE_FAILED",message:String(parsed.error??"transcribe failed")}}return{ok:true,op:"transcribe",summary:parsed}}catch{}}if(r.code!==0){const tail=r.stderr.trim().slice(-1e3);log3.warn(`hyperframes transcribe exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_ANALYZE_FAILED",message:`transcribe failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:false,errorCode:"E_ANALYZE_NO_OUTPUT",message:"transcribe produced no parseable output."}}if(p.op==="ocr"){const kind=ocrInputKind(p.inputAbsPath);if(kind==="unsupported"){return{ok:false,errorCode:"E_ANALYZE_ARG",message:`ocr input must be an image or video: ${p.inputAbsPath}`}}if(kind==="image"){const r=await ocrImageText({absPath:p.inputAbsPath,...p.signal?{signal:p.signal}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"ocr",summary:{op:"ocr",engine:"local:rapidocr-onnxruntime",kind:"image",text:r.text}}}const durationSec=await probeMediaDurationSec(p.inputAbsPath,p.signal)??0;if(durationSec<=0){return{ok:false,errorCode:"E_ANALYZE_FAILED",message:"could not probe video duration for frame sampling."}}const times=sampleTimecodes(durationSec,p.intervalSec??2.5,p.maxFrames??16);const tmp=await fs5.mkdtemp(path4.join(os.tmpdir(),"orkas-ocr-"));try{let firstErr=null;const extracted=[];for(const t of times){if(p.signal?.aborted)return{ok:false,errorCode:"E_ANALYZE_ABORTED",message:"ocr aborted."};const out=path4.join(tmp,`f-${Math.round(t*1e3)}.png`);const ex=await extractFrameAt(p.inputAbsPath,t,out,p.signal);if(ex.ok===false){if(!firstErr)firstErr=ex;continue}extracted.push({tSec:t,framePath:out})}if(!extracted.length){return{ok:false,errorCode:firstErr?.errorCode??"E_ANALYZE_FAILED",message:firstErr?.message??"ocr produced no frames."}}emitAnalyzeProgress("ocr",{status:"ocr_batch",frames:extracted.length});const batch=await ocrImagesText({absPaths:extracted.map(f=>f.framePath),...p.signal?{signal:p.signal}:{},onProgress:ev=>emitAnalyzeProgress("ocr",{status:ev.phase,...ev.message?{detail:ev.message}:{}})});if(batch.ok===false){return{ok:false,errorCode:batch.errorCode,message:batch.message}}const frames=[];for(let i=0;i<extracted.length;i++){const r=batch.results[i];if(!r||r.error){if(!firstErr&&r?.error)firstErr={errorCode:"E_OCR_FAILED",message:r.error};continue}frames.push({tSec:extracted[i].tSec,text:r.text})}if(!frames.length){return{ok:false,errorCode:firstErr?.errorCode??"E_ANALYZE_FAILED",message:firstErr?.message??"ocr produced no frames."}}const segments=collapseOcrSegments(frames,durationSec);return{ok:true,op:"ocr",summary:{op:"ocr",engine:"local:rapidocr-onnxruntime",kind:"video",durationSec:round22(durationSec),sampledFrames:frames.length,segments}}}finally{await fs5.rm(tmp,{recursive:true,force:true}).catch(()=>{})}}return{ok:false,errorCode:"E_ANALYZE_ARG",message:`unknown op: ${String(p.op)}`}}0&&(module.exports={analyzeMedia,collapseOcrSegments,sampleTimecodes});
+`;var round22=n=>Math.round((Number.isFinite(n)?n:0)*100)/100;function emitAnalyzeProgress(op,event){const payload={type:"progress",source:"video_analyze",op,phase:op,...event};try{process.stderr.write(`${JSON.stringify(payload)}
+`)}catch{}}var IMAGE_EXTS=new Set([".png",".jpg",".jpeg",".webp",".gif",".bmp"]);var VIDEO_EXTS=new Set([".mp4",".mov",".mkv",".webm",".avi",".m4v"]);function ocrInputKind(p){const ext=path4.extname(p).toLowerCase();if(IMAGE_EXTS.has(ext))return"image";if(VIDEO_EXTS.has(ext))return"video";return"unsupported"}function sampleTimecodes(durationSec,intervalSec,maxFrames){const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:0;if(dur<=0)return[0];const cap=Math.max(1,Math.min(Math.floor(Number.isFinite(maxFrames)&&maxFrames>0?maxFrames:16),60));const desired=Math.max(.5,Number.isFinite(intervalSec)&&intervalSec>0?intervalSec:2.5);const step=Math.max(desired,dur/cap);const out=[];for(let t=step/2;t<dur&&out.length<cap;t+=step){out.push(round22(t))}if(!out.length)out.push(round22(dur/2));return out}function collapseOcrSegments(frames,durationSec){const norm=s=>s.replace(/\s+/g," ").trim();const segs=[];for(const f of frames){const prev=segs[segs.length-1];if(prev&&norm(prev.text)===norm(f.text))prev.endSec=f.tSec;else segs.push({startSec:f.tSec,endSec:f.tSec,text:f.text})}for(let i=0;i<segs.length;i++){const next=segs[i+1];segs[i].startSec=round22(i===0?0:segs[i].startSec);segs[i].endSec=round22(next?next.startSec:Math.max(segs[i].endSec,durationSec))}return segs}async function analyzeMedia(p){const st=await fs4.stat(p.inputAbsPath).catch(()=>null);if(!st||!st.isFile()){return{ok:false,errorCode:"E_ANALYZE_NO_INPUT",message:`input is not a file: ${p.inputAbsPath}`}}if(p.op==="silence"){const meas=await measureSilenceCoverage(p.inputAbsPath,p.signal?{signal:p.signal}:{});if(meas.ok===false)return{ok:false,errorCode:meas.errorCode,message:meas.message};const t=meas.timing;const coverage=assessVoiceoverCoverage({referenceDurationSec:t.durationSec,offsetSec:0,audioDurationSec:t.durationSec,voicedStartSec:t.voicedStartSec,voicedEndSec:t.voicedEndSec});const summary={op:"silence",durationSec:round22(t.durationSec),voicedStartSec:round22(t.voicedStartSec),voicedEndSec:round22(t.voicedEndSec),voicedDurationSec:round22(t.voicedDurationSec),leadingSilenceSec:round22(t.leadingSilenceSec),trailingSilenceSec:round22(t.trailingSilenceSec),silences:t.silences.map(s=>({startSec:round22(s.startSec),endSec:round22(s.endSec)})),coverage};return{ok:true,op:"silence",summary}}if(p.op==="scenes"){const r=await detectSceneChanges(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...typeof p.threshold==="number"?{threshold:p.threshold}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"scenes",summary:{op:"scenes",durationSec:round22(r.durationSec),threshold:r.threshold,count:r.candidates.length,candidates:r.candidates.map(c=>({tSec:round22(c.tSec),score:c.score}))}}}if(p.op==="quality"){const r=await detectQuality(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...p.qualityThresholds?{thresholds:p.qualityThresholds}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"quality",summary:{op:"quality",...r.report}}}if(p.op==="ocr"){const kind=ocrInputKind(p.inputAbsPath);if(kind==="unsupported"){return{ok:false,errorCode:"E_ANALYZE_ARG",message:`ocr input must be an image or video: ${p.inputAbsPath}`}}if(kind==="image"){const r=await ocrImageText({absPath:p.inputAbsPath,...p.signal?{signal:p.signal}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"ocr",summary:{op:"ocr",engine:"local:rapidocr-onnxruntime",kind:"image",text:r.text}}}const durationSec=await probeMediaDurationSec(p.inputAbsPath,p.signal)??0;if(durationSec<=0){return{ok:false,errorCode:"E_ANALYZE_FAILED",message:"could not probe video duration for frame sampling."}}const times=sampleTimecodes(durationSec,p.intervalSec??2.5,p.maxFrames??16);const tmp=await fs4.mkdtemp(path4.join(os.tmpdir(),"orkas-ocr-"));try{let firstErr=null;const extracted=[];for(const t of times){if(p.signal?.aborted)return{ok:false,errorCode:"E_ANALYZE_ABORTED",message:"ocr aborted."};const out=path4.join(tmp,`f-${Math.round(t*1e3)}.png`);const ex=await extractFrameAt(p.inputAbsPath,t,out,p.signal);if(ex.ok===false){if(!firstErr)firstErr=ex;continue}extracted.push({tSec:t,framePath:out})}if(!extracted.length){return{ok:false,errorCode:firstErr?.errorCode??"E_ANALYZE_FAILED",message:firstErr?.message??"ocr produced no frames."}}emitAnalyzeProgress("ocr",{status:"ocr_batch",frames:extracted.length});const batch=await ocrImagesText({absPaths:extracted.map(f=>f.framePath),...p.signal?{signal:p.signal}:{},onProgress:ev=>emitAnalyzeProgress("ocr",{status:ev.phase,...ev.message?{detail:ev.message}:{}})});if(batch.ok===false){return{ok:false,errorCode:batch.errorCode,message:batch.message}}const frames=[];for(let i=0;i<extracted.length;i++){const r=batch.results[i];if(!r||r.error){if(!firstErr&&r?.error)firstErr={errorCode:"E_OCR_FAILED",message:r.error};continue}frames.push({tSec:extracted[i].tSec,text:r.text})}if(!frames.length){return{ok:false,errorCode:firstErr?.errorCode??"E_ANALYZE_FAILED",message:firstErr?.message??"ocr produced no frames."}}const segments=collapseOcrSegments(frames,durationSec);return{ok:true,op:"ocr",summary:{op:"ocr",engine:"local:rapidocr-onnxruntime",kind:"video",durationSec:round22(durationSec),sampledFrames:frames.length,segments}}}finally{await fs4.rm(tmp,{recursive:true,force:true}).catch(()=>{})}}return{ok:false,errorCode:"E_ANALYZE_ARG",message:`unknown op: ${String(p.op)}`}}0&&(module.exports={analyzeMedia,collapseOcrSegments,sampleTimecodes});
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_edit_core.cjs b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_edit_core.cjs
index d3e1783a..3938287d 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_edit_core.cjs
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_edit_core.cjs
@@ -1,4 +1,4 @@
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_edit_exports={};__export(video_edit_exports,{assessVoiceoverCoverage:()=>assessVoiceoverCoverage,buildMixFilter:()=>buildMixFilter,detectQuality:()=>detectQuality,detectSceneChanges:()=>detectSceneChanges,editVideo:()=>editVideo,escapeFfmpegFilterValue:()=>escapeFfmpegFilterValue,extractFrameAt:()=>extractFrameAt,mapWithConcurrencyLimit:()=>mapWithConcurrencyLimit,measureSilenceCoverage:()=>measureSilenceCoverage,parseEbur128Summary:()=>parseEbur128Summary,parseFfmpegProgressTimeSec:()=>parseFfmpegProgressTimeSec,parseSilenceDetect:()=>parseSilenceDetect,probeMediaDurationSec:()=>probeMediaDurationSec,validateTrimRequest:()=>validateTrimRequest});module.exports=__toCommonJS(video_edit_exports);var fs3=__toESM(require("node:fs/promises"));var os=__toESM(require("node:os"));var path3=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var import_node_crypto=require("node:crypto");var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var isNum=v=>typeof v==="number"&&Number.isFinite(v);var round3=n=>Math.round((isNum(n)?n:0)*1e3)/1e3;var clamp=(n,lo,hi)=>Math.min(hi,Math.max(lo,n));function mergeSpans(spans){const clean=spans.filter(s=>isNum(s.startSec)&&isNum(s.endSec)&&s.endSec>s.startSec).map(s=>({startSec:s.startSec,endSec:s.endSec})).sort((a,b)=>a.startSec-b.startSec);const out=[];for(const s of clean){const last=out[out.length-1];if(last&&s.startSec<=last.endSec){last.endSec=Math.max(last.endSec,s.endSec)}else{out.push({...s})}}return out}function keepIntervalsFromRemovals(durationSec,removeSpans,opts={}){const dur=isNum(durationSec)&&durationSec>0?durationSec:0;if(dur<=0)return[];const padSec=isNum(opts.padSec)&&opts.padSec>=0?opts.padSec:.1;const minRemoveSec=isNum(opts.minRemoveSec)&&opts.minRemoveSec>=0?opts.minRemoveSec:.5;const minKeepSec=isNum(opts.minKeepSec)&&opts.minKeepSec>=0?opts.minKeepSec:.3;const shrunk=[];for(const s of removeSpans){if(!isNum(s.startSec)||!isNum(s.endSec))continue;const start=clamp(s.startSec+padSec,0,dur);const end=clamp(s.endSec-padSec,0,dur);if(end-start>=minRemoveSec)shrunk.push({startSec:start,endSec:end})}const removals=mergeSpans(shrunk);if(!removals.length)return[{startSec:0,endSec:round3(dur)}];const kept=[];let cursor=0;for(const r of removals){if(r.startSec-cursor>=minKeepSec)kept.push({startSec:round3(cursor),endSec:round3(r.startSec)});cursor=Math.max(cursor,r.endSec)}if(dur-cursor>=minKeepSec)kept.push({startSec:round3(cursor),endSec:round3(dur)});return kept}function complementIntervals(kept,durationSec){const dur=isNum(durationSec)&&durationSec>0?durationSec:0;const removed=[];let cursor=0;for(const k of kept){if(!isNum(k.startSec)||!isNum(k.endSec))continue;if(k.startSec>cursor)removed.push({startSec:round3(cursor),endSec:round3(k.startSec)});cursor=Math.max(cursor,k.endSec)}if(dur>cursor)removed.push({startSec:round3(cursor),endSec:round3(dur)});return removed}var DEFAULT_FILLERS=["um","uh","umm","uhh","erm","er","ah","eh","hmm","mm","mmm"];var normToken=s=>s.toLowerCase().replace(/[^a-z']/g,"").trim();function fillerSpansFromWords(words,fillers=DEFAULT_FILLERS,opts={}){const set=new Set(Array.from(fillers,f=>normToken(f)));const padSec=isNum(opts.padSec)&&opts.padSec>=0?opts.padSec:.03;const spans=[];for(const w of words){if(!w||typeof w.text!=="string"||!isNum(w.startSec)||!isNum(w.endSec))continue;if(w.endSec<=w.startSec)continue;if(set.has(normToken(w.text))){spans.push({startSec:Math.max(0,w.startSec-padSec),endSec:w.endSec+padSec})}}return spans}function normalizeTranscriptWords(json){const collect=[];const visit=(node,depth)=>{if(depth>32||!node||typeof node!=="object")return;const o=node;if(Array.isArray(o.words))collect.push(...o.words);if(Array.isArray(o.segments))for(const seg of o.segments)visit(seg,depth+1);if(o.result)visit(o.result,depth+1);if(o.transcript)visit(o.transcript,depth+1)};if(Array.isArray(json))collect.push(...json);else visit(json,0);const out=[];for(const raw of collect){if(!raw||typeof raw!=="object")continue;const w=raw;const text=w.word??w.text??w.w;if(typeof text!=="string"||!text.trim())continue;let start;let end;if(isNum(w.startSec)&&isNum(w.endSec)){start=w.startSec;end=w.endSec}else if(isNum(w.start)&&isNum(w.end)){start=w.start;end=w.end}else if(w.offsets&&typeof w.offsets==="object"){const off=w.offsets;if(isNum(off.from)&&isNum(off.to)){start=off.from/1e3;end=off.to/1e3}}if(start===void 0||end===void 0||end<=start)continue;out.push({text:text.trim(),startSec:start,endSec:end})}return out}function parseSceneChanges(log2){const out=[];let pts=null;for(const line of log2.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){pts=Number(tp[1]);continue}const sc=line.match(/scene_score\s*[:=]\s*([\d.]+)/);if(sc&&pts!==null){const score=Number(sc[1]);out.push({tSec:round3(pts),score:Number.isFinite(score)?round3(score):0});pts=null}}return out}function buildKeepFilterComplex(intervals){const valid=intervals.filter(iv=>isNum(iv.startSec)&&isNum(iv.endSec)&&iv.endSec>iv.startSec);if(!valid.length)throw new Error("buildKeepFilterComplex: no intervals to keep");const expr=valid.map(iv=>`between(t,${iv.startSec.toFixed(3)},${iv.endSec.toFixed(3)})`).join("+");const filter=`[0:v]select='${expr}',setpts=N/FRAME_RATE/TB[v];[0:a]aselect='${expr}',asetpts=N/SR/TB[a]`;return{filter,maps:["-map","[v]","-map","[a]"]}}function spanSeconds(spans){return spans.reduce((s,iv)=>s+Math.max(0,iv.endSec-iv.startSec),0)}function decisionEvidence(removeSpans,keptIntervals,reason,confidence=.9){return{removed_spans:removeSpans.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)})),kept_intervals:keptIntervals.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)})),removed_count:removeSpans.length,removed_sec:round3(spanSeconds(removeSpans)),reason,confidence}}function parseQualityFrames(log2){const frames=[];let cur=null;for(const line of log2.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){if(cur)frames.push(cur);cur={tSec:round3(Number(tp[1]))};continue}if(!cur)continue;const b=line.match(/lavfi\.blur=\s*([\d.]+)/);if(b){cur.blur=round3(Number(b[1]));continue}const y=line.match(/lavfi\.signalstats\.YAVG=\s*([\d.]+)/);if(y){cur.brightness=round3(Number(y[1]));continue}}if(cur)frames.push(cur);return frames}function parseLabeledIntervals(log2,label){const spans=[];const re=new RegExp(`${label}_(start|end)[:=]\\s*(-?[\\d.]+)`,"g");let openStart=null;let m;while((m=re.exec(log2))!==null){const v=Number(m[2]);if(!Number.isFinite(v))continue;if(m[1]==="start")openStart=v;else if(openStart!==null){spans.push({startSec:round3(Math.max(0,openStart)),endSec:round3(v)});openStart=null}}return spans}function stats(nums){if(!nums.length)return null;const sum=nums.reduce((a,b)=>a+b,0);return{mean:round3(sum/nums.length),min:round3(Math.min(...nums)),max:round3(Math.max(...nums))}}function summarizeQuality(input){const blurT=isNum(input.thresholds?.blur)?input.thresholds.blur:15;const darkBelow=isNum(input.thresholds?.darkBelow)?input.thresholds.darkBelow:50;const brightAbove=isNum(input.thresholds?.brightAbove)?input.thresholds.brightAbove:200;const blur=stats(input.frames.map(f=>f.blur).filter(v=>isNum(v)));const brightness=stats(input.frames.map(f=>f.brightness).filter(v=>isNum(v)));const blackSpans=input.blackSpans??[];const freezeSpans=input.freezeSpans??[];const black_sec=round3(spanSeconds(blackSpans));const freeze_sec=round3(spanSeconds(freezeSpans));const dur=isNum(input.durationSec)&&input.durationSec>0?input.durationSec:0;const flags=[];if(blur&&blur.mean>blurT)flags.push("blurry");if(brightness&&brightness.mean<darkBelow)flags.push("too_dark");if(brightness&&brightness.mean>brightAbove)flags.push("too_bright");if(black_sec>0)flags.push("has_black");if(freeze_sec>0)flags.push("has_freeze");let score=1;if(flags.includes("blurry"))score-=.3;if(flags.includes("too_dark")||flags.includes("too_bright"))score-=.3;if(dur>0){score-=Math.min(.4,black_sec/dur);score-=Math.min(.3,freeze_sec/dur)}score=Math.max(0,Math.min(1,round3(score)));const roundSpans=ss=>ss.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)}));return{durationSec:round3(dur),frames_analyzed:input.frames.length,blur,brightness,black_sec,freeze_sec,black_spans:roundSpans(blackSpans),freeze_spans:roundSpans(freezeSpans),flags,score}}function finiteNum(v){return typeof v==="number"&&Number.isFinite(v)?v:void 0}var log=createLogger("video-edit");var FFMPEG_TIMEOUT_MS=20*60*1e3;var MIX_OUTPUT_SR=48e3;var MIX_LOUDNORM={I:-14,TP:-1,LRA:11};var SILENCE_NOISE_DB=-40;var SILENCE_MIN_SEC=.5;var COVERAGE_TRAILING_GAP_SEC=2;var COVERAGE_OVERSHOOT_SEC=.3;var COVERAGE_LEAD_GAP_SEC=3;var MIX_COVERAGE_CONCURRENCY=4;var MIN_TRIM_OUTPUT_SEC=.1;var RUN_PROGRESS_HEARTBEAT_MS=15e3;var RUN_PROGRESS_MIN_EMIT_MS=2e3;function parseEbur128Summary(stderr){const num=re=>{const m=stderr.match(re);if(!m)return null;if(/inf/i.test(m[1]))return null;const v=Number(m[1]);return Number.isFinite(v)?v:null};const hasIntegrated=/\bI:\s*(-?(?:inf|[\d.]+))\s*LUFS/i.test(stderr);if(!hasIntegrated)return null;return{integratedLufs:num(/\bI:\s*(-?(?:inf|[\d.]+))\s*LUFS/i),loudnessRangeLu:num(/\bLRA:\s*(-?(?:inf|[\d.]+))\s*LU\b/i),truePeakDbfs:num(/\bPeak:\s*(-?(?:inf|[\d.]+))\s*dBFS/i)}}function escapeFfmpegFilterValue(value){return value.replace(/\\/g,"\\\\").replace(/:/g,"\\:").replace(/'/g,"\\'").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function round2(n){return Math.round((Number.isFinite(n)?n:0)*100)/100}function clamp2(n,lo,hi){return Math.min(hi,Math.max(lo,n))}async function mapWithConcurrencyLimit(items,limit,worker){const width=Math.max(1,Math.min(items.length,Math.floor(limit)||1));const results=new Array(items.length);let next=0;await Promise.all(Array.from({length:width},async()=>{while(next<items.length){const index=next++;results[index]=await worker(items[index],index)}}));return results}function validateTrimRequest(inputDurationSec,startSec,durationSec){if(durationSec<MIN_TRIM_OUTPUT_SEC){return fail("E_EDIT_TRIM_RANGE",`trim duration must be at least ${MIN_TRIM_OUTPUT_SEC}s; got ${round2(durationSec)}s.`)}if(Number.isFinite(inputDurationSec)&&inputDurationSec>0){const remaining=inputDurationSec-startSec;if(remaining<MIN_TRIM_OUTPUT_SEC){return fail("E_EDIT_TRIM_RANGE",`trim start ${round2(startSec)}s is outside or too close to the end of the ${round2(inputDurationSec)}s input; choose a start at least ${MIN_TRIM_OUTPUT_SEC}s before the end.`)}}return null}function parseSilenceDetect(stderr,durationSec){const EPS_LEAD=.05;const EPS_TAIL=.3;const tokens=[];const re=/silence_(start|end):\s*(-?[\d.]+)/g;let m;while((m=re.exec(stderr))!==null){const t=Number(m[2]);if(Number.isFinite(t))tokens.push({kind:m[1],t})}const silences=[];let openStart=null;for(const tk of tokens){if(tk.kind==="start"){openStart=tk.t}else if(openStart!==null){silences.push({startSec:Math.max(0,openStart),endSec:tk.t});openStart=null}}const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:silences.length?silences[silences.length-1].endSec:0;if(openStart!==null)silences.push({startSec:Math.max(0,openStart),endSec:dur});const first=silences[0];const last=silences.length?silences[silences.length-1]:void 0;const leadingSilenceSec=first&&first.startSec<=EPS_LEAD?Math.min(first.endSec,dur):0;const trailingSilenceSec=last&&last.endSec>=dur-EPS_TAIL?Math.max(0,dur-last.startSec):0;const totalSilence=silences.reduce((s,iv)=>s+Math.max(0,Math.min(iv.endSec,dur)-iv.startSec),0);const voicedDurationSec=Math.max(0,dur-totalSilence);const voicedStartSec=leadingSilenceSec;const voicedEndSec=Math.max(voicedStartSec,dur-trailingSilenceSec);return{durationSec:dur,voicedStartSec,voicedEndSec,voicedDurationSec,leadingSilenceSec,trailingSilenceSec,silences}}function assessVoiceoverCoverage(input){const ref=Math.max(0,input.referenceDurationSec);const offset=Math.max(0,input.offsetSec??0);const voicedStart=offset+Math.max(0,input.voicedStartSec);const voicedEnd=offset+Math.max(0,input.voicedEndSec);const hasVoice=input.voicedEndSec-input.voicedStartSec>.05&&input.audioDurationSec>.05;const leadingGapSec=round2(voicedStart);const trailingGapSec=round2(ref-voicedEnd);const overshootSec=round2(offset+input.audioDurationSec-ref);const coverageRatio=ref>0?round2(clamp2(voicedEnd/ref,0,1)):0;const warnings=[];let status="ok";if(!hasVoice){status="silent";warnings.push("No speech detected in the added audio \u2014 the mux produced a silent or near-silent track.")}else{if(overshootSec>COVERAGE_OVERSHOOT_SEC){status="over";warnings.push(`Narration runs ${overshootSec}s past the ${round2(ref)}s clip and was truncated to fit \u2014 shorten the script so it ends before the clip does (trim the words; do not just raise speed).`)}if(trailingGapSec>COVERAGE_TRAILING_GAP_SEC){if(status==="ok")status="under";const pct=ref>0?Math.round(trailingGapSec/ref*100):0;warnings.push(`Narration ends at ${round2(voicedEnd)}s, leaving ${trailingGapSec}s of silent tail on a ${round2(ref)}s clip (~${pct}% uncovered) \u2014 lengthen the script, add a closing line, or trim the clip to match.`)}if(leadingGapSec>COVERAGE_LEAD_GAP_SEC){warnings.push(`Narration only starts at ${leadingGapSec}s \u2014 long silent lead-in; reduce the offset or trim the head.`)}}return{referenceDurationSec:round2(ref),voicedStartSec:round2(voicedStart),voicedEndSec:round2(voicedEnd),leadingGapSec,trailingGapSec,overshootSec,coverageRatio,status,warnings}}function buildMixFilter(opts){const{sr,segmentStartSec,baseHasAudio,mode,padWholeDurSec,loudnorm}=opts;const chains=[];const segLabels=[];segmentStartSec.forEach((startSec,i)=>{const idx=i+1;const parts=[`[${idx}:a]aresample=${sr}`];const ms=Math.round(Math.max(0,startSec)*1e3);if(ms>0)parts.push(`adelay=${ms}:all=1`);chains.push(`${parts.join(",")}[seg${i}]`);segLabels.push(`[seg${i}]`)});let bed;if(segLabels.length<=1){bed=segLabels[0]??""}else{chains.push(`${segLabels.join("")}amix=inputs=${segLabels.length}:duration=longest:normalize=0[vobed]`);bed="[vobed]"}const tail=`${padWholeDurSec&&padWholeDurSec>0?`apad=whole_dur=${padWholeDurSec.toFixed(3)},`:""}${loudnorm},aresample=${sr}`;if(baseHasAudio&&mode==="mix"){chains.push(`[0:a]aresample=${sr}[base]`);chains.push(`[base]${bed}amix=inputs=2:duration=longest:normalize=0,${tail}[aout]`)}else{chains.push(`${bed}${tail}[aout]`)}return chains.join(";")}function totalSpanSeconds(spans){return spans.reduce((sum,iv)=>sum+Math.max(0,iv.endSec-iv.startSec),0)}function resolveBins(){const b=bundledFfmpegPaths();if(!b.ffmpeg||!b.ffprobe)return null;return{ffmpeg:b.ffmpeg,ffprobe:b.ffprobe}}function parseProgressClock(raw){if(!raw)return null;const m=raw.trim().match(/^(\d+):(\d{2}):(\d{2}(?:\.\d+)?)$/);if(!m)return null;const h=Number(m[1]);const min=Number(m[2]);const sec=Number(m[3]);if(![h,min,sec].every(Number.isFinite))return null;return h*3600+min*60+sec}function parseFfmpegProgressTimeSec(fields){for(const key of["out_time_us","out_time_ms"]){const raw=fields[key];if(!raw)continue;const micros=Number(raw);if(Number.isFinite(micros)&&micros>=0)return micros/1e6}return parseProgressClock(fields.out_time)}function emitRunProgress(progress,event){const payload={type:"progress",source:"video_edit",op:progress.op,phase:progress.phase??"edit",...event};try{process.stderr.write(`${JSON.stringify(payload)}
`)}catch{}}function withFfmpegProgress(args){return args.includes("-progress")?args:["-progress","pipe:2",...args]}function run(bin,args,signal,progress){return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(bin,args,{...signal?{signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const startedAtMs=Date.now();let lastProgressEmitMs=0;let progressFields={};let progressLineBuffer="";const heartbeat=progress?setInterval(()=>{emitRunProgress(progress,{status:"heartbeat",elapsed_sec:round2((Date.now()-startedAtMs)/1e3)})},progress.heartbeatMs??RUN_PROGRESS_HEARTBEAT_MS):null;heartbeat?.unref?.();const emitFfmpegProgress=(status,force=false)=>{if(!progress)return;const now=Date.now();if(!force&&now-lastProgressEmitMs<RUN_PROGRESS_MIN_EMIT_MS)return;lastProgressEmitMs=now;const processedSec=parseFfmpegProgressTimeSec(progressFields);const configuredDurationSec=progress.durationSec;const durationSec=typeof configuredDurationSec==="number"&&Number.isFinite(configuredDurationSec)&&configuredDurationSec>0?configuredDurationSec:null;emitRunProgress(progress,{status:status==="end"?"completed":"running",elapsed_sec:round2((now-startedAtMs)/1e3),...processedSec!==null?{processed_sec:round2(processedSec)}:{},...processedSec!==null&&durationSec?{percent:round2(clamp2(processedSec/durationSec*100,0,100))}:{}})};const ingestProgressChunk=text=>{if(!progress)return;progressLineBuffer+=text.replace(/\r/g,"\n");const lines=progressLineBuffer.split("\n");progressLineBuffer=lines.pop()??"";for(const line of lines){const m=line.trim().match(/^([A-Za-z0-9_]+)=(.*)$/);if(!m)continue;progressFields[m[1]]=m[2];if(m[1]==="progress"){emitFfmpegProgress(m[2],m[2]==="end");if(m[2]==="end")progressFields={}}}};const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},FFMPEG_TIMEOUT_MS);let settled=false;const finish=result=>{if(settled)return;settled=true;clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);if(progress&&result.code!==0){emitRunProgress(progress,{status:result.aborted?"aborted":result.timedOut?"timed_out":"failed",elapsed_sec:round2((Date.now()-startedAtMs)/1e3),code:result.code})}resolve3(result)};child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>{const text=c.toString("utf8");errChunks.push(text);ingestProgressChunk(text)});child.stdin?.end();child.on("error",err=>{finish({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!signal?.aborted})});child.on("close",code=>{finish({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!signal?.aborted})})})}async function statSize(p){const st=await fs3.stat(p).catch(()=>null);return st&&st.isFile()?st.size:0}async function validateTrimOutput(ffprobe,outputAbsPath,signal){const bytes=await statSize(outputAbsPath);if(bytes<=0){return{ok:false,errorCode:"E_EDIT_EMPTY_OUTPUT",message:"trim produced an empty output file; check the requested start/duration."}}const durationSec=await probeDurationSec(ffprobe,outputAbsPath,signal);if(signal?.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"trim output validation aborted."};if(durationSec<MIN_TRIM_OUTPUT_SEC){return{ok:false,errorCode:"E_EDIT_EMPTY_OUTPUT",message:`trim produced a ${round2(durationSec)}s output, which is too short to use; check the requested start/duration.`}}return{ok:true,bytes,durationSec}}function fail(errorCode,message){return{ok:false,errorCode,message}}function ffmpegFailure(op,r){if(r.aborted)return fail("E_EDIT_ABORTED",`${op} aborted.`);if(r.timedOut)return fail("E_EDIT_TIMEOUT",`${op} timed out.`);const tail=r.stderr.trim().slice(-1200);log.warn(`ffmpeg ${op} exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return fail("E_EDIT_FAILED",`${op} failed (exit ${r.code}). ${tail||"No diagnostic output."}`)}async function measureLoudness(ffmpeg,ffprobe,inputAbsPath,signal){const durationSec=await probeDurationSec(ffprobe,inputAbsPath,signal);const r=await run(ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-af","ebur128=peak=true","-f","null","-"]),signal,{op:"loudness",phase:"analyze",durationSec});if(r.code!==0)return ffmpegFailure("loudness",r);const loudness=parseEbur128Summary(r.stderr);if(!loudness)return fail("E_EDIT_LOUDNESS_PARSE","Could not parse the ffmpeg ebur128 loudness summary.");return{ok:true,op:"loudness",loudness}}async function probeDurationSec(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v=Number(r.stdout.trim());if(Number.isFinite(v)&&v>0)return v;const r2=await run(ffprobe,["-v","error","-select_streams","a:0","-show_entries","stream=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v2=Number(r2.stdout.trim());return Number.isFinite(v2)&&v2>0?v2:0}async function probeBasic(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration:stream=codec_type","-of","json",input],signal);let durationSec=0;let hasAudio=false;try{const j=JSON.parse(r.stdout);const d=Number(j.format?.duration);if(Number.isFinite(d)&&d>0)durationSec=d;hasAudio=(j.streams??[]).some(s=>s.codec_type==="audio")}catch{}return{durationSec,hasAudio}}async function probeMediaDurationSec(inputAbsPath,signal){const bins=resolveBins();if(!bins)return null;const d=await probeDurationSec(bins.ffprobe,inputAbsPath,signal);return d>0?d:null}async function extractFrameAt(inputAbsPath,atSec,outAbsPath,signal){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const at=Number.isFinite(atSec)&&atSec>0?atSec:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",inputAbsPath,"-frames:v","1","-update","1",outAbsPath],signal);if(r.code!==0){const f=ffmpegFailure("extract_frame",r);return{ok:false,errorCode:f.errorCode,message:f.message}}return{ok:true}}async function measureSilenceCoverage(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const noise=opts?.noiseDb??SILENCE_NOISE_DB;const minSec=opts?.minSilenceSec??SILENCE_MIN_SEC;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-af",`silencedetect=noise=${noise}dB:d=${minSec}`,"-f","null","-"]),opts?.signal,{op:"silence_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"silence detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"silence detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg silencedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`silence detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,timing:parseSilenceDetect(r.stderr,dur)}}function runJumpCut(ffmpeg,inputAbsPath,kept,outputAbsPath,signal,progress){const{filter,maps}=buildKeepFilterComplex(kept);return run(ffmpeg,withFfmpegProgress(["-y","-i",inputAbsPath,"-filter_complex",filter,...maps,"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",outputAbsPath]),signal,progress)}async function detectSceneChanges(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const th=finiteNum(opts?.threshold);const threshold=th!==void 0&&th>=0&&th<=1?th:.4;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",`select='gt(scene,${threshold})',metadata=print`,"-an","-f","null","-"]),opts?.signal,{op:"scene_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"scene detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"scene detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg scenedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`scene detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,durationSec:dur,threshold,candidates:parseSceneChanges(`${r.stdout}
${r.stderr}`)}}async function detectQuality(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const fpsN=finiteNum(opts?.fps);const fps=fpsN!==void 0&&fpsN>0&&fpsN<=30?fpsN:3;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const vf=`fps=${fps},blackdetect=d=0.1:pix_th=0.10,freezedetect=n=0.003:d=0.5,blurdetect,signalstats,metadata=print`;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",vf,"-an","-f","null","-"]),opts?.signal,{op:"quality_scan",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"quality scan aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"quality scan timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg quality scan exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`quality scan failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}const logText=`${r.stdout}
-${r.stderr}`;const report=summarizeQuality({durationSec:dur,frames:parseQualityFrames(logText),blackSpans:parseLabeledIntervals(logText,"black"),freezeSpans:parseLabeledIntervals(logText,"freeze"),...opts?.thresholds?{thresholds:opts.thresholds}:{}});return{ok:true,report}}async function editVideo(p){const bins=resolveBins();if(!bins)return fail("E_EDIT_FFMPEG_MISSING","Bundled ffmpeg/ffprobe not found.");const ensureOutDir=async out=>{await fs3.mkdir(path3.dirname(out),{recursive:true}).catch(()=>{})};if(p.op==="probe"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","probe requires input_path");const r=await run(bins.ffprobe,["-v","error","-print_format","json","-show_format","-show_streams",p.inputAbsPath],p.signal);if(r.code!==0)return ffmpegFailure("probe",r);try{return{ok:true,op:"probe",probe:JSON.parse(r.stdout)}}catch{return fail("E_EDIT_PROBE_PARSE","ffprobe returned unparseable JSON")}}if(p.op==="loudness"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","loudness requires input_path");return measureLoudness(bins.ffmpeg,bins.ffprobe,p.inputAbsPath,p.signal)}if(!p.outputAbsPath)return fail("E_EDIT_ARG",`${p.op} requires output_path`);await ensureOutDir(p.outputAbsPath);if(p.op==="trim"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","trim requires input_path");const start=finiteNum(p.start);const duration=finiteNum(p.duration);if(start===void 0||start<0)return fail("E_EDIT_ARG","trim requires a finite start >= 0 (seconds)");if(duration===void 0||duration<=0)return fail("E_EDIT_ARG","trim requires a finite duration > 0 (seconds)");const inputDurationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const trimRangeError=validateTrimRequest(inputDurationSec,start,duration);if(trimRangeError)return trimRangeError;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-ss",String(start),"-t",String(duration),"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"trim",phase:"edit",durationSec:duration});if(r.code!==0)return ffmpegFailure("trim",r);const checked=await validateTrimOutput(bins.ffprobe,p.outputAbsPath,p.signal);if(checked.ok===false)return fail(checked.errorCode,checked.message);return{ok:true,op:"trim",path:p.outputAbsPath,bytes:checked.bytes}}if(p.op==="normalize_loudness"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","normalize_loudness requires input_path");const base=await probeBasic(bins.ffprobe,p.inputAbsPath,p.signal);if(!base.hasAudio)return fail("E_EDIT_NO_AUDIO","normalize_loudness requires an input with an audio stream.");const ln=`loudnorm=I=${MIX_LOUDNORM.I}:TP=${MIX_LOUDNORM.TP}:LRA=${MIX_LOUDNORM.LRA},aresample=${MIX_OUTPUT_SR}`;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-map","0:v?","-map","0:a:0","-c:v","copy","-filter:a:0",ln,"-c:a","aac","-ar",String(MIX_OUTPUT_SR),"-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"normalize_loudness",phase:"edit",durationSec:base.durationSec});if(r.code!==0)return ffmpegFailure("normalize_loudness",r);const loudnessResult=await measureLoudness(bins.ffmpeg,bins.ffprobe,p.outputAbsPath,p.signal);if(loudnessResult.ok===false)return loudnessResult;return{ok:true,op:"normalize_loudness",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),loudness:loudnessResult.loudness}}if(p.op==="concat"){const inputs=p.inputAbsPaths??[];if(inputs.length<2)return fail("E_EDIT_ARG","concat requires input_paths with at least 2 entries");const listPath=path3.join(os.tmpdir(),`orkas-concat-${(0,import_node_crypto.randomUUID)()}.txt`);const listBody=inputs.map(f=>`file '${f.replace(/'/g,"'\\''")}'`).join("\n");await fs3.writeFile(listPath,listBody,"utf8");try{const inputDurations=await mapWithConcurrencyLimit(inputs,MIX_COVERAGE_CONCURRENCY,input=>probeDurationSec(bins.ffprobe,input,p.signal));const concatDurationSec=inputDurations.every(d=>d>0)?inputDurations.reduce((sum,d)=>sum+d,0):null;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-f","concat","-safe","0","-i",listPath,"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"concat",phase:"edit",durationSec:concatDurationSec});if(r.code!==0)return ffmpegFailure("concat",r);return{ok:true,op:"concat",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}finally{await fs3.rm(listPath,{force:true}).catch(()=>{})}}if(p.op==="burnsubs"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","burnsubs requires input_path");if(!p.subtitlesAbsPath)return fail("E_EDIT_ARG","burnsubs requires subtitles_path (.srt/.ass)");const subEsc=escapeFfmpegFilterValue(p.subtitlesAbsPath);const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-vf",`subtitles=filename=${subEsc}`,"-c:v","libx264","-preset","veryfast","-c:a","copy","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"burnsubs",phase:"edit",durationSec});if(r.code!==0)return ffmpegFailure("burnsubs",r);return{ok:true,op:"burnsubs",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="overlay"){if(!p.inputAbsPath||!p.overlayAbsPath)return fail("E_EDIT_ARG","overlay requires input_path (base) and overlay_path");const clampXY=v=>Math.round(Math.max(-1e5,Math.min(1e5,finiteNum(v)??0)));const x=clampXY(p.x);const y=clampXY(p.y);const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-i",p.overlayAbsPath,"-filter_complex",`overlay=${x}:${y}`,"-c:v","libx264","-preset","veryfast","-c:a","copy","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"overlay",phase:"edit",durationSec});if(r.code!==0)return ffmpegFailure("overlay",r);return{ok:true,op:"overlay",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="extract_frame"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","extract_frame requires input_path");const sf=finiteNum(p.start);const at=sf!==void 0&&sf>=0?sf:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",p.inputAbsPath,"-frames:v","1","-update","1",p.outputAbsPath],p.signal);if(r.code!==0)return ffmpegFailure("extract_frame",r);return{ok:true,op:"extract_frame",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="trim_silence"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","trim_silence requires input_path");const noiseDb=finiteNum(p.noiseDb);const minSilenceSec=finiteNum(p.minSilenceSec);const padSec=finiteNum(p.padSec);const minKeepSec=finiteNum(p.minKeepSec);const meas=await measureSilenceCoverage(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...noiseDb!==void 0?{noiseDb}:{},...minSilenceSec!==void 0?{minSilenceSec}:{}});if(meas.ok===false)return fail(meas.errorCode,meas.message);const dur=meas.timing.durationSec;const kept=keepIntervalsFromRemovals(dur,meas.timing.silences,{...padSec!==void 0?{padSec}:{},...minSilenceSec!==void 0?{minRemoveSec:minSilenceSec}:{},...minKeepSec!==void 0?{minKeepSec}:{}});const removed=complementIntervals(kept,dur);if(!removed.length||!kept.length){return fail("E_EDIT_NO_CHANGE",`No silence \u2265 ${minSilenceSec??SILENCE_MIN_SEC}s found below ${noiseDb??SILENCE_NOISE_DB} dB \u2014 nothing to trim; use the original clip.`)}const cut=await runJumpCut(bins.ffmpeg,p.inputAbsPath,kept,p.outputAbsPath,p.signal,{op:"trim_silence",phase:"edit",durationSec:totalSpanSeconds(kept)});if(cut.code!==0)return ffmpegFailure("trim_silence",cut);const decision=decisionEvidence(removed,kept,`removed ${removed.length} silent span(s) below ${noiseDb??SILENCE_NOISE_DB} dB`);return{ok:true,op:"trim_silence",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),decision}}if(p.op==="remove_fillers"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","remove_fillers requires input_path");if(!p.transcriptAbsPath)return fail("E_EDIT_ARG","remove_fillers requires transcript_path (the analyze_media transcribe JSON with word timings)");let json;try{json=JSON.parse(await fs3.readFile(p.transcriptAbsPath,"utf8"))}catch(err){return fail("E_EDIT_TRANSCRIPT_PARSE",`could not read/parse transcript_path: ${err.message}`)}const words=normalizeTranscriptWords(json);if(!words.length)return fail("E_EDIT_NO_WORDS","transcript had no word-level timings \u2014 re-run analyze_media transcribe (--json) on this clip.");const padSec=finiteNum(p.padSec);const minKeepSec=finiteNum(p.minKeepSec);const removeSpans=fillerSpansFromWords(words,p.fillers&&p.fillers.length?p.fillers:DEFAULT_FILLERS,padSec!==void 0?{padSec}:{});if(!removeSpans.length)return fail("E_EDIT_NO_CHANGE","no filler words found \u2014 nothing to remove; use the original clip.");const dur=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal)||0;if(dur<=0)return fail("E_EDIT_FAILED","could not probe duration for filler removal.");const kept=keepIntervalsFromRemovals(dur,removeSpans,{padSec:0,minRemoveSec:0,...minKeepSec!==void 0?{minKeepSec}:{}});if(!kept.length)return fail("E_EDIT_NO_CHANGE","filler removal left nothing to keep.");const cut=await runJumpCut(bins.ffmpeg,p.inputAbsPath,kept,p.outputAbsPath,p.signal,{op:"remove_fillers",phase:"edit",durationSec:totalSpanSeconds(kept)});if(cut.code!==0)return ffmpegFailure("remove_fillers",cut);const removed=complementIntervals(kept,dur);const decision=decisionEvidence(removed,kept,`removed ${removeSpans.length} filler word(s)`);return{ok:true,op:"remove_fillers",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),decision}}if(p.op==="mix"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","mix requires input_path (the base video)");const segs=p.audioSegments&&p.audioSegments.length?p.audioSegments.filter(s=>s&&typeof s.audioAbsPath==="string"&&s.audioAbsPath).map(s=>({audioAbsPath:s.audioAbsPath,startSec:Math.max(0,finiteNum(s.startSec)??0)})):p.audioAbsPath?[{audioAbsPath:p.audioAbsPath,startSec:Math.max(0,finiteNum(p.start)??0)}]:[];if(!segs.length)return fail("E_EDIT_ARG","mix requires audio_path (the narration/music to add) or a non-empty audio_segments");const mode=p.onExistingAudio??"reject";const base=await probeBasic(bins.ffprobe,p.inputAbsPath,p.signal);if(base.hasAudio&&mode==="reject"){return fail("E_EDIT_BASE_HAS_AUDIO",`The base video already has an audio track, so mixing narration onto it would STACK a second voice (the "two voices" defect). Render the base SILENT first \u2014 for a compose segment, remove the narration <audio> from its index.html so render_composition produces no audio, then re-mix. If layering is intended (e.g. music under a talking-head's built-in lip-synced voice) pass on_existing_audio='mix'; to drop the base audio and keep only this narration pass on_existing_audio='replace'.`)}const sr=MIX_OUTPUT_SR;const ln=`loudnorm=I=${MIX_LOUDNORM.I}:TP=${MIX_LOUDNORM.TP}:LRA=${MIX_LOUDNORM.LRA}`;const filter=buildMixFilter({sr,segmentStartSec:segs.map(s=>s.startSec),baseHasAudio:base.hasAudio,mode:mode==="replace"?"replace":"mix",padWholeDurSec:base.durationSec>0?base.durationSec:null,loudnorm:ln});const inputArgs=["-y","-i",p.inputAbsPath];for(const s of segs)inputArgs.push("-i",s.audioAbsPath);const r=await run(bins.ffmpeg,withFfmpegProgress([...inputArgs,"-filter_complex",filter,"-map","0:v","-map","[aout]","-c:v","copy","-c:a","aac","-ar",String(sr),"-shortest","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"mix",phase:"edit",durationSec:base.durationSec});if(r.code!==0)return ffmpegFailure("mix",r);let coverage;const placedStarts=[];const placedEnds=[];const placedAudioEnds=[];const measurements=await mapWithConcurrencyLimit(segs,MIX_COVERAGE_CONCURRENCY,s=>measureSilenceCoverage(s.audioAbsPath,p.signal?{signal:p.signal}:{}));const measuredAll=measurements.every(meas=>meas.ok);if(measuredAll){for(let i=0;i<segs.length;i+=1){const s=segs[i];const meas=measurements[i];if(!meas.ok)continue;placedStarts.push(s.startSec+meas.timing.voicedStartSec);placedEnds.push(s.startSec+meas.timing.voicedEndSec);placedAudioEnds.push(s.startSec+meas.timing.durationSec)}}if(measuredAll&&placedEnds.length){coverage=assessVoiceoverCoverage({referenceDurationSec:base.durationSec,offsetSec:0,audioDurationSec:Math.max(...placedAudioEnds),voicedStartSec:Math.min(...placedStarts),voicedEndSec:Math.max(...placedEnds)})}return{ok:true,op:"mix",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),...coverage?{coverage}:{}}}return fail("E_EDIT_ARG",`unknown op: ${String(p.op)}`)}0&&(module.exports={assessVoiceoverCoverage,buildMixFilter,detectQuality,detectSceneChanges,editVideo,escapeFfmpegFilterValue,extractFrameAt,mapWithConcurrencyLimit,measureSilenceCoverage,parseEbur128Summary,parseFfmpegProgressTimeSec,parseSilenceDetect,probeMediaDurationSec,validateTrimRequest});
+${r.stderr}`;const report=summarizeQuality({durationSec:dur,frames:parseQualityFrames(logText),blackSpans:parseLabeledIntervals(logText,"black"),freezeSpans:parseLabeledIntervals(logText,"freeze"),...opts?.thresholds?{thresholds:opts.thresholds}:{}});return{ok:true,report}}async function editVideo(p){const bins=resolveBins();if(!bins)return fail("E_EDIT_FFMPEG_MISSING","Bundled ffmpeg/ffprobe not found.");const ensureOutDir=async out=>{await fs3.mkdir(path3.dirname(out),{recursive:true}).catch(()=>{})};if(p.op==="probe"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","probe requires input_path");const r=await run(bins.ffprobe,["-v","error","-print_format","json","-show_format","-show_streams",p.inputAbsPath],p.signal);if(r.code!==0)return ffmpegFailure("probe",r);try{return{ok:true,op:"probe",probe:JSON.parse(r.stdout)}}catch{return fail("E_EDIT_PROBE_PARSE","ffprobe returned unparseable JSON")}}if(p.op==="loudness"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","loudness requires input_path");return measureLoudness(bins.ffmpeg,bins.ffprobe,p.inputAbsPath,p.signal)}if(!p.outputAbsPath)return fail("E_EDIT_ARG",`${p.op} requires output_path`);await ensureOutDir(p.outputAbsPath);if(p.op==="trim"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","trim requires input_path");const start=finiteNum(p.start);const duration=finiteNum(p.duration);if(start===void 0||start<0)return fail("E_EDIT_ARG","trim requires a finite start >= 0 (seconds)");if(duration===void 0||duration<=0)return fail("E_EDIT_ARG","trim requires a finite duration > 0 (seconds)");const inputDurationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const trimRangeError=validateTrimRequest(inputDurationSec,start,duration);if(trimRangeError)return trimRangeError;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-ss",String(start),"-t",String(duration),"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"trim",phase:"edit",durationSec:duration});if(r.code!==0)return ffmpegFailure("trim",r);const checked=await validateTrimOutput(bins.ffprobe,p.outputAbsPath,p.signal);if(checked.ok===false)return fail(checked.errorCode,checked.message);return{ok:true,op:"trim",path:p.outputAbsPath,bytes:checked.bytes}}if(p.op==="normalize_loudness"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","normalize_loudness requires input_path");const base=await probeBasic(bins.ffprobe,p.inputAbsPath,p.signal);if(!base.hasAudio)return fail("E_EDIT_NO_AUDIO","normalize_loudness requires an input with an audio stream.");const ln=`loudnorm=I=${MIX_LOUDNORM.I}:TP=${MIX_LOUDNORM.TP}:LRA=${MIX_LOUDNORM.LRA},aresample=${MIX_OUTPUT_SR}`;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-map","0:v?","-map","0:a:0","-c:v","copy","-filter:a:0",ln,"-c:a","aac","-ar",String(MIX_OUTPUT_SR),"-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"normalize_loudness",phase:"edit",durationSec:base.durationSec});if(r.code!==0)return ffmpegFailure("normalize_loudness",r);const loudnessResult=await measureLoudness(bins.ffmpeg,bins.ffprobe,p.outputAbsPath,p.signal);if(loudnessResult.ok===false)return loudnessResult;return{ok:true,op:"normalize_loudness",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),loudness:loudnessResult.loudness}}if(p.op==="concat"){const inputs=p.inputAbsPaths??[];if(inputs.length<2)return fail("E_EDIT_ARG","concat requires input_paths with at least 2 entries");const listPath=path3.join(os.tmpdir(),`orkas-concat-${(0,import_node_crypto.randomUUID)()}.txt`);const listBody=inputs.map(f=>`file '${f.replace(/'/g,"'\\''")}'`).join("\n");await fs3.writeFile(listPath,listBody,"utf8");try{const inputDurations=await mapWithConcurrencyLimit(inputs,MIX_COVERAGE_CONCURRENCY,input=>probeDurationSec(bins.ffprobe,input,p.signal));const concatDurationSec=inputDurations.every(d=>d>0)?inputDurations.reduce((sum,d)=>sum+d,0):null;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-f","concat","-safe","0","-i",listPath,"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"concat",phase:"edit",durationSec:concatDurationSec});if(r.code!==0)return ffmpegFailure("concat",r);return{ok:true,op:"concat",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}finally{await fs3.rm(listPath,{force:true}).catch(()=>{})}}if(p.op==="burnsubs"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","burnsubs requires input_path");if(!p.subtitlesAbsPath)return fail("E_EDIT_ARG","burnsubs requires subtitles_path (.srt/.ass)");const subEsc=escapeFfmpegFilterValue(p.subtitlesAbsPath);const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-vf",`subtitles=filename=${subEsc}`,"-c:v","libx264","-preset","veryfast","-c:a","copy","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"burnsubs",phase:"edit",durationSec});if(r.code!==0)return ffmpegFailure("burnsubs",r);return{ok:true,op:"burnsubs",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="overlay"){if(!p.inputAbsPath||!p.overlayAbsPath)return fail("E_EDIT_ARG","overlay requires input_path (base) and overlay_path");const clampXY=v=>Math.round(Math.max(-1e5,Math.min(1e5,finiteNum(v)??0)));const x=clampXY(p.x);const y=clampXY(p.y);const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-i",p.overlayAbsPath,"-filter_complex",`overlay=${x}:${y}`,"-c:v","libx264","-preset","veryfast","-c:a","copy","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"overlay",phase:"edit",durationSec});if(r.code!==0)return ffmpegFailure("overlay",r);return{ok:true,op:"overlay",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="extract_frame"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","extract_frame requires input_path");const sf=finiteNum(p.start);const at=sf!==void 0&&sf>=0?sf:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",p.inputAbsPath,"-frames:v","1","-update","1",p.outputAbsPath],p.signal);if(r.code!==0)return ffmpegFailure("extract_frame",r);return{ok:true,op:"extract_frame",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="trim_silence"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","trim_silence requires input_path");const noiseDb=finiteNum(p.noiseDb);const minSilenceSec=finiteNum(p.minSilenceSec);const padSec=finiteNum(p.padSec);const minKeepSec=finiteNum(p.minKeepSec);const meas=await measureSilenceCoverage(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...noiseDb!==void 0?{noiseDb}:{},...minSilenceSec!==void 0?{minSilenceSec}:{}});if(meas.ok===false)return fail(meas.errorCode,meas.message);const dur=meas.timing.durationSec;const kept=keepIntervalsFromRemovals(dur,meas.timing.silences,{...padSec!==void 0?{padSec}:{},...minSilenceSec!==void 0?{minRemoveSec:minSilenceSec}:{},...minKeepSec!==void 0?{minKeepSec}:{}});const removed=complementIntervals(kept,dur);if(!removed.length||!kept.length){return fail("E_EDIT_NO_CHANGE",`No silence \u2265 ${minSilenceSec??SILENCE_MIN_SEC}s found below ${noiseDb??SILENCE_NOISE_DB} dB \u2014 nothing to trim; use the original clip.`)}const cut=await runJumpCut(bins.ffmpeg,p.inputAbsPath,kept,p.outputAbsPath,p.signal,{op:"trim_silence",phase:"edit",durationSec:totalSpanSeconds(kept)});if(cut.code!==0)return ffmpegFailure("trim_silence",cut);const decision=decisionEvidence(removed,kept,`removed ${removed.length} silent span(s) below ${noiseDb??SILENCE_NOISE_DB} dB`);return{ok:true,op:"trim_silence",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),decision}}if(p.op==="remove_fillers"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","remove_fillers requires input_path");if(!p.transcriptAbsPath)return fail("E_EDIT_ARG","remove_fillers requires transcript_path (the video_studio speech.transcribe JSON with word timings)");let json;try{json=JSON.parse(await fs3.readFile(p.transcriptAbsPath,"utf8"))}catch(err){return fail("E_EDIT_TRANSCRIPT_PARSE",`could not read/parse transcript_path: ${err.message}`)}const words=normalizeTranscriptWords(json);if(!words.length)return fail("E_EDIT_NO_WORDS",'transcript had no word-level timings \u2014 re-run video_studio op:"speech.transcribe" with timestamps:"word" on this clip.');const padSec=finiteNum(p.padSec);const minKeepSec=finiteNum(p.minKeepSec);const removeSpans=fillerSpansFromWords(words,p.fillers&&p.fillers.length?p.fillers:DEFAULT_FILLERS,padSec!==void 0?{padSec}:{});if(!removeSpans.length)return fail("E_EDIT_NO_CHANGE","no filler words found \u2014 nothing to remove; use the original clip.");const dur=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal)||0;if(dur<=0)return fail("E_EDIT_FAILED","could not probe duration for filler removal.");const kept=keepIntervalsFromRemovals(dur,removeSpans,{padSec:0,minRemoveSec:0,...minKeepSec!==void 0?{minKeepSec}:{}});if(!kept.length)return fail("E_EDIT_NO_CHANGE","filler removal left nothing to keep.");const cut=await runJumpCut(bins.ffmpeg,p.inputAbsPath,kept,p.outputAbsPath,p.signal,{op:"remove_fillers",phase:"edit",durationSec:totalSpanSeconds(kept)});if(cut.code!==0)return ffmpegFailure("remove_fillers",cut);const removed=complementIntervals(kept,dur);const decision=decisionEvidence(removed,kept,`removed ${removeSpans.length} filler word(s)`);return{ok:true,op:"remove_fillers",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),decision}}if(p.op==="mix"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","mix requires input_path (the base video)");const segs=p.audioSegments&&p.audioSegments.length?p.audioSegments.filter(s=>s&&typeof s.audioAbsPath==="string"&&s.audioAbsPath).map(s=>({audioAbsPath:s.audioAbsPath,startSec:Math.max(0,finiteNum(s.startSec)??0)})):p.audioAbsPath?[{audioAbsPath:p.audioAbsPath,startSec:Math.max(0,finiteNum(p.start)??0)}]:[];if(!segs.length)return fail("E_EDIT_ARG","mix requires audio_path (the narration/music to add) or a non-empty audio_segments");const mode=p.onExistingAudio??"reject";const base=await probeBasic(bins.ffprobe,p.inputAbsPath,p.signal);if(base.hasAudio&&mode==="reject"){return fail("E_EDIT_BASE_HAS_AUDIO",`The base video already has an audio track, so mixing narration onto it would STACK a second voice (the "two voices" defect). Render the base SILENT first \u2014 for a compose segment, remove the narration <audio> from its index.html so the native composition draft has no audio, then re-mix. If layering is intended (e.g. music under a talking-head's built-in lip-synced voice) pass on_existing_audio='mix'; to drop the base audio and keep only this narration pass on_existing_audio='replace'.`)}const sr=MIX_OUTPUT_SR;const ln=`loudnorm=I=${MIX_LOUDNORM.I}:TP=${MIX_LOUDNORM.TP}:LRA=${MIX_LOUDNORM.LRA}`;const filter=buildMixFilter({sr,segmentStartSec:segs.map(s=>s.startSec),baseHasAudio:base.hasAudio,mode:mode==="replace"?"replace":"mix",padWholeDurSec:base.durationSec>0?base.durationSec:null,loudnorm:ln});const inputArgs=["-y","-i",p.inputAbsPath];for(const s of segs)inputArgs.push("-i",s.audioAbsPath);const r=await run(bins.ffmpeg,withFfmpegProgress([...inputArgs,"-filter_complex",filter,"-map","0:v","-map","[aout]","-c:v","copy","-c:a","aac","-ar",String(sr),"-shortest","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"mix",phase:"edit",durationSec:base.durationSec});if(r.code!==0)return ffmpegFailure("mix",r);let coverage;const placedStarts=[];const placedEnds=[];const placedAudioEnds=[];const measurements=await mapWithConcurrencyLimit(segs,MIX_COVERAGE_CONCURRENCY,s=>measureSilenceCoverage(s.audioAbsPath,p.signal?{signal:p.signal}:{}));const measuredAll=measurements.every(meas=>meas.ok);if(measuredAll){for(let i=0;i<segs.length;i+=1){const s=segs[i];const meas=measurements[i];if(!meas.ok)continue;placedStarts.push(s.startSec+meas.timing.voicedStartSec);placedEnds.push(s.startSec+meas.timing.voicedEndSec);placedAudioEnds.push(s.startSec+meas.timing.durationSec)}}if(measuredAll&&placedEnds.length){coverage=assessVoiceoverCoverage({referenceDurationSec:base.durationSec,offsetSec:0,audioDurationSec:Math.max(...placedAudioEnds),voicedStartSec:Math.min(...placedStarts),voicedEndSec:Math.max(...placedEnds)})}return{ok:true,op:"mix",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),...coverage?{coverage}:{}}}return fail("E_EDIT_ARG",`unknown op: ${String(p.op)}`)}0&&(module.exports={assessVoiceoverCoverage,buildMixFilter,detectQuality,detectSceneChanges,editVideo,escapeFfmpegFilterValue,extractFrameAt,mapWithConcurrencyLimit,measureSilenceCoverage,parseEbur128Summary,parseFfmpegProgressTimeSec,parseSilenceDetect,probeMediaDurationSec,validateTrimRequest});
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-plan/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-plan/SKILL.md
index 1a36902e..29e1d293 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-plan/SKILL.md
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-plan/SKILL.md
@@ -9,7 +9,7 @@ category: creation
# stage-plan
-How to turn "here is my material + here's the video I want" into a single, inspectable plan that spans more than one production line. The output is `project/plan.json` — a cross-modal Edit Decision List (EDL) — which the assembler then walks deterministically. Host-neutral: ingest evidence comes from `stage-edit` skill scripts (probe / transcribe / silence / ocr / extract_frame via `bin/run-skill.cjs`), this skill provides the plan validator script, and the producers handle compose / generate / edit.
+How to turn "here is my material + here's the video I want" into a single, inspectable plan that spans more than one production line. The output is `project/plan.json` — a cross-modal Edit Decision List (EDL) — which the assembler then walks deterministically. Host-neutral: ingest evidence comes from `stage-edit` skill scripts (probe / silence / ocr / scenes / quality / extract_frame via `bin/run-skill.cjs`) plus the built-in `video_studio` transcription op, this skill provides the plan validator script, and the producers handle compose / generate / edit.
## How to call ingest scripts
diff --git a/scripts/build-video-studio-skill-core.cjs b/scripts/build-video-studio-skill-core.cjs
index 954dd039..4a1320ef 100644
--- a/scripts/build-video-studio-skill-core.cjs
+++ b/scripts/build-video-studio-skill-core.cjs
@@ -35,10 +35,6 @@ const outputs = [
entry: path.join(scriptCoreSrcDir, 'video_decide.ts'),
outfile: path.join(agentSkillsDir, 'stage-plan', 'scripts', 'lib', 'video_decide_core.cjs'),
},
- {
- entry: path.join(scriptCoreSrcDir, 'video_render.ts'),
- outfile: path.join(agentSkillsDir, 'stage-compose', 'scripts', 'lib', 'video_render_core.cjs'),
- },
];
const aliasMainLogger = {
diff --git a/scripts/fetch-ffmpeg.cjs b/scripts/fetch-ffmpeg.cjs
index 77f86888..81e34b94 100644
--- a/scripts/fetch-ffmpeg.cjs
+++ b/scripts/fetch-ffmpeg.cjs
@@ -2,10 +2,10 @@
/**
* Vendor ffmpeg + ffprobe into `PC/resources/runtime/ffmpeg/<platform>-<arch>/`.
*
- * HyperFrames render (the `render_composition` local backend) and VideoStudio's
- * deterministic media scripts require ffmpeg + ffprobe. Rather than depend on
- * whatever the user's machine happens to have, we ship our own and point the app
- * at them via util/bundled-runtime.ts `bundledFfmpegPaths`.
+ * VideoStudio's native render path and deterministic media scripts require
+ * ffmpeg + ffprobe. Rather than depend on whatever the user's machine happens
+ * to have, we ship our own and point the app at them via util/bundled-runtime.ts
+ * `bundledFfmpegPaths`.
*
* Source of the binaries: the `ffmpeg-static` and `@ffprobe-installer/ffprobe`
* devDependencies (their install scripts fetch the prebuilt binary for the
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index d04d85ca..cbae4c6f 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -313,7 +313,7 @@ function _formatValidationWarnings(
const MAX_PROCESS_ITEMS_PER_TURN = 300;
const MAX_WORKER_TURNS = 100; // hard ceiling against runaway loops
-// The commander orchestrates long multi-step builds (e.g. a hyperframes video:
+// The commander orchestrates long multi-step builds (e.g. a VideoStudio video:
// read several SKILL.md, scaffold, lint, render, fix, re-render) that legitimately
// exceed core-agent's default 50 tool rounds in a single turn. Raise its per-turn
// tool-loop cap so such a build isn't truncated mid-task; the identical-call
diff --git a/src/main/features/hyperframes_runtime.ts b/src/main/features/hyperframes_runtime.ts
deleted file mode 100644
index 1573a25a..00000000
--- a/src/main/features/hyperframes_runtime.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * Shared runtime for the HyperFrames-backed video tools (render_composition /
- * analyze_media / generate_speech). Centralizes: resolving the bundled Node +
- * npx, building the spawn env (PATH prepend, bundled ffmpeg lock, npm cache +
- * offline/retry hardening, shared Python venv on PATH for tts), and a generic
- * capture-spawn for `--json` ops. hyperframes itself is a runtime npx download
- * (deliberately not bundled — see the design plan §6.2); these knobs make that
- * download reliable.
- */
-
-import { spawn } from 'node:child_process';
-import * as fs from 'node:fs';
-
-import {
- bundledNodeExecutable,
- bundledNpxCli,
- bundledRuntimePathEntries,
- bundledFfmpegPaths,
-} from '../util/bundled-runtime';
-import * as paths from '../paths';
-
-/** Pinned HyperFrames version. Bump deliberately (reproducible + known flags). */
-export const HYPERFRAMES_SPEC = '[email protected]';
-
-/** Resolve the bundled Node + npm `npx-cli.js` to run hyperframes as
- * `node <npx-cli.js> ...` — robust cross-platform (no shebang/.cmd/shell). */
-export function resolveHyperframesRunner(): { node: string; npxCli: string } | null {
- const node = bundledNodeExecutable();
- const npxCli = bundledNpxCli();
- if (!node || !npxCli) return null;
- return { node, npxCli };
-}
-
-/** Env for any hyperframes npx invocation. */
-export function buildHyperframesEnv(): NodeJS.ProcessEnv {
- const env: NodeJS.ProcessEnv = { ...process.env };
- const sep = process.platform === 'win32' ? ';' : ':';
-
- const prepend = [...bundledRuntimePathEntries()];
- // Shared Python venv bin → `hyperframes tts` resolves the venv `python` that
- // carries kokoro-onnx. Harmless for render/transcribe (no python shell-out);
- // a non-existent dir is simply ignored by PATH resolution.
- prepend.push(paths.PYTHON_VENV_BIN_DIR);
- if (prepend.length) env.PATH = [...prepend, env.PATH || ''].filter(Boolean).join(sep);
-
- const ff = bundledFfmpegPaths();
- if (ff.ffmpeg) env.HYPERFRAMES_FFMPEG_PATH = ff.ffmpeg;
- if (ff.ffprobe) env.HYPERFRAMES_FFPROBE_PATH = ff.ffprobe;
-
- for (const dir of [paths.NODE_NPM_CACHE_DIR, paths.NODE_NPM_PREFIX_DIR, paths.NODE_NPM_GLOBAL_BIN_DIR]) {
- try { fs.mkdirSync(dir, { recursive: true }); } catch { /* npm will surface a clearer error later */ }
- }
- env.NPM_CONFIG_CACHE = paths.NODE_NPM_CACHE_DIR;
- env.NPM_CONFIG_PREFIX = paths.NODE_NPM_PREFIX_DIR;
- env.NPM_CONFIG_FUND = 'false';
- env.NPM_CONFIG_AUDIT = 'false';
- env.NPM_CONFIG_UPDATE_NOTIFIER = 'false';
- // Warm cache → zero network; bump retries so a cold-download network blip self-heals.
- env.NPM_CONFIG_PREFER_OFFLINE = 'true';
- env.NPM_CONFIG_FETCH_RETRIES = '4';
- return env;
-}
-
-export interface CaptureResult {
- code: number | null;
- stdout: string;
- stderr: string;
- timedOut: boolean;
- aborted: boolean;
-}
-
-/**
- * Run `npx hyperframes <args>` and capture stdout/stderr. For `--json` ops
- * (inspect / lint / transcribe) where the output is the product. Never rejects.
- */
-export function runHyperframesCapture(
- args: string[],
- opts: { cwd?: string; signal?: AbortSignal; timeoutMs?: number },
-): Promise<CaptureResult> {
- const runner = resolveHyperframesRunner();
- if (!runner) {
- return Promise.resolve({ code: -1, stdout: '', stderr: 'E_RUNTIME_MISSING: bundled Node not found', timedOut: false, aborted: false });
- }
- const env = buildHyperframesEnv();
- const fullArgs = [runner.npxCli, '--yes', HYPERFRAMES_SPEC, ...args];
- const timeoutMs = opts.timeoutMs ?? 10 * 60 * 1000;
-
- return new Promise<CaptureResult>((resolve) => {
- let child: ReturnType<typeof spawn>;
- try {
- child = spawn(runner.node, fullArgs, { ...(opts.cwd ? { cwd: opts.cwd } : {}), env, ...(opts.signal ? { signal: opts.signal } : {}) });
- } catch (err) {
- resolve({ code: -1, stdout: '', stderr: (err as Error).message, timedOut: false, aborted: false });
- return;
- }
- const out: string[] = [];
- const errChunks: string[] = [];
- let timedOut = false;
- const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeoutMs);
- child.stdout?.on('data', (c: Buffer) => out.push(c.toString('utf8')));
- child.stderr?.on('data', (c: Buffer) => errChunks.push(c.toString('utf8')));
- child.stdin?.end();
- child.on('error', (err) => {
- clearTimeout(timer);
- resolve({ code: -1, stdout: out.join(''), stderr: err.message, timedOut, aborted: !!opts.signal?.aborted });
- });
- child.on('close', (code) => {
- clearTimeout(timer);
- resolve({ code, stdout: out.join(''), stderr: errChunks.join(''), timedOut, aborted: !!opts.signal?.aborted });
- });
- });
-}
diff --git a/src/main/features/packages.ts b/src/main/features/packages.ts
index 087a342a..737715d6 100644
--- a/src/main/features/packages.ts
+++ b/src/main/features/packages.ts
@@ -16,12 +16,12 @@
* {
* "version": 1,
* "packages": [{
- * "name": "hyperframes", // dir name under packages/
+ * "name": "demo-cli", // dir name under packages/
* "repo_url": "https://github.com/...",
* "commit": "<sha>",
* "kind": "skill" | "cli" | "both",
* "skill_roots": [".", "skills"], // rel dirs whose children (or self) hold SKILL.md
- * "bin_entries": [{"name": "hyperframes", "target": "bin/cli.js", "runtime": "node" | "python" | "sh" | "native"}],
+ * "bin_entries": [{"name": "demo-cli", "target": "bin/cli.js", "runtime": "node" | "python" | "sh" | "native"}],
* "deps_consent": true, // D3: user approved dependency installs for this package
* "enabled": true,
* "installed_at": "<iso>", "updated_at": "<iso>"
diff --git a/src/main/features/video_studio.ts b/src/main/features/video_studio.ts
index c55a8774..17a423ac 100644
--- a/src/main/features/video_studio.ts
+++ b/src/main/features/video_studio.ts
@@ -3,14 +3,45 @@ import * as fss from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
import type { BrowserWindow as ElectronBrowserWindow } from 'electron';
-import { bundledFfmpegPaths } from '../util/bundled-runtime';
+import { bundledFfmpegPaths, bundledWhisperPaths } from '../util/bundled-runtime';
import { redactPaths } from '../util/redact';
import { createLogger } from '../logger';
+import {
+ DRAFT_REPAIR_MAX_PASSES,
+ analyzeNativeImage,
+ buildDraftFrameSamplePlan,
+ initDraftRepairBudget,
+ loadDesignContract,
+ loadNarrationMap,
+ loadSceneMap,
+ loadShotlist,
+ parseFindingsPayload,
+ recordDraftFailure,
+ recordDraftSuccess,
+ runAudioTimingQa,
+ runContractHtmlQa,
+ runSourceAlignmentQa,
+ samplePlanKey,
+ summarizeDraftInspectDisposition,
+ summarizeVideoFrameQa,
+ writeFrameContactSheet,
+ type DraftRepairBudget,
+ type FrameEvidence,
+ type FrameSampleEvidence,
+ type FrameSamplePlan,
+} from './video_studio_qa';
const log = createLogger('video-studio');
+const COMPOSITION_LOAD_TIMEOUT_MS = Number(process.env.ORKAS_VIDEO_STUDIO_LOAD_TIMEOUT_MS) || 30_000;
+const COMPOSITION_READY_TIMEOUT_MS = Number(process.env.ORKAS_VIDEO_STUDIO_READY_TIMEOUT_MS) || 20_000;
+const COMPOSITION_SCRIPT_TIMEOUT_MS = Number(process.env.ORKAS_VIDEO_STUDIO_SCRIPT_TIMEOUT_MS) || 15_000;
+const COMPOSITION_CAPTURE_TIMEOUT_MS = Number(process.env.ORKAS_VIDEO_STUDIO_CAPTURE_TIMEOUT_MS) || 15_000;
+const COMPOSITION_RENDER_FRAME_TIMEOUT_MS = Number(process.env.ORKAS_VIDEO_STUDIO_RENDER_FRAME_TIMEOUT_MS) || 20_000;
+
export type VideoStudioOp =
| 'composition.lint'
| 'composition.inspect'
@@ -32,6 +63,8 @@ export interface CompositionOptions {
fps?: number;
format?: RenderFormat;
variables?: Record<string, unknown>;
+ frameEvidenceDirAbs?: string;
+ frameSampleTimes?: Array<{ label: string; timeSec: number }>;
signal?: AbortSignal;
onProgress?: (event: { phase: string; message: string; data?: Record<string, unknown> }) => void;
}
@@ -95,6 +128,31 @@ type MediaProbe = {
};
};
+type NativeRenderProfile = {
+ constrained: boolean;
+ machine_ram_gb: number;
+ cost_units: number;
+ decision: 'proceed' | 'degrade' | 'fail_fast';
+ requested_fps: number;
+ render_fps: number;
+ observed_gpu_mode?: 'hardware' | 'software';
+ degraded_fps?: string;
+ degrade_ineffective?: string;
+};
+
+type LoudnessReport = {
+ ok: boolean;
+ input_i: number | null;
+ input_tp: number | null;
+ input_lra: number | null;
+ target_i: number;
+ target_tp: number;
+ target_lra: number;
+ normalized?: unknown;
+ raw_tail?: string;
+ error?: string;
+};
+
const DEFAULT_WIDTH = 1920;
const DEFAULT_HEIGHT = 1080;
const DEFAULT_DURATION_SEC = 5;
@@ -105,6 +163,14 @@ const FFPROBE_TIMEOUT_MS = 30 * 1000;
const AUDIO_DURATION_TOLERANCE_SEC = 0.5;
const MEDIA_DURATION_TOLERANCE_SEC = 0.5;
const VIDEO_STUDIO_AGENT_ID = '79df9cc89f5f';
+const LOW_RAM_GB = 8;
+const HEAVY_RENDER_COST = 3000;
+const LOUDNESS_TARGET_I = -14;
+const LOUDNESS_TARGET_TP = -1;
+const LOUDNESS_TARGET_LRA = 11;
+const LOUDNESS_DRAFT_NORMALIZE_DELTA_LU = 4;
+const REQUIRED_GSAP_TIMELINE_APIS = ['timeScale', 'totalTime', 'totalDuration', 'getChildren'];
+
function round2(n: number): number {
return Math.round((Number.isFinite(n) ? n : 0) * 100) / 100;
}
@@ -167,6 +233,13 @@ function isKnownBundledVendorRef(ref: string): boolean {
return normalizedLocalRefPath(ref) === 'assets/vendor/gsap.min.js';
}
+function gsapVendorCompatibilityIssue(text: string): { code: string; missing: string[] } | null {
+ const s = String(text || '');
+ if (!s.trim()) return { code: 'VENDOR_GSAP_EMPTY', missing: REQUIRED_GSAP_TIMELINE_APIS };
+ const missing = REQUIRED_GSAP_TIMELINE_APIS.filter((api) => !s.includes(api));
+ return missing.length ? { code: 'VENDOR_GSAP_MISSING_TIMELINE_API', missing } : null;
+}
+
function isFileSync(absPath: string): boolean {
try { return fss.statSync(absPath).isFile(); } catch { return false; }
}
@@ -214,14 +287,30 @@ function builtinGsapVendorCandidates(): string[] {
return out;
}
-async function prepareKnownBundledVendor(ref: string, targetAbsPath: string): Promise<boolean> {
- if (!isKnownBundledVendorRef(ref)) return false;
- if (isFileSync(targetAbsPath)) return true;
+async function copyKnownBundledVendor(ref: string, targetAbsPath: string): Promise<{ ok: true } | { ok: false; code: string; missing?: string[] }> {
+ if (!isKnownBundledVendorRef(ref)) return { ok: false, code: 'LOCAL_VENDOR_UNKNOWN' };
const source = builtinGsapVendorCandidates().find((candidate) => isFileSync(candidate));
- if (!source) return false;
+ if (!source) return { ok: false, code: 'VENDOR_GSAP_SOURCE_MISSING' };
+ const sourceIssue = gsapVendorCompatibilityIssue(await fs.readFile(source, 'utf8').catch(() => ''));
+ if (sourceIssue) return { ok: false, code: 'VENDOR_GSAP_SOURCE_INCOMPATIBLE', missing: sourceIssue.missing };
await fs.mkdir(path.dirname(targetAbsPath), { recursive: true });
await fs.copyFile(source, targetAbsPath);
- return true;
+ return { ok: true };
+}
+
+async function validateKnownBundledVendor(ref: string, targetAbsPath: string): Promise<Issue | null> {
+ if (!isKnownBundledVendorRef(ref)) return null;
+ const text = await fs.readFile(targetAbsPath, 'utf8').catch(() => '');
+ const issue = gsapVendorCompatibilityIssue(text);
+ if (!issue) return null;
+ return {
+ code: 'VENDOR_GSAP_INCOMPATIBLE',
+ severity: 'error',
+ selector: `[src="${ref}"]`,
+ message: `Existing GSAP vendor is missing required timeline APIs: ${issue.missing.join(', ')}. Remove or replace assets/vendor/gsap.min.js; do not patch it manually inside the composition.`,
+ fixHint: 'Delete the incompatible local vendor file so VideoStudio can prepare the built-in GSAP vendor, or replace it with a compatible full GSAP build.',
+ source: 'orkas-native-vendor-assets',
+ };
}
function extractResourceRefs(html: string): Array<{ attr: string; ref: string }> {
@@ -231,6 +320,10 @@ function extractResourceRefs(html: string): Array<{ attr: string; ref: string }>
while ((m = re.exec(html)) !== null) {
refs.push({ attr: m[1].toLowerCase(), ref: normalizeRef(m[2] ?? m[3] ?? '') });
}
+ const cssRe = /\burl\(\s*(?:"([^"]*)"|'([^']*)'|([^"')]+))\s*\)/gi;
+ while ((m = cssRe.exec(html)) !== null) {
+ refs.push({ attr: 'css-url', ref: normalizeRef(m[1] ?? m[2] ?? m[3] ?? '') });
+ }
return refs;
}
@@ -254,6 +347,73 @@ function qualityFps(quality: RenderQuality | undefined, fps: number | undefined)
return 30;
}
+function machineRamGB(): number {
+ const mocked = Number(process.env.ORKAS_MOCK_RAM_GB);
+ if (Number.isFinite(mocked) && mocked > 0) return Math.round(mocked * 10) / 10;
+ return Math.round((os.totalmem() / 1024 ** 3) * 10) / 10;
+}
+
+function renderProfilePath(compositionDirAbs: string): string {
+ return path.join(path.resolve(compositionDirAbs, '..', 'render'), '.render-profile.json');
+}
+
+async function readObservedGpuMode(compositionDirAbs: string): Promise<'hardware' | 'software' | undefined> {
+ const mocked = process.env.ORKAS_MOCK_OBSERVED_GPU_MODE;
+ if (mocked === 'hardware' || mocked === 'software') return mocked;
+ try {
+ const parsed = JSON.parse(await fs.readFile(renderProfilePath(compositionDirAbs), 'utf8')) as { gpuMode?: unknown };
+ return parsed.gpuMode === 'hardware' || parsed.gpuMode === 'software' ? parsed.gpuMode : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function isConstrainedMachine(totalRamGB: number, observedGpuMode?: 'hardware' | 'software'): boolean {
+ return totalRamGB <= LOW_RAM_GB || observedGpuMode === 'software';
+}
+
+function estimateRenderCost(width: number, height: number, durationSec: number, fps: number): number {
+ const frames = Math.max(1, durationSec) * Math.max(1, fps);
+ const megapixels = Math.max(1, (Math.max(1, width) * Math.max(1, height)) / 1e6);
+ return Math.round(frames * megapixels);
+}
+
+function renderCostDecision(opts: { constrained: boolean; costUnits: number; isFinal: boolean }): NativeRenderProfile['decision'] {
+ if (!opts.constrained || opts.costUnits <= HEAVY_RENDER_COST) return 'proceed';
+ return opts.isFinal ? 'fail_fast' : 'degrade';
+}
+
+function degradedFps(fps: number): number {
+ return fps > 30 ? 30 : fps;
+}
+
+async function resolveNativeRenderProfile(
+ compositionDirAbs: string,
+ meta: CompositionMeta,
+ quality: RenderQuality | undefined,
+ requestedFps: number,
+): Promise<NativeRenderProfile> {
+ const ramGB = machineRamGB();
+ const observedGpuMode = await readObservedGpuMode(compositionDirAbs);
+ const constrained = isConstrainedMachine(ramGB, observedGpuMode);
+ const costUnits = estimateRenderCost(meta.width, meta.height, meta.durationSec, requestedFps);
+ const decision = renderCostDecision({ constrained, costUnits, isFinal: quality === 'high' });
+ const renderFps = decision === 'degrade' ? degradedFps(requestedFps) : requestedFps;
+ return {
+ constrained,
+ machine_ram_gb: ramGB,
+ ...(observedGpuMode ? { observed_gpu_mode: observedGpuMode } : {}),
+ cost_units: costUnits,
+ decision,
+ requested_fps: requestedFps,
+ render_fps: renderFps,
+ ...(renderFps !== requestedFps ? { degraded_fps: `${requestedFps}->${renderFps}` } : {}),
+ ...(decision === 'degrade' && renderFps === requestedFps
+ ? { degrade_ineffective: 'fps already at floor; heavy composition may render slowly on this machine' }
+ : {}),
+ };
+}
+
function crfForQuality(quality: RenderQuality | undefined): number {
if (quality === 'high') return 16;
if (quality === 'standard') return 20;
@@ -405,18 +565,27 @@ async function loadCompositionMeta(compositionDirAbs: string): Promise<{ meta: C
}
let exists = await fs.stat(abs).catch(() => null);
if ((!exists || !exists.isFile()) && isKnownBundledVendorRef(item.ref)) {
- const prepared = await prepareKnownBundledVendor(item.ref, abs);
- if (prepared) exists = await fs.stat(abs).catch(() => null);
- else {
+ const prepared = await copyKnownBundledVendor(item.ref, abs);
+ if (prepared.ok === false) {
issues.push({
- code: 'LOCAL_VENDOR_MISSING',
+ code: prepared.code,
severity: 'error',
selector: `[${item.attr}="${item.ref}"]`,
message: `Built-in vendor resource could not be prepared: ${item.ref}`,
- fixHint: 'Use the built-in stage-compose vendor path assets/vendor/gsap.min.js or remove the runtime dependency.',
+ fixHint: prepared.missing
+ ? `Built-in GSAP vendor is missing required APIs: ${prepared.missing.join(', ')}.`
+ : 'Use the built-in stage-compose vendor path assets/vendor/gsap.min.js or remove the runtime dependency.',
});
continue;
}
+ exists = await fs.stat(abs).catch(() => null);
+ }
+ if (exists && exists.isFile() && isKnownBundledVendorRef(item.ref)) {
+ const vendorIssue = await validateKnownBundledVendor(item.ref, abs);
+ if (vendorIssue) {
+ issues.push(vendorIssue);
+ continue;
+ }
}
if (!exists || !exists.isFile()) {
issues.push({
@@ -469,6 +638,86 @@ function fileUrl(absPath: string): string {
return encodeURI(`file://${resolved}`);
}
+function realPathOrResolved(absPath: string): string {
+ const resolved = path.resolve(absPath);
+ try {
+ return fss.realpathSync.native(resolved);
+ } catch {
+ return resolved;
+ }
+}
+
+function pathInsideOrEqual(candidateAbs: string, rootAbs: string): boolean {
+ const candidate = realPathOrResolved(candidateAbs);
+ const root = realPathOrResolved(rootAbs);
+ const rel = path.relative(root, candidate);
+ return rel === '' || (!!rel && !rel.startsWith('..') && !path.isAbsolute(rel));
+}
+
+export function isCompositionRequestUrlAllowed(requestUrl: string, compositionDirAbs: string): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(requestUrl);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol === 'about:') return parsed.href === 'about:blank';
+ if (parsed.protocol === 'data:' || parsed.protocol === 'blob:') return true;
+ if (parsed.protocol !== 'file:') return false;
+ try {
+ return pathInsideOrEqual(fileURLToPath(parsed), compositionDirAbs);
+ } catch {
+ return false;
+ }
+}
+
+class VideoStudioTimeoutError extends Error {
+ constructor(
+ readonly errorCode: string,
+ message: string,
+ ) {
+ super(message);
+ this.name = 'VideoStudioTimeoutError';
+ }
+}
+
+function videoStudioErrorCode(err: unknown, fallback: string): string {
+ return err instanceof VideoStudioTimeoutError ? err.errorCode : fallback;
+}
+
+export async function withVideoStudioTimeout<T>(
+ promise: Promise<T>,
+ timeoutMs: number,
+ errorCode: string,
+ message: string,
+ onTimeout?: () => void,
+): Promise<T> {
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return promise;
+ return new Promise<T>((resolve, reject) => {
+ let settled = false;
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ try { onTimeout?.(); } catch { /* best effort */ }
+ reject(new VideoStudioTimeoutError(errorCode, message));
+ }, timeoutMs);
+ promise.then(
+ (value) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (err) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(err);
+ },
+ );
+ });
+}
+
async function withCompositionWindow<T>(
meta: CompositionMeta,
p: CompositionOptions,
@@ -481,7 +730,7 @@ async function withCompositionWindow<T>(
const ses = session.fromPartition(partition);
ses.webRequest.onBeforeRequest((details, callback) => {
const url = String(details.url || '');
- if (/^https?:\/\//i.test(url)) {
+ if (!isCompositionRequestUrlAllowed(url, p.compositionDirAbs)) {
callback({ cancel: true });
return;
}
@@ -503,14 +752,41 @@ async function withCompositionWindow<T>(
},
});
try {
+ const destroyOnTimeout = () => {
+ try { win.destroy(); } catch { /* best effort */ }
+ };
const loaded = new Promise<void>((resolve, reject) => {
win.webContents.once('did-finish-load', () => resolve());
win.webContents.once('did-fail-load', (_e, _code, desc) => reject(new Error(`did-fail-load: ${desc}`)));
});
- await win.loadURL(fileUrl(meta.htmlPath));
- await loaded;
- await win.webContents.executeJavaScript(buildTimelineAdapterScript(meta, p.variables), true);
- await waitForReady(win);
+ await withVideoStudioTimeout(
+ win.loadURL(fileUrl(meta.htmlPath)),
+ COMPOSITION_LOAD_TIMEOUT_MS,
+ 'E_COMPOSITION_LOAD_TIMEOUT',
+ 'composition window timed out while loading index.html.',
+ destroyOnTimeout,
+ );
+ await withVideoStudioTimeout(
+ loaded,
+ COMPOSITION_LOAD_TIMEOUT_MS,
+ 'E_COMPOSITION_LOAD_TIMEOUT',
+ 'composition window timed out before load completion.',
+ destroyOnTimeout,
+ );
+ await withVideoStudioTimeout(
+ win.webContents.executeJavaScript(buildTimelineAdapterScript(meta, p.variables), true),
+ COMPOSITION_SCRIPT_TIMEOUT_MS,
+ 'E_COMPOSITION_SCRIPT_TIMEOUT',
+ 'composition window timed out while installing the timeline adapter.',
+ destroyOnTimeout,
+ );
+ await withVideoStudioTimeout(
+ waitForReady(win),
+ COMPOSITION_READY_TIMEOUT_MS,
+ 'E_COMPOSITION_READY_TIMEOUT',
+ 'composition window timed out while waiting for fonts, images, and media metadata.',
+ destroyOnTimeout,
+ );
return await fn(win);
} finally {
try { win.destroy(); } catch { /* best effort */ }
@@ -635,13 +911,15 @@ async function waitForReady(win: ElectronBrowserWindow): Promise<void> {
}
async function seek(win: ElectronBrowserWindow, tSec: number): Promise<void> {
- await win.webContents.executeJavaScript(`
+ await withVideoStudioTimeout(win.webContents.executeJavaScript(`
(async () => {
if (window.__ORKAS_VIDEO__ && typeof window.__ORKAS_VIDEO__.seek === 'function') {
await window.__ORKAS_VIDEO__.seek(${JSON.stringify(tSec)});
}
})()
-`, true);
+`, true), COMPOSITION_SCRIPT_TIMEOUT_MS, 'E_COMPOSITION_SEEK_TIMEOUT', `composition seek timed out at ${round2(tSec)}s.`, () => {
+ try { win.destroy(); } catch { /* best effort */ }
+ });
}
function sampleTimes(durationSec: number): number[] {
@@ -660,13 +938,19 @@ export async function inspectComposition(p: CompositionOptions): Promise<VideoSt
await withCompositionWindow(loaded.meta, p, async (win) => {
for (const t of samples) {
await seek(win, t);
- const sampleIssues = await win.webContents.executeJavaScript(buildInspectScript(loaded.meta, t), true) as Issue[];
+ const sampleIssues = await withVideoStudioTimeout(
+ win.webContents.executeJavaScript(buildInspectScript(loaded.meta, t), true) as Promise<Issue[]>,
+ COMPOSITION_SCRIPT_TIMEOUT_MS,
+ 'E_INSPECT_TIMEOUT',
+ `composition inspect timed out at ${round2(t)}s.`,
+ () => { try { win.destroy(); } catch { /* best effort */ } },
+ );
issues.push(...sampleIssues);
}
});
} catch (err) {
issues.push({
- code: 'INSPECT_RENDERER_FAILED',
+ code: err instanceof VideoStudioTimeoutError ? 'INSPECT_RENDERER_TIMEOUT' : 'INSPECT_RENDERER_FAILED',
severity: 'error',
selector: 'document',
message: (err as Error).message,
@@ -734,13 +1018,28 @@ export async function snapshotComposition(p: CompositionOptions): Promise<VideoS
return { ok: false, op: 'composition.snapshot', errorCode: 'E_OUTPUT_REQUIRED', message: 'snapshot output path is required.' };
}
await fs.mkdir(path.dirname(p.snapshotAbsPath), { recursive: true });
- await withCompositionWindow(loaded.meta, p, async (win) => {
- await seek(win, 0);
- const image = await win.webContents.capturePage({ x: 0, y: 0, width: loaded.meta!.width, height: loaded.meta!.height });
- await fs.writeFile(p.snapshotAbsPath!, image.toPNG());
- });
- const st = await fs.stat(p.snapshotAbsPath);
- return { ok: true, op: 'composition.snapshot', path: p.snapshotAbsPath, bytes: st.size };
+ try {
+ await withCompositionWindow(loaded.meta, p, async (win) => {
+ await seek(win, 0);
+ const image = await withVideoStudioTimeout(
+ win.webContents.capturePage({ x: 0, y: 0, width: loaded.meta!.width, height: loaded.meta!.height }),
+ COMPOSITION_CAPTURE_TIMEOUT_MS,
+ 'E_SNAPSHOT_TIMEOUT',
+ 'composition snapshot timed out while capturing the frame.',
+ () => { try { win.destroy(); } catch { /* best effort */ } },
+ );
+ await fs.writeFile(p.snapshotAbsPath!, image.toPNG());
+ });
+ const st = await fs.stat(p.snapshotAbsPath);
+ return { ok: true, op: 'composition.snapshot', path: p.snapshotAbsPath, bytes: st.size };
+ } catch (err) {
+ return {
+ ok: false,
+ op: 'composition.snapshot',
+ errorCode: videoStudioErrorCode(err, 'E_SNAPSHOT_FAILED'),
+ message: (err as Error).message,
+ };
+ }
}
export async function renderComposition(p: CompositionOptions): Promise<VideoStudioResult> {
@@ -755,29 +1054,85 @@ export async function renderComposition(p: CompositionOptions): Promise<VideoStu
if (!p.outputAbsPath) {
return { ok: false, op: 'composition.render', errorCode: 'E_OUTPUT_REQUIRED', message: 'output path is required.' };
}
+ const requestedFps = qualityFps(p.quality, p.fps);
+ const renderProfile = await resolveNativeRenderProfile(p.compositionDirAbs, loaded.meta, p.quality, requestedFps);
+ if (renderProfile.decision === 'fail_fast') {
+ return {
+ ok: false,
+ op: 'composition.render',
+ errorCode: 'E_RENDER_TOO_HEAVY',
+ message: `This ${loaded.meta.width}x${loaded.meta.height}, ${Math.round(loaded.meta.durationSec)}s composition cannot be rendered at ${p.quality || 'standard'} quality on this constrained machine without likely hanging. Lower the resolution, fps, or length; keep the draft; or render on a stronger machine.`,
+ render_profile: renderProfile,
+ };
+ }
const bins = bundledFfmpegPaths();
if (!bins.ffmpeg) {
return { ok: false, op: 'composition.render', errorCode: 'E_FFMPEG_MISSING', message: 'Bundled ffmpeg not found.' };
}
- const fps = qualityFps(p.quality, p.fps);
+ const fps = renderProfile.render_fps;
const totalFrames = Math.max(1, Math.ceil(loaded.meta.durationSec * fps));
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'orkas-video-studio-'));
const framePattern = path.join(tmp, 'frame-%06d.png');
+ const evidenceDirAbs = p.frameEvidenceDirAbs;
+ const samplePlans = evidenceDirAbs
+ ? (p.frameSampleTimes || sampleTimes(loaded.meta.durationSec).map((timeSec, index) => ({ label: `sample-${index + 1}`, timeSec })))
+ .map((item) => ({
+ label: samplePlanKey(item.label),
+ timeSec: Math.max(0, Math.min(loaded.meta!.durationSec - 0.001, item.timeSec)),
+ frameIndex: Math.max(0, Math.min(totalFrames - 1, Math.floor(Math.max(0, item.timeSec) * fps))),
+ }))
+ : [];
+ const sampleByFrame = new Map<number, FrameSamplePlan>();
+ for (const sample of samplePlans) {
+ if (!sampleByFrame.has(sample.frameIndex)) sampleByFrame.set(sample.frameIndex, sample);
+ }
+ const capturedSamples: FrameSampleEvidence[] = [];
try {
+ if (evidenceDirAbs) await fs.mkdir(evidenceDirAbs, { recursive: true });
p.onProgress?.({ phase: 'composition.render', message: `Capturing ${totalFrames} frames with the native renderer.`, data: { totalFrames, fps } });
await withCompositionWindow(loaded.meta, p, async (win) => {
for (let frame = 0; frame < totalFrames; frame += 1) {
if (p.signal?.aborted) throw new Error('render aborted');
const t = frame / fps;
await seek(win, Math.min(t, Math.max(0, loaded.meta!.durationSec - 0.001)));
- const image = await win.webContents.capturePage({ x: 0, y: 0, width: loaded.meta!.width, height: loaded.meta!.height });
- await fs.writeFile(path.join(tmp, `frame-${String(frame + 1).padStart(6, '0')}.png`), image.toPNG());
+ const image = await withVideoStudioTimeout(
+ win.webContents.capturePage({ x: 0, y: 0, width: loaded.meta!.width, height: loaded.meta!.height }),
+ COMPOSITION_RENDER_FRAME_TIMEOUT_MS,
+ 'E_RENDER_CAPTURE_TIMEOUT',
+ `composition render timed out while capturing frame ${frame + 1}/${totalFrames}.`,
+ () => { try { win.destroy(); } catch { /* best effort */ } },
+ );
+ const png = image.toPNG();
+ await fs.writeFile(path.join(tmp, `frame-${String(frame + 1).padStart(6, '0')}.png`), png);
+ const sample = sampleByFrame.get(frame);
+ if (sample && evidenceDirAbs) {
+ const stats = analyzeNativeImage(image);
+ const samplePath = path.join(evidenceDirAbs, `${String(capturedSamples.length + 1).padStart(2, '0')}-${sample.label}.png`);
+ await fs.writeFile(samplePath, png);
+ capturedSamples.push({
+ label: sample.label,
+ time_seconds: round2(sample.timeSec),
+ frame_index: frame,
+ path: samplePath,
+ ...stats,
+ });
+ }
if (frame % Math.max(1, Math.floor(fps * 2)) === 0) {
p.onProgress?.({ phase: 'composition.render.capture', message: `Captured frame ${frame + 1}/${totalFrames}.`, data: { frame: frame + 1, totalFrames } });
}
}
});
+ let frameEvidence: FrameEvidence | undefined;
+ if (evidenceDirAbs) {
+ const contactSheet = await writeFrameContactSheet(evidenceDirAbs, capturedSamples);
+ frameEvidence = {
+ evidence_dir: evidenceDirAbs,
+ contact_sheet: contactSheet,
+ frame_paths: capturedSamples.map((sample) => sample.path),
+ samples: capturedSamples,
+ };
+ }
await fs.mkdir(path.dirname(p.outputAbsPath), { recursive: true });
const encoded = await encodeFrames({
ffmpeg: bins.ffmpeg,
@@ -804,9 +1159,16 @@ export async function renderComposition(p: CompositionOptions): Promise<VideoStu
fps,
frames: totalFrames,
canvas: { width: loaded.meta.width, height: loaded.meta.height, durationSec: loaded.meta.durationSec },
+ render_profile: renderProfile,
+ ...(frameEvidence ? { frame_evidence: frameEvidence } : {}),
};
} catch (err) {
- return { ok: false, op: 'composition.render', errorCode: p.signal?.aborted ? 'E_RENDER_ABORTED' : 'E_RENDER_FAILED', message: (err as Error).message };
+ return {
+ ok: false,
+ op: 'composition.render',
+ errorCode: p.signal?.aborted ? 'E_RENDER_ABORTED' : videoStudioErrorCode(err, 'E_RENDER_FAILED'),
+ message: (err as Error).message,
+ };
} finally {
await fs.rm(tmp, { recursive: true, force: true }).catch(() => {});
}
@@ -895,6 +1257,107 @@ async function runProcess(
});
}
+function parseLastJsonObject(text: string): Record<string, unknown> | null {
+ const raw = String(text || '');
+ const end = raw.lastIndexOf('}');
+ if (end < 0) return null;
+ const start = raw.lastIndexOf('{', end);
+ if (start < 0) return null;
+ try {
+ const parsed = JSON.parse(raw.slice(start, end + 1));
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;
+ } catch {
+ return null;
+ }
+}
+
+function loudnessNumber(value: unknown): number | null {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : null;
+}
+
+function loudnessReportFromJson(value: Record<string, unknown> | null, rawTail = ''): LoudnessReport {
+ if (!value) {
+ return {
+ ok: false,
+ input_i: null,
+ input_tp: null,
+ input_lra: null,
+ target_i: LOUDNESS_TARGET_I,
+ target_tp: LOUDNESS_TARGET_TP,
+ target_lra: LOUDNESS_TARGET_LRA,
+ raw_tail: rawTail,
+ error: 'Could not parse ffmpeg loudnorm JSON.',
+ };
+ }
+ return {
+ ok: true,
+ input_i: loudnessNumber(value.input_i),
+ input_tp: loudnessNumber(value.input_tp),
+ input_lra: loudnessNumber(value.input_lra),
+ target_i: LOUDNESS_TARGET_I,
+ target_tp: LOUDNESS_TARGET_TP,
+ target_lra: LOUDNESS_TARGET_LRA,
+ normalized: value,
+ };
+}
+
+export function shouldNormalizeLoudness(report: LoudnessReport | null, quality: RenderQuality | undefined): { normalize: boolean; reason: string } {
+ if (!report || report.ok === false) return { normalize: false, reason: 'loudness analysis unavailable' };
+ if (quality === 'high') return { normalize: true, reason: 'high quality export' };
+ const integrated = report.input_i;
+ if (integrated !== null && Math.abs(integrated - LOUDNESS_TARGET_I) >= LOUDNESS_DRAFT_NORMALIZE_DELTA_LU) {
+ return { normalize: true, reason: `integrated loudness ${round2(integrated)} LUFS is far from target ${LOUDNESS_TARGET_I} LUFS` };
+ }
+ const truePeak = report.input_tp;
+ if (truePeak !== null && truePeak > LOUDNESS_TARGET_TP + 0.5) {
+ return { normalize: true, reason: `true peak ${round2(truePeak)} dBTP exceeds target ${LOUDNESS_TARGET_TP} dBTP` };
+ }
+ return { normalize: false, reason: 'within draft loudness tolerance' };
+}
+
+async function analyzeLoudness(ffmpeg: string, mediaAbsPath: string, signal?: AbortSignal): Promise<LoudnessReport> {
+ const r = await runProcess(ffmpeg, [
+ '-hide_banner',
+ '-nostats',
+ '-i', mediaAbsPath,
+ '-af', `loudnorm=I=${LOUDNESS_TARGET_I}:TP=${LOUDNESS_TARGET_TP}:LRA=${LOUDNESS_TARGET_LRA}:print_format=json`,
+ '-f', 'null',
+ '-',
+ ], { signal, timeoutMs: FFPROBE_TIMEOUT_MS });
+ const text = `${r.stdout || ''}\n${r.stderr || ''}`;
+ if (r.aborted) return { ...loudnessReportFromJson(null), error: 'loudness analysis aborted.' };
+ if (r.timedOut) return { ...loudnessReportFromJson(null), error: 'loudness analysis timed out.' };
+ return loudnessReportFromJson(parseLastJsonObject(text), text.slice(-1000));
+}
+
+async function normalizeAudioInPlace(ffmpeg: string, mediaAbsPath: string, signal?: AbortSignal): Promise<Record<string, unknown>> {
+ const ext = path.extname(mediaAbsPath) || '.mp4';
+ if (ext.toLowerCase() !== '.mp4') {
+ return { skipped: true, reason: 'audio normalization currently applies only to mp4 output' };
+ }
+ const tmp = path.join(path.dirname(mediaAbsPath), `${path.basename(mediaAbsPath, ext)}.norm-${Date.now()}${ext}`);
+ const r = await runProcess(ffmpeg, [
+ '-y',
+ '-hide_banner',
+ '-loglevel', 'error',
+ '-i', mediaAbsPath,
+ '-af', `loudnorm=I=${LOUDNESS_TARGET_I}:TP=${LOUDNESS_TARGET_TP}:LRA=${LOUDNESS_TARGET_LRA}`,
+ '-c:v', 'copy',
+ '-c:a', 'aac',
+ '-b:a', '192k',
+ tmp,
+ ], { signal, timeoutMs: RENDER_TIMEOUT_MS });
+ if (r.aborted) return { skipped: true, reason: 'normalization aborted' };
+ if (r.timedOut) return { skipped: true, reason: 'normalization timed out' };
+ if (r.code !== 0) {
+ await fs.rm(tmp, { force: true }).catch(() => {});
+ return { skipped: true, reason: 'normalization failed', stderr_tail: redactPaths(r.stderr.slice(-1000)) };
+ }
+ await fs.rename(tmp, mediaAbsPath);
+ return { skipped: false, path: mediaAbsPath };
+}
+
async function buildMediaQa(
meta: CompositionMeta,
mediaProbe: MediaProbe | null,
@@ -1012,6 +1475,35 @@ async function buildMediaQa(
};
}
+async function failDraft(
+ report: Record<string, unknown>,
+ p: CompositionOptions,
+ code: string,
+ message: string,
+ extra: Record<string, unknown>,
+ repairBudget: DraftRepairBudget,
+): Promise<VideoStudioResult> {
+ report.error = {
+ code,
+ message,
+ ...(extra.repair_target ? { repair_target: extra.repair_target } : {}),
+ };
+ const budgetSummary = await recordDraftFailure(repairBudget, p.reportAbsPath, code, message, extra);
+ const steps = report.steps as Record<string, unknown>;
+ steps.repair_budget = budgetSummary;
+ report.repair_budget = budgetSummary;
+ await writeReportIfRequested(p.reportAbsPath, report);
+ return {
+ ok: false,
+ op: 'composition.draft',
+ errorCode: code,
+ message,
+ report,
+ repair_budget: budgetSummary,
+ ...extra,
+ };
+}
+
export async function draftComposition(p: CompositionOptions): Promise<VideoStudioResult> {
const report: Record<string, unknown> = {
ok: false,
@@ -1022,73 +1514,194 @@ export async function draftComposition(p: CompositionOptions): Promise<VideoStud
steps: {},
};
const steps = report.steps as Record<string, unknown>;
+ const repairBudget = await initDraftRepairBudget(p.compositionDirAbs);
+ steps.repair_budget = repairBudget.summary;
+ report.repair_budget = repairBudget.summary;
+ if (repairBudget.blocked) {
+ report.error = {
+ code: 'E_REPAIR_BUDGET_EXCEEDED',
+ message: `Draft repair budget exceeded: the initial draft plus ${DRAFT_REPAIR_MAX_PASSES} repair pass(es) still failed. Stop and report the blocker instead of continuing to patch.`,
+ };
+ await writeReportIfRequested(p.reportAbsPath, report);
+ return {
+ ok: false,
+ op: 'composition.draft',
+ errorCode: 'E_REPAIR_BUDGET_EXCEEDED',
+ message: String((report.error as Record<string, unknown>).message),
+ report,
+ repair_budget: repairBudget.summary,
+ last_error: repairBudget.summary.last_error,
+ };
+ }
+
const lint = await lintComposition(p);
steps.lint = lint;
if (lint.ok === false) return lint;
- const parsedLint = parseFindings(String(lint.findings || ''));
- if ((parsedLint.errorCount || 0) > 0) {
- report.error = { code: 'E_LINT_BLOCKED', message: 'composition lint failed.' };
- await writeReportIfRequested(p.reportAbsPath, report);
- return { ok: false, op: 'composition.draft', errorCode: 'E_LINT_BLOCKED', message: 'composition lint failed.', report };
+ const parsedLint = parseFindingsPayload(String(lint.findings || ''));
+ if (parsedLint.errorCount > 0) {
+ return failDraft(report, p, 'E_LINT_BLOCKED', 'composition lint failed.', {
+ lint_summary: {
+ error_count: parsedLint.errorCount,
+ warning_count: parsedLint.warningCount,
+ issues: parsedLint.issues.slice(0, 12),
+ },
+ }, repairBudget);
+ }
+
+ const loaded = await loadCompositionMeta(p.compositionDirAbs);
+ if (loaded.meta) {
+ const contractLoad = await loadDesignContract(p.compositionDirAbs);
+ const sceneMapLoad = await loadSceneMap(p.compositionDirAbs);
+ const narrationMapLoad = await loadNarrationMap(p.compositionDirAbs);
+ const shotlistLoad = await loadShotlist(p.compositionDirAbs);
+ steps.authoring = {
+ ok: true,
+ mode: 'model_authored_html',
+ path: loaded.meta.htmlPath,
+ design_contract_path: contractLoad.path,
+ scene_map_path: sceneMapLoad.exists ? sceneMapLoad.path : '',
+ shotlist_path: shotlistLoad.exists ? shotlistLoad.path : '',
+ };
+
+ const contractHtml = await runContractHtmlQa(loaded.meta, loaded.issues, contractLoad, sceneMapLoad, p.compositionDirAbs);
+ steps.contract_html = contractHtml;
+ if (contractHtml.ok === false) {
+ const firstError = ((contractHtml.issues as Issue[] | undefined) || []).find((issue) => issue.severity === 'error');
+ return failDraft(report, p, 'E_CONTRACT_HTML_BLOCKED', 'design-contract/scene-map/index.html consistency failed draft QA.', {
+ repair_target: firstError?.selector || 'index.html',
+ contract_html: contractHtml,
+ }, repairBudget);
+ }
+
+ const sourceAlignment = await runSourceAlignmentQa(sceneMapLoad, shotlistLoad);
+ steps.source_alignment = sourceAlignment;
+ if (sourceAlignment.ok === false) {
+ return failDraft(report, p, 'E_SOURCE_ALIGNMENT_BLOCKED', 'script/shotlist/scene-map alignment failed draft QA.', {
+ repair_target: 'scene-map.json',
+ source_alignment: sourceAlignment,
+ }, repairBudget);
+ }
+
+ const audioTiming = await runAudioTimingQa(loaded.meta, contractLoad, sceneMapLoad, narrationMapLoad, p.compositionDirAbs);
+ steps.audio_timing = audioTiming;
+ if (audioTiming.ok === false) {
+ const firstError = ((audioTiming.issues as Issue[] | undefined) || []).find((issue) => issue.severity === 'error');
+ return failDraft(report, p, 'E_AUDIO_TIMING_BLOCKED', 'audio timing or narration mapping failed draft QA.', {
+ repair_target: firstError?.selector || 'scene-map.json',
+ audio_timing: audioTiming,
+ }, repairBudget);
+ }
}
const inspect = await inspectComposition(p);
- steps.inspect = inspect;
+ const inspectDisposition = inspect.ok
+ ? summarizeDraftInspectDisposition(String(inspect.findings || ''))
+ : { blocking_error_count: 1, advisory_count: 0, blocking_issues: [], advisory_issues: [] };
+ steps.inspect = {
+ ...inspect,
+ draft_disposition: inspectDisposition,
+ };
if (inspect.ok === false) return inspect;
if (p.findingsAbsPath && inspect.ok) {
await fs.mkdir(path.dirname(p.findingsAbsPath), { recursive: true });
await fs.writeFile(p.findingsAbsPath, String(inspect.findings || ''), 'utf8');
}
+ if (Number(inspectDisposition.blocking_error_count || 0) > 0) {
+ return failDraft(report, p, 'E_INSPECT_BLOCKED', 'inspect found non-visual blockers; repair design-contract/scene-map/HTML before rendering.', {
+ inspect_summary: parseFindingsPayload(String(inspect.findings || '')),
+ draft_disposition: inspectDisposition,
+ }, repairBudget);
+ }
- const render = await renderComposition(p);
+ const metaForRender = loaded.meta ?? (await loadCompositionMeta(p.compositionDirAbs)).meta;
+ const sceneMapForSamples = await loadSceneMap(p.compositionDirAbs);
+ const fps = qualityFps(p.quality, p.fps);
+ const evidenceDirAbs = p.frameEvidenceDirAbs
+ || (p.outputAbsPath ? path.join(path.dirname(p.outputAbsPath), 'draft-evidence') : path.join(p.compositionDirAbs, 'qa', 'draft-evidence'));
+ const render = await renderComposition({
+ ...p,
+ frameEvidenceDirAbs: evidenceDirAbs,
+ ...(metaForRender ? { frameSampleTimes: buildDraftFrameSamplePlan(metaForRender, sceneMapForSamples.value, fps) } : {}),
+ });
steps.render = render;
+ if ((render as { render_profile?: unknown }).render_profile) {
+ steps.render_profile = (render as { render_profile?: unknown }).render_profile;
+ }
if (render.ok === false) {
- report.error = { code: render.errorCode, message: render.message };
- await writeReportIfRequested(p.reportAbsPath, report);
- return { ...render, report };
+ return failDraft(report, p, render.errorCode, render.message, {
+ render,
+ }, repairBudget);
}
- const loaded = await loadCompositionMeta(p.compositionDirAbs);
- const mediaProbe = ((render as { probe?: MediaProbe | null }).probe ?? null);
+ const renderPath = String(render.path || p.outputAbsPath || '');
+ let finalBytes = typeof render.bytes === 'number' ? render.bytes : 0;
+ let mediaProbe = ((render as { probe?: MediaProbe | null }).probe ?? null);
steps.media_probe = mediaProbe;
- if (loaded.meta) {
- const mediaQa = await buildMediaQa(loaded.meta, mediaProbe, bundledFfmpegPaths().ffprobe, p.signal);
+ const binsForPostprocess = bundledFfmpegPaths();
+ if (renderPath && mediaProbe?.audio && binsForPostprocess.ffmpeg) {
+ const loudnessBefore = await analyzeLoudness(binsForPostprocess.ffmpeg, renderPath, p.signal);
+ steps.loudness_before = loudnessBefore;
+ const normalizeDecision = shouldNormalizeLoudness(loudnessBefore, p.quality);
+ if (normalizeDecision.normalize) {
+ steps.audio_normalize = {
+ decision: normalizeDecision,
+ ...(await normalizeAudioInPlace(binsForPostprocess.ffmpeg, renderPath, p.signal)),
+ };
+ if ((steps.audio_normalize as { skipped?: boolean }).skipped === false) {
+ mediaProbe = binsForPostprocess.ffprobe ? await probeMedia(binsForPostprocess.ffprobe, renderPath, p.signal) : mediaProbe;
+ steps.media_probe = mediaProbe;
+ steps.loudness_after = await analyzeLoudness(binsForPostprocess.ffmpeg, renderPath, p.signal);
+ const st = await fs.stat(renderPath).catch(() => null);
+ if (st?.isFile()) finalBytes = st.size;
+ }
+ } else {
+ steps.audio_normalize = { skipped: true, reason: normalizeDecision.reason, decision: normalizeDecision };
+ }
+ } else {
+ steps.audio_normalize = { skipped: true, reason: mediaProbe?.audio ? 'ffmpeg unavailable' : 'no audio stream' };
+ }
+ if (metaForRender) {
+ const mediaQa = await buildMediaQa(metaForRender, mediaProbe, binsForPostprocess.ffprobe, p.signal);
steps.media_qa = mediaQa;
if (mediaQa.ok === false) {
- report.error = { code: 'E_MEDIA_QA_BLOCKED', message: 'draft media QA failed.' };
- await writeReportIfRequested(p.reportAbsPath, report);
- return { ok: false, op: 'composition.draft', errorCode: 'E_MEDIA_QA_BLOCKED', message: 'draft media QA failed.', report };
+ return failDraft(report, p, 'E_MEDIA_QA_BLOCKED', 'draft media QA failed.', {
+ media_qa: mediaQa,
+ }, repairBudget);
+ }
+ const videoQa = summarizeVideoFrameQa(((render as { frame_evidence?: FrameEvidence }).frame_evidence ?? null), metaForRender.durationSec);
+ steps.video_qa = videoQa;
+ if (videoQa.ok === false) {
+ return failDraft(report, p, 'E_VIDEO_QA_BLOCKED', 'video-level QA failed; repair design-contract/scene-map/HTML before Gate D.', {
+ video_qa: videoQa,
+ }, repairBudget);
}
}
+ const successBudget = await recordDraftSuccess(repairBudget, p.reportAbsPath, render.path as string | undefined);
+ steps.repair_budget = successBudget;
+ report.repair_budget = successBudget;
report.ok = true;
- report.media = { path: render.path, bytes: render.bytes };
+ report.media = { path: renderPath, bytes: finalBytes };
+ report.video_qa = (steps.video_qa as Record<string, unknown>) || null;
+ report.render_profile = (steps.render_profile as Record<string, unknown>) || null;
report.next_action = 'open_gate_d';
report.advisory_policy = 'visual inspect warnings are advisory after ok:true; open Gate D instead of self-repairing.';
await writeReportIfRequested(p.reportAbsPath, report);
return {
ok: true,
op: 'composition.draft',
- path: render.path,
- bytes: render.bytes,
+ path: renderPath,
+ bytes: finalBytes,
report_path: p.reportAbsPath || '',
findings_path: p.findingsAbsPath || '',
- media: `chat-media://local/${render.path}`,
+ media: `chat-media://local/${renderPath}`,
probe: mediaProbe,
+ render_profile: (steps.render_profile as Record<string, unknown>) || null,
next_action: 'open_gate_d',
report,
};
}
-function parseFindings(findings: string): { errorCount?: number } {
- try {
- const parsed = JSON.parse(findings);
- return { errorCount: typeof parsed.errorCount === 'number' ? parsed.errorCount : undefined };
- } catch {
- return {};
- }
-}
-
async function writeReportIfRequested(reportAbsPath: string | undefined, report: Record<string, unknown>): Promise<void> {
if (!reportAbsPath) return;
await fs.mkdir(path.dirname(reportAbsPath), { recursive: true });
@@ -1096,26 +1709,47 @@ async function writeReportIfRequested(reportAbsPath: string | undefined, report:
report.report_path = reportAbsPath;
}
-function resolveWhisperBackend(): { cli: string; model: string } | null {
- const cli = process.env.ORKAS_WHISPER_CPP || process.env.ORKAS_WHISPER_CLI || '';
- const model = process.env.ORKAS_WHISPER_MODEL || '';
- if (!cli || !model) return null;
+function filePathIfExists(value: string | undefined): string {
+ if (!value) return '';
try {
- if (!fss.statSync(cli).isFile() || !fss.statSync(model).isFile()) return null;
+ const resolved = path.resolve(value);
+ return fss.statSync(resolved).isFile() ? resolved : '';
} catch {
- return null;
+ return '';
}
- return { cli, model };
+}
+
+function resolveWhisperBackend(modelHint?: string): { cli: string; model: string; source: 'env' | 'bundled' } | null {
+ const cli = filePathIfExists(process.env.ORKAS_WHISPER_CPP || process.env.ORKAS_WHISPER_CLI);
+ const model = filePathIfExists(modelHint) || filePathIfExists(process.env.ORKAS_WHISPER_MODEL);
+ if (!cli || !model) return null;
+ return { cli, model, source: 'env' };
+}
+
+function resolveSpeechTranscribeBackend(modelHint?: string): { cli: string; model: string; source: 'env' | 'bundled' } | null {
+ const envBackend = resolveWhisperBackend(modelHint);
+ if (envBackend) return envBackend;
+ const bundled = bundledWhisperPaths(modelHint);
+ const envCli = filePathIfExists(process.env.ORKAS_WHISPER_CPP || process.env.ORKAS_WHISPER_CLI);
+ if (envCli && bundled.model) return { cli: envCli, model: bundled.model, source: 'bundled' };
+ const envModel = filePathIfExists(modelHint) || filePathIfExists(process.env.ORKAS_WHISPER_MODEL);
+ if (bundled.cli && envModel) return { cli: bundled.cli, model: envModel, source: 'bundled' };
+ if (bundled.cli && bundled.model) return { cli: bundled.cli, model: bundled.model, source: 'bundled' };
+ return null;
}
export async function transcribeSpeech(p: SpeechTranscribeOptions): Promise<VideoStudioResult> {
- const backend = resolveWhisperBackend();
+ const backend = resolveSpeechTranscribeBackend(p.model);
if (!backend) {
return {
ok: false,
op: 'speech.transcribe',
- errorCode: 'E_VIDEO_STUDIO_UNAVAILABLE',
- message: 'Orkas-native speech transcription backend is not installed/configured.',
+ errorCode: 'E_TRANSCRIBE_BACKEND_MISSING',
+ message: 'Speech transcription needs a bundled whisper.cpp runtime under resources/runtime/whisper or explicit ORKAS_WHISPER_CPP/ORKAS_WHISPER_MODEL paths.',
+ backend_resolution: {
+ checked: ['ORKAS_WHISPER_CPP', 'ORKAS_WHISPER_CLI', 'ORKAS_WHISPER_MODEL', 'resources/runtime/whisper/current', `resources/runtime/whisper/${process.platform}-${process.arch}`],
+ model_hint: p.model || '',
+ },
};
}
const bins = bundledFfmpegPaths();
@@ -1160,6 +1794,7 @@ export async function transcribeSpeech(p: SpeechTranscribeOptions): Promise<Vide
summary: parsed,
transcript_path: p.transcriptAbsPath || '',
backend: 'orkas-native:whisper.cpp',
+ backend_source: backend.source,
};
} finally {
await fs.rm(tmp, { recursive: true, force: true }).catch(() => {});
diff --git a/src/main/features/video_studio_qa.ts b/src/main/features/video_studio_qa.ts
new file mode 100644
index 00000000..ff7d5399
--- /dev/null
+++ b/src/main/features/video_studio_qa.ts
@@ -0,0 +1,1180 @@
+import * as crypto from 'node:crypto';
+import * as fs from 'node:fs/promises';
+import * as path from 'node:path';
+import type { NativeImage as ElectronNativeImage } from 'electron';
+
+export type Issue = {
+ code: string;
+ severity: 'error' | 'warning' | 'info';
+ selector?: string;
+ message: string;
+ fixHint?: string;
+ source?: string;
+};
+
+export type AudioTrack = {
+ absPath: string;
+ startSec: number;
+ declaredDurationSec?: number;
+ volume: number;
+};
+
+export type CompositionMeta = {
+ htmlPath: string;
+ html: string;
+ rootAttrs: Record<string, string>;
+ id: string;
+ width: number;
+ height: number;
+ durationSec: number;
+ audioTracks: AudioTrack[];
+};
+
+export type JsonLoad = {
+ path: string;
+ exists: boolean;
+ value: unknown;
+ error?: string;
+};
+
+export type DraftRepairBudget = {
+ compositionDirAbs: string;
+ statePath: string;
+ state: DraftRepairState;
+ summary: DraftRepairSummary;
+ blocked: boolean;
+};
+
+type DraftRepairState = {
+ status: 'ok' | 'failed';
+ failed_attempts: number;
+ repair_passes_used: number;
+ max_repair_passes: number;
+ last_error: Record<string, unknown> | null;
+ history: Array<Record<string, unknown>>;
+ last_success?: Record<string, unknown>;
+};
+
+export type DraftRepairSummary = {
+ ok: boolean;
+ budget_exhausted: boolean;
+ state_path: string;
+ max_repair_passes: number;
+ failed_attempts: number;
+ repair_passes_used: number;
+ repair_passes_remaining: number;
+ last_error: Record<string, unknown> | null;
+};
+
+export type FrameSamplePlan = {
+ label: string;
+ timeSec: number;
+ frameIndex: number;
+};
+
+export type FrameSampleEvidence = {
+ label: string;
+ time_seconds: number;
+ frame_index: number;
+ path: string;
+ hash: string;
+ brightness: number;
+ contrast: number;
+ width: number;
+ height: number;
+};
+
+export type FrameEvidence = {
+ evidence_dir: string;
+ contact_sheet: string;
+ frame_paths: string[];
+ samples: FrameSampleEvidence[];
+};
+
+export const DRAFT_REPAIR_MAX_PASSES = 2;
+
+const DRAFT_VISUAL_ADVISORY_CODES = new Set([
+ 'FONT_TOO_SMALL',
+ 'PALETTE_LARGE',
+ 'LOW_CONTRAST',
+ 'TEXT_BOX_OVERFLOW',
+ 'TEXT_OCCLUDED',
+ 'TEXT_OVERFLOW',
+ 'TEXT_CLIPPED',
+ 'CONTENT_OVERLAP',
+ 'CONTENT_OCCLUDED',
+ 'CONTENT_OVERFLOW',
+ 'CONTENT_CLIPPED',
+ 'SAFE_AREA_VIOLATION',
+ 'ELEMENT_OUT_OF_CANVAS',
+]);
+
+function round2(n: number): number {
+ return Math.round((Number.isFinite(n) ? n : 0) * 100) / 100;
+}
+
+function shortText(value: unknown, max = 220): string {
+ const s = String(value ?? '').replace(/\s+/g, ' ').trim();
+ return s.length > max ? `${s.slice(0, max - 1)}...` : s;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function numberFrom(value: unknown): number {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : 0;
+}
+
+function normalizeForSearch(value: unknown): string {
+ return String(value ?? '')
+ .toLowerCase()
+ .replace(/&amp;/g, '&')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+function isRemoteRef(ref: string): boolean {
+ return /^(?:https?:)?\/\//i.test(ref);
+}
+
+function isIgnorableRef(ref: string): boolean {
+ const s = String(ref || '').trim();
+ return !s || s.startsWith('#') || /^(?:data|blob|javascript):/i.test(s);
+}
+
+function safeResolveLocalRef(rootAbs: string, ref: string): string | null {
+ const clean = String(ref || '').split(/[?#]/)[0];
+ const abs = path.resolve(rootAbs, clean);
+ const rel = path.relative(rootAbs, abs);
+ if (abs === rootAbs || (rel && !rel.startsWith('..') && !path.isAbsolute(rel))) return abs;
+ return null;
+}
+
+export function parseFindingsPayload(findings: string): { errorCount: number; warningCount: number; issues: Issue[]; ok?: boolean } {
+ try {
+ const parsed = JSON.parse(String(findings || '{}')) as {
+ ok?: boolean;
+ errorCount?: number;
+ warningCount?: number;
+ issues?: Issue[];
+ findings?: Issue[];
+ };
+ const issues = Array.isArray(parsed.issues)
+ ? parsed.issues
+ : (Array.isArray(parsed.findings) ? parsed.findings : []);
+ return {
+ ok: parsed.ok,
+ errorCount: typeof parsed.errorCount === 'number'
+ ? parsed.errorCount
+ : issues.filter((i) => i.severity === 'error').length,
+ warningCount: typeof parsed.warningCount === 'number'
+ ? parsed.warningCount
+ : issues.filter((i) => i.severity === 'warning').length,
+ issues,
+ };
+ } catch {
+ return { errorCount: 0, warningCount: 0, issues: [] };
+ }
+}
+
+export function summarizeDraftInspectDisposition(findings: string): Record<string, unknown> {
+ const parsed = parseFindingsPayload(findings);
+ const advisoryIssues: Issue[] = [];
+ const blockingIssues: Issue[] = [];
+ for (const issue of parsed.issues) {
+ const code = String(issue.code || '').toUpperCase();
+ const isVisual = DRAFT_VISUAL_ADVISORY_CODES.has(code);
+ if (issue.severity === 'error' && !isVisual) blockingIssues.push(issue);
+ else advisoryIssues.push(issue);
+ }
+ return {
+ blocking_error_count: blockingIssues.length,
+ advisory_count: advisoryIssues.length,
+ blocking_issues: blockingIssues.slice(0, 12),
+ advisory_issues: advisoryIssues.slice(0, 12),
+ };
+}
+
+async function readJsonIfExists(absPath: string): Promise<JsonLoad> {
+ const st = await fs.stat(absPath).catch(() => null);
+ if (!st || !st.isFile()) return { path: absPath, exists: false, value: null };
+ try {
+ return { path: absPath, exists: true, value: JSON.parse(await fs.readFile(absPath, 'utf8')) };
+ } catch (err) {
+ return { path: absPath, exists: true, value: null, error: (err as Error).message };
+ }
+}
+
+export async function loadDesignContract(compositionDirAbs: string): Promise<JsonLoad> {
+ return readJsonIfExists(path.join(compositionDirAbs, 'design-contract.json'));
+}
+
+export async function loadSceneMap(compositionDirAbs: string): Promise<JsonLoad> {
+ return readJsonIfExists(path.join(compositionDirAbs, 'scene-map.json'));
+}
+
+export async function loadNarrationMap(compositionDirAbs: string): Promise<JsonLoad> {
+ return readJsonIfExists(path.join(compositionDirAbs, 'narration-map.json'));
+}
+
+export async function loadShotlist(compositionDirAbs: string): Promise<JsonLoad> {
+ return readJsonIfExists(path.resolve(compositionDirAbs, '..', 'shotlist.json'));
+}
+
+function jsonCanvas(value: unknown): { width: number; height: number; duration: number; fps: number } {
+ const canvas = isRecord(value) && isRecord(value.canvas) ? value.canvas : {};
+ return {
+ width: numberFrom(canvas.width),
+ height: numberFrom(canvas.height),
+ duration: numberFrom(canvas.duration ?? canvas.duration_sec ?? canvas.duration_seconds),
+ fps: numberFrom(canvas.fps),
+ };
+}
+
+function expectedCanvas(contract: unknown, sceneMap: unknown): { width: number; height: number; duration: number; fps: number } {
+ const fromSceneMap = jsonCanvas(sceneMap);
+ const fromContract = jsonCanvas(contract);
+ return {
+ width: fromSceneMap.width || fromContract.width,
+ height: fromSceneMap.height || fromContract.height,
+ duration: fromSceneMap.duration || fromContract.duration,
+ fps: fromSceneMap.fps || fromContract.fps,
+ };
+}
+
+function extractScenes(value: unknown): Array<Record<string, unknown>> {
+ if (Array.isArray(value)) return value.filter(isRecord);
+ if (!isRecord(value)) return [];
+ if (Array.isArray(value.scenes)) return value.scenes.filter(isRecord);
+ if (Array.isArray(value.shots)) return value.shots.filter(isRecord);
+ if (isRecord(value.timeline) && Array.isArray(value.timeline.scenes)) return value.timeline.scenes.filter(isRecord);
+ return [];
+}
+
+function extractShotlistShots(value: unknown): Array<Record<string, unknown>> {
+ if (Array.isArray(value)) return value.filter(isRecord);
+ if (!isRecord(value)) return [];
+ if (Array.isArray(value.shots)) return value.shots.filter(isRecord);
+ if (Array.isArray(value.scenes)) return value.scenes.filter(isRecord);
+ return [];
+}
+
+function sceneLabel(scene: Record<string, unknown>, index: number): string {
+ return shortText(scene.id || scene.title || scene.headline || scene.name || `scene-${index + 1}`, 80);
+}
+
+function flattenSceneText(scene: unknown): string[] {
+ const out: string[] = [];
+ const visit = (value: unknown, key = '') => {
+ if (typeof value === 'string') {
+ if (/^(id|kind|type|role|layout|asset|src|path|narration_ref)$/i.test(key)) return;
+ const s = value.trim();
+ if (s.length >= 3 && s.length <= 180) out.push(s);
+ return;
+ }
+ if (Array.isArray(value)) {
+ for (const item of value.slice(0, 12)) visit(item, key);
+ return;
+ }
+ if (isRecord(value)) {
+ for (const [k, v] of Object.entries(value)) visit(v, k);
+ }
+ };
+ if (isRecord(scene)) {
+ for (const key of ['headline', 'title', 'subtitle', 'body', 'copy', 'caption', 'label', 'text']) {
+ if (scene[key]) visit(scene[key], key);
+ }
+ }
+ return [...new Set(out)].slice(0, 8);
+}
+
+function htmlUsesGsap(html: string): boolean {
+ return /\bgsap\s*\./.test(html);
+}
+
+function htmlHasLocalGsapVendorScript(html: string): boolean {
+ return /<script\b[^>]*\bsrc\s*=\s*["']\.?\/?assets\/vendor\/gsap\.min\.js["'][^>]*>/i.test(html);
+}
+
+function contractAudio(value: unknown): Record<string, unknown> | null {
+ return isRecord(value) && isRecord(value.audio) ? value.audio : null;
+}
+
+function sceneMapAudio(value: unknown): Record<string, unknown> | null {
+ return isRecord(value) && isRecord(value.audio) ? value.audio : null;
+}
+
+function audioOwnsNarration(audio: Record<string, unknown> | null): boolean {
+ if (!audio) return false;
+ const owner = String(audio.owner || audio.mode || '').toLowerCase();
+ if (audio.render_silent === true || owner === 'assemble' || owner === 'assembler' || owner === 'external') return false;
+ return owner === 'composition' || !!(audio.narration || audio.narration_path || audio.path || audio.src);
+}
+
+function compositionOwnsNarration(contract: unknown, sceneMap: unknown): boolean {
+ const audio = contractAudio(contract);
+ const timelineAudio = sceneMapAudio(sceneMap);
+ return audioOwnsNarration(audio) || audioOwnsNarration(timelineAudio);
+}
+
+function narrationPathFromAudio(audio: Record<string, unknown> | null): string {
+ if (!audio) return '';
+ return String(audio.narration || audio.narration_path || audio.path || audio.src || '').trim();
+}
+
+function narrationPathFromSources(contract: unknown, sceneMap: unknown): string {
+ return narrationPathFromAudio(sceneMapAudio(sceneMap)) || narrationPathFromAudio(contractAudio(contract));
+}
+
+function resolveCompositionLocalPath(compositionDirAbs: string, raw: string): string | null {
+ if (!raw || isRemoteRef(raw) || isIgnorableRef(raw) || path.isAbsolute(raw)) return null;
+ return safeResolveLocalRef(compositionDirAbs, raw);
+}
+
+function sceneNarrationText(scene: Record<string, unknown>): string {
+ const raw = scene.narration ?? scene.narration_text ?? scene.voiceover ?? scene.audio_text ?? scene.script;
+ if (typeof raw === 'string') return raw.trim();
+ if (isRecord(raw)) return String(raw.text || raw.body || raw.line || '').trim();
+ return '';
+}
+
+function isTimedNarrationRef(ref: string): boolean {
+ return /#t\s*=/i.test(ref);
+}
+
+function isMediaNarrationRef(ref: string): boolean {
+ return /\.(?:mp3|wav|m4a|aac|ogg|opus)(?:[?#]|$)/i.test(ref);
+}
+
+function sceneNarrationRefs(scene: Record<string, unknown>): string[] {
+ const raw = scene.narration_ref || scene.voiceover_ref || scene.script_ref;
+ if (Array.isArray(raw)) return raw.map((item) => String(item).trim()).filter(Boolean);
+ if (typeof raw === 'string') {
+ const ref = raw.trim();
+ if (!ref) return [];
+ if (isTimedNarrationRef(ref) || isMediaNarrationRef(ref)) return [ref];
+ return ref.split(/[, ]+/).map((item) => item.trim()).filter(Boolean);
+ }
+ return [];
+}
+
+function sceneSourceShots(scene: Record<string, unknown>): string[] {
+ return Array.isArray(scene.source_shots) ? scene.source_shots.map((item) => String(item).trim()).filter(Boolean) : [];
+}
+
+function sceneStartSec(scene: Record<string, unknown>): number {
+ return numberFrom(scene.start ?? scene.start_sec);
+}
+
+function sceneDurationSec(scene: Record<string, unknown>): number {
+ const duration = numberFrom(scene.duration ?? scene.duration_sec);
+ if (duration > 0) return duration;
+ const start = sceneStartSec(scene);
+ const end = numberFrom(scene.end ?? scene.end_sec);
+ return end > start ? end - start : 0;
+}
+
+function sceneEndSec(scene: Record<string, unknown>): number {
+ const start = sceneStartSec(scene);
+ const duration = sceneDurationSec(scene);
+ if (duration > 0) return start + duration;
+ return numberFrom(scene.end ?? scene.end_sec);
+}
+
+function sceneKeyCandidates(scene: Record<string, unknown>): string[] {
+ const keys = [
+ scene.id,
+ scene.scene_id,
+ scene.shot_id,
+ scene.source_shot,
+ ...sceneSourceShots(scene),
+ ].map((item) => String(item || '').trim()).filter(Boolean);
+ return [...new Set(keys)];
+}
+
+type NarrationLine = {
+ id: string;
+ sceneId?: string;
+ shotId?: string;
+ start: number;
+ duration: number;
+ text: string;
+};
+
+function extractNarrationLines(value: unknown): NarrationLine[] {
+ const rawLines = isRecord(value) && Array.isArray(value.lines) ? value.lines : [];
+ const lines: NarrationLine[] = [];
+ for (const [index, raw] of rawLines.entries()) {
+ if (!isRecord(raw)) continue;
+ const sceneId = String(raw.scene_id || raw.sceneId || '').trim();
+ const shotId = String(raw.shot_id || raw.shotId || '').trim();
+ const id = String(raw.id || raw.line_id || sceneId || shotId || `line-${index + 1}`).trim();
+ const start = numberFrom(raw.start ?? raw.start_sec);
+ const explicitDuration = numberFrom(raw.duration ?? raw.duration_sec);
+ const end = numberFrom(raw.end ?? raw.end_sec);
+ const duration = explicitDuration > 0 ? explicitDuration : (end > start ? end - start : 0);
+ lines.push({
+ id,
+ ...(sceneId ? { sceneId } : {}),
+ ...(shotId ? { shotId } : {}),
+ start,
+ duration,
+ text: String(raw.text || raw.body || raw.line || '').trim(),
+ });
+ }
+ return lines;
+}
+
+function narrationLineEnd(line: NarrationLine): number {
+ return line.start + Math.max(line.duration, 0);
+}
+
+function narrationLineKeyIndex(lines: NarrationLine[]): Map<string, NarrationLine[]> {
+ const out = new Map<string, NarrationLine[]>();
+ const add = (key: string, line: NarrationLine) => {
+ const clean = String(key || '').trim();
+ if (!clean) return;
+ const bucket = out.get(clean) || [];
+ if (!bucket.includes(line)) bucket.push(line);
+ out.set(clean, bucket);
+ };
+ for (const line of lines) {
+ add(line.id, line);
+ if (line.sceneId) add(line.sceneId, line);
+ if (line.shotId) add(line.shotId, line);
+ }
+ return out;
+}
+
+function timedRefRange(ref: string): { start: number; end: number } | null {
+ const m = /#t\s*=\s*([0-9.]+)\s*,\s*([0-9.]+)/i.exec(ref);
+ if (!m) return null;
+ const start = Number(m[1]);
+ const end = Number(m[2]);
+ return Number.isFinite(start) && Number.isFinite(end) && end > start ? { start, end } : null;
+}
+
+function lineMatchesRange(line: NarrationLine, range: { start: number; end: number }): boolean {
+ return Math.abs(line.start - range.start) <= 0.35 && Math.abs(narrationLineEnd(line) - range.end) <= 0.35;
+}
+
+function narrationLinesForScene(
+ scene: Record<string, unknown>,
+ refs: string[],
+ lines: NarrationLine[],
+ byKey: Map<string, NarrationLine[]>,
+): { lines: NarrationLine[]; missingRefs: string[] } {
+ const matched: NarrationLine[] = [];
+ const missingRefs: string[] = [];
+ const add = (line: NarrationLine) => {
+ if (!matched.includes(line)) matched.push(line);
+ };
+ const timedRefs: string[] = [];
+
+ for (const ref of refs) {
+ const direct = byKey.get(ref);
+ if (direct?.length) {
+ direct.forEach(add);
+ } else if (isTimedNarrationRef(ref) || isMediaNarrationRef(ref)) {
+ timedRefs.push(ref);
+ } else {
+ missingRefs.push(ref);
+ }
+ }
+
+ if (timedRefs.length) {
+ for (const key of sceneKeyCandidates(scene)) {
+ byKey.get(key)?.forEach(add);
+ }
+ const ranges = timedRefs.map(timedRefRange).filter((range): range is { start: number; end: number } => !!range);
+ for (const range of ranges) {
+ for (const line of lines) {
+ if (lineMatchesRange(line, range)) add(line);
+ }
+ }
+ for (const ref of timedRefs) {
+ const range = timedRefRange(ref);
+ const hasRangeMatch = range ? matched.some((line) => lineMatchesRange(line, range)) : false;
+ const hasSceneMatch = matched.some((line) => {
+ const keys = sceneKeyCandidates(scene);
+ return (line.sceneId && keys.includes(line.sceneId)) || (line.shotId && keys.includes(line.shotId));
+ });
+ if (!hasRangeMatch && !hasSceneMatch) missingRefs.push(ref);
+ }
+ }
+
+ return { lines: matched, missingRefs };
+}
+
+function audioTargetDuration(contract: unknown, sceneMap: unknown): number {
+ const timelineAudio = sceneMapAudio(sceneMap);
+ const audio = contractAudio(contract);
+ return numberFrom(
+ timelineAudio?.narration_duration_seconds
+ ?? timelineAudio?.narration_duration_sec
+ ?? timelineAudio?.source_duration_seconds
+ ?? timelineAudio?.audio_duration_seconds
+ ?? timelineAudio?.duration_seconds
+ ?? timelineAudio?.duration
+ ?? timelineAudio?.duration_sec
+ ?? timelineAudio?.target_duration_seconds
+ ?? timelineAudio?.target_sec
+ ?? audio?.narration_duration_seconds
+ ?? audio?.narration_duration_sec
+ ?? audio?.source_duration_seconds
+ ?? audio?.audio_duration_seconds
+ ?? audio?.duration_seconds
+ ?? audio?.duration
+ ?? audio?.duration_sec
+ ?? audio?.target_duration_seconds
+ ?? audio?.target_sec,
+ );
+}
+
+export async function runContractHtmlQa(
+ meta: CompositionMeta,
+ metaIssues: Issue[],
+ contractLoad: JsonLoad,
+ sceneMapLoad: JsonLoad,
+ _compositionDirAbs: string,
+): Promise<Record<string, unknown>> {
+ const issues: Issue[] = metaIssues.map((issue) => ({
+ ...issue,
+ source: issue.source || 'orkas-native-contract-html',
+ }));
+ const contract = contractLoad.value;
+ const sceneMap = sceneMapLoad.value;
+
+ if (!contractLoad.exists) {
+ issues.push({
+ code: 'DESIGN_CONTRACT_MISSING',
+ severity: 'error',
+ selector: 'design-contract.json',
+ message: 'project/composition/design-contract.json is required before drafting model-authored HTML.',
+ source: 'orkas-native-contract-html',
+ });
+ } else if (contractLoad.error || !isRecord(contract)) {
+ issues.push({
+ code: 'DESIGN_CONTRACT_PARSE_FAILED',
+ severity: 'error',
+ selector: 'design-contract.json',
+ message: `Could not parse design-contract.json: ${contractLoad.error || 'not a JSON object'}`,
+ source: 'orkas-native-contract-html',
+ });
+ }
+ if (sceneMapLoad.exists && (sceneMapLoad.error || !isRecord(sceneMap))) {
+ issues.push({
+ code: 'SCENE_MAP_PARSE_FAILED',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: `Could not parse scene-map.json: ${sceneMapLoad.error || 'not a JSON object'}`,
+ source: 'orkas-native-contract-html',
+ });
+ }
+ if (htmlUsesGsap(meta.html) && !htmlHasLocalGsapVendorScript(meta.html)) {
+ issues.push({
+ code: 'GSAP_VENDOR_SCRIPT_MISSING',
+ severity: 'error',
+ selector: 'index.html',
+ message: 'index.html uses gsap but does not load ./assets/vendor/gsap.min.js.',
+ source: 'orkas-native-contract-html',
+ });
+ }
+
+ const contractCanvas = jsonCanvas(contract);
+ const sceneMapCanvas = jsonCanvas(sceneMap);
+ for (const key of ['width', 'height', 'duration'] as const) {
+ const tolerance = key === 'duration' ? 0.15 : 1;
+ if (contractCanvas[key] && sceneMapCanvas[key] && Math.abs(contractCanvas[key] - sceneMapCanvas[key]) > tolerance) {
+ issues.push({
+ code: 'CONTRACT_SCENE_MAP_CANVAS_MISMATCH',
+ severity: 'error',
+ selector: 'design-contract.json',
+ message: `design-contract canvas ${key}=${contractCanvas[key]} but scene-map canvas ${key}=${sceneMapCanvas[key]}.`,
+ source: 'orkas-native-contract-html',
+ });
+ }
+ }
+
+ const expected = expectedCanvas(contract, sceneMap);
+ const rootCanvas = { width: meta.width, height: meta.height, duration: meta.durationSec };
+ for (const key of ['width', 'height', 'duration'] as const) {
+ if (!expected[key]) continue;
+ const tolerance = key === 'duration' ? 0.15 : 1;
+ if (Math.abs(rootCanvas[key] - expected[key]) > tolerance) {
+ issues.push({
+ code: 'CANVAS_CONTRACT_MISMATCH',
+ severity: 'error',
+ selector: '[data-composition-id]',
+ message: `index.html root ${key}=${rootCanvas[key]} but contract/scene-map expects ${expected[key]}.`,
+ source: 'orkas-native-contract-html',
+ });
+ }
+ }
+
+ const scenes = extractScenes(sceneMap).length ? extractScenes(sceneMap) : extractScenes(contract);
+ const duration = expected.duration || meta.durationSec;
+ let prevEnd = -1;
+ scenes.forEach((scene, index) => {
+ const start = sceneStartSec(scene);
+ const sceneDuration = sceneDurationSec(scene);
+ if (sceneDuration <= 0) {
+ issues.push({
+ code: 'SCENE_TIMING_INVALID',
+ severity: 'error',
+ selector: sceneMapLoad.exists ? 'scene-map.json' : 'design-contract.json',
+ message: `Scene "${sceneLabel(scene, index)}" needs numeric start plus positive duration or end.`,
+ source: 'orkas-native-contract-html',
+ });
+ return;
+ }
+ if (start + sceneDuration > duration + 0.15) {
+ issues.push({
+ code: 'SCENE_TIMING_OUT_OF_RANGE',
+ severity: 'error',
+ selector: sceneMapLoad.exists ? 'scene-map.json' : 'design-contract.json',
+ message: `Scene "${sceneLabel(scene, index)}" ends beyond the composition duration.`,
+ source: 'orkas-native-contract-html',
+ });
+ }
+ if (prevEnd >= 0 && start < prevEnd - 0.15) {
+ issues.push({
+ code: 'SCENE_TIMING_OVERLAP',
+ severity: 'error',
+ selector: sceneMapLoad.exists ? 'scene-map.json' : 'design-contract.json',
+ message: `Scene "${sceneLabel(scene, index)}" starts before the prior scene ends.`,
+ source: 'orkas-native-contract-html',
+ });
+ }
+ prevEnd = Math.max(prevEnd, start + sceneDuration);
+ });
+
+ const htmlSearch = normalizeForSearch(meta.html);
+ for (const [index, scene] of scenes.slice(0, 16).entries()) {
+ for (const text of flattenSceneText(scene).slice(0, 5)) {
+ const needle = normalizeForSearch(text);
+ if (needle && !htmlSearch.includes(needle)) {
+ issues.push({
+ code: 'HTML_MISSING_SCENE_COPY',
+ severity: 'error',
+ selector: 'index.html',
+ message: `Scene "${sceneLabel(scene, index)}" declares on-screen copy not found in index.html: "${shortText(text, 100)}".`,
+ source: 'orkas-native-contract-html',
+ });
+ }
+ }
+ }
+
+ const errorCount = issues.filter((issue) => issue.severity === 'error').length;
+ return {
+ ok: errorCount === 0,
+ error_count: errorCount,
+ warning_count: issues.filter((issue) => issue.severity === 'warning').length,
+ issue_count: issues.length,
+ contract_path: contractLoad.path,
+ scene_map_path: sceneMapLoad.path,
+ issues,
+ };
+}
+
+export async function runSourceAlignmentQa(sceneMapLoad: JsonLoad, shotlistLoad: JsonLoad): Promise<Record<string, unknown>> {
+ const issues: Issue[] = [];
+ const scenes = extractScenes(sceneMapLoad.value);
+ const shots = extractShotlistShots(shotlistLoad.value);
+ if (!shotlistLoad.exists) {
+ return { ok: true, skipped: true, reason: 'shotlist_missing', issues };
+ }
+ if (shotlistLoad.error) {
+ issues.push({
+ code: 'SHOTLIST_PARSE_FAILED',
+ severity: 'error',
+ selector: 'shotlist.json',
+ message: `Could not parse shotlist.json: ${shotlistLoad.error}`,
+ source: 'orkas-native-source-alignment',
+ });
+ }
+ if (!sceneMapLoad.exists || sceneMapLoad.error || !scenes.length) {
+ issues.push({
+ code: 'SCENE_MAP_REQUIRED_FOR_SOURCE_ALIGNMENT',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: 'shotlist.json exists, but scene-map.json has no scenes to map approved beats.',
+ source: 'orkas-native-source-alignment',
+ });
+ }
+ const alignment = isRecord(sceneMapLoad.value) && isRecord(sceneMapLoad.value.source_alignment)
+ ? sceneMapLoad.value.source_alignment
+ : {};
+ const mergeReason = typeof alignment.merge_reason === 'string' && alignment.merge_reason.trim();
+ const mappedShotCount = new Set<string>();
+ for (const scene of scenes) {
+ const refs = Array.isArray(scene.source_shots) ? scene.source_shots : [];
+ refs.forEach((ref) => mappedShotCount.add(String(ref)));
+ }
+ if (shots.length > scenes.length && !mergeReason && mappedShotCount.size < shots.length) {
+ issues.push({
+ code: 'SHOTLIST_SCENE_MAP_MISMATCH',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: `shotlist has ${shots.length} shots but scene-map has ${scenes.length} scenes. Add source_alignment.merge_reason or per-scene source_shots when intentionally merging beats.`,
+ source: 'orkas-native-source-alignment',
+ });
+ }
+ const errorCount = issues.filter((issue) => issue.severity === 'error').length;
+ return {
+ ok: errorCount === 0,
+ skipped: false,
+ shot_count: shots.length,
+ scene_count: scenes.length,
+ mapped_source_shot_count: mappedShotCount.size,
+ error_count: errorCount,
+ issue_count: issues.length,
+ issues,
+ };
+}
+
+export async function runAudioTimingQa(
+ meta: CompositionMeta,
+ contractLoad: JsonLoad,
+ sceneMapLoad: JsonLoad,
+ narrationMapLoad: JsonLoad,
+ compositionDirAbs: string,
+): Promise<Record<string, unknown>> {
+ const issues: Issue[] = [];
+ const contract = contractLoad.value;
+ const sceneMap = sceneMapLoad.value;
+ const ownsNarration = compositionOwnsNarration(contract, sceneMap);
+ const scenes = extractScenes(sceneMapLoad.value);
+ const narrationPath = narrationPathFromSources(contract, sceneMap);
+ const narrationAbsPath = narrationPath ? resolveCompositionLocalPath(compositionDirAbs, narrationPath) : null;
+ const narrationFileExists = narrationAbsPath ? !!(await fs.stat(narrationAbsPath).catch(() => null)) : false;
+
+ if (narrationPath && !narrationFileExists) {
+ issues.push({
+ code: 'NARRATION_ASSET_MISSING',
+ severity: 'error',
+ selector: narrationPath,
+ message: `Narration audio is declared but the file does not exist: ${narrationPath}.`,
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ if (ownsNarration && (!meta.audioTracks.length || !narrationFileExists)) {
+ issues.push({
+ code: 'NARRATION_DECLARED_BUT_SILENT',
+ severity: 'error',
+ selector: meta.audioTracks.length ? narrationPath || 'design-contract.json' : 'index.html',
+ message: 'design-contract.json declares composition-owned narration, but the composition has no usable narration audio track.',
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ if ((ownsNarration || meta.audioTracks.length > 0) && !sceneMapLoad.exists) {
+ issues.push({
+ code: 'SCENE_MAP_REQUIRED_FOR_AUDIO_TIMING',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: 'Narrated compositions require scene-map.json so voiceover-to-visual alignment is auditable.',
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ if (sceneMapLoad.exists && sceneMapLoad.error) {
+ issues.push({
+ code: 'SCENE_MAP_PARSE_FAILED',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: `Could not parse scene-map.json: ${sceneMapLoad.error}`,
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ if (narrationMapLoad.exists && narrationMapLoad.error) {
+ issues.push({
+ code: 'NARRATION_MAP_PARSE_FAILED',
+ severity: 'error',
+ selector: 'narration-map.json',
+ message: `Could not parse narration-map.json: ${narrationMapLoad.error}`,
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ if (ownsNarration && scenes.length) {
+ const missing = scenes.filter((scene) => {
+ if (sceneNarrationText(scene)) return false;
+ if (sceneNarrationRefs(scene).length) return false;
+ if (sceneSourceShots(scene).length) return false;
+ return true;
+ });
+ if (missing.length) {
+ issues.push({
+ code: 'SCENE_NARRATION_MAPPING_MISSING',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: `${missing.length} scene(s) have no narration, narration_ref, or source_shots mapping.`,
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ }
+
+ const narrationLines = extractNarrationLines(narrationMapLoad.value);
+ const narrationLineByKey = narrationLineKeyIndex(narrationLines);
+ const refScenes = scenes.filter((scene) => sceneNarrationRefs(scene).length);
+ if (refScenes.length && narrationLines.length) {
+ for (const scene of refScenes) {
+ const refs = sceneNarrationRefs(scene);
+ const { lines, missingRefs } = narrationLinesForScene(scene, refs, narrationLines, narrationLineByKey);
+ if (missingRefs.length) {
+ issues.push({
+ code: 'NARRATION_REF_MISSING',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: `Scene "${sceneLabel(scene, scenes.indexOf(scene))}" references narration line(s) not found in narration-map.json: ${missingRefs.join(', ')}.`,
+ source: 'orkas-native-audio-timing',
+ });
+ continue;
+ }
+ if (!lines.length) continue;
+ const expectedStart = Math.min(...lines.map((line) => line.start));
+ const expectedEnd = Math.max(...lines.map(narrationLineEnd));
+ const actualStart = sceneStartSec(scene);
+ const actualEnd = sceneEndSec(scene);
+ const startDrift = actualStart - expectedStart;
+ if (Math.abs(startDrift) > 1.25) {
+ issues.push({
+ code: 'NARRATION_LINE_START_DRIFT',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: `Scene "${sceneLabel(scene, scenes.indexOf(scene))}" starts at ${round2(actualStart)}s but narration-map starts at ${round2(expectedStart)}s (${round2(startDrift)}s drift).`,
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ if (expectedEnd > actualEnd + 1.25) {
+ issues.push({
+ code: 'NARRATION_LINE_OVERFLOWS_SCENE',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: `Scene "${sceneLabel(scene, scenes.indexOf(scene))}" ends at ${round2(actualEnd)}s but referenced narration line(s) run until ${round2(expectedEnd)}s.`,
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ }
+ } else if (refScenes.length && !narrationLines.length) {
+ const refScenesWithoutInlineTiming = refScenes.filter((scene) => !sceneNarrationText(scene) || sceneDurationSec(scene) <= 0);
+ issues.push({
+ code: 'NARRATION_MAP_MISSING',
+ severity: refScenesWithoutInlineTiming.length ? 'error' : 'warning',
+ selector: 'narration-map.json',
+ message: refScenesWithoutInlineTiming.length
+ ? 'Scenes use narration_ref but narration-map.json has no lines and not every referenced scene has inline narration text with a numeric time window. Add project/composition/narration-map.json or inline per-scene narration text and timing before Gate D.'
+ : 'Scenes use narration_ref but narration-map.json has no lines, so draft QA falls back to coarse inline narration timing checks.',
+ source: 'orkas-native-audio-timing',
+ });
+ }
+
+ const mappedScenes = scenes.filter((scene) => sceneNarrationText(scene) || sceneNarrationRefs(scene).length || sceneSourceShots(scene).length);
+ const narratedScenes = scenes.filter((scene) => sceneNarrationText(scene));
+ const targetDuration = audioTargetDuration(contract, sceneMap);
+ if (!narrationLines.length && narratedScenes.length >= 2 && targetDuration > 0) {
+ const totalChars = narratedScenes.reduce((sum, scene) => sum + sceneNarrationText(scene).length, 0);
+ let cursorChars = 0;
+ for (const scene of narratedScenes) {
+ const expectedStart = totalChars > 0 ? (cursorChars / totalChars) * targetDuration : 0;
+ const actualStart = sceneStartSec(scene);
+ const drift = actualStart - expectedStart;
+ if (Math.abs(drift) > 3.5) {
+ issues.push({
+ code: 'AUDIO_TIMING_DRIFT',
+ severity: 'error',
+ selector: 'scene-map.json',
+ message: `Scene "${sceneLabel(scene, scenes.indexOf(scene))}" starts at ${round2(actualStart)}s but estimated narration timing is ${round2(expectedStart)}s (${round2(drift)}s drift).`,
+ source: 'orkas-native-audio-timing',
+ });
+ }
+ cursorChars += sceneNarrationText(scene).length;
+ }
+ } else if (!narrationLines.length && mappedScenes.length >= 2 && narratedScenes.length < 2) {
+ issues.push({
+ code: 'AUDIO_TIMING_ESTIMATE_SKIPPED',
+ severity: 'warning',
+ selector: 'scene-map.json',
+ message: 'Scenes use narration references or source_shots without inline narration text, so draft QA can verify mapping presence but cannot estimate timing drift.',
+ source: 'orkas-native-audio-timing',
+ });
+ }
+
+ const errorCount = issues.filter((issue) => issue.severity === 'error').length;
+ return {
+ ok: errorCount === 0,
+ skipped: !ownsNarration && meta.audioTracks.length === 0,
+ narration_path: narrationPath,
+ narration_file_exists: narrationFileExists,
+ narration_map_path: narrationMapLoad.path,
+ narration_line_count: narrationLines.length,
+ scene_count: scenes.length,
+ audio_track_count: meta.audioTracks.length,
+ error_count: errorCount,
+ warning_count: issues.filter((issue) => issue.severity === 'warning').length,
+ issue_count: issues.length,
+ issues,
+ };
+}
+
+function draftRepairStatePath(compositionDirAbs: string): string {
+ return path.join(compositionDirAbs, 'qa', 'draft-repair-state.json');
+}
+
+async function draftContentSignature(compositionDirAbs: string): Promise<string> {
+ const hash = crypto.createHash('sha256');
+ for (const name of ['design-contract.json', 'scene-map.json', 'narration-map.json', 'index.html']) {
+ const abs = path.join(compositionDirAbs, name);
+ const st = await fs.stat(abs).catch(() => null);
+ if (!st || !st.isFile()) continue;
+ hash.update(name);
+ hash.update('\0');
+ hash.update(await fs.readFile(abs));
+ hash.update('\0');
+ }
+ return hash.digest('hex');
+}
+
+function normalizeRepairState(raw: unknown): DraftRepairState {
+ const r = isRecord(raw) ? raw : {};
+ const failedAttempts = Math.max(0, Number(r.failed_attempts) || 0);
+ return {
+ status: r.status === 'failed' ? 'failed' : 'ok',
+ failed_attempts: failedAttempts,
+ repair_passes_used: Math.max(0, failedAttempts - 1),
+ max_repair_passes: DRAFT_REPAIR_MAX_PASSES,
+ last_error: isRecord(r.last_error) ? r.last_error : null,
+ history: Array.isArray(r.history) ? r.history.filter(isRecord).slice(-12) : [],
+ last_success: isRecord(r.last_success) ? r.last_success : undefined,
+ };
+}
+
+function repairBudgetSummary(statePath: string, state: DraftRepairState): DraftRepairSummary {
+ const failedAttempts = Math.max(0, Number(state.failed_attempts) || 0);
+ const used = Math.max(0, failedAttempts - 1);
+ const budgetExhausted = failedAttempts > 0 && used >= DRAFT_REPAIR_MAX_PASSES;
+ return {
+ ok: !budgetExhausted,
+ budget_exhausted: budgetExhausted,
+ state_path: statePath,
+ max_repair_passes: DRAFT_REPAIR_MAX_PASSES,
+ failed_attempts: failedAttempts,
+ repair_passes_used: used,
+ repair_passes_remaining: Math.max(0, DRAFT_REPAIR_MAX_PASSES - used),
+ last_error: state.last_error,
+ };
+}
+
+export async function initDraftRepairBudget(compositionDirAbs: string): Promise<DraftRepairBudget> {
+ const statePath = draftRepairStatePath(compositionDirAbs);
+ const raw = await readJsonIfExists(statePath);
+ const state = normalizeRepairState(raw.value);
+ const summary = repairBudgetSummary(statePath, state);
+ return {
+ compositionDirAbs,
+ statePath,
+ state,
+ summary,
+ blocked: state.status === 'failed' && summary.budget_exhausted,
+ };
+}
+
+async function writeRepairState(statePath: string, state: DraftRepairState): Promise<void> {
+ await fs.mkdir(path.dirname(statePath), { recursive: true });
+ await fs.writeFile(statePath, JSON.stringify(state, null, 2), 'utf8');
+}
+
+export async function recordDraftFailure(
+ repairBudget: DraftRepairBudget,
+ reportAbsPath: string | undefined,
+ code: string,
+ message: string,
+ extra: Record<string, unknown> = {},
+): Promise<DraftRepairSummary> {
+ const raw = await readJsonIfExists(repairBudget.statePath);
+ const previous = normalizeRepairState(raw.value || repairBudget.state);
+ const failedAttempts = previous.failed_attempts + 1;
+ const entry = {
+ ts: new Date().toISOString(),
+ code,
+ message: shortText(message, 300),
+ report_path: reportAbsPath || '',
+ repair_target: shortText(extra.repair_target || '', 120),
+ content_signature: await draftContentSignature(repairBudget.compositionDirAbs),
+ };
+ const next: DraftRepairState = {
+ status: 'failed',
+ failed_attempts: failedAttempts,
+ repair_passes_used: Math.max(0, failedAttempts - 1),
+ max_repair_passes: DRAFT_REPAIR_MAX_PASSES,
+ last_error: entry,
+ history: [...previous.history, entry].slice(-12),
+ };
+ await writeRepairState(repairBudget.statePath, next);
+ repairBudget.state = next;
+ repairBudget.summary = repairBudgetSummary(repairBudget.statePath, next);
+ repairBudget.blocked = repairBudget.summary.budget_exhausted;
+ return repairBudget.summary;
+}
+
+export async function recordDraftSuccess(
+ repairBudget: DraftRepairBudget,
+ reportAbsPath: string | undefined,
+ renderPath: string | undefined,
+): Promise<DraftRepairSummary> {
+ const raw = await readJsonIfExists(repairBudget.statePath);
+ const previous = normalizeRepairState(raw.value || repairBudget.state);
+ const next: DraftRepairState = {
+ status: 'ok',
+ failed_attempts: 0,
+ repair_passes_used: 0,
+ max_repair_passes: DRAFT_REPAIR_MAX_PASSES,
+ last_error: null,
+ history: previous.history,
+ last_success: {
+ ts: new Date().toISOString(),
+ report_path: reportAbsPath || '',
+ path: renderPath || '',
+ content_signature: await draftContentSignature(repairBudget.compositionDirAbs),
+ },
+ };
+ await writeRepairState(repairBudget.statePath, next);
+ repairBudget.state = next;
+ repairBudget.summary = repairBudgetSummary(repairBudget.statePath, next);
+ repairBudget.blocked = false;
+ return repairBudget.summary;
+}
+
+export function samplePlanKey(label: string): string {
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'sample';
+}
+
+export function buildDraftFrameSamplePlan(meta: CompositionMeta, sceneMap: unknown, fps: number): FrameSamplePlan[] {
+ const duration = Math.max(0.1, meta.durationSec);
+ const raw: Array<{ label: string; timeSec: number }> = [
+ { label: 'first-frame', timeSec: 0 },
+ { label: 'quarter', timeSec: duration * 0.25 },
+ { label: 'midpoint', timeSec: duration * 0.5 },
+ { label: 'three-quarter', timeSec: duration * 0.75 },
+ { label: 'payoff-frame', timeSec: Math.max(0, duration - 0.05) },
+ ];
+ extractScenes(sceneMap).slice(0, 8).forEach((scene, index) => {
+ const start = Math.max(0, numberFrom(scene.start ?? scene.start_sec));
+ const sceneDuration = Math.max(0, numberFrom(scene.duration ?? scene.duration_sec));
+ raw.push({ label: `${sceneLabel(scene, index)}-start`, timeSec: start });
+ if (sceneDuration > 0.2) raw.push({ label: `${sceneLabel(scene, index)}-mid`, timeSec: start + sceneDuration / 2 });
+ });
+
+ const totalFrames = Math.max(1, Math.ceil(duration * fps));
+ const seen = new Set<number>();
+ const out: FrameSamplePlan[] = [];
+ for (const item of raw) {
+ const t = Math.max(0, Math.min(duration - 0.001, item.timeSec));
+ const frameIndex = Math.max(0, Math.min(totalFrames - 1, Math.floor(t * fps)));
+ if (seen.has(frameIndex)) continue;
+ seen.add(frameIndex);
+ out.push({ label: samplePlanKey(item.label), timeSec: round2(frameIndex / fps), frameIndex });
+ if (out.length >= 14) break;
+ }
+ return out;
+}
+
+export function analyzeNativeImage(image: ElectronNativeImage): { hash: string; brightness: number; contrast: number; width: number; height: number } {
+ const size = image.getSize();
+ const bitmap = image.toBitmap();
+ const pixelCount = Math.max(1, size.width * size.height);
+ const stride = Math.max(1, Math.floor(bitmap.length / pixelCount));
+ let sum = 0;
+ let sumSq = 0;
+ for (let i = 0; i < bitmap.length; i += stride) {
+ const r = bitmap[i] ?? 0;
+ const g = bitmap[i + 1] ?? r;
+ const b = bitmap[i + 2] ?? r;
+ const y = (0.2126 * r) + (0.7152 * g) + (0.0722 * b);
+ sum += y;
+ sumSq += y * y;
+ }
+ const mean = sum / pixelCount;
+ const variance = Math.max(0, (sumSq / pixelCount) - mean * mean);
+ return {
+ hash: crypto.createHash('sha256').update(bitmap).digest('hex'),
+ brightness: round2(mean),
+ contrast: round2(Math.sqrt(variance)),
+ width: size.width,
+ height: size.height,
+ };
+}
+
+export async function writeFrameContactSheet(evidenceDirAbs: string, samples: FrameSampleEvidence[]): Promise<string> {
+ const thumbW = 320;
+ const thumbH = 180;
+ const gap = 16;
+ const cols = Math.min(3, Math.max(1, samples.length));
+ const rows = Math.max(1, Math.ceil(samples.length / cols));
+ const width = cols * thumbW + (cols + 1) * gap;
+ const height = rows * (thumbH + 36) + (rows + 1) * gap;
+ const items = samples.map((sample, index) => {
+ const col = index % cols;
+ const row = Math.floor(index / cols);
+ const x = gap + col * (thumbW + gap);
+ const y = gap + row * (thumbH + 36 + gap);
+ const href = path.basename(sample.path).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
+ const label = `${sample.label} @ ${sample.time_seconds}s`.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ return `<image href="${href}" x="${x}" y="${y}" width="${thumbW}" height="${thumbH}" preserveAspectRatio="xMidYMid meet"/><text x="${x}" y="${y + thumbH + 24}" fill="#111" font-family="system-ui, sans-serif" font-size="16">${label}</text>`;
+ }).join('\n');
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><rect width="100%" height="100%" fill="#fff"/>\n${items}\n</svg>\n`;
+ const out = path.join(evidenceDirAbs, 'contact-sheet.svg');
+ await fs.writeFile(out, svg, 'utf8');
+ return out;
+}
+
+export function summarizeVideoFrameQa(frameEvidence: FrameEvidence | null, durationSec: number): Record<string, unknown> {
+ const issues: Issue[] = [];
+ const samples = frameEvidence?.samples || [];
+ if (!samples.length) {
+ issues.push({
+ code: 'VIDEO_SAMPLE_FRAMES_MISSING',
+ severity: 'error',
+ message: 'No sampled evidence frames were captured for draft video QA.',
+ source: 'orkas-native-video-qa',
+ });
+ }
+ for (const sample of samples) {
+ if (sample.brightness < 4 || sample.brightness > 251 || sample.contrast < 1.5) {
+ issues.push({
+ code: sample.label === 'first-frame' ? 'EMPTY_HOOK_FRAME' : 'BLANK_SAMPLE_FRAME',
+ severity: 'error',
+ message: `Sample "${sample.label}" at ${sample.time_seconds}s appears blank or nearly flat (brightness=${sample.brightness}, contrast=${sample.contrast}).`,
+ source: 'orkas-native-video-qa',
+ });
+ }
+ }
+ let runStart = 0;
+ for (let i = 1; i <= samples.length; i += 1) {
+ const sameAsRun = i < samples.length && samples[i].hash === samples[runStart].hash;
+ if (sameAsRun) continue;
+ const runLen = i - runStart;
+ const span = runLen > 1 ? samples[i - 1].time_seconds - samples[runStart].time_seconds : 0;
+ if (runLen >= 3 && span >= Math.min(6, Math.max(2, durationSec * 0.35))) {
+ issues.push({
+ code: 'FROZEN_FRAME_RUN',
+ severity: 'error',
+ message: `${runLen} sampled frames are identical across ${round2(span)}s, indicating a frozen or static draft.`,
+ source: 'orkas-native-video-qa',
+ });
+ }
+ runStart = i;
+ }
+ const errorCount = issues.filter((issue) => issue.severity === 'error').length;
+ return {
+ ok: errorCount === 0,
+ issue_count: issues.length,
+ error_count: errorCount,
+ warning_count: issues.filter((issue) => issue.severity === 'warning').length,
+ evidence_dir: frameEvidence?.evidence_dir || '',
+ contact_sheet: frameEvidence?.contact_sheet || '',
+ frame_paths: frameEvidence?.frame_paths || [],
+ samples,
+ issues,
+ };
+}
diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.ts
index 97b4b7f6..31dfd143 100644
--- a/src/main/model/core-agent/tool-catalog.ts
+++ b/src/main/model/core-agent/tool-catalog.ts
@@ -129,7 +129,7 @@ export const TOOL_CATALOG: ToolCatalogEntry[] = [
// Image
{ name: 'generate_image', group: 'image', permission: 'localExec', summary: 'Call the configured image-generation API and save the result into the workspace.' },
- { name: 'video_studio', group: 'video', permission: 'localExec', ownerAgent: VIDEO_STUDIO_AGENT_ID, summary: 'VideoStudio-owned native runtime for HyperFrames-compatible HTML composition lint/inspect/render and speech transcription fallback orchestration.' },
+ { name: 'video_studio', group: 'video', permission: 'localExec', ownerAgent: VIDEO_STUDIO_AGENT_ID, summary: 'VideoStudio-owned native runtime for HTML composition lint/inspect/render/draft and speech transcription fallback orchestration.' },
// Web (when a vendor-native search is available the framework picks it automatically; the two below are the fallback channel)
{ name: 'web_search', group: 'web', summary: 'Built-in fallback web search (vendor-native search is preferred automatically when available).' },
diff --git a/src/main/util/bundled-runtime.ts b/src/main/util/bundled-runtime.ts
index 810e81d6..2b4d21ea 100644
--- a/src/main/util/bundled-runtime.ts
+++ b/src/main/util/bundled-runtime.ts
@@ -35,7 +35,7 @@ function runtimeRoots(): string[] {
return roots;
}
-function runtimeVariantDirs(kind: 'python' | 'uv' | 'node' | 'ffmpeg'): string[] {
+function runtimeVariantDirs(kind: 'python' | 'uv' | 'node' | 'ffmpeg' | 'whisper'): string[] {
const dirs: string[] = [];
for (const runtimeRoot of runtimeRoots()) {
const root = path.join(runtimeRoot, kind);
@@ -115,14 +115,68 @@ function resolveFfmpegBinary(kind: 'ffmpeg' | 'ffprobe'): string | undefined {
return undefined;
}
+function resolveWhisperBinary(): string | undefined {
+ const configured = process.env.ORKAS_WHISPER_CPP || process.env.ORKAS_WHISPER_CLI;
+ if (isFile(configured)) return configured;
+
+ const names = process.platform === 'win32'
+ ? [
+ 'whisper-cli.exe',
+ path.join('bin', 'whisper-cli.exe'),
+ 'main.exe',
+ path.join('bin', 'main.exe'),
+ ]
+ : [
+ 'whisper-cli',
+ path.join('bin', 'whisper-cli'),
+ 'main',
+ path.join('bin', 'main'),
+ ];
+ for (const dir of runtimeVariantDirs('whisper')) {
+ for (const name of names) {
+ const candidate = path.join(dir, name);
+ if (isFile(candidate)) return candidate;
+ }
+ }
+ return undefined;
+}
+
+function resolveWhisperModel(modelHint?: string): string | undefined {
+ const hinted = modelHint || process.env.ORKAS_WHISPER_MODEL;
+ if (isFile(hinted)) return path.resolve(hinted);
+
+ const normalizedHint = modelHint
+ ? String(modelHint).replace(/^ggml-/, '').replace(/\.bin$/i, '').trim()
+ : '';
+ const names = [
+ modelHint,
+ normalizedHint ? `ggml-${normalizedHint}.bin` : '',
+ 'ggml-large-v3.bin',
+ 'ggml-medium.bin',
+ 'ggml-small.bin',
+ 'ggml-base.bin',
+ 'ggml-tiny.bin',
+ ].filter((name): name is string => !!name);
+ for (const dir of runtimeVariantDirs('whisper')) {
+ for (const name of names) {
+ const candidates = [
+ path.join(dir, name),
+ path.join(dir, 'models', name),
+ ];
+ for (const candidate of candidates) {
+ if (isFile(candidate)) return candidate;
+ }
+ }
+ }
+ return undefined;
+}
+
/**
* Bundled ffmpeg/ffprobe absolute paths, or undefined when not vendored for
- * this platform. HyperFrames render REQUIRES system ffmpeg+ffprobe and ships
- * neither; pointing it at these via `HYPERFRAMES_FFMPEG_PATH` /
- * `HYPERFRAMES_FFPROBE_PATH` makes rendering deterministic instead of relying
- * on whatever the user's machine happens to have. When undefined (e.g. a dev
- * checkout before the vendor step), callers should leave the override unset so
- * HyperFrames falls back to scanning common install dirs.
+ * this platform. VideoStudio native render/edit/media analysis paths use these
+ * binaries instead of relying on whatever the user's machine happens to have.
+ * When undefined (e.g. a dev checkout before the vendor step), callers should
+ * surface a clear missing-runtime error or use their own explicit fallback.
*/
export function bundledFfmpegPaths(): { ffmpeg?: string; ffprobe?: string } {
const result: { ffmpeg?: string; ffprobe?: string } = {};
@@ -133,6 +187,20 @@ export function bundledFfmpegPaths(): { ffmpeg?: string; ffprobe?: string } {
return result;
}
+/**
+ * Bundled whisper.cpp paths. The app treats speech transcription as a native
+ * VideoStudio capability, so default installs can vendor `resources/runtime/whisper`
+ * without requiring users to hand-set ORKAS_WHISPER_*.
+ */
+export function bundledWhisperPaths(modelHint?: string): { cli?: string; model?: string } {
+ const result: { cli?: string; model?: string } = {};
+ const cli = resolveWhisperBinary();
+ const model = resolveWhisperModel(modelHint);
+ if (cli) result.cli = cli;
+ if (model) result.model = model;
+ return result;
+}
+
function pushPathDir(out: string[], seen: Set<string>, dir: string | undefined): void {
if (!isDir(dir)) return;
const resolved = path.resolve(dir);
diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.ts
index 5a7aafac..1d717aad 100644
--- a/test/main/features/skills.test.ts
+++ b/test/main/features/skills.test.ts
@@ -298,10 +298,10 @@ describe('skills › extractSkillMetadataBlocks', () => {
describe('skills › extractSkillAsPackageMarker', () => {
it('parses a self-closing marker with a name and strips it', async () => {
const s = await loadSkills();
- const text = 'Installed and ready.\n<skill-as-package name="hyperframes"/>';
+ const text = 'Installed and ready.\n<skill-as-package name="demo-cli"/>';
const r = s.extractSkillAsPackageMarker(text);
expect(r).not.toBeNull();
- expect(r!.name).toBe('hyperframes');
+ expect(r!.name).toBe('demo-cli');
expect(r!.cleanText).toBe('Installed and ready.');
});
@@ -798,6 +798,32 @@ describe('skills › listSkills', () => {
expect(found?.default_install).toBe(true);
});
+ it('updates marketplace skill display name in dev without renaming install dir', async () => {
+ const prevDevtools = process.env.ORKAS_DEVTOOLS;
+ process.env.ORKAS_DEVTOOLS = '1';
+ try {
+ const dir = path.join(builtinSkillsDir(), 'platform-excel');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'SKILL.md'),
+ '---\nname: "Old platform skill"\ndescription: "platform"\n---\n\nUse when editing spreadsheets.\n');
+
+ const s = await loadSkills();
+ const result = await s.applySkillMetadataForEdit('platform-excel', { name: 'Excel / XLSX' });
+
+ expect(result.ok).toBe(true);
+ expect(result.skillId).toBe('platform-excel');
+ expect(fs.existsSync(dir)).toBe(true);
+ expect(fs.existsSync(path.join(builtinSkillsDir(), 'Excel / XLSX'))).toBe(false);
+ const after = fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8');
+ expect(s.parseSkillFrontmatter(after).name).toBe('Excel / XLSX');
+ expect((await s.listSkills()).find((x) => x.id === 'platform-excel')?.name)
+ .toBe('Excel / XLSX');
+ } finally {
+ if (prevDevtools === undefined) delete process.env.ORKAS_DEVTOOLS;
+ else process.env.ORKAS_DEVTOOLS = prevDevtools;
+ }
+ });
+
it('cache-only invalidator picks up marketplace file rewrites', async () => {
const parent = builtinSkillsDir();
const dir = path.join(parent, 'platform-skill');
diff --git a/test/main/features/video_craft_lint.test.ts b/test/main/features/video_craft_lint.test.ts
deleted file mode 100644
index 7382af6e..00000000
--- a/test/main/features/video_craft_lint.test.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { lintCompositionCraft, formatCraftFindings } from '../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint';
-
-const codes = (html: string, opts?: { canvasHeight?: number }) =>
- lintCompositionCraft(html, opts).map((f) => f.code);
-
-describe('lintCompositionCraft — font legibility floor', () => {
- it('flags an explicit px font-size below the 1080p floor', () => {
- const html = '<div data-height="1080" style="font-size: 24px">hi</div>';
- expect(codes(html)).toContain('FONT_TOO_SMALL');
- });
-
- it('does not flag font sizes at or above the floor', () => {
- const html = '<div data-height="1080"><h1 style="font-size:96px">T</h1><p style="font-size: 40px">b</p></div>';
- expect(codes(html)).not.toContain('FONT_TOO_SMALL');
- });
-
- it('scales the floor to the canvas height (smaller canvas → smaller floor)', () => {
- // 540-tall canvas → floor = round(40 * 540/1080) = 20px.
- const ok = '<div data-height="540" style="font-size: 24px">ok</div>';
- expect(codes(ok)).not.toContain('FONT_TOO_SMALL');
- const bad = '<div data-height="540" style="font-size: 16px">small</div>';
- expect(codes(bad)).toContain('FONT_TOO_SMALL');
- });
-
- it('defaults the floor to 1080p when data-height is absent', () => {
- expect(codes('<div style="font-size: 30px">x</div>')).toContain('FONT_TOO_SMALL');
- });
-
- it('ignores non-px units (em / rem / vw / % / clamp) — not a hard pixel commitment', () => {
- const html = `<div data-height="1080">
- <span style="font-size: 1.2em">a</span>
- <span style="font-size: 2rem">b</span>
- <span style="font-size: 3vw">c</span>
- <span style="font-size: 90%">d</span>
- <span style="font-size: clamp(20px, 4vw, 60px)">e</span>
- </div>`;
- // clamp() embeds a literal 20px but is a responsive expression, not a fixed
- // commitment; the bare `px` regex requires `:<num>px` directly after the colon.
- expect(codes(html)).not.toContain('FONT_TOO_SMALL');
- });
-
- it('reports the actual small sizes in the message, deduped and sorted', () => {
- const html = '<div data-height="1080"><a style="font-size:30px">x</a><b style="font-size:18px">y</b><i style="font-size:30px">z</i></div>';
- const f = lintCompositionCraft(html).find((x) => x.code === 'FONT_TOO_SMALL')!;
- expect(f.message).toContain('18px');
- expect(f.message).toContain('30px');
- // 30px appears twice in the source but once in the message.
- expect(f.message.match(/30px/g)!.length).toBe(1);
- });
-});
-
-describe('lintCompositionCraft — palette size', () => {
- it('flags a composition with many distinct chromatic colors', () => {
- const palette = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff', '#ff8800', '#8800ff', '#0088ff'];
- const html = palette.map((c) => `<div style="color:${c}">x</div>`).join('');
- expect(codes(html)).toContain('PALETTE_LARGE');
- });
-
- it('does not flag neutrals — black, white, grays, transparent are not part of the budget', () => {
- const neutrals = ['#000', '#fff', '#333333', '#cccccc', 'rgb(20,20,20)', 'rgba(0,0,0,0)', 'transparent', 'hsl(0, 0%, 40%)'];
- const html = neutrals.map((c) => `<div style="color:${c}">x</div>`).join('');
- expect(codes(html)).not.toContain('PALETTE_LARGE');
- });
-
- it('does not flag a small, disciplined palette', () => {
- const html = '<div style="background:#102a43"><h1 style="color:#f0f4f8">t</h1><span style="color:#ffb000">accent</span></div>';
- expect(codes(html)).not.toContain('PALETTE_LARGE');
- });
-
- it('counts a 3-digit hex and its 6-digit form as the same color', () => {
- // #f00 and #ff0000 are the same red; with only one other color this stays small.
- const html = '<div style="color:#f00"></div><div style="color:#ff0000"></div><div style="color:#0a84ff"></div>';
- expect(codes(html)).not.toContain('PALETTE_LARGE');
- });
-});
-
-describe('formatCraftFindings', () => {
- it('returns empty string when there are no findings', () => {
- expect(formatCraftFindings([])).toBe('');
- expect(formatCraftFindings(lintCompositionCraft(''))).toBe('');
- });
-
- it('renders a labeled block with one line per finding', () => {
- const text = formatCraftFindings(lintCompositionCraft('<div style="font-size:12px">x</div>'));
- expect(text).toContain('[craft]');
- expect(text).toContain('FONT_TOO_SMALL');
- });
-
- it('labels only small text as blocking when strict craft mode is active', () => {
- const text = formatCraftFindings(lintCompositionCraft('<div style="font-size:12px">x</div>'), { strict: true });
- expect(text).toContain('FONT_TOO_SMALL blocks under --strict-craft');
- expect(text).toContain('PALETTE_LARGE is advisory');
- });
-
- it('keeps palette-size findings advisory even in strict craft mode', () => {
- const palette = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff', '#ff8800', '#8800ff', '#0088ff'];
- const html = palette.map((c) => `<div style="color:${c}">x</div>`).join('');
- const text = formatCraftFindings(lintCompositionCraft(html), { strict: true });
- expect(text).toContain('PALETTE_LARGE');
- expect(text).toContain('PALETTE_LARGE is advisory');
- });
-});
diff --git a/test/main/features/video_decide.test.ts b/test/main/features/video_decide.test.ts
index 3780e227..fda3904d 100644
--- a/test/main/features/video_decide.test.ts
+++ b/test/main/features/video_decide.test.ts
@@ -132,8 +132,8 @@ describe('normalizeTranscriptWords', () => {
]);
});
- it('reads a top-level array of {text,start,end} (the real hyperframes transcribe shape)', () => {
- // Verified against `npx hyperframes transcribe --json` output (small.en).
+ it('reads a top-level array of {text,start,end} (legacy transcript shape)', () => {
+ // Kept for backward compatibility with older transcript JSON artifacts.
expect(
normalizeTranscriptWords([
{ text: 'So,', start: 0.12, end: 0.41 },
diff --git a/test/main/features/video_media_skill_scripts.test.ts b/test/main/features/video_media_skill_scripts.test.ts
index 254d5bf4..1a38d81e 100644
--- a/test/main/features/video_media_skill_scripts.test.ts
+++ b/test/main/features/video_media_skill_scripts.test.ts
@@ -6,12 +6,12 @@ import { spawnSync } from 'node:child_process';
import { describe, expect, it } from 'vitest';
function pcDir() {
- return fs.existsSync(path.join(process.cwd(), 'bin', 'run-skill.cjs'))
+ return path.basename(process.cwd()) === 'PC'
? process.cwd()
: path.resolve(process.cwd(), 'PC');
}
-function skillDir(skillId: 'stage-edit' | 'stage-plan' | 'stage-compose') {
+function skillDir(skillId: 'stage-edit' | 'stage-plan') {
return path.join(
pcDir(),
'resources',
@@ -25,13 +25,12 @@ function skillDir(skillId: 'stage-edit' | 'stage-plan' | 'stage-compose') {
}
function runSkill(
- skillId: 'stage-edit' | 'stage-compose',
+ skillId: 'stage-edit',
script: string,
args: string[],
extraEnv: Record<string, string> = {},
) {
const dir = pcDir();
- const workspaceRoot = path.join(os.tmpdir(), 'orkas-video-skill-workspace');
return spawnSync(
process.execPath,
[path.join(dir, 'bin', 'run-skill.cjs'), skillId, script, '--', ...args],
@@ -42,72 +41,6 @@ function runSkill(
...process.env,
ORKAS_PC_DIR: dir,
ORKAS_RUN_SKILL_DIR: skillDir(skillId),
- ORKAS_WORKSPACE_ROOT: workspaceRoot,
- ...extraEnv,
- },
- },
- );
-}
-
-function runRenderCompositionWithMockCore(args: string[], extraEnv: Record<string, string> = {}) {
- const dir = pcDir();
- const scriptPath = path.join(skillDir('stage-compose'), 'scripts', 'render_composition.js');
- const code = [
- "const Module = require('node:module');",
- 'const scriptPath = process.argv[1];',
- 'const args = JSON.parse(process.argv[2]);',
- 'const originalLoad = Module._load;',
- 'Module._load = function(request, parent, isMain) {',
- " if (request === './lib/video_render_core.cjs' && parent && parent.filename === scriptPath) {",
- ' return {',
- ' qaComposition: async (op) => {',
- " if (process.env.ORKAS_MOCK_LINT_ERROR === '1' && op === 'lint') {",
- " return { ok: true, findings: JSON.stringify({ ok: false, errorCount: 1, warningCount: 0, findings: [{ code: 'gsap_timeline_not_registered', severity: 'error', message: 'timeline missing' }] }) };",
- ' }',
- " if (process.env.ORKAS_MOCK_INSPECT_VISUAL_ERROR === '1' && op === 'inspect') {",
- " return { ok: true, findings: JSON.stringify({ ok: false, errorCount: 2, warningCount: 1, issueCount: 3, totalIssueCount: 3, issues: [",
- " { code: 'text_box_overflow', severity: 'error', selector: 'p.card-copy', message: 'Text extends outside its nearest visual/container box.' },",
- " { code: 'text_occluded', severity: 'error', selector: 'h1.headline', message: 'Text is hidden beneath an opaque element.' },",
- " { code: 'content_overlap', severity: 'warning', selector: 'h1.headline', message: 'Two text blocks overlap.' }",
- ' ] }) };',
- ' }',
- " if (process.env.ORKAS_MOCK_INSPECT_STRUCTURAL_ERROR === '1' && op === 'inspect') {",
- " return { ok: true, findings: JSON.stringify({ ok: false, errorCount: 1, warningCount: 0, issueCount: 1, totalIssueCount: 1, issues: [{ code: 'timeline_runtime_missing', severity: 'error', message: 'Timeline runtime is not available.' }] }) };",
- ' }',
- " return { ok: true, findings: JSON.stringify({ ok: true, errorCount: 0, warningCount: 0, issueCount: 0, totalIssueCount: 0, issues: [] }) };",
- ' },',
- ' renderComposition: async (p) => {',
- " if (process.env.ORKAS_MOCK_RENDER_OK === '1') {",
- " require('node:fs').mkdirSync(require('node:path').dirname(p.outputAbsPath), { recursive: true });",
- " require('node:fs').writeFileSync(p.outputAbsPath, 'fake video output');",
- " return { ok: true, path: p.outputAbsPath, bytes: 17 };",
- ' }',
- " return { ok: false, errorCode: 'E_RENDER_FAILED', message: 'fake render failed' };",
- ' },',
- // Render-resilience helpers mirror the real pure functions; default RAM 32
- // keeps existing tests on the unconstrained "proceed" path.
- ' machineRamGB: () => (process.env.ORKAS_MOCK_RAM_GB ? Number(process.env.ORKAS_MOCK_RAM_GB) : 32),',
- " isConstrainedMachine: (ram, gpu) => (Number(ram) <= 8 || gpu === 'software'),",
- ' estimateRenderCost: (w, h, dur, fps) => Math.round(Math.max(1, dur) * Math.max(1, fps) * Math.max(1, (w * h) / 1e6)),',
- " renderCostDecision: (o) => (!o.constrained || o.costUnits <= 3000 ? 'proceed' : (o.isFinal ? 'fail_fast' : 'degrade')),",
- ' degradedFps: (fps) => (fps > 30 ? 30 : fps),',
- ' };',
- ' }',
- ' return originalLoad.apply(this, arguments);',
- '};',
- 'const script = require(scriptPath);',
- "Promise.resolve(script({ args })).then((out) => { process.stdout.write(JSON.stringify(out)); }).catch((err) => { process.stderr.write(err && err.stack ? err.stack : String(err)); process.exit(1); });",
- ].join('\n');
- return spawnSync(
- process.execPath,
- ['-e', code, scriptPath, JSON.stringify(args)],
- {
- cwd: path.dirname(dir),
- encoding: 'utf8',
- env: {
- ...process.env,
- ORKAS_PC_DIR: dir,
- ORKAS_RUN_SKILL_DIR: skillDir('stage-compose'),
ORKAS_WORKSPACE_ROOT: path.dirname(dir),
...extraEnv,
},
@@ -149,71 +82,6 @@ function makeFakeFfmpegEnv(tmp: string) {
};
}
-function makeFakeVideoProbeEnv(tmp: string) {
- const binDir = path.join(tmp, 'fake-probe-bin');
- fs.mkdirSync(binDir, { recursive: true });
- const ffprobePath = path.join(binDir, 'ffprobe');
- fs.writeFileSync(ffprobePath, [
- '#!/usr/bin/env node',
- 'process.stdout.write(JSON.stringify({',
- " streams: [{ codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, r_frame_rate: '30/1', bit_rate: '800000' }],",
- " format: { duration: '10', size: '17', bit_rate: '800000' }",
- '}));',
- '',
- ].join('\n'), 'utf8');
- fs.chmodSync(ffprobePath, 0o755);
- return { ORKAS_BUNDLED_FFPROBE: ffprobePath };
-}
-
-function writeMinimalCompositionHtml(
- compositionDir: string,
- text = 'Orkas 1.5.0',
- attrs: { width?: number; height?: number; duration?: number } = {},
- head = '',
-) {
- const width = attrs.width ?? 1920;
- const height = attrs.height ?? 1080;
- const duration = attrs.duration ?? 10;
- fs.writeFileSync(path.join(compositionDir, 'index.html'), [
- '<!doctype html>',
- '<html lang="en">',
- '<head>',
- '<meta charset="UTF-8" />',
- `<meta name="viewport" content="width=${width}, height=${height}" />`,
- head,
- '</head>',
- '<body>',
- `<div id="root" data-composition-id="main" data-start="0" data-duration="${duration}" data-width="${width}" data-height="${height}">`,
- `<div class="clip" data-start="0" data-duration="${duration}" data-track-index="1">${text}</div>`,
- '</div>',
- '<script>window.__timelines = window.__timelines || {}; window.__timelines.main = { seek() {} };</script>',
- '</body>',
- '</html>',
- ].join('\n'), 'utf8');
-}
-
-function writeDesignContract(
- compositionDir: string,
- overrides: Record<string, unknown> = {},
-) {
- const contract = {
- canvas: { width: 1920, height: 1080, duration: 10, fps: 30, language: 'en' },
- aesthetic: {
- subject_world: 'release notes',
- audience: 'product users',
- one_job: 'state the update',
- tone: ['clear'],
- signature_device: 'version lockup',
- aesthetic_risk: 'bold cover frame',
- anti_template_check: 'no generic cards',
- },
- scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0' }],
- color_tokens: { background: '#050b18', text: '#ffffff', primary: '#3b82f6' },
- ...overrides,
- };
- fs.writeFileSync(path.join(compositionDir, 'design-contract.json'), JSON.stringify(contract), 'utf8');
-}
-
describe('video media skill scripts', () => {
it('keeps VideoStudio media logic local to skill scripts', () => {
const files = [
@@ -224,8 +92,6 @@ describe('video media skill scripts', () => {
path.join(skillDir('stage-plan'), 'scripts', 'video_plan.js'),
path.join(skillDir('stage-plan'), 'scripts', 'lib', 'video_decide_core.cjs'),
path.join(skillDir('stage-plan'), 'scripts', 'lib', 'video_edl_core.cjs'),
- path.join(skillDir('stage-compose'), 'scripts', 'render_composition.js'),
- path.join(skillDir('stage-compose'), 'scripts', 'lib', 'video_render_core.cjs'),
];
const forbidden = [
/\bpcRequire\b/,
@@ -257,8 +123,9 @@ describe('video media skill scripts', () => {
expect(res.status, res.stderr).toBe(0);
const out = parseJson(res.stdout);
expect(out.ok).toBe(true);
- expect(out.ops).toContain('transcribe');
+ expect(out.ops).not.toContain('transcribe');
expect(out.ops).toContain('quality');
+ expect(out.usage).toContain('speech.transcribe');
});
it('exposes edit_video through the stage-edit skill runner', () => {
@@ -294,502 +161,6 @@ describe('video media skill scripts', () => {
]));
});
- it('exposes render_composition through the stage-compose skill runner', () => {
- const res = runSkill('stage-compose', 'render_composition', ['--help']);
- expect(res.status, res.stderr).toBe(0);
- const out = parseJson(res.stdout);
- expect(out.ok).toBe(true);
- expect(out.ops).toContain('inspect');
- expect(out.ops).toContain('render');
- expect(out.ops).toContain('draft');
- expect(out.ops).not.toContain('compile');
- expect(out.usage).toContain('--strict-craft');
- expect(out.usage).toContain('--findings-output');
- expect(out.usage).toContain('--findings-inline');
- expect(out.usage).toContain('hand-authored index.html');
- });
-
- it('blocks draft when hand-authored composition HTML is missing', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-html-missing-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_RENDER_NO_COMPOSITION');
- expect(out.message).toContain('hand-authored index.html');
- });
-
- it('rejects composition spec compilation so COMPOSE stays model-authored HTML', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-spec-rejected-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- fs.writeFileSync(path.join(compositionDir, 'spec.json'), JSON.stringify({ scenes: [] }), 'utf8');
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_SPEC_COMPILER_REMOVED');
- expect(out.message).toContain('index.html');
- });
-
- it('blocks draft when model-authored HTML has no design contract', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-contract-missing-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeMinimalCompositionHtml(compositionDir);
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');
- expect(out.repair_target).toBe('design-contract.json');
- expect(out.contract_html.issues).toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'DESIGN_CONTRACT_MISSING' }),
- ]));
- });
-
- it('warns when the contract declares narration but the composition is silent', () => {
- const runDraftIssues = (label: string, audio: Record<string, unknown> | undefined) => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), `orkas-compose-${label}-`));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir, {
- scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0 Release Highlights' }],
- ...(audio ? { audio } : {}),
- });
- // "Different title" forces HTML_MISSING_SCENE_COPY so draft blocks and
- // returns the full contract_html issue list (including any warnings).
- writeMinimalCompositionHtml(compositionDir, 'Different title', {});
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');
- return (out.contract_html.issues as Array<{ code: string }>);
- };
-
- // Composition-owned narration declared, but no <audio> and no narration file → warn.
- const silent = runDraftIssues('narration-silent', { owner: 'composition', narration_path: './assets/narration.mp3', target_sec: 10 });
- expect(silent.find((i) => i.code === 'NARRATION_DECLARED_BUT_SILENT')).toBeTruthy();
-
- // Assembler-owned narration (composition renders silent by design) → no warn.
- const assembler = runDraftIssues('narration-assemble', { owner: 'assemble', narration_path: './assets/narration.mp3', render_silent: true });
- expect(assembler.find((i) => i.code === 'NARRATION_DECLARED_BUT_SILENT')).toBeUndefined();
-
- // No audio section at all → no warn.
- const none = runDraftIssues('narration-none', undefined);
- expect(none.find((i) => i.code === 'NARRATION_DECLARED_BUT_SILENT')).toBeUndefined();
- });
-
- it('blocks draft when HTML depends on remote runtime resources', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-remote-resource-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(
- compositionDir,
- 'Orkas 1.5.0',
- {},
- '<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>',
- );
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');
- expect(out.repair_target).toBe('index.html');
- expect(out.contract_html.issues).toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'REMOTE_RUNTIME_RESOURCE' }),
- ]));
- });
-
- it('blocks draft when GSAP is used without the local vendor script', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-gsap-missing-vendor-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(
- compositionDir,
- 'Orkas 1.5.0',
- {},
- '<script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',
- );
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');
- expect(out.contract_html.issues).toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'GSAP_VENDOR_SCRIPT_MISSING' }),
- ]));
- });
-
- it('auto-copies the local GSAP vendor when the composition references it', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-gsap-vendor-copy-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir, {
- scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0 Release Highlights' }],
- });
- writeMinimalCompositionHtml(
- compositionDir,
- 'Different title',
- {},
- '<script src="./assets/vendor/gsap.min.js"></script><script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',
- );
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- expect(fs.existsSync(path.join(compositionDir, 'assets', 'vendor', 'gsap.min.js'))).toBe(true);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');
- expect(out.contract_html.issues).toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'HTML_MISSING_SCENE_COPY' }),
- ]));
- expect(out.contract_html.issues).not.toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'MISSING_LOCAL_ASSET' }),
- ]));
- });
-
- it('replaces the old managed GSAP shim with the built-in official vendor', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-gsap-vendor-replace-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- const vendorPath = path.join(compositionDir, 'assets', 'vendor', 'gsap.min.js');
- fs.mkdirSync(path.dirname(vendorPath), { recursive: true });
- fs.writeFileSync(vendorPath, [
- '/*',
- ' * Local HyperFrames timeline vendor.',
- ' * Provides the small GSAP-compatible surface VideoStudio compositions need.',
- ' */',
- 'window.gsap = { timeline() { return { seek() {}, pause() {}, play() {}, timeScale() {}, totalTime() {}, duration() { return 0; }, totalDuration() { return 0; }, getChildren() { return []; } }; } };',
- ].join('\n'), 'utf8');
- writeDesignContract(compositionDir, {
- scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0 Release Highlights' }],
- });
- writeMinimalCompositionHtml(
- compositionDir,
- 'Different title',
- {},
- '<script src="./assets/vendor/gsap.min.js"></script><script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',
- );
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const vendor = fs.readFileSync(vendorPath, 'utf8');
- expect(vendor).toContain('GSAP 3.15.0');
- expect(vendor).toContain('timeScale');
- expect(vendor).toContain('totalTime');
- expect(vendor).toContain('getChildren');
- });
-
- it('blocks a user-provided incompatible GSAP vendor before rendering', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-gsap-vendor-incompatible-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- const vendorPath = path.join(compositionDir, 'assets', 'vendor', 'gsap.min.js');
- fs.mkdirSync(path.dirname(vendorPath), { recursive: true });
- fs.writeFileSync(vendorPath, '/* custom gsap placeholder */ window.gsap = {};', 'utf8');
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(
- compositionDir,
- 'Orkas 1.5.0',
- {},
- '<script src="./assets/vendor/gsap.min.js"></script><script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',
- );
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_VENDOR_ASSETS_BLOCKED');
- expect(out.repair_target).toBe('assets/vendor/gsap.min.js');
- expect(out.vendor_assets.issues).toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'VENDOR_GSAP_INCOMPATIBLE' }),
- ]));
- expect(fs.readFileSync(vendorPath, 'utf8')).toContain('custom gsap placeholder');
- });
-
- it('writes the latest draft report when render fails after inspect', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-render-report-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- const outputPath = path.join(tmp, 'project', 'render', 'draft.mp4');
- const reportPath = path.join(tmp, 'project', 'render', 'draft-report.json');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0');
-
- const res = runRenderCompositionWithMockCore([
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', outputPath,
- '--report', reportPath,
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_RENDER_FAILED');
- expect(out.report_path).toBe(reportPath);
- const report = parseJson(fs.readFileSync(reportPath, 'utf8'));
- expect(report.error).toMatchObject({ code: 'E_RENDER_FAILED', message: 'fake render failed' });
- expect(report.steps.inspect.ok).toBe(true);
- expect(report.steps.render).toMatchObject({ ok: false, errorCode: 'E_RENDER_FAILED', message: 'fake render failed' });
- });
-
- it('blocks draft on HyperFrames lint errors before inspect/render', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-lint-blocked-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- const outputPath = path.join(tmp, 'project', 'render', 'draft.mp4');
- const reportPath = path.join(tmp, 'project', 'render', 'draft-report.json');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0');
-
- const res = runRenderCompositionWithMockCore([
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', outputPath,
- '--report', reportPath,
- ], { ORKAS_MOCK_LINT_ERROR: '1' });
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_LINT_BLOCKED');
- expect(out.lint_summary.issueCodes).toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'gsap_timeline_not_registered', severity: 'error' }),
- ]));
- const report = parseJson(fs.readFileSync(reportPath, 'utf8'));
- expect(report.steps.lint.ok).toBe(false);
- expect(report.steps.inspect).toBeUndefined();
- expect(report.steps.render).toBeUndefined();
- });
-
- it('renders draft when inspect only reports visual advisories', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-visual-advisory-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- const outputPath = path.join(tmp, 'project', 'render', 'draft.mp4');
- const reportPath = path.join(tmp, 'project', 'render', 'draft-report.json');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0');
-
- const res = runRenderCompositionWithMockCore([
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', outputPath,
- '--report', reportPath,
- '--skip-video-qa',
- '--skip-normalize-audio',
- ], {
- ...makeFakeVideoProbeEnv(tmp),
- ORKAS_MOCK_INSPECT_VISUAL_ERROR: '1',
- ORKAS_MOCK_RENDER_OK: '1',
- });
-
- expect(res.status, res.stderr).toBe(0);
- const out = parseJson(res.stdout);
- expect(out.ok).toBe(true);
- expect(out.inspect).toMatchObject({
- ok: true,
- qa_ok: false,
- advisory_count: 3,
- blocking_error_count: 0,
- });
- const report = parseJson(fs.readFileSync(reportPath, 'utf8'));
- expect(report.ok).toBe(true);
- expect(report.steps.inspect).toMatchObject({
- ok: true,
- qa_ok: false,
- draft_disposition: {
- blocking_error_count: 0,
- advisory_count: 3,
- },
- });
- expect(report.steps.render).toMatchObject({ ok: true, path: outputPath });
- });
-
- it('fails a heavy FINAL render fast on a constrained machine (P2)', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-final-heavy-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- // 1920x1080 × 60s → ~3726 cost units (> heavy threshold).
- writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0', { width: 1920, height: 1080, duration: 60 });
-
- const res = runRenderCompositionWithMockCore([
- '--op', 'render',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'video.mp4'),
- '--quality', 'high',
- ], { ORKAS_MOCK_RAM_GB: '8', ORKAS_MOCK_RENDER_OK: '1' });
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_RENDER_TOO_HEAVY');
- expect(out.render_profile).toMatchObject({ constrained: true, decision: 'fail_fast' });
- });
-
- it('degrades a heavy DRAFT render (lower fps) on a constrained machine instead of failing (P2)', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-degrade-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir, { canvas: { width: 1920, height: 1080, duration: 60, fps: 60, language: 'en' } });
- writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0', { width: 1920, height: 1080, duration: 60 });
-
- const res = runRenderCompositionWithMockCore([
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- '--report', path.join(tmp, 'project', 'render', 'draft-report.json'),
- '--skip-video-qa',
- '--skip-normalize-audio',
- ], { ...makeFakeVideoProbeEnv(tmp), ORKAS_MOCK_RAM_GB: '8', ORKAS_MOCK_RENDER_OK: '1' });
-
- expect(res.status, res.stderr).toBe(0);
- const out = parseJson(res.stdout);
- expect(out.ok).toBe(true);
- expect(out.render_profile).toMatchObject({ constrained: true, decision: 'degrade', degraded_fps: '60→30' });
- });
-
- it('blocks draft when inspect reports non-visual errors', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-inspect-blocked-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- const outputPath = path.join(tmp, 'project', 'render', 'draft.mp4');
- const reportPath = path.join(tmp, 'project', 'render', 'draft-report.json');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0');
-
- const res = runRenderCompositionWithMockCore([
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', outputPath,
- '--report', reportPath,
- ], { ORKAS_MOCK_INSPECT_STRUCTURAL_ERROR: '1' });
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_INSPECT_BLOCKED');
- expect(out.draft_disposition).toMatchObject({
- blocking_error_count: 1,
- advisory_count: 0,
- });
- const report = parseJson(fs.readFileSync(reportPath, 'utf8'));
- expect(report.steps.inspect).toMatchObject({
- ok: false,
- qa_ok: false,
- draft_disposition: {
- blocking_error_count: 1,
- },
- });
- expect(report.steps.render).toBeUndefined();
- });
-
- it('blocks draft when HTML canvas differs from the design contract', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-canvas-mismatch-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0', { width: 1080, height: 1080, duration: 10 });
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');
- expect(out.contract_html.issues).toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'CANVAS_CONTRACT_MISMATCH' }),
- ]));
- });
-
- it('blocks draft when declared scene copy is not present in HTML', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-scene-copy-missing-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir, {
- scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0 Release Highlights' }],
- });
- writeMinimalCompositionHtml(compositionDir, 'Different title');
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');
- expect(out.contract_html.issues).toEqual(expect.arrayContaining([
- expect.objectContaining({ code: 'HTML_MISSING_SCENE_COPY' }),
- ]));
- });
-
- it('blocks draft with a targeted error when scene-map JSON is invalid', () => {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-scene-map-invalid-'));
- const compositionDir = path.join(tmp, 'project', 'composition');
- fs.mkdirSync(compositionDir, { recursive: true });
- writeDesignContract(compositionDir);
- writeMinimalCompositionHtml(compositionDir);
- fs.writeFileSync(path.join(compositionDir, 'scene-map.json'), '{ nope', 'utf8');
-
- const res = runSkill('stage-compose', 'render_composition', [
- '--op', 'draft',
- '--composition-dir', compositionDir,
- '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),
- ]);
-
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.code).toBe('E_SCENE_MAP_PARSE_FAILED');
- expect(out.repair_target).toBe('scene-map.json');
- });
-
it('fails edit_video before invoking ffmpeg when an input is missing', () => {
const res = runSkill('stage-edit', 'edit_video', ['--op', 'probe', '--input', 'missing.mp4']);
expect(res.status).toBe(1);
@@ -798,11 +169,4 @@ describe('video media skill scripts', () => {
expect(out.code).toBe('E_INPUT');
});
- it('fails render_composition before invoking HyperFrames when the directory is missing', () => {
- const res = runSkill('stage-compose', 'render_composition', ['--op', 'inspect', '--composition-dir', 'missing-composition']);
- expect(res.status).toBe(1);
- const out = parseJson(res.stderr);
- expect(out.ok).toBe(false);
- expect(out.code).toBe('E_INPUT');
- });
});
diff --git a/test/main/features/video_render_diagnostics.test.ts b/test/main/features/video_render_diagnostics.test.ts
deleted file mode 100644
index 56b92078..00000000
--- a/test/main/features/video_render_diagnostics.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { describe, it, expect } from 'vitest';
-
-import {
- parseRenderDiagnostics,
- classifyRenderCrash,
- machineRamGB,
- isConstrainedMachine,
- estimateRenderCost,
- renderCostDecision,
- degradedFps,
- LOW_RAM_GB,
- HEAVY_RENDER_COST,
-} from '../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render';
-
-describe('parseRenderDiagnostics', () => {
- // Real line captured from `hyperframes render` (0.7.3), which has a NESTED
- // "fps":{...} object — the parser must not truncate at the first `}`.
- const REAL_PIPELINE = '[INFO] [Render] Pipeline started {"platform":"darwin","arch":"arm64","nodeVersion":"v22.22.3","fps":{"num":30,"den":1},"format":"mp4","quality":"draft","browserGpuMode":"software","forceScreenshot":false,"protocolTimeout":300000,"browserTimeout":120000,"pageNavigationTimeout":60000,"playerReadyTimeout":45000}';
-
- it('parses browserGpuMode + timeouts from the real (nested-object) pipeline line', () => {
- const d = parseRenderDiagnostics(`some noise\n${REAL_PIPELINE}\nmore noise`);
- expect(d.gpuMode).toBe('software');
- expect(d.protocolTimeoutMs).toBe(300000);
- expect(d.browserTimeoutMs).toBe(120000);
- expect(d.playerReadyTimeoutMs).toBe(45000);
- });
-
- it('reads a hardware pipeline line', () => {
- const d = parseRenderDiagnostics('[INFO] [Render] Pipeline started {"browserGpuMode":"hardware","requestedWorkers":"auto","protocolTimeout":300000}');
- expect(d.gpuMode).toBe('hardware');
- expect(d.workers).toBe('auto');
- });
-
- it('falls back to the gpu-probe banner when there is no pipeline line', () => {
- expect(parseRenderDiagnostics('[hyperframes] browserGpuMode auto → hardware (WebGL probe succeeded)').gpuMode).toBe('hardware');
- expect(parseRenderDiagnostics('[hyperframes] browserGpuMode auto → software (no GPU)').gpuMode).toBe('software');
- });
-
- it('returns no gpuMode for unrelated output', () => {
- expect(parseRenderDiagnostics('ffmpeg version 6.0\nrendering frame 12').gpuMode).toBeUndefined();
- expect(parseRenderDiagnostics('').gpuMode).toBeUndefined();
- });
-});
-
-describe('classifyRenderCrash', () => {
- // Real crash tail shape from the weak-Intel-Mac report.
- const NATIVE_CRASH = 'inspect produced no findings. node::NewIsolate(v8::Isolate::CreateParams*, uv_loop_s*, node::MultiIsolatePlatform*, ...) v8::internal::SnapshotData*, v8::internal::SnapshotData*';
-
- it('classifies a V8 isolate/snapshot native abort (exit null) as native_worker_crash', () => {
- expect(classifyRenderCrash(NATIVE_CRASH, null, false)).toBe('native_worker_crash');
- expect(classifyRenderCrash(NATIVE_CRASH, 134, false)).toBe('native_worker_crash'); // SIGABRT-style nonzero
- });
-
- it('classifies a timeout as timeout regardless of stderr', () => {
- expect(classifyRenderCrash('', null, true)).toBe('timeout');
- expect(classifyRenderCrash(NATIVE_CRASH, null, true)).toBe('timeout');
- });
-
- it('does not misclassify a clean exit or an ordinary error', () => {
- expect(classifyRenderCrash(NATIVE_CRASH, 0, false)).toBeNull(); // exit 0 is not a crash
- expect(classifyRenderCrash('E_EDIT_FAILED: some ffmpeg error', 1, false)).toBeNull();
- expect(classifyRenderCrash('', 1, false)).toBeNull();
- });
-});
-
-describe('machineRamGB', () => {
- it('reports a positive coarse RAM figure', () => {
- const gb = machineRamGB();
- expect(gb).toBeGreaterThan(0);
- expect(gb).toBeLessThan(4096);
- });
-});
-
-describe('render-resilience profile (P1/P2)', () => {
- it('isConstrainedMachine: low RAM or observed software GPU forces constrained', () => {
- expect(isConstrainedMachine(LOW_RAM_GB)).toBe(true); // boundary: ≤8GB
- expect(isConstrainedMachine(LOW_RAM_GB - 1)).toBe(true);
- expect(isConstrainedMachine(16)).toBe(false);
- expect(isConstrainedMachine(64, 'software')).toBe(true); // software GPU forces it even on a big box
- expect(isConstrainedMachine(64, 'hardware')).toBe(false);
- });
-
- it('estimateRenderCost: frames × megapixels — the 60s@60fps 1080x1920 case is heavy', () => {
- const heavy = estimateRenderCost(1080, 1920, 60, 60); // ~7452
- const ok = estimateRenderCost(1080, 1920, 30, 30); // ~1863
- expect(heavy).toBeGreaterThan(HEAVY_RENDER_COST);
- expect(ok).toBeLessThan(HEAVY_RENDER_COST);
- });
-
- it('renderCostDecision: capable machine or light comp proceeds; heavy+constrained draft degrades, final fails fast', () => {
- const heavy = HEAVY_RENDER_COST + 1000;
- const light = HEAVY_RENDER_COST - 1000;
- expect(renderCostDecision({ constrained: false, costUnits: heavy, isFinal: true })).toBe('proceed');
- expect(renderCostDecision({ constrained: true, costUnits: light, isFinal: true })).toBe('proceed');
- expect(renderCostDecision({ constrained: true, costUnits: heavy, isFinal: false })).toBe('degrade');
- expect(renderCostDecision({ constrained: true, costUnits: heavy, isFinal: true })).toBe('fail_fast');
- });
-
- it('degradedFps: lowers >30 fps to 30, leaves ≤30 as-is', () => {
- expect(degradedFps(60)).toBe(30);
- expect(degradedFps(48)).toBe(30);
- expect(degradedFps(30)).toBe(30);
- expect(degradedFps(24)).toBe(24);
- });
-});
diff --git a/test/main/features/video_studio_native_qa.test.ts b/test/main/features/video_studio_native_qa.test.ts
new file mode 100644
index 00000000..88006352
--- /dev/null
+++ b/test/main/features/video_studio_native_qa.test.ts
@@ -0,0 +1,554 @@
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ draftComposition,
+ isCompositionRequestUrlAllowed,
+ renderComposition,
+ shouldNormalizeLoudness,
+ transcribeSpeech,
+ withVideoStudioTimeout,
+} from '../../../src/main/features/video_studio';
+import {
+ loadDesignContract,
+ loadNarrationMap,
+ loadSceneMap,
+ runAudioTimingQa,
+ summarizeDraftInspectDisposition,
+ summarizeVideoFrameQa,
+ type CompositionMeta,
+} from '../../../src/main/features/video_studio_qa';
+
+function tmpProject(label: string) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), `orkas-native-video-${label}-`));
+ const compositionDir = path.join(root, 'project', 'composition');
+ fs.mkdirSync(compositionDir, { recursive: true });
+ return {
+ root,
+ compositionDir,
+ renderDir: path.join(root, 'project', 'render'),
+ reportPath: path.join(root, 'project', 'render', 'draft-report.json'),
+ outputPath: path.join(root, 'project', 'render', 'draft.mp4'),
+ };
+}
+
+function writeHtml(compositionDir: string, text: string, attrs: { width?: number; height?: number; duration?: number } = {}) {
+ const width = attrs.width ?? 1920;
+ const height = attrs.height ?? 1080;
+ const duration = attrs.duration ?? 10;
+ fs.writeFileSync(path.join(compositionDir, 'index.html'), [
+ '<!doctype html>',
+ '<html><body>',
+ `<main data-composition-id="main" data-width="${width}" data-height="${height}" data-duration="${duration}">`,
+ `<section class="clip" data-start="0" data-duration="${duration}"><h1>${text}</h1></section>`,
+ '</main>',
+ '</body></html>',
+ ].join('\n'), 'utf8');
+}
+
+function writeHtmlWithAudio(compositionDir: string, text: string, attrs: { width?: number; height?: number; duration?: number } = {}) {
+ const width = attrs.width ?? 1920;
+ const height = attrs.height ?? 1080;
+ const duration = attrs.duration ?? 10;
+ fs.writeFileSync(path.join(compositionDir, 'index.html'), [
+ '<!doctype html>',
+ '<html><body>',
+ `<main data-composition-id="main" data-width="${width}" data-height="${height}" data-duration="${duration}">`,
+ `<audio src="./assets/narration.mp3" data-start="0" data-duration="${duration}"></audio>`,
+ `<section class="clip" data-start="0" data-duration="${duration}"><h1>${text}</h1></section>`,
+ '</main>',
+ '</body></html>',
+ ].join('\n'), 'utf8');
+}
+
+function writeContract(compositionDir: string, overrides: Record<string, unknown> = {}) {
+ fs.writeFileSync(path.join(compositionDir, 'design-contract.json'), JSON.stringify({
+ canvas: { width: 1920, height: 1080, duration: 10, fps: 30 },
+ scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Launch' }],
+ ...overrides,
+ }, null, 2), 'utf8');
+}
+
+function writeSceneMap(compositionDir: string, overrides: Record<string, unknown> = {}) {
+ fs.writeFileSync(path.join(compositionDir, 'scene-map.json'), JSON.stringify({
+ canvas: { width: 1920, height: 1080, duration: 10, fps: 30 },
+ scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Launch', narration: 'Launch narration.' }],
+ ...overrides,
+ }, null, 2), 'utf8');
+}
+
+const ENV_KEYS = [
+ 'ORKAS_BUNDLED_FFMPEG',
+ 'ORKAS_RUNTIME_DIR',
+ 'ORKAS_WHISPER_CPP',
+ 'ORKAS_WHISPER_CLI',
+ 'ORKAS_WHISPER_MODEL',
+] as const;
+const originalEnv = new Map<string, string | undefined>();
+for (const key of ENV_KEYS) originalEnv.set(key, process.env[key]);
+
+afterEach(() => {
+ for (const key of ENV_KEYS) {
+ const original = originalEnv.get(key);
+ if (original === undefined) delete process.env[key];
+ else process.env[key] = original;
+ }
+});
+
+function writeExecutable(file: string, body: string) {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, body, 'utf8');
+ fs.chmodSync(file, 0o755);
+}
+
+describe('native VideoStudio draft QA parity', () => {
+ it('S1 blocks composition BrowserWindow file:// requests outside composition_dir', async () => {
+ const p = tmpProject('file-sandbox');
+ const inside = path.join(p.compositionDir, 'assets', 'ok.png');
+ fs.mkdirSync(path.dirname(inside), { recursive: true });
+ fs.writeFileSync(inside, 'ok');
+ const outside = path.join(p.root, 'secret.txt');
+ fs.writeFileSync(outside, 'secret');
+
+ expect(isCompositionRequestUrlAllowed(pathToFileURL(inside).toString(), p.compositionDir)).toBe(true);
+ expect(isCompositionRequestUrlAllowed('data:image/png;base64,AA==', p.compositionDir)).toBe(true);
+ expect(isCompositionRequestUrlAllowed('about:blank', p.compositionDir)).toBe(true);
+ expect(isCompositionRequestUrlAllowed(pathToFileURL(outside).toString(), p.compositionDir)).toBe(false);
+ expect(isCompositionRequestUrlAllowed('https://example.test/asset.png', p.compositionDir)).toBe(false);
+
+ const link = path.join(p.compositionDir, 'assets', 'secret-link.txt');
+ try {
+ fs.symlinkSync(outside, link);
+ expect(isCompositionRequestUrlAllowed(pathToFileURL(link).toString(), p.compositionDir)).toBe(false);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'EPERM') throw err;
+ }
+ });
+
+ it('S1 rejects stalled native renderer work through the watchdog', async () => {
+ await expect(withVideoStudioTimeout(
+ new Promise(() => {}),
+ 1,
+ 'E_TEST_TIMEOUT',
+ 'test timeout',
+ )).rejects.toMatchObject({ errorCode: 'E_TEST_TIMEOUT', message: 'test timeout' });
+ });
+
+ it('S1 enforces the draft repair budget and blocks attempts after two repairs', async () => {
+ const p = tmpProject('repair-budget');
+
+ const attempts = [];
+ for (let i = 0; i < 4; i += 1) {
+ attempts.push(await draftComposition({
+ compositionDirAbs: p.compositionDir,
+ outputAbsPath: p.outputPath,
+ reportAbsPath: p.reportPath,
+ }));
+ }
+
+ expect(attempts[0]).toMatchObject({ ok: false, errorCode: 'E_LINT_BLOCKED' });
+ expect(attempts[1]).toMatchObject({ ok: false, errorCode: 'E_LINT_BLOCKED' });
+ expect(attempts[2]).toMatchObject({
+ ok: false,
+ errorCode: 'E_LINT_BLOCKED',
+ repair_budget: expect.objectContaining({ budget_exhausted: true, repair_passes_used: 2 }),
+ });
+ expect(attempts[3]).toMatchObject({ ok: false, errorCode: 'E_REPAIR_BUDGET_EXCEEDED' });
+ expect(fs.existsSync(path.join(p.compositionDir, 'qa', 'draft-repair-state.json'))).toBe(true);
+ });
+
+ it('S2 blocks contract_html mismatches before rendering', async () => {
+ const p = tmpProject('contract-html');
+ writeHtml(p.compositionDir, 'Launch', { width: 1280, height: 720, duration: 10 });
+ writeContract(p.compositionDir);
+ writeSceneMap(p.compositionDir);
+
+ const res = await draftComposition({
+ compositionDirAbs: p.compositionDir,
+ outputAbsPath: p.outputPath,
+ reportAbsPath: p.reportPath,
+ });
+
+ expect(res).toMatchObject({
+ ok: false,
+ errorCode: 'E_CONTRACT_HTML_BLOCKED',
+ contract_html: expect.objectContaining({
+ ok: false,
+ issues: expect.arrayContaining([expect.objectContaining({ code: 'CANVAS_CONTRACT_MISMATCH' })]),
+ }),
+ });
+ expect(fs.existsSync(p.outputPath)).toBe(false);
+ });
+
+ it('S2 blocks shotlist/source alignment drift before rendering', async () => {
+ const p = tmpProject('source-alignment');
+ writeHtml(p.compositionDir, 'Launch');
+ writeContract(p.compositionDir);
+ writeSceneMap(p.compositionDir);
+ fs.writeFileSync(path.join(p.root, 'project', 'shotlist.json'), JSON.stringify({
+ shots: [
+ { id: 's1', headline: 'Launch' },
+ { id: 's2', headline: 'Second approved beat' },
+ ],
+ }, null, 2), 'utf8');
+
+ const res = await draftComposition({
+ compositionDirAbs: p.compositionDir,
+ outputAbsPath: p.outputPath,
+ reportAbsPath: p.reportPath,
+ });
+
+ expect(res).toMatchObject({
+ ok: false,
+ errorCode: 'E_SOURCE_ALIGNMENT_BLOCKED',
+ source_alignment: expect.objectContaining({
+ issues: expect.arrayContaining([expect.objectContaining({ code: 'SHOTLIST_SCENE_MAP_MISMATCH' })]),
+ }),
+ });
+ });
+
+ it('S1/S2 blocks declared composition narration that would render silent', async () => {
+ const p = tmpProject('silent-narration');
+ writeHtml(p.compositionDir, 'Launch');
+ writeContract(p.compositionDir, {
+ audio: { owner: 'composition', narration_path: './assets/narration.mp3', target_sec: 10 },
+ });
+ writeSceneMap(p.compositionDir);
+
+ const res = await draftComposition({
+ compositionDirAbs: p.compositionDir,
+ outputAbsPath: p.outputPath,
+ reportAbsPath: p.reportPath,
+ });
+
+ expect(res).toMatchObject({
+ ok: false,
+ errorCode: 'E_AUDIO_TIMING_BLOCKED',
+ audio_timing: expect.objectContaining({
+ issues: expect.arrayContaining([expect.objectContaining({ code: 'NARRATION_DECLARED_BUT_SILENT' })]),
+ }),
+ });
+ expect(fs.existsSync(p.outputPath)).toBe(false);
+ });
+
+ it('S2 blocks narration-map timing drift before rendering', async () => {
+ const p = tmpProject('narration-drift');
+ fs.mkdirSync(path.join(p.compositionDir, 'assets'), { recursive: true });
+ fs.writeFileSync(path.join(p.compositionDir, 'assets', 'narration.mp3'), 'fake narration');
+ writeHtmlWithAudio(p.compositionDir, 'Line one');
+ writeContract(p.compositionDir, {
+ audio: { owner: 'composition', narration_path: './assets/narration.mp3', target_sec: 10 },
+ });
+ writeSceneMap(p.compositionDir, {
+ audio: { narration: './assets/narration.mp3' },
+ scenes: [{ id: 'cover', start: 5, duration: 2, headline: 'Line one', narration_ref: 'n1' }],
+ });
+ fs.writeFileSync(path.join(p.compositionDir, 'narration-map.json'), JSON.stringify({
+ lines: [{ id: 'n1', start: 0, duration: 2, text: 'Line one.' }],
+ }, null, 2), 'utf8');
+
+ const res = await draftComposition({
+ compositionDirAbs: p.compositionDir,
+ outputAbsPath: p.outputPath,
+ reportAbsPath: p.reportPath,
+ });
+
+ expect(res).toMatchObject({
+ ok: false,
+ errorCode: 'E_AUDIO_TIMING_BLOCKED',
+ audio_timing: expect.objectContaining({
+ issues: expect.arrayContaining([expect.objectContaining({ code: 'NARRATION_LINE_START_DRIFT' })]),
+ }),
+ });
+ expect(fs.existsSync(p.outputPath)).toBe(false);
+ });
+
+ it('S2 blocks ref-only narrated scenes when narration-map is missing', async () => {
+ const p = tmpProject('missing-narration-map');
+ fs.mkdirSync(path.join(p.compositionDir, 'assets'), { recursive: true });
+ fs.writeFileSync(path.join(p.compositionDir, 'assets', 'narration.mp3'), 'fake narration');
+ writeHtmlWithAudio(p.compositionDir, 'Line one Line two');
+ writeContract(p.compositionDir, {
+ audio: { owner: 'composition', narration_path: './assets/narration.mp3', target_sec: 10 },
+ });
+ writeSceneMap(p.compositionDir, {
+ audio: { narration: './assets/narration.mp3', narration_duration_seconds: 10 },
+ scenes: [
+ { id: 's01', start: 0, duration: 5, headline: 'Line one', narration_ref: 'n01' },
+ { id: 's02', start: 5, duration: 5, headline: 'Line two', narration_ref: 'n02' },
+ ],
+ });
+
+ const res = await draftComposition({
+ compositionDirAbs: p.compositionDir,
+ outputAbsPath: p.outputPath,
+ reportAbsPath: p.reportPath,
+ });
+
+ expect(res).toMatchObject({
+ ok: false,
+ errorCode: 'E_AUDIO_TIMING_BLOCKED',
+ audio_timing: expect.objectContaining({
+ issues: expect.arrayContaining([expect.objectContaining({ code: 'NARRATION_MAP_MISSING', severity: 'error' })]),
+ }),
+ });
+ expect(fs.existsSync(p.outputPath)).toBe(false);
+ });
+
+ it('S2 accepts scene_id narration-map lines with end times for timed audio refs', async () => {
+ const p = tmpProject('scene-id-narration-map');
+ fs.mkdirSync(path.join(p.compositionDir, 'assets'), { recursive: true });
+ const narrationPath = path.join(p.compositionDir, 'assets', 'narration.mp3');
+ fs.writeFileSync(narrationPath, 'fake narration');
+ writeContract(p.compositionDir, {
+ audio: { owner: 'composition', narration_path: './assets/narration.mp3', target_sec: 8 },
+ });
+ writeSceneMap(p.compositionDir, {
+ audio: { narration: './assets/narration.mp3', narration_duration_seconds: 8 },
+ scenes: [
+ { id: 's01', start: 0, end: 4, headline: 'Line one', narration_ref: 'assets/narration.mp3#t=0.00,4.00' },
+ { id: 's02', start: 4, end: 8, headline: 'Line two', narration_ref: 'assets/narration.mp3#t=4.00,8.00' },
+ ],
+ });
+ fs.writeFileSync(path.join(p.compositionDir, 'narration-map.json'), JSON.stringify({
+ lines: [
+ { scene_id: 's01', start: 0, end: 4, text: 'Line one.' },
+ { scene_id: 's02', start: 4, end: 8, text: 'Line two.' },
+ ],
+ }, null, 2), 'utf8');
+
+ const meta: CompositionMeta = {
+ htmlPath: path.join(p.compositionDir, 'index.html'),
+ html: '',
+ rootAttrs: {},
+ id: 'main',
+ width: 1920,
+ height: 1080,
+ durationSec: 8,
+ audioTracks: [{ absPath: narrationPath, startSec: 0, declaredDurationSec: 8, volume: 1 }],
+ };
+ const audioTiming = await runAudioTimingQa(
+ meta,
+ await loadDesignContract(p.compositionDir),
+ await loadSceneMap(p.compositionDir),
+ await loadNarrationMap(p.compositionDir),
+ p.compositionDir,
+ );
+
+ expect(audioTiming).toMatchObject({
+ ok: true,
+ narration_line_count: 2,
+ error_count: 0,
+ });
+ });
+
+ it('S2 estimates inline narration_text timing against actual narration duration', async () => {
+ const p = tmpProject('inline-narration-text-drift');
+ fs.mkdirSync(path.join(p.compositionDir, 'assets'), { recursive: true });
+ const narrationPath = path.join(p.compositionDir, 'assets', 'narration.mp3');
+ fs.writeFileSync(narrationPath, 'fake narration');
+ writeContract(p.compositionDir, {
+ audio: { owner: 'composition', narration_path: './assets/narration.mp3', target_sec: 10 },
+ });
+ writeSceneMap(p.compositionDir, {
+ audio: { narration: './assets/narration.mp3', narration_duration_seconds: 5 },
+ scenes: [
+ { id: 's01', start: 0, duration: 2, headline: 'Line one', narration_text: 'Line one.' },
+ { id: 's02', start: 8, duration: 2, headline: 'Line two', narration_text: 'Line two.' },
+ ],
+ });
+
+ const meta: CompositionMeta = {
+ htmlPath: path.join(p.compositionDir, 'index.html'),
+ html: '',
+ rootAttrs: {},
+ id: 'main',
+ width: 1920,
+ height: 1080,
+ durationSec: 10,
+ audioTracks: [{ absPath: narrationPath, startSec: 0, declaredDurationSec: 5, volume: 1 }],
+ };
+ const audioTiming = await runAudioTimingQa(
+ meta,
+ await loadDesignContract(p.compositionDir),
+ await loadSceneMap(p.compositionDir),
+ await loadNarrationMap(p.compositionDir),
+ p.compositionDir,
+ );
+
+ expect(audioTiming).toMatchObject({
+ ok: false,
+ issues: expect.arrayContaining([expect.objectContaining({ code: 'AUDIO_TIMING_DRIFT' })]),
+ });
+ });
+
+ it('S2 discovers bundled whisper runtime for speech.transcribe without env-only setup', async () => {
+ const p = tmpProject('bundled-whisper');
+ const input = path.join(p.root, 'raw.mp4');
+ const transcript = path.join(p.root, 'project', 'transcript.json');
+ fs.writeFileSync(input, 'fake media');
+
+ const fakeFfmpeg = path.join(p.root, 'ffmpeg');
+ writeExecutable(fakeFfmpeg, [
+ '#!/usr/bin/env node',
+ "const fs = require('node:fs');",
+ "fs.writeFileSync(process.argv[process.argv.length - 1], 'wav');",
+ '',
+ ].join('\n'));
+
+ const runtimeRoot = path.join(p.root, 'runtime');
+ const fakeWhisper = path.join(runtimeRoot, 'whisper', 'current', 'bin', 'whisper-cli');
+ writeExecutable(fakeWhisper, [
+ '#!/usr/bin/env node',
+ "const fs = require('node:fs');",
+ "const outIndex = process.argv.indexOf('-of');",
+ "const outBase = outIndex >= 0 ? process.argv[outIndex + 1] : 'transcript';",
+ "fs.writeFileSync(`${outBase}.json`, JSON.stringify({ text: 'hello world', segments: [] }));",
+ '',
+ ].join('\n'));
+ const model = path.join(runtimeRoot, 'whisper', 'current', 'models', 'ggml-base.bin');
+ fs.mkdirSync(path.dirname(model), { recursive: true });
+ fs.writeFileSync(model, 'model');
+
+ process.env.ORKAS_BUNDLED_FFMPEG = fakeFfmpeg;
+ process.env.ORKAS_RUNTIME_DIR = runtimeRoot;
+ delete process.env.ORKAS_WHISPER_CPP;
+ delete process.env.ORKAS_WHISPER_CLI;
+ delete process.env.ORKAS_WHISPER_MODEL;
+
+ const res = await transcribeSpeech({ inputAbsPath: input, transcriptAbsPath: transcript });
+
+ expect(res).toMatchObject({
+ ok: true,
+ op: 'speech.transcribe',
+ backend: 'orkas-native:whisper.cpp',
+ backend_source: 'bundled',
+ });
+ expect(fs.existsSync(transcript)).toBe(true);
+ });
+
+ it('S2 blocks incompatible local GSAP vendor files before rendering', async () => {
+ const p = tmpProject('gsap-vendor-incompatible');
+ fs.mkdirSync(path.join(p.compositionDir, 'assets', 'vendor'), { recursive: true });
+ fs.writeFileSync(path.join(p.compositionDir, 'assets', 'vendor', 'gsap.min.js'), 'window.gsap = {};', 'utf8');
+ writeHtml(p.compositionDir, 'Launch');
+ fs.appendFileSync(path.join(p.compositionDir, 'index.html'), [
+ '<script src="./assets/vendor/gsap.min.js"></script>',
+ '<script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',
+ ].join('\n'), 'utf8');
+ writeContract(p.compositionDir);
+ writeSceneMap(p.compositionDir);
+
+ const res = await draftComposition({
+ compositionDirAbs: p.compositionDir,
+ outputAbsPath: p.outputPath,
+ reportAbsPath: p.reportPath,
+ });
+
+ expect(res).toMatchObject({
+ ok: false,
+ errorCode: 'E_LINT_BLOCKED',
+ lint_summary: expect.objectContaining({
+ issues: expect.arrayContaining([expect.objectContaining({ code: 'VENDOR_GSAP_INCOMPATIBLE' })]),
+ }),
+ });
+ expect(fs.existsSync(p.outputPath)).toBe(false);
+ });
+
+ it('S1 fails heavy high-quality renders fast on constrained machines', async () => {
+ const p = tmpProject('heavy-render');
+ writeHtml(p.compositionDir, 'Launch', { width: 1920, height: 1080, duration: 60 });
+ const previous = process.env.ORKAS_MOCK_RAM_GB;
+ process.env.ORKAS_MOCK_RAM_GB = '8';
+ try {
+ const res = await renderComposition({
+ compositionDirAbs: p.compositionDir,
+ outputAbsPath: p.outputPath,
+ quality: 'high',
+ });
+ expect(res).toMatchObject({
+ ok: false,
+ errorCode: 'E_RENDER_TOO_HEAVY',
+ render_profile: expect.objectContaining({ constrained: true, decision: 'fail_fast' }),
+ });
+ expect(fs.existsSync(p.outputPath)).toBe(false);
+ } finally {
+ if (previous === undefined) delete process.env.ORKAS_MOCK_RAM_GB;
+ else process.env.ORKAS_MOCK_RAM_GB = previous;
+ }
+ });
+
+ it('S3 classifies visual inspect issues as advisories and structural issues as blockers', () => {
+ const findings = JSON.stringify({
+ ok: false,
+ errorCount: 2,
+ warningCount: 1,
+ issues: [
+ { code: 'TEXT_OVERFLOW', severity: 'error', message: 'visual overflow' },
+ { code: 'timeline_runtime_missing', severity: 'error', message: 'no runtime' },
+ { code: 'FONT_TOO_SMALL', severity: 'warning', message: 'small text' },
+ ],
+ });
+
+ expect(summarizeDraftInspectDisposition(findings)).toMatchObject({
+ blocking_error_count: 1,
+ advisory_count: 2,
+ blocking_issues: [expect.objectContaining({ code: 'timeline_runtime_missing' })],
+ });
+ });
+
+ it('S3 reports blank/frozen sampled frames with contact-sheet evidence fields', () => {
+ const qa = summarizeVideoFrameQa({
+ evidence_dir: '/tmp/evidence',
+ contact_sheet: '/tmp/evidence/contact-sheet.svg',
+ frame_paths: ['/tmp/evidence/01.png', '/tmp/evidence/02.png', '/tmp/evidence/03.png'],
+ samples: [
+ { label: 'first-frame', time_seconds: 0, frame_index: 0, path: '/tmp/evidence/01.png', hash: 'same', brightness: 0, contrast: 0, width: 1920, height: 1080 },
+ { label: 'midpoint', time_seconds: 5, frame_index: 75, path: '/tmp/evidence/02.png', hash: 'same', brightness: 0, contrast: 0, width: 1920, height: 1080 },
+ { label: 'payoff-frame', time_seconds: 10, frame_index: 150, path: '/tmp/evidence/03.png', hash: 'same', brightness: 0, contrast: 0, width: 1920, height: 1080 },
+ ],
+ }, 10);
+
+ expect(qa).toMatchObject({
+ ok: false,
+ contact_sheet: '/tmp/evidence/contact-sheet.svg',
+ frame_paths: expect.arrayContaining(['/tmp/evidence/01.png']),
+ issues: expect.arrayContaining([
+ expect.objectContaining({ code: 'EMPTY_HOOK_FRAME' }),
+ expect.objectContaining({ code: 'FROZEN_FRAME_RUN' }),
+ ]),
+ });
+ });
+
+ it('P1 normalizes loudness only for high exports or clearly off-target drafts', () => {
+ const nearTarget = {
+ ok: true,
+ input_i: -15,
+ input_tp: -1.2,
+ input_lra: 6,
+ target_i: -14,
+ target_tp: -1,
+ target_lra: 11,
+ };
+ const quietDraft = {
+ ...nearTarget,
+ input_i: -22,
+ };
+
+ expect(shouldNormalizeLoudness(nearTarget, 'draft')).toMatchObject({
+ normalize: false,
+ reason: 'within draft loudness tolerance',
+ });
+ expect(shouldNormalizeLoudness(nearTarget, 'high')).toMatchObject({
+ normalize: true,
+ reason: 'high quality export',
+ });
+ expect(shouldNormalizeLoudness(quietDraft, 'draft')).toMatchObject({
+ normalize: true,
+ });
+ });
+});
diff --git a/test/main/util/run-skill.test.ts b/test/main/util/run-skill.test.ts
index b0d408f9..7f2e5b9a 100644
--- a/test/main/util/run-skill.test.ts
+++ b/test/main/util/run-skill.test.ts
@@ -100,9 +100,9 @@ describe('run-skill.cjs', () => {
});
it('resolves current-agent private marketplace scripts from the installed agent directory', () => {
- writeAgentMarketplaceSkill('agent-a', 'stage-compose', 'stage-compose', 'render_composition');
+ writeAgentMarketplaceSkill('agent-a', 'stage-compose', 'stage-compose', 'compose_preview');
- const r = runSkill('stage-compose', 'render_composition', ['--op', 'inspect'], {
+ const r = runSkill('stage-compose', 'compose_preview', ['--op', 'inspect'], {
ORKAS_UID: 'u1',
ORKAS_AGENT_ID: 'agent-a',
});
@@ -113,9 +113,9 @@ describe('run-skill.cjs', () => {
});
it('does not expose another agent private marketplace skill', () => {
- writeAgentMarketplaceSkill('agent-a', 'stage-compose', 'stage-compose', 'render_composition');
+ writeAgentMarketplaceSkill('agent-a', 'stage-compose', 'stage-compose', 'compose_preview');
- const r = runSkill('stage-compose', 'render_composition', [], {
+ const r = runSkill('stage-compose', 'compose_preview', [], {
ORKAS_UID: 'u1',
ORKAS_AGENT_ID: 'agent-b',
});
@@ -129,9 +129,9 @@ describe('run-skill.cjs', () => {
});
it('requires ORKAS_UID before resolving agent private marketplace skills', () => {
- writeAgentMarketplaceSkill('agent-a', 'stage-compose', 'stage-compose', 'render_composition');
+ writeAgentMarketplaceSkill('agent-a', 'stage-compose', 'stage-compose', 'compose_preview');
- const r = runSkill('stage-compose', 'render_composition', [], {
+ const r = runSkill('stage-compose', 'compose_preview', [], {
ORKAS_AGENT_ID: 'agent-a',
});