Show it a video you love. Get a new video in the same style. An AI crew (Claude Code or Codex) plans, builds and reviews it with you.
JavaScript 2d-animationai-agentsai-videoanimationclaude-codecodexmulti-agentstyle-transfervideo-generation
Faithful characters, more variety, much less render time
許元豪2dc44f39d3a2
diff --git a/.claude/skills/anime-cel/template/render.mjs b/.claude/skills/anime-cel/template/render.mjsindex 238f559..df708de 100644--- a/.claude/skills/anime-cel/template/render.mjs+++ b/.claude/skills/anime-cel/template/render.mjs@@ -2,25 +2,28 @@//// Look at it (open the images with your image viewer / Read tool):// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times-// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg a stretch at 12 fps (motion; --every=1 for every frame)// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs// Make the video:// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)-// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable, cached:+// only frames of shots whose files changed are redrawn)// node render.mjs --encode --out=out/video.mp4 out/frames → MP4// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,-// --chrome=<path to Chrome/Chromium>.+// --chrome=<path to Chrome/Chromium>, --no-cache (redraw every frame in --frames).+// At most RENDER_SLOTS (default 4) renders hold a Chrome at once on this machine; the rest wait their turn.import puppeteer from 'puppeteer-core';import { spawn } from 'node:child_process';-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync, unlinkSync } from 'node:fs';+import { createHash } from 'node:crypto';import { dirname, resolve } from 'node:path';import { pathToFileURL } from 'node:url';-import { homedir } from 'node:os';+import { homedir, tmpdir } from 'node:os';const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',@@ -70,6 +73,26 @@ const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swift: process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+// One machine-wide slot per render (lock files): many agents rendering at once made page loads time out and retry.+// A slot whose owner died (its turn was cut off) is taken back.+const SLOT_DIR = `${tmpdir()}/reelmimic_render_slots`, SLOTS = +(process.env.RENDER_SLOTS || 4);+const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };+async function takeSlot() {+ mkdirSync(SLOT_DIR, { recursive: true });+ for (let waited = 0; ; waited++) {+ for (let i = 0; i < SLOTS; i++) {+ const f = `${SLOT_DIR}/slot${i}`;+ try { writeFileSync(f, String(process.pid), { flag: 'wx' }); return f; } catch {}+ try { if (!alive(+readFileSync(f, 'utf8'))) unlinkSync(f); } catch {}+ }+ if (waited && waited % 30 === 0) console.log(`waiting for a render slot (${SLOTS} in use machine-wide)…`);+ await new Promise(r => setTimeout(r, 1000));+ }+}+const slot = await takeSlot();+process.on('exit', () => { try { unlinkSync(slot); } catch {} });+for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(1));+const browser = await puppeteer.launch({executablePath: CHROME, headless: true, protocolTimeout: 0,args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']@@ -90,13 +113,30 @@ const frameOf = async (page, t, type, q) => {const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');};+// Frame key = hash(every shared file) + hash(the scene file that draws the frame's shot). Shared: studio.html, src/ outside+// src/scenes/, assets/ (size + mtime). A shot's scene file is the one whose text contains its function. Shots come from+// the page (SHOTS: [start, fn] in time order); a page without SHOTS gets no cache.+async function frameKeyer(fps) {+ const probe = await openPage(), shots = await probe.evaluate(() => (typeof SHOTS !== 'undefined' ? SHOTS.map(s => [s[0], String(s[1])]) : [])); await probe.close();+ if (!shots.length) return () => null;+ const walk = d => existsSync(d) ? readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(`${d}/${e.name}`) : [`${d}/${e.name}`]) : [];+ const h = createHash('sha1');+ for (const f of ['studio.html', ...walk('src').filter(f => !f.startsWith('src/scenes/')), ...walk('assets')].sort()) {+ const st = statSync(f); h.update(/\.(js|json|html|css)$/.test(f) ? readFileSync(f) : `${f}:${st.size}:${st.mtimeMs}`);+ }+ const shared = h.digest('hex');+ const scenes = walk('src/scenes').map(f => [f, readFileSync(f, 'utf8')]);+ const keys = shots.map(([, src]) => { const own = scenes.find(([, txt]) => txt.includes(src)); return createHash('sha1').update(shared).update(own ? own[1] : src).digest('hex').slice(0, 16); });+ return i => { const t = i / fps; let k = 0; while (k + 1 < shots.length && t >= shots[k + 1][0]) k++; return keys[k]; };+}+// the length of whatever is being rendered: a loop's .len, or the video's durationconst lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);if (args.sheet || args.strip) {const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });let ts;- if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ if (args.strip) { const [a, b] = span(args.strip), step = +(args.every || Math.max(1, Math.round(fps / 12))); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i += step) ts.push(i / fps); }else ts = times(args.sheet);const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);@@ -127,8 +167,17 @@ if (args.sheet || args.strip) {const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);mkdirSync(FRAMES_DIR, { recursive: true });const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);- const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }- console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ // cache: each frame remembers the key it was drawn with (shared files + the scene file of its shot); a changed key redraws it+ const keyOf = args.loop || args['no-cache'] ? () => null : await frameKeyer(fps);+ const MAN = `${FRAMES_DIR}/manifest.json`, man = (() => { try { const m = JSON.parse(readFileSync(MAN, 'utf8')); return m.fps === fps ? m.frames : {}; } catch { return {}; } })();+ const saveMan = () => { writeFileSync(MAN + '.tmp', JSON.stringify({ fps, frames: man })); renameSync(MAN + '.tmp', MAN); };+ const todo = []; let stale = 0;+ for (let i = first; i <= last; i++) {+ const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`, k = keyOf(i);+ if (!existsSync(f) || statSync(f).size < 1000) todo.push(i);+ else if (k && man[i] !== k) { todo.push(i); stale++; }+ }+ console.log(`${todo.length} frames to render (${stale} changed since last render, ${last - first + 1 - todo.length} cached), ${workers} workers`);let next = 0, done = 0; const start = Date.now();await Promise.all(Array.from({ length: workers }, async (_, w) => {const page = await openPage('#' + w);@@ -136,7 +185,9 @@ if (args.sheet || args.strip) {const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;const buf = await frameOf(page, i / fps, 'image/jpeg', .94);writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ const k = keyOf(i); if (k) man[i] = k;if (++done % 24 === 0 || done === todo.length) {+ saveMan();const el = (Date.now() - start) / 1000;console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);}diff --git a/.claude/skills/crayon-storybook/template/render.mjs b/.claude/skills/crayon-storybook/template/render.mjsindex 4e21538..10093e4 100644--- a/.claude/skills/crayon-storybook/template/render.mjs+++ b/.claude/skills/crayon-storybook/template/render.mjs@@ -2,25 +2,28 @@//// Look at it (open the images with your image viewer / Read tool):// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times-// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg a stretch at 12 fps (motion; --every=1 for every frame)// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs// Make the video:// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)-// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable, cached:+// only frames of shots whose files changed are redrawn)// node render.mjs --encode --out=out/video.mp4 out/frames → MP4// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,-// --chrome=<path to Chrome/Chromium>.+// --chrome=<path to Chrome/Chromium>, --no-cache (redraw every frame in --frames).+// At most RENDER_SLOTS (default 4) renders hold a Chrome at once on this machine; the rest wait their turn.import puppeteer from 'puppeteer-core';import { spawn } from 'node:child_process';-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync, unlinkSync } from 'node:fs';+import { createHash } from 'node:crypto';import { dirname, resolve } from 'node:path';import { pathToFileURL } from 'node:url';-import { homedir } from 'node:os';+import { homedir, tmpdir } from 'node:os';const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',@@ -70,6 +73,26 @@ const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swift: process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+// One machine-wide slot per render (lock files): many agents rendering at once made page loads time out and retry.+// A slot whose owner died (its turn was cut off) is taken back.+const SLOT_DIR = `${tmpdir()}/reelmimic_render_slots`, SLOTS = +(process.env.RENDER_SLOTS || 4);+const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };+async function takeSlot() {+ mkdirSync(SLOT_DIR, { recursive: true });+ for (let waited = 0; ; waited++) {+ for (let i = 0; i < SLOTS; i++) {+ const f = `${SLOT_DIR}/slot${i}`;+ try { writeFileSync(f, String(process.pid), { flag: 'wx' }); return f; } catch {}+ try { if (!alive(+readFileSync(f, 'utf8'))) unlinkSync(f); } catch {}+ }+ if (waited && waited % 30 === 0) console.log(`waiting for a render slot (${SLOTS} in use machine-wide)…`);+ await new Promise(r => setTimeout(r, 1000));+ }+}+const slot = await takeSlot();+process.on('exit', () => { try { unlinkSync(slot); } catch {} });+for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(1));+const browser = await puppeteer.launch({executablePath: CHROME, headless: true, protocolTimeout: 0,args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']@@ -94,13 +117,30 @@ const frameOf = async (page, t, type, q) => {const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');};+// Frame key = hash(every shared file) + hash(the scene file that draws the frame's shot). Shared: studio.html, src/ outside+// src/scenes/, assets/ (size + mtime). A shot's scene file is the one whose text contains its function. Shots come from+// the page (SHOTS: [start, fn] in time order); a page without SHOTS gets no cache.+async function frameKeyer(fps) {+ const probe = await openPage(), shots = await probe.evaluate(() => (typeof SHOTS !== 'undefined' ? SHOTS.map(s => [s[0], String(s[1])]) : [])); await probe.close();+ if (!shots.length) return () => null;+ const walk = d => existsSync(d) ? readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(`${d}/${e.name}`) : [`${d}/${e.name}`]) : [];+ const h = createHash('sha1');+ for (const f of ['studio.html', ...walk('src').filter(f => !f.startsWith('src/scenes/')), ...walk('assets')].sort()) {+ const st = statSync(f); h.update(/\.(js|json|html|css)$/.test(f) ? readFileSync(f) : `${f}:${st.size}:${st.mtimeMs}`);+ }+ const shared = h.digest('hex');+ const scenes = walk('src/scenes').map(f => [f, readFileSync(f, 'utf8')]);+ const keys = shots.map(([, src]) => { const own = scenes.find(([, txt]) => txt.includes(src)); return createHash('sha1').update(shared).update(own ? own[1] : src).digest('hex').slice(0, 16); });+ return i => { const t = i / fps; let k = 0; while (k + 1 < shots.length && t >= shots[k + 1][0]) k++; return keys[k]; };+}+// the length of whatever is being rendered: a loop's .len, or the video's durationconst lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);if (args.sheet || args.strip) {const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });let ts;- if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ if (args.strip) { const [a, b] = span(args.strip), step = +(args.every || Math.max(1, Math.round(fps / 12))); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i += step) ts.push(i / fps); }else ts = times(args.sheet);const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);@@ -131,8 +171,17 @@ if (args.sheet || args.strip) {const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);mkdirSync(FRAMES_DIR, { recursive: true });const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);- const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }- console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ // cache: each frame remembers the key it was drawn with (shared files + the scene file of its shot); a changed key redraws it+ const keyOf = args.loop || args['no-cache'] ? () => null : await frameKeyer(fps);+ const MAN = `${FRAMES_DIR}/manifest.json`, man = (() => { try { const m = JSON.parse(readFileSync(MAN, 'utf8')); return m.fps === fps ? m.frames : {}; } catch { return {}; } })();+ const saveMan = () => { writeFileSync(MAN + '.tmp', JSON.stringify({ fps, frames: man })); renameSync(MAN + '.tmp', MAN); };+ const todo = []; let stale = 0;+ for (let i = first; i <= last; i++) {+ const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`, k = keyOf(i);+ if (!existsSync(f) || statSync(f).size < 1000) todo.push(i);+ else if (k && man[i] !== k) { todo.push(i); stale++; }+ }+ console.log(`${todo.length} frames to render (${stale} changed since last render, ${last - first + 1 - todo.length} cached), ${workers} workers`);let next = 0, done = 0; const start = Date.now();await Promise.all(Array.from({ length: workers }, async (_, w) => {const page = await openPage('#' + w);@@ -140,7 +189,9 @@ if (args.sheet || args.strip) {const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;const buf = await frameOf(page, i / fps, 'image/jpeg', .94);writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ const k = keyOf(i); if (k) man[i] = k;if (++done % 24 === 0 || done === todo.length) {+ saveMan();const el = (Date.now() - start) / 1000;console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);}diff --git a/.claude/skills/painted-animation/template/render.mjs b/.claude/skills/painted-animation/template/render.mjsindex 238f559..df708de 100644--- a/.claude/skills/painted-animation/template/render.mjs+++ b/.claude/skills/painted-animation/template/render.mjs@@ -2,25 +2,28 @@//// Look at it (open the images with your image viewer / Read tool):// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times-// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg a stretch at 12 fps (motion; --every=1 for every frame)// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs// Make the video:// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)-// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable, cached:+// only frames of shots whose files changed are redrawn)// node render.mjs --encode --out=out/video.mp4 out/frames → MP4// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,-// --chrome=<path to Chrome/Chromium>.+// --chrome=<path to Chrome/Chromium>, --no-cache (redraw every frame in --frames).+// At most RENDER_SLOTS (default 4) renders hold a Chrome at once on this machine; the rest wait their turn.import puppeteer from 'puppeteer-core';import { spawn } from 'node:child_process';-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync, unlinkSync } from 'node:fs';+import { createHash } from 'node:crypto';import { dirname, resolve } from 'node:path';import { pathToFileURL } from 'node:url';-import { homedir } from 'node:os';+import { homedir, tmpdir } from 'node:os';const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',@@ -70,6 +73,26 @@ const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swift: process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+// One machine-wide slot per render (lock files): many agents rendering at once made page loads time out and retry.+// A slot whose owner died (its turn was cut off) is taken back.+const SLOT_DIR = `${tmpdir()}/reelmimic_render_slots`, SLOTS = +(process.env.RENDER_SLOTS || 4);+const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };+async function takeSlot() {+ mkdirSync(SLOT_DIR, { recursive: true });+ for (let waited = 0; ; waited++) {+ for (let i = 0; i < SLOTS; i++) {+ const f = `${SLOT_DIR}/slot${i}`;+ try { writeFileSync(f, String(process.pid), { flag: 'wx' }); return f; } catch {}+ try { if (!alive(+readFileSync(f, 'utf8'))) unlinkSync(f); } catch {}+ }+ if (waited && waited % 30 === 0) console.log(`waiting for a render slot (${SLOTS} in use machine-wide)…`);+ await new Promise(r => setTimeout(r, 1000));+ }+}+const slot = await takeSlot();+process.on('exit', () => { try { unlinkSync(slot); } catch {} });+for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(1));+const browser = await puppeteer.launch({executablePath: CHROME, headless: true, protocolTimeout: 0,args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']@@ -90,13 +113,30 @@ const frameOf = async (page, t, type, q) => {const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');};+// Frame key = hash(every shared file) + hash(the scene file that draws the frame's shot). Shared: studio.html, src/ outside+// src/scenes/, assets/ (size + mtime). A shot's scene file is the one whose text contains its function. Shots come from+// the page (SHOTS: [start, fn] in time order); a page without SHOTS gets no cache.+async function frameKeyer(fps) {+ const probe = await openPage(), shots = await probe.evaluate(() => (typeof SHOTS !== 'undefined' ? SHOTS.map(s => [s[0], String(s[1])]) : [])); await probe.close();+ if (!shots.length) return () => null;+ const walk = d => existsSync(d) ? readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(`${d}/${e.name}`) : [`${d}/${e.name}`]) : [];+ const h = createHash('sha1');+ for (const f of ['studio.html', ...walk('src').filter(f => !f.startsWith('src/scenes/')), ...walk('assets')].sort()) {+ const st = statSync(f); h.update(/\.(js|json|html|css)$/.test(f) ? readFileSync(f) : `${f}:${st.size}:${st.mtimeMs}`);+ }+ const shared = h.digest('hex');+ const scenes = walk('src/scenes').map(f => [f, readFileSync(f, 'utf8')]);+ const keys = shots.map(([, src]) => { const own = scenes.find(([, txt]) => txt.includes(src)); return createHash('sha1').update(shared).update(own ? own[1] : src).digest('hex').slice(0, 16); });+ return i => { const t = i / fps; let k = 0; while (k + 1 < shots.length && t >= shots[k + 1][0]) k++; return keys[k]; };+}+// the length of whatever is being rendered: a loop's .len, or the video's durationconst lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);if (args.sheet || args.strip) {const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });let ts;- if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ if (args.strip) { const [a, b] = span(args.strip), step = +(args.every || Math.max(1, Math.round(fps / 12))); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i += step) ts.push(i / fps); }else ts = times(args.sheet);const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);@@ -127,8 +167,17 @@ if (args.sheet || args.strip) {const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);mkdirSync(FRAMES_DIR, { recursive: true });const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);- const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }- console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ // cache: each frame remembers the key it was drawn with (shared files + the scene file of its shot); a changed key redraws it+ const keyOf = args.loop || args['no-cache'] ? () => null : await frameKeyer(fps);+ const MAN = `${FRAMES_DIR}/manifest.json`, man = (() => { try { const m = JSON.parse(readFileSync(MAN, 'utf8')); return m.fps === fps ? m.frames : {}; } catch { return {}; } })();+ const saveMan = () => { writeFileSync(MAN + '.tmp', JSON.stringify({ fps, frames: man })); renameSync(MAN + '.tmp', MAN); };+ const todo = []; let stale = 0;+ for (let i = first; i <= last; i++) {+ const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`, k = keyOf(i);+ if (!existsSync(f) || statSync(f).size < 1000) todo.push(i);+ else if (k && man[i] !== k) { todo.push(i); stale++; }+ }+ console.log(`${todo.length} frames to render (${stale} changed since last render, ${last - first + 1 - todo.length} cached), ${workers} workers`);let next = 0, done = 0; const start = Date.now();await Promise.all(Array.from({ length: workers }, async (_, w) => {const page = await openPage('#' + w);@@ -136,7 +185,9 @@ if (args.sheet || args.strip) {const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;const buf = await frameOf(page, i / fps, 'image/jpeg', .94);writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ const k = keyOf(i); if (k) man[i] = k;if (++done % 24 === 0 || done === todo.length) {+ saveMan();const el = (Date.now() - start) / 1000;console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);}diff --git a/.claude/skills/paper-cutout/template/render.mjs b/.claude/skills/paper-cutout/template/render.mjsindex 238f559..df708de 100644--- a/.claude/skills/paper-cutout/template/render.mjs+++ b/.claude/skills/paper-cutout/template/render.mjs@@ -2,25 +2,28 @@//// Look at it (open the images with your image viewer / Read tool):// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times-// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg a stretch at 12 fps (motion; --every=1 for every frame)// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs// Make the video:// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)-// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable, cached:+// only frames of shots whose files changed are redrawn)// node render.mjs --encode --out=out/video.mp4 out/frames → MP4// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,-// --chrome=<path to Chrome/Chromium>.+// --chrome=<path to Chrome/Chromium>, --no-cache (redraw every frame in --frames).+// At most RENDER_SLOTS (default 4) renders hold a Chrome at once on this machine; the rest wait their turn.import puppeteer from 'puppeteer-core';import { spawn } from 'node:child_process';-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync, unlinkSync } from 'node:fs';+import { createHash } from 'node:crypto';import { dirname, resolve } from 'node:path';import { pathToFileURL } from 'node:url';-import { homedir } from 'node:os';+import { homedir, tmpdir } from 'node:os';const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',@@ -70,6 +73,26 @@ const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swift: process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+// One machine-wide slot per render (lock files): many agents rendering at once made page loads time out and retry.+// A slot whose owner died (its turn was cut off) is taken back.+const SLOT_DIR = `${tmpdir()}/reelmimic_render_slots`, SLOTS = +(process.env.RENDER_SLOTS || 4);+const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };+async function takeSlot() {+ mkdirSync(SLOT_DIR, { recursive: true });+ for (let waited = 0; ; waited++) {+ for (let i = 0; i < SLOTS; i++) {+ const f = `${SLOT_DIR}/slot${i}`;+ try { writeFileSync(f, String(process.pid), { flag: 'wx' }); return f; } catch {}+ try { if (!alive(+readFileSync(f, 'utf8'))) unlinkSync(f); } catch {}+ }+ if (waited && waited % 30 === 0) console.log(`waiting for a render slot (${SLOTS} in use machine-wide)…`);+ await new Promise(r => setTimeout(r, 1000));+ }+}+const slot = await takeSlot();+process.on('exit', () => { try { unlinkSync(slot); } catch {} });+for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(1));+const browser = await puppeteer.launch({executablePath: CHROME, headless: true, protocolTimeout: 0,args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']@@ -90,13 +113,30 @@ const frameOf = async (page, t, type, q) => {const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');};+// Frame key = hash(every shared file) + hash(the scene file that draws the frame's shot). Shared: studio.html, src/ outside+// src/scenes/, assets/ (size + mtime). A shot's scene file is the one whose text contains its function. Shots come from+// the page (SHOTS: [start, fn] in time order); a page without SHOTS gets no cache.+async function frameKeyer(fps) {+ const probe = await openPage(), shots = await probe.evaluate(() => (typeof SHOTS !== 'undefined' ? SHOTS.map(s => [s[0], String(s[1])]) : [])); await probe.close();+ if (!shots.length) return () => null;+ const walk = d => existsSync(d) ? readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(`${d}/${e.name}`) : [`${d}/${e.name}`]) : [];+ const h = createHash('sha1');+ for (const f of ['studio.html', ...walk('src').filter(f => !f.startsWith('src/scenes/')), ...walk('assets')].sort()) {+ const st = statSync(f); h.update(/\.(js|json|html|css)$/.test(f) ? readFileSync(f) : `${f}:${st.size}:${st.mtimeMs}`);+ }+ const shared = h.digest('hex');+ const scenes = walk('src/scenes').map(f => [f, readFileSync(f, 'utf8')]);+ const keys = shots.map(([, src]) => { const own = scenes.find(([, txt]) => txt.includes(src)); return createHash('sha1').update(shared).update(own ? own[1] : src).digest('hex').slice(0, 16); });+ return i => { const t = i / fps; let k = 0; while (k + 1 < shots.length && t >= shots[k + 1][0]) k++; return keys[k]; };+}+// the length of whatever is being rendered: a loop's .len, or the video's durationconst lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);if (args.sheet || args.strip) {const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });let ts;- if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ if (args.strip) { const [a, b] = span(args.strip), step = +(args.every || Math.max(1, Math.round(fps / 12))); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i += step) ts.push(i / fps); }else ts = times(args.sheet);const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);@@ -127,8 +167,17 @@ if (args.sheet || args.strip) {const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);mkdirSync(FRAMES_DIR, { recursive: true });const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);- const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }- console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ // cache: each frame remembers the key it was drawn with (shared files + the scene file of its shot); a changed key redraws it+ const keyOf = args.loop || args['no-cache'] ? () => null : await frameKeyer(fps);+ const MAN = `${FRAMES_DIR}/manifest.json`, man = (() => { try { const m = JSON.parse(readFileSync(MAN, 'utf8')); return m.fps === fps ? m.frames : {}; } catch { return {}; } })();+ const saveMan = () => { writeFileSync(MAN + '.tmp', JSON.stringify({ fps, frames: man })); renameSync(MAN + '.tmp', MAN); };+ const todo = []; let stale = 0;+ for (let i = first; i <= last; i++) {+ const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`, k = keyOf(i);+ if (!existsSync(f) || statSync(f).size < 1000) todo.push(i);+ else if (k && man[i] !== k) { todo.push(i); stale++; }+ }+ console.log(`${todo.length} frames to render (${stale} changed since last render, ${last - first + 1 - todo.length} cached), ${workers} workers`);let next = 0, done = 0; const start = Date.now();await Promise.all(Array.from({ length: workers }, async (_, w) => {const page = await openPage('#' + w);@@ -136,7 +185,9 @@ if (args.sheet || args.strip) {const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;const buf = await frameOf(page, i / fps, 'image/jpeg', .94);writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ const k = keyOf(i); if (k) man[i] = k;if (++done % 24 === 0 || done === todo.length) {+ saveMan();const el = (Date.now() - start) / 1000;console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);}diff --git a/.claude/skills/pixel-art/template/render.mjs b/.claude/skills/pixel-art/template/render.mjsindex 238f559..df708de 100644--- a/.claude/skills/pixel-art/template/render.mjs+++ b/.claude/skills/pixel-art/template/render.mjs@@ -2,25 +2,28 @@//// Look at it (open the images with your image viewer / Read tool):// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times-// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg a stretch at 12 fps (motion; --every=1 for every frame)// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs// Make the video:// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)-// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable, cached:+// only frames of shots whose files changed are redrawn)// node render.mjs --encode --out=out/video.mp4 out/frames → MP4// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,-// --chrome=<path to Chrome/Chromium>.+// --chrome=<path to Chrome/Chromium>, --no-cache (redraw every frame in --frames).+// At most RENDER_SLOTS (default 4) renders hold a Chrome at once on this machine; the rest wait their turn.import puppeteer from 'puppeteer-core';import { spawn } from 'node:child_process';-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync, unlinkSync } from 'node:fs';+import { createHash } from 'node:crypto';import { dirname, resolve } from 'node:path';import { pathToFileURL } from 'node:url';-import { homedir } from 'node:os';+import { homedir, tmpdir } from 'node:os';const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',@@ -70,6 +73,26 @@ const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swift: process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+// One machine-wide slot per render (lock files): many agents rendering at once made page loads time out and retry.+// A slot whose owner died (its turn was cut off) is taken back.+const SLOT_DIR = `${tmpdir()}/reelmimic_render_slots`, SLOTS = +(process.env.RENDER_SLOTS || 4);+const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };+async function takeSlot() {+ mkdirSync(SLOT_DIR, { recursive: true });+ for (let waited = 0; ; waited++) {+ for (let i = 0; i < SLOTS; i++) {+ const f = `${SLOT_DIR}/slot${i}`;+ try { writeFileSync(f, String(process.pid), { flag: 'wx' }); return f; } catch {}+ try { if (!alive(+readFileSync(f, 'utf8'))) unlinkSync(f); } catch {}+ }+ if (waited && waited % 30 === 0) console.log(`waiting for a render slot (${SLOTS} in use machine-wide)…`);+ await new Promise(r => setTimeout(r, 1000));+ }+}+const slot = await takeSlot();+process.on('exit', () => { try { unlinkSync(slot); } catch {} });+for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(1));+const browser = await puppeteer.launch({executablePath: CHROME, headless: true, protocolTimeout: 0,args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']@@ -90,13 +113,30 @@ const frameOf = async (page, t, type, q) => {const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');};+// Frame key = hash(every shared file) + hash(the scene file that draws the frame's shot). Shared: studio.html, src/ outside+// src/scenes/, assets/ (size + mtime). A shot's scene file is the one whose text contains its function. Shots come from+// the page (SHOTS: [start, fn] in time order); a page without SHOTS gets no cache.+async function frameKeyer(fps) {+ const probe = await openPage(), shots = await probe.evaluate(() => (typeof SHOTS !== 'undefined' ? SHOTS.map(s => [s[0], String(s[1])]) : [])); await probe.close();+ if (!shots.length) return () => null;+ const walk = d => existsSync(d) ? readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(`${d}/${e.name}`) : [`${d}/${e.name}`]) : [];+ const h = createHash('sha1');+ for (const f of ['studio.html', ...walk('src').filter(f => !f.startsWith('src/scenes/')), ...walk('assets')].sort()) {+ const st = statSync(f); h.update(/\.(js|json|html|css)$/.test(f) ? readFileSync(f) : `${f}:${st.size}:${st.mtimeMs}`);+ }+ const shared = h.digest('hex');+ const scenes = walk('src/scenes').map(f => [f, readFileSync(f, 'utf8')]);+ const keys = shots.map(([, src]) => { const own = scenes.find(([, txt]) => txt.includes(src)); return createHash('sha1').update(shared).update(own ? own[1] : src).digest('hex').slice(0, 16); });+ return i => { const t = i / fps; let k = 0; while (k + 1 < shots.length && t >= shots[k + 1][0]) k++; return keys[k]; };+}+// the length of whatever is being rendered: a loop's .len, or the video's durationconst lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);if (args.sheet || args.strip) {const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });let ts;- if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ if (args.strip) { const [a, b] = span(args.strip), step = +(args.every || Math.max(1, Math.round(fps / 12))); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i += step) ts.push(i / fps); }else ts = times(args.sheet);const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);@@ -127,8 +167,17 @@ if (args.sheet || args.strip) {const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);mkdirSync(FRAMES_DIR, { recursive: true });const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);- const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }- console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ // cache: each frame remembers the key it was drawn with (shared files + the scene file of its shot); a changed key redraws it+ const keyOf = args.loop || args['no-cache'] ? () => null : await frameKeyer(fps);+ const MAN = `${FRAMES_DIR}/manifest.json`, man = (() => { try { const m = JSON.parse(readFileSync(MAN, 'utf8')); return m.fps === fps ? m.frames : {}; } catch { return {}; } })();+ const saveMan = () => { writeFileSync(MAN + '.tmp', JSON.stringify({ fps, frames: man })); renameSync(MAN + '.tmp', MAN); };+ const todo = []; let stale = 0;+ for (let i = first; i <= last; i++) {+ const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`, k = keyOf(i);+ if (!existsSync(f) || statSync(f).size < 1000) todo.push(i);+ else if (k && man[i] !== k) { todo.push(i); stale++; }+ }+ console.log(`${todo.length} frames to render (${stale} changed since last render, ${last - first + 1 - todo.length} cached), ${workers} workers`);let next = 0, done = 0; const start = Date.now();await Promise.all(Array.from({ length: workers }, async (_, w) => {const page = await openPage('#' + w);@@ -136,7 +185,9 @@ if (args.sheet || args.strip) {const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;const buf = await frameOf(page, i / fps, 'image/jpeg', .94);writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ const k = keyOf(i); if (k) man[i] = k;if (++done % 24 === 0 || done === todo.length) {+ saveMan();const el = (Date.now() - start) / 1000;console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);}diff --git a/.claude/skills/video-clone/CONTRACT.md b/.claude/skills/video-clone/CONTRACT.mdindex 7a32e06..a60b263 100644--- a/.claude/skills/video-clone/CONTRACT.md+++ b/.claude/skills/video-clone/CONTRACT.md@@ -105,7 +105,8 @@ projects/<id>/## 生產線檔案(核准後)```-build/production.json 導演:{ cast_sheet, characters, chunks: [{id, shots}], shot_files, how_to_preview, how_to_render, shared_readonly }+build/production.json 導演:{ cast_sheet, characters, chunks: [{id, shots}], shot_files, how_to_preview, how_to_render, shared_readonly,+ prerender: { cwd, cmd 含 {start} {end} } ← 有影格快取的引擎才寫;每段通過審查後系統自動在背景渲染那段的正式影格 }out/check/cast/sheet_<角色>.jpg 每個角色一張設定圖(正面/3/4/側面/表情/姿勢);sheet.jpg = 全角色並排build/assets/cast/<角色>.js 每個角色一個定義檔(多角色時各自由一組審查+修正同時進行,不能共用一個檔)out/check/cast/review_<角色>.json / fixes_<角色>.json 個別角色的審查與修正(要改共用骨架的項目 status: shared,由導演統一改)diff --git a/.claude/skills/video-clone/SKILL.md b/.claude/skills/video-clone/SKILL.mdindex 81f8f42..260f9b3 100644--- a/.claude/skills/video-clone/SKILL.md+++ b/.claude/skills/video-clone/SKILL.md@@ -87,6 +87,9 @@ plan.json 每個 shot 填 `ref_shot`(參考片鏡頭編號)、`ref_what`(peaks 裡的鏡頭標 `hero: true`。核准前先把每個爆點那一格做到成片品質,和參考片同一格並排成 `out/check/key_<n>_vs_ref.jpg`,放在 style_frames 最前面給使用者看;比參考片弱就繼續改,不要交出去。+**變化**:同一場景+同一機位不超過片長 40%,高潮之間換場景或視角;鋪陳段每 1–1.5 秒畫面要有新東西,不要一個構圖停著等爆點。+要有情緒弧線(想要什麼 → 等待或阻礙 → 高潮時得到),不只是能量往上。+給使用者看分鏡並簡短說明;使用者說過「你自己決定」就直接開做。## 5. 製作:一關一關過,不要堆到最後才審@@ -127,6 +130,7 @@ peaks 裡的鏡頭標 `hero: true`。核准前先把每個爆點那一格做到- **角色**:- **使用者自己擁有的角色可以直接用**:使用者提供自家角色/吉祥物的設計圖(放在 inputs/),就照它製作並保持造型一致,不必換成原創。+ **設計圖就是規格**:比例、眼睛、手腳、配色照圖量(不要拿引擎內建的同名角色改),配件綁在臉的錨點上;角色關、鏡頭審查、評審都要把設計圖和畫面並排比。- **使用者點名要用的角色可以直接用**:自己上網找它的造型(衣服、髮型、配件、配色)照著做,不要拒絕或換成「神似原創」。- 使用者沒指定角色時用原創角色。- **歌詞**:只使用使用者提供的 LRC / 歌詞文字,不自行寫出歌詞;分鏡與回報中也不要引用歌詞內容。diff --git a/.claude/skills/video-clone/scripts/clip_strip.py b/.claude/skills/video-clone/scripts/clip_strip.pyindex 520b0f3..16115f3 100644--- a/.claude/skills/video-clone/scripts/clip_strip.py+++ b/.claude/skills/video-clone/scripts/clip_strip.py@@ -4,7 +4,11 @@Stills can't show motion or a climax: a hit is the frames around it. Use this whenever you judge a moment.python clip_strip.py out/video.mp4 --range 24.0:26.0 --out out/check/peak_1.jpg- python clip_strip.py out/video.mp4 --range 24.0:26.0 --vs analysis/source.mp4 --vs-range 25.0:27.0 --out out/check/peak_1_vs_ref.jpg+ python clip_strip.py out/video.mp4 --range 24.0:26.0 --vs analysis/proxy.mp4 --vs-range 25.0:27.0 --out out/check/peak_1_vs_ref.jpg++The reference is the file analyze.py actually analysed (report.json "analysed": proxy.mp4 when the picture had to be+cropped out of a screen recording). Passing analysis/source.mp4 is switched to proxy.mp4 automatically when one exists,+and a reference row that comes out (almost) black stops with an error instead of producing a fake comparison.--fps (default 12) frames per second of the stretch; --w (default 240) width of each frame; --cols (default 12).With --vs, the reference range is sampled into the same number of frames and each reference row sits directly above@@ -49,8 +53,15 @@ def main():ours = grab(a.video, s, e, n, a.w)ref = Noneif a.vs:+ vs = a.vs+ proxy = os.path.join(os.path.dirname(vs), "proxy.mp4")+ if os.path.basename(vs).startswith("source.") and os.path.isfile(proxy):+ print(f"reference: using {proxy} (the cropped picture) instead of {vs}"); vs = proxyrs, re_ = map(float, (a.vs_range or a.range).split(":"))- ref = grab(a.vs, rs, re_, len(ours), a.w)+ ref = grab(vs, rs, re_, len(ours), a.w)+ dark = sum(1 for _, im in ref if max(im.convert("L").getextrema()) < 30) / max(1, len(ref))+ if dark > 0.8:+ raise SystemExit(f"reference rows are black ({dark:.0%} of frames) — wrong file or time range? Use the file in report.json 'analysed' (usually analysis/proxy.mp4)")fh = ours[0][1].height; lab = 18; f = font(13)rows = [ours[i:i + a.cols] for i in range(0, len(ours), a.cols)]refrows = [ref[i:i + a.cols] for i in range(0, len(ref), a.cols)] if ref else []diff --git a/.claude/skills/whiteboard/template/render.mjs b/.claude/skills/whiteboard/template/render.mjsindex 238f559..df708de 100644--- a/.claude/skills/whiteboard/template/render.mjs+++ b/.claude/skills/whiteboard/template/render.mjs@@ -2,25 +2,28 @@//// Look at it (open the images with your image viewer / Read tool):// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times-// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg a stretch at 12 fps (motion; --every=1 for every frame)// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs// Make the video:// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)-// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable, cached:+// only frames of shots whose files changed are redrawn)// node render.mjs --encode --out=out/video.mp4 out/frames → MP4// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,-// --chrome=<path to Chrome/Chromium>.+// --chrome=<path to Chrome/Chromium>, --no-cache (redraw every frame in --frames).+// At most RENDER_SLOTS (default 4) renders hold a Chrome at once on this machine; the rest wait their turn.import puppeteer from 'puppeteer-core';import { spawn } from 'node:child_process';-import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync } from 'node:fs';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync, readFileSync, unlinkSync } from 'node:fs';+import { createHash } from 'node:crypto';import { dirname, resolve } from 'node:path';import { pathToFileURL } from 'node:url';-import { homedir } from 'node:os';+import { homedir, tmpdir } from 'node:os';const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',@@ -70,6 +73,26 @@ const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swift: process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+// One machine-wide slot per render (lock files): many agents rendering at once made page loads time out and retry.+// A slot whose owner died (its turn was cut off) is taken back.+const SLOT_DIR = `${tmpdir()}/reelmimic_render_slots`, SLOTS = +(process.env.RENDER_SLOTS || 4);+const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };+async function takeSlot() {+ mkdirSync(SLOT_DIR, { recursive: true });+ for (let waited = 0; ; waited++) {+ for (let i = 0; i < SLOTS; i++) {+ const f = `${SLOT_DIR}/slot${i}`;+ try { writeFileSync(f, String(process.pid), { flag: 'wx' }); return f; } catch {}+ try { if (!alive(+readFileSync(f, 'utf8'))) unlinkSync(f); } catch {}+ }+ if (waited && waited % 30 === 0) console.log(`waiting for a render slot (${SLOTS} in use machine-wide)…`);+ await new Promise(r => setTimeout(r, 1000));+ }+}+const slot = await takeSlot();+process.on('exit', () => { try { unlinkSync(slot); } catch {} });+for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(1));+const browser = await puppeteer.launch({executablePath: CHROME, headless: true, protocolTimeout: 0,args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']@@ -90,13 +113,30 @@ const frameOf = async (page, t, type, q) => {const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');};+// Frame key = hash(every shared file) + hash(the scene file that draws the frame's shot). Shared: studio.html, src/ outside+// src/scenes/, assets/ (size + mtime). A shot's scene file is the one whose text contains its function. Shots come from+// the page (SHOTS: [start, fn] in time order); a page without SHOTS gets no cache.+async function frameKeyer(fps) {+ const probe = await openPage(), shots = await probe.evaluate(() => (typeof SHOTS !== 'undefined' ? SHOTS.map(s => [s[0], String(s[1])]) : [])); await probe.close();+ if (!shots.length) return () => null;+ const walk = d => existsSync(d) ? readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(`${d}/${e.name}`) : [`${d}/${e.name}`]) : [];+ const h = createHash('sha1');+ for (const f of ['studio.html', ...walk('src').filter(f => !f.startsWith('src/scenes/')), ...walk('assets')].sort()) {+ const st = statSync(f); h.update(/\.(js|json|html|css)$/.test(f) ? readFileSync(f) : `${f}:${st.size}:${st.mtimeMs}`);+ }+ const shared = h.digest('hex');+ const scenes = walk('src/scenes').map(f => [f, readFileSync(f, 'utf8')]);+ const keys = shots.map(([, src]) => { const own = scenes.find(([, txt]) => txt.includes(src)); return createHash('sha1').update(shared).update(own ? own[1] : src).digest('hex').slice(0, 16); });+ return i => { const t = i / fps; let k = 0; while (k + 1 < shots.length && t >= shots[k + 1][0]) k++; return keys[k]; };+}+// the length of whatever is being rendered: a loop's .len, or the video's durationconst lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);if (args.sheet || args.strip) {const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });let ts;- if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ if (args.strip) { const [a, b] = span(args.strip), step = +(args.every || Math.max(1, Math.round(fps / 12))); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i += step) ts.push(i / fps); }else ts = times(args.sheet);const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);@@ -127,8 +167,17 @@ if (args.sheet || args.strip) {const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);mkdirSync(FRAMES_DIR, { recursive: true });const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);- const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }- console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ // cache: each frame remembers the key it was drawn with (shared files + the scene file of its shot); a changed key redraws it+ const keyOf = args.loop || args['no-cache'] ? () => null : await frameKeyer(fps);+ const MAN = `${FRAMES_DIR}/manifest.json`, man = (() => { try { const m = JSON.parse(readFileSync(MAN, 'utf8')); return m.fps === fps ? m.frames : {}; } catch { return {}; } })();+ const saveMan = () => { writeFileSync(MAN + '.tmp', JSON.stringify({ fps, frames: man })); renameSync(MAN + '.tmp', MAN); };+ const todo = []; let stale = 0;+ for (let i = first; i <= last; i++) {+ const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`, k = keyOf(i);+ if (!existsSync(f) || statSync(f).size < 1000) todo.push(i);+ else if (k && man[i] !== k) { todo.push(i); stale++; }+ }+ console.log(`${todo.length} frames to render (${stale} changed since last render, ${last - first + 1 - todo.length} cached), ${workers} workers`);let next = 0, done = 0; const start = Date.now();await Promise.all(Array.from({ length: workers }, async (_, w) => {const page = await openPage('#' + w);@@ -136,7 +185,9 @@ if (args.sheet || args.strip) {const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;const buf = await frameOf(page, i / fps, 'image/jpeg', .94);writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ const k = keyOf(i); if (k) man[i] = k;if (++done % 24 === 0 || done === todo.length) {+ saveMan();const el = (Date.now() - start) / 1000;console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);}diff --git a/app/scripts/doctor.mjs b/app/scripts/doctor.mjsindex ab2b248..2bbf8b8 100644--- a/app/scripts/doctor.mjs+++ b/app/scripts/doctor.mjs@@ -2,7 +2,7 @@// Plain JavaScript on purpose: it must run (and say "upgrade Node") even on a Node too old to run the TypeScript server.// @ts-checkimport { execFileSync } from 'node:child_process';-import { existsSync, readFileSync } from 'node:fs';+import { existsSync, readFileSync, statfsSync } from 'node:fs';import { homedir, platform } from 'node:os';import { join } from 'node:path';@@ -49,6 +49,11 @@ if (pyv) {for (const [m, pkg] of mods) probe(m) ? ok(pkg) : bad(pkg, `${PY} -m pip install -r requirements.txt`);for (const [m, pkg, why] of optMods) probe(m) ? ok(pkg) : opt(`${pkg} not installed`, why);}+// Renders write frames, previews and the encode next to the projects: a real run got down to 66 MB free mid-production.+try {+ const f = statfsSync(join(import.meta.dirname, '..', '..')), gb = (f.bavail * f.bsize) / 2 ** 30;+ gb >= 5 ? ok(`Disk: ${gb.toFixed(0)} GB free`) : bad(`Disk: only ${gb.toFixed(1)} GB free`, 'free at least 5 GB before making a video (old projects/*/build/out/frames can go)');+} catch { /* statfs unsupported */ }console.log('\nAI director (at least one)');const claude = run('claude', ['--version']);diff --git a/app/server/agents/index.test.ts b/app/server/agents/index.test.tsindex eb4aa4c..7f0d964 100644--- a/app/server/agents/index.test.ts+++ b/app/server/agents/index.test.ts@@ -60,8 +60,8 @@ test('Codex failure emits an error', () => {});test('long tool details are shortened', () => {- const { events } = run(parseClaude, [{ type: 'assistant', message: { content: [{ type: 'tool_use', name: 'Write', input: { file_path: 'x'.repeat(300) } }] } }]);+ const { events } = run(parseClaude, [{ type: 'assistant', message: { content: [{ type: 'tool_use', name: 'Write', input: { file_path: 'x'.repeat(600) } }] } }]);const e = events[0] as Extract<AgentEvent, { type: 'tool' }>;- assert.equal(e.detail.length, 161);+ assert.equal(e.detail.length, 401);assert.ok(e.detail.endsWith('…'));});diff --git a/app/server/agents/index.ts b/app/server/agents/index.tsindex 156d1de..ecafab7 100644--- a/app/server/agents/index.ts+++ b/app/server/agents/index.ts@@ -53,7 +53,7 @@ function lines(stream: Readable, onLine: (l: string) => void) {stream.on('end', () => { if (buf.trim()) onLine(buf.trim()); });}-const short = (v: unknown, n = 160) => { const s = typeof v === 'string' ? v : JSON.stringify(v); return s.length > n ? s.slice(0, n) + '…' : s; };+const short = (v: unknown, n = 400) => { const s = typeof v === 'string' ? v : JSON.stringify(v); return s.length > n ? s.slice(0, n) + '…' : s; };function claudeArgs(sessionId?: string | null) {const a = ['-p', '--output-format', 'stream-json', '--verbose', '--permission-mode', 'acceptEdits', '--allowedTools', CLAUDE_TOOLS];diff --git a/app/server/jobs.ts b/app/server/jobs.tsindex 2ca7130..062cf18 100644--- a/app/server/jobs.ts+++ b/app/server/jobs.ts@@ -8,9 +8,9 @@// → critiquing: final panel (fresh critic: continuity/pacing/seams, verifies earlier fixes) ⇄ revising// → done (needs_user items never trigger a revise: they pause the job and ask the user)// Quality is checked where defects are born (each character, each chunk), not only at the end.-import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync, cpSync } from 'node:fs';+import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync, statfsSync, cpSync } from 'node:fs';import { join, relative, resolve } from 'node:path';-import { spawn } from 'node:child_process';+import { spawn, type ChildProcess } from 'node:child_process';import { EventEmitter } from 'node:events';import { runAgent, type AgentResult } from './agents/index.ts';import { prompts as bootPrompts } from './prompts.ts';@@ -75,7 +75,7 @@ export type BusEvent = { type: 'job'; job: Job } | { type: 'log'; ev: LogEvent }export const bus = new EventEmitter<{ job: [id: string, ev: BusEvent] }>(); bus.setMaxListeners(100);const running = new Map<string, Set<AbortController>>();// Stop every agent this server started (on shutdown), so none keeps working unseen after a restart.-export function stopAll() { for (const set of running.values()) for (const ac of set) ac.abort(); }+export function stopAll() { for (const set of running.values()) for (const ac of set) ac.abort(); for (const set of prerenderProcs.values()) for (const p of set) p.kill(); }const now = () => new Date().toISOString();export const dirOf = (id: string) => join(PROJECTS, id);@@ -324,9 +324,19 @@ function collectNeeds(id: string, items: NeedRequest[] | undefined, from: stringreturn add.length;}+// Renders need room (frames, previews, the encode): warn early instead of failing mid-render. A real run had 66 MB left.+const MIN_FREE_GB = 5;+function diskWarning(id: string) {+ try {+ const f = statfsSync(PROJECTS), gb = (f.bavail * f.bsize) / 2 ** 30;+ if (gb < MIN_FREE_GB) chat(id, 'system', L(id, `⚠️ 磁碟只剩 ${gb.toFixed(1)} GB,渲染可能中途失敗;建議先清出 ${MIN_FREE_GB} GB 以上。`, `⚠️ Only ${gb.toFixed(1)} GB of disk left; rendering may fail midway. Free at least ${MIN_FREE_GB} GB first.`));+ } catch { /* statfs unsupported: skip */ }+}+// ---------- pre-production ----------const STYLE_OUT = ['analysis/STYLE.md', 'analysis/route.json', 'analysis/peaks.json']; // peaks: the reference's goosebump momentsexport async function start(id: string) {+ diskWarning(id);if (!(await analyze(id))) return;if (!(await step(id, 'styling', 'style', {}, STYLE_OUT, 'styled'))) return;await preProduction(id);@@ -423,6 +433,7 @@ export async function approve(id: string) {if (open.length) throw Object.assign(new Error('還有需要你提供或略過的素材:' + open.map((r) => r.label || r.id).join('、')), { code: 409 });await alignIfReady(id).catch(() => null); // lyrics pasted before the music arrived: time them now, before anything is builtupdate(id, (j) => { j.approvedAt = now(); j.approvedPlanVersion = readJSON<Plan>(join(dirOf(id), 'plan.json'))?.version; j.engineSnapshot = snapshotEngine(id); j.pipeline = {}; j.sessions = j.approvedAtPrev ? {} : Object.fromEntries(Object.entries(j.sessions || {}).filter(([k]) => k.startsWith('cast-'))); j.approvedAtPrev = true; j.needs = []; j.userNote = null; j.critiqueRounds = 0; });+ diskWarning(id);chat(id, 'system', L(id, `企劃已核准,開始生產:角色關 → 分段製作(每段做完立刻審)→ 組裝 → 最後評審`, 'Plan approved. Production: characters → parts built and reviewed as they finish → assembly → final review'));if (await production(id, { fresh: true })) await finalPanel(id);}@@ -496,8 +507,10 @@ async function production(id: string, { fresh = false } = {}): Promise<boolean>const needs = c.shots.flatMap((x) => results[x]?.needs || []);if (collectNeeds(id, needs, `shot-qa-${c.id}`)) { set({ state: 'needs_user' }); return false; }const bad = c.shots.map((x) => results[x]?.entry).filter((e): e is ShotEntry => !!e && !shotPassed(e));- if (!bad.length) { set({ state: 'passed' }); return true; }- if (round >= rounds(id).chunkRounds) { set({ state: 'failed', open: bad.length }); return false; }+ if (!bad.length) { set({ state: 'passed' }); prerender(id, c); return true; }+ // one blocker left at the limit: one more round instead of pausing (a real run sat 23 minutes waiting to say "fix it")+ const left = bad.flatMap((e) => e.issues || []).filter((x) => x.severity !== 'polish').length;+ if (round >= rounds(id).chunkRounds + (left <= 1 ? 1 : 0)) { set({ state: 'failed', open: bad.length }); return false; }set({ state: 'fixing' });const f = await turn(id, 'fix_chunk', { chunk: c, bad, round, message: load(id).userNote }, [`out/check/shots/${c.id}.fixes.json`], { session: key, who: key });if (!f.ok) { set({ state: 'error' }); return false; }@@ -530,8 +543,9 @@ async function production(id: string, { fresh = false } = {}): Promise<boolean>if ((j.needs || []).length) return pause(id);const failed = Object.entries(j.pipeline.chunks || {}).filter(([, v]) => v.state !== 'passed');if (failed.length) { chat(id, 'system', L(id, `有 ${failed.length} 段沒通過鏡頭審查:${failed.map(([k, v]) => `${k}(${v.state})`).join('、')},請你看這幾段決定`, `${failed.length} part${failed.length > 1 ? 's' : ''} didn't pass shot review: ${failed.map(([k, v]) => `${k} (${v.state})`).join(', ')}. Please take a look and decide`)); setStage(id, 'needs_input'); return false; }- // 4) assemble+ // 4) assemble (after the background renders of passed segments, so their frames are reused, not redrawn)pipe(id, (p) => { p.phase = 'assemble'; });+ await (prerenderQ.get(id) || Promise.resolve());return step(id, 'producing', 'assemble', {}, ['out/video.mp4'], 'done');}// ---------- cast gate ----------@@ -615,6 +629,31 @@ async function castSerial(id: string, prev: Pipeline, firstReview?: Review | nulreturn true;}+// ---------- background render of passed segments ----------+// Engines with a frame cache (render.mjs --frames) declare production.json "prerender": { cwd, cmd with {start} {end} }.+// When a segment passes review its final frames are rendered in the background, one segment at a time per project (they+// share out/frames/manifest.json), so assembly only redraws what changed afterwards. A real run spent 29 minutes+// re-rendering all 732 frames at assembly.+const prerenderQ = new Map<string, Promise<void>>(), prerenderProcs = new Map<string, Set<ChildProcess>>();+function prerender(id: string, c: Chunk) {+ const d = dirOf(id), pr = (readJSON<Production>(join(d, 'build', 'production.json')) || {}).prerender as { cwd?: string; cmd?: string } | undefined;+ if (!pr?.cmd) return;+ type S = { id?: string; start_s?: number; end_s?: number };+ const mine = ((readJSON<Plan>(join(d, 'plan.json'))?.shots || []) as S[]).filter((s) => s.id && c.shots.includes(s.id) && s.start_s != null && s.end_s != null);+ if (!mine.length) return;+ const a = Math.min(...mine.map((s) => s.start_s!)), b = Math.max(...mine.map((s) => s.end_s!));+ const [bin, ...args] = pr.cmd.replace('{start}', a.toFixed(3)).replace('{end}', b.toFixed(3)).split(/\s+/);+ const run = () => new Promise<void>((resolve) => {+ if (load(id).stage === 'error') return resolve(); // cancelled or failed meanwhile+ log(id, { type: 'tool', name: 'prerender', detail: `${c.id} ${a.toFixed(2)}–${b.toFixed(2)} s: ${bin} ${args.join(' ')}` });+ const t0 = Date.now(), p = spawn(bin, args, { cwd: join(d, pr.cwd || 'build'), env: process.env, stdio: 'ignore' });+ const set = prerenderProcs.get(id) || new Set(); set.add(p); prerenderProcs.set(id, set);+ const done = (ok: boolean) => { set.delete(p); log(id, { type: ok ? 'text' : 'error', text: `背景渲染 ${c.id}:${ok ? `完成(${Math.round((Date.now() - t0) / 1000)} s)` : '失敗(組裝時會重渲)'}` }); resolve(); };+ p.on('error', () => done(false)); p.on('close', (code) => done(code === 0));+ });+ prerenderQ.set(id, (prerenderQ.get(id) || Promise.resolve()).then(run));+}+// at most CONFIG.maxReviews shot reviews of one project at a time (each grabs frames in Chrome)const reviewQ = new Map<string, { n: number; wait: (() => void)[] }>();async function reviewSlot<T>(id: string, fn: () => Promise<T>): Promise<T> {@@ -644,7 +683,8 @@ async function finalPanel(id: string) {update(id, (j) => { j.critiqueRounds = total; j.lastCritique = { pass: !must.length, must: must.length, at: now() }; });const needs = collectNeeds(id, c.needs_user, 'critic');if (!must.length) { chat(id, 'system', needs ? L(id, '評審:導演能修的都過了,剩下需要你提供的項目', 'Final review: everything the director can fix is done. What is left needs your input') : L(id, `評審通過(第 ${total} 輪)`, `Final review passed (round ${total})`)); setStage(id, needs ? 'needs_input' : 'done'); return; }- if (round > rounds(id).finalRounds) { chat(id, 'system', L(id, `評審仍有 ${must.length} 項必修,已達自動修改上限,請你決定`, `The final review still has ${must.length} must-fix item${must.length > 1 ? 's' : ''} and the automatic fix limit is reached. Please decide`)); setStage(id, 'done'); return; }+ // ≤ 2 items left at the limit: one more revise instead of stopping with them unfixed+ if (round > rounds(id).finalRounds + (must.length <= 2 ? 1 : 0)) { chat(id, 'system', L(id, `評審仍有 ${must.length} 項必修,已達自動修改上限,請你決定`, `The final review still has ${must.length} must-fix item${must.length > 1 ? 's' : ''} and the automatic fix limit is reached. Please decide`)); setStage(id, 'done'); return; }const msg = must.map((m, i) => `${i + 1}. [${m.shot || '全片'}${m.time != null ? ' ' + m.time + 's' : ''}] ${m.issue}${m.fix ? ' → 建議:' + m.fix : ''}`).join('\n');chat(id, 'system', L(id, `評審第 ${total} 輪:${must.length} 項必修,交回導演(每項要附修改前後對照)`, `Final review round ${total}: ${must.length} must-fix item${must.length > 1 ? 's' : ''}, sent back to the director (each fix needs before/after proof)`));if (!(await step(id, 'revising', 'revise', { message: msg, round }, ['out/video.mp4', 'out/check/fixes.json']))) return;@@ -676,5 +716,5 @@ export async function accept(id: string) {if (await production(id)) await finalPanel(id);}-export function cancel(id: string) { for (const ac of running.get(id) || []) ac.abort(); }+export function cancel(id: string) { for (const ac of running.get(id) || []) ac.abort(); for (const p of prerenderProcs.get(id) || []) p.kill(); }export async function critique(id: string) { return finalPanel(id); }diff --git a/app/server/pipeline.test.ts b/app/server/pipeline.test.tsindex 9732ebe..44e2d48 100644--- a/app/server/pipeline.test.ts+++ b/app/server/pipeline.test.ts@@ -21,6 +21,7 @@ interface Scenario {castShared?: (char: string, call: number) => boolean;critique: (round: number) => { must?: number; needs?: number; lostPeak?: boolean };buildDelayMs?: number; // let the per-shot watcher (every 4 s) pick shots up+ prerender?: string; // production.json prerender command}let S: Scenario;let calls: string[] = [];@@ -37,7 +38,7 @@ function outputs(prompt: string, dir: string): [string, Record<string, unknown>]if (m(/## 步驟:整合前製結果/)) return ['plan_frames', { 'plan.json': { title: 'T', version: 2, characters: S.chars.map((id) => ({ id, name: id, file: `build/${id}.js` })) } }];if (m(/## 步驟:依使用者意見修改企劃/)) return ['replan', { 'plan.json': { title: 'T', version: 3 } }];if (m(/## 步驟:製作準備/)) return ['setup', {- 'build/production.json': { chunks: S.chunks, characters: S.chars.map((id) => ({ id, name: id, file: `build/${id}.js`, sheet: `out/check/cast/sheet_${id}.jpg` })) },+ 'build/production.json': { ...(S.prerender ? { prerender: { cwd: '.', cmd: S.prerender } } : {}), chunks: S.chunks, characters: S.chars.map((id) => ({ id, name: id, file: `build/${id}.js`, sheet: `out/check/cast/sheet_${id}.jpg` })) },...(S.chars.length ? { 'out/check/cast/sheet.jpg': 'jpg' } : {}), ...Object.fromEntries(S.chars.map((id) => [`out/check/cast/sheet_${id}.jpg`, 'jpg'])) }]; // no cast → no sheetif (m(/## 步驟:角色關/)) {const round = +(m(/第 (\d+) 輪/)?.[1] || 1), ch = m(/結果寫到 out\/check\/cast\/review_(\S+?)\.json/)?.[1];@@ -172,6 +173,36 @@ describe('production', () => {assert.ok(firstBuild > calls.lastIndexOf('cast_qa:serial'), calls.join(' '));});+ test('one blocker left at the round limit gets one more round instead of pausing', async () => {+ S = base({ shotPass: (s, r) => s !== 'S1' || r >= 4 });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ assert.ok(calls.includes('shot_qa:S1:4'));+ });++ test('two must-fix items left at the final limit get one more revise', async () => {+ S = base({ critique: (r) => ({ must: r <= 3 ? 2 : 0 }) });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(calls.filter((c) => c === 'revise').length, 3);+ assert.equal(J.load(id).lastCritique?.pass, true);+ });++ test('a passed segment is rendered in the background and assembly waits for it', async () => {+ S = base({ prerender: 'node -e setTimeout(()=>{},300)' });+ const id = newProject('plan_review');+ writeFileSync(join(J.dirOf(id), 'plan.json'), JSON.stringify({ title: 'T', version: 1, shots: [{ id: 'S1', start_s: 0, end_s: 2 }, { id: 'S2', start_s: 2, end_s: 4 }] }));+ await J.approve(id);+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ const ev = readFileSync(join(J.dirOf(id), 'logs', 'events.jsonl'), 'utf8').trim().split(/\r?\n/).map((l) => JSON.parse(l));+ const pre = ev.filter((e) => e.name === 'prerender'), doneAt = ev.filter((e) => /背景渲染 C\d:完成/.test(e.text || ''));+ assert.equal(pre.length, 2);+ assert.equal(doneAt.length, 2);+ const assemble = ev.findIndex((e) => e.type === 'turn' && e.phase === 'assemble');+ assert.ok(ev.indexOf(doneAt[1]) < assemble, 'assembly started before the background render finished');+ });+test('shot reviews start while the builder is still working (per-shot watcher)', async () => {S = base({ chunks: [{ id: 'C1', shots: ['S1', 'S2'] }], buildDelayMs: 4600 });const id = newProject('plan_review');diff --git a/app/server/prompts.ts b/app/server/prompts.tsindex cbdaab2..b887cfe 100644--- a/app/server/prompts.ts+++ b/app/server/prompts.ts@@ -13,12 +13,21 @@ const RULES = `規則:使用者在 inputs/ 提供的自家角色可直接照邊界:只改 repo 裡的檔案(不要改使用者的 shell 設定 ~/.bashrc、~/.bash_profile、環境變數或系統設定);只結束你自己開的程序(不要用 pkill/taskkill 加萬用字元比對去殺 Chrome、node 等,別的 agent 和專案也在用)。`;+// The reference as analysed: analyze.py crops a screen recording to proxy.mp4; source.mp4 is then the raw recording+// (a real run compared against black frames). clip_strip.py also switches source → proxy on its own.+const REF = 'analysis/proxy.mp4(沒有 proxy.mp4 才用 analysis/source.mp4;以 report.json 的 "analysed" 為準)';+// The user's own character drawing is the spec. A real run drew Clawd from the engine's built-in model instead, and no+// gate compared against the drawing: proportions drifted shot to shot, accessories sat on top of the head, arms vanished.+const DESIGN = `**使用者給的角色設計圖(inputs/ 裡的圖)就是規格**:輪廓比例(寬:高)、眼睛位置與大小、手腳的數量/位置/粗細、配色都照圖。+ 不要拿引擎內建的同名角色或自己的印象去改;配件(帽子、耳機、墨鏡、髮型)要戴在對的部位(墨鏡在眼睛上、耳機在頭兩側),跟著身體一起轉,不能疊在頭頂蓋掉身體;+ 倒過來、拉長、壓扁、特寫等特殊姿勢也一樣要認得出是同一隻。`;// The point of every video: a moment that gives goosebumps. Shared by the planner, builders, reviewers and the critic.const WOW = `**這支片的目標是驚艷,讓人起雞皮疙瘩**,不是「沒有錯」。驚艷來自高潮設計,不是平均用力:- 高潮 = 鋪陳(張力往上堆)→ 屏息(安靜、停住、收窄)→ 爆發(落在重拍:構圖、色彩、動作、聲音同時翻轉)→ 停住(讓情緒落地 ≥ 1 秒,不要馬上切走)。- 爆發那一下要「看得到」:主體大、清楚、畫面密度和參考片的爆點一樣滿;閃白、光圈、轉場只能當引信,**不准用閃白或轉場蓋掉該被看到的那一刻**(擁抱、揭露、表情)。- 力氣集中在 plan.peaks 的 hero 鏡頭:特製姿勢、誇張變形臉、衝擊格、smear、光芒/粒子、鏡頭震動、色彩翻轉、音效(蓄力、撞擊、爆點前的安靜)——參考片爆點用了什麼,我們至少一樣多。-- 判斷爆點一律用連續影格,不看單張:python ${SKILL}/scripts/clip_strip.py <我們的影片> --range a:b --vs analysis/<source 或 proxy> --vs-range c:d --out …(參考在上、我們在下,逐格對齊)。`;+- 判斷爆點一律用連續影格,不看單張:python ${SKILL}/scripts/clip_strip.py <我們的影片> --range a:b --vs ${REF} --vs-range c:d --out …(參考在上、我們在下,逐格對齊)。+- 驚艷也需要變化:同一個場景+同一個機位不能超過全片的 40%;兩個高潮之間要換場景、換視角或換色彩世界;鋪陳段每 1–1.5 秒畫面要有新的東西(運鏡、構圖、新元素),不能一個構圖停 3 秒等爆點。`;const ENGINE = (p: BaseVars) => `企劃核准後,製作引擎已凍結成快照 ${p.dir}/build/engine/<engine>/(SNAPSHOT.json):製作一律用快照裡的 SKILL.md 與 scripts。工具本體(.claude/skills/)是唯讀的;需要改引擎就複製到 build/ 裡改,並把「坑、修正、建議合回 skill」寫進 out/lessons.md。`;@@ -49,6 +58,7 @@ ${SPEED}`;const EYE = `用人眼逐處檢查(一定要看全解析度的放大截圖,縮圖看不出來):- 角色:每個身體部位都接在一起(頭—脖子—身體、肩—上臂—前臂—手、臀—腿—腳),沒有浮空的手、沒有硬黏在邊緣的手臂、沒有少脖子;關節處沒有接縫線或兩層描邊;比例、配色、髮型、服裝和角色設定圖一致;描線粗細全身一致;表情讀得懂;手拿的東西真的接觸到手。+- 設計圖:使用者有給角色設計圖(plan.characters[].design)就把它和畫面裡的角色並排比:比例、眼睛、手腳、配色、配件位置,走樣是 blocker。- 穿插與遮擋:角色之間、角色和道具不互相穿透;前後關係正確。- 畫面:主體夠大(有情緒、對話、表情戲的鏡頭,主角至少佔畫面高度 35%,看得清臉;只有刻意的遠景建立鏡頭例外)、沒有無用途的大片空白;字不壓主體;字幕要把整張圖縮到手機寬度(約 390px 寬)也讀得出來:字高至少畫面高度 4.5%、有描邊或半透明底;沒有色帶、髒污、破圖、閃格、跳格;轉場每個接縫都有。@@ -78,7 +88,7 @@ ${p.brief}2. 寫 analysis/STYLE.md:第一行寫媒材;把 shot_details 整理成鏡頭清單表;配色與色彩弧線、角色造型語言、剪接、轉場、敘事結構、字幕用法;最後列「這支好看的 3–5 個關鍵」。2b. **找參考片的高潮(起雞皮疙瘩的那 1–2 刻)**:report.json 的 audio.peak_candidates(音樂蓄力後爆發的時間點)與 flashes(閃白格)只是線索;- 對每個候選用 clip_strip.py 抽前 2 秒到後 2 秒的 12fps 連續影格(不加 --vs)存成 analysis/peak_<n>.jpg,打開看,確認真正的爆點。+ 對每個候選用 clip_strip.py 對參考片(${REF})抽前 2 秒到後 2 秒的 12fps 連續影格(不加 --vs)存成 analysis/peak_<n>.jpg,打開看,確認真正的爆點。寫 analysis/peaks.json:[ { "id": "P1", "from": 24.0, "hit": 26.0, "to": 29.0, "strip": "analysis/peak_1.jpg","build": "爆發前怎麼堆張力(畫面、運鏡、音樂)", "hold": "爆發前有沒有停住或安靜、多久", "hit_what": "爆發那一格發生什麼(構圖、色彩、主體大小、畫面密度)","after": "爆發後停多久、怎麼收", "sound": "音樂與音效在做什麼", "techniques": ["白閃引信", "布幕揭開", "群眾填滿畫面", "…"],@@ -108,9 +118,13 @@ ${WOW}"techniques": ["參考用的手法,一個都不少", "+ 我們多加的"], "emotion": "觀眾在這一刻應該感受到什麼", "key_frame": "out/check/key_1.jpg" }爆點要落在音樂的重拍或段落起點(hit_s 對拍)。peaks 裡的鏡頭在 shots 標 "hero": true,它們的 action 要寫到格的層級(預備、爆發、停住)。其他鏡頭的任務是把觀眾帶到高潮:開場 3 秒內要有鉤子,結尾要收回高潮的情緒(呼應)。+ **情緒弧線**:不只能量往上,要有一個小故事(想要什麼 → 遇到阻礙或等待 → 高潮時得到),讓爆點有意義。+ **變化**:在 STORYBOARD.md 列出每鏡的場景與機位,算出同一場景+機位佔片長的比例(≤ 40%),高潮之間換場景或視角。4. 寫 plan.json(CONTRACT.md 格式)與 STORYBOARD.md:logline、look、borrowed_from_reference、角色/產品、每鏡時間、動作、轉場、reads、素材與音效;逐鏡對照:ref_shot、ref_what、camera(engine 規格、pace 跟參考一致)。平均鏡頭長度、字卡比例、暗調比例與參考接近(±30%)。-5. 角色:plan.characters 每個角色寫清楚造型(輪廓、比例、配色、髮型、服裝、特徵)與 id。+5. 角色:plan.characters 每個角色寫清楚造型(輪廓、比例、配色、髮型、服裝、特徵)與 id;使用者有給設計圖的角色寫 "design": "inputs/<圖>",+ 並量出設計圖的比例寫進描述(例如:身體寬:高 = 1.9:1、眼睛在上 1/3、手從身體中段水平伸出、4 隻短腳)。+ ${DESIGN}引擎用 vector_rig 這類「每個角色一個定義檔」的做法時,填 "file": "build/assets/cast/<id>.js",並先在 build/ 建好引擎骨架、把 rig 複製到 build/assets/(角色檔要能在那裡跑)。**不要自己寫角色定義檔**:接下來每個角色會有一個 agent 同時做。6. 素材:plan.assets 每一項寫 purpose、kind、query(搜尋關鍵字)與 status:要從外部取得的標 to_fetch、程式畫的標 drawn_in_code、使用者提供的標 user。@@ -126,7 +140,9 @@ ${WOW}企劃裡的描述:${JSON.stringify(p.character)}1. 讀 plan.json(look、這個角色會出現的鏡頭與動作)、STYLE.md、${SKILL}/assets/vector_rig/README.md(或引擎 SKILL.md 的角色做法)。2. 只寫 ${p.character.file}:造型、配色、比例、本片會用到的表情與姿勢(寫成具名的姿勢,鏡頭之後直接呼叫)。不要改 rig 本體或其他角色的檔。-3. 輸出一張快速檢查圖 out/check/cast/pre_${p.character.id}.jpg(正面、3/4、側面、4 個以上表情、本片最重要的 3 個姿勢),整張打開看一次,+ ${p.character.design ? `**這個角色有使用者的設計圖 ${p.character.design}**:先打開它量比例,照它畫。${DESIGN}+ 比例寫成常數鎖在定義檔裡(所有姿勢、配件都從同一組比例與臉部錨點算),配件綁在臉/頭的錨點上。` : ''}+3. 輸出一張快速檢查圖 out/check/cast/pre_${p.character.id}.jpg(正面、3/4、側面、4 個以上表情、本片最重要的 3 個姿勢${p.character.design ? ';最左邊放使用者的設計圖,同高並排' : ''}),整張打開看一次,明顯的問題(斷肢、浮空、比例錯)當場修掉。**這是前製草稿,不用逐格放大檢查**:核准後的角色關會有獨立審查員做完整的人眼檢查,你之後也會負責修。4. 回報:做了哪些姿勢/表情、還沒做的(製作階段會補)。`,@@ -146,7 +162,7 @@ ${ENGINE(p)}1. 把 assets/fetched.json 合併進 plan.json 的 assets(file、source、license、attribution、status);抓不到的改用替代方案並更新該項。2. 看每個角色的 out/check/cast/pre_*.jpg;明顯不符合企劃或拼接感的地方直接改角色檔(角色 agent 沒做的角色,你自己做)。3. **高潮關鍵畫面(最重要)**:每個 plan.peaks 在 build/ 用真正的角色、素材、光影、特效,把爆發那一格做到**成片品質**存成 key_frame(全解析度),- 再做 out/check/key_<n>_vs_ref.jpg:左邊參考片 hit 那一格(ffmpeg 從 analysis 的 source/proxy 抽)、右邊我們的,同高並排。+ 再做 out/check/key_<n>_vs_ref.jpg:左邊參考片 hit 那一格(ffmpeg 從 ${REF} 抽)、右邊我們的,同高並排。打開並排圖誠實比較:主體大小、畫面密度、光影、色彩衝擊、情緒。**我們的明顯比較弱就繼續改**(加密度、加光、放大主體、改構圖),不要交出比參考片弱的關鍵畫面。在 plan.peaks[].key_frame_note 寫一句自評(哪裡已經贏、哪裡還輸)。使用者核准企劃時會先看這幾張。4. 照 plan.style_frames 其餘項目渲染 2–3 張 out/check/style_*.jpg(用真正的角色與素材),和對應參考鏡頭並排看,到水準才交出。@@ -193,6 +209,7 @@ ${ENGINE(p)}"rig_files": ["build/assets/rig.js"],"chunks": [ { "id": "C1", "shots": ["S1","S2","S3"] }, ... ], ← 依敘事段落把鏡頭分成 ${p.config.builders} 段左右(鏡頭少就少分幾段),每段 1–4 鏡;連續動作、跨鏡接縫多的鏡頭放同一段"shot_files": { "S1": "build/src/scenes/S1.js", ... },+ "prerender": { "cwd": "build", "cmd": "node render.mjs --frames --range={start}:{end} --workers=2" }, ← 有快取的逐格引擎(render.mjs --frames)才寫;系統會在每段通過審查後自動在背景先渲染那段的正式影格,組裝時只剩改過的鏡頭要重渲"how_to_preview": "製作 agent 怎麼渲染自己鏡頭的 stills 與 strip(指令;HyperFrames 專案用 hf_frames.py 包一層,鏡頭內時間換算成全片時間,一次輸出 sheet/strip/裁切)", "how_to_render": "…", "shared_readonly": ["…"] }`,cast_qa: (p) => `${HEADER(p, '角色審查員(獨立,沒參與製作)')}@@ -204,6 +221,8 @@ ${p.character ? `**這一輪你只審角色「${p.character.name || p.character.2. 第 2 輪以後:先讀 out/check/cast/fixes.json,逐項核對上一輪的問題是否真的修好(看修改後的截圖,不是看說明)。${EYE}另外判斷:造型是否符合企劃描述、是否夠有個性且在參考片的風格範圍內、會不會跟知名既有角色撞臉。+ **有使用者設計圖的角色**:把設計圖和設定圖裡每個姿勢並排(PIL 拼成 out/check/cast/qa_<id>_vs_design.jpg)逐格比;+ 比例漂移(變高變窄)、手腳數量或位置不對、配件蓋住身體或戴錯部位,都是 blocker。3. ${QA_OUT('out/check/cast/review.json', '{ "pass": true|false, "issues": [ { "character": "…", "what": "姿勢/表情/部位", "issue": "…", "fix": "…" } ], "verified_fixes": [ { "issue": "…", "fixed": true|false } ], "needs_user": [] }')}會讓觀眾覺得「拼湊、廉價、不一致」的都是 blocker。`,@@ -246,8 +265,10 @@ ${EYE}## 步驟:審查鏡頭 ${(p.shots || p.chunk.shots).join('、')}(屬於段落 ${p.chunk.id},第 ${p.round} 輪)1. 讀 plan.json 這幾鏡的規格(動作、運鏡、ref_shot)、out/check/cast/ 角色設定圖、out/check/shots/ 裡這幾鏡的 <shot>.done.json(或 ${p.chunk.id}.done.json)。同一段的其他鏡頭可能還在製作,只審指定的鏡頭;如果前一鏡已經做好,也檢查「前一鏡最後一格 → 這一鏡第一格」的接縫。-2. 角色關在製作期間可能改過共用角色,所以**先用 hf_frames 重新截這幾鏡的最新畫面**(一次呼叫),以最新畫面為準;再打開每一鏡的 sheet 與角色裁切;不夠清楚就自己再用預覽指令(build/production.json 的 how_to_preview)渲染單格、裁切放大看。- 參考片對應鏡頭在 analysis/(sheet_scenes.jpg;需要時用 ffmpeg 從 analysis/source 或 proxy 抽格)。+2. **先用製作 agent 已經輸出的圖**(<shot>_sheet.jpg、strip、裁切、<shot>_peak_vs_ref.jpg):它們比鏡頭檔新就直接看,不要重截(截圖是最花時間的事)。+ 只有鏡頭檔比那些圖新、圖不夠看、或要放大某一處時,才用預覽指令(build/production.json 的 how_to_preview;HyperFrames 用 hf_frames)補截,一次把要補的時間點全部截完。+ 連續影格一律 12fps(render.mjs --strip 預設就是 12fps),不要用 24fps。+ 參考片對應鏡頭在 analysis/(sheet_scenes.jpg;需要時用 ffmpeg 從 ${REF} 抽格)。3. 第 2 輪以後:先讀 out/check/shots/${p.chunk.id}.fixes.json,逐項用修改後的截圖核對是否真的修好;沒修好的直接列回問題。${EYE}另外:動作與運鏡是否照企劃、和參考鏡頭的手法一致;和角色設定圖比對造型一致性。@@ -287,7 +308,7 @@ ${ENGINE(p)}## 步驟:組裝成片(所有鏡頭段都已通過審查)1. 讀 build/production.json 與各段 out/check/shots/*.fixes.json 裡 "status": "shared" 的項目,先修共用檔的問題。2. 接起全部鏡頭:轉場、配樂、音效、字幕(歌詞字幕只能用 analysis/lyrics/subs.lrc 或 inputs 的 LRC;沒有就不上歌詞字幕)。-3. 正式渲染 out/video.mp4;確認有音軌(ffprobe;沒有就把混音 mux 進去)。跑 python ${SKILL}/scripts/compare.py ${p.dir};檢查每個接縫(前後 0.5 秒 strip)。+3. 正式渲染 out/video.mp4(render.mjs --frames 有快取:通過審查的段落多半已經在背景渲染好,只會重渲改過的鏡頭;不要刪 out/frames);確認有音軌(ffprobe;沒有就把混音 mux 進去)。跑 python ${SKILL}/scripts/compare.py ${p.dir};檢查每個接縫(前後 0.5 秒 strip)。4. 跑 python ${SKILL}/scripts/motion_check.py out/video.mp4 --out out/check/motion:片中黑格、片尾硬切黑、意外的長時間靜止都要修掉再交。5. 每個 plan.peaks 用 clip_strip.py 做 out/check/peak_<n>_vs_ref.jpg(我們的 build_from_s–hit_s+hold_after_s 對參考 peaks.json 的 from–to),打開比;明顯輸參考片就先修。6. 回報:長度、解析度、每鏡一句話、還不完美或暫代的部分。`,@@ -311,13 +332,17 @@ ${WOW}每個動作用 clip_strip.py 抽 12fps 連續影格看(跳格、瞬移、該動不動、僵硬);可疑處抽全解析度放大。跑 python ${SKILL}/scripts/motion_check.py out/video.mp4 --out out/check/critic/motion,打開它產生的每張 strip。4. 跑 compare.py,看 compare_all.jpg;逐鏡打分(CLAUDE.md 要求每鏡 ≥ 4)。-5. 第 2 輪以後:先讀 out/check/fixes.json,**逐項核對上一輪的必修是否真的修好**(看它附的 before/after,再自己在成片同一秒抽格確認;動作類的修正一定要看 12fps 連續影格,不是單張);- 說修好但沒修好的,原樣列回 must_fix 並註明「上一輪已列,仍未修好」。上一輪 nice_to_have 裡觀眾看得出來、改起來不難的項目還在的話,這輪升級成 must_fix。+4b. 角色設計圖(plan.characters[].design):每鏡抽一格角色清楚的畫面,和設計圖拼成一張並排圖逐一比對(比例、眼睛、手腳、配件位置)。+4c. 變化:從 0.5 秒總覽算出同一場景+機位佔片長的比例(> 40% 是 must_fix);高潮前的鋪陳有沒有一個構圖停太久。+5. **第 1 輪就把觀眾看得出來的問題全部列進 must_fix**,不要留到後面的輪次。+ 第 2 輪以後:先讀 out/check/fixes.json,**逐項核對上一輪的必修是否真的修好**(看它附的 before/after,再自己在成片同一秒抽格確認;動作類的修正一定要看 12fps 連續影格,不是單張);+ 說修好但沒修好的,原樣列回 must_fix 並註明「上一輪已列,仍未修好」。**被修改過的鏡頭整鏡用 12fps 重看一次**,修改引進的新問題列 must_fix。+ 第 2 輪以後新的 must_fix 只能是:沒修好的、修改造成的新問題、或真正的 blocker(觀眾一眼看得出來);其他放 nice_to_have,不要每輪加碼。${EYE}6. 寫 out/check/critique.json:{ "pass": false,- "peaks": [ { "id": "P1", "ours": [21.5, 25.5], "ref": [24.0, 29.0], "strip": "out/check/critic/peak_1_vs_ref.jpg", "verdict": "ours_better|equal|ref_better", "why": "具體" } ],- "scores": { "高潮震撼":1-5, "開場鉤子":1-5, "畫面質感":1-5, "角色表演":1-5, "動作流暢":1-5, "運鏡":1-5, "構圖密度":1-5, "瑕疵":1-5, "字幕標題":1-5, "節奏連戲":1-5, "聲音":1-5 },+ "peaks": [ { "id": "P1", "ours": [21.5, 25.5], "ref": [24.0, 29.0], "ref_file": "analysis/proxy.mp4", "strip": "out/check/critic/peak_1_vs_ref.jpg", "verdict": "ours_better|equal|ref_better", "why": "具體" } ],+ "scores": { "高潮震撼":1-5, "開場鉤子":1-5, "畫面質感":1-5, "角色忠實":1-5, "角色表演":1-5, "變化":1-5, "動作流暢":1-5, "運鏡":1-5, "構圖密度":1-5, "瑕疵":1-5, "字幕標題":1-5, "節奏連戲":1-5, "聲音":1-5 },"score_notes": { "高潮震撼": "給這個分數的證據(秒數+看到什麼)", "…": "…" },"shots": [ { "id": "S1", "score": 1-5, "why": "一句話" } ],"must_fix": [ { "shot": "S6", "time": 12.3, "issue": "具體問題", "fix": "具體改法" } ],@@ -342,6 +367,8 @@ ${p.message}- 改完用 hf_frames 截改動處前後 0.5 秒的全解析度畫面,照人眼清單自己看過再交;動作類的修正附 12fps 連續影格(clip_strip.py),不是單張。- 修到高潮(plan.peaks)的,重做 clip_strip.py 對參考的並排圖,確認我們的爆點不輸參考片。- 改完重跑 motion_check.py out/video.mp4 --out out/check/motion,確認沒有新的黑格、硬切黑。+- 重新輸出成片時用引擎的快取(render.mjs --frames 只會重渲改過的鏡頭),不要整片刪掉重渲。+- 動到角色(翻轉、配件、姿勢)時,用 12fps 看整鏡,確認配件跟著身體轉、沒有新問題。${EYE}**每一項都要附證據**,寫 out/check/fixes.json:[ { "issue": "…", "shot": "S6", "time": 12.3, "change": "改了什麼", "before": "out/check/fixes/<n>_before.png", "after": "…_after.png", "status": "fixed|cannot" } ]