Skip to content

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.

Harness: address review on #133

許元豪a0c3068f9148
diff --git a/.claude/harness/hooks/fast.mjs b/.claude/harness/hooks/fast.mjs
index f615866..ea97f04 100644
--- a/.claude/harness/hooks/fast.mjs
+++ b/.claude/harness/hooks/fast.mjs
@@ -7,17 +7,82 @@
// 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';
+import { homedir, tmpdir } from 'node:os';
+import { join, resolve } 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, '_'));
+/** Where the API keys can be, as app/server/env.ts looks for them: the env override, then ~/.reelmimic, then the
+ * pre-rename ~/.clone-studio. Absolute, forward slashes. Shared with policy.mts. */
+export const secretFiles = (/** @type {Record<string, string | undefined>} */ env = process.env) =>
+ [env.REELMIMIC_SECRETS, env.CLONE_STUDIO_SECRETS, join(homedir(), '.reelmimic', 'secrets.json'), join(homedir(), '.clone-studio', 'secrets.json')]
+ .filter((p) => !!p).map((p) => resolve(String(p)).replace(/\\/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;
+// secrets-write/read: the file name, its folders, a home-relative path · git-add-projects: git ·
+// second-server: the entry file, npm/pnpm/yarn, start scripts
+// (`Program Files/Git/` is a folder, never the program the git policy looks at.)
+const PRE_SHELL = /secrets|\.reelmimic|\.clone-studio|~|\bgit\b(?![\\/])|index\.ts|\b(?:npm|pnpm|yarn)\b|start\.(?:sh|bat|cmd)/i;
+/** `$PATH`, `$PYTHONPATH`, `$PATHEXT`, …: search lists, not a path. Neither side expands them (lib/shell.mts expandVars). */
+export const LIST_VAR = /PATH(?:EXT)?$/i;
+// Folder-walking commands (policy.mts TREE, recursive readers, find): the only ones a bare `/` matters to.
+const WALKS = /(?:^|[;&|(\n])\s*(?:sudo\s+)?(?:rm|rmdir|mv|cp|rsync|scp|tar|zip|7z|chmod|chown|shred|del|erase|rd|remove-item|ri|move-item|mi|copy-item|cpi|robocopy|xcopy|compress-archive|grep|egrep|fgrep|rg|ag|findstr|find|xargs)\b/im;
+
+// The secrets policies also act on a folder above the keys (`rm -rf $HOME`, `grep -r . /c/Users/me`, `cd ../.. && cp
+// -r . /tmp`). A command can only reach such a folder through an absolute path, a bare `cd` (home), or by climbing
+// with `..` from where it runs. Each is checked on the command with variables expanded as the parser expands them.
+const norm = (/** @type {string} */ p) => { const s = p.replace(/\\/g, '/').replace(/\/+$/, ''); return process.platform === 'win32' ? s.toLowerCase() : s; };
+/** True when `dir` is the keys file or a folder they sit under. */
+export const aboveSecrets = (/** @type {string} */ dir) => { const d = norm(dir); return secretFiles().some((f) => { const n = norm(f); return n === d || n.startsWith(`${d}/`); }); };
+const expand = (/** @type {string} */ s) => s.replace(/\$\{([A-Za-z_]\w*)\}|\$env:([A-Za-z_]\w*)|\$([A-Za-z_]\w*)|%([A-Za-z_]\w*)%/gi,
+ (m, a, b, c, d) => { const k = a ?? b ?? c ?? d; return LIST_VAR.test(k) ? m : process.env[k] ?? (/^(?:HOME|USERPROFILE)$/i.test(k) ? homedir() : m); });
+// `\(` or `\|` is an escape, not the drive root; `\Users\me` (quoted) is a path.
+const isAbs = (/** @type {string} */ t) => /^(?:[A-Za-z]:[\\/]|\/|\\(?=[\w.]))/.test(t);
+const climbsAbove = (/** @type {string} */ cmd, /** @type {string} */ cwd) => {
+ const q = expand(String(cmd).replace(/['"`]/g, ''));
+ if (/(?:^|[;&|(\n])\s*(?:cd|pushd|set-location|sl)\s*(?:$|[;&|)\n])/im.test(q)) return true; // bare cd: home
+ // Every directory the command can be in starts from the event's cwd or an absolute `cd` target, and moves from there
+ // by descending or by `..`. So anything it reaches by climbing lies under one of those, climbed at most k levels
+ // (k = every `..` in the command). If none of those is above the keys, no relative path is. A command that opens
+ // with `cd /abs` never uses the event's cwd (the parser applies a cd in order, and a subshell restores the cwd it
+ // was opened in, which is already after it).
+ const k = (q.match(/\.\.(?=[\\/]|$|[\s;&|)])/g) ?? []).length;
+ const up = (/** @type {string} */ p) => aboveSecrets(resolve(gitBash(p), ...Array(k).fill('..')));
+ const lead = /^\s*(?:cd|pushd|set-location|sl)(?:\s+-\S*)*\s+([^\s;&|)]+)\s*[;&|\n]/i.exec(q);
+ if (!(lead && isAbs(lead[1])) && up(cwd || '.')) return true;
+ for (const m of q.matchAll(/(?:^|[\s;&|(])(?:cd|pushd|set-location|sl)(?:\s+-\S*)*\s+([^\s;&|)]+)/gim)) if (isAbs(m[1]) && up(m[1])) return true;
+ const walks = WALKS.test(q);
+ return words(expand(String(cmd))).some(({ w, spaced }) => [w, w.slice(w.indexOf('=') + 1)].some((t) => { // `D=/abs`: its value too
+ if (!isAbs(t)) return false;
+ // A glob, unless it was quoted with spaces (the shell does not glob a quoted word; policy.mts reaches() agrees).
+ if (/[*?[]/.test(t) && !spaced) return aboveSecrets(resolve(gitBash(t.replace(/[^\\/]*[*?[].*$/, '')) || '/')); // its literal folder
+ return (walks || !/^(?:[A-Za-z]:)?[\\/]+$/.test(t)) && aboveSecrets(resolve(gitBash(t))); // `/` alone matters only to a walker
+ }));
+};
+/** Words as lib/shell.mts lex() splits them: quotes group and are dropped, `\` escapes as bash does inside and outside
+ * double quotes, operators separate. `spaced`: the word holds whitespace, so it was quoted. Here-documents are not
+ * told apart from commands: their text is checked too, which only sends more to the handler. */
+const words = (/** @type {string} */ s) => {
+ /** @type {{ w: string, spaced: boolean }[]} */ const out = [];
+ let cur = '', q = '', any = false;
+ const end = () => { if (any) out.push({ w: cur, spaced: /\s/.test(cur) }); cur = ''; any = false; };
+ for (let i = 0; i < s.length; i++) {
+ const c = s[i];
+ if (q === "'") { if (c === "'") q = ''; else cur += c; continue; }
+ if (q === '"') { if (c === '"') q = ''; else if (c === '\\' && '"\\$`'.includes(s[i + 1] ?? '')) cur += s[++i]; else cur += c; continue; }
+ if (c === "'" || c === '"') { q = c; any = true; continue; }
+ if (c === '\\') { if (s[i + 1] !== '\n') cur += s[i + 1] ?? ''; i++; any = true; continue; }
+ if (/[\s;&|()<>`]/.test(c)) { end(); continue; }
+ cur += c; any = true;
+ }
+ end();
+ return out;
+};
+/** Git Bash `/c/Users` → `C:/Users` on Windows, as lib/shell.mts resolvePath does. */
+const gitBash = (/** @type {string} */ p) => (process.platform === 'win32' ? p.replace(/^\/([a-zA-Z])(?=\/|$)/, '$1:') : p);
// render.mts classify(): render.mjs, hyperframes, remotion, hf_frames.py, ffmpeg, `npm run render`
const RENDER = /render|hf_frames|ffmpeg|hyperframes|remotion/i;
@@ -33,7 +98,11 @@ const hasPending = (/** @type {string | undefined} */ session) => {
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 === 'pre') {
+ if (shell) return PRE_SHELL.test(expand(flat(input.command))) || climbsAbove(input.command, e.cwd);
+ if (e.tool_name === 'Grep') { const p = String(input.path ?? ''); return SECRETS.test(p) || /[*?[]/.test(p) || aboveSecrets(resolve(e.cwd || '.', gitBash(p) || '.')); }
+ return 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;
diff --git a/.claude/harness/lib/shell.mts b/.claude/harness/lib/shell.mts
index 603e776..cfa95ec 100644
--- a/.claude/harness/lib/shell.mts
+++ b/.claude/harness/lib/shell.mts
@@ -1,10 +1,12 @@
// 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.
+// `export K=V` and `K=V cmd` set the environment, `$HOME` / `${VAR}` / `$env:VAR` / `%VAR%` expand from it, and
+// `bash -c '…'` / `sh -c` / `env` / `nohup` / `sudo` / `timeout` / `npx` and friends 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';
+import { LIST_VAR } from '../hooks/fast.mjs';
export interface Simple {
argv: string[];
@@ -14,7 +16,14 @@ export interface Simple {
}
type Tok = { k: 'w'; v: string } | { k: 'op'; v: string };
-const WRAPPERS = new Set(['sudo', 'nohup', 'time', 'command', 'exec', 'nice', 'stdbuf']);
+// Launchers that run the rest of the line as the real program, with the options that take a value (`sudo -u user`,
+// not `sudo -n`) and how many positionals they eat first (`timeout 600 node x`: the duration).
+const LAUNCHERS: Record<string, { valued?: string[]; positional?: number }> = {
+ sudo: { valued: ['-u', '-g', '-C', '-D', '-h', '-p', '-r', '-t', '-U', '-T'] }, nohup: {}, time: {}, command: {}, exec: { valued: ['-a'] },
+ nice: { valued: ['-n'] }, stdbuf: { valued: ['-i', '-o', '-e'] }, timeout: { valued: ['-s', '-k', '--signal', '--kill-after'], positional: 1 },
+ npx: { valued: ['-p', '--package'] }, pnpx: { valued: ['-p', '--package'] }, bunx: { valued: ['-p', '--package'] },
+};
+const PM_EXEC = new Set(['exec', 'dlx', 'x']); // `npm exec tsx …`, `pnpm dlx …`, `bun x …`
const SHELLS = /^(?:.*[\\/])?(?:bash|sh|zsh|dash)(?:\.exe)?$/i;
export function lex(src: string): Tok[] {
@@ -106,7 +115,7 @@ export function parse(src: string, cwd: string, env: Record<string, string> = {}
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; }
+ if (pending) { if (pending === '>' || pending === '>>') redirects.push(resolvePath(expandVars(t.v, state.env), state.cwd)); pending = ''; continue; }
words.push(t.v);
}
flush();
@@ -115,14 +124,23 @@ export function parse(src: string, cwd: string, env: Record<string, string> = {}
function expand(words: string[], redirects: string[], state: { cwd: string; env: Record<string, string> }, depth: number): Simple[] {
const local: Record<string, string> = {};
+ // Expanded with the environment as it was before this command: in `HOME=/x cat $HOME/f` the shell reads the old HOME.
+ words = words.map((w) => expandVars(w, state.env));
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`.
+ // Unwrap launchers so the policy sees the real program: `env -i K=V node x`, `nohup node x &`, `sudo -u u cmd`,
+ // `timeout 600 node x`, `npx tsx x`, `pnpm exec tsx x`.
for (;;) {
- const a0 = base(argv[0] ?? '');
+ const a0 = base(argv[0] ?? ''), l = LAUNCHERS[a0];
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; }
+ if (['npm', 'pnpm', 'yarn', 'bun'].includes(a0) && PM_EXEC.has(argv[1] ?? '')) { argv = argv.slice(2); while (argv[0]?.startsWith('-')) argv = argv.slice(argv[0] === '-p' || argv[0] === '--package' ? 2 : 1); continue; }
+ if (l) {
+ argv = argv.slice(1);
+ while (argv[0]?.startsWith('-')) { const o = argv.shift()!; if (o === '--') break; if (l.valued?.includes(o)) argv.shift(); }
+ argv = argv.slice(l.positional ?? 0);
+ continue;
+ }
break;
}
const env = { ...state.env, ...local };
@@ -142,6 +160,19 @@ function expand(words: string[], redirects: string[], state: { cwd: string; env:
return [self];
}
+/** `$HOME`, `${VAR}`, PowerShell `$env:VAR` and cmd `%VAR%`, from the command's own exports, then the hook's
+ * environment (which the agent's shell inherits). Unknown names stay as written, and so do search lists (`$PATH`):
+ * they are never one file, and hooks/fast.mjs skips them the same way. Single quotes would stop bash expanding; the
+ * lexer has dropped them by now, so this expands a little more than bash would — the safe side. */
+export function expandVars(w: string, env: Record<string, string> = {}): string {
+ if (!w.includes('$') && !w.includes('%')) return w;
+ return w.replace(/\$\{([A-Za-z_]\w*)\}|\$env:([A-Za-z_]\w*)|\$([A-Za-z_]\w*)|%([A-Za-z_]\w*)%/gi, (m, a, b, c, d) => {
+ const k = a ?? b ?? c ?? d;
+ if (LIST_VAR.test(k)) return m;
+ return env[k] ?? process.env[k] ?? (/^(?:HOME|USERPROFILE)$/i.test(k) ? homedir() : m);
+ });
+}
+
/** 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();
diff --git a/.claude/harness/lib/video.mts b/.claude/harness/lib/video.mts
index 828858f..d0330af 100644
--- a/.claude/harness/lib/video.mts
+++ b/.claude/harness/lib/video.mts
@@ -31,7 +31,7 @@ export interface Sheet { path: string; times: number[]; cols: number; duration:
* 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 key = createHash('sha1').update(`${file}|${st.size}|${st.mtimeMs}|${n}|${cols}|${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));
diff --git a/.claude/harness/policy.mts b/.claude/harness/policy.mts
index 4298094..a397f0a 100644
--- a/.claude/harness/policy.mts
+++ b/.claude/harness/policy.mts
@@ -2,9 +2,10 @@
// 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 { existsSync, readdirSync } from 'node:fs';
import { request } from 'node:http';
import { homedir } from 'node:os';
+import { secretFiles } from './hooks/fast.mjs';
import { ROOT } from './lib/hook.mts';
import { base, parse, resolvePath, samePath, within, type Simple } from './lib/shell.mts';
@@ -19,23 +20,55 @@ 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.
+// A command reaches the file by naming it, by a glob the shell expands to it (`cat ~/.reelmimic/*`), or, for tools
+// that walk folders (`grep -r`, `rg`, `rm -r`, `cp -r`, `find … -delete`, the Grep tool), by naming a folder above it.
+// `$HOME` and friends are expanded by the parser before any of this looks at a path.
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']);
+const READERS = new Set(['cat', 'type', 'head', 'tail', 'less', 'more', 'bat', 'jq', 'get-content', 'gc', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'findstr', 'select-string', 'sls', 'strings', 'od', 'xxd', 'hexdump', 'base64']);
// Mentioning the file is harmless for these: they cannot write it except through a redirect, which is checked anyway.
+// `find` only while it lists: with -delete / -exec / -ok / -fprint it acts on what it finds.
const INERT = new Set(['echo', 'printf', 'ls', 'dir', 'stat', 'test', '[', 'which', 'git', 'gh', 'find', 'wc', 'file', 'realpath', 'dirname', 'basename']);
+const FIND_ACTS = /^-(?:delete|exec|execdir|ok|okdir|fprint0?|fprintf|fls)$/;
+// These act on whole folders, so naming a folder above the keys reaches them.
+const TREE = new Set(['rm', 'rmdir', 'mv', 'cp', 'rsync', 'scp', 'tar', 'zip', '7z', 'chmod', 'chown', 'shred', 'del', 'erase', 'rd', 'remove-item', 'ri', 'move-item', 'mi', 'copy-item', 'cpi', 'robocopy', 'xcopy', 'compress-archive']);
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 recursiveRead = (p: string, argv: string[]) => p === 'rg' || p === 'ag'
+ || (['grep', 'egrep', 'fgrep'].includes(p) && argv.some((a) => /^-[a-zA-Z]*[rR]/.test(a) || /^--(?:dereference-)?recursive$/.test(a)))
+ || (p === 'findstr' && argv.some((a) => /^[/-]s$/i.test(a)));
+/** find with an action, unless every -name / -iname it filters on rules secrets.json out. */
+const findActs = (argv: string[]) => {
+ if (!argv.some((a) => FIND_ACTS.test(a))) return false;
+ const names = argv.flatMap((a, i) => (a === '-name' || a === '-iname' ? [{ glob: argv[i + 1] ?? '', ci: a === '-iname' }] : []));
+ return !names.length || names.some((n) => globRegex(n.glob, n.ci).test('secrets.json'));
+};
+
+/** The secrets file `arg` reaches, or null. `dirs`: the tool walks folders, so a folder above a known secrets file counts. */
+export function reaches(arg: string, cwd: string, env: Record<string, string | undefined>, dirs: boolean): string | null {
+ if (!arg || /^-[^/\\]*$/.test(arg)) return null; // an option, not a path
+ const p = resolvePath(arg, cwd);
+ // A word with whitespace was quoted (code, a message), and the shell does not glob quoted words.
+ for (const q of /[*?[]/.test(arg) && !/\s/.test(arg) ? expandGlob(p) : [p]) {
+ if (isSecrets(q) && existsSync(q)) return q;
+ if (dirs) { const f = secretFiles(env).find((s) => within(s, q) && existsSync(s)); if (f) return f; }
+ }
+ return null;
+}
+
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);
+ const hit = s.redirects.find((r) => isSecrets(r) || reaches(r, s.cwd, c.env, false));
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}` };
+ const p = base(s.argv[0] ?? ''), acts = p === 'find' && findActs(s.argv);
+ if ((INERT.has(p) && !acts) || READERS.has(p)) continue;
+ const args = s.argv.slice(1);
+ const named = args.some((a) => /secrets\.json/i.test(a) && !/secrets\.example\.json/i.test(a));
+ const f = named ? null : args.map((a) => reaches(a, s.cwd, c.env, acts || TREE.has(p))).find(Boolean);
+ if (named || f) return { decision: 'deny', reason: `\`${s.argv.join(' ').slice(0, 160)}\` reaches ${f ?? 'a secrets.json file'} and could change or copy it (rule \`secrets\`). ${SECRETS_HELP}` };
}
return null;
},
@@ -46,17 +79,52 @@ const secretsRead: Policy = {
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));
+ // The Grep tool searches folders: pointed at or above the keys, `pattern: "."` prints them all.
+ if (c.tool === 'Grep') { const f = reaches(String(c.input.path ?? '') || '.', resolvePath(c.cwd || '.', ROOT), c.env, true); return f ? ask(f) : null; }
if (!SHELL_TOOLS.has(c.tool)) return null;
for (const s of c.commands) {
- if (!READERS.has(base(s.argv[0] ?? ''))) continue;
+ const p = base(s.argv[0] ?? '');
+ if (!READERS.has(p)) 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));
+ const f = s.argv.slice(1).map((a) => reaches(a, s.cwd, c.env, recursiveRead(p, s.argv))).find(Boolean);
if (f) return ask(f);
}
return null;
},
};
+/** A shell glob as a regex over one path segment: `*` and `?` stop at `/`, `[!x]` negates, and as in bash a
+ * pattern that does not start with `.` does not match a dot-file. */
+export function globRegex(g: string, ci = process.platform === 'win32'): RegExp {
+ let r = '';
+ for (let i = 0; i < g.length; i++) {
+ const ch = g[i];
+ if (ch === '*') r += '[^/]*';
+ else if (ch === '?') r += '[^/]';
+ else if (ch === '[' && g.indexOf(']', i + 2) > 0) { const j = g.indexOf(']', i + 2); r += `[${g.slice(i + 1, j).replace(/^!/, '^').replace(/\\/g, '\\\\')}]`; i = j; }
+ else r += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
+ }
+ try { return new RegExp(`^${g.startsWith('.') ? '' : '(?!\\.)'}${r}$`, ci ? 'i' : ''); }
+ catch { return new RegExp(`^${g.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, ci ? 'i' : ''); } // `[z-a]`: bash matches it literally
+}
+
+/** What the shell expands an absolute glob path to, segment by segment. Capped: this runs inside a hook. */
+export function expandGlob(p: string, cap = 500): string[] {
+ const [root, ...segs] = p.split('/');
+ let cur = [root];
+ for (const seg of segs) {
+ if (!seg) continue;
+ if (!/[*?[]/.test(seg)) { cur = cur.map((d) => `${d}/${seg}`); continue; }
+ const re = globRegex(seg), next: string[] = [];
+ for (const d of cur) {
+ let names: string[] = []; try { names = readdirSync(/^[A-Za-z]:$|^$/.test(d) ? `${d}/` : d); } catch {} // `C:` alone is the drive's cwd
+ for (const n of names) if (re.test(n) && next.length < cap) next.push(`${d}/${n}`);
+ }
+ cur = next;
+ }
+ return cur;
+}
+
// --- 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.
diff --git a/.claude/harness/render.mts b/.claude/harness/render.mts
index 76dabcf..ea255f1 100644
--- a/.claude/harness/render.mts
+++ b/.claude/harness/render.mts
@@ -4,7 +4,7 @@
// 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 { 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';
@@ -70,9 +70,11 @@ export function newestVideo(dir: string, f: Freshness = {}): string | null {
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). */
+/** The file this render wrote, if it is there and fresh (a failed render leaves last run's file behind, or nothing).
+ * Only a render that did not say where it writes is looked for: when it did, a missing or stale file means it failed,
+ * and the newest video nearby is some other command's. */
export function freshOutput(r: Render, cwd: string, f: Freshness = {}): string | null {
- if (r.out && existsSync(r.out)) {
+ if (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;
}
diff --git a/.claude/harness/rules.mts b/.claude/harness/rules.mts
index 4eaf6d5..6356ed4 100644
--- a/.claude/harness/rules.mts
+++ b/.claude/harness/rules.mts
@@ -1,7 +1,7 @@
// 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
+// - each `at` exists, and its `#anchor` (when given) still appears in that file outside comments — 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';
@@ -35,8 +35,8 @@ export const ENFORCEMENT: Record<string, Enforcement[]> = {
{ 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: 'hook', at: '.claude/harness/policy.mts#secrets-write', how: 'writes to any secrets.json are denied (Write/Edit, redirects, cp/mv/sed/…, globs and folder-walking tools over it)' },
+ { layer: 'hook', at: '.claude/harness/policy.mts#secrets-read', how: 'reading the real file asks the user first (Read, Grep, cat, globs, grep -r over a folder above it)' },
{ layer: 'git', at: '.gitignore#secrets.json', how: 'never committed' },
],
'projects-private': [
diff --git a/.claude/harness/sync-rules.mts b/.claude/harness/sync-rules.mts
index 0754ce6..bc1f473 100644
--- a/.claude/harness/sync-rules.mts
+++ b/.claude/harness/sync-rules.mts
@@ -26,6 +26,69 @@ function replaceBlock(text: string, [open, close]: readonly [string, string], bo
const a = text.indexOf(open), b = text.indexOf(close);
return text.slice(0, text.indexOf('\n', a) + 1) + body + text.slice(b);
}
+/** `src` with its comments blanked out, strings kept: an anchor must name live code or text, not a comment that still
+ * mentions a function after it is gone. JS/TS: `//`, `/* *\/`, with strings, templates and regex literals skipped
+ * so `'//'` or `/["']/` cannot open a false comment. Python / shell / .gitignore: `#` (shell only at a word start).
+ * Markdown: `<!-- -->`. Newlines are kept, so nothing joins across a removed comment. */
+export function uncommented(src: string, file: string): string {
+ if (/\.md$/i.test(file)) return src.replace(/<!--[\s\S]*?-->/g, '');
+ if (/\.(?:py|sh)$|(?:^|\/)\.gitignore$/i.test(file)) {
+ const py = /\.py$/i.test(file); let out = '', q = '';
+ for (let i = 0; i < src.length; i++) {
+ const c = src[i];
+ if (q) { out += c; if (c === '\\') out += src[++i] ?? ''; else if (src.startsWith(q, i)) { out += q.slice(1); i += q.length - 1; q = ''; } continue; }
+ if (c === '#' && (py || i === 0 || /\s/.test(src[i - 1]))) { while (i < src.length && src[i] !== '\n') i++; out += '\n'; continue; }
+ if ((c === '"' || c === "'") && !/\.gitignore$/.test(file)) { q = py && src.startsWith(c.repeat(3), i) ? c.repeat(3) : c; out += q; i += q.length - 1; continue; }
+ out += c;
+ }
+ return out;
+ }
+ if (!/\.(?:[cm]?[jt]sx?)$/i.test(file)) return src;
+ let out = '';
+ // Code up to the `}` that closes a template's `${` (when `close`), or to the end. `last` is the last significant
+ // character: after an operator or bracket a `/` starts a regex, after a name or `)` it divides.
+ const code = (i: number, close: boolean): number => {
+ let depth = 0, last = '';
+ for (; i < src.length; i++) {
+ const c = src[i], n = src[i + 1];
+ if (close && c === '{') depth++;
+ else if (close && c === '}' && depth-- === 0) { out += c; return i + 1; }
+ if (c === '/' && n === '/') { while (i < src.length && src[i] !== '\n') i++; out += '\n'; continue; }
+ if (c === '/' && n === '*') { const e = src.indexOf('*/', i + 2), end = e < 0 ? src.length : e + 2; out += src.slice(i, end).replace(/[^\n]/g, ''); i = end - 1; continue; }
+ if (c === '`') { out += c; i = template(i + 1) - 1; last = c; continue; }
+ if (c === '"' || c === "'" || (c === '/' && (!last || /[(,=:[!&|?{};+\-*%<>~^]/.test(last)))) {
+ let j = i + 1, cls = false;
+ for (; j < src.length && src[j] !== '\n'; j++) {
+ if (src[j] === '\\') { j++; continue; }
+ if (c === '/' && src[j] === '[') cls = true; else if (cls && src[j] === ']') cls = false;
+ else if (src[j] === c && !cls) break;
+ }
+ out += src.slice(i, j + 1); i = j; last = c; continue;
+ }
+ out += c; if (!/\s/.test(c)) last = c;
+ }
+ return i;
+ };
+ // A template literal from just after its opening backtick; its `${ … }` parts are code (and may hold templates).
+ const template = (i: number): number => {
+ for (; i < src.length; i++) {
+ if (src[i] === '\\') { out += src.slice(i, i + 2); i++; continue; }
+ if (src[i] === '`') { out += '`'; return i + 1; }
+ if (src[i] === '$' && src[i + 1] === '{') { out += '${'; i = code(i + 2, true) - 1; continue; }
+ out += src[i];
+ }
+ return i;
+ };
+ code(0, false);
+ return out;
+}
+
+/** True when `anchor` appears in `file` outside comments; a bare identifier must appear as a whole word. */
+export function anchored(src: string, file: string, anchor: string): boolean {
+ const code = uncommented(src.replace(/\r\n/g, '\n'), file);
+ return /^[A-Za-z_$][\w$]*$/.test(anchor) ? new RegExp(`(?<![\\w$])${anchor.replace(/\$/g, '\\$')}(?![\\w$])`).test(code) : code.includes(anchor);
+}
+
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 {
@@ -55,7 +118,7 @@ export function problems(): string[] {
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 (anchor && !anchored(read(file), file, anchor)) P.push(`\`${id}\`: "${anchor}" no longer appears in ${file} (comments do not count)`);
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) {
diff --git a/.claude/harness/test/fast.test.mts b/.claude/harness/test/fast.test.mts
index d1dd4d8..8335151 100644
--- a/.claude/harness/test/fast.test.mts
+++ b/.claude/harness/test/fast.test.mts
@@ -3,8 +3,9 @@
// 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 { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
import { test } from 'node:test';
import { needsHandler } from '../hooks/fast.mjs';
import { ROOT } from '../lib/hook.mts';
@@ -15,8 +16,13 @@ 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 } });
+// A real keys file in a temp folder, known to both sides the way production knows ~/.reelmimic: through the environment.
+const K = mkdtempSync(join(tmpdir(), 'fast-keys-')).replace(/\\/g, '/'), KP = dirname(K).replace(/\\/g, '/');
+writeFileSync(join(K, 'secrets.json'), '{}');
+process.env.REELMIMIC_SECRETS = `${K}/secrets.json`;
+
async function check(command: string, cwd = ROOT) {
- const acts = !!(await evaluate('Bash', { command }, cwd, {}, up));
+ const acts = !!(await evaluate('Bash', { command }, cwd, process.env, 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}`);
@@ -29,10 +35,24 @@ const TRICKY = [
'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',
+ // reached without naming the file: globs, folders above it, variables, climbing, a bare cd
+ `cat ${K}/*`, `cat ${KP}/fast-keys-*/*`, `grep -r . ${K}`, `rm -rf ${KP}`, `find ${K} -delete`, `cp -r ${K} /tmp/b`,
+ `export D=${K}; cat $D/*`, `D=${KP} && rm -rf $D`, `cd ${K}/sub/.. && grep -r x .`, `cd ${K} && cat *`, `cd /x/y && cd ${K} && rm -rf .`,
+ 'cat $REELMIMIC_SECRETS', 'timeout 600 node app/server/index.ts', 'npx tsx app/server/index.ts',
];
test('tricky spellings never slip past the fast path', async () => {
for (const c of TRICKY) await check(c);
+ for (const c of [`rm -rf ${K}`, `grep -rn x ..`]) await check(c, `${K}/deeper`); // climbing from the event's cwd
+ await check('rm -rf .', K);
+});
+
+test('the Grep tool: the handler sees every call a policy acts on', async () => {
+ for (const [path, cwd] of [[`${K}/secrets.json`, ROOT], [K, ROOT], [KP, ROOT], ['', K], ['..', `${K}/deeper`], [`${ROOT}/app`, ROOT]]) {
+ const input = path ? { pattern: '.', path } : { pattern: '.' };
+ const acts = !!(await evaluate('Grep', input, cwd, process.env, up));
+ assert.equal(needsHandler('pre', { cwd, tool_name: 'Grep', tool_input: input }), acts, `${path} from ${cwd}`);
+ }
});
test('Read / Write: only a secrets.json path leaves the fast path; Stop and Read-after-render only with pending state', () => {
diff --git a/.claude/harness/test/hooks.test.mts b/.claude/harness/test/hooks.test.mts
index 90b5733..760d54c 100644
--- a/.claude/harness/test/hooks.test.mts
+++ b/.claude/harness/test/hooks.test.mts
@@ -9,7 +9,7 @@ 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';
+import { bin, contactSheet } 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') };
@@ -80,6 +80,22 @@ test('post-tool-use + stop: a film render is sheeted, scanned, and gated until l
assert.equal(hook('stop', { session_id: S }), null, 'looked at: free to stop');
});
+test('contact sheets are cached per layout', { skip: !ffmpeg && 'ffmpeg not found' }, async () => {
+ const film = join(TMP, 'proj', 'out', 'video.mp4');
+ if (!existsSync(film)) return; // made by the film test above
+ const a = await contactSheet(film, 9, 3), b = await contactSheet(film, 9, 9), again = await contactSheet(film, 9, 3);
+ assert.notEqual(a.path, b.path, '9 across is not 3 across');
+ assert.equal(again.path, a.path);
+});
+
+test('pre-tool-use: the Grep tool pointed at the keys asks', () => {
+ const keys = mkdtempSync(join(tmpdir(), 'harness-keys-')); writeFileSync(join(keys, 'secrets.json'), '{}');
+ const out = hook('pre-tool-use', { session_id: 'g', cwd: ROOT, tool_name: 'Grep', tool_input: { pattern: '.', path: keys } }, { ...ENV, REELMIMIC_SECRETS: join(keys, 'secrets.json') });
+ assert.equal(out.hookSpecificOutput.permissionDecision, 'ask');
+ assert.match(out.hookSpecificOutput.permissionDecisionReason, /^\[harness:secrets-read\]/);
+ assert.equal(hook('pre-tool-use', { session_id: 'g', cwd: ROOT, tool_name: 'Grep', tool_input: { pattern: 'x', path: join(ROOT, 'app') } }), null);
+});
+
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');
diff --git a/.claude/harness/test/policy.test.mts b/.claude/harness/test/policy.test.mts
index 01d9ae3..850b840 100644
--- a/.claude/harness/test/policy.test.mts
+++ b/.claude/harness/test/policy.test.mts
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import { test } from 'node:test';
import { ROOT } from '../lib/hook.mts';
import { evaluate } from '../policy.mts';
@@ -10,7 +10,7 @@ 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_DIR = mkdtempSync(join(tmpdir(), 'harness-secrets-')).replace(/\\/g, '/'); // as an agent writes it: unquoted `\` is an escape
const SECRETS = join(SECRETS_DIR, 'secrets.json').replace(/\\/g, '/');
writeFileSync(SECRETS, '{"YATING_KEY":"x"}');
@@ -36,6 +36,49 @@ test('secrets: reading the real file asks; naming it does not', async () => {
assert.equal(await evaluate('Edit', { file_path: `${ROOT}/secrets.example.json` }, ROOT, {}, down), null);
});
+// The keys file as app/server/env.ts would find it through REELMIMIC_SECRETS: what folder-walking tools are checked against.
+const KEYED = { REELMIMIC_SECRETS: SECRETS };
+const PARENT = dirname(SECRETS_DIR).replace(/\\/g, '/');
+
+test('secrets: $HOME and variables are expanded before a path is looked at', async () => {
+ assert.equal(await verdict(bash(`export SD=${SECRETS_DIR}; cat $SD/secrets.json`)), 'ask:secrets-read');
+ assert.equal(await verdict(bash(`SD=${SECRETS_DIR}; cat \${SD}/secrets.json`)), 'ask:secrets-read');
+ assert.equal(await verdict(bash(`D=${SECRETS_DIR}; echo '{}' > $D/secrets.json`)), 'deny:secrets-write', 'a redirect target is expanded too');
+});
+
+test('secrets: a glob the shell expands to the file reaches it', async () => {
+ for (const g of [`${SECRETS_DIR}/*`, `${SECRETS_DIR}/s*.json`, `${SECRETS_DIR}/secret?.json`, `${PARENT}/harness-secrets-*/*`])
+ assert.equal(await verdict(bash(`cat ${g}`)), 'ask:secrets-read', g);
+ assert.equal(await verdict(bash(`cp ${SECRETS_DIR}/* /tmp/keys/`)), 'deny:secrets-write');
+ assert.equal(await verdict(bash(`ls ${SECRETS_DIR}/*`)), null, 'listing is not reading');
+ assert.equal(await verdict(bash(`cat ${SECRETS_DIR}/*.txt`)), null, 'a glob that matches nothing of ours');
+ assert.equal(await verdict(bash(`python -c "print([1, 2][0])"`)), null, 'quoted code is not a glob');
+});
+
+test('secrets: folder-walking tools reach the file through any folder above it', async () => {
+ const keyed = (c: string) => verdict(evaluate('Bash', { command: c }, ROOT, KEYED, down));
+ for (const c of [`grep -r . ${SECRETS_DIR}`, `grep -rn KEY ${PARENT}`, `rg sk- ${SECRETS_DIR}`, `cd ${SECRETS_DIR} && grep -R x .`])
+ assert.equal(await keyed(c), 'ask:secrets-read', c);
+ for (const c of [`rm -rf ${SECRETS_DIR}`, `cp -r ${SECRETS_DIR} /tmp/backup`, `tar czf k.tgz ${SECRETS_DIR}`, `find ${SECRETS_DIR} -delete`, `find ${PARENT} -name secrets.json -exec cat {} ;`, `find ${SECRETS_DIR} -iname 'SECRETS.*' -delete`])
+ assert.equal(await keyed(c), 'deny:secrets-write', c);
+ for (const c of [`grep x ${SECRETS_DIR}`, `find ${SECRETS_DIR} -name '*.tmp' -delete`, `find ${SECRETS_DIR} -name secrets.json`, `rm -rf ${SECRETS_DIR}/cache`, 'grep -rn secrets.json app/'])
+ assert.equal(await keyed(c), null, c);
+});
+
+test('secrets: find acts on what it finds once it has -delete / -exec', async () => {
+ assert.equal(await verdict(bash('find ~/.reelmimic -name secrets.json -delete')), 'deny:secrets-write');
+ assert.equal(await verdict(bash(String.raw`find . -name secrets.json -exec rm {} \;`)), 'deny:secrets-write');
+ assert.equal(await verdict(bash('find . -name secrets.json')), null, 'just listing');
+});
+
+test('secrets: the Grep tool asks when its path is the file or a folder above it', async () => {
+ const grep = (input: Record<string, unknown>, cwd = ROOT) => evaluate('Grep', { pattern: '.', ...input }, cwd, KEYED, down);
+ assert.equal((await grep({ path: SECRETS }))?.decision, 'ask');
+ assert.equal((await grep({ path: SECRETS_DIR }))?.policy, 'secrets-read');
+ assert.equal((await grep({}, SECRETS_DIR))?.decision, 'ask', 'no path: searches the cwd');
+ assert.equal(await grep({ path: `${ROOT}/app` }), 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');
});
@@ -65,6 +108,12 @@ test('one-server: a second server on the real projects dir is denied while one a
['nohup node server/index.ts > /tmp/log 2>&1 &', `${ROOT}/app`],
['bash start.sh', ROOT],
['./start.sh', ROOT],
+ ['timeout 600 node app/server/index.ts', ROOT],
+ ['timeout -k 5 --signal=INT 10m node app/server/index.ts', ROOT],
+ ['npx tsx app/server/index.ts', ROOT],
+ ['npx -y tsx watch server/index.ts', `${ROOT}/app`],
+ ['pnpm exec tsx app/server/index.ts', ROOT],
+ ['sudo -n node app/server/index.ts', 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)`);
diff --git a/.claude/harness/test/render.test.mts b/.claude/harness/test/render.test.mts
index b6f5ca0..2e999a5 100644
--- a/.claude/harness/test/render.test.mts
+++ b/.claude/harness/test/render.test.mts
@@ -42,6 +42,14 @@ test('only a freshly written file counts as the output', () => {
assert.equal(freshOutput({ ...r, out: null }, d, { withinMs: 60_000 })?.endsWith('renders.mp4'), true);
});
+test('a render that named its output and did not write it wrote nothing (another fresh video is not it)', () => {
+ const d = mkdtempSync(join(tmpdir(), 'harness-named-'));
+ writeFileSync(join(d, 'other.mp4'), 'fresh, from some other command');
+ const r = { kind: 'film' as const, out: join(d, 'out', 'video.mp4').replace(/\\/g, '/'), engine: 'render.mjs' };
+ assert.equal(freshOutput(r, d, { withinMs: 60_000 }), null);
+ assert.equal(freshOutput({ ...r, out: null }, d, { withinMs: 60_000 })?.endsWith('other.mp4'), true, 'only an unnamed output is looked for');
+});
+
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));
diff --git a/.claude/harness/test/rules.test.mts b/.claude/harness/test/rules.test.mts
index 458048e..0f396d2 100644
--- a/.claude/harness/test/rules.test.mts
+++ b/.claude/harness/test/rules.test.mts
@@ -1,12 +1,35 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
-import { block, problems, renderTable, ruleIds } from '../sync-rules.mts';
+import { anchored, 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('an anchor in a comment does not count; in code or a string it does', () => {
+ const ts = [
+ '// contactSheet() builds the sheet',
+ '/* reviewFix is gone */',
+ "const url = 'http://x/*not a comment*/', re = /[\"'`]\\/\\//g, n = a / b / c;",
+ 'const p = `out/check/shots/*.review.json ${k ? `S${n}` : \'\'} 每鏡 ≥ 4`; // trailing stop_hook_active',
+ 'if (e.stop_hook_active) liveCode();',
+ ].join('\n');
+ assert.equal(anchored(ts, 'a.mts', 'contactSheet'), false);
+ assert.equal(anchored(ts, 'a.mts', 'reviewFix'), false);
+ assert.equal(anchored(ts, 'a.mts', 'not a comment'), true, '/* inside a string');
+ assert.equal(anchored(ts, 'a.mts', '每鏡 ≥ 4'), true, 'after a template nested in ${ }');
+ assert.equal(anchored(ts, 'a.mts', 'stop_hook_active'), true);
+ assert.equal(anchored(ts, 'a.mts', 'liveCode'), true);
+ assert.equal(anchored('stop_hook_active_x = 1', 'a.ts', 'stop_hook_active'), false, 'a whole word');
+ assert.equal(anchored("# ASSETS.md\nx = 1", 'f.py', 'ASSETS.md'), false);
+ assert.equal(anchored("p = 'ASSETS.md' # write it", 'f.py', 'ASSETS.md'), true);
+ assert.equal(anchored('"""\n# not a comment: ASSETS.md\n"""', 'f.py', 'ASSETS.md'), true, 'inside a docstring');
+ assert.equal(anchored('echo "not restarting" # fine', 'r.sh', 'not restarting'), true);
+ assert.equal(anchored('n=${#a} # x', 'r.sh', 'n=${#a}'), true, '# inside a word is not a comment');
+ assert.equal(anchored('<!-- 目前只做 2D -->\ntext', 'S.md', '目前只做 2D'), false);
+});
+
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 -->']);
diff --git a/.claude/harness/test/shell.test.mts b/.claude/harness/test/shell.test.mts
index 1d6ee58..64d6963 100644
--- a/.claude/harness/test/shell.test.mts
+++ b/.claude/harness/test/shell.test.mts
@@ -54,6 +54,26 @@ test('here-documents are stdin, not commands; an unquoted one still runs its sub
assert.deepEqual(argvs('grep x <<< "git add -f projects"'), [['grep', 'x']]);
});
+test('variables expand from the command, then the environment; search lists do not', () => {
+ const home = homedir().replace(/\\/g, '/');
+ assert.deepEqual(argvs('cat $HOME/.k ${HOME}/.k')[0].slice(1).map((a) => a.replace(/\\/g, '/')), [`${home}/.k`, `${home}/.k`]);
+ assert.deepEqual(argvs('D=/tmp/d; ls $D/x "${D}"/y'), [['ls', '/tmp/d/x', '/tmp/d/y']]);
+ assert.deepEqual(argvs('HOME=/elsewhere cat $HOME/f')[0][1].replace(/\\/g, '/'), `${home}/f`, 'a prefix applies to the command, not to its own words');
+ assert.deepEqual(argvs('echo $PATH $NOT_SET_ANYWHERE_X $1'), [['echo', '$PATH', '$NOT_SET_ANYWHERE_X', '$1']]);
+ assert.deepEqual(parse('D=/tmp/d; echo x > $D/out.txt', CWD)[0].redirects, [resolvePath('/tmp/d/out.txt', CWD)]);
+});
+
+test('launchers are unwrapped with their own options', () => {
+ assert.deepEqual(argvs('timeout 600 node a.js'), [['node', 'a.js']]);
+ assert.deepEqual(argvs('timeout -s INT -k 5 10m node a.js'), [['node', 'a.js']]);
+ assert.deepEqual(argvs('sudo -n node a.js'), [['node', 'a.js']], '-n takes no value: the old code ate `node`');
+ assert.deepEqual(argvs('sudo -u bob node a.js'), [['node', 'a.js']]);
+ assert.deepEqual(argvs('npx -y tsx a.ts'), [['tsx', 'a.ts']]);
+ assert.deepEqual(argvs('npx --package tsx tsx a.ts'), [['tsx', 'a.ts']]);
+ assert.deepEqual(argvs('pnpm exec -- tsx a.ts'), [['tsx', 'a.ts']]);
+ assert.deepEqual(argvs('npm test'), [['npm', 'test']]);
+});
+
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']]);
diff --git a/.claude/settings.json b/.claude/settings.json
index cee34df..080a1a5 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -7,7 +7,7 @@
"hooks": {
"PreToolUse": [
{
- "matcher": "Bash|PowerShell|Write|Edit|MultiEdit|NotebookEdit|Read",
+ "matcher": "Bash|PowerShell|Write|Edit|MultiEdit|NotebookEdit|Read|Grep",
"hooks": [{ "type": "command", "command": "node --disable-warning=ExperimentalWarning \"$CLAUDE_PROJECT_DIR/.claude/harness/hooks/dispatch.mjs\" pre", "timeout": 15 }]
}
],
diff --git a/docs/HARNESS.md b/docs/HARNESS.md
index 552aca8..3576eac 100644
--- a/docs/HARNESS.md
+++ b/docs/HARNESS.md
@@ -23,7 +23,9 @@ enforces it. The list is generated from code and checked in CI, so a rule nobody
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.
+function) is no longer in the file it points to. Comments do not count: a comment that still mentions a deleted function
+does not keep its anchor alive. A bare identifier must match as a whole word. Strings, templates and regex literals are
+skipped properly, so `'http://…'` does not start a comment.
<!-- harness:table — generated, do not edit by hand -->
| rule | strongest layer | enforced by |
@@ -32,7 +34,7 @@ function) is no longer in the file it points to.
| `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 |
+| `secrets` | hook | **hook** [policy.mts](../.claude/harness/policy.mts) — writes to any secrets.json are denied (Write/Edit, redirects, cp/mv/sed/…, globs and folder-walking tools over it)<br>**hook** [policy.mts](../.claude/harness/policy.mts) — reading the real file asks the user first (Read, Grep, cat, globs, grep -r over a folder above it)<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 |
@@ -69,34 +71,43 @@ plain JS: loading Node's TypeScript stripper alone costs ≈ 22 ms. It answers w
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.
+(`secrets`, `git`, `index.ts`, `render`, …) after quotes and backslashes are dropped. So `g''it` or `"secrets.json"` cannot slip past.
+The secrets policies can also reach the keys without naming them, through a glob or a folder above them (`rm -rf $HOME`).
+For that the fast path expands variables the way the parser does and bounds where the command can be. Every directory a
+command can be in starts at the event's cwd or at an absolute `cd` target, and moves by descending or by `..`. So if
+none of those, climbed by every `..` in the command, sits above the keys, no relative path does either. Absolute paths
+are checked directly (a glob by its literal folder); a bare `/` only counts for a folder-walking command.
[`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.)
+On 13,211 production commands: no unsafe skip, and the fast path is taken by **97.5 %** of PreToolUse and **80.5 %**
+of PostToolUse shell calls. The PreToolUse figure is a floor: the logs cut commands at 400 characters, and a cut-off
+`D="C:/Users/me/` reads as a path above the keys. On PostToolUse 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 | |
+| fast path (Read, Grep, `ls`, …: almost every call) | 108–124 ms | **63–68 ms** |
+| handler path (`git …`, a render) | 109–124 ms | 89–96 ms |
+| floor: `bash -c "node -e 0"` | 57–62 ms | |
-The fast path is now ≈ 7 ms above the cost of starting Node at all.
+The fast path costs ≈ 5 ms more than 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
+`$( )` and launchers (`env`, `nohup`, `sudo`, `timeout`, `npx`, `pnpm exec`, each with its own options) followed.
+`$HOME`, `${VAR}`, `$env:VAR` and `%VAR%` are expanded from the command's own exports, then the environment; search lists
+like `$PATH` are not. 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 | — |
+| `secrets-write` | Write/Edit of any `secrets.json`; redirects into it; any other command that reaches it: by name (`cp`, `mv`, `sed -i`, `python -c "…open(…secrets.json,'w')"`), by a glob (`cp ~/.reelmimic/* /tmp`), or as a folder-walking tool over a folder above it (`rm -rf`, `cp -r`, `tar`, `find … -delete / -exec`) | tell the user which key to add; `test -f` to check |
+| `secrets-read` | asks before reading the real file: Read, `cat`, `Get-Content`, …, a glob that expands to it, `grep -r` / `rg` over a folder above it, the Grep tool pointed at or above it. 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` |
+| `second-server` | starting `app/server/index.ts` (directly or through `timeout` / `npx tsx`, `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.
@@ -106,8 +117,10 @@ After a film render, the hook finds the output file and checks that **this call*
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.
+time, a 3-minute window is the fallback. A command that names its output (`--out`, `-o`, the default `out/video.mp4`)
+is judged on that file alone: if it is missing, the render failed, and the newest video nearby belongs to something
+else. Only an unnamed output is looked for. It then builds a 3×3 contact sheet (one input seek per frame,
+in parallel, cached by size + mtime + layout) 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>`.
@@ -159,6 +172,10 @@ and AGENTS.md says so.
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.
+- Folder-walking checks know the keys files `app/server/env.ts` would load (`$REELMIMIC_SECRETS`, `~/.reelmimic/`, the
+ pre-rename `~/.clone-studio/`). A `secrets.json` elsewhere is still caught by name or by glob, not through a folder
+ above it. Globs are expanded up to 500 matches per segment. `rg` skips dot-folders unless told otherwise; the policy
+ asks anyway.
- `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.