Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: show review evidence and allow authenticated music-video approvals (#9876)
[._.]/52594d23f61f
diff --git a/.claude/skills/portos-music-video-code/SKILL.md b/.claude/skills/portos-music-video-code/SKILL.mdindex 8394af3d63..56414eacd0 100644--- a/.claude/skills/portos-music-video-code/SKILL.md+++ b/.claude/skills/portos-music-video-code/SKILL.md@@ -24,6 +24,8 @@ For each section or shot, record time ranges and music anchors (downbeats, beatRender and watch a continuous chorus proof with its entry and exit, normal-speed playback and master audio. Compare the saved energy target against the result: do major subject/prop actions read, do accents land on the chosen beats/words, do camera and typography support the action, are holds readable, and does the next chorus develop rather than merely repeat? Check motion throughout the interval, including transitions; attractive stills, changing pixels, deterministic seeks and a valid render contract cannot establish choreography quality. If the proof is static or sluggish against an energetic plan, revise the authored actions and test playback again before approving. Record actionable feedback by time range and intended versus observed action. Fill the proof review’s energy comparison and timestamped playback notes (for example, `0:04` or `4.5s`); they are saved against that exact excerpt and filename. A replacement proof needs fresh notes and acknowledgement. Acknowledge audio playback against the saved choreography only after making that comparison; keep the server's revision-bound art, storyboard and proof gates intact.+Production approvals use the existing signed-in session, including authenticated agent sessions; do not ask for the instance password again or mint a new credential. Review authority does not establish review quality. An agent reviewing a proof must inspect continuous motion and audio alignment against the saved plan, then submit `proofReview.method: "machine"`, `watchedWithAudio: false`, the exact excerpt ID and filename, an energy comparison, timecoded notes, and `machineEvidence` containing `visualReview`, `audioReview`, and `limitations`. Describe the actual inspection method, observed actions and musical anchors, and any limits; never fabricate watched/listened evidence. Still frames, waveform checks or a successful render alone are insufficient. If available tools cannot assess motion and audio, leave proof approval pending and identify the missing review. Human playback continues to use its explicit playback acknowledgement. The server records the authenticated session and review evidence; a shared agent credential cannot identify the individual agent. Final public publishing remains manual.+Respect renderer capabilities while pursuing this direction: native Code uses its documented Canvas restrictions and native output size; composition documents support richer local fonts, authored worlds and the deterministic `seek(t)` contract. Code-only prohibits imagegen for guides as well as output. Build its guides and proofs from code-rendered scenes. A limitation is a reason to revise the implementation plan or choose a supported renderer, not to silently substitute raster assets or remote dependencies.## Revisions and footage variantsdiff --git a/client/src/components/musicVideo/AutoApproveFields.jsx b/client/src/components/musicVideo/AutoApproveFields.jsxindex caece2c661..d6741405ab 100644--- a/client/src/components/musicVideo/AutoApproveFields.jsx+++ b/client/src/components/musicVideo/AutoApproveFields.jsx@@ -1,21 +1,16 @@import ToggleChip from '../ui/ToggleChip.jsx';import { AUTONOMOUS_AUTO_APPROVE_LABELS, AUTONOMOUS_AUTO_APPROVE_STAGES } from '../../lib/musicVideoAutonomous.js';-const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';+// Proof is intentionally absent: it always needs recorded playback or machine evidence.+const planningStages = AUTONOMOUS_AUTO_APPROVE_STAGES.filter(stage => stage !== 'proof');-/**- * "Auto-approve" — the Production review stages the autonomous run may approve- * itself (art, storyboard, animated proof). Granting that is the operator's- * authority, so picking any stage asks for the instance password once, on this- * request; it is sent with it and never stored. `error` is the API's refusal.- */-export default function AutoApproveFields({ idPrefix, value, onChange, password, onPasswordChange, error = null, granted = [] }) {- const toggle = (stage) => onChange(AUTONOMOUS_AUTO_APPROVE_STAGES.filter((s) => (s === stage ? !value.includes(s) : value.includes(s))));+export default function AutoApproveFields({ idPrefix, value, onChange, error = null, granted = [] }) {+ const toggle = (stage) => onChange(planningStages.filter((s) => (s === stage ? !value.includes(s) : value.includes(s))));return (<fieldset className="min-w-0 space-y-1" aria-labelledby={`${idPrefix}-auto-approve-label`}>- <span id={`${idPrefix}-auto-approve-label`} className="block text-xs text-port-text-muted">Auto-approve (optional)</span>+ <span id={`${idPrefix}-auto-approve-label`} className="block text-xs text-port-text-muted">Automatic planning approvals (optional)</span><div className="flex flex-wrap gap-1.5">- {AUTONOMOUS_AUTO_APPROVE_STAGES.map((stage) => (+ {planningStages.map((stage) => (<ToggleChipkey={stage}id={`${idPrefix}-auto-approve-${stage}`}@@ -26,24 +21,9 @@ export default function AutoApproveFields({ idPrefix, value, onChange, password,))}</div><p className="text-[11px] text-port-text-muted">- The run approves these Production review stages itself once each has no open problems; the proof after its render finishes.- {granted.length > 0 && ` Currently granted: ${granted.map((s) => AUTONOMOUS_AUTO_APPROVE_LABELS[s] || s).join(', ')}.`}+ Your signed-in session lets this run approve selected planning stages once their checks pass. The animated proof still waits for recorded playback or machine review.+ {granted.some(s => s !== 'proof') && ` Currently granted: ${granted.filter(s => s !== 'proof').map((s) => AUTONOMOUS_AUTO_APPROVE_LABELS[s] || s).join(', ')}.`}</p>- {value.length > 0 && (- <div>- <label htmlFor={`${idPrefix}-auto-approve-password`} className="block text-xs text-port-text-muted mb-1">Instance password to grant this</label>- <input- id={`${idPrefix}-auto-approve-password`}- type="password"- autoComplete="current-password"- value={password}- onChange={(e) => onPasswordChange(e.target.value)}- aria-invalid={!!error}- className={inputClass}- />- <p className="text-[11px] text-port-text-muted mt-1">Enter it yourself, once. API tokens cannot grant approval.</p>- </div>- )}{error && <p role="alert" className="text-[11px] text-port-error break-words">{error}</p>}</fieldset>);diff --git a/client/src/components/musicVideo/AutonomousRunPanel.jsx b/client/src/components/musicVideo/AutonomousRunPanel.jsxindex 20fa403b51..b9ba751beb 100644--- a/client/src/components/musicVideo/AutonomousRunPanel.jsx+++ b/client/src/components/musicVideo/AutonomousRunPanel.jsx@@ -60,9 +60,9 @@ function StageOutput({ run, row, editableBelow }) {export default function AutonomousRunPanel({ project, auto, selectedStage = null, onSelectStage, framed = true }) {const run = project?.autonomousRun;const [edit, setEdit] = useState(null); // { for: stage, value } — the director's edit at a checkpoint- // "Auto-approve the rest": a grant sent with the next resume (password entered once, never kept).- const [autoApprove, setAutoApprove] = useState([]);- const [password, setPassword] = useState('');+ // Planning approval authority is granted with the next explicit resume.+ const [autoApproveEdit, setAutoApproveEdit] = useState(null);+ const autoApprove = autoApproveEdit && autoApproveEdit.runId === run?.id ? autoApproveEdit.value : (run?.brief?.autoApprove || []).filter(stage => stage !== 'proof');const [grantError, setGrantError] = useState(null);if (!run) return null;const rows = autonomousStageRows(run);@@ -79,15 +79,12 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null// A stale or hand-edited `?run-stage=` that names no finished, viewable stage opens nothing.const selectedRow = rows.find((row) => row.id === selectedStage && row.status === 'done' && AUTONOMOUS_VIEWABLE_STAGES.includes(row.id)) || null;const selected = selectedRow?.id || null;- const grantBlocked = autoApprove.length > 0 && !password;- // Every resume path carries the grant when one is picked; a refused password shows inline.+ // Every resume path carries the selected grant and shows authorization failures inline.const resume = (edits = {}) => {- if (!autoApprove.length) return auto.resume(edits);- const secret = password;- setPassword('');+ if (!autoApproveEdit || autoApproveEdit.runId !== run.id) return auto.resume(edits);setGrantError(null);- return auto.resume({ ...edits, autoApprove, password: secret }, { inline: true })- .then((res) => { setAutoApprove([]); return res; })+ return auto.resume({ ...edits, autoApprove }, { inline: true })+ .then((res) => { setAutoApproveEdit(null); return res; }).catch((err) => { setGrantError(err?.message || 'Could not grant auto-approval'); });};@@ -164,12 +161,12 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null</div>)}<div className="flex flex-wrap gap-2">- <button type="button" disabled={auto.busy || grantBlocked} onClick={() => resume(changed ? { [editable.key]: draft } : {})} className={`${buttonClass} bg-port-accent text-white border-port-accent`}>+ <button type="button" disabled={auto.busy} onClick={() => resume(changed ? { [editable.key]: draft } : {})} className={`${buttonClass} bg-port-accent text-white border-port-accent`}><Play size={14} aria-hidden="true" /> {changed ? 'Save edit & approve' : 'Approve & continue'}</button>{awaiting === 'song' && (// Discards this song and makes a new one (a new Suno generation spends credits), then pauses here again.- <button type="button" disabled={auto.busy || grantBlocked} onClick={() => resume({ retakeSong: true })} className={buttonClass}>+ <button type="button" disabled={auto.busy} onClick={() => resume({ retakeSong: true })} className={buttonClass}><RotateCcw size={14} aria-hidden="true" /> Retake song</button>)}@@ -181,9 +178,7 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null<AutoApproveFieldsidPrefix="mv-run"value={autoApprove}- onChange={(next) => { setAutoApprove(next); setGrantError(null); }}- password={password}- onPasswordChange={setPassword}+ onChange={(next) => { setAutoApproveEdit({ runId: run.id, value: next }); setGrantError(null); }}error={grantError}granted={run.brief?.autoApprove || []}/>@@ -192,7 +187,7 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null{live || run.status === 'failed' ? (<div className="flex flex-wrap gap-2">{canRetry && !awaiting && (- <button type="button" disabled={auto.busy || grantBlocked} onClick={() => resume()} className={buttonClass}>+ <button type="button" disabled={auto.busy} onClick={() => resume()} className={buttonClass}><Play size={14} aria-hidden="true" /> {run.status === 'failed' ? 'Retry' : 'Resume'}</button>)}diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsxindex 6d4f1b0225..46c9e57519 100644--- a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx@@ -283,42 +283,46 @@ describe('AutonomousStartDrawer', () => {});describe('auto-approve the rest', () => {- const refusal = () => Object.assign(new Error('Enter the instance password yourself to let the run approve production review stages.'), { status: 403, code: 'OPERATOR_REAUTH_REQUIRED' });+ const refusal = () => Object.assign(new Error('Sign in to grant automatic planning approvals.'), { status: 401, code: 'AUTH_REQUIRED' });- it('starts with the picked stages and the password, asking for the password only once a stage is picked, and shows a refusal inline', async () => {+ it('starts with selected planning grants using the session and shows sign-in failures inline', async () => {api.startAutonomousMusicVideo.mockRejectedValueOnce(refusal()).mockResolvedValue({ project: { id: 'mv-new' }, run: baseRun() });render(<AutonomousStartDrawer open onClose={() => {}} onStarted={() => {}} />);fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'p' } });fireEvent.change(screen.getByLabelText('Code authoring provider'), { target: { value: 'fixture-api' } });expect(screen.queryByLabelText('Instance password to grant this')).toBeNull();- fireEvent.click(screen.getByLabelText('Proof', { selector: '#mv-auto-auto-approve-proof' }));+ expect(screen.queryByLabelText('Proof', { selector: '#mv-auto-auto-approve-proof' })).toBeNull();fireEvent.click(screen.getByLabelText('Art', { selector: '#mv-auto-auto-approve-art' }));const submit = screen.getByRole('button', { name: /start autonomous video/i });- expect(submit.disabled).toBe(true);- fireEvent.change(screen.getByLabelText('Instance password to grant this'), { target: { value: 'wrong-password' } });+ expect(submit.disabled).toBe(false);fireEvent.click(submit);- await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('Enter the instance password yourself'));- expect(api.startAutonomousMusicVideo.mock.calls[0][0]).toMatchObject({ autoApprove: ['art', 'proof'], password: 'wrong-password' });- // The password is never kept for a retry.- expect(screen.getByLabelText('Instance password to grant this').value).toBe('');- fireEvent.change(screen.getByLabelText('Instance password to grant this'), { target: { value: 'synthetic-password' } });+ await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('Sign in to grant automatic planning approvals'));+ expect(api.startAutonomousMusicVideo.mock.calls[0][0]).toMatchObject({ autoApprove: ['art'] });fireEvent.click(submit);await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalledTimes(2));- expect(api.startAutonomousMusicVideo.mock.calls[1][0]).toMatchObject({ autoApprove: ['art', 'proof'], password: 'synthetic-password' });+ expect(api.startAutonomousMusicVideo.mock.calls[1][0]).toMatchObject({ autoApprove: ['art'] });+ });++ it('shows existing planning grants and sends an explicit empty list when revoked', async () => {+ api.resumeAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-1', autonomousRun: baseRun() }, run: baseRun() });+ render(<Harness initial={baseRun({ status: 'needs-human', stage: 'produce', brief: { autoApprove: ['art'] } })} />);+ const art = screen.getByLabelText('Art', { selector: '#mv-run-auto-approve-art' });+ expect(art.checked).toBe(true);+ fireEvent.click(art);+ fireEvent.click(screen.getByRole('button', { name: /resume/i }));+ await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenCalledWith('mv-1', { autoApprove: [] }, { silent: true }));});- it('resumes a parked run with "auto-approve the rest", showing a refused password next to the control', async () => {+ it('resumes a parked run with session-authorized planning grants and shows sign-in failures', async () => {api.resumeAutonomousMusicVideo.mockRejectedValueOnce(refusal()).mockResolvedValue({ project: { id: 'mv-1', autonomousRun: baseRun() }, run: baseRun() });render(<Harness initial={baseRun({ status: 'needs-human', stage: 'produce', error: 'Review and approve the current art direction first.', brief: { origin: { kind: 'manual' }, autoApprove: [] } })} />);- for (const stage of ['storyboard', 'art', 'proof']) fireEvent.click(screen.getByLabelText(stage[0].toUpperCase() + stage.slice(1), { selector: `#mv-run-auto-approve-${stage}` }));+ for (const stage of ['storyboard', 'art']) fireEvent.click(screen.getByLabelText(stage[0].toUpperCase() + stage.slice(1), { selector: `#mv-run-auto-approve-${stage}` }));const resume = screen.getByRole('button', { name: /resume/i });- expect(resume.disabled).toBe(true);- fireEvent.change(screen.getByLabelText('Instance password to grant this'), { target: { value: 'wrong-password' } });+ expect(resume.disabled).toBe(false);fireEvent.click(resume);- await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('Enter the instance password yourself'));- expect(api.resumeAutonomousMusicVideo).toHaveBeenLastCalledWith('mv-1', { autoApprove: ['art', 'storyboard', 'proof'], password: 'wrong-password' }, { silent: true });- fireEvent.change(screen.getByLabelText('Instance password to grant this'), { target: { value: 'synthetic-password' } });+ await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('Sign in to grant automatic planning approvals'));+ expect(api.resumeAutonomousMusicVideo).toHaveBeenLastCalledWith('mv-1', { autoApprove: ['art', 'storyboard'] }, { silent: true });fireEvent.click(resume);- await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenLastCalledWith('mv-1', { autoApprove: ['art', 'storyboard', 'proof'], password: 'synthetic-password' }, { silent: true }));+ await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenLastCalledWith('mv-1', { autoApprove: ['art', 'storyboard'] }, { silent: true }));});});diff --git a/client/src/components/musicVideo/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsxindex dfb93399a2..2c957472cd 100644--- a/client/src/components/musicVideo/AutonomousStartDrawer.jsx+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx@@ -33,9 +33,8 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {const [authoringReady, setAuthoringReady] = useState(false);const llm = useProviderModels({ allowDefault: true, silent: true, withEffort: true });const [effort, setEffort] = useState('');- // Kept out of the draft: the password rides one request and is cleared after it.+ // An explicit per-run grant, authorized by the signed-in session.const [autoApprove, setAutoApprove] = useState([]);- const [password, setPassword] = useState('');const [grantError, setGrantError] = useState(null);const patch = (next) => setDraft((d) => ({ ...d, ...next }));const toggleCheckpoint = (id) => patch({@@ -43,19 +42,17 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {});const patchSuno = (next) => setDraft((d) => ({ ...d, suno: { ...d.suno, ...next } }));const sunoModelValid = draft.songSource !== 'suno' || isSunoModelValid(draft.suno.model);- const valid = draft.prompt.trim().length > 0 && authoringReady && sunoModelValid && (!autoApprove.length || !!password);+ const valid = draft.prompt.trim().length > 0 && authoringReady && sunoModelValid;const handleSubmit = (e) => {e.preventDefault();if (!valid || submitting) return;setSubmitting(true);setGrantError(null);- const secret = password;- setPassword('');startAutonomousMusicVideo({...autonomousRequestFromDraft(draft, { providerId: llm.selectedProviderId || undefined, model: llm.selectedModel || undefined, effort: effort || undefined }),- ...(autoApprove.length ? { autoApprove, password: secret } : {}),+ ...(autoApprove.length ? { autoApprove } : {}),},{ silent: true },)@@ -66,7 +63,7 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {onStarted(project);}).catch((err) => {- if (String(err?.code || '').startsWith('OPERATOR_')) setGrantError(err.message);+ if (err?.code === 'AUTH_REQUIRED') setGrantError(err.message);else toast.error(err?.message || 'Failed to start the autonomous music video');}).finally(() => setSubmitting(false));@@ -177,15 +174,13 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {/>))}</div>- <p className="text-[11px] text-port-text-muted mt-1">Production still pauses for your art, storyboard and animated proof approvals unless you auto-approve them below.</p>+ <p className="text-[11px] text-port-text-muted mt-1">Select automatic planning approvals below if desired. The animated proof always needs a recorded review.</p></fieldset><AutoApproveFieldsidPrefix="mv-auto"value={autoApprove}onChange={(next) => { setAutoApprove(next); setGrantError(null); }}- password={password}- onPasswordChange={setPassword}error={grantError}/>diff --git a/client/src/components/musicVideo/DevArtifactDrawer.jsx b/client/src/components/musicVideo/DevArtifactDrawer.jsxindex 17687f4c27..e7d7ef8bbb 100644--- a/client/src/components/musicVideo/DevArtifactDrawer.jsx+++ b/client/src/components/musicVideo/DevArtifactDrawer.jsx@@ -1,6 +1,7 @@import { useState } from 'react';import { CheckCircle2, RotateCcw, Trash2, ExternalLink, MessageSquarePlus } from 'lucide-react';import Drawer from '../Drawer.jsx';+import DevArtifactPreview from './DevArtifactPreview.jsx';import Pill from '../ui/Pill.jsx';import { musicVideoDevArtifactFileUrl } from '../../services/apiMusicVideo.js';import { timeAgo } from '../../utils/formatters.js';@@ -21,27 +22,6 @@ function castAndSetsTargets(stage) {];}-function Viewer({ projectId, artifact, version }) {- const entry = (artifact.versions || []).find((v) => v.version === version) || artifact;- const url = musicVideoDevArtifactFileUrl(projectId, artifact.id, version === artifact.version ? null : version);- const title = `${artifact.title} v${entry.version || version}`;- if (entry.mimeType?.startsWith('image/')) return <img src={url} alt={title} className="w-full h-auto rounded border border-port-border" />;- if (entry.mimeType?.startsWith('video/')) return <video src={url} controls className="w-full rounded border border-port-border" aria-label={title} />;- // HTML and Markdown: an opaque-origin frame (no allow-same-origin), so a- // sheet's own script can run but can never reach PortOS. The server's CSP- // enforces the same sandbox and blocks every network fetch.- return (- <iframe- key={url}- src={url}- title={title}- sandbox="allow-scripts"- referrerPolicy="no-referrer"- className="w-full h-[60vh] lg:h-[calc(100vh-9rem)] rounded border border-port-border bg-white"- />- );-}-/*** One development artifact, full width: the file (sandboxed), its version* history, notes and review actions. For the sheet the Cast & Sets check-in is@@ -98,7 +78,7 @@ export default function DevArtifactDrawer({<ExternalLink size={12} aria-hidden="true" /> Open in a tab</a></div>- <Viewer projectId={project.id} artifact={artifact} version={shown} />+ <DevArtifactPreview projectId={project.id} artifact={artifact} version={shown} /></div><aside className="lg:w-80 shrink-0 space-y-3 min-w-0" aria-label="Review">diff --git a/client/src/components/musicVideo/DevArtifactPreview.jsx b/client/src/components/musicVideo/DevArtifactPreview.jsxnew file mode 100644index 0000000000..c1dae4cb80--- /dev/null+++ b/client/src/components/musicVideo/DevArtifactPreview.jsx@@ -0,0 +1,23 @@+import { useEffect, useState } from 'react';+import { musicVideoDevArtifactFileUrl } from '../../services/apiMusicVideo.js';++/** Pin the served version and check availability before embedding a sandboxed file. */+export default function DevArtifactPreview({ projectId, artifact, version = artifact.version, onReady }) {+ const entry = (artifact.versions || []).find(v => v.version === version) || artifact;+ const url = musicVideoDevArtifactFileUrl(projectId, artifact.id, version);+ const [response, setResponse] = useState(null);+ useEffect(() => {+ let active = true;+ fetch(url, { method: 'HEAD' }).then(result => {+ if (active) setResponse({ url, available: result.ok });+ }).catch(() => { if (active) setResponse({ url, available: false }); });+ return () => { active = false; };+ }, [url]);+ if (response?.url !== url) return <p role="status">Loading review asset…</p>;+ if (!response.available) return <p role="alert">This review asset could not be loaded. Restore or select an available Development file before approving.</p>;+ const title = `${artifact.title} v${version || 1}`;+ const props = { onLoad: () => onReady?.(true), onError: () => { onReady?.(false); setResponse({ url, available: false }); }, className: 'w-full min-w-0 rounded border border-port-border' };+ if (entry.mimeType?.startsWith('image/')) return <img {...props} src={url} alt={title} />;+ if (entry.mimeType?.startsWith('video/')) return <video {...props} onLoadedData={() => onReady?.(true)} src={url} controls aria-label={title} />;+ return <iframe {...props} key={url} src={url} title={title} sandbox="allow-scripts" referrerPolicy="no-referrer" className={`${props.className} h-[55vh] bg-white`} />;+}diff --git a/client/src/components/musicVideo/ProductionReviewContext.jsx b/client/src/components/musicVideo/ProductionReviewContext.jsxnew file mode 100644index 0000000000..6e8ea53786--- /dev/null+++ b/client/src/components/musicVideo/ProductionReviewContext.jsx@@ -0,0 +1,40 @@+import DevArtifactPreview from './DevArtifactPreview.jsx';+import { formatTimecode, formatCount } from '../../utils/formatters.js';++/** The saved evidence immediately preceding a revision-bound decision. */+export default function ProductionReviewContext({ stage, project, basis, approved, onOpenArtifact, onArtReady }) {+ const draft = project.productionReview?.draft || {};+ const guide = project.devArtifacts?.find(a => a.id === draft.guideArtifactId && !a.deleted);+ const document = draft.storyboardSource === 'document';+ const shots = draft.storyboard || [];+ const sheets = (project.devArtifacts || []).filter(a => !a.deleted && a.kind === 'storyboard');+ return <section aria-label={`${stage === 'art' ? 'Art direction' : 'Storyboard'} review content`} className="min-w-0 space-y-3 py-3">+ <p className="text-xs text-port-text-muted break-words">Project v{project.version || 1} · {approved ? 'Approved saved revision' : 'Current saved revision'} · {basis?.slice(0, 12) || 'Loading revision…'}</p>+ {stage === 'art' ? <>+ {guide ? <figure className="min-w-0 space-y-2">+ <figcaption className="text-sm font-medium">Selected visual guide: {guide.title} · v{guide.version || 1}</figcaption>+ <DevArtifactPreview key={`${guide.id}:${guide.version}`} projectId={project.id} artifact={guide} onReady={onArtReady} />+ <button type="button" className="min-h-[44px] text-sm text-port-accent" onClick={() => onOpenArtifact(guide.id)}>Open guide and version history</button>+ </figure> : <p role="status">No current visual guide selected. Choose a Development file in the planning editor below.</p>}+ <dl className="space-y-2 text-sm">{[['Cast', draft.cast], ['Environments', draft.environments], ['Visual language', draft.visualLanguage], ['Motion and energy', draft.motionLanguage]].map(([label, value]) => <div key={label}><dt className="font-medium">{label}</dt><dd className="whitespace-pre-wrap break-words">{value || 'Missing — complete this in the planning editor.'}</dd></div>)}</dl>+ </> : <>+ <p className="text-sm font-medium">{formatCount(shots.length)} {document ? 'document shots' : 'storyboard shots'} · {document ? `Document ${project.composition?.document?.directory?.split('/').at(-1) || 'not selected'}` : 'Current Board timing'}</p>+ {!shots.length && <p role="status">No storyboard shots to review. Import the current document’s shot manifest or prepare Board scenes below.</p>}+ <ol className="max-h-[60vh] overflow-y-auto space-y-3 rounded border border-port-border p-2" aria-label="Current storyboard shots" tabIndex={0}>+ {shots.map((shot, index) => {+ const scene = document ? shot : project.scenes?.find(s => s.sceneId === shot.sceneId);+ return <li key={shot.id || shot.sceneId || index} className="border-b border-port-border pb-3 text-sm">+ <p className="font-medium">{index + 1}. {scene?.label || shot.label || 'Shot'} · {Number.isFinite(scene?.startSec) ? `${formatTimecode(scene.startSec)}–${formatTimecode(scene.endSec)}` : 'Timing missing'}</p>+ <p className="whitespace-pre-wrap break-words">{shot.action || 'Action missing'}</p>+ <dl className="text-xs text-port-text-muted space-y-1">{['staging', 'camera', 'transition'].map(key => <div key={key}><dt className="capitalize font-medium">{key}</dt><dd className="whitespace-pre-wrap break-words">{shot[key] || 'Missing'}</dd></div>)}</dl>+ <p className="text-xs">Lyric anchors: {(shot.lyricCueIds || []).map(id => project.lyricCues?.find(c => c.id === id)?.text || id).join(' · ') || (draft.lyricsMode === 'instrumental' ? 'Instrumental' : 'None selected')}</p>+ </li>;+ })}+ </ol>+ {sheets.length > 0 && <details><summary className="min-h-[44px] cursor-pointer py-2 text-sm">Storyboard reference sheets ({formatCount(sheets.length)})</summary>+ <p className="text-xs text-port-text-muted">Reference files may predate the current document. Compare them with the exact saved shots above.</p>+ {sheets.map(sheet => <details key={sheet.id}><summary className="min-h-[44px] cursor-pointer py-2 text-sm">{sheet.title} · v{sheet.version || 1}</summary><DevArtifactPreview projectId={project.id} artifact={sheet} /></details>)}+ </details>}+ </>}+ </section>;+}diff --git a/client/src/components/musicVideo/ProductionReviewPanel.jsx b/client/src/components/musicVideo/ProductionReviewPanel.jsxindex 6d991d16a2..8b59f0822b 100644--- a/client/src/components/musicVideo/ProductionReviewPanel.jsx+++ b/client/src/components/musicVideo/ProductionReviewPanel.jsx@@ -1,4 +1,5 @@import { useEffect, useState } from 'react';+import ProductionReviewContext from './ProductionReviewContext.jsx';import { formatTimecode } from '../../utils/formatters.js';const EMPTY = { cast: '', environments: '', visualLanguage: '', motionLanguage: '', guideArtifactId: null,@@ -12,10 +13,12 @@ const labels = { art: 'Art direction', storyboard: 'Lyric-timed storyboard', proexport default function ProductionReviewPanel({ project, review, onOpenArtifact, framed = true }) {const fieldId = key => `mv-review-${project.id}-${key}`;const saved = project.productionReview?.draft || EMPTY;+ const [visibleArt, setVisibleArt] = useState(null);+ const [proofMedia, setProofMedia] = useState(null);+ const artIdentity = JSON.stringify([project.id, saved.guideArtifactId, project.devArtifacts?.find(a => a.id === saved.guideArtifactId)?.version]);const [local, setLocal] = useState(null);const draft = local || saved;const dirty = !!local && JSON.stringify(local) !== JSON.stringify(saved);- const [password, setPassword] = useState('');const [feedback, setFeedback] = useState({ stage: 'art', target: '', text: '', decision: 'request-changes' });const [resolutions, setResolutions] = useState({});const [importError, setImportError] = useState(null);@@ -41,40 +44,91 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,: { identity: proofIdentity, watched: false, energyComparison: '', timecodedNotes: '' }); }, [proofIdentity]);const playback = playbackReview.identity === proofIdentity ? playbackReview : { watched: false, energyComparison: '', timecodedNotes: '' };const setPlayback = patch => setPlaybackReview({ ...playback, identity: proofIdentity, ...patch });- const playbackBlocked = blocked || review.proof.active || !!ready?.proof.problems.length || excerpt?.status !== 'complete' || !excerpt.filename;+ const playbackBlocked = proofMedia?.identity !== proofIdentity || !proofMedia?.ready || blocked || review.proof.active || !!ready?.proof.problems.length || excerpt?.status !== 'complete' || !excerpt.filename;const playbackComplete = playback.watched && !!playback.energyComparison.trim()&& /(?:\b\d{1,2}:\d{2}(?:\.\d+)?\b|\b\d+(?:\.\d+)?s\b)/.test(playback.timecodedNotes);const approve = stage => {- const secret = password; setPassword('');- return review.approve(stage, secret, stage === 'proof' ? { watchedWithAudio: true,+ return review.approve(stage, stage === 'proof' ? { watchedWithAudio: true,energyComparison: playback.energyComparison.trim(), timecodedNotes: playback.timecodedNotes.trim(),excerptId: excerpt.id, filename: excerpt.filename } : undefined);};+ const nextStage = ['art', 'storyboard', 'proof'].find(stage => !ready?.[stage].approved) || 'proof';+ const proofContent = <>+ <p className="text-xs text-port-text-muted break-words">Project v{project.version || 1} · proof revision {ready?.basis.proof?.slice(0, 12) || 'Loading…'} · {excerpt ? `Excerpt ${excerpt.id}` : 'No registered proof'}</p>+ {excerpt && <p className="text-xs text-port-text-muted break-words">{excerpt.filename || excerpt.status} · {project.productionReview?.proof?.basis === ready?.basis.proof ? 'Current source revision' : 'Source changed — render a new proof'}</p>}++ <p className="text-sm">Author the approved storyboard in Compose, then render a 10–45 second chorus with its entry and exit. Watch with sound at normal speed and compare the chosen energy target and timed choreography below against the actual subject, props, camera, typography and transitions. Check accents against beat and lyric anchors, readable holds and repeated-chorus escalation. A strong static frame does not prove the motion works.</p>+ <section aria-label="Saved choreography for proof comparison" className="rounded border border-port-border bg-port-bg p-3">+ <h4 className="text-sm font-medium">Saved energy target and timed choreography</h4>+ <p className="mt-1 whitespace-pre-wrap text-sm">{saved.motionLanguage || 'Save an energy target and timed choreography in the planning editor before judging the proof.'}</p>+ <p className="mt-2 text-xs text-port-text-muted">Compare playback with this saved plan. If the chosen energy or actions are missing, record revision feedback with a time range before approving.</p>+ </section>+ <div id="mv-review-render" tabIndex={-1} style={{ scrollMarginTop: 'calc(var(--mv-header-h, 9rem) + 1rem)' }} className="flex flex-wrap items-end gap-2">+ <label htmlFor={fieldId('proof-start')} className="text-sm">Proof start (seconds)<input id={fieldId('proof-start')} type="number" min="0" step="0.01" value={startSec} onChange={e => setStartSec(Number(e.target.value))} className={fieldClass} /></label>+ <label htmlFor={fieldId('proof-end')} className="text-sm">Proof end (seconds)<input id={fieldId('proof-end')} type="number" min="0" step="0.01" value={endSec} onChange={e => setEndSec(Number(e.target.value))} className={fieldClass} /></label>+ <button type="button" className={buttonClass} disabled={blocked || review.proof.occupied || review.proof.active} onClick={() => review.renderProof({ startSec, endSec, kind: 'prototype' })}>Render feasibility prototype — unapproved</button>+ <button type="button" className={buttonClass} disabled={blocked || !ready?.storyboard.approved || review.proof.occupied || review.proof.active} onClick={() => review.renderProof({ startSec, endSec })}>Render animated proof</button>+ </div>+ {review.proof.occupied && !review.proof.active && <p role="status">Review evidence is rendering in another project. Wait for it to finish before starting another.</p>}+ {review.proof.active && <p role="status">{review.proof.connected === false ? 'Connecting to review render…' : `Rendering review evidence — ${review.proof.percent ?? 0}%.`} Production approvals are separate.</p>}+ <p className="text-xs text-port-text-muted">A feasibility prototype uses the current authored composition and master audio without approving the look or authorizing production. It can be made before art approval; it never becomes approved proof automatically.</p>+ {prototype?.status === 'complete' && prototype.filename && <figure><video controls className="mt-2 w-full rounded" aria-label="Unapproved feasibility prototype" src={`/data/videos/${encodeURIComponent(prototype.filename)}`} /><figcaption className="text-sm">Unapproved feasibility prototype — separate from production proof</figcaption></figure>}+ {excerpt?.status === 'complete' && excerpt.filename && <video key={proofIdentity} controls className="mt-2 w-full rounded" aria-label="Animated proof with master audio" src={`/data/videos/${encodeURIComponent(excerpt.filename)}`}+ onLoadedData={() => setProofMedia({ identity: proofIdentity, ready: true })}+ onError={() => setProofMedia({ identity: proofIdentity, ready: false, error: true })} />}+ {excerpt?.status === 'complete' && (proofMedia?.identity !== proofIdentity || !proofMedia.ready) && <p role={proofMedia?.identity === proofIdentity && proofMedia.error ? 'alert' : 'status'} className="text-sm">+ {proofMedia?.identity === proofIdentity && proofMedia.error ? 'This proof could not be played. Restore the exact file or render a new proof before approving.' : 'Load and play this exact proof with sound before recording your review.'}+ </p>}+ {matchingRecordedReview && <section aria-label="Recorded proof review" className="rounded border border-port-border p-3">+ <h4 className="text-sm font-medium">Recorded proof review</h4>+ <p className="text-xs text-port-text-muted">{matchingRecordedReview.method === 'machine' ? 'Machine review — no human playback claimed' : 'Playback review'}</p>+ {matchingRecordedReview.machineEvidence && <dl className="text-sm space-y-2">+ <dt>Visual review</dt><dd>{matchingRecordedReview.machineEvidence.visualReview}</dd>+ <dt>Audio review</dt><dd>{matchingRecordedReview.machineEvidence.audioReview}</dd>+ <dt>Review limitations</dt><dd>{matchingRecordedReview.machineEvidence.limitations}</dd>+ </dl>}+ <p className="mt-1 whitespace-pre-wrap text-sm">{matchingRecordedReview.energyComparison}</p>+ <p className="mt-2 whitespace-pre-wrap text-sm">{matchingRecordedReview.timecodedNotes}</p>+ </section>}+ <label htmlFor={fieldId('energy-comparison')} className="block text-sm">Playback energy compared with the saved plan+ <textarea id={fieldId('energy-comparison')} rows={3} maxLength={4000} disabled={playbackBlocked} value={playback.energyComparison} onChange={e => setPlayback({ energyComparison: e.target.value })} className={fieldClass}+ placeholder="Chosen energy target; observed subject, prop and camera activity; where playback matches or misses the intended arc." />+ </label>+ <label htmlFor={fieldId('playback-notes')} className="block text-sm">Timecoded playback notes+ <textarea id={fieldId('playback-notes')} rows={3} maxLength={4000} disabled={playbackBlocked} value={playback.timecodedNotes} onChange={e => setPlayback({ timecodedNotes: e.target.value })} className={fieldClass}+ placeholder="0:04 — subject turns on the downbeat; prop opens through 0:06; camera and type clear the lyric. Name any mismatch to revise." />+ </label>+ <p className="text-xs text-port-text-muted">Include at least one playback timestamp such as 0:04 or 4.5s. These notes are saved with this exact proof. A replacement proof requires a new comparison and acknowledgement.</p>+ <label htmlFor={fieldId('watched')} className="flex gap-2 py-2 text-sm"><input id={fieldId('watched')} type="checkbox" checked={playback.watched}+ disabled={playbackBlocked} onChange={e => setPlayback({ watched: e.target.checked })} />I watched this revision with audio at normal speed and compared its energy, timed choreography and lyric timing with the saved plan.</label>+ </>;return <section id="mv-production-review" aria-label="Production review" className={framed ? 'rounded-lg border border-port-border bg-port-card p-3 space-y-3' : 'space-y-3'}>{framed && <h3 className="font-medium">Production review</h3>}<p className="text-sm text-port-text-muted">Approve the visual direction, then the timed storyboard, then a watched animated proof. Approving a development file or rendering a draft does not approve production.</p>{review.error && <p role="alert" className="text-port-error">{review.error}</p>}- <ol className="grid gap-2 sm:grid-cols-3">- {Object.entries(labels).map(([key, label]) => <li key={key} id={`mv-review-${key}`} tabIndex={-1} style={{ scrollMarginTop: 'calc(var(--mv-header-h, 9rem) + 1rem)' }} className="rounded border border-port-border p-2 focus:outline focus:outline-2 focus:outline-port-accent">- <strong className="text-sm">{label}</strong>- <p role="status" className="text-xs">{ready?.[key].approved ? 'Approved for this revision' : 'Human review required'}</p>+ <ol className="space-y-3">+ {Object.entries(labels).map(([key, label]) => <li key={key}><details open={window.location.hash === `#mv-review-${key}` || key === nextStage} id={`mv-review-${key}`} tabIndex={-1} style={{ scrollMarginTop: 'calc(var(--mv-header-h, 9rem) + 1rem)' }} className="rounded border border-port-border p-2 focus:outline focus:outline-2 focus:outline-port-accent">+ <summary className="cursor-pointer min-h-[44px] py-2 text-sm font-medium">{label}</summary>+ <p role="status" className="text-xs">{ready?.[key].approved ? 'Approved for this revision' : 'Review required'}</p>{(ready?.[key].problems || []).map(problem => <p key={problem} className="mt-1 text-xs text-port-text-muted">{problem}</p>)}+ {key === 'proof' ? proofContent : <ProductionReviewContext stage={key} project={project} basis={ready?.basis[key]} approved={ready?.[key].approved} onOpenArtifact={onOpenArtifact} onArtReady={available => setVisibleArt(available ? artIdentity : null)} />}<button type="button" className={`${buttonClass} mt-2`} onClick={() => approve(key)}- disabled={blocked || !password || ready?.[key].approved || !!ready?.[key].problems.length+ disabled={blocked || (key === 'art' && visibleArt !== artIdentity) || ready?.[key].approved || !!ready?.[key].problems.length|| (key === 'proof' && (playbackBlocked || !playbackComplete))}>Approve {label.toLowerCase()}</button>- {!blocked && !password && !ready?.[key].approved && !ready?.[key].problems.length && (key !== 'proof' || (!playbackBlocked && playbackComplete)) && <button type="button" className="block min-h-[44px] text-xs text-port-accent" onClick={() => {- const input = document.getElementById(fieldId('password'));++ <button type="button" className={`${buttonClass} mt-2 ml-2`} onClick={() => {+ setFeedback({ ...feedback, stage: key, decision: 'request-changes' });+ const input = document.getElementById(fieldId('feedback-text'));+ const fold = input?.closest('details'); if (fold) fold.open = true;input?.scrollIntoView({ block: 'center' }); input?.focus({ preventScroll: true });- }}>Enter your password to enable approval</button>}- </li>)}+ }}>Request changes</button>+ </details></li>)}</ol>- <label htmlFor={fieldId('password')} className="block text-sm">Instance password for this approval- <input id={fieldId('password')} type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} className={fieldClass} />- </label>- <p className="text-xs text-port-text-muted">Enter it yourself. API tokens cannot approve. Password-free installs can prepare drafts; set an instance password in Settings → Security before approval.</p>+ <p className="text-xs text-port-text-muted">Your signed-in session can approve each reviewed stage. Authenticated agents can also review and approve. Proof approval requires recorded visual and audio evidence; publishing remains manual.</p>+ {dirty && <p role="status" className="text-sm">Save your planning edits before approving this revision.</p>}<details><summary className="cursor-pointer min-h-[44px] py-2 text-sm">Review feedback and revision history</summary><p className="text-sm">Name a cast member, environment, shot, artifact or frame time. Structure acceptance records agreement on organization only; it never approves the art or authorizes production.</p>@@ -96,8 +150,8 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,<details><summary className="cursor-pointer py-2 text-sm">Original reviewed content</summary><pre className="max-h-60 overflow-auto whitespace-pre-wrap break-all text-xs">{JSON.stringify(project.productionReview.reviewedRevisions?.[item.basis]?.draft, null, 2)}</pre></details>{item.resolvedAt ? <p className="text-sm">Resolution: {item.resolution}</p> : <><label htmlFor={fieldId(`resolution-${item.id}`)} className="block text-sm">Resolution for {item.target}<textarea id={fieldId(`resolution-${item.id}`)} className={fieldClass} value={resolutions[item.id] || ''} onChange={e => setResolutions({ ...resolutions, [item.id]: e.target.value })} /></label>- <button type="button" className={buttonClass} disabled={blocked || !password || !resolutions[item.id]?.trim()} onClick={async () => {- const secret = password; setPassword(''); await review.resolveFeedback(item.id, resolutions[item.id], secret);+ <button type="button" className={buttonClass} disabled={blocked || !resolutions[item.id]?.trim()} onClick={async () => {+ await review.resolveFeedback(item.id, resolutions[item.id]);}}>Resolve feedback after review</button></>}</li>)}</ul>@@ -202,41 +256,6 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact,{dirty && <p role="status" className="text-sm">Save edits before preparing, approving or rendering.</p>}</div></details>- <details open={ready?.storyboard.approved && !ready?.proof.approved}>- <summary className="cursor-pointer min-h-[44px] py-2 text-sm">Animated chorus proof</summary>- <p className="text-sm">Author the approved storyboard in Compose, then render a 10–45 second chorus with its entry and exit. Watch with sound at normal speed and compare the chosen energy target and timed choreography below against the actual subject, props, camera, typography and transitions. Check accents against beat and lyric anchors, readable holds and repeated-chorus escalation. A strong static frame does not prove the motion works.</p>- <section aria-label="Saved choreography for proof comparison" className="rounded border border-port-border bg-port-bg p-3">- <h4 className="text-sm font-medium">Saved energy target and timed choreography</h4>- <p className="mt-1 whitespace-pre-wrap text-sm">{saved.motionLanguage || 'Save an energy target and timed choreography in the planning editor before judging the proof.'}</p>- <p className="mt-2 text-xs text-port-text-muted">Compare playback with this saved plan. If the chosen energy or actions are missing, record revision feedback with a time range before approving.</p>- </section>- <div id="mv-review-render" tabIndex={-1} style={{ scrollMarginTop: 'calc(var(--mv-header-h, 9rem) + 1rem)' }} className="flex flex-wrap items-end gap-2">- <label htmlFor={fieldId('proof-start')} className="text-sm">Proof start (seconds)<input id={fieldId('proof-start')} type="number" min="0" step="0.01" value={startSec} onChange={e => setStartSec(Number(e.target.value))} className={fieldClass} /></label>- <label htmlFor={fieldId('proof-end')} className="text-sm">Proof end (seconds)<input id={fieldId('proof-end')} type="number" min="0" step="0.01" value={endSec} onChange={e => setEndSec(Number(e.target.value))} className={fieldClass} /></label>- <button type="button" className={buttonClass} disabled={blocked || review.proof.occupied || review.proof.active} onClick={() => review.renderProof({ startSec, endSec, kind: 'prototype' })}>Render feasibility prototype — unapproved</button>- <button type="button" className={buttonClass} disabled={blocked || !ready?.storyboard.approved || review.proof.occupied || review.proof.active} onClick={() => review.renderProof({ startSec, endSec })}>Render animated proof</button>- </div>- {review.proof.occupied && !review.proof.active && <p role="status">Review evidence is rendering in another project. Wait for it to finish before starting another.</p>}- {review.proof.active && <p role="status">{review.proof.connected === false ? 'Connecting to review render…' : `Rendering review evidence — ${review.proof.percent ?? 0}%.`} Production approvals are separate.</p>}- <p className="text-xs text-port-text-muted">A feasibility prototype uses the current authored composition and master audio without approving the look or authorizing production. It can be made before art approval; it never becomes approved proof automatically.</p>- {prototype?.status === 'complete' && prototype.filename && <figure><video controls className="mt-2 w-full rounded" aria-label="Unapproved feasibility prototype" src={`/data/videos/${encodeURIComponent(prototype.filename)}`} /><figcaption className="text-sm">Unapproved feasibility prototype — separate from production proof</figcaption></figure>}- {excerpt?.status === 'complete' && excerpt.filename && <video controls className="mt-2 w-full rounded" aria-label="Animated proof with master audio" src={`/data/videos/${encodeURIComponent(excerpt.filename)}`} />}- {matchingRecordedReview && <section aria-label="Recorded proof review" className="rounded border border-port-border p-3">- <h4 className="text-sm font-medium">Recorded proof review</h4>- <p className="mt-1 whitespace-pre-wrap text-sm">{matchingRecordedReview.energyComparison}</p>- <p className="mt-2 whitespace-pre-wrap text-sm">{matchingRecordedReview.timecodedNotes}</p>- </section>}- <label htmlFor={fieldId('energy-comparison')} className="block text-sm">Playback energy compared with the saved plan- <textarea id={fieldId('energy-comparison')} rows={3} maxLength={4000} disabled={playbackBlocked} value={playback.energyComparison} onChange={e => setPlayback({ energyComparison: e.target.value })} className={fieldClass}- placeholder="Chosen energy target; observed subject, prop and camera activity; where playback matches or misses the intended arc." />- </label>- <label htmlFor={fieldId('playback-notes')} className="block text-sm">Timecoded playback notes- <textarea id={fieldId('playback-notes')} rows={3} maxLength={4000} disabled={playbackBlocked} value={playback.timecodedNotes} onChange={e => setPlayback({ timecodedNotes: e.target.value })} className={fieldClass}- placeholder="0:04 — subject turns on the downbeat; prop opens through 0:06; camera and type clear the lyric. Name any mismatch to revise." />- </label>- <p className="text-xs text-port-text-muted">Include at least one playback timestamp such as 0:04 or 4.5s. These notes are saved with this exact proof. A replacement proof requires a new comparison and acknowledgement.</p>- <label htmlFor={fieldId('watched')} className="flex gap-2 py-2 text-sm"><input id={fieldId('watched')} type="checkbox" checked={playback.watched}- disabled={playbackBlocked} onChange={e => setPlayback({ watched: e.target.checked })} />I watched this revision with audio at normal speed and compared its energy, timed choreography and lyric timing with the saved plan.</label>- </details>+</section>;}diff --git a/client/src/components/musicVideo/ProductionReviewPanel.test.jsx b/client/src/components/musicVideo/ProductionReviewPanel.test.jsxindex caa11dbf07..fdc3d67c6c 100644--- a/client/src/components/musicVideo/ProductionReviewPanel.test.jsx+++ b/client/src/components/musicVideo/ProductionReviewPanel.test.jsx@@ -1,7 +1,9 @@-import { describe, expect, it, vi } from 'vitest';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';import ProductionReviewPanel from './ProductionReviewPanel.jsx';+afterEach(() => { vi.unstubAllGlobals(); window.location.hash = ''; });+const acknowledgement = 'I watched this revision with audio at normal speed and compared its energy, timed choreography and lyric timing with the saved plan.';const project = {id: 'example-project', scenes: [], lyricCues: [], composition: { mode: 'document' },@@ -17,13 +19,56 @@ const reviewFixture = () => ({ readiness: {art: { approved: true, problems: [] }, storyboard: { approved: true, problems: [] }, proof: { approved: false, problems: [] },}, busy: false, proof: { active: false }, approve: vi.fn(), save: vi.fn(async () => null) });function recordPlayback() {- fireEvent.change(screen.getByLabelText('Instance password for this approval'), { target: { value: 'synthetic-password' } });+ fireEvent.loadedData(screen.getByLabelText('Animated proof with master audio'));fireEvent.change(screen.getByLabelText('Playback energy compared with the saved plan'), { target: { value: 'The driving turn matches the chosen energy.' } });fireEvent.change(screen.getByLabelText('Timecoded playback notes'), { target: { value: '0:04 — figure turns on the downbeat; prop follows at 4.5s.' } });fireEvent.click(screen.getByLabelText(acknowledgement));}describe('Production proof playback evidence', () => {+ it('shows the selected version before permitting art approval without password re-entry', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true })));+ const review = reviewFixture(); review.readiness.art.approved = false;+ const art = { ...project, devArtifacts: [{ id: 'guide', title: 'Synthetic visual guide', version: 2, mimeType: 'image/png' }],+ productionReview: { ...project.productionReview, draft: { ...project.productionReview.draft, guideArtifactId: 'guide' } } };+ render(<ProductionReviewPanel project={art} review={review} onOpenArtifact={vi.fn()} />);+ const approve = screen.getByRole('button', { name: 'Approve art direction' });+ expect(approve.disabled).toBe(true);+ const image = await screen.findByAltText('Synthetic visual guide v2');+ expect(image.getAttribute('src')).toContain('?version=2');+ fireEvent.load(image);+ expect(screen.queryByLabelText('Instance password for this approval')).toBeNull();+ fireEvent.click(approve);+ expect(review.approve).toHaveBeenCalledWith('art', undefined);+ fireEvent.error(image);+ expect(approve.disabled).toBe(true);+ expect(screen.getByRole('alert').textContent).toContain('could not be loaded');+ });++ it('shows the document shots beside storyboard approval and targets change requests to that stage', () => {+ const review = reviewFixture(); review.readiness.storyboard.approved = false;+ const doc = { ...project, composition: { mode: 'document', document: { directory: 'synthetic/doc-2' } },+ productionReview: { ...project.productionReview, draft: { ...project.productionReview.draft, storyboardSource: 'document',+ storyboard: [{ id: 'shot-a', label: 'Doorway', startSec: 0, endSec: 10, action: 'Open the doorway on the downbeat', camera: 'Push in', staging: 'Figure left', transition: 'Match cut', lyricCueIds: [] }] } } };+ render(<ProductionReviewPanel project={doc} review={review} onOpenArtifact={vi.fn()} />);+ const content = screen.getByLabelText('Storyboard review content');+ expect(content.textContent).toContain('1 document shots');+ expect(content.textContent).toContain('doc-2');+ expect(content.textContent).toContain('Open the doorway on the downbeat');+ fireEvent.click(within(content.closest('details')).getByRole('button', { name: 'Request changes' }));+ expect(screen.getByLabelText('Feedback stage').value).toBe('storyboard');+ expect(document.activeElement).toBe(screen.getByLabelText('Requested change'));+ expect(screen.getByLabelText('Requested change').closest('details').open).toBe(true);+ });++ it('keeps the hash-selected art context open when readiness arrives', () => {+ window.location.hash = '#mv-review-art';+ const review = reviewFixture();+ const view = render(<ProductionReviewPanel project={project} review={{ ...review, readiness: null }} onOpenArtifact={vi.fn()} />);+ view.rerender(<ProductionReviewPanel project={project} review={review} onOpenArtifact={vi.fn()} />);+ expect(document.getElementById('mv-review-art').open).toBe(true);+ });+it('shows the recorded review for an approved artifact without treating it as fresh playback evidence', () => {const review = reviewFixture();review.readiness.proof.approved = true;@@ -56,12 +101,21 @@ describe('Production proof playback evidence', () => {expect(screen.getByRole('button', { name: 'Approve animated proof' }).disabled).toBe(true);recordPlayback();fireEvent.click(screen.getByRole('button', { name: 'Approve animated proof' }));- expect(review.approve).toHaveBeenCalledWith('proof', 'synthetic-password', expect.objectContaining({+ expect(review.approve).toHaveBeenCalledWith('proof', expect.objectContaining({excerptId: id, filename, watchedWithAudio: true, energyComparison: 'The driving turn matches the chosen energy.',timecodedNotes: '0:04 — figure turns on the downbeat; prop follows at 4.5s.',}));});+ it('blocks approval and explains a failed proof player', () => {+ const review = reviewFixture();+ render(<ProductionReviewPanel project={project} review={review} onOpenArtifact={vi.fn()} />);+ recordPlayback();+ fireEvent.error(screen.getByLabelText('Animated proof with master audio'));+ expect(screen.getByRole('alert').textContent).toContain('could not be played');+ expect(screen.getByRole('button', { name: 'Approve animated proof' }).disabled).toBe(true);+ });+it('keeps failed choreography saves dirty and blocks playback acknowledgement and approval', async () => {const review = reviewFixture();render(<ProductionReviewPanel project={project} review={review} onOpenArtifact={vi.fn()} />);diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsxindex 40fb2bfbc3..cc5b0d4f5e 100644--- a/client/src/components/musicVideo/PublishPostingPanel.jsx+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx@@ -125,7 +125,6 @@ function TargetRow({ project, kit, entry, publishing }) {const { target, label, note } = entry;const idFor = (key) => `mv-post-${project.id}-${target}-${key}`;const [options, setOptions] = useState({});- const [password, setPassword] = useState('');const setOption = (key, value) => setOptions((prev) => ({ ...prev, [key]: value }));const draft = publishing.drafts[target];const busy = publishing.busy[target];@@ -138,9 +137,6 @@ function TargetRow({ project, kit, entry, publishing }) {return (<li className="rounded border border-port-border p-2 space-y-2"><p className="text-xs text-port-text-muted">Preparing a draft may upload files and save platform metadata. This is separate from production and never publishes.</p>- <label htmlFor={idFor('password')} className="block text-xs">Instance password to prepare {label}- <input id={idFor('password')} type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} className={inputCls} />- </label><div className="flex flex-wrap items-start justify-between gap-2"><div className="min-w-0"><div className="text-xs font-medium">{label}{account && <span className="font-normal text-port-text-muted"> as @{account}</span>}</div>@@ -151,7 +147,7 @@ function TargetRow({ project, kit, entry, publishing }) {</a>)}</div>- <button type="button" onClick={() => { publishing.prepare(target, { ...clean, password }); setPassword(''); }} disabled={!!busy || !password}+ <button type="button" onClick={() => publishing.prepare(target, clean)} disabled={!!busy}className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">{busy === 'prepare' ? 'Filling…' : (draft ? 'Fill again' : 'Fill draft')}</button>diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsxindex f417ff4683..338f9c5452 100644--- a/client/src/components/musicVideo/PublishPostingPanel.test.jsx+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx@@ -31,9 +31,8 @@ describe('PublishPostingPanel (#9282)', () => {const reddit = row('Reddit');fireEvent.change(within(reddit).getByLabelText('Subreddit'), { target: { value: 'SunoAI' } });fireEvent.change(within(reddit).getByLabelText('Post type'), { target: { value: 'link' } });- fireEvent.change(within(reddit).getByLabelText('Instance password to prepare Reddit'), { target: { value: 'synthetic-password' } });fireEvent.click(within(reddit).getByRole('button', { name: 'Fill draft' }));- expect(publishing.prepare).toHaveBeenCalledWith('reddit', { subreddit: 'SunoAI', kind: 'link', password: 'synthetic-password' });+ expect(publishing.prepare).toHaveBeenCalledWith('reddit', { subreddit: 'SunoAI', kind: 'link' });});it('shows the filled draft and requires manual platform publication', () => {diff --git a/client/src/hooks/useMusicVideoProductionReview.js b/client/src/hooks/useMusicVideoProductionReview.jsindex ee46ff9b44..a17a55b85d 100644--- a/client/src/hooks/useMusicVideoProductionReview.js+++ b/client/src/hooks/useMusicVideoProductionReview.js@@ -51,14 +51,14 @@ export default function useMusicVideoProductionReview({ project, replaceProject};return { readiness: state?.owner === project ? state.readiness : null, busy, error, proof: { ...proof, occupied: proof.active, active: proof.active && proof.context === project?.id },feedback: body => call(() => addMusicVideoProductionFeedback(project.id, { ...body, basis: state?.readiness.basis[body.stage] }, { silent: true })),- resolveFeedback: (feedbackId, resolution, password) => call(() => resolveMusicVideoProductionFeedback(project.id, { feedbackId, resolution, password }, { silent: true })),+ resolveFeedback: (feedbackId, resolution) => call(() => resolveMusicVideoProductionFeedback(project.id, { feedbackId, resolution }, { silent: true })),importDocumentShots: body => call(() => importMusicVideoDocumentShots(project.id, body, { silent: true })),importPlanning: source => call(() => importMusicVideoProductionPlanning(project.id, source, { silent: true })),bindShot: shotId => call(() => bindMusicVideoProductionShot(project.id, shotId, { silent: true })),save: draft => call(() => saveMusicVideoProductionDraft(project.id, draft, { silent: true })),prepare: () => call(() => prepareMusicVideoProductionReview(project.id, {}, { silent: true })),- approve: (stage, password, proofReview) => call(() => approveMusicVideoProductionReview(project.id,- { stage, password, basis: state?.readiness.basis[stage], ...(stage === 'proof' ? { proofReview } : {}) }, { silent: true })),+ approve: (stage, proofReview) => call(() => approveMusicVideoProductionReview(project.id,+ { stage, basis: state?.readiness.basis[stage], ...(stage === 'proof' ? { proofReview } : {}) }, { silent: true })),renderProof: window => proof.start({ id: project.id, window }, project.id),};}diff --git a/client/src/hooks/useMusicVideoPublishing.test.jsx b/client/src/hooks/useMusicVideoPublishing.test.jsxindex 09d18b8735..4b5c01b15e 100644--- a/client/src/hooks/useMusicVideoPublishing.test.jsx+++ b/client/src/hooks/useMusicVideoPublishing.test.jsx@@ -40,7 +40,6 @@ describe('music-video publishing project boundary', () => {const view = render(<Posting id="project-a" />);await screen.findByText('YouTube', { selector: 'div' });fireEvent.change(within(row('Reddit')).getByLabelText('Subreddit'), { target: { value: 'example-community' } });- fireEvent.change(screen.getByLabelText('Instance password to prepare YouTube'), { target: { value: 'synthetic-password' } });await act(async () => { fireEvent.click(within(row('YouTube')).getByRole('button', { name: 'Fill draft' })); });expect(screen.getByText('Example A')).toBeInTheDocument();@@ -60,10 +59,8 @@ describe('music-video publishing project boundary', () => {api.submitMusicVideoPublishDraft.mockResolvedValue({ post: { url: 'https://example.com/post' } });const view = render(<Posting id="project-a" />);await screen.findByText('YouTube', { selector: 'div' });- fireEvent.change(screen.getByLabelText('Instance password to prepare YouTube'), { target: { value: 'synthetic-password' } });fireEvent.click(within(row('YouTube')).getByRole('button', { name: 'Fill draft' }));view.rerender(<Posting id="project-b" />);- fireEvent.change(screen.getByLabelText('Instance password to prepare YouTube'), { target: { value: 'synthetic-password' } });fireEvent.click(within(row('YouTube')).getByRole('button', { name: 'Fill draft' }));await act(async () => { first.resolve({ draftId: 'draft-a', summary: { title: 'Example A' } }); });expect(screen.queryByText('Example A')).not.toBeInTheDocument();@@ -72,7 +69,7 @@ describe('music-video publishing project boundary', () => {expect(screen.getByText('Example B')).toBeInTheDocument();expect(screen.queryByRole('button', { name: 'Post to YouTube' })).not.toBeInTheDocument();expect(api.submitMusicVideoPublishDraft).not.toHaveBeenCalled();- expect(screen.getByLabelText('Instance password to prepare YouTube')).toHaveValue('');+ expect(screen.queryByLabelText('Instance password to prepare YouTube')).toBeNull();});it('ignores an old-project sign-in error after switching away and back', async () => {@@ -80,14 +77,12 @@ describe('music-video publishing project boundary', () => {api.prepareMusicVideoPublishDraft.mockReturnValueOnce(first.promise);const view = render(<Posting id="project-a" />);await screen.findByText('YouTube', { selector: 'div' });- fireEvent.change(screen.getByLabelText('Instance password to prepare YouTube'), { target: { value: 'synthetic-password' } });fireEvent.click(within(row('YouTube')).getByRole('button', { name: 'Fill draft' }));view.rerender(<Posting id="project-b" />);view.rerender(<Posting id="project-a" />);await act(async () => { first.reject({ message: 'Example sign-in required', code: 'PUBLISH_LOGIN_REQUIRED' }); });expect(screen.queryByRole('alert')).not.toBeInTheDocument();- expect(screen.getByLabelText('Instance password to prepare YouTube')).toHaveValue('');- fireEvent.change(screen.getByLabelText('Instance password to prepare YouTube'), { target: { value: 'synthetic-password' } });+ expect(screen.queryByLabelText('Instance password to prepare YouTube')).toBeNull();expect(within(row('YouTube')).getByRole('button', { name: 'Fill draft' })).toBeEnabled();});});diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.jsindex 0c6fd1badf..7f440b7487 100644--- a/client/src/lib/musicVideoAutonomous.js+++ b/client/src/lib/musicVideoAutonomous.js@@ -26,7 +26,7 @@ export const AUTONOMOUS_CHECKPOINT_LABELS = Object.freeze({export const AUTONOMOUS_AUTO_APPROVE_LABELS = Object.freeze({ art: 'Art', storyboard: 'Storyboard', proof: 'Proof' });export const AUTONOMOUS_STATUS_LABELS = Object.freeze({- running: 'Running', 'awaiting-approval': 'Waiting for your approval', 'needs-human': 'Needs you', stopped: 'Paused',+ running: 'Running', 'awaiting-approval': 'Awaiting review', 'needs-human': 'Needs attention', stopped: 'Paused',completed: 'Finished', failed: 'Failed', canceled: 'Cancelled',});diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex c678e9e188..a5fad124f9 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -343,6 +343,8 @@ const renderMVWithNav = (to) => render(</MemoryRouter>,);+afterEach(() => vi.restoreAllMocks());+beforeEach(() => {// Keep the real artifact iframe and src assertions without navigating to its API URL.window.happyDOM.settings.navigation.disableChildFrameNavigation = true;@@ -1781,6 +1783,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {});it('opens a development file from its deep link in a sandboxed viewer', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true });const sheet = {id: 'mvd-1', kind: 'cast-sets', title: 'Cast & Sets — Nova', status: 'approved', version: 2, mimeType: 'text/html', updatedAt: '2026-01-02T00:00:00Z',versions: [{ version: 1, mimeType: 'text/html', source: 'upload', createdAt: '2026-01-01T00:00:00Z' }, { version: 2, mimeType: 'text/html', source: 'upload', createdAt: '2026-01-02T00:00:00Z' }],@@ -2504,8 +2507,8 @@ describe('direct production review navigation', () => {fireEvent.click(screen.getByRole('button', { name: 'Review art direction' }));expect(art).toHaveFocus();expect(screen.getByRole('button', { name: 'Approve art direction' })).toBeDisabled();- fireEvent.click(screen.getByRole('button', { name: 'Enter your password to enable approval' }));- expect(screen.getByLabelText('Instance password for this approval')).toHaveFocus();+ expect(screen.getByText('No current visual guide selected. Choose a Development file in the planning editor below.')).toBeInTheDocument();+ expect(screen.queryByLabelText('Instance password for this approval')).toBeNull();fireEvent.click(screen.getByRole('button', { name: 'go--1' }));expect(screen.getByTestId('loc')).toHaveTextContent('/review');fireEvent.click(screen.getByRole('button', { name: 'go-1' }));diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.mdindex f6091c9fbf..c79fd9c5d3 100644--- a/docs/features/music-video-autonomous.md+++ b/docs/features/music-video-autonomous.md@@ -1,6 +1,6 @@# Autonomous Music Video-One prompt in, a finished music video out. The Music Video page's **Autonomous** entry point (and the `music-video-autopilot` scheduled task) starts a server-owned run that does everything the hand-driven flow asks you to set up first: it writes the creative brief, the lyrics and a mood board, makes the song (in Suno, or on this machine), and produces the video with the tools you allowed. Song-writing checkpoints are optional. Production always pauses for revision-bound human review of the visual guide, lyric-timed storyboard and animated proof.+One prompt in, a finished music video out. The Music Video page's **Autonomous** entry point (and the `music-video-autopilot` scheduled task) starts a server-owned run that does everything the hand-driven flow asks you to set up first: it writes the creative brief, the lyrics and a mood board, makes the song (in Suno, or on this machine), and produces the video with the tools you allowed. Song-writing checkpoints are optional. Production requires revision-bound approval of the visual guide, lyric-timed storyboard and animated proof. Authenticated sessions may grant automatic planning approvals; proof always needs substantive playback or machine review evidence.## Pipeline@@ -16,7 +16,7 @@ brief → lyrics → style → song → analyze → produce| `song` | The PortOS Browser drives the Suno web UI (custom mode: lyrics, style, title), only M4A is selected in Suno's Download UI and the completed audio is validated and imported directly into the music library, a Track is created, the take is recorded with `source: 'suno'`, and the project is linked to it. | Suno credits || `song` (local) | `songSource: 'local'` renders the song with the on-device Music Designer engines instead (see [Local song source](#local-song-source)). | free (GPU time) || `analyze` | The usual offline beat / tempo / section analysis. | free |-| `produce` | **Footage** (any image/video tool picked): the existing server-owned production run (`/production-runs`) with a pool built from the picks, then the final render once it completes. **Code** (only `code:render`): a code-rendered video is authored after storyboard approval, renders a review proof, then waits for human proof approval before the final render. | per tool |+| `produce` | **Footage** (any image/video tool picked): the existing server-owned production run (`/production-runs`) with a pool built from the picks, then the final render once it completes. **Code** (only `code:render`): a code-rendered video is authored after storyboard approval, renders a review proof, then waits for an authenticated reviewer’s proof approval before the final render. | per tool |State lives on the project as `autonomousRun` — install-local like `productionRuns` (stripped from the peer wire, not carried into a clone). Each stage settles in one serialized project write, so a crash resumes at the stage that did not settle. After a server restart a run is shown **interrupted** and nothing advances until you resume it (no cold-bootstrap provider calls).@@ -76,15 +76,19 @@ The **Production review** panel is shared by the manual and autopilot paths. PreImported storyboard shots may remain unbound. Bind each to an existing Board scene or explicitly create its scene; an import never invents approval or verifies provisional timings. Vocal songs require bounded positive-duration word timings checked against the current master. An instrumental exception requires a rationale and cannot mask existing lyric cues.-Art, storyboard and proof decisions bind to exact content. Changes invalidate affected downstream approvals. Targeted comments and requests for changes retain the original reviewed draft and scene snapshot; unresolved requests block the affected stage. Accepting structure records organizational agreement only. Regeneration receives unresolved feedback, and a human must resolve it and approve the revised content.+Art, storyboard and proof decisions bind to exact content. Changes invalidate affected downstream approvals. Targeted comments and requests for changes retain the original reviewed draft and scene snapshot; unresolved requests block the affected stage. Accepting structure records organizational agreement only. Regeneration receives unresolved feedback; an authenticated reviewer must resolve it and approve the revised content.Use **Render feasibility prototype — unapproved** to test a current authored composition before committing to its art direction. This makes a local 1–45 second excerpt and never grants production approval. After art and storyboard approval, render a 10–45 second representative chorus proof, watch with audio and approve that revision. Autopilot pauses at the same boundaries; queued provider work and final renders recheck approval before dispatch.-Approval and feedback resolution require the operator to re-enter the existing instance password. Agent bearer credentials cannot authorize those operations. Password-free installs can draft and prototype; setting a password is required before production approval. This separates delegated agent credentials from operator authority; it does not defend against someone who controls the host or knows the password.+Approval and feedback resolution use an existing authenticated PortOS session: browser cookies and agent bearer sessions have the same creative-review authority, without password re-entry. Missing, invalid, expired or revoked sessions cannot approve; auth-off and peer/Basic access do not confer creative-review authority. The server records the verified session ID and label, never the credential, along with revision-bound decision history. A shared agent session identifies the credential, not an individual agent or a human. Older clients may send a password, but it is discarded rather than used as approval authority.-**Auto-approve the rest.** A run can be told once which of these stages it may approve itself: `autoApprove: ['art', 'storyboard', 'proof']` (any subset) on the start request or on `POST /api/music-video/:id/autonomous/resume`, together with `password` — the instance password, entered by the operator once on that request with the same checks as an approval (no `Authorization` header; a missing or wrong password is 403 `OPERATOR_REAUTH_REQUIRED`). The password is never stored; the run records the grant as `brief.autoApprove` and `brief.autoApproveAuthorizedAt`. A resume's list replaces the stored grant (`[]` clears it, no password needed). In **Produce** the run then approves art and the storyboard (`approvedBy: 'autopilot'`) only when that stage's readiness report has no problems — anything a human must fix, such as provisional lyric timings, still parks the run `needs-human` — and, for a code-rendered video, waits for the proof excerpt to finish rendering (up to 90 minutes; a failed render fails the run) and approves that exact excerpt with an `autoApproved` proof review instead of a watched-with-audio record. The approval HTTP route never accepts an `autoApproved` review. Footage runs still approve their proof in production review. Start drawer and run panel offer the same choice as **Auto-approve** chips with a password field.+The review panel shows the selected visual guide and its version, the saved storyboard shots and timing (including document manifests independently of Board scenes), or the exact registered proof before the decision. Reference contact sheets are labeled separately because they may predate the current document. Missing files and failed proof playback show a recovery action and block the corresponding UI approval. **Request changes** opens feedback for that review stage.-External draft preparation also requires operator reauthentication. PortOS never submits a final post: review and publish on the destination platform, then record the resulting link. Existing projects and assets remain intact, but an older project's final render now requires the same production review.+Proof requires an energy comparison and timecoded notes bound to its exact excerpt ID and filename. Human playback uses `watchedWithAudio: true`. An authenticated agent can submit `method: 'machine'`, `watchedWithAudio: false`, and `machineEvidence` containing substantive `visualReview`, `audioReview`, and `limitations`, alongside the same energy comparison, timecoded notes, excerpt ID and filename. The observations must come from actual motion and audio review against the saved plan; technical validation, isolated still frames or a completed render do not establish choreography quality. If the available tools cannot assess motion and audio, leave approval pending. The UI distinguishes machine review from playback. Persisted automatic waivers no longer count as approved proof; valid art and playback decisions remain valid.++**Automatic planning approvals.** An authenticated start or `POST /api/music-video/:id/autonomous/resume` can grant `autoApprove: ['art', 'storyboard']` (any subset). The run records `brief.autoApprove`, `brief.autoApproveAuthorizedAt`, and `brief.autoApproveAuthorizedBy`; automatic decisions also record the run ID. A resume list replaces the grant; explicit `[]` revokes it and also requires authentication. Omitting the list preserves the existing policy. In **Produce**, automatic planning approval requires a clean readiness report; provisional timings or other open problems still park the run. Proof always requires a substantive review. Legacy briefs listing `proof` may wait for its render to finish (up to 90 minutes) but then park for review rather than manufacturing evidence or automatically starting the final render. Start drawer and run panel expose the planning choices without a password field, and the run panel shows existing grants so they can be revoked.++External draft preparation uses the existing authenticated session without password re-entry; agents may prepare drafts. PortOS never submits a final post: review and publish on the destination platform, then record the resulting link. Existing projects and assets remain intact, but an older project's final render now requires the same production review.The local browser acceptance test (`server/routes/musicVideoProductionReview.browser.test.js`) exercises the real React controls, approval routes, native code renderer, ffmpeg output and video playback with synthetic data. It requires Chrome, ffmpeg and installed client dependencies; server-only CI skips this cross-workspace check. API and orchestration tests run independently of those visual-test prerequisites.@@ -131,9 +135,9 @@ The Suno adapter fills the form through `placeholder` / role selectors and reads| Method | Path | ||---|---|---|-| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `songSource` (`suno` default, or `local`), `localFallback`, `suno` (Suno form options), `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model`/`effort` (the direction LLM), `llmStages` (per-stage LLM pins), `lyricsReview`, `authoring` (code-rendered video), `autoApprove` (+ `password`, see Production review). |+| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `songSource` (`suno` default, or `local`), `localFallback`, `suno` (Suno form options), `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model`/`effort` (the direction LLM), `llmStages` (per-stage LLM pins), `lyricsReview`, `authoring` (code-rendered video), `autoApprove` (authenticated planning grant, see Production review). || `GET` | `/api/music-video/:id/autonomous` | The run. |-| `POST` | `/api/music-video/:id/autonomous/resume` | Approve the checkpoint, retry the stage that stopped, or resume an interrupted run. Optional `lyrics`, `style`, `suno` edits; `retakeSong: true` at the song checkpoint; `autoApprove` (+ `password`) to grant auto-approval of production review stages. |+| `POST` | `/api/music-video/:id/autonomous/resume` | Approve the checkpoint, retry the stage that stopped, or resume an interrupted run. Optional `lyrics`, `style`, `suno` edits; `retakeSong: true` at the song checkpoint; `autoApprove` to grant or revoke automatic planning approvals using the authenticated session. || `POST` | `/api/music-video/:id/autonomous/stop` / `cancel` | Pause / cancel (also stops/cancels its production run). |Progress is pushed over the `music-video:autonomous` socket event (`{ projectId, runId, run, project }`).diff --git a/scripts/vitestCiPool.test.js b/scripts/vitestCiPool.test.jsindex 3210ff6801..2b06b6b837 100644--- a/scripts/vitestCiPool.test.js+++ b/scripts/vitestCiPool.test.js@@ -42,6 +42,7 @@ describe('vitestCiPool', () => {it('leaves local runs unbounded', () => {delete process.env.CI;+ delete process.env.PORTOS_PREGATE_MAX_WORKERS;expect(vitestCiPool()).toEqual({});});diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex c8fc2cc09d..447819cf9f 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -790,7 +790,7 @@ export const musicVideoLlmStagesSchema = z.object(Object.fromEntries(// Production review stages the run may approve by itself (de-duplicated, in// review order). A non-empty list is approval authority, so the request must-// carry the instance password once (checked by the route, never stored); an+// use an authenticated session (checked by the route); an// empty list on resume clears the grant.const musicVideoAutoApproveFields = {autoApprove: z.array(z.enum(AUTONOMOUS_AUTO_APPROVE_STAGES)).max(AUTONOMOUS_AUTO_APPROVE_STAGES.length * 4)@@ -1071,9 +1071,15 @@ export const musicVideoDocumentShotsSchema = z.object({export const musicVideoProductionImportSchema = z.object({ source: z.string().min(2).max(250000) }).strict();export const musicVideoProductionApprovalSchema = z.object({stage: z.enum(['art', 'storyboard', 'proof']), basis: z.string().min(1).max(128),- password: z.string().min(1).max(1024),+ password: z.string().max(1024).optional(),proofReview: z.object({- watchedWithAudio: z.literal(true),+ method: z.enum(['playback', 'machine']).optional(),+ watchedWithAudio: z.boolean(),+ machineEvidence: z.object({+ visualReview: z.string().trim().min(40).max(8000),+ audioReview: z.string().trim().min(40).max(8000),+ limitations: z.string().trim().min(1).max(4000),+ }).strict().optional(),excerptId: z.string().min(1).max(200), filename: z.string().min(1).max(200),energyComparison: z.string().trim().min(1).max(4000),timecodedNotes: z.string().trim().min(1).max(4000)@@ -1280,5 +1286,5 @@ export const musicVideoProductionFeedbackSchema = z.object({decision: z.enum(['comment', 'structure-accepted', 'request-changes']),}).strict();export const musicVideoProductionFeedbackResolutionSchema = z.object({- feedbackId: z.string().min(1).max(128), resolution: z.string().trim().min(1).max(8000), password: z.string().min(1).max(1024),+ feedbackId: z.string().min(1).max(128), resolution: z.string().trim().min(1).max(8000), password: z.string().max(1024).optional(),}).strict();diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 6b36961542..d065551a2d 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -12,7 +12,7 @@ import { existsSync } from 'fs';import { unlink } from 'fs/promises';import { Router } from 'express';import { musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema } from '../lib/musicVideoValidation.js';-import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionOperator, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback } from '../services/musicVideo/productionReviewService.js';+import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback } from '../services/musicVideo/productionReviewService.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import {validateRequest,@@ -502,8 +502,8 @@ router.post('/:id/production-review/feedback', asyncHandler(async (req, res) =>}));router.post('/:id/production-review/feedback/resolve', asyncHandler(async (req, res) => {const input = validateRequest(musicVideoProductionFeedbackResolutionSchema, req.body);- await requireProductionOperator(req);- res.json(await closeProductionFeedback(req.params.id, { feedbackId: input.feedbackId, resolution: input.resolution }));+ const reviewer = await requireProductionReviewer(req);+ res.json(await closeProductionFeedback(req.params.id, { feedbackId: input.feedbackId, resolution: input.resolution, reviewer }));}));router.get('/:id/production-review', asyncHandler(async (req, res) => {res.json(await getProductionReview(req.params.id));@@ -531,8 +531,8 @@ router.post('/:id/production-review/prepare', asyncHandler(async (req, res) => {}));router.post('/:id/production-review/approve', asyncHandler(async (req, res) => {const input = validateRequest(musicVideoProductionApprovalSchema, req.body);- await requireProductionOperator(req);- res.json(await approveProductionReview(req.params.id, { stage: input.stage, basis: input.basis, proofReview: input.proofReview }));+ const reviewer = await requireProductionReviewer(req);+ res.json(await approveProductionReview(req.params.id, { stage: input.stage, basis: input.basis, proofReview: input.proofReview, reviewer }));}));router.post('/:id/production-review/proof', asyncHandler(async (req, res) => {res.status(202).json(await renderProductionProof(req.params.id, validateRequest(musicVideoProductionProofSchema, req.body)));@@ -748,7 +748,7 @@ router.put('/:id/publish/posts/:target', asyncHandler(async (req, res) => {router.post('/:id/publish/:target/prepare', asyncHandler(async (req, res) => {const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);- await requireProductionOperator(req);+ await requireProductionReviewer(req);const { password: _password, ...body } = req.body || {};const options = validateRequest(musicVideoPublishPrepareSchema, body);res.json(await preparePublishDraft(req.params.id, target, options));@@ -898,12 +898,10 @@ router.post('/:id/production-runs/:runId/cancel', asyncHandler(async (req, res)// `music-video:autonomous`. Optional checkpoints park it for approval. Only these// explicit requests (or the scheduled task) begin work — nothing at boot does.// A non-empty `autoApprove` lets the run approve those Production review stages-// itself. That is the operator's authority, so the request re-enters the-// instance password once (same check as an approval; never stored).+// itself. Bind the grant to the authenticated session; proof still needs review evidence.const authorizeAutoApprove = async (req, autoApprove) => {- if (!autoApprove?.length) return false;- await requireProductionOperator(req);- return true;+ if (autoApprove === undefined) return false;+ return requireProductionReviewer(req);};router.post('/autonomous', asyncHandler(async (req, res) => {const { password: _password, ...input } = validateRequest(musicVideoAutonomousStartSchema, req.body || {});diff --git a/server/routes/musicVideoAutonomous.test.js b/server/routes/musicVideoAutonomous.test.jsindex 984e33dc67..b6e82d9dea 100644--- a/server/routes/musicVideoAutonomous.test.js+++ b/server/routes/musicVideoAutonomous.test.js@@ -27,8 +27,10 @@ vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({}))vi.mock('../services/musicVideo/productionReviewService.js', async load => ({...await load(), prepareProductionReview: vi.fn(async () => {}),}));+const auth = vi.hoisted(() => ({ authenticated: true }));vi.mock('../services/auth.js', () => ({isAuthEnabled: async () => true,+ verifyRequestSessionIdentity: async req => auth.authenticated ? { kind: 'session', sessionId: 'fixture-session', label: req.headers.authorization ? 'agent' : null } : null,verifyPassword: async password => password === 'synthetic-operator-password',}));@@ -218,27 +220,23 @@ describe('POST /api/music-video/autonomous', () => {});});- it('grants auto-approve only with the operator password: none, a wrong one or an agent credential is 403 and changes nothing', async () => {+ it('requires a session for approval grants and audits an agent grant without storing legacy passwords', async () => {const res = await begin({ prompt: 'p', checkpoints: ['lyrics'] });const id = res.body.project.id;await settle();- const resume = (body) => request(app).post(`/api/music-video/${id}/autonomous/resume`).send(body);- for (const body of [{ autoApprove: ['art', 'storyboard'] }, { autoApprove: ['proof'], password: 'wrong' }]) {- const refused = await resume(body);- expect(refused.status, JSON.stringify(body)).toBe(403);- expect(refused.body.code).toBe('OPERATOR_REAUTH_REQUIRED');- }- const agent = await request(app).post(`/api/music-video/${id}/autonomous/resume`).set('authorization', 'Bearer synthetic-agent')- .send({ autoApprove: ['art'], password: 'synthetic-operator-password' });- expect(agent.status).toBe(403);- expect((await begin({ prompt: 'p', autoApprove: ['art'] })).status).toBe(403);+ auth.authenticated = false;+ const denied = await request(app).post(`/api/music-video/${id}/autonomous/resume`).send({ autoApprove: ['art'], password: 'synthetic-operator-password' });+ expect(denied.status).toBe(401);+ expect((await request(app).post(`/api/music-video/${id}/autonomous/resume`).send({ autoApprove: [] })).status).toBe(401);expect((await get(id))).toMatchObject({ status: 'awaiting-approval', brief: { autoApprove: [] } });-- const granted = await resume({ autoApprove: ['storyboard', 'art', 'art'], password: 'synthetic-operator-password' });+ auth.authenticated = true;+ const granted = await request(app).post(`/api/music-video/${id}/autonomous/resume`).set('authorization', 'Bearer synthetic-agent')+ .send({ autoApprove: ['storyboard', 'art', 'art'], password: 'synthetic-operator-password' });expect(granted.status).toBe(200);await settle();const stored = await projects.getProject(id);- expect(stored.autonomousRun.brief).toMatchObject({ autoApprove: ['art', 'storyboard'], autoApproveAuthorizedAt: expect.any(String) });+ expect(stored.autonomousRun.brief).toMatchObject({ autoApprove: ['art', 'storyboard'], autoApproveAuthorizedAt: expect.any(String),+ autoApproveAuthorizedBy: { kind: 'session', sessionId: 'fixture-session', label: 'agent' } });expect(JSON.stringify(stored)).not.toContain('synthetic-operator-password');});diff --git a/server/routes/musicVideoProductionReview.browser.test.js b/server/routes/musicVideoProductionReview.browser.test.jsindex 3e595e47c6..38b586f7bb 100644--- a/server/routes/musicVideoProductionReview.browser.test.js+++ b/server/routes/musicVideoProductionReview.browser.test.js@@ -13,7 +13,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('mv-review-browser-') }));vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: async () => 'synthetic-instance' }));vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}) }));-vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => true, verifyPassword: async p => p === 'synthetic-password' }));+vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => true, verifyPassword: async p => p === 'synthetic-password', verifyRequestSessionIdentity: async () => ({ kind: 'session', sessionId: 'synthetic-browser', label: null }) }));let endpoint;vi.mock('../services/browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));const { findFfmpeg } = await import('../lib/ffmpeg.js');@@ -97,8 +97,17 @@ describe.skipIf(!canRun)('production review in a real browser (Chrome, ffmpeg anconst page = await browser.newPage({ viewport: { width: 1280, height: 1000 } });const errors = []; page.on('pageerror', e => errors.push(e.message));await page.goto(`http://127.0.0.1:${server.address().port}`);- const password = page.getByLabel('Instance password for this approval');- await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve art direction', exact: true }).click();+ expect(await page.locator('input[type=password]').count()).toBe(0);+ await page.getByRole('button', { name: 'Approve art direction', exact: true }).waitFor();+ await page.waitForFunction(() => ![...document.querySelectorAll('button')].find(b => b.textContent === 'Approve art direction')?.disabled);+ if (process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR) {+ await mkdir(process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR, { recursive: true });+ await page.setViewportSize({ width: 390, height: 844 });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);+ await page.screenshot({ path: join(process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR, 'art-context-mobile.png'), fullPage: true });+ await page.setViewportSize({ width: 1280, height: 1000 });+ }+ await page.getByRole('button', { name: 'Approve art direction', exact: true }).click();await page.getByText('Review feedback and revision history', { exact: true }).click();await page.getByLabel('Feedback stage').selectOption('storyboard');await page.getByLabel('Feedback target').fill('shot: chorus / operator');@@ -107,11 +116,11 @@ describe.skipIf(!canRun)('production review in a real browser (Chrome, ffmpeg anawait page.getByText('Move the operator behind the threshold at the exit.', { exact: true }).waitFor();expect(await page.getByRole('button', { name: 'Approve lyric-timed storyboard' }).isDisabled()).toBe(true);await page.getByLabel('Resolution for shot: chorus / operator').fill('Reviewed the updated staging in the storyboard.');- await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Resolve feedback after review' }).click();+ await page.getByRole('button', { name: 'Resolve feedback after review' }).click();await page.getByText('Resolution: Reviewed the updated staging in the storyboard.', { exact: true }).waitFor();const beforeBoard = await page.evaluate(async id => (await fetch('/api/music-video/' + id + '/production-review')).json(), p.id);expect(beforeBoard.readiness.storyboard.problems).toEqual([]);- await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve lyric-timed storyboard' }).click();+ await page.getByRole('button', { name: 'Approve lyric-timed storyboard' }).click();await page.getByRole('button', { name: 'Render animated proof' }).click();await page.locator('video').waitFor({ timeout: 120000 });await page.locator('video').evaluate(async video => { await video.play(); await new Promise(r => setTimeout(r, 400)); video.pause(); });@@ -119,7 +128,7 @@ describe.skipIf(!canRun)('production review in a real browser (Chrome, ffmpeg anawait page.getByLabel('Playback energy compared with the saved plan').fill('The synthetic fixture demonstrates a driving chorus: the modeled subject changes pose and travels while the camera moves through the scene.');await page.getByLabel('Timecoded playback notes').fill('0:02 — subject enters the frame; 0:07 — pose and camera position differ and readable type remains clear. This is a synthetic workflow test, not artistic approval of a production video.');await page.getByLabel('I watched this revision with audio at normal speed and compared its energy, timed choreography and lyric timing with the saved plan.').check();- await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve animated proof' }).click();+ await page.getByRole('button', { name: 'Approve animated proof' }).click();await page.waitForFunction(() => [...document.querySelectorAll('[role=status]')].filter(el => el.textContent === 'Approved for this revision').length === 3);const result = await store.getProject(p.id);expect(result.productionReview.feedback[0].resolvedAt).toBeTruthy();diff --git a/server/routes/musicVideoProductionReview.test.js b/server/routes/musicVideoProductionReview.test.jsindex ae9dfa7994..6cd0afd6b5 100644--- a/server/routes/musicVideoProductionReview.test.js+++ b/server/routes/musicVideoProductionReview.test.js@@ -15,13 +15,18 @@ vi.mock('../services/promptRunner.js', () => ({},}));+const prepareExternalDraft = vi.hoisted(() => vi.fn(async () => ({ draftId: 'synthetic-external-draft' })));+vi.mock('../services/musicVideo/publish/index.js', async original => ({ ...await original(), preparePublishDraft: prepareExternalDraft }));+const ROOT = () => lazyTempDataRoot('mv-production-review-');vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: ROOT }));vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));const planner = vi.hoisted(() => vi.fn());vi.mock('../services/musicVideo/planner.js', () => ({ planProject: planner }));-const auth = vi.hoisted(() => ({ enabled: true }));-vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => auth.enabled, verifyPassword: async password => password === 'synthetic-operator-password' }));+const auth = vi.hoisted(() => ({ enabled: true, authenticated: true }));+vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => auth.enabled, verifyPassword: async password => password === 'synthetic-operator-password',+ verifyRequestSessionIdentity: async req => auth.authenticated && req.headers.authorization !== 'Bearer expired'+ ? { kind: 'session', sessionId: req.headers.authorization ? 'shared-agent-session' : 'browser-session', label: req.headers.authorization ? 'agent' : null } : null }));vi.mock('../services/musicVideo/excerptRender.js', async original => ({ ...await original(),startExcerptRender: vi.fn(async (id, window, options) => {const store = await import('../services/musicVideo/projects.js');@@ -49,11 +54,11 @@ async function approve(stage, extra = {}) {energyComparison: 'The playful energy target reads clearly in the subject and camera action.',timecodedNotes: '0:04 doorway opens on the accent; 0:12 the second gesture grows in scale.' } : undefined;return request(app).post(`${base}/production-review/approve`).send({ stage, proofReview,- basis: status.body.readiness.basis[stage], password: 'synthetic-operator-password', ...extra });+ basis: status.body.readiness.basis[stage], ...extra });}beforeEach(async () => {- auth.enabled = true;+ auth.enabled = true; auth.authenticated = true;author.calls = 0; author.sections = [];project = await store.createProject({ name: 'Example animation', uploadedAudioFilename: 'synthetic-song.wav', composition: { mode: 'code' } });base = `/api/music-video/${project.id}`;@@ -103,14 +108,22 @@ describe('human-reviewed Music Video workflow', () => {expect(repeated.scenes).toEqual(beforeRepeat.scenes);});- it('refuses API credentials, password-free approval, stale revisions and final-render bypasses', async () => {+ it('accepts authenticated browser and agent sessions, denies missing/expired/auth-off authority and stale revisions', async () => {const status = await read();- const body = { stage: 'art', basis: status.body.readiness.basis.art, password: 'synthetic-operator-password' };- expect((await request(app).post(`${base}/production-review/approve`).set('authorization', 'Bearer synthetic-agent').send(body)).status).toBe(403);- expect((await approve('art', { password: 'wrong' })).status).toBe(403);+ const body = { stage: 'art', basis: status.body.readiness.basis.art };+ auth.authenticated = false;+ expect((await approve('art', { password: 'synthetic-operator-password' })).status).toBe(401);+ auth.authenticated = true;+ expect((await request(app).post(`${base}/production-review/approve`).set('authorization', 'Bearer expired').send(body)).status).toBe(401);auth.enabled = false;- expect((await approve('art')).body.code).toBe('OPERATOR_PASSWORD_REQUIRED');+ expect((await approve('art')).body.code).toBe('AUTH_REQUIRED');auth.enabled = true;+ expect((await approve('art')).status).toBe(200);+ expect((await request(app).post(`${base}/production-review/approve`).set('authorization', 'Bearer synthetic-agent').send(body)).status).toBe(200);+ const reviewed = await store.getProject(project.id);+ expect(reviewed.productionReview.approvalHistory.map(a => a.reviewer.sessionId)).toEqual(['browser-session', 'shared-agent-session']);+ expect(reviewed.productionReview.approvals.art.reviewer).toMatchObject({ kind: 'session', label: 'agent' });+ expect((await approve('art', { reviewer: { kind: 'human' } })).status).toBe(400);await save({ ...draft, motionLanguage: 'A different motion direction' });expect((await request(app).post(`${base}/production-review/approve`).send(body)).status).toBe(409);expect((await request(app).patch(base).send({ productionReview: { approvals: { proof: true } } })).status).toBe(400);@@ -155,23 +168,29 @@ describe('human-reviewed Music Video workflow', () => {expect((await request(app).post(`${base}/render`).send({})).status).toBe(409);});- it('accepts an autonomous run\'s auto-approved proof for the current excerpt only, and never over HTTP', async () => {- expect((await approve('art')).status).toBe(200);- expect((await approve('storyboard')).status).toBe(200);- expect((await request(app).post(`${base}/production-review/proof`).send({ startSec: 0, endSec: 20 })).status).toBe(202);- const autoReview = { autoApproved: true, watchedWithAudio: false, excerptId: 'proof-fixture', filename: 'synthetic-proof.mp4',- energyComparison: 'Auto-approved by the autonomous run (brief.autoApprove).', timecodedNotes: '0:00 auto-approved' };- // The operator route cannot claim the waiver, even with the password.- expect((await approve('proof', { proofReview: autoReview })).status).toBe(400);+ it('records substantive machine proof evidence without claiming human playback and refuses automatic waivers', async () => {+ await approve('art'); await approve('storyboard');+ await request(app).post(`${base}/production-review/proof`).send({ startSec: 0, endSec: 20 });+ const machine = { method: 'machine', watchedWithAudio: false, excerptId: 'proof-fixture', filename: 'synthetic-proof.mp4',+ energyComparison: 'The doorway expansion matches the rising chorus energy.', timecodedNotes: '0:04 doorway opens on the accent; 0:12 the second gesture grows.',+ machineEvidence: { visualReview: 'Continuous synthetic sequence review: the doorway expands and the figure travels without jumps.',+ audioReview: 'Synthetic master comparison: the doorway opening coincides with the chorus accent at 0:04.',+ limitations: 'Synthetic test observations; not a review of any user video.' } };+ expect((await approve('proof', { proofReview: { ...machine, machineEvidence: undefined } })).body.code).toBe('MUSIC_VIDEO_PROOF_REVIEW_REQUIRED');+ expect((await approve('proof', { proofReview: { ...machine, watchedWithAudio: true } })).status).toBe(409);+ expect((await approve('proof', { proofReview: { ...machine, filename: 'older.mp4' } })).body.code).toBe('MUSIC_VIDEO_REVIEW_STALE');const current = await store.getProject(project.id);- const input = { stage: 'proof', basis: productionReviewBasis(current).proof, approvedBy: 'autopilot' };- expect(() => approveProductionStage(current, { ...input, proofReview: { ...autoReview, excerptId: 'older-proof' } }))- .toThrow(expect.objectContaining({ code: 'MUSIC_VIDEO_REVIEW_STALE' }));- expect(() => approveProductionStage(current, { ...input, proofReview: { ...autoReview, autoApproved: 'yes' } }))- .toThrow(expect.objectContaining({ code: 'MUSIC_VIDEO_PROOF_REVIEW_REQUIRED' }));- const approved = approveProductionStage(current, { ...input, proofReview: autoReview });- expect(approved.productionReview.approvals.proof).toMatchObject({ approvedBy: 'autopilot', proofReview: { autoApproved: true } });- expect(() => assertProductionApproval(approved)).not.toThrow();+ expect(() => approveProductionStage(current, { stage: 'proof', basis: productionReviewBasis(current).proof,+ proofReview: { ...machine, autoApproved: true } })).toThrow(expect.objectContaining({ code: 'MUSIC_VIDEO_PROOF_REVIEW_REQUIRED' }));+ expect((await request(app).post(`${base}/production-review/approve`).set('authorization', 'Bearer synthetic-agent')+ .send({ stage: 'proof', basis: productionReviewBasis(current).proof, proofReview: machine })).status).toBe(200);+ const accepted = await store.getProject(project.id);+ expect(accepted.productionReview.approvals.proof).toMatchObject({ reviewer: { sessionId: 'shared-agent-session', label: 'agent' }, proofReview: machine });+ expect(() => assertProductionApproval(accepted)).not.toThrow();+ const legacy = structuredClone(accepted);+ legacy.productionReview.approvals.proof.proofReview = { ...machine, autoApproved: true, machineEvidence: undefined };+ expect(() => assertProductionApproval(legacy)).toThrow(expect.objectContaining({ code: 'MUSIC_VIDEO_APPROVAL_REQUIRED' }));+ expect(legacy.productionReview.approvals.art).toEqual(accepted.productionReview.approvals.art);});it('distinguishes provisional/zero-length/missing lyrics from an explicit instrumental', async () => {@@ -282,8 +301,8 @@ describe('human-reviewed Music Video workflow', () => {expect(revised.body.project.productionReview.feedback.at(-1).resolvedAt).toBeUndefined();expect(revised.body.readiness.art.approved).toBe(true);expect(revised.body.readiness.storyboard.approved).toBe(false);- const resolution = { feedbackId: entry.id, resolution: 'Reviewed the revised staging.', password: 'synthetic-operator-password' };- expect((await request(app).post(`${base}/production-review/feedback/resolve`).set('authorization', 'Bearer synthetic-agent').send(resolution)).status).toBe(403);+ const resolution = { feedbackId: entry.id, resolution: 'Reviewed the revised staging.' };+ expect((await request(app).post(`${base}/production-review/feedback/resolve`).set('authorization', 'Bearer expired').send(resolution)).status).toBe(401);expect((await request(app).post(`${base}/production-review/feedback/resolve`).send(resolution)).status).toBe(200);expect((await read()).body.readiness.readyForProduction).toBe(false);await request(app).post(`${base}/production-review/import`).send({ source: JSON.stringify({ cast: 'Another proposal', storyboard: [] }) });@@ -297,7 +316,11 @@ describe('human-reviewed Music Video workflow', () => {const result = await request(app).post(`${base}/publish/drafts/any-draft/submit`).set('authorization', 'Bearer synthetic-agent').send({ approved: true, password: 'synthetic-operator-password' });expect(result.status).toBe(403);expect(result.body.code).toBe('PUBLISH_MANUAL_REQUIRED');- expect((await request(app).post(`${base}/publish/youtube/prepare`).send({ approved: true })).status).toBe(403);+ auth.authenticated = false;+ expect((await request(app).post(`${base}/publish/youtube/prepare`).send({})).status).toBe(401);+ auth.authenticated = true;+ expect((await request(app).post(`${base}/publish/youtube/prepare`).set('authorization', 'Bearer synthetic-agent').send({})).status).toBe(200);+ expect(prepareExternalDraft).toHaveBeenCalledWith(project.id, 'youtube', expect.any(Object));});});diff --git a/server/routes/musicVideoRichAuthoring.browser.test.js b/server/routes/musicVideoRichAuthoring.browser.test.jsindex 0cfbc6b5fd..9dbea45cff 100644--- a/server/routes/musicVideoRichAuthoring.browser.test.js+++ b/server/routes/musicVideoRichAuthoring.browser.test.js@@ -21,7 +21,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('mv-rich-ui-browser-') }));vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: async () => 'synthetic-instance' }));vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}) }));-vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => true, verifyPassword: async p => p === 'synthetic-password' }));+vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => true, verifyRequestSessionIdentity: async () => ({ kind: 'session', sessionId: 'synthetic-browser', label: null }) }));let endpoint;vi.mock('../services/browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));const { findFfmpeg } = await import('../lib/ffmpeg.js');@@ -134,11 +134,10 @@ describe.skipIf(!canRun)('rich document authoring in a real browser (Chrome, ffm]);expect(savedPlan.status()).toBe(200);expect((await store.getProject(p.id)).productionReview.draft.motionLanguage).toBe(choreography);- const password = page.getByLabel('Instance password for this approval');+ expect(await page.locator('input[type=password]').count()).toBe(0);// Each approval is awaited: the next step is gated on it server-side, and a click that races its// own approval request fails silently (this harness mounts no Toaster to show the rejection).const approve = async (name, options = {}) => {- await password.fill('synthetic-password');const [approved] = await Promise.all([page.waitForResponse(response => response.url().endsWith('/production-review/approve') && response.request().method() === 'POST'),page.getByRole('button', { name, ...options }).click(),@@ -161,7 +160,7 @@ describe.skipIf(!canRun)('rich document authoring in a real browser (Chrome, ffmawait page.getByText('Move the operator behind the threshold at the exit.', { exact: true }).waitFor();expect(await page.getByRole('button', { name: 'Approve lyric-timed storyboard' }).isDisabled()).toBe(true);await page.getByLabel('Resolution for shot: chorus / operator').fill('Reviewed the updated staging in the storyboard.');- await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Resolve feedback after review' }).click();+ await page.getByRole('button', { name: 'Resolve feedback after review' }).click();await page.getByText('Resolution: Reviewed the updated staging in the storyboard.', { exact: true }).waitFor();const beforeBoard = await page.evaluate(async id => (await fetch('/api/music-video/' + id + '/production-review')).json(), p.id);expect(beforeBoard.readiness.storyboard.problems).toEqual([]);@@ -195,7 +194,6 @@ describe.skipIf(!canRun)('rich document authoring in a real browser (Chrome, ffmawait page.locator('video').evaluate(async video => { await video.play(); await new Promise(r => setTimeout(r, 400)); video.pause(); });expect(await page.locator('video').evaluate(v => v.videoWidth)).toBeGreaterThan(0);expect(await page.getByRole('region', { name: 'Saved choreography for proof comparison' }).textContent()).toContain(choreography);- await password.fill('synthetic-password');expect(await page.getByRole('button', { name: 'Approve animated proof' }).isDisabled()).toBe(true);await page.getByLabel('Playback energy compared with the saved plan').fill('The synthetic fixture demonstrates a driving chorus: the modeled subject changes pose and travels while the camera moves through the scene.');await page.getByLabel('Timecoded playback notes').fill('0:02 — subject enters the frame; 0:07 — pose and camera position differ and readable type remains clear. This is a synthetic workflow test, not artistic approval of a production video.');diff --git a/server/services/auth.js b/server/services/auth.jsindex cb59c45963..4f07ccd080 100644--- a/server/services/auth.js+++ b/server/services/auth.js@@ -354,6 +354,15 @@ export const verifyRequestSession = async (req) => {return null;};+// Audit identity for a verified session. Never expose its token or hash; a shared+// agent session identifies the credential, not an individual agent or a human.+export const verifyRequestSessionIdentity = async (req) => {+ const token = await verifyRequestSession(req);+ if (!token) return null;+ const entry = sessions.get(hashToken(token));+ return entry ? { kind: 'session', sessionId: entry.id, label: entry.label || null } : null;+};+export const revokeSession = async (token) => {await ensureLoaded();if (sessions.delete(hashToken(token))) {diff --git a/server/services/auth.test.js b/server/services/auth.test.jsindex 88b438175f..bcafec8c73 100644--- a/server/services/auth.test.js+++ b/server/services/auth.test.js@@ -55,6 +55,19 @@ afterEach(() => {});describe('auth service', () => {+ it('derives audit identity from a valid session only, omits secrets and stops accepting revoked sessions', async () => {+ const auth = await import('./auth.js');+ const session = await auth.createSession({ label: 'agent' });+ const expected = { kind: 'session', sessionId: session.id, label: 'agent' };+ const bearer = { headers: { authorization: `Bearer ${session.token}` } };+ expect(await auth.verifyRequestSessionIdentity(bearer)).toEqual(expected);+ expect(await auth.verifyRequestSessionIdentity({ headers: { cookie: `portos_auth=${session.token}` } })).toEqual(expected);+ expect(await auth.verifyRequestSessionIdentity({ headers: { authorization: 'Basic fixture' } })).toBeNull();+ expect(await auth.verifyRequestSessionIdentity({ headers: {}, portosAuthContext: { authenticated: true } })).toBeNull();+ await auth.revokeSessionById(session.id);+ expect(await auth.verifyRequestSessionIdentity(bearer)).toBeNull();+ });+it('starts disabled when no password has been set', async () => {const auth = await import('./auth.js');expect(await auth.isAuthEnabled()).toBe(false);diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsindex 166ee2ecf9..1fddef1205 100644--- a/server/services/musicVideo/autonomousService.js+++ b/server/services/musicVideo/autonomousService.js@@ -33,13 +33,11 @@ import { assertProductionApproval, productionReadiness, productionProofNeedsRend* the code render) and finishes when that reports back over the `production`* event. Only explicit start/resume requests begin work.*- * Production review (art → storyboard → proof) is a human gate: `produce` parks- * `needs-human` until it is approved. `brief.autoApprove` lets the operator hand- * the listed stages to the run instead — granted once, with the instance- * password, on the start or resume request (the route checks it; the service- * only accepts a grant the route authorized). An auto-approval still needs a- * clean readiness report for that stage, and the proof is approved only once- * its excerpt has actually rendered.+ * Production review (art → storyboard → proof) parks `produce` until approved.+ * An authenticated start/resume can grant `brief.autoApprove` for planning;+ * the route binds the grant to a session and each automatic decision to this run.+ * Proof always requires recorded playback or machine review evidence. Older+ * briefs granting proof auto-approval still wait for rendering, then park for review.*/import { randomUUID } from 'crypto';@@ -92,7 +90,7 @@ const defaults = {acceptDocument: async (...args) => (await import('./documentGeneration.js')).acceptMixedMediaDocument(...args),generateCode: async (...args) => (await import('./codeGeneration.js')).generateMusicVideoCode(...args),renderVideo: async (...args) => (await import('./render.js')).renderMusicVideo(...args),- // The operator route's persistence path, minus its password check (the grant was checked on start/resume).+ // The review persistence path; session authority was checked on start/resume.approveProductionReview: async (...args) => (await import('./productionReviewService.js')).approveProductionReview(...args),wait: (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }),};@@ -152,13 +150,14 @@ const autoApproves = (run, stage) => normalizeAutoApprove(run.brief.autoApprove)/*** The brief fields for an auto-approve request: none when it lists no stage,* else the stages plus when the operator granted them. A non-empty list the- * route did not authorize (operator password) is refused.+ * route did not authorize (authenticated session) is refused.*/function autoApproveGrant(list, authorized) {const autoApprove = normalizeAutoApprove(list);- if (!autoApprove.length) return { autoApprove: [], autoApproveAuthorizedAt: null };- if (!authorized) throw runError(403, 'OPERATOR_REAUTH_REQUIRED', 'Enter the instance password yourself to let the run approve production review stages. Agent/API credentials cannot grant it.');- return { autoApprove, autoApproveAuthorizedAt: new Date().toISOString() };+ if (!autoApprove.length) return { autoApprove: [], autoApproveAuthorizedAt: null, autoApproveAuthorizedBy: null };+ if (!authorized) throw runError(403, 'AUTH_REQUIRED', 'Sign in to grant automatic planning approvals.');+ return { autoApprove, autoApproveAuthorizedAt: new Date().toISOString(),+ ...(typeof authorized === 'object' ? { autoApproveAuthorizedBy: structuredClone(authorized) } : {}) };}/** Approve `stage` for the run when the brief allows it and its readiness is clean; returns the fresh project. */@@ -166,7 +165,8 @@ async function autoApproveStage(project, run, stage) {if (!autoApproves(run, stage)) return project;const readiness = productionReadiness(project);if (readiness[stage].approved || readiness[stage].problems.length) return project;- await deps.approveProductionReview(project.id, { stage, basis: readiness.basis[stage], approvedBy: 'autopilot' });+ await deps.approveProductionReview(project.id, { stage, basis: readiness.basis[stage], approvedBy: 'autopilot',+ reviewer: { kind: 'autopilot', runId: run.id, authorizedBy: run.brief.autoApproveAuthorizedBy || null } });console.log(`🤖 Autonomous music video ${short(run.id)} auto-approved ${stage} (brief.autoApprove)`);return getProject(project.id);}@@ -195,23 +195,6 @@ async function awaitProofExcerpt(projectId, run) {}}-/** Approve the rendered proof for the run (brief lists `proof`); readiness problems are left for the assert to park on. */-async function autoApproveProof(projectId, run) {- const project = await awaitProofExcerpt(projectId, run);- const readiness = productionReadiness(project);- if (readiness.proof.approved || readiness.proof.problems.length) return;- const excerptId = project.productionReview.proof.excerptId;- const excerpt = project.excerpts.find((e) => e.id === excerptId);- await deps.approveProductionReview(projectId, {- stage: 'proof', basis: readiness.basis.proof, approvedBy: 'autopilot',- proofReview: {- autoApproved: true, watchedWithAudio: false, excerptId, filename: excerpt.filename,- energyComparison: 'Auto-approved by the autonomous run (brief.autoApprove).', timecodedNotes: '0:00 auto-approved',- },- });- console.log(`🤖 Autonomous music video ${short(run.id)} auto-approved proof ${short(excerptId)} (brief.autoApprove)`);-}-// ---- stage executors -------------------------------------------------------------// Each returns `{ output }` (merged into run.output) or `{ output, wait: true }`// when the stage's completion arrives later (production).@@ -423,7 +406,9 @@ const STAGES = {if (productionProofNeedsRender(project, readiness.basis.proof)) {await renderProductionProof(project.id, productionProofWindow(project));}- if (autoApproves(run, 'proof')) await autoApproveProof(project.id, run);+ // Older briefs may grant proof approval. Honor the render wait, but never+ // manufacture review evidence: a reviewer must approve the finished excerpt.+ if (autoApproves(run, 'proof')) await awaitProofExcerpt(project.id, run);assertProductionApproval(await getProject(project.id));const render = await deps.renderVideo(project.id);return { output: { renderJobId: render?.jobId || null } };diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.jsindex 18ea4cdf30..e661311877 100644--- a/server/services/musicVideo/autonomousService.test.js+++ b/server/services/musicVideo/autonomousService.test.js@@ -725,7 +725,6 @@ it('parks standalone code at real human gates and replaces a stale proof before});describe('auto-approve the rest (brief.autoApprove)', () => {- const PROOF_NOTE = 'Auto-approved by the autonomous run (brief.autoApprove).';let actual;beforeEach(async () => {creativeReview.real = true;@@ -755,14 +754,14 @@ describe('auto-approve the rest (brief.autoApprove)', () => {it('is granted only with operator authority, on start or on a resume of a parked run, and then approves clean art and storyboard itself', async () => {reviewFixture();await expect(service.startAutonomousVideo({ prompt: 'p', tools: ['image:local'], autoApprove: ['art'] }))- .rejects.toMatchObject({ status: 403, code: 'OPERATOR_REAUTH_REQUIRED' });+ .rejects.toMatchObject({ status: 403, code: 'AUTH_REQUIRED' });expect(store.size).toBe(0);await service.startAutonomousVideo({ prompt: 'p', tools: ['image:local'] });await settled('needs-human');expect(runOf()).toMatchObject({ errorCode: 'MUSIC_VIDEO_APPROVAL_REQUIRED', brief: { autoApprove: [], autoApproveAuthorizedAt: null } });await expect(service.resumeAutonomousVideo('mv-auto', { autoApprove: ['art', 'storyboard'] }))- .rejects.toMatchObject({ status: 403, code: 'OPERATOR_REAUTH_REQUIRED' });+ .rejects.toMatchObject({ status: 403, code: 'AUTH_REQUIRED' });expect(runOf()).toMatchObject({ status: 'needs-human', brief: { autoApprove: [] } });expect(doubles.approveProductionReview).not.toHaveBeenCalled();@@ -799,18 +798,16 @@ describe('auto-approve the rest (brief.autoApprove)', () => {return renderProductionProof;};- it('waits for the proof render to finish, then approves that excerpt and starts the final render', async () => {+ it('waits for the proof render then parks for substantive review even with a legacy proof grant', async () => {reviewFixture();await proofRenders({ status: 'complete', filename: 'proof-1.mp4' });await service.startAutonomousVideo({ prompt: 'p', tools: ['code:render'], authoring: { providerId: 'example', model: 'example-code' },autoApprove: ['art', 'storyboard', 'proof'] }, { autoApproveAuthorized: true });- await settled('completed');- expect(doubles.wait).toHaveBeenCalledOnce();+ await settled('needs-human');expect(doubles.wait).toHaveBeenCalledWith(5000);- expect(approvals().proof).toMatchObject({ approvedBy: 'autopilot', proofReview: {- autoApproved: true, watchedWithAudio: false, excerptId: 'proof-1', filename: 'proof-1.mp4', energyComparison: PROOF_NOTE } });- expect(actual.productionReadiness(store.get('mv-auto')).readyForProduction).toBe(true);- expect(doubles.renderVideo).toHaveBeenCalledOnce();+ expect(approvals().proof).toBeUndefined();+ expect(actual.productionReadiness(store.get('mv-auto')).readyForProduction).toBe(false);+ expect(doubles.renderVideo).not.toHaveBeenCalled();});it('fails the run with the excerpt error when the proof render fails', async () => {diff --git a/server/services/musicVideo/productionReview.js b/server/services/musicVideo/productionReview.jsindex 90004236ba..98c50b77a5 100644--- a/server/services/musicVideo/productionReview.js+++ b/server/services/musicVideo/productionReview.js@@ -25,6 +25,19 @@ export const documentStoryboardBasis = project => hash({shots: project.productionReview?.draft?.storyboard,});+// Share the evidence contract between new decisions and persisted approvals:+// a legacy automatic waiver must not become production-ready after an upgrade.+function hasProofEvidence(review) {+ if (!review || review.autoApproved || !text(review.energyComparison) || !text(review.timecodedNotes)+ || !/(?:\b\d{1,2}:\d{2}(?:\.\d+)?\b|\b\d+(?:\.\d+)?s\b)/.test(review.timecodedNotes)) return false;+ if (review.method === 'machine') {+ const evidence = review.machineEvidence;+ return review.watchedWithAudio === false && text(evidence?.visualReview) && evidence.visualReview.trim().length >= 40+ && text(evidence?.audioReview) && evidence.audioReview.trim().length >= 40 && text(evidence?.limitations);+ }+ return (review.method == null || review.method === 'playback') && review.watchedWithAudio === true;+}+export function productionReviewBasis(project) {const draft = project.productionReview?.draft || {};const art = hash({ projectId: project.id, mediaMode: project.mediaMode, authoringRenderer: project.composition?.authoringRenderer, mode: project.composition?.mode, policy: project.productionPolicy,@@ -116,7 +129,7 @@ export function productionReadiness(project) {if (!proof || proof.basis !== basis.proof || excerpt?.status !== 'complete' || !excerpt?.filename) {proofProblems.push('Render and watch a current animated chorus proof with the master song.');}- const proofApproved = !proofProblems.length && review.approvals?.proof?.basis === hash({ basis: basis.proof, excerptId: excerpt.id, filename: excerpt.filename });+ const proofApproved = !proofProblems.length && hasProofEvidence(review.approvals?.proof?.proofReview) && review.approvals?.proof?.basis === hash({ basis: basis.proof, excerptId: excerpt.id, filename: excerpt.filename });return { basis, documentShotImport: { documentDirectory: project.composition?.document?.directory || null, audioBasis: productionAlignmentBasis(project) }, art: { approved: artApproved, problems: [...new Set(artProblems)] },storyboard: { approved: storyboardApproved, problems: [...new Set(boardProblems)] },proof: { approved: proofApproved, problems: proofProblems, excerptId: excerpt?.id || null },@@ -126,18 +139,13 @@ export function productionReadiness(project) {export function assertProductionApproval(project, stage = 'proof') {const readiness = productionReadiness(project);if (!readiness[stage].approved) throw new ServerError(- readiness[stage].problems[0] || `A human must approve the current ${stage === 'art' ? 'art direction' : stage} in Production review.`,+ readiness[stage].problems[0] || `A reviewer must approve the current ${stage === 'art' ? 'art direction' : stage} in Production review.`,{ status: 409, code: 'MUSIC_VIDEO_APPROVAL_REQUIRED', context: { stage, readiness } });}-/**- * `approvedBy: 'autopilot'` marks an approval the autonomous run made under the- * operator's `brief.autoApprove` grant. Its proof review is `autoApproved: true`:- * nobody watched it, so the watched/notes record is waived, but it must still- * name the current excerpt. The HTTP approval schema rejects both fields, so- * only the run (in-process) can set them.- */-export function approveProductionStage(project, { stage, basis, proofReview, approvedBy }) {+/** Evidence is bound to the exact revision and excerpt. Machine review never+ * claims human playback; rendering alone is not a review. */+export function approveProductionStage(project, { stage, basis, proofReview, approvedBy, reviewer }) {const readiness = productionReadiness(project);const expected = stage === 'proof'? hash({ basis: readiness.basis.proof, excerptId: project.productionReview?.proof?.excerptId,@@ -147,17 +155,20 @@ export function approveProductionStage(project, { stage, basis, proofReview, appif (readiness[stage].problems.length) throw new ServerError(readiness[stage].problems.join(' '), { status: 409, code: 'MUSIC_VIDEO_REVIEW_INCOMPLETE' });if (stage === 'proof') {const excerpt = project.excerpts?.find(e => e.id === project.productionReview?.proof?.excerptId);- if (proofReview?.autoApproved !== true && (proofReview?.watchedWithAudio !== true || !text(proofReview.energyComparison)- || !text(proofReview.timecodedNotes) || !/(?:\b\d{1,2}:\d{2}(?:\.\d+)?\b|\b\d+(?:\.\d+)?s\b)/.test(proofReview.timecodedNotes))) {- throw new ServerError('Play this proof with audio and record the energy comparison and timecoded choreography notes before approving.', { status: 409, code: 'MUSIC_VIDEO_PROOF_REVIEW_REQUIRED' });+ if (!hasProofEvidence(proofReview)) {+ throw new ServerError('Review this proof with audio and record the energy comparison and timecoded choreography notes. Machine reviews also require visual, audio and limitation evidence.', { status: 409, code: 'MUSIC_VIDEO_PROOF_REVIEW_REQUIRED' });}if (proofReview.excerptId !== excerpt?.id || proofReview.filename !== excerpt?.filename || !excerpt?.filename) {throw new ServerError('The rendered proof changed. Play and review the new excerpt before approving.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });}}+ const decision = { stage, basis: expected, approvedAt: new Date().toISOString(),+ ...(approvedBy ? { approvedBy } : {}), ...(reviewer ? { reviewer: structuredClone(reviewer) } : {}),+ ...(stage === 'proof' ? { proofReview: structuredClone(proofReview) } : {}) };return { ...project, productionReview: { ...project.productionReview,+ approvalHistory: [...(project.productionReview?.approvalHistory || []), decision],reviewedRevisions: { ...project.productionReview?.reviewedRevisions, [basis]: { draft: structuredClone(project.productionReview?.draft || {}), scenes: structuredClone(project.scenes || []), proof: structuredClone(project.productionReview?.proof || null), capturedAt: new Date().toISOString() } },- approvals: { ...project.productionReview?.approvals, [stage]: { basis: expected, approvedAt: new Date().toISOString(), ...(approvedBy ? { approvedBy } : {}), ...(stage === 'proof' ? { proofReview: structuredClone(proofReview) } : {}) } } } };+ approvals: { ...project.productionReview?.approvals, [stage]: decision } } };}/** Comments retain the exact reviewed draft, even after a replacement import. */@@ -178,17 +189,17 @@ export function recordProductionFeedback(project, input) {feedback: [...(review.feedback || []), entry] } };}-export function resolveProductionFeedback(project, { feedbackId, resolution }) {+export function resolveProductionFeedback(project, { feedbackId, resolution, reviewer }) {const review = project.productionReview || {};const entry = review.feedback?.find(f => f.id === feedbackId);if (!entry || entry.resolvedAt) throw new ServerError('Open feedback not found.', { status: 409, code: 'MUSIC_VIDEO_FEEDBACK_CLOSED' });return { ...project, productionReview: { ...review, feedback: review.feedback.map(f => f.id === feedbackId- ? { ...f, resolution, resolvedAt: new Date().toISOString(), resolvedBasis: productionReviewBasis(project)[f.stage] } : f) } };+ ? { ...f, resolution, ...(reviewer ? { resolvedBy: structuredClone(reviewer) } : {}), resolvedAt: new Date().toISOString(), resolvedBasis: productionReviewBasis(project)[f.stage] } : f) } };}export function productionFeedbackContext(project) {const feedback = (project.productionReview?.feedback || []).filter(f => !f.resolvedAt);- return feedback.length ? `\nUNRESOLVED REVIEW FEEDBACK (retain until a human resolves it):\n${feedback.map(f => `${f.stage} / ${f.target} / ${f.decision}: ${f.text}`).join('\n')}` : '';+ return feedback.length ? `\nUNRESOLVED REVIEW FEEDBACK (retain until an authenticated reviewer resolves it):\n${feedback.map(f => `${f.stage} / ${f.target} / ${f.decision}: ${f.text}`).join('\n')}` : '';}diff --git a/server/services/musicVideo/productionReviewService.js b/server/services/musicVideo/productionReviewService.jsindex 389a2b7ec6..946d3c7c83 100644--- a/server/services/musicVideo/productionReviewService.js+++ b/server/services/musicVideo/productionReviewService.js@@ -98,16 +98,14 @@ export async function bindProductionShot(id, shotId) {return changed(project);}-/** The existing password is reverified; agent session tokens are not approval authority.- * This protects against delegated agents, not an adversary controlling the host or password.- * No password is persisted and password-free installs fail closed for approvals.+/** Creative decisions use an existing authenticated session, including agents.+ * Auth-off, peer credentials and caller-supplied identities confer no authority.*/-export async function requireProductionOperator(req) {- const { isAuthEnabled, verifyPassword } = await import('../auth.js');- if (!await isAuthEnabled()) throw new ServerError('Set an instance password in Settings > Security before approving production. Draft editing remains available.', { status: 403, code: 'OPERATOR_PASSWORD_REQUIRED' });- if (req.headers?.authorization || !await verifyPassword(req.body?.password)) {- throw new ServerError('Enter the instance password yourself to approve this revision. Agent/API credentials cannot approve it.', { status: 403, code: 'OPERATOR_REAUTH_REQUIRED' });- }+export async function requireProductionReviewer(req) {+ const { isAuthEnabled, verifyRequestSessionIdentity } = await import('../auth.js');+ const reviewer = await isAuthEnabled() && await verifyRequestSessionIdentity(req);+ if (!reviewer) throw new ServerError('Sign in to PortOS before approving production or granting automatic planning approvals.', { status: 401, code: 'AUTH_REQUIRED' });+ return reviewer;}export async function saveProductionDraft(id, draft) {diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsindex 0440c0a2f0..cf71a2f58e 100644--- a/server/services/musicVideo/publish/index.js+++ b/server/services/musicVideo/publish/index.js@@ -1,6 +1,6 @@/*** Prepare external platform drafts for manual review and publication.- * The authenticated operator route requires fresh password verification.+ * Draft preparation requires an existing authenticated session, including agents.* PortOS never submits a draft; the operator publishes in the destination* platform and records its URL. Adapter preparation runs in a serialized,* dedicated browser tab. Existing drafts can be discarded or replaced.