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
Server: one flow per project, shared review loop, split jobs.ts
revaldianggara3432c7007d06
diff --git a/.claude/skills/video-clone/CONTRACT.md b/.claude/skills/video-clone/CONTRACT.mdindex a60b263..5c741e3 100644--- a/.claude/skills/video-clone/CONTRACT.md+++ b/.claude/skills/video-clone/CONTRACT.md@@ -2,6 +2,7 @@每支影片一個資料夾 `projects/<id>/`。Agent(Claude Code 或 Codex)與 App 後端只透過這些檔案溝通,所以兩種 agent 都能接,前端也只要讀檔案就能畫出畫面。**Agent 必須照這裡的路徑與欄位寫檔。**+伺服器在每個回合結束時會檢查這一步必須寫的 JSON 檔(企劃、production.json、審查、修正、評審):格式不對會請你在同一個對話重寫一次,還是不對這一步就會停下。```projects/<id>/diff --git a/app/server/agents/index.ts b/app/server/agents/index.tsindex ecafab7..1391891 100644--- a/app/server/agents/index.ts+++ b/app/server/agents/index.ts@@ -16,6 +16,7 @@ import { existsSync } from 'node:fs';import { join } from 'node:path';import type { Readable } from 'node:stream';import type { AgentEvent, AgentKind, AgentStatus } from '../../shared/types.ts';+import { killTree, treeOpts } from '../runner.ts';const IS_WIN = process.platform === 'win32';// An old codex-cli can shadow a current one on PATH (e.g. a runtime manager's copy). Prefer CODEX_BIN, then npm's global shim.@@ -101,8 +102,9 @@ export function runAgent({ kind, cwd, prompt, sessionId, onEvent = () => {}, sigconst cmd = isClaude ? 'claude' : CODEX_BIN;const args = isClaude ? claudeArgs(sessionId) : codexArgs(sessionId, cwd);// Windows: npm shims (claude.cmd) need a shell; args are fixed literals, the prompt goes through stdin.- const child = spawn(cmd, args, { cwd, shell: IS_WIN, env: { ...process.env, HYPERFRAMES_NO_TELEMETRY: '1', DO_NOT_TRACK: '1' } });- if (signal) signal.addEventListener('abort', () => { try { IS_WIN ? spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F']) : child.kill('SIGTERM'); } catch {} });+ // its own process group (POSIX), so a cancel stops the renders and browsers it started too, not only the CLI+ const child = spawn(cmd, args, { cwd, shell: IS_WIN, ...treeOpts, env: { ...process.env, HYPERFRAMES_NO_TELEMETRY: '1', DO_NOT_TRACK: '1' } });+ if (signal) { if (signal.aborted) killTree(child); else signal.addEventListener('abort', () => killTree(child), { once: true }); }lines(child.stdout, (l) => {let obj: Json; try { obj = JSON.parse(l); } catch { return; }(isClaude ? parseClaude : parseCodex)(obj, emit, st);diff --git a/app/server/cast.ts b/app/server/cast.tsnew file mode 100644index 0000000..dfe01a2--- /dev/null+++ b/app/server/cast.ts@@ -0,0 +1,120 @@+// The cast gate: every character is reviewed and fixed before any shot review counts.+// Several characters, each in its own file → one reviewer + fixer pair per character, all at once; then one line-up check.+// One character, or everything in one file → the serial gate.+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { blockerFree, reviewFix, sharedItems, type LoopEnd } from './review.ts';+import { L, chat, collectNeeds, dirOf, pause, pipe, readJSON, rounds, setStage } from './store.ts';+import { fail, turn, type TurnResult } from './turn.ts';+import type { CastCharProgress, Pipeline, Review } from '../shared/types.ts';+import type { CastMember, Production, SharedItem } from './types.ts';++type CastResult = 'error' | 'needs' | 'passed' | 'failed' | 'shared';+const RESULT: Record<LoopEnd, CastResult> = { error: 'error', needs: 'needs', passed: 'passed', limit: 'failed', handoff: 'shared' };+const STATE: Record<LoopEnd, CastCharProgress['state']> = { error: 'error', needs: 'needs_user', passed: 'passed', limit: 'failed', handoff: 'waiting_shared' };++export async function castGate(id: string, prev: Pipeline): Promise<boolean> {+ const d = dirOf(id), prod = readJSON<Production>(join(d, 'build', 'production.json')) || {};+ const chars = (prod.characters || []).filter((c) => c && c.id && c.file && c.sheet);+ const files = new Set(chars.map((c) => c.file));+ const parallel = chars.length > 1 && files.size === chars.length && chars.every((c) => existsSync(join(d, c.sheet)));+ if (prev.cast?.pass) return true;+ if (!(prod.characters || []).length) { pipe(id, (p) => { p.cast = { round: 0, pass: true, state: 'passed' }; }); return true; } // no cast: nothing to review+ if (!parallel) return castSerial(id, prev);+ const setC = (cid: string, v: Partial<CastCharProgress>) => pipe(id, (p) => { const cast = p.cast!; cast.chars = cast.chars || {}; cast.chars[cid] = { ...(cast.chars[cid] ?? { state: 'queued', round: 0 }), ...v }; });+ const keep: Record<string, CastCharProgress> = prev.cast?.mode === 'parallel' ? prev.cast.chars || {} : {}; // resuming: characters that already passed stay passed+ pipe(id, (p) => { p.cast = { round: 0, pass: false, state: 'reviewing', mode: 'parallel', chars: Object.fromEntries(chars.map((c): [string, CastCharProgress] => [c.id, keep[c.id]?.state === 'passed' ? keep[c.id] : { state: 'queued', round: 0 }])) }; });+ chat(id, 'system', L(id, `角色關:${chars.length} 個角色各自由一組審查+修正同時進行`, `Characters: reviewing and fixing ${chars.length} character${chars.length > 1 ? 's' : ''} in parallel`));+ const shared: SharedItem[] = [];+ let broken = null as TurnResult | null; // the first agent turn that failed: reported as itself, not as "didn't pass review"+ const one = async (c: CastMember): Promise<CastResult> => {+ const reviewFile = join(d, 'out', 'check', 'cast', `review_${c.id}.json`);+ // resuming a character that stopped at its round limit: its last review is still current, so fix those issues first+ const reuse = keep[c.id]?.state === 'failed' && existsSync(reviewFile);+ const { end, last } = await reviewFix<Review>({+ review: async (round) => {+ setC(c.id, { state: 'reviewing', round });+ if (!(round === 1 && reuse)) {+ const r = await turn(id, 'cast_qa', { round, character: c }, [`out/check/cast/review_${c.id}.json`], { session: 'fresh', who: `cast-qa-${c.id}` });+ if (!r.ok) { broken ??= r; return null; }+ }+ return readJSON<Review>(reviewFile) || {};+ },+ verdict: (rv) => (collectNeeds(id, rv.needs_user, `cast-qa-${c.id}`) ? 'needs' : blockerFree(rv) ? 'passed' : 'fix'),+ limit: () => rounds(id).castRounds + (reuse ? 1 : 0), // a reused review isn't a round: resuming still gets its fixes+ fix: async (rv, round) => {+ 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) { broken ??= f; return 'error'; }+ const sh = sharedItems(readJSON(join(d, 'out', 'check', 'cast', `fixes_${c.id}.json`)));+ if (!sh.length) return 'ok';+ shared.push(...sh.map((x) => ({ ...x, character: c.id })));+ return 'handoff';+ },+ });+ setC(c.id, end === 'limit' ? { state: 'failed', issues: (last?.issues || []).length } : { state: STATE[end] });+ return RESULT[end];+ };+ let res: CastResult[] = await Promise.all(chars.map((c) => (keep[c.id]?.state === 'passed' ? 'passed' : one(c))));+ if (broken) return fail(id, 'producing', broken);+ if (res.includes('needs')) return pause(id);+ for (let k = 0; shared.length && k < rounds(id).castRounds; k++) { // skeleton changes: one director turn, then re-check who asked (and anyone it may affect)+ pipe(id, (p) => { p.cast!.state = 'fixing'; });+ const f = await turn(id, 'cast_fix', { issues: [...shared], round: 'shared', shared: true }, ['out/check/cast/sheet.jpg'], { who: 'director' });+ if (!f.ok) return fail(id, 'producing', f);+ shared.length = 0;+ res = await Promise.all(chars.map((c, i) => (res[i] === 'passed' || res[i] === 'shared' ? one(c) : res[i])));+ if (broken) return fail(id, 'producing', broken);+ if (res.includes('needs')) return pause(id);+ }+ if (res.some((x) => x !== 'passed')) {+ const names = chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id), n = rounds(id).castRounds;+ pipe(id, (p) => { p.cast!.state = 'failed'; p.cast!.round = n; });+ chat(id, 'system', L(id, `角色關:${names.join('、')} 審了 ${n} 輪還沒通過,請你看設定圖決定`, `Characters: ${names.join(', ')} still not passing after ${n} rounds. Please check the character sheets and decide`));+ return pause(id);+ }+ // every character passed on its own → one line-up check across them, then the serial gate handles anything it finds+ pipe(id, (p) => { p.cast!.state = 'reviewing'; p.cast!.lineup = true; });+ const r = await turn(id, 'cast_qa', { round: 'lineup', lineup: true }, ['out/check/cast/review.json'], { session: 'fresh', who: 'cast-qa' });+ if (!r.ok) return fail(id, 'producing', r);+ const rv = readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) || {};+ if (collectNeeds(id, rv.needs_user, 'cast-qa')) return pause(id);+ if (blockerFree(rv)) { pipe(id, (p) => { p.cast!.pass = true; p.cast!.state = 'passed'; }); chat(id, 'system', L(id, '角色關通過(每個角色各自通過+並排檢查)', 'Characters passed (each one on its own, then side by side)')); return true; }+ return castSerial(id, { cast: { round: 0, pass: false } }, rv);+}++// The whole cast as one: one reviewer, the director fixes. firstReview: the line-up check already reviewed, go straight to fixing.+async function castSerial(id: string, prev: Pipeline, firstReview?: Review | null): Promise<boolean> {+ const d = dirOf(id);+ if (prev.cast?.pass) return true;+ pipe(id, (p) => { p.cast = { round: 0, pass: false }; });+ let broken = null as TurnResult | null;+ const { end, round } = await reviewFix<Review>({+ review: async (round) => {+ pipe(id, (p) => { p.cast!.round = round; p.cast!.state = 'reviewing'; });+ if (firstReview) { const rv = firstReview; firstReview = null; return rv; }+ const r = await turn(id, 'cast_qa', { round }, ['out/check/cast/review.json'], { session: 'fresh', who: 'cast-qa' });+ if (!r.ok) { broken = r; return null; }+ return readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) || {};+ },+ verdict: (rv) => (collectNeeds(id, rv.needs_user, 'cast-qa') ? 'needs' : blockerFree(rv) ? 'passed' : 'fix'),+ limit: () => rounds(id).castRounds,+ fix: async (rv, round) => {+ 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) { broken = f; return 'error'; }+ return 'ok';+ },+ });+ if (end === 'error') return fail(id, 'producing', broken!);+ if (end === 'needs') return pause(id);+ if (end === 'limit') {+ 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!.pass = true; p.cast!.state = 'passed'; });+ chat(id, 'system', L(id, `角色關通過(第 ${round} 輪)`, `Characters passed (round ${round})`));+ return true;+}diff --git a/app/server/contract.test.ts b/app/server/contract.test.tsnew file mode 100644index 0000000..49e2e7f--- /dev/null+++ b/app/server/contract.test.ts@@ -0,0 +1,44 @@+// contract.ts: what an agent-written file must look like before the server acts on it.+import { describe, test } from 'node:test';+import assert from 'node:assert/strict';+import { checkFile } from './contract.ts';++const ok = (f: string, v: unknown) => assert.deepEqual(checkFile(f, JSON.stringify(v)), []);+const bad = (f: string, v: unknown, re: RegExp) => { const p = checkFile(f, typeof v === 'string' ? v : JSON.stringify(v)); assert.ok(p.some((x) => re.test(x)), p.join('\n') || 'no problems'); };++describe('checkFile', () => {+ test('any .json must parse; files without a schema need nothing more', () => {+ bad('out/check/shots/C1.done.json', '{ oops', /not valid JSON/);+ ok('out/check/shots/C1.done.json', { anything: 1 });+ });+ test('plan.json: the CONTRACT.md example passes, wrong field types are named', () => {+ ok('plan.json', { version: 1, title: 'T', music: { file: 'inputs/song.mp3', section: { start_s: 100.84, end_s: 131.7 } }, characters: [{ id: 'zhai', name: '阿宅', design: '…' }], assets: [{ id: 'A1', status: 'to_fetch' }], required_inputs: [{ id: 'lyrics', kind: 'lyrics' }], shots: [{ id: 'S1', camera: { move: 'dolly_in' } }] });+ bad('plan.json', { characters: [{ name: 'no id' }] }, /plan\.json\.characters\[0\]\.id: missing/);+ bad('plan.json', { required_inputs: [{ id: 'x' }] }, /required_inputs\[0\]\.kind: missing/);+ bad('plan.json', [], /expected object, got array/);+ });+ test('production.json needs chunks with shots', () => {+ ok('build/production.json', { chunks: [{ id: 'C1', shots: ['S1', 'S2'] }], characters: [{ id: 'hero', file: 'build/hero.js', sheet: 'out/check/cast/sheet_hero.jpg' }] });+ bad('build/production.json', {}, /chunks: missing/);+ bad('build/production.json', { chunks: [] }, /at least 1/);+ bad('build/production.json', { chunks: [{ id: 'C1', shots: [] }] }, /chunks\[0\]\.shots: needs at least 1/);+ });+ test('reviews need a verdict; issues need their text', () => {+ ok('out/check/cast/review.json', { pass: true, issues: [] });+ ok('out/check/cast/review_hero.json', { issues: [{ issue: 'arm floats', severity: 'blocker' }] });+ ok('out/check/shots/S1.review.json', { shots: [{ id: 'S1', pass: false, issues: [{ time: 1.2, where: 'left', issue: 'seam' }] }] });+ bad('out/check/shots/S1.review.json', { summary: 'looks fine' }, /needs "pass", "issues" or "shots"/);+ bad('out/check/cast/review.json', { pass: 'yes' }, /pass: expected boolean/);+ bad('out/check/cast/review.json', { pass: false, issues: ['arm'] }, /issues\[0\]: expected object/);+ bad('out/check/cast/review.json', { pass: false, needs_user: [{ kind: 'lyrics' }] }, /needs_user\[0\]\.issue: missing/);+ });+ test('fixes files: a list or { fixes }', () => {+ ok('out/check/shots/C1.fixes.json', [{ shot: 'S1', change: 'x', status: 'fixed' }]);+ ok('out/check/cast/fixes_hero.json', { fixes: [{ status: 'shared', issue: 'rig neck' }] });+ bad('out/check/fixes.json', { done: true }, /expected array/);+ });+ test('critique: must_fix items need an issue (nulls are tolerated); display fields are free', () => {+ ok('out/check/critique.json', { pass: false, must_fix: [{ shot: 'S1', time: '3.2s', issue: 'seam' }, null], needs_user: [] });+ bad('out/check/critique.json', { must_fix: [{ shot: 'S1' }] }, /must_fix\[0\]/);+ });+});diff --git a/app/server/contract.ts b/app/server/contract.tsnew file mode 100644index 0000000..46957d0--- /dev/null+++ b/app/server/contract.ts@@ -0,0 +1,61 @@+// The JSON files agents write and the server decides on (CONTRACT.md), checked when the turn that wrote them ends.+// Only the fields the server reads are checked, and extra fields are fine. A broken file goes back to the agent that wrote it+// (turn.ts) instead of being read as {} — an empty review would fail the gate, an empty plan would build nothing.+type Check = (v: unknown, at: string) => string[];++const kind = (v: unknown) => (v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v);+const is = (want: string): Check => (v, at) => (kind(v) === want ? [] : [`${at}: expected ${want}, got ${kind(v)}`]);+const str = is('string'), num = is('number'), bool = is('boolean');+const either = (...cs: Check[]): Check => (v, at) => { const all = cs.map((c) => c(v, at)); return all.some((p) => !p.length) ? [] : all[0]; };+const arr = (item: Check, { min = 0 } = {}): Check => (v, at) => {+ if (!Array.isArray(v)) return is('array')(v, at);+ if (v.length < min) return [`${at}: needs at least ${min} item${min > 1 ? 's' : ''}`];+ return v.flatMap((x, i) => item(x, `${at}[${i}]`));+};+const obj = (fields: Record<string, Check>, required: string[] = []): Check => (v, at) => {+ if (kind(v) !== 'object') return is('object')(v, at);+ const o = v as Record<string, unknown>;+ return [+ ...required.filter((k) => o[k] === undefined).map((k) => `${at}.${k}: missing`),+ ...Object.entries(fields).flatMap(([k, c]) => (o[k] === undefined ? [] : c(o[k], `${at}.${k}`))),+ ];+};+const nul: Check = (v, at) => (v === null ? [] : [`${at}: expected null`]);++const need = obj({ issue: str }, ['issue']);+const issue = obj({ issue: str, severity: str }, ['issue']);+const review: Check = (v, at) => {+ const p = obj({ pass: bool, issues: arr(issue), needs_user: arr(need), shots: arr(obj({ id: str, pass: bool, issues: arr(issue) }, ['id'])) })(v, at);+ if (p.length) return p;+ const o = v as Record<string, unknown>; // a verdict is required: an empty review would read as "failed, nothing to fix"+ return typeof o.pass === 'boolean' || Array.isArray(o.issues) || Array.isArray(o.shots) ? [] : [`${at}: needs "pass", "issues" or "shots"`];+};+const fix = obj({ status: str, issue: str });+const fixes = either(arr(fix), obj({ fixes: arr(fix) }, ['fixes']));++const SCHEMAS: [RegExp, Check][] = [+ [/(^|\/)analysis\/route\.json$/, obj({ engine: str, style: str })],+ [/(^|\/)plan\.json$/, obj({+ title: str, version: either(num, str),+ characters: arr(obj({ id: str, name: str, file: str }, ['id'])),+ assets: arr(obj({ id: str, status: str })),+ required_inputs: arr(obj({ id: str, kind: str, label: str, file: str, match: str }, ['id', 'kind'])),+ music: obj({ file: str }),+ })],+ [/(^|\/)build\/production\.json$/, obj({+ chunks: arr(obj({ id: str, shots: arr(str, { min: 1 }) }, ['id', 'shots']), { min: 1 }),+ characters: arr(obj({ id: str, name: str, file: str, sheet: str }, ['id'])),+ rig_files: arr(str),+ }, ['chunks'])],+ [/(^|\/)out\/check\/critique\.json$/, obj({ must_fix: arr(either(nul, obj({ issue: str }, ['issue']))), needs_user: arr(need) })],+ [/(^|\/)(review(_[^/]+)?|[^/]+\.review)\.json$/, review],+ [/(^|\/)(fixes(_[^/]+)?|[^/]+\.fixes)\.json$/, fixes],+];++// Problems with one agent-written file (project-relative path), [] when it's fine. Any .json must at least parse.+export function checkFile(rel: string, text: string): string[] {+ let v: unknown;+ try { v = JSON.parse(text); } catch (e) { return [`${rel}: not valid JSON (${(e as Error).message})`]; }+ const s = SCHEMAS.find(([re]) => re.test(rel));+ return s ? s[1](v, rel) : [];+}diff --git a/app/server/final.ts b/app/server/final.tsnew file mode 100644index 0000000..e6b535a--- /dev/null+++ b/app/server/final.ts@@ -0,0 +1,50 @@+// The final panel: a fresh critic looks only at what spans segments (seams, continuity, pacing, captions, the climaxes+// against the reference) and verifies every earlier fix ⇄ the director revises. finalRounds automatic revises, a few more+// while the list is short and shrinking; anything left after that is the user's call.+import { join } from 'node:path';+import { reviewFix } from './review.ts';+import { L, chat, collectNeeds, dirOf, load, now, pipe, readJSON, rounds, setStage, update } from './store.ts';+import { step } from './turn.ts';+import type { Critique } from './types.ts';++type MustFix = NonNullable<Critique['must_fix']>;++export async function finalPanel(id: string) {+ const d = dirOf(id);+ let needs = 0, total = 0, prevMust = Infinity, converging = false;+ const { end, last } = await reviewFix<MustFix>({+ review: async (round) => {+ pipe(id, (p) => { p.phase = 'final'; p.final = { round }; });+ if (!(await step(id, 'critiquing', 'critique', { round }, ['out/check/critique.json'], null, { session: 'fresh', who: 'critic' }))) return null;+ const c = readJSON<Critique>(join(d, 'out', 'check', 'critique.json')) || {};+ const must = (c.must_fix || []).filter(Boolean);+ // a climax that loses to the reference never passes, even if the critic forgot to list a fix for it+ for (const pk of (c.peaks || []).filter((x) => x?.verdict === 'ref_better'))+ if (!must.some((m) => m.issue.includes(pk.id))) must.push({ shot: pk.id, time: pk.ours?.[0], issue: `高潮 ${pk.id} 輸給參考片:${pk.why || ''}`, fix: `照 ${pk.strip || '高潮對照圖'} 逐格補上參考片爆點的手法,直到不輸參考片` });+ total = (load(id).critiqueRounds || 0) + 1; // every critic pass since approval (retries and user revisions included)+ update(id, (j) => { j.critiqueRounds = total; j.lastCritique = { pass: !must.length, must: must.length, at: now() }; });+ needs = collectNeeds(id, c.needs_user, 'critic'); // never sent to the director: they wait for the user+ // 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.+ converging = must.length <= 2 && must.length < prevMust && round <= rounds(id).finalRounds + 3;+ prevMust = must.length;+ return must;+ },+ verdict: (must) => (must.length ? 'fix' : 'passed'),+ limit: () => (converging ? Infinity : rounds(id).finalRounds + 1), // n automatic revises → up to n + 1 reviews+ fix: async (must, round) => {+ const msg = must.map((m, i) => `${i + 1}. [${m.shot || '全片'}${m.time != null ? ' ' + m.time + 's' : ''}] ${m.issue}${m.fix ? ' → 建議:' + m.fix : ''}`).join('\n');+ chat(id, 'system', L(id, `評審第 ${total} 輪:${must.length} 項必修,交回導演(每項要附修改前後對照)`, `Final review round ${total}: ${must.length} must-fix item${must.length > 1 ? 's' : ''}, sent back to the director (each fix needs before/after proof)`));+ return (await step(id, 'revising', 'revise', { message: msg, round }, ['out/video.mp4', 'out/check/fixes.json'])) ? 'ok' : 'error';+ },+ });+ if (end === 'error') return; // step() already stopped the job with the reason+ if (end === 'passed') {+ 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;+ }+ const n = last!.length;+ chat(id, 'system', L(id, `評審仍有 ${n} 項必修,已達自動修改上限,請你決定`, `The final review still has ${n} must-fix item${n > 1 ? 's' : ''} and the automatic fix limit is reached. Please decide`));+ setStage(id, 'done');+}diff --git a/app/server/inputs.ts b/app/server/inputs.tsnew file mode 100644index 0000000..8364ba3--- /dev/null+++ b/app/server/inputs.ts@@ -0,0 +1,77 @@+// Required inputs (lyrics, product photos, logos…) and lyric timing.+// plan.required_inputs: [{ id, kind: lyrics|audio|image|text|other, label, why }]. Satisfied by a file in inputs/ (or the+// aligned lyrics), or waived by the user. Approval is blocked while any is open, so production never runs without them.+import { existsSync, mkdirSync, writeFileSync, readdirSync } from 'node:fs';+import { join } from 'node:path';+import { spawnTool } from './runner.ts';+import { L, PY, ROOT, SCRIPTS, dirOf, load, log, noPython, readJSON, readText, update } from './store.ts';+import type { Job, Plan, RequiredInput } from '../shared/types.ts';++export function requiredInputs(id: string, plan: Plan | null, job: Job): RequiredInput[] {+ const d = dirOf(id), files = existsSync(join(d, 'inputs')) ? readdirSync(join(d, 'inputs')) : [];+ return (plan?.required_inputs || []).map((r) => {+ let status: RequiredInput['status'] = 'missing';+ const given = (job.provided?.[r.id] || []).filter((f) => existsSync(join(d, f)));+ if ((job.waived || []).includes(r.id)) status = 'waived';+ else if (given.length) status = 'provided'; // uploaded for this item from the web app+ else if (r.kind === 'lyrics' && (existsSync(join(d, 'inputs', 'lyrics.txt')) || existsSync(join(d, 'analysis', 'lyrics', 'subs.lrc')) || files.some((f) => /\.lrc$/i.test(f)))) status = 'provided';+ else if (r.file && existsSync(join(d, r.file))) status = 'provided';+ else if (r.kind !== 'lyrics' && files.some((f) => f.toLowerCase().includes((r.match || r.id).toLowerCase()))) status = 'provided';+ return { ...r, status, files: given };+ });+}+export function openInputs(id: string) { return requiredInputs(id, readJSON<Plan>(join(dirOf(id), 'plan.json')), load(id)).filter((r) => r.status === 'missing'); }+export function waive(id: string, inputId: string) { update(id, (j) => { j.waived = [...new Set([...(j.waived || []), inputId])]; j.needs = (j.needs || []).filter((n) => n.input !== inputId); }); }+export function unwaive(id: string, inputId: string) { update(id, (j) => { j.waived = (j.waived || []).filter((x) => x !== inputId); }); }++// Files uploaded for one required input (inputs/…): remember which item they answer, so any file name counts.+// A .txt for a lyrics item is taken as the lyric text. Then time the lyrics if the music is there now.+export function provideInput(id: string, inputId: string, saved: string[]) { // records the answer now; lyric timing (≈1 min) runs in the background+ const d = dirOf(id), r = (readJSON<Plan>(join(d, 'plan.json'))?.required_inputs || []).find((x) => x.id === inputId);+ if (!r || !saved.length) return false;+ update(id, (j) => { j.provided = { ...(j.provided || {}), [inputId]: saved }; j.waived = (j.waived || []).filter((x) => x !== inputId); });+ const txt = r.kind === 'lyrics' && saved.find((f) => /\.txt$/i.test(f)), text = txt && !/(^|\/)lyrics\.txt$/i.test(txt) ? readText(join(d, txt)) : null;+ (text?.trim() ? saveLyrics(id, text) : alignIfReady(id)).catch((e) => console.error(e));+ return true;+}+// Lyrics pasted before the music arrived are only text: time them as soon as there is audio (and again before production).+export async function alignIfReady(id: string): Promise<LyricsResult | null> {+ const d = dirOf(id);+ if (!existsSync(join(d, 'inputs', 'lyrics.txt')) || existsSync(join(d, 'analysis', 'lyrics', 'subs.lrc')) || !musicFile(id)) return null;+ return saveLyrics(id, readText(join(d, 'inputs', 'lyrics.txt')) ?? '');+}+// The song to time lyrics against: the plan's music file, else a file the user uploaded for an audio item, else any audio in inputs/.+function musicFile(id: string): string | null {+ const d = dirOf(id), plan = readJSON<Plan>(join(d, 'plan.json')) || {}, job = load(id), AUD = /\.(mp3|m4a|wav|aac|flac|ogg|opus|mp4|mov|webm)$/i;+ if (plan.music?.file && existsSync(join(d, plan.music.file))) return plan.music.file;+ const audioIds = (plan.required_inputs || []).filter((r) => r.kind === 'audio').map((r) => r.id);+ for (const k of audioIds) for (const f of job.provided?.[k] || []) if (AUD.test(f) && existsSync(join(d, f))) return f;+ const f = existsSync(join(d, 'inputs')) ? readdirSync(join(d, 'inputs')).find((x) => AUD.test(x) && !/^reference\./i.test(x)) : null;+ return f ? `inputs/${f}` : null;+}++// The user pastes lyrics (their text) → inputs/lyrics.txt → timed against the plan's music section → analysis/lyrics/subs.lrc+export interface LyricsResult { ok: boolean; aligned: boolean; report?: string }+export function saveLyrics(id: string, text: string): Promise<LyricsResult> {+ const d = dirOf(id); writeFileSync(join(d, 'inputs', 'lyrics.txt'), text.trim() + '\n');+ const plan = readJSON<Plan>(join(d, 'plan.json')) || {}, m = plan.music || {};+ const song = musicFile(id), audio = song ? join(d, song) : null;+ const out = join(d, 'analysis', 'lyrics'); mkdirSync(out, { recursive: true });+ if (!audio) { log(id, { type: 'text', text: L(id, '歌詞已存,收到配樂後會自動對時', 'Lyrics saved; they will be timed as soon as the music arrives') }); return Promise.resolve({ ok: true, aligned: false }); }+ const args = [join(SCRIPTS, 'align_lyrics.py'), audio, join(d, 'inputs', 'lyrics.txt'), '--out', join(out, 'subs.lrc')];+ if (m.section?.start_s != null && song && !/clip/i.test(song)) args.push('--start', String(m.section.start_s), '--end', String(m.section.end_s));+ log(id, { type: 'tool', name: 'align_lyrics.py', detail: `對時:${song}` });+ return new Promise((resolve) => {+ const p = spawnTool(id, PY, args, { cwd: ROOT, env: { ...process.env, PYTHONIOENCODING: 'utf-8' } }); let o = '', done = false;+ p.stdout.on('data', (b) => { o += b; }); p.stderr.on('data', () => {});+ const finish = (code: number | null, err?: Error) => {+ if (done) return; done = true;+ const first = o.split('\n').find((l) => l.startsWith('lines')) || '';+ log(id, { type: code === 0 ? 'text' : 'error', text: code === 0 ? `歌詞對時完成:${first}` : err ? `歌詞對時失敗:${noPython(err)}` : '歌詞對時失敗' });+ if (code === 0) update(id, (j) => { j.needs = (j.needs || []).filter((n) => n.kind !== 'lyrics'); });+ resolve({ ok: code === 0, aligned: code === 0, report: first });+ };+ p.on('error', (e) => finish(null, e)); // e.g. Python not found: without this listener the server crashes+ p.on('close', (code) => finish(code));+ });+}diff --git a/app/server/jobs.test.ts b/app/server/jobs.test.tsindex 5c6a9e3..5aff009 100644--- a/app/server/jobs.test.ts+++ b/app/server/jobs.test.ts@@ -2,7 +2,7 @@// Runs against a throwaway projects folder (REELMIMIC_PROJECTS), never the real one. No agent is started.import { after, before, describe, test } from 'node:test';import assert from 'node:assert/strict';-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -144,3 +144,35 @@ describe('project list', () => {assert.deepEqual(times, [...times].sort().reverse());});});++const S = await import('./store.ts');+describe('event log', () => {+ test('an event goes to events.jsonl and the snapshot, without rewriting job.json', () => {+ const { id } = newJob();+ const before = readFileSync(join(J.dirOf(id), 'job.json'), 'utf8');+ S.log(id, { type: 'text', text: 'hello' });+ assert.equal(readFileSync(join(J.dirOf(id), 'job.json'), 'utf8'), before);+ assert.equal(J.snapshot(id).job.log.at(-1)?.type, 'text');+ assert.match(readFileSync(join(J.dirOf(id), 'logs', 'events.jsonl'), 'utf8'), /hello/);+ assert.ok(!('log' in JSON.parse(before)));+ });+ test('after a restart the latest 600 come back from the tail of events.jsonl', () => {+ const id = 'restart-log', d = J.dirOf(id);+ mkdirSync(join(d, 'logs'), { recursive: true });+ writeFileSync(join(d, 'job.json'), JSON.stringify({ id, title: 't', agent: 'claude', stage: 'done', chat: [], needs: [], pipeline: {} }));+ writeFileSync(join(d, 'logs', 'events.jsonl'), Array.from({ length: 700 }, (_, i) => JSON.stringify({ ts: 't', type: 'text', text: `e${i}` })).join('\n') + '\n');+ const log = J.snapshot(id).job.log as { text?: string }[];+ assert.equal(log.length, 600);+ assert.equal(log[0].text, 'e100');+ assert.equal(log.at(-1)!.text, 'e699');+ });+ test('a project from before events.jsonl keeps its log: moved out of job.json on first write', () => {+ const id = 'old-log', d = J.dirOf(id);+ mkdirSync(d, { recursive: true });+ writeFileSync(join(d, 'job.json'), JSON.stringify({ id, title: 't', agent: 'claude', stage: 'done', chat: [], needs: [], pipeline: {}, log: [{ ts: 't', type: 'text', text: 'old' }] }));+ J.waive(id, 'x'); // any write+ assert.ok(!('log' in JSON.parse(readFileSync(join(d, 'job.json'), 'utf8'))));+ assert.match(readFileSync(join(d, 'logs', 'events.jsonl'), 'utf8'), /"old"/);+ assert.equal((J.snapshot(id).job.log[0] as { text?: string }).text, 'old');+ });+});diff --git a/app/server/jobs.ts b/app/server/jobs.tsindex 585519d..e6810b8 100644--- a/app/server/jobs.ts+++ b/app/server/jobs.ts@@ -1,139 +1,43 @@// Jobs: one folder per video under projects/<id>/, job.json is the state. The server owns the stage machine; agents only// write the files in CONTRACT.md. A step advances only when its output files exist.//-// new → analyzing → styling → planning → plan_review ⇄ replanning-// → [approve: required inputs must be provided or waived]-// → producing: setup (director) → CAST GATE (cast_qa ⇄ cast_fix) → SHOT LINE (N builders in parallel; every chunk-// is reviewed by a fresh shot_qa as soon as it is built ⇄ fix_chunk) → assemble (director)-// → critiquing: final panel (fresh critic: continuity/pacing/seams, verifies earlier fixes) ⇄ revising+// new → analyzing → styling → planning → plan_review ⇄ replanning preprod.ts+// → [approve: required inputs must be provided or waived] inputs.ts+// → producing: setup → cast gate ∥ shot line → assemble production.ts, cast.ts+// → critiquing: final panel ⇄ revising final.ts// → 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 { extname, 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 { prompts as bootPrompts } from './prompts.ts';+//+// This file is the server's API over all of that: the user's actions, each one run as the project's single flow+// (runner.ts), plus the project list and snapshot. Every review/fix gate shares one loop (review.ts); one agent turn is+// turn.ts; job.json and helpers are store.ts.+import { appendFileSync, existsSync, mkdirSync, writeFileSync, readdirSync, cpSync } from 'node:fs';+import { extname, join, relative } from 'node:path';+import { finalPanel } from './final.ts';+import { openInputs, alignIfReady, requiredInputs } from './inputs.ts';+import { flushNotes, fromAnalysis, fromStyle, preProduction } from './preprod.ts';+import { production } from './production.ts';+import { stopPrerenders } from './prerender.ts';+import * as runner from './runner.ts';+import { active, run } from './runner.ts';+import { CONFIG, L, PROJECTS, ROOT, ROUND_RANGE, chat, cleanRounds, diskWarning, dirOf, jpath, listFiles, load, now, oneOf, pipe, readJSON, readText, recentLog, rounds, save, update } from './store.ts';+import { step } from './turn.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 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-let promptCache: { m: number; p: Prompts } = { m: 0, p: bootPrompts };-async function livePrompts() {- const f = join(import.meta.dirname, 'prompts.ts'), m = statSync(f).mtimeMs;- if (m !== promptCache.m) { try { promptCache = { m, p: (await import(`./prompts.ts?v=${m}`)).prompts }; } catch (e) { console.error('prompts reload failed', e); } }- return promptCache.p;-}--export const ROOT = join(import.meta.dirname, '..', '..');-export const PROJECTS = process.env.REELMIMIC_PROJECTS ? resolve(process.env.REELMIMIC_PROJECTS) : join(ROOT, 'projects'); // override: tests, a second checkout-const SCRIPTS = join(ROOT, '.claude', 'skills', 'video-clone', 'scripts');-const PY = process.env.PYTHON || 'python';-const noPython = (e: Error) => `${PY} could not be started (${e.message}). Install Python 3.10+, or set PYTHON=/path/to/python`;-// A review passes when nothing it lists is a blocker (polish items are handed on, they never hold the line)-const 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; };+import type { AgentKind, ChatMessage, EngineSnapshot, Job, Lang, Plan, ProjectSummary, Reference, Review, RoundKey, Rounds, Snapshot, Stage } from '../shared/types.ts';+import type { Production } from './types.ts';-export const CONFIG: Config = {- builders: +(process.env.BUILDERS || 6), // parallel shot builders per project (12 cores / 32 GB measured)- castRounds: +(process.env.CAST_ROUNDS || 3), // cast gate: review/fix rounds before asking the user- chunkRounds: +(process.env.CHUNK_ROUNDS || 3), // shot line: review/fix rounds per chunk- finalRounds: +(process.env.FINAL_ROUNDS || 2), // final panel: automatic revise rounds- 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- // Build shots while the cast gate is still running? Faster, but on real runs character files changed under the- // builders and every segment needed an extra round (0nczg, 4f1jx, 1qo20, 7e45u). Off by default: quality first.- overlapCast: process.env.OVERLAP_CAST === '1',-};+export { ROUND_KEYS };+export { CANCELLED, CONFIG, PROJECTS, ROOT, ROUND_RANGE, bus, cleanRounds, dirOf, load, rounds, touch, type BusEvent } from './store.ts';+export { alignIfReady, openInputs, provideInput, saveLyrics, unwaive, waive, type LyricsResult } from './inputs.ts';+export { stopAll } from './runner.ts';+export const busy = active; // a flow is running for this project (runner.ts allows one at a time)+// Stop the project's flow and every process it started; background renders queued behind them don't start either.+export function cancel(id: string) { runner.cancel(id); stopPrerenders(id); }-// 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; }-// 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>> = {};- for (const k of ROUND_KEYS) {- if (!(k in input)) continue;- const raw = input[k];- if (raw === '' || raw == null) { out[k] = null; continue; }- const v = Number(raw);- if (!Number.isInteger(v) || v < ROUND_RANGE.min || v > ROUND_RANGE.max) throw new Error(`${k} must be a whole number from ${ROUND_RANGE.min} to ${ROUND_RANGE.max}`);- out[k] = v;- }- return out;-}-export function setRounds(id: string, input: Record<string, unknown>) {- const clean = cleanRounds(input);- update(id, (x) => { const s = { ...(x.settings || {}) }; for (const [k, v] of Object.entries(clean) as [RoundKey, number | null][]) { if (v == null) delete s[k]; else s[k] = v; } x.settings = s; });- return snapshot(id);-}// Uploaded references only need to look like a video (by extension); URL references are left to yt-dlp.export const REFERENCE_EXTS = ['.mp4', '.mov', '.mkv', '.webm', '.avi', '.m4v', '.mpg', '.mpeg'];export const isVideoName = (name: string) => REFERENCE_EXTS.includes(extname(name).toLowerCase());-export type BusEvent = { type: 'job'; job: Job } | { type: 'log'; ev: LogEvent };-export const bus = new EventEmitter<{ job: [id: string, ev: BusEvent] }>(); bus.setMaxListeners(100);-const running = new Map<string, Set<AbortController>>();-// Stop every agent this server started (on shutdown), so none keeps working unseen after a restart.-export function stopAll() { for (const set of running.values()) for (const ac of set) ac.abort(); for (const set of prerenderProcs.values()) for (const p of set) p.kill(); }--const now = () => new Date().toISOString();-export const dirOf = (id: string) => join(PROJECTS, id);-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; }-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 });- try { update(id, (j) => { j.log = [...(j.log || []).slice(-600), e]; }); } catch {}- // the full, uncapped record lives in logs/events.jsonl (job.json keeps only the latest 600 for the UI)- try { mkdirSync(join(dirOf(id), 'logs'), { recursive: true }); appendFileSync(join(dirOf(id), 'logs', 'events.jsonl'), JSON.stringify(e) + '\n'); } catch {}-}--// On startup nothing is running, so a job still marked as working was cut off by a restart: say so instead of pretending.-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;- const j = load(d);- if (!WORK.includes(j.stage)) continue;- cut.push(d);- update(d, (x) => { x.failed = x.stage; x.stage = 'error'; x.error = L(d, '伺服器重新啟動,這一輪被中斷了(它可能已經改了部分檔案)。按「重試這一步」從目前的檔案繼續。', 'The server restarted and this turn was cut off (it may have changed some files). Click “Retry this step” to continue from the current files.'); x.chat.push({ role: 'system', text: L(d, '這一輪因為伺服器重新啟動而中斷。', 'This turn was cut off by a server restart.'), ts: now() }); });- }- return cut;-}-// After a restart, pick the interrupted jobs up again on their own (one real run sat cut off for 11.5 hours overnight).-// Staggered so they don't all launch agents at once. AUTO_RESUME=0 turns it off.-export function autoResume(ids: string[], gapMs = 5000) {- ids.forEach((id, i) => setTimeout(() => {- if (load(id).stage !== 'error') return; // the user already did something with it- chat(id, 'system', L(id, '伺服器重新啟動後自動接續這一步。', 'Resuming this step automatically after the server restart.'));- 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 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);--// ---------- global agent slots (all projects share them) -----------// Reviews and fixes jump the queue: a defect is fixed while the builder still has it in mind, and nobody waits on a-// review behind a fresh 30-minute build. New builds take whatever slots are left.-let active = 0; const waiters: { r: () => void; hi: boolean }[] = [];-const URGENT = new Set(['cast_qa', 'cast_fix', 'shot_qa', 'fix_chunk', 'assemble', 'critique', 'revise', 'replan', 'plan', 'style']);-async function slot(phase: Phase) {- if (active < CONFIG.maxAgentsGlobal) { active++; return; }- await new Promise<void>((r) => { const w = { r, hi: URGENT.has(phase) }; if (w.hi) { const i = waiters.findIndex((x) => !x.hi); i < 0 ? waiters.push(w) : waiters.splice(i, 0, w); } else waiters.push(w); });- active++;-}-function release() { active--; const w = waiters.shift(); if (w) w.r(); }-+// ---------- projects ----------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 }; })@@ -142,8 +46,7 @@ export function listJobs(): ProjectSummary[] {// Everything the UI needs for one project, read straight from the contract files.export function snapshot(id: string): Snapshot {- const d = dirOf(id), job = load(id);- const list = (sub: string, re: RegExp) => { const p = join(d, sub); return existsSync(p) ? readdirSync(p).filter((f) => re.test(f)).map((f) => ({ f: `${sub}/${f}`, t: statSync(join(p, f)).mtimeMs })).sort((a, b) => b.t - a.t).map((x) => x.f) : []; };+ const d = dirOf(id), job = { ...load(id), log: [...recentLog(id)] }, list = (sub: string, re: RegExp) => listFiles(id, sub, re);const plan = readJSON<Plan>(join(d, 'plan.json'));return {job, brief: readText(join(d, 'brief.md')),@@ -176,212 +79,37 @@ export function createJob({ id, title, agent, brief, reference, lang = 'zh-TW',return job;}-const setStage = (id: string, stage: Stage, extra: Partial<Job> = {}) => update(id, (j) => Object.assign(j, { stage, ...extra }));-const chat = (id: string, role: ChatMessage['role'], text: string, extra: Partial<ChatMessage> = {}) => update(id, (j) => { j.chat.push({ role, text, ts: now(), ...extra }); });-const pipe = (id: string, fn: (p: Pipeline) => void) => update(id, (j) => { j.pipeline = j.pipeline || {}; fn(j.pipeline); });--// ---------- required inputs (lyrics, product photos, logos…) -----------// plan.required_inputs: [{ id, kind: lyrics|audio|image|text|other, label, why }]. Satisfied by a file in inputs/ (or the-// aligned lyrics), or waived by the user. Approval is blocked while any is open, so production never runs without them.-function requiredInputs(id: string, plan: Plan | null, job: Job): RequiredInput[] {- const d = dirOf(id), files = existsSync(join(d, 'inputs')) ? readdirSync(join(d, 'inputs')) : [];- return (plan?.required_inputs || []).map((r) => {- let status: RequiredInput['status'] = 'missing';- const given = (job.provided?.[r.id] || []).filter((f) => existsSync(join(d, f)));- if ((job.waived || []).includes(r.id)) status = 'waived';- else if (given.length) status = 'provided'; // uploaded for this item from the web app- else if (r.kind === 'lyrics' && (existsSync(join(d, 'inputs', 'lyrics.txt')) || existsSync(join(d, 'analysis', 'lyrics', 'subs.lrc')) || files.some((f) => /\.lrc$/i.test(f)))) status = 'provided';- else if (r.file && existsSync(join(d, r.file))) status = 'provided';- else if (r.kind !== 'lyrics' && files.some((f) => f.toLowerCase().includes((r.match || r.id).toLowerCase()))) status = 'provided';- return { ...r, status, files: given };- });-}-export function openInputs(id: string) { const s = snapshot(id); return s.requiredInputs.filter((r) => r.status === 'missing'); }-export function waive(id: string, inputId: string) { update(id, (j) => { j.waived = [...new Set([...(j.waived || []), inputId])]; j.needs = (j.needs || []).filter((n) => n.input !== inputId); }); }-export function unwaive(id: string, inputId: string) { update(id, (j) => { j.waived = (j.waived || []).filter((x) => x !== inputId); }); }-export function touch(id: string) { update(id, () => {}); } // tell open pages to reload (e.g. after files were added)--// Files uploaded for one required input (inputs/…): remember which item they answer, so any file name counts.-// A .txt for a lyrics item is taken as the lyric text. Then time the lyrics if the music is there now.-export function provideInput(id: string, inputId: string, saved: string[]) { // records the answer now; lyric timing (≈1 min) runs in the background- const d = dirOf(id), r = (readJSON<Plan>(join(d, 'plan.json'))?.required_inputs || []).find((x) => x.id === inputId);- if (!r || !saved.length) return false;- update(id, (j) => { j.provided = { ...(j.provided || {}), [inputId]: saved }; j.waived = (j.waived || []).filter((x) => x !== inputId); });- const txt = r.kind === 'lyrics' && saved.find((f) => /\.txt$/i.test(f)), text = txt && !/(^|\/)lyrics\.txt$/i.test(txt) ? readText(join(d, txt)) : null;- (text?.trim() ? saveLyrics(id, text) : alignIfReady(id)).catch((e) => console.error(e));- return true;-}-// Lyrics pasted before the music arrived are only text: time them as soon as there is audio (and again before production).-export async function alignIfReady(id: string): Promise<LyricsResult | null> {- const d = dirOf(id);- if (!existsSync(join(d, 'inputs', 'lyrics.txt')) || existsSync(join(d, 'analysis', 'lyrics', 'subs.lrc')) || !musicFile(id)) return null;- return saveLyrics(id, readText(join(d, 'inputs', 'lyrics.txt')) ?? '');-}-// The song to time lyrics against: the plan's music file, else a file the user uploaded for an audio item, else any audio in inputs/.-function musicFile(id: string): string | null {- const d = dirOf(id), plan = readJSON<Plan>(join(d, 'plan.json')) || {}, job = load(id), AUD = /\.(mp3|m4a|wav|aac|flac|ogg|opus|mp4|mov|webm)$/i;- if (plan.music?.file && existsSync(join(d, plan.music.file))) return plan.music.file;- const audioIds = (plan.required_inputs || []).filter((r) => r.kind === 'audio').map((r) => r.id);- for (const k of audioIds) for (const f of job.provided?.[k] || []) if (AUD.test(f) && existsSync(join(d, f))) return f;- const f = existsSync(join(d, 'inputs')) ? readdirSync(join(d, 'inputs')).find((x) => AUD.test(x) && !/^reference\./i.test(x)) : null;- return f ? `inputs/${f}` : null;-}--// The user pastes lyrics (their text) → inputs/lyrics.txt → timed against the plan's music section → analysis/lyrics/subs.lrc-export interface LyricsResult { ok: boolean; aligned: boolean; report?: string }-export function saveLyrics(id: string, text: string): Promise<LyricsResult> {- const d = dirOf(id); writeFileSync(join(d, 'inputs', 'lyrics.txt'), text.trim() + '\n');- const plan = readJSON<Plan>(join(d, 'plan.json')) || {}, m = plan.music || {};- const song = musicFile(id), audio = song ? join(d, song) : null;- const out = join(d, 'analysis', 'lyrics'); mkdirSync(out, { recursive: true });- if (!audio) { log(id, { type: 'text', text: L(id, '歌詞已存,收到配樂後會自動對時', 'Lyrics saved; they will be timed as soon as the music arrives') }); return Promise.resolve({ ok: true, aligned: false }); }- const args = [join(SCRIPTS, 'align_lyrics.py'), audio, join(d, 'inputs', 'lyrics.txt'), '--out', join(out, 'subs.lrc')];- if (m.section?.start_s != null && song && !/clip/i.test(song)) args.push('--start', String(m.section.start_s), '--end', String(m.section.end_s));- log(id, { type: 'tool', name: 'align_lyrics.py', detail: `對時:${song}` });- return new Promise((resolve) => {- const p = spawn(PY, args, { cwd: ROOT, env: { ...process.env, PYTHONIOENCODING: 'utf-8' } }); let o = '', done = false;- p.stdout.on('data', (b) => { o += b; }); p.stderr.on('data', () => {});- const finish = (code: number | null, err?: Error) => {- if (done) return; done = true;- const first = o.split('\n').find((l) => l.startsWith('lines')) || '';- log(id, { type: code === 0 ? 'text' : 'error', text: code === 0 ? `歌詞對時完成:${first}` : err ? `歌詞對時失敗:${noPython(err)}` : '歌詞對時失敗' });- if (code === 0) update(id, (j) => { j.needs = (j.needs || []).filter((n) => n.kind !== 'lyrics'); });- resolve({ ok: code === 0, aligned: code === 0, report: first });- };- p.on('error', (e) => finish(null, e)); // e.g. Python not found: without this listener the server crashes- p.on('close', (code) => finish(code));- });-}--// ---------- analysis -----------function analyze(id: string): Promise<boolean> {- const j = load(id), d = dirOf(id), src = j.reference.type === 'url' ? j.reference.src : join(d, j.reference.src);- setStage(id, 'analyzing');- log(id, { type: 'tool', name: 'analyze.py', detail: j.reference.src });- return new Promise((resolve) => {- const p = spawn(PY, [join(SCRIPTS, 'analyze.py'), src, '--out', join(d, 'analysis')], { cwd: ROOT, env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });- p.stdout.on('data', (b) => String(b).split('\n').filter(Boolean).forEach((l) => log(id, { type: 'text', text: l })));- p.stderr.on('data', (b) => { const s = String(b); if (!/Warning|warn\(/i.test(s)) log(id, { type: 'error', text: s.slice(0, 400) }); });- let done = false;- const finish = (code: number | null, err?: Error) => {- if (done) return; done = true;- const ok = code === 0 && existsSync(join(d, 'analysis', 'report.json'));- if (!ok) setStage(id, 'error', { failed: 'analyzing', error: err ? noPython(err) : 'analyze.py failed' });- resolve(ok);- };- p.on('error', (e) => finish(null, e)); // e.g. Python not found: without this listener the server crashes- p.on('close', (code) => finish(code));- });+export function setRounds(id: string, input: Record<string, unknown>) {+ const clean = cleanRounds(input);+ update(id, (x) => { const s = { ...(x.settings || {}) }; for (const [k, v] of Object.entries(clean) as [RoundKey, number | null][]) { if (v == null) delete s[k]; else s[k] = v; } x.settings = s; });+ return snapshot(id);}-// ---------- one agent turn -----------// session: 'director' (the project's main conversation), 'fresh' (a reviewer with no stake), or any key (a builder that keeps-// its own conversation across its fix rounds). Returns { ok, text } — never touches the stage; the orchestrator does.-interface TurnOpts { session?: string; who?: string }-interface TurnResult { ok: boolean; text?: string; missing?: string[]; stderr?: string; lastError?: string; aborted?: boolean }-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 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;- 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 });- } });- } 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 };- let missing = must.filter((f, i) => !(mtime(join(d, f)) > before[i]));- // first turn after "retry": the interrupted turn may already have written everything, and the agent rightly- // 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; });- 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 };-}-function fail(id: string, stageName: Stage, res: TurnResult) {- // an account limit is the real cause, even when it also left outputs missing: say so plainly- const limit = [res.lastError, res.text, res.stderr].find((t) => t && /usage limit|rate limit|hit your limit|limit reached|quota|credit balance/i.test(t));- if (limit && !res.aborted) {- setStage(id, 'error', { failed: stageName, error: L(id, `AI 帳號的用量到上限了,等額度恢復或換另一個 AI 導演再按「重試這一步」。原始訊息:${limit.slice(-300)}`, `Your AI account hit its usage limit. Wait until it resets (or switch to the other AI director), then click “Retry this step”. Message: ${limit.slice(-300)}`) });- return false;+// On startup nothing is running, so a job still marked as working was cut off by a restart: say so instead of pretending.+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;+ const j = load(d);+ if (!WORK.includes(j.stage)) continue;+ cut.push(d);+ update(d, (x) => { x.failed = x.stage; x.stage = 'error'; x.error = L(d, '伺服器重新啟動,這一輪被中斷了(它可能已經改了部分檔案)。按「重試這一步」從目前的檔案繼續。', 'The server restarted and this turn was cut off (it may have changed some files). Click “Retry this step” to continue from the current files.'); x.chat.push({ role: 'system', text: L(d, '這一輪因為伺服器重新啟動而中斷。', 'This turn was cut off by a server restart.'), ts: now() }); });}- setStage(id, 'error', { failed: stageName, error: res.aborted ? L(id, '已取消', 'Cancelled') : !res.missing?.length ? L(id, `agent 回合失敗 ${res.stderr ? ':' + res.stderr.slice(-300) : ''}`, `The agent turn failed${res.stderr ? ': ' + res.stderr.slice(-300) : ''}`) : L(id, `缺少輸出:${res.missing.join(', ')}`, `Missing output: ${res.missing.join(', ')}`) });- return false;-}-async function step<P extends Phase>(id: string, stageName: Stage, phase: P, vars: StepVars[P], must: string[], next?: Stage | null, opts?: TurnOpts) {- setStage(id, stageName, { error: null, failed: null });- const r = await turn(id, phase, vars, must, opts);- if (!r.ok) return fail(id, stageName, r);- if (next) setStage(id, next);- return true;-}--// needs_user items (from any reviewer) pause instead of looping-function collectNeeds(id: string, items: NeedRequest[] | undefined, from: string) {- const add: Need[] = (items || []).filter(Boolean).map((n) => ({ ...n, from, at: now() }));- if (!add.length) return 0;- // a new batch from the same reviewer replaces its earlier one (the critic re-reports open items every round)- update(id, (j) => { j.needs = [...(j.needs || []).filter((x) => x.from !== from && !add.some((a) => a.issue === x.issue)), ...add]; });- chat(id, 'system', L(id, `需要你提供:${add.map((n) => n.issue).join(';')}`, `Needs your input: ${add.map((n) => n.issue).join('; ')}`));- return add.length;-}--// Renders need room (frames, previews, the encode): warn early instead of failing mid-render. A real run had 66 MB left.-const MIN_FREE_GB = 5;-function diskWarning(id: string) {- try {- const f = statfsSync(PROJECTS), gb = (f.bavail * f.bsize) / 2 ** 30;- if (gb < MIN_FREE_GB) chat(id, 'system', L(id, `⚠️ 磁碟只剩 ${gb.toFixed(1)} GB,渲染可能中途失敗;建議先清出 ${MIN_FREE_GB} GB 以上。`, `⚠️ Only ${gb.toFixed(1)} GB of disk left; rendering may fail midway. Free at least ${MIN_FREE_GB} GB first.`));- } catch { /* statfs unsupported: skip */ }-}--// ---------- pre-production -----------const STYLE_OUT = ['analysis/STYLE.md', 'analysis/route.json', 'analysis/peaks.json']; // peaks: the reference's goosebump moments-export async function start(id: string) {- diskWarning(id);- if (!(await analyze(id))) return;- if (!(await step(id, 'styling', 'style', {}, STYLE_OUT, 'styled'))) return;- await preProduction(id);-}--// Pre-production as a small DAG: the director writes the plan core, then every character (one agent each) and the assets-// (one agent) are made at the same time, then the director merges them and paints the style frames with the real cast.-async function preProduction(id: string) {- const d = dirOf(id);- if (!(await step(id, 'planning', 'plan', {}, ['plan.json', 'STORYBOARD.md']))) return false;- const plan = readJSON<Plan>(join(d, 'plan.json')) || {};- const chars = (plan.characters || []).filter((c): c is typeof c & { file: string } => !!(c && c.id && c.file && /^build\//.test(c.file)));- const needAssets = (plan.assets || []).some((a) => a && a.status === 'to_fetch');- const work = [- ...chars.map((c) => turn(id, 'pre_cast', { character: c }, [c.file], { session: `cast-${c.id}`, who: `cast-${c.id}` }).then((r) => ({ what: `角色 ${c.name || c.id}`, ok: r.ok }))),- ...(needAssets ? [turn(id, 'pre_assets', {}, ['assets/fetched.json'], { session: 'fresh', who: 'assets' }).then((r) => ({ what: '素材', ok: r.ok }))] : []),- ];- if (work.length) chat(id, 'system', L(id, `企劃核心完成,${chars.length ? `${chars.length} 個角色` : ''}${chars.length && needAssets ? '和' : ''}${needAssets ? '素材' : ''}同時製作中`,- `Plan core done. Now drafting ${[chars.length ? `${chars.length} character${chars.length > 1 ? 's' : ''}` : '', needAssets ? 'the assets' : ''].filter(Boolean).join(' and ')} in parallel`));- const results = await Promise.all(work); // a failed helper is not fatal: the director finishes that part next- if (!(await step(id, 'planning', 'plan_frames', { results }, ['plan.json'], 'plan_review'))) return false;- return flushNotes(id);+ return cut;}--// Notes the user sent while the plan was being written: folded in with a replan as soon as the plan exists.-async function flushNotes(id: string): Promise<boolean> {- const notes = load(id).pendingNotes || [];- if (!notes.length) return true;- update(id, (x) => { x.pendingNotes = []; });- chat(id, 'system', L(id, '把企劃寫作期間你補充的意見修進企劃', 'Adding the notes you sent while the plan was being written'));- if (!(await step(id, 'replanning', 'replan', { message: notes.join('\n\n') }, ['plan.json'], 'plan_review'))) return false;- return flushNotes(id);+// After a restart, pick the interrupted jobs up again on their own (one real run sat cut off for 11.5 hours overnight).+// Staggered so they don't all launch agents at once. AUTO_RESUME=0 turns it off.+export function autoResume(ids: string[], gapMs = 5000) {+ ids.forEach((id, i) => setTimeout(() => {+ if (load(id).stage !== 'error') return; // the user already did something with it+ chat(id, 'system', L(id, '伺服器重新啟動後自動接續這一步。', 'Resuming this step automatically after the server restart.'));+ retry(id).catch((e) => console.error('auto-resume', id, e));+ }, (i + 1) * gapMs));}-export function busy(id: string) { return (running.get(id)?.size || 0) > 0 || ['analyzing', 'styling', 'planning', 'replanning', 'producing', 'revising', 'critiquing'].includes(load(id).stage); }+// ---------- the user's actions (each one is the project's single flow) ----------+export const start = (id: string) => run(id, () => fromAnalysis(id));export const PRE_PLAN: Stage[] = ['new', 'analyzing', 'styling', 'styled', 'planning', 'replanning']; // notes allowed while busy hereexport type MessageMeta = Pick<ChatMessage, 'shot' | 'time' | 'attachments' | 'notes'>;@@ -398,6 +126,9 @@ export async function message(id: string, text: string, meta: MessageMeta = {})if (['planning', 'replanning'].includes(j.stage)) update(id, (x) => { x.pendingNotes = [...(x.pendingNotes || []), tagged]; });return;}+ return run(id, () => noteFlow(id, j, tagged));+}+async function noteFlow(id: string, j: Job, tagged: string) {if (j.stage === 'plan_review' || (j.stage === 'error' && oneOf(j.failed, 'planning', 'replanning', 'styling'))) {if (!(await step(id, 'replanning', 'replan', { message: tagged }, ['plan.json'], 'plan_review'))) return false;return flushNotes(id);@@ -441,6 +172,9 @@ function snapshotEngine(id: string): EngineSnapshot | null {export async function approve(id: string) {const open = openInputs(id);if (open.length) throw Object.assign(new Error('還有需要你提供或略過的素材:' + open.map((r) => r.label || r.id).join('、')), { code: 409 });+ return run(id, () => approveFlow(id));+}+async function approveFlow(id: string) {await alignIfReady(id).catch(() => null); // lyrics pasted before the music arrived: time them now, before anything is builtupdate(id, (j) => { j.approvedAt = now(); j.approvedPlanVersion = readJSON<Plan>(join(dirOf(id), 'plan.json'))?.version; j.engineSnapshot = snapshotEngine(id); j.pipeline = {}; j.sessions = j.approvedAtPrev ? {} : Object.fromEntries(Object.entries(j.sessions || {}).filter(([k]) => k.startsWith('cast-'))); j.approvedAtPrev = true; j.needs = []; j.userNote = null; j.critiqueRounds = 0; });diskWarning(id);@@ -448,287 +182,12 @@ export async function approve(id: string) {if (await production(id, { fresh: true })) await finalPanel(id);}-// ---------- production: gates where defects are born -----------async function production(id: string, { fresh = false } = {}): Promise<boolean> {- const d = dirOf(id), prev: Pipeline = fresh ? {} : load(id).pipeline || {};- // a piece with no characters (typography, motion graphics) has no cast sheet to make- const sheet = (readJSON<Plan>(join(d, 'plan.json'))?.characters || []).length ? ['out/check/cast/sheet.jpg'] : [];- const hasSetup = !fresh && [join('build', 'production.json'), ...sheet].every((f) => existsSync(join(d, f)));- // 1) director: scaffold, shared assets, cast sheets, chunk plan (skipped when resuming)- if (!hasSetup) {- pipe(id, (p) => { p.phase = 'setup'; });- if (!(await step(id, 'producing', 'setup', {}, ['build/production.json', ...sheet]))) return false;- } else setStage(id, 'producing', { error: null, failed: null });- // 2) cast gate and 3) shot building run at the same time: shots only call the shared character definitions, so cast fixes- // flow into them automatically. Shot REVIEWS wait until the cast has passed, and re-grab fresh frames first.- prerenderStopped.delete(id); // a fresh or resumed production may render in the background again- const castP = castGate(id, prev);- if (!CONFIG.overlapCast && !(await castP)) return false; // characters are final before any shot is built- const prod = readJSON<Production>(join(d, 'build', 'production.json')) || {};- const chunks = prod.chunks || [];- const old = prev.chunks || {};- // a segment that stopped at its round limit already has a fresh review: resuming fixes those issues first instead of re-reviewing unchanged shots- pipe(id, (p) => { p.phase = 'shots'; p.chunks = Object.fromEntries(chunks.map((c): [string, ChunkProgress] => [c.id, old[c.id]?.state === 'passed' ? old[c.id] : { shots: c.shots, state: 'queued', round: 0, fixFirst: !!old[c.id]?.fixFirst || old[c.id]?.state === 'failed' }])); });- const runChunk = async (c: Chunk): Promise<boolean> => {- const key = `builder-${c.id}`, set = (s: Partial<ChunkProgress>) => pipe(id, (p) => Object.assign(p.chunks![c.id], s));- if (load(id).pipeline.chunks?.[c.id]?.state === 'passed') return true;- const SH = join(d, 'out', 'check', 'shots'), shotFile = (sid: string, kind: string) => join(SH, `${sid}.${kind}.json`);- // Every shot gets its own fresh reviewer as soon as the builder marks it done (<shot>.done.json), while the builder- // goes on with the next shot. Reviews still wait for the cast gate, and each one is a full review of that shot.- const reviews: Record<string, Promise<boolean>> = {}, results: Record<string, { entry: ShotEntry; needs: NeedRequest[]; verified: unknown[] }> = {};- const reviewShot = (sid: string, round: number) => (reviews[sid] = (async () => {- if (!(await castP)) return false;- const r = await reviewSlot(id, () => turn(id, 'shot_qa', { chunk: c, shots: [sid], round, out: `out/check/shots/${sid}.review.json` }, [`out/check/shots/${sid}.review.json`], { session: 'fresh', who: `shot-qa-${sid}` }));- if (!r.ok) return false;- const rv = readJSON<ChunkReview>(shotFile(sid, 'review')) || {};- results[sid] = { entry: (rv.shots || []).find((x) => x.id === sid) || { id: sid, pass: !!rv.pass, issues: rv.issues || [] }, needs: rv.needs_user || [], verified: rv.verified_fixes || [] };- return true;- })());- const mergeReview = () => { // the segment-level file the UI, fixes and resumes read- const all = c.shots.filter((x) => results[x]);- writeFileSync(join(SH, `${c.id}.review.json`), JSON.stringify({ shots: all.map((x) => results[x].entry), verified_fixes: all.flatMap((x) => results[x].verified), needs_user: all.flatMap((x) => results[x].needs) }, null, 1));- };- let reuse = load(id).pipeline.chunks?.[c.id]?.fixFirst && existsSync(join(SH, `${c.id}.review.json`));- if (reuse) set({ fixFirst: false });- if (fresh || !existsSync(join(SH, `${c.id}.done.json`))) {- set({ state: 'building' });- const t0 = Date.now(), seen = new Set();- const watch = setInterval(() => {- for (const sid of c.shots) if (!seen.has(sid) && existsSync(shotFile(sid, 'done')) && statSync(shotFile(sid, 'done')).mtimeMs > t0) { seen.add(sid); reviewShot(sid, 1); }- }, 4000);- const b = await turn(id, 'build_chunk', { chunk: c }, [`out/check/shots/${c.id}.done.json`], { session: key, who: key });- clearInterval(watch);- if (!b.ok) { set({ state: 'error' }); return false; }- }- if (!load(id).pipeline.cast?.pass) set({ state: 'waiting_cast' });- if (!(await castP)) { set({ state: 'built' }); return false; }- let todo = c.shots;- for (let round = 1; ; round++) {- set({ state: 'reviewing', round });- if (reuse) { // after a user note the latest review is still valid: fix first- const rv = readJSON<ChunkReview>(join(SH, `${c.id}.review.json`)) || {};- for (const e of rv.shots || []) results[e.id] = { entry: e, needs: [], verified: [] };- reuse = false;- } else {- for (const sid of todo) if (!reviews[sid] || round > 1) reviewShot(sid, round); // round 1: shots the watcher missed- const ok = await Promise.all(todo.map((sid) => reviews[sid]));- if (ok.includes(false)) { set({ state: 'error' }); return false; }- mergeReview();- }- const needs = c.shots.flatMap((x) => results[x]?.needs || []);- if (collectNeeds(id, needs, `shot-qa-${c.id}`)) { set({ state: 'needs_user' }); return false; }- const bad = c.shots.map((x) => results[x]?.entry).filter((e): e is ShotEntry => !!e && !shotPassed(e));- if (!bad.length) { set({ state: 'passed' }); prerender(id, c); return true; }- // one blocker left at the limit: one more round instead of pausing (a real run sat 23 minutes waiting to say "fix it")- const left = bad.flatMap((e) => e.issues || []).filter((x) => x.severity !== 'polish').length;- if (round >= rounds(id).chunkRounds + (left <= 1 ? 1 : 0)) { set({ state: 'failed', open: bad.length }); return false; }- set({ state: 'fixing' });- const f = await turn(id, 'fix_chunk', { chunk: c, bad, round, message: load(id).userNote }, [`out/check/shots/${c.id}.fixes.json`], { session: key, who: key });- if (!f.ok) { set({ state: 'error' }); return false; }- // shared-file problems (rig, cast, common assets) can't be fixed by a builder: the director fixes them right now,- // one at a time across segments, before this segment is reviewed again- const fx = readJSON<SharedItem[] | { fixes?: SharedItem[] }>(join(SH, `${c.id}.fixes.json`));- const shared = (Array.isArray(fx) ? fx : fx?.fixes || []).filter((x) => x && x.status === 'shared');- if (shared.length) {- set({ state: 'shared_fix' });- const ok = await sharedLock(id, async () => {- const r = await turn(id, 'shared_fix', { chunk: c, items: shared }, [`out/check/shots/${c.id}.shared.json`], { who: 'director' });- if (!r.ok) log(id, { type: 'error', text: `共用檔修正沒有完成(${c.id})` });- return r.ok;- });- if (ok) { // the builder applies the new shared feature in the same round, so the next review sees it- set({ state: 'fixing' });- const g = await turn(id, 'fix_chunk', { chunk: c, bad: shared.map((x) => ({ id: x.shot ?? '', issues: [{ issue: x.issue, fix: '導演已改好共用檔,照 shared.json 的 api 套用' }] })), round, message: load(id).userNote }, [`out/check/shots/${c.id}.fixes.json`], { session: key, who: key });- if (!g.ok) { set({ state: 'error' }); return false; }- }- }- todo = bad.map((e): string | undefined => e.id).concat(shared.map((x) => x.shot)).filter((x, i, A): x is string => !!x && A.indexOf(x) === i && c.shots.includes(x));- }- };- const queue = [...chunks], results: boolean[] = [];- await Promise.all(Array.from({ length: Math.max(1, Math.min(CONFIG.builders, chunks.length)) }, async () => {- while (queue.length) { const c = queue.shift()!; results.push(await runChunk(c)); }- }));- if (!(await castP)) return false; // the cast gate paused for the user; built segments are kept- const j = load(id);- if ((j.needs || []).length) return pause(id);- const failed = Object.entries(j.pipeline.chunks || {}).filter(([, v]) => v.state !== 'passed');- if (failed.length) { chat(id, 'system', L(id, `有 ${failed.length} 段沒通過鏡頭審查:${failed.map(([k, v]) => `${k}(${v.state})`).join('、')},請你看這幾段決定`, `${failed.length} part${failed.length > 1 ? 's' : ''} didn't pass shot review: ${failed.map(([k, v]) => `${k} (${v.state})`).join(', ')}. Please take a look and decide`)); setStage(id, 'needs_input'); return false; }- // 4) assemble (after the background renders of passed segments, so their frames are reused, not redrawn)- pipe(id, (p) => { p.phase = 'assemble'; });- await waitPrerenders(id);- return step(id, 'producing', 'assemble', {}, ['out/video.mp4'], 'done');-}-// ---------- cast gate -----------// Several characters, each in its own file → one reviewer + fixer pair per character, all at once; then one line-up check.-// One character, or everything in one file → the serial gate.-type CastResult = 'error' | 'needs' | 'passed' | 'failed' | 'shared';-async function castGate(id: string, prev: Pipeline): Promise<boolean> {- const d = dirOf(id), prod = readJSON<Production>(join(d, 'build', 'production.json')) || {};- const chars = (prod.characters || []).filter((c) => c && c.id && c.file && c.sheet);- const files = new Set(chars.map((c) => c.file));- const parallel = chars.length > 1 && files.size === chars.length && chars.every((c) => existsSync(join(d, c.sheet)));- if (prev.cast?.pass) return true;- if (!(prod.characters || []).length) { pipe(id, (p) => { p.cast = { round: 0, pass: true, state: 'passed' }; }); return true; } // no cast: nothing to review- if (!parallel) return castSerial(id, prev);- const setC = (cid: string, v: Partial<CastCharProgress>) => pipe(id, (p) => { const cast = p.cast!; cast.chars = cast.chars || {}; cast.chars[cid] = { ...(cast.chars[cid] ?? { state: 'queued', round: 0 }), ...v }; });- const keep: Record<string, CastCharProgress> = prev.cast?.mode === 'parallel' ? prev.cast.chars || {} : {}; // resuming: characters that already passed stay passed- pipe(id, (p) => { p.cast = { round: 0, pass: false, state: 'reviewing', mode: 'parallel', chars: Object.fromEntries(chars.map((c): [string, CastCharProgress] => [c.id, keep[c.id]?.state === 'passed' ? keep[c.id] : { state: 'queued', round: 0 }])) }; });- chat(id, 'system', L(id, `角色關:${chars.length} 個角色各自由一組審查+修正同時進行`, `Characters: reviewing and fixing ${chars.length} character${chars.length > 1 ? 's' : ''} in parallel`));- const shared: SharedItem[] = [];- const one = async (c: CastMember): Promise<CastResult> => {- // resuming a character that stopped at its round limit: its last review is still current, so fix those issues first- const reuse = keep[c.id]?.state === 'failed' && existsSync(join(d, 'out', 'check', 'cast', `review_${c.id}.json`));- for (let round = 1; ; round++) {- setC(c.id, { state: 'reviewing', round });- if (!(round === 1 && reuse)) {- const r = await turn(id, 'cast_qa', { round, character: c }, [`out/check/cast/review_${c.id}.json`], { session: 'fresh', who: `cast-qa-${c.id}` });- if (!r.ok) { setC(c.id, { state: 'error' }); return 'error'; }- }- 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'; }- 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'; }- const fx = readJSON<SharedItem[] | { fixes?: SharedItem[] }>(join(d, 'out', 'check', 'cast', `fixes_${c.id}.json`)) || [];- const sh = (Array.isArray(fx) ? fx : fx.fixes || []).filter((x) => x && x.status === 'shared');- if (sh.length) { shared.push(...sh.map((x) => ({ ...x, character: c.id }))); setC(c.id, { state: 'waiting_shared' }); return 'shared'; }- }- };- let res: CastResult[] = await Promise.all(chars.map((c) => (keep[c.id]?.state === 'passed' ? 'passed' : one(c))));- if (res.includes('needs')) return pause(id);- for (let k = 0; shared.length && k < rounds(id).castRounds; k++) { // skeleton changes: one director turn, then re-check who asked (and anyone it may affect)- pipe(id, (p) => { p.cast!.state = 'fixing'; });- const f = await turn(id, 'cast_fix', { issues: [...shared], round: 'shared', shared: true }, ['out/check/cast/sheet.jpg'], { who: 'director' });- if (!f.ok) return fail(id, 'producing', f);- shared.length = 0;- res = await Promise.all(chars.map((c, i) => (res[i] === 'passed' || res[i] === 'shared' ? one(c) : res[i])));- if (res.includes('needs')) return pause(id);- }- if (res.some((x) => x !== 'passed')) { pipe(id, (p) => { p.cast!.state = 'failed'; p.cast!.round = rounds(id).castRounds; }); chat(id, 'system', L(id, `角色關:${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join('、')} 審了 ${rounds(id).castRounds} 輪還沒通過,請你看設定圖決定`, `Characters: ${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join(', ')} still not passing after ${rounds(id).castRounds} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }- // every character passed on its own → one line-up check across them, then the serial gate handles anything it finds- pipe(id, (p) => { p.cast!.state = 'reviewing'; p.cast!.lineup = true; });- const r = await turn(id, 'cast_qa', { round: 'lineup', lineup: true }, ['out/check/cast/review.json'], { session: 'fresh', who: 'cast-qa' });- if (!r.ok) return fail(id, 'producing', r);- const rv = readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) || {};- 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, '角色關通過(每個角色各自通過+並排檢查)', 'Characters passed (each one on its own, then side by side)')); return true; }- return castSerial(id, { cast: { round: 0, pass: false } }, rv);-}--async function castSerial(id: string, prev: Pipeline, firstReview?: Review | null): Promise<boolean> {- const d = dirOf(id);- if (!prev.cast?.pass) pipe(id, (p) => { p.cast = { round: 0, pass: false }; });- for (let round = 1; !load(id).pipeline.cast?.pass; round++) {- pipe(id, (p) => { p.cast!.round = round; p.cast!.state = 'reviewing'; });- let rv: Review | null | undefined = firstReview; // the line-up check already reviewed: go straight to fixing- if (rv) firstReview = null;- else {- const r = await turn(id, 'cast_qa', { round }, ['out/check/cast/review.json'], { session: 'fresh', who: 'cast-qa' });- if (!r.ok) return fail(id, 'producing', r);- rv = readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) || {};- }- 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; }- 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);- }- return true;-}--// ---------- background render of passed segments -----------// Engines with a frame cache (render.mjs --frames) declare production.json "prerender": { cwd, cmd with {start} {end} }.-// When a segment passes review its final frames are rendered in the background, one segment at a time per project (they-// share out/frames/manifest.json), so assembly only redraws what changed afterwards. A real run spent 29 minutes-// re-rendering all 732 frames at assembly.-const prerenderQ = new Map<string, Promise<void>>(), prerenderProcs = new Map<string, Set<ChildProcess>>();-const PRERENDER_MAX_MS = (seconds: number) => Math.max(10 * 60e3, seconds * 24 * 6e3); // ~6 s a frame at worst, never under 10 min-const ASSEMBLY_WAIT_MS = +(process.env.PRERENDER_WAIT_MS || 10 * 60e3); // assembly waits this long for background renders, then stops them and renders what's missing itself-// Projects whose background renders were stopped: renders already queued behind the stopped one must not start later-// and write out/frames while assembly renders there too. Cleared when production (re)starts.-const prerenderStopped = new Set<string>();-function stopPrerenders(id: string) { prerenderStopped.add(id); for (const p of prerenderProcs.get(id) || []) p.kill(); prerenderQ.delete(id); }-export async function waitPrerenders(id: string, maxMs = ASSEMBLY_WAIT_MS) {- const q = prerenderQ.get(id); if (!q) return;- let timer: NodeJS.Timeout | undefined;- const late = await Promise.race([q.then(() => false), new Promise<boolean>((r) => { timer = setTimeout(() => r(true), maxMs); })]);- clearTimeout(timer);- if (late) { log(id, { type: 'error', text: `背景渲染超過 ${Math.round(maxMs / 60e3)} 分鐘,先停掉,組裝時補渲` }); stopPrerenders(id); }-}-function prerender(id: string, c: Chunk) {- const d = dirOf(id), pr = (readJSON<Production>(join(d, 'build', 'production.json')) || {}).prerender as { cwd?: string; cmd?: string; args?: string[] } | undefined;- if (!pr?.cmd && !pr?.args?.length) return;- type S = { id?: string; start_s?: number; end_s?: number };- const mine = ((readJSON<Plan>(join(d, 'plan.json'))?.shots || []) as S[]).filter((s) => s.id && c.shots.includes(s.id) && s.start_s != null && s.end_s != null);- if (!mine.length) return;- const a = Math.min(...mine.map((s) => s.start_s!)), b = Math.max(...mine.map((s) => s.end_s!));- // "args": ["node", "render.mjs", …] keeps arguments with spaces intact; "cmd" is split on whitespace- const fill = (x: string) => x.replace('{start}', a.toFixed(3)).replace('{end}', b.toFixed(3));- const [bin, ...args] = pr.args?.length ? pr.args.map(fill) : fill(pr.cmd!).split(/\s+/);- const run = () => new Promise<void>((resolve) => {- if (prerenderStopped.has(id) || load(id).stage === 'error') return resolve(); // stopped, cancelled or failed meanwhile- log(id, { type: 'tool', name: 'prerender', detail: `${c.id} ${a.toFixed(2)}–${b.toFixed(2)} s: ${bin} ${args.join(' ')}` });- const t0 = Date.now(), p = spawn(bin, args, { cwd: join(d, pr.cwd || 'build'), env: process.env, stdio: 'ignore' });- const set = prerenderProcs.get(id) || new Set(); set.add(p); prerenderProcs.set(id, set);- // a render that never exits must not hold the queue (seen: one sat 7 hours after finishing its frames)- const timer = setTimeout(() => p.kill(), PRERENDER_MAX_MS(b - a)); timer.unref();- let ended = false;- const done = (ok: boolean) => { if (ended) return; ended = true; clearTimeout(timer); set.delete(p); log(id, { type: ok ? 'text' : 'error', text: `背景渲染 ${c.id}:${ok ? `完成(${Math.round((Date.now() - t0) / 1000)} s)` : '失敗(組裝時會重渲)'}` }); resolve(); };- p.on('error', () => done(false)); p.on('close', (code) => done(code === 0));- });- prerenderQ.set(id, (prerenderQ.get(id) || Promise.resolve()).then(run));-}--// at most CONFIG.maxReviews shot reviews of one project at a time (each grabs frames in Chrome)-const reviewQ = new Map<string, { n: number; wait: (() => void)[] }>();-async function reviewSlot<T>(id: string, fn: () => Promise<T>): Promise<T> {- const q = reviewQ.get(id) || { n: 0, wait: [] }; reviewQ.set(id, q);- if (q.n >= CONFIG.maxReviews) await new Promise<void>((r) => q.wait.push(r)); // woken with the slot already counted- else q.n++;- try { return await fn(); } finally { const next = q.wait.shift(); if (next) next(); else q.n--; }-}--const sharedLocks = new Map<string, Promise<unknown>>(); // per project: one director edits shared files at a time-function sharedLock<T>(key: string, fn: () => Promise<T>): Promise<T> { const prev = sharedLocks.get(key) || Promise.resolve(); const next = prev.then(fn, fn); sharedLocks.set(key, next.catch(() => {})); return next; }--function pause(id: string) { setStage(id, 'needs_input'); return false; }--// ---------- final panel: seams, continuity, pacing; verifies every earlier fix -----------async function finalPanel(id: string) {- const d = dirOf(id);- let prevMust = Infinity;- for (let round = 1; ; round++) {- pipe(id, (p) => { p.phase = 'final'; p.final = { round }; });- if (!(await step(id, 'critiquing', 'critique', { round }, ['out/check/critique.json'], null, { session: 'fresh', who: 'critic' }))) return;- const c = readJSON<Critique>(join(d, 'out', 'check', 'critique.json')) || {};- const must = (c.must_fix || []).filter(Boolean);- // a climax that loses to the reference never passes, even if the critic forgot to list a fix for it- for (const pk of (c.peaks || []).filter((x) => x?.verdict === 'ref_better'))- if (!must.some((m) => m.issue.includes(pk.id))) must.push({ shot: pk.id, time: pk.ours?.[0], issue: `高潮 ${pk.id} 輸給參考片:${pk.why || ''}`, fix: `照 ${pk.strip || '高潮對照圖'} 逐格補上參考片爆點的手法,直到不輸參考片` });- const total = (load(id).critiqueRounds || 0) + 1; // every critic pass since approval (retries and user revisions included)- 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;- 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');- 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;- }-}--export async function retry(id: string) {+export const retry = (id: string) => run(id, () => retryFlow(id));+async function retryFlow(id: string) {const j = load(id), f = j.failed;update(id, (x) => { x.retryPending = true; });- if (f === 'analyzing') return start(id);- if (f === 'styling') { if (await step(id, 'styling', 'style', {}, STYLE_OUT, 'styled')) await preProduction(id); return; }+ if (f === 'analyzing') return fromAnalysis(id);+ if (f === 'styling') return fromStyle(id);if (f === 'planning') return preProduction(id);if (f === 'replanning') return step(id, 'replanning', 'replan', { message: [...j.chat].reverse().find((c) => c.role === 'user')?.text || '請重新整理企劃' }, ['plan.json'], 'plan_review');if (f === 'producing' || j.stage === 'needs_input') { if (await production(id)) await finalPanel(id); return; }@@ -736,10 +195,17 @@ export async function retry(id: string) {}// Resume after the user provided what was asked (or waived it)-export async function resume(id: string) { const j = load(id); update(id, (x) => { x.needs = []; }); if (existsSync(join(dirOf(id), 'out', 'video.mp4')) && j.pipeline?.phase === 'final') return finalPanel(id); if (await production(id)) await finalPanel(id); }+export const resume = (id: string) => run(id, () => resumeFlow(id));+async function resumeFlow(id: string) {+ const j = load(id);+ update(id, (x) => { x.needs = []; });+ if (existsSync(join(dirOf(id), 'out', 'video.mp4')) && j.pipeline?.phase === 'final') return finalPanel(id);+ if (await production(id)) await finalPanel(id);+}// The user looked at what the reviewers flagged and accepts it as is: mark the gate passed and keep going.-export async function accept(id: string) {+export const accept = (id: string) => run(id, () => acceptFlow(id));+async function acceptFlow(id: string) {const j = load(id), ph = j.pipeline?.cast && !j.pipeline.cast.pass ? 'cast' : j.pipeline?.phase;update(id, (x) => { x.needs = []; x.error = null; x.failed = null;if (ph === 'cast') x.pipeline.cast = { round: 0, ...x.pipeline.cast, pass: true, state: 'passed', acceptedByUser: true };@@ -749,5 +215,4 @@ export async function accept(id: string) {if (await production(id)) await finalPanel(id);}-export function cancel(id: string) { for (const ac of running.get(id) || []) ac.abort(); stopPrerenders(id); }-export async function critique(id: string) { return finalPanel(id); }+export const critique = (id: string) => run(id, () => finalPanel(id));diff --git a/app/server/pipeline.test.ts b/app/server/pipeline.test.tsindex b254c55..51a4c5d 100644--- a/app/server/pipeline.test.ts+++ b/app/server/pipeline.test.ts@@ -23,7 +23,12 @@ interface Scenario {critique: (round: number) => { must?: number; needs?: number; lostPeak?: boolean };buildDelayMs?: number; // let the per-shot watcher (every 4 s) pick shots upprerender?: string; // production.json prerender command+ blockers?: number; // blocker issues in a failing shot review (default 1)+ crash?: (step: string) => string | null; // this turn fails with that error text, writing nothing+ holdMs?: (step: string) => number; // this turn takes that long (ends early when cancelled)+ broken?: (step: string) => 'once' | 'always' | null; // its JSON files come out unreadable; 'once': the format fix repairs them}+const pending = new Map<string, { files: [string, unknown][]; always: boolean }>(); // per project: the good files a format fix writeslet S: Scenario;let calls: string[] = [];const count: Record<string, number> = {};@@ -61,7 +66,7 @@ function outputs(prompt: string, dir: string): [string, Record<string, unknown>]}if ((r = m(/## 步驟:審查鏡頭 (\S+?)(屬於段落 (\S+?),第 (\d+) 輪)/))) {const [sid, round] = [r[1], +r[3]], ok = S.shotPass(sid, round), out = m(/寫 (out\/check\/shots\/\S+?\.review\.json)(JSON)/)![1];- return [`shot_qa:${sid}:${round}`, { [out]: { shots: [{ id: sid, pass: ok, issues: ok ? [] : [{ issue: 'seam', severity: 'blocker' }] }] } }];+ return [`shot_qa:${sid}:${round}`, { [out]: { shots: [{ id: sid, pass: ok, issues: ok ? [] : Array.from({ length: S.blockers ?? 1 }, (_, i) => ({ issue: `seam ${i}`, severity: 'blocker' })) }] } }];}if ((r = m(/## 步驟:修鏡頭段 (\S+?)(/))) {const c = r[1], shared = S.sharedFix?.(c, bump(`sf-${c}`)), shot = S.chunks.find((x) => x.id === c)!.shots[0];@@ -77,16 +82,33 @@ function outputs(prompt: string, dir: string): [string, Record<string, unknown>]throw new Error('fake agent: unknown step\n' + prompt.slice(0, 300));}-async function fakeAgent({ cwd, prompt, onEvent }: AgentRun) {+async function fakeAgent({ cwd, prompt, onEvent, signal }: AgentRun) {const dir = resolve(cwd, prompt.match(/專案資料夾:(\S+?)[(。]/)![1]);+ if (/## 修正檔案格式/.test(prompt)) {+ calls.push('fix_format');+ const p = pending.get(dir); pending.delete(dir);+ if (p && !p.always) for (const [f, v] of p.files) put(dir, f, v);+ return { sessionId: 'sess-fix', text: 'fixed the format', ok: true, code: 0, stderr: '', lastError: '' };+ }const [name, files] = outputs(prompt, dir);calls.push(name);+ const hold = S.holdMs?.(name) || 0;+ if (hold) await new Promise<void>((r) => { const t = setTimeout(r, hold); signal?.addEventListener('abort', () => { clearTimeout(t); r(); }); });+ if (signal?.aborted) return { sessionId: null, text: '', ok: false, code: null, stderr: '', lastError: '' };+ const crash = S.crash?.(name);+ if (crash) return { sessionId: null, text: '', ok: false, code: 1, stderr: crash, lastError: crash };if (name.startsWith('build:') && S.buildDelayMs) { // shot files first, the segment file after the delayconst entries = Object.entries(files), last = entries.pop()!;for (const [f, v] of entries) put(dir, f, v);await new Promise((r) => setTimeout(r, S.buildDelayMs));put(dir, ...last);} else for (const [f, v] of Object.entries(files)) put(dir, f, v);+ const mode = S.broken?.(name);+ if (mode) {+ const json = Object.entries(files).filter(([f]) => f.endsWith('.json'));+ pending.set(dir, { files: json, always: mode === 'always' });+ for (const [f] of json) put(dir, f, '{ not json');+ }onEvent?.({ type: 'session', id: `sess-${calls.length}` });return { sessionId: `sess-${calls.length}`, text: `did ${name}`, ok: true, code: 0, stderr: '', lastError: '' };}@@ -381,3 +403,126 @@ describe('restart', () => {assert.ok(calls.includes('replan'));});});++describe('one flow per project', () => {+ test('an agent that fails inside the parallel cast gate is reported as that error, not as a failed review', async () => {+ S = base({ chars: ['hero', 'cat'], crash: (s) => (s === 'cast_qa:cat' ? 'You hit your limit' : null) });+ const id = newProject('plan_review');+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'error');+ assert.equal(j.failed, 'producing');+ assert.match(j.error || '', /用量到上限|usage limit/);+ assert.ok(!calls.includes('assemble'));+ });++ test('an agent that fails on the shot line is reported as that error, not as a part to judge', async () => {+ S = base({ crash: (s) => (s === 'build:C2' ? 'segfault' : null) });+ const id = newProject('plan_review');+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'error', j.chat.at(-1)?.text);+ assert.match(j.error || '', /缺少輸出:out\/check\/shots\/C2\.done\.json/);+ assert.ok(!j.chat.some((c) => /沒通過鏡頭審查/.test(c.text)));+ });++ test('a second flow is refused while one runs, and busy() says so', async () => {+ S = base({ holdMs: (s) => (s === 'setup' ? 300 : 0) });+ const id = newProject('plan_review');+ const first = J.approve(id);+ assert.equal(J.busy(id), true);+ await assert.rejects(J.retry(id), (e: Error & { code?: number }) => e.code === 409);+ await first;+ assert.equal(J.busy(id), false);+ assert.equal(J.load(id).stage, 'done');+ });++ test('cancel stops the whole run: no new segment starts after it', async () => {+ S = base({ chunks: ['C1', 'C2', 'C3', 'C4'].map((c, i) => ({ id: c, shots: [`S${i + 1}`] })), holdMs: (s) => (s.startsWith('build:') ? 400 : 0) });+ const id = newProject('plan_review');+ const saved = J.CONFIG.builders; J.CONFIG.builders = 1;+ try {+ const flow = J.approve(id);+ while (!calls.includes('build:C1')) await new Promise((r) => setTimeout(r, 10));+ J.cancel(id);+ await flow;+ } finally { J.CONFIG.builders = saved; }+ const j = J.load(id);+ assert.equal(j.stage, 'error');+ assert.match(j.error || '', /已取消|Cancelled/);+ assert.deepEqual(calls.filter((c) => c.startsWith('build:')), ['build:C1']);+ assert.equal(J.busy(id), false);+ });+});++describe('round limits', () => {+ test('final review: after finalRounds revises it stops and leaves the call to the user', async () => {+ S = base({ critique: () => ({ must: 1 }) });+ const id = newProject('plan_review');+ J.setRounds(id, { finalRounds: 1 });+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'done');+ assert.deepEqual(calls.slice(-3), ['critique', 'revise', 'critique']);+ assert.match(j.chat.at(-1)!.text, /自動修改上限|fix limit/);+ });++ test('parallel cast gate: a character that never passes stops the gate and is named', async () => {+ S = base({ chars: ['hero', 'cat'], castPass: (w) => w !== 'cat' });+ const id = newProject('plan_review');+ J.setRounds(id, { castRounds: 2 });+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'needs_input');+ assert.equal(j.pipeline.cast!.chars!.cat.state, 'failed');+ assert.equal(j.pipeline.cast!.chars!.hero.state, 'passed');+ assert.deepEqual(calls.filter((c) => c.includes('cat')), ['cast_qa:cat', 'cast_fix:cat', 'cast_qa:cat']);+ assert.match(j.chat.at(-1)!.text, /cat/);+ assert.ok(!calls.includes('cast_qa:lineup'));+ });++ test('a note on a segment stopped at its limit fixes first, then re-reviews only the bad shot (the reused review is not a round)', async () => {+ S = base({ shotPass: (s, r) => s !== 'S2' || r >= 2, blockers: 2 }); // two blockers: no extra round for a single one+ const id = newProject('plan_review');+ J.setRounds(id, { chunkRounds: 1 });+ await J.approve(id);+ assert.equal(J.load(id).pipeline.chunks!.C2.state, 'failed');+ calls = [];+ await J.message(id, 'the seam at S2 is fine if you soften it');+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ assert.deepEqual(calls, ['fix:C2', 'shot_qa:S2:2', 'assemble', 'critique']);+ });++ test('resuming a character stopped at its limit fixes it first (the reused review is not a round)', async () => {+ S = base({ chars: ['hero', 'cat'], castPass: (w, r) => w !== 'cat' || r >= 2 });+ const id = newProject('plan_review');+ J.setRounds(id, { castRounds: 1 });+ await J.approve(id);+ assert.equal(J.load(id).pipeline.cast!.chars!.cat.state, 'failed');+ calls = [];+ await J.resume(id);+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ assert.deepEqual(calls.filter((c) => c.startsWith('cast')), ['cast_fix:cat', 'cast_qa:cat', 'cast_qa:lineup']);+ });+});++describe('contract check', () => {+ test('a review that comes out unreadable goes back to its reviewer once, then the line goes on', async () => {+ S = base({ broken: (s) => (s === 'shot_qa:S1:1' ? 'once' : null) });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ assert.ok(calls.indexOf('fix_format') > calls.indexOf('shot_qa:S1:1')); // reviews run side by side: not necessarily the very next call+ assert.equal(calls.filter((c) => c === 'fix_format').length, 1);+ });++ test('a production plan that stays broken stops the job and says what is wrong', async () => {+ S = base({ broken: (s) => (s === 'setup' ? 'always' : null) });+ const id = newProject('plan_review');+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'error');+ assert.match(j.error || '', /格式不對.*build\/production\.json: not valid JSON/);+ assert.ok(!calls.some((c) => c.startsWith('build:')));+ });+});diff --git a/app/server/preprod.ts b/app/server/preprod.tsnew file mode 100644index 0000000..b7300b2--- /dev/null+++ b/app/server/preprod.ts@@ -0,0 +1,67 @@+// Pre-production: measure the reference (analyze.py), style it (director), then the plan as a small DAG — the director+// writes the plan core, every character (one agent each) and the assets (one agent) are drafted at the same time, then the+// director merges them and paints the style frames with the real cast. Ends in plan_review, waiting for the user.+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { aborted, spawnTool } from './runner.ts';+import { CANCELLED, L, PY, ROOT, SCRIPTS, chat, diskWarning, dirOf, load, log, noPython, readJSON, setStage, update } from './store.ts';+import { step, turn } from './turn.ts';+import type { Plan } from '../shared/types.ts';++function analyze(id: string): Promise<boolean> {+ const j = load(id), d = dirOf(id), src = j.reference.type === 'url' ? j.reference.src : join(d, j.reference.src);+ setStage(id, 'analyzing');+ log(id, { type: 'tool', name: 'analyze.py', detail: j.reference.src });+ return new Promise((resolve) => {+ const p = spawnTool(id, PY, [join(SCRIPTS, 'analyze.py'), src, '--out', join(d, 'analysis')], { cwd: ROOT, env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });+ p.stdout.on('data', (b) => String(b).split('\n').filter(Boolean).forEach((l) => log(id, { type: 'text', text: l })));+ p.stderr.on('data', (b) => { const s = String(b); if (!/Warning|warn\(/i.test(s)) log(id, { type: 'error', text: s.slice(0, 400) }); });+ let done = false;+ const finish = (code: number | null, err?: Error) => {+ if (done) return; done = true;+ const ok = code === 0 && existsSync(join(d, 'analysis', 'report.json'));+ if (!ok) setStage(id, 'error', { failed: 'analyzing', error: err ? noPython(err) : aborted(id) ? L(id, CANCELLED.zh, CANCELLED.en) : 'analyze.py failed' });+ resolve(ok);+ };+ p.on('error', (e) => finish(null, e)); // e.g. Python not found: without this listener the server crashes+ p.on('close', (code) => finish(code));+ });+}++export async function fromAnalysis(id: string) {+ diskWarning(id);+ if (!(await analyze(id))) return;+ await fromStyle(id);+}+const STYLE_OUT = ['analysis/STYLE.md', 'analysis/route.json', 'analysis/peaks.json']; // peaks: the reference's goosebump moments+export async function fromStyle(id: string) {+ if (!(await step(id, 'styling', 'style', {}, STYLE_OUT, 'styled'))) return;+ await preProduction(id);+}++export async function preProduction(id: string) {+ const d = dirOf(id);+ if (!(await step(id, 'planning', 'plan', {}, ['plan.json', 'STORYBOARD.md']))) return false;+ const plan = readJSON<Plan>(join(d, 'plan.json')) || {};+ const chars = (plan.characters || []).filter((c): c is typeof c & { file: string } => !!(c && c.id && c.file && /^build\//.test(c.file)));+ const needAssets = (plan.assets || []).some((a) => a && a.status === 'to_fetch');+ const work = [+ ...chars.map((c) => turn(id, 'pre_cast', { character: c }, [c.file], { session: `cast-${c.id}`, who: `cast-${c.id}` }).then((r) => ({ what: `角色 ${c.name || c.id}`, ok: r.ok }))),+ ...(needAssets ? [turn(id, 'pre_assets', {}, ['assets/fetched.json'], { session: 'fresh', who: 'assets' }).then((r) => ({ what: '素材', ok: r.ok }))] : []),+ ];+ if (work.length) chat(id, 'system', L(id, `企劃核心完成,${chars.length ? `${chars.length} 個角色` : ''}${chars.length && needAssets ? '和' : ''}${needAssets ? '素材' : ''}同時製作中`,+ `Plan core done. Now drafting ${[chars.length ? `${chars.length} character${chars.length > 1 ? 's' : ''}` : '', needAssets ? 'the assets' : ''].filter(Boolean).join(' and ')} in parallel`));+ const results = await Promise.all(work); // a failed helper is not fatal: the director finishes that part next+ if (!(await step(id, 'planning', 'plan_frames', { results }, ['plan.json'], 'plan_review'))) return false;+ return flushNotes(id);+}++// Notes the user sent while the plan was being written: folded in with a replan as soon as the plan exists.+export async function flushNotes(id: string): Promise<boolean> {+ const notes = load(id).pendingNotes || [];+ if (!notes.length) return true;+ update(id, (x) => { x.pendingNotes = []; });+ chat(id, 'system', L(id, '把企劃寫作期間你補充的意見修進企劃', 'Adding the notes you sent while the plan was being written'));+ if (!(await step(id, 'replanning', 'replan', { message: notes.join('\n\n') }, ['plan.json'], 'plan_review'))) return false;+ return flushNotes(id);+}diff --git a/app/server/prerender.ts b/app/server/prerender.tsnew file mode 100644index 0000000..e23efc3--- /dev/null+++ b/app/server/prerender.ts@@ -0,0 +1,51 @@+// Background render of passed segments.+// Engines with a frame cache (render.mjs --frames) declare production.json "prerender": { cwd, cmd with {start} {end} }.+// When a segment passes review its final frames are rendered in the background, one segment at a time per project (they+// share out/frames/manifest.json), so assembly only redraws what changed afterwards. A real run spent 29 minutes+// re-rendering all 732 frames at assembly. The processes are tool processes (runner.ts): Cancel stops them too.+import type { ChildProcess } from 'node:child_process';+import { join } from 'node:path';+import { killTree, spawnTool } from './runner.ts';+import { dirOf, load, log, readJSON } from './store.ts';+import type { Plan } from '../shared/types.ts';+import type { Chunk, Production } from './types.ts';++const queue = new Map<string, Promise<void>>(), procs = new Map<string, Set<ChildProcess>>();+const MAX_MS = (seconds: number) => Math.max(10 * 60e3, seconds * 24 * 6e3); // ~6 s a frame at worst, never under 10 min+const ASSEMBLY_WAIT_MS = +(process.env.PRERENDER_WAIT_MS || 10 * 60e3); // assembly waits this long for background renders, then stops them and renders what's missing itself+// Projects whose background renders were stopped: renders already queued behind the stopped one must not start later+// and write out/frames while assembly renders there too. Cleared when production (re)starts.+const stopped = new Set<string>();++export function resetPrerenders(id: string) { stopped.delete(id); }+export function stopPrerenders(id: string) { stopped.add(id); for (const p of procs.get(id) || []) killTree(p); queue.delete(id); }+export async function waitPrerenders(id: string, maxMs = ASSEMBLY_WAIT_MS) {+ const q = queue.get(id); if (!q) return;+ let timer: NodeJS.Timeout | undefined;+ const late = await Promise.race([q.then(() => false), new Promise<boolean>((r) => { timer = setTimeout(() => r(true), maxMs); })]);+ clearTimeout(timer);+ if (late) { log(id, { type: 'error', text: `背景渲染超過 ${Math.round(maxMs / 60e3)} 分鐘,先停掉,組裝時補渲` }); stopPrerenders(id); }+}+export function prerender(id: string, c: Chunk) {+ const d = dirOf(id), pr = (readJSON<Production>(join(d, 'build', 'production.json')) || {}).prerender as { cwd?: string; cmd?: string; args?: string[] } | undefined;+ if (!pr?.cmd && !pr?.args?.length) return;+ type S = { id?: string; start_s?: number; end_s?: number };+ const mine = ((readJSON<Plan>(join(d, 'plan.json'))?.shots || []) as S[]).filter((s) => s.id && c.shots.includes(s.id) && s.start_s != null && s.end_s != null);+ if (!mine.length) return;+ const a = Math.min(...mine.map((s) => s.start_s!)), b = Math.max(...mine.map((s) => s.end_s!));+ // "args": ["node", "render.mjs", …] keeps arguments with spaces intact; "cmd" is split on whitespace+ const fill = (x: string) => x.replace('{start}', a.toFixed(3)).replace('{end}', b.toFixed(3));+ const [bin, ...args] = pr.args?.length ? pr.args.map(fill) : fill(pr.cmd!).split(/\s+/);+ const run = () => new Promise<void>((resolve) => {+ if (stopped.has(id) || load(id).stage === 'error') return resolve(); // stopped, cancelled or failed meanwhile+ log(id, { type: 'tool', name: 'prerender', detail: `${c.id} ${a.toFixed(2)}–${b.toFixed(2)} s: ${bin} ${args.join(' ')}` });+ const t0 = Date.now(), p = spawnTool(id, bin, args, { cwd: join(d, pr.cwd || 'build'), env: process.env, stdio: 'ignore' });+ const set = procs.get(id) || new Set(); set.add(p); procs.set(id, set);+ // a render that never exits must not hold the queue (seen: one sat 7 hours after finishing its frames)+ const timer = setTimeout(() => killTree(p), MAX_MS(b - a)); timer.unref();+ let ended = false;+ const done = (ok: boolean) => { if (ended) return; ended = true; clearTimeout(timer); set.delete(p); log(id, { type: ok ? 'text' : 'error', text: `背景渲染 ${c.id}:${ok ? `完成(${Math.round((Date.now() - t0) / 1000)} s)` : '失敗(組裝時會重渲)'}` }); resolve(); };+ p.on('error', () => done(false)); p.on('close', (code) => done(code === 0));+ });+ queue.set(id, (queue.get(id) || Promise.resolve()).then(run));+}diff --git a/app/server/production.ts b/app/server/production.tsnew file mode 100644index 0000000..d872026--- /dev/null+++ b/app/server/production.ts@@ -0,0 +1,149 @@+// Production after approval: setup (director) → cast gate → shot line (N builders in parallel; every shot is reviewed by+// a fresh shot_qa as soon as it is built ⇄ fix_chunk; passed segments render in the background) → assemble (director).+// With OVERLAP_CAST=1 the shot line starts while the cast gate is still running.+// Quality is checked where defects are born (each character, each segment), not only at the end.+import { existsSync, writeFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { castGate } from './cast.ts';+import { prerender, resetPrerenders, waitPrerenders } from './prerender.ts';+import { blockerFree, reviewFix, sharedItems } from './review.ts';+import { aborted } from './runner.ts';+import { CONFIG, L, chat, collectNeeds, dirOf, load, log, pause, pipe, readJSON, rounds, setStage } from './store.ts';+import { fail, step, turn, type TurnResult } from './turn.ts';+import type { ChunkProgress, NeedRequest, Pipeline, Plan } from '../shared/types.ts';+import type { Chunk, ChunkReview, Production, ShotEntry } from './types.ts';++const sharedLocks = new Map<string, Promise<unknown>>(); // per project: one director edits shared files at a time+function sharedLock<T>(key: string, fn: () => Promise<T>): Promise<T> { const prev = sharedLocks.get(key) || Promise.resolve(); const next = prev.then(fn, fn); sharedLocks.set(key, next.catch(() => {})); return next; }++const STATE = { error: 'error', needs: 'needs_user', passed: 'passed', limit: 'failed', handoff: 'error' } as const;++// at most CONFIG.maxReviews shot reviews of one project at a time (each grabs frames in Chrome)+const reviewQ = new Map<string, { n: number; wait: (() => void)[] }>();+async function reviewSlot<T>(id: string, fn: () => Promise<T>): Promise<T> {+ const q = reviewQ.get(id) || { n: 0, wait: [] }; reviewQ.set(id, q);+ if (q.n >= CONFIG.maxReviews) await new Promise<void>((r) => q.wait.push(r)); // woken with the slot already counted+ else q.n++;+ try { return await fn(); } finally { const next = q.wait.shift(); if (next) next(); else q.n--; }+}++export async function production(id: string, { fresh = false } = {}): Promise<boolean> {+ const d = dirOf(id), prev: Pipeline = fresh ? {} : load(id).pipeline || {};+ // a piece with no characters (typography, motion graphics) has no cast sheet to make+ const sheet = (readJSON<Plan>(join(d, 'plan.json'))?.characters || []).length ? ['out/check/cast/sheet.jpg'] : [];+ const hasSetup = !fresh && [join('build', 'production.json'), ...sheet].every((f) => existsSync(join(d, f)));+ // 1) director: scaffold, shared assets, cast sheets, chunk plan (skipped when resuming)+ if (!hasSetup) {+ pipe(id, (p) => { p.phase = 'setup'; });+ if (!(await step(id, 'producing', 'setup', {}, ['build/production.json', ...sheet]))) return false;+ } else setStage(id, 'producing', { error: null, failed: null });+ // 2) cast gate, then 3) shot building. With overlapCast they run at the same time: shots only call the shared character+ // definitions, so cast fixes flow into them; shot REVIEWS still wait until the cast has passed.+ resetPrerenders(id); // a fresh or resumed production may render in the background again+ const castP = castGate(id, prev);+ if (!CONFIG.overlapCast && !(await castP)) return false; // characters are final before any shot is built+ const prod = readJSON<Production>(join(d, 'build', 'production.json')) || {};+ const chunks = prod.chunks || [];+ const old = prev.chunks || {};+ let broken = null as TurnResult | null; // the first agent turn that failed: reported as itself, not as "didn't pass review"+ // a segment that stopped at its round limit already has a fresh review: resuming fixes those issues first instead of re-reviewing unchanged shots+ pipe(id, (p) => { p.phase = 'shots'; p.chunks = Object.fromEntries(chunks.map((c): [string, ChunkProgress] => [c.id, old[c.id]?.state === 'passed' ? old[c.id] : { shots: c.shots, state: 'queued', round: 0, fixFirst: !!old[c.id]?.fixFirst || old[c.id]?.state === 'failed' }])); });+ const runChunk = async (c: Chunk): Promise<boolean> => {+ const key = `builder-${c.id}`, set = (s: Partial<ChunkProgress>) => pipe(id, (p) => Object.assign(p.chunks![c.id], s));+ if (load(id).pipeline.chunks?.[c.id]?.state === 'passed') return true;+ const SH = join(d, 'out', 'check', 'shots'), shotFile = (sid: string, kind: string) => join(SH, `${sid}.${kind}.json`);+ // Every shot gets its own fresh reviewer as soon as the builder marks it done (<shot>.done.json), while the builder+ // goes on with the next shot. Reviews still wait for the cast gate, and each one is a full review of that shot.+ const reviews: Record<string, Promise<boolean>> = {}, results: Record<string, { entry: ShotEntry; needs: NeedRequest[]; verified: unknown[] }> = {};+ const reviewShot = (sid: string, round: number) => (reviews[sid] = (async () => {+ if (!(await castP)) return false;+ const r = await reviewSlot(id, () => turn(id, 'shot_qa', { chunk: c, shots: [sid], round, out: `out/check/shots/${sid}.review.json` }, [`out/check/shots/${sid}.review.json`], { session: 'fresh', who: `shot-qa-${sid}` }));+ if (!r.ok) { broken ??= r; return false; }+ const rv = readJSON<ChunkReview>(shotFile(sid, 'review')) || {};+ results[sid] = { entry: (rv.shots || []).find((x) => x.id === sid) || { id: sid, pass: !!rv.pass, issues: rv.issues || [] }, needs: rv.needs_user || [], verified: rv.verified_fixes || [] };+ return true;+ })());+ const mergeReview = () => { // the segment-level file the UI, fixes and resumes read+ const all = c.shots.filter((x) => results[x]);+ writeFileSync(join(SH, `${c.id}.review.json`), JSON.stringify({ shots: all.map((x) => results[x].entry), verified_fixes: all.flatMap((x) => results[x].verified), needs_user: all.flatMap((x) => results[x].needs) }, null, 1));+ };+ let reuse = load(id).pipeline.chunks?.[c.id]?.fixFirst && existsSync(join(SH, `${c.id}.review.json`));+ if (reuse) set({ fixFirst: false });+ if (fresh || !existsSync(join(SH, `${c.id}.done.json`))) {+ set({ state: 'building' });+ const t0 = Date.now(), seen = new Set();+ const watch = setInterval(() => {+ for (const sid of c.shots) if (!seen.has(sid) && existsSync(shotFile(sid, 'done')) && statSync(shotFile(sid, 'done')).mtimeMs > t0) { seen.add(sid); reviewShot(sid, 1); }+ }, 4000);+ const b = await turn(id, 'build_chunk', { chunk: c }, [`out/check/shots/${c.id}.done.json`], { session: key, who: key });+ clearInterval(watch);+ if (!b.ok) { broken ??= b; set({ state: 'error' }); return false; }+ }+ if (!load(id).pipeline.cast?.pass) set({ state: 'waiting_cast' });+ if (!(await castP)) { set({ state: 'built' }); return false; }+ let todo = c.shots, reused = false;+ const { end, last } = await reviewFix<{ bad: ShotEntry[]; needs: NeedRequest[] }>({+ review: async (round) => {+ set({ state: 'reviewing', round });+ if (reuse) { // after a user note the latest review is still valid: fix first+ const rv = readJSON<ChunkReview>(join(SH, `${c.id}.review.json`)) || {};+ for (const e of rv.shots || []) results[e.id] = { entry: e, needs: [], verified: [] };+ reuse = false; reused = true;+ } else {+ for (const sid of todo) if (!reviews[sid] || round > 1) reviewShot(sid, round); // round 1: shots the watcher missed+ const ok = await Promise.all(todo.map((sid) => reviews[sid]));+ if (ok.includes(false)) return null;+ mergeReview();+ }+ return { needs: c.shots.flatMap((x) => results[x]?.needs || []), bad: c.shots.map((x) => results[x]?.entry).filter((e): e is ShotEntry => !!e && !blockerFree(e)) };+ },+ verdict: (r) => (collectNeeds(id, r.needs, `shot-qa-${c.id}`) ? 'needs' : r.bad.length ? 'fix' : 'passed'),+ // a reused review isn't a round: the user's note still gets its fixes. One blocker left at the limit: one more round+ // instead of pausing (a real run sat 23 minutes waiting to say "fix it")+ limit: ({ bad }) => rounds(id).chunkRounds + (reused ? 1 : 0) + (bad.flatMap((e) => e.issues || []).filter((x) => x.severity !== 'polish').length <= 1 ? 1 : 0),+ fix: async ({ bad }, round) => {+ 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) { broken ??= f; return 'error'; }+ // shared-file problems (rig, cast, common assets) can't be fixed by a builder: the director fixes them right now,+ // one at a time across segments, before this segment is reviewed again+ const shared = sharedItems(readJSON(join(SH, `${c.id}.fixes.json`)));+ if (shared.length) {+ set({ state: 'shared_fix' });+ const ok = await sharedLock(id, async () => {+ const r = await turn(id, 'shared_fix', { chunk: c, items: shared }, [`out/check/shots/${c.id}.shared.json`], { who: 'director' });+ if (!r.ok) log(id, { type: 'error', text: `共用檔修正沒有完成(${c.id})` });+ return r.ok;+ });+ if (ok) { // the builder applies the new shared feature in the same round, so the next review sees it+ set({ state: 'fixing' });+ const g = await turn(id, 'fix_chunk', { chunk: c, bad: shared.map((x) => ({ id: x.shot ?? '', issues: [{ issue: x.issue, fix: '導演已改好共用檔,照 shared.json 的 api 套用' }] })), round, message: load(id).userNote }, [`out/check/shots/${c.id}.fixes.json`], { session: key, who: key });+ if (!g.ok) { broken ??= g; return 'error'; }+ }+ }+ todo = bad.map((e): string | undefined => e.id).concat(shared.map((x) => x.shot)).filter((x, i, A): x is string => !!x && A.indexOf(x) === i && c.shots.includes(x));+ return 'ok';+ },+ });+ set(end === 'limit' ? { state: 'failed', open: last!.bad.length } : { state: STATE[end] });+ if (end === 'passed') prerender(id, c);+ return end === 'passed';+ };+ const queue = [...chunks];+ await Promise.all(Array.from({ length: Math.max(1, Math.min(CONFIG.builders, chunks.length)) }, async () => {+ while (queue.length && !aborted(id)) await runChunk(queue.shift()!);+ }));+ if (!(await castP)) return false; // the cast gate paused for the user; built segments are kept+ if (broken) return fail(id, 'producing', broken);+ const j = load(id);+ if ((j.needs || []).length) return pause(id);+ const failed = Object.entries(j.pipeline.chunks || {}).filter(([, v]) => v.state !== 'passed');+ if (failed.length) {+ chat(id, 'system', L(id, `有 ${failed.length} 段沒通過鏡頭審查:${failed.map(([k, v]) => `${k}(${v.state})`).join('、')},請你看這幾段決定`, `${failed.length} part${failed.length > 1 ? 's' : ''} didn't pass shot review: ${failed.map(([k, v]) => `${k} (${v.state})`).join(', ')}. Please take a look and decide`));+ return pause(id);+ }+ // 4) assemble (after the background renders of passed segments, so their frames are reused, not redrawn)+ pipe(id, (p) => { p.phase = 'assemble'; });+ await waitPrerenders(id);+ return step(id, 'producing', 'assemble', {}, ['out/video.mp4'], 'done');+}diff --git a/app/server/python.test.ts b/app/server/python.test.tsindex 58755d1..1cf6812 100644--- a/app/server/python.test.ts+++ b/app/server/python.test.ts@@ -29,6 +29,6 @@ describe('Python missing', () => {writeFileSync(join(J.dirOf(id), 'inputs', 'song.mp3'), '');const r = await J.saveLyrics(id, '第一句\n第二句');assert.deepEqual({ ok: r.ok, aligned: r.aligned }, { ok: false, aligned: false });- assert.ok(J.load(id).log?.some((e) => e.type === 'error' && /could not be started/.test(e.text || '')));+ assert.ok(J.snapshot(id).job.log.some((e) => e.type === 'error' && /could not be started/.test(e.text || ''))); // the log lives in events.jsonl, not job.json});});diff --git a/app/server/review.test.ts b/app/server/review.test.tsnew file mode 100644index 0000000..11765b6--- /dev/null+++ b/app/server/review.test.ts@@ -0,0 +1,50 @@+// review.ts: the review → fix loop every gate shares, and the pass rule.+import { describe, test } from 'node:test';+import assert from 'node:assert/strict';+import { blockerFree, reviewFix, sharedItems } from './review.ts';++const trace = (passAt: number, o: { limit?: number; failFix?: number; needsAt?: number; handoffAt?: number } = {}) => {+ const seen: string[] = [];+ return reviewFix<number>({+ review: async (r) => { seen.push(`review ${r}`); return r; },+ verdict: (r) => (r === o.needsAt ? 'needs' : r >= passAt ? 'passed' : 'fix'),+ limit: () => o.limit ?? 3,+ fix: async (r) => { seen.push(`fix ${r}`); return r === o.failFix ? 'error' : r === o.handoffAt ? 'handoff' : 'ok'; },+ }).then((res) => ({ ...res, seen }));+};++describe('reviewFix', () => {+ test('review → fix until it passes', async () => {+ const r = await trace(3);+ assert.equal(r.end, 'passed'); assert.equal(r.round, 3);+ assert.deepEqual(r.seen, ['review 1', 'fix 1', 'review 2', 'fix 2', 'review 3']);+ });+ test('stops at the limit without a last fix', async () => {+ const r = await trace(9, { limit: 2 });+ assert.equal(r.end, 'limit'); assert.equal(r.last, 2);+ assert.deepEqual(r.seen, ['review 1', 'fix 1', 'review 2']);+ });+ test('needs, a failed fix and a handoff end the loop', async () => {+ assert.equal((await trace(9, { needsAt: 2 })).end, 'needs');+ assert.equal((await trace(9, { failFix: 1 })).end, 'error');+ assert.equal((await trace(9, { handoffAt: 2 })).end, 'handoff');+ });+ test('a failed review ends it as an error', async () => {+ const r = await reviewFix<number>({ review: async () => null, verdict: () => 'passed', limit: () => 3, fix: async () => 'ok' });+ assert.deepEqual(r, { end: 'error', round: 1, last: null });+ });+});++describe('blockerFree', () => {+ test('only polish left passes; any blocker fails; no severities → the pass flag', () => {+ assert.equal(blockerFree({ issues: [{ issue: 'a', severity: 'polish' }] }), true);+ assert.equal(blockerFree({ issues: [{ issue: 'a', severity: 'polish' }, { issue: 'b', severity: 'blocker' }], pass: true }), false);+ assert.equal(blockerFree({ issues: [{ issue: 'a' }], pass: true }), true);+ assert.equal(blockerFree({}), false);+ });+ test('sharedItems reads both file shapes', () => {+ assert.deepEqual(sharedItems([{ status: 'shared', issue: 'x' }, { status: 'fixed', issue: 'y' } as never]), [{ status: 'shared', issue: 'x' }]);+ assert.equal(sharedItems({ fixes: [{ status: 'shared', issue: 'x' }] }).length, 1);+ assert.deepEqual(sharedItems(null), []);+ });+});diff --git a/app/server/review.ts b/app/server/review.tsnew file mode 100644index 0000000..45e979f--- /dev/null+++ b/app/server/review.ts@@ -0,0 +1,33 @@+// The review → fix loop every gate runs (each character, the cast as a whole, each segment, the final panel): a fresh+// reviewer looks, needs_user items pause, a clean review passes, otherwise the fixer works on what was found — until the+// project's round limit, where the job stops and asks the user instead of looping.+import type { Issue } from '../shared/types.ts';+import type { SharedItem } from './types.ts';++export type LoopEnd = 'passed' | 'needs' | 'limit' | 'error' | 'handoff';+export interface Loop<R> {+ review: (round: number) => Promise<R | null>; // null: the review turn failed+ verdict: (r: R, round: number) => 'passed' | 'needs' | 'fix';+ limit: (r: R, round: number) => number; // read every round: a changed setting applies next round+ fix: (r: R, round: number) => Promise<'ok' | 'error' | 'handoff'>; // handoff: someone else must act first (a shared file)+}+export async function reviewFix<R>(o: Loop<R>): Promise<{ end: LoopEnd; round: number; last: R | null }> {+ for (let round = 1; ; round++) {+ const r = await o.review(round);+ if (r == null) return { end: 'error', round, last: null };+ const v = o.verdict(r, round);+ if (v !== 'fix') return { end: v, round, last: r };+ if (round >= o.limit(r, round)) return { end: 'limit', round, last: r };+ const f = await o.fix(r, round);+ if (f !== 'ok') return { end: f, round, last: r };+ }+}++// A review passes when nothing it lists is a blocker (polish items are handed on, they never hold the line).+// Reviews without severities fall back to their own pass flag.+export function blockerFree(rv: { issues?: Issue[]; pass?: boolean }) {+ const L = rv.issues || [];+ return L.length && L.every((x) => x.severity) ? !L.some((x) => x.severity !== 'polish') : !!rv.pass;+}+// Items in a fixes file the fixer couldn't do alone because they live in a shared file (rig, cast, common assets).+export const sharedItems = (fx: SharedItem[] | { fixes?: SharedItem[] } | null) => (Array.isArray(fx) ? fx : fx?.fixes || []).filter((x) => x && x.status === 'shared');diff --git a/app/server/runner.test.ts b/app/server/runner.test.tsnew file mode 100644index 0000000..8ddbb2a--- /dev/null+++ b/app/server/runner.test.ts@@ -0,0 +1,33 @@+// runner.ts: one flow per project, and cancel reaches every process it started (including their children).+import { describe, test } from 'node:test';+import assert from 'node:assert/strict';+import * as R from './runner.ts';++const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };+const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));++describe('runner', () => {+ test('a second run for the same project is refused until the first ends', async () => {+ let done!: () => void;+ const first = R.run('a', () => new Promise<void>((r) => { done = r; }));+ await assert.rejects(R.run('a', async () => {}), R.Busy);+ await R.run('b', async () => {}); // other projects are not affected+ done(); await first;+ assert.equal(R.active('a'), false);+ await R.run('a', async () => {});+ });++ test('cancel aborts the run signal', async () => {+ await R.run('c', async () => { R.cancel('c'); assert.equal(R.signalOf('c').aborted, true); assert.equal(R.aborted('c'), true); });+ });++ test('cancel kills a tool process and the processes it started', { skip: process.platform === 'win32' }, async () => {+ const p = R.spawnTool('d', 'sh', ['-c', 'sleep 30 & echo $!; wait']);+ const grandchild = await new Promise<number>((r) => p.stdout.once('data', (b) => r(+String(b).trim())));+ const closed = new Promise((r) => p.on('close', r));+ assert.ok(alive(grandchild));+ R.cancel('d');+ await closed; await wait(100);+ assert.equal(alive(grandchild), false);+ });+});diff --git a/app/server/runner.ts b/app/server/runner.tsnew file mode 100644index 0000000..723628f--- /dev/null+++ b/app/server/runner.ts@@ -0,0 +1,46 @@+// One flow per project. Every entry point that does work (start, approve, retry, resume, accept, a note that triggers a+// replan or revise) runs inside run(): a second one is refused while the first is going, and cancel()/stopAll() reach+// everything the flow started — the agent turns (through the run's signal) and every tool process (whole process tree).+import { spawn, spawnSync, type ChildProcess, type SpawnOptions } from 'node:child_process';++const IS_WIN = process.platform === 'win32';+const runs = new Map<string, AbortController>();+const kids = new Map<string, Set<ChildProcess>>();++export class Busy extends Error { code = 409; constructor() { super('agent 正在工作中,請等這一輪完成'); } }++export const active = (id: string) => runs.has(id);+export function run<T>(id: string, fn: () => Promise<T>): Promise<T> {+ if (runs.has(id)) return Promise.reject(new Busy());+ runs.set(id, new AbortController());+ return fn().finally(() => runs.delete(id));+}+// The signal of the flow running for this project; turns and tools started outside a flow have nothing to cancel them.+const NEVER = new AbortController().signal;+export const signalOf = (id: string) => runs.get(id)?.signal ?? NEVER;+export const aborted = (id: string) => !!runs.get(id)?.signal.aborted;++// The CLI or tool and everything it started (ffmpeg, Chrome, yt-dlp…). POSIX: the child leads its own process group.+export function killTree(child: ChildProcess) {+ if (child.pid == null || child.exitCode != null) return;+ try {+ if (IS_WIN) spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F']);+ else process.kill(-child.pid, 'SIGTERM');+ } catch { try { child.kill('SIGTERM'); } catch {} }+}+export const treeOpts: { detached?: boolean } = IS_WIN ? {} : { detached: true };++// A tool process for this project (analyze.py, align_lyrics.py, background renders): stopped by cancel() and stopAll()+// like the agents. stdout/stderr are piped unless opts.stdio says otherwise.+export function spawnTool(id: string, cmd: string, args: string[], opts: SpawnOptions = {}) {+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], ...opts, ...treeOpts });+ if (!kids.has(id)) kids.set(id, new Set());+ kids.get(id)!.add(child);+ const forget = () => kids.get(id)?.delete(child);+ child.on('close', forget); child.on('error', forget);+ if (signalOf(id).aborted) killTree(child);+ return child as ChildProcess & { stdout: NonNullable<ChildProcess['stdout']>; stderr: NonNullable<ChildProcess['stderr']> };+}++export function cancel(id: string) { runs.get(id)?.abort(); for (const c of kids.get(id) || []) killTree(c); }+export function stopAll() { for (const id of new Set([...runs.keys(), ...kids.keys()])) cancel(id); }diff --git a/app/server/store.ts b/app/server/store.tsnew file mode 100644index 0000000..6625c85--- /dev/null+++ b/app/server/store.ts@@ -0,0 +1,123 @@+// The job's files: projects/<id>/job.json is the state, logs/events.jsonl the full event log. Everything that reads or+// writes them goes through here, and every write is announced on `bus` (the SSE stream and notify.ts listen).+import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync, readdirSync, statSync, statfsSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { EventEmitter } from 'node:events';+import { ROUND_KEYS } from '../shared/types.ts';+import type { ChatMessage, Config, Job, LogEntry, LogEvent, Need, NeedRequest, Pipeline, RoundKey, Rounds, Stage } from '../shared/types.ts';++export const ROOT = join(import.meta.dirname, '..', '..');+export const PROJECTS = process.env.REELMIMIC_PROJECTS ? resolve(process.env.REELMIMIC_PROJECTS) : join(ROOT, 'projects'); // override: tests, a second checkout+export const SCRIPTS = join(ROOT, '.claude', 'skills', 'video-clone', 'scripts');+export const PY = process.env.PYTHON || 'python';+export const noPython = (e: Error) => `${PY} could not be started (${e.message}). Install Python 3.10+, or set PYTHON=/path/to/python`;++export const CONFIG: Config = {+ builders: +(process.env.BUILDERS || 6), // parallel shot builders per project (12 cores / 32 GB measured)+ castRounds: +(process.env.CAST_ROUNDS || 3), // cast gate: review/fix rounds before asking the user+ chunkRounds: +(process.env.CHUNK_ROUNDS || 3), // shot line: review/fix rounds per chunk+ finalRounds: +(process.env.FINAL_ROUNDS || 2), // final panel: automatic revise rounds+ 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+ // Build shots while the cast gate is still running? Faster, but on real runs character files changed under the+ // builders and every segment needed an extra round (0nczg, 4f1jx, 1qo20, 7e45u). Off by default: quality first.+ overlapCast: process.env.OVERLAP_CAST === '1',+};++// 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; }+// 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>> = {};+ for (const k of ROUND_KEYS) {+ if (!(k in input)) continue;+ const raw = input[k];+ if (raw === '' || raw == null) { out[k] = null; continue; }+ const v = Number(raw);+ if (!Number.isInteger(v) || v < ROUND_RANGE.min || v > ROUND_RANGE.max) throw new Error(`${k} must be a whole number from ${ROUND_RANGE.min} to ${ROUND_RANGE.max}`);+ out[k] = v;+ }+ return out;+}++export type BusEvent = { type: 'job'; job: Job } | { type: 'log'; ev: LogEvent };+export const bus = new EventEmitter<{ job: [id: string, ev: BusEvent] }>(); bus.setMaxListeners(100);++export const now = () => new Date().toISOString();+export const dirOf = (id: string) => join(PROJECTS, id);+export 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).+export const L = (id: string, zh: string, en: string) => (load(id).lang === 'en' ? en : zh);+export const CANCELLED = { zh: '已取消', en: 'Cancelled' }; // the error text of a cancelled turn (notify.ts stays quiet on it)+// job.json carries no event log: rewriting the whole file for every agent event (a dozen agents streaming at once) was+// most of the server's disk work. The log is logs/events.jsonl (complete), and the latest LOG_KEEP events are kept in+// memory for the UI (snapshot() puts them in job.log).+export function load(id: string): Job { const j = JSON.parse(readFileSync(jpath(id), 'utf8')); j.log = []; return j; }+export function save(job: Job) {+ recentLog(job.id); // first touch: a project from before events.jsonl still has its log in job.json; move it out before it's dropped+ job.updatedAt = now(); writeFileSync(jpath(job.id), JSON.stringify({ ...job, log: undefined }, null, 1)); bus.emit('job', job.id, { type: 'job', job }); return job;+}+export function update(id: string, fn: (j: Job) => void) { const j = load(id); fn(j); return save(j); }+const LOG_KEEP = 600, TAIL_BYTES = 1 << 20;+const recent = new Map<string, LogEvent[]>();+const eventsFile = (id: string) => join(dirOf(id), 'logs', 'events.jsonl');+export function recentLog(id: string): LogEvent[] {+ let list = recent.get(id);+ if (list) return list;+ const f = eventsFile(id);+ if (existsSync(f)) { // the tail of the full log (one read per project per server start)+ const size = statSync(f).size, start = Math.max(0, size - TAIL_BYTES), buf = Buffer.alloc(size - start), fd = openSync(f, 'r');+ try { readSync(fd, buf, 0, buf.length, start); } finally { closeSync(fd); }+ const lines = buf.toString('utf8').split('\n').slice(start > 0 ? 1 : 0); // the first line may be cut+ list = lines.flatMap((l) => { try { return l.trim() ? [JSON.parse(l) as LogEvent] : []; } catch { return []; } }).slice(-LOG_KEEP);+ } else {+ list = (readJSON<Job>(jpath(id))?.log || []).slice(-LOG_KEEP);+ if (list.length) try { mkdirSync(dirname(f), { recursive: true }); appendFileSync(f, list.map((e) => JSON.stringify(e) + '\n').join('')); } catch {}+ }+ recent.set(id, list);+ return list;+}+export function log(id: string, ev: LogEntry) {+ const e = { ts: now(), ...ev }, list = recentLog(id);+ list.push(e); if (list.length > LOG_KEEP) list.splice(0, list.length - LOG_KEEP);+ try { mkdirSync(dirname(eventsFile(id)), { recursive: true }); appendFileSync(eventsFile(id), JSON.stringify(e) + '\n'); } catch {}+ bus.emit('job', id, { type: 'log', ev: e });+}+export function touch(id: string) { update(id, () => {}); } // tell open pages to reload (e.g. after files were added)++export const setStage = (id: string, stage: Stage, extra: Partial<Job> = {}) => update(id, (j) => Object.assign(j, { stage, ...extra }));+export const chat = (id: string, role: ChatMessage['role'], text: string, extra: Partial<ChatMessage> = {}) => update(id, (j) => { j.chat.push({ role, text, ts: now(), ...extra }); });+export const pipe = (id: string, fn: (p: Pipeline) => void) => update(id, (j) => { j.pipeline = j.pipeline || {}; fn(j.pipeline); });+export function pause(id: string) { setStage(id, 'needs_input'); return false; }++// Renders need room (frames, previews, the encode): warn early instead of failing mid-render. A real run had 66 MB left.+const MIN_FREE_GB = 5;+export function diskWarning(id: string) {+ try {+ const f = statfsSync(PROJECTS), gb = (f.bavail * f.bsize) / 2 ** 30;+ if (gb < MIN_FREE_GB) chat(id, 'system', L(id, `⚠️ 磁碟只剩 ${gb.toFixed(1)} GB,渲染可能中途失敗;建議先清出 ${MIN_FREE_GB} GB 以上。`, `⚠️ Only ${gb.toFixed(1)} GB of disk left; rendering may fail midway. Free at least ${MIN_FREE_GB} GB first.`));+ } catch { /* statfs unsupported: skip */ }+}++// needs_user items (from any reviewer) pause instead of looping+export function collectNeeds(id: string, items: NeedRequest[] | undefined, from: string) {+ const add: Need[] = (items || []).filter(Boolean).map((n) => ({ ...n, from, at: now() }));+ if (!add.length) return 0;+ // a new batch from the same reviewer replaces its earlier one (the critic re-reports open items every round)+ update(id, (j) => { j.needs = [...(j.needs || []).filter((x) => x.from !== from && !add.some((a) => a.issue === x.issue)), ...add]; });+ chat(id, 'system', L(id, `需要你提供:${add.map((n) => n.issue).join(';')}`, `Needs your input: ${add.map((n) => n.issue).join('; ')}`));+ return add.length;+}++export const readJSON = <T>(p: string): T | null => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };+export const readText = (p: string): string | null => { try { return readFileSync(p, 'utf8'); } catch { return null; } };+export const oneOf = (v: string | null | undefined, ...L: string[]) => !!v && L.includes(v);+export const mtime = (p: string) => (existsSync(p) ? statSync(p).mtimeMs : 0);+// Files in one folder of the project matching re, newest first, as project-relative paths.+export function listFiles(id: string, sub: string, re: RegExp) {+ const p = join(dirOf(id), sub);+ return existsSync(p) ? readdirSync(p).filter((f) => re.test(f)).map((f) => ({ f: `${sub}/${f}`, t: statSync(join(p, f)).mtimeMs })).sort((a, b) => b.t - a.t).map((x) => x.f) : [];+}diff --git a/app/server/turn.ts b/app/server/turn.tsnew file mode 100644index 0000000..37bfe1d--- /dev/null+++ b/app/server/turn.ts@@ -0,0 +1,117 @@+// One agent turn: a slot from the global budget, the step's prompt, and a check that the files it must write were updated.+// turn() never touches the stage; step() is a turn that does (it moves the job on, or stops it in `error` with the reason).+import { existsSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import { runAgent, type AgentResult } from './agents/index.ts';+import { checkFile } from './contract.ts';+import { prompts as bootPrompts } from './prompts.ts';+import { signalOf } from './runner.ts';+import { CANCELLED, CONFIG, L, ROOT, chat, dirOf, listFiles, load, log, mtime, readText, setStage, update } from './store.ts';+import type { Stage } from '../shared/types.ts';+import type { Phase, Prompts, StepVars } from './types.ts';++// prompts.ts is re-imported when it changes, so prompt fixes reach the next agent turn without restarting running jobs+let promptCache: { m: number; p: Prompts } = { m: 0, p: bootPrompts };+async function livePrompts() {+ const f = join(import.meta.dirname, 'prompts.ts'), m = statSync(f).mtimeMs;+ if (m !== promptCache.m) { try { promptCache = { m, p: (await import(`./prompts.ts?v=${m}`)).prompts }; } catch (e) { console.error('prompts reload failed', e); } }+ return promptCache.p;+}++// ---------- global agent slots (all projects share them) ----------+// Reviews and fixes jump the queue: a defect is fixed while the builder still has it in mind, and nobody waits on a+// review behind a fresh 30-minute build. New builds take whatever slots are left.+let used = 0; const waiters: { r: (ok: boolean) => void; hi: boolean }[] = [];+const URGENT = new Set(['cast_qa', 'cast_fix', 'shot_qa', 'fix_chunk', 'assemble', 'critique', 'revise', 'replan', 'plan', 'style']);+// false: the run was cancelled while waiting (no slot taken)+async function slot(phase: Phase, signal: AbortSignal): Promise<boolean> {+ if (signal.aborted) return false;+ if (used < CONFIG.maxAgentsGlobal) { used++; return true; }+ const ok = await new Promise<boolean>((r) => {+ const w = { r, hi: URGENT.has(phase) };+ if (w.hi) { const i = waiters.findIndex((x) => !x.hi); i < 0 ? waiters.push(w) : waiters.splice(i, 0, w); } else waiters.push(w);+ signal.addEventListener('abort', () => { const i = waiters.indexOf(w); if (i >= 0) { waiters.splice(i, 1); r(false); } }, { once: true });+ });+ if (ok) used++;+ return ok;+}+function release() { used--; const w = waiters.shift(); if (w) w.r(true); }++// session: 'director' (the project's main conversation), 'fresh' (a reviewer with no stake), or any key (a builder that keeps+// its own conversation across its fix rounds).+// A failed turn says why: cancelled, the AI account's usage limit, outputs not written, outputs that break CONTRACT.md+// (after one chance to fix them), or the agent itself failed.+export interface TurnOpts { session?: string; who?: string }+type Why = 'aborted' | 'limit' | 'missing' | 'invalid' | 'crashed';+export interface TurnResult { ok: boolean; why?: Why; text?: string; missing?: string[]; detail?: string }+const LIMIT = /usage limit|rate limit|hit your limit|limit reached|quota|credit balance/i;+export 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), signal = signalOf(id);+ const p = { dir: relative(ROOT, d).replace(/\\/g, '/'), brief: readText(join(d, 'brief.md')) || '', inputs: listFiles(id, 'inputs', /./), config: CONFIG, lang: j.lang || 'zh-TW', ...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);+ // one agent run in a slot; the session id is kept for the director and builders (a reviewer's only lives in this turn)+ const once = async (prompt: string, resume: string | null | undefined): Promise<AgentResult | null> => {+ if (!(await slot(phase, signal))) return null;+ log(id, { type: 'turn', state: 'start', phase, who: label });+ let res: AgentResult;+ try {+ res = await runAgent({ kind: j.agent, cwd: ROOT, prompt, sessionId: resume, 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 });+ } });+ } finally { release(); }+ log(id, { type: 'turn', state: 'end', phase, who: label, ok: !!res?.ok && !signal.aborted });+ return signal.aborted ? null : res;+ };+ let r = await once((await livePrompts())[phase](p), sid);+ if (!r) return { ok: false, why: 'aborted' };+ let missing = must.filter((f, i) => !(mtime(join(d, f)) > before[i]));+ // first turn after "retry": the interrupted turn may already have written everything, and the agent rightly+ // 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; });+ if (r.text) chat(id, session === 'fresh' ? 'critic' : session === 'director' ? 'agent' : 'builder', r.text, { phase, who: label });+ // an account limit is the real cause, even when it also left outputs missing: say so plainly+ const limit = [r.lastError, r.text, r.stderr].find((t) => t && LIMIT.test(t));+ if (limit) return { ok: false, why: 'limit', text: r.text, missing, detail: limit.slice(-300) };+ if (!r.ok && !missing.length) return { ok: false, why: 'crashed', text: r.text, detail: r.stderr.slice(-300) };+ if (missing.length) return { ok: false, why: 'missing', text: r.text, missing };+ // the files are there; do they follow CONTRACT.md? One chance to fix them, in the same conversation+ const check = () => must.filter((f) => f.endsWith('.json')).flatMap((f) => checkFile(f, readText(join(d, f)) ?? ''));+ let bad = check();+ if (bad.length && r.sessionId) {+ log(id, { type: 'error', text: `${label}: ${bad.join('; ')}`.slice(0, 400), who: label });+ r = await once(fixFormat(p.dir, bad), r.sessionId);+ if (!r) return { ok: false, why: 'aborted' };+ bad = check();+ }+ if (bad.length) return { ok: false, why: 'invalid', text: r.text, detail: bad.slice(0, 6).join('; ') };+ return { ok: true, text: r.text };+}+const fixFormat = (dir: string, bad: string[]) => `## 修正檔案格式+專案資料夾:${dir}。你剛寫的檔案不符合 .claude/skills/video-clone/CONTRACT.md,伺服器讀不懂:+${bad.map((b) => `- ${b}`).join('\n')}+只要把這些檔案照 CONTRACT.md 的格式重寫(內容保持你剛剛的判斷,只修格式),不要做別的事。`;++export function fail(id: string, stageName: Stage, res: TurnResult) {+ const d = res.detail || '';+ const error = {+ aborted: () => L(id, CANCELLED.zh, CANCELLED.en),+ limit: () => L(id, `AI 帳號的用量到上限了,等額度恢復或換另一個 AI 導演再按「重試這一步」。原始訊息:${d}`, `Your AI account hit its usage limit. Wait until it resets (or switch to the other AI director), then click “Retry this step”. Message: ${d}`),+ missing: () => L(id, `缺少輸出:${(res.missing || []).join(', ')}`, `Missing output: ${(res.missing || []).join(', ')}`),+ invalid: () => L(id, `agent 寫的檔案格式不對(已請它重寫一次):${d}`, `The agent's files don't follow the contract (it was asked to rewrite them once): ${d}`),+ crashed: () => L(id, `agent 回合失敗${d ? ':' + d : ''}`, `The agent turn failed${d ? ': ' + d : ''}`),+ }[res.why || 'crashed']();+ setStage(id, 'error', { failed: stageName, error });+ return false;+}+export async function step<P extends Phase>(id: string, stageName: Stage, phase: P, vars: StepVars[P], must: string[], next?: Stage | null, opts?: TurnOpts) {+ setStage(id, stageName, { error: null, failed: null });+ const r = await turn(id, phase, vars, must, opts);+ if (!r.ok) return fail(id, stageName, r);+ if (next) setStage(id, next);+ return true;+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex e049ec3..d3f7268 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -15,7 +15,18 @@ Browser (app/web, React + Vite)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)+ ├─ jobs.ts the user's actions (start, approve, message, retry…), project list and snapshot+ ├─ preprod.ts analysis → style → plan (characters and assets drafted in parallel)+ ├─ production.ts setup → cast gate → shot line (parallel builders, per-shot review) → assemble+ ├─ prerender.ts background render of passed segments (engines with a frame cache), stopped by Cancel+ ├─ cast.ts cast gate: per-character review/fix in parallel, line-up check, serial fallback+ ├─ final.ts final panel: critic ⇄ revise+ ├─ review.ts the review → fix loop every gate shares (round limits, needs_user, pass rule)+ ├─ turn.ts one agent turn: global slots (reviews and fixes jump the queue), required-file check, failure reason+ ├─ contract.ts format check for the JSON files agents write (plan, production, reviews, fixes, critique)+ ├─ runner.ts one flow per project; Cancel stops every agent and tool process it started (whole process tree)+ ├─ store.ts job.json, event log, live-update bus, round limits+ ├─ inputs.ts required inputs and lyric timing├─ 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 +60,9 @@ 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; if not, the job stops in `error` and the step can be retried. Updated JSON files are+then checked against the contract (`contract.ts`, only the fields the server acts on): a broken one goes back to the same+agent conversation once to be rewritten, and if it is still broken the step stops in `error` naming the bad fields.On server start, jobs still marked as working are flagged as interrupted (`recoverOrphans`); a retry continues from thecurrent files.@@ -98,8 +111,8 @@ The full format is in `.claude/skills/video-clone/CONTRACT.md`. In short:```projects/<id>/- job.json managed by the server: stage, session ids, chat, event log (latest 600), production state- logs/events.jsonl complete event log (never truncated)+ job.json managed by the server: stage, session ids, chat, production state+ logs/events.jsonl complete event log (never truncated; the UI gets the latest 600)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)diff --git a/docs/EXTENDING.md b/docs/EXTENDING.mdindex 5a6fe3b..631de3e 100644--- a/docs/EXTENDING.md+++ b/docs/EXTENDING.md@@ -11,7 +11,7 @@ Extension points, from shallow to deep:| Change how an agent handles a step | `app/server/prompts.ts` | Text only, applies on the next turn || Give agents a new tool | `.claude/skills/video-clone/scripts/` | Write the script, then mention it in a prompt / SKILL.md || Plug in another AI director (a new agent CLI) | `app/server/agents/index.ts` | Yes |-| Change the steps or order of the production line | `app/server/jobs.ts` + `prompts.ts` + `CONTRACT.md` | Yes |+| Change the steps or order of the production line | `app/server/` (see §5) + `prompts.ts` + `CONTRACT.md` | Yes |---@@ -125,16 +125,21 @@ The agent must be able to: read and write files in the repo, run a shell (python## 5. Change the production line-Main functions in `app/server/jobs.ts`:--- `production()`: setup → `castGate()` (runs alongside segment building) → `runChunk()` × N → assemble.-- `castGate()` / `castSerial()`: per-character parallel review and fixing; the serial version is used for a single- character or shared-file work.-- `finalPanel()`: final critic ⇄ revise.-- `turn()`: dispatches one agent turn (session handling, global slots, required-file check).--When changing a step, change three places together: `jobs.ts` (flow), `prompts.ts` (instructions) and `CONTRACT.md`-(format of any new file); plus `Project.tsx` if the web app should show it.+Where each part lives in `app/server/`:++- `preprod.ts` — `preProduction()`: plan core → characters and assets in parallel → plan frames.+- `production.ts` — `production()`: setup → `castGate()` (runs alongside segment building) → `runChunk()` × N → assemble.+- `cast.ts` — `castGate()` / `castSerial()`: per-character parallel review and fixing; the serial version is used for a+ single character or shared-file work.+- `final.ts` — `finalPanel()`: final critic ⇄ revise.+- `review.ts` — `reviewFix()`: the review → fix loop all of the above share. A new gate is a `review`, a `verdict`, a+ `limit` and a `fix`; the loop handles rounds, pauses and stopping at the limit.+- `turn.ts` — `turn()`: dispatches one agent turn (session handling, global slots, required-file check, failure reason);+ `step()` is a turn that also moves the stage.+- `jobs.ts` — the user's actions. Each runs as the project's single flow (`runner.ts`), so Cancel reaches all of it.++When changing a step, change three places together: the flow file above, `prompts.ts` (instructions) and `CONTRACT.md`+(format of any new file; if the server acts on it, add its schema to `contract.ts`); plus `Project.tsx` if the web app should show it.Parameters (parallelism, rounds per gate) are in `CONFIG` and can also be set through environment variables.## 6. Adding UI text / translationsdiff --git a/docs/zh-CN/ARCHITECTURE.md b/docs/zh-CN/ARCHITECTURE.mdindex 2c9e972..41cf336 100644--- a/docs/zh-CN/ARCHITECTURE.md+++ b/docs/zh-CN/ARCHITECTURE.md@@ -13,7 +13,18 @@ ReelMimic 由三层组成:**网站**(React)、**服务器**(Node,负服务器(app/server)├─ index.ts HTTP API、上传、SSE、提供项目文件(/files/:id/*)├─ env.ts 启动时加载 ~/.reelmimic/secrets.json- ├─ jobs.ts 流程状态机 + 生产线调度(谁先谁后、平行几个、何时暂停)+ ├─ jobs.ts 用户的操作(开始、批准、留言、重试…)、项目列表与快照+ ├─ preprod.ts 分析 → 风格 → 企划(角色与素材平行打草稿)+ ├─ production.ts 制作准备 → 角色关 → 分段制作(多个 builder 平行、每镜做完就审)→ 组装+ ├─ prerender.ts 通过审查的段落在后台先渲染(有帧缓存的引擎),取消时一起停+ ├─ cast.ts 角色关:每个角色平行审查修正、并排检查、串行版+ ├─ final.ts 最后评审 ⇄ 修改+ ├─ review.ts 每一关共用的「审查 → 修正」循环(轮数上限、needs_user、通过规则)+ ├─ turn.ts 一次 agent 回合:全局名额(审查与修正插队)、必须文件检查、失败原因+ ├─ contract.ts agent 写的 JSON 文件格式检查(企划、制作规划、审查、修正、评审)+ ├─ runner.ts 每个项目同时只跑一条流程;取消会停掉它开的所有 agent 与工具进程(整棵进程树)+ ├─ store.ts job.json、事件记录、实时更新、轮数设置+ ├─ inputs.ts 需要用户提供的素材、歌词对时├─ prompts.ts 每个步骤给 agent 的指令(改档后下一轮就生效,不用重启)└─ agents/index.ts agent 转接层:Claude Code / Codex → 统一事件│ spawn(stdin 给指令,stdout 串流事件)@@ -46,7 +57,7 @@ new → analyzing → styling → planning → plan_review ⇄ replanning| critiquing | 独立评审(全新对话) | `out/check/critique.json` || revising | 导演 agent | `out/video.mp4`、`out/check/fixes.json`(每项附修改前后截屏) |-**完成的判准是文件**:`turn()` 记下必须文件的修改时间,agent 回合结束后检查它们有没有被更新;没有就停在 `error`,可以「重试这一步」。+**完成的判准是文件**:`turn()` 记下必须文件的修改时间,agent 回合结束后检查它们有没有被更新;没有就停在 `error`,可以「重试这一步」。更新过的 JSON 文件再按合约检查(`contract.ts`,只查服务器会用到的字段):格式不对就请同一个 agent 对话重写一次,还是不对这一步就停在 `error`,并列出哪些字段有问题。服务器重启时,还标在工作中的项目会被标成「已中断」(`recoverOrphans`),重试会从目前的文件接着做。## 2. 生产线(核准之后)@@ -85,8 +96,8 @@ assemble(导演):组装、混音、全片输出```projects/<id>/- job.json 服务器管理:阶段、session id、对话、事件纪录(最近 600 笔)、生产线状态- logs/events.jsonl 完整事件纪录(不截断)+ job.json 服务器管理:阶段、session id、对话、生产线状态+ logs/events.jsonl 完整事件纪录(不截断;界面显示最近 600 笔)brief.md / inputs/ 用户的需求原文与上传的素材analysis/ report.json、STYLE.md、route.json、lyrics/subs.lrc|jsonplan.json 前制企划(网站的主要画面)diff --git a/docs/zh-CN/EXTENDING.md b/docs/zh-CN/EXTENDING.mdindex 65e5acf..4fbf65e 100644--- a/docs/zh-CN/EXTENDING.md+++ b/docs/zh-CN/EXTENDING.md@@ -11,7 +11,7 @@ ReelMimic 的扩充点由浅到深:| 调整 agent 在某一步怎么做 | `app/server/prompts.ts` | 只改文本,下一轮就生效 || 加新工具给 agent 用 | `.claude/skills/video-clone/scripts/` | 写脚本,再在 prompt/SKILL.md 提到它 || 接另一种 AI 导演(新的 agent CLI) | `app/server/agents/index.ts` | 要 |-| 改生产线的步骤或顺序 | `app/server/jobs.ts` + `prompts.ts` + `CONTRACT.md` | 要 |+| 改生产线的步骤或顺序 | `app/server/`(见第 5 节)+ `prompts.ts` + `CONTRACT.md` | 要 |---@@ -104,14 +104,17 @@ agent 需要能:读写 repo 内文件、运行 shell(python、node、ffmpeg## 5. 改生产线-`app/server/jobs.ts` 的主要函数:+`app/server/` 里各部分的位置:-- `production()`:setup → `castGate()`(与分段制作同时跑)→ `runChunk()` × N → assemble。-- `castGate()` / `castSerial()`:每个角色平行审查修正;一个角色或共用档时走串行版。-- `finalPanel()`:最后评审 ⇄ 修改。-- `turn()`:派一次 agent 回合(session 管理、全域名额、必须文件检查)。+- `preprod.ts` — `preProduction()`:企划核心 → 角色与素材平行 → 风格画面。+- `production.ts` — `production()`:setup → `castGate()`(与分段制作同时跑)→ `runChunk()` × N → assemble。+- `cast.ts` — `castGate()` / `castSerial()`:每个角色平行审查修正;一个角色或共用档时走串行版。+- `final.ts` — `finalPanel()`:最后评审 ⇄ 修改。+- `review.ts` — `reviewFix()`:上面每一关共用的「审查 → 修正」循环。新的关卡只要给 `review`、`verdict`、`limit`、`fix`,轮数、暂停、到上限停下都由循环处理。+- `turn.ts` — `turn()`:派一次 agent 回合(session 管理、全局名额、必须文件检查、失败原因);`step()` 是会推进阶段的回合。+- `jobs.ts` — 用户的操作,每一个都是这个项目唯一的一条流程(`runner.ts`),所以「取消」能停掉全部。-改步骤时三个地方要一起改:`jobs.ts`(流程)、`prompts.ts`(指令)、`CONTRACT.md`(新文件的格式),前端要显示的话再改 `Project.tsx`。+改步骤时三个地方要一起改:上面对应的流程文件、`prompts.ts`(指令)、`CONTRACT.md`(新文件的格式;服务器会读来做判断的话,在 `contract.ts` 加上它的格式),前端要显示的话再改 `Project.tsx`。参数(平行数、每关轮数)在 `CONFIG`,也可以用环境变量调整。## 6. 界面文本与翻译diff --git a/docs/zh-TW/ARCHITECTURE.md b/docs/zh-TW/ARCHITECTURE.mdindex dcc854a..a043297 100644--- a/docs/zh-TW/ARCHITECTURE.md+++ b/docs/zh-TW/ARCHITECTURE.md@@ -13,7 +13,18 @@ ReelMimic 由三層組成:**網站**(React)、**伺服器**(Node,負伺服器(app/server)├─ index.ts HTTP API、上傳、SSE、提供專案檔案(/files/:id/*)├─ env.ts 啟動時載入 ~/.reelmimic/secrets.json- ├─ jobs.ts 流程狀態機 + 生產線排程(誰先誰後、平行幾個、何時暫停)+ ├─ jobs.ts 使用者的操作(開始、核准、留言、重試…)、專案列表與快照+ ├─ preprod.ts 分析 → 風格 → 企劃(角色與素材平行打草稿)+ ├─ production.ts 製作準備 → 角色關 → 分段製作(多個 builder 平行、每鏡做完就審)→ 組裝+ ├─ prerender.ts 通過審查的段落在背景先渲染(有影格快取的引擎),取消時一起停+ ├─ cast.ts 角色關:每個角色平行審查修正、並排檢查、序列版+ ├─ final.ts 最後評審 ⇄ 修改+ ├─ review.ts 每一關共用的「審查 → 修正」迴圈(輪數上限、needs_user、通過規則)+ ├─ turn.ts 一次 agent 回合:全域名額(審查與修正插隊)、必須檔案檢查、失敗原因+ ├─ contract.ts agent 寫的 JSON 檔格式檢查(企劃、製作規劃、審查、修正、評審)+ ├─ runner.ts 每個專案同時只跑一條流程;取消會停掉它開的所有 agent 與工具程序(整棵程序樹)+ ├─ store.ts job.json、事件紀錄、即時更新、輪數設定+ ├─ inputs.ts 需要使用者提供的素材、歌詞對時├─ prompts.ts 每個步驟給 agent 的指令(改檔後下一輪就生效,不用重啟)└─ agents/index.ts agent 轉接層:Claude Code / Codex → 統一事件│ spawn(stdin 給指令,stdout 串流事件)@@ -46,7 +57,7 @@ new → analyzing → styling → planning → plan_review ⇄ replanning| critiquing | 獨立評審(全新對話) | `out/check/critique.json` || revising | 導演 agent | `out/video.mp4`、`out/check/fixes.json`(每項附修改前後截圖) |-**完成的判準是檔案**:`turn()` 記下必須檔案的修改時間,agent 回合結束後檢查它們有沒有被更新;沒有就停在 `error`,可以「重試這一步」。+**完成的判準是檔案**:`turn()` 記下必須檔案的修改時間,agent 回合結束後檢查它們有沒有被更新;沒有就停在 `error`,可以「重試這一步」。更新過的 JSON 檔再照合約檢查(`contract.ts`,只查伺服器會用到的欄位):格式不對就請同一個 agent 對話重寫一次,還是不對這一步就停在 `error`,並列出哪些欄位有問題。伺服器重啟時,還標在工作中的專案會被標成「已中斷」(`recoverOrphans`),重試會從目前的檔案接著做。## 2. 生產線(核准之後)@@ -85,8 +96,8 @@ assemble(導演):組裝、混音、全片輸出```projects/<id>/- job.json 伺服器管理:階段、session id、對話、事件紀錄(最近 600 筆)、生產線狀態- logs/events.jsonl 完整事件紀錄(不截斷)+ job.json 伺服器管理:階段、session id、對話、生產線狀態+ logs/events.jsonl 完整事件紀錄(不截斷;介面顯示最近 600 筆)brief.md / inputs/ 使用者的需求原文與上傳的素材analysis/ report.json、STYLE.md、route.json、lyrics/subs.lrc|jsonplan.json 前製企劃(網站的主要畫面)diff --git a/docs/zh-TW/EXTENDING.md b/docs/zh-TW/EXTENDING.mdindex ab30dff..8a96e1b 100644--- a/docs/zh-TW/EXTENDING.md+++ b/docs/zh-TW/EXTENDING.md@@ -11,7 +11,7 @@ ReelMimic 的擴充點由淺到深:| 調整 agent 在某一步怎麼做 | `app/server/prompts.ts` | 只改文字,下一輪就生效 || 加新工具給 agent 用 | `.claude/skills/video-clone/scripts/` | 寫腳本,再在 prompt/SKILL.md 提到它 || 接另一種 AI 導演(新的 agent CLI) | `app/server/agents/index.ts` | 要 |-| 改生產線的步驟或順序 | `app/server/jobs.ts` + `prompts.ts` + `CONTRACT.md` | 要 |+| 改生產線的步驟或順序 | `app/server/`(見第 5 節)+ `prompts.ts` + `CONTRACT.md` | 要 |---@@ -104,14 +104,17 @@ agent 需要能:讀寫 repo 內檔案、執行 shell(python、node、ffmpeg## 5. 改生產線-`app/server/jobs.ts` 的主要函式:+`app/server/` 裡各部分的位置:-- `production()`:setup → `castGate()`(與分段製作同時跑)→ `runChunk()` × N → assemble。-- `castGate()` / `castSerial()`:每個角色平行審查修正;一個角色或共用檔時走序列版。-- `finalPanel()`:最後評審 ⇄ 修改。-- `turn()`:派一次 agent 回合(session 管理、全域名額、必須檔案檢查)。+- `preprod.ts` — `preProduction()`:企劃核心 → 角色與素材平行 → 風格畫面。+- `production.ts` — `production()`:setup → `castGate()`(與分段製作同時跑)→ `runChunk()` × N → assemble。+- `cast.ts` — `castGate()` / `castSerial()`:每個角色平行審查修正;一個角色或共用檔時走序列版。+- `final.ts` — `finalPanel()`:最後評審 ⇄ 修改。+- `review.ts` — `reviewFix()`:上面每一關共用的「審查 → 修正」迴圈。新的關卡只要給 `review`、`verdict`、`limit`、`fix`,輪數、暫停、到上限停下都由迴圈處理。+- `turn.ts` — `turn()`:派一次 agent 回合(session 管理、全域名額、必須檔案檢查、失敗原因);`step()` 是會推進階段的回合。+- `jobs.ts` — 使用者的操作,每一個都是這個專案唯一的一條流程(`runner.ts`),所以「取消」能停掉全部。-改步驟時三個地方要一起改:`jobs.ts`(流程)、`prompts.ts`(指令)、`CONTRACT.md`(新檔案的格式),前端要顯示的話再改 `Project.tsx`。+改步驟時三個地方要一起改:上面對應的流程檔、`prompts.ts`(指令)、`CONTRACT.md`(新檔案的格式;伺服器會讀來做判斷的話,在 `contract.ts` 加上它的格式),前端要顯示的話再改 `Project.tsx`。參數(平行數、每關輪數)在 `CONFIG`,也可以用環境變數調整。## 6. 介面文字與翻譯