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

feat(fableloom): add export preflight and ZIP handoff UI and CLI (#13111)

[._.]/ Adam Eivy9282966a0817
diff --git a/.claude/skills/portos-api/SKILL.md b/.claude/skills/portos-api/SKILL.md
index 50e8bf3163..d670aa7be8 100644
--- a/.claude/skills/portos-api/SKILL.md
+++ b/.claude/skills/portos-api/SKILL.md
@@ -28,3 +28,12 @@ node scripts/portos-api.js get /api/api-docs/catalog.json # discover endpoints
Details: [docs/AGENT_API_KEY.md](../../../docs/AGENT_API_KEY.md).
For an outside terminal agent delivering a reviewed PR, use the supported [external merge-admission flow](../../../docs/AGENT_API_KEY.md#outside-agent-merge-admission). It binds a per-run secret and verified operator identity to the server-validated app, linked checkout and exact PR head/base; do not invent or borrow a CoS `agentId`.
+
+For FableLoom static package handoff, use `fableloom-export preflight|start LOOM`
+with `--episodes EP1,EP2`, `--player true`, `--characters true`, `--voice true`,
+`--allow-draft true`, `--profile source|web-720p|web-1080p`, and `--webm true`
+as needed. Flags are explicit values; voice requires character opt-in. Inspect
+preflight findings before `start`. Use `fableloom-export status|watch LOOM JOB`
+for findings/progress/size, then `fableloom-export download LOOM JOB --output
+story.zip` for its protected ZIP (refuses overwrite). This exports a static
+artifact and never deploys PortOS. See `docs/AGENT_API_KEY.md`.
diff --git a/client/src/components/fableloom/LoomExportModal.jsx b/client/src/components/fableloom/LoomExportModal.jsx
new file mode 100644
index 0000000000..584a153438
--- /dev/null
+++ b/client/src/components/fableloom/LoomExportModal.jsx
@@ -0,0 +1,115 @@
+import { useEffect, useRef, useState } from 'react';
+import Modal from '../ui/Modal';
+import * as api from '../../services/apiFableLoom.js';
+import socket from '../../services/socket';
+import { useSocketSubscription } from '../../hooks/useSocketSubscription.js';
+import useMounted from '../../hooks/useMounted.js';
+import { downloadBlob } from '../../lib/downloadBlob.js';
+import { formatBytes, formatCount } from '../../utils/formatters.js';
+
+const gates = ['graph', 'outline', 'production', 'media', 'approval', 'cast'];
+const terminal = job => ['completed', 'failed', 'cancelled'].includes(job?.status);
+
+export default function LoomExportModal({ loom, onClose }) {
+ const [options, setOptions] = useState({ episodeIds: loom.episodes.map(e => e.id), includePlayer: true,
+ includeCharacters: false, includeVoice: false, allowDraft: false, mediaProfile: 'source' });
+ const [preflight, setPreflight] = useState(null);
+ const [jobId, setJobId] = useState(null);
+ const [job, setJob] = useState(null);
+ const [error, setError] = useState('');
+ const [busy, setBusy] = useState(false);
+ const mounted = useMounted();
+ const identity = JSON.stringify([loom, options]);
+ const currentIdentity = useRef(identity);
+ currentIdentity.current = identity;
+ const controller = useRef(null);
+ useSocketSubscription('fableloom', { onResubscribe: () => controller.current?.() });
+
+ useEffect(() => {
+ let active = true;
+ setPreflight(null);
+ setError('');
+ if (options.episodeIds.length) {
+ api.preflightLoomExport(loom.id, options, { silent: true }).then(result => {
+ if (active) setPreflight({ identity, ...result });
+ }).catch(err => { if (active) setError(err.message); });
+ }
+ return () => { active = false; };
+ }, [loom.id, identity, options]);
+
+ useEffect(() => {
+ let active = true;
+ setJob(null);
+ const accept = next => {
+ if (!active || next.loomId !== loom.id || next.jobId !== jobId) return;
+ setJob(previous => previous && previous.revision >= next.revision ? previous : next);
+ };
+ const read = () => jobId && api.getLoomExport(loom.id, jobId, { silent: true }).then(accept)
+ .catch(err => { if (active) setError(err.message); });
+ controller.current = read;
+ socket.on('fableloom:export:job', accept);
+ read();
+ return () => { active = false; controller.current = null; socket.off('fableloom:export:job', accept); };
+ }, [loom.id, jobId]);
+
+ const change = patch => setOptions(previous => ({ ...previous, ...patch }));
+ const start = async () => {
+ if (busy || !preflight?.canBuild || preflight.identity !== identity) return;
+ setBusy(true);
+ setError('');
+ const startedIdentity = identity;
+ await api.startLoomExport(loom.id, options, { silent: true }).then(result => {
+ if (mounted.current && currentIdentity.current === startedIdentity) setJobId(result.jobId);
+ }).catch(err => { if (mounted.current) setError(err.message); });
+ if (mounted.current) setBusy(false);
+ };
+ const download = async () => {
+ setBusy(true);
+ await api.downloadLoomExport(loom.id, jobId, { silent: true }).then(blob => {
+ if (mounted.current) downloadBlob(blob, `fableloom-${jobId}.zip`);
+ }).catch(err => { if (mounted.current) setError(err.message); });
+ if (mounted.current) setBusy(false);
+ };
+ const checked = preflight?.identity === identity ? preflight : null;
+ const findings = checked?.findings || [];
+ const running = jobId && (!job || !terminal(job));
+ return <Modal open onClose={onClose} size="lg" ariaLabel="Export story" panelClassName="bg-port-card border border-port-border rounded-lg p-4 space-y-4">
+ <div className="flex items-center justify-between gap-2"><h2 className="text-lg font-semibold">Export story</h2><button onClick={onClose}>Close</button></div>
+ <p className="text-sm text-port-text-muted">Build a static ZIP for handoff. Draft assets are refused by default. Voice requires character opt-in and approved voice references.</p>
+ <fieldset disabled={busy || !!running} className="space-y-3">
+ <legend>Episodes in package order</legend>
+ {options.episodeIds.map((id, index) => <div key={id} className="flex flex-wrap items-center gap-2 text-sm">
+ <span className="min-w-0 flex-1 break-words">{loom.episodes.find(e => e.id === id)?.title || id}</span>
+ <button disabled={index === 0} aria-label={`Move episode ${index + 1} up`} onClick={() => {
+ const ids = [...options.episodeIds]; [ids[index - 1], ids[index]] = [ids[index], ids[index - 1]]; change({ episodeIds: ids });
+ }}>Up</button>
+ <button onClick={() => change({ episodeIds: options.episodeIds.filter(value => value !== id) })}>Remove</button>
+ </div>)}
+ {loom.episodes.filter(e => !options.episodeIds.includes(e.id)).map(e => <button key={e.id} className="text-sm mr-2" onClick={() => change({ episodeIds: [...options.episodeIds, e.id] })}>Add {e.title || e.id}</button>)}
+ <div className="flex flex-wrap gap-4">
+ {[['includePlayer', 'Reference player'], ['includeCharacters', 'Character inputs'], ['includeVoice', 'Approved voice references'], ['includeWebm', 'WebM alternative (web profiles only)'], ['allowDraft', 'Allow draft assets (not production approval)']].map(([key, label]) => <label key={key} htmlFor={`export-${key}`} className="flex items-center gap-2 text-sm">
+ <input id={`export-${key}`} type="checkbox" checked={!!options[key]} disabled={(key === 'includeVoice' && !options.includeCharacters) || (key === 'includeWebm' && options.mediaProfile === 'source')}
+ onChange={e => change({ [key]: e.target.checked, ...(key === 'includeCharacters' && !e.target.checked ? { includeVoice: false } : {}) })} />{label}
+ </label>)}
+ </div>
+ <label htmlFor="export-profile" className="block text-sm">Media profile</label>
+ <select id="export-profile" value={options.mediaProfile} onChange={e => change({ mediaProfile: e.target.value, ...(e.target.value === 'source' ? { includeWebm: false } : {}) })} className="bg-port-bg border border-port-border rounded p-2">
+ <option value="source">Source</option><option value="web-720p">Web 720p</option><option value="web-1080p">Web 1080p</option>
+ </select>
+ </fieldset>
+ <div aria-live="polite" className="space-y-2 text-sm">
+ <p>{!options.episodeIds.length ? 'Select at least one episode.' : !checked ? 'Checking server gates…' : checked.canBuild ? 'Preflight passed. Build rechecks source files and gates.' : 'Resolve the findings before building.'}</p>
+ <div className="flex flex-wrap gap-2">{gates.map(gate => <span key={gate} className="border border-port-border rounded px-2 py-1">{gate}: {!checked ? 'checking' : findings.some(f => f.gate === gate && f.severity === 'error') ? 'blocked' : findings.some(f => f.gate === gate) ? 'warning' : 'passed'}</span>)}</div>
+ {findings.map((finding, index) => <p key={index} className="break-words">{finding.severity}: {finding.message}</p>)}
+ {job && <p>Job {job.jobId}: {job.status} · {formatCount(job.progress.completed)} / {formatCount(job.progress.total)} assets{job.sizeReport ? ` · ZIP ${formatBytes(job.sizeReport.archiveBytes)}` : ''}</p>}
+ {!!job?.findings?.length && <div><p>Selected job findings</p>{job.findings.map((finding, index) => <p key={index}>{finding.severity}: {finding.message}</p>)}</div>}
+ {job?.error && <p role="alert">{job.error.message}</p>}
+ {error && <p role="alert">{error}</p>}
+ </div>
+ <div className="flex flex-wrap gap-3">
+ <button disabled={busy || !!running || !preflight?.canBuild || preflight.identity !== identity} onClick={start} className="rounded bg-port-accent px-3 py-2 text-white disabled:opacity-50">Build ZIP</button>
+ {jobId && error && <button onClick={() => { setError(''); controller.current?.(); }} className="rounded border border-port-border px-3 py-2">Refresh selected job</button>}
+ {job?.jobId === jobId && job?.status === 'completed' && <button disabled={busy} onClick={download} className="rounded border border-port-border px-3 py-2">Download selected ZIP</button>}
+ </div>
+ </Modal>;
+}
diff --git a/client/src/components/fableloom/LoomExportModal.test.jsx b/client/src/components/fableloom/LoomExportModal.test.jsx
new file mode 100644
index 0000000000..f65fab4899
--- /dev/null
+++ b/client/src/components/fableloom/LoomExportModal.test.jsx
@@ -0,0 +1,66 @@
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import LoomExportModal from './LoomExportModal.jsx';
+import * as api from '../../services/apiFableLoom.js';
+import socket from '../../services/socket';
+import { downloadBlob } from '../../lib/downloadBlob.js';
+
+vi.mock('../../services/apiFableLoom.js', () => ({ preflightLoomExport: vi.fn(), startLoomExport: vi.fn(), getLoomExport: vi.fn(), downloadLoomExport: vi.fn() }));
+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
+vi.mock('../../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));
+const loom = { id: 'loom', episodes: [{ id: 'one', title: 'One' }, { id: 'two', title: 'Two' }] };
+const snapshot = (jobId, status, revision = 1) => ({ loomId: 'loom', jobId, status, revision, findings: [], progress: { completed: 0, total: 1 } });
+const emit = async job => { await act(async () => { socket.on.mock.calls.filter(([event]) => event === 'fableloom:export:job').at(-1)[1](job); }); };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.preflightLoomExport.mockResolvedValue({ canBuild: true, findings: [] });
+ api.startLoomExport.mockResolvedValue({ jobId: 'selected' });
+ api.getLoomExport.mockResolvedValue(snapshot('selected', 'packing'));
+});
+
+describe('story export interaction', () => {
+ it('shows server refusal, explicit draft/character consent and ordered selections before building', async () => {
+ api.preflightLoomExport.mockImplementation(async (_id, options) => ({ canBuild: options.allowDraft, findings: options.allowDraft ? [] : [{ gate: 'approval', severity: 'error', message: 'Draft source' }] }));
+ render(<LoomExportModal loom={loom} onClose={vi.fn()} />);
+ await screen.findByText('error: Draft source');
+ expect(screen.getByText('Build ZIP')).toBeDisabled();
+ expect(screen.getByLabelText('Approved voice references')).toBeDisabled();
+ fireEvent.click(screen.getByLabelText('Character inputs'));
+ fireEvent.click(screen.getByLabelText('Approved voice references'));
+ fireEvent.click(screen.getByLabelText('Allow draft assets (not production approval)'));
+ fireEvent.click(screen.getByLabelText('Move episode 2 up'));
+ await waitFor(() => expect(screen.getByText('Build ZIP')).toBeEnabled());
+ fireEvent.click(screen.getByText('Build ZIP'));
+ await waitFor(() => expect(api.startLoomExport).toHaveBeenCalledWith('loom', expect.objectContaining({ episodeIds: ['two', 'one'], includeCharacters: true, includeVoice: true, allowDraft: true }), { silent: true }));
+ });
+
+ it('filters other jobs and stale revisions, displays failures and downloads only the selected completed job', async () => {
+ api.downloadLoomExport.mockResolvedValue(new Blob(['zip']));
+ render(<LoomExportModal loom={loom} onClose={vi.fn()} />);
+ await waitFor(() => expect(screen.getByText('Build ZIP')).toBeEnabled());
+ fireEvent.click(screen.getByText('Build ZIP'));
+ await screen.findByText(/selected: packing/);
+ await emit(snapshot('foreign', 'completed', 10));
+ expect(screen.queryByText('Download selected ZIP')).toBeNull();
+ await emit({ ...snapshot('selected', 'failed', 2), error: { message: 'Source missing' } });
+ expect(screen.getByRole('alert')).toHaveTextContent('Source missing');
+ await emit(snapshot('selected', 'packing', 1));
+ expect(screen.getByRole('alert')).toHaveTextContent('Source missing');
+ await emit({ ...snapshot('selected', 'completed', 3), sizeReport: { archiveBytes: 1024 } });
+ fireEvent.click(screen.getByText('Download selected ZIP'));
+ await waitFor(() => expect(downloadBlob).toHaveBeenCalled());
+ expect(api.downloadLoomExport).toHaveBeenCalledWith('loom', 'selected', { silent: true });
+ });
+
+ it('drops superseded preflight and loom responses', async () => {
+ let resolveOld;
+ api.preflightLoomExport.mockReturnValueOnce(new Promise(resolve => { resolveOld = resolve; }));
+ const { rerender } = render(<LoomExportModal loom={loom} onClose={vi.fn()} />);
+ rerender(<LoomExportModal key="other" loom={{ ...loom, id: 'other' }} onClose={vi.fn()} />);
+ await waitFor(() => expect(screen.getByText('Build ZIP')).toBeEnabled());
+ await act(async () => resolveOld({ canBuild: false, findings: [{ gate: 'graph', severity: 'error', message: 'Old loom' }] }));
+ expect(screen.queryByText('error: Old loom')).toBeNull();
+ expect(screen.getByText('Build ZIP')).toBeEnabled();
+ });
+});
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 49ab686bf0..d425bac8f6 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -19,7 +19,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, Navigate, useNavigate, useParams, useSearchParams } from 'react-router';
-import { ArrowLeft, BookOpenText, LayoutGrid, ListTree, PencilLine, Plus, Settings, Sparkles, Trash2, Waypoints, Workflow as WorkflowIcon, X } from 'lucide-react';
+import { ArrowLeft, Download, BookOpenText, LayoutGrid, ListTree, PencilLine, Plus, Settings, Sparkles, Trash2, Waypoints, Workflow as WorkflowIcon, X } from 'lucide-react';
import toast from '../components/ui/Toast';
import Drawer from '../components/Drawer';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
@@ -41,6 +41,7 @@ import LoomEpisodeFeedback from '../components/fableloom/LoomEpisodeFeedback';
import LoomMediaJobWatchers from '../components/fableloom/LoomMediaJobWatchers';
import LoomNodeEditor from '../components/fableloom/LoomNodeEditor';
import LoomPlayPanel from '../components/fableloom/LoomPlayPanel';
+import LoomExportModal from '../components/fableloom/LoomExportModal';
import LoomSettingsDrawer from '../components/fableloom/LoomSettingsDrawer';
import LoomSeriesPlan from '../components/fableloom/LoomSeriesPlan';
import LoomValidationPanel from '../components/fableloom/LoomValidationPanel';
@@ -89,6 +90,7 @@ export default function FableLoomStory({ view = 'graph' }) {
const [notFound, setNotFound] = useState(false);
const [setupOpen, setSetupOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
+ const [exportOpen, setExportOpen] = useState(false);
const playOpen = searchParams.get('play') === '1';
useScrollLock(playOpen);
const seriesPlanOpen = episodeId === 'plan';
@@ -468,6 +470,7 @@ export default function FableLoomStory({ view = 'graph' }) {
// same actions inside the overflow menu on phones, where five buttons plus
// the loom title ran off the right edge of the screen.
const headerActions = [
+ { id: 'export', label: 'Export story', short: 'Export', icon: Download, onSelect: () => setExportOpen(true) },
{ id: 'settings', label: 'Story settings', short: 'Settings', icon: Settings, onSelect: () => setSettingsOpen(true) },
...(episode ? [
{ id: 'add-scene', label: 'Add scene', short: 'Scene', icon: Plus, onSelect: handleAddNode },
@@ -781,6 +784,8 @@ export default function FableLoomStory({ view = 'graph' }) {
/>
)}
+ {exportOpen && <LoomExportModal key={loom.id} loom={loom} onClose={() => setExportOpen(false)} />}
+
<LoomSettingsDrawer
open={settingsOpen}
onClose={() => setSettingsOpen(false)}
diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.js
index 7a5be660fa..fdd614b604 100644
--- a/client/src/services/apiFableLoom.js
+++ b/client/src/services/apiFableLoom.js
@@ -191,3 +191,12 @@ export const applyLoomEpisodeShots = (id, episodeId, body, options = {}) => requ
export const startLoomEpisodeShotRun = (id, episodeId, body = {}, options = {}) => request(episodePath(id, episodeId, '/shots/start'), { method: 'POST', body: JSON.stringify(body), ...options });
export const getLoomEpisodeShotRun = (id, episodeId, options = {}) => request(episodePath(id, episodeId, '/shots/status'), options);
export const cancelLoomEpisodeShotRun = (id, episodeId, options = {}) => request(episodePath(id, episodeId, '/shots/cancel'), { method: 'POST', ...options });
+
+export const preflightLoomExport = (id, body = {}, options = {}) => request(loomPath(id, '/export/preflight'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const startLoomExport = (id, body = {}, options = {}) => request(loomPath(id, '/export'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const getLoomExport = (id, jobId, options = {}) => request(loomPath(id, `/export/${encodeURIComponent(jobId)}`), options);
+export const downloadLoomExport = (id, jobId, options = {}) => request(loomPath(id, `/export/${encodeURIComponent(jobId)}/download`), { ...options, responseType: 'blob' });
diff --git a/docs/AGENT_API_KEY.md b/docs/AGENT_API_KEY.md
index 93887854ac..5086cd9b16 100644
--- a/docs/AGENT_API_KEY.md
+++ b/docs/AGENT_API_KEY.md
@@ -150,3 +150,26 @@ blocker if it cannot be established. Do not edit the CoS state file, manufacture
a running parent, or borrow another owner's token. After expiry, an old holder
must reacquire and repeat final live checks; its old token cannot release a
successor's lease.
+
+## FableLoom static export
+
+The authenticated CLI supports read-only preflight, build, explicit job status/watch,
+and protected binary download. Episode IDs retain their supplied package order.
+Omitting episode IDs exports all episodes in story order. Draft media is refused
+unless `--allow-draft true` is explicit; voice also requires `--characters true`.
+Preflight reports graph, outline, production, media and approval findings before a
+build. The build repeats validation and checks source bytes; preflight is not a
+finished-package certification.
+
+```sh
+node scripts/portos-api.js fableloom-export preflight LOOM --episodes EP1,EP2 --player true --profile web-720p
+node scripts/portos-api.js fableloom-export start LOOM --episodes EP1,EP2 --player true --profile web-720p
+node scripts/portos-api.js fableloom-export status LOOM JOB
+node scripts/portos-api.js fableloom-export watch LOOM JOB --timeout 1800
+node scripts/portos-api.js fableloom-export download LOOM JOB --output story.zip
+```
+
+`watch` prints findings, progress and final size and exits nonzero for a failed or
+cancelled job. Downloads use the same credential transport, write ZIP bytes to a
+new file with private permissions and refuse overwriting an existing file. The
+ZIP is a static managed artifact; these commands do not deploy or host PortOS.
diff --git a/scripts/portos-api.js b/scripts/portos-api.js
index f25638be3d..8953c5eb86 100644
--- a/scripts/portos-api.js
+++ b/scripts/portos-api.js
@@ -24,7 +24,7 @@
* Builtins only, so it runs from any checkout without `npm install`.
*/
-import { readFile } from 'node:fs/promises';
+import { readFile, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { PORTS } from '../server/lib/ports.js';
@@ -54,6 +54,7 @@ const PRIORITIES = new Set(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']);
export const USAGE = `Usage:
portos-api whoami [--timeout <seconds>]
portos-api <get|post|put|patch|delete> <path> [json | @file | -] [--timeout <seconds>]
+ portos-api fableloom-export <preflight|start|status|watch|download> <loom-id> [job-id] [--episodes id1,id2] [--player true|false] [--characters true|false] [--voice true|false] [--allow-draft true|false] [--profile source|web-720p|web-1080p] [--webm true|false] [--output file.zip] [--timeout seconds]
portos-api task "<description>" [--app <id>] [--priority LOW|MEDIUM|HIGH|CRITICAL] [--context "<note>"] [--timeout <seconds>]
Requests wait up to 30 minutes by default, including the response body.
@@ -97,6 +98,35 @@ export const parseArgs = (argv) => {
if (!Number.isFinite(seconds) || seconds <= 0 || seconds * 1000 > 2 ** 31 - 1) throw new Error('--timeout must be positive seconds within the timer limit');
timeout.timeoutMs = seconds * 1000;
}
+ if (command === 'fableloom-export') {
+ const [action, loomId, jobId] = rest;
+ if (!['preflight', 'start', 'status', 'watch', 'download'].includes(action) || !loomId) throw new Error('fableloom-export needs an action and loom ID');
+ const allowed = new Set(['timeout', 'episodes', 'player', 'characters', 'voice', 'allow-draft', 'profile', 'webm', 'output']);
+ if (Object.keys(flags).some(key => !allowed.has(key))) throw new Error('Unknown fableloom-export flag');
+ const options = {};
+ for (const [flag, key] of Object.entries({ player: 'includePlayer', characters: 'includeCharacters', voice: 'includeVoice', 'allow-draft': 'allowDraft', webm: 'includeWebm' })) {
+ if (flags[flag] === undefined) continue;
+ if (!['true', 'false'].includes(flags[flag])) throw new Error(`--${flag} must be true or false`);
+ options[key] = flags[flag] === 'true';
+ }
+ if (options.includeVoice && !options.includeCharacters) throw new Error('--voice true needs --characters true');
+ if (flags.episodes !== undefined) options.episodeIds = flags.episodes.split(',');
+ if (flags.profile !== undefined) {
+ if (!['source', 'web-720p', 'web-1080p'].includes(flags.profile)) throw new Error('--profile must be source, web-720p or web-1080p');
+ options.mediaProfile = flags.profile;
+ }
+ const starts = ['preflight', 'start'].includes(action);
+ if (rest.length !== (starts ? 2 : 3)) throw new Error('Unexpected fableloom-export arguments');
+ if (flags.output && action !== 'download') throw new Error('--output must be used with download');
+ if (!starts && !jobId) throw new Error(`${action} needs a job ID`);
+ if (action === 'download' && !flags.output) throw new Error('download needs --output file.zip');
+ if (!starts && Object.keys(options).length) throw new Error('Export options must be supplied to preflight or start');
+ const path = `/api/fableloom/${encodeURIComponent(loomId)}/export`;
+ return { method: starts ? 'POST' : 'GET', path: starts ? `${path}${action === 'preflight' ? '/preflight' : ''}`
+ : `${path}/${encodeURIComponent(jobId)}${action === 'download' ? '/download' : ''}`,
+ body: starts ? JSON.stringify(options) : null, ...(action === 'download' ? { output: flags.output } : {}),
+ ...(action === 'watch' ? { watch: true } : {}), ...timeout };
+ }
if (command === 'whoami') return { method: 'GET', path: '/api/auth/whoami', body: null, ...timeout };
if (command === 'task') {
const description = rest.join(' ').trim();
@@ -157,7 +187,7 @@ export const requestApi = (url, { method, headers, body, timeoutMs }) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('error', reject);
- response.on('end', () => resolve({ status: response.statusCode, text: Buffer.concat(chunks).toString('utf8') }));
+ response.on('end', () => resolve({ status: response.statusCode, text: Buffer.concat(chunks).toString('utf8'), bytes: Buffer.concat(chunks) }));
});
request.on('error', reject);
timer = setTimeout(() => request.destroy(new Error(`Request timed out after ${timeoutMs / 1000} seconds; server work may still be running.`)), timeoutMs);
@@ -180,7 +210,8 @@ export const main = async (argv = process.argv.slice(2), env = process.env) => {
headers['X-PortOS-Admission-Session'] = env.PORTOS_ADMISSION_SESSION;
}
if (body !== null) headers['Content-Type'] = 'application/json';
- const { status, text } = await requestApi(`${url}${parsed.path}`, { method: parsed.method, headers, body, timeoutMs: parsed.timeoutMs ?? DEFAULT_TIMEOUT_MS })
+ const deadline = Date.now() + (parsed.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ let { status, text, bytes } = await requestApi(`${url}${parsed.path}`, { method: parsed.method, headers, body, timeoutMs: parsed.timeoutMs ?? DEFAULT_TIMEOUT_MS })
.catch((error) => {
const target = new URL(url);
if (error.code === 'ECONNRESET' && target.protocol === 'http:'
@@ -192,6 +223,24 @@ export const main = async (argv = process.argv.slice(2), env = process.env) => {
}
throw error;
});
+ if (parsed.watch) {
+ while (status >= 200 && status < 300) {
+ const job = JSON.parse(text);
+ console.log(JSON.stringify(job, null, 2));
+ if (['completed', 'failed', 'cancelled'].includes(job.status)) return job.status === 'completed' ? 0 : 1;
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) throw new Error('Export watch timed out; job may still be running.');
+ await new Promise(resolve => setTimeout(resolve, Math.min(1000, remaining)));
+ const left = deadline - Date.now();
+ if (left <= 0) throw new Error('Export watch timed out; job may still be running.');
+ ({ status, text } = await requestApi(`${url}${parsed.path}`, { method: 'GET', headers, body: null, timeoutMs: left }));
+ }
+ }
+ if (parsed.output && status >= 200 && status < 300) {
+ await writeFile(parsed.output, bytes, { flag: 'wx', mode: 0o600 });
+ console.log(`Saved ZIP to ${parsed.output}`);
+ return 0;
+ }
let out = text;
try { out = JSON.stringify(JSON.parse(text), null, 2); } catch { /* not JSON: print as-is */ }
if (status >= 200 && status < 300) {
diff --git a/scripts/portos-api.test.js b/scripts/portos-api.test.js
index c0022503c7..a34a938013 100644
--- a/scripts/portos-api.test.js
+++ b/scripts/portos-api.test.js
@@ -11,7 +11,7 @@ vi.mock('node:http', async (importOriginal) => {
const original = await importOriginal();
return { ...original, request: vi.fn(original.request) };
});
-import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
+import { mkdtemp, mkdir, rm, readFile, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createServer as createTlsServer } from 'node:https';
@@ -258,3 +258,38 @@ describe('local install URL selection', () => {
await expect(main(['whoami'], { ...config, PORTOS_URL: `http://127.0.0.1:${tlsPort}` })).rejects.toMatchObject({ code: 'ECONNRESET', message: 'socket hang up' });
});
});
+
+
+describe('FableLoom export CLI handoff', () => {
+ it('passes exact ordered export options and rejects implicit or incompatible consent', () => {
+ const parsed = parseArgs(['fableloom-export', 'preflight', 'loom/id', '--episodes', 'two,one', '--player', 'true', '--characters', 'true', '--voice', 'true', '--allow-draft', 'true', '--profile', 'web-720p']);
+ expect(parsed.path).toBe('/api/fableloom/loom%2Fid/export/preflight');
+ expect(JSON.parse(parsed.body)).toEqual({ episodeIds: ['two', 'one'], includePlayer: true, includeCharacters: true, includeVoice: true, allowDraft: true, mediaProfile: 'web-720p' });
+ expect(() => parseArgs(['fableloom-export', 'start', 'loom', '--voice', 'true'])).toThrow(/characters/);
+ expect(() => parseArgs(['fableloom-export', 'start', 'loom', '--allow-draft', 'yes'])).toThrow(/true or false/);
+ });
+
+ it('downloads protected ZIP bytes without printing the credential and refuses overwrite', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'portos-export-cli-'));
+ const output = join(dir, 'story.zip');
+ const bytes = Buffer.from([80, 75, 3, 4, 0, 255, 128]);
+ const received = [];
+ const server = createServer((request, response) => {
+ received.push({ path: request.url, authorization: request.headers.authorization });
+ response.writeHead(200, { 'Content-Type': 'application/zip' }); response.end(bytes);
+ });
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ const env = { PORTOS_URL: `http://127.0.0.1:${server.address().port}`, PORTOS_API_TOKEN: 'synthetic-export-token', PORTOS_AGENT_KEY_FILE: join(dir, 'absent') };
+ try {
+ expect(await main(['fableloom-export', 'download', 'loom', 'job', '--output', output], env)).toBe(0);
+ expect(await readFile(output)).toEqual(bytes);
+ expect(received[0]).toEqual({ path: '/api/fableloom/loom/export/job/download', authorization: 'Bearer synthetic-export-token' });
+ expect(JSON.stringify(log.mock.calls)).not.toContain('synthetic-export-token');
+ await expect(main(['fableloom-export', 'download', 'loom', 'job', '--output', output], env)).rejects.toMatchObject({ code: 'EEXIST' });
+ } finally {
+ server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
+ log.mockRestore(); await rm(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/server/hostControlCoverage.test.js b/server/hostControlCoverage.test.js
index 8c0639de8e..2cb38a9562 100644
--- a/server/hostControlCoverage.test.js
+++ b/server/hostControlCoverage.test.js
@@ -470,6 +470,7 @@ const REVIEWED_OPEN_MUTATIONS = [
['POST /api/eidoverse/world/presence', CONFIGURED_WORLD_SYNC],
['POST /api/eidoverse/world/project', CONFIGURED_WORLD_SYNC],
// /api/fableloom
+ ['POST /api/fableloom/:id/export/preflight', 'Read-only deterministic package gates and approved voice reference validation; no process, provider call or artifact write.'],
['POST /api/fableloom', RECORDS],
['DELETE /api/fableloom/:id', REMOVES_RECORD],
['PATCH /api/fableloom/:id', RECORDS],
diff --git a/server/lib/hostControlRoutes.test.js b/server/lib/hostControlRoutes.test.js
index bd7e354ad6..cf84853e03 100644
--- a/server/lib/hostControlRoutes.test.js
+++ b/server/lib/hostControlRoutes.test.js
@@ -663,6 +663,8 @@ describe('FableLoom mutation inventory (#10668)', () => {
// Reviewed record mutations, deterministic checks/planning, cancellation,
// session bookkeeping and fixed browser automation. New routes need review.
const recordOrContained = [
+ // Reads deterministic package gates; no process, provider or artifact creation.
+ 'POST /api/fableloom/:id/export/preflight',
'POST /api/fableloom',
'PATCH /api/fableloom/:id',
'DELETE /api/fableloom/:id',
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 38c9641e1c..ac25de7d28 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -538,6 +538,13 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
summary: 'A creative commission changed after persistence.',
payloadSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } }, additionalProperties: false },
}),
+ 'fableloom:export:job': Object.freeze({
+ direction: 'server-to-client',
+ summary: 'Persisted export job snapshot scoped to its loom and job identifier.',
+ payloadSchema: { type: 'object', required: ['loomId', 'jobId', 'status', 'revision', 'progress', 'findings'],
+ properties: { loomId: { type: 'string' }, jobId: { type: 'string' }, status: { type: 'string' },
+ revision: { type: 'integer' }, progress: { type: 'object' }, findings: { type: 'array', items: { type: 'object' } } } },
+ }),
'fableloom:editorial:run': loomRunSnapshot(false),
'fableloom:production:run': loomRunSnapshot(true),
'fableloom:shots:run': loomRunSnapshot(false),
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
index 740aab59e1..2555b88d19 100644
--- a/server/routes/fableLoom.js
+++ b/server/routes/fableLoom.js
@@ -131,6 +131,12 @@ router.get('/:id', asyncHandler(async (req, res) => {
res.json(loom);
}));
+router.post('/:id/export/preflight', asyncHandler(async (req, res) => {
+ const input = validateRequest(exportOptionsSchema, req.body ?? {});
+ const { preflightFableLoomExport } = await import('../services/fableLoom/exports.js');
+ res.json(await preflightFableLoomExport(req.params.id, input));
+}));
+
router.post('/:id/export', asyncHandler(async (req, res) => {
const input = validateRequest(exportOptionsSchema, req.body ?? {});
const { startFableLoomExport } = await import('../services/fableLoom/exports.js');
diff --git a/server/services/fableLoom/exports.js b/server/services/fableLoom/exports.js
index b2e9146243..6f180655ca 100644
--- a/server/services/fableLoom/exports.js
+++ b/server/services/fableLoom/exports.js
@@ -23,6 +23,7 @@ import { getLoom } from './records.js';
import { checkExportCancelled, readFableLoomExportSource } from './exportMedia.js';
import { readFableLoomVoiceReference } from './exportVoice.js';
import { createFableLoomMediaCache } from './exportMediaCache.js';
+import { fableLoomRunEvents } from './runEvents.js';
import { FABLELOOM_STATIC_PLAYER_FILES } from './staticPlayerFiles.js';
const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
@@ -41,7 +42,11 @@ const error = (code, message, status = 422) => new ServerError(message, { status
const missing = () => error('NOT_FOUND', 'Export job not found for this loom.', 404);
const invalidState = () => error('EXPORT_STATE_INVALID', 'Export state is unreadable or from an unsupported version.', 503);
const absentJob = Symbol('absent-export-job');
-const save = job => atomicWrite(jobFile(job.jobId), job);
+const save = async job => {
+ job.revision = (job.revision || 0) + 1;
+ await atomicWrite(jobFile(job.jobId), job);
+ fableLoomRunEvents.emit('export', structuredClone(publicJob(job)));
+};
function serializeAdmission(action) {
const pending = admissionTail.then(action);
admissionTail = pending.catch(() => {});
@@ -53,7 +58,7 @@ const portableLabel = value => typeof value === 'string'
function publicJob(job) {
return {
- jobId: job.jobId, status: job.status, progress: job.progress, findings: job.findings,
+ loomId: job.loomId, revision: job.revision || 0, jobId: job.jobId, status: job.status, progress: job.progress, findings: job.findings,
expiresAt: new Date(job.createdAt + FABLELOOM_EXPORT_LIMITS.maxAgeMs).toISOString(),
...(job.error ? { error: job.error } : {}),
...(job.sizeReport ? { sizeReport: job.sizeReport } : {}),
@@ -247,7 +252,7 @@ async function loadVoiceProfiles(universeId, characterId) {
return listVoiceProfiles({ universeId, characterId });
}
-async function build(job, snapshot, episodes, history, universe, signal) {
+async function inspectContext(job, snapshot, episodes, universe, signal) {
checkExportCancelled(signal);
job.status = 'validating';
job.findings = inspectFableLoomExport(snapshot, episodes, universe);
@@ -255,9 +260,6 @@ async function build(job, snapshot, episodes, history, universe, signal) {
? inspectFableLoomExportCharacters(snapshot, episodes, universe, { allowDraft: job.options.allowDraft })
: null;
if (characterProjection) job.findings.push(...characterProjection.findings);
- if (job.findings.some(f => f.severity === 'error')) {
- throw error('EXPORT_VALIDATION_FAILED', 'Resolve the graph, outline, production and character findings before exporting.');
- }
const requests = episodes.flatMap(episode => {
const reachable = computeGraphLayers(episode).depthById;
return episode.nodes.filter(n => reachable.has(n.id)).flatMap(node => (
@@ -338,8 +340,13 @@ async function build(job, snapshot, episodes, history, universe, signal) {
}
}
}
+ return { requests, voicePlans, characterProjection };
+}
+
+async function build(job, snapshot, episodes, history, universe, signal) {
+ const { requests, voicePlans, characterProjection } = await inspectContext(job, snapshot, episodes, universe, signal);
if (job.findings.some(f => f.severity === 'error')) {
- throw error('EXPORT_VALIDATION_FAILED', 'Resolve missing media, approval, character or voice findings, or explicitly allow draft assets.');
+ throw error('EXPORT_VALIDATION_FAILED', 'Resolve graph, outline, production, media, approval, character or voice findings before exporting.');
}
job.status = 'packing';
job.progress = { completed: 0, total: requests.length };
@@ -477,6 +484,27 @@ async function run(job, context, permit) {
}
}
+/** Read-only gates; the build repeats these against its own immutable snapshot. */
+export async function preflightFableLoomExport(loomId, input = {}) {
+ const options = exportOptionsSchema.parse(input);
+ if (options.includeVoice && !options.includeCharacters) {
+ throw error('EXPORT_VOICE_REQUIRES_CHARACTERS', 'Voice export requires character opt-in (includeCharacters).', 400);
+ }
+ if (options.mediaProfile === 'source' && options.includeWebm) {
+ throw error('EXPORT_OPTION_UNSUPPORTED', 'WebM requires a web media profile.', 400);
+ }
+ const loom = await getLoom(loomId);
+ if (!loom) throw error('NOT_FOUND', 'Loom not found.', 404);
+ const ids = options.episodeIds ?? loom.episodes.map(e => e.id);
+ const episodes = ids.map(id => loom.episodes.find(e => e.id === id));
+ if (!episodes.length || episodes.some(e => !e)) throw error('EXPORT_EPISODES_INVALID', 'Select existing episodes from this loom.', 400);
+ const universe = loom.universeId ? await getUniverse(loom.universeId) : null;
+ const job = { options, findings: [] };
+ await inspectContext(job, loom, episodes, universe);
+ return { findings: job.findings, canBuild: !job.findings.some(f => f.severity === 'error'),
+ episodeIds: ids, options, note: 'Build rechecks gates and source media bytes; preflight does not certify a finished package.' };
+}
+
export async function startFableLoomExport(loomId, input = {}) {
const options = exportOptionsSchema.parse(input);
if (options.mediaProfile === 'source' && options.includeWebm) {
@@ -497,7 +525,7 @@ export async function startFableLoomExport(loomId, input = {}) {
}
await prune();
const snapshot = structuredClone(loom);
- const episodes = snapshot.episodes.filter(e => ids.has(e.id));
+ const episodes = [...ids].map(id => snapshot.episodes.find(e => e.id === id));
const sourceHistory = await loadHistory();
if (!Array.isArray(sourceHistory)) throw error('EXPORT_MEDIA_INVALID', 'Video history is unreadable.');
const videoIds = new Set(episodes.flatMap(e => e.nodes.flatMap(n => fableLoomExportAssetRequests(n)
diff --git a/server/services/fableLoom/exports.test.js b/server/services/fableLoom/exports.test.js
index 3ea4f735d8..589bd8f590 100644
--- a/server/services/fableLoom/exports.test.js
+++ b/server/services/fableLoom/exports.test.js
@@ -34,9 +34,10 @@ import { getUniverse } from '../universeBuilder.js';
import { listVoiceProfiles } from '../voice/profiles.js';
import * as media from './exportMedia.js';
import {
- __testing, startFableLoomExport, getFableLoomExport, getFableLoomExportDownload,
+ __testing, preflightFableLoomExport, startFableLoomExport, getFableLoomExport, getFableLoomExportDownload,
} from './exports.js';
import routes from '../../routes/fableLoom.js';
+import { fableLoomRunEvents } from './runEvents.js';
const owned = ownTestBodies(vitestIt);
const it = owned.it;
@@ -237,6 +238,8 @@ describe('portable FableLoom export boundary', () => {
expect(manifest).toMatchObject({ schemaVersion: '1.0.0', runtimeVersion: '1.0.0',
loom: { name: 'The quiet gate', episodes: [{ id: 'episode-two' }] } });
expect(manifest.loom.episodes).toHaveLength(1);
+ const ordered = await archive(await begin({ episodeIds: ['episode-two', 'episode-one'] }));
+ expect(JSON.parse(ordered.files.get('manifest.json')).loom.episodes.map(e => e.id)).toEqual(['episode-two', 'episode-one']);
expect(manifest.characters).toBeUndefined();
expect([...first.files.keys()].some(name => name.startsWith('characters/'))).toBe(false);
const defaultProvenance = JSON.parse(first.files.get('provenance.json'));
@@ -837,3 +840,30 @@ describe('portable FableLoom export boundary', () => {
}
});
});
+
+// Regression: a read-only preflight surfaces build gates without creating a job,
+// and the selected package order and persisted snapshots survive the authoring flow.
+it('preflights refusal and explicit draft gates without building, then streams selected job revisions', async () => {
+ loom.episodes[0].nodes[0].visualCanon.storyboardImageApproved = false;
+ const blocked = await request(app()).post(`/api/fableloom/${loom.id}/export/preflight`).send({ includePlayer: true });
+ expect(blocked.status).toBe(200);
+ expect(blocked.body.canBuild).toBe(false);
+ expect(blocked.body.findings).toEqual(expect.arrayContaining([expect.objectContaining({ gate: 'approval', severity: 'error' })]));
+ const allowed = await preflightFableLoomExport(loom.id, { allowDraft: true });
+ expect(allowed.findings).toEqual(expect.arrayContaining([expect.objectContaining({ gate: 'approval', severity: 'warning' })]));
+ const snapshots = [];
+ const accept = value => snapshots.push(value);
+ fableLoomRunEvents.on('export', accept);
+ try {
+ const id = await begin({ allowDraft: true });
+ await terminal(id);
+ await __testing.drain();
+ const selected = snapshots.filter(job => job.jobId === id);
+ expect(selected.length).toBeGreaterThan(1);
+ expect(selected.every(job => job.loomId === loom.id)).toBe(true);
+ expect(selected.map(job => job.revision)).toEqual([...selected.map(job => job.revision)].sort((a, b) => a - b));
+ expect(['completed', 'failed']).toContain(selected.at(-1).status);
+ } finally {
+ fableLoomRunEvents.off('export', accept);
+ }
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index cf16206a8f..18fc9a6f66 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -933,6 +933,9 @@ function setupMediaGenEventForwarding() {
}
function setupFableLoomRunForwarding() {
+ fableLoomRunEvents.on('export', job => {
+ broadcastToSet(fableLoomSubscribers, 'fableloom:export:job', job);
+ });
fableLoomRunEvents.on('editorial', run => {
broadcastToSet(fableLoomSubscribers, 'fableloom:editorial:run', run);
});
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index a7277530b4..fcd409a365 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -441,9 +441,11 @@ describe('socket.js — initSocket', () => {
fableLoomRunEvents.emit('editorial', run);
fableLoomRunEvents.emit('production', run);
fableLoomRunEvents.emit('shots', run);
+ fableLoomRunEvents.emit('export', run);
expect(viewer.emitted).toContainEqual(['fableloom:editorial:run', run]);
expect(viewer.emitted).toContainEqual(['fableloom:production:run', run]);
expect(viewer.emitted).toContainEqual(['fableloom:shots:run', run]);
+ expect(viewer.emitted).toContainEqual(['fableloom:export:job', run]);
expect(peer.emitted.some(([name]) => name.startsWith('fableloom:'))).toBe(false);
expect(io.emitted.some(([name]) => name.startsWith('fableloom:'))).toBe(false);
viewer.handlers['fableloom:unsubscribe']();