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): orchestrate episodic production and continuity review (#5410)

[._.]/ Adam Eivy251524cd15bd
diff --git a/client/src/components/fableloom/LoomProductionPanel.jsx b/client/src/components/fableloom/LoomProductionPanel.jsx
new file mode 100644
index 0000000000..5bcc6d2b64
--- /dev/null
+++ b/client/src/components/fableloom/LoomProductionPanel.jsx
@@ -0,0 +1,560 @@
+/**
+ * FableLoom production orchestration and episodic continuity review panel.
+ *
+ * Provides user-triggered batch production planning, DAG asset enumeration,
+ * exact-input verification, batch execution tracking, and episodic continuity review.
+ */
+
+import { useEffect, useState } from 'react';
+import {
+ AlertTriangle,
+ CheckCircle2,
+ CircleAlert,
+ Cloud,
+ Cpu,
+ Film,
+ Info,
+ Layers,
+ Loader2,
+ Play,
+ RotateCcw,
+ Sparkles,
+ StopCircle,
+} from 'lucide-react';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import BackendChipStrip from '../media/BackendChipStrip';
+import {
+ cancelLoomEpisodeProductionBatch,
+ getLoomEpisodeProductionBatch,
+ listImageModels,
+ listVideoModels,
+ planLoomEpisodeProduction,
+ reviewLoomEpisodeContinuity,
+ resumeLoomEpisodeProductionBatch,
+ startLoomEpisodeProductionBatch,
+} from '../../services/api';
+
+const IMAGE_BACKENDS = [
+ { id: 'auto', label: 'Auto', icon: Layers },
+ { id: 'local', label: 'Local', icon: Cpu },
+ { id: 'codex', label: 'Codex', icon: Cloud },
+ { id: 'grok', label: 'Grok', icon: Cloud },
+ { id: 'agy', label: 'Agy', icon: Sparkles },
+];
+
+const VIDEO_BACKENDS = [
+ { id: 'auto', label: 'Auto', icon: Layers },
+ { id: 'local', label: 'Local', icon: Cpu },
+ { id: 'grok', label: 'Grok', icon: Cloud },
+];
+
+const modelOptions = (models) => (Array.isArray(models) ? models : [])
+ .filter((model) => model?.id)
+ .map((model) => ({ id: model.id, label: model.name || model.id }));
+
+const severityIcon = (severity) => {
+ if (severity === 'error' || severity === 'high') {
+ return <CircleAlert size={14} className="text-port-error shrink-0 mt-0.5" />;
+ }
+ if (severity === 'warning') {
+ return <AlertTriangle size={14} className="text-port-warning shrink-0 mt-0.5" />;
+ }
+ return <Info size={14} className="text-port-accent shrink-0 mt-0.5" />;
+};
+
+export default function LoomProductionPanel({ loom, episode, onSelectNode }) {
+ const [mode, setMode] = useState('current_canon');
+ const [plan, setPlan] = useState(null);
+ const [activeBatchRun, setActiveBatchRun] = useState(null);
+ const [continuityReview, setContinuityReview] = useState(null);
+ const [categoryFilter, setCategoryFilter] = useState('all');
+ const [imageMode, setImageMode] = useState(null);
+ const [imageModel, setImageModel] = useState(null);
+ const [videoMode, setVideoMode] = useState(null);
+ const [videoModel, setVideoModel] = useState(null);
+ const [effort, setEffort] = useState(null);
+ const [imageModels, setImageModels] = useState([]);
+ const [videoModels, setVideoModels] = useState([]);
+
+ const renderOptions = (targetMode = mode) => ({
+ mode: targetMode,
+ ...(imageMode ? { imageMode } : {}),
+ ...(imageModel ? { imageModel } : {}),
+ ...(videoMode ? { videoMode } : {}),
+ ...(videoModel ? { videoModel } : {}),
+ ...(effort ? { effort } : {}),
+ });
+
+ const [fetchPlan, planning] = useAsyncAction(async (targetMode = mode) => {
+ const res = await planLoomEpisodeProduction(loom.id, episode.id, renderOptions(targetMode), { silent: true });
+ setPlan(res);
+ }, { errorMessage: 'Production planning failed' });
+
+ useEffect(() => {
+ const load = (loader) => (typeof loader === 'function'
+ ? Promise.resolve().then(() => loader({ silent: true })).catch(() => [])
+ : Promise.resolve([]));
+ let mounted = true;
+ Promise.all([load(listImageModels), load(listVideoModels)]).then(([images, videos]) => {
+ if (!mounted) return;
+ setImageModels(images);
+ setVideoModels(videos);
+ });
+ return () => { mounted = false; };
+ }, []);
+
+ useEffect(() => {
+ fetchPlan(mode);
+ }, [loom.id, episode.id, mode, imageMode, imageModel, videoMode, videoModel, effort]);
+
+ // Batch run polling
+ useEffect(() => {
+ if (!activeBatchRun || activeBatchRun.status !== 'in_progress') return undefined;
+ const interval = setInterval(() => {
+ getLoomEpisodeProductionBatch(loom.id, episode.id, activeBatchRun.id, { silent: true })
+ .then((updated) => {
+ if (!updated) return;
+ setActiveBatchRun(updated);
+ if (updated.status === 'completed' || updated.status === 'canceled' || updated.status === 'failed') {
+ fetchPlan(mode);
+ }
+ })
+ .catch(() => {
+ // Polling is best-effort; the next interval can reattach to the run.
+ });
+ }, 2000);
+ return () => clearInterval(interval);
+ }, [activeBatchRun, loom.id, episode.id, mode]);
+
+ const [startBatch, startingBatch] = useAsyncAction(async () => {
+ const res = await startLoomEpisodeProductionBatch(loom.id, episode.id, renderOptions(), { silent: true });
+ setActiveBatchRun(res);
+ }, { errorMessage: 'Starting production batch failed' });
+
+ const [cancelBatch, cancelingBatch] = useAsyncAction(async () => {
+ if (!activeBatchRun) return;
+ const res = await cancelLoomEpisodeProductionBatch(loom.id, episode.id, activeBatchRun.id, { silent: true });
+ setActiveBatchRun(res);
+ }, { errorMessage: 'Canceling batch run failed' });
+
+ const [resumeBatch, resumingBatch] = useAsyncAction(async () => {
+ if (!activeBatchRun) return;
+ const res = await resumeLoomEpisodeProductionBatch(loom.id, episode.id, activeBatchRun.id, { silent: true });
+ setActiveBatchRun(res);
+ }, { errorMessage: 'Resuming batch run failed' });
+
+ const [runContinuityReview, reviewingContinuity] = useAsyncAction(async () => {
+ const res = await reviewLoomEpisodeContinuity(loom.id, episode.id, {}, { silent: true });
+ setContinuityReview(res);
+ }, { errorMessage: 'Continuity review failed' });
+
+ const filteredFindings = (continuityReview?.findings || []).filter((f) => {
+ if (categoryFilter === 'all') return true;
+ return f.category === categoryFilter;
+ });
+
+ const readinessBlockers = [
+ ...(plan?.planningIssues || []).map((message) => ({ message, nodeId: null })),
+ ...(plan?.plannedAssets || [])
+ .filter((asset) => asset.status === 'blocked' || asset.readiness?.ready === false)
+ .flatMap((asset) => (asset.readiness?.reasons || []).map((message) => ({
+ message,
+ nodeId: asset.nodeId,
+ }))),
+ ].filter((item, index, items) => items.findIndex((candidate) => (
+ candidate.message === item.message && candidate.nodeId === item.nodeId
+ )) === index);
+
+ return (
+ <div className="p-4 space-y-6">
+ {/* 1. Production Mode & Plan Summary */}
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <h3 className="text-sm font-semibold flex items-center gap-1.5">
+ <Layers size={14} className="text-port-accent" />
+ Episodic Production Plan
+ </h3>
+ <button
+ type="button"
+ onClick={() => fetchPlan(mode)}
+ disabled={planning}
+ className="text-xs text-port-text-muted hover:text-port-text flex items-center gap-1"
+ title="Refresh plan"
+ >
+ <RotateCcw size={11} className={planning ? 'animate-spin' : ''} />
+ Refresh
+ </button>
+ </div>
+
+ {/* Mode selector */}
+ <div className="flex items-center gap-2 mb-3">
+ <label htmlFor="fableloom-production-mode" className="text-xs text-port-text-muted">Mode:</label>
+ <select
+ id="fableloom-production-mode"
+ value={mode}
+ onChange={(e) => setMode(e.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="current_canon">Regenerate with current canon</option>
+ <option value="exact_inputs">Repeat exact inputs</option>
+ </select>
+ </div>
+
+ {planning && !plan && (
+ <div className="flex items-center gap-2 text-xs text-port-text-muted py-2">
+ <Loader2 size={12} className="animate-spin" />
+ Enumerating planned assets and DAG dependencies…
+ </div>
+ )}
+
+ {plan && (
+ <div className="space-y-3">
+ <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-[10px] text-port-text-muted mt-0.5">
+ {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}
+ </div>
+ <div className="text-[10px] text-port-text-muted mt-0.5">
+ {plan.blockedAssetsCount} blocked
+ </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">Reachable Scenes</div>
+ <div className="text-sm font-bold mt-0.5">
+ {plan.reachableNodeCount} / {plan.totalNodes}
+ </div>
+ <div className="text-[10px] text-port-text-muted mt-0.5">
+ {plan.executionStages?.length || 0} batches
+ </div>
+ </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">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-[11px] text-port-text-muted w-14">Images</span>
+ <BackendChipStrip
+ availableBackends={IMAGE_BACKENDS}
+ value={imageMode || 'auto'}
+ onChange={(value) => setImageMode(value === 'auto' ? null : value)}
+ size="sm"
+ ariaLabel="Image provider"
+ />
+ {(imageMode === 'local' || !imageMode) && (
+ <label htmlFor="fableloom-image-model" className="sr-only">Image model</label>
+ )}
+ {(imageMode === 'local' || !imageMode) && (
+ <select
+ id="fableloom-image-model"
+ value={imageModel || ''}
+ onChange={(event) => setImageModel(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 image model</option>
+ {modelOptions(imageModels).map((modelOption) => (
+ <option key={modelOption.id} value={modelOption.id}>{modelOption.label}</option>
+ ))}
+ </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>
+ <div className="flex items-center gap-2">
+ <label htmlFor="fableloom-render-effort" className="text-[11px] text-port-text-muted w-14">Effort</label>
+ <select
+ id="fableloom-render-effort"
+ value={effort || ''}
+ onChange={(event) => setEffort(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="">Provider default</option>
+ <option value="low">Low</option>
+ <option value="medium">Medium</option>
+ <option value="high">High</option>
+ </select>
+ <span className="text-[10px] text-port-text-muted">Used when the selected provider supports it.</span>
+ </div>
+ </div>
+ </div>
+
+ {readinessBlockers.length > 0 && (
+ <div className="p-2.5 rounded bg-port-warning/10 border border-port-warning/30 text-xs space-y-1">
+ <div className="font-semibold flex items-center gap-1 text-port-warning">
+ <AlertTriangle size={12} />
+ Resolve readiness blockers before starting
+ </div>
+ {readinessBlockers.map((blocker, index) => (
+ <button
+ key={`${blocker.nodeId || 'plan'}-${index}`}
+ type="button"
+ onClick={() => blocker.nodeId && onSelectNode && onSelectNode(blocker.nodeId)}
+ disabled={!blocker.nodeId}
+ className={`block w-full text-left text-[11px] text-port-text-muted pl-4 ${blocker.nodeId ? 'hover:text-port-text' : ''}`}
+ >
+ {blocker.message}{blocker.nodeId ? ` · scene [${blocker.nodeId}]` : ''}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* Exact Input Issues */}
+ {plan.exactInputIssues?.length > 0 && (
+ <div className="p-2.5 rounded bg-port-error/10 border border-port-error/30 text-xs text-port-error space-y-1">
+ <div className="font-semibold flex items-center gap-1">
+ <CircleAlert size={12} />
+ Exact-input reproduction refused ({plan.exactInputIssues.length} issue(s))
+ </div>
+ {plan.exactInputIssues.map((issue, idx) => (
+ <div key={idx} className="text-[11px] text-port-text-muted pl-4">
+ Scene [{issue.nodeId}]: {issue.errors.join('; ')}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Convergence details */}
+ {plan.convergenceIssues?.length > 0 && (
+ <div className="p-2 rounded bg-port-card border border-port-border text-xs space-y-1">
+ <div className="font-semibold text-port-text-muted flex items-center gap-1 text-[11px]">
+ <Info size={12} />
+ Graph Convergence ({plan.convergenceIssues.length} scene(s))
+ </div>
+ {plan.convergenceIssues.map((c, i) => (
+ <div key={i} className="text-[11px] text-port-text-muted">
+ "{c.nodeTitle}" ({c.predecessorCount} inputs) → {c.selectedPredecessorId
+ ? `using predecessor [${c.selectedPredecessorId}]`
+ : 'no predecessor inherited; set an explicit continuity source'}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {plan.plannedAssets?.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="max-h-52 overflow-y-auto space-y-1">
+ {plan.plannedAssets.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
+ type="button"
+ onClick={() => onSelectNode && onSelectNode(asset.nodeId)}
+ className="truncate text-left text-port-text hover:text-port-accent"
+ title={`Open scene ${asset.nodeId}`}
+ >
+ {asset.nodeTitle || asset.nodeId}
+ </button>
+ <span className="text-port-text-muted shrink-0">{asset.type.replaceAll('_', ' ')}</span>
+ <span className="text-port-text-muted ml-auto shrink-0">stage {asset.stageIndex + 1}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Batch execution controls */}
+ <div className="pt-1 flex items-center gap-2">
+ {activeBatchRun && ['failed', 'canceled'].includes(activeBatchRun.status) ? (
+ <button
+ type="button"
+ onClick={resumeBatch}
+ disabled={resumingBatch}
+ 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"
+ >
+ {resumingBatch ? <Loader2 size={12} className="animate-spin" /> : <RotateCcw size={12} />}
+ Resume Batch Production
+ </button>
+ ) : !activeBatchRun || activeBatchRun.status !== 'in_progress' ? (
+ <button
+ type="button"
+ onClick={startBatch}
+ disabled={startingBatch || plan.isFullyReady === false}
+ 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
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={cancelBatch}
+ disabled={cancelingBatch}
+ className="flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded bg-port-error text-white hover:bg-port-error/90 disabled:opacity-50"
+ >
+ {cancelingBatch ? <Loader2 size={12} className="animate-spin" /> : <StopCircle size={12} />}
+ Cancel Production Batch
+ </button>
+ )}
+
+ {activeBatchRun && (
+ <span className="text-xs text-port-text-muted">
+ Status: <strong className="capitalize">{activeBatchRun.status}</strong> ({activeBatchRun.summary?.completed || 0}/{activeBatchRun.summary?.total || 0} done)
+ {activeBatchRun.error ? ` — ${activeBatchRun.error}` : ''}
+ </span>
+ )}
+ </div>
+
+ {activeBatchRun?.assets?.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">Recorded asset provenance</div>
+ <div className="max-h-64 overflow-y-auto space-y-1">
+ {activeBatchRun.assets.map((asset) => {
+ const manifest = asset.visualConditioning;
+ const capability = manifest?.capability || {};
+ const render = manifest?.render || {};
+ const params = render.parameters || asset.effectiveParameters || {};
+ return (
+ <details key={asset.id} className="rounded border border-port-border/70 px-2 py-1 text-[11px]">
+ <summary className="cursor-pointer flex items-center gap-2">
+ <span className="font-medium text-port-text truncate">{asset.nodeTitle || asset.nodeId}</span>
+ <span className="text-port-text-muted">{asset.type.replaceAll('_', ' ')}</span>
+ <span className="ml-auto capitalize text-port-text-muted">{asset.status}</span>
+ </summary>
+ {manifest ? (
+ <div className="pt-1.5 pl-1 space-y-0.5 text-port-text-muted">
+ <div>Provider: {render.provider || capability.backend || 'unknown'} · Model: {render.modelId || capability.modelId || 'unknown'}{render.modelRevision || capability.modelRevision ? ` · revision ${render.modelRevision || capability.modelRevision}` : ''}</div>
+ <div>Canon refs: {manifest.assets?.length || 0} · adapters: {manifest.adapters?.length || 0} · temporal source: {manifest.temporalSourceNodeId || 'none'}</div>
+ <div>Omitted: {manifest.omitted?.length || 0} · warnings: {manifest.warnings?.length || 0}</div>
+ {Object.keys(params).length > 0 && <div>Effective parameters: {Object.entries(params).map(([key, value]) => `${key}=${String(value)}`).join(', ')}</div>}
+ </div>
+ ) : (
+ <div className="pt-1.5 pl-1 text-port-text-muted">No visual conditioning manifest was produced for this asset.</div>
+ )}
+ </details>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* 2. Episodic Continuity Review */}
+ <div className="border-t border-port-border pt-4">
+ <div className="flex items-center justify-between mb-2">
+ <h3 className="text-sm font-semibold flex items-center gap-1.5">
+ <Film size={14} className="text-port-accent" />
+ Continuity Review
+ </h3>
+ <button
+ type="button"
+ onClick={runContinuityReview}
+ disabled={reviewingContinuity}
+ className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50 font-medium"
+ >
+ {reviewingContinuity ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ Run Continuity Review
+ </button>
+ </div>
+
+ {continuityReview ? (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between text-xs">
+ <span className={continuityReview.passed ? 'text-port-success font-medium flex items-center gap-1' : 'text-port-error font-medium flex items-center gap-1'}>
+ {continuityReview.passed ? <CheckCircle2 size={13} /> : <CircleAlert size={13} />}
+ {continuityReview.passed ? 'All continuity checks passed' : `${continuityReview.summary?.errors || 0} error(s), ${continuityReview.summary?.warnings || 0} warning(s)`}
+ </span>
+ <span className="text-port-text-muted text-[11px]">
+ {continuityReview.nodesEvaluated} scenes evaluated
+ </span>
+ </div>
+
+ {/* Category filter pills */}
+ <div className="flex gap-1 overflow-x-auto pb-1 text-[11px]">
+ {['all', 'visual', 'voice', 'playback', 'graph'].map((cat) => (
+ <button
+ key={cat}
+ type="button"
+ onClick={() => setCategoryFilter(cat)}
+ className={`px-2 py-0.5 rounded capitalize ${
+ categoryFilter === cat
+ ? 'bg-port-accent text-white font-medium'
+ : 'bg-port-card border border-port-border text-port-text-muted hover:text-port-text'
+ }`}
+ >
+ {cat}
+ </button>
+ ))}
+ </div>
+
+ {/* Findings list */}
+ {filteredFindings.length > 0 ? (
+ <div className="space-y-1.5">
+ {filteredFindings.map((finding) => (
+ <button
+ key={finding.id}
+ type="button"
+ onClick={() => finding.nodeId && onSelectNode && onSelectNode(finding.nodeId)}
+ disabled={!finding.nodeId}
+ className={`w-full text-left flex items-start gap-2 text-xs rounded p-2 border border-port-border ${
+ finding.nodeId ? 'hover:border-port-accent cursor-pointer' : 'cursor-default'
+ }`}
+ >
+ {severityIcon(finding.severity)}
+ <div className="flex-1">
+ <div className="font-medium text-port-text">{finding.message}</div>
+ {finding.remediation && (
+ <div className="text-[11px] text-port-text-muted mt-0.5">
+ Remediation: {finding.remediation}
+ </div>
+ )}
+ {finding.nodeId && (
+ <div className="text-[10px] text-port-accent mt-1">
+ Jump to scene [{finding.nodeId}]
+ </div>
+ )}
+ </div>
+ </button>
+ ))}
+ </div>
+ ) : (
+ <p className="text-xs text-port-text-muted">
+ No {categoryFilter === 'all' ? '' : categoryFilter} continuity issues found.
+ </p>
+ )}
+ </div>
+ ) : (
+ <p className="text-xs text-port-text-muted">
+ Inspect character visual bindings, wardrobe continuity, voice profile drift, pronunciation anchors, and live hold loops.
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/fableloom/LoomProductionPanel.test.jsx b/client/src/components/fableloom/LoomProductionPanel.test.jsx
new file mode 100644
index 0000000000..33d40e9e4b
--- /dev/null
+++ b/client/src/components/fableloom/LoomProductionPanel.test.jsx
@@ -0,0 +1,109 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import LoomProductionPanel from './LoomProductionPanel';
+import * as api from '../../services/api';
+
+vi.mock('../../services/api');
+
+describe('LoomProductionPanel', () => {
+ const sampleLoom = { id: 'loom-1', name: 'Test Loom' };
+ const sampleEpisode = { id: 'ep-1', title: 'Episode 1' };
+
+ const samplePlan = {
+ mode: 'current_canon',
+ totalNodes: 3,
+ reachableNodeCount: 3,
+ totalAssets: 6,
+ readyAssetsCount: 4,
+ alreadyRenderedCount: 2,
+ blockedAssetsCount: 0,
+ assetsByType: { image: 3, video: 3, dialogue: 0 },
+ executionStages: [{ stageIndex: 0, assetCount: 2 }],
+ plannedAssets: [
+ { id: 'asset-1', nodeId: 'node-1', type: 'image', status: 'ready' },
+ { id: 'asset-2', nodeId: 'node-1', type: 'video_entry', status: 'ready' },
+ ],
+ convergenceIssues: [],
+ exactInputIssues: [],
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.planLoomEpisodeProduction.mockResolvedValue(samplePlan);
+ api.startLoomEpisodeProductionBatch.mockResolvedValue({
+ id: 'batch-1',
+ status: 'in_progress',
+ summary: { total: 6, completed: 2 },
+ });
+ api.reviewLoomEpisodeContinuity.mockResolvedValue({
+ passed: false,
+ nodesEvaluated: 3,
+ summary: { errors: 1, warnings: 0, info: 0 },
+ findings: [
+ {
+ id: 'f-1',
+ category: 'visual',
+ severity: 'error',
+ code: 'MISSING_UNIVERSE_CHARACTER',
+ message: 'Character missing in Universe',
+ remediation: 'Rebind character',
+ nodeId: 'node-1',
+ },
+ ],
+ });
+ });
+
+ it('renders plan summary and allows switching mode', async () => {
+ render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={vi.fn()} />);
+
+ await waitFor(() => {
+ expect(screen.getByText('Episodic Production Plan')).toBeInTheDocument();
+ });
+
+ expect(screen.getByText('6')).toBeInTheDocument(); // total assets
+ expect(screen.getByText('Start Batch Production')).toBeInTheDocument();
+
+ const modeSelect = screen.getByLabelText('Mode:');
+ fireEvent.change(modeSelect, { target: { value: 'exact_inputs' } });
+
+ await waitFor(() => {
+ expect(api.planLoomEpisodeProduction).toHaveBeenCalledWith('loom-1', 'ep-1', { mode: 'exact_inputs' }, { silent: true });
+ });
+ });
+
+ it('starts batch production when button is clicked', async () => {
+ render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={vi.fn()} />);
+
+ await waitFor(() => {
+ expect(screen.getByText('Start Batch Production')).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByText('Start Batch Production'));
+
+ await waitFor(() => {
+ expect(api.startLoomEpisodeProductionBatch).toHaveBeenCalledWith('loom-1', 'ep-1', { mode: 'current_canon' }, { silent: true });
+ expect(screen.getByText('Cancel Production Batch')).toBeInTheDocument();
+ });
+ });
+
+ it('runs continuity review and displays findings with node selection', async () => {
+ const onSelectNode = vi.fn();
+ render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={onSelectNode} />);
+
+ await waitFor(() => {
+ expect(screen.getByText('Run Continuity Review')).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByText('Run Continuity Review'));
+
+ await waitFor(() => {
+ expect(api.reviewLoomEpisodeContinuity).toHaveBeenCalledWith('loom-1', 'ep-1', {}, { silent: true });
+ expect(screen.getByText('Character missing in Universe')).toBeInTheDocument();
+ expect(screen.getByText('Remediation: Rebind character')).toBeInTheDocument();
+ });
+
+ const findingButton = screen.getByText('Character missing in Universe').closest('button');
+ fireEvent.click(findingButton);
+ expect(onSelectNode).toHaveBeenCalledWith('node-1');
+ });
+});
diff --git a/client/src/components/fableloom/LoomValidationPanel.jsx b/client/src/components/fableloom/LoomValidationPanel.jsx
index 2d644edea6..413b494192 100644
--- a/client/src/components/fableloom/LoomValidationPanel.jsx
+++ b/client/src/components/fableloom/LoomValidationPanel.jsx
@@ -6,18 +6,22 @@
*/
import { useEffect, useMemo, useState } from 'react';
-import { AlertTriangle, CircleAlert, Loader2, Sparkles } from 'lucide-react';
+import { AlertTriangle, CircleAlert, Layers, Loader2, Sparkles, Waypoints } from 'lucide-react';
import { useAsyncAction } from '../../hooks/useAsyncAction';
import { reviewLoomEpisode, validateLoomEpisode } from '../../services/api';
+import LoomProductionPanel from './LoomProductionPanel';
+
const severityIcon = (severity) => (severity === 'error' || severity === 'high'
? <CircleAlert size={13} className="text-port-error shrink-0 mt-0.5" />
: <AlertTriangle size={13} className="text-port-warning shrink-0 mt-0.5" />);
export default function LoomValidationPanel({ loom, episode, onSelectNode }) {
+ const [activeTab, setActiveTab] = useState('structure');
const [structural, setStructural] = useState(null);
const [review, setReview] = useState(null);
+
// Re-validate only when the graph STRUCTURE changes — a prose edit or a
// node drag bumps episode.updatedAt but can't change reachability, so
// keying on updatedAt would re-run the full-loom server analysis on every
@@ -63,76 +67,110 @@ export default function LoomValidationPanel({ loom, episode, onSelectNode }) {
return (
<div className="p-4 space-y-4">
- <div>
- <div className="flex items-center justify-between mb-2">
- <h3 className="text-sm font-semibold">Structure</h3>
- {structural?.stats && (
- <span className="text-xs text-port-text-muted">
- {structural.stats.automaticCutCount} cuts · {structural.stats.decisionCount} decisions ·{' '}
- {structural.stats.reachableEndingCount}/{structural.stats.endingCount} endings reachable
- · depth {structural.stats.maxDepth}
- </span>
- )}
- </div>
- {structural?.issues?.length ? (
- <div className="space-y-1.5">
- {structural.issues.map((issue, i) => findingRow(issue, `s-${i}`, issue.nodeId))}
- </div>
- ) : structural ? (
- <p className="text-xs text-port-success">Graph is sound — every path reaches an ending.</p>
- ) : (
- <p className="text-xs text-port-text-muted">Validating…</p>
- )}
+ {/* Panel Tab Navigation */}
+ <div className="flex border-b border-port-border mb-3 text-xs">
+ <button
+ type="button"
+ onClick={() => setActiveTab('structure')}
+ className={`px-3 py-1.5 font-medium border-b-2 flex items-center gap-1.5 ${
+ activeTab === 'structure'
+ ? 'border-port-accent text-port-accent'
+ : 'border-transparent text-port-text-muted hover:text-port-text'
+ }`}
+ >
+ <Waypoints size={13} />
+ Structure & Story
+ </button>
+ <button
+ type="button"
+ onClick={() => setActiveTab('production')}
+ className={`px-3 py-1.5 font-medium border-b-2 flex items-center gap-1.5 ${
+ activeTab === 'production'
+ ? 'border-port-accent text-port-accent'
+ : 'border-transparent text-port-text-muted hover:text-port-text'
+ }`}
+ >
+ <Layers size={13} />
+ Production & Continuity
+ </button>
</div>
- {structural?.productionReadiness && (
- <div>
- <div className="flex items-center justify-between mb-2">
- <h3 className="text-sm font-semibold">Production readiness</h3>
- <span className="text-xs text-port-text-muted">
- {structural.productionReadiness.ready ? 'Ready for live voice' : `${structural.productionReadiness.totalErrors} blocking error(s)`}
- </span>
+ {activeTab === 'production' ? (
+ <LoomProductionPanel loom={loom} episode={episode} onSelectNode={onSelectNode} />
+ ) : (
+ <>
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <h3 className="text-sm font-semibold">Structure</h3>
+ {structural?.stats && (
+ <span className="text-xs text-port-text-muted">
+ {structural.stats.automaticCutCount} cuts · {structural.stats.decisionCount} decisions ·{' '}
+ {structural.stats.reachableEndingCount}/{structural.stats.endingCount} endings reachable
+ · depth {structural.stats.maxDepth}
+ </span>
+ )}
+ </div>
+ {structural?.issues?.length ? (
+ <div className="space-y-1.5">
+ {structural.issues.map((issue, i) => findingRow(issue, `s-${i}`, issue.nodeId))}
+ </div>
+ ) : structural ? (
+ <p className="text-xs text-port-success">Graph is sound — every path reaches an ending.</p>
+ ) : (
+ <p className="text-xs text-port-text-muted">Validating…</p>
+ )}
</div>
- {structural.productionReadiness.findings?.length ? (
- <div className="space-y-1.5">
- {structural.productionReadiness.findings.map((f, i) => findingRow(f, `pr-${i}`, f.nodeId))}
+
+ {structural?.productionReadiness && (
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <h3 className="text-sm font-semibold">Production readiness</h3>
+ <span className="text-xs text-port-text-muted">
+ {structural.productionReadiness.ready ? 'Ready for live voice' : `${structural.productionReadiness.totalErrors} blocking error(s)`}
+ </span>
+ </div>
+ {structural.productionReadiness.findings?.length ? (
+ <div className="space-y-1.5">
+ {structural.productionReadiness.findings.map((f, i) => findingRow(f, `pr-${i}`, f.nodeId))}
+ </div>
+ ) : (
+ <p className="text-xs text-port-success">All scenes meet audio occupancy and off-screen voice standards.</p>
+ )}
</div>
- ) : (
- <p className="text-xs text-port-success">All scenes meet audio occupancy and off-screen voice standards.</p>
)}
- </div>
- )}
- <div>
- <div className="flex items-center justify-between mb-2">
- <h3 className="text-sm font-semibold">Story review</h3>
- <button
- type="button"
- onClick={runReview}
- disabled={reviewing}
- 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
- </button>
- </div>
- {review ? (
- <div className="space-y-2">
- {review.summary && <p className="text-xs text-port-text-muted">{review.summary}</p>}
- {review.findings.length ? (
- <div className="space-y-1.5">
- {review.findings.map((finding, i) => findingRow(finding, `r-${i}`, finding.nodeId))}
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <h3 className="text-sm font-semibold">Story review</h3>
+ <button
+ type="button"
+ onClick={runReview}
+ disabled={reviewing}
+ 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
+ </button>
+ </div>
+ {review ? (
+ <div className="space-y-2">
+ {review.summary && <p className="text-xs text-port-text-muted">{review.summary}</p>}
+ {review.findings.length ? (
+ <div className="space-y-1.5">
+ {review.findings.map((finding, i) => findingRow(finding, `r-${i}`, finding.nodeId))}
+ </div>
+ ) : (
+ <p className="text-xs text-port-success">No narrative issues found.</p>
+ )}
</div>
) : (
- <p className="text-xs text-port-success">No narrative issues found.</p>
+ <p className="text-xs text-port-text-muted">
+ Ask the AI story editor to critique intents, branches, and endings.
+ </p>
)}
</div>
- ) : (
- <p className="text-xs text-port-text-muted">
- Ask the AI story editor to critique intents, branches, and endings.
- </p>
- )}
- </div>
+ </>
+ )}
</div>
);
}
diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.js
index edbcf9c4bb..86629bf379 100644
--- a/client/src/services/apiFableLoom.js
+++ b/client/src/services/apiFableLoom.js
@@ -120,3 +120,30 @@ export const endHostedLoomSession = (sessionId, options = {}) =>
method: 'DELETE', ...options,
});
+export const planLoomEpisodeProduction = (id, episodeId, body = {}, options = {}) =>
+ request(episodePath(id, episodeId, '/production/plan'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
+
+export const startLoomEpisodeProductionBatch = (id, episodeId, body = {}, options = {}) =>
+ request(episodePath(id, episodeId, '/production/batch'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
+
+export const getLoomEpisodeProductionBatch = (id, episodeId, runId, options = {}) =>
+ request(episodePath(id, episodeId, `/production/batch/${encodeURIComponent(runId)}`), options);
+
+export const cancelLoomEpisodeProductionBatch = (id, episodeId, runId, options = {}) =>
+ request(episodePath(id, episodeId, `/production/batch/${encodeURIComponent(runId)}/cancel`), {
+ method: 'POST', body: JSON.stringify({}), ...options,
+ });
+
+export const resumeLoomEpisodeProductionBatch = (id, episodeId, runId, options = {}) =>
+ request(episodePath(id, episodeId, `/production/batch/${encodeURIComponent(runId)}/resume`), {
+ method: 'POST', body: JSON.stringify({}), ...options,
+ });
+
+export const reviewLoomEpisodeContinuity = (id, episodeId, body = {}, options = {}) =>
+ request(episodePath(id, episodeId, '/continuity/review'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
diff --git a/client/src/services/apiFableLoom.test.js b/client/src/services/apiFableLoom.test.js
index 6eccb58e29..ffdc2f51a4 100644
--- a/client/src/services/apiFableLoom.test.js
+++ b/client/src/services/apiFableLoom.test.js
@@ -14,7 +14,6 @@ beforeEach(async () => {
request.mockReset();
request.mockResolvedValue({});
});
-
describe('apiFableLoom', () => {
it('lists every loom when no series scope is given', async () => {
await api.listLooms({ silent: true });
@@ -112,4 +111,42 @@ describe('apiFableLoom', () => {
await api.deleteLoomNode('loom-1', 'ep-1', 'node-1');
expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/nodes/node-1', { method: 'DELETE' });
});
+
+ it('posts production planning and batch operations', async () => {
+ await api.planLoomEpisodeProduction('loom-1', 'ep-1', { mode: 'current_canon' });
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/production/plan', {
+ method: 'POST',
+ body: JSON.stringify({ mode: 'current_canon' }),
+ });
+
+ await api.startLoomEpisodeProductionBatch('loom-1', 'ep-1', { mode: 'exact_inputs' });
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/production/batch', {
+ method: 'POST',
+ body: JSON.stringify({ mode: 'exact_inputs' }),
+ });
+
+ await api.getLoomEpisodeProductionBatch('loom-1', 'ep-1', 'batch-1', { silent: true });
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/production/batch/batch-1', { silent: true });
+
+ await api.cancelLoomEpisodeProductionBatch('loom-1', 'ep-1', 'batch-1');
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/production/batch/batch-1/cancel', {
+ method: 'POST',
+ body: JSON.stringify({}),
+ });
+
+ await api.resumeLoomEpisodeProductionBatch('loom-1', 'ep-1', 'batch/1', { silent: true });
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/production/batch/batch%2F1/resume', {
+ method: 'POST',
+ body: JSON.stringify({}),
+ silent: true,
+ });
+ });
+
+ it('posts episodic continuity review', async () => {
+ await api.reviewLoomEpisodeContinuity('loom-1', 'ep-1');
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/continuity/review', {
+ method: 'POST',
+ body: JSON.stringify({}),
+ });
+ });
});
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 05117f2752..34acc85506 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -215,6 +215,30 @@ draft/degraded work. The completion hook
Decision videos are authored as seamless loops; automatic-cut videos land on
a final beat that hands cleanly to the next node.
+### Episodic production and continuity
+
+The **Production & Continuity** panel plans a whole episode before it queues
+provider work. It enumerates reachable scenes and typed assets (still,
+entry/hold/exit clips, and live-dialogue readiness), orders them by their
+dependencies, and exposes the selected image/video provider, model, and effort
+controls. Starting a batch is an explicit author action; it can be canceled,
+polled, and resumed after a failed or canceled asset. Dialogue is kept as a
+hosted interaction route rather than silently generating an offline audio
+batch.
+
+Each queued render records its effective provider, model/revision, parameters,
+canon bindings, references, adapters, omissions, warnings, and temporal source
+alongside the scene asset. **Repeat exact inputs** checks those recorded
+manifests and refuses missing assets, local model revisions, or changed
+compiled conditioning instead of falling back to a newer local default.
+
+**Run Continuity Review** is also explicit and deterministic. It reports
+wrong or missing character/wardrobe/place/object bindings, ambiguous graph
+convergence, voice/profile and pronunciation drift, unsafe hold-loop audio,
+clipping, and hosted-interaction readiness. Findings include scene links and
+remediation text; the review never mutates canon or promotes a replacement
+asset.
+
The character/environment canon-reference design and rationale is specified in
[`docs/plans/2026-08-29-fableloom-visual-continuity.md`](../plans/2026-08-29-fableloom-visual-continuity.md).
The character voice, production provenance, playback-asset, QR join, and
diff --git a/scripts/migrations/316-fableloom-production-assets.js b/scripts/migrations/316-fableloom-production-assets.js
new file mode 100644
index 0000000000..d25d6280ad
--- /dev/null
+++ b/scripts/migrations/316-fableloom-production-assets.js
@@ -0,0 +1,14 @@
+/**
+ * Register the additive FableLoom production provenance shape.
+ *
+ * Existing looms need no rewrite: the record sanitizer preserves the optional
+ * per-asset conditioning map, while new renders populate it as they complete.
+ * The fableLoom schema-version gate still advances so a peer that cannot retain
+ * typed playback provenance pauses federation instead of round-tripping it away.
+ */
+
+export default {
+ async up() {
+ console.log('🧶 FableLoom production provenance: additive playback fields are lazy-populated; no existing-record rewrite required');
+ },
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index 9b10d28615..a15dbe19b9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -36,6 +36,8 @@ 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. |
+| `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. |
| `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 3d928f3c3f..0f9236a260 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -8724,7 +8724,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 80
+ "line": 89
}
]
},
@@ -8735,7 +8735,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 87
+ "line": 96
}
]
},
@@ -8746,7 +8746,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 103
+ "line": 112
}
]
},
@@ -8757,7 +8757,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 92
+ "line": 101
}
]
},
@@ -8768,7 +8768,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 98
+ "line": 107
}
]
},
@@ -8779,7 +8779,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 127
+ "line": 136
}
]
},
@@ -8790,7 +8790,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 137
+ "line": 146
}
]
},
@@ -8801,7 +8801,18 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 132
+ "line": 141
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/continuity/review",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 322
}
]
},
@@ -8812,7 +8823,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 230
+ "line": 239
}
]
},
@@ -8823,7 +8834,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 169
+ "line": 178
}
]
},
@@ -8834,7 +8845,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 179
+ "line": 188
}
]
},
@@ -8845,7 +8856,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 174
+ "line": 183
}
]
},
@@ -8856,7 +8867,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 217
+ "line": 226
}
]
},
@@ -8867,7 +8878,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 158
+ "line": 167
}
]
},
@@ -8878,7 +8889,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 192
+ "line": 201
}
]
},
@@ -8889,7 +8900,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 204
+ "line": 213
}
]
},
@@ -8900,7 +8911,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 197
+ "line": 206
}
]
},
@@ -8911,7 +8922,62 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 235
+ "line": 244
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/production/batch",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 293
+ }
+ ]
+ },
+ {
+ "method": "GET",
+ "path": "/api/fableloom/:id/episodes/:episodeId/production/batch/:runId",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 298
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/production/batch/:runId/cancel",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 306
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/production/batch/:runId/resume",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 314
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/production/plan",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ {
+ "source": "server/routes/fableLoom.js",
+ "line": 288
}
]
},
@@ -8922,7 +8988,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 246
+ "line": 255
}
]
},
@@ -8933,7 +8999,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 222
+ "line": 231
}
]
},
@@ -8944,7 +9010,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 257
+ "line": 266
}
]
},
@@ -8955,7 +9021,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 253
+ "line": 262
}
]
},
@@ -8966,7 +9032,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 142
+ "line": 151
}
]
},
@@ -8977,7 +9043,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 212
+ "line": 221
}
]
},
@@ -8988,7 +9054,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 120
+ "line": 129
}
]
},
@@ -8999,7 +9065,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 110
+ "line": 119
}
]
},
@@ -9010,7 +9076,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 115
+ "line": 124
}
]
},
@@ -9021,7 +9087,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 273
+ "line": 282
}
]
},
@@ -9032,7 +9098,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 262
+ "line": 271
}
]
},
@@ -9043,7 +9109,7 @@
"sources": [
{
"source": "server/routes/fableLoom.js",
- "line": 268
+ "line": 277
}
]
},
@@ -10099,7 +10165,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 788
+ "line": 792
}
]
},
@@ -10110,7 +10176,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 812
+ "line": 816
}
]
},
@@ -10121,7 +10187,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 807
+ "line": 811
}
]
},
@@ -10132,7 +10198,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 841
+ "line": 845
}
]
},
@@ -10143,7 +10209,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 826
+ "line": 830
}
]
},
@@ -10154,7 +10220,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 803
+ "line": 807
}
]
},
@@ -10165,7 +10231,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 731
+ "line": 735
}
]
},
@@ -10176,7 +10242,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 339
+ "line": 340
}
]
},
@@ -10187,7 +10253,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 343
+ "line": 344
}
]
},
@@ -10198,7 +10264,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 599
+ "line": 603
}
]
},
@@ -10209,7 +10275,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 737
+ "line": 741
}
]
},
@@ -10220,7 +10286,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 722
+ "line": 726
}
]
},
@@ -10231,7 +10297,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 389
+ "line": 390
}
]
},
@@ -10242,7 +10308,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 718
+ "line": 722
}
]
},
@@ -10253,7 +10319,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 621
+ "line": 625
}
]
},
@@ -10264,7 +10330,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 699
+ "line": 703
}
]
},
@@ -10275,7 +10341,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 680
+ "line": 684
}
]
},
@@ -10286,7 +10352,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 632
+ "line": 636
}
]
},
@@ -10297,7 +10363,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 660
+ "line": 664
}
]
},
@@ -10308,7 +10374,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 356
+ "line": 357
}
]
},
@@ -10418,7 +10484,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 325
+ "line": 326
}
]
},
@@ -10440,7 +10506,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 615
+ "line": 619
}
]
},
@@ -21853,7 +21919,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 909
+ "line": 911
}
]
},
@@ -21864,7 +21930,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1285
+ "line": 1290
}
]
},
@@ -21875,7 +21941,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1261
+ "line": 1266
}
]
},
@@ -21886,7 +21952,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1290
+ "line": 1295
}
]
},
@@ -21897,7 +21963,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1319
+ "line": 1324
}
]
},
@@ -21908,7 +21974,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1367
+ "line": 1372
}
]
},
@@ -21919,7 +21985,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1339
+ "line": 1344
}
]
},
@@ -21930,7 +21996,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1375
+ "line": 1380
}
]
},
@@ -21941,7 +22007,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1371
+ "line": 1376
}
]
},
@@ -21952,7 +22018,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 788
+ "line": 790
}
]
},
@@ -21963,7 +22029,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 807
+ "line": 809
}
]
},
@@ -21974,7 +22040,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1392
+ "line": 1397
}
]
},
@@ -21985,7 +22051,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 441
+ "line": 443
}
]
},
@@ -21996,7 +22062,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 445
+ "line": 447
}
]
},
@@ -22007,7 +22073,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 513
+ "line": 515
}
]
},
@@ -22018,7 +22084,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 754
+ "line": 756
}
]
},
@@ -22029,7 +22095,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 739
+ "line": 741
}
]
},
@@ -22040,7 +22106,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 642
+ "line": 644
}
]
},
@@ -22051,7 +22117,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 722
+ "line": 724
}
]
},
@@ -22062,7 +22128,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 483
+ "line": 485
}
]
},
@@ -22073,7 +22139,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 485
+ "line": 487
}
]
},
@@ -22084,7 +22150,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 479
+ "line": 481
}
]
},
@@ -22095,7 +22161,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 391
+ "line": 393
}
]
},
@@ -22106,7 +22172,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1409
+ "line": 1414
}
]
},
@@ -22117,7 +22183,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 896
+ "line": 898
}
]
},
@@ -22128,7 +22194,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 882
+ "line": 884
}
]
},
@@ -22139,7 +22205,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 852
+ "line": 854
}
]
},
@@ -22150,7 +22216,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 862
+ "line": 864
}
]
},
@@ -22161,7 +22227,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1360
+ "line": 1365
}
]
},
@@ -22172,7 +22238,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1398
+ "line": 1403
}
]
},
@@ -23411,8 +23477,8 @@
],
"stats": {
"mounts": 145,
- "operations": 2112,
- "declarations": 2115,
+ "operations": 2118,
+ "declarations": 2121,
"sourceFiles": 225
}
}
diff --git a/server/lib/fableLoomContinuity.js b/server/lib/fableLoomContinuity.js
new file mode 100644
index 0000000000..889cdc38d0
--- /dev/null
+++ b/server/lib/fableLoomContinuity.js
@@ -0,0 +1,523 @@
+/**
+ * FableLoom episodic continuity review.
+ *
+ * Deterministic, multi-vector continuity checks across an episode graph:
+ * - Visual entity bindings (characters, wardrobes, places, objects)
+ * - Graph convergence & temporal continuity source unambiguousness
+ * - Voice profile consistency & revision drift detection
+ * - Pronunciation anchor coverage for Universe terminology
+ * - Audio occupancy safety (no dialogue on hold loops, blocking effects)
+ * - Live interaction window readiness & protagonist presence safety
+ *
+ * Produces structured findings without automatic mutations.
+ */
+
+import { computeTopologicalNodeOrder } from './fableLoomProduction.js';
+import { validateAudioOccupancy } from './fableLoomPlayback.js';
+
+export const CONTINUITY_CATEGORIES = Object.freeze(['visual', 'voice', 'playback', 'graph']);
+
+export const CONTINUITY_CODES = Object.freeze({
+ MISSING_UNIVERSE_CHARACTER: 'MISSING_UNIVERSE_CHARACTER',
+ MISSING_UNIVERSE_PLACE: 'MISSING_UNIVERSE_PLACE',
+ MISSING_UNIVERSE_OBJECT: 'MISSING_UNIVERSE_OBJECT',
+ MISSING_WARDROBE_REFERENCE: 'MISSING_WARDROBE_REFERENCE',
+ WARDROBE_DRIFT: 'WARDROBE_DRIFT',
+ AMBIGUOUS_CONVERGENCE: 'AMBIGUOUS_CONVERGENCE',
+ VOICE_PROFILE_REVISION_DRIFT: 'VOICE_PROFILE_REVISION_DRIFT',
+ VOICE_ENGINE_DRIFT: 'VOICE_ENGINE_DRIFT',
+ NO_APPROVED_VOICE_PROFILE: 'NO_APPROVED_VOICE_PROFILE',
+ MISSING_PRONUNCIATION_ANCHOR: 'MISSING_PRONUNCIATION_ANCHOR',
+ HOLD_LOOP_HAS_DIALOGUE: 'HOLD_LOOP_HAS_DIALOGUE',
+ HOLD_LOOP_HAS_BLOCKING_EFFECTS: 'HOLD_LOOP_HAS_BLOCKING_EFFECTS',
+ HOLD_LOOP_HAS_CLIPPING: 'HOLD_LOOP_HAS_CLIPPING',
+ PROTAGONIST_ONSCREEN_INTERACTION: 'PROTAGONIST_ONSCREEN_INTERACTION',
+ INTERACTION_ON_ENDING_OR_CUT: 'INTERACTION_ON_ENDING_OR_CUT',
+ DISCONNECTED_INTERACTION_CHANNEL: 'DISCONNECTED_INTERACTION_CHANNEL',
+ UNREACHABLE_SCENE_CONTINUITY: 'UNREACHABLE_SCENE_CONTINUITY',
+ VOICE_MODEL_REVISION_DRIFT: 'VOICE_MODEL_REVISION_DRIFT',
+ VOICE_PROFILE_BINDING_MISMATCH: 'VOICE_PROFILE_BINDING_MISMATCH',
+ PRONUNCIATION_REVISION_DRIFT: 'PRONUNCIATION_REVISION_DRIFT',
+});
+
+const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
+
+/**
+ * Run comprehensive episodic continuity review.
+ * Pure deterministic rule evaluation — NO unsolicited AI calls.
+ */
+export function analyzeEpisodeContinuity({
+ loom = null,
+ episode = null,
+ universe = null,
+ localVoiceProfiles = [],
+} = {}) {
+ const findings = [];
+ const push = ({ category, severity, code, message, remediation, nodeId = null, characterId = null, assetId = null }) => {
+ findings.push({
+ id: `finding-${findings.length + 1}`,
+ category,
+ severity, // 'error' | 'warning' | 'info'
+ code,
+ message,
+ remediation,
+ ...(nodeId ? { nodeId } : {}),
+ ...(characterId ? { characterId } : {}),
+ ...(assetId ? { assetId } : {}),
+ });
+ };
+
+ const nodes = Array.isArray(episode?.nodes) ? episode.nodes : [];
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
+
+ const {
+ orderedNodes,
+ depthById,
+ predecessorsByNodeId,
+ convergenceNodeIds,
+ unreachableNodeIds,
+ } = computeTopologicalNodeOrder(episode);
+
+ // Track character voice profile revisions seen across all nodes in the episode
+ // characterId -> Map of profile/engine/model revision -> array of nodeIds
+ const characterVoiceRevisions = new Map();
+
+ // Universe Terminology collection for pronunciation checking
+ const universeTerms = new Set();
+ const definedPronunciations = new Set();
+
+ if (universe) {
+ if (Array.isArray(universe.characters)) {
+ for (const char of universe.characters) {
+ if (char.name) universeTerms.add(char.name.toLowerCase());
+ if (Array.isArray(char.aliases)) {
+ for (const alias of char.aliases) universeTerms.add(alias.toLowerCase());
+ }
+ if (char.voiceCanon?.pronunciations && Array.isArray(char.voiceCanon.pronunciations)) {
+ for (const p of char.voiceCanon.pronunciations) {
+ if (p.term) definedPronunciations.add(p.term.toLowerCase());
+ }
+ }
+ }
+ }
+ if (Array.isArray(universe.places)) {
+ for (const place of universe.places) {
+ if (place.name) universeTerms.add(place.name.toLowerCase());
+ }
+ }
+ if (Array.isArray(universe.objects)) {
+ for (const obj of universe.objects) {
+ if (obj.name) universeTerms.add(obj.name.toLowerCase());
+ }
+ }
+ }
+
+ // 1. Graph & Convergence Continuity
+ for (const nodeId of unreachableNodeIds) {
+ const node = nodeById.get(nodeId);
+ push({
+ category: 'graph',
+ severity: 'warning',
+ code: CONTINUITY_CODES.UNREACHABLE_SCENE_CONTINUITY,
+ message: `Scene "${node?.title || nodeId}" is unreachable from opening scene and will not be reached in story continuity.`,
+ remediation: 'Connect an incoming transition from a reachable scene or mark as opening scene.',
+ nodeId,
+ });
+ }
+
+ for (const nodeId of convergenceNodeIds) {
+ const node = nodeById.get(nodeId);
+ const preds = predecessorsByNodeId.get(nodeId) || [];
+ const explicitSource = node.visualCanon?.continuitySourceNodeId;
+ const hasValidSource = explicitSource && preds.some((pred) => pred.nodeId === explicitSource);
+ if (!hasValidSource) {
+ push({
+ category: 'graph',
+ severity: explicitSource ? 'error' : 'info',
+ code: CONTINUITY_CODES.AMBIGUOUS_CONVERGENCE,
+ message: explicitSource
+ ? `Convergence scene "${node?.title || nodeId}" names a predecessor that is not one of its ${preds.length} incoming paths.`
+ : `Convergence scene "${node?.title || nodeId}" has ${preds.length} incoming paths without an explicit visual continuity source.`,
+ remediation: 'Set visualCanon.continuitySourceNodeId to one incoming predecessor to lock deterministic continuity.',
+ nodeId,
+ });
+ }
+ }
+
+ // 2. Node-by-Node Analysis
+ for (const node of orderedNodes) {
+ const visualCanon = node.visualCanon || {};
+ const interaction = node.interactionWindow || {};
+ const assets = node.playbackAssets || {};
+
+ // Visual entity validation
+ if (universe) {
+ // Check character appearances
+ const appearances = Array.isArray(visualCanon.characterAppearances) ? visualCanon.characterAppearances : [];
+ for (const app of appearances) {
+ const charId = app.characterId;
+ const char = universe.characters?.find((c) => c.id === charId);
+ if (!char) {
+ push({
+ category: 'visual',
+ severity: 'error',
+ code: CONTINUITY_CODES.MISSING_UNIVERSE_CHARACTER,
+ message: `Bound character "${charId}" in scene "${node.title || node.id}" does not exist in Universe.`,
+ remediation: 'Rebind to an existing Universe character or create the character in Universe.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ } else if (app.wardrobeId) {
+ const wardrobeExists = Array.isArray(char.wardrobes) && char.wardrobes.some((w) => w.id === app.wardrobeId);
+ if (!wardrobeExists) {
+ push({
+ category: 'visual',
+ severity: 'warning',
+ code: CONTINUITY_CODES.MISSING_WARDROBE_REFERENCE,
+ message: `Bound wardrobe "${app.wardrobeId}" for character "${char.name || charId}" is not in Universe character wardrobes.`,
+ remediation: 'Select an approved wardrobe from Universe character sheet.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ }
+ }
+ }
+
+ // Check places
+ if (visualCanon.placeId) {
+ const place = universe.places?.find((p) => p.id === visualCanon.placeId);
+ if (!place) {
+ push({
+ category: 'visual',
+ severity: 'error',
+ code: CONTINUITY_CODES.MISSING_UNIVERSE_PLACE,
+ message: `Bound place "${visualCanon.placeId}" in scene "${node.title || node.id}" does not exist in Universe.`,
+ remediation: 'Rebind to an existing Universe location.',
+ nodeId: node.id,
+ });
+ }
+ }
+
+ // Check objects
+ const objectIds = Array.isArray(visualCanon.objectIds) ? visualCanon.objectIds : [];
+ for (const objId of objectIds) {
+ const obj = universe.objects?.find((o) => o.id === objId);
+ if (!obj) {
+ push({
+ category: 'visual',
+ severity: 'error',
+ code: CONTINUITY_CODES.MISSING_UNIVERSE_OBJECT,
+ message: `Bound object "${objId}" in scene "${node.title || node.id}" does not exist in Universe.`,
+ remediation: 'Rebind to an existing Universe object.',
+ nodeId: node.id,
+ });
+ }
+ }
+ }
+
+ // Check Predecessor Wardrobe Continuity
+ const preds = predecessorsByNodeId.get(node.id) || [];
+ const explicitSource = visualCanon.continuitySourceNodeId;
+ const continuityPreds = preds.length === 1
+ ? preds
+ : (explicitSource ? preds.filter((pred) => pred.nodeId === explicitSource) : []);
+ if (continuityPreds.length === 1) {
+ const predNode = nodeById.get(continuityPreds[0].nodeId);
+ const predAppearances = Array.isArray(predNode?.visualCanon?.characterAppearances)
+ ? predNode.visualCanon.characterAppearances
+ : [];
+ const currentAppearances = Array.isArray(visualCanon.characterAppearances)
+ ? visualCanon.characterAppearances
+ : [];
+ if (predAppearances.length && currentAppearances.length) {
+ for (const app of currentAppearances) {
+ const predApp = predAppearances.find((a) => a.characterId === app.characterId);
+ if (predApp && predApp.wardrobeId && app.wardrobeId && predApp.wardrobeId !== app.wardrobeId) {
+ push({
+ category: 'visual',
+ severity: 'info',
+ code: CONTINUITY_CODES.WARDROBE_DRIFT,
+ message: `Character "${app.characterId}" changes wardrobe from "${predApp.wardrobeId}" to "${app.wardrobeId}" across adjacent scenes.`,
+ remediation: 'Confirm wardrobe change is intentional in narrative continuity.',
+ nodeId: node.id,
+ characterId: app.characterId,
+ });
+ }
+ }
+ }
+ }
+
+ // Voice & Provenance Review
+ if (Array.isArray(assets?.provenance?.characters)) {
+ const visualCharacterIds = new Set(
+ (Array.isArray(visualCanon.characterAppearances) ? visualCanon.characterAppearances : [])
+ .map((appearance) => appearance.characterId)
+ .filter(Boolean),
+ );
+ for (const charProv of assets.provenance.characters) {
+ const charId = charProv.characterId;
+ const voiceInfo = charProv.voice;
+ if (charId && visualCharacterIds.size > 0 && !visualCharacterIds.has(charId)) {
+ push({
+ category: 'voice',
+ severity: 'error',
+ code: CONTINUITY_CODES.VOICE_PROFILE_BINDING_MISMATCH,
+ message: `Voice provenance for character "${charId}" is not bound to a character visible in scene "${node.title || node.id}".`,
+ remediation: 'Re-render the asset with the scene character binding or correct the voice binding.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ }
+ if (charId && voiceInfo) {
+ const key = `${voiceInfo.profileId || 'default'}@v${voiceInfo.profileVersion || 1} (${voiceInfo.engine || 'preset'}:${voiceInfo.modelRevision || 'unknown'})`;
+ if (!characterVoiceRevisions.has(charId)) {
+ characterVoiceRevisions.set(charId, new Map());
+ }
+ const revMap = characterVoiceRevisions.get(charId);
+ const nodeList = revMap.get(key) || [];
+ nodeList.push(node.id);
+ revMap.set(key, nodeList);
+
+ const canonCharacter = universe?.characters?.find((character) => character.id === charId);
+ const pronunciationRevision = Number.isFinite(voiceInfo.pronunciationRevision)
+ ? voiceInfo.pronunciationRevision
+ : null;
+ if (pronunciationRevision !== null
+ && Number.isFinite(canonCharacter?.voiceCanon?.version)
+ && pronunciationRevision !== canonCharacter.voiceCanon.version) {
+ push({
+ category: 'voice',
+ severity: 'warning',
+ code: CONTINUITY_CODES.PRONUNCIATION_REVISION_DRIFT,
+ message: `Character "${charId}" audio uses pronunciation revision ${pronunciationRevision}, but the current Universe voice canon is revision ${canonCharacter.voiceCanon.version}.`,
+ remediation: 'Re-render dialogue after confirming the current pronunciation anchors.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ }
+
+ const matchingProfile = localVoiceProfiles?.find((profile) => profile.id === voiceInfo.profileId);
+ if (matchingProfile) {
+ if (matchingProfile.binding?.characterId && matchingProfile.binding.characterId !== charId) {
+ push({
+ category: 'voice',
+ severity: 'error',
+ code: CONTINUITY_CODES.VOICE_PROFILE_BINDING_MISMATCH,
+ message: `Voice profile "${voiceInfo.profileId}" is bound to a different character than scene provenance expects.`,
+ remediation: 'Select the voice profile bound to this scene character and re-render the dialogue asset.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ }
+ if (Number.isFinite(voiceInfo.profileVersion) && matchingProfile.version !== voiceInfo.profileVersion) {
+ push({
+ category: 'voice',
+ severity: 'warning',
+ code: CONTINUITY_CODES.VOICE_PROFILE_REVISION_DRIFT,
+ message: `Character "${charId}" audio uses voice profile revision ${voiceInfo.profileVersion}, while the installed profile is revision ${matchingProfile.version}.`,
+ remediation: 'Re-render dialogue assets with the installed approved voice profile revision.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ }
+ if (voiceInfo.engine && matchingProfile.engine && voiceInfo.engine !== matchingProfile.engine) {
+ push({
+ category: 'voice',
+ severity: 'warning',
+ code: CONTINUITY_CODES.VOICE_ENGINE_DRIFT,
+ message: `Character "${charId}" audio uses engine "${voiceInfo.engine}", while the installed profile uses "${matchingProfile.engine}".`,
+ remediation: 'Re-render dialogue with the approved profile engine.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ }
+ if (voiceInfo.modelRevision && matchingProfile.modelRevision
+ && voiceInfo.modelRevision !== matchingProfile.modelRevision) {
+ push({
+ category: 'voice',
+ severity: 'warning',
+ code: CONTINUITY_CODES.VOICE_MODEL_REVISION_DRIFT,
+ message: `Character "${charId}" audio uses model revision "${voiceInfo.modelRevision}", while the installed profile uses "${matchingProfile.modelRevision}".`,
+ remediation: 'Re-render dialogue with the model revision recorded by the approved profile.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ }
+ }
+ }
+ }
+ }
+
+ // Interaction & Voice Binding check
+ if (interaction.enabled && interaction.protagonistCharacterId) {
+ const charId = interaction.protagonistCharacterId;
+ const approvedProfile = localVoiceProfiles?.find(
+ (p) => p.binding?.characterId === charId && p.approval?.status === 'approved',
+ );
+ if (!approvedProfile) {
+ push({
+ category: 'voice',
+ severity: 'warning',
+ code: CONTINUITY_CODES.NO_APPROVED_VOICE_PROFILE,
+ message: `Live interaction protagonist "${charId}" has no approved local voice profile in Voice Lab.`,
+ remediation: 'Create and approve a local voice profile for this character in Voice Lab.',
+ nodeId: node.id,
+ characterId: charId,
+ });
+ }
+ }
+
+ // Pronunciation anchor check in scene prose
+ const sceneText = `${node.prose || ''} ${node.title || ''}`.toLowerCase();
+ for (const term of universeTerms) {
+ if (term.length >= 4 && sceneText.includes(term) && !definedPronunciations.has(term)) {
+ push({
+ category: 'voice',
+ severity: 'info',
+ code: CONTINUITY_CODES.MISSING_PRONUNCIATION_ANCHOR,
+ message: `Universe term "${term}" appears in scene dialogue/prose without a defined pronunciation anchor.`,
+ remediation: 'Add a pronunciation guide for this term in Universe voiceCanon.pronunciations.',
+ nodeId: node.id,
+ });
+ }
+ }
+
+ // Playback & Hosted Safety Review
+ if (Array.isArray(assets.holdLoopVideoHistoryIds) && assets.holdLoopVideoHistoryIds.length) {
+ for (const holdId of assets.holdLoopVideoHistoryIds) {
+ const occ = assets.audioOccupancy?.[holdId];
+ if (occ) {
+ const validated = validateAudioOccupancy(occ);
+ if (validated.characterDialogue.length > 0) {
+ push({
+ category: 'playback',
+ severity: 'error',
+ code: CONTINUITY_CODES.HOLD_LOOP_HAS_DIALOGUE,
+ message: `Hold loop "${holdId}" in scene "${node.title || node.id}" contains rendered dialogue and cannot be used for live interaction.`,
+ remediation: 'Remove dialogue from hold loop or render as separate entry clip.',
+ nodeId: node.id,
+ assetId: holdId,
+ });
+ }
+ if (validated.effects.some((e) => e.blocking)) {
+ push({
+ category: 'playback',
+ severity: 'warning',
+ code: CONTINUITY_CODES.HOLD_LOOP_HAS_BLOCKING_EFFECTS,
+ message: `Hold loop "${holdId}" contains author-marked voice-blocking sound effects.`,
+ remediation: 'Unmark blocking flag or adjust effect timing.',
+ nodeId: node.id,
+ assetId: holdId,
+ });
+ }
+ if (validated.clipping) {
+ push({
+ category: 'playback',
+ severity: 'error',
+ code: CONTINUITY_CODES.HOLD_LOOP_HAS_CLIPPING,
+ message: `Hold loop "${holdId}" contains clipped audio${validated.peakDb !== undefined ? ` (peak ${validated.peakDb} dBFS)` : ''}.`,
+ remediation: 'Remaster the hold loop below digital full scale before enabling hosted interaction.',
+ nodeId: node.id,
+ assetId: holdId,
+ });
+ }
+ }
+ }
+ }
+
+ if (interaction.enabled) {
+ if (interaction.protagonistPresence === 'onscreen') {
+ push({
+ category: 'playback',
+ severity: 'warning',
+ code: CONTINUITY_CODES.PROTAGONIST_ONSCREEN_INTERACTION,
+ message: `Scene "${node.title || node.id}" has live voice enabled with onscreen protagonist presence.`,
+ remediation: 'Change protagonist presence to off-screen for seamless live voice conversation.',
+ nodeId: node.id,
+ });
+ }
+ if (node.isEnding || node.playbackMode === 'cut') {
+ push({
+ category: 'playback',
+ severity: 'error',
+ code: CONTINUITY_CODES.INTERACTION_ON_ENDING_OR_CUT,
+ message: `Scene "${node.title || node.id}" has live interaction enabled on an ending or automatic cut scene.`,
+ remediation: 'Disable live interaction on this scene or change playbackMode to decision.',
+ nodeId: node.id,
+ });
+ }
+ if (loom?.participationMode === 'helper' && node.audienceConnection !== 'connected') {
+ push({
+ category: 'playback',
+ severity: 'error',
+ code: CONTINUITY_CODES.DISCONNECTED_INTERACTION_CHANNEL,
+ message: `Scene "${node.title || node.id}" has live voice enabled while audience communication channel is disconnected.`,
+ remediation: 'Set audience connection to connected or disable live interaction.',
+ nodeId: node.id,
+ });
+ }
+ }
+ }
+
+ // Check for voice profile revision drift across the episode
+ for (const [charId, revMap] of characterVoiceRevisions.entries()) {
+ const revisions = Array.from(revMap.keys());
+ const profileRevisions = new Set(revisions.map((value) => value.replace(/\s+\([^)]*\)$/, '')));
+ const engines = new Set(revisions.map((value) => value.match(/\(([^:]+):/)?.[1] || 'unknown'));
+ const modelRevisions = new Set(revisions.map((value) => value.match(/\([^:]+:(.*)\)$/)?.[1] || 'unknown'));
+ if (profileRevisions.size > 1) {
+ push({
+ category: 'voice',
+ severity: 'warning',
+ code: CONTINUITY_CODES.VOICE_PROFILE_REVISION_DRIFT,
+ message: `Character "${charId}" has assets rendered with different voice profile revisions across scenes (${revisions.join(', ')}).`,
+ remediation: 'Re-render dialogue assets with the latest approved voice profile for consistent character voice.',
+ characterId: charId,
+ });
+ }
+ if (engines.size > 1) {
+ push({
+ category: 'voice',
+ severity: 'warning',
+ code: CONTINUITY_CODES.VOICE_ENGINE_DRIFT,
+ message: `Character "${charId}" has assets rendered with different voice engines across scenes (${Array.from(engines).join(', ')}).`,
+ remediation: 'Re-render dialogue assets with one approved voice engine for the episode.',
+ characterId: charId,
+ });
+ }
+ if (modelRevisions.size > 1) {
+ push({
+ category: 'voice',
+ severity: 'warning',
+ code: CONTINUITY_CODES.VOICE_MODEL_REVISION_DRIFT,
+ message: `Character "${charId}" has assets rendered with different voice model revisions across scenes (${Array.from(modelRevisions).join(', ')}).`,
+ remediation: 'Re-render dialogue assets with one recorded model revision for the episode.',
+ characterId: charId,
+ });
+ }
+ }
+
+ const errorCount = findings.filter((f) => f.severity === 'error').length;
+ const warningCount = findings.filter((f) => f.severity === 'warning').length;
+ const infoCount = findings.filter((f) => f.severity === 'info').length;
+
+ const categoryCounts = {
+ visual: findings.filter((f) => f.category === 'visual').length,
+ voice: findings.filter((f) => f.category === 'voice').length,
+ playback: findings.filter((f) => f.category === 'playback').length,
+ graph: findings.filter((f) => f.category === 'graph').length,
+ };
+
+ return {
+ passed: errorCount === 0,
+ summary: {
+ totalFindings: findings.length,
+ errors: errorCount,
+ warnings: warningCount,
+ info: infoCount,
+ categoryCounts,
+ },
+ nodesEvaluated: orderedNodes.length,
+ findings,
+ };
+}
diff --git a/server/lib/fableLoomContinuity.test.js b/server/lib/fableLoomContinuity.test.js
new file mode 100644
index 0000000000..d374e61005
--- /dev/null
+++ b/server/lib/fableLoomContinuity.test.js
@@ -0,0 +1,207 @@
+import { describe, expect, it } from 'vitest';
+import {
+ CONTINUITY_CODES,
+ analyzeEpisodeContinuity,
+} from './fableLoomContinuity.js';
+
+describe('fableLoomContinuity', () => {
+ const sampleUniverse = {
+ characters: [
+ {
+ id: 'char-elena',
+ name: 'Elena Vance',
+ wardrobes: [{ id: 'wardrobe-explorer' }, { id: 'wardrobe-gala' }],
+ voiceCanon: {
+ pronunciations: [{ term: 'Aethelgard', pronunciation: 'AY-thel-gard' }],
+ },
+ },
+ ],
+ places: [{ id: 'place-temple', name: 'Sunken Temple' }],
+ objects: [{ id: 'obj-relic', name: 'Solar Relic' }],
+ };
+
+ it('detects visual binding errors and missing references', () => {
+ const episode = {
+ id: 'ep-1',
+ startNodeId: 'node-1',
+ nodes: [
+ {
+ id: 'node-1',
+ title: 'Temple Entrance',
+ prose: 'Elena enters the Sunken Temple.',
+ visualCanon: {
+ characterAppearances: [
+ { characterId: 'char-ghost', wardrobeId: 'unknown-wardrobe' },
+ { characterId: 'char-elena', wardrobeId: 'non-existent-wardrobe' },
+ ],
+ placeId: 'unknown-place',
+ objectIds: ['unknown-obj'],
+ },
+ transitions: [],
+ },
+ ],
+ };
+
+ const review = analyzeEpisodeContinuity({
+ episode,
+ universe: sampleUniverse,
+ });
+
+ expect(review.passed).toBe(false);
+ const codes = review.findings.map((f) => f.code);
+ expect(codes).toContain(CONTINUITY_CODES.MISSING_UNIVERSE_CHARACTER);
+ expect(codes).toContain(CONTINUITY_CODES.MISSING_WARDROBE_REFERENCE);
+ expect(codes).toContain(CONTINUITY_CODES.MISSING_UNIVERSE_PLACE);
+ expect(codes).toContain(CONTINUITY_CODES.MISSING_UNIVERSE_OBJECT);
+ });
+
+ it('detects voice profile revision drift across scenes in the same episode', () => {
+ const episode = {
+ id: 'ep-1',
+ startNodeId: 'node-1',
+ nodes: [
+ {
+ id: 'node-1',
+ title: 'Scene 1',
+ prose: 'Hello world.',
+ playbackAssets: {
+ provenance: {
+ characters: [
+ {
+ characterId: 'char-elena',
+ voice: { profileId: 'vp-elena', profileVersion: 1, engine: 'kokoro' },
+ },
+ ],
+ },
+ },
+ transitions: [{ id: 'tr-1', targetNodeId: 'node-2', intent: 'Next' }],
+ },
+ {
+ id: 'node-2',
+ title: 'Scene 2',
+ prose: 'Good morning.',
+ playbackAssets: {
+ provenance: {
+ characters: [
+ {
+ characterId: 'char-elena',
+ voice: { profileId: 'vp-elena', profileVersion: 2, engine: 'kokoro' },
+ },
+ ],
+ },
+ },
+ transitions: [],
+ },
+ ],
+ };
+
+ const review = analyzeEpisodeContinuity({
+ episode,
+ universe: sampleUniverse,
+ });
+
+ const driftFinding = review.findings.find(
+ (f) => f.code === CONTINUITY_CODES.VOICE_PROFILE_REVISION_DRIFT,
+ );
+ expect(driftFinding).toBeDefined();
+ expect(driftFinding.characterId).toBe('char-elena');
+ expect(driftFinding.severity).toBe('warning');
+ });
+
+ it('detects unsafe hold loop audio occupancy and interaction misconfigurations', () => {
+ const episode = {
+ id: 'ep-1',
+ startNodeId: 'node-1',
+ nodes: [
+ {
+ id: 'node-1',
+ title: 'Dangerous Hold Scene',
+ prose: 'Conversation awaits.',
+ playbackMode: 'decision',
+ interactionWindow: {
+ enabled: true,
+ protagonistCharacterId: 'char-elena',
+ protagonistPresence: 'onscreen',
+ },
+ playbackAssets: {
+ holdLoopVideoHistoryIds: ['video-unsafe-hold'],
+ audioOccupancy: {
+ 'video-unsafe-hold': {
+ durationMs: 5000,
+ characterDialogue: [{ startMs: 0, endMs: 2000, speaker: 'Elena' }],
+ music: [],
+ effects: [{ startMs: 3000, endMs: 4000, blocking: true }],
+ },
+ },
+ },
+ transitions: [],
+ },
+ ],
+ };
+
+ const review = analyzeEpisodeContinuity({
+ episode,
+ universe: sampleUniverse,
+ });
+
+ const codes = review.findings.map((f) => f.code);
+ expect(codes).toContain(CONTINUITY_CODES.HOLD_LOOP_HAS_DIALOGUE);
+ expect(codes).toContain(CONTINUITY_CODES.HOLD_LOOP_HAS_BLOCKING_EFFECTS);
+ expect(codes).toContain(CONTINUITY_CODES.PROTAGONIST_ONSCREEN_INTERACTION);
+ });
+
+ it('detects clipped hold audio and voice engine, model, and pronunciation drift', () => {
+ const episode = {
+ id: 'ep-1',
+ startNodeId: 'node-1',
+ nodes: [
+ {
+ id: 'node-1',
+ title: 'First scene',
+ prose: 'The hero speaks.',
+ playbackAssets: {
+ holdLoopVideoHistoryIds: ['hold-1'],
+ audioOccupancy: { 'hold-1': { durationMs: 2000, clippingDetected: true } },
+ provenance: {
+ characters: [{
+ characterId: 'char-elena',
+ voice: {
+ profileId: 'vp-elena', profileVersion: 1, engine: 'kokoro',
+ modelRevision: 'model-a', pronunciationRevision: 1,
+ },
+ }],
+ },
+ },
+ transitions: [{ id: 'tr-1', targetNodeId: 'node-2', intent: 'Next' }],
+ },
+ {
+ id: 'node-2',
+ title: 'Second scene',
+ prose: 'The hero answers.',
+ playbackAssets: {
+ provenance: {
+ characters: [{
+ characterId: 'char-elena',
+ voice: {
+ profileId: 'vp-elena', profileVersion: 1, engine: 'piper',
+ modelRevision: 'model-b', pronunciationRevision: 2,
+ },
+ }],
+ },
+ },
+ transitions: [],
+ },
+ ],
+ };
+
+ const review = analyzeEpisodeContinuity({ episode, universe: {
+ characters: [{ ...sampleUniverse.characters[0], voiceCanon: { version: 3 } }],
+ } });
+ const codes = review.findings.map((finding) => finding.code);
+
+ expect(codes).toContain(CONTINUITY_CODES.HOLD_LOOP_HAS_CLIPPING);
+ expect(codes).toContain(CONTINUITY_CODES.VOICE_ENGINE_DRIFT);
+ expect(codes).toContain(CONTINUITY_CODES.VOICE_MODEL_REVISION_DRIFT);
+ expect(codes).toContain(CONTINUITY_CODES.PRONUNCIATION_REVISION_DRIFT);
+ });
+});
diff --git a/server/lib/fableLoomPlayback.js b/server/lib/fableLoomPlayback.js
index 75fdc45ad8..9d19f0316c 100644
--- a/server/lib/fableLoomPlayback.js
+++ b/server/lib/fableLoomPlayback.js
@@ -34,6 +34,11 @@ export const isSafeVideoHistoryId = (value) =>
const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
const trimTo = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
+const SAFE_PRODUCTION_PARAMETER_KEYS = new Set([
+ 'width', 'height', 'numFrames', 'fps', 'steps', 'guidance', 'guidanceScale',
+ 'seed', 'imageStrength', 'quantize', 'effort', 'mode', 'videoMode',
+ 'aspectRatio', 'disableAudio', 'tiling',
+]);
/**
* Sanitize an audio interval (dialogue, music, or effect).
@@ -90,21 +95,136 @@ export function validateAudioOccupancy(raw) {
const hasCharacterDialogue = characterDialogue.length > 0;
const hasBlockingEffects = effects.some((e) => e.blocking === true);
-
- // safeForLiveVoice is false if any dialogue or blocking effects exist
- const safeForLiveVoice = !hasCharacterDialogue && !hasBlockingEffects;
+ const peakDb = Number.isFinite(raw.truePeakDb)
+ ? raw.truePeakDb
+ : (Number.isFinite(raw.peakDb) ? raw.peakDb : null);
+ const clipping = raw.clipping === true
+ || raw.clipped === true
+ || raw.clippingDetected === true
+ || (peakDb !== null && peakDb > 0);
+
+ // safeForLiveVoice is false if any dialogue, blocking effects, or clipping
+ // exists. A caller cannot override these derived safety fields with a stale
+ // `safeForLiveVoice: true` value from an older manifest.
+ const safeForLiveVoice = !hasCharacterDialogue && !hasBlockingEffects && !clipping;
return {
durationMs,
characterDialogue,
music,
effects,
+ clipping,
+ ...(peakDb !== null ? { peakDb } : {}),
safeForLiveVoice,
};
}
export const sanitizeAudioOccupancy = validateAudioOccupancy;
+/**
+ * Sanitize the path-free visual conditioning manifest attached to a scene or
+ * typed playback asset. The playback module owns this shape so the node
+ * sanitizer can safely handle one manifest per rendered clip without a
+ * records-module import cycle.
+ */
+export function sanitizeVisualConditioning(raw) {
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) return null;
+ const list = (value, max) => (Array.isArray(value) ? value.slice(0, max) : []);
+ 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 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 [];
+ if (typeof value === 'number' && Number.isFinite(value)) return [[key.slice(0, 40), value]];
+ if (typeof value === 'boolean') return [[key.slice(0, 40), value]];
+ if (isStr(value)) return [[key.slice(0, 40), trimTo(value, 200)]];
+ return [];
+ }))
+ : {};
+ return {
+ version: 1,
+ compilerVersion: trimTo(raw.compilerVersion, 40),
+ status: ['locked', 'draft', 'degraded'].includes(raw.status) ? raw.status : 'degraded',
+ universeId: nullableRef(raw.universeId),
+ capability: {
+ version: Number.isInteger(capability.version) ? capability.version : 1,
+ kind: capability.kind === 'video' ? 'video' : 'image',
+ backend: trimTo(capability.backend, 40),
+ modelId: nullableRef(capability.modelId),
+ modelRevision: nullableRef(capability.modelRevision),
+ referenceRoles: list(capability.referenceRoles, 24)
+ .map((item) => trimTo(item, 64)).filter(Boolean),
+ referenceBudget: Number.isInteger(capability.referenceBudget)
+ ? Math.max(0, Math.min(24, capability.referenceBudget)) : 0,
+ supportsLora: capability.supportsLora === true,
+ loraCompatKey: nullableRef(capability.loraCompatKey),
+ loraBudget: Number.isInteger(capability.loraBudget)
+ ? Math.max(0, Math.min(8, capability.loraBudget)) : 0,
+ multiCharacterPreservation: capability.multiCharacterPreservation === true,
+ ...(capability.kind === 'video' ? {
+ firstFrame: capability.firstFrame === true,
+ lastFrame: capability.lastFrame === true,
+ extension: capability.extension === true,
+ } : {}),
+ },
+ bindings: {
+ inferred: bindings.inferred === true,
+ characterAppearances: list(bindings.characterAppearances, LOOM_LIMITS.VISUAL_BINDINGS_MAX)
+ .filter((item) => item && typeof item === 'object' && nullableRef(item.characterId))
+ .map((item) => ({
+ characterId: nullableRef(item.characterId),
+ wardrobeId: nullableRef(item.wardrobeId),
+ expression: trimTo(item.expression, LOOM_LIMITS.VISUAL_NOTE_MAX),
+ continuityNotes: trimTo(item.continuityNotes, LOOM_LIMITS.VISUAL_NOTE_MAX),
+ })),
+ placeId: nullableRef(bindings.placeId),
+ objectIds: list(bindings.objectIds, LOOM_LIMITS.VISUAL_BINDINGS_MAX)
+ .map(nullableRef).filter(Boolean),
+ },
+ assets: list(raw.assets, LOOM_LIMITS.VISUAL_PROVENANCE_ASSETS_MAX)
+ .filter((item) => item && typeof item === 'object')
+ .map((item) => ({
+ role: trimTo(item.role, 64), bindingId: nullableRef(item.bindingId),
+ required: item.required === true, filename: trimTo(item.filename, 256),
+ })),
+ adapters: list(raw.adapters, 8)
+ .filter((item) => item && typeof item === 'object')
+ .map((item) => ({
+ characterId: nullableRef(item.characterId), filename: trimTo(item.filename, 256),
+ scale: Number.isFinite(item.scale) ? Math.max(0, Math.min(2, item.scale)) : 1,
+ sha256: typeof item.sha256 === 'string' && /^[a-f0-9]{64}$/i.test(item.sha256) ? item.sha256 : null,
+ })),
+ omitted: list(raw.omitted, LOOM_LIMITS.VISUAL_PROVENANCE_MESSAGES_MAX)
+ .filter((item) => item && typeof item === 'object')
+ .map((item) => ({
+ role: trimTo(item.role, 64), bindingId: nullableRef(item.bindingId),
+ reason: trimTo(item.reason, 80),
+ ...(item.filename ? { filename: trimTo(item.filename, 256) } : {}),
+ })),
+ warnings: (Array.isArray(raw.warnings) ? raw.warnings : [])
+ .map((item) => trimTo(item, LOOM_LIMITS.VISUAL_NOTE_MAX)).filter(Boolean)
+ .slice(0, LOOM_LIMITS.VISUAL_PROVENANCE_MESSAGES_MAX),
+ temporalSourceNodeId: nullableRef(raw.temporalSourceNodeId),
+ ...(typeof raw.compiledPrompt === 'string' ? { compiledPrompt: trimTo(raw.compiledPrompt, 8000) } : {}),
+ ...(typeof raw.compiledNegativePrompt === 'string' ? { compiledNegativePrompt: trimTo(raw.compiledNegativePrompt, 8000) } : {}),
+ referenceImageStrengths: (Array.isArray(raw.referenceImageStrengths) ? raw.referenceImageStrengths : [])
+ .filter((value) => Number.isFinite(value))
+ .map((value) => Math.max(0, Math.min(1, value)))
+ .slice(0, LOOM_LIMITS.VISUAL_PROVENANCE_ASSETS_MAX),
+ ...(isStr(raw.assetId) ? { assetId: nullableRef(raw.assetId) } : {}),
+ ...(raw.render && typeof raw.render === 'object' ? {
+ render: {
+ provider: trimTo(raw.render.provider, 40),
+ modelId: nullableRef(raw.render.modelId),
+ modelRevision: nullableRef(raw.render.modelRevision),
+ parameters: productionParameters,
+ },
+ } : {}),
+ compiledAt: isStr(raw.compiledAt) ? raw.compiledAt : null,
+ };
+}
+
/**
* Check if a manifest or asset is safe for live voice.
*/
@@ -210,6 +330,9 @@ export function sanitizeProvenance(raw) {
profileVersion: Number.isFinite(c.voice.profileVersion) ? Math.round(c.voice.profileVersion) : 1,
engine: trimTo(c.voice.engine, 80),
modelRevision: trimTo(c.voice.modelRevision, 120),
+ pronunciationRevision: Number.isFinite(c.voice.pronunciationRevision)
+ ? Math.max(1, Math.round(c.voice.pronunciationRevision))
+ : null,
} : null,
})),
visualConditioningVersion: Number.isFinite(raw.visualConditioningVersion) ? raw.visualConditioningVersion : 1,
@@ -253,13 +376,22 @@ export function sanitizePlaybackAssets(raw) {
}
const provenance = sanitizeProvenance(raw.provenance);
+ const visualConditioningByAsset = {};
+ if (raw.visualConditioningByAsset && typeof raw.visualConditioningByAsset === 'object') {
+ for (const [assetId, manifest] of Object.entries(raw.visualConditioningByAsset)) {
+ if (!isSafeVideoHistoryId(assetId)) continue;
+ const sanitized = sanitizeVisualConditioning(manifest);
+ if (sanitized) visualConditioningByAsset[assetId] = sanitized;
+ }
+ }
// If completely empty, return null
if (!entryVideoHistoryId
&& !holdLoopVideoHistoryIds.length
&& !Object.keys(exitByTransition).length
&& !Object.keys(audioOccupancy).length
- && !provenance) {
+ && !provenance
+ && !Object.keys(visualConditioningByAsset).length) {
return null;
}
@@ -269,6 +401,7 @@ export function sanitizePlaybackAssets(raw) {
exitByTransition,
audioOccupancy,
...(provenance ? { provenance } : {}),
+ ...(Object.keys(visualConditioningByAsset).length ? { visualConditioningByAsset } : {}),
};
}
diff --git a/server/lib/fableLoomPlayback.test.js b/server/lib/fableLoomPlayback.test.js
index 042cf9f843..6bb40a79e7 100644
--- a/server/lib/fableLoomPlayback.test.js
+++ b/server/lib/fableLoomPlayback.test.js
@@ -18,6 +18,7 @@ import {
sanitizeAudioOccupancy,
sanitizeInteractionWindow,
sanitizePlaybackAssets,
+ sanitizeVisualConditioning,
validateAudioOccupancy,
} from './fableLoomPlayback.js';
@@ -75,6 +76,19 @@ describe('FableLoom audio occupancy and validation', () => {
expect(manifestWithBlocking.safeForLiveVoice).toBe(false);
});
+ it('treats clipped audio as unsafe even when the source marked it safe', () => {
+ const clipped = validateAudioOccupancy({
+ durationMs: 4000,
+ clippingDetected: true,
+ peakDb: 1.2,
+ safeForLiveVoice: true,
+ });
+
+ expect(clipped.clipping).toBe(true);
+ expect(clipped.peakDb).toBe(1.2);
+ expect(clipped.safeForLiveVoice).toBe(false);
+ });
+
it('allows live voice when only music / non-blocking ambience is present', () => {
const safeManifest = validateAudioOccupancy({
durationMs: 8000,
@@ -151,6 +165,60 @@ describe('FableLoom playbackAssets and interactionWindow sanitizers', () => {
expect(sanitized.audioOccupancy['vid-hold-1'].safeForLiveVoice).toBe(true);
});
+ it('retains one sanitized visual-conditioning manifest per rendered clip', () => {
+ const manifest = {
+ version: 1,
+ compilerVersion: 'visual-v1',
+ status: 'locked',
+ capability: {
+ kind: 'image',
+ backend: 'local',
+ modelId: 'image-model',
+ modelRevision: 'revision-1',
+ },
+ bindings: { inferred: false, characterAppearances: [] },
+ assets: [{ role: 'environment', bindingId: 'place-1', required: true, filename: 'environment.png', path: '/private/input.png' }],
+ adapters: [],
+ omitted: [],
+ warnings: [],
+ compiledPrompt: 'A quiet example courtyard.',
+ compiledNegativePrompt: '',
+ referenceImageStrengths: [1],
+ render: {
+ provider: 'local',
+ modelId: 'image-model',
+ modelRevision: 'revision-1',
+ parameters: {
+ width: 1024,
+ initImagePath: '/private/input.png',
+ secret: 'must-not-persist',
+ },
+ },
+ };
+
+ expect(sanitizeVisualConditioning(manifest)).toMatchObject({
+ version: 1,
+ capability: { modelRevision: 'revision-1' },
+ compiledNegativePrompt: '',
+ render: { parameters: { width: 1024 } },
+ });
+ expect(JSON.stringify(sanitizeVisualConditioning(manifest))).not.toContain('/private/');
+ expect(sanitizeVisualConditioning(manifest).render.parameters.initImagePath).toBeUndefined();
+ expect(sanitizeVisualConditioning(manifest).render.parameters.secret).toBeUndefined();
+
+ const sanitized = sanitizePlaybackAssets({
+ entryVideoHistoryId: 'vid-entry',
+ visualConditioningByAsset: {
+ 'vid-entry': manifest,
+ '../unsafe': manifest,
+ },
+ });
+ expect(sanitized.visualConditioningByAsset).toHaveProperty('vid-entry');
+ expect(sanitized.visualConditioningByAsset['vid-entry'])
+ .toMatchObject({ capability: { modelRevision: 'revision-1' } });
+ expect(sanitized.visualConditioningByAsset).not.toHaveProperty('../unsafe');
+ });
+
it('sanitizes interactionWindow with defaults and clamped duck dB', () => {
expect(sanitizeInteractionWindow(null)).toBeNull();
@@ -356,4 +424,3 @@ describe('inspectNodeProductionReadiness & inspectEpisodeProductionReadiness', (
expect(epRes.nodeResults['node-1'].ready).toBe(true);
});
});
-
diff --git a/server/lib/fableLoomProduction.js b/server/lib/fableLoomProduction.js
new file mode 100644
index 0000000000..2334681d1b
--- /dev/null
+++ b/server/lib/fableLoomProduction.js
@@ -0,0 +1,732 @@
+/**
+ * FableLoom production batch planning and topological orchestration.
+ *
+ * Pure, side-effect-free helpers for enumerating planned production assets
+ * across reachable graph nodes, computing topological execution batches,
+ * evaluating readiness gates, and verifying exact-input provenance.
+ */
+
+import { computeGraphLayers } from './fableLoomGraph.js';
+import { validateAudioOccupancy } from './fableLoomPlayback.js';
+
+export const FABLELOOM_PRODUCTION_MODES = Object.freeze(['current_canon', 'exact_inputs']);
+export const FABLELOOM_PRODUCTION_MODE_DEFAULT = 'current_canon';
+
+export const FABLELOOM_ASSET_TYPES = Object.freeze([
+ 'image',
+ 'video_entry',
+ 'video_hold',
+ 'video_exit',
+ 'dialogue',
+]);
+
+const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
+const isLockedCanon = (node) => Boolean(node?.visualCanon && node.visualCanon.mode !== 'draft');
+
+/**
+ * Compute the topological ordering of reachable nodes in an episode graph,
+ * respecting graph convergence and path-specific predecessors.
+ */
+export function computeTopologicalNodeOrder(episode) {
+ const nodes = Array.isArray(episode?.nodes) ? episode.nodes : [];
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
+ const startId = episode?.startNodeId;
+
+ if (!startId || !nodeById.has(startId)) {
+ return {
+ orderedNodes: [],
+ depthById: new Map(),
+ predecessorsByNodeId: new Map(),
+ convergenceNodeIds: new Set(),
+ unreachableNodeIds: new Set(nodes.map((n) => n.id)),
+ };
+ }
+
+ const { depthById } = computeGraphLayers(episode);
+ const predecessorsByNodeId = new Map();
+ for (const node of nodes) {
+ predecessorsByNodeId.set(node.id, []);
+ }
+
+ for (const node of nodes) {
+ if (!depthById.has(node.id)) continue;
+ for (const tr of (node.transitions || [])) {
+ const targetId = tr?.targetNodeId;
+ if (targetId && nodeById.has(targetId)) {
+ const preds = predecessorsByNodeId.get(targetId) || [];
+ if (!preds.some((p) => p.nodeId === node.id && p.transitionId === tr.id)) {
+ preds.push({ nodeId: node.id, transitionId: tr.id, intent: tr.intent || '' });
+ }
+ predecessorsByNodeId.set(targetId, preds);
+ }
+ }
+ }
+
+ const convergenceNodeIds = new Set();
+ for (const [nodeId, preds] of predecessorsByNodeId.entries()) {
+ if (preds.length > 1) {
+ convergenceNodeIds.add(nodeId);
+ }
+ }
+
+ // Sort reachable nodes by BFS layer depth, then by array position for deterministic ordering
+ const orderedNodes = nodes
+ .filter((n) => depthById.has(n.id))
+ .sort((a, b) => {
+ const depthDiff = (depthById.get(a.id) ?? 0) - (depthById.get(b.id) ?? 0);
+ if (depthDiff !== 0) return depthDiff;
+ return nodes.indexOf(a) - nodes.indexOf(b);
+ });
+
+ const unreachableNodeIds = new Set(
+ nodes.filter((n) => !depthById.has(n.id)).map((n) => n.id),
+ );
+
+ return {
+ orderedNodes,
+ depthById,
+ predecessorsByNodeId,
+ convergenceNodeIds,
+ unreachableNodeIds,
+ };
+}
+
+/**
+ * Verify recorded asset provenance against the current local environment.
+ * For `exact_inputs` mode: refuses when a recorded revision/hash/model is missing
+ * or mismatched, preventing silent substitution.
+ */
+export function verifyExactInputProvenance(recordedProvenance, {
+ universe = null,
+ localVoiceProfiles = [],
+ localLoras = [],
+ availableImageModels = null,
+ availableVideoModels = null,
+ resolveAsset = null,
+} = {}) {
+ const errors = [];
+ const warnings = [];
+ const installedVoiceProfiles = Array.isArray(localVoiceProfiles) ? localVoiceProfiles : [];
+ const installedLoras = Array.isArray(localLoras) ? localLoras : [];
+
+ if (!recordedProvenance || typeof recordedProvenance !== 'object') {
+ return {
+ valid: false,
+ errors: ['No recorded provenance manifest found for exact-input reproduction.'],
+ warnings: [],
+ };
+ }
+
+ if (recordedProvenance.universeId) {
+ if (!universe) {
+ errors.push('The recorded Universe is unavailable for exact-input reproduction.');
+ } else if (universe.id && universe.id !== recordedProvenance.universeId) {
+ errors.push(`Recorded Universe "${recordedProvenance.universeId}" does not match the current Universe "${universe.id}".`);
+ }
+ }
+ if (Array.isArray(recordedProvenance.omitted) && recordedProvenance.omitted.length > 0) {
+ errors.push('The recorded provenance contains omitted inputs, so exact reproduction cannot be proven.');
+ }
+
+ // The visual-conditioning compiler writes a different, capability-based
+ // manifest than the original dialogue provenance envelope below. Keep both
+ // shapes readable so older renders remain reproducible, but never treat a
+ // visual manifest as verified merely because it has a `version` field.
+ const hasVisualManifest = recordedProvenance.capability
+ || recordedProvenance.bindings
+ || recordedProvenance.assets
+ || recordedProvenance.compilerVersion;
+ if (hasVisualManifest) {
+ if (recordedProvenance.version !== 1) {
+ errors.push(`Recorded visual conditioning manifest version "${recordedProvenance.version ?? 'unknown'}" is unsupported.`);
+ }
+ if (!isStr(recordedProvenance.compilerVersion)) {
+ errors.push('Recorded visual conditioning has no compiler revision.');
+ }
+ if (recordedProvenance.status !== 'locked') {
+ errors.push('Recorded visual conditioning is not canon-locked, so exact reproduction cannot be proven.');
+ }
+
+ const capability = recordedProvenance.capability;
+ if (!capability || typeof capability !== 'object') {
+ errors.push('Recorded visual conditioning has no provider capability manifest.');
+ } else {
+ if (!isStr(capability.backend)) errors.push('Recorded visual conditioning has no backend.');
+ if (!isStr(capability.modelId)) errors.push('Recorded visual conditioning has no model revision or model id.');
+ if (capability.backend === 'local' && !isStr(capability.modelRevision)) {
+ errors.push(`Recorded local ${capability.kind || 'media'} model "${capability.modelId || 'unknown'}" has no immutable model revision to verify exact inputs.`);
+ }
+ // Local model registries can only verify local manifests. Cloud model ids
+ // are provider-owned and are not present in the local registry, so do not
+ // mistake a perfectly valid cloud provenance record for a missing local
+ // model.
+ const availableModels = capability.backend === 'local'
+ ? (capability.kind === 'video' ? availableVideoModels : availableImageModels)
+ : null;
+ if (Array.isArray(availableModels) && isStr(capability.modelId)) {
+ const matchingModel = availableModels.find((model) => model?.id === capability.modelId);
+ if (!matchingModel) {
+ errors.push(`Recorded ${capability.kind || 'media'} model "${capability.modelId}" is not available locally.`);
+ } else if (isStr(capability.modelRevision)
+ && (!isStr(matchingModel.revision) || matchingModel.revision !== capability.modelRevision)) {
+ errors.push(`Recorded ${capability.kind || 'media'} model "${capability.modelId}" revision mismatch (recorded ${capability.modelRevision}, current local ${matchingModel.revision || 'unknown'}).`);
+ }
+ }
+ }
+
+ const bindings = recordedProvenance.bindings;
+ if (!bindings || typeof bindings !== 'object') {
+ errors.push('Recorded visual conditioning has no scene bindings.');
+ } else {
+ const appearances = Array.isArray(bindings.characterAppearances)
+ ? bindings.characterAppearances
+ : [];
+ if (universe && Array.isArray(universe.characters)) {
+ for (const appearance of appearances) {
+ const charId = appearance?.characterId;
+ const canonChar = universe.characters.find((character) => character.id === charId);
+ if (!canonChar) {
+ errors.push(`Character "${charId || 'unknown'}" in recorded visual bindings no longer exists in Universe.`);
+ } else if (isStr(appearance.wardrobeId)
+ && (!Array.isArray(canonChar.wardrobes)
+ || !canonChar.wardrobes.some((wardrobe) => wardrobe.id === appearance.wardrobeId))) {
+ errors.push(`Wardrobe "${appearance.wardrobeId}" in recorded visual bindings is not present on character "${charId}".`);
+ }
+ }
+ }
+ if (universe && isStr(bindings.placeId)
+ && Array.isArray(universe.places)
+ && !universe.places.some((place) => place.id === bindings.placeId)) {
+ errors.push(`Place "${bindings.placeId}" in recorded visual bindings no longer exists in Universe.`);
+ }
+ if (universe && Array.isArray(bindings.objectIds) && Array.isArray(universe.objects)) {
+ for (const objectId of bindings.objectIds) {
+ if (!universe.objects.some((object) => object.id === objectId)) {
+ errors.push(`Object "${objectId}" in recorded visual bindings no longer exists in Universe.`);
+ }
+ }
+ }
+ }
+
+ if (!Array.isArray(recordedProvenance.assets)) {
+ errors.push('Recorded visual conditioning has no asset manifest.');
+ } else {
+ for (const asset of recordedProvenance.assets) {
+ if (!isStr(asset?.filename)) {
+ errors.push(`Recorded visual conditioning asset "${asset?.role || 'unknown'}" has no filename.`);
+ } else if (typeof resolveAsset === 'function' && !resolveAsset(asset.filename)) {
+ errors.push(`Recorded visual conditioning asset "${asset.filename}" is unavailable locally.`);
+ }
+ }
+ }
+
+ if (!Array.isArray(recordedProvenance.adapters)) {
+ errors.push('Recorded visual conditioning has no adapter manifest.');
+ } else {
+ for (const adapter of recordedProvenance.adapters) {
+ if (!isStr(adapter?.filename)) {
+ errors.push('Recorded visual conditioning contains an adapter with no filename.');
+ continue;
+ }
+ if (!isStr(adapter.sha256)) {
+ errors.push(`Recorded character adapter "${adapter.filename}" has no checksum to verify exact inputs.`);
+ continue;
+ }
+ const matchedLora = installedLoras.find((lora) => lora?.filename === adapter.filename);
+ if (!matchedLora) {
+ errors.push(`Recorded character adapter "${adapter.filename}" is not installed locally.`);
+ } else if (!isStr(matchedLora.sha256)) {
+ errors.push(`Installed character adapter "${adapter.filename}" has no checksum to verify exact inputs.`);
+ } else if (matchedLora.sha256 !== adapter.sha256) {
+ errors.push(`Recorded character adapter "${adapter.filename}" checksum mismatch (expected ${adapter.sha256}, found ${matchedLora.sha256}).`);
+ }
+ }
+ }
+ if (!Array.isArray(recordedProvenance.omitted)) {
+ errors.push('Recorded visual conditioning has no omitted-input manifest.');
+ }
+ if (!Array.isArray(recordedProvenance.warnings)) {
+ warnings.push('Recorded visual conditioning has no warnings manifest.');
+ }
+ } else if (!Array.isArray(recordedProvenance.characters)) {
+ errors.push('Recorded provenance has no recognized asset bindings.');
+ }
+
+ const characters = Array.isArray(recordedProvenance.characters) ? recordedProvenance.characters : [];
+
+ for (const char of characters) {
+ const charId = char?.characterId;
+ if (!charId) continue;
+
+ // Check Universe Character existence if universe provided
+ if (universe && Array.isArray(universe.characters)) {
+ const canonChar = universe.characters.find((c) => c.id === charId);
+ if (!canonChar) {
+ errors.push(`Character "${charId}" in recorded provenance no longer exists in Universe.`);
+ }
+ }
+
+ // Check LoRA matching
+ if (char.lora) {
+ const recordedFilename = char.lora.filename;
+ if (!isStr(recordedFilename)) {
+ errors.push(`Recorded character LoRA binding for "${charId}" has no filename.`);
+ } else {
+ const recordedSha = char.lora.sha256;
+ const matchedLora = installedLoras.find((l) => l.filename === recordedFilename);
+ if (!matchedLora) {
+ errors.push(`Recorded character LoRA "${recordedFilename}" is not installed locally.`);
+ } else if (!isStr(recordedSha)) {
+ errors.push(`Recorded character LoRA "${recordedFilename}" has no checksum to verify.`);
+ } else if (!isStr(matchedLora.sha256)) {
+ errors.push(`Installed character LoRA "${recordedFilename}" has no checksum to verify exact inputs.`);
+ } else if (matchedLora.sha256 !== recordedSha) {
+ errors.push(`Recorded character LoRA "${recordedFilename}" checksum mismatch (expected ${recordedSha}, found ${matchedLora.sha256}).`);
+ }
+ }
+ }
+
+ // Check Voice Profile matching
+ if (char.voice) {
+ const recordedProfileId = char.voice.profileId;
+ const recordedVersion = char.voice.profileVersion;
+ const recordedEngine = char.voice.engine;
+ const recordedModelRev = char.voice.modelRevision;
+ if (!isStr(recordedProfileId)) {
+ errors.push(`Recorded voice binding for character "${charId}" has no profile id.`);
+ continue;
+ }
+
+ const matchedProfile = installedVoiceProfiles.find((p) => p.id === recordedProfileId);
+ if (!matchedProfile) {
+ errors.push(`Recorded voice profile "${recordedProfileId}" is not installed locally.`);
+ continue;
+ }
+ if (matchedProfile.binding?.characterId && matchedProfile.binding.characterId !== charId) {
+ errors.push(`Recorded voice profile "${recordedProfileId}" is bound to a different character.`);
+ }
+ if (recordedProvenance.universeId
+ && matchedProfile.binding?.universeId
+ && matchedProfile.binding.universeId !== recordedProvenance.universeId) {
+ errors.push(`Recorded voice profile "${recordedProfileId}" belongs to a different Universe.`);
+ }
+ if (!Number.isFinite(recordedVersion) || matchedProfile.version !== recordedVersion) {
+ errors.push(`Recorded voice profile "${recordedProfileId}" version mismatch (recorded v${recordedVersion ?? 'unknown'}, current local v${matchedProfile.version ?? 'unknown'}).`);
+ }
+ if (!isStr(recordedEngine) || !isStr(matchedProfile.engine) || matchedProfile.engine !== recordedEngine) {
+ errors.push(`Recorded voice profile "${recordedProfileId}" engine mismatch (recorded ${recordedEngine || 'unknown'}, current local ${matchedProfile.engine || 'unknown'}).`);
+ }
+ if (!isStr(recordedModelRev) || !isStr(matchedProfile.modelRevision) || matchedProfile.modelRevision !== recordedModelRev) {
+ errors.push(`Recorded voice profile "${recordedProfileId}" model revision mismatch (recorded ${recordedModelRev || 'unknown'}, current local ${matchedProfile.modelRevision || 'unknown'}).`);
+ }
+ }
+ }
+
+ return {
+ valid: errors.length === 0,
+ errors,
+ warnings,
+ };
+}
+
+/**
+ * Enumerate and plan all production assets for an episode.
+ * Pure deterministic preflight and DAG generation.
+ */
+export function buildEpisodeProductionPlan({
+ loom = null,
+ episode = null,
+ universe = null,
+ mode = FABLELOOM_PRODUCTION_MODE_DEFAULT,
+ localVoiceProfiles = [],
+ localLoras = [],
+ availableImageModels = null,
+ availableVideoModels = null,
+ resolveAsset = null,
+} = {}) {
+ const effectiveMode = FABLELOOM_PRODUCTION_MODES.includes(mode)
+ ? mode
+ : FABLELOOM_PRODUCTION_MODE_DEFAULT;
+
+ const {
+ orderedNodes,
+ depthById,
+ predecessorsByNodeId,
+ unreachableNodeIds,
+ } = computeTopologicalNodeOrder(episode);
+
+ const plannedAssets = [];
+ const convergenceDetails = [];
+ const exactInputIssues = [];
+ const planningIssues = [];
+
+ if (!orderedNodes.length) {
+ planningIssues.push('Episode has no reachable scenes from a valid start node.');
+ }
+
+ let totalImageAssets = 0;
+ let totalVideoAssets = 0;
+ let totalDialogueAssets = 0;
+
+ for (const node of orderedNodes) {
+ const depth = depthById.get(node.id) ?? 0;
+ const preds = predecessorsByNodeId.get(node.id) || [];
+ const nodeBlockers = [];
+ const visualCanon = node.visualCanon || null;
+ const lockedCanon = isLockedCanon(node);
+ const universeCharacters = Array.isArray(universe?.characters) ? universe.characters : [];
+ const characterById = new Map(universeCharacters.map((character) => [character.id, character]));
+
+ if (lockedCanon && !universe) {
+ nodeBlockers.push('Locked visual canon cannot be resolved because its Universe is unavailable.');
+ }
+ if (visualCanon && universe) {
+ for (const appearance of (Array.isArray(visualCanon.characterAppearances)
+ ? visualCanon.characterAppearances
+ : [])) {
+ const character = characterById.get(appearance.characterId);
+ if (!character) {
+ nodeBlockers.push(`Bound character "${appearance.characterId}" is not present in the linked Universe.`);
+ } else if (appearance.wardrobeId
+ && !character.wardrobes?.some((wardrobe) => wardrobe.id === appearance.wardrobeId)) {
+ nodeBlockers.push(`Bound wardrobe "${appearance.wardrobeId}" is not present on character "${appearance.characterId}".`);
+ }
+ }
+ if (visualCanon.placeId && !universe.places?.some((place) => place.id === visualCanon.placeId)) {
+ nodeBlockers.push(`Bound place "${visualCanon.placeId}" is not present in the linked Universe.`);
+ }
+ for (const objectId of (Array.isArray(visualCanon.objectIds) ? visualCanon.objectIds : [])) {
+ if (!universe.objects?.some((object) => object.id === objectId)) {
+ nodeBlockers.push(`Bound object "${objectId}" is not present in the linked Universe.`);
+ }
+ }
+ }
+
+ let temporalSourceNodeId = null;
+ const explicitTemporalSource = isStr(visualCanon?.continuitySourceNodeId)
+ ? visualCanon.continuitySourceNodeId
+ : null;
+
+ if (explicitTemporalSource && !preds.some((pred) => pred.nodeId === explicitTemporalSource)) {
+ convergenceDetails.push({
+ nodeId: node.id,
+ nodeTitle: node.title || node.id,
+ predecessorCount: preds.length,
+ selectedPredecessorId: null,
+ policy: 'no-inheritance',
+ reason: 'invalid-explicit-source',
+ remediation: 'Set visualCanon.continuitySourceNodeId to an incoming predecessor of this scene.',
+ });
+ if (lockedCanon) nodeBlockers.push('Locked visual canon names a predecessor that does not lead into this scene.');
+ } else if (preds.length === 1) {
+ temporalSourceNodeId = explicitTemporalSource || preds[0].nodeId;
+ } else if (preds.length > 1) {
+ if (explicitTemporalSource) {
+ temporalSourceNodeId = explicitTemporalSource;
+ } else {
+ // Convergent scenes never inherit an arbitrary predecessor. Drafts may
+ // still render from their own prompt, while locked canon must choose an
+ // explicit incoming source before continuity can be approved.
+ convergenceDetails.push({
+ nodeId: node.id,
+ nodeTitle: node.title || node.id,
+ predecessorCount: preds.length,
+ selectedPredecessorId: null,
+ policy: 'no-inheritance',
+ remediation: 'Set visualCanon.continuitySourceNodeId on this scene to explicitly select temporal continuity source.',
+ });
+ if (lockedCanon) nodeBlockers.push('Locked convergent scene needs an explicit temporal continuity source.');
+ }
+ }
+
+ const assets = node.playbackAssets || null;
+ const existingStill = isStr(node.image) ? node.image : null;
+ const existingEntryVideo = isStr(assets?.entryVideoHistoryId) ? assets.entryVideoHistoryId : (isStr(node.videoHistoryId) ? node.videoHistoryId : null);
+
+ // Exact input provenance verification if requested
+ if (effectiveMode === 'exact_inputs') {
+ const seenManifestKeys = new Set();
+ const provenanceManifests = [
+ assets?.provenance,
+ node.visualConditioning,
+ ...Object.values(assets?.visualConditioningByAsset || {}),
+ ].filter((manifest) => {
+ if (!manifest) return false;
+ const key = manifest.assetId || JSON.stringify(manifest);
+ if (seenManifestKeys.has(key)) return false;
+ seenManifestKeys.add(key);
+ return true;
+ });
+ if (provenanceManifests.length === 0) provenanceManifests.push(null);
+ for (const recordedProvenance of provenanceManifests) {
+ const provCheck = verifyExactInputProvenance(recordedProvenance, {
+ universe,
+ localVoiceProfiles,
+ localLoras,
+ availableImageModels,
+ availableVideoModels,
+ resolveAsset,
+ });
+ if (!provCheck.valid) {
+ exactInputIssues.push({
+ nodeId: node.id,
+ errors: provCheck.errors,
+ warnings: provCheck.warnings,
+ });
+ }
+ }
+ }
+
+ if (node.interactionWindow?.enabled) {
+ const interactionCharacterId = node.interactionWindow.protagonistCharacterId;
+ const interactionCharacter = characterById.get(interactionCharacterId);
+ if (!interactionCharacterId) {
+ nodeBlockers.push('Live interaction is enabled without a protagonist character binding.');
+ } else if (!universe || !interactionCharacter) {
+ nodeBlockers.push(`Live interaction protagonist "${interactionCharacterId}" is not present in the linked Universe.`);
+ }
+
+ const approvedProfile = localVoiceProfiles?.find((profile) => (
+ profile.binding?.characterId === interactionCharacterId
+ && (!universe?.id || profile.binding?.universeId === universe.id)
+ && profile.approval?.status === 'approved'
+ ));
+ if (!approvedProfile && !interactionCharacter?.voiceId && !loom?.defaultVoiceId) {
+ nodeBlockers.push(`Live interaction protagonist "${interactionCharacterId || 'unknown'}" has no approved voice binding.`);
+ }
+
+ const holdIds = Array.isArray(assets?.holdLoopVideoHistoryIds)
+ ? assets.holdLoopVideoHistoryIds
+ : [];
+ if (!holdIds.length) {
+ nodeBlockers.push('Live interaction requires a dedicated hold loop asset.');
+ }
+ for (const holdId of holdIds) {
+ const occupancy = assets?.audioOccupancy?.[holdId];
+ if (occupancy && !validateAudioOccupancy(occupancy).safeForLiveVoice) {
+ nodeBlockers.push(`Hold loop "${holdId}" is not safe for live voice.`);
+ }
+ }
+ }
+
+ // 1. Image still asset
+ const imageAssetId = `asset-${node.id}-still`;
+ const imageDependencies = temporalSourceNodeId ? [`asset-${temporalSourceNodeId}-still`] : [];
+ const imageReady = Boolean(node.imagePrompt || node.prose) && nodeBlockers.length === 0;
+ const imageBlockers = [...nodeBlockers];
+ const imageHasPrompt = Boolean(node.imagePrompt || node.prose);
+ if (!imageHasPrompt) imageBlockers.push('Scene has neither imagePrompt nor prose.');
+
+ plannedAssets.push({
+ id: imageAssetId,
+ nodeId: node.id,
+ nodeTitle: node.title || node.id,
+ depth,
+ type: 'image',
+ role: 'image',
+ prompt: node.imagePrompt || node.prose || '',
+ temporalSourceNodeId,
+ dependencies: imageDependencies,
+ existingAssetId: existingStill,
+ status: existingStill && nodeBlockers.length === 0 ? 'already_rendered' : (imageHasPrompt && nodeBlockers.length === 0 ? 'ready' : 'blocked'),
+ readiness: {
+ ready: imageReady,
+ reasons: imageBlockers,
+ },
+ });
+ totalImageAssets += 1;
+
+ // 2. Video entry asset
+ const videoEntryAssetId = `asset-${node.id}-video-entry`;
+ const videoPrompt = node.videoPrompt || node.prose || '';
+ const videoHasPrompt = Boolean(videoPrompt);
+ const videoBlockers = [...nodeBlockers];
+ if (!videoHasPrompt) videoBlockers.push('Scene has neither videoPrompt nor prose for video.');
+ if (lockedCanon && !existingEntryVideo && node.visualCanon?.storyboardImageApproved !== true) {
+ videoBlockers.push('Locked canon video requires an author-approved storyboard image.');
+ }
+ const videoReady = videoBlockers.length === 0;
+
+ plannedAssets.push({
+ id: videoEntryAssetId,
+ nodeId: node.id,
+ nodeTitle: node.title || node.id,
+ depth,
+ type: 'video_entry',
+ role: 'entry',
+ prompt: videoPrompt,
+ cameraMovement: node.cameraMovement || null,
+ dependencies: [imageAssetId],
+ existingAssetId: existingEntryVideo,
+ status: existingEntryVideo && nodeBlockers.length === 0 ? 'already_rendered' : (videoReady ? 'ready' : 'blocked'),
+ readiness: {
+ ready: videoReady,
+ reasons: videoBlockers,
+ },
+ });
+ totalVideoAssets += 1;
+
+ // 3. Video hold loop assets (for non-cut decision / interactive scenes)
+ if (!node.isEnding && node.playbackMode !== 'cut') {
+ const holdLoops = Array.isArray(assets?.holdLoopVideoHistoryIds) ? assets.holdLoopVideoHistoryIds : [];
+ const holdAssetId = `asset-${node.id}-video-hold-0`;
+ const existingHold = holdLoops[0] || null;
+ const holdBlockers = [...nodeBlockers];
+ if (lockedCanon && !existingHold && node.visualCanon?.storyboardImageApproved !== true) {
+ holdBlockers.push('Locked canon video requires an author-approved storyboard image.');
+ }
+ if (node.interactionWindow?.enabled) {
+ for (const holdId of holdLoops) {
+ const occupancy = assets?.audioOccupancy?.[holdId];
+ if (occupancy && !validateAudioOccupancy(occupancy).safeForLiveVoice) {
+ holdBlockers.push(`Hold loop "${holdId}" is not safe for live voice.`);
+ }
+ }
+ }
+
+ plannedAssets.push({
+ id: holdAssetId,
+ nodeId: node.id,
+ nodeTitle: node.title || node.id,
+ depth,
+ type: 'video_hold',
+ role: 'hold',
+ prompt: videoPrompt,
+ cameraMovement: node.cameraMovement || null,
+ dependencies: [imageAssetId],
+ existingAssetId: existingHold,
+ status: existingHold && holdBlockers.length === 0 ? 'already_rendered' : (videoHasPrompt && holdBlockers.length === 0 ? 'ready' : 'blocked'),
+ readiness: {
+ ready: videoHasPrompt && holdBlockers.length === 0,
+ reasons: videoHasPrompt ? holdBlockers : [...holdBlockers, 'Scene has neither videoPrompt nor prose for video.'],
+ },
+ });
+ totalVideoAssets += 1;
+ }
+
+ // 4. Video exit assets for transitions
+ for (const tr of (node.transitions || [])) {
+ const exitAssetId = `asset-${node.id}-video-exit-${tr.id}`;
+ const existingExit = assets?.exitByTransition?.[tr.id] || null;
+ const exitHasPrompt = Boolean(tr.description || videoPrompt);
+ const exitBlockers = [...nodeBlockers];
+ if (!exitHasPrompt) exitBlockers.push('Transition has no description or scene video prompt.');
+ if (lockedCanon && !existingExit && node.visualCanon?.storyboardImageApproved !== true) {
+ exitBlockers.push('Locked canon video requires an author-approved storyboard image.');
+ }
+ plannedAssets.push({
+ id: exitAssetId,
+ nodeId: node.id,
+ nodeTitle: node.title || node.id,
+ transitionId: tr.id,
+ intent: tr.intent || '',
+ depth,
+ type: 'video_exit',
+ role: 'exit',
+ prompt: tr.description || videoPrompt,
+ dependencies: [imageAssetId],
+ existingAssetId: existingExit,
+ status: existingExit && exitBlockers.length === 0 ? 'already_rendered' : (exitHasPrompt && exitBlockers.length === 0 ? 'ready' : 'blocked'),
+ readiness: {
+ ready: exitHasPrompt && exitBlockers.length === 0,
+ reasons: exitBlockers,
+ },
+ });
+ totalVideoAssets += 1;
+ }
+
+ // 5. Dialogue assets if character interaction is configured
+ if (node.interactionWindow?.enabled && node.interactionWindow?.protagonistCharacterId) {
+ const charId = node.interactionWindow.protagonistCharacterId;
+ const dialogueAssetId = `asset-${node.id}-dialogue-${charId}`;
+ const character = characterById.get(charId);
+ const charInUniverse = Boolean(character);
+ const profile = localVoiceProfiles?.find((p) => (
+ p.binding?.characterId === charId
+ && (!universe?.id || p.binding?.universeId === universe.id)
+ && p.approval?.status === 'approved'
+ ));
+
+ const dialogueBlockers = [];
+ if (!charInUniverse && universe) dialogueBlockers.push(`Protagonist "${charId}" not found in Universe.`);
+ if (!profile && !character?.voiceId && !loom?.defaultVoiceId) dialogueBlockers.push(`No approved voice binding for "${charId}".`);
+ dialogueBlockers.push(...nodeBlockers);
+ const dialogueBlocked = dialogueBlockers.length > 0;
+
+ plannedAssets.push({
+ id: dialogueAssetId,
+ nodeId: node.id,
+ nodeTitle: node.title || node.id,
+ characterId: charId,
+ depth,
+ type: 'dialogue',
+ role: 'dialogue',
+ dependencies: [imageAssetId],
+ existingAssetId: null,
+ status: dialogueBlocked ? 'blocked' : 'skipped',
+ skipReason: dialogueBlocked ? null : 'Live dialogue is generated per hosted interaction; no standalone batch audio is created.',
+ readiness: {
+ ready: !dialogueBlocked,
+ reasons: dialogueBlocked
+ ? dialogueBlockers
+ : ['Live dialogue is generated per hosted interaction; no standalone batch audio is created.'],
+ },
+ });
+ totalDialogueAssets += 1;
+ }
+ }
+
+ // Compute execution stages from asset dependencies, not only node depth.
+ // A scene's video depends on its still, so grouping by scene depth alone
+ // would incorrectly expose both as independent work in one batch.
+ const stageByAssetId = new Map();
+ for (const asset of plannedAssets) {
+ const stageIndex = (asset.dependencies || []).reduce(
+ (maxStage, dependencyId) => Math.max(maxStage, (stageByAssetId.get(dependencyId) ?? -1) + 1),
+ 0,
+ );
+ stageByAssetId.set(asset.id, stageIndex);
+ asset.stageIndex = stageIndex;
+ }
+ const stageGroups = new Map();
+ for (const asset of plannedAssets) {
+ const stage = stageGroups.get(asset.stageIndex) || [];
+ stage.push(asset);
+ stageGroups.set(asset.stageIndex, stage);
+ }
+ const executionStages = Array.from(stageGroups.entries()).map(([stageIndex, stageAssets]) => ({
+ stageIndex,
+ depth: Math.min(...stageAssets.map((asset) => asset.depth)),
+ assetCount: stageAssets.length,
+ assetIds: stageAssets.map((asset) => asset.id),
+ }));
+
+ const readyAssetsCount = plannedAssets.filter((a) => a.status === 'ready').length;
+ const alreadyRenderedCount = plannedAssets.filter((a) => a.status === 'already_rendered').length;
+ const skippedAssetsCount = plannedAssets.filter((a) => a.status === 'skipped').length;
+ const blockedAssetsCount = plannedAssets.filter((a) => a.status === 'blocked').length;
+
+ return {
+ mode: effectiveMode,
+ totalNodes: (episode?.nodes || []).length,
+ reachableNodeCount: orderedNodes.length,
+ unreachableNodeCount: unreachableNodeIds.size,
+ unreachableNodeIds: Array.from(unreachableNodeIds),
+ totalAssets: plannedAssets.length,
+ assetsByType: {
+ image: totalImageAssets,
+ video: totalVideoAssets,
+ dialogue: totalDialogueAssets,
+ },
+ readyAssetsCount,
+ alreadyRenderedCount,
+ skippedAssetsCount,
+ blockedAssetsCount,
+ isFullyReady: blockedAssetsCount === 0 && exactInputIssues.length === 0 && planningIssues.length === 0,
+ planningIssues,
+ convergenceIssues: convergenceDetails,
+ exactInputIssues,
+ plannedAssets,
+ executionStages,
+ };
+}
diff --git a/server/lib/fableLoomProduction.test.js b/server/lib/fableLoomProduction.test.js
new file mode 100644
index 0000000000..a023036136
--- /dev/null
+++ b/server/lib/fableLoomProduction.test.js
@@ -0,0 +1,216 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildEpisodeProductionPlan,
+ computeTopologicalNodeOrder,
+ verifyExactInputProvenance,
+} from './fableLoomProduction.js';
+
+describe('fableLoomProduction', () => {
+ const sampleEpisode = {
+ id: 'ep-1',
+ startNodeId: 'node-1',
+ nodes: [
+ {
+ id: 'node-1',
+ title: 'Opening Scene',
+ prose: 'Opening scene prose.',
+ imagePrompt: 'A wide vista at sunset.',
+ videoPrompt: 'Camera slowly pans left.',
+ transitions: [
+ { id: 'tr-1', targetNodeId: 'node-2', intent: 'Go north' },
+ { id: 'tr-2', targetNodeId: 'node-3', intent: 'Go south' },
+ ],
+ },
+ {
+ id: 'node-2',
+ title: 'North Forest',
+ prose: 'Dark misty woods.',
+ imagePrompt: 'Misty forest path.',
+ videoPrompt: 'Tracking shot through trees.',
+ transitions: [
+ { id: 'tr-3', targetNodeId: 'node-4', intent: 'Enter cave' },
+ ],
+ },
+ {
+ id: 'node-3',
+ title: 'South Bridge',
+ prose: 'Old stone bridge over river.',
+ imagePrompt: 'Ancient stone bridge.',
+ videoPrompt: 'Aerial shot over water.',
+ transitions: [
+ { id: 'tr-4', targetNodeId: 'node-4', intent: 'Cross into cave' },
+ ],
+ },
+ {
+ id: 'node-4',
+ title: 'Convergence Cave',
+ prose: 'Deep subterranean cavern.',
+ imagePrompt: 'Crystal cave interior.',
+ videoPrompt: 'Dolly forward into cavern.',
+ isEnding: true,
+ transitions: [],
+ },
+ {
+ id: 'node-unreachable',
+ title: 'Floating Island',
+ prose: 'An unreachable island in the clouds.',
+ transitions: [],
+ },
+ ],
+ };
+
+ it('computes topological node ordering and detects convergence', () => {
+ const topo = computeTopologicalNodeOrder(sampleEpisode);
+ expect(topo.orderedNodes.map((n) => n.id)).toEqual(['node-1', 'node-2', 'node-3', 'node-4']);
+ expect(topo.depthById.get('node-1')).toBe(0);
+ expect(topo.depthById.get('node-2')).toBe(1);
+ expect(topo.depthById.get('node-3')).toBe(1);
+ expect(topo.depthById.get('node-4')).toBe(2);
+
+ expect(topo.convergenceNodeIds.has('node-4')).toBe(true);
+ expect(topo.unreachableNodeIds.has('node-unreachable')).toBe(true);
+ });
+
+ it('builds comprehensive episode production plan with assets and dependencies', () => {
+ const plan = buildEpisodeProductionPlan({
+ episode: sampleEpisode,
+ loom: { id: 'loom-1' },
+ mode: 'current_canon',
+ });
+
+ expect(plan.mode).toBe('current_canon');
+ expect(plan.totalNodes).toBe(5);
+ expect(plan.reachableNodeCount).toBe(4);
+ expect(plan.unreachableNodeCount).toBe(1);
+ expect(plan.assetsByType.image).toBe(4);
+ expect(plan.assetsByType.video).toBeGreaterThanOrEqual(4);
+
+ // Node-1 (opening) should have no image dependencies
+ const node1Image = plan.plannedAssets.find((a) => a.id === 'asset-node-1-still');
+ expect(node1Image.dependencies).toEqual([]);
+
+ // Node-2 (child of node-1) should depend on node-1 still
+ const node2Image = plan.plannedAssets.find((a) => a.id === 'asset-node-2-still');
+ expect(node2Image.dependencies).toEqual(['asset-node-1-still']);
+
+ // Video should depend on own still
+ const node1Video = plan.plannedAssets.find((a) => a.id === 'asset-node-1-video-entry');
+ expect(node1Video.dependencies).toEqual(['asset-node-1-still']);
+
+ // Convergence note for node-4
+ expect(plan.convergenceIssues.length).toBe(1);
+ expect(plan.convergenceIssues[0].nodeId).toBe('node-4');
+ expect(plan.convergenceIssues[0].selectedPredecessorId).toBeNull();
+ expect(plan.plannedAssets.find((a) => a.id === 'asset-node-4-still').temporalSourceNodeId).toBeNull();
+
+ const stillStage = plan.executionStages.find((stage) => stage.assetIds.includes('asset-node-1-still'));
+ const videoStage = plan.executionStages.find((stage) => stage.assetIds.includes('asset-node-1-video-entry'));
+ expect(videoStage.stageIndex).toBeGreaterThan(stillStage.stageIndex);
+ });
+
+ it('refuses exact-input planning when a node has no recorded provenance', () => {
+ const plan = buildEpisodeProductionPlan({
+ episode: sampleEpisode,
+ mode: 'exact_inputs',
+ });
+
+ expect(plan.isFullyReady).toBe(false);
+ expect(plan.exactInputIssues.length).toBe(4);
+ expect(plan.exactInputIssues[0].errors[0]).toContain('No recorded provenance');
+ });
+
+ it('verifies exact input provenance matching without silent substitution', () => {
+ const validProvenance = {
+ version: 1,
+ characters: [
+ {
+ characterId: 'char-1',
+ lora: { filename: 'char-1-flux.safetensors', sha256: 'abc123sha' },
+ voice: {
+ profileId: 'vp-1', profileVersion: 2, engine: 'kokoro', modelRevision: 'rev-1',
+ },
+ },
+ ],
+ };
+
+ const universe = { characters: [{ id: 'char-1', name: 'Hero' }] };
+ const localVoiceProfiles = [{ id: 'vp-1', version: 2, engine: 'kokoro', modelRevision: 'rev-1' }];
+ const localLoras = [{ filename: 'char-1-flux.safetensors', sha256: 'abc123sha' }];
+
+ const result = verifyExactInputProvenance(validProvenance, {
+ universe,
+ localVoiceProfiles,
+ localLoras,
+ });
+ expect(result.valid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+
+ // Mismatched LoRA hash
+ const mismatchedLora = verifyExactInputProvenance(validProvenance, {
+ universe,
+ localVoiceProfiles,
+ localLoras: [{ filename: 'char-1-flux.safetensors', sha256: 'different-hash' }],
+ });
+ expect(mismatchedLora.valid).toBe(false);
+ expect(mismatchedLora.errors[0]).toContain('checksum mismatch');
+
+ // Mismatched Voice Profile version
+ const mismatchedVoice = verifyExactInputProvenance(validProvenance, {
+ universe,
+ localVoiceProfiles: [{ id: 'vp-1', version: 3, engine: 'kokoro', modelRevision: 'rev-1' }],
+ localLoras,
+ });
+ expect(mismatchedVoice.valid).toBe(false);
+ expect(mismatchedVoice.errors[0]).toContain('version mismatch');
+
+ const missingModelRevision = verifyExactInputProvenance(validProvenance, {
+ universe,
+ localVoiceProfiles: [{ id: 'vp-1', version: 2, engine: 'kokoro' }],
+ localLoras,
+ });
+ expect(missingModelRevision.valid).toBe(false);
+ expect(missingModelRevision.errors.some((error) => error.includes('model revision mismatch'))).toBe(true);
+ });
+
+ it('refuses exact visual reproduction when local inputs are empty, missing, or revised', () => {
+ const visualProvenance = {
+ version: 1,
+ compilerVersion: 'visual-v1',
+ status: 'locked',
+ universeId: 'univ-1',
+ capability: {
+ kind: 'image',
+ backend: 'local',
+ modelId: 'image-model',
+ modelRevision: 'revision-1',
+ },
+ bindings: { inferred: false, characterAppearances: [], objectIds: [] },
+ assets: [{ role: 'environment', required: true, filename: 'environment.png' }],
+ adapters: [],
+ omitted: [],
+ warnings: [],
+ };
+ const baseOptions = {
+ universe: { id: 'univ-1', characters: [], places: [], objects: [] },
+ availableImageModels: [{ id: 'image-model', revision: 'revision-1' }],
+ resolveAsset: () => '/safe/environment.png',
+ };
+
+ expect(verifyExactInputProvenance(visualProvenance, baseOptions).valid).toBe(true);
+ expect(verifyExactInputProvenance(visualProvenance, {
+ ...baseOptions,
+ availableImageModels: [],
+ }).errors).toContain('Recorded image model "image-model" is not available locally.');
+ expect(verifyExactInputProvenance(visualProvenance, {
+ ...baseOptions,
+ availableImageModels: [{ id: 'image-model', revision: 'revision-2' }],
+ }).errors.some((error) => error.includes('revision mismatch'))).toBe(true);
+ const unpinned = structuredClone(visualProvenance);
+ delete unpinned.capability.modelRevision;
+ expect(verifyExactInputProvenance(unpinned, baseOptions).errors.some((error) => error.includes('immutable model revision'))).toBe(true);
+ expect(verifyExactInputProvenance(visualProvenance, {
+ ...baseOptions,
+ resolveAsset: () => null,
+ }).errors).toContain('Recorded visual conditioning asset "environment.png" is unavailable locally.');
+ });
+});
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
index 9e787e4387..da9897b0b6 100644
--- a/server/lib/fableLoomValidation.js
+++ b/server/lib/fableLoomValidation.js
@@ -18,6 +18,12 @@ import {
FABLELOOM_AUDIENCE_CONNECTION_STATES,
FABLELOOM_PARTICIPATION_MODES,
} from './fableLoomParticipation.js';
+import {
+ FABLELOOM_ASSET_TYPES,
+ FABLELOOM_PRODUCTION_MODES,
+} from './fableLoomProduction.js';
+import { EFFORT_LEVELS } from './providerModels.js';
+import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';
import { llmRoutePinSchema } from './llmRoutePin.js';
const name = z.string().trim().min(1).max(LOOM_LIMITS.NAME_MAX);
@@ -163,6 +169,11 @@ export const audioOccupancySchema = z.object({
characterDialogue: z.array(audioIntervalSchema).max(LOOM_LIMITS.AUDIO_INTERVALS_MAX).optional(),
music: z.array(audioIntervalSchema).max(LOOM_LIMITS.AUDIO_INTERVALS_MAX).optional(),
effects: z.array(audioIntervalSchema).max(LOOM_LIMITS.AUDIO_INTERVALS_MAX).optional(),
+ clipping: z.boolean().optional(),
+ clipped: z.boolean().optional(),
+ clippingDetected: z.boolean().optional(),
+ peakDb: z.number().optional(),
+ truePeakDb: z.number().optional(),
safeForLiveVoice: z.boolean().optional(),
});
@@ -172,6 +183,7 @@ export const playbackAssetsSchema = z.object({
exitByTransition: z.record(z.string(), z.string().max(200)).optional(),
audioOccupancy: z.record(z.string(), audioOccupancySchema).optional(),
provenance: z.record(z.string(), z.any()).nullable().optional(),
+ visualConditioningByAsset: z.record(z.string().max(200), z.record(z.string(), z.any())).optional(),
}).nullable();
export const interactionWindowSchema = z.object({
@@ -276,3 +288,25 @@ export const hostedSessionPatchSchema = z.object({
playbackPhase: z.enum(['entry', 'hold', 'exit', 'ended']).optional(),
activeHoldIndex: z.number().int().min(0).max(10).optional(),
});
+
+export const productionPlanSchema = z.object({
+ mode: z.enum(FABLELOOM_PRODUCTION_MODES).optional(),
+ imageMode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),
+ imageModel: z.string().trim().min(1).max(200).optional(),
+ videoMode: z.enum(VIDEO_GEN_MODES).optional(),
+ videoModel: z.string().trim().min(1).max(200).optional(),
+ effort: z.enum(EFFORT_LEVELS).optional(),
+});
+
+export const productionBatchCreateSchema = z.object({
+ mode: z.enum(FABLELOOM_PRODUCTION_MODES).optional(),
+ assetTypes: z.array(z.enum(FABLELOOM_ASSET_TYPES)).max(20).optional(),
+ nodeIds: z.array(nodeIdStr).max(LOOM_LIMITS.NODES_MAX).optional(),
+ imageMode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),
+ imageModel: z.string().trim().min(1).max(200).optional(),
+ videoMode: z.enum(VIDEO_GEN_MODES).optional(),
+ videoModel: z.string().trim().min(1).max(200).optional(),
+ effort: z.enum(EFFORT_LEVELS).optional(),
+});
+
+export const continuityReviewSchema = z.object({});
diff --git a/server/lib/index.js b/server/lib/index.js
index 4a3173b84c..3bf5fd6aa8 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -86,6 +86,8 @@ export * from './fableLoomPlayback.js';
export * from './fableLoomParticipation.js';
export * from './fableLoomLimits.js';
export * from './fableLoomFormats.js';
+export * from './fableLoomProduction.js';
+export * from './fableLoomContinuity.js';
export * from './scenePrompt.js';
export * from './proseExportSettings.js';
export * from './shotGrammar.js';
diff --git a/server/lib/renderTargets.js b/server/lib/renderTargets.js
index e75a714126..2085763ad7 100644
--- a/server/lib/renderTargets.js
+++ b/server/lib/renderTargets.js
@@ -25,6 +25,7 @@ export const RENDER_TARGET = Object.freeze({
MUSIC_VIDEO: 'music-video',
LORA_DATASET: 'lora-dataset',
CREATIVE_AGENT: 'creative-agent',
+ FABLELOOM_PRODUCTION: 'fableloom-production',
});
export const RENDER_TARGETS = Object.freeze(Object.values(RENDER_TARGET));
diff --git a/server/lib/renderTargets.parity.test.js b/server/lib/renderTargets.parity.test.js
index d20944742c..90dee98813 100644
--- a/server/lib/renderTargets.parity.test.js
+++ b/server/lib/renderTargets.parity.test.js
@@ -32,9 +32,11 @@ import {
} from '../../client/src/lib/imageGenModes.js';
// Targets the Settings UI deliberately does NOT list — a pin nobody's
-// resolver reads would be a control that silently does nothing. Empty since
-// the Phase 4 video lane wired music-video (the last unlisted target).
-const DELIBERATELY_UNLISTED = new Set([]);
+// resolver reads would be a control that silently does nothing. FableLoom
+// production exposes per-run controls instead of a persistent Settings pin;
+// its server-only target exists so the service still goes through the shared
+// resolver guard.
+const DELIBERATELY_UNLISTED = new Set([RENDER_TARGET.FABLELOOM_PRODUCTION]);
describe('render-target client mirror parity (#3231)', () => {
it('every client option id is a real server render target', () => {
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index ca792a641f..e2e71fd910 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -357,7 +357,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v2 = scene nodes gained portable `visualCanon` bindings plus the latest
// render's path-free `visualConditioning` provenance. A v1 peer would strip
// both during whole-record LWW, so newer sends must pause until it upgrades.
- fableLoom: 2,
+ // 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,
// 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/socketEventCatalog.generated.json b/server/lib/socketEventCatalog.generated.json
index 4ffe1f1073..6ed40dc3e7 100644
--- a/server/lib/socketEventCatalog.generated.json
+++ b/server/lib/socketEventCatalog.generated.json
@@ -215,7 +215,12 @@
{
"direction": "server-to-client",
"source": "client/src/hooks/useAIStatusNotifications.js",
- "line": 195
+ "line": 196
+ },
+ {
+ "direction": "server-to-client",
+ "source": "client/src/hooks/useFableLoomAiRun.js",
+ "line": 17
},
{
"direction": "server-to-client",
@@ -5481,6 +5486,6 @@
"clientToServer": 72,
"serverToClient": 217,
"bidirectional": 9,
- "sourceFiles": 107
+ "sourceFiles": 108
}
}
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
index 9b33c58219..0b3c262c60 100644
--- a/server/routes/fableLoom.js
+++ b/server/routes/fableLoom.js
@@ -32,6 +32,9 @@ import {
weaveSchema,
hostedSessionCreateSchema,
hostedSessionPatchSchema,
+ productionPlanSchema,
+ productionBatchCreateSchema,
+ continuityReviewSchema,
} from '../lib/fableLoomValidation.js';
import { analyzeEpisodeGraph } from '../lib/fableLoomGraph.js';
import {
@@ -44,6 +47,7 @@ import {
addNode,
addNodeTransition,
branchNode,
+ cancelEpisodeProductionBatch,
checkHostedSessionReadiness,
createHostedSession,
createLoom,
@@ -55,13 +59,18 @@ import {
feedbackEpisode,
feedbackSeriesPlan,
generateSeriesPlan,
+ getEpisodeProductionBatch,
getHostedSession,
getLoom,
listLoomSummaries,
+ planEpisodeProduction,
playTurn,
reformatEpisodeScenes,
reviewEpisode,
+ reviewEpisodeContinuity,
+ resumeEpisodeProductionBatch,
reviewSeriesPlan,
+ startEpisodeProductionBatch,
updateEpisode,
updateHostedSession,
updateLoom,
@@ -274,5 +283,45 @@ router.delete('/sessions/:sessionId', asyncHandler(async (req, res) => {
res.json(endHostedSession(req.params.sessionId, { reason: 'api_deleted' }));
}));
-export default router;
+// --- Production Orchestration & Continuity Review ---------------------------
+
+router.post('/:id/episodes/:episodeId/production/plan', asyncHandler(async (req, res) => {
+ const input = validateRequest(productionPlanSchema, req.body ?? {});
+ res.json(await planEpisodeProduction(req.params.id, req.params.episodeId, input));
+}));
+
+router.post('/:id/episodes/:episodeId/production/batch', asyncHandler(async (req, res) => {
+ const input = validateRequest(productionBatchCreateSchema, req.body ?? {});
+ res.status(201).json(await startEpisodeProductionBatch(req.params.id, req.params.episodeId, input));
+}));
+
+router.get('/:id/episodes/:episodeId/production/batch/:runId', asyncHandler(async (req, res) => {
+ const run = getEpisodeProductionBatch(req.params.runId);
+ if (!run || run.loomId !== req.params.id || run.episodeId !== req.params.episodeId) {
+ throw new ServerError('Batch production run not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(run);
+}));
+router.post('/:id/episodes/:episodeId/production/batch/:runId/cancel', asyncHandler(async (req, res) => {
+ const run = getEpisodeProductionBatch(req.params.runId);
+ if (!run || run.loomId !== req.params.id || run.episodeId !== req.params.episodeId) {
+ throw new ServerError('Batch production run not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(await cancelEpisodeProductionBatch(req.params.runId));
+}));
+
+router.post('/:id/episodes/:episodeId/production/batch/:runId/resume', asyncHandler(async (req, res) => {
+ const run = getEpisodeProductionBatch(req.params.runId);
+ if (!run || run.loomId !== req.params.id || run.episodeId !== req.params.episodeId) {
+ throw new ServerError('Batch production run not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(resumeEpisodeProductionBatch(req.params.runId));
+}));
+
+router.post('/:id/episodes/:episodeId/continuity/review', asyncHandler(async (req, res) => {
+ validateRequest(continuityReviewSchema, req.body ?? {});
+ res.json(await reviewEpisodeContinuity(req.params.id, req.params.episodeId));
+}));
+
+export default router;
diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.js
index 75ddd1bf47..dd268f54d7 100644
--- a/server/routes/fableLoom.test.js
+++ b/server/routes/fableLoom.test.js
@@ -32,6 +32,12 @@ vi.mock('../services/fableLoom/index.js', () => ({
getHostedSession: vi.fn(),
updateHostedSession: vi.fn(),
endHostedSession: vi.fn(),
+ planEpisodeProduction: vi.fn(),
+ startEpisodeProductionBatch: vi.fn(),
+ getEpisodeProductionBatch: vi.fn(),
+ cancelEpisodeProductionBatch: vi.fn(),
+ resumeEpisodeProductionBatch: vi.fn(),
+ reviewEpisodeContinuity: vi.fn(),
}));
import * as fableLoom from '../services/fableLoom/index.js';
@@ -354,5 +360,64 @@ describe('FableLoom routes', () => {
expect(fableLoom.endHostedSession).toHaveBeenCalledWith('sess-1', { reason: 'api_deleted' });
});
});
-});
+ describe('production orchestration & continuity review', () => {
+ it('POST /:id/episodes/:episodeId/production/plan returns production plan', async () => {
+ fableLoom.planEpisodeProduction.mockResolvedValueOnce({ mode: 'current_canon', plannedAssets: [] });
+ const res = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/production/plan')
+ .send({ mode: 'current_canon' });
+ expect(res.status).toBe(200);
+ expect(res.body.mode).toBe('current_canon');
+ expect(fableLoom.planEpisodeProduction).toHaveBeenCalledWith('loom-1', 'ep-1', { mode: 'current_canon' });
+ });
+
+ it('POST /:id/episodes/:episodeId/production/batch starts a batch run', async () => {
+ fableLoom.startEpisodeProductionBatch.mockResolvedValueOnce({ id: 'batch-1', status: 'in_progress' });
+ const res = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/production/batch')
+ .send({ mode: 'current_canon' });
+ expect(res.status).toBe(201);
+ expect(res.body.id).toBe('batch-1');
+ expect(fableLoom.startEpisodeProductionBatch).toHaveBeenCalledWith('loom-1', 'ep-1', { mode: 'current_canon' });
+ });
+
+ it('GET /:id/episodes/:episodeId/production/batch/:runId retrieves batch run or 404s', async () => {
+ fableLoom.getEpisodeProductionBatch.mockReturnValueOnce({ id: 'batch-1', loomId: 'loom-1', episodeId: 'ep-1', status: 'in_progress' });
+ const res = await request(makeApp()).get('/api/fableloom/loom-1/episodes/ep-1/production/batch/batch-1');
+ expect(res.status).toBe(200);
+ expect(res.body.id).toBe('batch-1');
+
+ fableLoom.getEpisodeProductionBatch.mockReturnValueOnce(null);
+ const notFound = await request(makeApp()).get('/api/fableloom/loom-1/episodes/ep-1/production/batch/batch-none');
+ expect(notFound.status).toBe(404);
+ });
+
+ it('POST /:id/episodes/:episodeId/production/batch/:runId/cancel cancels run', async () => {
+ fableLoom.getEpisodeProductionBatch.mockReturnValueOnce({ id: 'batch-1', loomId: 'loom-1', episodeId: 'ep-1', status: 'in_progress' });
+ fableLoom.cancelEpisodeProductionBatch.mockReturnValueOnce({ id: 'batch-1', status: 'canceled' });
+ const res = await request(makeApp()).post('/api/fableloom/loom-1/episodes/ep-1/production/batch/batch-1/cancel');
+ expect(res.status).toBe(200);
+ expect(res.body.status).toBe('canceled');
+ });
+
+ it('POST /:id/episodes/:episodeId/production/batch/:runId/resume resumes a run', async () => {
+ fableLoom.getEpisodeProductionBatch.mockReturnValueOnce({ id: 'batch-1', loomId: 'loom-1', episodeId: 'ep-1', status: 'failed' });
+ fableLoom.resumeEpisodeProductionBatch.mockReturnValueOnce({ id: 'batch-1', status: 'in_progress' });
+ const res = await request(makeApp()).post('/api/fableloom/loom-1/episodes/ep-1/production/batch/batch-1/resume');
+ expect(res.status).toBe(200);
+ expect(res.body.status).toBe('in_progress');
+ expect(fableLoom.resumeEpisodeProductionBatch).toHaveBeenCalledWith('batch-1');
+ });
+
+ it('POST /:id/episodes/:episodeId/continuity/review performs continuity review', async () => {
+ fableLoom.reviewEpisodeContinuity.mockResolvedValueOnce({ passed: true, findings: [] });
+ const res = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/continuity/review')
+ .send({});
+ expect(res.status).toBe(200);
+ expect(res.body.passed).toBe(true);
+ expect(fableLoom.reviewEpisodeContinuity).toHaveBeenCalledWith('loom-1', 'ep-1');
+ });
+ });
+});
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 77432e4f33..ae8cf8bf7a 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -177,6 +177,7 @@ const generateSchema = z.object({
loomId: z.string().min(1).max(200),
episodeId: z.string().min(1).max(200),
nodeId: z.string().min(1).max(200),
+ role: z.literal('image').optional(),
}).optional(),
// Music Video scene reference-frame render (#1760 Phase 1b). When present, the
// mediaJobQueue completion hook (`musicVideoSceneImageHook`) files the finished
@@ -399,7 +400,10 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// approved assets and deterministic graph continuity own the final request.
if (params.fableLoom) {
const selected = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModel(params.modelId) : null;
- const model = selected ? { ...selected, loraCompatKey: loraCompatKey(selected) } : null;
+ const cloud = selected ? null : resolveCloudProviderConfig(settings, mode, { model: params.cloudModel });
+ const model = selected
+ ? { ...selected, loraCompatKey: loraCompatKey(selected) }
+ : (cloud ? { id: cloud.modelId } : null);
const providerMode = params.mediaProviderPeerId ? 'federated' : mode;
const compiled = await compileFableLoomVisualRequest({
tag: params.fableLoom,
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index bb1c458188..18f6b3d366 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -372,6 +372,8 @@ const generateBodySchema = z.object({
loomId: z.string().min(1).max(200),
episodeId: z.string().min(1).max(200),
nodeId: z.string().min(1).max(200),
+ role: z.enum(['entry', 'hold', 'exit']).optional(),
+ transitionId: z.string().min(1).max(200).optional(),
}).optional(),
),
// Federated media provider (#4348). When set, the render is submitted to
@@ -1033,10 +1035,13 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
const { backend, cleanupStaged } = prepared;
if (body.fableLoom) {
+ const conditioningModel = backend === IMAGE_GEN_MODE.GROK
+ ? { id: 'grok-video', supportedModes: ['image'] }
+ : prepared.effectiveModel;
const compiled = await compileFableLoomVisualRequest({
tag: body.fableLoom,
kind: 'video',
- capability: fableLoomVideoCapabilities({ backend, model: prepared.effectiveModel }),
+ capability: fableLoomVideoCapabilities({ backend, model: conditioningModel }),
authoredPrompt: body.prompt,
authoredNegativePrompt: body.negativePrompt,
sourceImagePath: prepared.sourceImagePath,
diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.md
index c7f3f9f26c..e3144cac1c 100644
--- a/server/services/fableLoom/README.md
+++ b/server/services/fableLoom/README.md
@@ -12,6 +12,7 @@ intent to a transition and moves them through the graph until an ending.
| `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). |
| `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). |
| `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). |
| `db.js` | PostgreSQL leaf I/O. |
diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.js
index f26c71e127..52b070af6f 100644
--- a/server/services/fableLoom/index.js
+++ b/server/services/fableLoom/index.js
@@ -76,4 +76,11 @@ export {
updateHostedSession,
verifyHostedToken,
} from './hostedSession.js';
-
+export {
+ cancelEpisodeProductionBatch,
+ getEpisodeProductionBatch,
+ planEpisodeProduction,
+ reviewEpisodeContinuity,
+ resumeEpisodeProductionBatch,
+ startEpisodeProductionBatch,
+} from './production.js';
diff --git a/server/services/fableLoom/production.js b/server/services/fableLoom/production.js
new file mode 100644
index 0000000000..b3545b2b9b
--- /dev/null
+++ b/server/services/fableLoom/production.js
@@ -0,0 +1,951 @@
+/**
+ * FableLoom production batch service.
+ *
+ * Planning is deterministic and side-effect free. A batch run is explicitly
+ * started by the user, then advances its dependency graph through the shared
+ * media queue. The run registry is intentionally process-local: media jobs
+ * remain the durable work records, while this small state machine provides the
+ * episode-level grouping, dependency barriers, cancellation, and resume UX.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { basename } from 'node:path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { resolveImageInputPath } from '../../lib/fileUtils.js';
+import { getImageModels, isEditOnly } from '../../lib/mediaModels.js';
+import { selectLocalImageModel, resolveLocalImageModel } from '../imageGen/prepareParams.js';
+import {
+ IMAGE_GEN_MODE,
+ QUEUEABLE_IMAGE_MODES,
+ resolveQueueImageMode,
+} from '../imageGen/modes.js';
+import { maxInputImages, resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';
+import { RENDER_TARGET } from '../../lib/renderTargets.js';
+import { getSettings } from '../settings.js';
+import {
+ DEFAULT_NUM_FRAMES,
+ defaultVideoModelId,
+ listVideoModels,
+ resolveVideoModel,
+} from '../videoGen/local.js';
+import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode } from '../videoGen/modes.js';
+import {
+ compileFableLoomVisualRequest,
+ fableLoomImageCapabilities,
+ fableLoomVideoCapabilities,
+} from './visualConditioning.js';
+import { cancelJob, enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';
+import {
+ buildEpisodeProductionPlan,
+ FABLELOOM_PRODUCTION_MODE_DEFAULT,
+} from '../../lib/fableLoomProduction.js';
+import { analyzeEpisodeContinuity } from '../../lib/fableLoomContinuity.js';
+import { getUniverse } from '../universeBuilder.js';
+import { listVoiceProfiles } from '../voice/profiles.js';
+import { listLoras } from '../loras.js';
+import { getLoom, findEpisode } from './records.js';
+
+const BATCH_RUN_MAX_AGE_MS = 2 * 60 * 60 * 1000;
+const MAX_CONCURRENT_RUNS = 20;
+const _batchRuns = new Map();
+const _runRuntime = new Map();
+const _jobToAsset = new Map();
+
+const TERMINAL_JOB_EVENTS = Object.freeze(['completed', 'failed', 'canceled']);
+const ACTIVE_ASSET_STATUSES = new Set(['preparing', 'queued', 'running']);
+const EFFECTIVE_PARAMETER_KEYS = Object.freeze([
+ 'width', 'height', 'numFrames', 'fps', 'steps', 'guidance', 'guidanceScale',
+ 'seed', 'imageStrength', 'quantize', 'effort', 'mode', 'videoMode',
+ 'aspectRatio', 'disableAudio', 'tiling',
+]);
+
+const nowIso = () => new Date().toISOString();
+const text = (value) => (typeof value === 'string' ? value.trim() : '');
+const errorMessage = (error) => error?.message || String(error);
+const isTerminalRun = (run) => ['completed', 'canceled', 'failed'].includes(run?.status);
+
+function effectiveParameters(params = {}) {
+ return Object.fromEntries(EFFECTIVE_PARAMETER_KEYS.flatMap((key) => {
+ const value = params[key];
+ if (typeof value === 'number' && Number.isFinite(value)) return [[key, value]];
+ if (typeof value === 'boolean') return [[key, value]];
+ if (typeof value === 'string' && value.trim()) return [[key, value.trim()]];
+ return [];
+ }));
+}
+
+const exactInputError = (message) => new ServerError(message, {
+ status: 409,
+ code: 'EXACT_INPUTS_REFUSED',
+});
+
+function updateSummary(run) {
+ const summary = {
+ total: run.assets.length,
+ pending: 0,
+ preparing: 0,
+ queued: 0,
+ running: 0,
+ completed: 0,
+ failed: 0,
+ skipped: 0,
+ blocked: 0,
+ canceled: 0,
+ };
+ for (const asset of run.assets) {
+ if (summary[asset.status] !== undefined) summary[asset.status] += 1;
+ }
+ run.summary = summary;
+}
+
+function touchRun(run) {
+ run.updatedAt = nowIso();
+ updateSummary(run);
+}
+
+function cleanStaleRuns() {
+ const cutoff = Date.now() - BATCH_RUN_MAX_AGE_MS;
+ for (const [runId, run] of _batchRuns.entries()) {
+ if (!isTerminalRun(run)) continue;
+ const updatedAt = Date.parse(run.updatedAt || run.createdAt || '');
+ if (Number.isFinite(updatedAt) && updatedAt < cutoff) {
+ _batchRuns.delete(runId);
+ _runRuntime.delete(runId);
+ for (const [jobId, mapping] of _jobToAsset.entries()) {
+ if (mapping.runId === runId) _jobToAsset.delete(jobId);
+ }
+ }
+ }
+}
+
+function normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel, effort } = {}) {
+ return {
+ imageMode: QUEUEABLE_IMAGE_MODES.includes(imageMode) ? imageMode : null,
+ imageModel: text(imageModel) || null,
+ videoMode: VIDEO_GEN_MODES.includes(videoMode) ? videoMode : null,
+ videoModel: text(videoModel) || null,
+ effort: text(effort) || null,
+ };
+}
+
+function selectAssets(plan, { assetTypes = null, nodeIds = null } = {}) {
+ const typeFilter = Array.isArray(assetTypes) && assetTypes.length > 0 ? new Set(assetTypes) : null;
+ const nodeFilter = Array.isArray(nodeIds) && nodeIds.length > 0 ? new Set(nodeIds) : null;
+ const byId = new Map(plan.plannedAssets.map((asset) => [asset.id, asset]));
+ const selected = new Set(plan.plannedAssets
+ .filter((asset) => (!typeFilter || typeFilter.has(asset.type))
+ && (!nodeFilter || nodeFilter.has(asset.nodeId)))
+ .map((asset) => asset.id));
+
+ // A filtered batch must carry the full dependency closure. Selecting only
+ // video stills must not enqueue a clip before its scene still exists.
+ const visit = (assetId) => {
+ const asset = byId.get(assetId);
+ if (!asset || selected.has(assetId)) return;
+ selected.add(assetId);
+ for (const dependencyId of asset.dependencies || []) visit(dependencyId);
+ };
+ for (const assetId of [...selected]) {
+ for (const dependencyId of byId.get(assetId)?.dependencies || []) visit(dependencyId);
+ }
+ return plan.plannedAssets.filter((asset) => selected.has(asset.id));
+}
+
+function assetState(asset) {
+ const alreadyRendered = asset.status === 'already_rendered';
+ const skipped = asset.status === 'skipped';
+ return {
+ id: asset.id,
+ nodeId: asset.nodeId,
+ nodeTitle: asset.nodeTitle,
+ type: asset.type,
+ role: asset.role || null,
+ transitionId: asset.transitionId || null,
+ characterId: asset.characterId || null,
+ intent: asset.intent || null,
+ depth: asset.depth,
+ stageIndex: asset.stageIndex,
+ prompt: asset.prompt || '',
+ cameraMovement: asset.cameraMovement || null,
+ temporalSourceNodeId: asset.temporalSourceNodeId || null,
+ dependencies: Array.isArray(asset.dependencies) ? [...asset.dependencies] : [],
+ existingAssetId: asset.existingAssetId || null,
+ readiness: asset.readiness || { ready: false, reasons: [] },
+ skipReason: asset.skipReason || null,
+ status: alreadyRendered ? 'completed' : skipped ? 'skipped' : 'pending',
+ jobId: null,
+ provider: null,
+ modelId: null,
+ modelRevision: null,
+ result: alreadyRendered && asset.existingAssetId
+ ? { filename: basename(asset.existingAssetId), existing: true }
+ : null,
+ visualConditioning: null,
+ effectiveParameters: null,
+ error: null,
+ };
+}
+
+async function loadRecordedConditioning(run, asset) {
+ if (run.mode !== 'exact_inputs') return null;
+ const loom = await getLoom(run.loomId);
+ const episode = loom?.episodes?.find((item) => item.id === run.episodeId);
+ const node = episode?.nodes?.find((item) => item.id === asset.nodeId);
+ const perAsset = node?.playbackAssets?.visualConditioningByAsset || {};
+ const matched = perAsset[asset.id]
+ || Object.values(perAsset).find((manifest) => manifest?.assetId === asset.id)
+ || (asset.existingAssetId ? perAsset[asset.existingAssetId] : null);
+ return matched || node?.visualConditioning || null;
+}
+
+function exactConditioningMismatches(recorded, current) {
+ if (!recorded || !current) return ['The recorded visual conditioning could not be reconstructed.'];
+ const mismatches = [];
+ const recordedCapability = recorded.capability || {};
+ const currentCapability = current.capability || {};
+ for (const key of ['kind', 'backend', 'modelId', 'modelRevision']) {
+ if (recordedCapability[key] != null && recordedCapability[key] !== currentCapability[key]) {
+ mismatches.push(`Recorded ${key} "${recordedCapability[key]}" does not match the current compiled value "${currentCapability[key] || 'unknown'}".`);
+ }
+ }
+ for (const key of ['bindings', 'assets', 'adapters', 'temporalSourceNodeId', 'referenceImageStrengths']) {
+ if (recorded[key] !== undefined && JSON.stringify(recorded[key]) !== JSON.stringify(current[key])) {
+ mismatches.push(`Recorded visual conditioning ${key} changed.`);
+ }
+ }
+ for (const key of ['compiledPrompt', 'compiledNegativePrompt']) {
+ if (recorded[key] !== undefined && recorded[key] !== current[key]) {
+ mismatches.push(`Recorded ${key} changed.`);
+ }
+ }
+ return mismatches;
+}
+
+function assertExactConditioning(recorded, current) {
+ const mismatches = exactConditioningMismatches(recorded, current);
+ if (mismatches.length) {
+ throw exactInputError(`Exact-input reproduction refused: ${mismatches.join(' ')}`);
+ }
+}
+
+function enrichConditioning(conditioning, job, asset) {
+ if (!conditioning) return null;
+ return {
+ ...conditioning,
+ assetId: asset.id,
+ render: {
+ provider: job.provider,
+ modelId: job.modelId || null,
+ modelRevision: job.modelRevision || conditioning.capability?.modelRevision || null,
+ parameters: effectiveParameters(job.params),
+ },
+ };
+}
+
+function productionTag(run, asset) {
+ const tag = {
+ loomId: run.loomId,
+ episodeId: run.episodeId,
+ nodeId: asset.nodeId,
+ };
+ if (asset.type === 'image') tag.role = 'image';
+ if (asset.type !== 'image' && asset.role) tag.role = asset.role;
+ if (asset.transitionId) tag.transitionId = asset.transitionId;
+ return tag;
+}
+
+async function loadRunLoom(run) {
+ const loom = await getLoom(run.loomId);
+ if (!loom) throw new ServerError('Loom not found', { status: 404, code: 'NOT_FOUND' });
+ const outputByNode = new Map(run.assets
+ .filter((asset) => asset.type === 'image' && asset.status === 'completed' && asset.result?.filename)
+ .map((asset) => [asset.nodeId, asset.result.filename]));
+ if (!outputByNode.size) return loom;
+ return {
+ ...loom,
+ episodes: loom.episodes.map((episode) => (episode.id !== run.episodeId ? episode : {
+ ...episode,
+ nodes: episode.nodes.map((node) => (outputByNode.has(node.id)
+ ? { ...node, image: outputByNode.get(node.id) }
+ : node)),
+ })),
+ };
+}
+
+function imageInputForNode(run, asset) {
+ const imageAsset = run.assets.find((candidate) => candidate.type === 'image' && candidate.nodeId === asset.nodeId);
+ return resolveImageInputPath(imageAsset?.result?.filename || null);
+}
+
+function requestedImageModel(settings, render, recordedConditioning = null) {
+ return recordedConditioning?.capability?.modelId
+ || render.imageModel
+ || settings.imageGen?.local?.modelId
+ || undefined;
+}
+
+function resolveImageBackend(settings, render, recordedConditioning = null) {
+ const recordedBackend = recordedConditioning?.capability?.backend;
+ if (recordedBackend) {
+ if (render.imageMode && render.imageMode !== recordedBackend) {
+ throw exactInputError(`Exact-input reproduction refuses image backend "${render.imageMode}"; the recorded render used "${recordedBackend}".`);
+ }
+ if (!QUEUEABLE_IMAGE_MODES.includes(recordedBackend)) {
+ throw exactInputError(`Exact-input reproduction cannot replay unsupported image backend "${recordedBackend}".`);
+ }
+ const resolvedRecorded = resolveQueueImageMode(recordedBackend, settings);
+ if (resolvedRecorded !== recordedBackend) {
+ const recordedCloud = resolveRenderTargetConfig(settings, RENDER_TARGET.FABLELOOM_PRODUCTION, {
+ mode: recordedBackend,
+ }).cloud;
+ throw exactInputError(recordedCloud?.disabledError?.message
+ || `Exact-input reproduction cannot use recorded image backend "${recordedBackend}" on this machine.`);
+ }
+ return recordedBackend;
+ }
+ const requested = render.imageMode || (render.imageModel ? IMAGE_GEN_MODE.LOCAL : null);
+ const mode = requested ? resolveQueueImageMode(requested, settings) : resolveQueueImageMode(null, settings);
+ if (requested && mode !== requested) {
+ const requestedCloud = resolveRenderTargetConfig(settings, RENDER_TARGET.FABLELOOM_PRODUCTION, {
+ mode: requested,
+ }).cloud;
+ if (requestedCloud?.disabledError) throw requestedCloud.disabledError;
+ }
+ return mode;
+}
+
+function resolveVideoBackend(settings, render, recordedConditioning = null) {
+ const recordedBackend = recordedConditioning?.capability?.backend;
+ if (recordedBackend) {
+ if (render.videoMode && render.videoMode !== recordedBackend) {
+ throw exactInputError(`Exact-input reproduction refuses video backend "${render.videoMode}"; the recorded render used "${recordedBackend}".`);
+ }
+ if (!VIDEO_GEN_MODES.includes(recordedBackend)) {
+ throw exactInputError(`Exact-input reproduction cannot replay unsupported video backend "${recordedBackend}".`);
+ }
+ const resolvedRecorded = resolveVideoMode(recordedBackend, settings);
+ if (resolvedRecorded !== recordedBackend) {
+ throw exactInputError(`Exact-input reproduction cannot use recorded video backend "${recordedBackend}" on this machine.`);
+ }
+ return recordedBackend;
+ }
+ const requested = render.videoMode;
+ const mode = requested ? resolveVideoMode(requested, settings) : resolveVideoMode(null, settings);
+ if (requested === VIDEO_GEN_MODE.GROK && mode !== VIDEO_GEN_MODE.GROK) {
+ throw new ServerError('Grok video is disabled — enable Grok in Settings → Image Gen first', {
+ status: 400,
+ code: 'GROK_VIDEO_DISABLED',
+ });
+ }
+ return mode;
+}
+
+function conditionRequest(run, asset, kind, capability, sourceImagePath = null) {
+ return compileFableLoomVisualRequest({
+ tag: productionTag(run, asset),
+ kind,
+ capability,
+ authoredPrompt: asset.prompt,
+ sourceImagePath,
+ loadLoom: () => loadRunLoom(run),
+ });
+}
+
+async function prepareImageJob(run, asset) {
+ const settings = await getSettings();
+ const recordedConditioning = await loadRecordedConditioning(run, asset);
+ const mode = resolveImageBackend(settings, run.render, recordedConditioning);
+ const allModels = getImageModels();
+ const requestedModel = requestedImageModel(settings, run.render, recordedConditioning);
+ const provisionalModel = selectLocalImageModel(requestedModel, allModels);
+ const cloud = mode === IMAGE_GEN_MODE.LOCAL
+ ? null
+ : resolveRenderTargetConfig(settings, RENDER_TARGET.FABLELOOM_PRODUCTION, {
+ mode,
+ model: recordedConditioning?.capability?.modelId
+ || (run.render.imageMode === mode ? run.render.imageModel : null),
+ }).cloud;
+ const capability = fableLoomImageCapabilities({
+ mode,
+ model: mode === IMAGE_GEN_MODE.LOCAL ? provisionalModel : { id: cloud?.modelId || null },
+ inputBudget: maxInputImages(mode) || 4,
+ });
+ const conditioned = await conditionRequest(run, asset, 'image', capability);
+ if (run.mode === 'exact_inputs') assertExactConditioning(recordedConditioning, conditioned?.visualConditioning);
+ const referenceImagePaths = conditioned?.referenceImagePaths || [];
+ const localInitImagePath = conditioned?.sourceImagePath || referenceImagePaths[0] || null;
+
+ if (mode === IMAGE_GEN_MODE.LOCAL) {
+ const local = resolveLocalImageModel(settings, {
+ modelId: requestedModel,
+ initImagePath: localInitImagePath,
+ });
+ if (!local.selectedModel) {
+ throw new ServerError('No compatible local image model is available.', {
+ status: 409,
+ code: 'IMAGE_GEN_UNKNOWN_MODEL',
+ });
+ }
+ const selectedIsEditOnly = isEditOnly(local.selectedModel);
+ return {
+ kind: 'image',
+ provider: mode,
+ modelId: local.selectedModel.id,
+ modelRevision: local.selectedModel.revision || null,
+ params: {
+ pythonPath: local.pythonPath,
+ prompt: conditioned?.prompt || asset.prompt,
+ negativePrompt: conditioned?.negativePrompt || '',
+ modelId: local.selectedModel.id,
+ width: 1024,
+ height: 1024,
+ steps: settings.imageGen?.local?.steps,
+ guidance: settings.imageGen?.local?.guidance,
+ quantize: settings.imageGen?.local?.quantize ?? '8',
+ ...(selectedIsEditOnly && localInitImagePath ? { initImagePath: localInitImagePath } : {}),
+ referenceImagePaths: selectedIsEditOnly ? referenceImagePaths.slice(1) : referenceImagePaths,
+ referenceImageStrengths: selectedIsEditOnly
+ ? (conditioned?.referenceImageStrengths || []).slice(1)
+ : (conditioned?.referenceImageStrengths || []),
+ loraFilenames: conditioned?.loraFilenames || [],
+ loraScales: conditioned?.loraScales || [],
+ visualConditioning: conditioned?.visualConditioning || null,
+ fableLoom: productionTag(run, asset),
+ },
+ };
+ }
+
+ if (!cloud?.enabled) {
+ throw cloud?.disabledError || new ServerError('Image provider is disabled.', {
+ status: 400,
+ code: 'IMAGE_PROVIDER_DISABLED',
+ });
+ }
+ const providerParams = {
+ ...cloud.providerParams,
+ ...(mode === IMAGE_GEN_MODE.CODEX && run.render.effort ? { effort: run.render.effort } : {}),
+ };
+ return {
+ kind: 'image',
+ provider: mode,
+ modelId: cloud.modelId,
+ modelRevision: capability.modelRevision || null,
+ params: {
+ mode,
+ ...providerParams,
+ prompt: conditioned?.prompt || asset.prompt,
+ negativePrompt: conditioned?.negativePrompt || '',
+ width: 1024,
+ height: 1024,
+ initImagePath: conditioned?.sourceImagePath || null,
+ referenceImagePaths,
+ referenceImageStrengths: conditioned?.referenceImageStrengths || [],
+ loraFilenames: conditioned?.loraFilenames || [],
+ loraScales: conditioned?.loraScales || [],
+ visualConditioning: conditioned?.visualConditioning || null,
+ fableLoom: productionTag(run, asset),
+ },
+ };
+}
+
+async function prepareVideoJob(run, asset) {
+ const settings = await getSettings();
+ const recordedConditioning = await loadRecordedConditioning(run, asset);
+ const backend = resolveVideoBackend(settings, run.render, recordedConditioning);
+ const requestedModelId = recordedConditioning?.capability?.modelId
+ || run.render.videoModel
+ || settings.videoGen?.defaultModelId
+ || defaultVideoModelId();
+ const model = resolveVideoModel(requestedModelId);
+ if (backend === VIDEO_GEN_MODE.LOCAL && !model) {
+ throw new ServerError(`Unknown video model: ${requestedModelId}`, {
+ status: 400,
+ code: 'VIDEO_GEN_UNKNOWN_MODEL',
+ });
+ }
+ const capability = fableLoomVideoCapabilities({
+ backend,
+ model: backend === VIDEO_GEN_MODE.LOCAL
+ ? model
+ : { id: 'grok-video', supportedModes: ['image'] },
+ });
+ const requestedSourceImagePath = imageInputForNode(run, asset);
+ const conditioned = await conditionRequest(run, asset, 'video', capability, requestedSourceImagePath);
+ if (run.mode === 'exact_inputs') assertExactConditioning(recordedConditioning, conditioned?.visualConditioning);
+ const sourceImagePath = conditioned ? conditioned.sourceImagePath : requestedSourceImagePath;
+
+ if (backend === VIDEO_GEN_MODE.LOCAL) {
+ const supportedModes = Array.isArray(model.supportedModes) ? model.supportedModes : [];
+ const videoMode = sourceImagePath ? 'image' : 'text';
+ if (!supportedModes.includes(videoMode)) {
+ throw new ServerError(`Video model "${model.id}" does not support ${videoMode}-to-video renders.`, {
+ status: 409,
+ code: 'VIDEO_MODEL_UNSUPPORTED_MODE',
+ });
+ }
+ return {
+ kind: 'video',
+ provider: backend,
+ modelId: model.id,
+ modelRevision: model.revision || null,
+ params: {
+ pythonPath: settings.imageGen?.local?.pythonPath || null,
+ prompt: conditioned?.prompt || asset.prompt,
+ negativePrompt: conditioned?.negativePrompt || '',
+ modelId: model.id,
+ width: model.defaultWidth || 1024,
+ height: model.defaultHeight || 576,
+ numFrames: model.defaultFrames || DEFAULT_NUM_FRAMES,
+ fps: model.defaultFps || 24,
+ steps: model.defaultSteps,
+ guidanceScale: model.defaultGuidanceScale,
+ sourceImagePath,
+ mode: videoMode,
+ visualConditioning: conditioned?.visualConditioning || null,
+ fableLoom: productionTag(run, asset),
+ },
+ };
+ }
+
+ const cloud = resolveRenderTargetConfig(settings, RENDER_TARGET.FABLELOOM_PRODUCTION, {
+ mode: IMAGE_GEN_MODE.GROK,
+ model: recordedConditioning?.capability?.modelId || null,
+ }).cloud;
+ if (!cloud?.enabled) {
+ throw cloud?.disabledError || new ServerError('Grok video is disabled.', {
+ status: 400,
+ code: 'GROK_VIDEO_DISABLED',
+ });
+ }
+ return {
+ kind: 'video',
+ provider: backend,
+ modelId: cloud.modelId,
+ modelRevision: capability.modelRevision || null,
+ params: {
+ mode: VIDEO_GEN_MODE.GROK,
+ videoMode: sourceImagePath ? 'image' : 'text',
+ ...cloud.providerParams,
+ prompt: conditioned?.prompt || asset.prompt,
+ negativePrompt: conditioned?.negativePrompt || '',
+ width: 1024,
+ height: 576,
+ sourceImagePath,
+ visualConditioning: conditioned?.visualConditioning || null,
+ fableLoom: productionTag(run, asset),
+ },
+ };
+}
+
+async function prepareJob(run, asset) {
+ if (asset.type === 'image') return prepareImageJob(run, asset);
+ if (asset.type === 'dialogue') return null;
+ return prepareVideoJob(run, asset);
+}
+
+function failRun(run, error) {
+ if (isTerminalRun(run)) return;
+ run.status = 'failed';
+ run.error = errorMessage(error);
+ for (const asset of run.assets) {
+ if (asset.status === 'pending' || asset.status === 'preparing') {
+ asset.status = 'blocked';
+ asset.error = 'Batch stopped before this dependency stage could run.';
+ }
+ }
+ touchRun(run);
+}
+
+function scheduleRun(runId, operation) {
+ const runtime = _runRuntime.get(runId);
+ if (!runtime) return Promise.resolve(null);
+ const next = runtime.tail.then(operation);
+ const handled = next.catch((error) => {
+ const run = _batchRuns.get(runId);
+ if (run) failRun(run, error);
+ console.error(`❌ FableLoom production batch ${runId.slice(0, 16)} failed: ${errorMessage(error)}`);
+ return null;
+ });
+ runtime.tail = handled;
+ return handled;
+}
+
+function dependenciesReady(run, asset) {
+ const byId = new Map(run.assets.map((candidate) => [candidate.id, candidate]));
+ for (const dependencyId of asset.dependencies) {
+ const dependency = byId.get(dependencyId);
+ if (!dependency) return { ready: false, failed: true, reason: `Missing dependency ${dependencyId}.` };
+ if (['failed', 'canceled', 'blocked'].includes(dependency.status)) {
+ return { ready: false, failed: true, reason: `Dependency ${dependencyId} did not complete.` };
+ }
+ if (!['completed', 'skipped'].includes(dependency.status)) return { ready: false, failed: false };
+ }
+ return { ready: true, failed: false };
+}
+
+async function advanceRun(runId) {
+ const run = _batchRuns.get(runId);
+ if (!run || run.status !== 'in_progress' || run.cancelRequested) return run;
+ if (run.assets.some((asset) => ACTIVE_ASSET_STATUSES.has(asset.status))) return run;
+
+ const pending = run.assets.filter((asset) => asset.status === 'pending');
+ if (!pending.length) {
+ run.status = run.assets.some((asset) => ['failed', 'blocked', 'canceled'].includes(asset.status))
+ ? 'failed'
+ : 'completed';
+ run.error = run.status === 'failed' ? (run.error || 'One or more production assets failed.') : null;
+ touchRun(run);
+ return run;
+ }
+
+ const nextStage = Math.min(...pending.map((asset) => asset.stageIndex ?? 0));
+ const stageAssets = pending.filter((asset) => (asset.stageIndex ?? 0) === nextStage);
+ const dependencyState = stageAssets.map((asset) => ({ asset, state: dependenciesReady(run, asset) }));
+ const blocked = dependencyState.filter(({ state }) => state.failed);
+ if (blocked.length) {
+ for (const { asset, state } of blocked) {
+ asset.status = 'blocked';
+ asset.error = state.reason;
+ }
+ run.status = 'failed';
+ run.error = 'A production dependency failed; resume after repairing the failed asset.';
+ touchRun(run);
+ return run;
+ }
+ if (dependencyState.some(({ state }) => !state.ready)) return run;
+
+ for (const asset of stageAssets) asset.status = 'preparing';
+ touchRun(run);
+ const prepared = await Promise.all(stageAssets.map(async (asset) => ({
+ asset,
+ job: await prepareJob(run, asset),
+ })));
+ if (run.cancelRequested || run.status !== 'in_progress') return run;
+
+ for (const { asset, job } of prepared) {
+ if (!job) {
+ asset.status = 'skipped';
+ asset.skipReason = asset.skipReason || 'No queue-backed render is required for this asset.';
+ continue;
+ }
+ const visualConditioning = enrichConditioning(job.params.visualConditioning, job, asset);
+ if (visualConditioning) job.params.visualConditioning = visualConditioning;
+ const enqueued = enqueueJob({
+ kind: job.kind,
+ params: job.params,
+ owner: `fableloom:${run.loomId}:${run.episodeId}:${asset.id}`,
+ });
+ asset.jobId = enqueued.jobId;
+ asset.provider = job.provider || (job.kind === 'image' ? IMAGE_GEN_MODE.LOCAL : VIDEO_GEN_MODE.LOCAL);
+ asset.modelId = job.modelId || null;
+ asset.modelRevision = job.modelRevision || visualConditioning?.render?.modelRevision || null;
+ asset.visualConditioning = visualConditioning;
+ asset.effectiveParameters = effectiveParameters(job.params);
+ asset.status = 'queued';
+ _jobToAsset.set(enqueued.jobId, { runId, assetId: asset.id });
+ }
+ touchRun(run);
+ return run;
+}
+
+async function handleJobTerminal(event, job) {
+ const mapping = _jobToAsset.get(job?.id);
+ if (!mapping) return;
+ const run = _batchRuns.get(mapping.runId);
+ const asset = run?.assets.find((candidate) => candidate.id === mapping.assetId);
+ if (!run || !asset) {
+ _jobToAsset.delete(job.id);
+ return;
+ }
+ _jobToAsset.delete(job.id);
+ if (event === 'completed') {
+ asset.status = 'completed';
+ asset.result = job.result || null;
+ asset.error = null;
+ } else if (event === 'canceled') {
+ asset.status = 'canceled';
+ asset.error = job.error || 'Media job canceled.';
+ } else {
+ asset.status = 'failed';
+ asset.error = job.error || 'Media job failed.';
+ run.error = run.error || asset.error;
+ }
+ touchRun(run);
+ if (run.status === 'in_progress' && event === 'completed') await advanceRun(run.id);
+ if (run.status === 'in_progress' && event === 'canceled') {
+ run.status = 'canceled';
+ run.cancelRequested = true;
+ touchRun(run);
+ }
+ if (run.status === 'in_progress' && event === 'failed') {
+ run.status = 'failed';
+ for (const pendingAsset of run.assets) {
+ if (pendingAsset.status === 'pending' || pendingAsset.status === 'preparing') {
+ pendingAsset.status = 'blocked';
+ pendingAsset.error = 'Batch stopped after a media job failed.';
+ }
+ }
+ touchRun(run);
+ }
+}
+
+for (const event of TERMINAL_JOB_EVENTS) {
+ mediaJobEvents.on(event, (job) => {
+ const mapping = _jobToAsset.get(job?.id);
+ if (!mapping) return;
+ void scheduleRun(mapping.runId, () => handleJobTerminal(event, job)).catch((error) => {
+ console.error(`❌ FableLoom production media event failed: ${errorMessage(error)}`);
+ });
+ });
+}
+
+/** Plan production assets and topological execution for an episode. */
+export async function planEpisodeProduction(loomId, episodeId, {
+ mode = FABLELOOM_PRODUCTION_MODE_DEFAULT,
+ imageMode,
+ imageModel,
+ videoMode,
+ videoModel,
+ effort,
+} = {}) {
+ const loom = await getLoom(loomId);
+ if (!loom) throw new ServerError('Loom not found', { status: 404, code: 'NOT_FOUND' });
+ const episode = findEpisode(loom, episodeId);
+ if (!episode) throw new ServerError('Episode not found', { status: 404, code: 'NOT_FOUND' });
+ const [universe, voiceProfiles, loras] = await Promise.all([
+ loom.universeId ? getUniverse(loom.universeId) : null,
+ listVoiceProfiles(),
+ listLoras(),
+ ]);
+ const plan = buildEpisodeProductionPlan({
+ loom,
+ episode,
+ universe,
+ mode,
+ localVoiceProfiles: voiceProfiles,
+ localLoras: loras,
+ availableImageModels: getImageModels(),
+ availableVideoModels: listVideoModels(),
+ resolveAsset: resolveImageInputPath,
+ });
+ const render = normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel, effort });
+ const settings = await getSettings();
+ if (plan.mode === 'exact_inputs') {
+ const exactEnvironmentIssues = new Set();
+ for (const node of episode.nodes || []) {
+ const manifests = [
+ node.visualConditioning,
+ ...Object.values(node.playbackAssets?.visualConditioningByAsset || {}),
+ ].filter((manifest) => manifest && typeof manifest === 'object');
+ for (const manifest of manifests) {
+ const capability = manifest.capability || {};
+ const key = `${node.id}:${capability.kind || 'media'}:${capability.backend || 'unknown'}:${capability.modelId || 'unknown'}`;
+ let issue = null;
+ if (capability.kind === 'video') {
+ if (!VIDEO_GEN_MODES.includes(capability.backend)) {
+ issue = `Recorded visual conditioning names unsupported video backend "${capability.backend || 'unknown'}".`;
+ } else if (capability.backend === VIDEO_GEN_MODE.GROK
+ && settings.imageGen?.grok?.enabled !== true) {
+ issue = 'Recorded visual conditioning requires Grok video, which is disabled in Settings → Image Gen.';
+ }
+ } else if (!QUEUEABLE_IMAGE_MODES.includes(capability.backend)) {
+ issue = `Recorded visual conditioning names unsupported image backend "${capability.backend || 'unknown'}".`;
+ } else if (capability.backend !== IMAGE_GEN_MODE.LOCAL) {
+ const provider = resolveRenderTargetConfig(settings, RENDER_TARGET.FABLELOOM_PRODUCTION, {
+ mode: capability.backend,
+ }).cloud;
+ if (provider && !provider.enabled) issue = provider.disabledError.message;
+ }
+ if (issue && !exactEnvironmentIssues.has(`${key}:${issue}`)) {
+ exactEnvironmentIssues.add(`${key}:${issue}`);
+ plan.exactInputIssues.push({ nodeId: node.id, errors: [issue], warnings: [] });
+ }
+ }
+ }
+ }
+ if (render.imageMode && render.imageMode !== IMAGE_GEN_MODE.LOCAL) {
+ const imageProvider = resolveRenderTargetConfig(settings, RENDER_TARGET.FABLELOOM_PRODUCTION, {
+ mode: render.imageMode,
+ }).cloud;
+ if (imageProvider && !imageProvider.enabled) {
+ plan.planningIssues.push(`${render.imageMode} image generation is disabled in Settings → Image Gen.`);
+ }
+ }
+ if (render.imageMode === IMAGE_GEN_MODE.LOCAL || render.imageModel) {
+ const imageModelId = render.imageModel || settings.imageGen?.local?.modelId;
+ if (imageModelId && !getImageModels().some((model) => model.id === imageModelId)) {
+ plan.planningIssues.push(`Image model "${imageModelId}" is not available on this machine.`);
+ }
+ }
+ if (render.videoMode === VIDEO_GEN_MODE.GROK
+ && settings.imageGen?.grok?.enabled !== true) {
+ plan.planningIssues.push('Grok video is disabled in Settings → Image Gen.');
+ }
+ if (render.videoMode === VIDEO_GEN_MODE.LOCAL || render.videoModel) {
+ const videoModelId = render.videoModel || settings.videoGen?.defaultModelId;
+ if (videoModelId && !listVideoModels().some((model) => model.id === videoModelId)) {
+ plan.planningIssues.push(`Video model "${videoModelId}" is not available on this machine.`);
+ }
+ }
+ return {
+ ...plan,
+ renderOptions: render,
+ };
+}
+
+/** Start a user-triggered batch production run. */
+export async function startEpisodeProductionBatch(loomId, episodeId, {
+ mode = FABLELOOM_PRODUCTION_MODE_DEFAULT,
+ assetTypes = null,
+ nodeIds = null,
+ imageMode,
+ imageModel,
+ videoMode,
+ videoModel,
+ effort,
+} = {}) {
+ cleanStaleRuns();
+ const activeRuns = [..._batchRuns.values()].filter((run) => run.status === 'in_progress').length;
+ if (activeRuns >= MAX_CONCURRENT_RUNS) {
+ throw new ServerError('The maximum number of active production runs is already in progress.', {
+ status: 409,
+ code: 'PRODUCTION_RUN_LIMIT',
+ });
+ }
+
+ const render = normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel, effort });
+ const plan = await planEpisodeProduction(loomId, episodeId, { mode, ...render });
+ const targetAssets = selectAssets(plan, { assetTypes, nodeIds });
+ const blockedAssets = targetAssets.filter((asset) => asset.status === 'blocked');
+ if (blockedAssets.length > 0 || plan.exactInputIssues.length > 0 || plan.planningIssues.length > 0) {
+ throw new ServerError(
+ plan.mode === 'exact_inputs'
+ ? 'Exact-input reproduction refused: recorded assets or revisions are missing or mismatched.'
+ : 'Production batch is not ready: resolve the reported asset and continuity blockers first.',
+ {
+ status: 409,
+ code: plan.mode === 'exact_inputs' ? 'EXACT_INPUTS_REFUSED' : 'PRODUCTION_NOT_READY',
+ context: {
+ details: {
+ blockedAssetCount: blockedAssets.length,
+ exactInputIssueCount: plan.exactInputIssues.length,
+ planningIssueCount: plan.planningIssues.length,
+ },
+ },
+ },
+ );
+ }
+
+ const runId = `batch-${randomUUID()}`;
+ const createdAt = nowIso();
+ const run = {
+ id: runId,
+ loomId,
+ episodeId,
+ mode: plan.mode,
+ status: 'in_progress',
+ createdAt,
+ updatedAt: createdAt,
+ cancelRequested: false,
+ error: null,
+ render,
+ plan: {
+ mode: plan.mode,
+ totalNodes: plan.totalNodes,
+ totalAssets: targetAssets.length,
+ executionStages: plan.executionStages
+ .map((stage) => ({
+ ...stage,
+ assetIds: stage.assetIds.filter((assetId) => targetAssets.some((asset) => asset.id === assetId)),
+ }))
+ .filter((stage) => stage.assetIds.length > 0),
+ },
+ assets: targetAssets.map(assetState),
+ summary: null,
+ };
+ updateSummary(run);
+ _batchRuns.set(runId, run);
+ _runRuntime.set(runId, { tail: Promise.resolve() });
+ if (run.summary.pending === 0) {
+ run.status = run.summary.failed || run.summary.blocked ? 'failed' : 'completed';
+ touchRun(run);
+ } else {
+ void scheduleRun(runId, () => advanceRun(runId));
+ }
+ return run;
+}
+
+/** Get the status of an ongoing or completed batch run. */
+export function getEpisodeProductionBatch(runId) {
+ if (!runId || typeof runId !== 'string') return null;
+ return _batchRuns.get(runId) || null;
+}
+
+/** Cancel an in-flight batch run and its queued/running media jobs. */
+export async function cancelEpisodeProductionBatch(runId) {
+ const run = _batchRuns.get(runId);
+ if (!run) throw new ServerError('Batch run not found', { status: 404, code: 'NOT_FOUND' });
+ if (run.status !== 'in_progress') return run;
+ run.cancelRequested = true;
+ const jobIds = run.assets
+ .filter((asset) => asset.jobId && ['queued', 'running'].includes(asset.status))
+ .map((asset) => asset.jobId);
+ await Promise.all(jobIds.map((jobId) => cancelJob(jobId)));
+ for (const asset of run.assets) {
+ if (asset.status === 'pending' || asset.status === 'preparing'
+ || asset.status === 'queued' || asset.status === 'running') {
+ asset.status = 'canceled';
+ asset.error = 'Canceled by the user.';
+ }
+ }
+ for (const jobId of jobIds) _jobToAsset.delete(jobId);
+ run.status = 'canceled';
+ touchRun(run);
+ return run;
+}
+
+/** Resume a failed or canceled run after the user repairs its blockers. */
+export function resumeEpisodeProductionBatch(runId) {
+ const run = _batchRuns.get(runId);
+ if (!run) throw new ServerError('Batch run not found', { status: 404, code: 'NOT_FOUND' });
+ if (!['failed', 'canceled'].includes(run.status)) return run;
+ for (const asset of run.assets) {
+ if (asset.status === 'failed' || asset.status === 'blocked' || asset.status === 'canceled') {
+ asset.status = 'pending';
+ asset.jobId = null;
+ asset.error = null;
+ }
+ }
+ run.status = 'in_progress';
+ run.cancelRequested = false;
+ run.error = null;
+ _runRuntime.set(runId, _runRuntime.get(runId) || { tail: Promise.resolve() });
+ touchRun(run);
+ void scheduleRun(runId, () => advanceRun(runId));
+ return run;
+}
+
+/** Perform a user-triggered continuity review across an episode. */
+export async function reviewEpisodeContinuity(loomId, episodeId) {
+ const loom = await getLoom(loomId);
+ if (!loom) throw new ServerError('Loom not found', { status: 404, code: 'NOT_FOUND' });
+ const episode = findEpisode(loom, episodeId);
+ if (!episode) throw new ServerError('Episode not found', { status: 404, code: 'NOT_FOUND' });
+ const [universe, voiceProfiles] = await Promise.all([
+ loom.universeId ? getUniverse(loom.universeId) : null,
+ listVoiceProfiles(),
+ ]);
+ return analyzeEpisodeContinuity({
+ loom,
+ episode,
+ universe,
+ localVoiceProfiles: voiceProfiles,
+ });
+}
+
+/** Test-only helper to reset in-memory batch runs. */
+export function _resetProductionBatchRuns() {
+ _batchRuns.clear();
+ _runRuntime.clear();
+ _jobToAsset.clear();
+}
diff --git a/server/services/fableLoom/production.test.js b/server/services/fableLoom/production.test.js
new file mode 100644
index 0000000000..bdaf764236
--- /dev/null
+++ b/server/services/fableLoom/production.test.js
@@ -0,0 +1,227 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ _resetProductionBatchRuns,
+ cancelEpisodeProductionBatch,
+ getEpisodeProductionBatch,
+ planEpisodeProduction,
+ reviewEpisodeContinuity,
+ resumeEpisodeProductionBatch,
+ startEpisodeProductionBatch,
+} from './production.js';
+import * as records from './records.js';
+import * as universeBuilder from '../universeBuilder.js';
+import * as voiceProfiles from '../voice/profiles.js';
+import * as loras from '../loras.js';
+
+const queueMocks = vi.hoisted(() => {
+ const listeners = new Map();
+ const mediaJobEvents = {
+ on: vi.fn((event, handler) => {
+ const handlers = listeners.get(event) || [];
+ handlers.push(handler);
+ listeners.set(event, handlers);
+ }),
+ emit: (event, payload) => {
+ for (const handler of listeners.get(event) || []) handler(payload);
+ },
+ };
+ return { enqueueJob: vi.fn(), cancelJob: vi.fn(), mediaJobEvents };
+});
+const settingsMocks = vi.hoisted(() => ({ getSettings: vi.fn() }));
+const mediaModelMocks = vi.hoisted(() => ({
+ getImageModels: vi.fn(),
+ isEditOnly: vi.fn(),
+}));
+const imagePrepareMocks = vi.hoisted(() => ({
+ selectLocalImageModel: vi.fn(),
+ resolveLocalImageModel: vi.fn(),
+}));
+const videoModelMocks = vi.hoisted(() => ({
+ DEFAULT_NUM_FRAMES: 16,
+ defaultVideoModelId: vi.fn(),
+ listVideoModels: vi.fn(),
+ resolveVideoModel: vi.fn(),
+}));
+const visualConditioningMocks = vi.hoisted(() => ({
+ compileFableLoomVisualRequest: vi.fn(),
+ fableLoomImageCapabilities: vi.fn(),
+ fableLoomVideoCapabilities: vi.fn(),
+}));
+
+vi.mock('./records.js');
+vi.mock('../universeBuilder.js');
+vi.mock('../voice/profiles.js');
+vi.mock('../loras.js');
+vi.mock('../settings.js', () => settingsMocks);
+vi.mock('../../lib/mediaModels.js', () => mediaModelMocks);
+vi.mock('../imageGen/prepareParams.js', () => imagePrepareMocks);
+vi.mock('../videoGen/local.js', () => videoModelMocks);
+vi.mock('../mediaJobQueue/index.js', () => queueMocks);
+vi.mock('./visualConditioning.js', () => visualConditioningMocks);
+
+describe('fableLoom production service', () => {
+ const sampleLoom = {
+ id: 'loom-1',
+ name: 'Test Loom',
+ universeId: 'univ-1',
+ episodes: [
+ {
+ id: 'ep-1',
+ title: 'Episode 1',
+ startNodeId: 'node-1',
+ nodes: [
+ {
+ id: 'node-1',
+ title: 'Node 1',
+ prose: 'Opening scene prose.',
+ imagePrompt: 'Visual prompt 1',
+ videoPrompt: 'Video prompt 1',
+ transitions: [{ id: 'tr-1', targetNodeId: 'node-2', intent: 'Go forward' }],
+ },
+ {
+ id: 'node-2',
+ title: 'Node 2',
+ prose: 'Second scene prose.',
+ imagePrompt: 'Visual prompt 2',
+ videoPrompt: 'Video prompt 2',
+ isEnding: true,
+ transitions: [],
+ },
+ ],
+ },
+ ],
+ };
+
+ const sampleUniverse = {
+ id: 'univ-1',
+ characters: [{ id: 'char-1', name: 'Hero', wardrobes: [{ id: 'w-1' }] }],
+ places: [],
+ objects: [],
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ _resetProductionBatchRuns();
+ records.getLoom.mockResolvedValue(sampleLoom);
+ records.findEpisode.mockImplementation((loom, epId) => loom.episodes.find((e) => e.id === epId));
+ universeBuilder.getUniverse.mockResolvedValue(sampleUniverse);
+ voiceProfiles.listVoiceProfiles.mockResolvedValue([]);
+ loras.listLoras.mockResolvedValue([]);
+ settingsMocks.getSettings.mockResolvedValue({ imageGen: { local: {} }, videoGen: {} });
+ const imageModel = { id: 'image-model', runner: 'flux2', hardwareCompatibility: { state: 'ready', reasons: [] } };
+ mediaModelMocks.getImageModels.mockReturnValue([imageModel]);
+ mediaModelMocks.isEditOnly.mockReturnValue(false);
+ imagePrepareMocks.selectLocalImageModel.mockReturnValue(imageModel);
+ imagePrepareMocks.resolveLocalImageModel.mockReturnValue({ pythonPath: null, selectedModel: imageModel });
+ videoModelMocks.defaultVideoModelId.mockReturnValue('video-model');
+ const videoModel = {
+ id: 'video-model',
+ supportedModes: ['text', 'image'],
+ defaultWidth: 1024,
+ defaultHeight: 576,
+ defaultFrames: 16,
+ };
+ videoModelMocks.listVideoModels.mockReturnValue([videoModel]);
+ videoModelMocks.resolveVideoModel.mockReturnValue(videoModel);
+ visualConditioningMocks.compileFableLoomVisualRequest.mockResolvedValue(null);
+ visualConditioningMocks.fableLoomImageCapabilities.mockReturnValue({
+ kind: 'image', backend: 'local', modelId: 'image-model', referenceRoles: [], referenceBudget: 0,
+ });
+ visualConditioningMocks.fableLoomVideoCapabilities.mockReturnValue({
+ kind: 'video', backend: 'local', modelId: 'video-model', referenceRoles: [], referenceBudget: 0,
+ });
+ let nextJobId = 1;
+ queueMocks.enqueueJob.mockImplementation(() => ({ jobId: `job-${nextJobId++}`, position: 1, status: 'queued' }));
+ queueMocks.cancelJob.mockResolvedValue({ ok: true, status: 'canceled' });
+ });
+
+ it('plans episode production with topological asset enumeration', async () => {
+ const plan = await planEpisodeProduction('loom-1', 'ep-1', { mode: 'current_canon' });
+ expect(plan.totalNodes).toBe(2);
+ expect(plan.reachableNodeCount).toBe(2);
+ 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);
+ });
+
+ it('creates and tracks batch production runs', async () => {
+ const run = await startEpisodeProductionBatch('loom-1', 'ep-1', { mode: 'current_canon' });
+ expect(run.id).toMatch(/^batch-/);
+ expect(run.loomId).toBe('loom-1');
+ expect(run.episodeId).toBe('ep-1');
+ expect(run.assets.length).toBeGreaterThan(0);
+ expect(run.plan.executionStages.length).toBeGreaterThan(0);
+ expect(run.assets[0]).toHaveProperty('dependencies');
+
+ const fetched = getEpisodeProductionBatch(run.id);
+ expect(fetched).toEqual(run);
+ });
+
+ it('refuses a batch when its selected assets are blocked', async () => {
+ const blockedLoom = structuredClone(sampleLoom);
+ blockedLoom.episodes[0].nodes[0].prose = '';
+ blockedLoom.episodes[0].nodes[0].imagePrompt = '';
+ blockedLoom.episodes[0].nodes[0].videoPrompt = '';
+ records.getLoom.mockResolvedValueOnce(blockedLoom);
+
+ await expect(startEpisodeProductionBatch('loom-1', 'ep-1', { mode: 'current_canon' }))
+ .rejects.toMatchObject({ code: 'PRODUCTION_NOT_READY', status: 409 });
+ });
+
+ it('refuses exact-input reproduction without recorded provenance', async () => {
+ await expect(startEpisodeProductionBatch('loom-1', 'ep-1', { mode: 'exact_inputs' }))
+ .rejects.toMatchObject({ code: 'EXACT_INPUTS_REFUSED', status: 409 });
+ });
+
+ it('cancels an in-progress batch run', async () => {
+ const run = await startEpisodeProductionBatch('loom-1', 'ep-1', { mode: 'current_canon' });
+ const canceled = await cancelEpisodeProductionBatch(run.id);
+ expect(canceled.status).toBe('canceled');
+ expect(canceled.cancelRequested).toBe(true);
+ });
+
+ it('resumes a canceled run after resetting unfinished assets', async () => {
+ const run = await startEpisodeProductionBatch('loom-1', 'ep-1', { mode: 'current_canon' });
+ await cancelEpisodeProductionBatch(run.id);
+
+ const resumed = resumeEpisodeProductionBatch(run.id);
+ expect(resumed.status).toBe('in_progress');
+ expect(resumed.assets.every((asset) => !['failed', 'blocked', 'canceled'].includes(asset.status))).toBe(true);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(queueMocks.enqueueJob).toHaveBeenCalled();
+ });
+
+ it('advances to the next dependency stage only after queue jobs complete', async () => {
+ const run = await startEpisodeProductionBatch('loom-1', 'ep-1', { mode: 'current_canon' });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(queueMocks.enqueueJob).toHaveBeenCalledTimes(1);
+ expect(queueMocks.enqueueJob.mock.calls[0][0].kind).toBe('image');
+
+ queueMocks.mediaJobEvents.emit('completed', {
+ id: 'job-1',
+ result: { filename: 'node-1.png' },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(queueMocks.enqueueJob.mock.calls.length).toBeGreaterThan(1);
+ expect(queueMocks.enqueueJob.mock.calls.slice(1).some(([job]) => job.kind === 'video')).toBe(true);
+
+ for (let stage = 0; stage < 4 && run.status === 'in_progress'; stage += 1) {
+ for (const asset of run.assets.filter((candidate) => candidate.jobId
+ && ['queued', 'running'].includes(candidate.status))) {
+ queueMocks.mediaJobEvents.emit('completed', {
+ id: asset.jobId,
+ result: { filename: `${asset.jobId}.mp4` },
+ });
+ }
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ expect(run.status).toBe('completed');
+ });
+
+ it('performs episodic continuity review returning structured findings', async () => {
+ const review = await reviewEpisodeContinuity('loom-1', 'ep-1');
+ expect(review.passed).toBe(true);
+ expect(review.nodesEvaluated).toBe(2);
+ expect(review.findings).toBeDefined();
+ });
+});
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index e365294cde..564df9d839 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -47,6 +47,7 @@ import {
isSafeVideoHistoryId,
sanitizeInteractionWindow,
sanitizePlaybackAssets,
+ sanitizeVisualConditioning,
} from '../../lib/fableLoomPlayback.js';
import {
FABLELOOM_LEGACY_PARTICIPATION_MODE,
@@ -67,78 +68,6 @@ const sanitizePos = (raw) => (raw && typeof raw === 'object'
? { x: Math.round(raw.x), y: Math.round(raw.y) }
: null);
-const sanitizeVisualConditioning = (raw) => {
- if (!raw || typeof raw !== 'object' || raw.version !== 1) return null;
- const list = (value, max) => (Array.isArray(value) ? value.slice(0, max) : []);
- const capability = raw.capability && typeof raw.capability === 'object' ? raw.capability : {};
- const bindings = raw.bindings && typeof raw.bindings === 'object' ? raw.bindings : {};
- return {
- version: 1,
- compilerVersion: trimTo(raw.compilerVersion, 40),
- status: ['locked', 'draft', 'degraded'].includes(raw.status) ? raw.status : 'degraded',
- universeId: nullableRef(raw.universeId),
- capability: {
- version: Number.isInteger(capability.version) ? capability.version : 1,
- kind: capability.kind === 'video' ? 'video' : 'image',
- backend: trimTo(capability.backend, 40),
- modelId: nullableRef(capability.modelId),
- referenceRoles: list(capability.referenceRoles, 24)
- .map((item) => trimTo(item, 64)).filter(Boolean),
- referenceBudget: Number.isInteger(capability.referenceBudget)
- ? Math.max(0, Math.min(24, capability.referenceBudget)) : 0,
- supportsLora: capability.supportsLora === true,
- loraCompatKey: nullableRef(capability.loraCompatKey),
- loraBudget: Number.isInteger(capability.loraBudget)
- ? Math.max(0, Math.min(8, capability.loraBudget)) : 0,
- multiCharacterPreservation: capability.multiCharacterPreservation === true,
- ...(capability.kind === 'video' ? {
- firstFrame: capability.firstFrame === true,
- lastFrame: capability.lastFrame === true,
- extension: capability.extension === true,
- } : {}),
- },
- bindings: {
- inferred: bindings.inferred === true,
- characterAppearances: list(bindings.characterAppearances, LOOM_LIMITS.VISUAL_BINDINGS_MAX)
- .filter((item) => item && typeof item === 'object' && nullableRef(item.characterId))
- .map((item) => ({
- characterId: nullableRef(item.characterId),
- wardrobeId: nullableRef(item.wardrobeId),
- expression: trimTo(item.expression, LOOM_LIMITS.VISUAL_NOTE_MAX),
- continuityNotes: trimTo(item.continuityNotes, LOOM_LIMITS.VISUAL_NOTE_MAX),
- })),
- placeId: nullableRef(bindings.placeId),
- objectIds: list(bindings.objectIds, LOOM_LIMITS.VISUAL_BINDINGS_MAX)
- .map(nullableRef).filter(Boolean),
- },
- assets: list(raw.assets, LOOM_LIMITS.VISUAL_PROVENANCE_ASSETS_MAX)
- .filter((item) => item && typeof item === 'object')
- .map((item) => ({
- role: trimTo(item.role, 64), bindingId: nullableRef(item.bindingId),
- required: item.required === true, filename: trimTo(item.filename, 256),
- })),
- adapters: list(raw.adapters, 8)
- .filter((item) => item && typeof item === 'object')
- .map((item) => ({
- characterId: nullableRef(item.characterId), filename: trimTo(item.filename, 256),
- scale: Number.isFinite(item.scale) ? Math.max(0, Math.min(2, item.scale)) : 1,
- sha256: typeof item.sha256 === 'string' && /^[a-f0-9]{64}$/i.test(item.sha256) ? item.sha256 : null,
- })),
- omitted: list(raw.omitted, LOOM_LIMITS.VISUAL_PROVENANCE_MESSAGES_MAX)
- .filter((item) => item && typeof item === 'object')
- .map((item) => ({
- role: trimTo(item.role, 64), bindingId: nullableRef(item.bindingId),
- reason: trimTo(item.reason, 80),
- ...(item.filename ? { filename: trimTo(item.filename, 256) } : {}),
- })),
- warnings: (Array.isArray(raw.warnings) ? raw.warnings : [])
- .map((item) => trimTo(item, LOOM_LIMITS.VISUAL_NOTE_MAX)).filter(Boolean)
- .slice(0, LOOM_LIMITS.VISUAL_PROVENANCE_MESSAGES_MAX),
- temporalSourceNodeId: nullableRef(raw.temporalSourceNodeId),
- compiledAt: isStr(raw.compiledAt) ? raw.compiledAt : null,
- };
-};
-
const sanitizeVisualCanon = (raw) => {
if (!raw || typeof raw !== 'object') return null;
const appearances = (Array.isArray(raw.characterAppearances) ? raw.characterAppearances : [])
@@ -502,12 +431,13 @@ export async function deleteLoom(id) {
emitRecordDeleted('fableLoom', id);
}
-// A v1 peer cannot represent the v2 scene production fields. When that older
+// An older peer cannot represent newer scene production fields. When that
// peer wins whole-record LWW after an unrelated edit, retain the local fields
// on nodes that still exist instead of letting its unaware sanitizer clear
-// them. A v2 sender's present null remains an intentional clear.
+// them. A sender at the current schema version's present null remains an
+// intentional clear.
const preserveLegacyVisualProduction = (remote, local, senderVersion) => {
- if (!local || senderVersion >= 2) return remote;
+ if (!local || senderVersion >= 3) return remote;
const localEpisodes = new Map(local.episodes.map((episode) => [episode.id, episode]));
return {
...remote,
@@ -521,6 +451,14 @@ const preserveLegacyVisualProduction = (remote, local, senderVersion) => {
...node,
visualCanon: localNode.visualCanon,
visualConditioning: localNode.visualConditioning,
+ playbackAssets: senderVersion < 3
+ ? {
+ ...node.playbackAssets,
+ ...(localNode.playbackAssets?.visualConditioningByAsset
+ ? { visualConditioningByAsset: localNode.playbackAssets.visualConditioningByAsset }
+ : {}),
+ }
+ : node.playbackAssets,
} : node;
}),
};
@@ -537,7 +475,7 @@ export async function mergeLoomsFromSync(
remoteLooms,
{
source = { via: 'sync', peerId: null },
- senderSchemaVersions = { fableLoom: 2 },
+ senderSchemaVersions = { fableLoom: 3 },
} = {},
) {
if (!Array.isArray(remoteLooms)) return { applied: false, count: 0 };
@@ -800,6 +738,15 @@ export async function attachNodeImage(loomId, episodeId, nodeId, { filename, job
node.image = filename;
node.imageJobId = isStr(jobId) ? jobId : null;
node.visualConditioning = visualConditioning;
+ if (visualConditioning && isSafeVideoHistoryId(visualConditioning.assetId)) {
+ node.playbackAssets = {
+ ...(node.playbackAssets || {}),
+ visualConditioningByAsset: {
+ ...(node.playbackAssets?.visualConditioningByAsset || {}),
+ [visualConditioning.assetId]: visualConditioning,
+ },
+ };
+ }
if (node.visualCanon) node.visualCanon.storyboardImageApproved = false;
episode.updatedAt = new Date().toISOString();
return loom;
@@ -836,6 +783,7 @@ export async function attachNodePlaybackAsset(loomId, episodeId, nodeId, {
transitionId = null,
audioOccupancy = null,
provenance = null,
+ visualConditioning = null,
} = {}) {
if (!isValidLoomId(loomId) || !isSafeVideoHistoryId(videoHistoryId)) return null;
const updated = await mutateLoom(loomId, (loom) => {
@@ -855,6 +803,7 @@ export async function attachNodePlaybackAsset(loomId, episodeId, nodeId, {
exitByTransition: { ...(currentAssets.exitByTransition || {}) },
audioOccupancy: { ...(currentAssets.audioOccupancy || {}) },
holdLoopVideoHistoryIds: [...(currentAssets.holdLoopVideoHistoryIds || [])],
+ visualConditioningByAsset: { ...(currentAssets.visualConditioningByAsset || {}) },
};
if (role === 'entry') {
@@ -875,6 +824,10 @@ export async function attachNodePlaybackAsset(loomId, episodeId, nodeId, {
if (provenance) {
nextAssets.provenance = provenance;
}
+ if (visualConditioning) {
+ nextAssets.visualConditioningByAsset[videoHistoryId] = visualConditioning;
+ node.visualConditioning = visualConditioning;
+ }
node.playbackAssets = nextAssets;
episode.updatedAt = new Date().toISOString();
@@ -883,4 +836,3 @@ export async function attachNodePlaybackAsset(loomId, episodeId, nodeId, {
return updated?.episodes.find((e) => e.id === episodeId)?.nodes.find((n) => n.id === nodeId) ?? null;
}
-
diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.js
index b3e587c150..7a9226dd27 100644
--- a/server/services/fableLoom/records.test.js
+++ b/server/services/fableLoom/records.test.js
@@ -602,6 +602,7 @@ describe('attachNodeImage', () => {
const node = updated.episodes[0].nodes[0];
const visualConditioning = {
version: 1, compilerVersion: '1.0.0', status: 'locked',
+ assetId: 'asset-node-still',
capability: { kind: 'image', backend: 'local', referenceRoles: ['character-neutral'], injected: 'x'.repeat(1000) },
bindings: { inferred: false, characterAppearances: [{ characterId: 'char-a' }], injected: 'x'.repeat(1000) },
assets: [{ role: 'character-neutral', bindingId: 'char-a', filename: 'identity.png', path: '/private/identity.png' }],
@@ -612,6 +613,8 @@ describe('attachNodeImage', () => {
});
expect(attached.visualCanon.storyboardImageApproved).toBe(false);
expect(attached.visualConditioning).toMatchObject({ version: 1, status: 'locked' });
+ expect(attached.playbackAssets.visualConditioningByAsset['asset-node-still'])
+ .toMatchObject({ version: 1, status: 'locked' });
expect(JSON.stringify(attached.visualConditioning)).not.toContain('/private/');
expect(attached.visualConditioning.capability.injected).toBeUndefined();
expect(attached.visualConditioning.bindings.injected).toBeUndefined();
@@ -669,14 +672,38 @@ describe('attachNodePlaybackAsset and node playback fields', () => {
let attached = await attachNodePlaybackAsset(loom.id, episodeId, node.id, {
role: 'entry',
videoHistoryId: 'video-entry-1',
+ visualConditioning: {
+ version: 1,
+ compilerVersion: 'visual-v1',
+ status: 'locked',
+ capability: { kind: 'video', backend: 'local', modelId: 'video-model', modelRevision: 'revision-1' },
+ bindings: { inferred: false, characterAppearances: [] },
+ assets: [],
+ adapters: [],
+ omitted: [],
+ warnings: [],
+ },
});
expect(attached.playbackAssets.entryVideoHistoryId).toBe('video-entry-1');
expect(attached.videoHistoryId).toBe('video-entry-1'); // back-compat
+ expect(attached.playbackAssets.visualConditioningByAsset['video-entry-1'])
+ .toMatchObject({ capability: { modelRevision: 'revision-1' } });
// Attach hold loop with occupancy manifest
attached = await attachNodePlaybackAsset(loom.id, episodeId, node.id, {
role: 'hold',
videoHistoryId: 'video-hold-1',
+ visualConditioning: {
+ version: 1,
+ compilerVersion: 'visual-v1',
+ status: 'locked',
+ capability: { kind: 'video', backend: 'local', modelId: 'video-model', modelRevision: 'revision-2' },
+ bindings: { inferred: false, characterAppearances: [] },
+ assets: [],
+ adapters: [],
+ omitted: [],
+ warnings: [],
+ },
audioOccupancy: {
durationMs: 5000,
music: [{ startMs: 0, endMs: 5000 }],
@@ -705,6 +732,10 @@ describe('attachNodePlaybackAsset and node playback fields', () => {
entryVideoHistoryId: 'video-entry-1',
holdLoopVideoHistoryIds: ['video-hold-1'],
exitByTransition: { 'tr-escape': 'video-exit-1' },
+ visualConditioningByAsset: {
+ 'video-entry-1': { capability: { modelRevision: 'revision-1' } },
+ 'video-hold-1': { capability: { modelRevision: 'revision-2' } },
+ },
});
});
@@ -733,4 +764,3 @@ describe('attachNodePlaybackAsset and node playback fields', () => {
expect(targetNode.playbackAssets.holdLoopVideoHistoryIds).toEqual(['vid-h1', 'vid-h2']);
});
});
-
diff --git a/server/services/fableLoom/visualConditioning.js b/server/services/fableLoom/visualConditioning.js
index 60ee01489b..0f2bf617c0 100644
--- a/server/services/fableLoom/visualConditioning.js
+++ b/server/services/fableLoom/visualConditioning.js
@@ -321,6 +321,9 @@ export async function compileFableLoomVisualRequest({
omitted,
warnings,
temporalSourceNodeId: temporal.node?.id || null,
+ compiledPrompt: positive,
+ compiledNegativePrompt: negativePrompt,
+ referenceImageStrengths: allocation.accepted.map((asset) => asset.role === 'temporal-predecessor' ? 0.4 : 1),
compiledAt: now(),
};
if (locked && failures.length) throw blockedError(unique(failures), { ...manifest, status: 'degraded', warnings: unique([...warnings, ...failures]) });
@@ -341,6 +344,7 @@ export function fableLoomImageCapabilities({ mode, model = null, inputBudget = 4
const cloudEdit = ['codex', 'grok', 'agy'].includes(mode);
return Object.freeze({
version: 1, kind: 'image', backend: mode, modelId: model?.id || null,
+ modelRevision: model?.revision || null,
referenceRoles: localFlux2 || cloudEdit
? ['temporal-predecessor', 'character-neutral', 'character-profile', 'character-full-body', 'character-expression-gesture', 'character-wardrobe', 'character-prop-scale', 'character-negative-identity', 'character-draft-reference', 'environment', 'object']
: [],
@@ -356,6 +360,7 @@ export function fableLoomVideoCapabilities({ backend, model = null }) {
const supportedModes = Array.isArray(model?.supportedModes) ? model.supportedModes : [];
return Object.freeze({
version: 1, kind: 'video', backend, modelId: model?.id || null,
+ modelRevision: model?.revision || null,
referenceRoles: supportedModes.includes('image') ? ['storyboard-first-frame'] : [],
referenceBudget: supportedModes.includes('image') ? 1 : 0,
supportsLora: false,
diff --git a/server/services/fableLoomSceneVideoHook.js b/server/services/fableLoomSceneVideoHook.js
index e388bb14cd..b33af576ca 100644
--- a/server/services/fableLoomSceneVideoHook.js
+++ b/server/services/fableLoomSceneVideoHook.js
@@ -7,7 +7,7 @@
*/
import { createMediaJobImageHook } from './mediaJobImageHook.js';
-import { attachNodeVideo } from './fableLoom/records.js';
+import { attachNodePlaybackAsset, attachNodeVideo } from './fableLoom/records.js';
const hook = createMediaJobImageHook({
label: 'fableloom scene-video',
@@ -20,16 +20,32 @@ const hook = createMediaJobImageHook({
return videoHistoryId ? { videoHistoryId } : null;
},
identify: (tag) => (tag?.loomId && tag.episodeId && tag.nodeId
- ? { loomId: tag.loomId, episodeId: tag.episodeId, nodeId: tag.nodeId }
+ ? {
+ loomId: tag.loomId,
+ episodeId: tag.episodeId,
+ nodeId: tag.nodeId,
+ role: tag.role || null,
+ transitionId: tag.transitionId || null,
+ }
: null),
serializeKey: ({ loomId }) => loomId,
sceneKey: ({ loomId, episodeId, nodeId }) => `${loomId}:${episodeId}:${nodeId}`,
describe: ({ loomId, nodeId }) => `${loomId.slice(0, 13)}/${nodeId.slice(0, 13)}`,
- attach: ({ loomId, episodeId, nodeId, videoHistoryId, job }) =>
- attachNodeVideo(loomId, episodeId, nodeId, {
+ attach: ({ loomId, episodeId, nodeId, role, transitionId, videoHistoryId, job }) => {
+ const visualConditioning = job.params?.visualConditioning || null;
+ if (!role) {
+ return attachNodeVideo(loomId, episodeId, nodeId, {
+ videoHistoryId,
+ ...(visualConditioning ? { visualConditioning } : {}),
+ });
+ }
+ return attachNodePlaybackAsset(loomId, episodeId, nodeId, {
+ role,
videoHistoryId,
- ...(job.params?.visualConditioning ? { visualConditioning: job.params.visualConditioning } : {}),
- }),
+ transitionId,
+ ...(visualConditioning ? { visualConditioning } : {}),
+ });
+ },
onAttached: ({ loomId, nodeId, videoHistoryId }, result) => {
if (!result) return;
console.log(`🎬 fableloom scene video ${loomId.slice(0, 13)}/${nodeId.slice(0, 13)} ← ${videoHistoryId}`);
diff --git a/server/services/fableLoomSceneVideoHook.test.js b/server/services/fableLoomSceneVideoHook.test.js
index 2ae6f3398e..6179e3302f 100644
--- a/server/services/fableLoomSceneVideoHook.test.js
+++ b/server/services/fableLoomSceneVideoHook.test.js
@@ -3,7 +3,10 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
const attachNodeVideo = vi.fn(async (loomId, episodeId, nodeId, { videoHistoryId }) => ({
id: nodeId, videoHistoryId,
}));
-vi.mock('./fableLoom/records.js', () => ({ attachNodeVideo }));
+const attachNodePlaybackAsset = vi.fn(async (loomId, episodeId, nodeId, fields) => ({
+ id: nodeId, ...fields,
+}));
+vi.mock('./fableLoom/records.js', () => ({ attachNodePlaybackAsset, attachNodeVideo }));
const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
const hook = await import('./fableLoomSceneVideoHook.js');
@@ -29,6 +32,7 @@ describe('fableLoomSceneVideoHook', () => {
hook.__testing.reset();
hook.initFableLoomSceneVideoHook();
attachNodeVideo.mockClear();
+ attachNodePlaybackAsset.mockClear();
});
afterEach(() => hook.__testing.reset());
@@ -47,6 +51,23 @@ describe('fableLoomSceneVideoHook', () => {
expect(attachNodeVideo.mock.calls[0][3]).toEqual({ videoHistoryId: 'video-2' });
});
+ it('files typed playback assets with their transition identity and conditioning', async () => {
+ mediaJobEvents.emit('completed', completedVideoJob({
+ id: 'video-exit',
+ params: {
+ fableLoom: tag({ role: 'exit', transitionId: 'tr-1' }),
+ visualConditioning: { version: 1, status: 'locked' },
+ },
+ }));
+ await waitFor(() => attachNodePlaybackAsset.mock.calls.length > 0);
+ expect(attachNodePlaybackAsset).toHaveBeenCalledWith('loom-1', 'ep-1', 'node-1', {
+ role: 'exit',
+ videoHistoryId: 'video-exit',
+ transitionId: 'tr-1',
+ visualConditioning: { version: 1, status: 'locked' },
+ });
+ });
+
it('ignores image jobs and videos without a complete destination tag', async () => {
mediaJobEvents.emit('completed', { kind: 'image', id: 'image-1', params: { fableLoom: tag() }, result: { filename: 'image-1.png' } });
mediaJobEvents.emit('completed', completedVideoJob({ params: { fableLoom: { loomId: 'loom-1' } } }));