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
Quality modes, parallel final fixes, faster frame grabs, safer job files
許元豪ee99319ce0c8
diff --git a/.claude/skills/video-clone/scripts/hf_frames.py b/.claude/skills/video-clone/scripts/hf_frames.pyindex dd6a133..44af3e5 100644--- a/.claude/skills/video-clone/scripts/hf_frames.py+++ b/.claude/skills/video-clone/scripts/hf_frames.py@@ -8,18 +8,28 @@ This tool makes that cheap:* crops are cut from the full-resolution frame with PIL — never a separate --zoom render;* frames are cached by the content of the build folder: asking again for an unchanged moment costs nothing;* at most N snapshot processes run machine-wide (lock files), so parallel agents queue instead of timing out;+ * frames are taken from a silent mirror of the build (<audio> removed): headless Chrome held the page's DOMContentLoaded+ until the music had streamed, ~14 of the ~20 s a one-frame call cost; frames are pixel-identical without it;* automatic retry on the flaky "navigation timeout".Usage (from anywhere):python hf_frames.py <build_dir> --at 12.4,13.0,15.25 --out <dir> → <dir>/t12.400.png …python hf_frames.py <build_dir> --at 12.4 --crop 1100,300,600,500 --tag face --out <dir> → also t12.400_face.pngpython hf_frames.py <build_dir> --range 12.0:14.0:0.1 --out <dir> --sheet strip.jpg → every 0.1 s + a contact sheet+ python hf_frames.py <build_dir> --range 12.0:12.5:f --out <dir> → every frame of the filmPrints one output path per line. Times are global (composition) seconds.++Every time is snapped to the frame the film shows at that moment (frame floor(t·fps), fps from plan.json /+production.json; --exact turns it off). A real run lost a review round to this: a builder checked a pose change at+times a few ms off the 30 fps grid, saw the in-between it had designed, and the film -- which only has the grid frames+-- jumped in one frame. Files keep the requested time in their name."""import argparse, glob, hashlib, json, os, re, shutil, subprocess, sys, tempfile, time+from concurrent.futures import ThreadPoolExecutorfrom PIL import ImageMAX_PARALLEL = int(os.environ.get("HF_SNAPSHOT_SLOTS", "3"))+PER_PROCESS = 12 # below this many frames a second Chrome costs more than it savesLOCK_DIR = os.path.join(tempfile.gettempdir(), "hf_snapshot_slots")CACHE = os.path.join(tempfile.gettempdir(), "hf_frame_cache")@@ -27,7 +37,7 @@ CACHE = os.path.join(tempfile.gettempdir(), "hf_frame_cache")def build_hash(build):h = hashlib.sha1()for root, dirs, files in os.walk(build):- dirs[:] = [d for d in dirs if d not in ("node_modules", "renders", "snapshots", ".git", "out")]+ dirs[:] = [d for d in dirs if d not in SKIP]for f in sorted(files):if f.endswith((".html", ".js", ".css", ".json", ".svg", ".png", ".jpg", ".webp", ".woff", ".woff2", ".ttf", ".otf", ".mp3", ".m4a", ".wav")):p = os.path.join(root, f); st = os.stat(p)@@ -35,25 +45,59 @@ def build_hash(build):return h.hexdigest()[:16]+STATS = {"wait_s": 0.0, "render_s": 0.0, "rendered": 0}++class Slot:def __enter__(self):os.makedirs(LOCK_DIR, exist_ok=True)+ self.t0 = time.time()while True:for i in range(MAX_PARALLEL):p = os.path.join(LOCK_DIR, f"slot{i}")try:if os.path.exists(p) and time.time() - os.path.getmtime(p) > 900: os.remove(p) # stale- self.fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY); self.p = p; return self+ self.fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY); self.p = p+ STATS["wait_s"] += time.time() - self.t0; self.t1 = time.time(); return selfexcept FileExistsError:continuetime.sleep(1.5)def __exit__(self, *a):+ STATS["render_s"] += time.time() - self.t1os.close(self.fd); os.remove(self.p)+AUDIO = re.compile(r"<audio\b[^>]*>(?:\s*</audio>)?", re.I)+SKIP = ("node_modules", "renders", "snapshots", ".git", "out")+++def silent_mirror(build, key):+ """A copy of the build without <audio> elements, made once per build content (files hard-linked when possible)."""+ dst = os.path.join(CACHE, "mirror2", key)+ if os.path.isfile(os.path.join(dst, ".ok")): return dst+ tmp = dst + f".{os.getpid()}"+ shutil.rmtree(tmp, ignore_errors=True)+ for root, dirs, files in os.walk(build):+ dirs[:] = [d for d in dirs if d not in SKIP]+ rel = os.path.relpath(root, build); os.makedirs(os.path.join(tmp, rel), exist_ok=True)+ for f in files:+ src, out = os.path.join(root, f), os.path.join(tmp, rel, f)+ if f.endswith(".html"):+ s = open(src, encoding="utf-8", errors="surrogateescape").read()+ open(out, "w", encoding="utf-8", errors="surrogateescape").write(AUDIO.sub("", s))+ else:+ try: os.link(src, out)+ except OSError: shutil.copy2(src, out)+ open(os.path.join(tmp, ".ok"), "w").close()+ try: os.replace(tmp, dst)+ except OSError: shutil.rmtree(tmp, ignore_errors=True) # another process made it first+ return dst++def snapshot(build, times, outdir):- cmd = ["npx", "[email protected]", "snapshot", ".", "--at", ",".join(f"{t:.3f}" for t in times), "--no-end",+ os.environ.setdefault("PRODUCER_PAGE_NAVIGATION_TIMEOUT_MS", "60000") # 10 s default fails under load with many agents+ cmd = ["npx", "[email protected]", "snapshot", ".", "--at", ",".join(f"{t:.6f}" for t in times), "--no-end","-o", outdir, "--describe", "false", "--timeout", "30000"]for attempt in range(3):if os.path.isdir(outdir): shutil.rmtree(outdir)@@ -66,16 +110,69 @@ def snapshot(build, times, outdir):time.sleep(2 + attempt * 3)+def film_fps(build):+ for f in (os.path.join(os.path.dirname(build), "plan.json"), os.path.join(build, "production.json")):+ try:+ d = json.load(open(f, encoding="utf-8-sig")); v = (d.get("format") or {}).get("fps") or d.get("fps")+ if v: return float(v)+ except (OSError, ValueError, AttributeError): pass+ return None+++def frame_time(t, fps):+ """Start of the frame shown at time t (+10 µs so the seek never lands just before it). Times are written with 3+ decimals (19.733 for frame 592 = 19.7333 s at 30 fps), so up to 1.5 ms before a frame counts as that frame."""+ return round(int(t * fps + 0.0015 * fps) / fps + 1e-5, 6)+++CACHE_MAX_GB = float(os.environ.get("HF_CACHE_GB", "4"))+++def prune_cache(keep):+ """Every build edit makes a new cache folder; without a cap it filled the system drive (24 GB in one day, and a+ project's job.json was truncated when the disk ran out). Oldest folders go first; the current one stays."""+ try:+ dirs = [os.path.join(r, d) for r in (CACHE, os.path.join(CACHE, "mirror2")) if os.path.isdir(r) for d in os.listdir(r) if d != "mirror2"]+ dirs = [d for d in dirs if os.path.isdir(d) and os.path.basename(d) != keep]+ size = lambda d: sum(os.path.getsize(os.path.join(r, f)) for r, _, fs in os.walk(d) for f in fs)+ sizes = {d: size(d) for d in dirs}+ total = sum(sizes.values())+ for d in sorted(dirs, key=os.path.getmtime):+ if total <= CACHE_MAX_GB * 1e9: break+ shutil.rmtree(d, ignore_errors=True); total -= sizes[d]+ except OSError:+ pass++def grab(build, times):"""Full-resolution PNG path for every time, rendering only the ones not cached for this exact build content."""- key = build_hash(build); cdir = os.path.join(CACHE, key); os.makedirs(cdir, exist_ok=True)- want = {t: os.path.join(cdir, f"t{t:.3f}.png") for t in times}+ key = build_hash(build)+ prune_cache(key); cdir = os.path.join(CACHE, key); os.makedirs(cdir, exist_ok=True)+ want = {t: os.path.join(cdir, f"t{t:.6f}.png") for t in times}todo = sorted({t for t, p in want.items() if not os.path.exists(p)})- for i in range(0, len(todo), 60): # one Chrome for up to 60 frames- chunk = todo[i:i + 60]+ src = build+ if todo:+ try: src = silent_mirror(build, key)+ except OSError: src = build+ # Big requests are split over several Chrome processes (each takes its own slot): a frame costs ~1 s of seek and+ # screenshot, 36 frames took 36 s in one process and 17.5 s in three. Frames differ by at most 2/255 (GPU rounding).+ parts = max(1, min(MAX_PARALLEL, len(todo) // PER_PROCESS, 60), -(-len(todo) // 60))+ size = -(-len(todo) // parts) if todo else 0+ chunks = [todo[i:i + size] for i in range(0, len(todo), size)] if todo else []++ def run(chunk):tmp = tempfile.mkdtemp(prefix="hf_snap_")- for t, fr in zip(chunk, snapshot(build, chunk, tmp)): shutil.move(fr, want[t])- shutil.rmtree(tmp, ignore_errors=True)+ try:+ for t, fr in zip(chunk, snapshot(src, chunk, tmp)): shutil.move(fr, want[t])+ finally:+ shutil.rmtree(tmp, ignore_errors=True)+ STATS["rendered"] += len(chunk)++ if len(chunks) > 1:+ with ThreadPoolExecutor(len(chunks)) as ex:+ for f in [ex.submit(run, c) for c in chunks]: f.result()+ elif chunks:+ run(chunks[0])return [want[t] for t in times]@@ -85,16 +182,25 @@ def main():ap.add_argument("--crop", action="append", default=[], help="x,y,w,h (repeatable; applied to every time)")ap.add_argument("--tag", action="append", default=[]); ap.add_argument("--out", required=True)ap.add_argument("--sheet", help="also write a contact sheet with this file name"); ap.add_argument("--cols", type=int, default=4)- ap.add_argument("--prefix", default="t")+ ap.add_argument("--prefix", default="t"); ap.add_argument("--exact", action="store_true", help="seek the exact times, not the film's frames")a = ap.parse_args()build = os.path.abspath(a.build)+ fps = None if a.exact else film_fps(build)times = [float(x) for x in a.at.split(",")] if a.at else []if a.range:- s, e, st = (float(x) for x in a.range.split(":")); n = int(round((e - s) / st)) + 1- times += [round(s + i * st, 3) for i in range(n)]+ s, e, st = a.range.split(":"); s, e = float(s), float(e)+ if st == "f":+ if not fps: sys.exit("--range a:b:f needs the film's fps (plan.json or production.json)")+ times += [round(i / fps, 3) for i in range(int(s * fps + 1e-6), int(e * fps + 1e-6) + 1)]+ else:+ n = int(round((e - s) / float(st))) + 1+ times += [round(s + i * float(st), 3) for i in range(n)]if not times: sys.exit("give --at or --range")os.makedirs(a.out, exist_ok=True)- t0 = time.time(); paths = grab(build, times); outs = []+ seek = [frame_time(t, fps) for t in times] if fps else times+ if fps and len(set(seek)) < len(seek):+ print(f"# {len(seek) - len(set(seek))} of the requested times fall on a frame already asked for (the film has {fps:g} frames/s)", file=sys.stderr)+ t0 = time.time(); paths = grab(build, seek); outs = []for t, p in zip(times, paths):dst = os.path.join(a.out, f"{a.prefix}{t:.3f}.png"); shutil.copy(p, dst); outs.append(dst); print(dst)for k, c in enumerate(a.crop):@@ -107,6 +213,18 @@ def main():for i, im in enumerate(ims): sheet.paste(im.convert("RGB").resize((w, h)), ((i % cols) * w, (i // cols) * h))sp = os.path.join(a.out, a.sheet); sheet.save(sp, quality=88); print(sp)print(f"# {len(times)} frames in {time.time() - t0:.1f}s", file=sys.stderr)+ log_call(build, len(times), time.time() - t0)+++def log_call(build, n, total):+ """One line per call in <project>/logs/hf_frames.jsonl: where the time of a frame request goes (queue vs Chrome)."""+ logs = os.path.join(os.path.dirname(build), "logs")+ if not os.path.isdir(logs): return+ rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "frames": n, "rendered": STATS["rendered"], "total_s": round(total, 1),+ "wait_s": round(STATS["wait_s"], 1), "render_s": round(STATS["render_s"], 1), "slots": MAX_PARALLEL}+ try:+ with open(os.path.join(logs, "hf_frames.jsonl"), "a", encoding="utf-8") as f: f.write(json.dumps(rec) + "\n")+ except OSError: passif __name__ == "__main__":diff --git a/.claude/skills/video-clone/scripts/tests/test_hf_frames.py b/.claude/skills/video-clone/scripts/tests/test_hf_frames.pynew file mode 100644index 0000000..ba8d032--- /dev/null+++ b/.claude/skills/video-clone/scripts/tests/test_hf_frames.py@@ -0,0 +1,40 @@+"""hf_frames takes frames from a silent mirror of the build: same files, no <audio> elements."""+import os+from pathlib import Path++import hf_frames+++def test_silent_mirror_drops_audio_only(tmp_path, monkeypatch):+ build = tmp_path / "build"+ (build / "compositions").mkdir(parents=True)+ (build / "assets").mkdir()+ (build / "node_modules").mkdir()+ (build / "index.html").write_text(+ '<div id="root"><div id="S1"></div>\n <audio id="music" src="assets/mix.m4a" data-start="0"></audio>\n'+ '<AUDIO src="b.mp3">\n<audiogram-note></div>', encoding="utf-8")+ (build / "compositions" / "S1.html").write_text('<template><audio src="sfx.wav"></audio><video src="v.mp4"></video></template>', encoding="utf-8")+ (build / "assets" / "kit.js").write_text("window.kit = 1;", encoding="utf-8")+ (build / "node_modules" / "big.js").write_text("x", encoding="utf-8")+ monkeypatch.setattr(hf_frames, "CACHE", str(tmp_path / "cache"))++ m = hf_frames.silent_mirror(str(build), "k1")+ index = (Path(m) / "index.html").read_text(encoding="utf-8")+ assert "<audio" not in index.lower().replace("<audiogram", "")+ assert '<div id="S1">' in index and "<audiogram-note>" in index # only audio elements go+ s1 = (Path(m) / "compositions" / "S1.html").read_text(encoding="utf-8")+ assert "<audio" not in s1 and '<video src="v.mp4">' in s1 # video frames are pictures: kept+ assert (Path(m) / "assets" / "kit.js").read_text(encoding="utf-8") == "window.kit = 1;"+ assert not os.path.exists(os.path.join(m, "node_modules"))+ assert hf_frames.silent_mirror(str(build), "k1") == m # made once per build content+++def test_times_snap_to_the_frame_the_film_shows(tmp_path):+ ft = hf_frames.frame_time+ assert abs(ft(19.75, 30) - 592 / 30) < 1e-4 # between frames → the frame on screen at that moment+ assert ft(19.733, 30) == ft(19.75, 30) # a 3-decimal frame time is that frame, not the one before+ assert ft(19.767, 30) > ft(19.75, 30)+ assert ft(19.733, 30) >= 592 / 30 # never seeks just before the frame starts+ (tmp_path / "build").mkdir()+ (tmp_path / "plan.json").write_text('{"format": {"fps": 24}}', encoding="utf-8")+ assert hf_frames.film_fps(str(tmp_path / "build")) == 24diff --git a/.claude/skills/video-clone/scripts/timeline.py b/.claude/skills/video-clone/scripts/timeline.pyindex 606097d..ed27125 100644--- a/.claude/skills/video-clone/scripts/timeline.py+++ b/.claude/skills/video-clone/scripts/timeline.py@@ -35,10 +35,12 @@ if tA: print(f" approved → last event: {mins(tA, last):.0f} min")# phases after approvalby_phase = collections.defaultdict(lambda: [None, None])+first_final = min((ts(t['start']) for t in turns if t['phase'] in ('assemble', 'critique')), default=None)for t in turns:if tA and ts(t['start']) < tA: continueph = {'setup': 'setup', 'cast_qa': 'cast', 'cast_fix': 'cast', 'build_chunk': 'shots', 'shot_qa': 'shots', 'fix_chunk': 'shots','assemble': 'assemble', 'critique': 'final', 'revise': 'final'}.get(t['phase'], t['phase'])+ if ph == 'shots' and first_final and ts(t['start']) >= first_final: ph = 'final' # builders fixing final-review itemss, e = ts(t['start']), ts(t['end']) if t['end'] else lastb = by_phase[ph]; b[0] = s if b[0] is None or s < b[0] else b[0]; b[1] = e if b[1] is None or e > b[1] else b[1]print('\nwall-clock per production phase (min):')diff --git a/app/README.md b/app/README.mdindex f186784..3fcff9c 100644--- a/app/README.md+++ b/app/README.md@@ -3,7 +3,8 @@Install and start it as described in the root [README](../README.md); how it works is in [docs/ARCHITECTURE.md](../docs/ARCHITECTURE.md).```-server/ index.ts (HTTP/SSE) · jobs.ts (workflow and production line) · prompts.ts (agent instructions) · agents/ (Claude Code / Codex adapters) · env.ts (keys)+server/ index.ts (HTTP/SSE) · jobs.ts (workflow and production line) · outputs.ts (agent output checks) · prompts.ts (agent instructions)+ · agents/ (Claude Code / Codex adapters) · env.ts (keys)web/ React UI: App.tsx (home) · Project.tsx (project page) · Chat.tsx (chat and live agent steps) · ui.tsx (components) · i18n.ts (languages) · styles.cssshared/ types.ts (job.json, the project snapshot and live events: the contract between server and web)scripts/ doctor.mjs (environment check; plain JS so it can run on any Node and say what to upgrade)diff --git a/app/server/index.ts b/app/server/index.tsindex 10d768b..9da990b 100644--- a/app/server/index.ts+++ b/app/server/index.ts@@ -40,8 +40,9 @@ app.post('/api/projects', upload.fields([{ name: 'reference', maxCount: 1 }, { nlet settings;try { settings = Object.fromEntries(Object.entries(J.cleanRounds(req.body)).filter(([, v]) => v != null)); }catch (e) { for (const f of Object.values(files || {}).flat()) try { unlinkSync(f.path); } catch {} return res.status(400).json({ error: (e as Error).message }); }+ const quality = ['fast', 'standard', 'fine'].includes(req.body.quality) ? req.body.quality : 'standard';const id = slug();- const job = J.createJob({ id, title: (title || brief.split('\n')[0] || '未命名').slice(0, 40), agent, brief, lang, settings,+ const job = J.createJob({ id, title: (title || brief.split('\n')[0] || '未命名').slice(0, 40), agent, brief, lang, settings, quality,reference: ref ? { type: 'file', src: 'inputs/reference' + (extname(ref.originalname) || '.mp4') } : { type: 'url', src: url.trim() } });if (ref) renameSync(ref.path, join(J.dirOf(id), job.reference.src));for (const f of files?.inputs || []) renameSync(f.path, join(J.dirOf(id), 'inputs', fileName(f)));@@ -99,6 +100,12 @@ app.post('/api/projects/:id/settings', (req, res) => {if (!guard(res, req.params.id)) return;try { res.json(J.setRounds(req.params.id, req.body || {})); } catch (e) { res.status(400).json({ error: (e as Error).message }); }});+// Quality mode (fast / standard / fine). Upgrading a finished film starts a new final review under the stricter bar.+app.post('/api/projects/:id/quality', (req, res) => {+ const { id } = req.params; if (!guard(res, id)) return;+ try { if (J.setQuality(id, req.body?.quality).upgrade) J.critique(id).catch((e) => console.error(e)); res.json(J.snapshot(id)); }+ catch (e) { res.status(400).json({ error: (e as Error).message }); }+});app.get('/api/config', (req, res) => res.json(J.CONFIG));app.post('/api/projects/:id/retry', act(J.retry));app.post('/api/projects/:id/critique', act(J.critique));diff --git a/app/server/jobs.test.ts b/app/server/jobs.test.tsindex 484f89f..5f0d4c7 100644--- a/app/server/jobs.test.ts+++ b/app/server/jobs.test.ts@@ -30,9 +30,24 @@ describe('cleanRounds', () => {});describe('project settings', () => {- test('a new project uses the server defaults', () => {+ test('a new project is standard quality and uses that preset', () => {const { id } = newJob();- assert.deepEqual(J.rounds(id), { castRounds: J.CONFIG.castRounds, chunkRounds: J.CONFIG.chunkRounds, finalRounds: J.CONFIG.finalRounds });+ const P = J.CONFIG.presets.standard;+ assert.equal(J.snapshot(id).quality, 'standard');+ assert.deepEqual(J.rounds(id), { castRounds: P.castRounds, chunkRounds: P.chunkRounds, finalRounds: P.finalRounds });+ });+ test('a project made before quality modes runs the fine line', () => {+ const { id } = newJob();+ const j = J.load(id); delete j.quality; writeFileSync(join(J.dirOf(id), 'job.json'), JSON.stringify(j));+ assert.equal(J.snapshot(id).quality, 'fine');+ assert.equal(J.rounds(id).chunkRounds, J.CONFIG.chunkRounds);+ });+ test('changing the quality changes the defaults; the own settings still win', () => {+ const { id } = newJob({ settings: { finalRounds: 4 } });+ J.setQuality(id, 'fast');+ assert.equal(J.rounds(id).chunkRounds, J.CONFIG.presets.fast.chunkRounds);+ assert.equal(J.rounds(id).finalRounds, 4);+ assert.throws(() => J.setQuality(id, 'ultra'), /quality must be/);});test('setRounds overrides one limit, and null resets it', () => {const { id } = newJob({ settings: { finalRounds: 4 } });@@ -41,8 +56,8 @@ describe('project settings', () => {assert.equal(J.rounds(id).castRounds, 7);assert.equal(J.rounds(id).finalRounds, 4);const snap = J.setRounds(id, { finalRounds: '' });- assert.equal(snap.rounds.values.finalRounds, J.CONFIG.finalRounds);- assert.equal(snap.rounds.defaults.castRounds, J.CONFIG.castRounds);+ assert.equal(snap.rounds.values.finalRounds, J.CONFIG.presets.standard.finalRounds);+ assert.equal(snap.rounds.defaults.castRounds, J.CONFIG.presets.standard.castRounds);});});diff --git a/app/server/jobs.ts b/app/server/jobs.tsindex efcff88..7a4814c 100644--- a/app/server/jobs.ts+++ b/app/server/jobs.ts@@ -8,14 +8,15 @@// → 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, statfsSync, cpSync } from 'node:fs';+import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync, statfsSync, cpSync, renameSync, rmSync } from 'node:fs';import { join, relative, resolve } from 'node:path';import { spawn, type ChildProcess } from 'node:child_process';import { EventEmitter } from 'node:events';import { runAgent, type AgentResult } from './agents/index.ts';+import { checkOutputs, parseJSON, repairPrompt } from './outputs.ts';import { prompts as bootPrompts } from './prompts.ts';-import { ROUND_KEYS } from '../shared/types.ts';-import type { AgentKind, CastCharProgress, ChatMessage, ChunkProgress, Config, EngineSnapshot, Job, Lang, LogEntry, LogEvent, Need, NeedRequest, Pipeline, Plan, ProjectSummary, Reference, RequiredInput, Review, RoundKey, Rounds, Snapshot, Stage } from '../shared/types.ts';+import { QUALITIES, ROUND_KEYS } from '../shared/types.ts';+import type { AgentKind, CastCharProgress, ChatMessage, ChunkProgress, Config, EngineSnapshot, Job, Lang, LogEntry, LogEvent, Need, NeedRequest, Pipeline, Plan, ProjectSummary, Quality, QualityPreset, Reference, RequiredInput, Review, RoundKey, Rounds, Snapshot, Stage } from '../shared/types.ts';import type { CastMember, Chunk, ChunkReview, Critique, Phase, Production, Prompts, SharedItem, ShotEntry, StepVars } from './types.ts';export { ROUND_KEYS };// prompts.ts is re-imported when it changes, so prompt fixes reach the next agent turn without restarting running jobs@@ -35,11 +36,21 @@ const noPython = (e: Error) => `${PY} could not be started (${e.message}). Instaconst passed = (rv: Review) => { const L = rv.issues || []; return L.length && L.every((x) => x.severity) ? !L.some((x) => x.severity !== 'polish') : !!rv.pass; };const shotPassed = (s: ShotEntry) => { const L = s.issues || []; return L.length && L.every((x) => x.severity) ? !L.some((x) => x.severity !== 'polish') : !!s.pass; };-export const CONFIG: Config = {- builders: +(process.env.BUILDERS || 6), // parallel shot builders per project (12 cores / 32 GB measured)+const FINE: Rounds = {castRounds: +(process.env.CAST_ROUNDS || 3), // cast gate: review/fix rounds before asking the userchunkRounds: +(process.env.CHUNK_ROUNDS || 3), // shot line: review/fix rounds per chunkfinalRounds: +(process.env.FINAL_ROUNDS || 2), // final panel: automatic revise rounds+};+export const CONFIG: Config = {+ ...FINE, // the 'fine' line (projects made before modes existed)+ // Quality modes (shared/types.ts). The prompts change with the mode too: what blocks, and where every frame is checked.+ presets: {+ // a round is one review: 2 = review, fix, review again+ fast: { castRounds: 2, chunkRounds: 2, finalRounds: 1, converge: 0, pauseAtLimit: false },+ standard: { castRounds: 2, chunkRounds: 3, finalRounds: 2, converge: 1, pauseAtLimit: true },+ fine: { ...FINE, converge: 3, pauseAtLimit: true },+ },+ builders: +(process.env.BUILDERS || 6), // parallel shot builders per project (12 cores / 32 GB measured)maxAgentsGlobal: +(process.env.MAX_AGENTS || 12), // all projects together (CLI rate limits, CPU/GPU for renders)maxReviews: +(process.env.MAX_REVIEWS || 4), // shot reviews at once per project: each one opens Chrome to grab frames;// 13 at once meant 80–200 Chrome processes and screenshot timeouts@@ -51,7 +62,10 @@ export const CONFIG: Config = {// Review/fix round limits: CONFIG holds the defaults; a project can set its own (job.settings), read at every check so a// change applies from the next round on. When a limit is reached the job pauses for the user instead of looping.export const ROUND_RANGE = { min: 1, max: 10 };-export function rounds(id: string): Rounds { const s = load(id).settings || {}; return Object.fromEntries(ROUND_KEYS.map((k) => [k, s[k] ?? CONFIG[k]])) as Rounds; }+export const qualityOf = (j: Job): Quality => (QUALITIES.includes(j.quality as Quality) ? j.quality! : 'fine');+export const preset = (id: string): QualityPreset => CONFIG.presets[qualityOf(load(id))];+const presetRounds = (q: Quality) => Object.fromEntries(ROUND_KEYS.map((k) => [k, CONFIG.presets[q][k]])) as Rounds;+export function rounds(id: string): Rounds { const j = load(id), s = j.settings || {}, p = CONFIG.presets[qualityOf(j)]; return Object.fromEntries(ROUND_KEYS.map((k) => [k, s[k] ?? p[k]])) as Rounds; }// Validates { castRounds?, chunkRounds?, finalRounds? } (whole numbers 1–10; '' / null = back to the default). Throws on bad input.export function cleanRounds(input: Record<string, unknown> = {}) {const out: Partial<Record<RoundKey, number | null>> = {};@@ -71,6 +85,23 @@ export function setRounds(id: string, input: Record<string, unknown>) {return snapshot(id);}+// Change the quality mode. Mid-production it applies from the next check (rounds and prompts read it every turn).+// A finished film moved to a stricter mode goes back to the final review under the new bar, fixing from this film.+const RANK: Record<Quality, number> = { fast: 0, standard: 1, fine: 2 };+export const QUALITY_NAME: Record<Quality, [string, string]> = { fast: ['快速', 'Fast'], standard: ['標準', 'Standard'], fine: ['精緻', 'Fine'] };+export function setQuality(id: string, q: unknown): { upgrade: boolean } {+ if (!QUALITIES.includes(q as Quality)) throw new Error(`quality must be one of ${QUALITIES.join(', ')}`);+ const j = load(id), from = qualityOf(j), to = q as Quality;+ if (from === to) return { upgrade: false };+ const upgrade = RANK[to] > RANK[from] && j.stage === 'done' && !busy(id) && existsSync(join(dirOf(id), 'out', 'video.mp4'));+ const [zh, en] = QUALITY_NAME[to];+ update(id, (x) => { x.quality = to; });+ chat(id, 'system', upgrade+ ? L(id, `品質升級為「${zh}」:用新的標準重新評審,從這支片接著修。`, `Quality upgraded to ${en}: the film goes back to the final review under the new bar and is fixed from here.`)+ : L(id, `品質改為「${zh}」,從下一次檢查開始生效。`, `Quality set to ${en}; it applies from the next check.`));+ return { upgrade };+}+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>>();@@ -83,7 +114,15 @@ const jpath = (id: string) => join(dirOf(id), 'job.json');// System messages in the project's language (Simplified Chinese is converted from the Chinese text by the UI).const L = (id: string, zh: string, en: string) => (load(id).lang === 'en' ? en : zh);export function load(id: string): Job { return JSON.parse(readFileSync(jpath(id), 'utf8')); }-function save(job: Job) { job.updatedAt = now(); writeFileSync(jpath(job.id), JSON.stringify(job, null, 1)); bus.emit('job', job.id, { type: 'job', job }); return job; }+// Atomic: write a temp file, then rename over job.json. A full disk once truncated job.json to 0 bytes mid-write and the+// project could no longer be opened; now a failed write leaves the previous job.json intact.+function save(job: Job) {+ job.updatedAt = now();+ const f = jpath(job.id), tmp = `${f}.${process.pid}.tmp`;+ try { writeFileSync(tmp, JSON.stringify(job, null, 1)); renameSync(tmp, f); }+ catch (e) { try { rmSync(tmp, { force: true }); } catch {} throw e; }+ bus.emit('job', job.id, { type: 'job', job }); return job;+}function update(id: string, fn: (j: Job) => void) { const j = load(id); fn(j); return save(j); }function log(id: string, ev: LogEntry) {const e = { ts: now(), ...ev }; bus.emit('job', id, { type: 'log', ev: e });@@ -93,11 +132,19 @@ function log(id: string, ev: LogEntry) {}// On startup nothing is running, so a job still marked as working was cut off by a restart: say so instead of pretending.+// Projects whose job.json can be read; a broken one (e.g. truncated by a full disk before writes were atomic) is+// reported and skipped instead of stopping the server from starting.+function readableJobs(): string[] {+ return (existsSync(PROJECTS) ? readdirSync(PROJECTS) : []).filter((d) => {+ if (!existsSync(jpath(d))) return false;+ try { load(d); return true; } catch (e) { console.error(`skipping project ${d}: job.json unreadable (${(e as Error).message})`); return false; }+ });+}+export function recoverOrphans(): string[] {const cut: string[] = [];const WORK = ['analyzing', 'styling', 'planning', 'replanning', 'producing', 'revising', 'critiquing'];- for (const d of existsSync(PROJECTS) ? readdirSync(PROJECTS) : []) {- if (!existsSync(jpath(d))) continue;+ for (const d of readableJobs()) {const j = load(d);if (!WORK.includes(j.stage)) continue;cut.push(d);@@ -114,7 +161,7 @@ export function autoResume(ids: string[], gapMs = 5000) {retry(id).catch((e) => console.error('auto-resume', id, e));}, (i + 1) * gapMs));}-const readJSON = <T>(p: string): T | null => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };+const readJSON = <T>(p: string): T | null => { try { return parseJSON(readFileSync(p, 'utf8')) as T; } catch { return null; } };const readText = (p: string): string | null => { try { return readFileSync(p, 'utf8'); } catch { return null; } };const oneOf = (v: string | null | undefined, ...L: string[]) => !!v && L.includes(v);const mtime = (p: string) => (existsSync(p) ? statSync(p).mtimeMs : 0);@@ -133,7 +180,7 @@ function release() { active--; const w = waiters.shift(); if (w) w.r(); }export function listJobs(): ProjectSummary[] {if (!existsSync(PROJECTS)) return [];- return readdirSync(PROJECTS).filter((d) => existsSync(jpath(d))).map((d) => { const j = load(d); return { id: j.id, title: readJSON<Plan>(join(dirOf(d), 'plan.json'))?.title || j.title, stage: j.stage, agent: j.agent, updatedAt: j.updatedAt, needs: (j.needs || []).length, thumb: existsSync(join(dirOf(d), 'out', 'check', 'style_1.jpg')) ? 'out/check/style_1.jpg' : existsSync(join(dirOf(d), 'analysis', 'sheet_1fps.jpg')) ? 'analysis/sheet_1fps.jpg' : null }; })+ return readableJobs().map((d) => { const j = load(d); return { id: j.id, title: readJSON<Plan>(join(dirOf(d), 'plan.json'))?.title || j.title, stage: j.stage, agent: j.agent, updatedAt: j.updatedAt, needs: (j.needs || []).length, thumb: existsSync(join(dirOf(d), 'out', 'check', 'style_1.jpg')) ? 'out/check/style_1.jpg' : existsSync(join(dirOf(d), 'analysis', 'sheet_1fps.jpg')) ? 'analysis/sheet_1fps.jpg' : null }; }).sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));}@@ -148,20 +195,22 @@ export function snapshot(id: string): Snapshot {plan, storyboard: readText(join(d, 'STORYBOARD.md')), assetsMd: readText(join(d, 'assets', 'ASSETS.md')),checks: list('out/check', /\.(jpg|png)$/i).slice(0, 24), video: existsSync(join(d, 'out', 'video.mp4')) ? 'out/video.mp4' : null,critique: readJSON(join(d, 'out', 'check', 'critique.json')),+ styleDistance: readJSON(join(d, 'out', 'check', 'style_distance.json')),cast: { sheets: list('out/check/cast', /sheet[^/]*\.(jpg|png)$/i).slice(0, 8), review: readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) },shots: list('out/check/shots', /_sheet\.(jpg|png)$/i).slice(0, 60),production: readJSON(join(d, 'build', 'production.json')),lyrics: readJSON(join(d, 'analysis', 'lyrics', 'subs.json')),requiredInputs: requiredInputs(id, plan, job),- rounds: { values: rounds(id), defaults: Object.fromEntries(ROUND_KEYS.map((k) => [k, CONFIG[k]])) as Rounds, ...ROUND_RANGE },+ rounds: { values: rounds(id), defaults: presetRounds(qualityOf(job)), ...ROUND_RANGE },+ quality: qualityOf(job),inputs: list('inputs', /./),};}-export function createJob({ id, title, agent, brief, reference, lang = 'zh-TW', settings = {} }: { id: string; title: string; agent: AgentKind; brief: string; reference: Reference; lang?: Lang; settings?: Partial<Rounds> }) {+export function createJob({ id, title, agent, brief, reference, lang = 'zh-TW', settings = {}, quality = 'standard' }: { id: string; title: string; agent: AgentKind; brief: string; reference: Reference; lang?: Lang; settings?: Partial<Rounds>; quality?: Quality }) {const d = dirOf(id); mkdirSync(join(d, 'inputs'), { recursive: true }); mkdirSync(join(d, 'analysis'), { recursive: true });writeFileSync(join(d, 'brief.md'), brief || '');- const job: Job = { id, title, agent, lang, reference, settings, stage: 'new', sessionId: null, sessions: {}, createdAt: now(), chat: [], log: [], needs: [], waived: [], pipeline: {} };+ const job: Job = { id, title, agent, lang, reference, settings, quality, stage: 'new', sessionId: null, sessions: {}, createdAt: now(), chat: [], log: [], needs: [], waived: [], pipeline: {} };save(job);return job;}@@ -272,19 +321,28 @@ interface TurnResult { ok: boolean; text?: string; missing?: string[]; stderr?:async function turn<P extends Phase>(id: string, phase: P, vars: StepVars[P], must: string[], { session = 'director', who }: TurnOpts = {}): Promise<TurnResult> {const j = load(id), d = dirOf(id);const ac = new AbortController(); if (!running.has(id)) running.set(id, new Set()); running.get(id)!.add(ac);- const p = { dir: relative(ROOT, d).replace(/\\/g, '/'), brief: readText(join(d, 'brief.md')) || '', inputs: snapshot(id).inputs, config: CONFIG, lang: j.lang || 'zh-TW', ...vars };+ const p = { dir: relative(ROOT, d).replace(/\\/g, '/'), brief: readText(join(d, 'brief.md')) || '', inputs: snapshot(id).inputs, config: CONFIG, lang: j.lang || 'zh-TW', quality: qualityOf(j), ...vars };const before = must.map((f) => mtime(join(d, f)));const sid = session === 'fresh' ? undefined : session === 'director' ? j.sessionId : (j.sessions || {})[session];const label = who || (session === 'fresh' ? 'reviewer' : session);await slot(phase);log(id, { type: 'turn', state: 'start', phase, who: label });let r: AgentResult;+ let broken: { file: string; problem: string }[];+ const onEvent = (e: Parameters<NonNullable<Parameters<typeof runAgent>[0]['onEvent']>>[0]) => {+ if (e.type === 'session' && session !== 'fresh') update(id, (jj) => { if (session === 'director') jj.sessionId = e.id; else { jj.sessions = jj.sessions || {}; jj.sessions[session] = e.id; } });+ if (e.type !== 'done') log(id, { ...e, who: label });+ };try {- r = await runAgent({ kind: j.agent, cwd: ROOT, prompt: (await livePrompts())[phase](p), sessionId: sid, signal: ac.signal,- onEvent: (e) => {- if (e.type === 'session' && session !== 'fresh') update(id, (jj) => { if (session === 'director') jj.sessionId = e.id; else { jj.sessions = jj.sessions || {}; jj.sessions[session] = e.id; } });- if (e.type !== 'done') log(id, { ...e, who: label });- } });+ r = await runAgent({ kind: j.agent, cwd: ROOT, prompt: (await livePrompts())[phase](p), sessionId: sid, signal: ac.signal, onEvent });+ // the files it wrote must be readable: one repair turn in the same conversation (it knows what it meant), still in this slot+ broken = r.ok && !ac.signal.aborted ? checkOutputs(d, must) : [];+ if (broken.length) {+ log(id, { type: 'error', text: `輸出檔讀不懂,請同一個 agent 修正:${broken.map((b) => `${b.file}(${b.problem})`).join(';')}`, who: label });+ const fix = await runAgent({ kind: j.agent, cwd: ROOT, prompt: repairPrompt(p.dir, broken), sessionId: r.sessionId ?? sid, signal: ac.signal, onEvent });+ broken = ac.signal.aborted ? [] : checkOutputs(d, must);+ if (!fix.ok) r = { ...r, ok: false, stderr: fix.stderr, lastError: fix.lastError };+ }} finally { release(); running.get(id)?.delete(ac); }log(id, { type: 'turn', state: 'end', phase, who: label, ok: !!r?.ok && !ac.signal.aborted });if (ac.signal.aborted) return { ok: false, aborted: true };@@ -293,6 +351,7 @@ async function turn<P extends Phase>(id: string, phase: P, vars: StepVars[P], mu// changes nothing. Existing outputs count then, so the user isn't stuck retrying a finished step.if (missing.length && r.ok && load(id).retryPending) missing = missing.filter((f) => !existsSync(join(d, f)));if (load(id).retryPending) update(id, (x) => { delete x.retryPending; });+ missing = [...missing, ...broken.filter((b) => !missing.includes(b.file)).map((b) => `${b.file}(${b.problem})`)]if (r.text) chat(id, session === 'fresh' ? 'critic' : session === 'director' ? 'agent' : 'builder', r.text, { phase, who: label });return { ok: r.ok && !missing.length, text: r.text, missing, stderr: r.stderr, lastError: r.lastError };}@@ -511,7 +570,13 @@ async function production(id: string, { fresh = false } = {}): Promise<boolean>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; }+ if (round >= rounds(id).chunkRounds + (left <= 1 ? 1 : 0)) {+ if (preset(id).pauseAtLimit) { set({ state: 'failed', open: bad.length }); return false; }+ // fast mode: carry on with what is left (the final review sees the whole film; the user can upgrade the mode)+ set({ state: 'passed', open: bad.length, acceptedAtLimit: true }); prerender(id, c);+ chat(id, 'system', L(id, `快速模式:${c.id} 審了 ${round} 輪,還有 ${left} 個問題,先繼續製作(最後評審會再看整支片)`, `Fast mode: ${c.id} had ${round} review rounds and ${left} issue${left > 1 ? 's' : ''} left; carrying on (the final review sees the whole film)`));+ return true;+ }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; }@@ -578,7 +643,10 @@ async function castGate(id: string, prev: Pipeline): Promise<boolean> {const rv = readJSON<Review>(join(d, 'out', 'check', 'cast', `review_${c.id}.json`)) || {};if (collectNeeds(id, rv.needs_user, `cast-qa-${c.id}`)) { setC(c.id, { state: 'needs_user' }); return 'needs'; }if (passed(rv)) { setC(c.id, { state: 'passed' }); return 'passed'; }- if (round >= rounds(id).castRounds) { setC(c.id, { state: 'failed', issues: (rv.issues || []).length }); return 'failed'; }+ if (round >= rounds(id).castRounds) {+ if (preset(id).pauseAtLimit) { setC(c.id, { state: 'failed', issues: (rv.issues || []).length }); return 'failed'; }+ setC(c.id, { state: 'passed', issues: (rv.issues || []).length, acceptedAtLimit: true }); return 'passed';+ }setC(c.id, { state: 'fixing' });const f = await turn(id, 'cast_fix', { issues: rv.issues || [], round, character: c, rigFiles: prod.rig_files || [] }, [c.sheet, `out/check/cast/fixes_${c.id}.json`], { session: `cast-${c.id}`, who: `cast-${c.id}` });if (!f.ok) { setC(c.id, { state: 'error' }); return 'error'; }@@ -622,7 +690,10 @@ async function castSerial(id: string, prev: Pipeline, firstReview?: Review | nul}if (collectNeeds(id, rv.needs_user, 'cast-qa')) return pause(id);if (passed(rv)) { pipe(id, (p) => { p.cast!.pass = true; p.cast!.state = 'passed'; }); chat(id, 'system', L(id, `角色關通過(第 ${round} 輪)`, `Characters passed (round ${round})`)); break; }- if (round >= rounds(id).castRounds) { pipe(id, (p) => { p.cast!.state = 'failed'; }); chat(id, 'system', L(id, `角色關 ${round} 輪仍未通過,請你看角色設定圖決定`, `Characters still not passing after ${round} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }+ if (round >= rounds(id).castRounds) {+ if (!preset(id).pauseAtLimit) { pipe(id, (p) => { p.cast!.pass = true; p.cast!.state = 'passed'; p.cast!.acceptedAtLimit = true; }); chat(id, 'system', L(id, `快速模式:角色關審了 ${round} 輪,還有 ${(rv.issues || []).length} 個問題,先繼續製作`, `Fast mode: characters had ${round} review rounds with ${(rv.issues || []).length} issue(s) left; carrying on`)); break; }+ pipe(id, (p) => { p.cast!.state = 'failed'; }); chat(id, 'system', L(id, `角色關 ${round} 輪仍未通過,請你看角色設定圖決定`, `Characters still not passing after ${round} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false;+ }pipe(id, (p) => { p.cast!.state = 'fixing'; });const f = await turn(id, 'cast_fix', { issues: rv.issues || [], round }, ['out/check/cast/sheet.jpg', 'out/check/cast/fixes.json'], { who: 'director' });if (!f.ok) return fail(id, 'producing', f);@@ -688,6 +759,38 @@ function sharedLock<T>(key: string, fn: () => Promise<T>): Promise<T> { const prfunction pause(id: string) { setStage(id, 'needs_input'); return false; }// ---------- final panel: seams, continuity, pacing; verifies every earlier fix ----------+type MustFix = NonNullable<Critique['must_fix']>[number];+// A must-fix item is a segment's when every shot it names is in that one segment.+function splitBySegment(id: string, must: MustFix[]): { local: Map<Chunk, MustFix[]>; global: MustFix[] } {+ const chunks = readJSON<Production>(join(dirOf(id), 'build', 'production.json'))?.chunks || [];+ const local = new Map<Chunk, MustFix[]>(), global: MustFix[] = [];+ for (const m of must) {+ const shots = [...new Set(String(m.shot || '').match(/S\d+/g) || [])];+ const owners = new Set(shots.map((s) => chunks.find((c) => c.shots.includes(s))));+ const [owner] = [...owners];+ if (shots.length && owners.size === 1 && owner) local.set(owner, [...(local.get(owner) || []), m]);+ else global.push(m);+ }+ return { local, global };+}++// The builders fix their own segments in parallel (their conversations still hold how each shot was made). Returns+// the fixes files for the director's render and evidence, or null when a builder turn failed (the job is in error).+async function fixSegments(id: string, local: Map<Chunk, MustFix[]>, round: number): Promise<string[] | null> {+ if (!local.size) return [];+ chat(id, 'system', L(id, `${[...local.keys()].map((c) => c.id).join('、')} 的必修交回各段的製作 agent 同時修,全片性的交給導演`,+ `Segment items go back to their builders (${[...local.keys()].map((c) => c.id).join(', ')}) in parallel; film-wide ones to the director`));+ const results = await Promise.all([...local.entries()].map(([c, items]) => {+ const bad: ShotEntry[] = [...new Set(items.flatMap((m) => String(m.shot).match(/S\d+/g) || []))]+ .map((sid) => ({ id: sid, issues: items.filter((m) => String(m.shot).includes(sid)).map((m) => ({ issue: `${m.time != null ? `[${m.time}s] ` : ''}${m.issue}`, fix: m.fix })) }));+ return turn(id, 'fix_chunk', { chunk: c, bad, round: `final-${round}`, final: true }, [`out/check/shots/${c.id}.fixes.json`], { session: `builder-${c.id}`, who: `builder-${c.id}` })+ .then((r) => ({ c, r }));+ }));+ const failed = results.find((x) => !x.r.ok);+ if (failed) { fail(id, 'revising', failed.r); return null; }+ return results.map((x) => `out/check/shots/${x.c.id}.fixes.json`);+}+async function finalPanel(id: string) {const d = dirOf(id);let prevMust = Infinity;@@ -703,14 +806,29 @@ 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; }- // Past the limit, keep going while the list is short (≤ 2) and still shrinking, up to 3 extra rounds: a real run went- // 8 → 3 → 2 → 1 and stopped with its last, most visible defect unfixed. A list that stops shrinking stops the loop.- const converging = must.length <= 2 && must.length < prevMust && round <= rounds(id).finalRounds + 3;+ // Past the limit, keep going while the list is clearly shrinking — short (≤ 3) or at most half of the last round's —+ // up to 3 extra rounds. Real runs went 8 → 3 → 2 → 1 and 9 → 3 and stopped with visible defects (a character+ // teleporting between two frames) unfixed. A list that stops shrinking stops the loop.+ const shrinking = must.length < prevMust && (must.length <= 3 || must.length <= prevMust / 2);+ const converging = shrinking && round <= rounds(id).finalRounds + preset(id).converge;prevMust = must.length;- if (round > rounds(id).finalRounds && !converging) { 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');+ if (round > rounds(id).finalRounds && !converging) {+ chat(id, 'system', preset(id).pauseAtLimit+ ? 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`)+ : L(id, `快速模式交件:評審還列了 ${must.length} 項可以再修(在評審報告裡)。想修掉就把品質升級,會從這支片接著修。`, `Fast mode delivered: the final review lists ${must.length} more item${must.length > 1 ? 's' : ''} to fix (see the review). Upgrade the quality to fix them, starting from this film.`));+ setStage(id, 'done'); return;+ }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;+ setStage(id, 'revising', { error: null, failed: null });+ // Items that belong to one segment go back to the builder who made it, all segments at once; the rest (shared+ // files, the mix, items across segments) and the render stay with the director. Real runs: the director fixing+ // 9–12 items alone was the longest step after approval (14–17 min), and its edits to shots it had not built+ // brought back the very defect being fixed (a character teleporting between two frames) in another shot.+ const { local, global } = splitBySegment(id, must);+ const builderFixes = await fixSegments(id, local, round);+ if (builderFixes === null) return;+ const msg = global.map((m, i) => `${i + 1}. [${m.shot || '全片'}${m.time != null ? ' ' + m.time + 's' : ''}] ${m.issue}${m.fix ? ' → 建議:' + m.fix : ''}`).join('\n');+ if (!(await step(id, 'revising', 'revise', { message: msg, round, builderFixes }, ['out/video.mp4', 'out/check/fixes.json']))) return;}}diff --git a/app/server/outputs.test.ts b/app/server/outputs.test.tsnew file mode 100644index 0000000..859cf03--- /dev/null+++ b/app/server/outputs.test.ts@@ -0,0 +1,41 @@+// Output checks: what counts as a readable agent output (JSON that parses, in the shape the orchestrator reads).+import { after, describe, test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { checkOutputs, parseJSON, repairPrompt } from './outputs.ts';++const D = mkdtempSync(join(tmpdir(), 'reelmimic-out-'));+after(() => rmSync(D, { recursive: true, force: true }));+const put = (f: string, text: string) => { mkdirSync(join(D, f, '..'), { recursive: true }); writeFileSync(join(D, f), text); };++describe('agent outputs', () => {+ test('valid files pass, a byte-order mark is not an error', () => {+ put('out/check/critique.json', '\uFEFF{ "must_fix": [], "pass": true }');+ put('build/production.json', JSON.stringify({ chunks: [{ id: 'C1', shots: ['S1'] }] }));+ put('out/check/shots/C1.fixes.json', JSON.stringify({ fixes: [] }));+ put('out/video.mp4', 'not json, not checked');+ assert.deepEqual(checkOutputs(D, ['out/check/critique.json', 'build/production.json', 'out/check/shots/C1.fixes.json', 'out/video.mp4']), []);+ assert.deepEqual(parseJSON('\uFEFF[1]'), [1]);+ });+ test('broken JSON and wrong shapes are reported with the file', () => {+ put('a/critique.json', '{ "must_fix": [ { "issue": "x" }, ] }');+ put('b/production.json', JSON.stringify({ shots: [] }));+ put('c/review_hero.json', JSON.stringify([{ pass: true }]));+ put('d/fixes.json', JSON.stringify({ issue: 'x' }));+ put('e/critique.json', JSON.stringify({ must_fix: 'none' }));+ const got = Object.fromEntries(checkOutputs(D, ['a/critique.json', 'b/production.json', 'c/review_hero.json', 'd/fixes.json', 'e/critique.json']).map((p) => [p.file, p.problem]));+ assert.match(got['a/critique.json'], /not valid JSON/);+ assert.match(got['b/production.json'], /chunks/);+ assert.match(got['c/review_hero.json'], /object/);+ assert.match(got['d/fixes.json'], /list of fixes/);+ assert.match(got['e/critique.json'], /must_fix/);+ });+ test('missing files are left to the mtime check, and the repair prompt names every file', () => {+ assert.deepEqual(checkOutputs(D, ['nope/critique.json']), []);+ const p = repairPrompt('projects/x', [{ file: 'out/check/critique.json', problem: 'not valid JSON' }]);+ assert.match(p, /專案資料夾:projects\/x(/);+ assert.match(p, /^- out\/check\/critique\.json:not valid JSON$/m);+ });+});diff --git a/app/server/outputs.ts b/app/server/outputs.tsnew file mode 100644index 0000000..8f818c6--- /dev/null+++ b/app/server/outputs.ts@@ -0,0 +1,49 @@+// Agent outputs are checked, not just timestamped. A step is done when its files were written AND the JSON ones parse+// and have the shape the orchestrator reads. Before this, a critique.json with a trailing comma was read as {} — no+// must-fix items — and the film was delivered as "passed"; a broken production.json meant no segments, so nothing was+// built and the job still reached "done" (both reproduced in pipeline.test.ts).+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++export interface OutputProblem { file: string; problem: string }++type Check = (v: unknown) => string | null;+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);+const object: Check = (v) => (isObj(v) ? null : 'must be a JSON object { … }');+const listOf = (key: string): Check => (v) => object(v) ?? (v === null || (isObj(v) && (v[key] === undefined || Array.isArray(v[key]))) ? null : `"${key}" must be a list`);++// Only the shape the orchestrator relies on; everything else about a file is the agents' contract (CONTRACT.md).+const SHAPES: [RegExp, Check][] = [+ [/(^|\/)plan\.json$/, object],+ [/(^|\/)production\.json$/, (v) => object(v) ?? (isObj(v) && Array.isArray(v.chunks) ? null : '"chunks" must be a list of segments')],+ [/(^|\/)critique\.json$/, listOf('must_fix')],+ [/review(_[^/]*)?\.json$/, (v) => object(v) ?? listOf('issues')(v) ?? listOf('shots')(v)],+ [/fixes(_[^/]*)?\.json$/, (v) => (Array.isArray(v) || (isObj(v) && Array.isArray(v.fixes)) ? null : 'must be a list of fixes [ … ] (or { "fixes": [ … ] })')],+];++/** JSON text as the orchestrator reads it: a UTF-8 byte-order mark (some Windows tools write one) is not an error. */+export const parseJSON = (text: string): unknown => JSON.parse(text.replace(/^\uFEFF/, ''));++/** Problems with the .json files among `files` (paths relative to dir); files that do not exist are not checked here. */+export function checkOutputs(dir: string, files: string[]): OutputProblem[] {+ const out: OutputProblem[] = [];+ for (const f of files.filter((x) => x.endsWith('.json'))) {+ let text: string;+ try { text = readFileSync(join(dir, f), 'utf8'); } catch { continue; }+ let v: unknown;+ try { v = parseJSON(text); } catch (e) { out.push({ file: f, problem: `not valid JSON (${(e as Error).message.slice(0, 160)})` }); continue; }+ const shape = SHAPES.find(([re]) => re.test(f))?.[1];+ const problem = shape?.(v);+ if (problem) out.push({ file: f, problem });+ }+ return out;+}++/** The turn that asks the same agent (same conversation, so it knows what it meant) to repair its files. */+export function repairPrompt(projectDir: string, problems: OutputProblem[]): string {+ return `## 步驟:修正輸出檔的 JSON+專案資料夾:${projectDir}(以下路徑相對於它)+你剛才這一步寫的檔案,系統讀不懂。只修正這些檔案,內容照你原本要表達的意思,不要改其他任何檔案:+${problems.map((p) => `- ${p.file}:${p.problem}`).join('\n')}+寫成標準 JSON:不能有註解、結尾逗號、單引號或 NaN;最外層的型態照 ${'.claude/skills/video-clone'}/CONTRACT.md。改完用 python -c "import json;json.load(open(r'<檔案>',encoding='utf-8'))" 自己確認每個都讀得出來。最後用一行回報。`;+}diff --git a/app/server/pipeline.test.ts b/app/server/pipeline.test.tsindex b254c55..13b7eb7 100644--- a/app/server/pipeline.test.ts+++ b/app/server/pipeline.test.ts@@ -20,9 +20,11 @@ interface Scenario {shotPass: (shot: string, round: number) => boolean;sharedFix?: (chunk: string, call: number) => boolean; // the builder reports a shared-file problem insteadcastShared?: (char: string, call: number) => boolean;- critique: (round: number) => { must?: number; needs?: number; lostPeak?: boolean };+ critique: (round: number) => { must?: number; needs?: number; lostPeak?: boolean; items?: { shot: string; issue: string }[] };buildDelayMs?: number; // let the per-shot watcher (every 4 s) pick shots upprerender?: string; // production.json prerender command+ badJson?: (step: string, call: number) => boolean; // the agent writes broken JSON for this step (LLMs do: trailing commas, comments)+ repairFails?: boolean; // … and its repair turn does not fix it}let S: Scenario;let calls: string[] = [];@@ -71,15 +73,25 @@ function outputs(prompt: string, dir: string): [string, Record<string, unknown>]if (m(/## 步驟:組裝成片/)) return ['assemble', { 'out/video.mp4': 'mp4' }];if (m(/獨立評審/)) {const round = bump(`critique-${dir}`), c = S.critique(round);- return [`critique`, { 'out/check/critique.json': { peaks: [{ id: 'P1', verdict: c.lostPeak ? 'ref_better' : 'equal', why: 'smaller hit' }], must_fix: Array.from({ length: c.must || 0 }, (_, i) => ({ shot: 'S1', issue: `must ${i}` })), needs_user: Array.from({ length: c.needs || 0 }, () => ({ kind: 'text', issue: 'confirm the lyric' })) } }];+ return [`critique`, { 'out/check/critique.json': { peaks: [{ id: 'P1', verdict: c.lostPeak ? 'ref_better' : 'equal', why: 'smaller hit' }], must_fix: c.items ?? Array.from({ length: c.must || 0 }, (_, i) => ({ shot: 'S1', issue: `must ${i}` })), needs_user: Array.from({ length: c.needs || 0 }, () => ({ kind: 'text', issue: 'confirm the lyric' })) } }];}if (m(/## 步驟:修改成片/)) return ['revise', { 'out/video.mp4': 'mp4', 'out/check/fixes.json': [{ status: 'fixed' }] }];throw new Error('fake agent: unknown step\n' + prompt.slice(0, 300));}+const intended: Record<string, unknown> = {}; // what a broken file should have said (the repair turn writes it)async function fakeAgent({ cwd, prompt, onEvent }: AgentRun) {const dir = resolve(cwd, prompt.match(/專案資料夾:(\S+?)[(。]/)![1]);+ if (/## 步驟:修正輸出檔的 JSON/.test(prompt)) {+ calls.push('repair_json');+ for (const f of [...prompt.matchAll(/^- (\S+\.json):/gm)].map((x) => x[1])) put(dir, f, S.repairFails ? '{ still: broken, }' : intended[f]);+ onEvent?.({ type: 'session', id: `sess-${calls.length}` });+ return { sessionId: `sess-${calls.length}`, text: 'fixed the JSON', ok: true, code: 0, stderr: '', lastError: '' };+ }const [name, files] = outputs(prompt, dir);+ if (S.badJson?.(name, bump(`bad-${name}`))) {+ for (const [f, v] of Object.entries(files)) if (f.endsWith('.json')) { intended[f] = v; files[f] = '{ "must_fix": [ { "issue": "x" }, ], // trailing comma and a comment'; }+ }calls.push(name);if (name.startsWith('build:') && S.buildDelayMs) { // shot files first, the segment file after the delayconst entries = Object.entries(files), last = entries.pop()!;@@ -104,7 +116,7 @@ function newProject(stage: 'plan_review' | 'error', extra: Record<string, unknowconst id = `p-${++n}`;J.createJob({ id, title: 't', agent: 'claude', brief: 'make a video', reference: { type: 'url', src: 'https://example.com' } });const f = join(J.dirOf(id), 'job.json');- writeFileSync(f, JSON.stringify({ ...J.load(id), stage, ...extra }));+ writeFileSync(f, JSON.stringify({ ...J.load(id), quality: 'fine', stage, ...extra })); // most tests describe the fine lineif (stage === 'plan_review') writeFileSync(join(J.dirOf(id), 'plan.json'), JSON.stringify({ title: 'T', version: 1 }));return id;}@@ -127,6 +139,27 @@ describe('pre-production', () => {});});+describe('broken agent output', () => {+ test('a critique that is not valid JSON never passes: the same agent repairs it, then the real verdict counts', async () => {+ S = base({ critique: (r) => ({ must: r === 1 ? 1 : 0 }), badJson: (step, call) => step === 'critique' && call === 1 });+ const id = newProject('plan_review');+ await J.approve(id);+ const j = J.load(id);+ assert.ok(calls.includes('repair_json'), calls.join(' '));+ assert.ok(calls.includes('revise'), 'the repaired critique had a must-fix item: it must be revised, not passed');+ assert.equal(j.stage, 'done', j.error || '');+ });+ test('a production.json that stays broken stops the job with a clear error instead of building nothing', async () => {+ S = base({ badJson: (step) => step === 'setup', repairFails: true });+ const id = newProject('plan_review');+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'error');+ assert.match(j.error || '', /production\.json.*JSON/);+ assert.ok(!calls.some((c) => c.startsWith('build:')), 'no shot is built on a broken production.json');+ });+});+describe('production', () => {test('happy path: one character, two segments, final review passes → done', async () => {S = base();@@ -151,11 +184,23 @@ describe('production', () => {assert.deepEqual(calls.filter((c) => c.startsWith('cast')), ['cast_qa:serial', 'cast_fix:serial', 'cast_qa:serial']);assert.ok(calls.indexOf('fix:C2') > calls.indexOf('shot_qa:S2:1'));assert.ok(calls.includes('shot_qa:S2:2'));- assert.ok(!calls.includes('fix:C1'));- assert.deepEqual(calls.slice(-3), ['critique', 'revise', 'critique']);+ assert.ok(!calls.slice(0, calls.indexOf('critique')).includes('fix:C1')); // C1 passed its shot review first time+ // the final review's item is in S1: its builder fixes it, then the director renders the film+ assert.deepEqual(calls.slice(-4), ['critique', 'fix:C1', 'revise', 'critique']);assert.equal(J.load(id).critiqueRounds, 2);});+ test('final must-fix items: one segment each to its builder in parallel, across segments to the director', async () => {+ // round 1: one item in each segment and one across both+ S = base({ critique: (r) => (r === 1 ? { items: [{ shot: 'S1', issue: 'pose pops' }, { shot: 'S2', issue: 'arm floats' }, { shot: 'S1/S2', issue: 'silhouette' }] } : {}) });+ const id = newProject('plan_review');+ await J.approve(id);+ const fin = calls.slice(calls.indexOf('critique'));+ assert.deepEqual(fin.slice(1, 3).sort(), ['fix:C1', 'fix:C2']);+ assert.equal(fin[3], 'revise');+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ });+test('a climax that loses to the reference is sent back even with no must-fix listed', async () => {S = base({ critique: (r) => ({ lostPeak: r === 1 }) });const id = newProject('plan_review');@@ -190,6 +235,21 @@ describe('production', () => {assert.equal(J.load(id).lastCritique?.pass, true);});+ test('a long list that halves keeps revising past the limit (9 → 3 → 0)', async () => {+ S = base({ critique: (r) => ({ must: [9, 3, 0][r - 1] }) });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(J.load(id).lastCritique?.pass, true);+ });++ test('a list that shrinks slowly and stays long stops at the limit (9 → 7 → 6)', async () => {+ S = base({ critique: (r) => ({ must: [9, 7, 6, 5][r - 1] ?? 5 }) });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(J.load(id).lastCritique?.pass, false);+ assert.equal(calls.filter((c) => c === 'revise').length, 2);+ });+test('a must-fix list that stops shrinking stops at the limit', async () => {S = base({ critique: () => ({ must: 2 }) });const id = newProject('plan_review');@@ -330,6 +390,56 @@ describe('pauses', () => {});});+describe('quality modes', () => {+ test('fast: a segment and a character at their limit carry on, and the film is delivered without pausing', async () => {+ S = base({ castPass: () => false, shotPass: (s) => s !== 'S2', critique: () => ({ must: 3 }) });+ const id = newProject('plan_review', { quality: 'fast' });+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'done', j.error || '');+ assert.equal(j.pipeline.chunks!.C2.state, 'passed');+ assert.equal(j.pipeline.chunks!.C2.acceptedAtLimit, true);+ assert.ok(calls.includes('assemble'));+ assert.equal(calls.filter((c) => c === 'revise').length, J.CONFIG.presets.fast.finalRounds); // a list that never shrinks: no extra rounds+ assert.match(j.chat.at(-1)!.text, /快速模式交件|Fast mode delivered/);+ });++ test('fast: a shrinking list gets no extra rounds past the limit', async () => {+ S = base({ critique: (r) => ({ must: [3, 1, 0][r - 1] ?? 0 }) });+ const id = newProject('plan_review', { quality: 'fast' });+ await J.approve(id);+ assert.equal(calls.filter((c) => c === 'revise').length, 1);+ assert.equal(J.load(id).lastCritique?.pass, false);+ });++ test('upgrading a delivered fast film sends it back to the final review under the new bar', async () => {+ let critiques = 0;+ S = base({ critique: () => ({ must: ++critiques <= 2 ? 2 : 0 }) });+ const id = newProject('plan_review', { quality: 'fast' });+ await J.approve(id);+ assert.equal(J.load(id).lastCritique?.pass, false);+ calls = [];+ assert.equal(J.setQuality(id, 'fine').upgrade, true);+ await J.critique(id);+ const j = J.load(id);+ assert.equal(j.quality, 'fine');+ assert.equal(j.lastCritique?.pass, true);+ assert.deepEqual(calls, ['critique']);+ assert.equal(J.setQuality(id, 'fast').upgrade, false); // going down never re-runs anything+ });++ test('the prompts follow the mode: fast blocks only what a viewer sees at once', async () => {+ const { prompts } = await import('./prompts.ts');+ const v = { dir: 'projects/x', brief: 'b', inputs: [], config: J.CONFIG, lang: 'zh-TW' as const, chunk: { id: 'C1', shots: ['S1'] }, shots: ['S1'], round: 1, out: 'o.json' };+ const fast = prompts.shot_qa({ ...v, quality: 'fast' }), fine = prompts.shot_qa({ ...v, quality: 'fine' });+ assert.match(fast, /品質模式:\*\*快速/);+ assert.match(fine, /都是 blocker/);+ assert.doesNotMatch(fast, /都是 blocker/);+ assert.match(prompts.critique({ ...v, quality: 'fast', round: 1 }), /品質模式:快速/);+ assert.doesNotMatch(prompts.critique({ ...v, quality: 'standard', round: 1 }), /品質模式:快速/);+ });+});+describe('no characters', () => {test('a piece with no cast (typography, motion graphics) skips the cast sheet and the cast gate', async () => {S = base({ chars: [] });diff --git a/app/server/prompts.ts b/app/server/prompts.tsindex de0d967..26d3ec4 100644--- a/app/server/prompts.ts+++ b/app/server/prompts.ts@@ -1,6 +1,6 @@// Phase prompts. Each agent turn does exactly one step and writes the files CONTRACT.md defines; the server advances only// when those files exist. Same prompts for Claude Code and Codex (skills are referenced by path, no Skill tool needed).-import type { Lang } from '../shared/types.ts';+import type { Lang, Quality } from '../shared/types.ts';import type { BaseVars, Prompts } from './types.ts';const SKILL = '.claude/skills/video-clone';@@ -55,8 +55,22 @@ ${process.env.PYTHON && process.env.PYTHON !== 'python' ? `這台電腦的 Pytho${RULES}${SPEED}`;+// Quality mode (job.quality, chosen by the user): where every frame is checked, and what blocks.+// fine is the line that made v8z8p (every pose change checked frame by frame); fast keeps only what a viewer sees at once.+const FRAMES: Record<Quality, string> = {+ fine: '姿勢或表情改變、角色出場/離場的那一刻前後 0.25 秒看成片的每一格',+ standard: 'hero 鏡頭(plan.peaks)裡姿勢或表情改變、角色出場的那一刻前後 0.25 秒看成片的每一格(其他鏡頭看 12fps strip)',+ fast: 'hero 鏡頭的爆點前後 0.25 秒看成片的每一格(其他鏡頭看 12fps strip)',+};+const BAR = (p: BaseVars) => ({+ fast: `品質模式:**快速**(使用者選了速度,之後可以升級再修)。blocker 只限觀眾用正常速度一眼就看得出的硬傷:角色和設定圖不像、身體部位斷開或浮空、穿模、+破圖/黑格/閃格、字幕讀不出、主角找不到、高潮的爆點沒做出來;其他(一般鏡頭裡一格換姿勢、構圖或表演可以更好)一律標 polish。`,+ standard: '品質模式:**標準**。一格就換姿勢在 hero 鏡頭(plan.peaks)裡是 blocker;其他鏡頭要正常速度看得出來才是 blocker。',+ fine: '品質模式:**精緻**(要交出去的成品):照下面的標準最嚴格地審,hero 鏡頭的每一格都要經得起逐格看。',+}[p.quality]);+// The human-eye checklist every reviewer applies to FULL-RESOLUTION CROPS, not thumbnails.-const EYE = `用人眼逐處檢查(一定要看全解析度的放大截圖,縮圖看不出來):+const EYE = (p: BaseVars) => `用人眼逐處檢查(一定要看全解析度的放大截圖,縮圖看不出來):- 角色:每個身體部位都接在一起(頭—脖子—身體、肩—上臂—前臂—手、臀—腿—腳),沒有浮空的手、沒有硬黏在邊緣的手臂、沒有少脖子;關節處沒有接縫線或兩層描邊;比例、配色、髮型、服裝和角色設定圖一致;描線粗細全身一致;表情讀得懂;手拿的東西真的接觸到手。- 設計圖:使用者有給角色設計圖(plan.characters[].design)就把它和畫面裡的角色並排比:比例、眼睛、手腳、配色、配件位置,走樣是 blocker。@@ -65,7 +79,7 @@ const EYE = `用人眼逐處檢查(一定要看全解析度的放大截圖,- 畫面:主體夠大(有情緒、對話、表情戲的鏡頭,主角至少佔畫面高度 35%,看得清臉;只有刻意的遠景建立鏡頭例外)、沒有無用途的大片空白;字不壓主體;字幕要把整張圖縮到手機寬度(約 390px 寬)也讀得出來:字高至少畫面高度 4.5%、有描邊或半透明底;沒有色帶、髒污、破圖、閃格、跳格;轉場每個接縫都有。- 動作:有預備動作與餘韻、不機械;同一鏡內造型不跳動(例如眼鏡突然變墨鏡)。**動作只能從連續影格判斷**:每個動作(拿、轉身、坐下、跳、表情變化、道具移動)- 都要看 12fps 的連續 strip,找:一格就換姿勢/表情(沒有中間格)、道具瞬移、該動的手不動、整個人僵硬平移或旋轉、超過 1 秒完全靜止的表演鏡頭。+ 都要看 12fps 的連續 strip;**${FRAMES[p.quality]}**(成片 fps 見 plan.format.fps;12fps 只看到一部分格,一格內換姿勢會被看成正常動作——兩次真實製作的跳格都是這樣漏到最後評審),找:一格就換姿勢/表情(沒有中間格)、道具瞬移、該動的手不動、整個人僵硬平移或旋轉、超過 1 秒完全靜止的表演鏡頭。- 不要用閃白、轉場或鏡頭切走去蓋掉做不到的動作;做不到就在共用角色定義新增姿勢或換一個做得到的演法。`;const QA_OUT = (file: string, extra = '') => `寫 ${file}(JSON):${extra}@@ -86,8 +100,12 @@ export const prompts: Prompts = {使用者需求(brief.md):${p.brief}-1. analyze.py 已跑完:讀 analysis/report.json,打開 analysis/sheet_1fps.jpg 與 sheet_scenes.jpg 實際看。-2. 寫 analysis/STYLE.md:第一行寫媒材;把 shot_details 整理成鏡頭清單表;配色與色彩弧線、角色造型語言、剪接、轉場、敘事結構、字幕用法;+1. analyze.py 已跑完:讀 analysis/report.json,打開 analysis/sheet_1fps.jpg、sheet_scenes.jpg 與 fingerprint.png 實際看。+ analysis/fingerprint.json 是實測的時間序列:每鏡 shots[].move(運鏡種類、起點、時長、量、擬合出的緩動 ease.named / ease.bezier、+ overshoot、同一鏡的其他運鏡 other_moves)、cadence(一拍一/一拍二:每秒幾張新畫面)、tension 曲線的 peaks(鋪陳斜率、屏息深度、爆點幾格到位、停多久)、+ rhythm(切點落在拍點的比例與相位)。數字只是指路,影格才是答案;但寫規格時用實測值,不要用「慢慢推近」這種形容詞。+2. 寫 analysis/STYLE.md:第一行寫媒材;把 shot_details 整理成鏡頭清單表(運鏡欄寫實測的種類、時長與緩動,例如「推近 +18%,0.55 s,expo.out」);+ 寫一行 cadence 與一行剪接節奏(切點對拍比例);配色與色彩弧線、角色造型語言、剪接、轉場、敘事結構、字幕用法;最後列「這支好看的 3–5 個關鍵」。2b. **找參考片的高潮(起雞皮疙瘩的那 1–2 刻)**:report.json 的 audio.peak_candidates(音樂蓄力後爆發的時間點)與 flashes(閃白格)只是線索;對每個候選用 clip_strip.py 對參考片(${REF})抽前 2 秒到後 2 秒的 12fps 連續影格(不加 --vs)存成 analysis/peak_<n>.jpg,打開看,確認真正的爆點。@@ -123,7 +141,11 @@ ${WOW}**情緒弧線**:不只能量往上,要有一個小故事(想要什麼 → 遇到阻礙或等待 → 高潮時得到),讓爆點有意義。**變化**:在 STORYBOARD.md 列出每鏡的場景與機位,算出同一場景+機位佔片長的比例(≤ 40%),高潮之間換場景或視角。4. 寫 plan.json(CONTRACT.md 格式)與 STORYBOARD.md:logline、look、borrowed_from_reference、角色/產品、每鏡時間、動作、轉場、reads、- 素材與音效;逐鏡對照:ref_shot、ref_what、camera(engine 規格、pace 跟參考一致)。平均鏡頭長度、字卡比例、暗調比例與參考接近(±30%)。+ 素材與音效;逐鏡對照:ref_shot、ref_what、camera(engine 規格;有對應參考鏡頭時,時長、量與緩動照 fingerprint.json 該鏡的實測值,+ 例如 cubic-bezier 直接抄 ease.bezier)。動畫節奏照參考片的 cadence(一拍二就每張畫停兩格)。平均鏡頭長度、字卡比例、暗調比例與參考接近(±30%)。+ **畫面變化至少要和參考片一樣頻繁**:參考片的換場 = 硬切+鏡頭內的轉場換景(布幕、煙霧、光圈…,看 STYLE.md 鏡頭表括號裡的場景),+ 數出它每 10 秒換幾次畫面,企劃的構圖/場景變化不能更少(使用者要更熱鬧就更多)。寫完跑 python ${SKILL}/scripts/fingerprint.py plan-check ${p.dir}:+ 它比的是硬切數,「比參考慢」要加切點或鏡頭內換景;比參考快沒關係;它列出的「太短」鏡頭只是提醒運鏡會被壓縮。5. 角色:plan.characters 每個角色寫清楚造型(輪廓、比例、配色、髮型、服裝、特徵)與 id;使用者有給設計圖的角色寫 "design": "inputs/<圖>",並量出設計圖的比例寫進描述(例如:身體寬:高 = 1.9:1、眼睛在上 1/3、手從身體中段水平伸出、4 隻短腳)。${DESIGN}@@ -170,7 +192,7 @@ ${ENGINE(p)}4. 照 plan.style_frames 其餘項目渲染 2–3 張 out/check/style_*.jpg(用真正的角色與素材),和對應參考鏡頭並排看,到水準才交出。5. 更新 plan.json(style_frames:key_*_vs_ref.jpg 放最前面;assets)與 STORYBOARD.md;鏡頭內容除非必要不要改。${WOW}-${EYE}`,+${EYE(p)}`,replan: (p) => `${HEADER(p)}@@ -179,7 +201,8 @@ ${EYE}`,${p.message}修改 plan.json 與 STORYBOARD.md(version +1,changelog),必要時補抓素材、重畫受影響的定調畫面(改到高潮就重做 key_<n>_vs_ref.jpg)。不要開始生成。逐條回報怎麼處理;做不到的直說並給替代方案。-改動如果犧牲了參考片的核心(例如雙人故事改成獨角戲、拿掉高潮),在回報裡明講這個取捨。`,+改動如果犧牲了參考片的核心(例如雙人故事改成獨角戲、拿掉高潮),在回報裡明講這個取捨。+改到鏡頭時間就再跑 python ${SKILL}/scripts/fingerprint.py plan-check ${p.dir}:不要比參考片慢(使用者明確要求除外);畫面變化不能比參考片少。`,// ---------- production: setup → cast gate → shot line → assemble ----------setup: (p) => `${HEADER(p)}@@ -198,9 +221,24 @@ ${ENGINE(p)}- 高潮音效:plan.peaks 的 sound(爆點前的安靜或抽空、蓄力上升音、落在 hit_s 的撞擊/音樂重拍)在共用混音裡先放好。每個鏡頭各自一個檔案(painted-animation:src/scenes/<shot>.js;hyperframes:compositions/<shot>.html),總檔先把全部鏡頭的引用都掛好,讓製作 agent 只需要改自己的鏡頭檔,不會互相衝突。+1b. **運鏡與時間寫成 Motion Score**(docs/COMPILER.md 第 2 階段;鏡頭檔不再手寫運鏡與寫死的秒數):+ - python ${SKILL}/scripts/motion_score.py from-ref ${p.dir} → build/score/(film.json + shots/<shot>.json):每鏡的運鏡從參考片對應鏡頭**實測轉移**+ (同樣的時長、量、擬合出的緩動;from_ref 記錄來源)。+ - 照企劃調整:每鏡 camera.base(x, y = 畫面中心對準的世界座標、zoom、rot 弧度)與 moves 的目標(例如推到眼睛就讓 base 和 by 對準眼睛),+ **保留轉移來的時長與 ease**,除非企劃刻意不同;film.json 的 cues 寫高潮與關鍵動作的時間(例如 "P1_hit": "B28",時間寫法見 ${SKILL}/scripts/score/timeexpr.py)。+ - python ${SKILL}/scripts/motion_score.py validate build/score(有 error 一定要修);python ${SKILL}/scripts/motion_score.py predict ${p.dir}+ (不渲染就預測每鏡運鏡和參考片的差距;major 要修,或在 production.json 的 score.notes 寫為什麼故意不同)。+ - 改完構圖目標後跑 python ${SKILL}/scripts/motion_score.py optimize ${p.dir} --peaks:不渲染,搜尋每鏡運鏡的起點、時長與緩動(不改構圖量),+ 讓它更接近參考片,並把高潮附近的鏡頭一起調、讓預測的張力在 plan.peaks 的爆點更像參考片的爆發;看 out/check/score_optimize.json 的 changes,+ 合理就加 --apply 再跑一次寫回 build/score(每個改動都記在 "tuned")。+ - python ${SKILL}/scripts/motion_score.py compile build/score --out <引擎載入的位置>:canvas 引擎(painted、pixel…)build/src/score.js,+ 在 studio.html 的鏡頭 script 之前載入;HyperFrames build/assets/score.js,在 index.html 的 kit.js 之後載入。+ - production.json 加 "score": { "dir": "build/score", "js": "<compile 輸出>", "compile": "<完整 compile 指令>", "notes": "…" }。2. **角色**:用 engine 的角色系統做出每個角色(2D 向量風格一律用 ${SKILL}/assets/vector_rig/ 的骨架+一體輪廓角色,不准用分開的形狀拼角色;painted 風格用角色骨架 cast_rig)。**每個角色一個定義檔**(例如 build/assets/cast/<角色id>.js),骨架/rig 本體另外一個共用檔;鏡頭只能呼叫角色定義、不准在鏡頭裡另外畫角色的身體部位。(每個角色會由不同 agent 同時審查與修正,所以不能把所有角色寫在同一個檔案裡。)+ 共用檔提供姿勢過渡(例如 blendPose(P0, P1, k)),內插的是**畫出來的**手腳位置與角度:IK 目標超出手長時先夾到手搆得到的地方再內插。+ (一次真實製作內插了搆不到的 IK 目標:前八成時間手一直伸直不動,整個 0.26 秒的動作擠進最後一格,審查退了三輪。)3. **角色設定圖**:每個角色一張 out/check/cast/sheet_<角色id>.jpg(全解析度):正面、3/4、側面、5 個以上表情、6 個以上本片會用到的動作姿勢(舉手、揮手、拿東西、坐、跑、驚嚇…)。再加一張所有角色並排的 out/check/cast/sheet.jpg(比例、互動姿勢)。每張都要有可以重新輸出的指令(寫進 production.json 的 characters[].render)。自己先打開看過。@@ -221,10 +259,11 @@ ${p.character ? `**這一輪你只審角色「${p.character.name || p.character.1. 讀 plan.json 的 characters 與 brief;打開 out/check/cast/ 的所有設定圖,**每個角色、每個表情、每個姿勢都放大看**(用 Python PIL 裁切全解析度區塊存到 out/check/cast/qa_*.png 再打開)。2. 第 2 輪以後:先讀 out/check/cast/fixes.json,逐項核對上一輪的問題是否真的修好(看修改後的截圖,不是看說明)。-${EYE}+${EYE(p)}另外判斷:造型是否符合企劃描述、是否夠有個性且在參考片的風格範圍內、會不會跟知名既有角色撞臉。**有使用者設計圖的角色**:把設計圖和設定圖裡每個姿勢並排(PIL 拼成 out/check/cast/qa_<id>_vs_design.jpg)逐格比;比例漂移(變高變窄)、手腳數量或位置不對、配件蓋住身體或戴錯部位,都是 blocker。+${BAR(p)}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。`,@@ -251,13 +290,17 @@ ${ENGINE(p)}- 同時有好幾個製作 agent 在渲染:預覽只渲染需要的幾格(stills/strip),不要反覆整段渲染,也不要開大量平行 worker。- 只改自己的鏡頭檔;共用檔(角色、配色、總檔)唯讀,發現共用檔有問題寫進 out/check/shots/${p.chunk.id}.done.json 的 notes,不要改。- 角色一律呼叫共用角色定義,造型、比例、配色和設定圖一致;不准在鏡頭裡自己畫手臂、手、身體。+- **運鏡一律從 Motion Score 取**(production.json 的 score):canvas 引擎 \`const c = Score.cam('S3', t); camBegin(c.x, c.y, c.zoom, c.rot)\`;+ HyperFrames 在 draw(t, S) 裡 \`S.cam.setAttribute('transform', Score.svgCamLocal('S3', t))\`(不要用專案 Kit 的 S.camera:有些專案的版本會忽略滾轉)。+ 不要在鏡頭檔手寫 lerp 運鏡或寫死秒數:關鍵時間用 Score.cue('P1_hit')、Score.beat(n);一拍二的鏡頭用 Score.held('S3', t) 當角色動作的時間。+ 運鏡要改就改自己那一鏡的 build/score/shots/<shot>.json(只改自己的鏡頭;film.json 唯讀),再跑 production.json 的 score.compile。- **hero 鏡頭**(plan.shots 裡 "hero": true,屬於 plan.peaks):照 plan.peaks 的 build/hit/after 做到格的層級;可以用特製姿勢、誇張變形、衝擊格、smear、光芒、粒子、鏡頭震動(需要新的角色姿勢或變形臉就在 notes 寫 "status": "shared" 請導演加進共用角色定義,不要在鏡頭裡疊畫手臂或身體)。做完用 clip_strip.py 把這段和參考高潮(analysis/peaks.json 的 from–to)並排成 out/check/shots/<shot>_peak_vs_ref.jpg,打開比:我們的爆點不如參考片震撼就繼續加,不要交。${WOW}- 每一鏡做完就渲染檢查(不要全部做完才看):stills(開頭/中間/結尾)與**每個動作 12fps 的連續 strip**,存成 out/check/shots/<shot>_sheet.jpg,並把每個角色裁切成全解析度 out/check/shots/<shot>_crop_*.png,自己打開看。-${EYE}+${EYE(p)}- **每一鏡做完、自己檢查過,就立刻寫 out/check/shots/<shot>.done.json**:{ "id": "S1", "sheet": "…", "crops": ["…"], "notes": "…" },然後接著做下一鏡。寫出這個檔的那一刻,獨立審查員就會開始審這一鏡(你不用等);之後不要再改已交出的鏡頭,除非是修正輪。- 全部做完寫 out/check/shots/${p.chunk.id}.done.json:{ "shots": [ { "id": "S1", "sheet": "…", "crops": ["…"], "notes": "…" } ] }`,@@ -269,28 +312,35 @@ ${EYE}同一段的其他鏡頭可能還在製作,只審指定的鏡頭;如果前一鏡已經做好,也檢查「前一鏡最後一格 → 這一鏡第一格」的接縫。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。+ 連續影格整體用 12fps,姿勢/表情改變的那一刻前後 0.25 秒看成片的每一格(只截那一小段:render.mjs --strip=a:b 本來就是逐格、+ hf_frames.py --range a:b:f、clip_strip.py --fps <成片 fps>)。只看成片真的有的格:hf_frames 會把時間對到那一刻畫面上的那一格,+ 自己算時間時用 格數/fps,不要用 0.0417 這種步距(30fps 的片有一次就是在格與格之間看到設計好的中間姿勢,成片卻一格跳完)。+ 一格就換姿勢時,在 issue 寫出是哪兩格(格的時間)和兩格之間變了什麼,讓製作 agent 直接逐格查。參考片對應鏡頭在 analysis/(sheet_scenes.jpg;需要時用 ffmpeg 從 ${REF} 抽格)。3. 第 2 輪以後:先讀 out/check/shots/${p.chunk.id}.fixes.json,逐項用修改後的截圖核對是否真的修好;沒修好的直接列回問題。-${EYE}+${EYE(p)}另外:動作與運鏡是否照企劃、和參考鏡頭的手法一致;和角色設定圖比對造型一致性。**動作**:每個動作都要看 12fps 連續影格(製作 agent 的 strip 不夠就自己用預覽指令的 strip 模式或 hf_frames --range 截)。一格換姿勢、道具瞬移、- 該動不動、僵硬整塊旋轉、表演鏡頭超過 1 秒完全靜止,都是 blocker。+ 該動不動、僵硬整塊旋轉、表演鏡頭超過 1 秒完全靜止,${p.quality === 'fine' ? '都是 blocker' : '照上面的品質模式判 blocker 或 polish'}。**hero 鏡頭**(plan.peaks):打開 <shot>_peak_vs_ref.jpg(沒有就自己用 clip_strip.py 做),參考在上、我們在下逐格比。爆點比參考片弱(主體小、畫面空、沒有停住、被閃白蓋掉、沒有預備或衝擊)是 blocker,寫清楚差在哪、要加什麼。+${BAR(p)}4. ${QA_OUT(p.out || `out/check/shots/${p.chunk.id}.review.json`, '{ "shots": [ { "id": "S1", "pass": true|false, "issues": [ { "time": 1.2, "where": "畫面位置", "issue": "…", "fix": "…" } ] } ], "verified_fixes": [ { "issue": "…", "fixed": true|false } ], "needs_user": [] }')}- 嚴格:專業動畫導演會退回的就不過。`,+ ${p.quality === 'fast' ? '快速模式:只有上面列的硬傷才不過。' : '嚴格:專業動畫導演會退回的就不過。'}`,fix_chunk: (p) => `${HEADER(p, '製作')}${ENGINE(p)}-## 步驟:修鏡頭段 ${p.chunk.id}(審查第 ${p.round} 輪沒過)+## 步驟:修鏡頭段 ${p.chunk.id}(${p.final ? '最後評審看完整支片後列的必修,這幾項在你的段落' : `審查第 ${p.round} 輪沒過`})沒過的鏡頭與問題:${JSON.stringify(p.bad, null, 1)}${p.message ? `\n使用者的指示(優先照做):${p.message}\n` : ''}先看 out/check/shots/${p.chunk.id}.shared.json(如果有):導演已經改好的共用功能,照它的 api 套用到鏡頭裡。逐項修改(只改自己的鏡頭檔),重新渲染受影響的 stills/strip 與角色裁切。寫 out/check/shots/${p.chunk.id}.fixes.json:[ { "shot": "S2", "issue": "…", "change": "改了什麼", "before": "…_before.png", "after": "…_after.png" } ],-before/after 是同一秒、同一位置的全解析度裁切,自己打開確認改好了。共用檔的問題不要自己改,寫 "status": "shared" 說明要導演改什麼。`,+before/after 是同一秒、同一位置的全解析度裁切,自己打開確認改好了;動作類的修正再附改動處前後 0.25 秒的**成片逐格**連續影格(hf_frames.py --range a:b:f;一格內換姿勢只有逐格看得出來)。+逐格的範圍從**改動區間開始前 0.3 秒到結束後 0.3 秒**:改出來的新問題幾乎都在改動和沒改的交界(一次真實製作只看了改動之後的格,交界那一格一次換四件事,又多跑一輪)。+共用檔的問題不要自己改,寫 "status": "shared" 說明要導演改什麼。${p.final ? `+這是最後評審階段:導演會在你之後重新輸出整支成片,你只要改好、渲染檢查自己的鏡頭檔,不要渲染整支片。` : ''}`,shared_fix: (p) => `${HEADER(p)}${ENGINE(p)}@@ -311,6 +361,8 @@ ${ENGINE(p)}1. 讀 build/production.json 與各段 out/check/shots/*.fixes.json 裡 "status": "shared" 的項目,先修共用檔的問題。2. 接起全部鏡頭:轉場、配樂、音效、字幕(歌詞字幕只能用 analysis/lyrics/subs.lrc 或 inputs 的 LRC;沒有就不上歌詞字幕)。3. 正式渲染 out/video.mp4(render.mjs --frames 有快取:通過審查的段落多半已經在背景渲染好,只會重渲改過的鏡頭;不要刪 out/frames);確認有音軌(ffprobe;沒有就把混音 mux 進去)。跑 python ${SKILL}/scripts/compare.py ${p.dir};檢查每個接縫(前後 0.5 秒 strip)。+ 整支片渲染一次要好幾分鐘:看到要調的地方先全部列出來、改完用截圖指令(HyperFrames:hf_frames)看改動處,**全部改完才重新渲染一次**;+ 不要改一處就渲染整支片(一次真實製作在這一步渲染了 4 次,多花 12 分鐘)。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. 回報:長度、解析度、每鏡一句話、還不完美或暫代的部分。`,@@ -324,6 +376,11 @@ ${RULES}你只能讀、量、看,並寫 out/check/critique.json 與 critique.md;不要修改其他檔案。每個鏡頭在製作時已經過鏡頭審查(他們只抓瑕疵)。**你的工作是判斷這支片能不能讓人起雞皮疙瘩、有沒有到參考片的水準**,不是確認「沒有錯」。${WOW}+${p.quality === 'fast' ? `+**品質模式:快速**(使用者選了速度,之後可以升級再修)。分數照實打、問題照實寫,但 **must_fix 只放**:觀眾用正常速度一眼就看得出的硬傷+(角色和設計圖不像、身體斷開或穿模、破圖/黑格/閃格、字幕讀不出、主角找不到)和判 ref_better 的高潮;其他(包含 ours_better 高潮在 why 裡的弱點、+< 4 的項目)都放 nice_to_have,使用者升級品質時會照它修。下面「必須有對應 must_fix」的規則在快速模式不適用。+` : ''}1. 參考片:analysis/report.json、peaks.json、sheet 圖。2. **高潮對決(最先做、最重要)**:plan.peaks 每一個,用 clip_strip.py 做 out/check/critic/peak_<n>_vs_ref.jpg@@ -335,7 +392,9 @@ ${WOW}3. 成片:ffmpeg 每 0.5 秒抽一格做總覽到 out/check/critic/,全部打開;每個接縫抽前後 0.5 秒的 strip;每個動作用 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)。+4. 跑 compare.py,看 compare_all.jpg 與 fingerprint_overlay.png;讀 out/check/style_distance.json 的 findings(實測:運鏡緩動與時長、+ 張力曲線與高潮形狀、切點對拍、cadence、色彩)。每條 major 都要自己抽影格確認:屬實且觀眾看得出來就列 must_fix(把實測數字和建議的+ cubic-bezier/格數寫進 fix);量測誤判(例如 UI 疊層、轉場被當成運鏡)就在 critique.md 註明。逐鏡打分(CLAUDE.md 要求每鏡 ≥ 4)。4b. 角色設計圖(plan.characters[].design):每鏡抽一格角色清楚的畫面,和設計圖拼成一張並排圖逐一比對(比例、眼睛、手腳、配件位置)。4c. 變化:從 0.5 秒總覽算出同一場景+機位佔片長的比例(> 40% 是 must_fix);高潮前的鋪陳有沒有一個構圖停太久。5. **第 1 輪就把觀眾看得出來的問題全部列進 must_fix**,不要留到後面的輪次。@@ -344,7 +403,7 @@ ${WOW}第 2 輪以後新的 must_fix 只能是:沒修好的、修改造成的新問題、或真正的 blocker(觀眾一眼看得出來);其他放 nice_to_have,不要每輪加碼。**nice_to_have 只能放觀眾用正常速度看不出來的東西。** 角色輪廓破損(凹口、缺角、斜切、手腳和身體接不起來)、沒有描邊的碎片、配件讀錯——只要在一般大小的成片裡看得到,就是 must_fix,不論是哪一輪發現的。-${EYE}+${EYE(p)}6. 寫 out/check/critique.json:{ "pass": false,"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": "具體" } ],@@ -365,17 +424,22 @@ ${EYE}${ENGINE(p)}## 步驟:修改成片${p.round === 'user' ? '(使用者回饋)' : `(評審第 ${p.round} 輪必修)`}-${p.message}--逐項修改(只動相關鏡頭;共用檔的改動要檢查所有用到的鏡頭),重新輸出 out/video.mp4,同步更新 plan.json(version +1、changelog)。+${p.message || '(全片性的必修這一輪沒有。)'}+${p.builderFixes?.length ? `+各段的製作 agent 已經修好自己段落的必修(${p.builderFixes.join('、')},每項附 before/after):不要重做那些鏡頭,+重新輸出成片時把它們一起渲染進去,並把它們的修正逐項併進 out/check/fixes.json(before/after 照抄它們的檔案;status 是 shared 的那幾項換你處理)。+` : ''}+逐項修改(只動相關鏡頭;共用檔的改動要檢查所有用到的鏡頭),每項先用截圖指令看改動處,全部改完再重新輸出 out/video.mp4 一次(整片渲染要好幾分鐘),同步更新 plan.json(version +1、changelog)。- 角色的動作一律改 pose 參數(手臂角度、手型、表情)或共用角色定義;**不准在鏡頭裡另外疊畫手臂、手、身體**(會產生肩膀接縫、描邊伸進衣服)。需要角色做 rig 做不到的動作,就在共用角色定義新增姿勢或手型,再重截設定圖確認。-- 改完用 hf_frames 截改動處前後 0.5 秒的全解析度畫面,照人眼清單自己看過再交;動作類的修正附 12fps 連續影格(clip_strip.py),不是單張。+- 改完用 hf_frames 截改動處前後 0.5 秒的全解析度畫面,照人眼清單自己看過再交;動作類的修正附**成片逐格**的連續影格(clip_strip.py --fps <成片 fps> 或 hf_frames.py --range a:b:f),+ 不是單張也不是 12fps:一格內換姿勢、瞬移只有逐格才看得出來(評審就是這樣抓到的)。+ 逐格的範圍從改動區間開始前 0.3 秒到結束後 0.3 秒——改出來的新問題幾乎都在改動和沒改的交界。- 修到高潮(plan.peaks)的,重做 clip_strip.py 對參考的並排圖,確認我們的爆點不輸參考片。- 改完重跑 motion_check.py out/video.mp4 --out out/check/motion,確認沒有新的黑格、硬切黑。- 重新輸出成片時用引擎的快取(render.mjs --frames 只會重渲改過的鏡頭),不要整片刪掉重渲。- 動到角色(翻轉、配件、姿勢)時,用 12fps 看整鏡,確認配件跟著身體轉、沒有新問題。-${EYE}+${EYE(p)}**每一項都要附證據**,寫 out/check/fixes.json:[ { "issue": "…", "shot": "S6", "time": 12.3, "change": "改了什麼", "before": "out/check/fixes/<n>_before.png", "after": "…_after.png", "status": "fixed|cannot" } ]before 從修改前的成片同一秒抽格、after 從新成片同一秒抽格(全解析度裁切到問題位置),自己打開確認真的改好;做不到的寫 cannot 和原因。diff --git a/app/server/types.ts b/app/server/types.tsindex 4ac5984..9098dfc 100644--- a/app/server/types.ts+++ b/app/server/types.ts@@ -1,5 +1,5 @@// Server-only shapes: build/production.json (written by the director at setup) and the variables each agent step gets.-import type { Config, Issue, Lang, NeedRequest, PlanCharacter } from '../shared/types.ts';+import type { Config, Issue, Lang, Quality, NeedRequest, PlanCharacter } from '../shared/types.ts';export interface Chunk { id: string; shots: string[] }export interface CastMember { id: string; name?: string; file: string; sheet: string }@@ -21,7 +21,7 @@ export interface Critique { must_fix?: { shot?: string; time?: number; issue: sttype NoVars = Record<never, never>;// Every prompt gets these…-export interface BaseVars { dir: string; brief: string; inputs: string[]; config: Config; lang: Lang }+export interface BaseVars { dir: string; brief: string; inputs: string[]; config: Config; lang: Lang; quality: Quality }// …plus the variables of its own step.export interface StepVars {style: NoVars;@@ -35,11 +35,11 @@ export interface StepVars {cast_fix: { issues: unknown[]; round: number | 'user' | 'shared'; character?: CastMember; rigFiles?: string[]; shared?: boolean; message?: string };build_chunk: { chunk: Chunk };shot_qa: { chunk: Chunk; shots: string[]; round: number; out: string };- fix_chunk: { chunk: Chunk; bad: ShotEntry[]; round: number; message?: string | null };+ fix_chunk: { chunk: Chunk; bad: ShotEntry[]; round: number | string; message?: string | null; final?: boolean };shared_fix: { chunk: Chunk; items: SharedItem[] };assemble: NoVars;critique: { round: number };- revise: { message: string; round: number | 'user' };+ revise: { message: string; round: number | 'user'; builderFixes?: string[] };}export type Phase = keyof StepVars;export type Prompts = { [P in Phase]: (p: BaseVars & StepVars[P]) => string };diff --git a/app/shared/types.ts b/app/shared/types.tsindex a5ba6c0..7490865 100644--- a/app/shared/types.ts+++ b/app/shared/types.ts@@ -12,7 +12,21 @@ export const ROUND_KEYS = ['castRounds', 'chunkRounds', 'finalRounds'] as const;export type RoundKey = (typeof ROUND_KEYS)[number];export type Rounds = Record<RoundKey, number>;+// Quality mode, chosen per project: how strictly reviewers check and how many fix rounds each gate gets.+// fast: only defects a viewer sees at once block, few rounds, never pauses at a limit (delivers and lists what is left);+// standard: per-frame checks on the climaxes; fine: per-frame checks on every pose change, the climaxes must beat the reference.+export const QUALITIES = ['fast', 'standard', 'fine'] as const;+export type Quality = (typeof QUALITIES)[number];+export interface QualityPreset extends Rounds {+ converge: number; // extra final-review rounds while the must-fix list keeps shrinking+ pauseAtLimit: boolean; // at a round limit: pause and ask the user (true) or carry on and list what is left (false)+}+// Minutes from plan approval to the finished film, for a 30 s film (scaled by length in the UI). From real runs:+// fine 167 and 222 min (6upkv, v8z8p); fast and standard are first estimates until measured.+export const QUALITY_MINUTES: Record<Quality, [number, number]> = { fast: [50, 80], standard: [100, 150], fine: [170, 230] };+export interface Config extends Rounds {+ presets: Record<Quality, QualityPreset>;builders: number;maxAgentsGlobal: number;maxReviews: number;@@ -61,10 +75,11 @@ export interface ChunkProgress {fixFirst?: boolean;open?: number;acceptedByUser?: boolean;+ acceptedAtLimit?: boolean; // fast mode: the round limit was reached and production carried on with `open` issues}export type CastCharState = 'queued' | 'reviewing' | 'fixing' | 'waiting_shared' | 'needs_user' | 'passed' | 'failed' | 'error';-export interface CastCharProgress { state: CastCharState; round: number; issues?: number }+export interface CastCharProgress { state: CastCharState; round: number; issues?: number; acceptedAtLimit?: boolean }export interface CastProgress {round: number;@@ -74,6 +89,7 @@ export interface CastProgress {lineup?: boolean;chars?: Record<string, CastCharProgress>;acceptedByUser?: boolean;+ acceptedAtLimit?: boolean;}export interface Pipeline {@@ -92,6 +108,7 @@ export interface Job {lang: Lang;reference: Reference;settings: Partial<Rounds>;+ quality?: Quality; // missing on projects made before modes existed: they ran the 'fine' linestage: Stage;failed?: Stage | null;error?: string | null;@@ -176,12 +193,14 @@ export interface Snapshot {checks: string[];video: string | null;critique: Record<string, unknown> | null;+ styleDistance: Record<string, unknown> | null; // out/check/style_distance.json: measured film vs reference (compare.py)cast: { sheets: string[]; review: Review | null };shots: string[];production: Record<string, unknown> | null;lyrics: unknown;requiredInputs: RequiredInput[];rounds: { values: Rounds; defaults: Rounds; min: number; max: number };+ quality: Quality;inputs: string[];}diff --git a/app/web/src/App.tsx b/app/web/src/App.tsxindex a753e4e..31a9f1d 100644--- a/app/web/src/App.tsx+++ b/app/web/src/App.tsx@@ -1,7 +1,7 @@import React, { useEffect, useMemo, useRef, useState } from 'react';-import type { AgentKind, AgentStatus, ProjectSummary, Rounds } from '../../shared/types.ts';+import type { AgentKind, AgentStatus, Config, ProjectSummary, Quality } from '../../shared/types.ts';import { api } from './api.ts';-import { I, BrandMark, Orb, Seg, AutoText, ago, RoundsEditor } from './ui.tsx';+import { I, BrandMark, Orb, Seg, AutoText, ago, RoundsEditor, QualityPicker, QUALITY_INFO, estimate } from './ui.tsx';import type { IconName, RoundValues } from './ui.tsx';import { Project, Status } from './Project.tsx';import { LANGS, lang as initialLang, setLang } from './i18n.ts';@@ -90,8 +90,10 @@ function Composer({ agents }: { agents?: Partial<AgentStatus> }) {const [file, setFile] = useState<File | null>(null), [url, setUrl] = useState(''), [linkMode, setLinkMode] = useState(false);const [brief, setBrief] = useState(''), [agent, setAgent] = useState<AgentKind>('claude'), [inputs, setInputs] = useState<File[]>([]);const [drag, setDrag] = useState(false), [busy, setBusy] = useState(false), [err, setErr] = useState('');- const [rounds, setRounds] = useState<RoundValues>({}), [roundsOpen, setRoundsOpen] = useState(false), [defaults, setDefaults] = useState<Rounds | null>(null);- useEffect(() => { api.config().then((c) => setDefaults({ castRounds: c.castRounds, chunkRounds: c.chunkRounds, finalRounds: c.finalRounds })).catch(() => {}); }, []);+ const [rounds, setRounds] = useState<RoundValues>({}), [roundsOpen, setRoundsOpen] = useState(false), [config, setConfig] = useState<Config | null>(null);+ const [quality, setQuality] = useState<Quality>('standard'), [qualityOpen, setQualityOpen] = useState(false);+ useEffect(() => { api.config().then(setConfig).catch(() => {}); }, []);+ const preset = config?.presets?.[quality], defaults = preset ? { castRounds: preset.castRounds, chunkRounds: preset.chunkRounds, finalRounds: preset.finalRounds } : null;const customRounds = Object.entries(rounds).filter(([, v]) => v != null);const pick = useRef<HTMLInputElement>(null), assets = useRef<HTMLInputElement>(null);const preview = useMemo(() => (file ? URL.createObjectURL(file) : null), [file]);@@ -104,7 +106,7 @@ function Composer({ agents }: { agents?: Partial<AgentStatus> }) {if (!ok) return; setBusy(true); setErr('');const f = new FormData();if (file) f.append('reference', file); else f.append('url', url.trim());- f.append('brief', brief); f.append('agent', agent); f.append('lang', document.documentElement.lang || 'zh-TW');+ f.append('brief', brief); f.append('agent', agent); f.append('quality', quality); f.append('lang', document.documentElement.lang || 'zh-TW');inputs.forEach((x) => f.append('inputs', x));customRounds.forEach(([k, v]) => f.append(k, String(v)));try { const { id } = await api.create(f); location.hash = `#/p/${id}`; } catch (e) { setErr((e as Error).message); setBusy(false); }@@ -141,8 +143,10 @@ function Composer({ agents }: { agents?: Partial<AgentStatus> }) {<button className={`tool-chip ${inputs.length ? 'on' : ''}`} onClick={() => assets.current!.click()} title="配樂、歌詞、圖片、Logo、自家角色設計圖"><I n="clip" />素材{inputs.length > 0 && <span className="n">{inputs.length}</span>}</button><input ref={assets} type="file" multiple hidden onChange={(e) => setInputs([...e.target.files!])} />- {defaults && <button className={`tool-chip ${customRounds.length ? 'on' : ''}`} onClick={() => setRoundsOpen(!roundsOpen)} aria-expanded={roundsOpen} title="每一關最多審查、修改幾輪">- <I n="sliders" />審查輪數{customRounds.length > 0 && <span className="n">{customRounds.length}</span>}</button>}+ <button className={`tool-chip ${quality !== 'standard' ? 'on' : ''}`} onClick={() => { setQualityOpen(!qualityOpen); setRoundsOpen(false); }} aria-expanded={qualityOpen} title="品質越高,檢查越細、時間越長">+ <I n="spark" />{QUALITY_INFO[quality].label}</button>+ {defaults && <button className={`tool-chip ${customRounds.length ? 'on' : ''}`} onClick={() => { setRoundsOpen(!roundsOpen); setQualityOpen(false); }} aria-expanded={roundsOpen} title="每一關最多審查、修改幾輪">+ <I n="sliders" /><span className="lbl-wide">審查輪數</span>{customRounds.length > 0 && <span className="n">{customRounds.length}</span>}</button>}<span className="grow" /><Seg value={agent} onChange={setAgent} options={[{ value: 'claude', label: <><span className="long">Claude Code</span><span className="short">Claude</span></>, disabled: agents && !agents.claude, title: agents?.claude || '未偵測到' },@@ -150,10 +154,11 @@ function Composer({ agents }: { agents?: Partial<AgentStatus> }) {<button className="send" disabled={!ok} onClick={submit} aria-label="開始">{busy ? <span className="spin-ring" /> : <I n="up" s={2.2} />}</button></div>{inputs.length > 0 && <div className="small faint" style={{ padding: '8px 10px 2px' }}>素材:{inputs.map((f) => f.name).join('、')}</div>}- {roundsOpen && defaults && <div className="comp-rounds fade-in"><RoundsEditor value={rounds} defaults={defaults} onChange={setRounds} /></div>}+ {qualityOpen && <div className="comp-rounds fade-in"><QualityPicker value={quality} onChange={(q) => { setQuality(q); setQualityOpen(false); }} /><div className="tiny faint" style={{ padding: '6px 2px 0' }}>時間以 30 秒的片、核准企劃後計算;做到一半或做完都可以再換(做完升級會從這支片接著修)。</div></div>}+ {roundsOpen && defaults && <div className="comp-rounds fade-in"><RoundsEditor value={rounds} defaults={defaults} onChange={setRounds} pauses={preset?.pauseAtLimit !== false} /></div>}</div>{err ? <div className="small" style={{ color: 'var(--red)', textAlign: 'center', marginTop: 12 }}>{err}</div>- : <div className="small faint" style={{ textAlign: 'center', marginTop: 12 }}>先拆解與企劃,你核准前不會開始生成 · Ctrl+Enter 送出</div>}+ : <div className="small faint" style={{ textAlign: 'center', marginTop: 12 }}><span>{QUALITY_INFO[quality].label}</span> <span>{estimate(quality)}</span> · <span>先拆解與企劃,你核准前不會開始生成</span> · <span>Ctrl+Enter 送出</span></div>}<div className="suggest">{SUGGEST.map((x) => <button key={x} onClick={() => setBrief(x)}>{x}</button>)}</div></>);diff --git a/app/web/src/Project.tsx b/app/web/src/Project.tsxindex f6289e6..ca736c9 100644--- a/app/web/src/Project.tsx+++ b/app/web/src/Project.tsx@@ -1,11 +1,11 @@import React, { useEffect, useMemo, useRef, useState } from 'react';import type { ReactNode } from 'react';-import type { InputKind, Job, Pipeline as PipelineState, RequiredInput, RoundKey, Rounds, Stage } from '../../shared/types.ts';+import type { InputKind, Job, Pipeline as PipelineState, Quality, RequiredInput, RoundKey, Rounds, Stage } from '../../shared/types.ts';import { api } from './api.ts';-import { I, Orb, Md, Ring, AutoText, useNow, clock, fmt, RoundsEditor } from './ui.tsx';+import { I, Orb, Md, Ring, AutoText, useNow, clock, fmt, RoundsEditor, QualityPicker, QUALITY_INFO } from './ui.tsx';import type { IconName, RoundValues } from './ui.tsx';import { Conversation, buildThread, STAGE_DO } from './Chat.tsx';-import type { Critique as CritiqueData, MustFix, PlanAsset, Shot as ShotData, SnapshotView, Tag } from './types.ts';+import type { Critique as CritiqueData, MustFix, PlanAsset, Shot as ShotData, SnapshotView, StyleDistance, Tag } from './types.ts';export const STATUS: Record<Stage, [string, string]> = {new: ['排隊中', ''], analyzing: ['拆解中', 'live'], styling: ['判斷風格', 'live'], styled: ['風格完成', ''], planning: ['企劃中', 'live'],@@ -58,7 +58,7 @@ export function Project({ id }: { id: string }) {<a className="back" href="#/"><I n="back" s={2.2} />專案</a><div className="p-head"><div className="grow"><h1>{s.plan?.title || job.title}</h1>{s.plan?.title && <div className="brief-line">{s.plan.logline || s.brief}</div>}</div>- <div className="p-head-r">{s.rounds && <RoundsButton id={id} r={s.rounds} />}<Status stage={job.stage} /></div>+ <div className="p-head-r">{s.quality && <QualityButton id={id} q={s.quality} stage={job.stage} durS={s.plan?.format?.duration_s} />}{s.rounds && <RoundsButton id={id} r={s.rounds} pauses={s.quality !== 'fast'} />}<Status stage={job.stage} /></div></div><div className="progress">{STEPS.map((x, i) => {@@ -385,7 +385,31 @@ function Needs({ id, s, file, onZoom }: { id: string; s: SnapshotView; file: Fil}// ---------- review/fix round limits (header button + panel) -----------function RoundsButton({ id, r }: { id: string; r: SnapshotView['rounds'] }) {+// ---------- quality mode (header button + panel) ----------+// Mid-production a change applies from the next check; on a finished film a stricter mode starts a new final review.+function QualityButton({ id, q, stage, durS }: { id: string; q: Quality; stage: Stage; durS?: number }) {+ const [open, setOpen] = useState(false), [saving, setSaving] = useState(false), [err, setErr] = useState(''), ref = useRef<HTMLDivElement>(null);+ useEffect(() => { if (!open) return; const k = (e: PointerEvent) => { if (!ref.current?.contains(e.target as Node)) setOpen(false); }; addEventListener('pointerdown', k); return () => removeEventListener('pointerdown', k); }, [open]);+ const done = stage === 'done', before = ['new', 'analyzing', 'styling', 'styled', 'planning', 'replanning', 'plan_review'].includes(stage);+ const pick = async (next: Quality) => {+ if (next === q) { setOpen(false); return; }+ setSaving(true); setErr('');+ try { await api.quality(id, next); setOpen(false); } catch (e) { setErr((e as Error).message); } finally { setSaving(false); }+ };+ return (+ <div className="rd-wrap" ref={ref}>+ <button className="tool-chip" onClick={() => setOpen(!open)} aria-expanded={open} title="品質越高,檢查越細、時間越長"><I n="spark" />{QUALITY_INFO[q].label}</button>+ {open && <div className="rd-pop">+ <div className="row" style={{ marginBottom: 4 }}><b style={{ fontSize: 15 }}>品質</b><span className="grow" />{saving && <span className="spin-ring" style={{ width: 12, height: 12 }} />}</div>+ <div className="tiny muted" style={{ marginBottom: 8 }}>{done ? '片已經做好:選更高的品質,會用新的標準重新評審,從這支片接著修。' : before ? '核准企劃後開始計時;時間依片長估計。' : '做到一半也可以改,從下一次檢查開始生效。'}</div>+ <QualityPicker value={q} current={q} durS={durS} onChange={pick} disabled={saving} showTime={!done} />+ {err && <div className="small" style={{ color: 'var(--red)', marginTop: 6 }}>{err}</div>}+ </div>}+ </div>+ );+}++function RoundsButton({ id, r, pauses = true }: { id: string; r: SnapshotView['rounds']; pauses?: boolean }) {const [open, setOpen] = useState(false), [saving, setSaving] = useState(false), [err, setErr] = useState(''), ref = useRef<HTMLDivElement>(null);const [local, setLocal] = useState(r.values);useEffect(() => { if (!saving) setLocal(r.values); }, [r.values.castRounds, r.values.chunkRounds, r.values.finalRounds]);@@ -403,7 +427,7 @@ function RoundsButton({ id, r }: { id: string; r: SnapshotView['rounds'] }) {{open && <div className="rd-pop"><div className="row" style={{ marginBottom: 4 }}><b style={{ fontSize: 15 }}>審查輪數</b><span className="grow" />{saving ? <span className="spin-ring" style={{ width: 12, height: 12 }} /> : <span className="tiny faint">已自動儲存</span>}</div><div className="tiny muted" style={{ marginBottom: 6 }}>做到一半也可以改,從下一次檢查開始生效。</div>- <RoundsEditor value={Object.fromEntries(Object.entries(local).map(([k, v]) => [k, v === r.defaults[k as RoundKey] ? null : v]))} defaults={r.defaults} min={r.min} max={r.max} onChange={change} />+ <RoundsEditor value={Object.fromEntries(Object.entries(local).map(([k, v]) => [k, v === r.defaults[k as RoundKey] ? null : v]))} defaults={r.defaults} min={r.min} max={r.max} onChange={change} pauses={pauses} />{err && <div className="small" style={{ color: 'var(--red)', marginTop: 6 }}>{err}</div>}</div>}</div>@@ -412,6 +436,7 @@ function RoundsButton({ id, r }: { id: string; r: SnapshotView['rounds'] }) {// ---------- production line ----------const CHUNK: Record<string, [string, string]> = { queued: ['排隊中', ''], building: ['製作中', 'live'], reviewing: ['審查中', 'live'], fixing: ['修正中', 'warn'], passed: ['通過', 'ok'], failed: ['未通過', 'bad'], error: ['錯誤', 'bad'], needs_user: ['等你提供', 'warn'], shared_fix: ['導演改共用檔', 'live'], waiting_cast: ['做好了,等角色關', ''], built: ['做好了,等角色關', ''] };+const AT_LIMIT: [string, string] = ['到上限,先繼續', 'warn']; // fast mode: round limit reached, production carried onconst PHASES: [NonNullable<PipelineState['phase']>, string, IconName][] = [['setup', '建置', 'layers'], ['cast', '角色關', 'user'], ['shots', '分段製作', 'film'], ['assemble', '組裝', 'play'], ['final', '最後評審', 'mag']];function Pipeline({ s, file, onZoom }: { s: SnapshotView; file: FileUrl; onZoom: Zoom }) {const p: PipelineState = s.job.pipeline || {}, rv = s.cast?.review, chunks = Object.entries(p.chunks || {}), R: Partial<Rounds> = s.rounds?.values || {};@@ -429,13 +454,13 @@ function Pipeline({ s, file, onZoom }: { s: SnapshotView; file: FileUrl; onZoom:<div className="row" style={{ marginTop: 22, marginBottom: 10 }}><div className="sub-h" style={{ margin: 0 }}>角色設定圖</div><span className="grow" />{p.cast?.state && <span className={`cap ${p.cast.pass ? 'ok' : p.cast.state === 'failed' ? 'bad' : p.cast.state === 'fixing' ? 'warn' : 'live'}`}>{p.cast.pass ? <><I n="check" s={2.4} />已通過</> : ({ reviewing: '審查中', fixing: '導演修正中', failed: '未通過' } as Record<string, string>)[p.cast.state] || p.cast.state}{p.cast.round > 1 ? ` · 第 ${p.cast.round} / ${R.castRounds} 輪` : ''}</span>}</div><div className="scroller">{(s.cast.sheets.filter((f) => /sheet/i.test(f.split('/').pop()!)).length ? s.cast.sheets.filter((f) => /sheet/i.test(f.split('/').pop()!)) : s.cast.sheets).map((f) => <img key={f} className="shot-img" src={file(f)} onClick={() => onZoom(file(f))} />)}</div>- {p.cast?.chars && <div className="chunks" style={{ marginTop: 12 }}>{Object.entries(p.cast.chars).map(([k, c]) => { const [t, cl] = CHUNK[c.state] || (c.state === 'waiting_shared' ? ['等導演改骨架', 'warn'] : [c.state, '']); return <div key={k} className={`chunk ${c.state}`}><div className="ch-h"><b style={{ fontSize: 15 }}>{(s.production?.characters || []).find((x) => x.id === k)?.name || k}</b><span className="grow" /><span className={`cap ${cl}`} style={{ height: 22, fontSize: 11.5 }}>{cl === 'live' && <span className="dot live" />}{t}</span></div>{c.round > 1 && <div className="tiny faint">第 {c.round} / {R.castRounds} 輪</div>}</div>; })}</div>}+ {p.cast?.chars && <div className="chunks" style={{ marginTop: 12 }}>{Object.entries(p.cast.chars).map(([k, c]) => { const [t, cl] = c.acceptedAtLimit ? AT_LIMIT : CHUNK[c.state] || (c.state === 'waiting_shared' ? ['等導演改骨架', 'warn'] : [c.state, '']); return <div key={k} className={`chunk ${c.state}`}><div className="ch-h"><b style={{ fontSize: 15 }}>{(s.production?.characters || []).find((x) => x.id === k)?.name || k}</b><span className="grow" /><span className={`cap ${cl}`} style={{ height: 22, fontSize: 11.5 }}>{cl === 'live' && <span className="dot live" />}{t}</span></div>{c.round > 1 && <div className="tiny faint">第 {c.round} / {R.castRounds} 輪</div>}</div>; })}</div>}{rv && !rv.pass && (rv.issues || []).length > 0 && <ul className="issues" onClick={(e) => (e.target as Element).closest('li')?.classList.toggle('open')}>{rv.issues!.map((x, i) => <li key={i}><span className="tagc">{x.character || '角色'}</span><span>{x.what && <b>{x.what}:</b>}{x.issue}{x.fix && <span className="faint"> → {x.fix}</span>}</span></li>)}</ul>}</>}{chunks.length > 0 && <><div className="row" style={{ marginTop: 22, marginBottom: 10 }}><div className="sub-h" style={{ margin: 0 }}>分段</div><span className="grow" /><span className="small faint">{passed} / {chunks.length} 段通過 · 每段做完立刻由獨立審查員檢查</span></div>- <div className="chunks">{chunks.map(([k, v]) => { const [t, c] = CHUNK[v.state] || [v.state, '']; return (+ <div className="chunks">{chunks.map(([k, v]) => { const [t, c] = v.acceptedAtLimit ? AT_LIMIT : CHUNK[v.state] || [v.state, '']; return (<div key={k} className={`chunk ${v.state}`}><div className="ch-h"><b>{k}</b><span className="grow" /><span className={`cap ${c}`} style={{ height: 22, fontSize: 11.5 }}>{c === 'live' && <span className="dot live" />}{t}</span></div><div className="small muted">{(v.shots || []).join(' · ')}</div>@@ -509,9 +534,29 @@ function Result({ s, file, onZoom }: { s: SnapshotView; file: FileUrl; onZoom: Z</div></div>}{s.critique && <Critique c={s.critique} onSeek={seek} id={id} stage={s.job.stage} file={file} onZoom={onZoom} />}+ {s.styleDistance && <Measured sd={s.styleDistance} overlay={s.checks.find((c) => c.endsWith('fingerprint_overlay.png'))} file={file} onZoom={onZoom} />}</section>);}+// Measured, not judged: compare.py's style_distance.json (scripts/perception) — 0–100, higher = closer to the reference.+const COMPONENT: Record<string, string> = { camera: '運鏡', palette: '整體色調', pace: '節奏密度', look: '逐鏡色彩', rhythm: '剪接對拍', frames: '畫面構成', tension: '張力起伏', peaks: '高潮形狀' };+function Measured({ sd, overlay, file, onZoom }: { sd: StyleDistance; overlay?: string; file: FileUrl; onZoom: Zoom }) {+ const comps = Object.entries(sd.components || {}).filter(([, v]) => typeof v?.score === 'number') as [string, { score: number }][];+ const findings = (sd.findings || []).filter((f) => f.severity === 'major').slice(0, 8);+ const head = ([['風格', sd.style], ['結構', sd.structure], ['整體', sd.overall]] as const).filter(([, v]) => typeof v === 'number') as [string, number][];+ return (+ <div className="critique measured">+ <div className="row"><div className="avatar-ai"><I n="chart" /></div><b>和參考片的相似度</b><span className="grow" />+ {head.map(([k, v]) => <span key={k} className="cap">{`${k} ${Math.round(v)}`}</span>)}</div>+ <p className="small muted" style={{ margin: '10px 0 0' }}>逐格量測和參考片有多像(0–100,越高越像):風格=看起來、動起來像不像;結構=有沒有照參考段落的起伏走。這不是品質分數——換媒材、換色調這類刻意的不同也會讓它變低;品質看上面的獨立評審。</p>+ {comps.length > 0 && <div className="scores">{comps.map(([k, v]) => <div key={k} className="score"><div className="row"><span>{COMPONENT[k] || k}</span><b>{Math.round(v.score)}</b></div>+ <div className="bar"><i style={{ width: `${Math.max(2, Math.min(100, v.score))}%` }} /></div></div>)}</div>}+ {overlay && <img className="shot-img" style={{ marginTop: 12 }} src={file(overlay)} onClick={() => onZoom(file(overlay))} title="橘:參考片(對齊到我們的時間軸)・藍:我們" />}+ {findings.length > 0 && <ul className="issues" onClick={(e) => (e.target as Element).closest('li')?.classList.toggle('open')}>+ {findings.map((f, i) => <li key={i}><span className="tagc">{COMPONENT[f.component] || f.component} · {f.where}</span><span translate="no">{f.text}</span></li>)}</ul>}+ </div>+ );+}const VERDICT = { ours_better: ['贏過參考片', 'ok'], equal: ['和參考片同級', 'ok'], ref_better: ['輸給參考片', 'bad'] } as const;function Critique({ c, onSeek, id, stage, file, onZoom }: { c: CritiqueData; onSeek?: (t: number) => void; id: string; stage: Stage; file: FileUrl; onZoom: Zoom }) {const sc = Object.entries(c.scores || {}), must = (c.must_fix || []).filter((m): m is MustFix => !!m), [busy, setBusy] = useState(false);diff --git a/app/web/src/api.ts b/app/web/src/api.tsindex ad756ab..7b72e10 100644--- a/app/web/src/api.ts+++ b/app/web/src/api.ts@@ -1,5 +1,5 @@// Thin client for the ReelMimic server.-import type { AgentStatus, Config, ProjectSummary, RoundKey, ServerEvent, Snapshot } from '../../shared/types.ts';+import type { AgentStatus, Config, ProjectSummary, Quality, RoundKey, ServerEvent, Snapshot } from '../../shared/types.ts';import type { MessageMeta } from './types.ts';type Ok = { ok: true };const j = async <T>(r: Response): Promise<T> => { const d: unknown = await r.json().catch(() => ({})); if (!r.ok) throw new Error((d as { error?: string }).error || r.statusText); return d as T; };@@ -17,6 +17,7 @@ export const api = {waive: (id: string, input: string) => fetch(`/api/projects/${id}/waive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input }) }).then(j<Snapshot>),config: () => fetch('/api/config').then(j<Config>),settings: (id: string, body: Partial<Record<RoundKey, number | ''>>) => fetch(`/api/projects/${id}/settings`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(j<Snapshot>),+ quality: (id: string, quality: Quality) => fetch(`/api/projects/${id}/quality`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ quality }) }).then(j<Snapshot>),accept: (id: string) => fetch(`/api/projects/${id}/accept`, { method: 'POST' }).then(j<Ok>),resume: (id: string) => fetch(`/api/projects/${id}/resume`, { method: 'POST' }).then(j<Ok>),cancel: (id: string) => fetch(`/api/projects/${id}/cancel`, { method: 'POST' }).then(j<Ok>),diff --git a/app/web/src/i18n.ts b/app/web/src/i18n.tsindex c2c3f77..b147482 100644--- a/app/web/src/i18n.ts+++ b/app/web/src/i18n.ts@@ -29,6 +29,16 @@ const EN: Record<string, string> = {'換影片': 'Change video', '移除': 'Remove', '素材': 'Assets', '配樂、歌詞、圖片、Logo、自家角色設計圖': 'Music, lyrics, images, logos, your own character designs','開始': 'Start', '未偵測到': 'Not found', '請選擇影片檔(mp4 / mov / webm)': 'Please choose a video file (mp4 / mov / webm)','先拆解與企劃,你核准前不會開始生成 · Ctrl+Enter 送出': 'Analysis and planning come first — nothing renders until you approve · Ctrl+Enter to send',+ '先拆解與企劃,你核准前不會開始生成': 'Analysis and planning come first — nothing renders until you approve', 'Ctrl+Enter 送出': 'Ctrl+Enter to send',+ // quality modes+ '到上限,先繼續': 'At the limit, carried on', '快速': 'Fast', '標準': 'Standard', '精緻': 'Fine', '品質': 'Quality', '目前': 'current', '品質越高,檢查越細、時間越長': 'Higher quality: closer checks, more time',+ '先看方向:只修一眼看得出的硬傷,到上限就先交件': 'See the direction first: fixes only defects you notice at once, delivers at the round limit',+ '大部分情況:高潮逐格檢查,其他鏡頭看連續影格': 'Most projects: climaxes checked frame by frame, other shots as motion strips',+ '要交出去的成品:每個姿勢變化逐格檢查,高潮要贏參考片': 'A film to deliver: every pose change checked frame by frame, climaxes must beat the reference',+ '時間以 30 秒的片、核准企劃後計算;做到一半或做完都可以再換(做完升級會從這支片接著修)。': 'Times are for a 30 s film, counted from plan approval. You can switch mid-production or after (upgrading a finished film continues from it).',+ '片已經做好:選更高的品質,會用新的標準重新評審,從這支片接著修。': 'The film is done: pick a higher quality and it goes back to the final review under the stricter bar, fixed from this film.',+ '核准企劃後開始計時;時間依片長估計。': 'Timed from plan approval; estimated from the film length.',+ '快速模式到了上限會先交件,把剩下的問題列出來;之後可以升級品質接著修。': 'In Fast mode a limit delivers the film and lists what is left; upgrade the quality later to fix it.','做一支類似風格的 30 秒影片,主軸是愛情,要有好笑的反轉': 'A 30-second video in this style about love, with a funny twist','同樣的剪法,改成介紹我們的新 App': 'Same editing, but introducing our new app','保留節奏和轉場,主題換成親情,直式 9:16': 'Keep the rhythm and transitions, make it about family, vertical 9:16',@@ -38,6 +48,10 @@ const EN: Record<string, string> = {'前製企劃': 'Pre-production', '分鏡、運鏡、素材、定調畫面,和你來回對焦': 'Storyboard, camera, assets and style frames, refined with you','關卡審查': 'Gated review', '角色、每一段都即時檢查,過關才往下做': 'Characters and every segment are checked as they are made','專案': 'Projects', '剛剛': 'just now',+ '和參考片的相似度': 'Similarity to the reference', '整體色調': 'Palette', '節奏密度': 'Pace', '逐鏡色彩': 'Colour per shot',+ '剪接對拍': 'Cuts on the beat', '畫面構成': 'Composition', '張力起伏': 'Tension arc', '高潮形狀': 'Climax shape',+ '逐格量測和參考片有多像(0–100,越高越像):風格=看起來、動起來像不像;結構=有沒有照參考段落的起伏走。這不是品質分數——換媒材、換色調這類刻意的不同也會讓它變低;品質看上面的獨立評審。':+ 'How close the film measures to the reference, frame by frame (0–100, higher = closer): style = does it look and move like it; structure = does it follow the arc of the section it clones. Not a quality score — deliberate differences such as another medium or palette lower it too; for quality, see the independent review above.',// status'排隊中': 'Queued', '拆解中': 'Analyzing', '判斷風格': 'Styling', '風格完成': 'Styled', '企劃中': 'Planning', '等你確認企劃': 'Awaiting your approval','修改企劃': 'Revising plan', '生產中': 'Producing', '等你提供': 'Needs your input', '評審中': 'Reviewing', '修改中': 'Revising', '完成': 'Done', '需要處理': 'Needs attention',@@ -110,9 +124,10 @@ const EN: Record<string, string> = {};// text with numbers / names in itconst EN_RE: [RegExp, string][] = [+ [/^約 (\d+)–(\d+) 分鐘$/, 'about $1–$2 min'], [/^約 ([\d.]+)–([\d.]+) 小時$/, 'about $1–$2 h'],[/^(\d+) 秒$/, '$1 s'], [/^(\d+) 分 (\d+) 秒$/, '$1 min $2 s'], [/^(\d+) 小時 (\d+) 分$/, '$1 h $2 min'],[/^(\d+) 分鐘前$/, '$1 min ago'], [/^(\d+) 小時前$/, '$1 h ago'], [/^(\d+) 天前$/, '$1 d ago'],- [/^(\d+) 項必修$/, '$1 must-fix'], [/^· (\d+) 項待你提供$/, '· $1 need your input'], [/^(\d+) 張$/, '$1 frames'], [/^張$/, 'frames'],+ [/^(\d+) 項必修$/, '$1 must-fix'], [/^風格 (\d+)$/, 'Style $1'], [/^結構 (\d+)$/, 'Structure $1'], [/^整體 (\d+)$/, 'Overall $1'], [/^· (\d+) 項待你提供$/, '· $1 need your input'], [/^(\d+) 張$/, '$1 frames'], [/^張$/, 'frames'],[/^(\d+) 個 agent 同時工作中$/, '$1 agents working'], [/^· (\d+) 個 agent 同時工作$/, '· $1 agents working'],[/^· 第 (\d+) 輪$/, '· round $1'], [/^第 (\d+) 輪$/, 'round $1'], [/^第$/, 'round'], [/^輪審查$/, 'review'], [/^輪$/, ''],[/^平均鏡頭 · ([\d.]+) 拍$/, 'avg shot · $1 beats'], [/^鏡$/, 'shots'], [/^項$/, 'items'], [/^筆 · 完整紀錄在$/, 'entries · full log in'], [/^顯示最近$/, 'Showing the latest'],diff --git a/app/web/src/styles.css b/app/web/src/styles.cssindex 4989a59..745f518 100644--- a/app/web/src/styles.css+++ b/app/web/src/styles.css@@ -180,7 +180,7 @@ h1, h2, h3 { font-family: var(--font-display); margin: 0; letter-spacing: -.022e.composer textarea { display: block; width: 100%; min-height: 96px; max-height: 280px; resize: none; border: 0; outline: 0; background: none; padding: 12px 10px 6px; font-size: 16.5px; line-height: 1.55; color: var(--label); }.composer textarea::placeholder { color: var(--label-3); }.comp-bar { display: flex; align-items: center; gap: 6px; padding: 4px 2px 0; flex-wrap: wrap; }-.tool-chip { display: inline-flex; align-items: center; gap: 6px; height: 34px; padding: 0 12px; border-radius: 99px; font-size: 13.5px; color: var(--label-2); transition: background .2s, color .2s; }+.tool-chip { display: inline-flex; align-items: center; gap: 6px; height: 34px; padding: 0 12px; border-radius: 99px; font-size: 13.5px; white-space: nowrap; flex-shrink: 0; color: var(--label-2); transition: background .2s, color .2s; }.tool-chip:hover { background: var(--fill-2); color: var(--label); }.tool-chip.on { background: var(--accent-soft); color: var(--accent-ink); }.tool-chip .n { font-size: 11.5px; font-weight: 700; min-width: 18px; height: 18px; border-radius: 9px; background: var(--accent); color: #fff; display: grid; place-items: center; padding: 0 5px; }@@ -397,6 +397,9 @@ h1, h2, h3 { font-family: var(--font-display); margin: 0; letter-spacing: -.022e.score .pips { display: grid; grid-template-columns: repeat(5, 1fr); gap: 3px; }.score .pips i { height: 5px; border-radius: 3px; background: var(--fill); }.score .pips i.on { background: var(--green); }+.score .bar { height: 5px; border-radius: 3px; background: var(--fill); overflow: hidden; }+.score .bar i { display: block; height: 100%; border-radius: 3px; background: var(--label-2); } /* similarity, not good or bad: neutral */+.critique.measured { margin-top: 14px; }.score.low .pips i.on { background: var(--orange); }.critique { margin-top: 18px; padding: 16px; border-radius: var(--r); background: var(--surface-2); }@@ -497,7 +500,9 @@ h1, h2, h3 { font-family: var(--font-display); margin: 0; letter-spacing: -.022e.comp-bar { flex-wrap: nowrap; }.seg button { padding: 0 9px; font-size: 12.5px; }.seg .long { display: none; }- .tool-chip { padding: 0 8px; }+ .tool-chip { padding: 0 8px; gap: 4px; }+ .comp-bar .lbl-wide { display: none; }+ .comp-bar { gap: 2px; }.card { padding: 18px 16px; border-radius: 20px; }.livebar .small { display: none; }.p-head h1 { font-size: 26px; }@@ -629,6 +634,14 @@ h1, h2, h3 { font-family: var(--font-display); margin: 0; letter-spacing: -.022e.rd-note { padding-top: 8px; line-height: 1.5; }.comp-rounds { margin: 10px 6px 4px; padding: 6px 14px 10px; border-radius: 14px; background: var(--fill-2); }.comp-rounds .rd-row:last-of-type { border-bottom: 0; }+.q-pick { display: grid; gap: 6px; }+.q-opt { display: block; width: 100%; text-align: left; padding: 9px 12px; border-radius: 12px; border: 1px solid var(--sep); background: transparent; color: inherit; font: inherit; cursor: pointer; transition: background .15s, border-color .15s; }+.q-opt:hover:not(:disabled) { background: var(--fill-2); }+.q-opt.on { border-color: var(--accent); background: var(--fill-2); }+.q-opt:disabled { opacity: .6; cursor: default; }+.q-opt .row { gap: 8px; margin-bottom: 2px; }+.q-opt b { font-size: 14px; font-weight: 600; }+.q-time { color: var(--accent); font-variant-numeric: tabular-nums; white-space: nowrap; }/* required inputs: at the top of the page while the plan is being written / reviewed */.card.req-top { box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--orange, #FF9F0A) 55%, transparent), var(--shadow-2); }diff --git a/app/web/src/types.ts b/app/web/src/types.tsindex 80b890f..7084b8b 100644--- a/app/web/src/types.ts+++ b/app/web/src/types.ts@@ -32,13 +32,17 @@ export type Route = { engine?: string; style?: string; medium?: string; confidenexport type MustFix = { shot?: string; time?: number | null; issue: string; fix?: string };export type PeakVerdict = { id: string; ours?: number[]; ref?: number[]; strip?: string; verdict?: 'ours_better' | 'equal' | 'ref_better'; why?: string };export type Critique = { pass?: boolean; summary?: string; scores?: Record<string, number>; must_fix?: (MustFix | null)[]; peaks?: PeakVerdict[] };+export type Finding = { component: string; where: string; severity: 'major' | 'minor' | string; text: string };+export type StyleDistance = { overall?: number | null; style?: number | null; structure?: number | null;+ components?: Record<string, { score?: number | null }>; findings?: Finding[] };export type Production = { characters?: { id: string; name?: string }[] };export type LyricLine = { start?: number; end?: number; text: string; match: number };export type Lyrics = { lines?: LyricLine[] };// the project snapshot with those files narrowed (cast once where it is loaded)-export type SnapshotView = Omit<Snapshot, 'report' | 'route' | 'plan' | 'critique' | 'production' | 'lyrics'> & {+export type SnapshotView = Omit<Snapshot, 'report' | 'route' | 'plan' | 'critique' | 'production' | 'lyrics' | 'styleDistance'> & {report: Report | null; route: Route | null; plan: PlanView | null; critique: Critique | null; production: Production | null; lyrics: Lyrics | null;+ styleDistance: StyleDistance | null;};// what a chat message is about (a shot, a moment in the film, or an open question from the plan)diff --git a/app/web/src/ui.tsx b/app/web/src/ui.tsxindex 774ca80..2cdada6 100644--- a/app/web/src/ui.tsx+++ b/app/web/src/ui.tsx@@ -1,6 +1,7 @@import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import type { CSSProperties, ReactNode, TextareaHTMLAttributes } from 'react';-import type { RoundKey, Rounds } from '../../shared/types.ts';+import { QUALITIES, QUALITY_MINUTES } from '../../shared/types.ts';+import type { Quality, RoundKey, Rounds } from '../../shared/types.ts';// ---------- icons (SF-Symbols-like strokes) ----------const P = {@@ -23,6 +24,7 @@ const P = {search: 'M10.5 4.5a6 6 0 1 1 0 12 6 6 0 0 1 0-12ZM15 15l5 5',image: 'M4 5h16v14H4zM4 16l5-5 4 4 2.5-2.5L20 17M15.5 9.2a1.2 1.2 0 1 0 0 .1',wand: 'M5 19 16 8M14 6l4 4M18 3v3M16.5 4.5h3M20 9.5v2M19 10.5h2',+ chart: 'M4 20h16M7 16v-5M12 16V6M17 16v-8',pause: 'M8.5 5.5v13M15.5 5.5v13',alert: 'M12 4 21 19.5H3zM12 10v4.5M12 17.2v.1',download: 'M12 4.5V15M7 10.5l5 5 5-5M5 19.5h14',@@ -145,7 +147,7 @@ export const ROUND_FIELDS: [RoundKey, string, string][] = [['finalRounds', '最後評審', '自動修改最多幾輪'],];export type RoundValues = Partial<Record<RoundKey, number | null>>;-export function RoundsEditor({ value = {}, defaults, min = 1, max = 10, onChange, disabled }: { value?: RoundValues; defaults: Rounds; min?: number; max?: number; onChange: (next: RoundValues) => void; disabled?: boolean }) {+export function RoundsEditor({ value = {}, defaults, min = 1, max = 10, onChange, disabled, pauses = true }: { value?: RoundValues; defaults: Rounds; min?: number; max?: number; onChange: (next: RoundValues) => void; disabled?: boolean; pauses?: boolean }) {const set = (k: RoundKey, v: number) => onChange({ ...value, [k]: v === defaults[k] ? null : v });return (<div className="rounds">@@ -163,9 +165,36 @@ export function RoundsEditor({ value = {}, defaults, min = 1, max = 10, onChange);})}<div className="rd-foot">- <div className="tiny faint rd-note">到了上限還沒通過,會暫停請你決定,不會一直來回修改。輪數多,品質有機會更好,但時間和 AI 用量也會增加。</div>+ <div className="tiny faint rd-note">{pauses ? '到了上限還沒通過,會暫停請你決定,不會一直來回修改。輪數多,品質有機會更好,但時間和 AI 用量也會增加。' : '快速模式到了上限會先交件,把剩下的問題列出來;之後可以升級品質接著修。'}</div>{ROUND_FIELDS.some(([k]) => value[k] != null && value[k] !== defaults[k]) && <button className="btn sm plain" disabled={disabled} onClick={() => onChange(Object.fromEntries(ROUND_FIELDS.map(([k]) => [k, null])))}>恢復預設</button>}</div></div>);}++// ---------- quality modes ----------+export const QUALITY_INFO: Record<Quality, { label: string; what: string }> = {+ fast: { label: '快速', what: '先看方向:只修一眼看得出的硬傷,到上限就先交件' },+ standard: { label: '標準', what: '大部分情況:高潮逐格檢查,其他鏡頭看連續影格' },+ fine: { label: '精緻', what: '要交出去的成品:每個姿勢變化逐格檢查,高潮要贏參考片' },+};+// Minutes after approval, scaled from the 30 s figures by film length (setup and review have a fixed part).+export function estimate(q: Quality, durS?: number | null): string {+ const k = durS ? 0.3 + 0.7 * Math.min(durS, 180) / 30 : 1, [a, b] = QUALITY_MINUTES[q].map((m) => m * k);+ if (b < 100) { const r = (m: number) => Math.max(5, Math.round(m / 5) * 5); return `約 ${r(a)}–${r(b)} 分鐘`; }+ const h = (m: number) => String(Math.max(0.5, Math.round(m / 30) / 2));+ return `約 ${h(a)}–${h(b)} 小時`;+}+// A row of the three modes with what each does and how long it takes. `current` marks the project's mode (project page).+export function QualityPicker({ value, onChange, durS, current, disabled, showTime = true }: { value: Quality; onChange: (q: Quality) => void; durS?: number | null; current?: Quality; disabled?: boolean; showTime?: boolean }) {+ return (+ <div className="q-pick" role="radiogroup">+ {QUALITIES.map((q) => (+ <button key={q} role="radio" aria-checked={value === q} className={`q-opt ${value === q ? 'on' : ''}`} disabled={disabled} onClick={() => onChange(q)}>+ <div className="row"><b>{QUALITY_INFO[q].label}</b>{current === q && <span className="tiny faint">目前</span>}<span className="grow" />{showTime && <span className="tiny q-time">{estimate(q, durS)}</span>}</div>+ <div className="tiny muted">{QUALITY_INFO[q].what}</div>+ </button>+ ))}+ </div>+ );+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex ba0d749..642407d 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -16,6 +16,7 @@ Server (app/server)├─ index.ts HTTP API, uploads, SSE, project files (/files/:id/*)├─ env.ts loads ~/.reelmimic/secrets.json at startup├─ jobs.ts workflow state machine + production scheduling (order, parallelism, pausing)+ ├─ outputs.ts checks agent outputs: the JSON files a step must write parse and have the shape jobs.ts reads├─ prompts.ts the instructions each step gives its agent (edits apply on the next turn, no restart)└─ agents/index.ts agent adapters: Claude Code / Codex → one event stream│ spawn (prompt on stdin, events streamed on stdout)@@ -49,7 +50,10 @@ new → analyzing → styling → planning → plan_review ⇄ replanning| revising | director agent | `out/video.mp4`, `out/check/fixes.json` (before/after crops for every fix) |**Files decide completion**: `turn()` records the modification time of the required files and checks after the agent-turn whether they were updated; if not, the job stops in `error` and the step can be retried.+turn whether they were updated, and that the JSON ones parse and have the shape the orchestrator reads (`outputs.ts`).+A file that does not gets one repair turn in the same agent conversation (it knows what it meant); if it is still+broken the job stops in `error` naming the file, and the step can be retried. Without this a critique.json with a+trailing comma read as "no must-fix items" and the film was delivered as passed.On server start, jobs still marked as working are flagged as interrupted (`recoverOrphans`); a retry continues from thecurrent files.@@ -59,23 +63,37 @@ current files.setup (director): shared assets, one definition file per character, character sheets, segments (build/production.json)│├──────────────── cast gate (runs alongside shot building) ─────────────┐- │ per character: reviewer (fresh) ⇄ fixer agent, up to 3 rounds │+ │ per character: reviewer (fresh) ⇄ fixer agent, up to N rounds (mode) ││ items that need the shared rig changed → director fixes → re-review ││ all passed → line-up check (relative scale, interactions) ││ │├── segments: up to BUILDERS builders in parallel, 1–4 shots each ││ each finished shot writes <shot>.done.json → a fresh shot reviewer ││ is dispatched at once; reviews wait for the cast gate ←────────────┘- │ → failing shots go back to the same builder → only those are re-reviewed, up to 3 rounds+ │ → failing shots go back to the same builder → only those are re-reviewed, up to N rounds (mode)│ → shared-file problems: the director fixes them on the spot (one at a time, additive only),│ the builder applies them in the same round▼assemble (director): assembly, mix, full render▼-final critic (fresh): only what spans segments — seams, continuity, pacing, consistent captions; verifies every-earlier "fixed" first ⇄ director revises (up to 2 rounds)+final critic (fresh): the climaxes against the reference, then the whole film; verifies every earlier "fixed" first+ ⇄ items inside one segment go back to that segment's builder (all segments at once); the rest to the director,+ who renders once (rounds by mode, more while the must-fix list keeps halving)```+**Quality modes** (`job.quality`, picked when a project is created, changeable at any time): one table in+`jobs.ts` (`CONFIG.presets`) sets the rounds per gate, and the prompts read the mode to decide what blocks.++| mode | rounds cast / shots / final | what blocks | at a round limit |+|---|---|---|---|+| fast | 2 / 2 / 1, no extra rounds | only what a viewer sees at once (broken character, black frame, unreadable caption, missing climax) | carries on and lists what is left |+| standard | 2 / 3 / 2, +1 while shrinking | one-frame pose changes in the climax shots, everything visible at normal speed | pauses for the user |+| fine | 3 / 3 / 2, +3 while shrinking | every pose change checked frame by frame; a climax must beat the reference | pauses for the user |++Upgrading a finished film (for example fast → fine) starts a new final review under the stricter bar and fixes from+the current film. Projects made before modes existed run the fine line. Times shown in the UI+(`QUALITY_MINUTES`, scaled by film length) come from real runs: fine 167–222 min for a 30 s film.+Design points:- **Catch defects where they are made**: characters are reviewed before shots, every shot as soon as it is built —problems don't pile up at the end.@@ -103,7 +121,8 @@ projects/<id>/brief.md / inputs/ the user's brief and uploaded inputsanalysis/ report.json, STYLE.md, route.json, lyrics/subs.lrc|jsonplan.json the pre-production plan (the web app's main view)- build/ engine project: production.json, character definitions, one file per shot, engine snapshot+ build/ engine project: production.json, character definitions, one file per shot, engine snapshot,+ score/ (Motion Score: film.json + shots/<id>.json, compiled to the engine's score.js)out/check/ cast/ (sheets, reviews, fixes), shots/ (per-segment done/review/fixes/shared, per-shot frames), critique.json, fixes.jsonout/video.mp4 the film```@@ -152,7 +171,9 @@ builder (kept across fix rounds); reviewers always start fresh.| Tool | Purpose ||---|---|| `analyze.py` | download (yt-dlp) and measure the reference: shots, pacing, BPM, palette, camera moves, contact sheets |-| `compare.py` | shot-by-shot side-by-side comparison of the film and the reference |+| `compare.py` | shot-by-shot side-by-side comparison of the film and the reference, plus the measured `style_distance.json` |+| `motion_score.py` | Motion Score (`score/`, `optimize/`): the film's camera and timing as data — `from-ref` (transfer the reference's measured camera), `validate`, `predict` (render-free), `optimize` (CMA-ES), `compile` (runtime for the engines) — see [COMPILER.md](COMPILER.md) |+| `fingerprint.py` | Style Fingerprint (`perception/`): camera trajectories with fitted eases, tension peaks, cut/beat phase, cadence, colour; `style_distance` with findings; `plan-check` (does the plan cut as often as the reference) — see [COMPILER.md](COMPILER.md) || `hf_frames.py` | frame grabs for HyperFrames projects: many moments per call, PIL crops, content-hash cache, machine-wide concurrency limit || `fetch_assets.py` | license-safe asset search and download (Openverse, Pixabay, Freesound), writes ASSETS.md || `align_lyrics.py` | user-provided lyric text × audio → per-line timing (faster-whisper only as a ruler) |