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): make episodic visual production human-drivable (#5430)

[._.]/ Adam Eivycc6f1d7001c5
diff --git a/client/src/components/fableloom/LoomEpisodeOutline.jsx b/client/src/components/fableloom/LoomEpisodeOutline.jsx
index 3550afd664..c6cc1006ba 100644
--- a/client/src/components/fableloom/LoomEpisodeOutline.jsx
+++ b/client/src/components/fableloom/LoomEpisodeOutline.jsx
@@ -73,6 +73,11 @@ function SceneBlock({ node, number, episode, format, byId, onSelectNode }) {
{!node.isEnding && (
<span>{node.playbackMode === 'cut' ? 'Automatic cut' : 'Decision loop'}</span>
)}
+ {node.protagonistPresence && (
+ <span className={node.protagonistPresence === 'offscreen' ? 'text-port-accent' : ''}>
+ Protagonist {node.protagonistPresence === 'offscreen' ? 'off-screen · side-device' : 'on-screen'}
+ </span>
+ )}
</div>
</div>
</div>
@@ -127,6 +132,40 @@ function SceneBlock({ node, number, episode, format, byId, onSelectNode }) {
);
}
+function BeatOutline({ outline }) {
+ const scenes = asArray(outline?.scenes);
+ if (!scenes.length) return null;
+ return (
+ <section className="rounded-lg border border-port-accent/30 bg-port-accent/5 p-4" aria-label="Story beat outline">
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <h3 className="font-semibold">Story beat outline</h3>
+ <p className="mt-1 text-xs text-port-text-muted">The validated log-line arc that this teleplay expands.</p>
+ </div>
+ <span className={`shrink-0 text-xs ${outline.validation?.status === 'valid' ? 'text-port-success' : 'text-port-warning'}`}>
+ {outline.validation?.status || 'draft'}
+ </span>
+ </div>
+ <ol className="mt-3 space-y-2">
+ {scenes.map((scene, index) => (
+ <li key={scene.key || index} className="flex items-start gap-2 text-sm">
+ <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-port-accent/15 text-[10px] font-semibold text-port-accent">{index + 1}</span>
+ <span className="min-w-0">
+ <span className="font-medium">{scene.title || 'Untitled beat'}</span>
+ <span className="block whitespace-pre-wrap text-xs text-port-text-muted">{scene.summary || 'No log-line yet.'}</span>
+ {scene.protagonistPresence && (
+ <span className="mt-1 block text-[11px] text-port-accent">
+ Protagonist {scene.protagonistPresence === 'offscreen' ? 'off-screen · side-device' : 'on-screen'}
+ </span>
+ )}
+ </span>
+ </li>
+ ))}
+ </ol>
+ </section>
+ );
+}
+
export default function LoomEpisodeOutline({ loom, episode, onSelectNode }) {
const { reachable, unreachable, byId } = useMemo(() => orderEpisodeNodes(episode), [episode]);
const nodes = asArray(episode?.nodes);
@@ -142,7 +181,7 @@ export default function LoomEpisodeOutline({ loom, episode, onSelectNode }) {
[byId, numberedNodes],
);
- if (!reachable.length && !unreachable.length) {
+ if (!reachable.length && !unreachable.length && !episode.storyOutline?.scenes?.length) {
return (
<section className="flex-1 overflow-y-auto p-4 md:p-6" aria-label="Episode outline">
<div className="mx-auto grid min-h-full max-w-4xl place-items-center text-center">
@@ -172,19 +211,28 @@ export default function LoomEpisodeOutline({ loom, episode, onSelectNode }) {
{episode.synopsis && <p className="mt-2 max-w-3xl text-sm text-port-text-muted">{episode.synopsis}</p>}
</header>
- <ol className="space-y-4 border-l border-port-border pl-0">
- {reachable.map((node) => (
- <SceneBlock
- key={node.id}
- node={node}
- number={numberedNodes.get(node.id)}
- episode={episode}
- format={loom.format}
- byId={numberedById}
- onSelectNode={onSelectNode}
- />
- ))}
- </ol>
+ {episode.storyOutline?.scenes?.length ? <BeatOutline outline={episode.storyOutline} /> : null}
+
+ {reachable.length || unreachable.length ? (
+ <>
+ <p className="text-xs uppercase tracking-wide text-port-text-muted">Expanded teleplay scenes</p>
+ <ol className="space-y-4 border-l border-port-border pl-0">
+ {reachable.map((node) => (
+ <SceneBlock
+ key={node.id}
+ node={node}
+ number={numberedNodes.get(node.id)}
+ episode={episode}
+ format={loom.format}
+ byId={numberedById}
+ onSelectNode={onSelectNode}
+ />
+ ))}
+ </ol>
+ </>
+ ) : (
+ <p className="rounded border border-port-border p-4 text-sm text-port-text-muted">No teleplay scenes yet. Expand the validated beat outline from Episode setup.</p>
+ )}
{unreachable.length > 0 && (
<section className="rounded-lg border border-port-warning/40 bg-port-warning/5 p-4" aria-label="Unreachable scenes">
diff --git a/client/src/components/fableloom/LoomEpisodeOutline.test.jsx b/client/src/components/fableloom/LoomEpisodeOutline.test.jsx
index 2901f188c6..24f7dbd990 100644
--- a/client/src/components/fableloom/LoomEpisodeOutline.test.jsx
+++ b/client/src/components/fableloom/LoomEpisodeOutline.test.jsx
@@ -54,6 +54,27 @@ describe('LoomEpisodeOutline', () => {
expect(onSelectNode).toHaveBeenCalledWith('node-2');
});
+ it('surfaces on-screen versus side-device protagonist beats in the teleplay review', () => {
+ const reviewedEpisode = {
+ ...episode,
+ nodes: episode.nodes.map((node, index) => ({
+ ...node,
+ protagonistPresence: index === 0 ? 'onscreen' : 'offscreen',
+ })),
+ storyOutline: {
+ validation: { status: 'valid' },
+ scenes: [{
+ key: 's1', title: 'The choice', summary: 'The viewer speaks through the communicator.',
+ protagonistPresence: 'offscreen',
+ }],
+ },
+ };
+ render(<LoomEpisodeOutline loom={{ name: 'Example Loom', format: 'prose' }} episode={reviewedEpisode} />);
+
+ expect(screen.getAllByText('Protagonist on-screen')).toHaveLength(1);
+ expect(screen.getAllByText('Protagonist off-screen · side-device')).toHaveLength(3);
+ });
+
it('explains when an episode has no scenes', () => {
render(<LoomEpisodeOutline loom={{ name: 'Example Loom', format: 'prose' }} episode={{ ...episode, nodes: [], startNodeId: null }} />);
diff --git a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx
new file mode 100644
index 0000000000..46fd4f1a39
--- /dev/null
+++ b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx
@@ -0,0 +1,390 @@
+import { useEffect, useMemo, useState } from 'react';
+import { AlertTriangle, CheckCircle2, ChevronDown, ChevronUp, CircleAlert, Loader2, Save, Sparkles, Trash2 } from 'lucide-react';
+import ProviderModelSelector from '../ProviderModelSelector';
+import { FormField } from '../ui/FormField.jsx';
+import toast from '../ui/Toast';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import useFableLoomAiRun from '../../hooks/useFableLoomAiRun';
+import useProviderModels from '../../hooks/useProviderModels';
+import {
+ generateLoomEpisodeOutline,
+ reviewLoomEpisodeOutline,
+ updateLoomEpisode,
+ validateLoomEpisodeOutline,
+} from '../../services/api';
+import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providers';
+import { fieldClass, labelClass } from './fieldStyles';
+import LoomAiRunStatus from './LoomAiRunStatus';
+
+const asArray = (value) => (Array.isArray(value) ? value : []);
+
+const cloneOutline = (outline) => (outline ? {
+ ...outline,
+ scenes: asArray(outline.scenes).map((scene) => ({
+ ...scene,
+ transitions: asArray(scene.transitions).map((transition) => ({ ...transition })),
+ })),
+ validation: outline.validation ? { ...outline.validation, issues: asArray(outline.validation.issues).map((issue) => ({ ...issue })) } : {
+ status: 'draft', issues: [],
+ },
+} : null);
+
+const draftValidation = { status: 'draft', issues: [] };
+
+function ValidationResult({ validation }) {
+ if (!validation) return null;
+ const issues = asArray(validation.issues);
+ const hasErrors = issues.some((issue) => issue.severity !== 'warning');
+ const status = validation.stats
+ ? (validation.stats.errorCount ? 'invalid' : 'valid')
+ : validation.status || 'draft';
+ const label = status === 'valid' ? 'Outline is structurally valid' : status === 'invalid' ? 'Outline needs edits' : 'Outline is a draft';
+ return (
+ <div className={`rounded border p-3 space-y-2 ${status === 'valid' ? 'border-port-success/40 bg-port-success/5' : hasErrors ? 'border-port-error/40 bg-port-error/5' : 'border-port-warning/40 bg-port-warning/5'}`} aria-live="polite">
+ <div className="flex items-center gap-2 text-sm font-semibold">
+ {status === 'valid' ? <CheckCircle2 size={15} className="text-port-success" /> : hasErrors ? <CircleAlert size={15} className="text-port-error" /> : <AlertTriangle size={15} className="text-port-warning" />}
+ {label}
+ {validation.stats ? <span className="ml-auto text-xs font-normal text-port-text-muted">
+ {validation.stats.sceneCount} beats · {validation.stats.decisionCount} choices · {validation.stats.endingCount} endings
+ </span> : null}
+ </div>
+ {issues.length ? (
+ <ul className="space-y-1 text-xs text-port-text-muted">
+ {issues.map((issue, index) => <li key={`${issue.code || 'issue'}-${issue.sceneKey || 'outline'}-${index}`} className="flex items-start gap-1.5">
+ {issue.severity === 'warning' ? <AlertTriangle size={12} className="mt-0.5 shrink-0 text-port-warning" /> : <CircleAlert size={12} className="mt-0.5 shrink-0 text-port-error" />}
+ <span>{issue.message}</span>
+ </li>)}
+ </ul>
+ ) : status === 'valid' ? (
+ <p className="text-xs text-port-success">Every beat is reachable, choices are distinct, and each path reaches an ending.</p>
+ ) : null}
+ </div>
+ );
+}
+
+function OutlineBeat({ scene, index, scenes, onChange, onRemovePath, onAddPath, expanded, onToggle }) {
+ const possibleTargets = scenes.filter((candidate) => candidate.key !== scene.key);
+ return (
+ <article className="rounded-lg border border-port-border bg-port-bg/40" data-testid={`outline-beat-${scene.key}`}>
+ <button
+ type="button"
+ onClick={onToggle}
+ className="flex w-full items-start justify-between gap-3 p-3 text-left hover:bg-port-bg/60"
+ aria-expanded={expanded}
+ >
+ <span className="flex min-w-0 items-start gap-2">
+ <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-port-accent/15 text-[10px] font-semibold text-port-accent">{index + 1}</span>
+ <span className="min-w-0">
+ <span className="block break-words text-sm font-semibold">{scene.title || 'Untitled beat'}</span>
+ <span className="mt-1 block break-words text-xs text-port-text-muted">{scene.summary || 'No log-line yet.'}</span>
+ </span>
+ </span>
+ {expanded ? <ChevronUp size={15} className="shrink-0 text-port-text-muted" /> : <ChevronDown size={15} className="shrink-0 text-port-text-muted" />}
+ </button>
+ {expanded ? (
+ <div className="space-y-3 border-t border-port-border p-3">
+ <FormField label="Beat title" labelClassName={labelClass}>
+ <input
+ className={fieldClass}
+ value={scene.title || ''}
+ onChange={(event) => onChange({ title: event.target.value })}
+ />
+ </FormField>
+ <FormField label="Log-line / summary" labelClassName={labelClass} hint="What changes in this camera-cut beat, and why does it matter?">
+ <textarea
+ rows={3}
+ className={fieldClass}
+ value={scene.summary || ''}
+ onChange={(event) => onChange({ summary: event.target.value })}
+ />
+ </FormField>
+ <div className="grid grid-cols-2 gap-2">
+ <label className={labelClass}>
+ Playback
+ <select className={`${fieldClass} mt-1`} value={scene.playbackMode || 'decision'} onChange={(event) => onChange({ playbackMode: event.target.value })}>
+ <option value="cut">Automatic cut</option>
+ <option value="decision">Viewer choice</option>
+ </select>
+ </label>
+ <label className={labelClass}>
+ Audience channel
+ <select className={`${fieldClass} mt-1`} value={scene.audienceConnection || 'disconnected'} onChange={(event) => onChange({ audienceConnection: event.target.value })}>
+ <option value="disconnected">Disconnected</option>
+ <option value="connected">Connected</option>
+ </select>
+ </label>
+ </div>
+ <label className="flex items-center gap-2 text-xs text-port-text-muted">
+ <input type="checkbox" checked={scene.isEnding === true} onChange={(event) => onChange({ isEnding: event.target.checked })} />
+ Ending beat
+ </label>
+ {scene.isEnding ? (
+ <FormField label="Ending label" labelClassName={labelClass}>
+ <input className={fieldClass} value={scene.endingLabel || ''} onChange={(event) => onChange({ endingLabel: event.target.value })} />
+ </FormField>
+ ) : (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <h4 className="text-xs font-semibold uppercase tracking-wide text-port-text-muted">Paths to the next beat</h4>
+ <button type="button" onClick={onAddPath} className="text-xs text-port-accent hover:underline">+ Add path</button>
+ </div>
+ {asArray(scene.transitions).map((transition, transitionIndex) => (
+ <div key={`${scene.key}-path-${transitionIndex}`} className="flex items-start gap-2">
+ <div className="min-w-0 flex-1 space-y-1">
+ <input
+ className={fieldClass}
+ aria-label={`Path ${transitionIndex + 1} choice label for ${scene.title || scene.key}`}
+ placeholder="choice label"
+ value={transition.intent || ''}
+ onChange={(event) => onChange({ transitions: asArray(scene.transitions).map((item, index) => index === transitionIndex ? { ...item, intent: event.target.value } : item) })}
+ />
+ <select
+ className={fieldClass}
+ aria-label={`Path ${transitionIndex + 1} destination for ${scene.title || scene.key}`}
+ value={transition.targetKey || ''}
+ onChange={(event) => onChange({ transitions: asArray(scene.transitions).map((item, index) => index === transitionIndex ? { ...item, targetKey: event.target.value } : item) })}
+ >
+ <option value="">Choose destination…</option>
+ {possibleTargets.map((target) => <option key={target.key} value={target.key}>{target.title || target.key}</option>)}
+ </select>
+ </div>
+ <button type="button" onClick={() => onRemovePath(transitionIndex)} className="mt-2 p-1 text-port-text-muted hover:text-port-error" aria-label={`Remove path ${transitionIndex + 1} from ${scene.title || scene.key}`}>
+ <Trash2 size={14} />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ ) : null}
+ </article>
+ );
+}
+
+export default function LoomEpisodeOutlinePlanner({
+ open,
+ loom,
+ episode,
+ guidance = '',
+ disabled = false,
+ onLoomUpdate,
+ onExpand,
+ expanding = false,
+}) {
+ const [outline, setOutline] = useState(() => cloneOutline(episode.storyOutline));
+ const [dirty, setDirty] = useState(false);
+ const [validation, setValidation] = useState(null);
+ const [review, setReview] = useState(null);
+ const [expandedKey, setExpandedKey] = useState(null);
+ const [route, setRoute] = useState({ providerId: '', model: '', effort: '' });
+ const generateRun = useFableLoomAiRun();
+ const reviewRun = useFableLoomAiRun();
+ const { providers, loading: providersLoading } = useProviderModels({
+ allowDefault: true, silent: true, withEffort: true, enabled: open,
+ });
+ const selectedProvider = providers.find((provider) => provider.id === route.providerId);
+ const routeBody = useMemo(() => ({
+ ...(route.providerId ? { providerId: route.providerId } : {}),
+ ...(route.model ? { model: route.model } : {}),
+ ...(route.effort ? { effort: route.effort } : {}),
+ }), [route]);
+
+ useEffect(() => {
+ setOutline(cloneOutline(episode.storyOutline));
+ setDirty(false);
+ setValidation(null);
+ setReview(null);
+ setExpandedKey(null);
+ }, [episode.id]);
+
+ const scenes = asArray(outline?.scenes);
+ const outlineStatus = validation?.stats
+ ? (validation.stats.errorCount ? 'invalid' : 'valid')
+ : outline?.validation?.status || 'draft';
+ const busy = disabled || providersLoading || generateRun.run?.phase === 'running' || reviewRun.run?.phase === 'running';
+ const hasScenes = episode.nodes.length > 0;
+
+ const updateOutline = (updater) => {
+ setOutline((current) => {
+ if (!current) return current;
+ const next = typeof updater === 'function' ? updater(current) : updater;
+ return { ...next, validation: { ...draftValidation } };
+ });
+ setDirty(true);
+ setValidation(null);
+ setReview(null);
+ };
+
+ const updateBeat = (key, patch) => updateOutline((current) => ({
+ ...current,
+ scenes: current.scenes.map((scene) => scene.key === key ? { ...scene, ...patch } : scene),
+ }));
+
+ const [generateOutline, generating] = useAsyncAction(async () => {
+ const operationId = generateRun.begin();
+ const result = await generateLoomEpisodeOutline(loom.id, episode.id, {
+ ...routeBody,
+ ...(guidance.trim() ? { guidance: guidance.trim() } : {}),
+ operationId,
+ }, { silent: true }).catch((error) => {
+ generateRun.fail(error.message);
+ throw error;
+ });
+ const next = cloneOutline(result.outline || result.loom?.episodes?.find((item) => item.id === episode.id)?.storyOutline);
+ setOutline(next);
+ setValidation(result.validation || null);
+ setReview(null);
+ setDirty(false);
+ onLoomUpdate(result.loom);
+ toast.success(hasScenes ? 'Beat outline refreshed from the episode' : 'Episode beat outline drafted');
+ }, { errorMessage: 'Episode outline drafting failed' });
+
+ const [saveOutline, saving] = useAsyncAction(async () => {
+ if (!outline) return;
+ const updated = await updateLoomEpisode(loom.id, episode.id, {
+ storyOutline: { ...outline, validation: { ...draftValidation } },
+ }, { silent: true });
+ onLoomUpdate(updated);
+ const saved = updated.episodes.find((item) => item.id === episode.id)?.storyOutline;
+ setOutline(cloneOutline(saved));
+ setDirty(false);
+ setValidation(null);
+ setReview(null);
+ toast.success('Beat outline saved');
+ return updated;
+ }, { errorMessage: 'Could not save episode outline' });
+
+ const [validateOutline, validating] = useAsyncAction(async () => {
+ if (dirty) {
+ const saved = await saveOutline();
+ if (!saved) return;
+ }
+ const result = await validateLoomEpisodeOutline(loom.id, episode.id, { silent: true });
+ setOutline(cloneOutline(result.outline));
+ setValidation(result.validation);
+ setDirty(false);
+ onLoomUpdate(result.loom);
+ toast.success(result.validation.stats.errorCount ? 'Outline needs edits' : 'Outline validated — ready for expansion');
+ }, { errorMessage: 'Outline validation failed' });
+
+ const [reviewOutline, reviewing] = useAsyncAction(async () => {
+ if (dirty) return;
+ const operationId = reviewRun.begin();
+ const result = await reviewLoomEpisodeOutline(loom.id, episode.id, { ...routeBody, operationId }, { silent: true })
+ .catch((error) => { reviewRun.fail(error.message); throw error; });
+ setReview(result.analysis);
+ if (result.structural) setValidation(result.structural);
+ }, { errorMessage: 'Episode outline review failed' });
+
+ return (
+ <section className="space-y-3 border-t border-port-border pt-4" aria-label="Episode story outline planner">
+ <div>
+ <h4 className="flex items-center gap-1.5 text-sm font-semibold"><Sparkles size={14} className="text-port-accent" /> Story beats → teleplay</h4>
+ <p className="mt-1 text-xs text-port-text-muted">
+ Plan the complete episode as log-lines first. Review and validate the arc before expanding it into full scene text, choices, and media prompts.
+ </p>
+ </div>
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={route.providerId}
+ selectedModel={route.model}
+ availableModels={effortAwareModelOptions(selectedProvider, route.model)}
+ onProviderChange={(providerId) => setRoute({ providerId, model: '', effort: '' })}
+ onModelChange={(model) => setRoute((current) => ({ ...current, model }))}
+ effort={route.effort}
+ onEffortChange={(effort) => setRoute((current) => ({ ...current, effort }))}
+ label="Outline AI route"
+ layout="stacked"
+ disabled={busy || generating || saving || validating || reviewing || expanding}
+ modelDisabled={busy || generating || saving || validating || reviewing || expanding}
+ emptyProviderOption="Default (outline stage or active provider)"
+ emptyModelOption="Default model"
+ alwaysShowModel={!!route.providerId}
+ />
+ {selectedProvider ? <p className="text-xs text-port-text-muted">Uses {selectedProvider.name}{effectiveModelFor(selectedProvider, route.model) ? ` (${effectiveModelFor(selectedProvider, route.model)})` : ''} for outline actions.</p> : null}
+
+ {!outline ? (
+ <button
+ type="button"
+ onClick={generateOutline}
+ disabled={busy || generating || saving || validating || reviewing || expanding}
+ className="flex w-full items-center justify-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50"
+ >
+ {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {generating ? 'Drafting beat outline…' : hasScenes ? 'Draft outline from current teleplay' : 'Draft story beat outline'}
+ </button>
+ ) : (
+ <>
+ <div className="flex items-center justify-between gap-2 text-xs text-port-text-muted">
+ <span>{scenes.length} beat{scenes.length === 1 ? '' : 's'} · {scenes.filter((scene) => scene.isEnding).length} ending{scenes.filter((scene) => scene.isEnding).length === 1 ? '' : 's'} · {outlineStatus}</span>
+ <button type="button" onClick={generateOutline} disabled={busy || generating || saving || validating || reviewing || expanding} className="text-port-accent hover:underline disabled:opacity-50">
+ {generating ? 'Refreshing…' : 'Refresh with AI'}
+ </button>
+ </div>
+ <div className="max-h-[42vh] space-y-2 overflow-y-auto pr-1">
+ {scenes.map((scene, index) => (
+ <OutlineBeat
+ key={scene.key}
+ scene={scene}
+ index={index}
+ scenes={scenes}
+ expanded={expandedKey === scene.key}
+ onToggle={() => setExpandedKey((current) => current === scene.key ? null : scene.key)}
+ onChange={(patch) => updateBeat(scene.key, patch)}
+ onRemovePath={(transitionIndex) => updateBeat(scene.key, {
+ transitions: asArray(scene.transitions).filter((_, pathIndex) => pathIndex !== transitionIndex),
+ })}
+ onAddPath={() => updateBeat(scene.key, {
+ transitions: [...asArray(scene.transitions), { targetKey: '', intent: '' }],
+ })}
+ />
+ ))}
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={saveOutline} disabled={!dirty || busy || saving || generating || validating || reviewing || expanding} className="flex items-center gap-1.5 rounded border border-port-border px-3 py-2 text-xs hover:border-port-accent disabled:opacity-50">
+ {saving ? <Loader2 size={13} className="animate-spin" /> : <Save size={13} />}
+ {saving ? 'Saving…' : 'Save outline'}
+ </button>
+ <button type="button" onClick={validateOutline} disabled={busy || saving || generating || validating || reviewing || expanding} className="flex items-center gap-1.5 rounded border border-port-accent px-3 py-2 text-xs text-port-accent hover:bg-port-accent/10 disabled:opacity-50">
+ {validating ? <Loader2 size={13} className="animate-spin" /> : <CheckCircle2 size={13} />}
+ {validating ? 'Validating…' : dirty ? 'Save & validate' : 'Validate outline'}
+ </button>
+ <button type="button" onClick={reviewOutline} disabled={busy || dirty || saving || generating || validating || reviewing || expanding} className="flex items-center gap-1.5 rounded border border-port-border px-3 py-2 text-xs hover:border-port-accent disabled:opacity-50">
+ {reviewing ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}
+ {reviewing ? 'Reviewing…' : 'Review arc with AI'}
+ </button>
+ </div>
+ {dirty ? <p className="text-xs text-port-warning">Save the edited log-lines before asking the AI to review them.</p> : null}
+ <ValidationResult validation={validation || outline.validation} />
+ {onExpand ? (
+ <button
+ type="button"
+ onClick={onExpand}
+ disabled={busy || dirty || outlineStatus !== 'valid' || saving || generating || validating || reviewing || expanding}
+ className="flex w-full items-center justify-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50"
+ >
+ {expanding ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {expanding ? 'Expanding validated outline…' : 'Expand validated outline to teleplay'}
+ </button>
+ ) : null}
+ {review ? (
+ <div className="space-y-2 rounded border border-port-accent/30 bg-port-bg p-3" aria-live="polite">
+ <h5 className="text-sm font-semibold">Editorial outline review</h5>
+ {review.summary ? <p className="text-xs text-port-text-muted">{review.summary}</p> : null}
+ {[
+ ['Strengths', review.strengths],
+ ['Story risks', review.risks],
+ ['Recommended edits', review.recommendations],
+ ].map(([heading, items]) => items?.length ? <div key={heading}>
+ <h6 className="text-[11px] font-semibold uppercase tracking-wide text-port-text-muted">{heading}</h6>
+ <ul className="mt-1 list-disc space-y-1 pl-4 text-xs">{items.map((item) => <li key={item}>{item}</li>)}</ul>
+ </div> : null)}
+ </div>
+ ) : null}
+ </>
+ )}
+ <LoomAiRunStatus run={generateRun.run} />
+ <LoomAiRunStatus run={reviewRun.run} />
+ </section>
+ );
+}
diff --git a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx
new file mode 100644
index 0000000000..db83648b24
--- /dev/null
+++ b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+const toastMocks = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn(), warning: vi.fn() }));
+vi.mock('../ui/Toast', () => ({ default: toastMocks }));
+vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [], loading: false }) }));
+vi.mock('../../hooks/useFableLoomAiRun', () => ({
+ default: () => ({ run: null, begin: () => '00000000-0000-4000-8000-000000000001', fail: vi.fn() }),
+}));
+vi.mock('../ProviderModelSelector', () => ({ default: () => <div data-testid="outline-route">Outline AI route</div> }));
+
+vi.mock('../../services/api', () => ({
+ generateLoomEpisodeOutline: vi.fn(),
+ reviewLoomEpisodeOutline: vi.fn(),
+ updateLoomEpisode: vi.fn(),
+ validateLoomEpisodeOutline: vi.fn(),
+}));
+
+import * as api from '../../services/api';
+import LoomEpisodeOutlinePlanner from './LoomEpisodeOutlinePlanner';
+
+const outline = {
+ version: 1,
+ startKey: 's1',
+ scenes: [
+ { key: 's1', title: 'Signal', summary: 'A signal arrives.', playbackMode: 'cut', audienceConnection: 'disconnected', transitions: [{ targetKey: 's2', intent: 'follow it' }] },
+ { key: 's2', title: 'Choice', summary: 'The signal demands a cost.', playbackMode: 'decision', audienceConnection: 'connected', transitions: [{ targetKey: 's3', intent: 'answer' }, { targetKey: 's4', intent: 'wait' }] },
+ { key: 's3', title: 'Answer', summary: 'The answer opens a door.', playbackMode: 'cut', isEnding: true, endingLabel: 'Open door', transitions: [] },
+ { key: 's4', title: 'Wait', summary: 'The silence grows.', playbackMode: 'cut', isEnding: true, endingLabel: 'Long night', transitions: [] },
+ ],
+ validation: { status: 'valid', issues: [] },
+};
+
+const loom = { id: 'loom-1', name: 'Example Loom', episodes: [] };
+const episode = { id: 'ep-1', number: 1, title: 'Pilot', synopsis: 'A signal arrives.', nodes: [], storyOutline: outline };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('LoomEpisodeOutlinePlanner', () => {
+ it('shows the beat arc and only enables expansion after validation', async () => {
+ const user = userEvent.setup();
+ const onExpand = vi.fn();
+ render(<LoomEpisodeOutlinePlanner open loom={loom} episode={episode} onLoomUpdate={vi.fn()} onExpand={onExpand} />);
+
+ expect(screen.getByRole('heading', { name: 'Story beats → teleplay' })).toBeInTheDocument();
+ expect(screen.getByText('Signal')).toBeInTheDocument();
+ const expand = screen.getByRole('button', { name: 'Expand validated outline to teleplay' });
+ expect(expand).toBeEnabled();
+ await user.click(expand);
+ expect(onExpand).toHaveBeenCalledTimes(1);
+ });
+
+ it('saves edited log-lines before the deterministic validation request', async () => {
+ const user = userEvent.setup();
+ const updatedLoom = { ...loom, episodes: [{ ...episode, storyOutline: { ...outline, validation: { status: 'draft', issues: [] } } }] };
+ api.updateLoomEpisode.mockResolvedValueOnce(updatedLoom);
+ api.validateLoomEpisodeOutline.mockResolvedValueOnce({
+ loom: { ...updatedLoom, episodes: [{ ...episode, storyOutline: { ...outline, validation: { status: 'valid', issues: [] } } }] },
+ outline: { ...outline, validation: { status: 'valid', issues: [] } },
+ validation: { issues: [], stats: { sceneCount: 4, decisionCount: 1, endingCount: 2, errorCount: 0 } },
+ });
+ render(<LoomEpisodeOutlinePlanner open loom={loom} episode={episode} onLoomUpdate={vi.fn()} />);
+
+ await user.click(screen.getByTestId('outline-beat-s1').querySelector('button'));
+ const summary = screen.getByLabelText('Log-line / summary');
+ await user.clear(summary);
+ await user.type(summary, 'The signal names a living ship.');
+ await user.click(screen.getByRole('button', { name: 'Save & validate' }));
+
+ await waitFor(() => expect(api.updateLoomEpisode).toHaveBeenCalled());
+ expect(api.validateLoomEpisodeOutline).toHaveBeenCalledWith('loom-1', 'ep-1', { silent: true });
+ expect(await screen.findByText('Outline is structurally valid')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsx
index b89d9d0e94..c45cba3d01 100644
--- a/client/src/components/fableloom/LoomNodeEditor.jsx
+++ b/client/src/components/fableloom/LoomNodeEditor.jsx
@@ -13,6 +13,7 @@
*/
import { useEffect, useMemo, useState } from 'react';
+import { Link } from 'react-router';
import { GitBranch, Loader2, Trash2 } from 'lucide-react';
import toast from '../ui/Toast';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
@@ -32,6 +33,7 @@ import {
FABLELOOM_PLAYBACK_MODES,
FABLELOOM_PROTAGONIST_PRESENCE,
inspectNodeProductionReadiness,
+ resolveFableLoomProtagonistPresence,
} from '../../../../server/lib/fableLoomPlayback.js';
import { FABLELOOM_AUDIENCE_CONNECTION_STATES } from '../../../../server/lib/fableLoomParticipation.js';
@@ -43,6 +45,28 @@ const rowToPatch = ({ targetNodeId, intent, triggersText, description }) => ({
description: description || '',
});
+const REQUIRED_IDENTITY_ROLES = ['neutral', 'profile', 'full-body'];
+
+const characterReferenceInfo = (character) => {
+ const imageRefs = Array.isArray(character?.imageRefs) ? character.imageRefs.filter(Boolean) : [];
+ const sheetRefs = [
+ character?.referenceSheetImageRef,
+ ...Object.values(character?.referenceSheets || {}),
+ ].filter(Boolean);
+ const approvedRoles = new Set(
+ (Array.isArray(character?.identityPack?.assets) ? character.identityPack.assets : [])
+ .filter((asset) => asset?.approved === true)
+ .map((asset) => asset.role),
+ );
+ const missingIdentityRoles = REQUIRED_IDENTITY_ROLES.filter((role) => !approvedRoles.has(role));
+ return {
+ hasVisualReference: imageRefs.length > 0 || sheetRefs.length > 0 || Boolean(character?.primaryImageRef),
+ sheetCount: sheetRefs.length,
+ identityPackReady: missingIdentityRoles.length === 0,
+ missingIdentityRoles,
+ };
+};
+
export default function LoomNodeEditor({
loom, episode, node, universe, onLoomUpdate, onClearSelection, onMakeStart,
mediaJobs = {}, onGenerateImage, onGenerateVideo,
@@ -77,6 +101,7 @@ export default function LoomNodeEditor({
} : null,
playbackMode: node.playbackMode || 'decision',
audienceConnection: node.audienceConnection || 'disconnected',
+ protagonistPresence: node.protagonistPresence || null,
playbackAssets: node.playbackAssets || null,
interactionWindow: node.interactionWindow || {
enabled: false,
@@ -235,6 +260,74 @@ export default function LoomNodeEditor({
const aiBlocked = pendingSaves > 0;
const helperMode = loom.participationMode === 'helper';
const audienceConnected = !helperMode || form.audienceConnection === 'connected';
+ const universeCharacters = Array.isArray(universe?.characters) ? universe.characters : [];
+ const canonicalProtagonistId = loom.protagonistCharacterId || '';
+ const interactionProtagonistId = form.interactionWindow?.protagonistCharacterId || '';
+ const protagonistId = interactionProtagonistId || canonicalProtagonistId;
+ const protagonist = universeCharacters.find((character) => character.id === protagonistId) || null;
+ const protagonistReference = protagonist ? characterReferenceInfo(protagonist) : null;
+ const protagonistAppearance = form.visualCanon?.characterAppearances?.find(
+ (appearance) => appearance.characterId === protagonistId,
+ );
+ const linkedUniverseId = universe?.id || loom.universeId || null;
+ const recommendedPresence = helperMode && form.playbackMode === 'decision' && form.audienceConnection === 'connected'
+ ? 'offscreen'
+ : canonicalProtagonistId ? 'onscreen' : null;
+ const scenePresence = resolveFableLoomProtagonistPresence({
+ ...node,
+ playbackMode: form.playbackMode,
+ audienceConnection: form.audienceConnection,
+ protagonistPresence: form.protagonistPresence,
+ interactionWindow: form.interactionWindow,
+ }, loom) || recommendedPresence;
+ const presenceControlVisible = Boolean(
+ canonicalProtagonistId || protagonistId || form.visualCanon?.characterAppearances?.length,
+ );
+
+ const setScenePresence = (value) => {
+ const nextPresence = value || null;
+ const protagonistIds = new Set([canonicalProtagonistId, interactionProtagonistId, protagonistId].filter(Boolean));
+ let nextVisualCanon = form.visualCanon;
+ if (form.visualCanon && value === 'offscreen') {
+ nextVisualCanon = {
+ ...form.visualCanon,
+ characterAppearances: form.visualCanon.characterAppearances.filter(
+ (appearance) => !protagonistIds.has(appearance.characterId),
+ ),
+ };
+ } else if (form.visualCanon && value === 'onscreen' && canonicalProtagonistId
+ && !form.visualCanon.characterAppearances.some((appearance) => appearance.characterId === canonicalProtagonistId)) {
+ nextVisualCanon = {
+ ...form.visualCanon,
+ characterAppearances: [
+ ...form.visualCanon.characterAppearances,
+ {
+ characterId: canonicalProtagonistId,
+ wardrobeId: loom.protagonistWardrobeId || null,
+ expression: '',
+ continuityNotes: '',
+ },
+ ],
+ };
+ }
+ const nextInteraction = form.interactionWindow?.enabled
+ ? {
+ ...form.interactionWindow,
+ protagonistPresence: value || recommendedPresence || 'offscreen',
+ }
+ : form.interactionWindow;
+ setForm((current) => ({
+ ...current,
+ protagonistPresence: nextPresence,
+ visualCanon: nextVisualCanon,
+ interactionWindow: nextInteraction,
+ }));
+ patchNode({
+ protagonistPresence: nextPresence,
+ ...(form.interactionWindow?.enabled ? { interactionWindow: nextInteraction } : {}),
+ ...(nextVisualCanon !== form.visualCanon ? { visualCanon: nextVisualCanon } : {}),
+ });
+ };
return (
<div className="space-y-4 p-4">
@@ -338,6 +431,37 @@ export default function LoomNodeEditor({
</FormField>
)}
+ {presenceControlVisible && (
+ <div className="rounded border border-port-accent/30 bg-port-accent/5 p-3 space-y-2">
+ <FormField label="Visual protagonist presence" labelClassName={labelClass}>
+ <select
+ className={fieldClass}
+ aria-label="Visual protagonist presence"
+ value={form.protagonistPresence || ''}
+ onChange={(event) => setScenePresence(event.target.value)}
+ >
+ <option value="">
+ Inherit story default{recommendedPresence ? ` (${recommendedPresence === 'offscreen' ? 'off-screen' : 'on-screen'})` : ''}
+ </option>
+ {FABLELOOM_PROTAGONIST_PRESENCE.map((presence) => (
+ <option key={presence} value={presence}>
+ {presence === 'offscreen' ? 'Off-screen — omit protagonist from storyboard' : 'On-screen — include protagonist in storyboard'}
+ </option>
+ ))}
+ </select>
+ </FormField>
+ {scenePresence === 'offscreen' ? (
+ <p className="text-[11px] text-port-accent">
+ Side-device conversation: the decision loop stays visible while the protagonist speaks directly with the audience. The protagonist is removed from this scene&apos;s visual cast.
+ </p>
+ ) : (
+ <p className="text-[11px] text-port-text-muted">
+ On-screen scenes inherit the loom&apos;s canonical protagonist and locked wardrobe when the shot is bound to Universe canon.
+ </p>
+ )}
+ </div>
+ )}
+
<div className="flex items-center gap-3">
<label className="flex items-center gap-2 text-sm" htmlFor="loom-node-ending">
<input
@@ -376,6 +500,12 @@ export default function LoomNodeEditor({
const nextInteraction = {
...(form.interactionWindow || {}),
enabled: e.target.checked,
+ protagonistCharacterId: form.interactionWindow?.protagonistCharacterId
+ || canonicalProtagonistId
+ || null,
+ protagonistPresence: form.interactionWindow?.protagonistPresence
+ || scenePresence
+ || 'offscreen',
};
setForm((p) => ({ ...p, interactionWindow: nextInteraction }));
patchNode({ interactionWindow: nextInteraction });
@@ -386,29 +516,82 @@ export default function LoomNodeEditor({
{form.interactionWindow?.enabled && (
<div className="space-y-3 pl-5 pt-1 border-l-2 border-port-accent/30 text-xs">
- <FormField label="Protagonist Character ID" labelClassName={labelClass}>
- <input
+ <FormField label="Protagonist from Universe Bible" labelClassName={labelClass}>
+ <select
className={fieldClass}
- placeholder="e.g. char-protagonist"
- value={form.interactionWindow.protagonistCharacterId || ''}
+ id="loom-protagonist-character"
+ aria-label="Protagonist character"
+ value={protagonistId}
onChange={(e) => {
- const next = { ...form.interactionWindow, protagonistCharacterId: e.target.value };
+ const next = {
+ ...form.interactionWindow,
+ protagonistCharacterId: e.target.value || null,
+ };
setForm((p) => ({ ...p, interactionWindow: next }));
+ patchNode({ interactionWindow: next });
}}
- onBlur={() => patchNode({ interactionWindow: form.interactionWindow })}
- />
+ >
+ <option value="">Choose a Universe character</option>
+ {protagonistId && !protagonist && (
+ <option value={protagonistId}>Missing Universe character ({protagonistId})</option>
+ )}
+ {universeCharacters.map((character) => (
+ <option key={character.id} value={character.id}>{character.name || character.id}</option>
+ ))}
+ </select>
</FormField>
+ {protagonist ? (
+ <div className="rounded border border-port-border/70 bg-port-bg/40 p-2 space-y-1.5" role="status">
+ <div className="font-medium text-port-text">{protagonist.name || protagonist.id}</div>
+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-[11px]">
+ <span className={protagonistReference.hasVisualReference ? 'text-port-success' : 'text-port-warning'}>
+ {protagonistReference.hasVisualReference ? 'Visual reference ready' : 'Needs visual reference'}
+ </span>
+ <span className={protagonistReference.sheetCount ? 'text-port-success' : 'text-port-warning'}>
+ {protagonistReference.sheetCount
+ ? `${protagonistReference.sheetCount} character sheet${protagonistReference.sheetCount === 1 ? '' : 's'}`
+ : 'Needs character sheet'}
+ </span>
+ <span className={protagonistReference.identityPackReady ? 'text-port-success' : 'text-port-warning'}>
+ {protagonistReference.identityPackReady
+ ? 'Identity pack ready'
+ : `Identity pack missing ${protagonistReference.missingIdentityRoles.join(', ')}`}
+ </span>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {linkedUniverseId && (
+ <Link
+ to={`/universes/${encodeURIComponent(linkedUniverseId)}?tab=cast`}
+ className="text-[11px] text-port-accent hover:underline"
+ >
+ Open Universe character sheets
+ </Link>
+ )}
+ </div>
+ {scenePresence === 'offscreen' && form.visualCanon && protagonistAppearance && (
+ <p className="text-[11px] text-port-accent">
+ Protagonist binding is omitted from this off-screen storyboard; it will return when this scene is marked on-screen.
+ </p>
+ )}
+ {scenePresence !== 'offscreen' && !protagonistAppearance && form.visualCanon && (
+ <p className="text-[11px] text-port-warning">
+ This scene&apos;s locked image/video cast does not include the protagonist yet.
+ </p>
+ )}
+ </div>
+ ) : (
+ <p className="text-[11px] text-port-warning">
+ Select the protagonist from the linked Universe before enabling canon-locked voice or visual production.
+ </p>
+ )}
+
<div className="grid grid-cols-2 gap-2">
<FormField label="Protagonist presence" labelClassName={labelClass}>
<select
className={fieldClass}
- value={form.interactionWindow.protagonistPresence || 'offscreen'}
- onChange={(e) => {
- const next = { ...form.interactionWindow, protagonistPresence: e.target.value };
- setForm((p) => ({ ...p, interactionWindow: next }));
- patchNode({ interactionWindow: next });
- }}
+ value={form.interactionWindow.protagonistPresence || scenePresence || 'offscreen'}
+ onChange={(e) => setScenePresence(e.target.value)}
>
{FABLELOOM_PROTAGONIST_PRESENCE.map((p) => (
<option key={p} value={p}>{p === 'offscreen' ? 'Off-screen' : 'On-screen'}</option>
@@ -453,7 +636,7 @@ export default function LoomNodeEditor({
)}
{(() => {
- const readiness = inspectNodeProductionReadiness(node, { loom });
+ const readiness = inspectNodeProductionReadiness(node, { loom, universe });
if (!readiness.findings.length) return null;
return (
<div className="mt-2 space-y-1.5 pt-2 border-t border-port-border/60">
@@ -520,30 +703,78 @@ export default function LoomNodeEditor({
<fieldset className="space-y-2">
<legend className={labelClass}>Characters</legend>
+ <p className="text-[11px] text-port-text-muted">
+ Bind every on-screen character to the Universe Bible. Canon-locked renders use each selected character&apos;s visual reference, wardrobe, and approved neutral/profile/full-body identity assets.
+ </p>
+ {canonicalProtagonistId && scenePresence !== 'offscreen'
+ && !form.visualCanon.characterAppearances.some((appearance) => appearance.characterId === canonicalProtagonistId) && (
+ <button
+ type="button"
+ aria-label="Add canonical protagonist to visual cast"
+ className="text-xs text-port-accent hover:underline"
+ onClick={() => updateVisualCanon({
+ characterAppearances: [
+ ...form.visualCanon.characterAppearances,
+ {
+ characterId: canonicalProtagonistId,
+ wardrobeId: loom.protagonistWardrobeId || null,
+ expression: '',
+ continuityNotes: '',
+ },
+ ],
+ })}
+ >
+ Add canonical protagonist to visual cast
+ </button>
+ )}
{(universe?.characters || []).map((character) => {
const appearance = form.visualCanon.characterAppearances
.find((item) => item.characterId === character.id);
+ const reference = characterReferenceInfo(character);
+ const canonicalWardrobeLocked = character.id === canonicalProtagonistId
+ && loom.protagonistWardrobeLocked === true
+ && Boolean(loom.protagonistWardrobeId);
+ const wardrobeValue = canonicalWardrobeLocked
+ ? loom.protagonistWardrobeId
+ : appearance?.wardrobeId || '';
return (
<div key={character.id} className="rounded bg-port-bg-subtle p-2 space-y-2">
- <label className="flex items-center gap-2 text-xs" htmlFor={`loom-canon-character-${character.id}`}>
- <input
- id={`loom-canon-character-${character.id}`}
- aria-label={character.name}
- type="checkbox"
- checked={Boolean(appearance)}
- onChange={(event) => updateVisualCanon({
- characterAppearances: event.target.checked
- ? [...form.visualCanon.characterAppearances, { characterId: character.id, wardrobeId: null, expression: '', continuityNotes: '' }]
- : form.visualCanon.characterAppearances.filter((item) => item.characterId !== character.id),
- })}
- />
- {character.name}
- </label>
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <label className="flex items-center gap-2 text-xs" htmlFor={`loom-canon-character-${character.id}`}>
+ <input
+ id={`loom-canon-character-${character.id}`}
+ aria-label={character.name}
+ type="checkbox"
+ checked={Boolean(appearance)}
+ onChange={(event) => updateVisualCanon({
+ characterAppearances: event.target.checked
+ ? [...form.visualCanon.characterAppearances, {
+ characterId: character.id,
+ wardrobeId: character.id === canonicalProtagonistId
+ ? loom.protagonistWardrobeId || null
+ : null,
+ expression: '',
+ continuityNotes: '',
+ }]
+ : form.visualCanon.characterAppearances.filter((item) => item.characterId !== character.id),
+ })}
+ />
+ {character.name}
+ </label>
+ <span className={`text-[10px] ${reference.identityPackReady ? 'text-port-success' : 'text-port-warning'}`}>
+ {reference.identityPackReady
+ ? 'Identity pack ready'
+ : reference.sheetCount
+ ? `Sheet ready · identity missing ${reference.missingIdentityRoles.join(', ')}`
+ : 'Needs character sheet'}
+ </span>
+ </div>
{appearance && (character.wardrobes || []).length > 0 && (
<select
className={fieldClass}
aria-label={`${character.name} wardrobe`}
- value={appearance.wardrobeId || ''}
+ value={wardrobeValue}
+ disabled={canonicalWardrobeLocked}
onChange={(event) => updateVisualCanon({
characterAppearances: form.visualCanon.characterAppearances.map((item) => (
item.characterId === character.id ? { ...item, wardrobeId: event.target.value || null } : item
@@ -551,11 +782,17 @@ export default function LoomNodeEditor({
})}
>
<option value="">Default wardrobe</option>
+ {wardrobeValue && !character.wardrobes.some((wardrobe) => wardrobe.id === wardrobeValue) && (
+ <option value={wardrobeValue}>Missing wardrobe ({wardrobeValue})</option>
+ )}
{character.wardrobes.map((wardrobe) => (
<option key={wardrobe.id} value={wardrobe.id}>{wardrobe.name || wardrobe.label || 'Wardrobe'}</option>
))}
</select>
)}
+ {appearance && canonicalWardrobeLocked && (
+ <p className="text-[11px] text-port-accent">Locked to the loom&apos;s canonical protagonist wardrobe.</p>
+ )}
{appearance && (
<div className="grid gap-2 sm:grid-cols-2">
<input
diff --git a/client/src/components/fableloom/LoomNodeEditor.test.jsx b/client/src/components/fableloom/LoomNodeEditor.test.jsx
index 79bed9ac79..3f8b45cc48 100644
--- a/client/src/components/fableloom/LoomNodeEditor.test.jsx
+++ b/client/src/components/fableloom/LoomNodeEditor.test.jsx
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
import userEvent from '@testing-library/user-event';
vi.mock('../../services/api', () => ({
@@ -39,20 +40,23 @@ const renderEditor = (transitions = [existingPath]) => {
const onGenerateImage = vi.fn().mockResolvedValue({ jobId: 'image-1' });
const onGenerateVideo = vi.fn().mockResolvedValue({ jobId: 'video-1' });
render(
- <LoomNodeEditor
- loom={loom}
- episode={episode}
- node={nodes[0]}
- universe={{
- characters: [{ id: 'char-1', name: 'Aria', wardrobes: [{ id: 'coat', name: 'Travel coat' }] }],
- places: [{ id: 'place-1', name: 'Atrium' }],
- objects: [{ id: 'object-1', name: 'Compass' }],
- }}
- onLoomUpdate={onLoomUpdate}
- onClearSelection={() => {}}
- onGenerateImage={onGenerateImage}
- onGenerateVideo={onGenerateVideo}
- />,
+ <MemoryRouter>
+ <LoomNodeEditor
+ loom={loom}
+ episode={episode}
+ node={nodes[0]}
+ universe={{
+ id: 'universe-1',
+ characters: [{ id: 'char-1', name: 'Aria', wardrobes: [{ id: 'coat', name: 'Travel coat' }] }],
+ places: [{ id: 'place-1', name: 'Atrium' }],
+ objects: [{ id: 'object-1', name: 'Compass' }],
+ }}
+ onLoomUpdate={onLoomUpdate}
+ onClearSelection={() => {}}
+ onGenerateImage={onGenerateImage}
+ onGenerateVideo={onGenerateVideo}
+ />
+ </MemoryRouter>,
);
return { onLoomUpdate, onGenerateImage, onGenerateVideo };
};
@@ -76,6 +80,45 @@ const renderHelperEditor = () => {
);
};
+const renderCanonicalEditor = (presence = 'onscreen') => {
+ const nodes = makeNodes([]);
+ nodes[0].protagonistPresence = presence;
+ nodes[0].visualCanon = {
+ mode: 'locked',
+ characterAppearances: presence === 'offscreen' ? [{ characterId: 'char-1', wardrobeId: 'coat' }] : [],
+ placeId: null,
+ objectIds: [],
+ continuitySourceNodeId: null,
+ shotNotes: '',
+ storyboardImageApproved: false,
+ };
+ const canonicalLoom = {
+ ...loom,
+ protagonistCharacterId: 'char-1',
+ protagonistWardrobeId: 'coat',
+ protagonistWardrobeLocked: true,
+ };
+ render(
+ <MemoryRouter>
+ <LoomNodeEditor
+ loom={canonicalLoom}
+ episode={{ id: 'ep-1', startNodeId: 'n1', nodes }}
+ node={nodes[0]}
+ universe={{
+ id: 'universe-1',
+ characters: [{ id: 'char-1', name: 'Aria', wardrobes: [{ id: 'coat', name: 'Travel coat' }] }],
+ places: [],
+ objects: [],
+ }}
+ onLoomUpdate={vi.fn()}
+ onClearSelection={() => {}}
+ onGenerateImage={vi.fn()}
+ onGenerateVideo={vi.fn()}
+ />
+ </MemoryRouter>,
+ );
+};
+
beforeEach(() => vi.clearAllMocks());
describe('LoomNodeEditor paths', () => {
@@ -167,6 +210,28 @@ describe('LoomNodeEditor paths', () => {
});
describe('LoomNodeEditor scene media', () => {
+ it('selects a protagonist from the linked Universe and surfaces reference readiness', async () => {
+ const user = userEvent.setup();
+ updateLoomNode.mockResolvedValue({ id: 'loom-1' });
+ renderEditor();
+
+ await user.click(screen.getByLabelText('Live conversation window (off-screen voice)'));
+ await user.selectOptions(screen.getByLabelText('Protagonist character'), 'char-1');
+
+ await waitFor(() => expect(updateLoomNode).toHaveBeenLastCalledWith(
+ 'loom-1', 'ep-1', 'n1', {
+ interactionWindow: expect.objectContaining({
+ enabled: true,
+ protagonistCharacterId: 'char-1',
+ }),
+ }, { silent: true },
+ ));
+ expect(screen.getByRole('status')).toHaveTextContent('Needs character sheet');
+ expect(screen.getByRole('link', { name: 'Open Universe character sheets' })).toHaveAttribute(
+ 'href', '/universes/universe-1?tab=cast',
+ );
+ });
+
it('persists structured canon bindings and explicit storyboard approval', async () => {
const user = userEvent.setup();
updateLoomNode.mockResolvedValue({ id: 'loom-1' });
@@ -190,6 +255,40 @@ describe('LoomNodeEditor scene media', () => {
));
});
+ it('offers the canonical protagonist as a one-click visual-cast binding', async () => {
+ const user = userEvent.setup();
+ updateLoomNode.mockResolvedValue({ id: 'loom-1' });
+ renderCanonicalEditor();
+
+ await user.click(screen.getByRole('button', { name: 'Add canonical protagonist to visual cast' }));
+
+ await waitFor(() => expect(updateLoomNode).toHaveBeenCalledWith(
+ 'loom-1', 'ep-1', 'n1', {
+ visualCanon: expect.objectContaining({
+ characterAppearances: [{
+ characterId: 'char-1', wardrobeId: 'coat', expression: '', continuityNotes: '',
+ }],
+ }),
+ }, { silent: true },
+ ));
+ });
+
+ it('removes the protagonist visual binding when a scene becomes off-screen', async () => {
+ const user = userEvent.setup();
+ updateLoomNode.mockResolvedValue({ id: 'loom-1' });
+ renderCanonicalEditor('offscreen');
+
+ await user.selectOptions(screen.getByLabelText('Visual protagonist presence'), 'offscreen');
+
+ await waitFor(() => expect(updateLoomNode).toHaveBeenCalledWith(
+ 'loom-1', 'ep-1', 'n1', {
+ protagonistPresence: 'offscreen',
+ visualCanon: expect.objectContaining({ characterAppearances: [] }),
+ }, { silent: true },
+ ));
+ expect(screen.getByText(/Side-device conversation/)).toBeInTheDocument();
+ });
+
it('queues a local video from the teleplay scene and rendered still', async () => {
const user = userEvent.setup();
const { onGenerateVideo } = renderEditor();
@@ -312,7 +411,7 @@ describe('LoomNodeEditor scene media', () => {
{ silent: true },
));
- expect(screen.getByLabelText('Protagonist Character ID')).toBeInTheDocument();
+ expect(screen.getByLabelText('Protagonist character')).toBeInTheDocument();
expect(screen.getByLabelText('Protagonist presence')).toBeInTheDocument();
});
diff --git a/client/src/components/fableloom/LoomPlayPanel.jsx b/client/src/components/fableloom/LoomPlayPanel.jsx
index e00f977229..7f716b6e1c 100644
--- a/client/src/components/fableloom/LoomPlayPanel.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.jsx
@@ -22,7 +22,10 @@ import { playLoomTurn } from '../../services/api';
import { sceneProseClass } from './fieldStyles';
import LoomHostedSessionModal from './LoomHostedSessionModal';
import { audienceCanParticipate } from '../../../../server/lib/fableLoomParticipation.js';
-import { resolvePlaybackPhaseAsset } from '../../../../server/lib/fableLoomPlayback.js';
+import {
+ resolveFableLoomProtagonistPresence,
+ resolvePlaybackPhaseAsset,
+} from '../../../../server/lib/fableLoomPlayback.js';
const findNode = (episode, id) => episode?.nodes.find((n) => n.id === id) || null;
const hasPlayableStart = (episode) => !!findNode(episode, episode?.startNodeId);
@@ -30,7 +33,7 @@ const hasPlayableStart = (episode) => !!findNode(episode, episode?.startNodeId);
// Reader-facing projection of an authored node — the OPENING scene only, which
// the panel shows before any turn has been taken. Every later scene arrives
// from the play endpoint already in this shape (the server's `publicNode`).
-const asPublic = (node) => (node ? {
+const asPublic = (node, loom) => (node ? {
id: node.id,
title: node.title,
prose: node.prose,
@@ -38,6 +41,7 @@ const asPublic = (node) => (node ? {
videoHistoryId: node.videoHistoryId,
playbackAssets: node.playbackAssets || null,
interactionWindow: node.interactionWindow || null,
+ protagonistPresence: resolveFableLoomProtagonistPresence(node, loom),
playbackMode: node.playbackMode || 'decision',
audienceConnection: node.audienceConnection || 'disconnected',
isEnding: !!node.isEnding,
@@ -64,13 +68,22 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode }) {
? (loom.episodes || []).findIndex((item, index) => index > episodeIndex && hasPlayableStart(item))
: -1;
const nextEpisode = nextEpisodeIndex >= 0 ? loom.episodes[nextEpisodeIndex] : null;
+ const deliveryOptions = loom.seriesPlan?.deliveryOptions || {};
+ const overnightVoicemail = nextEpisode && deliveryOptions.overnightVoicemails === true
+ ? (loom.seriesPlan?.interEpisodeVoicemails || []).find((item) => (
+ item.fromEpisodeId === episode.id && item.toEpisodeId === nextEpisode.id
+ )) || { title: 'A message left overnight', transcript: '' }
+ : null;
+ const nextSeasonTeaser = !nextEpisode && deliveryOptions.nextSeasonTeaser === true
+ ? loom.seriesPlan?.nextSeasonTeaser || { title: 'A signal beyond the ending', transcript: '' }
+ : null;
// Anchored on scalars so an authoring echo elsewhere in the loom (a node
// PATCH, a drag) doesn't mint a new `start` identity and wipe an
// in-progress read-through. The trade: mid-session edits to the opening
// scene's text don't reach an open drawer until restart.
const start = useMemo(
- () => asPublic(findNode(episode, episode?.startNodeId)),
- [episode.id, episode.startNodeId],
+ () => asPublic(findNode(episode, episode?.startNodeId), loom),
+ [episode.id, episode.startNodeId, loom.participationMode, loom.protagonistCharacterId],
);
const [scene, setScene] = useState(start);
const [playbackPhase, setPlaybackPhase] = useState(() => initialPhaseForNode(start));
@@ -418,6 +431,11 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode }) {
<span>Presence: {scene.interactionWindow.protagonistPresence || 'offscreen'}</span>
</div>
)}
+ {scene.protagonistPresence && !scene.interactionWindow?.enabled && (
+ <div className="text-[10px] text-port-text-muted">
+ Visual protagonist: {scene.protagonistPresence === 'offscreen' ? 'off-screen — side-device conversation' : 'on-screen'}
+ </div>
+ )}
</div>
)}
@@ -484,6 +502,22 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode }) {
{scene?.endingLabel ? `Ending: ${scene.endingLabel}` : 'The End'}
</div>
)}
+ {ended && overnightVoicemail && (
+ <SeriesDeliveryCard
+ label={`Overnight voicemail · Episode ${episode.number || episodeIndex + 1} → Episode ${nextEpisode.number || nextEpisodeIndex + 1}`}
+ title={overnightVoicemail.title || 'A message left overnight'}
+ transcript={overnightVoicemail.transcript}
+ emptyMessage="This episode boundary is configured for a voicemail, but its transcript is still waiting to be authored."
+ />
+ )}
+ {ended && nextSeasonTeaser && (
+ <SeriesDeliveryCard
+ label="Next-season teaser"
+ title={nextSeasonTeaser.title || 'A signal beyond the ending'}
+ transcript={nextSeasonTeaser.transcript}
+ emptyMessage="The next-season teaser is enabled, but its cliffhanger is still waiting to be authored."
+ />
+ )}
</div>
<div className="border-t border-port-border p-3 space-y-2">
{!ended && audienceConnected && !automaticCut && scene?.choices?.length > 0 && (
@@ -566,6 +600,18 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode }) {
);
}
+function SeriesDeliveryCard({ label, title, transcript, emptyMessage }) {
+ return (
+ <div className="border border-port-accent/40 rounded-lg bg-port-accent/5 p-3" role="region" aria-label={label}>
+ <div className="text-[10px] uppercase tracking-wide text-port-accent mb-1">{label}</div>
+ <div className="text-sm font-medium mb-1">{title}</div>
+ <p className="text-sm whitespace-pre-wrap">
+ {transcript?.trim() || emptyMessage}
+ </p>
+ </div>
+ );
+}
+
function SceneCard({
node, isOpening = false, format, previewMode, onCutEnded, automaticCut,
playbackPhase = 'hold', activeAsset = null,
@@ -605,6 +651,16 @@ function SceneCard({
{isOpening ? 'Opening' : node.isEnding ? (node.endingLabel || 'Ending') : node.title || 'Scene'}
</div>
{previewMode === 'text' && <p className={sceneProseClass(format)}>{node.prose}</p>}
+ {previewMode === 'image' && (
+ <div className="mt-2 rounded border border-port-border/70 bg-port-bg/40 p-2.5">
+ <div className="text-[10px] uppercase tracking-wide text-port-text-muted mb-1">
+ Scene description &amp; dialogue
+ </div>
+ <p className={sceneProseClass(format)}>
+ {node.prose || 'No scene description has been authored yet.'}
+ </p>
+ </div>
+ )}
{previewMode === 'image' && !node.image && <p className="text-sm text-port-text-muted">No storyboard image rendered for this cut yet.</p>}
{previewMode === 'video' && (!videoId || videoFailed) && (
<p className="text-sm text-port-text-muted">
@@ -622,8 +678,12 @@ function SceneCard({
: 'Decision loop — waits for viewer input'}
</p>
)}
+ {!node.isEnding && node.protagonistPresence === 'offscreen' && (
+ <p className="mt-1 text-xs text-port-accent">
+ Protagonist off-screen — keep this decision loop running while the audience conversation happens on the side device.
+ </p>
+ )}
</div>
</div>
);
}
-
diff --git a/client/src/components/fableloom/LoomPlayPanel.test.jsx b/client/src/components/fableloom/LoomPlayPanel.test.jsx
index aeccdd1b34..4ae9739e5a 100644
--- a/client/src/components/fableloom/LoomPlayPanel.test.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.test.jsx
@@ -37,6 +37,16 @@ describe('LoomPlayPanel', () => {
expect(screen.getByRole('button', { name: 'Take path: enter the gate' })).toBeInTheDocument();
});
+ it('keeps the scene description and dialogue visible in storyboard image mode', async () => {
+ const user = userEvent.setup();
+ render(<LoomPlayPanel loom={loom} episode={episode} />);
+
+ await user.selectOptions(screen.getByLabelText('Preview stage'), 'image');
+
+ expect(screen.getByText('Scene description & dialogue')).toBeInTheDocument();
+ expect(screen.getByText('You stand before it.')).toBeInTheDocument();
+ });
+
it('keeps a helper audience passive and follows the first canon path until the channel connects', async () => {
const user = userEvent.setup();
const helperEpisode = {
@@ -261,6 +271,60 @@ describe('LoomPlayPanel', () => {
expect(screen.queryByText('Episode one ends.')).not.toBeInTheDocument();
});
+ it('shows an authored overnight voicemail at an episode boundary', async () => {
+ const first = {
+ id: 'ep-1', number: 1, title: 'One', startNodeId: 'end-1',
+ nodes: [{ id: 'end-1', title: 'First ending', prose: 'Episode one ends.', isEnding: true, transitions: [] }],
+ };
+ const second = {
+ id: 'ep-2', number: 2, title: 'Two', startNodeId: 'start-2',
+ nodes: [{ id: 'start-2', title: 'Second opening', prose: 'Episode two begins.', transitions: [] }],
+ };
+ render(<LoomPlayPanel
+ loom={{
+ ...loom,
+ episodes: [first, second],
+ seriesPlan: {
+ deliveryOptions: { overnightVoicemails: true, nextSeasonTeaser: false },
+ interEpisodeVoicemails: [{
+ id: 'vm-1', fromEpisodeId: 'ep-1', toEpisodeId: 'ep-2',
+ title: 'A voice in the dark', transcript: 'Don’t let the signal go cold.',
+ }],
+ },
+ }}
+ episode={first}
+ />);
+
+ expect(screen.getByRole('region', { name: 'Overnight voicemail · Episode 1 → Episode 2' })).toHaveTextContent(
+ 'Don’t let the signal go cold.',
+ );
+ });
+
+ it('shows a configured next-season teaser after the final ending', () => {
+ const finale = {
+ id: 'ep-final', number: 3, title: 'Finale', startNodeId: 'end-final',
+ nodes: [{ id: 'end-final', title: 'Final ending', prose: 'The season closes.', isEnding: true, transitions: [] }],
+ };
+ render(<LoomPlayPanel
+ loom={{
+ ...loom,
+ episodes: [finale],
+ seriesPlan: {
+ deliveryOptions: { overnightVoicemails: false, nextSeasonTeaser: true },
+ nextSeasonTeaser: {
+ title: 'The answer beyond the relay',
+ transcript: 'A second voice answers in her own voice.',
+ },
+ },
+ }}
+ episode={finale}
+ />);
+
+ expect(screen.getByRole('region', { name: 'Next-season teaser' })).toHaveTextContent(
+ 'A second voice answers in her own voice.',
+ );
+ });
+
it('does not offer an unplayable empty episode', () => {
const first = {
id: 'ep-1', number: 1, startNodeId: 'end-1',
@@ -383,4 +447,3 @@ describe('LoomPlayPanel', () => {
expect(screen.getByText(/Asset: vid-entry-hall/)).toBeInTheDocument();
});
});
-
diff --git a/client/src/components/fableloom/LoomProductionPanel.jsx b/client/src/components/fableloom/LoomProductionPanel.jsx
index 5bcc6d2b64..4afa39c2a9 100644
--- a/client/src/components/fableloom/LoomProductionPanel.jsx
+++ b/client/src/components/fableloom/LoomProductionPanel.jsx
@@ -33,6 +33,7 @@ import {
resumeLoomEpisodeProductionBatch,
startLoomEpisodeProductionBatch,
} from '../../services/api';
+import { fableLoomStoryReadiness } from '../../lib/fableLoomReadiness';
const IMAGE_BACKENDS = [
{ id: 'auto', label: 'Auto', icon: Layers },
@@ -52,6 +53,14 @@ const modelOptions = (models) => (Array.isArray(models) ? models : [])
.filter((model) => model?.id)
.map((model) => ({ id: model.id, label: model.name || model.id }));
+const productionAssetsForScope = (plan, scope) => {
+ if (!Array.isArray(plan?.plannedAssets)) return [];
+ if (scope === 'images') return plan.plannedAssets.filter((asset) => asset.type === 'image');
+ return plan.plannedAssets;
+};
+
+const assetIsReady = (asset) => asset.status !== 'blocked' && asset.readiness?.ready !== false;
+
const severityIcon = (severity) => {
if (severity === 'error' || severity === 'high') {
return <CircleAlert size={14} className="text-port-error shrink-0 mt-0.5" />;
@@ -64,6 +73,7 @@ const severityIcon = (severity) => {
export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
const [mode, setMode] = useState('current_canon');
+ const [assetScope, setAssetScope] = useState('images');
const [plan, setPlan] = useState(null);
const [activeBatchRun, setActiveBatchRun] = useState(null);
const [continuityReview, setContinuityReview] = useState(null);
@@ -127,7 +137,10 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
}, [activeBatchRun, loom.id, episode.id, mode]);
const [startBatch, startingBatch] = useAsyncAction(async () => {
- const res = await startLoomEpisodeProductionBatch(loom.id, episode.id, renderOptions(), { silent: true });
+ const res = await startLoomEpisodeProductionBatch(loom.id, episode.id, {
+ ...renderOptions(),
+ ...(selectedAssetTypes ? { assetTypes: selectedAssetTypes } : {}),
+ }, { silent: true });
setActiveBatchRun(res);
}, { errorMessage: 'Starting production batch failed' });
@@ -148,15 +161,35 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
setContinuityReview(res);
}, { errorMessage: 'Continuity review failed' });
+ const scopedAssets = productionAssetsForScope(plan, assetScope);
+ const hasAssetList = Array.isArray(plan?.plannedAssets);
+ const plannedCount = hasAssetList
+ ? scopedAssets.length
+ : assetScope === 'images' ? plan?.assetsByType?.image || 0 : plan?.totalAssets || 0;
+ const readyCount = hasAssetList
+ ? scopedAssets.filter(assetIsReady).length
+ : assetScope === 'images' ? plan?.assetsByType?.image || 0 : plan?.readyAssetsCount || 0;
+ const renderedCount = hasAssetList
+ ? scopedAssets.filter((asset) => asset.status === 'already_rendered' || asset.status === 'skipped').length
+ : plan?.alreadyRenderedCount || 0;
+ const blockedCount = hasAssetList
+ ? scopedAssets.filter((asset) => !assetIsReady(asset)).length
+ : assetScope === 'images' ? 0 : plan?.blockedAssetsCount || 0;
+ const selectedAssetTypes = assetScope === 'images' ? ['image'] : null;
+ const storyReadiness = fableLoomStoryReadiness(loom);
+
const filteredFindings = (continuityReview?.findings || []).filter((f) => {
if (categoryFilter === 'all') return true;
return f.category === categoryFilter;
});
const readinessBlockers = [
+ ...(episode?.nodes?.length && !storyReadiness.ready
+ ? [{ message: storyReadiness.reason, nodeId: null }]
+ : []),
...(plan?.planningIssues || []).map((message) => ({ message, nodeId: null })),
- ...(plan?.plannedAssets || [])
- .filter((asset) => asset.status === 'blocked' || asset.readiness?.ready === false)
+ ...scopedAssets
+ .filter((asset) => !assetIsReady(asset))
.flatMap((asset) => (asset.readiness?.reasons || []).map((message) => ({
message,
nodeId: asset.nodeId,
@@ -164,6 +197,8 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
].filter((item, index, items) => items.findIndex((candidate) => (
candidate.message === item.message && candidate.nodeId === item.nodeId
)) === index);
+ const canStart = readinessBlockers.length === 0
+ && (mode !== 'exact_inputs' || !plan?.exactInputIssues?.length);
return (
<div className="p-4 space-y-6">
@@ -200,6 +235,22 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
</select>
</div>
+ <div className="flex flex-wrap items-center gap-2 mb-3">
+ <label htmlFor="fableloom-production-scope" className="text-xs text-port-text-muted">Production target:</label>
+ <select
+ id="fableloom-production-scope"
+ value={assetScope}
+ onChange={(event) => setAssetScope(event.target.value)}
+ className="text-xs bg-port-card border border-port-border rounded px-2 py-1 text-port-text focus:outline-none focus:border-port-accent"
+ >
+ <option value="images">Storyboard images only</option>
+ <option value="all">Images + video assets</option>
+ </select>
+ <span className="text-[10px] text-port-text-muted">
+ {assetScope === 'images' ? 'Video stays unqueued until you opt in.' : 'Queues the complete audiovisual plan.'}
+ </span>
+ </div>
+
{planning && !plan && (
<div className="flex items-center gap-2 text-xs text-port-text-muted py-2">
<Loader2 size={12} className="animate-spin" />
@@ -212,19 +263,21 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
<div className="grid grid-cols-3 gap-2 text-xs">
<div className="p-2 rounded bg-port-card border border-port-border">
<div className="text-port-text-muted text-[10px] uppercase font-semibold">Planned Assets</div>
- <div className="text-sm font-bold mt-0.5">{plan.totalAssets}</div>
+ <div className="text-sm font-bold mt-0.5">{plannedCount}</div>
<div className="text-[10px] text-port-text-muted mt-0.5">
- {plan.assetsByType?.image || 0} stills · {plan.assetsByType?.video || 0} clips
+ {assetScope === 'images'
+ ? `${plannedCount} stills · video not queued`
+ : `${plan.assetsByType?.image || 0} stills · ${plan.assetsByType?.video || 0} clips`}
</div>
</div>
<div className="p-2 rounded bg-port-card border border-port-border">
<div className="text-port-text-muted text-[10px] uppercase font-semibold">Ready / Rendered</div>
<div className="text-sm font-bold text-port-success mt-0.5">
- {plan.readyAssetsCount} / {plan.alreadyRenderedCount}
+ {readyCount} / {renderedCount}
</div>
<div className="text-[10px] text-port-text-muted mt-0.5">
- {plan.blockedAssetsCount} blocked
+ {blockedCount} blocked
</div>
</div>
@@ -239,6 +292,27 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
</div>
</div>
+ {plan.episodeOrderReadiness && (
+ <div className={`rounded border p-2.5 text-xs ${plan.episodeOrderReadiness.ready
+ ? 'border-port-success/30 bg-port-success/10'
+ : 'border-port-warning/30 bg-port-warning/10'}`}>
+ <div className="font-semibold flex items-center gap-1">
+ {plan.episodeOrderReadiness.ready
+ ? <CheckCircle2 size={12} className="text-port-success" />
+ : <AlertTriangle size={12} className="text-port-warning" />}
+ Ordered storyboard sequence
+ </div>
+ <div className="text-[11px] text-port-text-muted mt-1">
+ {plan.episodeOrderReadiness.reason}
+ </div>
+ {!plan.episodeOrderReadiness.ready && plan.episodeOrderReadiness.missingScenes?.length > 0 && (
+ <div className="text-[11px] text-port-text-muted mt-1">
+ {plan.episodeOrderReadiness.missingScenes.length} prior scene image(s) still need to be rendered.
+ </div>
+ )}
+ </div>
+ )}
+
<div className="rounded bg-port-card border border-port-border p-2.5 space-y-2">
<div className="text-[10px] uppercase font-semibold text-port-text-muted">Render settings</div>
<div className="space-y-1.5">
@@ -268,32 +342,34 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
</select>
)}
</div>
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-[11px] text-port-text-muted w-14">Video</span>
- <BackendChipStrip
- availableBackends={VIDEO_BACKENDS}
- value={videoMode || 'auto'}
- onChange={(value) => setVideoMode(value === 'auto' ? null : value)}
- size="sm"
- ariaLabel="Video provider"
- />
- {(videoMode === 'local' || !videoMode) && (
- <label htmlFor="fableloom-video-model" className="sr-only">Video model</label>
- )}
- {(videoMode === 'local' || !videoMode) && (
- <select
- id="fableloom-video-model"
- value={videoModel || ''}
- onChange={(event) => setVideoModel(event.target.value || null)}
- className="text-[11px] bg-port-bg border border-port-border rounded px-1.5 py-1 text-port-text"
- >
- <option value="">Saved video model</option>
- {modelOptions(videoModels).map((modelOption) => (
- <option key={modelOption.id} value={modelOption.id}>{modelOption.label}</option>
- ))}
- </select>
- )}
- </div>
+ {assetScope === 'all' && (
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-[11px] text-port-text-muted w-14">Video</span>
+ <BackendChipStrip
+ availableBackends={VIDEO_BACKENDS}
+ value={videoMode || 'auto'}
+ onChange={(value) => setVideoMode(value === 'auto' ? null : value)}
+ size="sm"
+ ariaLabel="Video provider"
+ />
+ {(videoMode === 'local' || !videoMode) && (
+ <label htmlFor="fableloom-video-model" className="sr-only">Video model</label>
+ )}
+ {(videoMode === 'local' || !videoMode) && (
+ <select
+ id="fableloom-video-model"
+ value={videoModel || ''}
+ onChange={(event) => setVideoModel(event.target.value || null)}
+ className="text-[11px] bg-port-bg border border-port-border rounded px-1.5 py-1 text-port-text"
+ >
+ <option value="">Saved video model</option>
+ {modelOptions(videoModels).map((modelOption) => (
+ <option key={modelOption.id} value={modelOption.id}>{modelOption.label}</option>
+ ))}
+ </select>
+ )}
+ </div>
+ )}
<div className="flex items-center gap-2">
<label htmlFor="fableloom-render-effort" className="text-[11px] text-port-text-muted w-14">Effort</label>
<select
@@ -364,11 +440,13 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
</div>
)}
- {plan.plannedAssets?.length > 0 && (
+ {scopedAssets.length > 0 && (
<div className="rounded bg-port-card border border-port-border p-2.5 space-y-2">
- <div className="text-[10px] uppercase font-semibold text-port-text-muted">Asset execution order</div>
+ <div className="text-[10px] uppercase font-semibold text-port-text-muted">
+ {assetScope === 'images' ? 'Storyboard image execution order' : 'Asset execution order'}
+ </div>
<div className="max-h-52 overflow-y-auto space-y-1">
- {plan.plannedAssets.map((asset) => (
+ {scopedAssets.map((asset) => (
<div key={asset.id} className="flex items-center gap-2 text-[11px] py-1 border-b border-port-border/50 last:border-0">
<span className={`w-1.5 h-1.5 rounded-full shrink-0 ${asset.status === 'blocked' ? 'bg-port-error' : asset.status === 'already_rendered' || asset.status === 'skipped' ? 'bg-port-success' : 'bg-port-accent'}`} />
<button
@@ -403,11 +481,11 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
<button
type="button"
onClick={startBatch}
- disabled={startingBatch || plan.isFullyReady === false}
+ disabled={startingBatch || !canStart}
className="flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"
>
{startingBatch ? <Loader2 size={12} className="animate-spin" /> : <Play size={12} />}
- Start Batch Production
+ {assetScope === 'images' ? 'Generate Storyboard Images' : 'Start Batch Production'}
</button>
) : (
<button
diff --git a/client/src/components/fableloom/LoomProductionPanel.test.jsx b/client/src/components/fableloom/LoomProductionPanel.test.jsx
index 33d40e9e4b..fc8b874461 100644
--- a/client/src/components/fableloom/LoomProductionPanel.test.jsx
+++ b/client/src/components/fableloom/LoomProductionPanel.test.jsx
@@ -22,6 +22,10 @@ describe('LoomProductionPanel', () => {
plannedAssets: [
{ id: 'asset-1', nodeId: 'node-1', type: 'image', status: 'ready' },
{ id: 'asset-2', nodeId: 'node-1', type: 'video_entry', status: 'ready' },
+ { id: 'asset-3', nodeId: 'node-2', type: 'image', status: 'already_rendered' },
+ { id: 'asset-4', nodeId: 'node-2', type: 'video_entry', status: 'ready' },
+ { id: 'asset-5', nodeId: 'node-3', type: 'image', status: 'ready' },
+ { id: 'asset-6', nodeId: 'node-3', type: 'video_entry', status: 'ready' },
],
convergenceIssues: [],
exactInputIssues: [],
@@ -60,8 +64,8 @@ describe('LoomProductionPanel', () => {
expect(screen.getByText('Episodic Production Plan')).toBeInTheDocument();
});
- expect(screen.getByText('6')).toBeInTheDocument(); // total assets
- expect(screen.getByText('Start Batch Production')).toBeInTheDocument();
+ expect(screen.getByText('3')).toBeInTheDocument(); // storyboard images only by default
+ expect(screen.getByText('Generate Storyboard Images')).toBeInTheDocument();
const modeSelect = screen.getByLabelText('Mode:');
fireEvent.change(modeSelect, { target: { value: 'exact_inputs' } });
@@ -75,17 +79,55 @@ describe('LoomProductionPanel', () => {
render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={vi.fn()} />);
await waitFor(() => {
- expect(screen.getByText('Start Batch Production')).toBeInTheDocument();
+ expect(screen.getByText('Generate Storyboard Images')).toBeInTheDocument();
});
- fireEvent.click(screen.getByText('Start Batch Production'));
+ fireEvent.click(screen.getByText('Generate Storyboard Images'));
await waitFor(() => {
- expect(api.startLoomEpisodeProductionBatch).toHaveBeenCalledWith('loom-1', 'ep-1', { mode: 'current_canon' }, { silent: true });
+ expect(api.startLoomEpisodeProductionBatch).toHaveBeenCalledWith(
+ 'loom-1', 'ep-1', { mode: 'current_canon', assetTypes: ['image'] }, { silent: true },
+ );
expect(screen.getByText('Cancel Production Batch')).toBeInTheDocument();
});
});
+ it('blocks batch media until the ordered beat arc is ready', async () => {
+ render(
+ <LoomProductionPanel
+ loom={{ ...sampleLoom, episodes: [{ id: 'ep-1', number: 1 }] }}
+ episode={{ ...sampleEpisode, nodes: [{ id: 'node-1' }] }}
+ onSelectNode={vi.fn()}
+ />,
+ );
+
+ const generate = await screen.findByText('Generate Storyboard Images');
+ expect(generate).toBeDisabled();
+ expect(screen.getByText(/ordered beat arc/i)).toBeInTheDocument();
+ expect(api.startLoomEpisodeProductionBatch).not.toHaveBeenCalled();
+ });
+
+ it('shows and enforces the ordered storyboard sequence gate', async () => {
+ api.planLoomEpisodeProduction.mockResolvedValueOnce({
+ ...samplePlan,
+ episodeOrderReadiness: {
+ ready: false,
+ reason: 'Finish storyboard images for Episode 1 before generating Episode 2.',
+ missingScenes: [{ episodeId: 'ep-1', nodeId: 'node-1' }],
+ },
+ planningIssues: ['Episode order: Finish storyboard images for Episode 1 before generating Episode 2.'],
+ });
+
+ render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={vi.fn()} />);
+
+ const generate = await screen.findByText('Generate Storyboard Images');
+ expect(generate).toBeDisabled();
+ expect(screen.getByText('Ordered storyboard sequence')).toBeInTheDocument();
+ expect(screen.getByText(/1 prior scene image\(s\) still need to be rendered/i)).toBeInTheDocument();
+ expect(screen.getAllByText(/Finish storyboard images for Episode 1 before generating Episode 2/i)).toHaveLength(2);
+ expect(api.startLoomEpisodeProductionBatch).not.toHaveBeenCalled();
+ });
+
it('runs continuity review and displays findings with node selection', async () => {
const onSelectNode = vi.fn();
render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={onSelectNode} />);
diff --git a/client/src/components/fableloom/LoomSeriesPlan.jsx b/client/src/components/fableloom/LoomSeriesPlan.jsx
index 6ad56c7e75..2da543d11c 100644
--- a/client/src/components/fableloom/LoomSeriesPlan.jsx
+++ b/client/src/components/fableloom/LoomSeriesPlan.jsx
@@ -5,7 +5,8 @@
*/
import { useEffect, useRef, useState } from 'react';
-import { BrainCircuit, ChevronDown, ChevronUp, Loader2, Plus, Save, Sparkles, Trash2 } from 'lucide-react';
+import { Link } from 'react-router';
+import { BrainCircuit, CheckCircle2, ChevronDown, ChevronUp, Loader2, Plus, Save, Sparkles, Trash2 } from 'lucide-react';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import toast from '../ui/Toast';
import { FormField } from '../ui/FormField.jsx';
@@ -17,7 +18,8 @@ import useFableLoomAiRun from '../../hooks/useFableLoomAiRun';
import useProviderModels from '../../hooks/useProviderModels';
import useUnsavedChangesGuard from '../../hooks/useUnsavedChangesGuard';
import {
- feedbackLoomSeriesPlan, generateLoomSeriesPlan, reviewLoomSeriesPlan, updateLoom,
+ feedbackLoomSeriesPlan, generateLoomSeriesPlan, reviewLoomSeriesPlan, reviewLoomTeleplay,
+ updateLoom, validateLoomSeriesOutlines,
} from '../../services/api';
import { uuidv4 } from '../../lib/uuid.js';
import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providers';
@@ -26,12 +28,39 @@ import LoomAiRunStatus from './LoomAiRunStatus';
const newItemId = (prefix) => `${prefix}-${uuidv4()}`;
+const normalizeDeliveryOptions = (options) => ({
+ overnightVoicemails: options?.overnightVoicemails === true,
+ nextSeasonTeaser: options?.nextSeasonTeaser === true,
+});
+
const normalizePlan = (plan) => ({
storyArc: plan?.storyArc || '',
plotPoints: Array.isArray(plan?.plotPoints) ? plan.plotPoints : [],
sideQuests: Array.isArray(plan?.sideQuests) ? plan.sideQuests : [],
+ deliveryOptions: normalizeDeliveryOptions(plan?.deliveryOptions),
+ interEpisodeVoicemails: Array.isArray(plan?.interEpisodeVoicemails)
+ ? plan.interEpisodeVoicemails : [],
+ nextSeasonTeaser: plan?.nextSeasonTeaser || null,
});
+const episodeBoundaryKey = (fromEpisodeId, toEpisodeId) => `${fromEpisodeId}::${toEpisodeId}`;
+
+const withVoicemailDrafts = (plan, episodes) => {
+ const current = new Map((plan.interEpisodeVoicemails || [])
+ .filter((item) => item?.fromEpisodeId && item?.toEpisodeId)
+ .map((item) => [episodeBoundaryKey(item.fromEpisodeId, item.toEpisodeId), item]));
+ return episodes.slice(0, -1).map((fromEpisode, index) => {
+ const toEpisode = episodes[index + 1];
+ return current.get(episodeBoundaryKey(fromEpisode.id, toEpisode.id)) || {
+ id: newItemId('voicemail'),
+ fromEpisodeId: fromEpisode.id,
+ toEpisodeId: toEpisode.id,
+ title: `Overnight voicemail: Episode ${fromEpisode.number || index + 1} → ${toEpisode.number || index + 2}`,
+ transcript: '',
+ };
+ });
+};
+
export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
const [plan, setPlan] = useState(() => normalizePlan(loom.seriesPlan));
const [dirty, setDirty] = useState(false);
@@ -148,6 +177,8 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
</FormField>
</div>
+ <EpisodeBeatReadiness loom={loom} />
+
<PlanCollection
title="Plot points"
description="Order the tentpole beats and connect each one to the episode where it should land."
@@ -174,6 +205,12 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
onRemove={(id) => removeItem('sideQuests', id)}
onMove={(index, direction) => moveItem('sideQuests', index, direction)}
/>
+
+ <SeriesDeliveryPlan
+ plan={plan}
+ episodes={loom.episodes}
+ onChange={changePlan}
+ />
</div>
<aside className="w-full lg:w-[380px] xl:w-[420px] shrink-0 space-y-6 lg:sticky lg:top-0 lg:max-h-[calc(100vh-3rem)] lg:overflow-y-auto" aria-label="AI tools and actions">
@@ -206,12 +243,108 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
);
}
+function EpisodeBeatReadiness({ loom }) {
+ const episodes = loom.episodes || [];
+ const readyCount = episodes.filter((episode) => episode.storyOutline?.validation?.status === 'valid').length;
+ const [validation, setValidation] = useState(null);
+
+ useEffect(() => {
+ setValidation(null);
+ }, [loom.id, loom.updatedAt]);
+
+ const [validateArc, validating] = useAsyncAction(async () => {
+ const result = await validateLoomSeriesOutlines(loom.id, { silent: true });
+ setValidation(result);
+ }, { errorMessage: 'Full beat-arc validation failed' });
+
+ const validationIssues = validation?.issues || [];
+ const validationReady = validation?.stats?.ready === true;
+ return (
+ <section className="rounded-lg border border-port-accent/30 bg-port-accent/5 p-4 space-y-3" aria-label="Episode beat outlines">
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <h3 className="font-semibold">Episode beat outlines</h3>
+ <p className="mt-1 text-xs text-port-text-muted">
+ Draft the full series as scene log-lines first. Open episodes in order, review each arc, and validate every outline before expanding any teleplay.
+ </p>
+ </div>
+ <span className={`shrink-0 text-xs ${readyCount === episodes.length && episodes.length ? 'text-port-success' : 'text-port-warning'}`}>
+ {readyCount}/{episodes.length} ready
+ </span>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={validateArc}
+ disabled={validating || !episodes.length}
+ className="flex items-center gap-1.5 rounded border border-port-accent px-3 py-2 text-xs text-port-accent hover:bg-port-accent/10 disabled:opacity-50"
+ >
+ {validating ? <Loader2 size={13} className="animate-spin" /> : <CheckCircle2 size={13} />}
+ {validating ? 'Validating full beat arc…' : 'Validate full beat arc'}
+ </button>
+ {validation ? (
+ <span className={`text-xs ${validationReady ? 'text-port-success' : 'text-port-error'}`} role="status">
+ {validationReady ? 'Series beat arc is structurally ready' : `${validation.stats?.errorCount || validationIssues.length} blocking issue${(validation.stats?.errorCount || validationIssues.length) === 1 ? '' : 's'}`}
+ </span>
+ ) : null}
+ </div>
+ {episodes.length ? (
+ <ol className="space-y-1.5">
+ {episodes.map((episode) => {
+ const status = episode.storyOutline?.validation?.status || 'missing';
+ const statusClass = status === 'valid' ? 'text-port-success' : 'text-port-warning';
+ return (
+ <li key={episode.id} className="flex items-center justify-between gap-3 text-sm">
+ <Link to={`/fableloom/${encodeURIComponent(loom.id)}/${encodeURIComponent(episode.id)}`} className="min-w-0 truncate text-port-accent hover:underline">
+ Episode {episode.number}: {episode.title || 'Untitled'}
+ </Link>
+ <span className={`shrink-0 text-xs ${statusClass}`}>{status}</span>
+ </li>
+ );
+ })}
+ </ol>
+ ) : (
+ <p className="text-xs text-port-warning">Add episodes before drafting the beat arc.</p>
+ )}
+ {validation && validationIssues.length ? (
+ <div className="space-y-1.5 rounded border border-port-error/30 bg-port-error/5 p-3" aria-label="Full beat arc validation results">
+ <p className="text-xs font-semibold text-port-error">Resolve these before expanding any teleplay:</p>
+ <ul className="space-y-1 text-xs text-port-text-muted">
+ {validationIssues.slice(0, 12).map((issue, index) => {
+ const episode = episodes.find((candidate) => candidate.id === issue.episodeId);
+ return (
+ <li key={`${issue.code || 'issue'}-${issue.episodeId || 'series'}-${index}`}>
+ {episode ? (
+ <Link className="text-port-accent hover:underline" to={`/fableloom/${encodeURIComponent(loom.id)}/${encodeURIComponent(episode.id)}`}>
+ Episode {episode.number}
+ </Link>
+ ) : <span>Series</span>}
+ {': '}{issue.message}
+ </li>
+ );
+ })}
+ </ul>
+ {validationIssues.length > 12 ? <p className="text-[11px] text-port-text-muted">Showing the first 12 issues.</p> : null}
+ </div>
+ ) : validation ? (
+ <p className="text-xs text-port-success" role="status">Every episode outline and configured delivery handoff passes deterministic checks.</p>
+ ) : null}
+ {readyCount === episodes.length && episodes.length ? (
+ <p className="text-xs text-port-success">The complete episode beat arc is ready for ordered teleplay expansion.</p>
+ ) : (
+ <p className="text-xs text-port-text-muted">The expansion gate also checks any configured overnight voicemail and finale teaser handoffs.</p>
+ )}
+ </section>
+ );
+}
+
function SeriesAiEditor({ loom, dirty, onLoomUpdate }) {
const [feedback, setFeedback] = useState('');
const [analysis, setAnalysis] = useState(null);
const [route, setRoute] = useState({ providerId: '', model: '', effort: '' });
const regenerateConfirm = useConfirmDelete();
const reviewRun = useFableLoomAiRun();
+ const teleplayReviewRun = useFableLoomAiRun();
const generateRun = useFableLoomAiRun();
const feedbackRun = useFableLoomAiRun();
const { providers, loading } = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
@@ -249,7 +382,16 @@ function SeriesAiEditor({ loom, dirty, onLoomUpdate }) {
toast.success(result.changes?.[0] || 'Series plan updated');
}, { errorMessage: 'Series-plan feedback failed' });
- const busy = generating || reviewing || applying;
+ const [reviewTeleplay, reviewingTeleplay] = useAsyncAction(async () => {
+ const operationId = teleplayReviewRun.begin();
+ const result = await reviewLoomTeleplay(loom.id, { ...routeBody, operationId }, { silent: true })
+ .catch((error) => { teleplayReviewRun.fail(error.message); throw error; });
+ setTeleplayAnalysis(result.analysis);
+ }, { errorMessage: 'Full teleplay review failed' });
+
+ const [teleplayAnalysis, setTeleplayAnalysis] = useState(null);
+ const fullTeleplayReady = loom.episodes.length > 0 && loom.episodes.every((episode) => episode.nodes?.length > 0);
+ const busy = generating || reviewing || applying || reviewingTeleplay;
const hasPlan = !!loom.seriesPlan?.storyArc?.trim()
|| !!loom.seriesPlan?.plotPoints?.length
|| !!loom.seriesPlan?.sideQuests?.length;
@@ -326,8 +468,19 @@ function SeriesAiEditor({ loom, dirty, onLoomUpdate }) {
{reviewing ? <Loader2 size={14} className="animate-spin" /> : <BrainCircuit size={14} />}
{reviewing ? 'Analyzing…' : 'Analyze series'}
</button>
+ <button
+ type="button"
+ onClick={reviewTeleplay}
+ disabled={busy || dirty || !fullTeleplayReady}
+ className="flex items-center gap-2 px-3 py-2 rounded border border-port-border text-sm hover:border-port-accent disabled:opacity-50"
+ >
+ {reviewingTeleplay ? <Loader2 size={14} className="animate-spin" /> : <BrainCircuit size={14} />}
+ {reviewingTeleplay ? 'Reviewing teleplay…' : 'Review full teleplay'}
+ </button>
</div>
<LoomAiRunStatus run={reviewRun.run} />
+ <LoomAiRunStatus run={teleplayReviewRun.run} />
+ {!fullTeleplayReady ? <p className="text-xs text-port-text-muted">Expand every episode before reviewing the complete teleplay series.</p> : null}
<FormField
label="Edit outline & plot points"
hint="Ask the AI to refine or restructure plot points, story beats, or side quests across the entire series."
@@ -354,11 +507,12 @@ function SeriesAiEditor({ loom, dirty, onLoomUpdate }) {
<LoomAiRunStatus run={feedbackRun.run} />
{dirty ? <p className="text-xs text-port-warning">Save the plan before running AI so it reads the edits on screen.</p> : null}
{analysis ? <SeriesAnalysis analysis={analysis} /> : null}
+ {teleplayAnalysis ? <SeriesAnalysis title="Full teleplay review" analysis={teleplayAnalysis} /> : null}
</div>
);
}
-function SeriesAnalysis({ analysis }) {
+function SeriesAnalysis({ analysis, title = 'Series analysis' }) {
const groups = [
['Strengths', analysis.strengths],
['Story risks', analysis.risks],
@@ -366,7 +520,7 @@ function SeriesAnalysis({ analysis }) {
];
return (
<div className="rounded border border-port-accent/30 bg-port-bg p-3 space-y-3" aria-live="polite">
- <h4 className="text-sm font-semibold">Series analysis</h4>
+ <h4 className="text-sm font-semibold">{title}</h4>
{analysis.summary ? <p className="text-sm text-port-text-muted">{analysis.summary}</p> : null}
{groups.map(([label, items]) => items?.length ? (
<div key={label}>
@@ -380,6 +534,159 @@ function SeriesAnalysis({ analysis }) {
);
}
+function SeriesDeliveryPlan({ plan, episodes, onChange }) {
+ const options = normalizeDeliveryOptions(plan.deliveryOptions);
+ const boundaries = episodes.slice(0, -1).map((fromEpisode, index) => ({
+ fromEpisode,
+ toEpisode: episodes[index + 1],
+ }));
+ const voicemails = plan.interEpisodeVoicemails || [];
+ const voicemailFor = (fromEpisodeId, toEpisodeId) => voicemails.find((item) => (
+ item.fromEpisodeId === fromEpisodeId && item.toEpisodeId === toEpisodeId
+ )) || null;
+ const missingVoicemails = boundaries.filter(({ fromEpisode, toEpisode }) => {
+ const item = voicemailFor(fromEpisode.id, toEpisode.id);
+ return !item?.transcript?.trim();
+ }).length;
+
+ const toggle = (key, enabled) => onChange((current) => {
+ const next = {
+ ...current,
+ deliveryOptions: { ...normalizeDeliveryOptions(current.deliveryOptions), [key]: enabled },
+ };
+ if (key === 'overnightVoicemails' && enabled) {
+ next.interEpisodeVoicemails = withVoicemailDrafts(current, episodes);
+ }
+ if (key === 'nextSeasonTeaser' && enabled && !next.nextSeasonTeaser) {
+ next.nextSeasonTeaser = { title: 'A signal beyond the corridor', transcript: '' };
+ }
+ return next;
+ });
+
+ const updateVoicemail = (fromEpisodeId, toEpisodeId, patch) => onChange((current) => ({
+ ...current,
+ interEpisodeVoicemails: (current.interEpisodeVoicemails || []).map((item) => (
+ item.fromEpisodeId === fromEpisodeId && item.toEpisodeId === toEpisodeId
+ ? { ...item, ...patch } : item
+ )),
+ }));
+
+ return (
+ <section className="rounded-lg border border-port-border bg-port-card p-4 space-y-4" aria-label="Series delivery">
+ <div>
+ <h3 className="font-semibold">Viewer handoffs</h3>
+ <p className="text-xs text-port-text-muted mt-1">
+ Optional authored beats that carry the viewer from one episode to the next and leave the season looking forward.
+ </p>
+ </div>
+
+ <label className="flex items-start gap-2 text-sm" htmlFor="series-delivery-overnight-voicemails">
+ <input
+ id="series-delivery-overnight-voicemails"
+ type="checkbox"
+ checked={options.overnightVoicemails}
+ onChange={(event) => toggle('overnightVoicemails', event.target.checked)}
+ className="mt-0.5"
+ />
+ <span>
+ <span className="font-medium block">Overnight voicemail between episodes</span>
+ <span className="text-xs text-port-text-muted">The protagonist leaves a personal handoff after each episode to motivate the next watch.</span>
+ </span>
+ </label>
+
+ {options.overnightVoicemails && (
+ <div className="space-y-3 pl-5 border-l-2 border-port-accent/30">
+ {!boundaries.length ? (
+ <p className="text-xs text-port-warning">Add a second episode to author the first overnight voicemail.</p>
+ ) : boundaries.map(({ fromEpisode, toEpisode }) => {
+ const item = voicemailFor(fromEpisode.id, toEpisode.id);
+ return (
+ <div key={episodeBoundaryKey(fromEpisode.id, toEpisode.id)} className="rounded border border-port-border p-3 space-y-3">
+ <div className="text-xs font-medium text-port-text-muted">
+ Episode {fromEpisode.number} → Episode {toEpisode.number}
+ </div>
+ <FormField label="Voicemail title" labelClassName={labelClass}>
+ <input
+ className={fieldClass}
+ value={item?.title || ''}
+ onChange={(event) => updateVoicemail(fromEpisode.id, toEpisode.id, { title: event.target.value })}
+ />
+ </FormField>
+ <FormField
+ label="Voicemail transcript"
+ hint="Write what the protagonist says overnight. Voice rendering can be attached later without losing this authored text."
+ labelClassName={labelClass}
+ >
+ <textarea
+ rows={4}
+ className={`${fieldClass} ${item?.transcript?.trim() ? '' : 'border-port-warning/60'}`}
+ value={item?.transcript || ''}
+ onChange={(event) => updateVoicemail(fromEpisode.id, toEpisode.id, { transcript: event.target.value })}
+ placeholder="I kept the receiver warm through the night…"
+ />
+ </FormField>
+ </div>
+ );
+ })}
+ <p className={`text-xs ${missingVoicemails ? 'text-port-warning' : 'text-port-success'}`} role="status">
+ {missingVoicemails
+ ? `${missingVoicemails} voicemail${missingVoicemails === 1 ? '' : 's'} still needs a transcript.`
+ : 'Every episode boundary has an authored voicemail.'}
+ </p>
+ </div>
+ )}
+
+ <label className="flex items-start gap-2 text-sm" htmlFor="series-delivery-next-season-teaser">
+ <input
+ id="series-delivery-next-season-teaser"
+ type="checkbox"
+ checked={options.nextSeasonTeaser}
+ onChange={(event) => toggle('nextSeasonTeaser', event.target.checked)}
+ className="mt-0.5"
+ />
+ <span>
+ <span className="font-medium block">Next-season teaser after the finale</span>
+ <span className="text-xs text-port-text-muted">Leave a final image-preview/player beat that opens the next season’s question.</span>
+ </span>
+ </label>
+
+ {options.nextSeasonTeaser && (
+ <div className="pl-5 border-l-2 border-port-accent/30 space-y-3">
+ <FormField label="Teaser title" labelClassName={labelClass}>
+ <input
+ className={fieldClass}
+ value={plan.nextSeasonTeaser?.title || ''}
+ onChange={(event) => onChange((current) => ({
+ ...current,
+ nextSeasonTeaser: { ...(current.nextSeasonTeaser || {}), title: event.target.value },
+ }))}
+ />
+ </FormField>
+ <FormField
+ label="Teaser / cliffhanger"
+ hint="This plays after the final episode ending in the one-device walkthrough."
+ labelClassName={labelClass}
+ >
+ <textarea
+ rows={4}
+ className={`${fieldClass} ${plan.nextSeasonTeaser?.transcript?.trim() ? '' : 'border-port-warning/60'}`}
+ value={plan.nextSeasonTeaser?.transcript || ''}
+ onChange={(event) => onChange((current) => ({
+ ...current,
+ nextSeasonTeaser: { ...(current.nextSeasonTeaser || {}), transcript: event.target.value },
+ }))}
+ placeholder="Beyond the frozen relay, something answers in the protagonist’s own voice…"
+ />
+ </FormField>
+ <p className={`text-xs ${plan.nextSeasonTeaser?.transcript?.trim() ? 'text-port-success' : 'text-port-warning'}`} role="status">
+ {plan.nextSeasonTeaser?.transcript?.trim() ? 'Next-season teaser authored.' : 'Teaser transcript still needs to be authored.'}
+ </p>
+ </div>
+ )}
+ </section>
+ );
+}
+
function PlanCollection({ title, description, items, episodes, sideQuests = false, onAdd, onUpdate, onRemove, onMove }) {
return (
<div className="rounded-lg border border-port-border bg-port-card p-4 space-y-4">
diff --git a/client/src/components/fableloom/LoomSeriesPlan.test.jsx b/client/src/components/fableloom/LoomSeriesPlan.test.jsx
index a8a7ce044f..12e242b946 100644
--- a/client/src/components/fableloom/LoomSeriesPlan.test.jsx
+++ b/client/src/components/fableloom/LoomSeriesPlan.test.jsx
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { createMemoryRouter, RouterProvider } from 'react-router';
import { useState } from 'react';
@@ -7,7 +8,9 @@ vi.mock('../../services/api', () => ({
feedbackLoomSeriesPlan: vi.fn(),
generateLoomSeriesPlan: vi.fn(),
reviewLoomSeriesPlan: vi.fn(),
+ reviewLoomTeleplay: vi.fn(),
updateLoom: vi.fn(),
+ validateLoomSeriesOutlines: vi.fn(),
}));
vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [], loading: false }) }));
vi.mock('../../services/socket', () => ({
@@ -178,4 +181,81 @@ describe('LoomSeriesPlan', () => {
expect(rightRail).toContainElement(screen.getByRole('button', { name: /analyze series/i }));
expect(rightRail).toContainElement(screen.getByRole('button', { name: /(draft|regenerate) full plan/i }));
});
+
+ it('reviews the complete expanded teleplay only when every episode has scenes', async () => {
+ api.reviewLoomTeleplay.mockResolvedValue({
+ analysis: {
+ summary: 'The full teleplay escalates cleanly.',
+ strengths: ['The handoff is earned.'],
+ risks: [],
+ recommendations: [],
+ },
+ });
+ const fullLoom = loom({
+ episodes: [
+ { id: 'ep-1', number: 1, title: 'Pilot', nodes: [{ id: 'node-1' }] },
+ { id: 'ep-2', number: 2, title: 'Finale', nodes: [{ id: 'node-2' }] },
+ ],
+ });
+ renderPlan({ loom: fullLoom, onLoomUpdate: () => {} });
+
+ expect(screen.getByRole('button', { name: 'Review full teleplay' })).toBeEnabled();
+ await userEvent.setup().click(screen.getByRole('button', { name: 'Review full teleplay' }));
+ expect(await screen.findByText('The full teleplay escalates cleanly.')).toBeInTheDocument();
+ expect(api.reviewLoomTeleplay).toHaveBeenCalledWith('loom-1', { operationId: expect.any(String) }, { silent: true });
+ });
+
+ it('validates the complete ordered beat arc and links blocking issues to episodes', async () => {
+ api.validateLoomSeriesOutlines.mockResolvedValue({
+ stats: { ready: false, errorCount: 1 },
+ issues: [{ code: 'MISSING_EPISODE_OUTLINE', episodeId: 'ep-1', message: 'Draft Episode 1 first.' }],
+ });
+ const user = userEvent.setup();
+ renderPlan({ loom: loom(), onLoomUpdate: () => {} });
+
+ await user.click(screen.getByRole('button', { name: 'Validate full beat arc' }));
+
+ expect(await screen.findByText(/Draft Episode 1 first\./)).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Episode 1' })).toHaveAttribute('href', '/fableloom/loom-1/ep-1');
+ expect(api.validateLoomSeriesOutlines).toHaveBeenCalledWith('loom-1', { silent: true });
+ });
+
+ it('authors configured overnight handoffs and a finale teaser in the series plan', async () => {
+ const user = userEvent.setup();
+ const threeEpisodeLoom = loom({
+ episodes: [
+ { id: 'ep-1', number: 1, title: 'Pilot' },
+ { id: 'ep-2', number: 2, title: 'The Turn' },
+ { id: 'ep-3', number: 3, title: 'Finale' },
+ ],
+ });
+ const onLoomUpdate = vi.fn();
+ renderPlan({ loom: threeEpisodeLoom, onLoomUpdate });
+
+ await user.click(screen.getByLabelText(/overnight voicemail between episodes/i));
+ expect(screen.getAllByRole('textbox', { name: 'Voicemail transcript' })).toHaveLength(2);
+ await user.type(screen.getAllByRole('textbox', { name: 'Voicemail transcript' })[0], 'Stay awake. The beacon is listening.');
+ await user.click(screen.getByLabelText(/next-season teaser after the finale/i));
+ await user.type(screen.getByRole('textbox', { name: 'Teaser / cliffhanger' }), 'Something answers from beyond the relay.');
+ await user.click(screen.getByRole('button', { name: /save plan/i }));
+
+ await waitFor(() => expect(api.updateLoom).toHaveBeenCalledWith(
+ 'loom-1',
+ expect.objectContaining({
+ seriesPlan: expect.objectContaining({
+ deliveryOptions: { overnightVoicemails: true, nextSeasonTeaser: true },
+ interEpisodeVoicemails: expect.arrayContaining([
+ expect.objectContaining({
+ fromEpisodeId: 'ep-1', toEpisodeId: 'ep-2',
+ transcript: 'Stay awake. The beacon is listening.',
+ }),
+ ]),
+ nextSeasonTeaser: expect.objectContaining({
+ transcript: 'Something answers from beyond the relay.',
+ }),
+ }),
+ }),
+ { silent: true },
+ ));
+ });
});
diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsx
index 89add9ee3c..e8e68fd0e1 100644
--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx
+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx
@@ -17,7 +17,8 @@
*/
import { useEffect, useRef, useState } from 'react';
-import { Loader2, Sparkles } from 'lucide-react';
+import { CheckCircle2, Loader2, Sparkles } from 'lucide-react';
+import { Link } from 'react-router';
import Drawer from '../Drawer';
import ProviderModelSelector from '../ProviderModelSelector';
import { FormField } from '../ui/FormField.jsx';
@@ -42,7 +43,7 @@ const rewriteProgressLabel = ({ index, total, title, scenesLeft }) => [
scenesLeft ? ` ${scenesLeft} scene${scenesLeft === 1 ? '' : 's'} left in it.` : '',
].join('');
-export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate, onRewritten }) {
+export default function LoomSettingsDrawer({ open, onClose, loom, universe, onLoomUpdate, onRewritten }) {
const { providers } = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
// Which episode the rewrite is on. The walk is one request per episode, so
@@ -53,11 +54,17 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,
const format = loom.format || 'prose';
const [participationMode, setParticipationMode] = useState(loom.participationMode || 'protagonist');
const [communicationMedium, setCommunicationMedium] = useState(loom.audienceCommunicationMedium || '');
+ const [protagonistCharacterId, setProtagonistCharacterId] = useState(loom.protagonistCharacterId || '');
+ const [protagonistWardrobeId, setProtagonistWardrobeId] = useState(loom.protagonistWardrobeId || '');
+ const [protagonistWardrobeLocked, setProtagonistWardrobeLocked] = useState(loom.protagonistWardrobeLocked === true);
useEffect(() => {
if (open) return;
setParticipationMode(loom.participationMode || 'protagonist');
setCommunicationMedium(loom.audienceCommunicationMedium || '');
- }, [open, loom.participationMode, loom.audienceCommunicationMedium]);
+ setProtagonistCharacterId(loom.protagonistCharacterId || '');
+ setProtagonistWardrobeId(loom.protagonistWardrobeId || '');
+ setProtagonistWardrobeLocked(loom.protagonistWardrobeLocked === true);
+ }, [open, loom.participationMode, loom.audienceCommunicationMedium, loom.protagonistCharacterId, loom.protagonistWardrobeId, loom.protagonistWardrobeLocked]);
const play = loom.playSettings || {};
const playProvider = providers.find((p) => p.id === play.providerId);
// Only scenes not already in the target format are sent, so this is what the
@@ -74,6 +81,49 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,
{ errorMessage: 'Save failed' },
);
+ const universeCharacters = Array.isArray(universe?.characters) ? universe.characters : [];
+ const protagonist = universeCharacters.find((character) => character.id === protagonistCharacterId) || null;
+ const protagonistWardrobes = Array.isArray(protagonist?.wardrobes) ? protagonist.wardrobes : [];
+ const protagonistSheets = [
+ protagonist?.referenceSheetImageRef,
+ ...Object.values(protagonist?.referenceSheets || {}),
+ ].filter(Boolean);
+ const approvedIdentityRoles = new Set(
+ (Array.isArray(protagonist?.identityPack?.assets) ? protagonist.identityPack.assets : [])
+ .filter((asset) => asset?.approved === true)
+ .map((asset) => asset.role),
+ );
+ const missingIdentityRoles = ['neutral', 'profile', 'full-body'].filter((role) => !approvedIdentityRoles.has(role));
+ const linkedUniverseId = universe?.id || loom.universeId || null;
+
+ const saveProtagonist = (changes) => patch(changes);
+
+ const chooseProtagonist = (event) => {
+ const nextId = event.target.value;
+ const nextCharacter = universeCharacters.find((character) => character.id === nextId);
+ const nextWardrobe = protagonistWardrobeId && nextCharacter?.wardrobes?.some((wardrobe) => wardrobe.id === protagonistWardrobeId)
+ ? protagonistWardrobeId
+ : '';
+ setProtagonistCharacterId(nextId);
+ setProtagonistWardrobeId(nextWardrobe);
+ setProtagonistWardrobeLocked(Boolean(nextWardrobe));
+ saveProtagonist({
+ protagonistCharacterId: nextId || null,
+ protagonistWardrobeId: nextWardrobe || null,
+ protagonistWardrobeLocked: Boolean(nextWardrobe),
+ });
+ };
+
+ const chooseProtagonistWardrobe = (event) => {
+ const nextId = event.target.value;
+ setProtagonistWardrobeId(nextId);
+ setProtagonistWardrobeLocked(Boolean(nextId));
+ saveProtagonist({
+ protagonistWardrobeId: nextId || null,
+ protagonistWardrobeLocked: Boolean(nextId),
+ });
+ };
+
// The merge base is a ref, not the render-time props, because the picker can
// emit TWO changes in one tick: choosing a model whose provider tier has no
// effort ladder also clears the effort. Both callbacks would otherwise build
@@ -205,6 +255,100 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,
)}
</section>
+ <section className="border-t border-port-border pt-4 space-y-3">
+ <div>
+ <h4 className="text-sm font-semibold">Character continuity</h4>
+ <p className="mt-1 text-xs text-port-text-muted">
+ Set the one Universe character and wardrobe that anchor every on-screen protagonist beat. Scene editors can mark a beat off-screen when the audience is speaking with the protagonist on another device.
+ </p>
+ </div>
+ {!universe ? (
+ <div className="rounded border border-port-warning/40 bg-port-warning/5 p-3 text-xs text-port-warning">
+ Link a Universe before binding a canonical protagonist, character sheets, or wardrobe references.
+ {linkedUniverseId && (
+ <Link to={`/universes/${encodeURIComponent(linkedUniverseId)}?tab=cast`} className="ml-1 underline">
+ Open Universe Cast
+ </Link>
+ )}
+ </div>
+ ) : (
+ <>
+ <FormField label="Canonical protagonist" labelClassName={labelClass}>
+ <select
+ className={fieldClass}
+ aria-label="Canonical protagonist"
+ value={protagonistCharacterId}
+ disabled={saving || reformatting}
+ onChange={chooseProtagonist}
+ >
+ <option value="">Choose a Universe character</option>
+ {protagonistCharacterId && !protagonist && (
+ <option value={protagonistCharacterId}>Missing Universe character ({protagonistCharacterId})</option>
+ )}
+ {universeCharacters.map((character) => (
+ <option key={character.id} value={character.id}>{character.name || character.id}</option>
+ ))}
+ </select>
+ </FormField>
+ <FormField label="Canonical wardrobe" labelClassName={labelClass}>
+ <select
+ className={fieldClass}
+ aria-label="Canonical protagonist wardrobe"
+ value={protagonistWardrobeId}
+ disabled={!protagonist || saving || reformatting}
+ onChange={chooseProtagonistWardrobe}
+ >
+ <option value="">Choose a wardrobe reference</option>
+ {protagonistWardrobeId && !protagonistWardrobes.some((wardrobe) => wardrobe.id === protagonistWardrobeId) && (
+ <option value={protagonistWardrobeId}>Missing wardrobe ({protagonistWardrobeId})</option>
+ )}
+ {protagonistWardrobes.map((wardrobe) => (
+ <option key={wardrobe.id} value={wardrobe.id}>{wardrobe.name || wardrobe.label || 'Wardrobe'}</option>
+ ))}
+ </select>
+ </FormField>
+ <label className="flex items-start gap-2 text-xs" htmlFor="loom-protagonist-wardrobe-locked">
+ <input
+ id="loom-protagonist-wardrobe-locked"
+ type="checkbox"
+ checked={protagonistWardrobeLocked}
+ disabled={!protagonistWardrobeId || saving || reformatting}
+ onChange={(event) => {
+ const locked = event.target.checked;
+ setProtagonistWardrobeLocked(locked);
+ saveProtagonist({ protagonistWardrobeLocked: locked });
+ }}
+ />
+ <span>
+ Lock this wardrobe across on-screen scenes
+ <span className="mt-0.5 block text-[11px] text-port-text-muted">When locked, stale scene wardrobe choices are replaced by this canonical reference at render time.</span>
+ </span>
+ </label>
+ {protagonist && (
+ <div className="rounded border border-port-border/70 bg-port-bg/40 p-2.5 text-xs" role="status">
+ <div className="flex items-center gap-1.5 font-medium">
+ {protagonistSheets.length > 0 ? <CheckCircle2 size={13} className="text-port-success" /> : null}
+ {protagonist.name || protagonist.id}
+ </div>
+ <div className="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-[11px]">
+ <span className={protagonistSheets.length ? 'text-port-success' : 'text-port-warning'}>
+ {protagonistSheets.length ? `${protagonistSheets.length} character sheet${protagonistSheets.length === 1 ? '' : 's'}` : 'Needs character sheet'}
+ </span>
+ <span className={missingIdentityRoles.length ? 'text-port-warning' : 'text-port-success'}>
+ {missingIdentityRoles.length ? `Identity pack missing ${missingIdentityRoles.join(', ')}` : 'Identity pack ready'}
+ </span>
+ </div>
+ {linkedUniverseId && (
+ <Link to={`/universes/${encodeURIComponent(linkedUniverseId)}?tab=cast`} className="mt-1 inline-block text-[11px] text-port-accent hover:underline">
+ Open character sheets and wardrobe references
+ </Link>
+ )}
+ </div>
+ )}
+ </>
+ )}
+ </section>
+
<section className="border-t border-port-border pt-4 space-y-2">
<FormField label="Scene format" labelClassName={labelClass}>
<select
diff --git a/client/src/components/fableloom/LoomSettingsDrawer.test.jsx b/client/src/components/fableloom/LoomSettingsDrawer.test.jsx
index 0f09e1bdc7..ac66dff627 100644
--- a/client/src/components/fableloom/LoomSettingsDrawer.test.jsx
+++ b/client/src/components/fableloom/LoomSettingsDrawer.test.jsx
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
import userEvent from '@testing-library/user-event';
vi.mock('../../services/api', () => ({
@@ -35,14 +36,16 @@ const renderDrawer = (loom, props = {}) => {
const onLoomUpdate = vi.fn();
const onRewritten = vi.fn();
render(
- <LoomSettingsDrawer
- open
- onClose={() => {}}
- loom={loom}
- onLoomUpdate={onLoomUpdate}
- onRewritten={onRewritten}
- {...props}
- />,
+ <MemoryRouter>
+ <LoomSettingsDrawer
+ open
+ onClose={() => {}}
+ loom={loom}
+ onLoomUpdate={onLoomUpdate}
+ onRewritten={onRewritten}
+ {...props}
+ />
+ </MemoryRouter>,
);
return { onLoomUpdate, onRewritten };
};
@@ -200,3 +203,39 @@ describe('LoomSettingsDrawer audience participation', () => {
expect(screen.getByLabelText('Audience role')).toHaveValue('protagonist');
});
});
+
+describe('LoomSettingsDrawer character continuity', () => {
+ it('associates the canonical protagonist with a Universe wardrobe and locks it by default', async () => {
+ const user = userEvent.setup();
+ const loom = makeLoom([]);
+ updateLoom.mockResolvedValue({
+ ...loom,
+ protagonistCharacterId: 'char-1',
+ protagonistWardrobeId: 'coat',
+ protagonistWardrobeLocked: true,
+ });
+ renderDrawer(loom, {
+ universe: {
+ id: 'universe-1',
+ characters: [{
+ id: 'char-1',
+ name: 'Aria',
+ referenceSheetImageRef: 'aria-sheet.png',
+ wardrobes: [{ id: 'coat', name: 'Travel coat' }],
+ identityPack: { assets: [] },
+ }],
+ },
+ });
+
+ await user.selectOptions(screen.getByLabelText('Canonical protagonist'), 'char-1');
+ await user.selectOptions(screen.getByLabelText('Canonical protagonist wardrobe'), 'coat');
+
+ await waitFor(() => expect(updateLoom).toHaveBeenLastCalledWith('loom-1', {
+ protagonistWardrobeId: 'coat',
+ protagonistWardrobeLocked: true,
+ }, { silent: true }));
+ expect(screen.getByRole('status')).toHaveTextContent('1 character sheet');
+ expect(screen.getByRole('status')).toHaveTextContent('Identity pack missing neutral, profile, full-body');
+ expect(screen.getByRole('checkbox', { name: /Lock this wardrobe across on-screen scenes/ })).toBeChecked();
+ });
+});
diff --git a/client/src/components/fableloom/LoomValidationPanel.jsx b/client/src/components/fableloom/LoomValidationPanel.jsx
index 413b494192..6433cf50f6 100644
--- a/client/src/components/fableloom/LoomValidationPanel.jsx
+++ b/client/src/components/fableloom/LoomValidationPanel.jsx
@@ -1,8 +1,9 @@
/**
* FableLoom validation panel — the deterministic graph checks plus the
- * optional AI story review. Structural checks run instantly server-side (no
- * LLM); "Review with AI" layers the story-editor critique on top. Clicking a
- * scene-anchored finding selects that node on the canvas.
+ * optional episode-level AI story review. Structural checks run instantly
+ * server-side (no LLM); the series-level "Review full teleplay" action lives
+ * in the series plan. Clicking a scene-anchored finding selects that node on
+ * the canvas.
*/
import { useEffect, useMemo, useState } from 'react';
@@ -149,7 +150,7 @@ export default function LoomValidationPanel({ loom, episode, onSelectNode }) {
className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50"
>
{reviewing ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
- Review with AI
+ Review episode teleplay with AI
</button>
</div>
{review ? (
@@ -165,7 +166,7 @@ export default function LoomValidationPanel({ loom, episode, onSelectNode }) {
</div>
) : (
<p className="text-xs text-port-text-muted">
- Ask the AI story editor to critique intents, branches, and endings.
+ Ask the AI story editor to critique this episode's intents, branches, scene craft, and endings.
</p>
)}
</div>
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 52b4bee7b6..5cba37db25 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -47,6 +47,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |
| `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. |
| `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. `federatedMediaModelsForPeer(peer, kind)` intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their `ready` / `unavailableReason`), so no surface can offer a model the server would refuse or hide why a listed one cannot run. `federatedMediaSupports(status, feature, capability)` mirrors the server helper of the same name and is the ONE place the "absent reads as false" rule lives on this side (#4826): it answers whether the peer’s BUILD speaks a wire feature (`lyrics`, `inputAssets`) from the status-root `features` list, retaining only the legacy `inputAssets` capability block for peers on the previous build because that signal is genuinely per-model, and `peerMediaProviderSnapshot(peer)` returns the status payload to ask it against. `peerModelAcceptsInput(capability, role, status)` / `peerModelRequiresInput(capability)` read the capability’s `inputAssets` block — which conditioning slots (`initImage` / `referenceImages` / `sourceImage` / `lastImage`) a peer model takes, and whether it can render without one — gated first on the build speaking conditioning at all, with **absent reading as NO**, so a provider predating that field is never offered a render it would reject. Display only — the server re-probes and fail-closes before any job leaves. |
+| `fableLoomReadiness.js` | Ordered FableLoom story-first readiness: every episode outline validated, configured voicemail/teaser handoffs authored, then media generation is enabled. |
| `glbFailure.js` | Turns a 3D asset failure into an actionable sentence. `glbFailureHint(error)` matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns `null` when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. `glbErrorText(error)` reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by `media/GlbViewer.jsx` and `cos/CoSCanvasGuard.jsx`. |
| `grokVideoClip.js` | Mirror of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. |
| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |
@@ -211,4 +212,3 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeMarkdownFilename.js` | `slugifyUniverseName` / `universeMarkdownFilename` — client-side safe filename helpers for Universe Markdown world-bible downloads, kept in step with the server attachment name. |
| `universeMarkdownFilename.cases.js` | Shared client/server filename contract cases used to keep the browser download name and server attachment name in lockstep. |
| `qrCode.js` | Deterministic SVG QR code generator for scoped mobile session join links (#5383). |
-
diff --git a/client/src/lib/fableLoomReadiness.js b/client/src/lib/fableLoomReadiness.js
new file mode 100644
index 0000000000..56aba56371
--- /dev/null
+++ b/client/src/lib/fableLoomReadiness.js
@@ -0,0 +1,106 @@
+/**
+ * Client-side FableLoom story-first readiness checks.
+ *
+ * Media controls use this small mirror of the server's ordered beat-arc gate
+ * so a human sees the same sequence everywhere: outline every episode,
+ * validate the arc, author configured handoffs, then render storyboard stills.
+ * The server remains authoritative for expansion and batch preflight.
+ */
+
+const asArray = (value) => (Array.isArray(value) ? value : []);
+const hasText = (value) => typeof value === 'string' && value.trim().length > 0;
+
+const reachableNodes = (episode) => {
+ const nodes = asArray(episode?.nodes);
+ const byId = new Map(nodes.map((node) => [node.id, node]));
+ if (!byId.has(episode?.startNodeId)) return [];
+ const ordered = [];
+ const seen = new Set();
+ const queue = [episode.startNodeId];
+ for (let index = 0; index < queue.length; index += 1) {
+ const nodeId = queue[index];
+ if (seen.has(nodeId)) continue;
+ const node = byId.get(nodeId);
+ if (!node) continue;
+ seen.add(nodeId);
+ ordered.push(node);
+ asArray(node.transitions).forEach((transition) => {
+ if (byId.has(transition?.targetNodeId) && !seen.has(transition.targetNodeId)) {
+ queue.push(transition.targetNodeId);
+ }
+ });
+ }
+ return ordered;
+};
+
+export function fableLoomEpisodeOrderReadiness(loom, episode) {
+ const episodes = asArray(loom?.episodes);
+ const currentIndex = episodes.findIndex((candidate) => candidate?.id === episode?.id);
+ if (currentIndex < 0) {
+ return { ready: false, reason: 'The selected episode is not present in the ordered loom.' };
+ }
+ for (const [index, priorEpisode] of episodes.slice(0, currentIndex).entries()) {
+ const missing = reachableNodes(priorEpisode).filter((node) => !hasText(node.image));
+ if (missing.length) {
+ const priorNumber = priorEpisode.number || index + 1;
+ const currentNumber = episode.number || currentIndex + 1;
+ return {
+ ready: false,
+ reason: `Finish storyboard images for Episode ${priorNumber} before generating Episode ${currentNumber}.`,
+ blockedBy: { episodeId: priorEpisode.id, episodeNumber: priorNumber, missingScenes: missing.length },
+ };
+ }
+ }
+ return { ready: true, reason: '' };
+}
+
+export function fableLoomStoryReadiness(loom) {
+ const episodes = asArray(loom?.episodes);
+ if (!episodes.length) {
+ return { ready: false, reason: 'Add episodes and validate their ordered beat outlines before generating media.' };
+ }
+
+ const missingOutlines = episodes
+ .map((episode, index) => ({ episode, number: episode?.number || index + 1 }))
+ .filter(({ episode }) => episode?.storyOutline?.validation?.status !== 'valid');
+ if (missingOutlines.length) {
+ const labels = missingOutlines.slice(0, 3).map(({ number }) => `Episode ${number}`).join(', ');
+ const suffix = missingOutlines.length > 3 ? '…' : '';
+ return {
+ ready: false,
+ reason: `Validate the complete ordered beat arc before generating media (${labels}${suffix} still needs outline review).`,
+ };
+ }
+
+ const deliveryOptions = loom?.seriesPlan?.deliveryOptions || {};
+ if (deliveryOptions.overnightVoicemails === true) {
+ const voicemails = new Map(asArray(loom?.seriesPlan?.interEpisodeVoicemails)
+ .filter((item) => item?.fromEpisodeId && item?.toEpisodeId)
+ .map((item) => [`${item.fromEpisodeId}::${item.toEpisodeId}`, item]));
+ for (let index = 0; index < episodes.length - 1; index += 1) {
+ const from = episodes[index];
+ const to = episodes[index + 1];
+ const voicemail = voicemails.get(`${from.id}::${to.id}`);
+ if (!hasText(voicemail?.transcript)) {
+ return {
+ ready: false,
+ reason: `Author the overnight voicemail from Episode ${from.number || index + 1} to Episode ${to.number || index + 2} before generating media.`,
+ };
+ }
+ }
+ }
+
+ if (deliveryOptions.nextSeasonTeaser === true
+ && !hasText(loom?.seriesPlan?.nextSeasonTeaser?.transcript)) {
+ return { ready: false, reason: 'Author the finale next-season teaser before generating media.' };
+ }
+
+ return { ready: true, reason: '' };
+}
+
+export function fableLoomMediaReadiness(loom, episode) {
+ if (!episode?.nodes?.length) return { ready: true, reason: '' };
+ const story = fableLoomStoryReadiness(loom);
+ if (!story.ready) return story;
+ return fableLoomEpisodeOrderReadiness(loom, episode);
+}
diff --git a/client/src/lib/fableLoomReadiness.test.js b/client/src/lib/fableLoomReadiness.test.js
new file mode 100644
index 0000000000..595ade008b
--- /dev/null
+++ b/client/src/lib/fableLoomReadiness.test.js
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import {
+ fableLoomEpisodeOrderReadiness, fableLoomMediaReadiness, fableLoomStoryReadiness,
+} from './fableLoomReadiness.js';
+
+const outline = { validation: { status: 'valid' } };
+
+describe('FableLoom story-first readiness', () => {
+ it('blocks media until every episode outline is validated', () => {
+ const loom = {
+ episodes: [
+ { id: 'ep-1', number: 1, storyOutline: outline },
+ { id: 'ep-2', number: 2 },
+ ],
+ };
+
+ expect(fableLoomStoryReadiness(loom)).toMatchObject({
+ ready: false,
+ reason: expect.stringContaining('Episode 2'),
+ });
+ });
+
+ it('requires configured delivery handoffs before media generation', () => {
+ const loom = {
+ episodes: [
+ { id: 'ep-1', number: 1, storyOutline: outline },
+ { id: 'ep-2', number: 2, storyOutline: outline },
+ ],
+ seriesPlan: {
+ deliveryOptions: { overnightVoicemails: true, nextSeasonTeaser: true },
+ interEpisodeVoicemails: [{ fromEpisodeId: 'ep-1', toEpisodeId: 'ep-2', transcript: '' }],
+ nextSeasonTeaser: { title: 'Beyond', transcript: '' },
+ },
+ };
+
+ expect(fableLoomStoryReadiness(loom).reason).toContain('overnight voicemail');
+ });
+
+ it('does not block an empty episode because there is nothing to render yet', () => {
+ const loom = { episodes: [{ id: 'ep-1', number: 1 }] };
+ expect(fableLoomMediaReadiness(loom, { id: 'ep-1', nodes: [] })).toEqual({ ready: true, reason: '' });
+ });
+
+ it('blocks direct image generation for a later episode until prior reachable scenes have images', () => {
+ const loom = {
+ episodes: [
+ {
+ id: 'ep-1', number: 1, startNodeId: 'prior-start',
+ nodes: [{ id: 'prior-start', image: '', transitions: [] }],
+ },
+ {
+ id: 'ep-2', number: 2, startNodeId: 'later-start',
+ nodes: [{ id: 'later-start', transitions: [] }],
+ },
+ ],
+ };
+
+ expect(fableLoomEpisodeOrderReadiness(loom, loom.episodes[1])).toMatchObject({
+ ready: false,
+ reason: 'Finish storyboard images for Episode 1 before generating Episode 2.',
+ blockedBy: { missingScenes: 1 },
+ });
+ expect(fableLoomMediaReadiness(loom, loom.episodes[1]).ready).toBe(false);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index f7d68d9609..96ada92f8a 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -29,6 +29,7 @@ export * from './creativeDirectorPlan.js';
export * from './creativeDirectorPreview.js';
export * from './editorialRoadmap.js';
export * from './federatedMediaReadiness.js';
+export * from './fableLoomReadiness.js';
export * from './glbFailure.js';
export * from './grokVideoClip.js';
export * from './imageCleaners.js';
@@ -180,4 +181,3 @@ export * from './webglSupport.js';
export * from './wrSceneCursor.js';
export * from './writingGuide.js';
export * from './qrCode.js';
-
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index e5e5dd4bdc..be3ca07a79 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -13,7 +13,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, Navigate, useNavigate, useParams, useSearchParams } from 'react-router';
-import { ArrowLeft, BookOpenText, ListTree, Loader2, Plus, Settings, Sparkles, Trash2, Waypoints, Workflow as WorkflowIcon, X } from 'lucide-react';
+import { ArrowLeft, BookOpenText, 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';
@@ -26,6 +26,7 @@ import useFableLoomAiRun from '../hooks/useFableLoomAiRun';
import useContainerWidth from '../hooks/useContainerWidth';
import LoomCanvas from '../components/fableloom/LoomCanvas';
import LoomEpisodeOutline from '../components/fableloom/LoomEpisodeOutline';
+import LoomEpisodeOutlinePlanner from '../components/fableloom/LoomEpisodeOutlinePlanner';
import LoomEpisodeFeedback from '../components/fableloom/LoomEpisodeFeedback';
import LoomMediaJobWatchers from '../components/fableloom/LoomMediaJobWatchers';
import LoomNodeEditor from '../components/fableloom/LoomNodeEditor';
@@ -39,6 +40,7 @@ import {
buildFableLoomImageRequest, buildFableLoomVideoRequest,
} from '../components/fableloom/sceneMediaRequests';
import { universeStylePreset } from '../lib/universeStylePreset';
+import { fableLoomMediaReadiness } from '../lib/fableLoomReadiness';
import { LOOM_ORIENTATION, LOOM_STACK_WIDTH } from '../lib/loomLayout';
import {
addLoomEpisode, addLoomNode, deleteLoomEpisode, generateImage, generateVideo,
@@ -152,6 +154,14 @@ export default function FableLoomStory({ view = 'graph' }) {
const episode = seriesPlanOpen ? null : loom?.episodes.find((e) => e.id === episodeId) || null;
const node = episode?.nodes.find((n) => n.id === nodeId) || null;
+ const mediaReadiness = useMemo(
+ () => fableLoomMediaReadiness(loom, episode),
+ [loom, episode],
+ );
+ const mediaWorkflowBlocked = Boolean(episode?.nodes?.length && !mediaReadiness.ready);
+ const mediaGenerationDisabledReason = mediaWorkflowBlocked
+ ? mediaReadiness.reason
+ : generationDisabledReason;
const setSceneMediaJob = useCallback((targetNodeId, kind, nextJob) => {
setMediaJobs((prev) => {
@@ -222,6 +232,10 @@ export default function FableLoomStory({ view = 'graph' }) {
toast.error('Write an image prompt first');
return null;
}
+ if (mediaWorkflowBlocked) {
+ toast.error(mediaReadiness.reason);
+ return null;
+ }
if (styleContextLoading || styleContextUnavailable) {
toast.error(generationDisabledReason || 'Scene style is not ready');
return null;
@@ -271,7 +285,7 @@ export default function FableLoomStory({ view = 'graph' }) {
});
toast.success('Scene image queued');
return queued;
- }, [applySceneMedia, episode, episodeId, generationDisabledReason, loom, sceneStylePreset, setSceneMediaJob, styleContextLoading, styleContextUnavailable]);
+ }, [applySceneMedia, episode, episodeId, generationDisabledReason, loom, mediaReadiness.reason, mediaWorkflowBlocked, sceneStylePreset, setSceneMediaJob, styleContextLoading, styleContextUnavailable]);
const queueSceneVideo = useCallback(async (targetNode) => {
const prompt = (targetNode?.videoPrompt || '').trim() || (targetNode?.prose || '').trim();
@@ -279,6 +293,10 @@ export default function FableLoomStory({ view = 'graph' }) {
toast.error('Write the scene first');
return null;
}
+ if (mediaWorkflowBlocked) {
+ toast.error(mediaReadiness.reason);
+ return null;
+ }
if (styleContextLoading || styleContextUnavailable) {
toast.error(generationDisabledReason || 'Scene style is not ready');
return null;
@@ -307,7 +325,7 @@ export default function FableLoomStory({ view = 'graph' }) {
});
toast.success('Scene video queued');
return queued;
- }, [episodeId, generationDisabledReason, loom, sceneStylePreset, setSceneMediaJob, styleContextLoading, styleContextUnavailable]);
+ }, [episodeId, generationDisabledReason, loom, mediaReadiness.reason, mediaWorkflowBlocked, sceneStylePreset, setSceneMediaJob, styleContextLoading, styleContextUnavailable]);
const basePath = `/fableloom/${loomId}`;
const episodePath = useCallback(
@@ -443,10 +461,20 @@ export default function FableLoomStory({ view = 'graph' }) {
<button
type="button"
onClick={handleAddNode}
+ aria-label="Add scene"
className="flex items-center gap-1 px-2.5 py-1.5 rounded border border-port-border text-xs hover:border-port-accent"
>
<Plus size={13} /> Scene
</button>
+ <button
+ type="button"
+ onClick={() => setSetupOpen(true)}
+ aria-label="Edit episode"
+ title="Edit episode title and synopsis"
+ className="flex items-center gap-1 px-2.5 py-1.5 rounded border border-port-border text-xs hover:border-port-accent"
+ >
+ <PencilLine size={13} /> Edit episode
+ </button>
<button
type="button"
onClick={() => setSetupOpen(true)}
@@ -538,8 +566,8 @@ export default function FableLoomStory({ view = 'graph' }) {
mediaJobs={mediaJobs}
onGenerateImage={queueSceneImage}
onGenerateVideo={queueSceneVideo}
- generationDisabled={styleContextLoading || styleContextUnavailable}
- generationDisabledReason={generationDisabledReason}
+ generationDisabled={styleContextLoading || styleContextUnavailable || mediaWorkflowBlocked}
+ generationDisabledReason={mediaGenerationDisabledReason}
/>
) : (
<div className="h-full grid place-items-center p-8 text-center">
@@ -611,8 +639,8 @@ export default function FableLoomStory({ view = 'graph' }) {
mediaJobs={mediaJobs[node.id]}
onGenerateImage={queueSceneImage}
onGenerateVideo={queueSceneVideo}
- generationDisabled={styleContextLoading || styleContextUnavailable}
- generationDisabledReason={generationDisabledReason}
+ generationDisabled={styleContextLoading || styleContextUnavailable || mediaWorkflowBlocked}
+ generationDisabledReason={mediaGenerationDisabledReason}
onMakeStart={node.id !== episode.startNodeId ? async () => {
const updated = await updateLoomEpisode(loomId, episode.id, { startNodeId: node.id })
.catch(() => null);
@@ -650,6 +678,7 @@ export default function FableLoomStory({ view = 'graph' }) {
open={settingsOpen}
onClose={() => setSettingsOpen(false)}
loom={loom}
+ universe={linkedUniverse}
onLoomUpdate={setLoom}
onRewritten={handleRewritten}
/>
@@ -675,6 +704,7 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed
const [feedbackRunning, setFeedbackRunning] = useState(false);
const { run: aiRun, begin: beginAiRun, fail: failAiRun } = useFableLoomAiRun();
const del = useConfirmDelete();
+ const expansionConfirm = useConfirmDelete();
const hasScenes = episode.nodes.length > 0;
// Sync from the record on episode switch ONLY — re-syncing on every server
@@ -698,6 +728,7 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed
const result = await weaveLoomEpisode(loom.id, episode.id, {
guidance: form.guidance,
replace: hasScenes,
+ expandFromOutline: true,
operationId,
}, { silent: true }).catch((error) => {
failAiRun(error.message);
@@ -708,6 +739,14 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed
onClose();
}, { errorMessage: 'Weave failed' });
+ const requestWeave = () => {
+ if (hasScenes) {
+ expansionConfirm.requestDelete(episode.id);
+ return;
+ }
+ runWeave();
+ };
+
const handleDelete = async () => {
const updated = await deleteLoomEpisode(loom.id, episode.id).catch(() => null);
if (updated) {
@@ -740,7 +779,7 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed
<div className="border-t border-port-border pt-4 space-y-3">
<h4 className="text-sm font-semibold flex items-center gap-1.5">
- <Sparkles size={14} className="text-port-accent" /> Weave the scene graph
+ <Sparkles size={14} className="text-port-accent" /> Expand the episode
</h4>
<FormField label="Guidance (optional)" labelClassName={labelClass}>
<textarea
@@ -752,22 +791,34 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed
/>
</FormField>
<p className="text-xs text-port-text-muted">
- The story writer and creative director choose the number of camera-cut scenes and endings from the episode.
+ Start with the beat outline below, review the whole arc, then expand it into one-camera-cut teleplay scenes.
</p>
+ <LoomEpisodeOutlinePlanner
+ open={open}
+ loom={loom}
+ episode={episode}
+ guidance={form.guidance}
+ disabled={metaSaving > 0 || feedbackRunning || weaving}
+ onLoomUpdate={onLoomUpdate}
+ onExpand={requestWeave}
+ expanding={weaving}
+ />
+ {expansionConfirm.isConfirming(episode.id) && (
+ <ConfirmButtonPair
+ prompt={`Replace ${episode.nodes.length} existing scene${episode.nodes.length === 1 ? '' : 's'} and remove their rendered stills and video clips?`}
+ confirmText="Replace scenes"
+ tone="error"
+ ariaLabel="Confirm replacing episode scenes"
+ onConfirm={() => expansionConfirm.confirmDelete(runWeave)}
+ onCancel={expansionConfirm.cancelDelete}
+ largeTouchTargets
+ />
+ )}
{hasScenes && (
<p className="text-xs text-port-warning">
- Weaving replaces this episode's {episode.nodes.length} existing scene{episode.nodes.length === 1 ? '' : 's'} and drops their rendered stills and video clips.
+ Expansion replaces this episode's {episode.nodes.length} existing scene{episode.nodes.length === 1 ? '' : 's'} and drops their rendered stills and video clips.
</p>
)}
- <button
- type="button"
- onClick={runWeave}
- disabled={weaving || feedbackRunning || metaSaving > 0}
- className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-60"
- >
- {weaving ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
- {weaving ? 'Weaving…' : hasScenes ? 'Reweave episode' : 'Weave episode'}
- </button>
<LoomAiRunStatus run={aiRun} />
</div>
diff --git a/client/src/pages/FableLoomStory.test.jsx b/client/src/pages/FableLoomStory.test.jsx
index e8892da90c..fdb4eb1bb5 100644
--- a/client/src/pages/FableLoomStory.test.jsx
+++ b/client/src/pages/FableLoomStory.test.jsx
@@ -66,6 +66,12 @@ vi.mock('../components/fableloom/LoomMediaJobWatchers', () => ({
},
}));
vi.mock('../components/fableloom/LoomEpisodeOutline', () => ({ default: ({ episode }) => <div data-testid="episode-outline">{episode.title}</div> }));
+vi.mock('../components/fableloom/LoomEpisodeOutlinePlanner', () => ({
+ default: ({ onExpand }) => (
+ <button type="button" onClick={onExpand}>Expand validated outline to teleplay</button>
+ ),
+}));
+vi.mock('../components/fableloom/LoomEpisodeFeedback', () => ({ default: () => null }));
vi.mock('../components/fableloom/LoomNodeEditor', () => ({
default: ({ node }) => <div>Editing scene: {node.title}</div>,
}));
@@ -93,6 +99,7 @@ const episode = (fields = {}) => ({
title: 'The First Door',
synopsis: 'A choice waits in the dark.',
startNodeId: 'node-1',
+ storyOutline: { validation: { status: 'valid' } },
nodes: [
{ id: 'node-1', title: 'Threshold', prose: 'You stand before the first door.', transitions: [] },
],
@@ -197,6 +204,46 @@ describe('FableLoomStory episode outline route', () => {
});
});
+describe('FableLoomStory episode expansion safety', () => {
+ it('exposes an explicit episode editor for changing the title and synopsis', async () => {
+ const user = userEvent.setup();
+ api.getLoom.mockResolvedValue(loom({ episodes: [episode()] }));
+ renderEditor('/fableloom/loom-1/ep-1');
+
+ await user.click(await screen.findByRole('button', { name: 'Edit episode' }));
+
+ expect(screen.getByRole('heading', { name: 'Episode setup' })).toBeInTheDocument();
+ expect(screen.getByLabelText('Title')).toHaveValue('The First Door');
+ expect(screen.getByLabelText('Synopsis (feeds the weave)')).toHaveValue('A choice waits in the dark.');
+ });
+
+ it('confirms before replacing an existing episode scene graph', async () => {
+ const user = userEvent.setup();
+ const existingEpisode = episode({ nodes: [
+ { id: 'node-1', title: 'Existing scene', prose: 'Existing text.', transitions: [] },
+ { id: 'node-2', title: 'Existing ending', prose: 'Existing ending text.', transitions: [] },
+ ] });
+ api.getLoom.mockResolvedValue(loom({ episodes: [existingEpisode] }));
+ api.weaveLoomEpisode.mockResolvedValue({ loom: loom({ episodes: [existingEpisode] }) });
+ renderEditor('/fableloom/loom-1/ep-1');
+
+ await user.click(await screen.findByRole('button', { name: 'Weave' }));
+ await user.click(screen.getByRole('button', { name: 'Expand validated outline to teleplay' }));
+
+ expect(api.weaveLoomEpisode).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'Replace scenes' })).toBeInTheDocument();
+ expect(screen.getByText(/Replace 2 existing scenes and remove their rendered stills and video clips/)).toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: 'Replace scenes' }));
+ await waitFor(() => expect(api.weaveLoomEpisode).toHaveBeenCalledWith(
+ 'loom-1',
+ 'ep-1',
+ expect.objectContaining({ replace: true, expandFromOutline: true }),
+ { silent: true },
+ ));
+ });
+});
+
describe('FableLoomStory mobile scene details', () => {
it('opens the selected scene in a slide-up sheet and closes back to the graph', async () => {
const user = userEvent.setup();
@@ -218,6 +265,15 @@ describe('FableLoomStory mobile scene details', () => {
});
describe('FableLoomStory scene media lifecycle', () => {
+ it('keeps scene media disabled until the ordered beat arc is validated', async () => {
+ api.getLoom.mockResolvedValue(loom({
+ episodes: [episode({ storyOutline: null })],
+ }));
+ renderEditor();
+
+ expect(await screen.findByRole('button', { name: 'Canvas generate image' })).toBeDisabled();
+ });
+
it('queues with canonical universe style and notifies when the render later fails', async () => {
const user = userEvent.setup();
api.getLoom.mockResolvedValue(loom({
diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.js
index 86629bf379..d3a2753f8d 100644
--- a/client/src/services/apiFableLoom.js
+++ b/client/src/services/apiFableLoom.js
@@ -33,6 +33,9 @@ export const reviewLoomSeriesPlan = (id, body = {}, options = {}) => request(loo
export const feedbackLoomSeriesPlan = (id, body, options = {}) => request(loomPath(id, '/plan/feedback'), {
method: 'POST', body: JSON.stringify(body), ...options,
});
+export const reviewLoomTeleplay = (id, body = {}, options = {}) => request(loomPath(id, '/review-teleplay'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
export const addLoomEpisode = (id, body, options = {}) => request(loomPath(id, '/episodes'), {
method: 'POST', body: JSON.stringify(body), ...options,
@@ -45,6 +48,20 @@ export const deleteLoomEpisode = (id, episodeId, options = {}) => request(episod
});
export const validateLoomEpisode = (id, episodeId, options = {}) =>
request(episodePath(id, episodeId, '/validate'), options);
+export const generateLoomEpisodeOutline = (id, episodeId, body = {}, options = {}) =>
+ request(episodePath(id, episodeId, '/outline/generate'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
+export const validateLoomEpisodeOutline = (id, episodeId, options = {}) =>
+ request(episodePath(id, episodeId, '/outline/validate'), {
+ method: 'POST', body: JSON.stringify({}), ...options,
+ });
+export const reviewLoomEpisodeOutline = (id, episodeId, body = {}, options = {}) =>
+ request(episodePath(id, episodeId, '/outline/review'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
+export const validateLoomSeriesOutlines = (id, options = {}) =>
+ request(loomPath(id, '/outlines/validate'), options);
export const addLoomNode = (id, episodeId, body, options = {}) => request(episodePath(id, episodeId, '/nodes'), {
method: 'POST', body: JSON.stringify(body), ...options,
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index af471e9ba5..85e5f34fca 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -996,6 +996,13 @@
"returnsJson": true,
"variables": []
},
+ "fableloom-outline-episode": {
+ "name": "FableLoom — Draft Episode Beat Outline",
+ "description": "Plans one episode as concise log-line beats, transitions, audience-connection states, and distinct endings before any teleplay prose or scene media is generated.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
"fableloom-branch-node": {
"name": "FableLoom — Branch a Scene",
"description": "Turns one camera-cut node into an interactive decision and grows new intent paths from it. Each branch is a new single-shot node with playback, image, video, and camera-movement direction. Returns { branches[] }.",
@@ -1045,12 +1052,26 @@
"returnsJson": true,
"variables": []
},
+ "fableloom-review-episode-outline": {
+ "name": "FableLoom — Review Episode Beat Outline",
+ "description": "Story-editor review of one episode's pre-teleplay log-line arc, branch consequences, continuity, audience contract, endings, and handoff to adjacent episodes.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
"fableloom-review-series-plan": {
"name": "FableLoom — Review Series Plan",
"description": "Holistic story-editor analysis of the series arc, ordered plot points, side-quest lifecycle, and episode outline. Returns a summary, strengths, risks, and actionable recommendations without modifying the loom.",
"model": "heavy",
"returnsJson": true,
"variables": []
+ },
+ "fableloom-review-series-teleplay": {
+ "name": "FableLoom — Review Full Teleplay Series",
+ "description": "Reviews every expanded episode scene as one interactive teleplay series for continuity, escalation, choice clarity, endings, visual beats, and configured delivery handoffs.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/fableloom-outline-episode.md b/data.reference/prompts/stages/fableloom-outline-episode.md
new file mode 100644
index 0000000000..19b0d5413c
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-outline-episode.md
@@ -0,0 +1,77 @@
+# FableLoom — Draft Episode Beat Outline
+
+You are the story architect for one episode of an interactive branching series. Plan the episode before writing its teleplay. Return one concise log-line or summary per camera-cut beat, with the viewer paths and ending beats, but do not write scene prose, dialogue, image prompts, or video prompts.
+
+## Story
+
+{{storyContext}}
+
+## World canon
+
+{{canonDigest}}
+
+## Episode order
+
+{{episodeSequence}}
+
+## Existing teleplay graph
+
+{{currentGraph}}
+
+## Existing beat outline
+
+{{currentOutline}}
+
+## Author guidance
+
+{{guidance}}
+
+## Audience participation contract
+
+{{participationContract}}
+
+## Planning contract
+
+- Plan the complete dramatic job of this episode, including setup, escalation, a meaningful turn, branch consequences, and distinct endings that hand off cleanly to the next episode when one exists.
+- Use one beat per eventual camera-cut scene. Keep each `summary` to 1–3 sentences describing what changes, what the protagonist wants, and why the beat matters.
+- Use `playbackMode: "cut"` for setup/action beats that automatically advance and give them exactly one transition. Use `playbackMode: "decision"` only for genuine viewer choices and give them 2–4 clearly different paths.
+- In helper mode, mark a beat `audienceConnection: "connected"` only after the communication medium is activated. Never put a decision beat on a disconnected channel. The first episode must invite the audience near its opening; later episodes should state whether the channel is restored, carried forward, or unavailable.
+- Mark `protagonistPresence: "offscreen"` for decision beats where the protagonist speaks directly to the audience through the communicator. Those beats are the side-device conversation: keep the visual beat open-ended and do not put the protagonist in the storyboard. Use `"onscreen"` when the protagonist is visibly present; choose deliberately for every beat.
+- Every beat must be reachable from `startKey`. Every non-ending beat needs a path forward. Endings have no outgoing paths, and their outcomes must differ in consequence or tone rather than only in label.
+- Continue the exact protagonist, character identities, locations, objects, unresolved threads, and emotional consequences established by the preceding episodes. Do not replace the established protagonist with a new one merely to create novelty.
+- The final beat of an episode should make the next episode feel necessary. Series delivery notes may require an overnight voicemail between episodes or a next-season teaser after the final ending; preserve those promises in the beat plan without writing the voicemail itself here.
+
+Return ONLY valid JSON matching this shape — no prose, markdown fence, or commentary:
+
+```json
+{
+ "startKey": "s1",
+ "scenes": [
+ {
+ "key": "s1",
+ "title": "short evocative beat title",
+ "summary": "one to three sentence log-line",
+ "playbackMode": "cut",
+ "audienceConnection": "disconnected",
+ "protagonistPresence": "onscreen",
+ "isEnding": false,
+ "endingLabel": "",
+ "transitions": [
+ { "targetKey": "s2", "intent": "continue" }
+ ]
+ },
+ {
+ "key": "s8",
+ "title": "distinct outcome",
+ "summary": "what the protagonist gains or loses and why the series must continue",
+ "playbackMode": "cut",
+ "audienceConnection": "connected",
+ "isEnding": true,
+ "endingLabel": "short outcome name",
+ "transitions": []
+ }
+ ]
+}
+```
+
+Use short stable keys (`s1`, `s2`, …). Every `targetKey` must reference a key in `scenes`. The server will validate the outline before it can be expanded into a teleplay.
diff --git a/data.reference/prompts/stages/fableloom-review-episode-outline.md b/data.reference/prompts/stages/fableloom-review-episode-outline.md
new file mode 100644
index 0000000000..d085c1074c
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-review-episode-outline.md
@@ -0,0 +1,36 @@
+# FableLoom — Review Episode Beat Outline
+
+You are a senior story editor reviewing the beat outline for one episode inside a complete interactive series. Assess the arc before it becomes teleplay scenes. Do not rewrite the outline and do not invent full scene prose.
+
+## Story
+
+{{storyContext}}
+
+## World canon
+
+{{canonDigest}}
+
+## Episode order
+
+{{episodeSequence}}
+
+## Beat outline
+
+{{outlineDigest}}
+
+## Deterministic findings
+
+{{structuralDigest}}
+
+Evaluate whether the episode has a clear dramatic job, escalation, protagonist agency, branch consequences, meaningful and distinct endings, continuity with adjacent episodes, side-quest movement, and a compelling handoff. Check that choices are legible from their preceding beat and that the audience connection rules are dramatized rather than merely technical. Check that off-screen protagonist beats are reserved for direct audience conversations and that visible beats keep the canonical wardrobe. Flag only concrete risks that a writer can fix before teleplay expansion.
+
+Return ONLY valid JSON matching this shape — no prose, markdown fence, or commentary:
+
+```json
+{
+ "summary": "concise editorial assessment",
+ "strengths": ["specific strength"],
+ "risks": ["specific story risk"],
+ "recommendations": ["concrete pre-expansion edit"]
+}
+```
diff --git a/data.reference/prompts/stages/fableloom-review-series-plan.md b/data.reference/prompts/stages/fableloom-review-series-plan.md
index d0dc785b36..bedfea177f 100644
--- a/data.reference/prompts/stages/fableloom-review-series-plan.md
+++ b/data.reference/prompts/stages/fableloom-review-series-plan.md
@@ -14,7 +14,7 @@ You are a senior story editor analyzing the complete plan for an interactive bra
{{seriesPlanJson}}
-Evaluate the long-form dramatic arc, escalation and payoff of the ordered plot points, pacing across episodes, integration and resolution of side quests, continuity, thematic coherence, and whether the plan leaves each episode a distinct dramatic job. Account for branching storytelling: meaningful paths can vary locally, but the series-level promises and payoffs still need to remain legible.
+Evaluate the long-form dramatic arc, escalation and payoff of the ordered plot points, pacing across episodes, integration and resolution of side quests, continuity, thematic coherence, and whether the plan leaves each episode a distinct dramatic job. When beat outlines are present in the episode outline, review their scene-by-scene progression as one continuous teleplay series: check that each episode inherits the previous episode's consequences, that the protagonist and world remain consistent, that branch outcomes reconverge honestly, and that the finale's configured voicemail/teaser handoffs are earned. Account for branching storytelling: meaningful paths can vary locally, but the series-level promises and payoffs still need to remain legible.
Return ONLY valid JSON matching this shape:
diff --git a/data.reference/prompts/stages/fableloom-review-series-teleplay.md b/data.reference/prompts/stages/fableloom-review-series-teleplay.md
new file mode 100644
index 0000000000..0b11d64f63
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-review-series-teleplay.md
@@ -0,0 +1,34 @@
+# FableLoom — Review the Full Teleplay Series
+
+You are the senior story editor on a complete interactive teleplay series. Review the expanded scene set as one continuous experience. Do not rewrite scenes; return only actionable editorial guidance.
+
+## Story and series plan
+
+{{storyContext}}
+
+{{seriesPlanJson}}
+
+## World canon
+
+{{canonDigest}}
+
+## Expanded teleplay
+
+{{teleplayDigest}}
+
+## Deterministic structure findings
+
+{{structuralDigest}}
+
+Evaluate the full series for protagonist continuity, character and place consistency, escalation, midpoint reversal, climax and resolution, episode-to-episode causality, branch consequences, choice clarity, side-quest payoff, scene-level pacing, distinct endings, and the configured overnight voicemail/finale teaser handoffs. Treat the image-preview/player experience as part of the review: every scene should have a clear visual beat and every decision should be available only when the audience channel is active. Flag concrete issues with the smallest useful fix; do not pad the review with generic advice.
+
+Return ONLY valid JSON matching this shape — no prose, markdown fence, or commentary:
+
+```json
+{
+ "summary": "concise assessment of the complete teleplay series",
+ "strengths": ["specific strength"],
+ "risks": ["specific series-level risk"],
+ "recommendations": ["concrete edit"]
+}
+```
diff --git a/data.reference/prompts/stages/fableloom-weave-episode.md b/data.reference/prompts/stages/fableloom-weave-episode.md
index 99536e9568..7997b114dc 100644
--- a/data.reference/prompts/stages/fableloom-weave-episode.md
+++ b/data.reference/prompts/stages/fableloom-weave-episode.md
@@ -24,6 +24,12 @@ You are a story writer and creative director. Build ONE complete episode of an i
When an existing graph is present, this is a reweave: preserve its story events, dialogue, branch meanings, and ending outcomes while expanding or recomposing nodes as needed to satisfy the one-camera-cut-per-node contract.
+## Validated episode beat outline
+
+{{outlineDigest}}
+
+When a validated beat outline is present, it is the authoritative story plan for this expansion. Expand every outline beat into one corresponding camera-cut node in the same dramatic order, preserve its path meanings and ending outcomes, and add only the scene-level prose and production directions needed to make those beats playable. Do not replace the established protagonist, world, or episode handoff.
+
## Design contract
- Choose the node count and ending count yourself from the story's pacing, dramatic coverage, and branching needs. Never compress multiple camera cuts into one node to hit an arbitrary count.
@@ -31,6 +37,7 @@ When an existing graph is present, this is a reweave: preserve its story events,
- Set `playbackMode: "cut"` on setup/action nodes that play once and automatically feed the next camera cut. They must have exactly one `Continue` transition.
- Set `playbackMode: "decision"` on choice or feedback nodes. Their video is designed to loop seamlessly while the experience waits for the viewer; give them 1–4 distinct intent paths. The loop must show an ongoing, repeatable situation rather than irreversible action (for example, a guard pacing a hallway while the viewer decides when to move).
- Set `audienceConnection` on every node. In helper mode, the opening is passive until the configured communication medium is visibly activated close to the beginning; that first connected scene must invite the audience into the story as themselves. Only `connected` scenes may use `playbackMode: "decision"`. Every `disconnected` scene uses `playbackMode: "cut"` with exactly one canon continuation, including scenes after the medium is lost, stolen, broken, or jammed. A later scene may restore it. In protagonist mode use `connected` on decision scenes and `disconnected` on automatic cuts.
+- Set `protagonistPresence` on every node. A helper-mode connected decision beat that is the protagonist's direct communicator conversation with the audience should be `"offscreen"`: the scene image must omit the protagonist so the host can keep the decision scene looping while the audience speaks on a second device. Use `"onscreen"` for a visible protagonist beat. When a canonical protagonist wardrobe is supplied in the story context, keep that wardrobe unchanged in every on-screen scene unless the story explicitly records a wardrobe change.
- Reserve multiple paths for genuine viewer decisions. Endings must differ meaningfully in outcome and tone.
- Exactly one scene is the opening (`startKey`). Every scene must be reachable from it.
- Every non-ending node needs either one `Continue` path for consecutive coverage or 2–4 outgoing paths at a genuine decision. Each path gets: an `intent` (a short imperative label, ≤10 words), 2–4 `triggers` (example free-text phrasings a reader might type), and a one-sentence `description` of where it leads (spoiler-safe).
@@ -64,6 +71,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c
"cameraMovement": "slow-dolly-in",
"playbackMode": "cut",
"audienceConnection": "disconnected",
+ "protagonistPresence": "onscreen",
"isEnding": false,
"transitions": [
{ "targetKey": "s2", "intent": "string", "triggers": ["string"], "description": "string" }
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 34acc85506..a2e87d3338 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -12,9 +12,9 @@ rehearse the same experience at any of those three production stages.
| Term | Meaning |
|---|---|
-| **Loom** | A branching-narrative story (`loom-*`): name/logline/premise, scene `format`, audience `participationMode`, helper `audienceCommunicationMedium`, optional `playSettings` pin, optional `universeId` + `seriesId` links, episodes. |
-| **Episode** | One playable graph (`ep-*`): title, synopsis (feeds generation), `startNodeId`, nodes. |
-| **Scene node** | One camera cut (`node-*`): teleplay/prose, image prompt/render, single-clip video prompt/render, camera movement, `playbackMode`, `audienceConnection`, ending state, transitions. |
+| **Loom** | A branching-narrative story (`loom-*`): name/logline/premise, scene `format`, audience `participationMode`, helper `audienceCommunicationMedium`, optional canonical Universe protagonist/wardrobe pin, optional `playSettings` pin, optional `universeId` + `seriesId` links, episodes. |
+| **Episode** | One playable graph (`ep-*`): title, synopsis (feeds generation), an optional validated `storyOutline` of log-line beats, `startNodeId`, nodes. |
+| **Scene node** | One camera cut (`node-*`): teleplay/prose, image prompt/render, single-clip video prompt/render, camera movement, `playbackMode`, `audienceConnection`, `protagonistPresence`, ending state, transitions. |
| **Transition** | An intent-labeled edge (`tr-*`): `intent`, `triggers` (example phrasings), spoiler-safe `description`, `targetNodeId`. |
## Playback contract
@@ -57,6 +57,16 @@ their single automatic canon path until a later scene restores the connection.
The graph validator flags helper episodes that never connect, connect too late,
or expose a decision while disconnected.
+Story settings also pin the canonical protagonist to one Universe character and
+optionally one locked wardrobe. The scene editor shows the character's sheet
+and approved identity-pack readiness, offers a one-click visual-cast binding,
+and lets each scene choose on-screen or off-screen presence. An off-screen
+connected decision is the side-device conversation: its decision image omits
+the protagonist while the loop remains visible to the host. The server-side
+visual compiler applies the canonical wardrobe to every on-screen protagonist
+binding and records the presence decision in render provenance, so stale
+scene-local clothes cannot silently reappear between episodes.
+
## Surfaces
- **`/fableloom`** — index: create/delete looms, link a universe (canon +
@@ -70,9 +80,16 @@ or expose a decision while disconnected.
below it on small ones, with a path strip for inbound/outbound intents
when the graph is stacked. `?play=1` opens the reader drawer.
- **`/fableloom/:loomId/:episodeId/outline`** — a text-first episode outline:
- reachable scenes appear in story order with their authored prose, endings,
- and reader paths. Unreachable scenes remain visible in a separate section,
- and path destinations return to the matching scene in the visual editor.
+ the saved beat outline appears first, followed by reachable teleplay scenes in
+ story order with their authored prose, endings, and reader paths. Unreachable
+ scenes remain visible in a separate section, and path destinations return to
+ the matching scene in the visual editor.
+- **Episode setup → Story beats → teleplay** — the production gate: draft one
+ concise log-line per eventual camera cut, edit paths and audience-channel
+ states, run the deterministic validator, and optionally ask the AI story
+ editor to review the arc. Teleplay expansion is blocked until every episode
+ in the series has a valid beat outline and any configured voicemail/finale
+ teaser handoffs have authored text.
- **Play drawer** — an interactive production preview with **Text**,
**Storyboard images**, and **Rendered video** modes. All three traverse the
same graph. Rendered automatic cuts advance on the video's `ended` event;
@@ -158,10 +175,13 @@ in the request body beats both.
| Stage | What it does |
|---|---|
| `fableloom-generate-series-plan` | Drafts the full series arc, ordered plot points, and side quests from the loom metadata, linked-universe canon, and episode outline. |
+| `fableloom-outline-episode` | Drafts one episode as concise camera-cut log-lines, viewer paths, audience-channel states, and distinct endings without writing teleplay or media prompts. |
| `fableloom-weave-episode` | Generates or reweaves a full episode as single-camera-cut nodes. The story writer/creative director chooses node and ending counts, establishes the configured audience role/medium near the opening, tracks connection availability, marks automatic cuts vs decision loops, and assigns camera/video direction. A reweave sees and preserves the existing story graph while splitting multi-cut scenes. |
| `fableloom-branch-node` | Grows N new intent-labeled single-cut branches with playback and camera direction. |
| `fableloom-play-turn` | Resolves one reader message: `move` through a matched transition or `stay` with in-world narration. |
| `fableloom-review` | Story-editor critique (intent clarity, branch coherence, ending payoff) layered over the deterministic checks. |
+| `fableloom-review-episode-outline` | Story-editor review of one episode's pre-teleplay arc, branch consequences, canon continuity, audience contract, endings, and handoff. |
+| `fableloom-review-series-teleplay` | Story-editor review of every expanded episode as one complete interactive teleplay series, including continuity, escalation, endings, visual beats, and delivery handoffs. |
| `fableloom-reformat-scenes` | Rewrites existing scenes into the loom's other format (prose ⇄ teleplay), preserving every beat and decision point. |
Deterministic graph validation (no LLM) lives in
@@ -171,6 +191,15 @@ audience-connection availability, and the exactly-one-next-path contract for aut
and renders in the editor's Structure panel via
`GET /api/fableloom/:id/episodes/:episodeId/validate`.
+Beat-outline validation is a separate deterministic gate. The per-episode
+result is persisted on `episode.storyOutline.validation`; the series result is
+available at `GET /api/fableloom/:id/outlines/validate`. Expansion rechecks
+both results server-side, so a stale client cannot bypass the story-first
+workflow. Scene-level and batch media controls mirror that readiness state in
+the UI: storyboard generation stays disabled until the ordered beat arc and
+any configured delivery handoffs are ready, preventing image spend on an
+unreviewed or out-of-order teleplay.
+
Reweaving preserves story events and path meanings, but it replaces node ids;
existing rendered stills and clips are therefore dropped. The setup drawer
warns about that production cost before the author starts the reweave.
@@ -201,6 +230,11 @@ capabilities, selected asset basenames, adapter SHA-256/scales, compiler
version, temporal source, and omissions; machine-local paths never enter the
loom or Universe record.
+The compiler treats an off-screen protagonist as an intentional omission, not
+as a missing reference: any stale protagonist binding is listed as omitted with
+reason `protagonist-offscreen`, and the manifest still records the canonical
+character, wardrobe, and presence for auditability.
+
**Generate video** prefers the node's dedicated single-clip `videoPrompt`, adds
the selected movement's production direction from the shared camera registry,
and falls back to scene text for legacy nodes. The registry includes dolly,
diff --git a/docs/plans/2026-08-29-fableloom-visual-continuity.md b/docs/plans/2026-08-29-fableloom-visual-continuity.md
index 000c787dc9..9751b2f1a5 100644
--- a/docs/plans/2026-08-29-fableloom-visual-continuity.md
+++ b/docs/plans/2026-08-29-fableloom-visual-continuity.md
@@ -12,6 +12,17 @@ The design reuses the Universe's existing canon records and assets. It does not
create a second FableLoom-only character or location registry, train models, or
attempt automatic face recognition.
+FableLoom also pins an optional canonical protagonist and wardrobe at the loom
+level. This is the stable identity anchor for every episode: the scene binding
+may add other characters and per-shot state, but it cannot silently substitute
+another protagonist. Each scene separately declares `protagonistPresence` as
+`onscreen` or `offscreen`. Off-screen is a first-class visual state for a
+helper-mode connected decision: the protagonist speaks with the audience on a
+side device while the host's decision image remains open-ended and contains no
+protagonist appearance. A locked loom wardrobe is applied by the compiler to
+every on-screen protagonist binding, while off-screen bindings are recorded as
+intentional omissions.
+
## Why the prior-shot bridge is insufficient
A previous shot can carry palette, lighting, costume, and likeness into the
@@ -77,6 +88,22 @@ Add an optional `visualCanon` object to each scene node:
}
```
+The loom-level identity pin is deliberately separate from this per-shot object:
+
+```json
+{
+ "protagonistCharacterId": "char-example",
+ "protagonistWardrobeId": "wardrobe-field",
+ "protagonistWardrobeLocked": true
+}
+```
+
+The editor links these ids to the Universe Cast, shows character-sheet and
+approved identity-pack readiness, and provides a one-click binding for any
+on-screen shot. `protagonistPresence: "offscreen"` removes the pinned
+protagonist from the compiled character cast and records the omission in the
+manifest; it is not treated as a missing canon reference.
+
All keys are optional and bounded. IDs are soft references because Universe
canon is independently editable; a missing id produces an explicit degraded
binding rather than invalidating the story graph. `continuitySourceNodeId` is
@@ -211,6 +238,12 @@ source to finish before queueing its dependent. Independent branches may render
in parallel. A failed predecessor blocks only descendants that require it;
canon-only branches can continue.
+At the series level, storyboard production follows the ordered episode list as
+well: every reachable still in an earlier episode must exist before a later
+episode can render. The batch planner, scene-level image controls, and their
+server route share this gate, so a direct click cannot bypass temporal
+continuity.
+
## Provenance and observability
Persist a versioned `visualConditioning` manifest in image sidecars and video
diff --git a/scripts/migrations/288-fableloom-scene-format.js b/scripts/migrations/288-fableloom-scene-format.js
index 51d4cd8892..b1059935e3 100644
--- a/scripts/migrations/288-fableloom-scene-format.js
+++ b/scripts/migrations/288-fableloom-scene-format.js
@@ -11,6 +11,10 @@
* they still hash to the shipped v1 body; a customized template is left alone
* and warned about.
*
+ * The weave template is resynced here when a later migration evolves it. Its
+ * former current hash remains accepted so an install whose migration ledger is
+ * replayed can still advance through this lineage before the latest sample.
+ *
* Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.
*/
@@ -18,14 +22,17 @@ import { makePromptReplaceMigration } from './_lib.js';
// Pre-change shipped hashes — the v1 bodies seeded by migration 286.
export const ACCEPTED_OLD_MD5 = {
- 'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46'],
+ 'fableloom-weave-episode.md': [
+ '1fea11b8c4269008561ac22a30494d46',
+ '18a442e39b973e4074a0d595928a665d', // post-311 / pre-319
+ ],
'fableloom-branch-node.md': ['f558e4804b056a5961af1ea74fdef2ba'],
'fableloom-play-turn.md': ['bb33dc9bc483668d88196ca972d5f364'],
};
// Post-change shipped hashes (format contract rendered from the loom record).
export const NEW_SHIPPED_MD5 = {
- 'fableloom-weave-episode.md': '18a442e39b973e4074a0d595928a665d',
+ 'fableloom-weave-episode.md': 'e0f8d864caa8746912b56cd567f1c09d', // post-319 continuity contract
'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da',
'fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',
};
diff --git a/scripts/migrations/310-fableloom-camera-cuts.js b/scripts/migrations/310-fableloom-camera-cuts.js
index 2e89f326a2..c67478d540 100644
--- a/scripts/migrations/310-fableloom-camera-cuts.js
+++ b/scripts/migrations/310-fableloom-camera-cuts.js
@@ -1,18 +1,23 @@
/**
* Upgrade FableLoom generation/editing prompts to one renderable camera cut
- * per node and add the shared camera-movement vocabulary.
+ * per node and add the shared camera-movement vocabulary. The weave template's
+ * current hash is resynced to the latest continuity contract; its former
+ * current hash is retained as an accepted intermediate for replayed ledgers.
*/
import { makePromptReplaceMigration } from './_lib.js';
export const ACCEPTED_OLD_MD5 = {
- 'fableloom-weave-episode.md': ['1b27f5b0073a304c21079aa6e2c71447'],
+ 'fableloom-weave-episode.md': [
+ '1b27f5b0073a304c21079aa6e2c71447',
+ '18a442e39b973e4074a0d595928a665d', // post-311 / pre-319
+ ],
'fableloom-branch-node.md': ['6279b1c9912c300363a727245d22fe84'],
'fableloom-feedback-episode.md': ['43d1525fcedce99b933ae5b003516a36'],
};
export const NEW_SHIPPED_MD5 = {
- 'fableloom-weave-episode.md': '18a442e39b973e4074a0d595928a665d',
+ 'fableloom-weave-episode.md': 'e0f8d864caa8746912b56cd567f1c09d', // post-319 continuity contract
'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da',
'fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670',
};
diff --git a/scripts/migrations/311-fableloom-audience-participation.js b/scripts/migrations/311-fableloom-audience-participation.js
index 0b80a91249..d8684de236 100644
--- a/scripts/migrations/311-fableloom-audience-participation.js
+++ b/scripts/migrations/311-fableloom-audience-participation.js
@@ -1,16 +1,23 @@
-/** Upgrade FableLoom prompts with audience-role and communication-channel rules. */
+/**
+ * Upgrade FableLoom prompts with audience-role and communication-channel rules.
+ * The weave template is resynced to the latest continuity contract; its former
+ * current hash remains accepted as an intermediate replay state.
+ */
import { makePromptReplaceMigration } from './_lib.js';
export const ACCEPTED_OLD_MD5 = {
- 'fableloom-weave-episode.md': ['4c9454d1537c4ebb3becbfa04fae3ed8'],
+ 'fableloom-weave-episode.md': [
+ '4c9454d1537c4ebb3becbfa04fae3ed8',
+ '18a442e39b973e4074a0d595928a665d', // post-311 / pre-319
+ ],
'fableloom-branch-node.md': ['c14e2b9c435e43a8c3b134a62cd66d08'],
'fableloom-feedback-episode.md': ['d09bb405478d24c294b0c658ef365cd1'],
'fableloom-review.md': ['2802f269f246e00ec5a8937637d42de6'],
};
export const NEW_SHIPPED_MD5 = {
- 'fableloom-weave-episode.md': '18a442e39b973e4074a0d595928a665d',
+ 'fableloom-weave-episode.md': 'e0f8d864caa8746912b56cd567f1c09d', // post-319 continuity contract
'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da',
'fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670',
'fableloom-review.md': 'c26a641f6d0530caef7d1186c3b09937',
diff --git a/scripts/migrations/317-fableloom-episode-outline-stages.js b/scripts/migrations/317-fableloom-episode-outline-stages.js
new file mode 100644
index 0000000000..8d60601948
--- /dev/null
+++ b/scripts/migrations/317-fableloom-episode-outline-stages.js
@@ -0,0 +1,8 @@
+/** Seed the FableLoom episode-outline planning and review stages. */
+
+import { makeSeedMigrations } from './_seedStageHelpers.js';
+
+export default makeSeedMigrations([
+ 'fableloom-outline-episode',
+ 'fableloom-review-episode-outline',
+]);
diff --git a/scripts/migrations/317-fableloom-episode-outline-stages.test.js b/scripts/migrations/317-fableloom-episode-outline-stages.test.js
new file mode 100644
index 0000000000..a1a2560095
--- /dev/null
+++ b/scripts/migrations/317-fableloom-episode-outline-stages.test.js
@@ -0,0 +1,12 @@
+import { describe } from 'vitest';
+
+import migration from './317-fableloom-episode-outline-stages.js';
+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';
+
+describe('migration 317 — seed the FableLoom episode-outline stages', () => {
+ runSeedStageMigrationTests({
+ migration,
+ stages: ['fableloom-outline-episode', 'fableloom-review-episode-outline'],
+ prefix: 'migration-317-',
+ });
+});
diff --git a/scripts/migrations/318-fableloom-series-teleplay-review-stage.js b/scripts/migrations/318-fableloom-series-teleplay-review-stage.js
new file mode 100644
index 0000000000..ba40ca0b24
--- /dev/null
+++ b/scripts/migrations/318-fableloom-series-teleplay-review-stage.js
@@ -0,0 +1,5 @@
+/** Seed the FableLoom full-teleplay series review stage. */
+
+import { makeSeedMigration } from './_seedStageHelpers.js';
+
+export default makeSeedMigration('fableloom-review-series-teleplay');
diff --git a/scripts/migrations/318-fableloom-series-teleplay-review-stage.test.js b/scripts/migrations/318-fableloom-series-teleplay-review-stage.test.js
new file mode 100644
index 0000000000..135fb2e513
--- /dev/null
+++ b/scripts/migrations/318-fableloom-series-teleplay-review-stage.test.js
@@ -0,0 +1,12 @@
+import { describe } from 'vitest';
+
+import migration from './318-fableloom-series-teleplay-review-stage.js';
+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';
+
+describe('migration 318 — seed the FableLoom full-teleplay review stage', () => {
+ runSeedStageMigrationTests({
+ migration,
+ stages: ['fableloom-review-series-teleplay'],
+ prefix: 'migration-318-',
+ });
+});
diff --git a/scripts/migrations/319-fableloom-protagonist-continuity.js b/scripts/migrations/319-fableloom-protagonist-continuity.js
new file mode 100644
index 0000000000..783561849f
--- /dev/null
+++ b/scripts/migrations/319-fableloom-protagonist-continuity.js
@@ -0,0 +1,30 @@
+/** Upgrade FableLoom prompts with canonical protagonist and off-screen scene rules. */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ // 18a442 is the shipped FableLoom audience/camera-cut template. The outline
+ // and outline-review hashes also cover the templates seeded by migrations
+ // 317/318 before the protagonist-presence additions in this migration.
+ 'fableloom-weave-episode.md': ['18a442e39b973e4074a0d595928a665d'],
+ 'fableloom-outline-episode.md': ['3f5144103b2ab6203fa071ff5026251b'],
+ 'fableloom-review-episode-outline.md': ['96d631104155ff11be08bcc5144cca1c'],
+};
+
+export const NEW_SHIPPED_MD5 = {
+ 'fableloom-weave-episode.md': 'e0f8d864caa8746912b56cd567f1c09d',
+ 'fableloom-outline-episode.md': '513b2b5b8fa98766852cdde7b87198c9',
+ 'fableloom-review-episode-outline.md': '8154b4c289b10268df8fd3c625bcdac2',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'FableLoom protagonist identity, wardrobe, and off-screen presence',
+ customizedHint: (filename) =>
+ ` Merge the canonical protagonist wardrobe and off-screen communicator rules from\n`
+ + ` data.reference/prompts/stages/${filename} into the installed template.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/319-fableloom-protagonist-continuity.test.js b/scripts/migrations/319-fableloom-protagonist-continuity.test.js
new file mode 100644
index 0000000000..03db27b85e
--- /dev/null
+++ b/scripts/migrations/319-fableloom-protagonist-continuity.test.js
@@ -0,0 +1,16 @@
+import { describe } from 'vitest';
+
+import migration, {
+ applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5,
+} from './319-fableloom-protagonist-continuity.js';
+import { runPromptMigrationTests } from './_testHelpers.js';
+
+describe('migration 319 — FableLoom protagonist continuity prompts', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-319-',
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 013ca251b1..d08f0a000b 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -55,11 +55,13 @@ const EXPECTED_STAGE_OLD = {
'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f'],
'pipeline-observer.md': ['f3dc51ac077050a887c2161ee7438181'],
'pipeline-self-improve.md': ['ed0b0df42e0690d515b8dd88911931e4'],
- 'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46', '1b27f5b0073a304c21079aa6e2c71447', '4c9454d1537c4ebb3becbfa04fae3ed8'],
+ 'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46', '1b27f5b0073a304c21079aa6e2c71447', '4c9454d1537c4ebb3becbfa04fae3ed8', '18a442e39b973e4074a0d595928a665d'],
'fableloom-branch-node.md': ['f558e4804b056a5961af1ea74fdef2ba', '6279b1c9912c300363a727245d22fe84', 'c14e2b9c435e43a8c3b134a62cd66d08'],
'fableloom-play-turn.md': ['bb33dc9bc483668d88196ca972d5f364'],
'fableloom-feedback-episode.md': ['43d1525fcedce99b933ae5b003516a36', 'd09bb405478d24c294b0c658ef365cd1'],
'fableloom-review.md': ['2802f269f246e00ec5a8937637d42de6'],
+ 'fableloom-outline-episode.md': ['3f5144103b2ab6203fa071ff5026251b'],
+ 'fableloom-review-episode-outline.md': ['96d631104155ff11be08bcc5144cca1c'],
};
const EXPECTED_STAGE_NEW = {
'pipeline-idea-expansion.md': 'a032e4a724251ed3e3495d33c4dbab8e',
@@ -93,11 +95,13 @@ const EXPECTED_STAGE_NEW = {
'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410',
'pipeline-observer.md': '29e0212d2252b1be3278f20e2959eb8e',
'pipeline-self-improve.md': '95b378832ff78e5976a6a63fcf328090',
- 'fableloom-weave-episode.md': '18a442e39b973e4074a0d595928a665d',
+ 'fableloom-weave-episode.md': 'e0f8d864caa8746912b56cd567f1c09d',
'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da',
'fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',
'fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670',
'fableloom-review.md': 'c26a641f6d0530caef7d1186c3b09937',
+ 'fableloom-outline-episode.md': '513b2b5b8fa98766852cdde7b87198c9',
+ 'fableloom-review-episode-outline.md': '8154b4c289b10268df8fd3c625bcdac2',
};
const EXPECTED_PARTIAL_OLD = {
'bible-deference.md': ['218f0e85643609ed85a12b1ccc7b5a8d'],
diff --git a/server/lib/README.md b/server/lib/README.md
index a15dbe19b9..7f31b24729 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -36,8 +36,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fableLoomPlayback.js` | FableLoom node playback modes (`cut` auto-advances; `decision` loops while awaiting input), with the backward-compatible default. |
| `fableLoomParticipation.js` | FableLoom audience roles (helper vs protagonist), per-scene connection availability, prompt contracts, and backward-compatible defaults. |
| `fableLoomFormats.js` | FableLoom scene formats (`LOOM_FORMATS`, `asLoomFormat`, `sceneFormatContract`, …) — how a loom writes scene text, read by validation, the sanitizer, and every generative stage. |
-| `fableLoomProduction.js` | FableLoom production batch planning and topological orchestration: DAG resolution, asset enumeration, execution stages, and exact-input provenance verification. |
+| `fableLoomProduction.js` | FableLoom production batch planning and topological orchestration: ordered episode storyboard gates, DAG resolution, asset enumeration, execution stages, and exact-input provenance verification. |
| `fableLoomContinuity.js` | FableLoom episodic continuity review: multi-vector deterministic checks for visual entity bindings, convergence clarity, voice profile consistency/drift, pronunciation anchors, and playback safety. |
+| `fableLoomOutline.js` | FableLoom story-first episode beat outlines: bounded log-lines, deterministic arc validation, and compact prompt rendering before teleplay expansion. |
| `postDrillTypes.js` | MeatSpace POST drill vocabularies (`CACHEABLE_TYPES`, `COGNITIVE_DRILL_TYPES`), kept below validation so a route schema never pulls in the POST services (and, through them, the LLM drill generator). |
| `spriteVocabulary.js` | Sprite id pattern, record kinds, the canonical 8-direction order + derived anchor set, `TURNAROUND_ID`, and the animation provider ids — the alphabets the sprite route schemas enumerate, kept below the sprite services. |
| `spriteChromaKey.js` | Chroma-key selection color math (`CHROMA_KEYS`, `CHROMA_KEY_HEXES`, `DEFAULT_CHROMA_KEY`, hue-distance picking). Pure color math, no image I/O — that lives in `services/sprites/normalize.js`. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index e3beefba57..b482cd2d36 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -8724,7 +8724,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 89
+ "line": 97
}
]
},
@@ -8735,7 +8735,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 96
+ "line": 104
}
]
},
@@ -8746,7 +8746,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 112
+ "line": 120
}
]
},
@@ -8757,7 +8757,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 101
+ "line": 109
}
]
},
@@ -8768,7 +8768,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 107
+ "line": 115
}
]
},
@@ -8779,7 +8779,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 136
+ "line": 149
}
]
},
@@ -8790,7 +8790,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 146
+ "line": 159
}
]
},
@@ -8801,7 +8801,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 141
+ "line": 154
}
]
},
@@ -8812,7 +8812,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 322
+ "line": 359
}
]
},
@@ -8823,7 +8823,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 239
+ "line": 276
}
]
},
@@ -8834,7 +8834,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 178
+ "line": 197
}
]
},
@@ -8845,7 +8845,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 188
+ "line": 207
}
]
},
@@ -8856,7 +8856,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 183
+ "line": 202
}
]
},
@@ -8867,7 +8867,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 226
+ "line": 263
}
]
},
@@ -8878,7 +8878,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 167
+ "line": 186
}
]
},
@@ -8889,7 +8889,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 201
+ "line": 220
}
]
},
@@ -8900,7 +8900,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 213
+ "line": 232
}
]
},
@@ -8911,7 +8911,40 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 206
+ "line": 225
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/outline/generate",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 248
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/outline/review",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 258
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/outline/validate",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 253
}
]
},
@@ -8922,7 +8955,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 244
+ "line": 281
}
]
},
@@ -8933,7 +8966,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 293
+ "line": 330
}
]
},
@@ -8944,7 +8977,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 298
+ "line": 335
}
]
},
@@ -8955,7 +8988,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 306
+ "line": 343
}
]
},
@@ -8966,7 +8999,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 314
+ "line": 351
}
]
},
@@ -8977,7 +9010,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 288
+ "line": 325
}
]
},
@@ -8988,7 +9021,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 255
+ "line": 292
}
]
},
@@ -8999,7 +9032,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 231
+ "line": 268
}
]
},
@@ -9010,7 +9043,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 266
+ "line": 303
}
]
},
@@ -9021,7 +9054,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 262
+ "line": 299
}
]
},
@@ -9032,7 +9065,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 151
+ "line": 170
}
]
},
@@ -9043,7 +9076,18 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 221
+ "line": 240
+ }
+ ]
+ },
+ {
+ "method": "GET",
+ "path": "/api/fableloom/:id/outlines/validate",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 164
}
]
},
@@ -9054,7 +9098,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 129
+ "line": 142
}
]
},
@@ -9065,7 +9109,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 119
+ "line": 127
}
]
},
@@ -9076,7 +9120,18 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 124
+ "line": 132
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/review-teleplay",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 137
}
]
},
@@ -9087,7 +9142,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 282
+ "line": 319
}
]
},
@@ -9098,7 +9153,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 271
+ "line": 308
}
]
},
@@ -9109,7 +9164,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 277
+ "line": 314
}
]
},
@@ -10165,7 +10220,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 792
+ "line": 808
}
]
},
@@ -10176,7 +10231,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 816
+ "line": 832
}
]
},
@@ -10187,7 +10242,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 811
+ "line": 827
}
]
},
@@ -10198,7 +10253,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 845
+ "line": 861
}
]
},
@@ -10209,7 +10264,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 830
+ "line": 846
}
]
},
@@ -10220,7 +10275,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 807
+ "line": 823
}
]
},
@@ -10231,7 +10286,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 735
+ "line": 751
}
]
},
@@ -10242,7 +10297,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 340
+ "line": 341
}
]
},
@@ -10253,7 +10308,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 344
+ "line": 345
}
]
},
@@ -10264,7 +10319,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 603
+ "line": 619
}
]
},
@@ -10275,7 +10330,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 741
+ "line": 757
}
]
},
@@ -10286,7 +10341,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 726
+ "line": 742
}
]
},
@@ -10297,7 +10352,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 390
+ "line": 391
}
]
},
@@ -10308,7 +10363,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 722
+ "line": 738
}
]
},
@@ -10319,7 +10374,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 625
+ "line": 641
}
]
},
@@ -10330,7 +10385,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 703
+ "line": 719
}
]
},
@@ -10341,7 +10396,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 684
+ "line": 700
}
]
},
@@ -10352,7 +10407,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 636
+ "line": 652
}
]
},
@@ -10363,7 +10418,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 664
+ "line": 680
}
]
},
@@ -10374,7 +10429,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 357
+ "line": 358
}
]
},
@@ -10484,7 +10539,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 326
+ "line": 327
}
]
},
@@ -10495,7 +10550,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 66
+ "line": 67
}
]
},
@@ -10506,7 +10561,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 619
+ "line": 635
}
]
},
@@ -23488,8 +23543,8 @@
],
"stats": {
"mounts": 145,
- "operations": 2119,
- "declarations": 2122,
+ "operations": 2124,
+ "declarations": 2127,
"sourceFiles": 225
}
}
diff --git a/server/lib/fableLoomContinuity.js b/server/lib/fableLoomContinuity.js
index 889cdc38d0..5c8a8205cd 100644
--- a/server/lib/fableLoomContinuity.js
+++ b/server/lib/fableLoomContinuity.js
@@ -13,7 +13,11 @@
*/
import { computeTopologicalNodeOrder } from './fableLoomProduction.js';
-import { validateAudioOccupancy } from './fableLoomPlayback.js';
+import {
+ resolveFableLoomProtagonistPresence,
+ validateAudioOccupancy,
+} from './fableLoomPlayback.js';
+import { characterIdentityPackReadiness } from './storyBible.js';
export const CONTINUITY_CATEGORIES = Object.freeze(['visual', 'voice', 'playback', 'graph']);
@@ -23,6 +27,12 @@ export const CONTINUITY_CODES = Object.freeze({
MISSING_UNIVERSE_OBJECT: 'MISSING_UNIVERSE_OBJECT',
MISSING_WARDROBE_REFERENCE: 'MISSING_WARDROBE_REFERENCE',
WARDROBE_DRIFT: 'WARDROBE_DRIFT',
+ CANONICAL_PROTAGONIST_UNRESOLVED: 'CANONICAL_PROTAGONIST_UNRESOLVED',
+ CANONICAL_WARDROBE_UNRESOLVED: 'CANONICAL_WARDROBE_UNRESOLVED',
+ CANONICAL_IDENTITY_PACK_NOT_READY: 'CANONICAL_IDENTITY_PACK_NOT_READY',
+ PROTAGONIST_BINDING_MISMATCH: 'PROTAGONIST_BINDING_MISMATCH',
+ PROTAGONIST_VISUAL_BINDING_WHILE_OFFSCREEN: 'PROTAGONIST_VISUAL_BINDING_WHILE_OFFSCREEN',
+ CANONICAL_WARDROBE_DRIFT: 'CANONICAL_WARDROBE_DRIFT',
AMBIGUOUS_CONVERGENCE: 'AMBIGUOUS_CONVERGENCE',
VOICE_PROFILE_REVISION_DRIFT: 'VOICE_PROFILE_REVISION_DRIFT',
VOICE_ENGINE_DRIFT: 'VOICE_ENGINE_DRIFT',
@@ -112,6 +122,61 @@ export function analyzeEpisodeContinuity({
}
}
+ const canonicalProtagonistId = isStr(loom?.protagonistCharacterId)
+ ? loom.protagonistCharacterId
+ : null;
+ const canonicalWardrobeId = isStr(loom?.protagonistWardrobeId)
+ ? loom.protagonistWardrobeId
+ : null;
+ const canonicalProtagonist = canonicalProtagonistId && Array.isArray(universe?.characters)
+ ? universe.characters.find((character) => character.id === canonicalProtagonistId)
+ : null;
+ if (canonicalProtagonistId && !universe) {
+ push({
+ category: 'visual',
+ severity: 'error',
+ code: CONTINUITY_CODES.CANONICAL_PROTAGONIST_UNRESOLVED,
+ message: `Canonical protagonist "${canonicalProtagonistId}" cannot be resolved because the linked Universe is unavailable.`,
+ remediation: 'Restore the linked Universe before reviewing or rendering character continuity.',
+ characterId: canonicalProtagonistId,
+ });
+ } else if (canonicalProtagonistId && !canonicalProtagonist) {
+ push({
+ category: 'visual',
+ severity: 'error',
+ code: CONTINUITY_CODES.CANONICAL_PROTAGONIST_UNRESOLVED,
+ message: `Canonical protagonist "${canonicalProtagonistId}" is not present in the linked Universe.`,
+ remediation: 'Choose an existing Universe character or restore the missing character.',
+ characterId: canonicalProtagonistId,
+ });
+ } else if (canonicalProtagonist && canonicalWardrobeId) {
+ const wardrobeExists = Array.isArray(canonicalProtagonist.wardrobes)
+ && canonicalProtagonist.wardrobes.some((wardrobe) => wardrobe.id === canonicalWardrobeId);
+ if (!wardrobeExists) {
+ push({
+ category: 'visual',
+ severity: 'error',
+ code: CONTINUITY_CODES.CANONICAL_WARDROBE_UNRESOLVED,
+ message: `Canonical wardrobe "${canonicalWardrobeId}" is not present on protagonist "${canonicalProtagonistId}".`,
+ remediation: 'Choose a wardrobe from the protagonist character sheet or clear the stale reference.',
+ characterId: canonicalProtagonistId,
+ });
+ }
+ }
+ if (canonicalProtagonist) {
+ const identityReadiness = characterIdentityPackReadiness(canonicalProtagonist);
+ if (identityReadiness.status !== 'ready') {
+ push({
+ category: 'visual',
+ severity: 'warning',
+ code: CONTINUITY_CODES.CANONICAL_IDENTITY_PACK_NOT_READY,
+ message: `Canonical protagonist "${canonicalProtagonist.name || canonicalProtagonistId}" identity pack is ${identityReadiness.status}; canon-locked storyboard renders need approved neutral, profile, and full-body references.`,
+ remediation: 'Open the Universe character sheet and approve one neutral, profile, and full-body reference image.',
+ characterId: canonicalProtagonistId,
+ });
+ }
+ }
+
// 1. Graph & Convergence Continuity
for (const nodeId of unreachableNodeIds) {
const node = nodeById.get(nodeId);
@@ -149,11 +214,63 @@ export function analyzeEpisodeContinuity({
const visualCanon = node.visualCanon || {};
const interaction = node.interactionWindow || {};
const assets = node.playbackAssets || {};
+ const interactionProtagonistId = isStr(interaction.protagonistCharacterId)
+ ? interaction.protagonistCharacterId
+ : null;
+ const sceneProtagonistIds = new Set(
+ [canonicalProtagonistId, interactionProtagonistId].filter(Boolean),
+ );
+ const protagonistPresence = resolveFableLoomProtagonistPresence(node, loom);
// Visual entity validation
if (universe) {
// Check character appearances
const appearances = Array.isArray(visualCanon.characterAppearances) ? visualCanon.characterAppearances : [];
+ const protagonistAppearances = appearances.filter((appearance) => (
+ sceneProtagonistIds.has(appearance?.characterId)
+ ));
+ if (protagonistPresence === 'offscreen' && protagonistAppearances.length) {
+ push({
+ category: 'visual',
+ severity: 'warning',
+ code: CONTINUITY_CODES.PROTAGONIST_VISUAL_BINDING_WHILE_OFFSCREEN,
+ message: `Scene "${node.title || node.id}" is marked off-screen for the protagonist but still declares a protagonist visual binding; the render compiler will omit it.`,
+ remediation: 'Remove the protagonist from this scene cast, or mark the beat on-screen if the audience should see them.',
+ nodeId: node.id,
+ characterId: interactionProtagonistId || canonicalProtagonistId,
+ });
+ }
+ if (canonicalProtagonistId && interactionProtagonistId
+ && interactionProtagonistId !== canonicalProtagonistId) {
+ push({
+ category: 'playback',
+ severity: 'error',
+ code: CONTINUITY_CODES.PROTAGONIST_BINDING_MISMATCH,
+ message: `Live interaction in scene "${node.title || node.id}" binds protagonist "${interactionProtagonistId}" instead of the loom's canonical protagonist "${canonicalProtagonistId}".`,
+ remediation: 'Use the canonical protagonist selected in Story settings so voice and visual identity stay aligned.',
+ nodeId: node.id,
+ characterId: interactionProtagonistId,
+ });
+ }
+ if (canonicalProtagonistId && canonicalWardrobeId && protagonistPresence !== 'offscreen') {
+ for (const appearance of protagonistAppearances.filter(
+ (item) => item.characterId === canonicalProtagonistId,
+ )) {
+ if (appearance.wardrobeId && appearance.wardrobeId !== canonicalWardrobeId) {
+ push({
+ category: 'visual',
+ severity: loom.protagonistWardrobeLocked === true ? 'warning' : 'info',
+ code: CONTINUITY_CODES.CANONICAL_WARDROBE_DRIFT,
+ message: `Scene "${node.title || node.id}" selects wardrobe "${appearance.wardrobeId}" for the canonical protagonist instead of "${canonicalWardrobeId}".`,
+ remediation: loom.protagonistWardrobeLocked === true
+ ? 'Keep the scene wardrobe on the locked canonical reference or change the loom wardrobe deliberately in Story settings.'
+ : 'Confirm the wardrobe change is intentional, or select the loom canonical wardrobe for this scene.',
+ nodeId: node.id,
+ characterId: canonicalProtagonistId,
+ });
+ }
+ }
+ }
for (const app of appearances) {
const charId = app.characterId;
const char = universe.characters?.find((c) => c.id === charId);
diff --git a/server/lib/fableLoomContinuity.test.js b/server/lib/fableLoomContinuity.test.js
index d374e61005..cc41a1ff13 100644
--- a/server/lib/fableLoomContinuity.test.js
+++ b/server/lib/fableLoomContinuity.test.js
@@ -204,4 +204,77 @@ describe('fableLoomContinuity', () => {
expect(codes).toContain(CONTINUITY_CODES.VOICE_MODEL_REVISION_DRIFT);
expect(codes).toContain(CONTINUITY_CODES.PRONUNCIATION_REVISION_DRIFT);
});
+
+ it('checks canonical protagonist wardrobe and off-screen visual bindings', () => {
+ const review = analyzeEpisodeContinuity({
+ loom: {
+ participationMode: 'helper',
+ protagonistCharacterId: 'char-elena',
+ protagonistWardrobeId: 'wardrobe-explorer',
+ protagonistWardrobeLocked: true,
+ },
+ episode: {
+ id: 'ep-1',
+ startNodeId: 'node-1',
+ nodes: [
+ {
+ id: 'node-1',
+ title: 'Visible approach',
+ protagonistPresence: 'onscreen',
+ visualCanon: {
+ mode: 'locked',
+ characterAppearances: [{ characterId: 'char-elena', wardrobeId: 'wardrobe-gala' }],
+ },
+ transitions: [{ id: 'tr-1', targetNodeId: 'node-2', intent: 'Talk' }],
+ },
+ {
+ id: 'node-2',
+ title: 'Communicator decision',
+ playbackMode: 'decision',
+ audienceConnection: 'connected',
+ protagonistPresence: 'offscreen',
+ visualCanon: {
+ mode: 'locked',
+ characterAppearances: [{ characterId: 'char-elena', wardrobeId: 'wardrobe-explorer' }],
+ },
+ transitions: [],
+ },
+ ],
+ },
+ universe: sampleUniverse,
+ });
+
+ const codes = review.findings.map((finding) => finding.code);
+ expect(codes).toContain(CONTINUITY_CODES.CANONICAL_WARDROBE_DRIFT);
+ expect(codes).toContain(CONTINUITY_CODES.PROTAGONIST_VISUAL_BINDING_WHILE_OFFSCREEN);
+ });
+
+ it('flags live interaction that binds a different protagonist than the loom canon', () => {
+ const review = analyzeEpisodeContinuity({
+ loom: {
+ participationMode: 'helper',
+ protagonistCharacterId: 'char-elena',
+ },
+ episode: {
+ id: 'ep-1',
+ startNodeId: 'node-1',
+ nodes: [{
+ id: 'node-1',
+ title: 'Wrong communicator binding',
+ playbackMode: 'decision',
+ audienceConnection: 'connected',
+ interactionWindow: {
+ enabled: true,
+ protagonistCharacterId: 'char-other',
+ protagonistPresence: 'offscreen',
+ },
+ transitions: [],
+ }],
+ },
+ universe: sampleUniverse,
+ });
+
+ expect(review.findings.map((finding) => finding.code))
+ .toContain(CONTINUITY_CODES.PROTAGONIST_BINDING_MISMATCH);
+ });
});
diff --git a/server/lib/fableLoomGraph.js b/server/lib/fableLoomGraph.js
index 970d98ca70..6f7b549d33 100644
--- a/server/lib/fableLoomGraph.js
+++ b/server/lib/fableLoomGraph.js
@@ -210,6 +210,8 @@ export function describeGraphForPrompt(episode, {
participationMode === 'helper'
? (node?.audienceConnection === 'connected' ? 'AUDIENCE CONNECTED' : 'AUDIENCE DISCONNECTED')
: null,
+ node?.protagonistPresence === 'offscreen' ? 'PROTAGONIST OFF-SCREEN' : null,
+ node?.protagonistPresence === 'onscreen' ? 'PROTAGONIST ON-SCREEN' : null,
].filter(Boolean);
lines.push(`[${node.id}] ${node.title || 'Untitled scene'}${flags.length ? ` (${flags.join(') (')})` : ''}`);
const prose = typeof node.prose === 'string' ? node.prose.trim() : '';
diff --git a/server/lib/fableLoomLimits.js b/server/lib/fableLoomLimits.js
index 25f93a41c1..f47f2ee233 100644
--- a/server/lib/fableLoomLimits.js
+++ b/server/lib/fableLoomLimits.js
@@ -15,6 +15,13 @@ export const LOOM_LIMITS = Object.freeze({
PLAN_ITEMS_MAX: 50,
PLAN_ITEM_TITLE_MAX: 300,
PLAN_ITEM_DESCRIPTION_MAX: 4000,
+ DELIVERY_MESSAGE_MAX: 4000,
+ OUTLINE_SCENES_MAX: 200,
+ OUTLINE_KEY_MAX: 80,
+ OUTLINE_SUMMARY_MAX: 1200,
+ OUTLINE_TRANSITIONS_MAX: 12,
+ OUTLINE_ISSUES_MAX: 100,
+ OUTLINE_ISSUE_MESSAGE_MAX: 500,
REF_ID_MAX: 64,
EPISODES_MAX: 100,
EPISODE_TITLE_MAX: 300,
@@ -43,4 +50,3 @@ export const LOOM_LIMITS = Object.freeze({
AMBIENT_DUCK_DB_MAX: 0,
AMBIENT_DUCK_DB_DEFAULT: -8,
});
-
diff --git a/server/lib/fableLoomOutline.js b/server/lib/fableLoomOutline.js
new file mode 100644
index 0000000000..0c261a2f26
--- /dev/null
+++ b/server/lib/fableLoomOutline.js
@@ -0,0 +1,416 @@
+/**
+ * FableLoom episode beat outlines — the story-first contract between a
+ * series plan and a fully written teleplay.
+ *
+ * An outline is deliberately smaller than a scene graph: one short log-line
+ * per camera-cut beat, the intended audience contract, and the paths between
+ * beats. This module stays pure so the same deterministic checks can run
+ * before an outline is expanded and whenever an author edits it by hand.
+ */
+
+import { trimTo } from './storyBible.js';
+import { LOOM_LIMITS } from './fableLoomLimits.js';
+import { FABLELOOM_PROTAGONIST_PRESENCE } from './fableLoomPlayback.js';
+
+const asArray = (value) => (Array.isArray(value) ? value : []);
+const isObject = (value) => value && typeof value === 'object';
+const isText = (value) => typeof value === 'string' && value.trim().length > 0;
+
+export const OUTLINE_ISSUE_CODES = Object.freeze({
+ NO_SCENES: 'NO_SCENES',
+ MISSING_START: 'MISSING_START',
+ START_NOT_FOUND: 'START_NOT_FOUND',
+ NO_ENDINGS: 'NO_ENDINGS',
+ UNREACHABLE_SCENE: 'UNREACHABLE_SCENE',
+ DEAD_END: 'DEAD_END',
+ DANGLING_TRANSITION: 'DANGLING_TRANSITION',
+ SELF_LOOP: 'SELF_LOOP',
+ ENDING_WITH_TRANSITIONS: 'ENDING_WITH_TRANSITIONS',
+ EMPTY_SUMMARY: 'EMPTY_SUMMARY',
+ EMPTY_INTENT: 'EMPTY_INTENT',
+ DUPLICATE_INTENT: 'DUPLICATE_INTENT',
+ CUT_TRANSITION_COUNT: 'CUT_TRANSITION_COUNT',
+ DECISION_TRANSITION_COUNT: 'DECISION_TRANSITION_COUNT',
+ DISCONNECTED_DECISION: 'DISCONNECTED_DECISION',
+ NO_AUDIENCE_CONNECTION: 'NO_AUDIENCE_CONNECTION',
+ LATE_AUDIENCE_CONNECTION: 'LATE_AUDIENCE_CONNECTION',
+ MISSING_EPISODE_OUTLINE: 'MISSING_EPISODE_OUTLINE',
+ EPISODE_OUTLINE_NOT_VALIDATED: 'EPISODE_OUTLINE_NOT_VALIDATED',
+ MISSING_OVERNIGHT_VOICEMAIL: 'MISSING_OVERNIGHT_VOICEMAIL',
+ EMPTY_OVERNIGHT_VOICEMAIL: 'EMPTY_OVERNIGHT_VOICEMAIL',
+ MISSING_NEXT_SEASON_TEASER: 'MISSING_NEXT_SEASON_TEASER',
+});
+
+const OUTLINE_STATUSES = new Set(['draft', 'valid', 'invalid']);
+
+const uniqueKey = (candidate, index, seen) => {
+ const base = isText(candidate)
+ ? candidate.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
+ : `s${index + 1}`;
+ let key = base || `s${index + 1}`;
+ let suffix = 2;
+ while (seen.has(key)) {
+ const stem = base.slice(0, Math.max(1, LOOM_LIMITS.OUTLINE_KEY_MAX - String(suffix).length - 1));
+ key = `${stem}-${suffix}`;
+ suffix += 1;
+ }
+ seen.add(key);
+ return key;
+};
+
+const sanitizeValidation = (raw) => {
+ if (!isObject(raw)) return { status: 'draft', issues: [] };
+ const status = OUTLINE_STATUSES.has(raw.status) ? raw.status : 'draft';
+ const issues = asArray(raw.issues)
+ .filter(isObject)
+ .slice(0, LOOM_LIMITS.OUTLINE_ISSUES_MAX)
+ .map((issue) => ({
+ code: trimTo(issue.code, 80),
+ severity: issue.severity === 'warning' ? 'warning' : 'error',
+ message: trimTo(issue.message, LOOM_LIMITS.OUTLINE_ISSUE_MESSAGE_MAX),
+ ...(isText(issue.sceneKey) ? { sceneKey: issue.sceneKey.slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX) } : {}),
+ ...(Number.isInteger(issue.transitionIndex) && issue.transitionIndex >= 0
+ ? { transitionIndex: issue.transitionIndex }
+ : {}),
+ }))
+ .filter((issue) => issue.message);
+ return {
+ status,
+ issues,
+ ...(isText(raw.validatedAt) ? { validatedAt: raw.validatedAt.slice(0, 80) } : {}),
+ };
+};
+
+/**
+ * Normalize an AI- or author-provided outline into the bounded persisted
+ * shape. Unknown target keys are intentionally retained so validation can
+ * explain the broken edge instead of silently changing the author's arc.
+ */
+export function sanitizeStoryOutline(raw, { participationMode = 'protagonist' } = {}) {
+ if (!isObject(raw)) return null;
+ const rawScenes = asArray(raw.scenes).slice(0, LOOM_LIMITS.OUTLINE_SCENES_MAX);
+ const seen = new Set();
+ const keyByRawKey = new Map();
+ const scenes = rawScenes.map((scene, index) => {
+ const key = uniqueKey(scene?.key, index, seen);
+ if (isText(scene?.key) && !keyByRawKey.has(scene.key.trim())) keyByRawKey.set(scene.key.trim(), key);
+ const transitions = asArray(scene?.transitions)
+ .slice(0, LOOM_LIMITS.OUTLINE_TRANSITIONS_MAX)
+ .filter(isObject)
+ .map((transition) => ({
+ targetKey: isText(transition.targetKey)
+ ? transition.targetKey.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
+ : '',
+ intent: trimTo(transition.intent, LOOM_LIMITS.INTENT_MAX),
+ }));
+ return {
+ key,
+ title: trimTo(scene?.title, LOOM_LIMITS.NODE_TITLE_MAX),
+ summary: trimTo(scene?.summary, LOOM_LIMITS.OUTLINE_SUMMARY_MAX),
+ playbackMode: scene?.playbackMode === 'cut' ? 'cut' : 'decision',
+ audienceConnection: scene?.audienceConnection === 'connected' ? 'connected' : 'disconnected',
+ protagonistPresence: FABLELOOM_PROTAGONIST_PRESENCE.includes(scene?.protagonistPresence)
+ ? scene.protagonistPresence
+ : participationMode === 'helper'
+ && scene?.audienceConnection === 'connected'
+ && scene?.playbackMode !== 'cut'
+ ? 'offscreen'
+ : 'onscreen',
+ isEnding: scene?.isEnding === true,
+ endingLabel: trimTo(scene?.endingLabel, LOOM_LIMITS.ENDING_LABEL_MAX),
+ transitions,
+ };
+ });
+ const rawStart = isText(raw.startKey) ? raw.startKey.trim() : '';
+ const startKey = keyByRawKey.get(rawStart) || rawStart.slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX) || scenes[0]?.key || null;
+ return {
+ version: 1,
+ startKey,
+ scenes,
+ validation: sanitizeValidation(raw.validation),
+ };
+}
+
+const outlineIssue = (issues, code, severity, message, extra = {}) => {
+ issues.push({ code, severity, message, ...extra });
+};
+
+/** Deterministic validation for the log-line graph, independent of an LLM. */
+export function analyzeStoryOutline(outline, {
+ participationMode = 'protagonist', requireAudienceIntroduction = false,
+} = {}) {
+ const scenes = asArray(outline?.scenes);
+ const byKey = new Map(scenes.map((scene) => [scene.key, scene]));
+ const issues = [];
+ const push = (code, severity, message, extra = {}) => outlineIssue(issues, code, severity, message, extra);
+
+ if (!scenes.length) {
+ push(OUTLINE_ISSUE_CODES.NO_SCENES, 'error', 'The story outline has no scene beats yet.');
+ }
+ const startKey = outline?.startKey;
+ if (!isText(startKey)) {
+ if (scenes.length) push(OUTLINE_ISSUE_CODES.MISSING_START, 'error', 'The story outline has no opening beat.');
+ } else if (scenes.length && !byKey.has(startKey)) {
+ push(OUTLINE_ISSUE_CODES.START_NOT_FOUND, 'error', 'The opening beat points at a key that does not exist.');
+ }
+
+ const reachable = new Set();
+ const depthByKey = new Map();
+ if (byKey.has(startKey)) {
+ const queue = [startKey];
+ depthByKey.set(startKey, 0);
+ let cursor = 0;
+ while (cursor < queue.length) {
+ const key = queue[cursor];
+ cursor += 1;
+ if (reachable.has(key)) continue;
+ reachable.add(key);
+ for (const transition of asArray(byKey.get(key)?.transitions)) {
+ if (byKey.has(transition.targetKey) && !depthByKey.has(transition.targetKey)) {
+ depthByKey.set(transition.targetKey, depthByKey.get(key) + 1);
+ queue.push(transition.targetKey);
+ }
+ }
+ }
+ }
+
+ const endings = scenes.filter((scene) => scene.isEnding);
+ if (scenes.length && !endings.length) {
+ push(OUTLINE_ISSUE_CODES.NO_ENDINGS, 'error', 'The story outline has no ending beat.');
+ }
+ const reachableEndings = endings.filter((scene) => reachable.has(scene.key));
+ if (endings.length && !reachableEndings.length) {
+ push(OUTLINE_ISSUE_CODES.NO_ENDINGS, 'error', 'No ending beat is reachable from the opening.');
+ }
+
+ if (participationMode === 'helper' && requireAudienceIntroduction && scenes.length) {
+ const connected = scenes.filter((scene) => scene.audienceConnection === 'connected' && reachable.has(scene.key));
+ if (!connected.length) {
+ push(
+ OUTLINE_ISSUE_CODES.NO_AUDIENCE_CONNECTION,
+ 'error',
+ 'The outline never activates the audience communication channel.',
+ );
+ } else {
+ const firstDepth = Math.min(...connected.map((scene) => depthByKey.get(scene.key)));
+ if (firstDepth > 3) {
+ push(
+ OUTLINE_ISSUE_CODES.LATE_AUDIENCE_CONNECTION,
+ 'warning',
+ 'The audience communication channel is not activated until late in the opening sequence.',
+ { sceneKey: connected.find((scene) => depthByKey.get(scene.key) === firstDepth)?.key },
+ );
+ }
+ }
+ }
+
+ for (const scene of scenes) {
+ const transitions = asArray(scene.transitions);
+ const label = scene.title || scene.key || 'Untitled beat';
+ if (!isText(scene.summary)) {
+ push(OUTLINE_ISSUE_CODES.EMPTY_SUMMARY, 'error', `"${label}" has no scene log-line.`, { sceneKey: scene.key });
+ }
+ if (!reachable.has(scene.key)) {
+ push(OUTLINE_ISSUE_CODES.UNREACHABLE_SCENE, 'error', `"${label}" cannot be reached from the opening beat.`, { sceneKey: scene.key });
+ }
+ if (!scene.isEnding && !transitions.length) {
+ push(OUTLINE_ISSUE_CODES.DEAD_END, 'error', `"${label}" has no path to a later beat.`, { sceneKey: scene.key });
+ }
+ if (scene.isEnding && transitions.length) {
+ push(OUTLINE_ISSUE_CODES.ENDING_WITH_TRANSITIONS, 'error', `Ending "${label}" must not have outgoing paths.`, { sceneKey: scene.key });
+ }
+ if (!scene.isEnding && scene.playbackMode === 'cut' && transitions.length !== 1) {
+ push(
+ OUTLINE_ISSUE_CODES.CUT_TRANSITION_COUNT,
+ 'error',
+ `Automatic beat "${label}" must have exactly one next beat.`,
+ { sceneKey: scene.key },
+ );
+ }
+ if (!scene.isEnding && scene.playbackMode !== 'cut'
+ && (transitions.length < 2 || transitions.length > 4)) {
+ push(
+ OUTLINE_ISSUE_CODES.DECISION_TRANSITION_COUNT,
+ 'error',
+ `Decision beat "${label}" needs 2–4 distinct viewer paths.`,
+ { sceneKey: scene.key },
+ );
+ }
+ if (participationMode === 'helper' && !scene.isEnding
+ && scene.audienceConnection !== 'connected' && scene.playbackMode !== 'cut') {
+ push(
+ OUTLINE_ISSUE_CODES.DISCONNECTED_DECISION,
+ 'error',
+ `"${label}" asks for viewer input while the communication channel is disconnected.`,
+ { sceneKey: scene.key },
+ );
+ }
+
+ const seenIntents = new Set();
+ transitions.forEach((transition, transitionIndex) => {
+ const intent = isText(transition.intent) ? transition.intent.trim().toLowerCase() : '';
+ if (!intent) {
+ push(
+ OUTLINE_ISSUE_CODES.EMPTY_INTENT,
+ 'error',
+ `A path out of "${label}" has no choice label.`,
+ { sceneKey: scene.key, transitionIndex },
+ );
+ } else if (seenIntents.has(intent)) {
+ push(
+ OUTLINE_ISSUE_CODES.DUPLICATE_INTENT,
+ 'warning',
+ `"${label}" repeats the choice label "${transition.intent}".`,
+ { sceneKey: scene.key, transitionIndex },
+ );
+ } else {
+ seenIntents.add(intent);
+ }
+ if (!byKey.has(transition.targetKey)) {
+ push(
+ OUTLINE_ISSUE_CODES.DANGLING_TRANSITION,
+ 'error',
+ `A path out of "${label}" points at a missing beat.`,
+ { sceneKey: scene.key, transitionIndex },
+ );
+ } else if (transition.targetKey === scene.key) {
+ push(
+ OUTLINE_ISSUE_CODES.SELF_LOOP,
+ 'warning',
+ `"${label}" loops straight back to itself.`,
+ { sceneKey: scene.key, transitionIndex },
+ );
+ }
+ });
+ }
+
+ const stats = {
+ sceneCount: scenes.length,
+ automaticCutCount: scenes.filter((scene) => !scene.isEnding && scene.playbackMode === 'cut').length,
+ decisionCount: scenes.filter((scene) => !scene.isEnding && scene.playbackMode !== 'cut').length,
+ endingCount: endings.length,
+ reachableCount: reachable.size,
+ reachableEndingCount: reachableEndings.length,
+ maxDepth: depthByKey.size ? Math.max(...depthByKey.values()) : 0,
+ errorCount: issues.filter((issue) => issue.severity === 'error').length,
+ warningCount: issues.filter((issue) => issue.severity === 'warning').length,
+ };
+ return { issues, stats };
+}
+
+/**
+ * Validate outline coverage for the complete series. This is the hard gate
+ * used by teleplay expansion: authors can draft episodes in order, but no
+ * episode is expanded until the whole series has a validated beat arc and its
+ * optional delivery handoffs are authored.
+ */
+export function analyzeSeriesStoryOutlines(loom) {
+ const episodes = asArray(loom?.episodes);
+ const issues = [];
+ const push = (code, severity, message, extra = {}) => outlineIssue(issues, code, severity, message, extra);
+ const validVoicemails = new Map(asArray(loom?.seriesPlan?.interEpisodeVoicemails)
+ .filter((item) => item?.fromEpisodeId && item?.toEpisodeId)
+ .map((item) => [`${item.fromEpisodeId}::${item.toEpisodeId}`, item]));
+
+ episodes.forEach((episode, index) => {
+ if (!episode?.storyOutline) {
+ push(
+ OUTLINE_ISSUE_CODES.MISSING_EPISODE_OUTLINE,
+ 'error',
+ `Episode ${episode?.number || index + 1} has no beat outline yet.`,
+ { episodeId: episode?.id },
+ );
+ return;
+ }
+ const validation = analyzeStoryOutline(episode.storyOutline, {
+ participationMode: loom?.participationMode,
+ requireAudienceIntroduction: index === 0,
+ });
+ validation.issues.forEach((issue) => push(issue.code, issue.severity, `Episode ${episode.number || index + 1}: ${issue.message}`, {
+ episodeId: episode.id,
+ ...(issue.sceneKey ? { sceneKey: issue.sceneKey } : {}),
+ ...(Number.isInteger(issue.transitionIndex) ? { transitionIndex: issue.transitionIndex } : {}),
+ }));
+ if (episode.storyOutline.validation?.status !== 'valid') {
+ push(
+ OUTLINE_ISSUE_CODES.EPISODE_OUTLINE_NOT_VALIDATED,
+ 'error',
+ `Episode ${episode.number || index + 1}'s beat outline must be validated before teleplay expansion.`,
+ { episodeId: episode.id },
+ );
+ }
+ });
+
+ const delivery = loom?.seriesPlan?.deliveryOptions || {};
+ if (delivery.overnightVoicemails === true) {
+ episodes.slice(0, -1).forEach((fromEpisode, index) => {
+ const toEpisode = episodes[index + 1];
+ const key = `${fromEpisode.id}::${toEpisode.id}`;
+ const voicemail = validVoicemails.get(key);
+ if (!voicemail) {
+ push(
+ OUTLINE_ISSUE_CODES.MISSING_OVERNIGHT_VOICEMAIL,
+ 'error',
+ `The handoff from Episode ${fromEpisode.number} to Episode ${toEpisode.number} needs an overnight voicemail.`,
+ { episodeId: fromEpisode.id },
+ );
+ } else if (!isText(voicemail.transcript)) {
+ push(
+ OUTLINE_ISSUE_CODES.EMPTY_OVERNIGHT_VOICEMAIL,
+ 'error',
+ `The overnight voicemail from Episode ${fromEpisode.number} to Episode ${toEpisode.number} has no transcript.`,
+ { episodeId: fromEpisode.id },
+ );
+ }
+ });
+ }
+ if (delivery.nextSeasonTeaser === true && !isText(loom?.seriesPlan?.nextSeasonTeaser?.transcript)) {
+ push(
+ OUTLINE_ISSUE_CODES.MISSING_NEXT_SEASON_TEASER,
+ 'error',
+ 'The final episode needs a next-season teaser or cliffhanger transcript.',
+ { episodeId: episodes.at(-1)?.id },
+ );
+ }
+
+ const readyEpisodeCount = episodes.filter((episode) => episode.storyOutline?.validation?.status === 'valid').length;
+ return {
+ issues,
+ stats: {
+ episodeCount: episodes.length,
+ readyEpisodeCount,
+ errorCount: issues.filter((issue) => issue.severity === 'error').length,
+ warningCount: issues.filter((issue) => issue.severity === 'warning').length,
+ ready: episodes.length > 0 && issues.every((issue) => issue.severity !== 'error'),
+ },
+ };
+}
+
+export const outlineValidationStatus = (validation) => {
+ if (!validation?.stats) return 'draft';
+ return validation.stats.errorCount ? 'invalid' : 'valid';
+};
+
+/** Compact outline rendering for the outline-review and expansion prompts. */
+export function describeStoryOutlineForPrompt(outline) {
+ const scenes = asArray(outline?.scenes);
+ const byKey = new Map(scenes.map((scene) => [scene.key, scene]));
+ return scenes.map((scene, index) => {
+ const flags = [
+ scene.key === outline?.startKey ? 'START' : null,
+ scene.isEnding ? `ENDING${scene.endingLabel ? `: ${scene.endingLabel}` : ''}` : null,
+ scene.isEnding ? null : scene.playbackMode === 'cut' ? 'AUTO CUT' : 'DECISION',
+ scene.audienceConnection === 'connected' ? 'AUDIENCE CONNECTED' : 'AUDIENCE DISCONNECTED',
+ scene.protagonistPresence === 'offscreen' ? 'PROTAGONIST OFF-SCREEN' : 'PROTAGONIST ON-SCREEN',
+ ].filter(Boolean);
+ const paths = asArray(scene.transitions).map((transition) => {
+ const target = byKey.get(transition.targetKey);
+ return `-> [${transition.targetKey || '?'}] ${transition.intent || '(unlabeled)'}${target?.title ? ` (${target.title})` : ''}`;
+ });
+ return [
+ `${index + 1}. [${scene.key}] ${scene.title || 'Untitled beat'}${flags.length ? ` (${flags.join(') (')})` : ''}`,
+ scene.summary || '(no log-line)',
+ ...paths,
+ ].join('\n');
+ }).join('\n\n');
+}
diff --git a/server/lib/fableLoomOutline.test.js b/server/lib/fableLoomOutline.test.js
new file mode 100644
index 0000000000..80519dc0aa
--- /dev/null
+++ b/server/lib/fableLoomOutline.test.js
@@ -0,0 +1,130 @@
+import { describe, expect, it } from 'vitest';
+import {
+ analyzeSeriesStoryOutlines,
+ analyzeStoryOutline,
+ describeStoryOutlineForPrompt,
+ sanitizeStoryOutline,
+} from './fableLoomOutline.js';
+
+const validOutline = {
+ startKey: 's1',
+ scenes: [
+ {
+ key: 's1',
+ title: 'Signal',
+ summary: 'The protagonist catches a signal that proves the missing ship is still alive.',
+ playbackMode: 'cut',
+ audienceConnection: 'disconnected',
+ transitions: [{ targetKey: 's2', intent: 'follow the signal' }],
+ },
+ {
+ key: 's2',
+ title: 'The choice',
+ summary: 'The signal offers two routes, each demanding a different sacrifice.',
+ playbackMode: 'decision',
+ audienceConnection: 'connected',
+ transitions: [
+ { targetKey: 's3', intent: 'protect the survivors' },
+ { targetKey: 's4', intent: 'take the shortcut' },
+ ],
+ },
+ {
+ key: 's3',
+ title: 'A costly rescue',
+ summary: 'The rescue succeeds but strands the protagonist beyond the safe corridor.',
+ playbackMode: 'cut',
+ audienceConnection: 'connected',
+ isEnding: true,
+ endingLabel: 'The long way home',
+ transitions: [],
+ },
+ {
+ key: 's4',
+ title: 'The shortcut',
+ summary: 'The shortcut opens the corridor while leaving one unanswered voice behind.',
+ playbackMode: 'cut',
+ audienceConnection: 'connected',
+ isEnding: true,
+ endingLabel: 'The open door',
+ transitions: [],
+ },
+ ],
+};
+
+describe('FableLoom story beat outlines', () => {
+ it('accepts a reachable arc with real choices and distinct endings', () => {
+ const outline = sanitizeStoryOutline(validOutline);
+ const result = analyzeStoryOutline(outline, { participationMode: 'helper', requireAudienceIntroduction: true });
+
+ expect(result.issues).toEqual([]);
+ expect(result.stats).toMatchObject({
+ sceneCount: 4,
+ automaticCutCount: 1,
+ decisionCount: 1,
+ endingCount: 2,
+ reachableCount: 4,
+ reachableEndingCount: 2,
+ errorCount: 0,
+ });
+ });
+
+ it('surfaces missing summaries, unreachable beats, invalid paths, and disconnected choices', () => {
+ const outline = sanitizeStoryOutline({
+ startKey: 's1',
+ scenes: [
+ { key: 's1', title: 'Opening', playbackMode: 'cut', audienceConnection: 'disconnected', transitions: [{ targetKey: 's2', intent: 'continue' }] },
+ { key: 's2', title: 'Choice', summary: 'A choice.', playbackMode: 'decision', audienceConnection: 'disconnected', transitions: [{ targetKey: 'missing', intent: '' }] },
+ { key: 's3', title: 'Lost', summary: 'Never reached.', playbackMode: 'cut', isEnding: true },
+ ],
+ });
+ const result = analyzeStoryOutline(outline, { participationMode: 'helper', requireAudienceIntroduction: true });
+ const codes = result.issues.map((issue) => issue.code);
+
+ expect(codes).toEqual(expect.arrayContaining([
+ 'EMPTY_SUMMARY', 'DECISION_TRANSITION_COUNT', 'DISCONNECTED_DECISION',
+ 'EMPTY_INTENT', 'DANGLING_TRANSITION', 'UNREACHABLE_SCENE', 'NO_AUDIENCE_CONNECTION',
+ ]));
+ expect(result.stats.errorCount).toBeGreaterThan(0);
+ });
+
+ it('keeps outline rendering compact for the AI prompt', () => {
+ const outline = sanitizeStoryOutline(validOutline);
+ const digest = describeStoryOutlineForPrompt(outline);
+
+ expect(digest).toContain('[s1] Signal (START) (AUTO CUT)');
+ expect(digest).toContain('-> [s2] follow the signal (The choice)');
+ expect(digest).toContain('The shortcut opens the corridor');
+ });
+
+ it('defaults connected decision beats off-screen only for helper stories', () => {
+ const protagonistOutline = sanitizeStoryOutline(validOutline, { participationMode: 'protagonist' });
+ const helperOutline = sanitizeStoryOutline(validOutline, { participationMode: 'helper' });
+
+ expect(protagonistOutline.scenes.find((scene) => scene.key === 's2').protagonistPresence)
+ .toBe('onscreen');
+ expect(helperOutline.scenes.find((scene) => scene.key === 's2').protagonistPresence)
+ .toBe('offscreen');
+ });
+
+ it('requires every episode outline and configured delivery handoff before the series is ready', () => {
+ const loom = {
+ participationMode: 'protagonist',
+ episodes: [
+ { id: 'ep-1', number: 1, storyOutline: { ...sanitizeStoryOutline(validOutline), validation: { status: 'valid', issues: [] } } },
+ { id: 'ep-2', number: 2 },
+ ],
+ seriesPlan: {
+ deliveryOptions: { overnightVoicemails: true, nextSeasonTeaser: true },
+ interEpisodeVoicemails: [{ fromEpisodeId: 'ep-1', toEpisodeId: 'ep-2', transcript: '' }],
+ nextSeasonTeaser: { title: 'Beyond', transcript: '' },
+ },
+ };
+ const result = analyzeSeriesStoryOutlines(loom);
+ const codes = result.issues.map((issue) => issue.code);
+
+ expect(codes).toEqual(expect.arrayContaining([
+ 'MISSING_EPISODE_OUTLINE', 'EMPTY_OVERNIGHT_VOICEMAIL', 'MISSING_NEXT_SEASON_TEASER',
+ ]));
+ expect(result.stats.ready).toBe(false);
+ });
+});
diff --git a/server/lib/fableLoomPlayback.js b/server/lib/fableLoomPlayback.js
index 9d19f0316c..b78cc34068 100644
--- a/server/lib/fableLoomPlayback.js
+++ b/server/lib/fableLoomPlayback.js
@@ -17,6 +17,29 @@ export const FABLELOOM_PLAYBACK_PHASES = Object.freeze(['entry', 'hold', 'exit',
export const FABLELOOM_PROTAGONIST_PRESENCE = Object.freeze(['offscreen', 'onscreen']);
export const FABLELOOM_PROTAGONIST_PRESENCE_DEFAULT = 'offscreen';
+/**
+ * Resolve the visual presence contract for one scene. Explicit live-window
+ * presence wins because hosted playback must obey that safety setting. Helper
+ * decision scenes default to an off-screen audience conversation; a loom with
+ * a canonical protagonist defaults other scenes to on-screen until the author
+ * marks them otherwise.
+ */
+export const resolveFableLoomProtagonistPresence = (node, loom = null) => {
+ if (node?.interactionWindow?.enabled
+ && FABLELOOM_PROTAGONIST_PRESENCE.includes(node.interactionWindow.protagonistPresence)) {
+ return node.interactionWindow.protagonistPresence;
+ }
+ if (FABLELOOM_PROTAGONIST_PRESENCE.includes(node?.protagonistPresence)) {
+ return node.protagonistPresence;
+ }
+ if (loom?.participationMode === 'helper'
+ && node?.playbackMode === 'decision'
+ && node?.audienceConnection === 'connected') {
+ return 'offscreen';
+ }
+ return loom?.protagonistCharacterId ? 'onscreen' : null;
+};
+
export const FABLELOOM_AUDIO_TARGETS = Object.freeze(['host', 'audience']);
export const FABLELOOM_AUDIO_TARGET_DEFAULT = 'host';
@@ -133,6 +156,16 @@ export function sanitizeVisualConditioning(raw) {
const nullableRef = (value) => (isStr(value) ? trimTo(value, LOOM_LIMITS.REF_ID_MAX) : null);
const capability = raw.capability && typeof raw.capability === 'object' ? raw.capability : {};
const bindings = raw.bindings && typeof raw.bindings === 'object' ? raw.bindings : {};
+ const protagonistBinding = bindings.protagonist && typeof bindings.protagonist === 'object'
+ && nullableRef(bindings.protagonist.characterId)
+ ? {
+ characterId: nullableRef(bindings.protagonist.characterId),
+ wardrobeId: nullableRef(bindings.protagonist.wardrobeId),
+ presence: FABLELOOM_PROTAGONIST_PRESENCE.includes(bindings.protagonist.presence)
+ ? bindings.protagonist.presence
+ : null,
+ }
+ : null;
const productionParameters = raw.render?.parameters && typeof raw.render.parameters === 'object'
? Object.fromEntries(Object.entries(raw.render.parameters).flatMap(([key, value]) => {
if (!SAFE_PRODUCTION_PARAMETER_KEYS.has(key)) return [];
@@ -181,6 +214,7 @@ export function sanitizeVisualConditioning(raw) {
placeId: nullableRef(bindings.placeId),
objectIds: list(bindings.objectIds, LOOM_LIMITS.VISUAL_BINDINGS_MAX)
.map(nullableRef).filter(Boolean),
+ ...(protagonistBinding ? { protagonist: protagonistBinding } : {}),
},
assets: list(raw.assets, LOOM_LIMITS.VISUAL_PROVENANCE_ASSETS_MAX)
.filter((item) => item && typeof item === 'object')
diff --git a/server/lib/fableLoomPlayback.test.js b/server/lib/fableLoomPlayback.test.js
index 6bb40a79e7..c912f0f9f7 100644
--- a/server/lib/fableLoomPlayback.test.js
+++ b/server/lib/fableLoomPlayback.test.js
@@ -14,6 +14,7 @@ import {
isFableLoomPlaybackMode,
muxAudioTracks,
resolvePlaybackPhaseAsset,
+ resolveFableLoomProtagonistPresence,
sanitizeAudioInterval,
sanitizeAudioOccupancy,
sanitizeInteractionWindow,
@@ -38,6 +39,19 @@ describe('FableLoom playback modes and vocabulary', () => {
expect(FABLELOOM_AUDIO_TARGETS).toEqual(['host', 'audience']);
expect(FABLELOOM_HOLD_ROTATION_MODES).toEqual(['deterministic', 'shuffle', 'sequential']);
});
+
+ it('defaults helper connected decisions off-screen while keeping other canonical scenes visible', () => {
+ const loom = { participationMode: 'helper', protagonistCharacterId: 'char-elena' };
+ expect(resolveFableLoomProtagonistPresence({
+ playbackMode: 'decision', audienceConnection: 'connected',
+ }, loom)).toBe('offscreen');
+ expect(resolveFableLoomProtagonistPresence({
+ playbackMode: 'cut', audienceConnection: 'disconnected',
+ }, loom)).toBe('onscreen');
+ expect(resolveFableLoomProtagonistPresence({
+ playbackMode: 'decision', audienceConnection: 'connected', protagonistPresence: 'onscreen',
+ }, loom)).toBe('onscreen');
+ });
});
describe('FableLoom audio occupancy and validation', () => {
diff --git a/server/lib/fableLoomProduction.js b/server/lib/fableLoomProduction.js
index 2334681d1b..8cf37a8d35 100644
--- a/server/lib/fableLoomProduction.js
+++ b/server/lib/fableLoomProduction.js
@@ -91,6 +91,80 @@ export function computeTopologicalNodeOrder(episode) {
};
}
+/**
+ * Keep episodic storyboard production in narrative order. A later episode may
+ * be planned at any time, but it cannot start rendering until every reachable
+ * scene in the preceding episodes has a still that can serve as the visual
+ * continuity baseline for the next production pass.
+ *
+ * The check intentionally follows the loom's episode array (the same ordered
+ * sequence used by the player and series plan), not numeric labels that an
+ * author may have edited independently.
+ */
+export function inspectEpisodeProductionOrder(loom, episode) {
+ const episodes = Array.isArray(loom?.episodes) ? loom.episodes : [];
+ const currentIndex = episodes.findIndex((candidate) => candidate?.id === episode?.id);
+ if (currentIndex < 0) {
+ return {
+ ready: false,
+ currentEpisodeId: episode?.id || null,
+ currentEpisodeNumber: episode?.number || null,
+ previousEpisodeCount: 0,
+ blockedBy: [],
+ missingScenes: [],
+ reason: 'The selected episode is not present in the loom episode order.',
+ };
+ }
+
+ const missingScenes = [];
+ const blockedBy = [];
+ for (const [index, priorEpisode] of episodes.slice(0, currentIndex).entries()) {
+ const { orderedNodes } = computeTopologicalNodeOrder(priorEpisode);
+ if (!orderedNodes.length) {
+ blockedBy.push({
+ episodeId: priorEpisode.id,
+ episodeNumber: priorEpisode.number || index + 1,
+ episodeTitle: priorEpisode.title || `Episode ${priorEpisode.number || index + 1}`,
+ reason: 'no-reachable-scenes',
+ });
+ continue;
+ }
+ for (const node of orderedNodes) {
+ if (isStr(node.image)) continue;
+ const missing = {
+ episodeId: priorEpisode.id,
+ episodeNumber: priorEpisode.number || index + 1,
+ episodeTitle: priorEpisode.title || `Episode ${priorEpisode.number || index + 1}`,
+ nodeId: node.id,
+ nodeTitle: node.title || node.id,
+ };
+ missingScenes.push(missing);
+ if (!blockedBy.some((item) => item.episodeId === priorEpisode.id)) {
+ blockedBy.push({
+ episodeId: priorEpisode.id,
+ episodeNumber: missing.episodeNumber,
+ episodeTitle: missing.episodeTitle,
+ reason: 'missing-storyboard-images',
+ });
+ }
+ }
+ }
+
+ const currentEpisodeNumber = episode.number || currentIndex + 1;
+ const firstBlocker = blockedBy[0];
+ return {
+ ready: blockedBy.length === 0,
+ currentEpisodeId: episode.id,
+ currentEpisodeNumber,
+ previousEpisodeCount: currentIndex,
+ blockedBy,
+ missingScenes,
+ reason: firstBlocker
+ ? `Finish storyboard images for Episode ${firstBlocker.episodeNumber} before generating Episode ${currentEpisodeNumber}.`
+ : `Episode ${currentEpisodeNumber} is next in the ordered storyboard production sequence.`,
+ };
+}
+
/**
* Verify recorded asset provenance against the current local environment.
* For `exact_inputs` mode: refuses when a recorded revision/hash/model is missing
@@ -376,10 +450,24 @@ export function buildEpisodeProductionPlan({
const lockedCanon = isLockedCanon(node);
const universeCharacters = Array.isArray(universe?.characters) ? universe.characters : [];
const characterById = new Map(universeCharacters.map((character) => [character.id, character]));
+ const canonicalProtagonistId = isStr(loom?.protagonistCharacterId)
+ ? loom.protagonistCharacterId
+ : null;
+ const canonicalProtagonist = canonicalProtagonistId
+ ? characterById.get(canonicalProtagonistId)
+ : null;
if (lockedCanon && !universe) {
nodeBlockers.push('Locked visual canon cannot be resolved because its Universe is unavailable.');
}
+ if (canonicalProtagonistId && !universe) {
+ nodeBlockers.push('The canonical protagonist cannot be resolved because the linked Universe is unavailable.');
+ } else if (canonicalProtagonistId && !canonicalProtagonist) {
+ nodeBlockers.push(`Canonical protagonist "${canonicalProtagonistId}" is not present in the linked Universe.`);
+ } else if (canonicalProtagonist?.id && loom.protagonistWardrobeId
+ && !canonicalProtagonist.wardrobes?.some((wardrobe) => wardrobe.id === loom.protagonistWardrobeId)) {
+ nodeBlockers.push(`Canonical wardrobe "${loom.protagonistWardrobeId}" is not present on protagonist "${canonicalProtagonistId}".`);
+ }
if (visualCanon && universe) {
for (const appearance of (Array.isArray(visualCanon.characterAppearances)
? visualCanon.characterAppearances
@@ -485,6 +573,9 @@ export function buildEpisodeProductionPlan({
} else if (!universe || !interactionCharacter) {
nodeBlockers.push(`Live interaction protagonist "${interactionCharacterId}" is not present in the linked Universe.`);
}
+ if (canonicalProtagonistId && interactionCharacterId && interactionCharacterId !== canonicalProtagonistId) {
+ nodeBlockers.push(`Live interaction protagonist "${interactionCharacterId}" differs from the loom's canonical protagonist "${canonicalProtagonistId}".`);
+ }
const approvedProfile = localVoiceProfiles?.find((profile) => (
profile.binding?.characterId === interactionCharacterId
diff --git a/server/lib/fableLoomProduction.test.js b/server/lib/fableLoomProduction.test.js
index a023036136..f11fa6b19c 100644
--- a/server/lib/fableLoomProduction.test.js
+++ b/server/lib/fableLoomProduction.test.js
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
buildEpisodeProductionPlan,
computeTopologicalNodeOrder,
+ inspectEpisodeProductionOrder,
verifyExactInputProvenance,
} from './fableLoomProduction.js';
@@ -71,6 +72,35 @@ describe('fableLoomProduction', () => {
expect(topo.unreachableNodeIds.has('node-unreachable')).toBe(true);
});
+ it('requires prior episodes to have reachable storyboard images before production', () => {
+ const firstEpisode = {
+ id: 'ep-1', number: 1, startNodeId: 'first-node', nodes: [
+ { id: 'first-node', title: 'First image', image: 'first.png', isEnding: true, transitions: [] },
+ ],
+ };
+ const secondEpisode = {
+ id: 'ep-2', number: 2, startNodeId: 'second-node', nodes: [
+ { id: 'second-node', title: 'Second image', transitions: [] },
+ ],
+ };
+ const loom = { episodes: [firstEpisode, secondEpisode] };
+
+ expect(inspectEpisodeProductionOrder(loom, firstEpisode)).toMatchObject({
+ ready: true, previousEpisodeCount: 0,
+ });
+ expect(inspectEpisodeProductionOrder(loom, secondEpisode)).toMatchObject({
+ ready: true, previousEpisodeCount: 1,
+ });
+
+ firstEpisode.nodes[0].image = '';
+ const blocked = inspectEpisodeProductionOrder(loom, secondEpisode);
+ expect(blocked.ready).toBe(false);
+ expect(blocked.reason).toContain('Episode 1');
+ expect(blocked.missingScenes).toEqual([
+ expect.objectContaining({ episodeId: 'ep-1', nodeId: 'first-node' }),
+ ]);
+ });
+
it('builds comprehensive episode production plan with assets and dependencies', () => {
const plan = buildEpisodeProductionPlan({
episode: sampleEpisode,
@@ -108,6 +138,20 @@ describe('fableLoomProduction', () => {
expect(videoStage.stageIndex).toBeGreaterThan(stillStage.stageIndex);
});
+ it('blocks production when the canonical protagonist cannot resolve in the linked Universe', () => {
+ const plan = buildEpisodeProductionPlan({
+ episode: sampleEpisode,
+ loom: { id: 'loom-1', protagonistCharacterId: 'char-elena' },
+ universe: { id: 'universe-1', characters: [] },
+ });
+
+ expect(plan.isFullyReady).toBe(false);
+ expect(plan.plannedAssets
+ .filter((asset) => asset.status === 'blocked')
+ .some((asset) => asset.readiness.reasons.some((reason) => /canonical protagonist/i.test(reason))))
+ .toBe(true);
+ });
+
it('refuses exact-input planning when a node has no recorded provenance', () => {
const plan = buildEpisodeProductionPlan({
episode: sampleEpisode,
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
index da9897b0b6..9dc935bdc5 100644
--- a/server/lib/fableLoomValidation.js
+++ b/server/lib/fableLoomValidation.js
@@ -62,8 +62,57 @@ const seriesPlan = z.object({
startEpisodeId: planEpisodeId,
endEpisodeId: planEpisodeId,
})).max(LOOM_LIMITS.PLAN_ITEMS_MAX),
+ deliveryOptions: z.object({
+ overnightVoicemails: z.boolean().optional(),
+ nextSeasonTeaser: z.boolean().optional(),
+ }).optional(),
+ interEpisodeVoicemails: z.array(z.object({
+ id: planItemId,
+ fromEpisodeId: planEpisodeId,
+ toEpisodeId: planEpisodeId,
+ title: z.string().max(LOOM_LIMITS.PLAN_ITEM_TITLE_MAX),
+ transcript: z.string().max(LOOM_LIMITS.DELIVERY_MESSAGE_MAX),
+ })).max(LOOM_LIMITS.EPISODES_MAX).optional(),
+ nextSeasonTeaser: z.object({
+ title: z.string().max(LOOM_LIMITS.PLAN_ITEM_TITLE_MAX),
+ transcript: z.string().max(LOOM_LIMITS.DELIVERY_MESSAGE_MAX),
+ }).nullable().optional(),
});
+const outlineTransitionSchema = z.object({
+ targetKey: z.string().max(LOOM_LIMITS.OUTLINE_KEY_MAX),
+ intent: z.string().max(LOOM_LIMITS.INTENT_MAX),
+});
+
+const outlineValidationSchema = z.object({
+ status: z.enum(['draft', 'valid', 'invalid']).optional(),
+ issues: z.array(z.object({
+ code: z.string().max(80).optional(),
+ severity: z.enum(['error', 'warning']).optional(),
+ message: z.string().max(LOOM_LIMITS.OUTLINE_ISSUE_MESSAGE_MAX),
+ sceneKey: z.string().max(LOOM_LIMITS.OUTLINE_KEY_MAX).optional(),
+ transitionIndex: z.number().int().min(0).optional(),
+ })).max(LOOM_LIMITS.OUTLINE_ISSUES_MAX).optional(),
+ validatedAt: z.string().max(80).optional(),
+}).optional();
+
+const storyOutline = z.object({
+ version: z.number().int().min(1).max(1).optional(),
+ startKey: z.string().max(LOOM_LIMITS.OUTLINE_KEY_MAX).nullable().optional(),
+ scenes: z.array(z.object({
+ key: z.string().max(LOOM_LIMITS.OUTLINE_KEY_MAX),
+ title: z.string().max(LOOM_LIMITS.NODE_TITLE_MAX).optional(),
+ summary: z.string().max(LOOM_LIMITS.OUTLINE_SUMMARY_MAX).optional(),
+ playbackMode: z.enum(['cut', 'decision']).optional(),
+ audienceConnection: z.enum(['connected', 'disconnected']).optional(),
+ protagonistPresence: z.enum(FABLELOOM_PROTAGONIST_PRESENCE).optional(),
+ isEnding: z.boolean().optional(),
+ endingLabel: z.string().max(LOOM_LIMITS.ENDING_LABEL_MAX).optional(),
+ transitions: z.array(outlineTransitionSchema).max(LOOM_LIMITS.OUTLINE_TRANSITIONS_MAX).optional(),
+ })).max(LOOM_LIMITS.OUTLINE_SCENES_MAX),
+ validation: outlineValidationSchema,
+}).nullable().optional();
+
// Index filter. `?seriesId=` scopes the list to the looms soft-linked to one
// pipeline series (the series detail page's "Branching narratives" card). An
// empty value is a no-op filter, not a 400 — a UI that builds the query from a
@@ -82,6 +131,9 @@ export const loomCreateSchema = z.object({
format: format.optional(),
playSettings: playSettings.optional(),
seriesPlan: seriesPlan.optional(),
+ protagonistCharacterId: refId.optional(),
+ protagonistWardrobeId: refId.optional(),
+ protagonistWardrobeLocked: z.boolean().optional(),
universeId: refId.optional(),
seriesId: refId.optional(),
});
@@ -96,6 +148,9 @@ export const loomPatchSchema = z.object({
format: format.optional(),
playSettings: playSettings.optional(),
seriesPlan: seriesPlan.optional(),
+ protagonistCharacterId: refId.optional(),
+ protagonistWardrobeId: refId.optional(),
+ protagonistWardrobeLocked: z.boolean().optional(),
universeId: refId.optional(),
seriesId: refId.optional(),
});
@@ -110,6 +165,7 @@ export const episodePatchSchema = z.object({
synopsis: synopsis.optional(),
number: z.number().int().min(1).max(9999).optional(),
startNodeId: nodeIdStr.nullable().optional(),
+ storyOutline,
});
const transitionFields = {
@@ -204,6 +260,7 @@ const nodeFields = {
visualCanon: visualCanonSchema.optional(),
playbackMode: z.enum(FABLELOOM_PLAYBACK_MODES).optional(),
audienceConnection: z.enum(FABLELOOM_AUDIENCE_CONNECTION_STATES).optional(),
+ protagonistPresence: z.enum(FABLELOOM_PROTAGONIST_PRESENCE).nullable().optional(),
videoHistoryId: z.string().max(200).nullable().optional(),
playbackAssets: playbackAssetsSchema.optional(),
interactionWindow: interactionWindowSchema.optional(),
@@ -229,9 +286,19 @@ const aiRunFields = { ...llmPickFields, operationId: z.string().uuid().optional(
export const weaveSchema = z.object({
guidance: z.string().max(4000).optional(),
replace: z.boolean().optional(),
+ expandFromOutline: z.boolean().optional(),
+ ...aiRunFields,
+});
+
+export const outlineGenerateSchema = z.object({
+ guidance: z.string().max(4000).optional(),
...aiRunFields,
});
+export const outlineReviewSchema = z.object({ ...aiRunFields });
+
+export const outlineValidateSchema = z.object({});
+
export const branchSchema = z.object({
guidance: z.string().max(4000).optional(),
branchCount: z.number().int().min(1).max(4).optional(),
diff --git a/server/lib/index.js b/server/lib/index.js
index 3bf5fd6aa8..8aab3fe517 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -88,6 +88,7 @@ export * from './fableLoomLimits.js';
export * from './fableLoomFormats.js';
export * from './fableLoomProduction.js';
export * from './fableLoomContinuity.js';
+export * from './fableLoomOutline.js';
export * from './scenePrompt.js';
export * from './proseExportSettings.js';
export * from './shotGrammar.js';
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
index 165d867134..e51ff4fd24 100644
--- a/server/lib/promptStageCallSites.generated.json
+++ b/server/lib/promptStageCallSites.generated.json
@@ -43,6 +43,9 @@
"fableloom-generate-series-plan": [
"server/services/fableLoom/weave.js"
],
+ "fableloom-outline-episode": [
+ "server/services/fableLoom/weave.js"
+ ],
"fableloom-play-turn": [
"server/services/fableLoom/weave.js"
],
@@ -52,9 +55,15 @@
"fableloom-review": [
"server/services/fableLoom/weave.js"
],
+ "fableloom-review-episode-outline": [
+ "server/services/fableLoom/weave.js"
+ ],
"fableloom-review-series-plan": [
"server/services/fableLoom/weave.js"
],
+ "fableloom-review-series-teleplay": [
+ "server/services/fableLoom/weave.js"
+ ],
"fableloom-weave-episode": [
"server/services/fableLoom/weave.js"
],
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index e2e71fd910..491a0e8e0c 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -360,7 +360,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v3 = typed playback assets retain one visual-conditioning manifest per
// rendered clip, so entry/hold/exit provenance cannot overwrite each other.
// A v2 peer would strip that map during whole-record LWW.
- fableLoom: 3,
+ // v4 = the loom pins one canonical protagonist and wardrobe, while each
+ // scene records whether that protagonist is on-screen or speaking through a
+ // side-device off-screen. A v3 peer would silently strip those fields on a
+ // whole-record round trip and could restore wardrobe drift or put a removed
+ // protagonist back into a scene.
+ fableLoom: 4,
// v1 = Creative Director projects (PostgreSQL `creative_director_projects`)
// federated via the per-record peer-sync push pipeline (record kind
// `creativeDirectorProject`, sync category `creativeDirectorProjects`, #1564).
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index fd17a56150..df379bc35a 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -42,6 +42,12 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
expect(PORTOS_SCHEMA_VERSIONS.mediaCollections).toBe(1);
});
+ it('version-gates the canonical FableLoom protagonist continuity shape', () => {
+ // v4 adds the loom-level protagonist/wardrobe pin and per-scene presence;
+ // migration 319 upgrades the shipped prompt contract alongside it.
+ expect(PORTOS_SCHEMA_VERSIONS.fableLoom).toBe(4);
+ });
+
it('version-gates the additive Creative Commission taste brief shape', () => {
expect(PORTOS_SCHEMA_VERSIONS.creativeCommissions).toBe(4);
});
diff --git a/server/lib/socketEventCatalog.generated.json b/server/lib/socketEventCatalog.generated.json
index 6ed40dc3e7..5e9613cee1 100644
--- a/server/lib/socketEventCatalog.generated.json
+++ b/server/lib/socketEventCatalog.generated.json
@@ -2261,7 +2261,7 @@
{
"direction": "server-to-client",
"source": "client/src/components/fableloom/LoomPlayPanel.jsx",
- "line": 101
+ "line": 114
}
]
},
@@ -2300,7 +2300,7 @@
{
"direction": "server-to-client",
"source": "client/src/components/fableloom/LoomPlayPanel.jsx",
- "line": 132
+ "line": 145
}
]
},
@@ -2339,7 +2339,7 @@
{
"direction": "server-to-client",
"source": "client/src/components/fableloom/LoomPlayPanel.jsx",
- "line": 124
+ "line": 137
}
]
},
@@ -2365,7 +2365,7 @@
{
"direction": "server-to-client",
"source": "client/src/components/fableloom/LoomPlayPanel.jsx",
- "line": 105
+ "line": 118
}
]
},
@@ -2396,7 +2396,7 @@
{
"direction": "server-to-client",
"source": "client/src/components/fableloom/LoomPlayPanel.jsx",
- "line": 109
+ "line": 122
}
]
},
@@ -2409,7 +2409,7 @@
{
"direction": "server-to-client",
"source": "client/src/components/fableloom/LoomPlayPanel.jsx",
- "line": 113
+ "line": 126
}
]
},
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
index 0b3c262c60..43f6604506 100644
--- a/server/routes/fableLoom.js
+++ b/server/routes/fableLoom.js
@@ -21,6 +21,9 @@ import {
loomPatchSchema,
nodeCreateSchema,
nodePatchSchema,
+ outlineGenerateSchema,
+ outlineReviewSchema,
+ outlineValidateSchema,
playTurnSchema,
reformatSchema,
reviewSchema,
@@ -37,6 +40,7 @@ import {
continuityReviewSchema,
} from '../lib/fableLoomValidation.js';
import { analyzeEpisodeGraph } from '../lib/fableLoomGraph.js';
+import { analyzeSeriesStoryOutlines } from '../lib/fableLoomOutline.js';
import {
inspectEpisodeProductionReadiness,
inspectNodeProductionReadiness,
@@ -58,6 +62,7 @@ import {
endHostedSession,
feedbackEpisode,
feedbackSeriesPlan,
+ generateEpisodeOutline,
generateSeriesPlan,
getEpisodeProductionBatch,
getHostedSession,
@@ -67,15 +72,18 @@ import {
playTurn,
reformatEpisodeScenes,
reviewEpisode,
+ reviewEpisodeOutline,
reviewEpisodeContinuity,
resumeEpisodeProductionBatch,
reviewSeriesPlan,
+ reviewSeriesTeleplay,
startEpisodeProductionBatch,
updateEpisode,
updateHostedSession,
updateLoom,
updateNode,
updateNodeTransition,
+ validateEpisodeOutline,
weaveEpisode,
} from '../services/fableLoom/index.js';
@@ -126,6 +134,11 @@ router.post('/:id/plan/review', asyncHandler(async (req, res) => {
res.json(await reviewSeriesPlan(req.params.id, input));
}));
+router.post('/:id/review-teleplay', asyncHandler(async (req, res) => {
+ const input = validateRequest(reviewSchema, req.body);
+ res.json(await reviewSeriesTeleplay(req.params.id, input));
+}));
+
router.post('/:id/plan/feedback', asyncHandler(async (req, res) => {
const input = validateRequest(seriesPlanFeedbackSchema, req.body);
res.json(await feedbackSeriesPlan(req.params.id, input));
@@ -148,6 +161,12 @@ router.delete('/:id/episodes/:episodeId', asyncHandler(async (req, res) => {
}));
// Deterministic graph validation and production readiness — no LLM.
+router.get('/:id/outlines/validate', asyncHandler(async (req, res) => {
+ const loom = await getLoom(req.params.id);
+ if (!loom) throw new ServerError('Loom not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(analyzeSeriesStoryOutlines(loom));
+}));
+
router.get('/:id/episodes/:episodeId/validate', asyncHandler(async (req, res) => {
const loom = await getLoom(req.params.id);
const episode = loom?.episodes.find((e) => e.id === req.params.episodeId);
@@ -223,6 +242,24 @@ router.post('/:id/episodes/:episodeId/weave', asyncHandler(async (req, res) => {
res.json(await weaveEpisode(req.params.id, req.params.episodeId, input));
}));
+// Story-first authoring: draft and review the small beat outline before the
+// full teleplay graph is expanded. Validation is deterministic and persisted
+// so the expansion button can enforce the same gate from every client.
+router.post('/:id/episodes/:episodeId/outline/generate', asyncHandler(async (req, res) => {
+ const input = validateRequest(outlineGenerateSchema, req.body);
+ res.json(await generateEpisodeOutline(req.params.id, req.params.episodeId, input));
+}));
+
+router.post('/:id/episodes/:episodeId/outline/validate', asyncHandler(async (req, res) => {
+ validateRequest(outlineValidateSchema, req.body ?? {});
+ res.json(await validateEpisodeOutline(req.params.id, req.params.episodeId));
+}));
+
+router.post('/:id/episodes/:episodeId/outline/review', asyncHandler(async (req, res) => {
+ const input = validateRequest(outlineReviewSchema, req.body);
+ res.json(await reviewEpisodeOutline(req.params.id, req.params.episodeId, input));
+}));
+
router.post('/:id/episodes/:episodeId/nodes/:nodeId/branch', asyncHandler(async (req, res) => {
const input = validateRequest(branchSchema, req.body);
res.json(await branchNode(req.params.id, req.params.episodeId, req.params.nodeId, input));
diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.js
index dd268f54d7..4035ad673f 100644
--- a/server/routes/fableLoom.test.js
+++ b/server/routes/fableLoom.test.js
@@ -15,17 +15,21 @@ vi.mock('../services/fableLoom/index.js', () => ({
deleteNodeTransition: vi.fn(),
feedbackEpisode: vi.fn(),
feedbackSeriesPlan: vi.fn(),
+ generateEpisodeOutline: vi.fn(),
generateSeriesPlan: vi.fn(),
getLoom: vi.fn(),
listLoomSummaries: vi.fn(async () => []),
playTurn: vi.fn(),
reformatEpisodeScenes: vi.fn(),
reviewEpisode: vi.fn(),
+ reviewEpisodeOutline: vi.fn(),
reviewSeriesPlan: vi.fn(),
+ reviewSeriesTeleplay: vi.fn(),
updateEpisode: vi.fn(),
updateLoom: vi.fn(),
updateNode: vi.fn(),
updateNodeTransition: vi.fn(),
+ validateEpisodeOutline: vi.fn(),
weaveEpisode: vi.fn(),
checkHostedSessionReadiness: vi.fn(),
createHostedSession: vi.fn(),
@@ -138,6 +142,17 @@ describe('FableLoom routes', () => {
expect(fableLoom.feedbackSeriesPlan).toHaveBeenCalledTimes(1);
});
+ it('reviews the complete expanded teleplay through the series route', async () => {
+ fableLoom.reviewSeriesTeleplay.mockResolvedValueOnce({ analysis: { summary: 'The season holds together.' } });
+ const response = await request(makeApp())
+ .post('/api/fableloom/loom-1/review-teleplay')
+ .send({ providerId: 'writer', effort: 'high' });
+ expect(response.status).toBe(200);
+ expect(fableLoom.reviewSeriesTeleplay).toHaveBeenCalledWith('loom-1', {
+ providerId: 'writer', effort: 'high',
+ });
+ });
+
it('validates and forwards structured series-plan patches', async () => {
const seriesPlan = {
storyArc: 'A courier becomes a leader.',
@@ -232,6 +247,13 @@ describe('FableLoom routes', () => {
expect(response.body.issues).toEqual([]);
});
+ it('GET /outlines/validate reports whether the complete series beat arc is ready', async () => {
+ fableLoom.getLoom.mockResolvedValueOnce({ id: 'loom-1', episodes: [] });
+ const response = await request(makeApp()).get('/api/fableloom/loom-1/outlines/validate');
+ expect(response.status).toBe(200);
+ expect(response.body.stats.ready).toBe(false);
+ });
+
it('POST weave ignores legacy count hints and forwards current options', async () => {
fableLoom.weaveEpisode.mockResolvedValueOnce({ loom: { id: 'loom-1' }, runId: 'r' });
const ok = await request(makeApp())
@@ -241,6 +263,31 @@ describe('FableLoom routes', () => {
expect(fableLoom.weaveEpisode).toHaveBeenCalledWith('loom-1', 'ep-1', { guidance: 'darker', replace: true });
});
+ it('plans, validates, and reviews an episode outline before expansion', async () => {
+ fableLoom.generateEpisodeOutline.mockResolvedValueOnce({ outline: { scenes: [] }, runId: 'outline-run' });
+ const generated = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/outline/generate')
+ .send({ guidance: 'Keep the turn costly.', providerId: 'writer', model: 'large' });
+ expect(generated.status).toBe(200);
+ expect(fableLoom.generateEpisodeOutline).toHaveBeenCalledWith('loom-1', 'ep-1', {
+ guidance: 'Keep the turn costly.', providerId: 'writer', model: 'large',
+ });
+
+ fableLoom.validateEpisodeOutline.mockResolvedValueOnce({ validation: { stats: { errorCount: 0 } } });
+ const validated = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/outline/validate')
+ .send({});
+ expect(validated.status).toBe(200);
+ expect(fableLoom.validateEpisodeOutline).toHaveBeenCalledWith('loom-1', 'ep-1');
+
+ fableLoom.reviewEpisodeOutline.mockResolvedValueOnce({ analysis: { summary: 'Sound.' } });
+ const reviewed = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/outline/review')
+ .send({ effort: 'high' });
+ expect(reviewed.status).toBe(200);
+ expect(fableLoom.reviewEpisodeOutline).toHaveBeenCalledWith('loom-1', 'ep-1', { effort: 'high' });
+ });
+
it('POST feedback requires an instruction and forwards the route selection', async () => {
const invalid = await request(makeApp())
.post('/api/fableloom/loom-1/episodes/ep-1/feedback')
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index ae8cf8bf7a..dd08b321b2 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -45,7 +45,8 @@ import { getSettings } from '../services/settings.js';
import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';
import { collectRemoteInputAssets } from '../services/federatedMedia/inputAssets.js';
import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';
-import { attachNodeImage } from '../services/fableLoom/records.js';
+import { inspectEpisodeProductionOrder } from '../lib/fableLoomProduction.js';
+import { attachNodeImage, getLoom } from '../services/fableLoom/records.js';
import {
compileFableLoomVisualRequest, fableLoomImageCapabilities,
} from '../services/fableLoom/visualConditioning.js';
@@ -399,6 +400,21 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// browser's prompt/reference fields are hints only: stable scene bindings,
// approved assets and deterministic graph continuity own the final request.
if (params.fableLoom) {
+ const taggedLoom = await getLoom(params.fableLoom.loomId);
+ const taggedEpisode = taggedLoom?.episodes?.find((episode) => episode.id === params.fableLoom.episodeId);
+ if (taggedLoom && taggedEpisode) {
+ const episodeOrder = inspectEpisodeProductionOrder(taggedLoom, taggedEpisode);
+ if (!episodeOrder.ready) {
+ throw new ServerError(
+ `FableLoom storyboard production is out of order: ${episodeOrder.reason}`,
+ {
+ status: 409,
+ code: 'FABLELOOM_EPISODE_ORDER_BLOCKED',
+ context: { details: { episodeOrder } },
+ },
+ );
+ }
+ }
const selected = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModel(params.modelId) : null;
const cloud = selected ? null : resolveCloudProviderConfig(settings, mode, { model: params.cloudModel });
const model = selected
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 316c9865d3..c19326b097 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -11,7 +11,8 @@ import { tmpdir } from 'os';
import { join as pathJoin } from 'path';
const attachNodeImage = vi.hoisted(() => vi.fn(async () => ({})));
-vi.mock('../services/fableLoom/records.js', () => ({ attachNodeImage }));
+const getLoom = vi.hoisted(() => vi.fn(async () => null));
+vi.mock('../services/fableLoom/records.js', () => ({ attachNodeImage, getLoom }));
const compiledVisual = vi.hoisted(() => ({
version: 1, compilerVersion: '1.0.0', status: 'locked', assets: [], adapters: [], omitted: [], warnings: [],
@@ -275,6 +276,39 @@ describe('Image Gen Routes', () => {
}));
});
+ it('refuses a scene image in a later episode until prior storyboard images exist', async () => {
+ getLoom.mockResolvedValueOnce({
+ id: 'loom-1',
+ episodes: [
+ {
+ id: 'ep-1',
+ number: 1,
+ startNodeId: 'scene-1',
+ nodes: [{ id: 'scene-1', title: 'Prior scene', image: null, transitions: [] }],
+ },
+ {
+ id: 'ep-2',
+ number: 2,
+ startNodeId: 'scene-2',
+ nodes: [{ id: 'scene-2', title: 'Later scene', transitions: [] }],
+ },
+ ],
+ });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({
+ prompt: 'a later episode scene',
+ fableLoom: { loomId: 'loom-1', episodeId: 'ep-2', nodeId: 'scene-2' },
+ });
+
+ expect(response.status).toBe(409);
+ expect(response.body.code).toBe('FABLELOOM_EPISODE_ORDER_BLOCKED');
+ expect(response.body.error).toContain('Finish storyboard images for Episode 1');
+ expect(imageGen.generateImage).not.toHaveBeenCalled();
+ expect(compileFableLoomVisualRequest).not.toHaveBeenCalled();
+ });
+
it('accepts a missing/empty prompt (i2i / edit / unconditional), defaulting it to empty', async () => {
imageGen.generateImage.mockResolvedValue({
generationId: 'gen-empty',
diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.md
index e3144cac1c..249391fb06 100644
--- a/server/services/fableLoom/README.md
+++ b/server/services/fableLoom/README.md
@@ -9,7 +9,7 @@ intent to a transition and moves them through the graph until an ending.
|---|---|
| `records.js` | Sanitizer + CRUD + peer LWW/tombstone merge for looms/episodes/nodes; transitions are addressable one at a time (`addNodeTransition` / `updateNodeTransition` / `deleteNodeTransition`) as well as replaceable as a whole array via the node patch; `attachNodeImage`, `attachNodeVideo`, and `attachNodePlaybackAsset` for media-job hooks. |
| `visualConditioning.js` | Compiles stable scene canon bindings into capability-budgeted prompts, typed reference assets, local character adapters, and durable render provenance. |
-| `weave.js` | AI ops via `runStagedLLM`: `generateSeriesPlan` (full arc / plot-point / side-quest scaffold), `weaveEpisode` (single-camera-cut graph with automatic cuts and looping decisions), `branchNode` (grow paths), `feedbackEpisode` (apply a conversational sparse patch to one episode), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; tapped/automatic paths resolve with NO LLM call), `reformatEpisodeScenes` (rewrite ONE episode's scenes into another format; the loom's format pin lands only once every episode is converted). |
+| `weave.js` | AI ops via `runStagedLLM`: `generateSeriesPlan` (full arc / plot-point / side-quest scaffold), `generateEpisodeOutline` + `validateEpisodeOutline` + `reviewEpisodeOutline` (log-line beat planning before teleplay expansion), `weaveEpisode` (single-camera-cut graph with automatic cuts and looping decisions), `branchNode` (grow paths), `feedbackEpisode` (apply a conversational sparse patch to one episode), `reviewEpisode` + `reviewSeriesTeleplay` (episode or complete-series critique with deterministic analysis), `playTurn` (reader intent → transition; tapped/automatic paths resolve with NO LLM call), `reformatEpisodeScenes` (rewrite ONE episode's scenes into another format; the loom's format pin lands only once every episode is converted). |
| `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. |
| `hostedSession.js` | Scoped QR-hosted play session lifecycle, HTTPS readiness preflight, token hashing, live voice gate revalidation, and half-duplex turn taking (#5383). |
| `production.js` | Episodic production orchestration: batch planning, DAG generation, cancellable batch runs, and user-triggered episodic continuity review (#5384). |
diff --git a/server/services/fableLoom/hostedSession.js b/server/services/fableLoom/hostedSession.js
index 1557e629e4..2da8428c12 100644
--- a/server/services/fableLoom/hostedSession.js
+++ b/server/services/fableLoom/hostedSession.js
@@ -550,7 +550,7 @@ export async function processHostedUtterance(sessionId, {
playResult = {
action: 'stay',
narration: node?.prose?.slice(0, 200) || "I hear you. Let's see what happens next.",
- node: node ? publicNode(node) : null,
+ node: node ? publicNode(node, loom) : null,
ended: false,
};
}
@@ -634,7 +634,7 @@ export async function processHostedUtterance(sessionId, {
if (io) {
io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:story:transition', {
- node: publicNode(targetNode),
+ node: publicNode(targetNode, loom),
transitionId: playResult.transitionId,
playbackPhase: session.playbackPhase,
});
diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.js
index 52b070af6f..123b24df28 100644
--- a/server/services/fableLoom/index.js
+++ b/server/services/fableLoom/index.js
@@ -30,6 +30,7 @@ export {
export {
branchNode,
buildCanonDigest,
+ generateEpisodeOutline,
feedbackEpisode,
feedbackSeriesPlan,
generateSeriesPlan,
@@ -38,8 +39,11 @@ export {
publicNode,
reformatEpisodeScenes,
reviewEpisode,
+ reviewEpisodeOutline,
reviewSeriesPlan,
+ reviewSeriesTeleplay,
weaveEpisode,
+ validateEpisodeOutline,
} from './weave.js';
export {
_resetFableLoomBackend,
diff --git a/server/services/fableLoom/production.js b/server/services/fableLoom/production.js
index b3545b2b9b..1da46fbf16 100644
--- a/server/services/fableLoom/production.js
+++ b/server/services/fableLoom/production.js
@@ -38,8 +38,10 @@ import { cancelJob, enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js
import {
buildEpisodeProductionPlan,
FABLELOOM_PRODUCTION_MODE_DEFAULT,
+ inspectEpisodeProductionOrder,
} from '../../lib/fableLoomProduction.js';
import { analyzeEpisodeContinuity } from '../../lib/fableLoomContinuity.js';
+import { analyzeSeriesStoryOutlines } from '../../lib/fableLoomOutline.js';
import { getUniverse } from '../universeBuilder.js';
import { listVoiceProfiles } from '../voice/profiles.js';
import { listLoras } from '../loras.js';
@@ -728,6 +730,16 @@ export async function planEpisodeProduction(loomId, episodeId, {
availableVideoModels: listVideoModels(),
resolveAsset: resolveImageInputPath,
});
+ const episodeOrderReadiness = inspectEpisodeProductionOrder(loom, episode);
+ plan.episodeOrderReadiness = episodeOrderReadiness;
+ if (!episodeOrderReadiness.ready) {
+ plan.planningIssues.push(`Episode order: ${episodeOrderReadiness.reason}`);
+ }
+ const seriesStoryReadiness = analyzeSeriesStoryOutlines(loom);
+ plan.seriesStoryReadiness = seriesStoryReadiness;
+ for (const issue of seriesStoryReadiness.issues.filter((candidate) => candidate.severity === 'error')) {
+ plan.planningIssues.push(`Story arc: ${issue.message}`);
+ }
const render = normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel, effort });
const settings = await getSettings();
if (plan.mode === 'exact_inputs') {
diff --git a/server/services/fableLoom/production.test.js b/server/services/fableLoom/production.test.js
index bdaf764236..e7890754fa 100644
--- a/server/services/fableLoom/production.test.js
+++ b/server/services/fableLoom/production.test.js
@@ -69,6 +69,32 @@ describe('fableLoom production service', () => {
id: 'ep-1',
title: 'Episode 1',
startNodeId: 'node-1',
+ storyOutline: {
+ version: 1,
+ startKey: 's1',
+ scenes: [
+ {
+ key: 's1', title: 'Opening', summary: 'The hero reaches the threshold.',
+ playbackMode: 'cut', audienceConnection: 'disconnected', protagonistPresence: 'onscreen',
+ isEnding: false, transitions: [{ targetKey: 's2', intent: 'Continue' }],
+ },
+ {
+ key: 's2', title: 'Choice', summary: 'The hero chooses a direction.',
+ playbackMode: 'decision', audienceConnection: 'connected', protagonistPresence: 'onscreen',
+ isEnding: false,
+ transitions: [
+ { targetKey: 's3', intent: 'Take the left path' },
+ { targetKey: 's3', intent: 'Take the right path' },
+ ],
+ },
+ {
+ key: 's3', title: 'Arrival', summary: 'The choice opens a way forward.',
+ playbackMode: 'cut', audienceConnection: 'disconnected', protagonistPresence: 'onscreen',
+ isEnding: true, endingLabel: 'Forward', transitions: [],
+ },
+ ],
+ validation: { status: 'valid', issues: [] },
+ },
nodes: [
{
id: 'node-1',
@@ -142,6 +168,37 @@ describe('fableLoom production service', () => {
expect(plan.plannedAssets.length).toBeGreaterThan(0);
expect(plan.plannedAssets.some((a) => a.id === 'asset-node-1-still')).toBe(true);
expect(plan.plannedAssets.some((a) => a.id === 'asset-node-2-still')).toBe(true);
+ expect(plan.seriesStoryReadiness.stats.ready).toBe(true);
+ });
+
+ it('blocks production planning until the complete series beat arc is validated', async () => {
+ const draftLoom = structuredClone(sampleLoom);
+ draftLoom.episodes[0].storyOutline.validation = { status: 'draft', issues: [] };
+ records.getLoom.mockResolvedValueOnce(draftLoom);
+
+ const plan = await planEpisodeProduction('loom-1', 'ep-1', { mode: 'current_canon' });
+
+ expect(plan.seriesStoryReadiness.stats.ready).toBe(false);
+ expect(plan.planningIssues).toEqual(expect.arrayContaining([
+ expect.stringContaining("Episode 1's beat outline must be validated"),
+ ]));
+ });
+
+ it('reports the ordered storyboard gate for a later episode', async () => {
+ const laterLoom = structuredClone(sampleLoom);
+ laterLoom.episodes.push({
+ id: 'ep-2', number: 2, title: 'Episode 2', startNodeId: 'later-node',
+ storyOutline: structuredClone(sampleLoom.episodes[0].storyOutline),
+ nodes: [{ id: 'later-node', title: 'Later node', prose: 'Later prose.', imagePrompt: 'Later prompt.', transitions: [] }],
+ });
+ records.getLoom.mockResolvedValueOnce(laterLoom);
+
+ const plan = await planEpisodeProduction('loom-1', 'ep-2', { mode: 'current_canon' });
+
+ expect(plan.episodeOrderReadiness.ready).toBe(false);
+ expect(plan.planningIssues).toEqual(expect.arrayContaining([
+ expect.stringContaining('Episode order: Finish storyboard images for Episode 1'),
+ ]));
});
it('creates and tracks batch production runs', async () => {
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index 564df9d839..3b27452fb3 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -44,6 +44,7 @@ import { LOOM_LIMITS } from './limits.js';
import { asLoomFormat, isLoomFormat } from './formats.js';
import {
asFableLoomPlaybackMode,
+ FABLELOOM_PROTAGONIST_PRESENCE,
isSafeVideoHistoryId,
sanitizeInteractionWindow,
sanitizePlaybackAssets,
@@ -55,6 +56,7 @@ import {
asFableLoomParticipationMode,
} from '../../lib/fableLoomParticipation.js';
import { normalizeFableLoomCameraMovement } from '../../lib/fableLoomCameraMovements.js';
+import { sanitizeStoryOutline } from '../../lib/fableLoomOutline.js';
export { LOOM_LIMITS };
@@ -123,6 +125,9 @@ function sanitizeNode(raw) {
visualConditioning: sanitizeVisualConditioning(raw.visualConditioning),
playbackMode: asFableLoomPlaybackMode(raw.playbackMode),
audienceConnection: asFableLoomAudienceConnection(raw.audienceConnection),
+ protagonistPresence: FABLELOOM_PROTAGONIST_PRESENCE.includes(raw.protagonistPresence)
+ ? raw.protagonistPresence
+ : null,
videoHistoryId: isSafeVideoHistoryId(raw.videoHistoryId) ? raw.videoHistoryId : null,
playbackAssets: sanitizePlaybackAssets(raw.playbackAssets),
interactionWindow: sanitizeInteractionWindow(raw.interactionWindow),
@@ -142,7 +147,7 @@ function sanitizeNode(raw) {
};
}
-function sanitizeEpisode(raw) {
+function sanitizeEpisode(raw, participationMode = 'protagonist') {
if (!raw || typeof raw !== 'object' || !isStr(raw.id) || !raw.id) return null;
const nodes = (Array.isArray(raw.nodes) ? raw.nodes : [])
.map(sanitizeNode)
@@ -153,6 +158,7 @@ function sanitizeEpisode(raw) {
// since-deleted id) are deliberately KEPT — the graph validation surfaces
// them as errors the author resolves, rather than silently rewriting edges.
const now = new Date().toISOString();
+ const storyOutline = sanitizeStoryOutline(raw.storyOutline, { participationMode });
return {
id: raw.id,
number: Number.isFinite(raw.number) ? Math.max(1, Math.round(raw.number)) : 1,
@@ -160,6 +166,7 @@ function sanitizeEpisode(raw) {
synopsis: trimTo(raw.synopsis, LOOM_LIMITS.SYNOPSIS_MAX),
startNodeId: isStr(raw.startNodeId) && nodeIds.has(raw.startNodeId) ? raw.startNodeId : (nodes[0]?.id ?? null),
nodes,
+ ...(storyOutline ? { storyOutline } : {}),
createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : now,
updatedAt: isStr(raw.updatedAt) && raw.updatedAt ? raw.updatedAt : now,
};
@@ -181,6 +188,33 @@ function sanitizeSeriesPlan(raw, episodes) {
const episodeIds = new Set(episodes.map((episode) => episode.id));
const plotIds = new Set();
const questIds = new Set();
+ const hasDeliveryPlan = source.deliveryOptions && typeof source.deliveryOptions === 'object'
+ || Array.isArray(source.interEpisodeVoicemails)
+ || source.nextSeasonTeaser !== undefined;
+ const deliveryOptions = source.deliveryOptions && typeof source.deliveryOptions === 'object'
+ ? {
+ overnightVoicemails: source.deliveryOptions.overnightVoicemails === true,
+ nextSeasonTeaser: source.deliveryOptions.nextSeasonTeaser === true,
+ }
+ : { overnightVoicemails: false, nextSeasonTeaser: false };
+ const voicemailIds = new Set();
+ const interEpisodeVoicemails = (Array.isArray(source.interEpisodeVoicemails)
+ ? source.interEpisodeVoicemails : [])
+ .slice(0, LOOM_LIMITS.EPISODES_MAX)
+ .filter((item) => item && typeof item === 'object')
+ .map((item) => ({
+ id: planItemId('voicemail', item.id, voicemailIds),
+ fromEpisodeId: planEpisodeRef(item.fromEpisodeId, episodeIds),
+ toEpisodeId: planEpisodeRef(item.toEpisodeId, episodeIds),
+ title: trimTo(item.title, LOOM_LIMITS.PLAN_ITEM_TITLE_MAX),
+ transcript: trimTo(item.transcript, LOOM_LIMITS.DELIVERY_MESSAGE_MAX),
+ }));
+ const teaser = source.nextSeasonTeaser && typeof source.nextSeasonTeaser === 'object'
+ ? {
+ title: trimTo(source.nextSeasonTeaser.title, LOOM_LIMITS.PLAN_ITEM_TITLE_MAX),
+ transcript: trimTo(source.nextSeasonTeaser.transcript, LOOM_LIMITS.DELIVERY_MESSAGE_MAX),
+ }
+ : null;
return {
storyArc: trimTo(source.storyArc, LOOM_LIMITS.STORY_ARC_MAX),
plotPoints: (Array.isArray(source.plotPoints) ? source.plotPoints : [])
@@ -203,6 +237,11 @@ function sanitizeSeriesPlan(raw, episodes) {
startEpisodeId: planEpisodeRef(item.startEpisodeId, episodeIds),
endEpisodeId: planEpisodeRef(item.endEpisodeId, episodeIds),
})),
+ ...(hasDeliveryPlan ? {
+ deliveryOptions,
+ interEpisodeVoicemails,
+ nextSeasonTeaser: teaser,
+ } : {}),
};
}
@@ -213,11 +252,14 @@ export function sanitizeLoom(raw) {
if (!name) return null;
const now = new Date().toISOString();
const { deleted, deletedAt } = sanitizeSoftDeleteFields(raw);
+ const participationMode = asFableLoomParticipationMode(raw.participationMode);
const episodes = (Array.isArray(raw.episodes) ? raw.episodes : [])
- .map(sanitizeEpisode)
+ .map((episode) => sanitizeEpisode(episode, participationMode))
.filter(Boolean)
.slice(0, LOOM_LIMITS.EPISODES_MAX)
.sort((a, b) => a.number - b.number || a.createdAt.localeCompare(b.createdAt));
+ const protagonistCharacterId = nullableRef(raw.protagonistCharacterId);
+ const protagonistWardrobeId = nullableRef(raw.protagonistWardrobeId);
return {
id: raw.id,
schemaVersion: 2,
@@ -225,7 +267,7 @@ export function sanitizeLoom(raw) {
logline: trimTo(raw.logline, LOOM_LIMITS.LOGLINE_MAX),
premise: trimTo(raw.premise, LOOM_LIMITS.PREMISE_MAX),
styleNotes: trimTo(raw.styleNotes, LOOM_LIMITS.STYLE_NOTES_MAX),
- participationMode: asFableLoomParticipationMode(raw.participationMode),
+ participationMode,
audienceCommunicationMedium: trimTo(
raw.audienceCommunicationMedium,
LOOM_LIMITS.AUDIENCE_COMMUNICATION_MEDIUM_MAX,
@@ -235,6 +277,9 @@ export function sanitizeLoom(raw) {
// turns a reader's free text into a path. An unset dimension stays null
// ('fall through to the stage pin / active provider').
playSettings: sanitizeLlmRoutePin(raw.playSettings),
+ protagonistCharacterId,
+ protagonistWardrobeId,
+ protagonistWardrobeLocked: Boolean(protagonistWardrobeId && raw.protagonistWardrobeLocked !== false),
universeId: nullableRef(raw.universeId),
seriesId: nullableRef(raw.seriesId),
seriesPlan: sanitizeSeriesPlan(raw.seriesPlan, episodes),
@@ -329,6 +374,7 @@ const assertParticipationConfigured = ({ participationMode, audienceCommunicatio
export async function createLoom({
name, logline, premise, styleNotes, format, playSettings, seriesPlan,
+ protagonistCharacterId, protagonistWardrobeId, protagonistWardrobeLocked,
participationMode = FABLELOOM_LEGACY_PARTICIPATION_MODE,
audienceCommunicationMedium, universeId, seriesId,
} = {}) {
@@ -345,6 +391,9 @@ export async function createLoom({
audienceCommunicationMedium,
format,
playSettings,
+ protagonistCharacterId,
+ protagonistWardrobeId,
+ protagonistWardrobeLocked,
seriesPlan,
universeId,
seriesId,
@@ -381,11 +430,13 @@ export async function mutateLoom(id, mutator) {
const PATCH_FIELDS = [
'name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan',
+ 'protagonistCharacterId', 'protagonistWardrobeId', 'protagonistWardrobeLocked',
'participationMode', 'audienceCommunicationMedium', 'universeId', 'seriesId',
];
const RESTORABLE_FIELDS = [
'name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan',
+ 'protagonistCharacterId', 'protagonistWardrobeId', 'protagonistWardrobeLocked',
'participationMode', 'audienceCommunicationMedium', 'episodes',
];
@@ -437,10 +488,15 @@ export async function deleteLoom(id) {
// them. A sender at the current schema version's present null remains an
// intentional clear.
const preserveLegacyVisualProduction = (remote, local, senderVersion) => {
- if (!local || senderVersion >= 3) return remote;
+ if (!local || senderVersion >= 4) return remote;
const localEpisodes = new Map(local.episodes.map((episode) => [episode.id, episode]));
return {
...remote,
+ ...(senderVersion < 4 ? {
+ protagonistCharacterId: local.protagonistCharacterId,
+ protagonistWardrobeId: local.protagonistWardrobeId,
+ protagonistWardrobeLocked: local.protagonistWardrobeLocked,
+ } : {}),
episodes: remote.episodes.map((episode) => {
const localNodes = new Map((localEpisodes.get(episode.id)?.nodes || []).map((node) => [node.id, node]));
return {
@@ -449,16 +505,17 @@ const preserveLegacyVisualProduction = (remote, local, senderVersion) => {
const localNode = localNodes.get(node.id);
return localNode ? {
...node,
- visualCanon: localNode.visualCanon,
- visualConditioning: localNode.visualConditioning,
- playbackAssets: senderVersion < 3
- ? {
+ ...(senderVersion < 4 ? { protagonistPresence: localNode.protagonistPresence } : {}),
+ ...(senderVersion < 3 ? {
+ visualCanon: localNode.visualCanon,
+ visualConditioning: localNode.visualConditioning,
+ playbackAssets: {
...node.playbackAssets,
...(localNode.playbackAssets?.visualConditioningByAsset
? { visualConditioningByAsset: localNode.playbackAssets.visualConditioningByAsset }
: {}),
- }
- : node.playbackAssets,
+ },
+ } : {}),
} : node;
}),
};
@@ -475,7 +532,7 @@ export async function mergeLoomsFromSync(
remoteLooms,
{
source = { via: 'sync', peerId: null },
- senderSchemaVersions = { fableLoom: 3 },
+ senderSchemaVersions = { fableLoom: 4 },
} = {},
) {
if (!Array.isArray(remoteLooms)) return { applied: false, count: 0 };
@@ -586,6 +643,16 @@ export function updateEpisode(loomId, episodeId, patch = {}) {
for (const key of ['title', 'synopsis', 'number', 'startNodeId']) {
if (key in patch) episode[key] = patch[key];
}
+ if ('storyOutline' in patch) {
+ episode.storyOutline = patch.storyOutline
+ ? { ...patch.storyOutline, validation: { status: 'draft', issues: [] } }
+ : null;
+ } else if (('title' in patch || 'synopsis' in patch) && episode.storyOutline) {
+ // A changed synopsis or title can change the dramatic contract the
+ // outline was validated against, so expansion must pass through the
+ // outline validation step again.
+ episode.storyOutline.validation = { status: 'draft', issues: [] };
+ }
episode.updatedAt = new Date().toISOString();
return loom;
});
@@ -603,7 +670,7 @@ export function deleteEpisode(loomId, episodeId) {
const NODE_PATCH_FIELDS = [
'title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode',
- 'audienceConnection', 'visualCanon', 'videoHistoryId', 'playbackAssets', 'interactionWindow',
+ 'audienceConnection', 'protagonistPresence', 'visualCanon', 'videoHistoryId', 'playbackAssets', 'interactionWindow',
'isEnding', 'endingLabel', 'pos', 'transitions',
];
diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.js
index 7a9226dd27..1153a29c6d 100644
--- a/server/services/fableLoom/records.test.js
+++ b/server/services/fableLoom/records.test.js
@@ -132,6 +132,27 @@ describe('sanitizeLoom', () => {
expect(loom.episodes[0].nodes[0].audienceConnection).toBe('disconnected');
});
+ it('round-trips the canonical protagonist wardrobe pin and per-scene presence', () => {
+ const loom = sanitizeLoom({
+ id: 'loom-1',
+ name: 'X',
+ protagonistCharacterId: 'char-1',
+ protagonistWardrobeId: 'wardrobe-field',
+ protagonistWardrobeLocked: true,
+ episodes: [{
+ id: 'ep-1',
+ nodes: [{ id: 'n1', protagonistPresence: 'offscreen' }],
+ }],
+ });
+
+ expect(loom).toMatchObject({
+ protagonistCharacterId: 'char-1',
+ protagonistWardrobeId: 'wardrobe-field',
+ protagonistWardrobeLocked: true,
+ });
+ expect(loom.episodes[0].nodes[0].protagonistPresence).toBe('offscreen');
+ });
+
it('keeps a partial play pin but collapses an all-empty one to null', () => {
const pinned = sanitizeLoom({
id: 'loom-1', name: 'X', playSettings: { providerId: ' claude ', model: '', effort: null },
@@ -168,6 +189,51 @@ describe('sanitizeLoom', () => {
expect(loom.seriesPlan.sideQuests[0]).toMatchObject({ status: 'idea', startEpisodeId: null, endEpisodeId: 'ep-1' });
});
+ it('sanitizes optional series delivery beats without accepting dangling episode ids', () => {
+ const loom = sanitizeLoom({
+ id: 'loom-1',
+ name: 'X',
+ episodes: [{ id: 'ep-1', number: 1 }, { id: 'ep-2', number: 2 }],
+ seriesPlan: {
+ storyArc: '', plotPoints: [], sideQuests: [],
+ deliveryOptions: { overnightVoicemails: true, nextSeasonTeaser: true },
+ interEpisodeVoicemails: [{
+ id: 'vm-1', fromEpisodeId: 'ep-1', toEpisodeId: 'gone',
+ title: 'Night call', transcript: 'The signal is still there.',
+ }],
+ nextSeasonTeaser: { title: 'Beyond', transcript: 'Something answers.' },
+ },
+ });
+
+ expect(loom.seriesPlan.deliveryOptions).toEqual({ overnightVoicemails: true, nextSeasonTeaser: true });
+ expect(loom.seriesPlan.interEpisodeVoicemails[0]).toMatchObject({
+ id: 'vm-1', fromEpisodeId: 'ep-1', toEpisodeId: null, transcript: 'The signal is still there.',
+ });
+ expect(loom.seriesPlan.nextSeasonTeaser).toEqual({ title: 'Beyond', transcript: 'Something answers.' });
+ });
+
+ it('round-trips an episode beat outline and invalidates it when the synopsis changes', async () => {
+ let loom = await makeLoom();
+ loom = await addEpisode(loom.id, { title: 'Pilot', synopsis: 'A signal appears.' });
+ const episodeId = loom.episodes[0].id;
+ const storyOutline = {
+ startKey: 's1',
+ scenes: [
+ { key: 's1', title: 'Signal', summary: 'A signal appears.', playbackMode: 'cut', transitions: [{ targetKey: 's2', intent: 'follow it' }] },
+ { key: 's2', title: 'Choice', summary: 'The signal asks for a sacrifice.', playbackMode: 'decision', transitions: [{ targetKey: 's3', intent: 'answer' }, { targetKey: 's4', intent: 'wait' }] },
+ { key: 's3', title: 'Answer', summary: 'The answer opens a door.', isEnding: true },
+ { key: 's4', title: 'Wait', summary: 'The silence closes in.', isEnding: true },
+ ],
+ validation: { status: 'valid', issues: [] },
+ };
+ const saved = await updateEpisode(loom.id, episodeId, { storyOutline });
+ expect(saved.episodes[0].storyOutline).toMatchObject({ version: 1, startKey: 's1' });
+ expect(saved.episodes[0].storyOutline.validation.status).toBe('draft');
+
+ const revised = await updateEpisode(loom.id, episodeId, { synopsis: 'The signal moves.' });
+ expect(revised.episodes[0].storyOutline.validation).toEqual({ status: 'draft', issues: [] });
+ });
+
it('re-mints duplicate planning ids so each editable row remains addressable', () => {
const loom = sanitizeLoom({
id: 'loom-1', name: 'X',
@@ -265,6 +331,38 @@ describe('loom CRUD', () => {
expect(mergedNode.visualConditioning).toMatchObject({ version: 1, compilerVersion: '1.0.0' });
});
+ it('preserves canonical protagonist continuity fields when a v3 peer wins an unrelated LWW edit', async () => {
+ let loom = await makeLoom({
+ name: 'Local production',
+ protagonistCharacterId: 'char-1',
+ protagonistWardrobeId: 'wardrobe-field',
+ protagonistWardrobeLocked: true,
+ });
+ loom = await addEpisode(loom.id, { title: 'Pilot' });
+ loom = await addNode(loom.id, loom.episodes[0].id, { protagonistPresence: 'offscreen' });
+ const remoteV3 = {
+ ...loom,
+ name: 'Renamed by v3 peer',
+ updatedAt: '2099-01-01T00:00:00.000Z',
+ protagonistCharacterId: undefined,
+ protagonistWardrobeId: undefined,
+ protagonistWardrobeLocked: undefined,
+ episodes: loom.episodes.map((episode) => ({
+ ...episode,
+ nodes: episode.nodes.map(({ protagonistPresence: _presence, ...rest }) => rest),
+ })),
+ };
+
+ await mergeLoomsFromSync([remoteV3], { senderSchemaVersions: { fableLoom: 3 } });
+ const merged = await getLoom(loom.id);
+ expect(merged).toMatchObject({
+ protagonistCharacterId: 'char-1',
+ protagonistWardrobeId: 'wardrobe-field',
+ protagonistWardrobeLocked: true,
+ });
+ expect(merged.episodes[0].nodes[0].protagonistPresence).toBe('offscreen');
+ });
+
it('journals divergent story edits and can restore the authored snapshot', async () => {
const local = await makeLoom({ name: 'Local story', premise: 'Local premise' });
const base = { ...local, name: 'Shared story', premise: 'Shared premise' };
diff --git a/server/services/fableLoom/visualConditioning.js b/server/services/fableLoom/visualConditioning.js
index 0f2bf617c0..07eba1b334 100644
--- a/server/services/fableLoom/visualConditioning.js
+++ b/server/services/fableLoom/visualConditioning.js
@@ -15,6 +15,7 @@ import { characterIdentityPackReadiness } from '../../lib/storyBible.js';
import {
matchCharactersInText, matchObjectsInText, matchPlacesInText,
} from '../../lib/scenePrompt.js';
+import { resolveFableLoomProtagonistPresence } from '../../lib/fableLoomPlayback.js';
import { getUniverse } from '../universeBuilder.js';
import { resolveCharacterLoras } from '../characterLoraResolver.js';
import { getSeries } from '../pipeline/series.js';
@@ -67,7 +68,7 @@ const resolveTemporalNode = (episode, node, explicitId) => {
return { node: null, reason: incoming.length > 1 ? 'ambiguous-convergence' : 'no-predecessor' };
};
-const bindScene = ({ node, episode, universe }) => {
+const bindScene = ({ node, episode, universe, loom }) => {
const declared = node.visualCanon;
const characters = Array.isArray(universe.characters) ? universe.characters : [];
const places = Array.isArray(universe.places) ? universe.places : [];
@@ -76,9 +77,41 @@ const bindScene = ({ node, episode, universe }) => {
const characterMap = byId(characters);
const placeMap = byId(places);
const objectMap = byId(objects);
- const appearances = declared
+ const protagonistIds = unique([
+ loom?.protagonistCharacterId,
+ node.interactionWindow?.protagonistCharacterId,
+ ].map(text));
+ const protagonistId = protagonistIds[0] || null;
+ const protagonistPresence = resolveFableLoomProtagonistPresence(node, loom);
+ const rawAppearances = declared
? declared.characterAppearances || []
: matchCharactersInText(sourceText, characters).map((character) => ({ characterId: character.id }));
+ const hasCanonicalProtagonist = rawAppearances.some((appearance) => (
+ appearance?.characterId === loom?.protagonistCharacterId
+ ));
+ const appearancesWithImplicitProtagonist = loom?.protagonistCharacterId
+ && protagonistPresence !== 'offscreen'
+ && characterMap.has(loom.protagonistCharacterId)
+ && !hasCanonicalProtagonist
+ ? [...rawAppearances, { characterId: loom.protagonistCharacterId }]
+ : rawAppearances;
+ const appearancesWithBaselineWardrobe = appearancesWithImplicitProtagonist.map((appearance) => {
+ if (appearance?.characterId !== loom?.protagonistCharacterId || !loom?.protagonistWardrobeId) {
+ return appearance;
+ }
+ // A selected wardrobe is the default for the protagonist. A locked
+ // wardrobe also overrides a stale scene-local selection so a re-render
+ // cannot silently change clothes between episodes.
+ return loom.protagonistWardrobeLocked || !appearance.wardrobeId
+ ? { ...appearance, wardrobeId: loom.protagonistWardrobeId }
+ : appearance;
+ });
+ const offscreenAppearances = protagonistPresence === 'offscreen'
+ ? appearancesWithBaselineWardrobe.filter((appearance) => protagonistIds.includes(appearance?.characterId))
+ : [];
+ const appearances = appearancesWithBaselineWardrobe.filter(
+ (appearance) => !offscreenAppearances.includes(appearance),
+ );
const boundCharacters = appearances.map((appearance) => ({ appearance, character: characterMap.get(appearance.characterId) }))
.filter((item) => item.character);
const boundPlace = declared
@@ -95,8 +128,28 @@ const bindScene = ({ node, episode, universe }) => {
}).map((item) => ({ role: 'wardrobe', bindingId: item.wardrobeId, reason: 'binding-not-found' })),
...(declared.placeId && !boundPlace ? [{ role: 'environment', bindingId: declared.placeId, reason: 'binding-not-found' }] : []),
...(declared.objectIds || []).filter((id) => !objectMap.has(id)).map((id) => ({ role: 'object', bindingId: id, reason: 'binding-not-found' })),
+ ...(loom?.protagonistCharacterId && !characterMap.has(loom.protagonistCharacterId)
+ ? [{ role: 'protagonist', bindingId: loom.protagonistCharacterId, reason: 'binding-not-found' }]
+ : []),
+ ...(protagonistPresence !== 'offscreen'
+ && loom?.protagonistWardrobeId
+ && characterMap.has(loom.protagonistCharacterId)
+ && !characterMap.get(loom.protagonistCharacterId).wardrobes?.some((wardrobe) => wardrobe.id === loom.protagonistWardrobeId)
+ ? [{ role: 'protagonist-wardrobe', bindingId: loom.protagonistWardrobeId, reason: 'binding-not-found' }]
+ : []),
] : [];
- return { declared: Boolean(declared), appearances, boundCharacters, boundPlace, boundObjects, missing };
+ return {
+ declared: Boolean(declared),
+ appearances,
+ boundCharacters,
+ boundPlace,
+ boundObjects,
+ missing,
+ protagonistId,
+ protagonistPresence,
+ protagonistWardrobeId: loom?.protagonistWardrobeId || null,
+ offscreenAppearances,
+ };
};
const imageAssetsForCharacter = (character, locked, resolveAsset) => {
@@ -173,11 +226,16 @@ export async function compileFableLoomVisualRequest({
if (!universe && !node.visualCanon) return null;
if (!universe) throw new ServerError('FableLoom linked universe not found', { status: 409, code: 'FABLELOOM_UNIVERSE_UNAVAILABLE' });
- const bindings = bindScene({ node, episode, universe });
+ const bindings = bindScene({ node, episode, universe, loom });
const locked = bindings.declared && node.visualCanon.mode !== 'draft';
const warnings = bindings.declared ? [] : ['Bindings inferred from scene text; render is draft-only'];
const failures = [];
const omitted = [...bindings.missing];
+ omitted.push(...bindings.offscreenAppearances.map((appearance) => ({
+ role: 'character',
+ bindingId: appearance.characterId,
+ reason: 'protagonist-offscreen',
+ })));
if (locked && bindings.missing.length) failures.push('one or more stable bindings no longer resolve');
if (locked && bindings.boundCharacters.length > 1 && !capability.multiCharacterPreservation) {
failures.push(`backend does not declare multi-character preservation for ${bindings.boundCharacters.length} characters`);
@@ -291,15 +349,21 @@ export async function compileFableLoomVisualRequest({
universe.influences?.embrace?.length && universe.influences.embrace.join(', '),
universe.styleNotes,
]);
+ const protagonistFraming = bindings.protagonistPresence === 'offscreen'
+ ? 'Framing constraint: the canonical protagonist is speaking through the communicator off-screen. The camera is the remote witness: show the obstacle or environment the protagonist cannot see around a corner, beyond a bend, at a distance, or otherwise outside their sightline. The communicator stays on the protagonist\'s person and completely out of frame; never use a standalone comms device as the subject. Do not show their face, body, silhouette, or duplicate presence in this storyboard image.'
+ : '';
const positive = compact([
universeStyle.length && `Universe style: ${universeStyle.join('. ')}`,
placePrompt, ...characterPrompts, ...objectPrompts,
+ protagonistFraming,
authoredPrompt || (kind === 'video' ? node.videoPrompt || node.prose : node.imagePrompt),
node.visualCanon?.shotNotes && `Shot continuity: ${node.visualCanon.shotNotes}`,
]).join('\n\n').slice(0, 8000);
const identityAvoid = bindings.boundCharacters.flatMap(({ character }) => character.identityPack?.avoid || []);
const negativePrompt = unique(compact([
- authoredNegativePrompt, ...(universe.influences?.avoid || []), ...identityAvoid,
+ authoredNegativePrompt,
+ bindings.protagonistPresence === 'offscreen' && 'visible canonical protagonist, protagonist face, protagonist body, protagonist silhouette, standalone communicator, comms device close-up, radio prop hero shot',
+ ...(universe.influences?.avoid || []), ...identityAvoid,
])).join(', ').slice(0, 8000);
const manifest = {
version: 1,
@@ -309,6 +373,13 @@ export async function compileFableLoomVisualRequest({
capability,
bindings: {
inferred: !bindings.declared,
+ ...(bindings.protagonistId ? {
+ protagonist: {
+ characterId: bindings.protagonistId,
+ wardrobeId: bindings.protagonistWardrobeId,
+ presence: bindings.protagonistPresence || null,
+ },
+ } : {}),
characterAppearances: bindings.boundCharacters.map(({ character, appearance }) => ({
characterId: character.id, wardrobeId: appearance.wardrobeId || null,
expression: appearance.expression || '', continuityNotes: appearance.continuityNotes || '',
diff --git a/server/services/fableLoom/visualConditioning.test.js b/server/services/fableLoom/visualConditioning.test.js
index 8f7ad2a1e5..03dc4f1881 100644
--- a/server/services/fableLoom/visualConditioning.test.js
+++ b/server/services/fableLoom/visualConditioning.test.js
@@ -95,6 +95,65 @@ describe('FableLoom visual conditioning compiler', () => {
expect(JSON.stringify(result.visualConditioning)).not.toContain('/approved/');
});
+ it('injects the loom canonical protagonist and locked wardrobe into an on-screen canon shot', async () => {
+ const loom = loomWith({ ...lockedBinding, characterAppearances: [] });
+ loom.protagonistCharacterId = 'char-a';
+ loom.protagonistWardrobeId = 'wardrobe-red';
+ loom.protagonistWardrobeLocked = true;
+
+ const result = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' },
+ kind: 'image',
+ capability: fableLoomImageCapabilities({
+ mode: 'local', model: { id: 'flux2-klein', runner: 'flux2' }, inputBudget: 6,
+ }),
+ ...deps(loom),
+ });
+
+ expect(result.prompt).toContain('Character: Aria');
+ expect(result.prompt).toContain('Wardrobe: Red coat');
+ expect(result.visualConditioning.bindings).toMatchObject({
+ protagonist: { characterId: 'char-a', wardrobeId: 'wardrobe-red', presence: 'onscreen' },
+ characterAppearances: [{ characterId: 'char-a', wardrobeId: 'wardrobe-red' }],
+ });
+ });
+
+ it('omits the protagonist from an off-screen communicator scene while preserving the side-device manifest', async () => {
+ const loom = loomWith({ ...lockedBinding });
+ loom.protagonistCharacterId = 'char-a';
+ loom.protagonistWardrobeId = 'wardrobe-red';
+ loom.protagonistWardrobeLocked = true;
+ loom.participationMode = 'helper';
+ loom.episodes[0].nodes.at(-1).interactionWindow = {
+ enabled: true,
+ protagonistCharacterId: 'char-a',
+ protagonistPresence: 'offscreen',
+ };
+
+ const result = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' },
+ kind: 'image',
+ capability: fableLoomImageCapabilities({
+ mode: 'local', model: { id: 'flux2-klein', runner: 'flux2' }, inputBudget: 6,
+ }),
+ ...deps(loom),
+ });
+
+ expect(result.prompt).not.toContain('Character: Aria');
+ expect(result.prompt).toContain('canonical protagonist is speaking through the communicator off-screen');
+ expect(result.prompt).toContain('show the obstacle or environment the protagonist cannot see');
+ expect(result.prompt).toContain('never use a standalone comms device as the subject');
+ expect(result.negativePrompt).toContain('visible canonical protagonist');
+ expect(result.negativePrompt).toContain('standalone communicator');
+ expect(result.visualConditioning.bindings).toMatchObject({
+ protagonist: { characterId: 'char-a', wardrobeId: 'wardrobe-red', presence: 'offscreen' },
+ characterAppearances: [],
+ });
+ expect(result.visualConditioning.omitted).toContainEqual({
+ role: 'character', bindingId: 'char-a', reason: 'protagonist-offscreen',
+ });
+ });
+
it('fails a locked render when a backend cannot preserve the bound cast', async () => {
const loom = loomWith({
...lockedBinding,
diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.js
index 1c3ad71559..d92981515a 100644
--- a/server/services/fableLoom/weave.js
+++ b/server/services/fableLoom/weave.js
@@ -25,7 +25,16 @@ import {
fableLoomCameraMovementCatalogForPrompt,
normalizeFableLoomCameraMovement,
} from '../../lib/fableLoomCameraMovements.js';
-import { isFableLoomPlaybackMode } from '../../lib/fableLoomPlayback.js';
+import {
+ analyzeSeriesStoryOutlines,
+ analyzeStoryOutline,
+ describeStoryOutlineForPrompt,
+ sanitizeStoryOutline,
+} from '../../lib/fableLoomOutline.js';
+import {
+ isFableLoomPlaybackMode,
+ resolveFableLoomProtagonistPresence,
+} from '../../lib/fableLoomPlayback.js';
import {
asFableLoomAudienceConnection,
audienceCanParticipate,
@@ -154,10 +163,27 @@ const seriesPlanContext = (loom, episode) => {
const end = item.endEpisodeId ? episodeLabels.get(item.endEpisodeId) || item.endEpisodeId : 'unassigned';
return `Side quest (${item.status}; starts ${start}; ends ${end}): ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`;
});
+ const delivery = plan.deliveryOptions || {};
+ const deliveryLines = [];
+ if (delivery.overnightVoicemails === true) {
+ deliveryLines.push('Series delivery: include an authored overnight voicemail between every adjacent episode; it should carry the protagonist\'s emotional handoff and a reason to watch the next episode.');
+ for (const voicemail of plan.interEpisodeVoicemails || []) {
+ if (voicemail.transcript) {
+ deliveryLines.push(`Overnight voicemail ${voicemail.fromEpisodeId || '?'} -> ${voicemail.toEpisodeId || '?'}: ${trimTo(voicemail.transcript, 500)}`);
+ }
+ }
+ }
+ if (delivery.nextSeasonTeaser === true) {
+ deliveryLines.push('Series delivery: the final episode must leave a next-season teaser or unresolved cliffhanger after its ending.');
+ if (plan.nextSeasonTeaser?.transcript) {
+ deliveryLines.push(`Next-season teaser: ${trimTo(plan.nextSeasonTeaser.transcript, 500)}`);
+ }
+ }
return [
plan.storyArc ? `Series arc: ${trimTo(plan.storyArc, 4000)}` : '',
...plotPoints,
...sideQuests,
+ ...deliveryLines,
].filter(Boolean);
};
@@ -169,10 +195,21 @@ const audienceContract = (loom, episode) => participationContractForPrompt(loom,
requiresIntroduction: requiresAudienceIntroduction(loom, episode),
});
+const protagonistContinuityContext = (loom) => [
+ loom.protagonistCharacterId
+ ? `Canonical protagonist binding: ${loom.protagonistCharacterId}. Every visible protagonist beat must use this Universe character.`
+ : 'Canonical protagonist binding: (not configured — choose and bind the protagonist before visual production).',
+ loom.protagonistWardrobeId
+ ? `Canonical protagonist wardrobe: ${loom.protagonistWardrobeId}${loom.protagonistWardrobeLocked ? ' (locked across every on-screen scene)' : ' (default; an intentional scene change must be explicit).'}`
+ : 'Canonical protagonist wardrobe: (not configured — do not invent a new outfit per scene).',
+ 'Every scene must declare protagonist presence. Off-screen protagonist scenes are valid: use them for direct communicator conversations with the audience and keep the protagonist out of the storyboard image. For an off-screen helper scene, frame the obstacle or space the protagonist cannot see — around a corner, beyond a bend, at a distance, or otherwise outside their sightline. The communicator stays on the protagonist\'s person and out of frame; never make a standalone comms device the subject of the storyboard image.',
+];
+
const storyContext = (loom, episode) => [
`Story: ${loom.name}`,
`Scene format: ${loomFormatLabel(loom.format)}`,
`Audience participation: ${audienceContract(loom, episode)}`,
+ ...protagonistContinuityContext(loom),
loom.logline ? `Logline: ${loom.logline}` : '',
loom.premise ? `Premise: ${loom.premise}` : '',
...seriesPlanContext(loom, episode),
@@ -188,11 +225,34 @@ const seriesPlanDigest = (loom) => JSON.stringify({
sideQuests: (loom.seriesPlan?.sideQuests || []).map((item) => ({
...item, description: trimTo(item.description, 400),
})),
- episodes: loom.episodes.map(({ id, number, title, synopsis }) => ({
- id, number, title, synopsis: trimTo(synopsis, 300),
+ deliveryOptions: loom.seriesPlan?.deliveryOptions || null,
+ interEpisodeVoicemails: (loom.seriesPlan?.interEpisodeVoicemails || []).map((item) => ({
+ ...item, transcript: trimTo(item.transcript, 500),
+ })),
+ nextSeasonTeaser: loom.seriesPlan?.nextSeasonTeaser
+ ? { ...loom.seriesPlan.nextSeasonTeaser, transcript: trimTo(loom.seriesPlan.nextSeasonTeaser.transcript, 500) }
+ : null,
+ protagonistCharacterId: loom.protagonistCharacterId || null,
+ protagonistWardrobeId: loom.protagonistWardrobeId || null,
+ protagonistWardrobeLocked: loom.protagonistWardrobeLocked === true,
+ episodes: loom.episodes.map(({ id, number, title, synopsis, storyOutline }) => ({
+ id,
+ number,
+ title,
+ synopsis: trimTo(synopsis, 300),
+ beatOutline: storyOutline ? describeStoryOutlineForPrompt(storyOutline) : '(missing)',
})),
}, null, 2);
+const seriesTeleplayDigest = (loom) => loom.episodes.map((episode) => [
+ `## Episode ${episode.number}: ${episode.title || 'Untitled'}`,
+ episode.synopsis ? `Synopsis: ${trimTo(episode.synopsis, 500)}` : '',
+ episode.storyOutline ? `Beat outline:\n${describeStoryOutlineForPrompt(episode.storyOutline)}` : 'Beat outline: (missing)',
+ episode.nodes.length
+ ? describeGraphForPrompt(episode, { proseLimit: 800, participationMode: loom.participationMode })
+ : '(no expanded teleplay scenes)',
+].filter(Boolean).join('\n')).join('\n\n');
+
// A full-plan draft replaces the whole scaffold after a potentially slow
// provider call. Capture every authored input the stage read so a save made
// while that call is in flight cannot be overwritten by a stale response.
@@ -202,8 +262,13 @@ const seriesPlanGenerationFingerprint = (loom) => JSON.stringify({
premise: loom.premise,
format: loom.format,
universeId: loom.universeId,
+ protagonistCharacterId: loom.protagonistCharacterId,
+ protagonistWardrobeId: loom.protagonistWardrobeId,
+ protagonistWardrobeLocked: loom.protagonistWardrobeLocked,
seriesPlan: loom.seriesPlan,
- episodes: loom.episodes.map(({ id, number, title, synopsis }) => ({ id, number, title, synopsis })),
+ episodes: loom.episodes.map(({ id, number, title, synopsis, storyOutline }) => ({
+ id, number, title, synopsis, storyOutline,
+ })),
});
// --- Weave: generate a full episode graph -----------------------------------
@@ -218,6 +283,7 @@ const generatedNodeFields = (raw) => ({
visualCanon: raw.visualCanon,
playbackMode: raw.playbackMode,
audienceConnection: raw.audienceConnection,
+ protagonistPresence: raw.protagonistPresence,
isEnding: raw.isEnding === true,
endingLabel: raw.endingLabel,
});
@@ -255,11 +321,152 @@ export function mapGeneratedGraph(parsed) {
return { nodes, startNodeId };
}
+const episodeOutlineFingerprint = (loom, episode) => JSON.stringify({
+ loom: {
+ name: loom.name,
+ logline: loom.logline,
+ premise: loom.premise,
+ format: loom.format,
+ universeId: loom.universeId,
+ seriesId: loom.seriesId,
+ protagonistCharacterId: loom.protagonistCharacterId,
+ protagonistWardrobeId: loom.protagonistWardrobeId,
+ protagonistWardrobeLocked: loom.protagonistWardrobeLocked,
+ seriesPlan: loom.seriesPlan,
+ },
+ episodes: loom.episodes.map(({ id, number, title, synopsis, startNodeId, nodes, storyOutline }) => ({
+ id, number, title, synopsis, startNodeId, nodes, storyOutline,
+ })),
+ episodeId: episode.id,
+});
+
+const outlineStructuralAnalysis = (loom, episode) => analyzeStoryOutline(episode.storyOutline, {
+ participationMode: loom.participationMode,
+ requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),
+});
+
+const outlineInvalidError = (analysis, message = 'The episode outline must be valid before teleplay expansion') => {
+ const firstIssue = analysis?.issues?.find((issue) => issue.severity === 'error');
+ return new ServerError(firstIssue ? `${message}: ${firstIssue.message}` : message, {
+ status: 409,
+ code: 'OUTLINE_INVALID',
+ });
+};
+
+const episodeSequenceDigest = (loom, currentEpisodeId) => loom.episodes.map((episode) => (
+ `Episode ${episode.number}: ${episode.title || 'Untitled'}${episode.id === currentEpisodeId ? ' [CURRENT]' : ''}`
+ + (episode.synopsis ? ` — ${trimTo(episode.synopsis, 500)}` : '')
+)).join('\n');
+
+/** Draft one episode's camera-cut beats without writing scene prose. */
+export async function generateEpisodeOutline(loomId, episodeId, {
+ guidance = '', providerId, model, effort, operationId,
+} = {}) {
+ const loom = await requireLoom(loomId);
+ const episode = findEpisode(loom, episodeId);
+ const sourceFingerprint = episodeOutlineFingerprint(loom, episode);
+ const canonDigest = await buildCanonDigest(loom);
+ const { content, runId } = await runLoomAi('fableloom-outline-episode', {
+ storyContext: storyContext(loom, episode),
+ canonDigest: canonDigest || '(none — invent only what the premise needs)',
+ episodeSequence: episodeSequenceDigest(loom, episode.id),
+ currentGraph: episode.nodes.length
+ ? describeGraphForPrompt(episode, { proseLimit: 300, participationMode: loom.participationMode })
+ : '(none — this episode has not been expanded yet)',
+ currentOutline: episode.storyOutline
+ ? describeStoryOutlineForPrompt(episode.storyOutline)
+ : '(none — draft the first beat outline)',
+ guidance: guidance || '(none)',
+ participationContract: audienceContract(loom, episode),
+ }, { providerId, model, effort, operationId }, {
+ action: 'outline-episode', label: 'Drafting episode outline', source: 'fableloom-outline-episode',
+ });
+
+ const outline = sanitizeStoryOutline(content, { participationMode: loom.participationMode });
+ if (!outline?.scenes?.length) throw aiShapeError('The model returned no usable episode outline beats');
+ const validation = analyzeStoryOutline(outline, {
+ participationMode: loom.participationMode,
+ requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),
+ });
+ const draft = {
+ ...outline,
+ validation: {
+ status: 'draft',
+ issues: validation.issues,
+ },
+ };
+ const updated = await mutateLoom(loomId, (current) => {
+ if (episodeOutlineFingerprint(current, findEpisode(current, episodeId)) !== sourceFingerprint) {
+ throw new ServerError('The episode changed while its outline was being drafted', {
+ status: 409,
+ code: 'LOOM_CHANGED_DURING_GENERATION',
+ });
+ }
+ const currentEpisode = findEpisode(current, episodeId);
+ currentEpisode.storyOutline = draft;
+ currentEpisode.updatedAt = new Date().toISOString();
+ return current;
+ });
+ return {
+ loom: updated,
+ episodeId,
+ outline: findEpisode(updated, episodeId).storyOutline,
+ validation,
+ runId,
+ };
+}
+
+/** Validate and persist the deterministic status of an episode beat outline. */
+export async function validateEpisodeOutline(loomId, episodeId) {
+ const loom = await requireLoom(loomId);
+ const episode = findEpisode(loom, episodeId);
+ const validation = outlineStructuralAnalysis(loom, episode);
+ if (!episode.storyOutline) return { loom, episodeId, outline: null, validation };
+ const updated = await mutateLoom(loomId, (current) => {
+ const currentEpisode = findEpisode(current, episodeId);
+ const currentValidation = outlineStructuralAnalysis(current, currentEpisode);
+ currentEpisode.storyOutline = {
+ ...currentEpisode.storyOutline,
+ validation: {
+ status: currentValidation.stats.errorCount ? 'invalid' : 'valid',
+ issues: currentValidation.issues,
+ validatedAt: new Date().toISOString(),
+ },
+ };
+ currentEpisode.updatedAt = new Date().toISOString();
+ return current;
+ });
+ const updatedEpisode = findEpisode(updated, episodeId);
+ return {
+ loom: updated,
+ episodeId,
+ outline: updatedEpisode.storyOutline,
+ validation,
+ };
+}
+
export async function weaveEpisode(loomId, episodeId, {
- guidance = '', replace = false, providerId, model, effort, operationId,
+ guidance = '', replace = false, expandFromOutline = false, providerId, model, effort, operationId,
} = {}) {
const loom = await requireLoom(loomId);
const episode = findEpisode(loom, episodeId);
+ const outlineValidation = expandFromOutline ? outlineStructuralAnalysis(loom, episode) : null;
+ if (expandFromOutline && (!episode.storyOutline || episode.storyOutline.validation?.status !== 'valid')) {
+ throw outlineInvalidError(outlineValidation);
+ }
+ if (expandFromOutline && outlineValidation.stats.errorCount) {
+ throw outlineInvalidError(outlineValidation);
+ }
+ if (expandFromOutline) {
+ const seriesOutlineValidation = analyzeSeriesStoryOutlines(loom);
+ if (seriesOutlineValidation.stats.errorCount) {
+ const firstIssue = seriesOutlineValidation.issues.find((issue) => issue.severity === 'error');
+ throw new ServerError(`Complete the series beat outlines before expansion: ${firstIssue.message}`, {
+ status: 409,
+ code: 'SERIES_OUTLINE_INVALID',
+ });
+ }
+ }
if (episode.nodes.length && !replace) {
throw new ServerError('Episode already has scenes — pass replace to regenerate', { status: 409, code: 'EPISODE_NOT_EMPTY' });
}
@@ -271,6 +478,9 @@ export async function weaveEpisode(loomId, episodeId, {
existingGraph: episode.nodes.length
? describeGraphForPrompt(episode, { proseLimit: 1200, participationMode: loom.participationMode })
: '(none — create the episode from the story context)',
+ outlineDigest: expandFromOutline
+ ? describeStoryOutlineForPrompt(episode.storyOutline)
+ : '(none — use the story context directly)',
cameraMovementCatalog: fableLoomCameraMovementCatalogForPrompt(),
sceneFormatContract: sceneFormatContract(loom.format),
participationContract: audienceContract(loom, episode),
@@ -279,6 +489,16 @@ export async function weaveEpisode(loomId, episodeId, {
});
const { nodes, startNodeId } = mapGeneratedGraph(content);
+ const generatedAnalysis = analyzeEpisodeGraph(
+ { ...episode, nodes, startNodeId },
+ {
+ participationMode: loom.participationMode,
+ requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),
+ },
+ );
+ if (expandFromOutline && generatedAnalysis.issues.some((issue) => issue.severity === 'error')) {
+ throw aiShapeError(`The expanded teleplay has structural issues: ${generatedAnalysis.issues.find((issue) => issue.severity === 'error').message}`);
+ }
if (loom.participationMode === 'helper') {
const audienceErrors = analyzeEpisodeGraph(
{ ...episode, nodes, startNodeId },
@@ -559,6 +779,38 @@ const analysisStrings = (value) => (Array.isArray(value) ? value : [])
.filter(Boolean)
.slice(0, 12);
+/** Read-only story-editor pass over one episode's beat outline. */
+export async function reviewEpisodeOutline(loomId, episodeId, { providerId, model, effort, operationId } = {}) {
+ const loom = await requireLoom(loomId);
+ const episode = findEpisode(loom, episodeId);
+ if (!episode.storyOutline) {
+ throw new ServerError('Draft an episode outline before reviewing it', { status: 409, code: 'OUTLINE_REQUIRED' });
+ }
+ const structural = outlineStructuralAnalysis(loom, episode);
+ const canonDigest = await buildCanonDigest(loom);
+ const { content, runId } = await runLoomAi('fableloom-review-episode-outline', {
+ storyContext: storyContext(loom, episode),
+ canonDigest: canonDigest || '(none)',
+ episodeSequence: episodeSequenceDigest(loom, episode.id),
+ outlineDigest: describeStoryOutlineForPrompt(episode.storyOutline),
+ structuralDigest: structural.issues.length
+ ? structural.issues.map((issue) => `- [${issue.severity}] ${issue.message}`).join('\n')
+ : '(no structural issues)',
+ }, { providerId, model, effort, operationId }, {
+ action: 'review-episode-outline', label: 'Reviewing episode outline', source: 'fableloom-review-episode-outline',
+ });
+ const analysis = {
+ summary: trimTo(content?.summary, 2000),
+ strengths: analysisStrings(content?.strengths),
+ risks: analysisStrings(content?.risks),
+ recommendations: analysisStrings(content?.recommendations),
+ };
+ if (!analysis.summary && !analysis.strengths.length && !analysis.risks.length && !analysis.recommendations.length) {
+ throw aiShapeError('The model returned no usable episode-outline analysis');
+ }
+ return { structural, analysis, runId };
+}
+
/**
* Draft the complete series-level scaffold from the story metadata, linked
* universe canon, current episode outline, and any useful ideas already in the
@@ -595,7 +847,7 @@ export async function generateSeriesPlan(loomId, { providerId, model, effort, op
code: 'LOOM_CHANGED_DURING_GENERATION',
});
}
- current.seriesPlan = { storyArc, plotPoints, sideQuests };
+ current.seriesPlan = { ...current.seriesPlan, storyArc, plotPoints, sideQuests };
return current;
});
return { loom: updated, runId };
@@ -627,6 +879,51 @@ export async function reviewSeriesPlan(loomId, { providerId, model, effort, oper
};
}
+/** Read-only story-editor pass over every expanded episode as one teleplay series. */
+export async function reviewSeriesTeleplay(loomId, { providerId, model, effort, operationId } = {}) {
+ const loom = await requireLoom(loomId);
+ if (!loom.episodes.length || loom.episodes.some((episode) => !episode.nodes.length)) {
+ throw new ServerError('Expand every episode before reviewing the full teleplay series', {
+ status: 409,
+ code: 'TELEPLAY_INCOMPLETE',
+ });
+ }
+ const canonDigest = await buildCanonDigest(loom);
+ const structural = loom.episodes.map((episode) => ({
+ episodeId: episode.id,
+ episodeNumber: episode.number,
+ ...analyzeEpisodeGraph(episode, {
+ participationMode: loom.participationMode,
+ requireAudienceIntroduction: episode.id === loom.episodes[0]?.id,
+ }),
+ }));
+ const structuralDigest = structural.map((episode) => {
+ const issues = episode.issues.length
+ ? episode.issues.map((issue) => `- [${issue.severity}] ${issue.message}`).join('\n')
+ : '(no structural issues)';
+ return `Episode ${episode.episodeNumber}:\n${issues}`;
+ }).join('\n');
+ const { content, runId } = await runLoomAi('fableloom-review-series-teleplay', {
+ storyContext: storyContext(loom),
+ canonDigest: canonDigest || '(none)',
+ seriesPlanJson: seriesPlanDigest(loom),
+ teleplayDigest: seriesTeleplayDigest(loom),
+ structuralDigest,
+ }, { providerId, model, effort, operationId }, {
+ action: 'review-series-teleplay', label: 'Reviewing full teleplay series', source: 'fableloom-review-series-teleplay',
+ });
+ const analysis = {
+ summary: trimTo(content?.summary, 2000),
+ strengths: analysisStrings(content?.strengths),
+ risks: analysisStrings(content?.risks),
+ recommendations: analysisStrings(content?.recommendations),
+ };
+ if (!analysis.summary && !analysis.strengths.length && !analysis.risks.length && !analysis.recommendations.length) {
+ throw aiShapeError('The model returned no usable full-teleplay analysis');
+ }
+ return { structural, analysis, runId };
+}
+
/** Apply one author instruction to the series-level plan without touching episode scene graphs. */
export async function feedbackSeriesPlan(loomId, {
feedback, providerId, model, effort, operationId,
@@ -709,7 +1006,7 @@ function applyPlanItemEdits(currentItems = [], rawEdits, rawOrder, { prefix, fie
// --- Play: resolve a reader's free-text intent ------------------------------
/** Reader-facing scene shape — trigger phrases stay server-side. */
-export const publicNode = (node) => ({
+export const publicNode = (node, loom = null) => ({
id: node.id,
title: node.title,
prose: node.prose,
@@ -717,6 +1014,7 @@ export const publicNode = (node) => ({
videoHistoryId: node.videoHistoryId,
playbackAssets: node.playbackAssets || null,
interactionWindow: node.interactionWindow || null,
+ protagonistPresence: resolveFableLoomProtagonistPresence(node, loom),
playbackMode: node.playbackMode,
audienceConnection: asFableLoomAudienceConnection(node.audienceConnection),
isEnding: node.isEnding,
@@ -746,7 +1044,7 @@ export async function playTurn(loomId, episodeId, {
const episode = findEpisode(loom, episodeId);
const node = findNode(episode, nodeId);
if (node.isEnding || !(node.transitions || []).length) {
- return { action: 'stay', narration: '', node: publicNode(node), ended: true, resolvedBy: 'graph' };
+ return { action: 'stay', narration: '', node: publicNode(node, loom), ended: true, resolvedBy: 'graph' };
}
if (transitionId) {
@@ -760,6 +1058,7 @@ export async function playTurn(loomId, episodeId, {
return moveResult(episode, node, taken, {
narration: '',
resolvedBy: interactive ? 'choice' : 'graph',
+ loom,
});
}
@@ -793,9 +1092,9 @@ export async function playTurn(loomId, episodeId, {
// No usable choice — including a dangling edge whose target was deleted —
// stays in place rather than crashing the read.
if (!chosen) {
- return { action: 'stay', narration, node: publicNode(node), ended: false, resolvedBy: 'llm', runId };
+ return { action: 'stay', narration, node: publicNode(node, loom), ended: false, resolvedBy: 'llm', runId };
}
- return moveResult(episode, node, chosen, { narration, resolvedBy: 'llm', runId });
+ return moveResult(episode, node, chosen, { narration, resolvedBy: 'llm', runId, loom });
}
/**
@@ -803,12 +1102,12 @@ export async function playTurn(loomId, episodeId, {
* deleted since the graph was woven) keeps the reader where they are rather
* than ending the read-through on a crash.
*/
-function moveResult(episode, node, transition, { narration = '', resolvedBy, runId } = {}) {
+function moveResult(episode, node, transition, { narration = '', resolvedBy, runId, loom = null } = {}) {
const next = episode.nodes.find((n) => n.id === transition.targetNodeId);
const common = { narration, resolvedBy, ...(runId ? { runId } : {}) };
return next
- ? { action: 'move', transitionId: transition.id, node: publicNode(next), ended: next.isEnding === true, ...common }
- : { action: 'stay', node: publicNode(node), ended: false, ...common };
+ ? { action: 'move', transitionId: transition.id, node: publicNode(next, loom), ended: next.isEnding === true, ...common }
+ : { action: 'stay', node: publicNode(node, loom), ended: false, ...common };
}
// --- Reformat: rewrite existing scenes into another format ------------------
diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.js
index a4cc4d3393..22b2c3dec6 100644
--- a/server/services/fableLoom/weave.test.js
+++ b/server/services/fableLoom/weave.test.js
@@ -26,8 +26,9 @@ const { createLoom, addEpisode, addNode, mutateLoom, updateLoom, updateNode, get
const { _resetFableLoomBackend } = await import('./store.js');
const { aiStatusEvents } = await import('../aiStatusEvents.js');
const {
- branchNode, buildCanonDigest, feedbackEpisode, feedbackSeriesPlan, generateSeriesPlan, mapGeneratedGraph, playTurn,
- reformatEpisodeScenes, reviewEpisode, reviewSeriesPlan, weaveEpisode,
+ branchNode, buildCanonDigest, feedbackEpisode, feedbackSeriesPlan, generateEpisodeOutline, generateSeriesPlan,
+ mapGeneratedGraph, playTurn, reformatEpisodeScenes, reviewEpisode, reviewEpisodeOutline, reviewSeriesPlan,
+ validateEpisodeOutline, reviewSeriesTeleplay, weaveEpisode,
} = await import('./weave.js');
beforeEach(() => {
@@ -62,6 +63,16 @@ const generatedGraph = () => ({
],
});
+const generatedOutline = () => ({
+ startKey: 's1',
+ scenes: [
+ { key: 's1', title: 'Signal', summary: 'A signal proves the missing ship is alive.', playbackMode: 'cut', transitions: [{ targetKey: 's2', intent: 'follow the signal' }] },
+ { key: 's2', title: 'The choice', summary: 'The signal offers two routes with different costs.', playbackMode: 'decision', transitions: [{ targetKey: 's3', intent: 'protect the survivors' }, { targetKey: 's4', intent: 'take the shortcut' }] },
+ { key: 's3', title: 'Rescue', summary: 'The rescue succeeds but strands the protagonist.', isEnding: true, endingLabel: 'The long way home' },
+ { key: 's4', title: 'Shortcut', summary: 'The shortcut opens a door and leaves a voice behind.', isEnding: true, endingLabel: 'The open door' },
+ ],
+});
+
describe('mapGeneratedGraph', () => {
it('mints server ids, remaps targets, and drops unknown-target transitions', () => {
const { nodes, startNodeId } = mapGeneratedGraph(generatedGraph());
@@ -154,6 +165,114 @@ describe('weaveEpisode', () => {
expect(result.loom.episodes[0].nodes.map((node) => node.audienceConnection))
.toEqual(['disconnected', 'connected', 'disconnected']);
});
+
+ it('requires a validated beat outline before expansion', async () => {
+ const { loomId, episodeId } = await setup();
+ await expect(weaveEpisode(loomId, episodeId, { expandFromOutline: true }))
+ .rejects.toMatchObject({ code: 'OUTLINE_INVALID' });
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('drafts, validates, and expands an outline without losing its story contract', async () => {
+ const { loomId, episodeId } = await setup();
+ runStagedLLM.mockResolvedValueOnce({ content: generatedOutline(), runId: 'outline-run' });
+ const drafted = await generateEpisodeOutline(loomId, episodeId, { guidance: 'Make the choice costly.' });
+ expect(drafted.runId).toBe('outline-run');
+ expect(drafted.outline.scenes).toHaveLength(4);
+ expect(drafted.outline.validation.status).toBe('draft');
+
+ const checked = await validateEpisodeOutline(loomId, episodeId);
+ expect(checked.validation.issues).toEqual([]);
+ expect(checked.outline.validation.status).toBe('valid');
+
+ runStagedLLM.mockResolvedValueOnce({ content: generatedGraph(), runId: 'expand-run' });
+ const expanded = await weaveEpisode(loomId, episodeId, {
+ guidance: 'Write the full teleplay now.', replace: false, expandFromOutline: true,
+ });
+ expect(expanded.runId).toBe('expand-run');
+ expect(expanded.loom.episodes[0].nodes).toHaveLength(3);
+ expect(runStagedLLM.mock.calls[1][0]).toBe('fableloom-weave-episode');
+ expect(runStagedLLM.mock.calls[1][1].outlineDigest).toContain('[s1] Signal');
+ });
+
+ it('uses the loom participation mode when normalizing helper outline beats', async () => {
+ const { loomId, episodeId } = await setup();
+ await updateLoom(loomId, {
+ participationMode: 'helper',
+ audienceCommunicationMedium: 'A pocket radio.',
+ });
+ const outline = generatedOutline();
+ outline.scenes[1].audienceConnection = 'connected';
+ runStagedLLM.mockResolvedValueOnce({ content: outline, runId: 'helper-outline-run' });
+
+ const drafted = await generateEpisodeOutline(loomId, episodeId, {});
+
+ expect(drafted.outline.scenes[1].protagonistPresence).toBe('offscreen');
+ });
+
+ it('does not expand one episode until every episode in the series has a validated outline', async () => {
+ const { loomId, episodeId } = await setup();
+ const withSecond = await addEpisode(loomId, { title: 'Second', synopsis: 'The consequence.' });
+ runStagedLLM.mockResolvedValueOnce({ content: generatedOutline(), runId: 'outline-run' });
+ await generateEpisodeOutline(loomId, episodeId, {});
+ await validateEpisodeOutline(loomId, episodeId);
+
+ await expect(weaveEpisode(loomId, episodeId, { expandFromOutline: true }))
+ .rejects.toMatchObject({ code: 'SERIES_OUTLINE_INVALID' });
+ expect(withSecond.episodes).toHaveLength(2);
+ expect(runStagedLLM).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('episode outline AI review', () => {
+ it('returns deterministic findings alongside editorial analysis', async () => {
+ const { loomId, episodeId } = await setup();
+ runStagedLLM.mockResolvedValueOnce({ content: generatedOutline(), runId: 'outline-run' });
+ await generateEpisodeOutline(loomId, episodeId, {});
+ runStagedLLM.mockResolvedValueOnce({
+ content: { summary: 'The turn lands.', strengths: ['The endings diverge.'], risks: ['The handoff needs a sharper hook.'], recommendations: ['Make the final beat reveal the next threat.'] },
+ runId: 'outline-review-run',
+ });
+ const result = await reviewEpisodeOutline(loomId, episodeId, {});
+ expect(result).toMatchObject({
+ runId: 'outline-review-run',
+ structural: { stats: { errorCount: 0 } },
+ analysis: { summary: 'The turn lands.' },
+ });
+ });
+});
+
+describe('reviewSeriesTeleplay', () => {
+ it('reviews all expanded episodes together and returns per-episode structure', async () => {
+ const { loomId, episodeId } = await setup();
+ runStagedLLM.mockResolvedValueOnce({ content: generatedGraph(), runId: 'expand-1' });
+ await weaveEpisode(loomId, episodeId, {});
+ const second = await addEpisode(loomId, { title: 'Second', synopsis: 'The consequence.' });
+ runStagedLLM.mockResolvedValueOnce({ content: generatedGraph(), runId: 'expand-2' });
+ await weaveEpisode(loomId, second.episodes[1].id, {});
+ runStagedLLM.mockResolvedValueOnce({
+ content: { summary: 'The series escalates.', strengths: ['The protagonist changes.'], risks: [], recommendations: [] },
+ runId: 'teleplay-review-run',
+ });
+
+ const result = await reviewSeriesTeleplay(loomId, {});
+ expect(result).toMatchObject({
+ runId: 'teleplay-review-run',
+ structural: [
+ { episodeId, episodeNumber: 1 },
+ { episodeNumber: 2 },
+ ],
+ analysis: { summary: 'The series escalates.' },
+ });
+ expect(runStagedLLM.mock.calls[2][0]).toBe('fableloom-review-series-teleplay');
+ expect(runStagedLLM.mock.calls[2][1].teleplayDigest).toContain('## Episode 1: Pilot');
+ });
+
+ it('refuses a full-series review while an episode has not expanded', async () => {
+ const { loomId } = await setup();
+ await expect(reviewSeriesTeleplay(loomId, {})).rejects.toMatchObject({ code: 'TELEPLAY_INCOMPLETE' });
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
});
describe('branchNode', () => {
@@ -864,4 +983,35 @@ describe('series plan AI', () => {
storyContext: expect.stringContaining('Plot point 1 [planned for Episode 1: Pilot]: Episode turn'),
}), expect.anything());
});
+
+ it('carries enabled series delivery beats into episode context and preserves them during plan drafting', async () => {
+ const { loomId, episodeId } = await setup();
+ const delivery = {
+ deliveryOptions: { overnightVoicemails: true, nextSeasonTeaser: true },
+ interEpisodeVoicemails: [{
+ id: 'vm-1', fromEpisodeId: episodeId, toEpisodeId: null,
+ title: 'Night call', transcript: 'Keep the receiver warm.',
+ }],
+ nextSeasonTeaser: { title: 'Beyond', transcript: 'Something answers.' },
+ };
+ await updateLoom(loomId, { seriesPlan: {
+ storyArc: 'A courier learns to listen.', plotPoints: [], sideQuests: [], ...delivery,
+ } });
+ runStagedLLM.mockResolvedValueOnce({ content: generatedGraph(), runId: 'run-weave-delivery' });
+ await weaveEpisode(loomId, episodeId, {});
+ expect(runStagedLLM.mock.calls[0][1].storyContext).toContain('authored overnight voicemail');
+ expect(runStagedLLM.mock.calls[0][1].storyContext).toContain('Keep the receiver warm.');
+ });
+
+ it('tells episode expansion to frame unseen obstacles for off-screen helper scenes', async () => {
+ const { loomId, episodeId } = await setup();
+ runStagedLLM.mockResolvedValueOnce({ content: generatedGraph(), runId: 'run-offscreen-framing' });
+
+ await weaveEpisode(loomId, episodeId, {});
+
+ expect(runStagedLLM.mock.calls[0][1].storyContext)
+ .toContain('frame the obstacle or space the protagonist cannot see');
+ expect(runStagedLLM.mock.calls[0][1].storyContext)
+ .toContain('never make a standalone comms device the subject');
+ });
});