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
Harness: rule ↔ enforcement map, Claude Code hooks, one rule set for both agents
許元豪4aecab151472
diff --git a/.claude/harness/hooks/dispatch.mjs b/.claude/harness/hooks/dispatch.mjsnew file mode 100644index 0000000..96d6998--- /dev/null+++ b/.claude/harness/hooks/dispatch.mjs@@ -0,0 +1,23 @@+// The one entry point for every Claude Code hook (.claude/settings.json): `node dispatch.mjs pre|post|stop`.+// Reads the event, answers the common case on the fast path (./fast.mjs: no TypeScript, no module graph), and only+// otherwise loads the handler — with Node's compile cache on, so even that skips re-stripping and re-compiling the+// .mts files after the first run. Measured per call on Windows (median of 15): 99 ms before → see docs/HARNESS.md.+import module from 'node:module';+import { markStart, needsHandler } from './fast.mjs';++const kind = /** @type {'pre' | 'post' | 'stop'} */ (process.argv[2]);+let raw = '';+for await (const chunk of process.stdin) raw += chunk;+let e = null;+try { e = JSON.parse(raw || '{}'); } catch {}++if (kind === 'pre') markStart(e);+if (needsHandler(kind, e)) {+ module.enableCompileCache?.();+ const [{ respond }, { handle }] = await Promise.all([+ import('../lib/hook.mts'),+ import(kind === 'pre' ? './pre-tool-use.mts' : kind === 'post' ? './post-tool-use.mts' : './stop.mts'),+ ]);+ await respond({ pre: 'pre-tool-use', post: 'post-tool-use', stop: 'stop' }[kind] ?? String(kind), raw, handle);+}+process.exit(0);diff --git a/.claude/harness/hooks/fast.mjs b/.claude/harness/hooks/fast.mjsnew file mode 100644index 0000000..f615866--- /dev/null+++ b/.claude/harness/hooks/fast.mjs@@ -0,0 +1,50 @@+// The fast path: which hook events can be answered without loading the TypeScript handlers at all.+// Plain JS on purpose: a .mts entry costs Node's type stripper (≈ 22 ms) before the first line runs, and every tool+// call of every production agent pays this twice (PreToolUse + PostToolUse; 870–2,330 tool calls per job measured).+//+// Contract: each filter is a cheap SUPERSET of what its handler acts on — it may send work to the handler that turns out+// to be nothing, never the reverse. test/fast.test.mts holds every case from the policy and render tests to it.+// Quotes and backslashes are dropped before matching, so `g''it`, "secrets.json" or secrets\.json cannot slip past+// a filter that the full shell parser would have caught.+import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++export const stateRoot = () => process.env.REELMIMIC_HARNESS_STATE || join(tmpdir(), 'reelmimic-harness');+/** Per-session state dir; shared with lib/hook.mts so both sides agree on where pending renders live. */+export const sessionDir = (/** @type {string | undefined} */ session) => join(stateRoot(), String(session || 'default').replace(/[^\w-]/g, '_'));++const flat = (/** @type {unknown} */ s) => String(s ?? '').replace(/[\\'"`]/g, '');+const SECRETS = /secrets\.json/i;+// secrets-write/read: the file name · git-add-projects: git · second-server: the entry file, npm/pnpm/yarn, start scripts+const PRE_SHELL = /secrets\.json|\bgit\b|index\.ts|\b(?:npm|pnpm|yarn)\b|start\.(?:sh|bat|cmd)/i;+// render.mts classify(): render.mjs, hyperframes, remotion, hf_frames.py, ffmpeg, `npm run render`+const RENDER = /render|hf_frames|ffmpeg|hyperframes|remotion/i;++const hasPending = (/** @type {string | undefined} */ session) => {+ const d = sessionDir(session);+ try { return existsSync(d) && readdirSync(d).some((f) => f.endsWith('.json')); } catch { return true; }+};++/**+ * @param {'pre' | 'post' | 'stop'} kind+ * @param {any} e the hook event, or null when stdin was not JSON (the handler logs that)+ */+export function needsHandler(kind, e) {+ if (!e || typeof e !== 'object') return true;+ const input = e.tool_input ?? {}, shell = e.tool_name === 'Bash' || e.tool_name === 'PowerShell';+ if (kind === 'pre') return shell ? PRE_SHELL.test(flat(input.command)) : SECRETS.test(String(input.file_path ?? input.notebook_path ?? ''));+ if (kind === 'post') return shell ? RENDER.test(flat(input.command)) : e.tool_name === 'Read' && hasPending(e.session_id);+ if (kind === 'stop') return !e.stop_hook_active && hasPending(e.session_id);+ return true;+}++/** PreToolUse of a command that may render: note when it started, keyed by tool_use_id, so PostToolUse can tell the+ * file this run wrote from one an earlier run left behind (exactly, instead of guessing from a time window). */+export function markStart(/** @type {any} */ e) {+ if (!e?.tool_use_id || !(e.tool_name === 'Bash' || e.tool_name === 'PowerShell') || !RENDER.test(flat(e.tool_input?.command))) return;+ try {+ const d = join(sessionDir(e.session_id), 'starts'); mkdirSync(d, { recursive: true });+ writeFileSync(join(d, String(e.tool_use_id).replace(/[^\w-]/g, '_')), String(Date.now()));+ } catch {}+}diff --git a/.claude/harness/hooks/post-tool-use.mts b/.claude/harness/hooks/post-tool-use.mtsnew file mode 100644index 0000000..860e983--- /dev/null+++ b/.claude/harness/hooks/post-tool-use.mts@@ -0,0 +1,51 @@+// PostToolUse, the feedback half of rule `look-after-render`:+// Bash / PowerShell that rendered a film → contact sheet + black/frozen scan, handed straight back to the agent as+// context, and remembered as "not looked at yet";+// … that rendered review images → remembered until read;+// Read of an image → marks the renders it covers as looked at (the Stop hook checks what is left).+import { classify, freshOutput } from '../render.mts';+import { addPending, clearPending, listPending, takeStart, type Handler } from '../lib/hook.mts';+import { parse, resolvePath, samePath, within } from '../lib/shell.mts';+import { contactSheet, defects, type Span } from '../lib/video.mts';++const IMAGE = /\.(png|jpe?g|webp|gif)$/i;+const fmt = (L: Span[]) => L.map((s) => `${s.start.toFixed(1)}–${s.end.toFixed(1)} s`).join(', ');++export const handle: Handler = async (e) => {+ const session = e.session_id ?? 'default', input = e.tool_input ?? {};+ if (e.tool_name === 'Read') {+ const f = resolvePath(String(input.file_path ?? ''), e.cwd ?? process.cwd());+ if (!IMAGE.test(f)) return null;+ // A film counts as looked at once any image is read after it (the sheet, or frames the agent pulled itself);+ // review images only when that file (or a file in that folder, for --stills) is read.+ for (const p of listPending(session)) if (p.kind === 'film' || samePath(f, p.path) || within(f, p.path)) clearPending(session, p.id);+ return null;+ }+ if (e.tool_name !== 'Bash' && e.tool_name !== 'PowerShell') return null;+ const command = String(input.command ?? ''), cwd = e.cwd ?? process.cwd(), now = Date.now();+ const since = takeStart(session, e.tool_use_id);+ const notes: string[] = [];+ for (const c of parse(command, cwd)) {+ const r = classify(c);+ if (!r) continue;+ if (input.run_in_background) {+ if (r.kind === 'film') notes.push(`Render running in the background (${r.engine}). When it finishes, run \`node .claude/harness/look.mts ${r.out ?? '<video>'}\` for a contact sheet and Read it before going on (rule \`look-after-render\`).`);+ addPending(session, { kind: r.kind, path: r.out ?? c.cwd, at: now, command: command.slice(0, 200) });+ continue;+ }+ const out = freshOutput(r, c.cwd, { since, now });+ if (!out) { if (r.kind === 'film') notes.push(`${r.engine} ran but wrote no new video${r.out ? ` at ${r.out}` : ''}${since ? ' during this call' : ''}: check the command output before assuming it rendered.`); continue; }+ if (r.kind === 'check') { addPending(session, { kind: 'check', path: out, at: now, command: command.slice(0, 200) }); continue; }+ const sheet = await contactSheet(out);+ const d = await defects(out, sheet.duration);+ addPending(session, { kind: 'film', path: out, sheet: sheet.path, at: now, command: command.slice(0, 200) });+ const lines = [`Rendered ${out} (${sheet.duration.toFixed(1)} s). Contact sheet: ${sheet.path} — frames at ${sheet.times.join(', ')} s, left→right, top→bottom, ${sheet.cols} per row. Read it now (rule \`look-after-render\`); pull full-size frames for anything that needs a closer look.`];+ // A dark end card / fade-out is a house standard, not a defect: say where the black is and let the agent judge.+ const tail = (s: Span) => s.end >= sheet.duration - 0.05;+ if (d.black.length) lines.push(`Black picture at ${fmt(d.black)}${d.black.every(tail) ? ' (only at the end: the end fade?)' : ' — check it is intended'}.`);+ if (d.frozen.length) lines.push(`Picture frozen ≥ 2.5 s at ${fmt(d.frozen)} — a hold, or a render that stopped moving?`);+ if (!d.scanned) lines.push('(Longer than 5 min: black/frozen scan skipped.)');+ notes.push(lines.join(' '));+ }+ return notes.length ? { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: notes.join('\n') } } : null;+};diff --git a/.claude/harness/hooks/pre-tool-use.mts b/.claude/harness/hooks/pre-tool-use.mtsnew file mode 100644index 0000000..8f8237c--- /dev/null+++ b/.claude/harness/hooks/pre-tool-use.mts@@ -0,0 +1,8 @@+// PreToolUse: run the policies (../policy.mts) on the call about to happen; deny or ask with a reason the agent can act on.+import type { Handler } from '../lib/hook.mts';+import { evaluate } from '../policy.mts';++export const handle: Handler = async (e) => {+ const v = await evaluate(e.tool_name ?? '', e.tool_input ?? {}, e.cwd ?? process.cwd());+ return v && { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: v.decision, permissionDecisionReason: `[harness:${v.policy}] ${v.reason}` } };+};diff --git a/.claude/harness/hooks/stop.mts b/.claude/harness/hooks/stop.mtsnew file mode 100644index 0000000..d7b742f--- /dev/null+++ b/.claude/harness/hooks/stop.mts@@ -0,0 +1,14 @@+// Stop: the gate half of rule `look-after-render`. If this session rendered something it never looked at, the agent is+// sent back once to look. `stop_hook_active` (set when Claude Code is already continuing because of a Stop hook) lets+// the second stop through, so a render that genuinely cannot be checked never traps the agent in a loop.+import { listPending, type Handler } from '../lib/hook.mts';++const STALE_MS = 6 * 3600_000; // older than a working session: forget it rather than nag about yesterday's render++export const handle: Handler = (e) => {+ if (e.stop_hook_active) return null;+ const left = listPending(e.session_id ?? 'default').filter((p) => Date.now() - p.at < STALE_MS);+ if (!left.length) return null;+ const list = left.map((p) => `- ${p.kind === 'film' ? 'film' : 'review image'} ${p.path}${p.sheet ? ` (contact sheet ${p.sheet})` : ''}`).join('\n');+ return { decision: 'block', reason: `Rule \`look-after-render\`: these renders were never looked at:\n${list}\nRead them (or frames from them) and fix what you see before finishing. If one was superseded by a later render you did check, say so and stop.` };+};diff --git a/.claude/harness/lib/hook.mts b/.claude/harness/lib/hook.mtsnew file mode 100644index 0000000..43d114c--- /dev/null+++ b/.claude/harness/lib/hook.mts@@ -0,0 +1,83 @@+// Shared plumbing for the Claude Code hooks: read the event from stdin, answer on stdout, keep an audit trail, and keep+// per-session state between hooks (a render seen by PostToolUse is what the Stop hook later checks for).+//+// Failure policy: a hook that crashes must never take the agent down or block work, so every handler runs through+// `respond()`, which logs the error and returns no decision (fail open). Guardrails here catch honest mistakes by an+// agent working in this repo; they are not a sandbox against a hostile one (see docs/HARNESS.md, "Limits").+import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { sessionDir } from '../hooks/fast.mjs';++export const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..').replace(/\\/g, '/');++export interface HookEvent {+ session_id?: string;+ tool_use_id?: string;+ cwd?: string;+ hook_event_name?: string;+ tool_name?: string;+ tool_input?: Record<string, unknown>;+ tool_response?: unknown;+ stop_hook_active?: boolean;+}+export type Handler = (e: HookEvent) => Promise<Output | null> | Output | null;++export type Output =+ | { hookSpecificOutput: { hookEventName: 'PreToolUse'; permissionDecision: 'deny' | 'ask'; permissionDecisionReason: string } }+ | { hookSpecificOutput: { hookEventName: 'PostToolUse'; additionalContext: string } }+ | { decision: 'block'; reason: string };++const AUDIT = () => process.env.REELMIMIC_HARNESS_AUDIT || join(ROOT, '.claude/harness/audit.jsonl');++/** One line per decision the harness made (deny / ask / injected context / block / crash), for `tail` and review.+ * Inside a production job the app sets REELMIMIC_JOB_DIR / REELMIMIC_AGENT on the agent (app/server/turn.ts), and the+ * same line also goes to that project's logs/harness.jsonl, next to events.jsonl, where timeline.py reports it. */+export function audit(rec: Record<string, unknown>) {+ const job = process.env.REELMIMIC_JOB_DIR, line = JSON.stringify({ ts: new Date().toISOString(), agent: process.env.REELMIMIC_AGENT, ...rec }) + '\n';+ try { appendFileSync(AUDIT(), line); } catch {}+ if (job) try { mkdirSync(join(job, 'logs'), { recursive: true }); appendFileSync(join(job, 'logs', 'harness.jsonl'), line); } catch {}+}++/** Run a handler on the raw event and print its decision. Never throws: errors are audited and mean "no decision". */+export async function respond(name: string, raw: string, handle: Handler) {+ let e: HookEvent = {};+ try {+ e = JSON.parse(raw || '{}');+ if (process.env.REELMIMIC_HARNESS_DEBUG) audit({ hook: name, debug: e });+ const out = await handle(e);+ if (out) {+ audit({ hook: name, session: e.session_id, tool: e.tool_name, out });+ process.stdout.write(JSON.stringify(out));+ }+ } catch (err) {+ audit({ hook: name, session: e.session_id, tool: e.tool_name, error: String((err as Error)?.stack || err) });+ }+}++// --- session state: one file per pending item, so parallel tool calls never race on a shared read-modify-write ---++export interface Pending { id: string; kind: 'film' | 'check'; path: string; sheet?: string; at: number; command: string }+const dirOf = (session: string) => sessionDir(session);++/** When the call that may have rendered started (written by dispatch.mjs on PreToolUse), or null. Consumed once. */+export function takeStart(session: string, toolUseId: string | undefined): number | null {+ if (!toolUseId) return null;+ const f = join(dirOf(session), 'starts', toolUseId.replace(/[^\w-]/g, '_'));+ try { const t = +readFileSync(f, 'utf8'); rmSync(f, { force: true }); return t > 0 ? t : null; } catch { return null; }+}++export function addPending(session: string, p: Omit<Pending, 'id'>) {+ const d = dirOf(session); mkdirSync(d, { recursive: true });+ const id = `${p.at}-${Math.random().toString(36).slice(2, 8)}`;+ writeFileSync(join(d, id + '.json'), JSON.stringify({ id, ...p }));+}+export function listPending(session: string): Pending[] {+ const d = dirOf(session);+ try {+ return readdirSync(d).filter((f) => f.endsWith('.json')).flatMap((f) => {+ try { return [JSON.parse(readFileSync(join(d, f), 'utf8')) as Pending]; } catch { return []; }+ });+ } catch { return []; }+}+export function clearPending(session: string, id: string) { rmSync(join(dirOf(session), id + '.json'), { force: true }); }diff --git a/.claude/harness/lib/shell.mts b/.claude/harness/lib/shell.mtsnew file mode 100644index 0000000..603e776--- /dev/null+++ b/.claude/harness/lib/shell.mts@@ -0,0 +1,158 @@+// Reads an agent's shell command the way the shell will run it — enough for policy, not a shell. Splits a command line+// into simple commands (on ; && || | & newlines, subshells and $( ) / `` substitutions, whose insides run too), honours+// quotes and escapes, and tracks what changes between them: `cd` / `pushd` / `git -C` move the working directory,+// `export K=V` and `K=V cmd` set the environment, and `bash -c '…'` / `sh -c` / `env` / `nohup` / `sudo` are unwrapped.+// A regex over the raw string would miss `cd app && npm start` and `echo $(cat ~/.reelmimic/secrets.json)`.+import { homedir } from 'node:os';+import { resolve } from 'node:path';++export interface Simple {+ argv: string[];+ env: Record<string, string>; // inherited exports + this command's K=V prefixes+ redirects: string[]; // files written by > >> &> (not 2>&1 style fd copies)+ cwd: string; // where it runs+}+type Tok = { k: 'w'; v: string } | { k: 'op'; v: string };++const WRAPPERS = new Set(['sudo', 'nohup', 'time', 'command', 'exec', 'nice', 'stdbuf']);+const SHELLS = /^(?:.*[\\/])?(?:bash|sh|zsh|dash)(?:\.exe)?$/i;++export function lex(src: string): Tok[] {+ const out: Tok[] = []; let cur = '', word = false, i = 0;+ const end = () => { if (word) out.push({ k: 'w', v: cur }); cur = ''; word = false; };+ const op = (v: string) => { end(); out.push({ k: 'op', v }); };+ // Here-documents whose bodies start after the current line: `cat <<'EOF' > msg.txt && git commit -F msg.txt`.+ // A body is the command's stdin, not commands. Quoted delimiter: plain data. Unquoted: its $( ) and `…` still run.+ const heredocs: { delim: string; tabs: boolean; quoted: boolean }[] = [];+ const bodies = () => {+ for (const h of heredocs.splice(0)) {+ for (;;) {+ const e = src.indexOf('\n', i), line = src.slice(i, e < 0 ? src.length : e).replace(/\r$/, '');+ i = e < 0 ? src.length : e + 1;+ if ((h.tabs ? line.replace(/^\t+/, '') : line) === h.delim || e < 0) break;+ for (let j = 0; !h.quoted && j < line.length; j++) {+ let inner: string | null = null;+ if (line[j] === '$' && line[j + 1] === '(') { const e = closeParen(line, j + 1); inner = line.slice(j + 2, e); j = e; }+ else if (line[j] === '`') { const e = line.indexOf('`', j + 1), k = e < 0 ? line.length : e; inner = line.slice(j + 1, k); j = k; }+ if (inner != null) out.push({ k: 'op', v: ';' }, ...lex(inner), { k: 'op', v: ';' });+ }+ }+ }+ };+ while (i < src.length) {+ const c = src[i], n = src[i + 1] ?? '';+ if (c === '\\') { if (n === '\n') { i += 2; continue; } cur += n; word = true; i += 2; continue; }+ if (c === "'") { const j = src.indexOf("'", i + 1), e = j < 0 ? src.length : j; cur += src.slice(i + 1, e); word = true; i = e + 1; continue; }+ if (c === '"') {+ // A $( ) inside double quotes still runs: hand it to the caller as its own command, keep the rest as the word.+ word = true; i++;+ while (i < src.length && src[i] !== '"') {+ if (src[i] === '\\' && '"\\$`'.includes(src[i + 1] ?? '')) { cur += src[i + 1]; i += 2; }+ else if (src[i] === '$' && src[i + 1] === '(') { const j = closeParen(src, i + 1); out.push({ k: 'op', v: '(' }, ...lex(src.slice(i + 2, j)), { k: 'op', v: ')' }); i = j + 1; }+ else if (src[i] === '`') { const j = src.indexOf('`', i + 1), e = j < 0 ? src.length : j; out.push({ k: 'op', v: '(' }, ...lex(src.slice(i + 1, e)), { k: 'op', v: ')' }); i = e + 1; }+ else cur += src[i++];+ }+ i++; continue;+ }+ if (c === '#' && !word) { while (i < src.length && src[i] !== '\n') i++; continue; }+ if (c === ' ' || c === '\t' || c === '\r') { end(); i++; continue; }+ if (c === '\n') { op(';'); i++; bodies(); continue; }+ if (c === '<' && n === '<' && src[i + 2] === '<') { op('<'); i += 3; continue; } // here-string: the word after it is data+ if (c === '<' && n === '<') {+ end(); i += 2;+ const tabs = src[i] === '-'; if (tabs) i++;+ while (src[i] === ' ' || src[i] === '\t') i++;+ const m = /^(?:'([^']*)'|"([^"]*)"|((?:\\.|[^\s;&|<>()])+))/.exec(src.slice(i)) ?? ['', '', '', ''];+ const raw = m[3] ?? '';+ heredocs.push({ delim: m[1] ?? m[2] ?? raw.replace(/\\(.)/g, '$1'), tabs, quoted: m[1] != null || m[2] != null || raw.includes('\\') });+ i += m[0].length; continue;+ }+ if (c === '$' && n === '(') { const j = closeParen(src, i + 1); out.push({ k: 'op', v: '(' }, ...lex(src.slice(i + 2, j)), { k: 'op', v: ')' }); i = j + 1; continue; }+ if (c === '`') { const j = src.indexOf('`', i + 1), e = j < 0 ? src.length : j; out.push({ k: 'op', v: '(' }, ...lex(src.slice(i + 1, e)), { k: 'op', v: ')' }); i = e + 1; continue; }+ if (c === '&' && n === '&') { op('&&'); i += 2; continue; }+ if (c === '|' && n === '|') { op('||'); i += 2; continue; }+ if (c === '&' && n === '>') { op(src[i + 2] === '>' ? '>>' : '>'); i += src[i + 2] === '>' ? 3 : 2; continue; }+ if (c === '>' || c === '<') {+ if (word && /^\d+$/.test(cur)) { cur = ''; word = false; } // 2> file: the fd number is not a word+ if (c === '>' && n === '&') { end(); i += 2; while (/[\d-]/.test(src[i] ?? '')) i++; continue; } // 2>&1: no file+ const v = c === '>' && n === '>' ? '>>' : c === '<' && n === '<' ? '<<' : c;+ op(v); i += v.length; continue;+ }+ if (';|&()'.includes(c)) { op(c); i++; continue; }+ cur += c; word = true; i++;+ }+ end();+ return out;+}++function closeParen(s: string, open: number) {+ for (let d = 0, i = open; i < s.length; i++) { if (s[i] === '(') d++; else if (s[i] === ')' && --d === 0) return i; }+ return s.length;+}++/** Every simple command in `src`, in the order they run, with the cwd and environment each one sees. */+export function parse(src: string, cwd: string, env: Record<string, string> = {}, depth = 0): Simple[] {+ const out: Simple[] = []; let words: string[] = [], redirects: string[] = [], pending = '';+ const state = { cwd, env: { ...env } };+ // ( … ) and $( … ) run on their own: park the enclosing command's words, parse the inside, then pick them back up.+ // The inside's `cd` does not leak out (a subshell has its own cwd).+ const stack: { words: string[]; redirects: string[]; pending: string; cwd: string }[] = [];+ const flush = () => {+ if (words.length || redirects.length) out.push(...expand(words, redirects, state, depth));+ words = []; redirects = []; pending = '';+ };+ for (const t of lex(src)) {+ if (t.k === 'op' && (t.v === '>' || t.v === '>>' || t.v === '<' || t.v === '<<')) { pending = t.v; continue; }+ if (t.k === 'op' && t.v === '(') { stack.push({ words, redirects, pending, cwd: state.cwd }); words = []; redirects = []; pending = ''; continue; }+ if (t.k === 'op' && t.v === ')') { flush(); const s = stack.pop(); if (s) { ({ words, redirects, pending } = s); state.cwd = s.cwd; } continue; }+ if (t.k === 'op') { flush(); continue; }+ if (pending) { if (pending === '>' || pending === '>>') redirects.push(resolvePath(t.v, state.cwd)); pending = ''; continue; }+ words.push(t.v);+ }+ flush();+ return out;+}++function expand(words: string[], redirects: string[], state: { cwd: string; env: Record<string, string> }, depth: number): Simple[] {+ const local: Record<string, string> = {};+ let i = 0;+ for (; i < words.length && /^[A-Za-z_]\w*=/.test(words[i]); i++) { const [k, ...v] = words[i].split('='); local[k] = v.join('='); }+ let argv = words.slice(i);+ // Unwrap launchers so the policy sees the real program: `env -i K=V node x`, `nohup node x &`, `sudo -u u cmd`.+ for (;;) {+ const a0 = base(argv[0] ?? '');+ if (a0 === 'env') { argv = argv.slice(1); while (argv[0] && (argv[0].startsWith('-') || argv[0].includes('='))) { const w = argv.shift()!; if (w.includes('=') && !w.startsWith('-')) { const [k, ...v] = w.split('='); local[k] = v.join('='); } } continue; }+ if (WRAPPERS.has(a0)) { argv = argv.slice(1); while (argv[0]?.startsWith('-')) argv = argv.slice(argv[0] === '-u' || argv[0] === '-n' ? 2 : 1); continue; }+ break;+ }+ const env = { ...state.env, ...local };+ if (!argv.length) { Object.assign(state.env, local); return redirects.length ? [{ argv: [], env, redirects, cwd: state.cwd }] : []; }+ const a0 = base(argv[0]);+ if ((a0 === 'cd' || a0 === 'pushd' || a0 === 'set-location' || a0 === 'sl') && argv.length <= 2) {+ const to = argv[1] && argv[1] !== '-' ? argv[1] : argv[1] ? state.cwd : homedir();+ state.cwd = resolvePath(to, state.cwd);+ return [];+ }+ if (a0 === 'export') { for (const w of argv.slice(1)) if (w.includes('=')) { const [k, ...v] = w.split('='); state.env[k] = v.join('='); } return []; }+ const self: Simple = { argv, env, redirects, cwd: state.cwd };+ if (depth < 4 && SHELLS.test(argv[0])) {+ const c = argv.indexOf('-c');+ if (c > 0 && argv[c + 1] != null) return [self, ...parse(argv[c + 1], state.cwd, env, depth + 1)];+ }+ return [self];+}++/** Lower-case program name without directory or .exe/.cmd, so `C:\…\node.exe` and `node` compare equal. */+export const base = (p: string) => p.replace(/^.*[\\/]/, '').replace(/\.(exe|cmd|bat|ps1)$/i, '').toLowerCase();++/** An absolute, forward-slash path: `~` → home, Git Bash `/c/Users` → `C:/Users`, relative → against cwd. */+export function resolvePath(p: string, cwd: string): string {+ let s = p.replace(/^~(?=$|[\\/])/, homedir().replace(/\\/g, '/'));+ if (process.platform === 'win32') s = s.replace(/^\/([a-zA-Z])(?=\/|$)/, '$1:');+ return resolve(cwd, s).replace(/\\/g, '/').replace(/^[a-z](?=:)/, (d) => d.toUpperCase()); // Claude Code reports c:\…, Node C:\…+}++const norm = (p: string) => (process.platform === 'win32' ? p.toLowerCase() : p).replace(/\/+$/, '');+export const samePath = (a: string, b: string) => norm(a) === norm(b);+/** True when `child` is `parent` or anything below it. */+export const within = (child: string, parent: string) => { const c = norm(child), p = norm(parent); return c === p || c.startsWith(p + '/'); };diff --git a/.claude/harness/lib/video.mts b/.claude/harness/lib/video.mtsnew file mode 100644index 0000000..828858f--- /dev/null+++ b/.claude/harness/lib/video.mts@@ -0,0 +1,66 @@+// What the post-render hook does to a fresh film before the agent looks at it: a contact sheet of evenly spaced+// frames (one image to Read instead of none), and a mechanical scan for the defects that are cheap to find by+// machine — black stretches and frozen picture — so the agent's eyes go to what only eyes can judge.+import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { promisify } from 'node:util';++const exec = promisify(execFile);+export const VIDEO = /\.(mp4|mov|webm|mkv|m4v)$/i;++/** ffmpeg / ffprobe, from FFMPEG_DIR when set (same lookup as app/server/env.ts), else PATH. */+export function bin(name: 'ffmpeg' | 'ffprobe') {+ const d = process.env.FFMPEG_DIR;+ const p = d && join(d, process.platform === 'win32' ? name + '.exe' : name);+ return p && existsSync(p) ? p : name;+}++export async function duration(file: string): Promise<number> {+ const { stdout } = await exec(bin('ffprobe'), ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file], { timeout: 20000 });+ const d = parseFloat(stdout);+ if (!(d > 0)) throw new Error(`no duration for ${file}`);+ return d;+}++export interface Sheet { path: string; times: number[]; cols: number; duration: number }++/** n frames at the middle of n equal slices (never the very first or last frame), tiled into one JPEG. Cached by+ * file + size + mtime, so asking twice for the same render costs nothing. */+export async function contactSheet(file: string, n = 9, cols = 3, width = 480): Promise<Sheet> {+ const st = statSync(file), dur = await duration(file);+ const key = createHash('sha1').update(`${file}|${st.size}|${st.mtimeMs}|${n}|${width}`).digest('hex').slice(0, 16);+ const dir = join(tmpdir(), 'reelmimic-harness', 'sheets'); mkdirSync(dir, { recursive: true });+ const path = join(dir, `${key}.jpg`).replace(/\\/g, '/');+ const times = Array.from({ length: n }, (_, k) => +(((k + 0.5) * dur) / n).toFixed(2));+ if (existsSync(path)) return { path, times, cols, duration: dur };+ const work = join(dir, key); mkdirSync(work, { recursive: true });+ try {+ // One seek per frame, in parallel: input seeking is near-instant, decoding the whole film to pick 9 frames is not.+ await Promise.all(times.map((t, k) => exec(bin('ffmpeg'), ['-v', 'error', '-y', '-ss', String(t), '-i', file, '-frames:v', '1',+ '-vf', `scale=${width}:-2`, '-q:v', '3', join(work, `${k}.jpg`)], { timeout: 30000 })));+ await exec(bin('ffmpeg'), ['-v', 'error', '-y', '-start_number', '0', '-i', join(work, '%d.jpg'), '-frames:v', '1',+ '-vf', `tile=${cols}x${Math.ceil(n / cols)}:padding=4:color=0x18181c`, '-q:v', '3', path], { timeout: 30000 });+ } finally { rmSync(work, { recursive: true, force: true }); }+ return { path, times, cols, duration: dur };+}++export interface Span { start: number; end: number }+export interface Defects { black: Span[]; frozen: Span[]; scanned: boolean }++/** Black (≥ 0.4 s) and frozen (≥ 2.5 s) stretches in one decode pass at low resolution. Films longer than `maxSec`+ * are skipped: the scan is linear in length and a hook must stay quick. */+export async function defects(file: string, dur: number, maxSec = 300): Promise<Defects> {+ if (dur > maxSec) return { black: [], frozen: [], scanned: false };+ const { stderr } = await exec(bin('ffmpeg'), ['-hide_banner', '-nostats', '-i', file, '-an', '-vf',+ 'scale=320:-2,blackdetect=d=0.4:pix_th=0.10,freezedetect=n=0.002:d=2.5', '-f', 'null', '-'],+ { timeout: 90000, maxBuffer: 64 * 1024 * 1024 });+ const black = [...stderr.matchAll(/black_start:([\d.]+)\s+black_end:([\d.]+)/g)].map((m) => ({ start: +m[1], end: +m[2] }));+ const fs = [...stderr.matchAll(/freeze_start[:=]\s*([\d.]+)/g)].map((m) => +m[1]);+ const fe = [...stderr.matchAll(/freeze_end[:=]\s*([\d.]+)/g)].map((m) => +m[1]);+ const frozen = fs.map((s, k) => ({ start: s, end: fe[k] ?? dur }));+ return { black, frozen: dedupe(frozen), scanned: true };+}+const dedupe = (L: Span[]) => L.filter((s, i) => L.findIndex((x) => Math.abs(x.start - s.start) < 0.01) === i);diff --git a/.claude/harness/look.mts b/.claude/harness/look.mtsnew file mode 100644index 0000000..5e92810--- /dev/null+++ b/.claude/harness/look.mts@@ -0,0 +1,10 @@+// The post-render check by hand, for renders that ran in the background or outside an agent:+// node .claude/harness/look.mts <video> [--n 9] [--cols 3] → contact sheet path + black/frozen stretches+import { contactSheet, defects } from './lib/video.mts';++const [file, ...rest] = process.argv.slice(2);+if (!file) { console.error('usage: node .claude/harness/look.mts <video> [--n 9] [--cols 3]'); process.exit(2); }+const opt = (k: string, d: number) => { const i = rest.indexOf(k); return i >= 0 ? +rest[i + 1] : d; };+const sheet = await contactSheet(file, opt('--n', 9), opt('--cols', 3));+const d = await defects(file, sheet.duration);+console.log(JSON.stringify({ sheet: sheet.path, times: sheet.times, duration: +sheet.duration.toFixed(2), black: d.black, frozen: d.frozen, scanned: d.scanned }, null, 1));diff --git a/.claude/harness/policy.mts b/.claude/harness/policy.mtsnew file mode 100644index 0000000..4298094--- /dev/null+++ b/.claude/harness/policy.mts@@ -0,0 +1,141 @@+// PreToolUse policies: the project rules that can be checked before a tool call runs. Each policy names the rule it+// enforces (the ids in CLAUDE.md's rule list); `sync-rules.mts --check` fails CI if a policy points at a rule that no+// longer exists, or a rule claims a policy that is not here. A policy returns null when it has nothing to say; when+// several speak, deny wins over ask. Reasons are written for the agent: what was stopped, why, and the allowed way.+import { existsSync } from 'node:fs';+import { request } from 'node:http';+import { homedir } from 'node:os';+import { ROOT } from './lib/hook.mts';+import { base, parse, resolvePath, samePath, within, type Simple } from './lib/shell.mts';++export interface Ctx { tool: string; input: Record<string, unknown>; cwd: string; env: Record<string, string | undefined>; commands: Simple[]; probe: (port: number) => Promise<boolean> }+export interface Verdict { decision: 'deny' | 'ask'; reason: string }+export interface Policy { id: string; rule: string; check: (c: Ctx) => Verdict | null | Promise<Verdict | null> }++const SHELL_TOOLS = new Set(['Bash', 'PowerShell']);+const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);+const filePath = (c: Ctx) => String(c.input.file_path ?? c.input.notebook_path ?? '');++// --- secrets ----------------------------------------------------------------------------------------------------+// Keys live in ~/.reelmimic/secrets.json (app/server/env.ts). The user fills it in; an agent writing it can silently+// replace a working key, and an agent printing it puts every key into the transcript and the job log.+const isSecrets = (p: string) => /(^|[\\/])secrets\.json$/i.test(p);+const READERS = new Set(['cat', 'type', 'head', 'tail', 'less', 'more', 'bat', 'jq', 'get-content', 'gc', 'grep', 'rg', 'findstr', 'select-string', 'strings', 'od', 'xxd']);+// Mentioning the file is harmless for these: they cannot write it except through a redirect, which is checked anyway.+const INERT = new Set(['echo', 'printf', 'ls', 'dir', 'stat', 'test', '[', 'which', 'git', 'gh', 'find', 'wc', 'file', 'realpath', 'dirname', 'basename']);+const SECRETS_HELP = 'API keys belong to the user and live in ~/.reelmimic/secrets.json (copy secrets.example.json). Tell the user which key to add instead; to check whether one is set, use `test -f ~/.reelmimic/secrets.json` or read it from the environment the server exports.';++const secretsWrite: Policy = {+ id: 'secrets-write', rule: 'secrets',+ check(c) {+ if (WRITE_TOOLS.has(c.tool) && isSecrets(filePath(c))) return { decision: 'deny', reason: `Writing ${filePath(c)} is blocked (rule \`secrets\`). ${SECRETS_HELP}` };+ if (!SHELL_TOOLS.has(c.tool)) return null;+ for (const s of c.commands) {+ const hit = s.redirects.find(isSecrets);+ if (hit) return { decision: 'deny', reason: `This command writes ${hit} (rule \`secrets\`). ${SECRETS_HELP}` };+ const p = base(s.argv[0] ?? '');+ if (!s.argv.slice(1).some((a) => /secrets\.json/i.test(a) && !/secrets\.example\.json/i.test(a)) || INERT.has(p) || READERS.has(p)) continue;+ return { decision: 'deny', reason: `\`${s.argv.join(' ').slice(0, 160)}\` touches a secrets.json file and could change or copy it (rule \`secrets\`). ${SECRETS_HELP}` };+ }+ return null;+ },+};++const secretsRead: Policy = {+ id: 'secrets-read', rule: 'secrets',+ check(c) {+ const ask = (p: string): Verdict => ({ decision: 'ask', reason: `Reading ${p} would copy the user's API keys into the transcript (rule \`secrets\`). Allow only if the user asked for it.` });+ if (c.tool === 'Read' && isSecrets(filePath(c)) && existsSync(filePath(c))) return ask(filePath(c));+ if (!SHELL_TOOLS.has(c.tool)) return null;+ for (const s of c.commands) {+ if (!READERS.has(base(s.argv[0] ?? ''))) continue;+ // Only real files count: `grep -rn secrets.json app/` searches for the name, it does not open the file.+ const f = s.argv.slice(1).map((a) => resolvePath(a, s.cwd)).find((a) => isSecrets(a) && existsSync(a));+ if (f) return ask(f);+ }+ return null;+ },+};++// --- projects-private ---------------------------------------------------------------------------------------------+// projects/ holds the user's references, uploads and films (gitignored). `git add -f` is the only way in, and once a+// film is pushed to a public repo it cannot be taken back.+const PROJECTS = `${ROOT}/projects`;+const gitAddProjects: Policy = {+ id: 'git-add-projects', rule: 'projects-private',+ check(c) {+ if (!SHELL_TOOLS.has(c.tool)) return null;+ for (const s of c.commands) {+ if (base(s.argv[0] ?? '') !== 'git') continue;+ let i = 1, cwd = s.cwd;+ for (; i < s.argv.length && s.argv[i].startsWith('-'); i++) if (s.argv[i] === '-C' || s.argv[i] === '-c') { if (s.argv[i] === '-C') cwd = resolvePath(s.argv[i + 1] ?? '.', cwd); i++; }+ if (!['add', 'stage'].includes(s.argv[i] ?? '') || !within(cwd, ROOT)) continue;+ const args = s.argv.slice(i + 1), dd = args.indexOf('--');+ const opts = dd < 0 ? args.filter((a) => a.startsWith('-')) : args.slice(0, dd).filter((a) => a.startsWith('-'));+ const specs = (dd < 0 ? args.filter((a) => !a.startsWith('-')) : [...args.slice(0, dd).filter((a) => !a.startsWith('-')), ...args.slice(dd + 1)]);+ const force = opts.some((o) => o === '--force' || /^-[a-zA-Z]*f/.test(o));+ const whole = opts.some((o) => o === '-A' || o === '--all' || /^-[a-zA-Z]*A/.test(o)) && !specs.length;+ const paths = specs.map((p) => (p.startsWith(':/') ? `${ROOT}/${p.slice(2)}` : resolvePath(p, cwd)));+ const inside = paths.find((p) => within(p, PROJECTS) && !samePath(p, `${PROJECTS}/.gitkeep`));+ const covers = force && (whole ? ROOT : paths.find((p) => within(PROJECTS, p)));+ if (inside || covers) return { decision: 'deny', reason: `\`${s.argv.join(' ')}\` would stage ${inside ?? 'projects/'} (rule \`projects-private\`): projects/ is the user's references and films and never goes into git. Stage the code you changed by path instead.` };+ }+ return null;+ },+};++// --- one-server ---------------------------------------------------------------------------------------------------+// A second server on the real projects dir runs recoverOrphans() at startup (app/server/jobs.ts) and marks every job+// the first server is running as interrupted. Starting one is fine when none is up, or when it points at a scratch+// dir. restart.sh is the sanctioned way to replace a running one: it refuses while agents are working.+export function startsServer(s: Simple): boolean {+ const a = s.argv, p = base(a[0] ?? '');+ if (['node', 'tsx', 'bun'].includes(p)) return a.slice(1).some((x) => samePath(resolvePath(x, s.cwd), `${ROOT}/app/server/index.ts`));+ if (['npm', 'pnpm', 'yarn'].includes(p)) {+ const pre = a.indexOf('--prefix'), dir = pre > 0 ? resolvePath(a[pre + 1] ?? '.', s.cwd) : s.cwd;+ const script = a.find((x) => ['start', 'server'].includes(x));+ return !!script && samePath(dir, `${ROOT}/app`);+ }+ const script = a.find((x) => /(^|[\\/])start\.(sh|bat|cmd)$/i.test(x)) ?? (/(^|[\\/])start\.(sh|bat|cmd)$/i.test(a[0] ?? '') ? a[0] : null);+ return !!script && samePath(resolvePath(script, s.cwd), `${ROOT}/${script.replace(/^.*[\\/]/, '')}`);+}++export function probeHealth(port: number, timeoutMs = 600): Promise<boolean> {+ return new Promise((done) => {+ const req = request({ host: '127.0.0.1', port, path: '/api/health', timeout: timeoutMs }, (res) => {+ let b = ''; res.on('data', (d) => (b += d)).on('end', () => { try { done(JSON.parse(b).ok === true); } catch { done(false); } });+ });+ req.on('timeout', () => { req.destroy(); done(false); }).on('error', () => done(false)).end();+ });+}++const secondServer: Policy = {+ id: 'second-server', rule: 'one-server',+ async check(c) {+ if (!SHELL_TOOLS.has(c.tool)) return null;+ for (const s of c.commands) {+ if (!startsServer(s)) continue;+ const dir = s.env.REELMIMIC_PROJECTS ?? c.env.REELMIMIC_PROJECTS;+ if (dir && !samePath(resolvePath(dir, s.cwd), PROJECTS)) continue; // a scratch projects dir: isolated, fine+ const ports = [...new Set([+(s.env.PORT ?? c.env.PORT ?? 4318), 4318])];+ for (const port of ports) if (await c.probe(port)) {+ return { decision: 'deny', reason: `A ReelMimic server is already running on :${port} against projects/ (rule \`one-server\`). A second one would mark the jobs it is running as interrupted. To pick up server changes run \`bash app/restart.sh\` (it refuses while agents are working); to test, set REELMIMIC_PROJECTS to a scratch folder and PORT to a free port.` };+ }+ }+ return null;+ },+};++export const POLICIES: Policy[] = [secretsWrite, secretsRead, gitAddProjects, secondServer];++export async function evaluate(tool: string, input: Record<string, unknown>, cwd: string, env = process.env, probe = probeHealth): Promise<(Verdict & { policy: string; rule: string }) | null> {+ const commands = SHELL_TOOLS.has(tool) && typeof input.command === 'string' ? parse(input.command, resolvePath(cwd || homedir(), ROOT)) : [];+ const ctx: Ctx = { tool, input, cwd, env, commands, probe };+ let best: (Verdict & { policy: string; rule: string }) | null = null;+ for (const p of POLICIES) {+ const v = await p.check(ctx);+ if (v && (!best || (v.decision === 'deny' && best.decision === 'ask'))) best = { ...v, policy: p.id, rule: p.rule };+ if (best?.decision === 'deny') break;+ }+ return best;+}diff --git a/.claude/harness/render.mts b/.claude/harness/render.mtsnew file mode 100644index 0000000..76dabcf--- /dev/null+++ b/.claude/harness/render.mts@@ -0,0 +1,80 @@+// Which shell commands render something an agent must then look at (rule `look-after-render`), and what they wrote.+// film — a video: the engines' `render.mjs --encode|--clip`, `hyperframes render`, `remotion render`, or ffmpeg+// writing a project's out/*.mp4 (the assemble step). The post-render hook builds a contact sheet for it.+// check — review images the agent asked for (`render.mjs --sheet|--strip|--stills`, `hf_frames.py`): already the+// thing to Read, so the hook only remembers them until they are read.+// `render.mjs --frames` (frames to disk, encoded later) is neither: the encode that follows is the film.+import { existsSync, readdirSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { base, resolvePath, type Simple } from './lib/shell.mts';+import { VIDEO } from './lib/video.mts';++export interface Render { kind: 'film' | 'check'; out: string | null; engine: string }++const flag = (argv: string[], ...names: string[]) => {+ for (let i = 0; i < argv.length; i++) for (const n of names) {+ if (argv[i] === n) return argv[i + 1] ?? '';+ if (argv[i].startsWith(n + '=')) return argv[i].slice(n.length + 1);+ }+ return null;+};+const has = (argv: string[], ...names: string[]) => argv.some((a) => names.some((n) => a === n || a.startsWith(n + '=')));++export function classify(c: Simple): Render | null {+ const { argv } = c, at = (p: string | null) => (p ? resolvePath(p, c.cwd) : null);+ if (!argv.length) return null; // a bare redirect (`> log.txt`): found by replaying production commands+ const script = argv.findIndex((a) => /(^|[\\/])render\.mjs$/.test(a));+ if (script >= 0 && ['node', 'bun', 'deno'].includes(base(argv[0]))) {+ const rest = argv.slice(script + 1), out = at(flag(rest, '--out'));+ if (has(rest, '--sheet', '--strip', '--stills', '--loop')) return { kind: 'check', out, engine: 'render.mjs' };+ if (has(rest, '--frames') && !has(rest, '--encode', '--clip')) return null;+ return { kind: 'film', out: out ?? resolvePath('out/video.mp4', c.cwd), engine: 'render.mjs' };+ }+ const hf = argv.findIndex((a) => base(a) === 'hyperframes');+ if (hf >= 0 && argv[hf + 1] === 'render') return { kind: 'film', out: at(flag(argv, '--output', '-o')), engine: 'hyperframes' };+ const rm = argv.findIndex((a) => base(a) === 'remotion');+ if (rm >= 0 && argv[rm + 1] === 'render') return { kind: 'film', out: at(argv.slice(rm + 2).filter((a) => !a.startsWith('-')).find((a) => VIDEO.test(a)) ?? null), engine: 'remotion' };+ if (base(argv[0]).startsWith('python') && argv.some((a) => /(^|[\\/])hf_frames\.py$/.test(a))) return { kind: 'check', out: at(flag(argv, '--out')), engine: 'hf_frames' };+ if (base(argv[0]) === 'ffmpeg') {+ const last = argv[argv.length - 1] ?? '';+ if (VIDEO.test(last) && /(^|[\\/])out[\\/][^\\/]+$/.test(last.replace(/\\/g, '/'))) return { kind: 'film', out: at(last), engine: 'ffmpeg' };+ }+ if (['npm', 'pnpm', 'yarn'].includes(base(argv[0])) && argv.includes('render')) return { kind: 'film', out: null, engine: 'npm run render' };+ return null;+}++/** When a file must have been written to count as this run's output. With the call's start time (recorded on+ * PreToolUse by tool_use_id) it is exact: anything older is a previous run's leftover, however recent. Without one+ * (hooks enabled mid-call, an event without an id) fall back to a window. 2 s of slack covers filesystems that store+ * mtime coarsely (FAT: 2 s) and a render that opens its output file just before the hook's clock reading. */+export interface Freshness { since?: number | null; withinMs?: number; now?: number }+const cutoff = ({ since, withinMs = 180_000, now = Date.now() }: Freshness) => (since ? since - 2000 : now - withinMs);++/** The newest video under `dir` (two levels down, skipping node_modules and dot-dirs) written after the cutoff:+ * where the output went when the command did not say. */+export function newestVideo(dir: string, f: Freshness = {}): string | null {+ const after = cutoff(f);+ let best: { p: string; t: number } | null = null;+ const walk = (d: string, depth: number) => {+ let names: string[] = [];+ try { names = readdirSync(d); } catch { return; }+ for (const n of names) {+ if (n === 'node_modules' || n.startsWith('.')) continue;+ const p = join(d, n);+ let st; try { st = statSync(p); } catch { continue; }+ if (st.isDirectory()) { if (depth < 2) walk(p, depth + 1); }+ else if (VIDEO.test(n) && st.mtimeMs >= after && (!best || st.mtimeMs > best.t)) best = { p, t: st.mtimeMs };+ }+ };+ walk(dir, 0);+ return best ? (best as { p: string }).p.replace(/\\/g, '/') : null;+}++/** The file this render wrote, if it is there and fresh (a failed render leaves last run's file behind). */+export function freshOutput(r: Render, cwd: string, f: Freshness = {}): string | null {+ if (r.out && existsSync(r.out)) {+ try { const st = statSync(r.out); if (st.mtimeMs >= cutoff(f)) return r.out; } catch {} // a file, or a --stills folder+ return null;+ }+ return r.kind === 'film' ? newestVideo(cwd, f) : null;+}diff --git a/.claude/harness/rules.mts b/.claude/harness/rules.mtsnew file mode 100644index 0000000..4eaf6d5--- /dev/null+++ b/.claude/harness/rules.mts@@ -0,0 +1,51 @@+// Every project rule, and every place that enforces it. A rule that only lives in a prompt is a wish; this table says+// which ones are wishes. `sync-rules.mts --check` (CI) keeps it honest in both directions:+// - each rule id in CLAUDE.md's shared block has an entry here, and each entry here is a rule there;+// - each `at` exists, and its `#anchor` (when given) still appears in that file — so renaming a policy, moving a+// script or deleting the prompt line that carries a rule breaks the build instead of silently dropping the rule;+// - each `hook` entry names a policy in policy.mts that declares this rule, and every policy is listed here.+export type Layer = 'hook' | 'runtime' | 'ci' | 'tool' | 'git' | 'prompt';+export interface Enforcement { layer: Layer; at: string; how: string }++export const LAYERS: Record<Layer, string> = {+ hook: 'Claude Code hook: every tool call of every Claude Code session in the repo, the app’s production agents included',+ runtime: 'the app pipeline: gates every production job, Claude Code or Codex',+ ci: 'GitHub Actions on every push and pull request',+ tool: 'a script the workflow runs, whose output is the evidence',+ git: 'repository configuration',+ prompt: 'instructions only: followed when read, nothing checks it',+};++export const ENFORCEMENT: Record<string, Enforcement[]> = {+ '2d-only': [+ { layer: 'prompt', at: '.claude/skills/video-clone/SKILL.md#目前只做 2D', how: 'style router filters by medium; 3D styles sit in styles/_disabled/' },+ ],+ 'assets': [+ { layer: 'tool', at: '.claude/skills/video-clone/scripts/fetch_assets.py#ASSETS.md', how: 'only reuse-licensed sources; every download is recorded with its licence' },+ { layer: 'prompt', at: '.claude/skills/video-clone/SKILL.md', how: 'characters, lyrics and reference footage rules' },+ ],+ 'compare-gate': [+ { layer: 'runtime', at: 'app/server/prompts.ts#每鏡 ≥ 4', how: 'the final critic scores every shot against the reference; must-fix items go back to the builders' },+ { layer: 'runtime', at: 'app/server/review.ts#reviewFix', how: 'review → fix loop with a fresh reviewer each round, up to the quality mode’s limit' },+ { layer: 'tool', at: '.claude/skills/video-clone/scripts/compare.py', how: 'side-by-side reference vs film, per shot' },+ ],+ 'look-after-render': [+ { layer: 'hook', at: '.claude/harness/hooks/post-tool-use.mts#contactSheet', how: 'after a film render: contact sheet + black/frozen scan handed to the agent' },+ { layer: 'hook', at: '.claude/harness/hooks/stop.mts#stop_hook_active', how: 'an agent that rendered and never read an image is sent back once' },+ { layer: 'runtime', at: 'app/server/prompts.ts#動作只能從連續影格判斷', how: 'reviewers that did not build the shot judge it from consecutive frames, with before/after crops as evidence' },+ ],+ 'secrets': [+ { layer: 'hook', at: '.claude/harness/policy.mts#secrets-write', how: 'writes to any secrets.json are denied (Write/Edit, redirects, cp/mv/sed/…)' },+ { layer: 'hook', at: '.claude/harness/policy.mts#secrets-read', how: 'reading the real file asks the user first' },+ { layer: 'git', at: '.gitignore#secrets.json', how: 'never committed' },+ ],+ 'projects-private': [+ { layer: 'hook', at: '.claude/harness/policy.mts#git-add-projects', how: '`git add` of anything under projects/ (or -f over it) is denied' },+ { layer: 'git', at: '.gitignore#projects/*', how: 'ignored, so only a forced add could stage it' },+ ],+ 'one-server': [+ { layer: 'hook', at: '.claude/harness/policy.mts#second-server', how: 'starting a server on the real projects/ while one answers /api/health is denied' },+ { layer: 'runtime', at: 'app/restart.sh#not restarting', how: 'the sanctioned restart refuses while agents are working' },+ { layer: 'ci', at: 'app/server/jobs.test.ts#REELMIMIC_PROJECTS', how: 'tests run against a throwaway projects dir' },+ ],+};diff --git a/.claude/harness/sync-rules.mts b/.claude/harness/sync-rules.mtsnew file mode 100644index 0000000..0754ce6--- /dev/null+++ b/.claude/harness/sync-rules.mts@@ -0,0 +1,82 @@+// One rule set, two agents. CLAUDE.md (Claude Code) is the source; AGENTS.md (Codex) carries a copy of its shared block+// between the `harness:shared` markers. This script keeps the copy, the enforcement table (rules.mts) and the table+// in docs/HARNESS.md in step:+// node .claude/harness/sync-rules.mts --check CI: exit 1 listing every drift+// node .claude/harness/sync-rules.mts --write copy CLAUDE.md's block into AGENTS.md, regenerate the docs table+import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';+import { ROOT } from './lib/hook.mts';+import { POLICIES } from './policy.mts';+import { ENFORCEMENT, LAYERS, type Layer } from './rules.mts';++const SHARED = ['<!-- harness:shared', '<!-- /harness:shared -->'] as const;+const TABLE = ['<!-- harness:table', '<!-- /harness:table -->'] as const;+const RULE_LINE = /^- `([a-z0-9][a-z0-9-]*)` /;++const read = (f: string) => readFileSync(join(ROOT, f), 'utf8').replace(/\r\n/g, '\n');++/** The text between a marker pair (the opening marker may carry a comment), or null when the markers are missing. */+export function block(text: string, [open, close]: readonly [string, string]): string | null {+ const a = text.indexOf(open), b = text.indexOf(close);+ if (a < 0 || b < a) return null;+ return text.slice(text.indexOf('\n', a) + 1, b);+}+function replaceBlock(text: string, [open, close]: readonly [string, string], body: string) {+ const a = text.indexOf(open), b = text.indexOf(close);+ return text.slice(0, text.indexOf('\n', a) + 1) + body + text.slice(b);+}+export const ruleIds = (shared: string) => shared.split('\n').map((l) => RULE_LINE.exec(l)?.[1]).filter((x): x is string => !!x);++export function renderTable(): string {+ const order: Layer[] = ['hook', 'runtime', 'ci', 'tool', 'git', 'prompt'];+ const rows = Object.entries(ENFORCEMENT).map(([id, L]) => {+ const by = [...L].sort((x, y) => order.indexOf(x.layer) - order.indexOf(y.layer));+ const strongest = by[0].layer;+ const cell = by.map((e) => `**${e.layer}** [${e.at.split('#')[0].replace(/^.*\//, '')}](../${e.at.split('#')[0]}) — ${e.how}`).join('<br>');+ return `| \`${id}\` | ${strongest === 'prompt' ? '⚠️ prompt only' : strongest} | ${cell} |`;+ });+ const legend = order.map((l) => `- **${l}** — ${LAYERS[l]}`).join('\n');+ return `| rule | strongest layer | enforced by |\n|---|---|---|\n${rows.join('\n')}\n\n${legend}\n`;+}++/** Every drift between the rule files, the enforcement table, the policies and the docs. Empty when in step. */+export function problems(): string[] {+ const P: string[] = [];+ const claude = read('CLAUDE.md'), agents = read('AGENTS.md'), docs = read('docs/HARNESS.md');+ const src = block(claude, SHARED), copy = block(agents, SHARED);+ if (src == null) return ['CLAUDE.md: no harness:shared block'];+ if (copy == null) P.push('AGENTS.md: no harness:shared block');+ else if (copy !== src) P.push('AGENTS.md: shared block differs from CLAUDE.md (run sync-rules.mts --write)');+ const ids = ruleIds(src);+ for (const d of ids.filter((x, i) => ids.indexOf(x) !== i)) P.push(`CLAUDE.md: rule \`${d}\` listed twice`);+ for (const id of ids) if (!ENFORCEMENT[id]) P.push(`rule \`${id}\` (CLAUDE.md) has no entry in rules.mts`);+ for (const id of Object.keys(ENFORCEMENT)) if (!ids.includes(id)) P.push(`rules.mts: \`${id}\` is not a rule in CLAUDE.md`);+ for (const [id, L] of Object.entries(ENFORCEMENT)) for (const e of L) {+ const [file, anchor] = e.at.split('#');+ if (!existsSync(join(ROOT, file))) { P.push(`\`${id}\`: ${file} does not exist`); continue; }+ if (anchor && !read(file).includes(anchor)) P.push(`\`${id}\`: "${anchor}" no longer appears in ${file}`);+ if (e.layer === 'hook' && file.endsWith('policy.mts') && !POLICIES.some((p) => p.id === anchor && p.rule === id)) P.push(`\`${id}\`: policy.mts has no policy "${anchor}" for this rule`);+ }+ for (const p of POLICIES) {+ if (!ids.includes(p.rule)) P.push(`policy \`${p.id}\` enforces \`${p.rule}\`, which is not a rule in CLAUDE.md`);+ if (!(ENFORCEMENT[p.rule] ?? []).some((e) => e.at.endsWith(`#${p.id}`))) P.push(`policy \`${p.id}\` is missing from rules.mts`);+ }+ const t = block(docs, TABLE);+ if (t == null) P.push('docs/HARNESS.md: no harness:table block');+ else if (t !== renderTable()) P.push('docs/HARNESS.md: enforcement table is stale (run sync-rules.mts --write)');+ return P;+}++if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {+ if (process.argv.includes('--write')) {+ const src = block(read('CLAUDE.md'), SHARED);+ if (src == null) { console.error('CLAUDE.md: no harness:shared block'); process.exit(1); }+ writeFileSync(join(ROOT, 'AGENTS.md'), replaceBlock(read('AGENTS.md'), SHARED, src));+ writeFileSync(join(ROOT, 'docs/HARNESS.md'), replaceBlock(read('docs/HARNESS.md'), TABLE, renderTable()));+ }+ const P = problems();+ for (const p of P) console.error('✗ ' + p);+ if (P.length) process.exit(1);+ console.log(`✓ rules in step: ${Object.keys(ENFORCEMENT).length} rules, ${POLICIES.length} policies, AGENTS.md and docs/HARNESS.md match CLAUDE.md`);+}diff --git a/.claude/harness/test/fast.test.mts b/.claude/harness/test/fast.test.mtsnew file mode 100644index 0000000..d1dd4d8--- /dev/null+++ b/.claude/harness/test/fast.test.mts@@ -0,0 +1,58 @@+// The fast path may only skip what the handlers would ignore anyway. Checked as a property over a corpus:+// for every command, "a policy speaks or classify() finds a render" ⇒ needsHandler() is true.+// The corpus is the tricky cases below, plus — when this checkout has production logs — every shell command real agents+// ran (projects/*/logs/events.jsonl), which also measures how often the fast path is taken.+import assert from 'node:assert/strict';+import { existsSync, readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { test } from 'node:test';+import { needsHandler } from '../hooks/fast.mjs';+import { ROOT } from '../lib/hook.mts';+import { evaluate } from '../policy.mts';+import { classify } from '../render.mts';+import { parse } from '../lib/shell.mts';++const up = async (_port: number) => true; // assume a server is up: the widest set of commands a policy acts on+const ev = (command: string, cwd = ROOT) => ({ session_id: 'fast', cwd, tool_name: 'Bash', tool_input: { command } });++async function check(command: string, cwd = ROOT) {+ const acts = !!(await evaluate('Bash', { command }, cwd, {}, up));+ const renders = parse(command, cwd).some((c) => classify(c));+ if (acts) assert.ok(needsHandler('pre', ev(command, cwd)), `pre fast path would skip: ${command}`);+ if (renders) assert.ok(needsHandler('post', ev(command, cwd)), `post fast path would skip: ${command}`);+ return { pre: needsHandler('pre', ev(command, cwd)), post: needsHandler('post', ev(command, cwd)) };+}++const TRICKY = [+ `g''it add -f projects`, `"git" add -f projects/x`, `\\git add -f projects`, 'cd projects && git add -f .',+ 'echo x > ~/.reelmimic/se""crets.json', `cat ~/.reelmimic/'secrets'.json`, 'cp a ~/.reelmimic/secrets\\.json',+ 'bash -c "cd app && npm start"', 'nohup node app/server/index.ts &', 'npm --prefix app run server', 'cmd /c start.bat',+ 'node render.mjs --encode --out=out/video.mp4', `node "render.mjs" --sheet=1 --out=out/check/a.jpg`,+ 'npx hyperframes render --output out.mp4', 'ffmpeg -i v.mp4 -i a.wav out/video.mp4', 'python hf_frames.py build --at 1 --out o',+];++test('tricky spellings never slip past the fast path', async () => {+ for (const c of TRICKY) await check(c);+});++test('Read / Write: only a secrets.json path leaves the fast path; Stop and Read-after-render only with pending state', () => {+ assert.equal(needsHandler('pre', { tool_name: 'Read', tool_input: { file_path: `${ROOT}/README.md` } }), false);+ assert.equal(needsHandler('pre', { tool_name: 'Write', tool_input: { file_path: 'C:\\Users\\u\\.reelmimic\\secrets.json' } }), true);+ assert.equal(needsHandler('post', { session_id: 'never-rendered', tool_name: 'Read', tool_input: { file_path: 'a.png' } }), false);+ assert.equal(needsHandler('stop', { session_id: 'never-rendered' }), false);+ assert.equal(needsHandler('pre', null), true, 'malformed stdin goes to the handler, which logs it');+});++const logs = existsSync(join(ROOT, 'projects')) ? readdirSync(join(ROOT, 'projects')).map((p) => join(ROOT, 'projects', p, 'logs', 'events.jsonl')).filter(existsSync) : [];++test('every shell command real agents ran: no skip the handlers would have acted on; fast-path rate', { skip: !logs.length && 'no production logs in this checkout' }, async () => {+ let n = 0, pre = 0, post = 0;+ for (const f of logs) for (const line of readFileSync(f, 'utf8').split('\n')) {+ if (!line.includes('"type":"tool"') || !line.includes('"name":"Bash"')) continue;+ let e: { detail?: string }; try { e = JSON.parse(line); } catch { continue; }+ const cmd = String(e.detail ?? '').replace(/…$/, ''); // logged commands are cut at 400 chars+ const r = await check(cmd, join(ROOT, 'projects'));+ n++; if (!r.pre) pre++; if (!r.post) post++;+ }+ console.log(` ${n} commands from ${logs.length} jobs — fast path: PreToolUse ${(100 * pre / n).toFixed(1)} %, PostToolUse ${(100 * post / n).toFixed(1)} %`);+});diff --git a/.claude/harness/test/hooks.test.mts b/.claude/harness/test/hooks.test.mtsnew file mode 100644index 0000000..90b5733--- /dev/null+++ b/.claude/harness/test/hooks.test.mts@@ -0,0 +1,109 @@+// The hooks end to end, run exactly as Claude Code runs them: a fresh `node` process, the event as JSON on stdin,+// the decision as JSON on stdout. State and audit go to a temp dir.+import assert from 'node:assert/strict';+import { execFileSync, spawn, spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, utimesSync, writeFileSync } from 'node:fs';+import { createServer } from 'node:http';+import type { AddressInfo } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { ROOT } from '../lib/hook.mts';+import { bin } from '../lib/video.mts';++const TMP = mkdtempSync(join(tmpdir(), 'harness-hooks-'));+const ENV: NodeJS.ProcessEnv = { ...process.env, REELMIMIC_HARNESS_STATE: join(TMP, 'state'), REELMIMIC_HARNESS_AUDIT: join(TMP, 'audit.jsonl') };+delete ENV.REELMIMIC_PROJECTS;++// The exact command line .claude/settings.json gives Claude Code.+const HOOK = (kind: string) => ['--disable-warning=ExperimentalWarning', join(ROOT, '.claude/harness/hooks/dispatch.mjs'), kind];+const KIND: Record<string, string> = { 'pre-tool-use': 'pre', 'post-tool-use': 'post', stop: 'stop' };++function hook(name: string, event: object | string, env: NodeJS.ProcessEnv = ENV) {+ const r = spawnSync(process.execPath, HOOK(KIND[name]),+ { input: typeof event === 'string' ? event : JSON.stringify(event), env, encoding: 'utf8', timeout: 120_000 });+ assert.equal(r.status, 0, r.stderr);+ return r.stdout ? JSON.parse(r.stdout) : null;+}+const audit = () => (existsSync(ENV.REELMIMIC_HARNESS_AUDIT!) ? readFileSync(ENV.REELMIMIC_HARNESS_AUDIT!, 'utf8').trim().split('\n').map((l) => JSON.parse(l)) : []);++test('pre-tool-use: deny carries the policy and the way out; allowed calls print nothing', () => {+ const out = hook('pre-tool-use', { session_id: 's1', cwd: ROOT, tool_name: 'Bash', tool_input: { command: 'git add -f projects' } });+ assert.equal(out.hookSpecificOutput.hookEventName, 'PreToolUse');+ assert.equal(out.hookSpecificOutput.permissionDecision, 'deny');+ assert.match(out.hookSpecificOutput.permissionDecisionReason, /^\[harness:git-add-projects\].*projects-private/);+ assert.equal(hook('pre-tool-use', { session_id: 's1', cwd: ROOT, tool_name: 'Bash', tool_input: { command: 'git status' } }), null);+ assert.ok(audit().some((a) => a.out?.hookSpecificOutput?.permissionDecision === 'deny'));+});++test('pre-tool-use: fails open on garbage, and says why in the audit log', () => {+ assert.equal(hook('pre-tool-use', '{not json'), null);+ assert.ok(audit().some((a) => a.hook === 'pre-tool-use' && /JSON/.test(a.error)));+});++test('pre-tool-use: second-server sees a real server answering /api/health', async () => {+ const srv = createServer((req, res) => res.end(req.url === '/api/health' ? '{"ok":true}' : '{}'));+ await new Promise<void>((r) => srv.listen(0, '127.0.0.1', r));+ const port = (srv.address() as AddressInfo).port;+ try {+ const ev = (command: string) => ({ session_id: 's1', cwd: ROOT, tool_name: 'Bash', tool_input: { command } });+ // spawnSync would block this process's event loop and the fake server with it: run the hook asynchronously.+ const run = (command: string) => new Promise<string>((done) => {+ const c = spawn(process.execPath, HOOK('pre'), { env: ENV });+ let o = ''; c.stdout.on('data', (d) => (o += d)); c.on('close', () => done(o)); c.stdin.end(JSON.stringify(ev(command)));+ });+ assert.match(await run(`PORT=${port} node app/server/index.ts`), /second-server/);+ assert.equal(await run(`PORT=${port} REELMIMIC_PROJECTS=${TMP}/p node app/server/index.ts`), '');+ } finally { srv.close(); }+});++const ffmpeg = spawnSync(bin('ffmpeg'), ['-version']).status === 0;++test('post-tool-use + stop: a film render is sheeted, scanned, and gated until looked at', { skip: !ffmpeg && 'ffmpeg not found' }, () => {+ const proj = join(TMP, 'proj'); mkdirSync(join(proj, 'out'), { recursive: true });+ // 3 s of picture, 1 s of black, 3 s of one still colour: a contact sheet, a black stretch and a frozen tail.+ execFileSync(bin('ffmpeg'), ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'testsrc2=s=640x360:r=24:d=3', '-f', 'lavfi', '-i', 'color=black:s=640x360:r=24:d=1',+ '-f', 'lavfi', '-i', 'color=0x3366cc:s=640x360:r=24:d=3', '-filter_complex', '[0][1][2]concat=n=3:v=1', '-pix_fmt', 'yuv420p', join(proj, 'out', 'video.mp4')]);+ const S = 'film-session', base = { session_id: S, cwd: proj, tool_name: 'Bash' };+ const out = hook('post-tool-use', { ...base, tool_input: { command: 'node render.mjs --encode --out=out/video.mp4' } });+ const ctx: string = out.hookSpecificOutput.additionalContext;+ const sheet = /Contact sheet: (\S+\.jpg)/.exec(ctx)?.[1];+ assert.ok(sheet && existsSync(sheet), ctx);+ assert.match(ctx, /Black picture at 3\.0–4\.0 s — check it is intended/);+ assert.match(ctx, /frozen ≥ 2\.5 s at 4\.\d–7\.0 s/);++ const block = hook('stop', { session_id: S });+ assert.equal(block.decision, 'block');+ assert.match(block.reason, /look-after-render[\s\S]*video\.mp4/);+ assert.equal(hook('stop', { session_id: S, stop_hook_active: true }), null, 'second stop goes through');+ hook('post-tool-use', { ...base, tool_name: 'Read', tool_input: { file_path: sheet } });+ assert.equal(hook('stop', { session_id: S }), null, 'looked at: free to stop');+});++test('post-tool-use + stop: review images are pending until that file is read', () => {+ const d = join(TMP, 'checks'); mkdirSync(join(d, 'out', 'check'), { recursive: true });+ const img = join(d, 'out', 'check', 'a.jpg'); writeFileSync(img, 'x');+ const S = 'check-session';+ assert.equal(hook('post-tool-use', { session_id: S, cwd: d, tool_name: 'Bash', tool_input: { command: 'node render.mjs --sheet=1,2 --out=out/check/a.jpg' } }), null);+ assert.equal(hook('stop', { session_id: S }).decision, 'block');+ hook('post-tool-use', { session_id: S, cwd: d, tool_name: 'Read', tool_input: { file_path: join(d, 'other.png') } });+ assert.equal(hook('stop', { session_id: S }).decision, 'block', 'a different image does not count');+ hook('post-tool-use', { session_id: S, cwd: d, tool_name: 'Read', tool_input: { file_path: img } });+ assert.equal(hook('stop', { session_id: S }), null);+});++test('post-tool-use: a background render is noted with the command to check it later', () => {+ const out = hook('post-tool-use', { session_id: 'bg', cwd: TMP, tool_name: 'Bash', tool_input: { command: 'npx hyperframes render --output out.mp4', run_in_background: true } });+ assert.match(out.hookSpecificOutput.additionalContext, /background[\s\S]*look\.mts .*out\.mp4/);+});++test('pre → post by tool_use_id: a video from just before this call is not taken for this call’s output', () => {+ const d = join(TMP, 'since'); mkdirSync(join(d, 'out'), { recursive: true });+ const f = join(d, 'out', 'video.mp4'); writeFileSync(f, 'x');+ const t = new Date(Date.now() - 20_000); utimesSync(f, t, t); // last run, 20 s ago: inside the old 3-minute window+ const ev = { session_id: 'since', tool_use_id: 'toolu_since_1', cwd: d, tool_name: 'Bash', tool_input: { command: 'node render.mjs --encode --out=out/video.mp4' } };+ assert.equal(hook('pre-tool-use', ev), null); // records the start+ const out = hook('post-tool-use', ev);+ assert.match(out.hookSpecificOutput.additionalContext, /wrote no new video at .*video\.mp4 during this call/);+ assert.equal(hook('stop', { session_id: 'since' }), null, 'nothing rendered, nothing to look at');+});diff --git a/.claude/harness/test/policy.test.mts b/.claude/harness/test/policy.test.mtsnew file mode 100644index 0000000..01d9ae3--- /dev/null+++ b/.claude/harness/test/policy.test.mts@@ -0,0 +1,90 @@+import assert from 'node:assert/strict';+import { mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { ROOT } from '../lib/hook.mts';+import { evaluate } from '../policy.mts';++const down = async (_port: number) => false, up = async (_port: number) => true;+const bash = (command: string, cwd = ROOT, probe = down, env: Record<string, string> = {}) => evaluate('Bash', { command }, cwd, env, probe);+const verdict = async (p: ReturnType<typeof bash>) => { const v = await p; return v ? `${v.decision}:${v.policy}` : null; };++const SECRETS_DIR = mkdtempSync(join(tmpdir(), 'harness-secrets-'));+const SECRETS = join(SECRETS_DIR, 'secrets.json').replace(/\\/g, '/');+writeFileSync(SECRETS, '{"YATING_KEY":"x"}');++test('secrets: writes are denied however they are spelled', async () => {+ assert.equal((await evaluate('Write', { file_path: SECRETS }, ROOT, {}, down))?.policy, 'secrets-write');+ assert.equal((await evaluate('Edit', { file_path: 'C:\\Users\\u\\.reelmimic\\secrets.json' }, ROOT, {}, down))?.decision, 'deny');+ for (const c of [+ `echo '{"K":1}' > ~/.reelmimic/secrets.json`,+ 'cp mine.json ~/.reelmimic/secrets.json',+ `sed -i 's/a/b/' ~/.reelmimic/secrets.json`,+ `python -c "import json; json.dump({}, open('/home/u/.reelmimic/secrets.json', 'w'))"`,+ 'cd ~/.reelmimic && tee secrets.json < new.json',+ 'Set-Content ~/.reelmimic/secrets.json "{}"',+ ]) assert.equal(await verdict(bash(c)), 'deny:secrets-write', c);+});++test('secrets: reading the real file asks; naming it does not', async () => {+ assert.equal((await evaluate('Read', { file_path: SECRETS }, ROOT, {}, down))?.decision, 'ask');+ assert.equal(await verdict(bash(`cat ${SECRETS}`)), 'ask:secrets-read');+ assert.equal(await verdict(bash(`echo $(cat ${SECRETS})`)), 'ask:secrets-read');+ for (const c of ['grep -rn "secrets.json" app/', 'git commit -m "load keys from secrets.json"', `test -f ${SECRETS} && echo set`, 'cp secrets.example.json /tmp/x.json'])+ assert.equal(await verdict(bash(c)), null, c);+ assert.equal(await evaluate('Edit', { file_path: `${ROOT}/secrets.example.json` }, ROOT, {}, down), null);+});++test('secrets: deny wins over ask in the same command', async () => {+ assert.equal(await verdict(bash(`cat ${SECRETS} && echo x > ${SECRETS}`)), 'deny:secrets-write');+});++test('projects-private: nothing under projects/ gets staged', async () => {+ for (const [c, cwd] of [+ ['git add projects/20261019-hvuc0/out/video.mp4', ROOT],+ ['git add -f projects', ROOT],+ ['git add -fA', ROOT],+ ['git add --force .', `${ROOT}/projects`],+ ['git add -f out/video.mp4', `${ROOT}/projects/abc`],+ ['git -C projects add -f abc', ROOT],+ ['git add :/projects/abc/plan.json', `${ROOT}/app`],+ ['cd projects/abc && git add -f .', ROOT],+ ]) assert.equal(await verdict(bash(c, cwd)), 'deny:git-add-projects', c);+ for (const c of ['git add -A', 'git add .', 'git add app/server/jobs.ts docs/', 'git add projects/.gitkeep', 'git add -f .claude/settings.json', 'git status projects'])+ assert.equal(await verdict(bash(c)), null, c);+ assert.equal(await verdict(bash('git add -f projects', join(tmpdir(), 'elsewhere'))), null, 'another repo is not ours to police');+});++test('one-server: a second server on the real projects dir is denied while one answers', async () => {+ for (const [c, cwd] of [+ ['node app/server/index.ts', ROOT],+ ['cd app && npm start', ROOT],+ ['npm run server', `${ROOT}/app`],+ ['npm --prefix app start', ROOT],+ ['nohup node server/index.ts > /tmp/log 2>&1 &', `${ROOT}/app`],+ ['bash start.sh', ROOT],+ ['./start.sh', ROOT],+ ]) {+ assert.equal(await verdict(bash(c, cwd, up)), 'deny:second-server', c);+ assert.equal(await verdict(bash(c, cwd, down)), null, `${c} (nothing running)`);+ }+});++test('one-server: scratch projects dirs, restart.sh and tests pass', async () => {+ for (const c of ['REELMIMIC_PROJECTS=/tmp/scratch PORT=4400 node app/server/index.ts', 'export REELMIMIC_PROJECTS=/tmp/s; cd app && npm start', 'bash app/restart.sh', 'cd app && npm test', 'node app/scripts/doctor.mjs'])+ assert.equal(await verdict(bash(c, ROOT, up)), null, c);+ assert.equal(await verdict(bash('node app/server/index.ts', ROOT, up, { REELMIMIC_PROJECTS: '/tmp/s' })), null, 'isolated by the session environment');+ assert.equal(await verdict(bash(`REELMIMIC_PROJECTS=${ROOT}/projects node app/server/index.ts`, ROOT, up)), 'deny:second-server', 'pointing at the real dir is not isolation');+});++test('one-server: probes the port the new server would use and the default', async () => {+ const seen: number[] = [];+ await bash('PORT=5001 node app/server/index.ts', ROOT, async (p) => { seen.push(p); return false; });+ assert.deepEqual(seen, [5001, 4318]);+});++test('other tools and harmless commands are left alone', async () => {+ assert.equal(await evaluate('Grep', { pattern: 'secrets.json' }, ROOT, {}, up), null);+ assert.equal(await verdict(bash('node render.mjs --encode --out=out/video.mp4', `${ROOT}/projects/x/build`, up)), null);+});diff --git a/.claude/harness/test/render.test.mts b/.claude/harness/test/render.test.mtsnew file mode 100644index 0000000..b6f5ca0--- /dev/null+++ b/.claude/harness/test/render.test.mts@@ -0,0 +1,52 @@+import assert from 'node:assert/strict';+import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { classify, freshOutput, newestVideo } from '../render.mts';+import { parse, resolvePath } from '../lib/shell.mts';++const B = resolvePath('/p/x/build', process.cwd());+const one = (src: string, cwd = B) => { const r = parse(src, cwd).map(classify).filter(Boolean); return r.length ? r[0] : null; };++test('film renders, with where they write', () => {+ assert.deepEqual(one('node render.mjs --encode --out=out/video.mp4'), { kind: 'film', out: `${B}/out/video.mp4`, engine: 'render.mjs' });+ assert.deepEqual(one('node render.mjs --clip --range=0:4'), { kind: 'film', out: `${B}/out/video.mp4`, engine: 'render.mjs' });+ assert.equal(one('node render.mjs --frames --workers=4 && node render.mjs --encode --out=out/video.mp4')?.kind, 'film');+ assert.deepEqual(one('npx hyperframes render --quality looks --output out.mp4'), { kind: 'film', out: `${B}/out.mp4`, engine: 'hyperframes' });+ assert.deepEqual(one('npx hyperframes render --quality draft'), { kind: 'film', out: null, engine: 'hyperframes' });+ assert.equal(one('npx remotion render src/index.ts Main out/v.mp4')?.out, `${B}/out/v.mp4`);+ assert.equal(one('ffmpeg -y -i v.mp4 -i mix.wav -c:v copy -shortest ../out/video.mp4')?.out, resolvePath('/p/x/out/video.mp4', process.cwd()));+});++test('review images are checks, not films', () => {+ for (const c of ['node render.mjs --sheet=0.5,1,1.5 --out=out/check/a.jpg', 'node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg', 'node render.mjs --stills=1.2 --out=out/stills'])+ assert.equal(one(c)?.kind, 'check', c);+ assert.deepEqual(one('python ../../.claude/skills/video-clone/scripts/hf_frames.py build --at 12.4 --out out/check'), { kind: 'check', out: `${B}/out/check`, engine: 'hf_frames' });+});++test('not renders', () => {+ for (const c of ['node render.mjs --frames --range=0:8 --workers=4', 'ffmpeg -i ref.mp4 -t 5 analysis/clip.mp4', 'npm test', 'node app/server/index.ts', 'cat render.mjs'])+ assert.equal(one(c), null, c);+});++test('only a freshly written file counts as the output', () => {+ const d = mkdtempSync(join(tmpdir(), 'harness-render-')), now = Date.now();+ mkdirSync(join(d, 'out')); const f = join(d, 'out', 'video.mp4'); writeFileSync(f, 'x');+ const r = { kind: 'film' as const, out: f.replace(/\\/g, '/'), engine: 'render.mjs' };+ assert.equal(freshOutput(r, d, { withinMs: 60_000, now }), r.out);+ utimesSync(f, new Date(now - 3600_000), new Date(now - 3600_000));+ assert.equal(freshOutput(r, d, { withinMs: 60_000, now }), null, 'last run’s file left behind by a failed render');+ writeFileSync(join(d, 'renders.mp4'), 'y');+ assert.equal(newestVideo(d, { withinMs: 60_000 })?.endsWith('renders.mp4'), true, 'output not named: the newest fresh video');+ assert.equal(freshOutput({ ...r, out: null }, d, { withinMs: 60_000 })?.endsWith('renders.mp4'), true);+});++test('with the call’s start time, a file from 30 s before it is a leftover (the window alone would take it)', () => {+ const d = mkdtempSync(join(tmpdir(), 'harness-since-')), now = Date.now(), f = join(d, 'video.mp4');+ writeFileSync(f, 'x'); utimesSync(f, new Date(now - 30_000), new Date(now - 30_000));+ const r = { kind: 'film' as const, out: f.replace(/\\/g, '/'), engine: 'render.mjs' };+ assert.equal(freshOutput(r, d, { now }), r.out, 'window only: looks fresh');+ assert.equal(freshOutput(r, d, { since: now - 5_000, now }), null, 'started 5 s ago: written before this call');+ assert.equal(freshOutput(r, d, { since: now - 31_000, now }), r.out, 'written during this call');+});diff --git a/.claude/harness/test/rules.test.mts b/.claude/harness/test/rules.test.mtsnew file mode 100644index 0000000..458048e--- /dev/null+++ b/.claude/harness/test/rules.test.mts@@ -0,0 +1,22 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { block, problems, renderTable, ruleIds } from '../sync-rules.mts';+import { ENFORCEMENT } from '../rules.mts';++test('the repo is in step: CLAUDE.md, AGENTS.md, rules.mts, policies and docs/HARNESS.md', () => {+ assert.deepEqual(problems(), []);+});++test('rule ids are read from the shared block only', () => {+ const t = 'intro\n- `not-a-rule` above\n<!-- harness:shared x -->\n## 規則\n- `a-rule` 文字\n- plain line\n- `b2` more\n<!-- /harness:shared -->\n';+ const b = block(t, ['<!-- harness:shared', '<!-- /harness:shared -->']);+ assert.deepEqual(ruleIds(b!), ['a-rule', 'b2']);+ assert.equal(block('nothing here', ['<!-- a', '<!-- /a -->']), null);+});++test('the table marks rules nothing checks', () => {+ const rows = renderTable().split('\n').filter((l) => l.startsWith('| `'));+ assert.equal(rows.length, Object.keys(ENFORCEMENT).length);+ for (const [id, L] of Object.entries(ENFORCEMENT))+ assert.equal(rows.find((r) => r.startsWith(`| \`${id}\``))!.includes('⚠️ prompt only'), L.every((e) => e.layer === 'prompt'), id);+});diff --git a/.claude/harness/test/shell.test.mts b/.claude/harness/test/shell.test.mtsnew file mode 100644index 0000000..1d6ee58--- /dev/null+++ b/.claude/harness/test/shell.test.mts@@ -0,0 +1,68 @@+import assert from 'node:assert/strict';+import { homedir } from 'node:os';+import { test } from 'node:test';+import { parse, resolvePath, within } from '../lib/shell.mts';++const CWD = resolvePath('/work/repo', process.cwd());+const argvs = (src: string) => parse(src, CWD).map((c) => c.argv);++test('splits on every operator and follows cd', () => {+ const [npm] = parse('cd app && npm start', CWD);+ assert.deepEqual(npm.argv, ['npm', 'start']);+ assert.equal(npm.cwd, `${CWD}/app`);+ assert.deepEqual(argvs('a; b || c | d & e\nf'), [['a'], ['b'], ['c'], ['d'], ['e'], ['f']]);+});++test('quotes, escapes, comments and line continuations', () => {+ assert.deepEqual(argvs(`git commit -m "fix: a \\"b\\" c" -m 'it''s'`), [['git', 'commit', '-m', 'fix: a "b" c', '-m', 'its']]);+ assert.deepEqual(argvs('echo a\\ b # not run: rm -rf /'), [['echo', 'a b']]);+ assert.deepEqual(argvs('node render.mjs \\\n --encode'), [['node', 'render.mjs', '--encode']]);+});++test('environment: K=V prefixes, export, and env/nohup/sudo launchers', () => {+ const [c] = parse('FOO=1 BAR="a b" node x.js', CWD);+ assert.deepEqual(c.env, { FOO: '1', BAR: 'a b' });+ assert.deepEqual(c.argv, ['node', 'x.js']);+ const e = parse('export REELMIMIC_PROJECTS=/tmp/p; node server/index.ts', CWD);+ assert.deepEqual(e.map((x) => x.argv), [['node', 'server/index.ts']]);+ assert.equal(e[0].env.REELMIMIC_PROJECTS, '/tmp/p');+ const [w] = parse('nohup env PORT=5000 node app/server/index.ts > log.txt 2>&1 &', CWD);+ assert.deepEqual(w.argv, ['node', 'app/server/index.ts']);+ assert.equal(w.env.PORT, '5000');+ assert.deepEqual(w.redirects, [`${CWD}/log.txt`]); // 2>&1 copies a descriptor, it names no file+});++test('substitutions and subshells run as their own commands; a subshell cd does not leak', () => {+ assert.deepEqual(argvs('echo $(cat ~/.reelmimic/secrets.json)'), [['cat', '~/.reelmimic/secrets.json'], ['echo']]);+ const q = parse('echo "pre $(cat f) post" > out.txt', CWD);+ assert.deepEqual(q.map((c) => c.argv), [['cat', 'f'], ['echo', 'pre post']]);+ assert.deepEqual(q[1].redirects, [`${CWD}/out.txt`]);+ assert.deepEqual(argvs('ls `which node`'), [['which', 'node'], ['ls']]);+ const s = parse('(cd sub; ls) && pwd', CWD);+ assert.equal(s[0].cwd, `${CWD}/sub`);+ assert.equal(s[1].cwd, CWD);+});++test('here-documents are stdin, not commands; an unquoted one still runs its substitutions', () => {+ // Found live: a commit message mentioning secrets.json, passed with -F - <<'EOF', was read as a command and denied.+ const msg = `git commit -q -F - <<'EOF'\nFix: yating_tts.py read secrets.json without an encoding\nrm -rf /\nEOF\ngit log --oneline -1`;+ assert.deepEqual(argvs(msg), [['git', 'commit', '-q', '-F', '-'], ['git', 'log', '--oneline', '-1']]);+ assert.deepEqual(argvs('cat <<-"END" > out.txt && ls\n\tbody line\n\tEND\npwd'), [['cat'], ['ls'], ['pwd']]);+ assert.deepEqual(parse('cat <<EOF > out.txt\nb\nEOF', CWD)[0].redirects, [`${CWD}/out.txt`]);+ assert.deepEqual(argvs('cat <<EOF\nkey: $(cat ~/.reelmimic/secrets.json) and `whoami`\nEOF'), [['cat'], ['cat', '~/.reelmimic/secrets.json'], ['whoami']]);+ assert.deepEqual(argvs('cat <<\\EOF\n$(rm x)\nEOF'), [['cat']], 'a backslash quotes the delimiter too');+ assert.deepEqual(argvs('grep x <<< "git add -f projects"'), [['grep', 'x']]);+});++test('bash -c is parsed as the commands it runs', () => {+ const L = parse(`bash -c 'cd /tmp && git add x'`, CWD);+ assert.deepEqual(L.map((c) => c.argv), [['bash', '-c', 'cd /tmp && git add x'], ['git', 'add', 'x']]);+ assert.equal(L[1].cwd, resolvePath('/tmp', CWD));+});++test('paths: ~, Git Bash drive paths, containment', () => {+ assert.equal(resolvePath('~/.reelmimic/secrets.json', CWD), resolvePath(`${homedir()}/.reelmimic/secrets.json`, CWD));+ if (process.platform === 'win32') assert.equal(resolvePath('/c/Users/x', CWD), 'C:/Users/x');+ assert.ok(within(`${CWD}/projects/a`, `${CWD}/projects`));+ assert.ok(!within(`${CWD}/projects-old`, `${CWD}/projects`));+});diff --git a/.claude/harness/tsconfig.json b/.claude/harness/tsconfig.jsonnew file mode 100644index 0000000..3e66662--- /dev/null+++ b/.claude/harness/tsconfig.json@@ -0,0 +1,13 @@+{+ // The harness runs on Node's type stripping like app/server; `tsc` only checks. Types come from app/node_modules.+ // The hook entry (hooks/dispatch.mjs, hooks/fast.mjs) is plain JS for start-up speed and is checked through JSDoc.+ "extends": "../../app/tsconfig.base.json",+ "compilerOptions": {+ "lib": ["ES2023"],+ "types": ["node"],+ "typeRoots": ["../../app/node_modules/@types"],+ "allowJs": true,+ "checkJs": true+ },+ "include": ["**/*.mts", "**/*.mjs"]+}diff --git a/.claude/settings.json b/.claude/settings.jsonindex 48d1ab1..cee34df 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -3,5 +3,24 @@"HYPERFRAMES_NO_TELEMETRY": "1","DO_NOT_TRACK": "1","REMOTION_TELEMETRY_DISABLED": "1"+ },+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Bash|PowerShell|Write|Edit|MultiEdit|NotebookEdit|Read",+ "hooks": [{ "type": "command", "command": "node --disable-warning=ExperimentalWarning \"$CLAUDE_PROJECT_DIR/.claude/harness/hooks/dispatch.mjs\" pre", "timeout": 15 }]+ }+ ],+ "PostToolUse": [+ {+ "matcher": "Bash|PowerShell|Read",+ "hooks": [{ "type": "command", "command": "node --disable-warning=ExperimentalWarning \"$CLAUDE_PROJECT_DIR/.claude/harness/hooks/dispatch.mjs\" post", "timeout": 120 }]+ }+ ],+ "Stop": [+ {+ "hooks": [{ "type": "command", "command": "node --disable-warning=ExperimentalWarning \"$CLAUDE_PROJECT_DIR/.claude/harness/hooks/dispatch.mjs\" stop", "timeout": 15 }]+ }+ ]}}diff --git a/.claude/skills/video-clone/scripts/timeline.py b/.claude/skills/video-clone/scripts/timeline.pyindex ed27125..fd488bd 100644--- a/.claude/skills/video-clone/scripts/timeline.py+++ b/.claude/skills/video-clone/scripts/timeline.py@@ -4,17 +4,18 @@ wall-clock per stage, every agent turn (who / phase / minutes), the critical patpython timeline.py projects/<id> [--json out.json]"""-import argparse, collections, datetime as D, json, os, re, sys+import argparse, collections, datetime as D, json, os, re+from pathlib import Pathdef ts(x): return D.datetime.fromisoformat(x.replace('Z', ''))def mins(a, b): return (b - a).total_seconds() / 60ap = argparse.ArgumentParser(); ap.add_argument('proj'); ap.add_argument('--json'); a = ap.parse_args()-j = json.load(open(os.path.join(a.proj, 'job.json'), encoding='utf-8'))+j = json.loads(Path(a.proj, 'job.json').read_text(encoding='utf-8'))ev = j.get('log', [])full = os.path.join(a.proj, 'logs', 'events.jsonl')if os.path.exists(full):- ev = [json.loads(l) for l in open(full, encoding='utf-8') if l.strip()] or ev+ ev = [json.loads(l) for l in Path(full).read_text(encoding='utf-8').splitlines() if l.strip()] or ev# agent turnsopen_t, turns = {}, []@@ -54,7 +55,7 @@ for t in turns: print(f" {t['start'][11:16]} {t['who'] or '-':14s} {t['phase']chunks = collections.defaultdict(list)shot2chunk = {}try:- prod = json.load(open(os.path.join(a.proj, 'build', 'production.json'), encoding='utf-8'))+ prod = json.loads(Path(a.proj, 'build', 'production.json').read_text(encoding='utf-8'))for c in prod.get('chunks') or []:for s in c.get('shots') or []: shot2chunk[s] = c['id']except (OSError, ValueError): pass@@ -65,15 +66,16 @@ for t in turns:if chunks:print('\nper segment (build / review / fix minutes, rounds):')for c in sorted(chunks, key=lambda x: int(x[1:])):- L = chunks[c]; f = lambda p: sum(m for ph, m in L if ph == p)+ L = chunks[c]; f = collections.Counter(); n = collections.Counter()+ for ph, m in L: f[ph] += m; n[ph] += 1rounds = (j.get('pipeline') or {}).get('chunks', {}).get(c, {}).get('round')- print(f" {c}: build {f('build_chunk'):.0f}, review {f('shot_qa'):.0f} ({sum(1 for ph, _ in L if ph == 'shot_qa')} shot reviews), fix {f('fix_chunk'):.0f} ({sum(1 for ph, _ in L if ph == 'fix_chunk')} fix turns), rounds {rounds or '?'} → {sum(m for _, m in L):.0f} min")+ print(f" {c}: build {f['build_chunk']:.0f}, review {f['shot_qa']:.0f} ({n['shot_qa']} shot reviews), fix {f['fix_chunk']:.0f} ({n['fix_chunk']} fix turns), rounds {rounds or '?'} → {sum(m for _, m in L):.0f} min")# what agents spend time on (gap to their next event)cat = collections.Counter(); byw = collections.defaultdict(list)for e in ev:if e.get('who'): byw[e['who']].append(e)-for w, es in byw.items():+for es in byw.values():for x, y in zip(es, es[1:]):g = (ts(y['ts']) - ts(x['ts'])).total_seconds()if g > 1800 or x.get('type') == 'turn': continue@@ -86,4 +88,19 @@ for w, es in byw.items():tot = sum(cat.values()) or 1print('\nagent time by activity (all agents summed):')for k, v in cat.most_common(): print(f" {k:18s} {v / 60:6.0f} min {100 * v / tot:4.0f}%")-if a.json: json.dump({'turns': turns, 'activity_min': {k: round(v / 60, 1) for k, v in cat.items()}}, open(a.json, 'w'), indent=1)+# what the harness hooks did in this job (.claude/harness, logged by the agents' hooks to logs/harness.jsonl)+hl = Path(a.proj, 'logs', 'harness.jsonl')+H = [json.loads(l) for l in hl.read_text(encoding='utf-8').splitlines() if l.strip()] if hl.exists() else []+if H:+ def kind(h):+ o = h.get('out') or {}; hs = o.get('hookSpecificOutput') or {}+ if h.get('error'): return 'hook error (failed open)'+ if hs.get('permissionDecision'): return f"{hs['permissionDecision']}: {hs.get('permissionDecisionReason', '').split(']')[0].lstrip('[')}"+ if o.get('decision') == 'block': return 'stop: sent back to look at a render'+ ctx = hs.get('additionalContext', '')+ return 'render: contact sheet + scan' if 'Contact sheet' in ctx else 'render: noted' if ctx else 'other'+ K = collections.Counter(kind(h) for h in H); who = collections.defaultdict(collections.Counter)+ for h in H: who[kind(h)][h.get('agent') or '-'] += 1+ print('\nharness (hooks):')+ for k, v in K.most_common(): print(f" {k:44s} {v:4d} {', '.join(f'{w}×{c}' for w, c in who[k].most_common(4))}")+if a.json: Path(a.json).write_text(json.dumps({'turns': turns, 'activity_min': {k: round(v / 60, 1) for k, v in cat.items()}, 'harness': dict(K) if H else {}}, indent=1), encoding='utf-8')diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 44398da..9ff22ec 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -24,6 +24,8 @@ jobs:cache-dependency-path: app/package-lock.json- run: npm ci- run: npm run typecheck+ - name: Typecheck the harness (.claude/harness, same strict config)+ run: npx tsc -p ../.claude/harness/tsconfig.json- run: npm run lint- run: npm test- run: npm run build@@ -39,7 +41,21 @@ jobs:cache: pip- run: sudo apt-get update && sudo apt-get install -y ffmpeg- run: pip install numpy opencv-python-headless scipy librosa pillow pytest ruff- - name: Lint (pyflakes rules, bugbear, simplify)+ - name: Lint every script (pyflakes rules, bugbear, simplify)working-directory: .claude/skills/video-clone/scripts- run: ruff check perception score optimize tests fingerprint.py motion_score.py --select F,E9,B,UP,SIM --ignore UP006,UP035,SIM108,B905,UP038+ run: ruff check . --select F,E9,B,UP,SIM --ignore UP006,UP035,SIM108,B905,UP038- run: python -m pytest .claude/skills/video-clone/scripts/tests -q++ harness:+ name: Harness (rules + hooks)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '22.18'+ - run: sudo apt-get update && sudo apt-get install -y ffmpeg+ - name: Rules in step (CLAUDE.md ↔ AGENTS.md ↔ rules.mts ↔ policies ↔ docs/HARNESS.md)+ run: node --disable-warning=ExperimentalWarning .claude/harness/sync-rules.mts --check+ - name: Hook tests (shell parsing, policies, render detection, hooks end to end)+ run: node --disable-warning=ExperimentalWarning --test ".claude/harness/test/*.test.mts"diff --git a/.gitignore b/.gitignoreindex 2e15ef2..035532b 100644--- a/.gitignore+++ b/.gitignore@@ -14,6 +14,7 @@ secrets.json.env.*.claude/scheduled_tasks.lock.claude/settings.local.json+.claude/harness/audit.jsonl# --- build output & dependencies ---node_modules/diff --git a/AGENTS.md b/AGENTS.mdindex 62fa465..2e560cc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,13 +1,37 @@-# AGENTS.md(Codex 讀這份;Claude Code 讀 CLAUDE.md,兩份規則相同)+# AGENTS.md(Codex 讀這份;Claude Code 讀 CLAUDE.md)這是「風格克隆影片工作室」:使用者給參考影片+需求 → 拆解風格 → 選製作技能 → 前製企劃(與使用者討論到核准)→ 生成 → 依回饋修改。+## 入口(Codex 沒有 Skill 工具,直接讀這些檔案照做)- 流程與規則:`.claude/skills/video-clone/SKILL.md`- 檔案格式(必須照寫):`.claude/skills/video-clone/CONTRACT.md`- 風格對應表:`.claude/skills/video-clone/styles/*.md`-- 各製作技能的說明:`.claude/skills/<engine>/SKILL.md`(例如 painted-animation、hyperframes)。Codex 沒有 Skill 工具,直接讀這些檔案照做。+- 各製作技能的說明:`.claude/skills/<engine>/SKILL.md`(例如 painted-animation、hyperframes)。- 分析:`python .claude/skills/video-clone/scripts/analyze.py <檔案或網址> --out <專案>/analysis`- 授權安全素材:`python .claude/skills/video-clone/scripts/fetch_assets.py search|get …`-規則:目前只做 2D(3D 暫停),3D 參考片用 2D 重現並明講;不生成真人實拍或真實人物;使用者自己擁有的角色(提供設計圖)可直接用,其他角色與畫面原創也可直接使用;歌詞只用使用者提供的檔案,不自行寫出;參考片只學手法不抄素材;-每次渲染後打開影格檢查,修到好才輸出。FFmpeg 找不到時看環境變數 `FFMPEG_DIR`。+下面三段從 CLAUDE.md 同步,不要直接改這裡。Codex 不會執行 Claude Code 的 hooks:docs/HARNESS.md 表裡 strongest layer 是 hook 的規則,在 Codex 底下只靠你自己遵守,加上 app 的審查關卡;渲染後請自己跑 `node .claude/harness/look.mts <影片>` 再看圖。++<!-- harness:shared — 這段是唯一來源,AGENTS.md 有同一份。改完跑 `node .claude/harness/sync-rules.mts --write`;CI 會檢查兩份一致,以及每條規則由誰執行(docs/HARNESS.md) -->+## 規則+- `2d-only` 媒材:目前只做 2D(3D 賽道暫停,blender-product-film 保留但不選用)。3D 參考片用 2D 重現並明講;不生成真人實拍影像或真實人物。+- `assets` 角色:使用者自己擁有的角色(提供設計圖)可直接用;或是我們根據此使用者所述自行去抓取的腳色可以直接使用;素材可以自己上網找(記來源與授權,不明的要標示);歌詞只用使用者提供的文字或 LRC;參考片只學手法不抄素材;使用者自己的產品照片可以用來重建產品。+- `compare-gate` 企劃逐鏡對照參考片(ref_shot + camera),完成後用 compare.py 並排比較、每鏡評分 ≥ 4 才交件。+- `look-after-render` 每次渲染後抽影格用 Read 看,有問題修完再出片。+- `secrets` API 金鑰只放 `~/.reelmimic/secrets.json`,由使用者自己填;不要寫入它,也不要把內容印出來(要確認有沒有設定就用 `test -f`)。+- `projects-private` `projects/` 是使用者的參考片、素材與成片,不進版本控制(不要 `git add -f`)。+- `one-server` 不要在真的 `projects/` 上再開第二個 server(啟動時會把跑到一半的工作標成 interrupted);要套用 server 修改就跑 `bash app/restart.sh`,測試把 `REELMIMIC_PROJECTS` 指到別的資料夾。++## 工具+- 需要的程式與安裝方式見 README(`npm run doctor` 會逐項檢查):Node 22.18+、Python 3.10+(requirements.txt)、FFmpeg、Chrome、Claude Code 或 Codex CLI。+- 找不到 FFmpeg 時看環境變數 `FFMPEG_DIR`;Chrome 看 `CHROME_PATH`;Blender 看 `BLENDER`;API 金鑰在 `~/.reelmimic/secrets.json`(伺服器啟動時載入)。+- yt-dlp:`python -m yt_dlp`;截圖一律用 `.claude/skills/video-clone/scripts/hf_frames.py`(HyperFrames 專案)或引擎自己的 render 指令。+- 背景渲染完的片:`node .claude/harness/look.mts <影片>` 產生縮圖總覽並掃黑畫面/定格。++## 資料夾+- `app/` — ReelMimic 網站(server + React 前端)+- `projects/<代號>/` — 每支影片一個專案(`analysis/`、`plan.json`、`build/`、`out/video.mp4`);不進版本控制+- `.claude/skills/` — skills:`video-clone` 是核心(流程、合約、風格表、工具),其他是製作引擎+- `.claude/harness/` — Claude Code hooks 與規則檢查(說明見 `docs/HARNESS.md`)+- `docs/` — 架構與擴充說明+<!-- /harness:shared -->diff --git a/CLAUDE.md b/CLAUDE.mdindex 90f21da..0dcfa02 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -6,19 +6,26 @@- **一律先載入 `/video-clone`**(`.claude/skills/video-clone/SKILL.md`),照它的流程走:拆解 → 選風格 → 交給製作 skill → 分鏡 → 製作 → 逐格審查 → 輸出 → 依回饋修改。- 風格對應表在 `.claude/skills/video-clone/styles/`,一種風格一個檔;新增風格就加一個檔(範本 `_TEMPLATE.md`)。+<!-- harness:shared — 這段是唯一來源,AGENTS.md 有同一份。改完跑 `node .claude/harness/sync-rules.mts --write`;CI 會檢查兩份一致,以及每條規則由誰執行(docs/HARNESS.md) -->## 規則-- 媒材:目前只做 2D(3D 賽道暫停,blender-product-film 保留但不選用)。3D 參考片用 2D 重現並明講;不生成真人實拍影像或真實人物。-- 角色:使用者自己擁有的角色(提供設計圖)可直接用;或是我們根據此使用者所述自行去抓取的腳色可以直接使用;素材可以自己上網找(記來源與授權,不明的要標示);歌詞只用使用者提供的文字或 LRC;參考片只學手法不抄素材;使用者自己的產品照片可以用來重建產品。-- 企劃逐鏡對照參考片(ref_shot + camera),完成後用 compare.py 並排比較、每鏡評分 ≥ 4 才交件。-- 每次渲染後抽影格用 Read 看,有問題修完再出片。+- `2d-only` 媒材:目前只做 2D(3D 賽道暫停,blender-product-film 保留但不選用)。3D 參考片用 2D 重現並明講;不生成真人實拍影像或真實人物。+- `assets` 角色:使用者自己擁有的角色(提供設計圖)可直接用;或是我們根據此使用者所述自行去抓取的腳色可以直接使用;素材可以自己上網找(記來源與授權,不明的要標示);歌詞只用使用者提供的文字或 LRC;參考片只學手法不抄素材;使用者自己的產品照片可以用來重建產品。+- `compare-gate` 企劃逐鏡對照參考片(ref_shot + camera),完成後用 compare.py 並排比較、每鏡評分 ≥ 4 才交件。+- `look-after-render` 每次渲染後抽影格用 Read 看,有問題修完再出片。+- `secrets` API 金鑰只放 `~/.reelmimic/secrets.json`,由使用者自己填;不要寫入它,也不要把內容印出來(要確認有沒有設定就用 `test -f`)。+- `projects-private` `projects/` 是使用者的參考片、素材與成片,不進版本控制(不要 `git add -f`)。+- `one-server` 不要在真的 `projects/` 上再開第二個 server(啟動時會把跑到一半的工作標成 interrupted);要套用 server 修改就跑 `bash app/restart.sh`,測試把 `REELMIMIC_PROJECTS` 指到別的資料夾。## 工具- 需要的程式與安裝方式見 README(`npm run doctor` 會逐項檢查):Node 22.18+、Python 3.10+(requirements.txt)、FFmpeg、Chrome、Claude Code 或 Codex CLI。- 找不到 FFmpeg 時看環境變數 `FFMPEG_DIR`;Chrome 看 `CHROME_PATH`;Blender 看 `BLENDER`;API 金鑰在 `~/.reelmimic/secrets.json`(伺服器啟動時載入)。- yt-dlp:`python -m yt_dlp`;截圖一律用 `.claude/skills/video-clone/scripts/hf_frames.py`(HyperFrames 專案)或引擎自己的 render 指令。+- 背景渲染完的片:`node .claude/harness/look.mts <影片>` 產生縮圖總覽並掃黑畫面/定格。## 資料夾- `app/` — ReelMimic 網站(server + React 前端)- `projects/<代號>/` — 每支影片一個專案(`analysis/`、`plan.json`、`build/`、`out/video.mp4`);不進版本控制- `.claude/skills/` — skills:`video-clone` 是核心(流程、合約、風格表、工具),其他是製作引擎+- `.claude/harness/` — Claude Code hooks 與規則檢查(說明見 `docs/HARNESS.md`)- `docs/` — 架構與擴充說明+<!-- /harness:shared -->diff --git a/app/server/agents/index.ts b/app/server/agents/index.tsindex b700c12..f3c321d 100644--- a/app/server/agents/index.ts+++ b/app/server/agents/index.ts@@ -32,6 +32,7 @@ export interface AgentRun {sessionId?: string | null;onEvent?: (e: AgentEvent) => void;signal?: AbortSignal;+ env?: Record<string, string>; // extra environment for the agent and everything it starts (its hooks read REELMIMIC_JOB_DIR)}export interface AgentResult { sessionId?: string | null; text: string; ok: boolean; code: number | null; stderr: string; lastError: string }// Turn state while the CLI streams: filled in by the parsers, returned when the process closes@@ -120,7 +121,7 @@ export function noteDropped(st: TurnState, drop: DropTrack, emit: Emit): void {if (st.text || drop.n === 0 || st.lastError) return;emit({ type: 'error', text: `dropped ${drop.n} non-JSON stdout line(s), first 200 chars: ${drop.sample}` });}-export function runAgent({ kind, cwd, prompt, sessionId, onEvent = () => {}, signal }: AgentRun): Promise<AgentResult> {+export function runAgent({ kind, cwd, prompt, sessionId, onEvent = () => {}, signal, env = {} }: AgentRun): Promise<AgentResult> {return new Promise((resolve) => {const st: TurnState = { sessionId, text: '', ok: false, cost: null, lastError: '' };const emit: Emit = (e) => { if (e.type === 'error') st.lastError = e.text; onEvent(e); }; // keep the last error for the job's error card@@ -130,7 +131,7 @@ export function runAgent({ kind, cwd, prompt, sessionId, onEvent = () => {}, sigconst args = isClaude ? claudeArgs(sessionId) : codexArgs(sessionId, cwd);// Windows: npm shims (claude.cmd) need a shell; args are fixed literals, the prompt goes through stdin.// 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' } });+ const child = spawn(cmd, args, { cwd, shell: IS_WIN, ...treeOpts, env: { ...process.env, ...env, HYPERFRAMES_NO_TELEMETRY: '1', DO_NOT_TRACK: '1' } });// the signal lives as long as the whole flow: drop the listener when this turn ends, so finished children aren't killed (or kept) laterconst onAbort = () => killTree(child);if (signal) { if (signal.aborted) killTree(child); else signal.addEventListener('abort', onAbort, { once: true }); }diff --git a/app/server/pipeline.test.ts b/app/server/pipeline.test.tsindex 32799cd..271bc64 100644--- a/app/server/pipeline.test.ts+++ b/app/server/pipeline.test.ts@@ -32,6 +32,7 @@ interface Scenario {const pending = new Map<string, { files: [string, unknown][]; always: boolean }>(); // per project: the good files a format fix writeslet S: Scenario;let calls: string[] = [];+let envs: Record<string, string>[] = []; // what each agent was started with (the harness hooks read it)const count: Record<string, number> = {};const bump = (k: string) => (count[k] = (count[k] || 0) + 1);@@ -83,8 +84,9 @@ 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, signal }: AgentRun) {+async function fakeAgent({ cwd, prompt, onEvent, signal, env = {} }: AgentRun) {const dir = resolve(cwd, prompt.match(/專案資料夾:(\S+?)[(。]/)![1]);+ envs.push(env);if (/## 修正檔案格式/.test(prompt)) {calls.push('fix_format');const p = pending.get(dir); pending.delete(dir);@@ -135,7 +137,7 @@ const base = (o: Partial<Scenario> = {}): Scenario => ({chars: ['hero'], chunks: [{ id: 'C1', shots: ['S1'] }, { id: 'C2', shots: ['S2'] }],castPass: () => true, shotPass: () => true, critique: () => ({}), ...o,});-beforeEach(() => { calls = []; for (const k of Object.keys(count)) delete count[k]; });+beforeEach(() => { calls = []; envs = []; for (const k of Object.keys(count)) delete count[k]; });describe('pre-production', () => {test('retrying a failed style step runs style → plan → characters → plan frames, then waits for approval', async () => {@@ -164,6 +166,9 @@ describe('production', () => {assert.deepEqual(Object.values(j.pipeline.chunks!).map((c) => c.state), ['passed', 'passed']);assert.equal(j.pipeline.cast?.pass, true);assert.ok(j.approvedAt);+ // every agent knows its job folder and its own name, so the hooks can log into this project's logs/harness.jsonl+ assert.ok(envs.length >= calls.length && envs.every((e) => e.REELMIMIC_JOB_DIR === J.dirOf(id) && e.REELMIMIC_AGENT));+ assert.ok(new Set(envs.map((e) => e.REELMIMIC_AGENT)).size >= 4, 'each agent by its own name (director, builders, reviewers)');});test('failed reviews are fixed and re-reviewed: cast round 2, shot round 2, one revise', async () => {diff --git a/app/server/turn.ts b/app/server/turn.tsindex 026d6a6..883d651 100644--- a/app/server/turn.ts+++ b/app/server/turn.ts@@ -57,7 +57,8 @@ export async function turn<P extends Phase>(id: string, phase: P, vars: StepVarslog(id, { type: 'turn', state: 'start', phase, who: label });let res: AgentResult;try {- res = await runAgent({ kind: j.agent, cwd: ROOT, prompt, sessionId: resume, signal,+ // the job's folder and agent name reach the harness hooks (.claude/harness), which log their decisions to logs/harness.jsonl+ res = await runAgent({ kind: j.agent, cwd: ROOT, prompt, sessionId: resume, signal, env: { REELMIMIC_JOB_DIR: d, REELMIMIC_AGENT: label },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 });diff --git a/docs/HARNESS.md b/docs/HARNESS.mdnew file mode 100644index 0000000..552aca8--- /dev/null+++ b/docs/HARNESS.md@@ -0,0 +1,167 @@+# Harness++Most of ReelMimic's work is done by agents (Claude Code or Codex). "Harness" here means everything around them+that makes that work checkable instead of trusted: the rules they read, the hooks that stop or redirect a tool call,+the gates every production job passes, CI, and the logs that show afterwards what happened.++The design rule: **a rule that only lives in a prompt is a wish.** Every project rule is listed with the strongest thing that+enforces it. The list is generated from code and checked in CI, so a rule nobody enforces shows up as one.++```+ agent reads agent acts after the fact+ ┌──────────────────────┐ ┌──────────────────────────────────────────────┐ ┌───────────────────────┐+ │ CLAUDE.md / AGENTS.md│ │ PreToolUse policy.mts deny / ask + reason │ │ logs/events.jsonl │+ │ (one shared block, │──▶│ PostToolUse render → contact sheet, scan │──▶│ timeline.py │+ │ rule ids) │ │ Stop rendered but never looked → back │ │ .claude/harness/ │+ │ skills, CONTRACT.md │ │ app gates contract.ts, review.ts loops │ │ audit.jsonl │+ └──────────────────────┘ └──────────────────────────────────────────────┘ └───────────────────────┘+ ▲ ▲+ └──────── CI: sync-rules --check, harness tests, typecheck, lint, app + perception tests ────────┘+```++## Rules and who enforces them++Generated from [`.claude/harness/rules.mts`](../.claude/harness/rules.mts) by `node .claude/harness/sync-rules.mts --write`. CI fails when it is stale,+when a rule in CLAUDE.md has no entry, when a file is missing, or when an anchor (the policy id, the prompt line, the+function) is no longer in the file it points to.++<!-- harness:table — generated, do not edit by hand -->+| rule | strongest layer | enforced by |+|---|---|---|+| `2d-only` | ⚠️ prompt only | **prompt** [SKILL.md](../.claude/skills/video-clone/SKILL.md) — style router filters by medium; 3D styles sit in styles/_disabled/ |+| `assets` | tool | **tool** [fetch_assets.py](../.claude/skills/video-clone/scripts/fetch_assets.py) — only reuse-licensed sources; every download is recorded with its licence<br>**prompt** [SKILL.md](../.claude/skills/video-clone/SKILL.md) — characters, lyrics and reference footage rules |+| `compare-gate` | runtime | **runtime** [prompts.ts](../app/server/prompts.ts) — the final critic scores every shot against the reference; must-fix items go back to the builders<br>**runtime** [review.ts](../app/server/review.ts) — review → fix loop with a fresh reviewer each round, up to the quality mode’s limit<br>**tool** [compare.py](../.claude/skills/video-clone/scripts/compare.py) — side-by-side reference vs film, per shot |+| `look-after-render` | hook | **hook** [post-tool-use.mts](../.claude/harness/hooks/post-tool-use.mts) — after a film render: contact sheet + black/frozen scan handed to the agent<br>**hook** [stop.mts](../.claude/harness/hooks/stop.mts) — an agent that rendered and never read an image is sent back once<br>**runtime** [prompts.ts](../app/server/prompts.ts) — reviewers that did not build the shot judge it from consecutive frames, with before/after crops as evidence |+| `secrets` | hook | **hook** [policy.mts](../.claude/harness/policy.mts) — writes to any secrets.json are denied (Write/Edit, redirects, cp/mv/sed/…)<br>**hook** [policy.mts](../.claude/harness/policy.mts) — reading the real file asks the user first<br>**git** [.gitignore](../.gitignore) — never committed |+| `projects-private` | hook | **hook** [policy.mts](../.claude/harness/policy.mts) — `git add` of anything under projects/ (or -f over it) is denied<br>**git** [.gitignore](../.gitignore) — ignored, so only a forced add could stage it |+| `one-server` | hook | **hook** [policy.mts](../.claude/harness/policy.mts) — starting a server on the real projects/ while one answers /api/health is denied<br>**runtime** [restart.sh](../app/restart.sh) — the sanctioned restart refuses while agents are working<br>**ci** [jobs.test.ts](../app/server/jobs.test.ts) — tests run against a throwaway projects dir |++- **hook** — Claude Code hook: every tool call of every Claude Code session in the repo, the app’s production agents included+- **runtime** — the app pipeline: gates every production job, Claude Code or Codex+- **ci** — GitHub Actions on every push and pull request+- **tool** — a script the workflow runs, whose output is the evidence+- **git** — repository configuration+- **prompt** — instructions only: followed when read, nothing checks it+<!-- /harness:table -->++## Hooks (`.claude/harness/hooks/`, wired in `.claude/settings.json`)++They run on every tool call of every Claude Code session in the repo. That includes the app's production agents: the+app starts each one at the repo root (`turn.ts`, `cwd: ROOT`), where `.claude/settings.json` is loaded. The app also tells+each agent its job folder and its name (`REELMIMIC_JOB_DIR`, `REELMIMIC_AGENT`). Every hook decision then lands in+that project's `logs/harness.jsonl` too, and `timeline.py` prints it per job:++```+harness (hooks):+ render: contact sheet + scan 3 builder-C1×2, director×1+ stop: sent back to look at a render 1 shot-qa-S4×1+```++Hooks don't change where an agent's commands run: the `cwd` in each event follows the agent's own `cd` (checked live).+So `cd .claude` followed by `git add -f ../projects/x` is still resolved to `projects/` and denied.++### Cost: the fast path++Every tool call starts a hook process before it runs (PreToolUse) and after (PostToolUse), and a production job makes+870–2,330 tool calls (19 real jobs). So start-up time is the budget. The only entry is [`hooks/dispatch.mjs`](../.claude/harness/hooks/dispatch.mjs). It is+plain JS: loading Node's TypeScript stripper alone costs ≈ 22 ms. It answers what it can on a **fast path**+([`hooks/fast.mjs`](../.claude/harness/hooks/fast.mjs), no imports beyond Node built-ins). Only the rest loads the TypeScript handlers, with+Node's compile cache on.++The fast-path filters are a **conservative superset**: each tests for a token every matching case must contain+(`secrets.json`, `git`, `index.ts`, `render`, …) after quotes and backslashes are dropped. So `g''it` or `"secrets.json"` cannot slip past.+[`test/fast.test.mts`](../.claude/harness/test/fast.test.mts) checks it as a property: on a tricky-spelling corpus, and, where production logs exist, on every+shell command real agents ran. For each command, *a policy acts or a render is found* ⇒ *the fast path lets it through*.+On 13,211 production commands: no unsafe skip, and the fast path is taken by **99.4 %** of PreToolUse and **80.5 %**+of PostToolUse shell calls. (The rest are mostly the builders' own `render.mjs --sheet` checks, which do need the handler.)++Measured through the real `bash -c` command line, median of 21 runs, Windows:++| hook call | before | after |+|---|---|---|+| fast path (Read, `ls`, …: almost every call) | 108–124 ms | **63–66 ms** |+| handler path (`git …`, a render) | 109–124 ms | 77–88 ms |+| floor: `bash -c "node -e 0"` | 57 ms | |++The fast path is now ≈ 7 ms above the cost of starting Node at all.++**PreToolUse → [`policy.mts`](../.claude/harness/policy.mts).** Shell commands are parsed first ([`lib/shell.mts`](../.claude/harness/lib/shell.mts)):+split into the simple commands that will actually run, with `cd`, `git -C`, `export`, `K=V` prefixes, `bash -c '…'`,+`$( )` and launchers (`env`, `nohup`, `sudo`) followed. Here-document bodies are read as stdin data, not commands. An unquoted+body's `$( )` still runs, so it is still checked. This matters because a regex over the raw string misses `cd app && npm start`+or `echo $(cat ~/.reelmimic/secrets.json)`.++| policy | stops | the allowed way (told to the agent) |+|---|---|---|+| `secrets-write` | Write/Edit of any `secrets.json`; redirects into it; any other command that names it (`cp`, `mv`, `sed -i`, `python -c "…open(…secrets.json,'w')"`) | tell the user which key to add; `test -f` to check |+| `secrets-read` | asks before reading the real file (Read, `cat`, `Get-Content`, …); a search for the *name* (`grep -rn secrets.json app/`) passes | — |+| `git-add-projects` | `git add` / `git stage` of a path under `projects/` (except `.gitkeep`), or `-f` over a folder that contains it | stage changed code by path |+| `second-server` | starting `app/server/index.ts` (directly, `npm start`/`npm run server`, `start.sh`/`start.bat`) on the real `projects/` while a server answers `/api/health` on 4318 or `$PORT` | `bash app/restart.sh` (refuses while agents work), or a scratch `REELMIMIC_PROJECTS` |++When more than one policy matches, deny beats ask. Every reason is prefixed `[harness:<policy>]` and names its rule.++**PostToolUse: render feedback.** [`render.mts`](../.claude/harness/render.mts) tells a *film* render (`render.mjs --encode|--clip`, `hyperframes render`,+`remotion render`, ffmpeg writing `out/*.mp4`) apart from *review images* (`render.mjs --sheet|--strip|--stills`, `hf_frames.py`).+After a film render, the hook finds the output file and checks that **this call** wrote it. The dispatcher records the+start of every render-like command on PreToolUse, keyed by `tool_use_id` (present in every event, checked live).+PostToolUse only accepts a file written after that. A failed re-render 20 s after a good one leaves a file that any+time window would call fresh; this way it is reported as "wrote no new video during this call". When there is no start+time, a 3-minute window is the fallback. It then builds a 3×3 contact sheet (one input seek per frame,+in parallel, cached by size + mtime) and scans the film once at 320 px for black (≥ 0.4 s) and frozen (≥ 2.5 s) picture.+The sheet path, frame times and any findings are handed back to the agent as context. Black that only touches the+last frame is reported as a likely end fade, not a defect. Renders started in the background are noted, with+the command to check them by hand: `node .claude/harness/look.mts <video>`.++**Stop: the gate.** Every render is remembered per session, one file per item so that parallel tool calls never race.+Reading an image clears it: any image clears a film, and only that file (or folder) clears review images. If anything is+left when the agent tries to finish, it is sent back once with the list. `stop_hook_active` lets the second stop+through, so a render that cannot be checked never traps the agent in a loop. Items older than 6 h are forgotten.++**Failure policy: fail open.** Every handler runs through `respond()` in [`lib/hook.mts`](../.claude/harness/lib/hook.mts), which catches any error,+writes it to the audit log and returns no decision; the dispatcher always exits 0. A bug in a guardrail must not stop production. Decisions are+returned as JSON on stdout, not as exit code 2, so the reason reaches the agent as written.++**Audit.** Every deny, ask, injected context, block and crash is one line in `.claude/harness/audit.jsonl` (gitignored).+`REELMIMIC_HARNESS_AUDIT` and `REELMIMIC_HARNESS_STATE` move the log and the session state, which the tests use.+`REELMIMIC_HARNESS_DEBUG=1` also logs every event a handler receives (how `tool_use_id` and `cwd` were checked).++## One rule set, two agents++Claude Code reads CLAUDE.md and Codex reads AGENTS.md. The rules, tools and folders sections exist once, in CLAUDE.md+between `harness:shared` markers, and AGENTS.md carries a copy (`sync-rules.mts --write` makes it, `--check` fails CI on+any difference). Each rule line starts with its id (`` `secrets` ``), which ties it to its row in the table above.+Codex does not run Claude Code hooks. For Codex, the rules whose strongest layer is `hook` are backed only by the app's gates,+and AGENTS.md says so.++## CI (`.github/workflows/ci.yml`)++| job | checks |+|---|---|+| App | typecheck (app and harness), eslint, server tests, build on Node 22.18 and 24 |+| Perception | ruff over all of `video-clone/scripts`, the perception / score / optimizer tests |+| Harness | `sync-rules.mts --check`, then the harness tests: shell parsing, every policy (with a fake server on a free port for `second-server`), render classification and freshness, the fast-path superset property, and the hooks end to end through `dispatch.mjs` as Claude Code runs them: JSON on stdin, a real ffmpeg-made film, pre → post by `tool_use_id`, the Stop gate before and after a Read |+| App | also: every production agent is started with its job folder and name (`pipeline.test.ts`) |++## Adding a rule++1. Add a line to the rules list in CLAUDE.md: `` - `my-rule` … ``.+2. Add `'my-rule': [...]` to `rules.mts` with where it is enforced. If nothing enforces it yet, say so (`layer: 'prompt'`):+ the table will show it as ⚠️ prompt only.+3. If a tool call can be checked before it runs, add a policy to `policy.mts` with `rule: 'my-rule'` and a test in+ `test/policy.test.mts`, then list it in `rules.mts` as `{ layer: 'hook', at: '.claude/harness/policy.mts#<policy id>' }`.+4. `node .claude/harness/sync-rules.mts --write`.++## Limits++- Codex agents run no Claude Code hooks. For a Codex job, the runtime gates are what is left.+- The production timings in ARCHITECTURE.md (fast 79 min, fine 222 min) were measured before the hooks. The start-up+ cost per call is measured above. The Stop gate's extra turns and the contact sheets' effect on review quality show up+ in `logs/harness.jsonl` and `timeline.py` on the next real runs. They have not been measured yet.+- The hooks catch honest mistakes by an agent working in this repo. They are not a sandbox. Code that builds a path at+ runtime (`open(os.path.expanduser('~') + …)`) is invisible to a command parser.+- `second-server` can only see servers on the ports it probes (4318 and `$PORT`). A server on some other port with the real+ `projects/` is not detected.+- The black / frozen scan finds what a machine can see. Whether a hold is intended, or a pose reads, is still the reviewer's call.+ Films longer than 5 min skip the scan.+- The Stop gate checks that an image was read, not that it was understood. The judgement stays with the reviewers+ in the app pipeline (`review.ts`, `final.ts`).