Skip to content

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

Export portable Music Video making-of packages (#10237)

[._.]/544a370a3e32
diff --git a/client/src/components/musicVideo/MakingOfExportPanel.jsx b/client/src/components/musicVideo/MakingOfExportPanel.jsx
new file mode 100644
index 0000000000..8a74c3f154
--- /dev/null
+++ b/client/src/components/musicVideo/MakingOfExportPanel.jsx
@@ -0,0 +1,122 @@
+import { useEffect, useRef, useState } from 'react';
+import { getMusicVideoMakingOfCatalog, listMusicVideoProjectSummaries, previewMusicVideoMakingOf, exportMusicVideoMakingOf } from '../../services/apiMusicVideo.js';
+import { downloadBlob } from '../../lib/downloadBlob.js';
+import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import { formatBytes, formatCount } from '../../utils/formatters.js';
+
+/** Transient export selections; project navigation remains owned by the URL. */
+export default function MakingOfExportPanel({ project }) {
+ const [catalogs, setCatalogs] = useState([]);
+ const [options, setOptions] = useState([]);
+ const [projectCursor, setProjectCursor] = useState(null);
+ const [nextProject, setNextProject] = useState('');
+ const [picks, setPicks] = useState({});
+ const [preview, setPreview] = useState(null);
+ const [error, setError] = useState('');
+ const generation = useRef(0);
+ const selection = { projects: catalogs.map(catalog => ({ projectId: catalog.project.id, snapshot: catalog.snapshot,
+ assets: catalog.assets.filter(asset => picks[`${catalog.project.id}:${asset.id}`]).map(asset => ({ id: asset.id, ...picks[`${catalog.project.id}:${asset.id}`] })) })) };
+
+ useEffect(() => {
+ let active = true;
+ generation.current += 1;
+ setCatalogs([]); setPicks({}); setPreview(null); setError('');
+ Promise.all([getMusicVideoMakingOfCatalog(project.id, { silent: true }), listMusicVideoProjectSummaries({ limit: 100 }, { silent: true })])
+ .then(([catalog, summaries]) => { if (active) { setCatalogs([catalog]); setOptions(summaries.items); setProjectCursor(summaries.nextCursor ?? null); } })
+ .catch(err => { if (active) setError(err.message); });
+ return () => { active = false; };
+ }, [project.id, project.updatedAt]);
+
+ const [loadMore, loadingMore] = useAsyncAction(async () => {
+ const runGeneration = generation.current;
+ const summaries = await listMusicVideoProjectSummaries({ cursor: projectCursor, limit: 100 }, { silent: true });
+ if (runGeneration !== generation.current) return;
+ setOptions(current => [...current, ...summaries.items.filter(item => !current.some(existing => existing.id === item.id))]);
+ setProjectCursor(summaries.nextCursor ?? null);
+ });
+
+ const [addProject, adding] = useAsyncAction(async () => {
+ const runGeneration = generation.current;
+ const catalog = await getMusicVideoMakingOfCatalog(nextProject, { silent: true });
+ if (runGeneration !== generation.current) return;
+ setCatalogs(current => current.some(item => item.project.id === catalog.project.id) ? current : [...current, catalog]);
+ setNextProject(''); setPreview(null);
+ });
+ const [inspect, inspecting] = useAsyncAction(async () => {
+ const runGeneration = generation.current;
+ setPreview(null);
+ const refreshed = await Promise.all(catalogs.map(catalog => getMusicVideoMakingOfCatalog(catalog.project.id, { silent: true })));
+ if (runGeneration !== generation.current) return;
+ setCatalogs(refreshed);
+ const freshSelection = { projects: selection.projects.map((selected, index) => ({ ...selected, snapshot: refreshed[index].snapshot })) };
+ if (freshSelection.projects.some((selected, index) => selected.assets.some(asset => !refreshed[index].assets.some(item => item.id === asset.id)))) {
+ throw new Error('A selected artifact was removed. Review the refreshed catalog and preview again.');
+ }
+ const result = await previewMusicVideoMakingOf(freshSelection, { silent: true });
+ if (runGeneration === generation.current) setPreview({ ...result, selection: freshSelection });
+ });
+ const [download, downloading] = useAsyncAction(async () => {
+ const buffer = await exportMusicVideoMakingOf({ ...preview.selection, previewDigest: preview.previewDigest }, { silent: true });
+ downloadBlob(buffer, 'music-video-making-of.zip', 'application/zip');
+ });
+ const busy = adding || inspecting || downloading || loadingMore;
+ const changePick = (key, value) => { setPicks(current => ({ ...current, [key]: value })); setPreview(null); };
+
+ return <section aria-label="Making-of export" className="min-w-0 rounded-lg border border-port-border bg-port-card p-3 space-y-3">
+ <h3 className="text-sm font-medium">Making-of export</h3>
+ <p className="text-xs text-port-text-muted">Compile blueprint and video versions into a portable planning ZIP. Select exact files, inspect the inventory, then download. GitHub publication is a separate step.</p>
+ {error && <p role="alert" className="text-sm text-port-error">{error}</p>}
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="min-w-0 max-w-full">
+ <label htmlFor="making-of-project" className="block text-xs">Add another version or project</label>
+ <select id="making-of-project" className="max-w-full rounded border border-port-border bg-port-bg p-2 text-sm" value={nextProject} disabled={busy} onChange={e => setNextProject(e.target.value)}>
+ <option value="">Choose a project</option>
+ {options.filter(item => !catalogs.some(catalog => catalog.project.id === item.id)).map(item => <option key={item.id} value={item.id}>{item.name}</option>)}
+ </select>
+ </div>
+ <button type="button" disabled={!nextProject || busy || catalogs.length >= 8} onClick={addProject} className="rounded border border-port-border p-2 text-sm">Add to package</button>
+ {projectCursor != null && <button type="button" disabled={busy} onClick={loadMore} className="rounded border border-port-border p-2 text-sm">Load more projects</button>}
+ </div>
+ {catalogs.map(catalog => <fieldset key={catalog.project.id} disabled={busy} className="min-w-0 border border-port-border rounded p-2 space-y-2">
+ <legend className="text-sm px-1">{catalog.project.name} · v{catalog.project.version}</legend>
+ <p className="text-xs text-port-text-muted">Planning JSON, cast/set sheet, storyboard and shot JSON/CSV are included. No image files are selected by default.</p>
+ {catalog.project.id !== project.id && <button type="button" className="text-xs text-port-accent" onClick={() => { setCatalogs(current => current.filter(item => item !== catalog)); setPreview(null); }}>Remove project</button>}
+ {!catalog.assets.length && <p className="text-xs">No artifact or image files available. Missing sheets remain visible in the inventory.</p>}
+ {catalog.assets.map((asset, index) => {
+ const key = `${catalog.project.id}:${asset.id}`;
+ const pick = picks[key];
+ const inputId = `making-of-${catalog.project.id}-${index}`;
+ return <div key={asset.id} className="min-w-0 space-y-1 border-t border-port-border pt-2">
+ <div className="flex gap-2 items-start">
+ <input id={inputId} type="checkbox" checked={!!pick} disabled={!['included', 'partial', 'requires-ownership', 'requires-owner-project'].includes(asset.status)} onChange={e => changePick(key, e.target.checked ? { rights: 'unknown', attribution: '', ownershipConfirmed: false } : null)} />
+ <label htmlFor={inputId} className="break-words text-xs min-w-0">{asset.label} — {asset.status === 'included' ? `available, ${formatBytes(asset.bytes)}` : `${asset.status}: ${asset.reason}`}{asset.visualCount ? ` · ${formatCount(asset.visualCount)} graphics` : ''}</label>
+ </div>
+ {pick && <div className="flex flex-wrap gap-2 pl-5">
+ <div><label htmlFor={`${inputId}-rights`} className="block text-xs">Rights declaration</label>
+ <select id={`${inputId}-rights`} value={pick.rights} onChange={e => changePick(key, { ...pick, rights: e.target.value })} className="rounded border border-port-border bg-port-bg p-1 text-xs">
+ <option value="unknown">Unverified</option><option value="owned">Owned</option><option value="licensed">Licensed</option>
+ </select></div>
+ <div className="min-w-0"><label htmlFor={`${inputId}-credit`} className="block text-xs">Attribution / license note</label>
+ <input id={`${inputId}-credit`} value={pick.attribution} maxLength={2000} onChange={e => changePick(key, { ...pick, attribution: e.target.value })} className="rounded border border-port-border bg-port-bg p-1 text-xs max-w-full" /></div>
+ {asset.ownershipDeclarationAvailable && <div className="flex gap-2 items-start w-full">
+ <input id={`${inputId}-owned`} type="checkbox" checked={pick.ownershipConfirmed || false} disabled={pick.rights !== 'owned'} onChange={e => changePick(key, { ...pick, ownershipConfirmed: e.target.checked })} />
+ <label htmlFor={`${inputId}-owned`} className="text-xs">I own this file and its embedded raster graphics. This records my declaration; it does not verify publication clearance. Choose Owned to confirm.</label>
+ </div>}
+ </div>}
+ </div>;
+ })}
+ </fieldset>)}
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={inspect} disabled={busy || !catalogs.length} className="rounded border border-port-border p-2 text-sm">{inspecting ? 'Compiling preview…' : 'Preview inventory'}</button>
+ <button type="button" onClick={download} disabled={busy || !preview} className="rounded bg-port-accent text-port-bg p-2 text-sm">{downloading ? 'Downloading…' : 'Download planning ZIP'}</button>
+ </div>
+ {preview && <div className="space-y-2 text-xs min-w-0" aria-label="Package inventory">
+ <p>{formatCount(preview.files.length)} files · {formatBytes(preview.bytes)} · Rights require review before sharing.</p>
+ <ul className="space-y-1">{preview.manifest.inventory.map(item => <li key={`${item.projectId}:${item.id}`} className="break-words">
+ {item.label || item.id}: {item.status}{item.reason ? ` (${item.reason})` : ''} · rights: {item.rights || 'unknown'}
+ {item.transformation && ` · ${item.transformation}`}
+ </li>)}</ul>
+ <details><summary>Package files and checksums</summary><ul>{preview.files.map(file => <li key={file.path} className="break-all">{file.path} · {formatBytes(file.bytes)} · SHA-256 {file.sha256}</li>)}</ul></details>
+ </div>}
+ </section>;
+}
diff --git a/client/src/components/musicVideo/MakingOfExportPanel.test.jsx b/client/src/components/musicVideo/MakingOfExportPanel.test.jsx
new file mode 100644
index 0000000000..f914f1694d
--- /dev/null
+++ b/client/src/components/musicVideo/MakingOfExportPanel.test.jsx
@@ -0,0 +1,87 @@
+import { act, fireEvent, render, screen, waitFor, cleanup } from '@testing-library/react';
+import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
+import MakingOfExportPanel from './MakingOfExportPanel.jsx';
+
+const { api, downloadBlob, toast } = vi.hoisted(() => ({ api: {
+ getMusicVideoMakingOfCatalog: vi.fn(), listMusicVideoProjectSummaries: vi.fn(), previewMusicVideoMakingOf: vi.fn(), exportMusicVideoMakingOf: vi.fn(),
+}, downloadBlob: vi.fn(), toast: { error: vi.fn() } }));
+vi.mock('../../services/apiMusicVideo.js', () => api);
+vi.mock('../../lib/downloadBlob.js', () => ({ downloadBlob }));
+vi.mock('../ui/Toast', () => ({ default: toast }));
+const project = { id: 'mv-example', name: 'Example Blueprint', version: 1 };
+const catalog = (id = 'mv-example') => ({ project: { id, name: id === 'mv-example' ? 'Example Blueprint' : 'Example Hybrid', version: 1 }, snapshot: 'a'.repeat(64),
+ assets: [{ id: 'artifact:example:v1', label: 'Example guide · v1', kind: 'cast-sets', status: 'included', bytes: 100 },
+ { id: 'frame:scene-example', label: 'Missing frame', kind: 'storyboard', status: 'missing', reason: 'not-generated' }] });
+const result = { previewDigest: 'b'.repeat(64), bytes: 300, files: [{ path: 'README.md', bytes: 300, sha256: 'c'.repeat(64) }],
+ manifest: { inventory: [{ projectId: 'mv-example', id: 'frame:scene-example', status: 'missing', reason: 'not-generated', rights: 'unknown' }] } };
+beforeEach(() => {
+ api.getMusicVideoMakingOfCatalog.mockImplementation(async id => catalog(id));
+ api.listMusicVideoProjectSummaries.mockResolvedValue({ items: [{ id: 'mv-example', name: 'Example Blueprint' }, { id: 'mv-hybrid', name: 'Example Hybrid' }] });
+ api.previewMusicVideoMakingOf.mockResolvedValue(result);
+ api.exportMusicVideoMakingOf.mockResolvedValue(new ArrayBuffer(4));
+});
+afterEach(cleanup);
+
+describe('Making-of export panel', () => {
+ it('requires explicit file selection and inventory preview, combines variants, and binds the download to the preview', async () => {
+ render(<MakingOfExportPanel project={project} />);
+ const guide = await screen.findByRole('checkbox', { name: /Example guide/ });
+ expect(guide.checked).toBe(false);
+ expect(screen.getByRole('checkbox', { name: /Missing frame/ }).disabled).toBe(true);
+ expect(screen.getByRole('button', { name: 'Download planning ZIP' }).disabled).toBe(true);
+ fireEvent.click(guide);
+ fireEvent.change(screen.getByLabelText('Rights declaration'), { target: { value: 'licensed' } });
+ fireEvent.change(screen.getByLabelText('Attribution / license note'), { target: { value: 'Example license' } });
+ fireEvent.change(screen.getByLabelText('Add another version or project'), { target: { value: 'mv-hybrid' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add to package' }));
+ await screen.findByText('Example Hybrid · v1');
+ fireEvent.click(screen.getByRole('button', { name: 'Preview inventory' }));
+ await screen.findByLabelText('Package inventory');
+ const selection = api.previewMusicVideoMakingOf.mock.calls[0][0];
+ expect(selection.projects).toHaveLength(2);
+ expect(selection.projects[0].assets).toEqual([{ id: 'artifact:example:v1', rights: 'licensed', attribution: 'Example license', ownershipConfirmed: false }]);
+ expect(screen.getByLabelText('Package inventory').textContent).toContain('missing (not-generated)');
+ fireEvent.click(screen.getByRole('button', { name: 'Download planning ZIP' }));
+ await waitFor(() => expect(downloadBlob).toHaveBeenCalledWith(expect.any(ArrayBuffer), 'music-video-making-of.zip', 'application/zip'));
+ expect(api.exportMusicVideoMakingOf).toHaveBeenCalledWith({ ...selection, previewDigest: result.previewDigest }, { silent: true });
+ fireEvent.change(screen.getByLabelText('Attribution / license note'), { target: { value: 'Changed credit' } });
+ expect(screen.getByRole('button', { name: 'Download planning ZIP' }).disabled).toBe(true);
+ });
+
+ it('drops catalog responses from an earlier project and surfaces catalog failures', async () => {
+ let finish;
+ api.getMusicVideoMakingOfCatalog.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const { rerender } = render(<MakingOfExportPanel project={project} />);
+ rerender(<MakingOfExportPanel project={{ id: 'mv-hybrid' }} />);
+ await screen.findByText('Example Hybrid · v1');
+ await act(async () => finish(catalog()));
+ expect(screen.queryByText('Example Blueprint · v1')).toBeNull();
+ api.getMusicVideoMakingOfCatalog.mockRejectedValueOnce(new Error('Catalog unavailable'));
+ rerender(<MakingOfExportPanel project={{ id: 'mv-third' }} />);
+ expect((await screen.findByRole('alert')).textContent).toBe('Catalog unavailable');
+ });
+
+ it('refreshes changed project snapshots before compiling a new inventory', async () => {
+ render(<MakingOfExportPanel project={project} />);
+ fireEvent.click(await screen.findByRole('checkbox', { name: /Example guide/ }));
+ api.getMusicVideoMakingOfCatalog.mockResolvedValueOnce({ ...catalog(), snapshot: 'd'.repeat(64) });
+ fireEvent.click(screen.getByRole('button', { name: 'Preview inventory' }));
+ await screen.findByLabelText('Package inventory');
+ expect(api.previewMusicVideoMakingOf.mock.calls[0][0].projects[0]).toMatchObject({ snapshot: 'd'.repeat(64), assets: [{ id: 'artifact:example:v1', rights: 'unknown', attribution: '', ownershipConfirmed: false }] });
+ });
+
+ it('records explicit ownership for embedded graphics and invalidates its preview when that declaration changes', async () => {
+ api.getMusicVideoMakingOfCatalog.mockImplementation(async () => ({ ...catalog(), assets: [{ ...catalog().assets[0], status: 'partial', reason: 'some-visuals-not-exported', visualCount: 26, ownershipDeclarationAvailable: true }] }));
+ render(<MakingOfExportPanel project={project} />);
+ fireEvent.click(await screen.findByRole('checkbox', { name: /Example guide/ }));
+ const declaration = screen.getByRole('checkbox', { name: /I own this file/ });
+ expect(declaration.disabled).toBe(true);
+ fireEvent.change(screen.getByLabelText('Rights declaration'), { target: { value: 'owned' } });
+ fireEvent.click(declaration);
+ fireEvent.click(screen.getByRole('button', { name: 'Preview inventory' }));
+ await screen.findByLabelText('Package inventory');
+ expect(api.previewMusicVideoMakingOf.mock.calls[0][0].projects[0].assets[0]).toMatchObject({ rights: 'owned', ownershipConfirmed: true });
+ fireEvent.click(declaration);
+ expect(screen.getByRole('button', { name: 'Download planning ZIP' }).disabled).toBe(true);
+ });
+});
diff --git a/client/src/components/musicVideo/stages/ReviewStage.jsx b/client/src/components/musicVideo/stages/ReviewStage.jsx
index 195b02c7ca..589363c24d 100644
--- a/client/src/components/musicVideo/stages/ReviewStage.jsx
+++ b/client/src/components/musicVideo/stages/ReviewStage.jsx
@@ -2,6 +2,7 @@ import DependencyImpactPanel from '../DependencyImpactPanel.jsx';
import RenderStatusPanel, { RenderFailure } from '../RenderStatusPanel.jsx';
import ExcerptPanel from '../ExcerptPanel.jsx';
import DevArtifactsPanel from '../DevArtifactsPanel.jsx';
+import MakingOfExportPanel from '../MakingOfExportPanel.jsx';
import StageSection from '../StageSection.jsx';
import { isFinalRenderStale } from '../../../lib/musicVideoStages.js';
import { RenderFinalButton } from '../ProjectActionGroups.jsx';
@@ -65,6 +66,8 @@ export default function ReviewStage({ board }) {
/>
</StageSection>
+ <MakingOfExportPanel project={project} />
+
</fieldset>
);
}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index ffb5c7d1d4..b65d5cebc0 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -44,6 +44,9 @@ vi.mock('../hooks/useMusicVideoProductionReview.js', () => ({ default: ({ projec
}) }));
vi.mock('../services/apiMusicVideo.js', () => ({
+ getMusicVideoMakingOfCatalog: vi.fn(async id => ({ project: { id, name: 'Example making-of project', version: 1 }, snapshot: 'a'.repeat(64), assets: [] })),
+ previewMusicVideoMakingOf: vi.fn(),
+ exportMusicVideoMakingOf: vi.fn(),
listMusicVideoProjects: vi.fn(async () => []),
listMusicVideoProjectSummaries: vi.fn(async (params, options) => {
const res = await listMusicVideoProjects(params, options);
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 02a0ff4bd4..b773ce2ed6 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -1,5 +1,13 @@
import { request } from './apiCore.js';
+export const getMusicVideoMakingOfCatalog = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/making-of/catalog`, options);
+export const previewMusicVideoMakingOf = (selection, options = {}) => request('/music-video/making-of/preview', {
+ method: 'POST', body: JSON.stringify(selection), ...options,
+});
+export const exportMusicVideoMakingOf = (selection, options = {}) => request('/music-video/making-of/export', {
+ method: 'POST', body: JSON.stringify(selection), responseType: 'arraybuffer', ...options,
+});
+
// Music Video production mode (#1760). Director scene-board project CRUD + the
// offline beat/tempo/section analysis. `options` lets a caller suppress
// request()'s auto-toast with `{ silent: true }` when it owns its own error UI.
diff --git a/docs/README.md b/docs/README.md
index 215fdeb26b..cc72b7bd06 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -51,6 +51,8 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
## Feature deep dives (`features/`)
+- [Music Video making-of export](./features/music-video-making-of.md) — local multi-variant planning packages, inventory previews, source planning retention and publication boundaries
+
Start with the [product surface map](./features/product-surfaces.md) for a complete, user-facing inventory of the application. The focused guides below explain the features with their own operating contracts.
App management: [app-wizard](./features/app-wizard.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)
diff --git a/docs/features/music-video-making-of.md b/docs/features/music-video-making-of.md
new file mode 100644
index 0000000000..def61fd5c5
--- /dev/null
+++ b/docs/features/music-video-making-of.md
@@ -0,0 +1,133 @@
+# Music Video making-of export
+
+Music Video → Review & Export → Making-of export compiles a local planning ZIP
+from up to eight projects. This supports combining a blueprint with its video
+variant and reusing the workflow for later productions. It does not create a
+GitHub repository, push, publish, acquire credentials, render media or edit projects.
+
+Choose projects, select exact development-artifact versions and generated image
+slots, enter rights/attribution declarations, then **Preview inventory**. No asset
+bytes are selected by default. **Download planning ZIP** becomes available after
+the preview. Changing selection or credits invalidates it. The server binds the
+download to a digest of the preview's content and inventory; changed project data,
+file bytes or availability returns `409 MAKING_OF_CHANGED` and requires a new preview.
+
+## Package contract
+
+The ZIP uses stable project/artifact/scene IDs and relative paths:
+
+```text
+README.md
+manifest.json
+SHA256SUMS
+projects/<project-id>/
+ planning.json
+ shots.json
+ shots.csv
+ cast-set-sheet.md
+ storyboard.md
+ artifacts/<artifact-id>/v<version>.md|json|png|jpg|webp
+ artifacts/<artifact-id>/v<version>-storyboard.csv|md
+ artifacts/<artifact-id>/v<version>-visuals/visual-<ordinal>-<source-hash>.png
+ images/cast-<slot>.png|jpg|webp
+ images/frame-<scene-id>.png|jpg|webp
+```
+
+Planning preserves the current scene board separately from the editable timed
+storyboard, project lineage, cue IDs and word timing, full cast/set direction,
+prompts, selected settings, recorded generation settings, alignment basis,
+readiness and revision-bound approval truth. A missing recorded master content hash
+is reported as `not-recorded`; an alignment checksum is not claimed to be a hash
+of the audio bytes. This exporter does not read audio to invent a content hash.
+
+Select the **Original planning import** artifact when richer authored planning
+exists. Its JSON structure is preserved with privacy redactions instead of being
+projected down to the editable importer's fields. Its authored storyboard also
+gets a CSV with all original columns and a Markdown companion. This retains
+purpose, holds, treatments, cast/set IDs, overlays, word anchors, prompt negatives,
+provider constraints and benchmark notes when present in that source. Original
+planning is unverified evidence and never supplies live approval authority.
+
+The inventory records every candidate as included, partial, missing, excluded or
+not selected, with per-item reasons, transformations, selected versions, rights,
+attribution, provenance and checksums. Selected HTML sheets retain source-ordered
+graphics and captions in Markdown with relative PNG links. This preserves their
+visual content without reproducing the complete HTML layout pixel for pixel.
+Validated static SVG previews are rasterized; embedded raster plates require the
+explicit **I own this file and its embedded raster graphics** declaration with
+rights set to Owned. Unsafe or unavailable graphics stay visibly omitted, with
+individual inventory entries; the sheet is marked partial.
+
+Visual-spec references start unselected. Shared generated images are admitted
+when their owning project is explicitly selected and retained job evidence matches.
+Shared artifact versions require an exact immutable version in the selected
+owner's record. Imported user-owned artifacts/gallery images can be admitted with
+the explicit Owned declaration; this is operator evidence, not independent
+verification or publication clearance. Unknown ownership remains excluded as
+`ownership-unverified`. Original-planning asset records remain metadata only.
+Selectable historical versions are artifact versions; a selected project's
+planning is its current snapshot.
+
+Identical inputs on the same image-library runtime produce identical archive
+bytes: entry order is sorted, ZIP timestamps fixed, and no export-time clock is
+inserted. `SHA256SUMS` covers every file except itself. After unpacking, verify with
+`shasum -a 256 -c SHA256SUMS` (or another SHA-256 checker).
+
+## Boundaries
+
+- Metadata uses bounded projections; raw project records, logs, provider config,
+ credentials and execution settings are not copied. URLs, recognizable credentials,
+ private hosts and absolute paths in creative prose are redacted. Original JSON
+ drops secret/private transport and embedded binary fields. Review content before
+ sharing; a local export is not a public-content clearance decision.
+- Artifact reads must match a selected project's exact immutable file path.
+ Shared gallery images require a retained image job with the matching project,
+ slot/scene and output filename. Cloned pointers without a selected verified
+ owner remain excluded. Declarations cannot bypass path/type boundaries.
+- Allowed file types are PNG/JPEG/WebP and safe conversions of Markdown/HTML.
+ Raster output is decoded/re-encoded with EXIF orientation applied to pixels
+ before metadata is stripped. Inline SVG uses a strict static geometry/text/gradient
+ allowlist and bounded viewBox; rejected SVG never
+ reaches the rasterizer. Scripts, remote resources, canvas, entities, links and
+ active SVG features are omitted without execution or network access. Raw SVG,
+ executable source, audio/video, arbitrary paths, symlinks, hard links and special
+ files are excluded.
+- CSS graphics and external stylesheet dependencies are recorded as visible
+ omissions with partial sheet status; CSS resources are never loaded. Image
+ captions are normalized to one line and escaped before Markdown insertion.
+- Each file is bounded to 20 MiB, the package to 100 MiB, each project to 300
+ candidates and each request to eight projects. A sheet allows 80 graphic/resource
+ elements, 5 MiB per decoded image, 512 KiB per SVG, and 20 MiB each for cumulative
+ decoded inputs and PNG outputs. SVG outputs are at most 1,600 pixels per side;
+ raster input is limited to 40 million pixels. Reads use checked file handles.
+- Rights start as unknown; an owned/licensed declaration is recorded as a
+ declaration, not independently verified. No license is inferred. A public repo
+ requires separate explicit content, owner, name and visibility approval.
+
+API: `GET /api/music-video/:id/making-of/catalog`,
+`POST /api/music-video/making-of/preview`, and
+`POST /api/music-video/making-of/export`. POST bodies use the strict
+`musicVideoMakingOfSelectionSchema`; export additionally requires the returned
+`previewDigest`. No API accepts a filesystem path or shell command.
+
+## Follow-up boundaries
+
+An eventual GitHub publishing feature needs a supported authenticated integration,
+an explicit destination/content review and truthful publication status. None is
+implemented here. Layout-faithful full-page rendering, video/audio packaging,
+external-resource fetching and historical whole-project snapshots are also
+outside this initial exporter.
+
+The current production-planning importer projects rich shot objects down to
+action/staging/camera/transition. Binding an editable action into a Board scene
+also crosses a 4,000-character action limit into a 2,000-character visual-intent
+limit. A focused validation/field-contract follow-up should address that boundary;
+this change preserves selected source planning rather than altering authoring.
+
+Validation: synthetic Express-route tests cover determinism/checksums, exact
+versions, richer source retention, two variants, missing planning, ownership,
+private-content redaction, symlinks, size bounds, stale previews, a native
+photographic cast sheet, a native SVG character sheet, 26 ordered storyboard
+graphics, partial unsafe-resource exclusions and selected shared owners. Component
+tests cover explicit selection, rights/credits, inventory-before-download and
+superseded project responses. No live project data is used.
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index eb3009f639..69403bf69f 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -12,6 +12,26 @@ import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicV
import { z } from 'zod';
+const makingOfId = z.string().regex(/^[A-Za-z0-9_-]{1,100}$/);
+export const musicVideoMakingOfSelectionSchema = z.object({
+ projects: z.array(z.object({
+ projectId: makingOfId,
+ snapshot: z.string().regex(/^[a-f0-9]{64}$/),
+ assets: z.array(z.object({
+ id: z.string().min(1).max(250),
+ rights: z.enum(['unknown', 'owned', 'licensed']).default('unknown'),
+ attribution: z.string().max(2000).default(''),
+ ownershipConfirmed: z.boolean().default(false),
+ }).strict()).max(300),
+ }).strict()).min(1).max(8),
+ previewDigest: z.string().regex(/^[a-f0-9]{64}$/).optional(),
+}).strict().superRefine((selection, ctx) => {
+ if (new Set(selection.projects.map(p => p.projectId)).size !== selection.projects.length
+ || selection.projects.some(p => new Set(p.assets.map(a => a.id)).size !== p.assets.length)) {
+ ctx.addIssue({ code: 'custom', message: 'Duplicate project or asset selection' });
+ }
+});
+
export const musicVideoSongDraftSchema = z.object({
title: z.string().trim().min(1).max(80), style: z.string().trim().min(1).max(1000),
lyrics: z.string().max(5000), instrumental: z.boolean().default(false),
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index f3a77283f3..a88451902c 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -751,6 +751,31 @@ router.delete('/:id/composition/document/candidate', asyncHandler(async (req, re
res.json(await discardGeneratedDocument(req.params.id, directory));
}));
+// Local making-of compilation. The preview digest binds download to the exact
+// reviewed metadata, content, rights declarations and explicit asset selection.
+router.get('/:id/making-of/catalog', asyncHandler(async (req, res) => {
+ const { getMakingOfCatalog } = await import('../services/musicVideo/makingOf.js');
+ res.json(await getMakingOfCatalog(req.params.id));
+}));
+
+router.post('/making-of/preview', asyncHandler(async (req, res) => {
+ const { musicVideoMakingOfSelectionSchema } = await import('../lib/musicVideoValidation.js');
+ const input = validateRequest(musicVideoMakingOfSelectionSchema, req.body ?? {});
+ const { compileMakingOf } = await import('../services/musicVideo/makingOf.js');
+ res.json(await compileMakingOf(input));
+}));
+
+router.post('/making-of/export', asyncHandler(async (req, res) => {
+ const { musicVideoMakingOfSelectionSchema } = await import('../lib/musicVideoValidation.js');
+ const input = validateRequest(musicVideoMakingOfSelectionSchema, req.body ?? {});
+ const { compileMakingOf } = await import('../services/musicVideo/makingOf.js');
+ const { zip } = await compileMakingOf(input, { download: true });
+ res.set('Content-Type', 'application/zip');
+ res.set('Content-Disposition', 'attachment; filename="music-video-making-of.zip"');
+ res.set('Cache-Control', 'no-store');
+ res.send(zip);
+}));
+
router.get('/:id/composition/document/export', asyncHandler(async (req, res) => {
const { zip, filename } = await exportDocumentZip(await requireProject(req.params.id));
res.set('Content-Type', 'application/zip');
diff --git a/server/routes/musicVideoMakingOf.test.js b/server/routes/musicVideoMakingOf.test.js
new file mode 100644
index 0000000000..90eb673c80
--- /dev/null
+++ b/server/routes/musicVideoMakingOf.test.js
@@ -0,0 +1,397 @@
+import { beforeEach, afterAll, describe, it, expect, vi } from 'vitest';
+import express from 'express';
+import { mkdir, writeFile, symlink, link as hardLinkFile, truncate } from 'node:fs/promises';
+import { join } from 'node:path';
+import { createHash } from 'node:crypto';
+import sharp from 'sharp';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { lazyTempDataRoot, makePathsProxy, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+
+const { records, jobs } = vi.hoisted(() => ({ records: new Map(), jobs: new Map() }));
+vi.mock('../lib/fileUtils.js', async importOriginal => makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-making-of-') }));
+vi.mock('../services/musicVideo/projects.js', async importOriginal => ({ ...await importOriginal(), getProject: vi.fn(async id => records.get(id) || null) }));
+vi.mock('../services/mediaJobQueue/index.js', () => ({ getJob: id => jobs.get(id) }));
+import musicVideoRoutes from './musicVideo.js';
+import { compileMakingOf, getMakingOfCatalog } from '../services/musicVideo/makingOf.js';
+import { renderCastAndSetsSheet } from '../services/musicVideo/castAndSetsSheet.js';
+
+const root = () => lazyTempDataRoot('portos-making-of-');
+const app = express();
+app.use(express.json());
+app.use('/api/music-video', musicVideoRoutes);
+app.use(errorMiddleware);
+afterAll(cleanupTempDataRoots);
+
+async function file(relative, data) {
+ const path = join(root(), relative);
+ await mkdir(join(path, '..'), { recursive: true });
+ await writeFile(path, data);
+}
+const artifact = (id, ext = 'html', source = 'generated') => ({ id, kind: 'cast-sets', title: 'Example guide', version: 1, status: 'pending',
+ versions: [{ version: 1, source, file: `music-video/mv-example/dev/${id}/v1.${ext}` }] });
+function fixture(extra = {}) {
+ return { id: 'mv-example', name: 'Example Blueprint', version: 1, mediaMode: 'code-only', updatedAt: '2026-01-01T00:00:00Z',
+ concept: { prompt: 'Example story' }, audioAnalysis: { durationSec: 120 },
+ scenes: [{ sceneId: 'scene-example', label: '=unsafe formula', startSec: 0, endSec: 12, visualIntent: 'Open at the fictional harbor', framePrompt: 'A room', takes: [] }],
+ lyricCues: [{ id: 'cue-example', text: 'Example lyric', startSec: 0, endSec: 5, words: [{ w: 'Example', startSec: 0, endSec: 1 }] }],
+ productionReview: { draft: { cast: 'A keeper', environments: 'Harbor', storyboard: [{ id: 'shot-example', sceneId: 'scene-example', startSec: 0, endSec: 12, lyricCueIds: ['cue-example'], action: 'Light the lamp', staging: 'Doorway', camera: 'Dolly', transition: 'Hold' }] } },
+ devArtifacts: [], ...extra };
+}
+async function select(ids = []) {
+ const catalog = await request(app).get('/api/music-video/mv-example/making-of/catalog');
+ expect(catalog.status).toBe(200);
+ return { projects: [{ projectId: 'mv-example', snapshot: catalog.body.snapshot, assets: ids.map(id => ({ id, rights: 'unknown', attribution: '' })) }] };
+}
+async function preview(selection) {
+ const result = await request(app).post('/api/music-video/making-of/preview').send(selection);
+ expect(result.status).toBe(200);
+ return result.body;
+}
+// Stored ZIP members: inspect the actual deliverable bytes, not only its echo.
+function members(zip) {
+ const entries = new Map();
+ let offset = 0;
+ while (zip.readUInt32LE(offset) === 0x04034b50) {
+ const size = zip.readUInt32LE(offset + 18);
+ const nameLength = zip.readUInt16LE(offset + 26);
+ const extraLength = zip.readUInt16LE(offset + 28);
+ const name = zip.subarray(offset + 30, offset + 30 + nameLength).toString();
+ const start = offset + 30 + nameLength + extraLength;
+ entries.set(name, zip.subarray(start, start + size));
+ offset = start + size;
+ }
+ return entries;
+}
+beforeEach(() => { records.clear(); jobs.clear(); records.set('mv-example', fixture()); });
+
+describe('local making-of compilation', () => {
+ it('keeps multiline entity-encoded image captions inert in exported Markdown', async () => {
+ const png = await sharp({ create: { width: 2, height: 2, channels: 3, background: '#227766' } }).png().toBuffer();
+ const sheet = artifact('caption-example');
+ records.get('mv-example').devArtifacts = [sheet];
+ await file(sheet.versions[0].file, `<img src="data:image/png;base64,${png.toString('base64')}" alt="Harbor [plate]\\\n\r\n&lt;script&gt;active()&lt;/script&gt;\n&lt;img src=evil onerror=active()&gt;">`);
+ const selection = await select(['artifact:caption-example:v1']);
+ selection.projects[0].assets[0] = { ...selection.projects[0].assets[0], rights: 'owned', ownershipConfirmed: true };
+ const result = await preview(selection);
+ const out = await compileMakingOf({ ...selection, previewDigest: result.previewDigest }, { download: true });
+ const md = members(out.zip).get('projects/mv-example/artifacts/caption-example/v1.md').toString();
+ expect(md).not.toMatch(/<script>|<img|\r/);
+ expect(md).toContain('&lt;script&gt;active()&lt;/script&gt;');
+ const link = md.split('\n').find(line => line.startsWith('!['));
+ expect(link).toContain('Harbor \\[plate\\]');
+ expect(link).toContain('&lt;img src=evil onerror=active()&gt;');
+ expect(link).toMatch(/\]\(v1-visuals\/visual-01-[a-f0-9]+\.png\)$/);
+ });
+
+ it('bakes mirrored and rotated JPEG orientation into portable pixels before stripping EXIF', async () => {
+ const colors = [[200, 20, 30], [20, 200, 30], [20, 30, 200], [200, 200, 20]];
+ const width = 48, height = 32;
+ const pixels = Buffer.alloc(width * height * 3);
+ for (let y = 0; y < height; y += 1) for (let x = 0; x < width; x += 1) {
+ const color = colors[(y >= height / 2 ? 2 : 0) + (x >= width / 2 ? 1 : 0)];
+ pixels.set(color, (y * width + x) * 3);
+ }
+ const orientations = [{ value: 2, corners: [1, 0, 3, 2], width, height },
+ { value: 6, corners: [2, 0, 3, 1], width: height, height: width },
+ { value: 7, corners: [3, 1, 2, 0], width: height, height: width }];
+ const sheet = artifact('orientation-example');
+ records.get('mv-example').devArtifacts = [sheet];
+ const inputs = await Promise.all(orientations.map(async orientation => {
+ const jpeg = await sharp(pixels, { raw: { width, height, channels: 3 } }).jpeg({ quality: 100, chromaSubsampling: '4:4:4' }).withMetadata({ orientation: orientation.value }).toBuffer();
+ expect((await sharp(jpeg).metadata()).orientation).toBe(orientation.value);
+ return `<img src="data:image/jpeg;base64,${jpeg.toString('base64')}" alt="Orientation ${orientation.value}">`;
+ }));
+ await file(sheet.versions[0].file, inputs.join('\n'));
+ const selection = await select(['artifact:orientation-example:v1']);
+ selection.projects[0].assets[0] = { ...selection.projects[0].assets[0], rights: 'owned', ownershipConfirmed: true };
+ const result = await preview(selection);
+ const out = await compileMakingOf({ ...selection, previewDigest: result.previewDigest }, { download: true });
+ const files = members(out.zip);
+ const visuals = out.manifest.inventory.filter(item => item.id.startsWith('artifact:orientation-example:v1:visual:'));
+ expect(visuals).toHaveLength(orientations.length);
+ for (let index = 0; index < visuals.length; index += 1) {
+ const image = files.get(visuals[index].path);
+ const metadata = await sharp(image).metadata();
+ const expected = orientations[index];
+ expect(metadata).toMatchObject({ width: expected.width, height: expected.height, format: 'png' });
+ expect(metadata.orientation).toBeUndefined(); expect(metadata.exif).toBeUndefined();
+ const { data, info } = await sharp(image).removeAlpha().raw().toBuffer({ resolveWithObject: true });
+ const positions = [[4, 4], [info.width - 5, 4], [4, info.height - 5], [info.width - 5, info.height - 5]];
+ positions.forEach(([x, y], corner) => colors[expected.corners[corner]].forEach((channel, component) => {
+ expect(Math.abs(data[(y * info.width + x) * info.channels + component] - channel)).toBeLessThan(10);
+ }));
+ }
+ });
+
+ it('marks unsupported CSS graphics and stylesheet dependencies partial without loading them', async () => {
+ const sheet = artifact('css-resource-example');
+ records.get('mv-example').devArtifacts = [sheet];
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(() => { throw new Error('Export must not fetch CSS'); });
+ try {
+ await file(sheet.versions[0].file, `<style>.panel{background-image:url(https://example.com/private-reference.png)}</style>
+ <div style="background:url(data:image/png;base64,AAAA)">Panel caption</div>
+ <section style="back\\67round-image:linear-gradient(red,blue)">Gradient caption</section>
+ <link rel="stylesheet" href="https://example.com/private-style.css"><p>Story notes</p>
+ <style>.plain{background-image: none; background:#123;}</style>`);
+ // Use the service boundary while spying: the route-test client itself uses fetch.
+ const catalog = await getMakingOfCatalog('mv-example');
+ const selection = { projects: [{ projectId: 'mv-example', snapshot: catalog.snapshot, assets: [{ id: 'artifact:css-resource-example:v1', rights: 'unknown' }] }] };
+ expect(catalog.assets[0]).toMatchObject({ status: 'partial', visualCount: 4 });
+ const result = await compileMakingOf(selection);
+ expect(result.manifest.inventory.find(item => item.id === 'artifact:css-resource-example:v1')).toMatchObject({ status: 'partial', reason: 'some-visuals-not-exported' });
+ const omitted = result.manifest.inventory.filter(item => item.id.startsWith('artifact:css-resource-example:v1:visual:'));
+ expect(omitted).toHaveLength(4);
+ expect(omitted.every(item => item.status === 'excluded' && item.reason === 'css-visual-not-exported' && item.path === null)).toBe(true);
+ const out = await compileMakingOf({ ...selection, previewDigest: result.previewDigest }, { download: true });
+ const md = members(out.zip).get('projects/mv-example/artifacts/css-resource-example/v1.md').toString();
+ expect(md.match(/omitted: css-visual-not-exported/g)).toHaveLength(4);
+ expect(md).toContain('Panel caption'); expect(md).toContain('Gradient caption'); expect(md).toContain('Story notes');
+ expect(out.zip.toString()).not.toMatch(/https?:\/\/|data:image|<style|<link/);
+ await file(sheet.versions[0].file, '<div style="background-image:url(https://example.com/reference.png)"></div>'.repeat(81));
+ expect((await getMakingOfCatalog('mv-example')).assets[0]).toMatchObject({ status: 'excluded', reason: 'visual-count-limit' });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ } finally { fetchSpy.mockRestore(); }
+ });
+
+ it('retains native cast/set raster plates and all 26 static storyboard graphics as portable images in source order', async () => {
+ const png = await sharp({ create: { width: 16, height: 9, channels: 3, background: '#227766' } }).png().toBuffer();
+ const cast = artifact('visual-cast-example');
+ const storyboard = artifact('visual-board-example'); storyboard.kind = 'storyboard';
+ records.get('mv-example').devArtifacts = [cast, storyboard];
+ const castHTML = renderCastAndSetsSheet({ title: 'Example Production',
+ direction: { protagonist: { name: 'Example Keeper' }, sets: [{ id: 'harbor', name: 'Harbor', description: 'Lanterns', lighting: 'Warm', sections: [] }], tests: [], looks: [], songMap: [] },
+ images: { character: `data:image/png;base64,${png.toString('base64')}`, 'set:harbor': `data:image/png;base64,${png.toString('base64')}` } });
+ const boardHTML = `<html><style>body{background:#111}</style><h1>Full storyboard</h1>${Array.from({ length: 26 }, (_, index) => `<figure><h2>Shot ${index + 1}</h2><svg viewBox="0 0 160 90" role="img" aria-label="Shot ${index + 1}"><rect x="0" y="0" width="160" height="90" fill="#17232f"/><circle cx="80" cy="45" r="${index + 2}" fill="#ffbb66"/><text x="8" y="15" font-size="12" fill="#ffffff">S${index + 1}</text></svg><figcaption>Hold at the harbor — ${index + 1}</figcaption></figure>`).join('')}</html>`;
+ await file(cast.versions[0].file, castHTML);
+ await file(storyboard.versions[0].file, boardHTML);
+ const selection = await select(['artifact:visual-cast-example:v1', 'artifact:visual-board-example:v1']);
+ // Raster bytes are not inferred to be owned merely because their container was generated.
+ const undeclared = await preview(selection);
+ expect(undeclared.manifest.inventory.filter(item => item.id.startsWith('artifact:visual-cast-example:v1:visual:')).every(item => item.reason === 'embedded-raster-ownership-unverified')).toBe(true);
+ selection.projects[0].assets[0] = { ...selection.projects[0].assets[0], rights: 'owned', attribution: 'Original project art', ownershipConfirmed: true };
+ const inventory = await preview(selection);
+ const out = await compileMakingOf({ ...selection, previewDigest: inventory.previewDigest }, { download: true });
+ const files = members(out.zip);
+ const boardVisuals = out.manifest.inventory.filter(item => item.id.startsWith('artifact:visual-board-example:v1:visual:'));
+ expect(boardVisuals).toHaveLength(26);
+ expect(boardVisuals.every(item => item.status === 'included' && files.has(item.path))).toBe(true);
+ const castVisuals = out.manifest.inventory.filter(item => item.id.startsWith('artifact:visual-cast-example:v1:visual:'));
+ expect(castVisuals).toHaveLength(2);
+ expect(castVisuals.every(item => item.status === 'included' && item.rights === 'owned' && item.provenance.ownership === 'operator-declared')).toBe(true);
+ const boardMD = files.get('projects/mv-example/artifacts/visual-board-example/v1.md').toString();
+ expect(boardMD.indexOf('Shot 1')).toBeLessThan(boardMD.indexOf('Shot 26'));
+ expect(boardMD).toContain('Hold at the harbor — 26');
+ expect(boardMD.match(/!\[[^\]]*\]\(v1-visuals\/[^)]+\.png\)/g)).toHaveLength(26);
+ expect(files.get('projects/mv-example/storyboard.md').toString()).toContain('artifacts/visual-board-example/v1.md');
+ expect(out.zip.toString()).not.toMatch(/<svg|<script|data:image|https?:\/\//);
+ for (const visual of [...boardVisuals, ...castVisuals]) {
+ const metadata = await sharp(files.get(visual.path)).metadata();
+ expect(metadata.format).toBe('png'); expect(metadata.exif).toBeUndefined();
+ expect(createHash('sha256').update(files.get(visual.path)).digest('hex')).toBe(visual.sha256);
+ }
+ expect((await compileMakingOf({ ...selection, previewDigest: inventory.previewDigest }, { download: true })).zip.equals(out.zip)).toBe(true);
+ });
+
+ it('preserves actual procedural cast definitions without executing a browser or exporting active SVG', async () => {
+ const cast = artifact('procedural-cast-example');
+ records.get('mv-example').devArtifacts = [cast];
+ const direction = { medium: 'procedural', protagonist: { name: 'Example boat' }, sets: [],
+ definitions: { characters: [{ id: 'boat', name: 'Paper boat', renderer: 'svg', palette: [{ name: 'cream', hex: '#f5f0e6' }],
+ parts: [{ id: 'hull', shape: 'rect', x: 40, y: 100, width: 120, height: 40, fill: 'cream' }],
+ expressions: [{ name: 'proud', overrides: { hull: { rotate: -5 } } }], poses: [], motion: [] }] } };
+ await file(cast.versions[0].file, renderCastAndSetsSheet({ title: 'Example Blueprint', direction }));
+ const selection = await select(['artifact:procedural-cast-example:v1']);
+ const result = await preview(selection);
+ expect(result.manifest.inventory.filter(item => item.id.startsWith('artifact:procedural-cast-example:v1:visual:'))).toEqual([
+ expect.objectContaining({ status: 'included', provenance: expect.objectContaining({ ownership: 'project-generated' }) }),
+ expect.objectContaining({ status: 'included', provenance: expect.objectContaining({ ownership: 'project-generated' }) }),
+ ]);
+ });
+
+ it('rejects active, remote, entity-bearing and unsafe SVG graphics with per-item errors and bounded decoded bytes', async () => {
+ const sheet = artifact('unsafe-visual-example');
+ records.get('mv-example').devArtifacts = [sheet];
+ const svg = body => `<svg viewBox="0 0 16 9">${body}</svg>`;
+ await file(sheet.versions[0].file, `<h1>Unapproved resources</h1>${svg('<image href="file:///private-source"/>')}${svg('<rect width="16" height="9" fill="url(https://example.com/reference.png)"/>')}${svg('<text>&external;</text>')}<img src="https://example.com/reference.png"><script>fetch('https://example.com/private')</script><canvas>Needs active rendering</canvas>&lt;script&gt;escapedActiveText()&lt;/script&gt;`);
+ const selected = await select(['artifact:unsafe-visual-example:v1']);
+ selected.projects[0].assets[0] = { ...selected.projects[0].assets[0], rights: 'owned', ownershipConfirmed: true };
+ const result = await preview(selected);
+ const errors = result.manifest.inventory.filter(item => item.id.startsWith('artifact:unsafe-visual-example:v1:visual:'));
+ expect(errors).toHaveLength(6);
+ expect(errors.every(item => item.status === 'excluded' && item.path === null)).toBe(true);
+ expect(errors.map(item => item.reason)).toEqual(['unsafe-or-invalid-svg', 'unsafe-or-invalid-svg', 'unsafe-or-invalid-svg', 'remote-visual-not-exported', 'active-visual-not-exported', 'active-visual-not-exported']);
+ expect(result.manifest.inventory.find(item => item.id === 'artifact:unsafe-visual-example:v1').status).toBe('partial');
+ const out = await compileMakingOf({ ...selected, previewDigest: result.previewDigest }, { download: true });
+ expect(out.zip.toString()).not.toMatch(/<svg|<script|https?:\/\/|\/private-source/);
+ await file(sheet.versions[0].file, '<img src="data:image/png;base64,' + Buffer.alloc(5 * 1024 * 1024 + 1).toString('base64') + '">');
+ expect((await preview(selected)).manifest.inventory.find(item => item.id.endsWith(':visual:1')).reason).toBe('visual-size-limit');
+ await file(sheet.versions[0].file, Array.from({ length: 81 }, () => svg('<rect width="16" height="9" fill="#ffffff"/>')).join(''));
+ expect((await preview(selected)).manifest.inventory.find(item => item.id === 'artifact:unsafe-visual-example:v1')).toMatchObject({ status: 'excluded', reason: 'visual-count-limit' });
+ });
+
+ it('admits selected shared references and cloned artifacts only through a selected owning project or an explicit owned declaration', async () => {
+ const png = await sharp({ create: { width: 2, height: 2, channels: 3, background: 'blue' } }).png().toBuffer();
+ const sourceArtifact = artifact('shared-guide-example');
+ const owner = records.get('mv-example');
+ owner.devArtifacts = [sourceArtifact];
+ owner.castAndSets = { plan: { 'set:harbor': { label: 'Harbor' } }, images: { 'set:harbor': { imageId: 'shared-owned.png', jobId: 'shared-job' } } };
+ jobs.set('shared-job', { kind: 'image', params: { musicVideo: { projectId: owner.id, castAndSets: { key: 'set:harbor' } } }, result: { filename: 'shared-owned.png' } });
+ await file('images/shared-owned.png', png); await file(sourceArtifact.versions[0].file, '<h1>Shared original guide</h1>');
+ const hybrid = fixture({ id: 'mv-shared-hybrid', name: 'Example Shared Hybrid', devArtifacts: [sourceArtifact],
+ visualSpec: { references: [{ id: 'shared-reference', imageId: 'shared-owned.png', label: 'Shared owned set' }] } });
+ records.set(hybrid.id, hybrid);
+ const hybridCatalog = await request(app).get(`/api/music-video/${hybrid.id}/making-of/catalog`);
+ const selection = { projects: [{ projectId: hybrid.id, snapshot: hybridCatalog.body.snapshot, assets: [{ id: 'reference:shared-reference', rights: 'unknown' }, { id: 'artifact:shared-guide-example:v1', rights: 'unknown' }] }] };
+ const alone = await preview(selection);
+ expect(alone.manifest.inventory.find(item => item.id === 'reference:shared-reference').reason).toBe('ownership-unverified');
+ expect(alone.manifest.inventory.find(item => item.id === 'artifact:shared-guide-example:v1').reason).toBe('owner-project-not-selected');
+ const ownerCatalog = await request(app).get(`/api/music-video/${owner.id}/making-of/catalog`);
+ selection.projects.push({ projectId: owner.id, snapshot: ownerCatalog.body.snapshot, assets: [] });
+ const verified = await preview(selection);
+ expect(verified.manifest.inventory.find(item => item.projectId === hybrid.id && item.id === 'reference:shared-reference')).toMatchObject({ status: 'included', delivery: 'file', provenance: expect.objectContaining({ sourceProjectId: owner.id, ownership: 'project-generated' }) });
+ expect(verified.manifest.inventory.find(item => item.projectId === hybrid.id && item.id === 'artifact:shared-guide-example:v1').status).toBe('included');
+ expect(verified.manifest.inventory.find(item => item.projectId === owner.id && item.id === 'cast:set:harbor').status).toBe('not-selected');
+ jobs.clear();
+ selection.projects[0].assets[0] = { ...selection.projects[0].assets[0], rights: 'owned', ownershipConfirmed: true };
+ expect((await preview(selection)).manifest.inventory.find(item => item.projectId === hybrid.id && item.id === 'reference:shared-reference')).toMatchObject({ status: 'included', provenance: expect.objectContaining({ ownership: 'operator-declared' }) });
+ });
+
+ it('exports selected exact versions and original rich planning alongside the current draft, with deterministic bytes and checksums', async () => {
+ const source = { master: { contentHash: 'a'.repeat(64), durationSec: 120 }, storyboard: Array.from({ length: 26 }, (_, i) => ({ id: `interval-${i}`, purpose: 'Hold', treatment: 'composite', castIds: ['keeper'], setId: 'harbor', wordAnchors: ['cue-example:0'], overlay: { caption: 'Example' } })), api_key: 'synthetic-private-value' };
+ source.assets = [{ id: 'panel-example', path: 'panels/scene-example.png', privatePath: '/Users/example/internal/source.png', bytes: [137, 80, 78] }];
+ const escaped = JSON.stringify(source).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+ const guide = artifact('guide-example');
+ guide.versions.push({ version: 2, source: 'generated', file: 'music-video/mv-example/dev/guide-example/v2.html' });
+ guide.version = 2;
+ const original = artifact('original-example', 'html', 'planning-import');
+ original.kind = 'other';
+ records.get('mv-example').devArtifacts = [guide, original];
+ await file(guide.versions[0].file, '<h1>Version one</h1><img src="data:image/png;base64,THIRD_PARTY"><script>privateStuff()</script>');
+ await file(guide.versions[1].file, '<h1>Version two</h1>');
+ await file(original.versions[0].file, `<pre>${escaped}</pre>`);
+ const selection = await select(['artifact:guide-example:v1', 'artifact:original-example:v1']);
+ const inventory = await preview(selection);
+ const out = await compileMakingOf({ ...selection, previewDigest: inventory.previewDigest }, { download: true });
+ const again = await compileMakingOf({ ...selection, previewDigest: inventory.previewDigest }, { download: true });
+ expect(out.zip.equals(again.zip)).toBe(true);
+ const files = members(out.zip);
+ expect(files.get('projects/mv-example/artifacts/guide-example/v1.md').toString()).toContain('Version one');
+ expect(out.zip.toString()).not.toMatch(/Version two|THIRD_PARTY|privateStuff|synthetic-private-value|data:image/);
+ const originalJSON = JSON.parse(files.get('projects/mv-example/artifacts/original-example/v1.json'));
+ expect(originalJSON.storyboard).toHaveLength(26);
+ expect(originalJSON.storyboard[0]).toMatchObject({ treatment: 'composite', castIds: ['keeper'], wordAnchors: ['cue-example:0'] });
+ expect(originalJSON.assets[0]).toEqual({ id: 'panel-example', path: 'panels/scene-example.png', privatePath: '[path omitted]' });
+ expect(out.manifest.inventory.find(item => item.sourceAssetId === 'panel-example')).toMatchObject({ status: 'excluded', delivery: 'metadata-only', reason: 'source-planning-metadata-only' });
+ expect(files.get('projects/mv-example/artifacts/original-example/v1-storyboard.csv').toString()).toContain('wordAnchors');
+ expect(files.get('projects/mv-example/artifacts/original-example/v1-storyboard.md').toString()).toContain('interval-25');
+ const plan = JSON.parse(files.get('projects/mv-example/planning.json'));
+ expect(plan.originalScenes).toHaveLength(1);
+ expect(plan.shots[0]).toMatchObject({ id: 'shot-example', action: 'Light the lamp', lyricCueIds: ['cue-example'] });
+ expect(plan.master).toMatchObject({ durationSec: 120, contentHashStatus: 'not-recorded' });
+ expect(plan.readiness.storyboard.approved).toBe(false);
+ expect(files.get('projects/mv-example/shots.csv').toString()).toContain("'=unsafe formula");
+ expect(out.manifest.inventory.find(item => item.id === 'artifact:guide-example:v1').provenance.reviewStatus).toBe('historical-unverified');
+ for (const line of files.get('SHA256SUMS').toString().trim().split('\n')) {
+ const [digest, path] = line.split(' ');
+ expect(createHash('sha256').update(files.get(path)).digest('hex')).toBe(digest);
+ }
+ const download = await request(app).post('/api/music-video/making-of/export').send({ ...selection, previewDigest: inventory.previewDigest });
+ expect(download.status).toBe(200);
+ expect(download.headers['content-type']).toContain('application/zip');
+ expect(records.get('mv-example').devArtifacts).toEqual([guide, original]);
+ });
+
+ it('includes two independent variants and keeps missing planning and files explicit', async () => {
+ const second = fixture({ id: 'mv-hybrid', name: 'Example Hybrid', version: 2, parentProjectId: 'mv-example', scenes: [], devArtifacts: [], productionReview: {} });
+ records.set(second.id, second);
+ const missing = artifact('missing-example', 'png');
+ records.get('mv-example').devArtifacts = [missing];
+ const selected = await select(['artifact:missing-example:v1']);
+ const catalog = await request(app).get('/api/music-video/mv-hybrid/making-of/catalog');
+ selected.projects.push({ projectId: second.id, snapshot: catalog.body.snapshot, assets: [] });
+ const result = await preview(selected);
+ expect(result.manifest.projects).toHaveLength(2);
+ expect(result.manifest.inventory).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: 'artifact:missing-example:v1', status: 'missing' }),
+ expect.objectContaining({ projectId: second.id, id: 'missing:shots', status: 'missing' }),
+ expect.objectContaining({ projectId: second.id, id: 'missing:cast-planning', status: 'missing' }),
+ ]));
+ expect(result.manifest.publication).toBe('not-published');
+ });
+
+ it('refuses stale previews and invalid selections before downloading', async () => {
+ const selection = await select();
+ const result = await preview(selection);
+ expect((await request(app).post('/api/music-video/making-of/export').send(selection)).status).toBe(409);
+ records.get('mv-example').scenes[0].visualIntent = 'Changed planning';
+ expect((await request(app).post('/api/music-video/making-of/export').send({ ...selection, previewDigest: result.previewDigest })).status).toBe(409);
+ expect((await request(app).post('/api/music-video/making-of/preview').send({ projects: [{ ...selection.projects[0], projectId: '../escape' }] })).status).toBe(400);
+ expect((await request(app).post('/api/music-video/making-of/preview').send({ projects: [selection.projects[0], selection.projects[0]] })).status).toBe(400);
+ const fresh = await select(['artifact:not-owned:v1']);
+ expect((await request(app).post('/api/music-video/making-of/preview').send(fresh)).status).toBe(400);
+ });
+
+ it('excludes cross-project paths, symlinks, uploaded references and oversize files, without reading their bytes', async () => {
+ const cross = artifact('cross-example'); cross.versions[0].file = 'music-video/mv-other/dev/cross-example/v1.html';
+ const link = artifact('link-example', 'md');
+ const uploaded = artifact('upload-example', 'png', 'upload');
+ const large = artifact('large-example', 'png');
+ const directoryLink = artifact('directory-link-example', 'md');
+ const hardLink = artifact('hard-link-example', 'md');
+ const forgedImage = artifact('forged-image-example', 'png');
+ await file('private-secret.md', 'not-for-export');
+ await mkdir(join(root(), 'music-video/mv-example/dev/link-example'), { recursive: true });
+ await symlink(join(root(), 'private-secret.md'), join(root(), link.versions[0].file));
+ await file('outside-project/v1.md', 'not-for-export');
+ await symlink(join(root(), 'outside-project'), join(root(), 'music-video/mv-example/dev/directory-link-example'));
+ await mkdir(join(root(), 'music-video/mv-example/dev/hard-link-example'), { recursive: true });
+ await hardLinkFile(join(root(), 'private-secret.md'), join(root(), hardLink.versions[0].file));
+ await file(forgedImage.versions[0].file, '<svg><image href="file:///private-source"/></svg>');
+ await file(large.versions[0].file, ''); await truncate(join(root(), large.versions[0].file), 21 * 1024 * 1024);
+ records.get('mv-example').devArtifacts = [cross, link, uploaded, large, directoryLink, hardLink, forgedImage];
+ const selected = await select(['artifact:cross-example:v1', 'artifact:link-example:v1', 'artifact:upload-example:v1', 'artifact:large-example:v1', 'artifact:directory-link-example:v1', 'artifact:hard-link-example:v1', 'artifact:forged-image-example:v1']);
+ selected.projects[0].assets.forEach(asset => { asset.rights = 'owned'; });
+ const result = await preview(selected);
+ expect(result.manifest.inventory.filter(item => item.id.startsWith('artifact:')).map(item => item.reason).sort()).toEqual(['invalid-or-oversize-image', 'owner-project-not-selected', 'ownership-unverified', 'shared-file-link', 'size-limit', 'symlink', 'symlink']);
+ expect(JSON.stringify(result)).not.toContain('not-for-export');
+ });
+
+ it('includes only tagged project-generated gallery images, strips image metadata and detects changed bytes', async () => {
+ const project = records.get('mv-example');
+ project.castAndSets = { plan: { character: { label: 'Keeper', prompt: 'A keeper' } }, images: { character: { imageId: 'example-owned.png', jobId: 'job-example' } } };
+ project.scenes[0].referenceImageId = 'example-reference.png';
+ project.scenes[0].takes = [{ kind: 'image', assetId: 'example-reference.png', source: 'imported' }];
+ project.visualSpec = { references: [{ imageId: 'example-reference.png' }] };
+ jobs.set('job-example', { kind: 'image', params: { musicVideo: { projectId: project.id, castAndSets: { key: 'character' } } }, result: { filename: 'example-owned.png' } });
+ const png = await sharp({ create: { width: 2, height: 2, channels: 3, background: 'red' } }).png().toBuffer();
+ await file('images/example-owned.png', png);
+ const selected = await select(['cast:character', 'frame:scene-example']);
+ const result = await preview(selected);
+ expect(result.manifest.inventory.find(item => item.id === 'cast:character')).toMatchObject({ status: 'included', transformation: 'raster re-encoded without metadata' });
+ expect(result.manifest.inventory.find(item => item.id === 'frame:scene-example')).toMatchObject({ status: 'excluded', reason: 'ownership-unverified' });
+ expect(result.manifest.inventory.find(item => item.kind === 'reference')).toMatchObject({ status: 'excluded', delivery: 'metadata-only', reason: 'ownership-unverified' });
+ await file('images/example-owned.png', await sharp(png).negate().png().toBuffer());
+ await expect(compileMakingOf({ ...selected, previewDigest: result.previewDigest }, { download: true })).rejects.toMatchObject({ code: 'MAKING_OF_CHANGED' });
+ jobs.get('job-example').params.musicVideo.projectId = 'mv-other';
+ expect((await preview(selected)).manifest.inventory.find(item => item.id === 'cast:character')).toMatchObject({ status: 'excluded', reason: 'ownership-unverified' });
+ });
+
+ it('redacts private paths, tailnet URLs and credentials in selected creative fields and source planning', async () => {
+ const project = records.get('mv-example');
+ project.concept.prompt = 'A lamp /Users/example/private/file.txt https://private-node.example.ts.net/data api_key=example-secret';
+ project.productionReview.draft.cast = 'Bearer synthetic-credential sk-examplesecret';
+ project.name = 'Example </a><script>active()</script>';
+ project.productionReview.draft.storyboard[0].action = '<script>active()</script> ![external](javascript:active)';
+ project.castAndSets = { direction: { notes: '```\n<script>cast()</script>' } };
+ const selected = await select();
+ const result = await preview(selected);
+ const out = await compileMakingOf({ ...selected, previewDigest: result.previewDigest }, { download: true });
+ expect(out.zip.toString()).not.toMatch(/\/Users\/|\.ts\.net|example-secret|synthetic-credential|sk-examplesecret/);
+ expect(out.zip.toString()).toContain('[credential omitted]');
+ const files = members(out.zip);
+ expect(files.get('README.md').toString()).not.toContain('<script>');
+ expect(files.get('projects/mv-example/storyboard.md').toString()).not.toMatch(/<script>|javascript:/);
+ expect(files.get('projects/mv-example/cast-set-sheet.md').toString()).toContain(' {');
+ });
+});
diff --git a/server/services/musicVideo/makingOf.js b/server/services/musicVideo/makingOf.js
new file mode 100644
index 0000000000..14ae9d7e87
--- /dev/null
+++ b/server/services/musicVideo/makingOf.js
@@ -0,0 +1,400 @@
+/** Read-only, deterministic making-of packages. No network, persistence or publication. */
+import { constants } from 'node:fs';
+import { lstat, open } from 'node:fs/promises';
+import { extname, join } from 'node:path';
+import { createHash } from 'node:crypto';
+import { PATHS } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { createZip } from '../../lib/zipWriter.js';
+import { escapeRegExp } from '../../lib/textUtils.js';
+import { getProject } from './projects.js';
+import { productionReadiness, productionAlignmentBasis } from './productionReview.js';
+import { extractMakingOfVisuals, reencodeMakingOfRaster, MAKING_OF_VISUAL_LIMITS } from './makingOfVisuals.js';
+
+const SEGMENT = /^[A-Za-z0-9_-]{1,100}$/;
+const validSegment = value => typeof value === 'string' && SEGMENT.test(value);
+const TYPES = new Set(['.png', '.jpg', '.jpeg', '.webp', '.md', '.html', '.htm']);
+const MAX_FILE = 20 * 1024 * 1024;
+const MAX_PACKAGE = 100 * 1024 * 1024;
+const MAX_ITEMS = 300;
+const rasterExtension = filename => {
+ const ext = extname(String(filename || '')).toLowerCase();
+ return ['.png', '.jpg', '.jpeg', '.webp'].includes(ext) ? ext : '.png';
+};
+const json = value => `${JSON.stringify(value, null, 2)}\n`;
+const hash = value => createHash('sha256').update(value).digest('hex');
+const conflict = () => { throw new ServerError('Planning or assets changed. Preview the inventory again.', { status: 409, code: 'MAKING_OF_CHANGED' }); };
+const badSelection = () => { throw new ServerError('Invalid making-of selection', { status: 400, code: 'VALIDATION_ERROR' }); };
+
+// Export a bounded projection, never raw records, provider configuration or logs.
+// Remove URLs (including private server links), absolute paths and recognizable
+// credentials even when pasted into an otherwise legitimate creative field.
+function scrubText(value, limit) {
+ if (typeof value !== 'string') return '';
+ if (value.length >= 256 && /^[A-Za-z0-9+/]+={0,2}$/.test(value)) return '[binary omitted]';
+ return value.slice(0, limit)
+ .replace(/(?:(?:https?:)?\/\/|file:\/\/|data:)[^\s<>"')]+/gi, '[link omitted]')
+ .replace(/(^|[\s('"=:])(?:[A-Z]:[\\/]|~[\\/]|\/)[^\s<>"')]+/gi, '$1[path omitted]')
+ .replace(/\\\\[^\s<>"')]+/g, '[path omitted]')
+ .replace(/\b[A-Za-z0-9.-]+\.ts\.net\b/gi, '[private host omitted]')
+ .replace(/\b(?:Bearer\s+\S+|(?:sk-|ghp_|github_pat_)[A-Za-z0-9_-]+|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\b/gi, '[credential omitted]')
+ .replace(/\b(?:api[_ -]?key|password|secret|token|authorization|cookie)\s*[:=]\s*[^\s,;]+/gi, '[credential omitted]');
+}
+const text = value => scrubText(value, 16000);
+const markdown = value => text(value).replace(/!?\[[^\]]*\]\([^)]*\)/g, '[link omitted]').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+const linkLabel = value => markdown(value).replace(/[\[\]\\]/g, character => escapeRegExp(character));
+const jsonBlock = value => json(value).split('\n').map(line => ` ${line}`).join('\n');
+const fields = (obj, keys) => Object.fromEntries(keys.map(k => [k, text(obj?.[k])]));
+const time = value => Number.isFinite(value) && value >= 0 ? value : null;
+
+// Original planning imports can carry richer contracts than the editable draft.
+// Preserve that structure, with explicit privacy redaction rather than projecting
+// it down to the four fields the current importer understands.
+function portable(value, depth = 0) {
+ if (depth > 25) return '[depth limit]';
+ if (typeof value === 'string') return scrubText(value, MAX_FILE);
+ if (Array.isArray(value)) return value.map(item => portable(item, depth + 1));
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value)
+ .filter(([key, item]) => !/(?:password|secret|token|credential|authorization|cookie|api[_-]?key|private[_-]?key|absolute[_-]?path|server[_-]?url|logs|base64|referenceBytes|imageData|binaryData|embeddedAssets)/i.test(key)
+ && !(/^(?:bytes|data|blob|buffer|binary)$/i.test(key) && (Array.isArray(item) || typeof item === 'string')))
+ .map(([key, item]) => [text(key), portable(item, depth + 1)]));
+ return value;
+}
+
+function planning(project) {
+ const draft = project.productionReview?.draft || {};
+ const direction = project.castAndSets?.direction;
+ const scenes = project.scenes || [];
+ const sourceShots = draft.storyboard?.length ? draft.storyboard : scenes;
+ const shots = sourceShots.map((shot, index) => {
+ const scene = scenes.find(s => s.sceneId === shot.sceneId) || shot;
+ return {
+ id: text(shot.id || shot.sceneId) || `unbound-${index + 1}`,
+ identityStatus: shot.id || shot.sceneId ? 'recorded' : 'missing',
+ sceneId: text(shot.sceneId) || null,
+ order: index,
+ startSec: time(shot.startSec), endSec: time(shot.endSec),
+ timingStatus: draft.timingStatus || 'provisional',
+ ...fields(scene, ['label', 'sectionLabel', 'lyricText', 'visualIntent', 'framePrompt', 'prompt', 'medium']),
+ ...fields(shot, ['action', 'staging', 'camera', 'transition']),
+ lyricCueIds: (shot.lyricCueIds || []).map(text),
+ };
+ });
+ return {
+ project: { id: project.id, name: text(project.name), version: project.version || 1, mediaMode: text(project.mediaMode), updatedAt: text(project.updatedAt),
+ parentProjectId: text(project.parentProjectId) || null, rootProjectId: text(project.rootProjectId) || project.id },
+ master: { durationSec: time(project.audioAnalysis?.durationSec), alignmentBasis: productionAlignmentBasis(project),
+ contentHash: text(project.audioAnalysis?.audioHash) || null, contentHashStatus: project.audioAnalysis?.audioHash ? 'recorded' : 'not-recorded' },
+ lyricCues: (project.lyricCues || []).map(cue => ({ id: text(cue.id), text: text(cue.text), startSec: time(cue.startSec), endSec: time(cue.endSec), words: portable(cue.words || []) })),
+ originalScenes: scenes.map(scene => ({ sceneId: text(scene.sceneId), startSec: time(scene.startSec), endSec: time(scene.endSec),
+ ...fields(scene, ['label', 'sectionLabel', 'visualIntent', 'framePrompt', 'prompt', 'medium']), action: portable(scene.action), direction: portable(scene.direction), visualLayer: portable(scene.visualLayer) })),
+ readiness: portable(productionReadiness(project)),
+ approvals: Object.fromEntries(Object.entries(project.productionReview?.approvals || {}).map(([stage, approval]) => [stage, fields(approval, ['basis', 'approvedAt'])])),
+ concept: fields(project.concept, ['prompt', 'style']),
+ castAndSets: direction ? portable(direction) : null,
+ review: { ...fields(draft, ['cast', 'environments', 'visualLanguage', 'motionLanguage', 'implementationPlan', 'timingNotes']), storyboardSource: text(draft.storyboardSource) || 'board' },
+ settings: {
+ compositionMode: text(project.composition?.mode), authoringRenderer: text(project.composition?.authoringRenderer),
+ aspectRatio: text(project.aspectRatio), strategy: text(project.productionPolicy?.strategy),
+ palette: (project.visualSpec?.palette || []).map(text), ...fields(project.visualSpec, ['cameraRules', 'typography']),
+ castSetsRoute: fields(project.castAndSets?.route, ['mode', 'model']),
+ },
+ shots,
+ };
+}
+
+function candidates(project) {
+ const items = [];
+ for (const artifact of project.devArtifacts || []) {
+ if (artifact.deleted || !validSegment(artifact.id)) continue;
+ for (const version of artifact.versions || []) {
+ if (!Number.isInteger(version.version) || version.version < 1) continue;
+ const ext = extname(String(version.file || '')).toLowerCase();
+ const safeExt = /^\.[a-z0-9]{1,5}$/.test(ext) ? ext : '.unsupported';
+ const expected = `music-video/${project.id}/dev/${artifact.id}/v${version.version}${ext}`;
+ items.push({ id: `artifact:${artifact.id}:v${version.version}`, kind: text(artifact.kind), label: `${text(artifact.title)} · v${version.version}`,
+ version: version.version, source: text(version.source), reviewStatus: version.version === artifact.version ? text(artifact.status) : 'historical-unverified',
+ relative: expected, ext,
+ recordedFile: version.file,
+ sharedArtifact: version.file !== expected,
+ ownershipRequired: !['generated', 'planning-import'].includes(version.source),
+ sourceAssetId: artifact.id,
+ path: `projects/${project.id}/artifacts/${artifact.id}/v${version.version}${version.source === 'planning-import' ? '.json' : ['.html', '.htm'].includes(ext) ? '.md' : safeExt}` });
+ }
+ }
+ for (const [key, item] of Object.entries(project.castAndSets?.plan || {})) {
+ if (!/^[A-Za-z0-9_:-]{1,100}$/.test(key)) continue;
+ const image = project.castAndSets?.images?.[key];
+ const filename = image?.imageId;
+ items.push({ id: `cast:${key}`, kind: 'cast-sets', label: text(item.label) || key,
+ source: 'generated', jobId: image?.jobId, filename, tag: { castKey: key },
+ sourceAssetId: /^[A-Za-z0-9_-]+\.(png|jpg|jpeg|webp)$/i.test(filename) ? filename : null,
+ ext: extname(String(filename || '')).toLowerCase(), path: `projects/${project.id}/images/cast-${key.replace(/:/g, '_')}-${hash(key).slice(0, 8)}${rasterExtension(filename)}`,
+ prompt: text(image?.submittedPrompt || item.prompt), generationStatus: text(image?.status), revision: image?.submittedRevision ?? null,
+ });
+ }
+ for (const scene of project.scenes || []) {
+ if (!validSegment(scene.sceneId)) continue;
+ const take = (scene.takes || []).find(t => t.kind === 'image' && t.assetId === scene.referenceImageId);
+ items.push({ id: `frame:${scene.sceneId}`, kind: 'storyboard', label: text(scene.label || scene.sectionLabel) || scene.sceneId,
+ source: text(take?.source), jobId: take?.jobId, filename: scene.referenceImageId, tag: { sceneId: scene.sceneId },
+ sourceAssetId: /^[A-Za-z0-9_-]+\.(png|jpg|jpeg|webp)$/i.test(scene.referenceImageId) ? scene.referenceImageId : null,
+ ext: extname(String(scene.referenceImageId || '')).toLowerCase(), path: `projects/${project.id}/images/frame-${scene.sceneId}${rasterExtension(scene.referenceImageId)}`,
+ prompt: text(take?.prompt || scene.framePrompt),
+ });
+ }
+ for (const reference of project.visualSpec?.references || []) {
+ const id = validSegment(reference.id) ? reference.id : hash(String(reference.imageId || reference.label || '')).slice(0, 16);
+ items.push({ id: `reference:${id}`, kind: 'reference', label: text(reference.label) || 'Visual reference', source: 'reference',
+ sourceAssetId: text(reference.id) || null, filename: reference.imageId,
+ path: `projects/${project.id}/images/reference-${id}${rasterExtension(reference.imageId)}`, ext: extname(String(reference.imageId || '')).toLowerCase() });
+ }
+ if (items.length > MAX_ITEMS) throw new ServerError('Too many export candidates', { status: 413, code: 'MAKING_OF_LIMIT' });
+ return items.sort((a, b) => a.id.localeCompare(b.id, 'en'));
+}
+
+async function loadProject(id) {
+ if (!validSegment(id)) badSelection();
+ const project = await getProject(id);
+ if (!project || project.id !== id || project.deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ return project;
+}
+
+// Reject every symlink component and open the leaf with O_NOFOLLOW. Read through
+// the checked handle with a bounded buffer, never follow arbitrary record paths.
+async function readOwned(relative) {
+ const segments = relative.split('/');
+ if (segments.some(s => !/^[A-Za-z0-9_.-]+$/.test(s) || s === '.' || s === '..')) return { status: 'excluded', reason: 'unsafe-path' };
+ let abs = PATHS.data;
+ let handle;
+ try {
+ for (const segment of ['', ...segments]) {
+ abs = segment ? join(abs, segment) : abs;
+ if ((await lstat(abs)).isSymbolicLink()) return { status: 'excluded', reason: 'symlink' };
+ }
+ handle = await open(abs, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ const stat = await handle.stat();
+ if (!stat.isFile()) return { status: 'excluded', reason: 'not-file' };
+ if (stat.nlink !== 1) return { status: 'excluded', reason: 'shared-file-link' };
+ if (stat.size > MAX_FILE) return { status: 'excluded', reason: 'size-limit' };
+ const data = Buffer.alloc(stat.size + 1);
+ let bytesRead = 0;
+ while (bytesRead < data.length) {
+ const read = await handle.read(data, bytesRead, data.length - bytesRead, bytesRead);
+ if (!read.bytesRead) break;
+ bytesRead += read.bytesRead;
+ }
+ const after = await handle.stat();
+ if (bytesRead !== stat.size || stat.mtimeMs !== after.mtimeMs || stat.size !== after.size) return { status: 'excluded', reason: 'changed-during-read' };
+ return { status: 'included', data: data.subarray(0, bytesRead) };
+ } catch (err) {
+ return { status: err.code === 'ENOENT' ? 'missing' : 'excluded', reason: err.code === 'ENOENT' ? 'file-missing' : 'unreadable' };
+ } finally { await handle?.close(); }
+}
+
+function declaredOwnership(pick) { return pick?.ownershipConfirmed === true && pick.rights === 'owned'; }
+
+async function galleryGeneration(filename, owners) {
+ const { getJob } = await import('../mediaJobQueue/index.js');
+ for (const owner of owners) {
+ const images = Object.entries(owner.castAndSets?.images || {}).filter(([, image]) => image.imageId === filename)
+ .map(([key, image]) => ({ jobId: image.jobId, key }));
+ for (const scene of owner.scenes || []) {
+ for (const take of scene.takes || []) {
+ if (take.kind === 'image' && take.source === 'generated' && take.assetId === filename) images.push({ jobId: take.jobId, sceneId: scene.sceneId });
+ }
+ }
+ for (const image of images) {
+ const job = image.jobId ? getJob(image.jobId) : null;
+ const tag = job?.params?.musicVideo;
+ if (job?.kind === 'image' && tag?.projectId === owner.id && job.result?.filename === filename
+ && (image.key ? tag?.castAndSets?.key === image.key : tag?.sceneId === image.sceneId)) return { job, projectId: owner.id };
+ }
+ }
+ return null;
+}
+
+async function readCandidate(project, item, pick = null, owners = [project], { catalog = false } = {}) {
+ if (!item.relative && !item.filename) return { status: 'missing', reason: 'not-generated' };
+ if (!TYPES.has(item.ext)) return { status: 'excluded', reason: 'unsupported-type' };
+ let generationSettings = null;
+ let sourceProjectId = project.id;
+ let relative = item.relative;
+ let ownership = 'project-generated';
+ if (item.relative) {
+ let source = item.source;
+ if (item.sharedArtifact) {
+ const found = owners.flatMap(owner => (owner.devArtifacts || []).filter(artifact => !artifact.deleted && artifact.id === item.sourceAssetId)
+ .flatMap(artifact => (artifact.versions || []).filter(version => version.version === item.version
+ && version.file === item.recordedFile && version.file === `music-video/${owner.id}/dev/${artifact.id}/v${version.version}${item.ext}`)
+ .map(version => ({ owner, version })))).find(Boolean);
+ if (!found) return { status: catalog ? 'requires-owner-project' : 'excluded', reason: 'owner-project-not-selected' };
+ relative = found.version.file; source = found.version.source; sourceProjectId = found.owner.id;
+ }
+ if (!['generated', 'planning-import'].includes(source)) {
+ if (!declaredOwnership(pick)) return { status: catalog ? 'requires-ownership' : 'excluded', reason: 'ownership-unverified' };
+ ownership = 'operator-declared';
+ }
+ }
+ if (!item.relative) {
+ if (!/^[A-Za-z0-9_-]+\.(png|jpg|jpeg|webp)$/i.test(item.filename)) return { status: 'excluded', reason: 'unsafe-path' };
+ // Membership is necessary but not sufficient. Shared generated assets may
+ // be verified against another explicitly selected owning project. An owned
+ // declaration admits imported user-owned bytes, but never grants arbitrary paths.
+ const proof = await galleryGeneration(item.filename, owners);
+ if (!proof && !declaredOwnership(pick)) return { status: catalog ? 'requires-ownership' : 'excluded', reason: 'ownership-unverified' };
+ if (proof) {
+ sourceProjectId = proof.projectId;
+ generationSettings = Object.fromEntries(['mode', 'model', 'modelId', 'negativePrompt', 'negative_prompt', 'seed', 'width', 'height', 'steps', 'cfg', 'scheduler']
+ .filter(key => proof.job.params[key] != null).map(key => [key, portable(proof.job.params[key])]));
+ } else ownership = 'operator-declared';
+ }
+ const read = await readOwned(relative || `images/${item.filename}`);
+ if (!read.data) return read;
+ if (['.html', '.htm', '.md'].includes(item.ext)) {
+ if (item.source === 'planning-import') {
+ const pre = read.data.toString('utf8').match(/<pre\b[^>]*>([\s\S]*?)<\/pre>/i)?.[1];
+ const decoded = pre?.replace(/&quot;/g, '"').replace(/&#39;|&apos;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
+ let parsed;
+ try { parsed = JSON.parse(decoded); } catch { return { status: 'excluded', reason: 'invalid-source-planning' }; }
+ if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') return { status: 'excluded', reason: 'invalid-source-planning' };
+ return { status: 'included', data: Buffer.from(json(portable(parsed))), sourceProjectId, ownership,
+ transformation: 'original planning JSON with privacy redactions; approvals remain unverified' };
+ }
+ if (['.html', '.htm'].includes(item.ext)) {
+ const sheet = await extractMakingOfVisuals(read.data.toString('utf8'), { path: item.path, parentId: item.id,
+ allowRaster: declaredOwnership(pick), scrub: value => scrubText(value, MAX_FILE) });
+ return { ...sheet, generationSettings, sourceProjectId, ownership };
+ }
+ const clean = scrubText(read.data.toString('utf8').replace(/<[^>]*>/g, '\n'), MAX_FILE)
+ .replace(/!?\[[^\]]*\]\([^)]*\)/g, '[link omitted]').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+ read.data = Buffer.from(`${clean}\n`);
+ read.transformation = 'Markdown text with unverified links omitted';
+ } else {
+ // Re-encode raster bytes to strip EXIF, private paths, embedded metadata and
+ // polyglot payloads. No SVG/HTML may masquerade as a selected image.
+ const format = item.ext === '.png' ? 'png' : item.ext === '.webp' ? 'webp' : 'jpeg';
+ const output = await reencodeMakingOfRaster(read.data, format);
+ if (!output || output.length > MAX_FILE) return { status: 'excluded', reason: 'invalid-or-oversize-image' };
+ read.data = output;
+ read.transformation = 'raster re-encoded without metadata';
+ }
+ return { ...read, generationSettings, sourceProjectId, ownership };
+}
+
+function snapshot(project) { return hash(json({ planning: planning(project), candidates: candidates(project) })); }
+export async function getMakingOfCatalog(projectId) {
+ const project = await loadProject(projectId);
+ const assets = [];
+ for (const item of candidates(project)) {
+ const read = await readCandidate(project, item, null, [project], { catalog: true });
+ assets.push({ id: item.id, label: item.label, kind: item.kind, version: item.version ?? null, source: item.source,
+ status: read.status, reason: read.reason || null, bytes: (read.data?.length ?? 0) + (read.visuals || []).reduce((sum, visual) => sum + (visual.data?.length || 0), 0), path: item.path,
+ visualCount: read.visuals?.length || 0, ownershipDeclarationAvailable: ['.html', '.htm'].includes(item.ext) || read.status === 'requires-ownership' });
+ }
+ return { project: planning(project).project, snapshot: snapshot(project), assets };
+}
+
+const csvCell = value => `"${String(value ?? '').replace(/^\s*[=+@-]/, "'$&").replace(/"/g, '""')}"`;
+const csv = shots => {
+ const keys = ['id', 'sceneId', 'order', 'startSec', 'endSec', 'timingStatus', 'label', 'lyricText', 'visualIntent', 'action', 'staging', 'camera', 'transition', 'medium'];
+ return `${keys.join(',')}\n${shots.map(shot => keys.map(key => csvCell(shot[key])).join(',')).join('\n')}\n`;
+};
+
+export async function compileMakingOf(selection, { download = false } = {}) {
+ const files = [];
+ let total = 0;
+ const add = (name, data) => {
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data);
+ total += buffer.length;
+ if (total > MAX_PACKAGE) throw new ServerError('Making-of package exceeds 100 MiB', { status: 413, code: 'MAKING_OF_LIMIT' });
+ files.push({ name, data: buffer });
+ };
+ const inventory = [];
+ const projects = [];
+ const owners = await Promise.all(selection.projects.map(selected => loadProject(selected.projectId)));
+ for (const selected of [...selection.projects].sort((a, b) => a.projectId.localeCompare(b.projectId, 'en'))) {
+ const project = owners.find(owner => owner.id === selected.projectId);
+ if (snapshot(project) !== selected.snapshot) conflict();
+ const plan = planning(project);
+ projects.push(plan.project);
+ const root = `projects/${project.id}`;
+ const items = candidates(project);
+ const chosen = new Map(selected.assets.map(asset => [asset.id, asset]));
+ if ([...chosen.keys()].some(id => !items.some(item => item.id === id))) badSelection();
+ const imageLinks = { 'cast-sets': [], storyboard: [] };
+ const artifactLinks = { 'cast-sets': [], storyboard: [] };
+ for (const item of items) {
+ const pick = chosen.get(item.id);
+ const checked = await readCandidate(project, item, pick, owners);
+ const read = pick ? checked : { status: checked.data ? 'not-selected' : checked.status, reason: checked.reason || null };
+ const entry = { projectId: project.id, id: item.id, kind: item.kind, label: item.label, version: item.version ?? null,
+ path: item.path, selected: !!pick, status: read.status, reason: read.reason || null, bytes: read.data?.length ?? 0,
+ sha256: read.data ? hash(read.data) : null,
+ rights: pick?.rights || 'unknown', attribution: text(pick?.attribution),
+ delivery: read.data ? 'file' : item.kind === 'reference' ? 'metadata-only' : 'unavailable-or-unselected',
+ provenance: { source: item.source, sourceAssetId: item.sourceAssetId || null, reviewStatus: item.reviewStatus || null,
+ prompt: item.prompt || '', revision: item.revision ?? null, generationSettings: read.generationSettings || null,
+ sourceProjectId: read.sourceProjectId || null, ownership: read.ownership || 'unverified' },
+ transformation: read.transformation || null };
+ inventory.push(entry);
+ if (read.data) {
+ add(item.path, read.data);
+ if (artifactLinks[item.kind] && /\.md$/.test(item.path)) artifactLinks[item.kind].push(`[${item.id}](${item.path.slice(root.length + 1)})`);
+ for (const visual of read.visuals || []) {
+ inventory.push({ projectId: project.id, id: visual.id, label: visual.label, kind: item.kind, status: visual.status, reason: visual.reason,
+ path: visual.path, bytes: visual.data?.length || 0, sha256: visual.data ? hash(visual.data) : null,
+ rights: pick.rights || 'unknown', attribution: text(pick.attribution), delivery: visual.data ? 'file' : 'unavailable',
+ provenance: { source: 'embedded-sheet-graphic', sourceArtifactId: item.sourceAssetId, sourceVersion: item.version,
+ sourceSha256: visual.sourceSha256, sourceProjectId: read.sourceProjectId,
+ ownership: declaredOwnership(pick) ? 'operator-declared' : read.ownership } });
+ if (visual.data) {
+ add(visual.path, visual.data);
+ if (imageLinks[item.kind]) imageLinks[item.kind].push(`![${visual.id}](${visual.path.slice(root.length + 1)})`);
+ }
+ }
+ if (item.source === 'planning-import') {
+ const original = JSON.parse(read.data.toString());
+ for (const sourceAsset of Array.isArray(original.assets) ? original.assets : []) {
+ const sourceId = text(sourceAsset?.id) || hash(json(sourceAsset)).slice(0, 16);
+ inventory.push({ projectId: project.id, id: `source:${item.id}:${sourceId}`, kind: 'source-reference',
+ label: text(sourceAsset?.label) || sourceId, sourceAssetId: sourceId, path: null,
+ status: 'excluded', reason: 'source-planning-metadata-only', delivery: 'metadata-only', rights: 'unknown', attribution: '' });
+ }
+ if (Array.isArray(original.storyboard) && original.storyboard.length) {
+ const keys = [...new Set(original.storyboard.flatMap(shot => Object.keys(shot || {})))].sort();
+ const base = item.path.replace(/\.json$/, '-storyboard');
+ add(`${base}.csv`, `${keys.map(csvCell).join(',')}\n${original.storyboard.map(shot => keys.map(key => csvCell(typeof shot?.[key] === 'object' ? JSON.stringify(shot[key]) : shot?.[key])).join(',')).join('\n')}\n`);
+ add(`${base}.md`, `# Original planning storyboard — unverified\n\n${original.storyboard.map(shot => jsonBlock(shot)).join('\n\n')}`);
+ }
+ }
+ if (imageLinks[item.kind] && /\.(png|jpe?g|webp)$/.test(item.path)) imageLinks[item.kind].push(`![${item.id}](${item.path.slice(root.length + 1)})`);
+ }
+ }
+ for (const kind of ['cast-sets', 'storyboard']) {
+ if (!items.some(item => item.kind === kind)) inventory.push({ projectId: project.id, id: `missing:${kind}`, kind,
+ status: 'missing', reason: 'no-artifact-or-image', path: null, rights: 'unknown', attribution: '' });
+ }
+ if (!plan.castAndSets && !plan.review.cast && !plan.review.environments) inventory.push({ projectId: project.id, id: 'missing:cast-planning', status: 'missing', reason: 'no-cast-set-planning', path: null });
+ if (!plan.shots.length) inventory.push({ projectId: project.id, id: 'missing:shots', status: 'missing', reason: 'no-shot-planning', path: null });
+ add(`${root}/planning.json`, json(plan));
+ add(`${root}/shots.json`, json(plan.shots));
+ add(`${root}/shots.csv`, csv(plan.shots));
+ add(`${root}/cast-set-sheet.md`, `# ${markdown(plan.project.name)} — Cast & Sets\n\nSelected visual sheets: ${artifactLinks['cast-sets'].join(', ') || 'none'}\n\n${plan.castAndSets ? jsonBlock(plan.castAndSets) : 'Cast & Sets direction missing.'}\n\n${markdown(plan.review.cast)}\n\n${markdown(plan.review.environments)}\n\n${imageLinks['cast-sets'].join('\n\n')}\n`);
+ add(`${root}/storyboard.md`, `# ${markdown(plan.project.name)} — Storyboard\n\nSelected visual sheets: ${artifactLinks.storyboard.join(', ') || 'none'}\n\nTiming: ${markdown(project.productionReview?.draft?.timingStatus) || 'provisional'}\n\n${plan.shots.length ? plan.shots.map(shot => `## ${markdown(shot.id)}: ${shot.startSec ?? '?'}–${shot.endSec ?? '?'} seconds\n\n${markdown(shot.visualIntent)}\n\nAction: ${markdown(shot.action)}\n\nStaging: ${markdown(shot.staging)}\n\nCamera: ${markdown(shot.camera)}\n\nTransition: ${markdown(shot.transition)}\n`).join('\n') : 'Shot planning missing.'}\n\n${imageLinks.storyboard.join('\n\n')}\n`);
+ }
+ const unresolved = inventory.filter(item => item.status !== 'included' || item.rights === 'unknown' || (item.rights === 'licensed' && !item.attribution));
+ add('README.md', `# Music Video Making-of\n\nLocal planning export from PortOS. No repository has been created or published.\n\n${projects.map(project => `- [${linkLabel(project.name)}](projects/${project.id}/storyboard.md) — ${project.mediaMode || 'unspecified medium'}, version ${project.version}`).join('\n')}\n\nEach project contains cast/set and storyboard sheets, shot JSON/CSV, and planning.json with prompts and selected settings. manifest.json records every selected, missing, excluded and unselected candidate, provenance, rights and transformations. Paths are relative; no PortOS server is required.\n\n${unresolved.length} inventory entries need review. Missing files and unresolved rights remain unresolved; export is not proof of completion or publication clearance. Licensed assets require attribution. Review all content before sharing. Unselected or unverified reference bytes, logs, credentials, audio/video and executable composition files are excluded. Selected HTML sheets become Markdown with ordered relative PNG graphics and captions. Validated static SVG geometry is rasterized without executing HTML; embedded raster graphics require an explicit owned declaration. Raster output is re-encoded without metadata. Unsafe or unavailable graphics remain visible omissions. Sheet content is portable; the original HTML layout is not reproduced pixel for pixel. Shared assets require a selected, verified owner or an explicit ownership declaration where offered.\n\nSHA256SUMS covers every package file except itself. No license is inferred. Future GitHub publication requires explicit content, owner, repository name and visibility approval.\n`);
+ const manifest = { format: 'portos-music-video-making-of', version: 1, projects, inventory,
+ publication: 'not-published', rightsStatus: 'requires-review', limits: { fileBytes: MAX_FILE, packageBytes: MAX_PACKAGE, visuals: MAKING_OF_VISUAL_LIMITS },
+ files: files.map(file => ({ path: file.name, bytes: file.data.length, sha256: hash(file.data) })).sort((a, b) => a.path.localeCompare(b.path, 'en')) };
+ add('manifest.json', json(manifest));
+ files.sort((a, b) => a.name.localeCompare(b.name, 'en'));
+ add('SHA256SUMS', files.map(file => `${hash(file.data)} ${file.name}\n`).join(''));
+ files.sort((a, b) => a.name.localeCompare(b.name, 'en'));
+ const digest = hash(json(files.map(file => [file.name, hash(file.data)])));
+ if (download && (!selection.previewDigest || digest !== selection.previewDigest)) conflict();
+ return { manifest, previewDigest: digest, bytes: total,
+ files: files.map(file => ({ path: file.name, bytes: file.data.length, sha256: hash(file.data) })),
+ ...(download ? { zip: createZip(files) } : {}) };
+}
diff --git a/server/services/musicVideo/makingOfVisuals.js b/server/services/musicVideo/makingOfVisuals.js
new file mode 100644
index 0000000000..cbf0e1c84e
--- /dev/null
+++ b/server/services/musicVideo/makingOfVisuals.js
@@ -0,0 +1,204 @@
+/** Static sheet graphics only: no HTML execution, resource loading or raw SVG export. */
+import { createHash } from 'node:crypto';
+import { posix } from 'node:path';
+import { escapeRegExp } from '../../lib/textUtils.js';
+
+export const MAKING_OF_VISUAL_LIMITS = Object.freeze({ count: 80, decodedBytes: 5 * 1024 * 1024, artifactBytes: 20 * 1024 * 1024, svgBytes: 512 * 1024 });
+const hash = value => createHash('sha256').update(value).digest('hex');
+const xml = value => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+const entities = value => value.replace(/&(?:amp|lt|gt|quot|apos|#39);/g, token => ({ '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&apos;': "'", '&#39;': "'" })[token]);
+const tags = new Set(['svg', 'g', 'rect', 'circle', 'ellipse', 'line', 'polygon', 'polyline', 'path', 'text', 'tspan', 'title', 'desc', 'defs', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'marker']);
+const numeric = new Set(['x', 'y', 'x1', 'x2', 'y1', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height', 'stroke-width', 'opacity', 'fill-opacity', 'stroke-opacity', 'font-size', 'letter-spacing', 'offset', 'markerWidth', 'markerHeight', 'refX', 'refY', 'dx', 'dy']);
+const paint = /^(?:none|transparent|currentColor|[a-z]{1,30}|#[a-f0-9]{3,8}|rgba?\([0-9.,%\s]+\)|url\(#[A-Za-z0-9_-]{1,100}\))$/i;
+const list = /^[-+0-9.eE,\s]+$/;
+const SAFE_STYLE = new Set(['fill', 'stroke', 'stroke-width', 'opacity', 'fill-opacity', 'stroke-opacity', 'font-size', 'font-family', 'font-weight', 'text-anchor', 'dominant-baseline', 'letter-spacing']);
+const caption = value => xml(value.replace(/[\r\n\u2028\u2029]+/g, ' ')).replace(/[\[\]\\]/g, character => escapeRegExp(character));
+
+// CSS is never rendered or fetched. Notice graphics that stripping CSS would
+// silently lose, including escaped property names and external style imports.
+function unsupportedCssVisual(css) {
+ const normalized = entities(css).replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/\\([a-f0-9]{1,6})\s?|\\([^\r\n])/gi, (_, hex, character) => hex ? String.fromCodePoint(Math.min(parseInt(hex, 16), 0x10ffff)) : character);
+ return /(?:\b(?:url|(?:-webkit-)?image-set|(?:repeating-)?(?:linear|radial|conic)-gradient)\s*\(|@import\b)/i.test(normalized)
+ || [...normalized.matchAll(/\b(?:background-image|border-image(?:-source)?|list-style-image|(?:-webkit-)?mask(?:-image)?)\s*:\s*([^;}]+)/gi)]
+ .some(match => !/^(?:none|inherit|initial|unset|revert(?:-layer)?)$/i.test(match[1].replace(/\s*!important\s*$/i, '').trim()));
+}
+
+function attributes(raw) {
+ const result = [];
+ let rest = raw;
+ for (const match of raw.matchAll(/([A-Za-z_:][A-Za-z0-9_.:-]*)\s*=\s*("[^"]*"|'[^']*')/g)) {
+ result.push([match[1], entities(match[2].slice(1, -1))]);
+ rest = rest.replace(match[0], '');
+ }
+ if (rest.trim() || new Set(result.map(([key]) => key)).size !== result.length) throw new Error('unsafe-attributes');
+ return result;
+}
+
+function safeAttribute(key, value) {
+ if (numeric.has(key)) return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?%?$/i.test(value) && Math.abs(Number.parseFloat(value)) <= 100000;
+ if (key === 'viewBox') { const parts = value.trim().split(/[\s,]+/).map(Number); return parts.length === 4 && parts.every(Number.isFinite) && parts.every(n => Math.abs(n) <= 100000) && parts[2] > 0 && parts[3] > 0; }
+ if (key === 'fill' || key === 'stroke' || key === 'color' || key === 'stop-color') return paint.test(value);
+ if (key === 'stop-opacity') return /^(?:0(?:\.\d+)?|1(?:\.0+)?)$/.test(value);
+ if (key === 'd') return value.length <= 64000 && /^[MmZzLlHhVvCcSsQqTtAa0-9.eE,+\-\s]*$/.test(value);
+ if (key === 'points' || key === 'stroke-dasharray') return value.length <= 64000 && list.test(value);
+ if (key === 'transform' || key === 'gradientTransform') return /^(?:(?:matrix|translate|scale|rotate|skewX|skewY)\([-+0-9.eE,\s]+\)\s*)+$/.test(value);
+ if (key === 'id') return /^[A-Za-z0-9_-]{1,100}$/.test(value);
+ if (key === 'clip-path' || key === 'marker-start' || key === 'marker-mid' || key === 'marker-end') return /^url\(#[A-Za-z0-9_-]{1,100}\)$/.test(value);
+ if (key === 'font-family') return /^(?:Arial|Helvetica|sans-serif|serif|monospace|system-ui)(?:\s*,\s*(?:Arial|Helvetica|sans-serif|serif|monospace|system-ui))*$/i.test(value);
+ if (key === 'font-weight') return /^(?:normal|bold|[1-9]00)$/.test(value);
+ if (key === 'text-anchor') return /^(?:start|middle|end)$/.test(value);
+ if (key === 'dominant-baseline') return /^(?:auto|middle|central|hanging|alphabetic|text-before-edge|text-after-edge)$/.test(value);
+ if (key === 'stroke-linecap') return /^(?:butt|round|square)$/.test(value);
+ if (key === 'stroke-linejoin') return /^(?:miter|round|bevel)$/.test(value);
+ if (key === 'fill-rule' || key === 'clip-rule') return /^(?:nonzero|evenodd)$/.test(value);
+ if (key === 'gradientUnits' || key === 'clipPathUnits') return /^(?:userSpaceOnUse|objectBoundingBox)$/.test(value);
+ if (key === 'orient') return value === 'auto' || value === 'auto-start-reverse' || /^[-+0-9.]+$/.test(value);
+ if (key === 'preserveAspectRatio') return /^(?:none|x(?:Min|Mid|Max)Y(?:Min|Mid|Max)(?:\s+(?:meet|slice))?)$/.test(value);
+ return false;
+}
+
+// Parse a deliberately small SVG grammar and reconstruct it from approved
+// geometry and text. Never hand a rejected SVG or arbitrary markup to librsvg.
+function staticSvg(source, scrub) {
+ source = source.trim();
+ if (Buffer.byteLength(source) > MAKING_OF_VISUAL_LIMITS.svgBytes || /<!|<\?|&(?!(?:amp|lt|gt|quot|apos|#39);)/.test(source)) throw new Error('unsafe-svg');
+ const output = [];
+ const stack = [];
+ let count = 0;
+ let viewBox = null;
+ for (const token of source.match(/<[^>]*>|[^<]+/g) || []) {
+ if (!token.startsWith('<')) {
+ if (token.trim() && !['text', 'tspan', 'title', 'desc'].includes(stack.at(-1))) throw new Error('unsafe-svg-text');
+ output.push(xml(scrub(entities(token))));
+ continue;
+ }
+ const match = token.match(/^<(\/?)([A-Za-z]+)([^>]*?)(\/?)>$/);
+ if (!match || !tags.has(match[2]) || ++count > 2000) throw new Error('unsafe-svg');
+ const [, closing, name, raw, selfClosing] = match;
+ if (closing) {
+ if (raw.trim() || selfClosing || stack.pop() !== name) throw new Error('unsafe-svg');
+ output.push(`</${name}>`); continue;
+ }
+ if (!stack.length && (output.length || name !== 'svg')) throw new Error('unsafe-svg');
+ if (stack.length && name === 'svg') throw new Error('nested-svg');
+ const safe = [];
+ for (const [key, value] of attributes(raw)) {
+ if (key === 'xmlns' && name === 'svg' && value === 'http://www.w3.org/2000/svg') continue;
+ if (key === 'role' || key === 'aria-label') continue;
+ const pairs = key === 'style' ? value.split(';').filter(v => v.trim()).map(declaration => {
+ const colon = declaration.indexOf(':');
+ const property = declaration.slice(0, colon).trim();
+ if (colon < 0 || !SAFE_STYLE.has(property)) throw new Error('unsafe-svg-style');
+ return [property, declaration.slice(colon + 1).trim()];
+ }) : [[key, value]];
+ for (const [property, attribute] of pairs) {
+ if (!safeAttribute(property, attribute)) throw new Error('unsafe-svg-attribute');
+ if (name === 'svg' && property === 'viewBox') viewBox = attribute;
+ if (name === 'svg' && ['width', 'height'].includes(property)) continue;
+ safe.push(`${property}="${xml(attribute)}"`);
+ }
+ }
+ output.push(`<${name}${name === 'svg' ? ' xmlns="http://www.w3.org/2000/svg" width="1024" height="1024"' : ''}${safe.length ? ` ${safe.join(' ')}` : ''}${selfClosing ? '/>' : '>'}`);
+ if (!selfClosing) stack.push(name);
+ }
+ if (stack.length || !viewBox || !output.join('').endsWith('</svg>')) throw new Error('unsafe-svg');
+ const parts = viewBox.trim().split(/[\s,]+/).map(Number);
+ const width = Math.min(1600, Math.max(1, Math.ceil(parts[2])));
+ const height = Math.min(1600, Math.max(1, Math.ceil(width * parts[3] / parts[2])));
+ return Buffer.from(output.join('').replace('width="1024" height="1024"', `width="${width}" height="${height}"`));
+}
+
+export async function reencodeMakingOfRaster(data, format = 'png') {
+ const raster = data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
+ || (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff)
+ || (data.subarray(0, 4).toString() === 'RIFF' && data.subarray(8, 12).toString() === 'WEBP');
+ if (!raster) return null;
+ const { default: sharp } = await import('sharp');
+ return sharp(data, { limitInputPixels: 40_000_000 }).rotate().toFormat(format).toBuffer().catch(() => null);
+}
+
+export async function extractMakingOfVisuals(html, { path, parentId, allowRaster = false, scrub }) {
+ const matches = [...html.matchAll(/<svg\b[\s\S]*?<\/svg\s*>|<img\b[^>]*>|<script\b[\s\S]*?(?:<\/script\s*>|$)|<canvas\b[\s\S]*?(?:<\/canvas\s*>|$)|<style\b[\s\S]*?(?:<\/style\s*>|$)|<(?:link|iframe|object|embed|video|audio|image)\b[^>]*>/gi)]
+ .filter(match => {
+ if (/^<style\b/i.test(match[0])) match.unsupportedCss = unsupportedCssVisual(match[0].replace(/^<style\b[^>]*>|<\/style\s*>$/gi, ''));
+ else if (/^<link\b/i.test(match[0])) match.unsupportedCss = /\brel\s*=\s*(?:"[^"]*\bstylesheet\b|'[^']*\bstylesheet\b|stylesheet\b)/i.test(match[0]);
+ else return true;
+ return match.unsupportedCss;
+ });
+ if (matches.length > MAKING_OF_VISUAL_LIMITS.count) return { status: 'excluded', reason: 'visual-count-limit' };
+ for (const match of html.matchAll(/<[A-Za-z][^>]*>/g)) {
+ const style = match[0].match(/\bstyle\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
+ if (!style || !unsupportedCssVisual(style[1] ?? style[2] ?? style[3])
+ || matches.some(existing => match.index >= existing.index && match.index < existing.index + existing[0].length)) continue;
+ match.unsupportedCss = true;
+ matches.push(match);
+ if (matches.length > MAKING_OF_VISUAL_LIMITS.count) return { status: 'excluded', reason: 'visual-count-limit' };
+ }
+ matches.sort((a, b) => a.index - b.index);
+ const visuals = [];
+ const documentHash = hash(html).slice(0, 16);
+ let decodedTotal = 0;
+ let outputTotal = 0;
+ let cleaned = html;
+ // Reverse substitutions keep original source offsets and image order intact.
+ for (let index = matches.length - 1; index >= 0; index -= 1) {
+ const match = matches[index];
+ const source = match[0];
+ const ordinal = index + 1;
+ const visual = { id: `${parentId}:visual:${ordinal}`, sourceSha256: hash(source), status: 'excluded', reason: null, path: null, data: null, label: `Graphic ${ordinal}` };
+ let decoded;
+ let svg = /^<svg\b/i.test(source);
+ if (match.unsupportedCss) visual.reason = 'css-visual-not-exported';
+ else if (/^<(?:script|canvas|iframe|object|embed|video|audio|image)\b/i.test(source)) visual.reason = 'active-visual-not-exported';
+ else {
+ try {
+ if (svg) decoded = Buffer.from(source);
+ else {
+ const imageAttributes = attributes(source.replace(/^<img\b/i, '').replace(/\/?\s*>$/, ''));
+ if (imageAttributes.some(([key]) => /^on|^(?:srcset|style)$/i.test(key))) throw new Error('unsafe-image-attributes');
+ const src = imageAttributes.find(([key]) => key.toLowerCase() === 'src')?.[1];
+ visual.label = scrub(imageAttributes.find(([key]) => key.toLowerCase() === 'alt')?.[1] || visual.label);
+ const uri = src?.match(/^data:image\/(png|jpe?g|webp|svg\+xml)(?:;charset=utf-8)?;base64,([A-Za-z0-9+/]+={0,2})$/i);
+ if (!uri) throw new Error(src && /^(?:https?:)?\/\//i.test(src) ? 'remote-visual-not-exported' : 'unsupported-image-source');
+ if (uri[2].length > Math.ceil(MAKING_OF_VISUAL_LIMITS.decodedBytes / 3) * 4) throw new Error('visual-size-limit');
+ decoded = Buffer.from(uri[2], 'base64');
+ if (decoded.toString('base64') !== uri[2]) throw new Error('invalid-base64');
+ svg = uri[1].toLowerCase() === 'svg+xml';
+ }
+ decodedTotal += decoded.length;
+ if (decoded.length > MAKING_OF_VISUAL_LIMITS.decodedBytes || decodedTotal > MAKING_OF_VISUAL_LIMITS.artifactBytes) throw new Error('visual-size-limit');
+ visual.sourceSha256 = hash(decoded);
+ if (!svg && !allowRaster) throw new Error('embedded-raster-ownership-unverified');
+ if (svg) {
+ const safe = staticSvg(decoded.toString('utf8'), scrub);
+ const { default: sharp } = await import('sharp');
+ visual.data = await sharp(safe, { limitInputPixels: 4_000_000 }).png().toBuffer();
+ } else visual.data = await reencodeMakingOfRaster(decoded);
+ if (!visual.data || visual.data.length > MAKING_OF_VISUAL_LIMITS.decodedBytes) throw new Error('invalid-or-oversize-image');
+ if (outputTotal + visual.data.length > MAKING_OF_VISUAL_LIMITS.artifactBytes) throw new Error('visual-size-limit');
+ outputTotal += visual.data.length;
+ const folder = path.replace(/\.md$/, '-visuals');
+ visual.path = `${folder}/visual-${String(ordinal).padStart(2, '0')}-${visual.sourceSha256.slice(0, 16)}.png`;
+ visual.status = 'included';
+ } catch (err) { visual.data = null; visual.reason = ['unsafe-image-attributes', 'remote-visual-not-exported', 'unsupported-image-source', 'visual-size-limit', 'invalid-base64', 'embedded-raster-ownership-unverified', 'invalid-or-oversize-image'].includes(err.message) ? err.message : 'unsafe-or-invalid-svg'; }
+ }
+ const replacement = visual.data ? `\n![${caption(visual.label)}](${posix.relative(posix.dirname(path), visual.path)})\n` : `\n[Graphic ${ordinal} omitted: ${visual.reason}]\n`;
+ // Protect generated relative links from generic HTML stripping/redaction.
+ const placeholder = `PORTOSVISUAL${documentHash}NUMBER${ordinal}PLACEHOLDER`;
+ visual.markdown = replacement;
+ visual.placeholder = placeholder;
+ cleaned = `${cleaned.slice(0, match.index)}\n${placeholder}\n${cleaned.slice(match.index + source.length)}`;
+ visuals.unshift(visual);
+ }
+ cleaned = cleaned.replace(/<style\b[\s\S]*?(?:<\/style\s*>|$)/gi, '')
+ .replace(/<h([1-6])\b[^>]*>/gi, (_, level) => `\n${'#'.repeat(Number(level))} `)
+ .replace(/<[^>]*>/g, '\n');
+ cleaned = scrub(entities(cleaned)).replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1 [link omitted]')
+ .replace(/</g, '&lt;').replace(/>/g, '&gt;');
+ for (const visual of visuals) cleaned = cleaned.replace(visual.placeholder, visual.markdown);
+ return { status: visuals.some(visual => visual.status !== 'included') ? 'partial' : 'included',
+ reason: visuals.some(visual => visual.status !== 'included') ? 'some-visuals-not-exported' : null,
+ data: Buffer.from(`${cleaned}\n`), visuals,
+ transformation: 'static sheet: safe graphics extracted to relative PNGs; no active HTML exported' };
+}