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

add FableLoom: branching narratives with intent-driven play, graph editor, and scene renders

[._.]/ Adam Eivy0beb6490d099
diff --git a/client/src/App.jsx b/client/src/App.jsx
index b79a68a92b..f5f143f52f 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -113,6 +113,8 @@ const WritersRoomGuide = lazyWithReload(() => import('./pages/WritersRoomGuide')
const Pipeline = lazyWithReload(() => import('./pages/Pipeline'));
const Sharing = lazyWithReload(() => import('./pages/Sharing'));
const Importer = lazyWithReload(() => import('./pages/Importer'));
+const FableLoom = lazyWithReload(() => import('./pages/FableLoom'));
+const FableLoomStory = lazyWithReload(() => import('./pages/FableLoomStory'));
const StartStory = lazyWithReload(() => import('./pages/StartStory'));
const StoryBuilder = lazyWithReload(() => import('./pages/StoryBuilder'));
const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));
@@ -502,6 +504,10 @@ export default function App() {
<Route path="sharing/:section" element={<Sharing />} />
<Route path="sharing/:section/:bucketId" element={<Sharing />} />
<Route path="importer" element={<Importer />} />
+ <Route path="fableloom" element={<FableLoom />} />
+ <Route path="fableloom/:loomId" element={<FableLoomStory />} />
+ <Route path="fableloom/:loomId/:episodeId" element={<FableLoomStory />} />
+ <Route path="fableloom/:loomId/:episodeId/:nodeId" element={<FableLoomStory />} />
<Route path="start-story" element={<StartStory />} />
<Route path="story-builder" element={<StoryBuilder />} />
<Route path="story-builder/:storyId" element={<Navigate to="idea" replace />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index f4e65dc4c6..556dcd8083 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -103,6 +103,7 @@ import {
Box,
Boxes,
Gamepad2,
+ Waypoints,
AtSign
} from 'lucide-react';
// `__APP_VERSION__` is a Vite build-time define (see vite.config.js). Biome does
@@ -241,6 +242,7 @@ const navItems = [
{ to: '/creative-commission', label: 'Creative Commissions', icon: CalendarClock },
{ to: '/creative-director', label: 'Creative Director', icon: Clapperboard },
{ to: '/pipeline/editorial-checks', label: 'Editorial Checks', icon: ListChecks },
+ { to: '/fableloom', label: 'FableLoom', icon: Waypoints },
{ to: '/game', label: 'Game', icon: Gamepad2 },
{ to: '/importer', label: 'Importer', icon: FileInput },
{ to: '/media', label: 'Media Gen', icon: Layers },
@@ -572,6 +574,10 @@ const FULL_WIDTH_PATH_PREFIXES = [
// stepper that owns its own scroll; the bare /story-builder index
// (list + create form) takes the normal padded+scrolling main.
'/story-builder/',
+ // FableLoom EDITOR (/fableloom/:loomId/...) is a full-width canvas that
+ // owns its own scroll; the bare /fableloom index takes the normal
+ // padded+scrolling main.
+ '/fableloom/',
// The AI Providers editor is a drawer over the same page (/ai/new,
// /ai/:providerId), so its sub-routes need the bare full-width main the
// bare /ai index gets from EXACT_FULL_WIDTH_PATHS above — without it the
diff --git a/client/src/components/fableloom/LoomCanvas.jsx b/client/src/components/fableloom/LoomCanvas.jsx
new file mode 100644
index 0000000000..aea7229174
--- /dev/null
+++ b/client/src/components/fableloom/LoomCanvas.jsx
@@ -0,0 +1,177 @@
+/**
+ * FableLoom canvas — the visual editor for one episode's scene graph.
+ *
+ * Renders scene nodes as SVG cards (BFS-layered by `layoutLoomGraph`,
+ * author-dragged positions win) with intent-labeled transition edges. Click
+ * selects a scene (selection lives in the URL — the parent navigates); drag
+ * repositions it and persists `pos` on release. The wrapper owns scrolling in
+ * both axes so a wide graph pans instead of clipping.
+ */
+
+import { useMemo, useRef, useState } from 'react';
+import { Play, Flag } from 'lucide-react';
+import { layoutLoomGraph, loomEdgePath, LOOM_NODE_W, LOOM_NODE_H } from '../../lib/loomLayout';
+
+const DRAG_THRESHOLD_PX = 4;
+
+const truncate = (text, max) => {
+ const s = typeof text === 'string' ? text : '';
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
+};
+
+export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMoveNode }) {
+ // Live drag override: nodeId → { x, y } while a pointer drag is in flight,
+ // so the node follows the cursor without a server round-trip per move.
+ const [dragPos, setDragPos] = useState(null);
+ const dragRef = useRef(null);
+
+ const layout = useMemo(() => layoutLoomGraph(episode), [episode]);
+ const positions = useMemo(() => {
+ if (!dragPos) return layout.positions;
+ return { ...layout.positions, [dragPos.id]: { x: dragPos.x, y: dragPos.y } };
+ }, [layout.positions, dragPos]);
+
+ const nodes = episode?.nodes || [];
+ const nodeById = useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes]);
+
+ const handlePointerDown = (event, node) => {
+ if (event.button !== 0) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ const start = positions[node.id] || { x: 0, y: 0 };
+ dragRef.current = {
+ id: node.id,
+ startX: event.clientX,
+ startY: event.clientY,
+ originX: start.x,
+ originY: start.y,
+ moved: false,
+ };
+ };
+
+ const handlePointerMove = (event) => {
+ const drag = dragRef.current;
+ if (!drag) return;
+ const dx = event.clientX - drag.startX;
+ const dy = event.clientY - drag.startY;
+ if (!drag.moved && Math.abs(dx) < DRAG_THRESHOLD_PX && Math.abs(dy) < DRAG_THRESHOLD_PX) return;
+ drag.moved = true;
+ setDragPos({
+ id: drag.id,
+ x: Math.max(0, drag.originX + dx),
+ y: Math.max(0, drag.originY + dy),
+ });
+ };
+
+ const handlePointerUp = () => {
+ const drag = dragRef.current;
+ dragRef.current = null;
+ if (!drag) return;
+ if (drag.moved && dragPos && dragPos.id === drag.id) {
+ onMoveNode?.(drag.id, { x: Math.round(dragPos.x), y: Math.round(dragPos.y) });
+ } else {
+ onSelectNode?.(drag.id);
+ }
+ setDragPos(null);
+ };
+
+ if (!nodes.length) return null;
+
+ const width = Math.max(layout.width, dragPos ? dragPos.x + LOOM_NODE_W + 24 : 0);
+ const height = Math.max(layout.height, dragPos ? dragPos.y + LOOM_NODE_H + 24 : 0);
+
+ return (
+ <div className="overflow-auto h-full w-full" data-testid="loom-canvas">
+ <svg width={width} height={height} className="block select-none touch-none">
+ <g>
+ {nodes.flatMap((node) => (node.transitions || []).map((tr) => {
+ const from = positions[node.id];
+ const to = positions[tr.targetNodeId];
+ if (!from || !to || !nodeById.has(tr.targetNodeId)) return null;
+ const { d, labelX, labelY } = loomEdgePath(from, to);
+ const active = node.id === selectedNodeId;
+ return (
+ <g key={tr.id} className={active ? 'opacity-100' : 'opacity-70'}>
+ <path d={d} fill="none" strokeWidth={active ? 2 : 1.5}
+ className={active ? 'stroke-port-accent' : 'stroke-port-border'} />
+ {tr.intent && (
+ <text x={labelX} y={labelY - 6} textAnchor="middle"
+ className="fill-port-text-muted text-[10px] pointer-events-none">
+ {truncate(tr.intent, 28)}
+ </text>
+ )}
+ </g>
+ );
+ }))}
+ </g>
+ <g>
+ {nodes.map((node) => {
+ const pos = positions[node.id];
+ if (!pos) return null;
+ const selected = node.id === selectedNodeId;
+ const isStart = node.id === episode.startNodeId;
+ return (
+ <g
+ key={node.id}
+ transform={`translate(${pos.x}, ${pos.y})`}
+ className="cursor-pointer"
+ role="button"
+ tabIndex={0}
+ aria-label={`Scene: ${node.title || 'Untitled'}`}
+ onPointerDown={(e) => handlePointerDown(e, node)}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onSelectNode?.(node.id);
+ }
+ }}
+ >
+ <rect
+ width={LOOM_NODE_W}
+ height={LOOM_NODE_H}
+ rx={10}
+ strokeWidth={selected ? 2 : 1}
+ className={`${node.isEnding ? 'fill-port-success/10' : 'fill-port-card'} ${
+ selected ? 'stroke-port-accent' : 'stroke-port-border'
+ }`}
+ />
+ {node.image && (
+ <image
+ href={`/data/images/${node.image}`}
+ x={8} y={26} width={54} height={LOOM_NODE_H - 34}
+ preserveAspectRatio="xMidYMid slice"
+ />
+ )}
+ <text x={10} y={17} className="fill-port-text text-[11px] font-semibold pointer-events-none">
+ {truncate(node.title || 'Untitled scene', 26)}
+ </text>
+ <foreignObject x={node.image ? 68 : 10} y={24} width={LOOM_NODE_W - (node.image ? 78 : 20)} height={LOOM_NODE_H - 48}>
+ <div className="text-[10px] leading-snug text-port-text-muted overflow-hidden h-full pointer-events-none">
+ {truncate(node.prose, 110)}
+ </div>
+ </foreignObject>
+ <g transform={`translate(10, ${LOOM_NODE_H - 16})`} className="pointer-events-none">
+ {isStart && (
+ <g>
+ <Play size={10} className="text-port-accent" x={0} y={-8} />
+ <text x={14} y={1} className="fill-port-accent text-[9px] font-medium">Opening</text>
+ </g>
+ )}
+ {node.isEnding && (
+ <g transform={isStart ? 'translate(64, 0)' : ''}>
+ <Flag size={10} className="text-port-success" x={0} y={-8} />
+ <text x={14} y={1} className="fill-port-success text-[9px] font-medium">
+ {truncate(node.endingLabel || 'Ending', 20)}
+ </text>
+ </g>
+ )}
+ </g>
+ </g>
+ );
+ })}
+ </g>
+ </svg>
+ </div>
+ );
+}
diff --git a/client/src/components/fableloom/LoomCanvas.test.jsx b/client/src/components/fableloom/LoomCanvas.test.jsx
new file mode 100644
index 0000000000..45ca40199e
--- /dev/null
+++ b/client/src/components/fableloom/LoomCanvas.test.jsx
@@ -0,0 +1,49 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import LoomCanvas from './LoomCanvas';
+
+const episode = () => ({
+ id: 'ep-1',
+ startNodeId: 'n1',
+ nodes: [
+ {
+ id: 'n1',
+ title: 'The Gate',
+ prose: 'You stand before it.',
+ transitions: [{ id: 't1', targetNodeId: 'n2', intent: 'enter the gate' }],
+ },
+ {
+ id: 'n2',
+ title: 'Inside',
+ prose: 'Torchlight.',
+ isEnding: true,
+ endingLabel: 'Within',
+ transitions: [],
+ },
+ ],
+});
+
+describe('LoomCanvas', () => {
+ it('renders scene cards with start/ending markers and edge intent labels', () => {
+ render(<LoomCanvas episode={episode()} selectedNodeId={null} onSelectNode={() => {}} />);
+ expect(screen.getByLabelText('Scene: The Gate')).toBeInTheDocument();
+ expect(screen.getByLabelText('Scene: Inside')).toBeInTheDocument();
+ expect(screen.getByText('Opening')).toBeInTheDocument();
+ expect(screen.getByText('Within')).toBeInTheDocument();
+ expect(screen.getByText('enter the gate')).toBeInTheDocument();
+ });
+
+ it('selects a node on keyboard activation', () => {
+ const onSelectNode = vi.fn();
+ render(<LoomCanvas episode={episode()} selectedNodeId={null} onSelectNode={onSelectNode} />);
+ fireEvent.keyDown(screen.getByLabelText('Scene: Inside'), { key: 'Enter' });
+ expect(onSelectNode).toHaveBeenCalledWith('n2');
+ });
+
+ it('renders nothing for an empty episode', () => {
+ const { container } = render(
+ <LoomCanvas episode={{ id: 'ep-1', nodes: [] }} selectedNodeId={null} onSelectNode={() => {}} />,
+ );
+ expect(container.firstChild).toBeNull();
+ });
+});
diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsx
new file mode 100644
index 0000000000..c8dc23bb5a
--- /dev/null
+++ b/client/src/components/fableloom/LoomNodeEditor.jsx
@@ -0,0 +1,335 @@
+/**
+ * FableLoom scene editor — the side panel for the selected node: title/prose,
+ * ending flag + label, the intent-transition list, the scene image (prompt +
+ * queued render via the shared image-gen lane), and the AI branch action.
+ *
+ * Fields save on blur (silent PATCH; the server returns the full loom, which
+ * the parent folds into state). Transitions edit locally and save per-row on
+ * blur through the same node PATCH.
+ */
+
+import { useEffect, useMemo, useState } from 'react';
+import { GitBranch, ImagePlus, Loader2, Trash2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import ConfirmButtonPair from '../ui/ConfirmButtonPair';
+import MediaImage from '../MediaImage';
+import { useConfirmDelete } from '../../hooks/useConfirmDelete';
+import {
+ branchLoomNode, deleteLoomNode, generateImage, updateLoomNode,
+} from '../../services/api';
+
+const field = 'w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
+const label = 'block text-xs font-medium text-port-text-muted mb-1';
+
+export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onClearSelection, onMakeStart }) {
+ const [form, setForm] = useState(null);
+ const [busy, setBusy] = useState('');
+ const del = useConfirmDelete();
+
+ // Sync from the record on scene switch ONLY (the parent keys this component
+ // by node.id, so this is effectively the mount). Re-syncing on every server
+ // echo would clobber typing in a sibling field while a blur-save round-trips.
+ // Server-side additions that arrive mid-edit (AI branch, image attach) are
+ // folded in explicitly where they happen.
+ useEffect(() => {
+ setForm({
+ title: node.title || '',
+ prose: node.prose || '',
+ imagePrompt: node.imagePrompt || '',
+ isEnding: !!node.isEnding,
+ endingLabel: node.endingLabel || '',
+ transitions: (node.transitions || []).map((t) => ({ ...t, triggersText: (t.triggers || []).join('; ') })),
+ });
+ }, [node.id]);
+
+ const otherNodes = useMemo(
+ () => episode.nodes.filter((n) => n.id !== node.id),
+ [episode.nodes, node.id],
+ );
+
+ if (!form) return null;
+
+ const patchNode = async (patch) => {
+ const updated = await updateLoomNode(loom.id, episode.id, node.id, patch, { silent: true })
+ .catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
+ if (updated) onLoomUpdate(updated);
+ return updated;
+ };
+
+ const syncTransitionsFrom = (updatedLoom) => {
+ const saved = updatedLoom?.episodes.find((e) => e.id === episode.id)
+ ?.nodes.find((n) => n.id === node.id)?.transitions;
+ if (!saved) return;
+ setForm((prev) => ({
+ ...prev,
+ transitions: saved.map((t) => ({ ...t, triggersText: (t.triggers || []).join('; ') })),
+ }));
+ };
+
+ const saveTransitions = async (transitions) => {
+ const updated = await patchNode({
+ transitions: transitions
+ .filter((t) => t.targetNodeId)
+ .map(({ id, targetNodeId, intent, triggersText, description }) => ({
+ id, targetNodeId, intent,
+ triggers: (triggersText || '').split(';').map((s) => s.trim()).filter(Boolean),
+ description: description || '',
+ })),
+ });
+ // Re-sync just the transition rows so server-minted ids replace the
+ // locally-added rows' missing ones (id churn otherwise re-mints per save).
+ syncTransitionsFrom(updated);
+ };
+
+ const setTransition = (index, patch) => {
+ setForm((prev) => {
+ const transitions = prev.transitions.map((t, i) => (i === index ? { ...t, ...patch } : t));
+ return { ...prev, transitions };
+ });
+ };
+
+ const removeTransition = (index) => {
+ const transitions = form.transitions.filter((_, i) => i !== index);
+ setForm((prev) => ({ ...prev, transitions }));
+ saveTransitions(transitions);
+ };
+
+ const addTransition = () => {
+ const target = otherNodes[0];
+ if (!target) {
+ toast.error('Add another scene first — a path needs somewhere to go');
+ return;
+ }
+ setForm((prev) => ({
+ ...prev,
+ transitions: [...prev.transitions, { targetNodeId: target.id, intent: '', triggersText: '', description: '' }],
+ }));
+ };
+
+ const handleBranch = async () => {
+ setBusy('branch');
+ const result = await branchLoomNode(loom.id, episode.id, node.id, { branchCount: 2 })
+ .catch(() => null);
+ setBusy('');
+ if (result?.loom) {
+ onLoomUpdate(result.loom);
+ syncTransitionsFrom(result.loom);
+ toast.success('New branches woven');
+ }
+ };
+
+ const handleGenerateImage = async () => {
+ const prompt = form.imagePrompt.trim();
+ if (!prompt) {
+ toast.error('Write an image prompt first');
+ return;
+ }
+ setBusy('image');
+ // Persist the prompt, then queue the render with the fableLoom destination
+ // tag — the server-side completion hook files the finished image onto this
+ // node even if the page unmounts mid-render.
+ await patchNode({ imagePrompt: prompt });
+ const queued = await generateImage({
+ prompt: loom.styleNotes ? `${prompt}\n\nStyle: ${loom.styleNotes}` : prompt,
+ fableLoom: { loomId: loom.id, episodeId: episode.id, nodeId: node.id },
+ }).catch(() => null);
+ setBusy('');
+ if (queued) toast.success('Scene render queued — it will attach when it completes');
+ };
+
+ const handleDelete = async () => {
+ const updated = await deleteLoomNode(loom.id, episode.id, node.id).catch(() => null);
+ if (updated) {
+ onLoomUpdate(updated);
+ onClearSelection();
+ }
+ };
+
+ return (
+ <div className="space-y-4 p-4">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <h3 className="text-sm font-semibold">Scene</h3>
+ {onMakeStart && (
+ <button
+ type="button"
+ onClick={onMakeStart}
+ className="text-xs text-port-accent hover:underline"
+ >
+ Set as opening
+ </button>
+ )}
+ </div>
+ {del.isConfirming(node.id) ? (
+ <ConfirmButtonPair prompt="Delete scene?" onConfirm={handleDelete} onCancel={del.cancelDelete} />
+ ) : (
+ <button
+ type="button"
+ onClick={() => del.requestDelete(node.id)}
+ className="text-port-text-muted hover:text-port-error"
+ aria-label="Delete scene"
+ >
+ <Trash2 size={16} />
+ </button>
+ )}
+ </div>
+
+ <div>
+ <label className={label} htmlFor="loom-node-title">Title</label>
+ <input
+ id="loom-node-title"
+ className={field}
+ value={form.title}
+ onChange={(e) => setForm((p) => ({ ...p, title: e.target.value }))}
+ onBlur={() => patchNode({ title: form.title })}
+ />
+ </div>
+
+ <div>
+ <label className={label} htmlFor="loom-node-prose">Scene prose</label>
+ <textarea
+ id="loom-node-prose"
+ rows={7}
+ className={field}
+ value={form.prose}
+ onChange={(e) => setForm((p) => ({ ...p, prose: e.target.value }))}
+ onBlur={() => patchNode({ prose: form.prose })}
+ />
+ </div>
+
+ <div className="flex items-center gap-3">
+ <label className="flex items-center gap-2 text-sm" htmlFor="loom-node-ending">
+ <input
+ id="loom-node-ending"
+ type="checkbox"
+ checked={form.isEnding}
+ onChange={(e) => {
+ setForm((p) => ({ ...p, isEnding: e.target.checked }));
+ patchNode({ isEnding: e.target.checked });
+ }}
+ />
+ This scene is an ending
+ </label>
+ </div>
+ {form.isEnding && (
+ <div>
+ <label className={label} htmlFor="loom-node-ending-label">Ending name</label>
+ <input
+ id="loom-node-ending-label"
+ className={field}
+ placeholder="e.g. Treasure found"
+ value={form.endingLabel}
+ onChange={(e) => setForm((p) => ({ ...p, endingLabel: e.target.value }))}
+ onBlur={() => patchNode({ endingLabel: form.endingLabel })}
+ />
+ </div>
+ )}
+
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-xs font-medium text-port-text-muted">Scene image</span>
+ <button
+ type="button"
+ onClick={handleGenerateImage}
+ disabled={busy === 'image'}
+ className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50"
+ >
+ {busy === 'image' ? <Loader2 size={12} className="animate-spin" /> : <ImagePlus size={12} />}
+ Generate
+ </button>
+ </div>
+ <textarea
+ rows={2}
+ className={field}
+ placeholder="Visual description for the image generator"
+ aria-label="Image prompt"
+ value={form.imagePrompt}
+ onChange={(e) => setForm((p) => ({ ...p, imagePrompt: e.target.value }))}
+ onBlur={() => patchNode({ imagePrompt: form.imagePrompt })}
+ />
+ {node.image && (
+ <MediaImage
+ src={`/data/images/${node.image}`}
+ alt={form.title || 'Scene render'}
+ className="mt-2 rounded max-w-full max-h-48 object-cover"
+ />
+ )}
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-xs font-medium text-port-text-muted">
+ Paths out ({form.transitions.length})
+ </span>
+ <div className="flex items-center gap-3">
+ <button
+ type="button"
+ onClick={handleBranch}
+ disabled={busy === 'branch'}
+ className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50"
+ >
+ {busy === 'branch' ? <Loader2 size={12} className="animate-spin" /> : <GitBranch size={12} />}
+ Branch with AI
+ </button>
+ <button type="button" onClick={addTransition} className="text-xs text-port-accent hover:underline">
+ + Add path
+ </button>
+ </div>
+ </div>
+ {form.isEnding && form.transitions.length > 0 && (
+ <p className="text-xs text-port-warning mb-2">Endings never fire their outgoing paths.</p>
+ )}
+ <div className="space-y-3">
+ {form.transitions.map((tr, index) => (
+ <div key={tr.id || `new-${index}`} className="border border-port-border rounded p-2 space-y-2">
+ <div className="flex items-center gap-2">
+ <input
+ className={field}
+ placeholder='Reader intent, e.g. "search the wreck"'
+ aria-label="Intent"
+ value={tr.intent}
+ onChange={(e) => setTransition(index, { intent: e.target.value })}
+ onBlur={() => saveTransitions(form.transitions)}
+ />
+ <button
+ type="button"
+ onClick={() => removeTransition(index)}
+ className="text-port-text-muted hover:text-port-error shrink-0"
+ aria-label="Remove path"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ <select
+ className={field}
+ aria-label="Leads to scene"
+ value={tr.targetNodeId}
+ onChange={(e) => {
+ setTransition(index, { targetNodeId: e.target.value });
+ saveTransitions(form.transitions.map((t, i) => (i === index ? { ...t, targetNodeId: e.target.value } : t)));
+ }}
+ >
+ {otherNodes.map((n) => (
+ <option key={n.id} value={n.id}>{n.title || 'Untitled scene'}</option>
+ ))}
+ </select>
+ <input
+ className={field}
+ placeholder="Example phrasings, separated by ;"
+ aria-label="Trigger phrasings"
+ value={tr.triggersText}
+ onChange={(e) => setTransition(index, { triggersText: e.target.value })}
+ onBlur={() => saveTransitions(form.transitions)}
+ />
+ </div>
+ ))}
+ {!form.transitions.length && !form.isEnding && (
+ <p className="text-xs text-port-warning">
+ No paths out — mark this an ending or add a path.
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/fableloom/LoomPlayPanel.jsx b/client/src/components/fableloom/LoomPlayPanel.jsx
new file mode 100644
index 0000000000..4ae0a82cc5
--- /dev/null
+++ b/client/src/components/fableloom/LoomPlayPanel.jsx
@@ -0,0 +1,177 @@
+/**
+ * FableLoom play panel — the reader-side chat for one episode.
+ *
+ * The reader types what they want to do; the play stage matches it against
+ * the current scene's intent paths and either moves them (new scene prose +
+ * image) or answers in-world without leaving the scene. The session lives in
+ * this panel's state (current scene + transcript) — restarting is free, and
+ * nothing persists server-side.
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Loader2, RotateCcw, Send, Flag } from 'lucide-react';
+import MediaImage from '../MediaImage';
+import { playLoomTurn } from '../../services/api';
+
+const findNode = (episode, id) => episode?.nodes.find((n) => n.id === id) || null;
+
+// Reader-facing projection of an authored node (mirrors the server's
+// publicNode shape, for local moves that never hit the API).
+const asPublic = (node) => (node ? {
+ id: node.id,
+ title: node.title,
+ prose: node.prose,
+ image: node.image,
+ isEnding: !!node.isEnding,
+ endingLabel: node.endingLabel,
+ choices: (node.transitions || []).map((t) => ({ id: t.id, intent: t.intent })),
+} : null);
+
+export default function LoomPlayPanel({ loom, episode }) {
+ const start = useMemo(() => asPublic(findNode(episode, episode?.startNodeId)), [episode]);
+ const [scene, setScene] = useState(start);
+ const [transcript, setTranscript] = useState([]);
+ const [message, setMessage] = useState('');
+ const [sending, setSending] = useState(false);
+ const [ended, setEnded] = useState(!!start?.isEnding);
+ const scrollRef = useRef(null);
+
+ const restart = () => {
+ setScene(start);
+ setTranscript([]);
+ setEnded(!!start?.isEnding);
+ setMessage('');
+ };
+
+ // Scene changes (including an episode switch) re-anchor the session.
+ useEffect(() => { restart(); }, [start]);
+
+ useEffect(() => {
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
+ }, [transcript, scene]);
+
+ const send = async () => {
+ const text = message.trim();
+ if (!text || sending || !scene) return;
+ setMessage('');
+ setSending(true);
+ const history = [...transcript, { role: 'reader', text }];
+ setTranscript(history);
+ const result = await playLoomTurn(loom.id, episode.id, {
+ nodeId: scene.id,
+ message: text,
+ transcript: history.slice(-12).map(({ role, text: t }) => ({ role, text: t })),
+ }).catch(() => null);
+ setSending(false);
+ if (!result) return;
+ const additions = [];
+ if (result.narration) additions.push({ role: 'narrator', text: result.narration });
+ if (result.action === 'move' && result.node) {
+ setScene(result.node);
+ additions.push({ role: 'scene', node: result.node });
+ setEnded(!!result.ended);
+ }
+ if (additions.length) setTranscript((prev) => [...prev, ...additions]);
+ };
+
+ if (!start) {
+ return (
+ <p className="p-4 text-sm text-port-text-muted">
+ This episode has no opening scene yet — weave or add scenes first.
+ </p>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full">
+ <div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-4">
+ <SceneCard node={start} isOpening />
+ {transcript.map((turn, i) => {
+ if (turn.role === 'scene') return <SceneCard key={i} node={turn.node} />;
+ return (
+ <div key={i} className={turn.role === 'reader' ? 'text-right' : ''}>
+ <div
+ className={`inline-block max-w-[85%] rounded-lg px-3 py-2 text-sm whitespace-pre-wrap text-left ${
+ turn.role === 'reader'
+ ? 'bg-port-accent/15 text-port-text'
+ : 'bg-port-card border border-port-border text-port-text'
+ }`}
+ >
+ {turn.text}
+ </div>
+ </div>
+ );
+ })}
+ {ended && (
+ <div className="flex items-center gap-2 justify-center text-port-success text-sm font-medium py-2">
+ <Flag size={14} />
+ {scene?.endingLabel ? `Ending: ${scene.endingLabel}` : 'The End'}
+ </div>
+ )}
+ </div>
+ <div className="border-t border-port-border p-3 space-y-2">
+ {!ended && scene?.choices?.length > 0 && (
+ <div className="flex flex-wrap gap-1.5">
+ {scene.choices.filter((c) => c.intent).map((c) => (
+ <button
+ key={c.id}
+ type="button"
+ onClick={() => setMessage(c.intent)}
+ className="text-xs px-2 py-1 rounded-full border border-port-border text-port-text-muted hover:border-port-accent hover:text-port-accent"
+ >
+ {c.intent}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="flex gap-2">
+ <input
+ className="flex-1 bg-port-bg border border-port-border rounded px-3 py-2 text-sm"
+ placeholder={ended ? 'The story has ended' : 'What do you do?'}
+ aria-label="Your action"
+ value={message}
+ disabled={ended || sending}
+ onChange={(e) => setMessage(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
+ />
+ {ended ? (
+ <button
+ type="button"
+ onClick={restart}
+ className="flex items-center gap-1.5 px-3 py-2 rounded bg-port-accent/15 text-port-accent text-sm"
+ >
+ <RotateCcw size={14} /> Read again
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={send}
+ disabled={sending || !message.trim()}
+ aria-label="Send"
+ className="px-3 py-2 rounded bg-port-accent text-white disabled:opacity-50"
+ >
+ {sending ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function SceneCard({ node, isOpening = false }) {
+ if (!node) return null;
+ return (
+ <div className="border border-port-border rounded-lg overflow-hidden bg-port-card">
+ {node.image && (
+ <MediaImage src={`/data/images/${node.image}`} alt={node.title || 'Scene'} className="w-full max-h-56 object-cover" />
+ )}
+ <div className="p-3">
+ <div className="text-xs uppercase tracking-wide text-port-text-muted mb-1">
+ {isOpening ? 'Opening' : node.isEnding ? (node.endingLabel || 'Ending') : node.title || 'Scene'}
+ </div>
+ <p className="text-sm whitespace-pre-wrap">{node.prose}</p>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/fableloom/LoomValidationPanel.jsx b/client/src/components/fableloom/LoomValidationPanel.jsx
new file mode 100644
index 0000000000..4dc47ce028
--- /dev/null
+++ b/client/src/components/fableloom/LoomValidationPanel.jsx
@@ -0,0 +1,114 @@
+/**
+ * FableLoom validation panel — the deterministic graph checks plus the
+ * optional AI story review. Structural checks run instantly server-side (no
+ * LLM); "Review with AI" layers the story-editor critique on top. Clicking a
+ * scene-anchored finding selects that node on the canvas.
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+import { AlertTriangle, CircleAlert, Loader2, Sparkles } from 'lucide-react';
+import { reviewLoomEpisode, validateLoomEpisode } from '../../services/api';
+
+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 [structural, setStructural] = useState(null);
+ const [review, setReview] = useState(null);
+ const [reviewing, setReviewing] = useState(false);
+
+ const refresh = useCallback(() => {
+ validateLoomEpisode(loom.id, episode.id, { silent: true })
+ .then(setStructural)
+ .catch(() => setStructural(null));
+ }, [loom.id, episode.id]);
+
+ // Re-validate whenever the graph content changes (updatedAt moves on every
+ // node/transition mutation).
+ useEffect(() => { refresh(); }, [refresh, episode.updatedAt]);
+
+ const runReview = async () => {
+ setReviewing(true);
+ const result = await reviewLoomEpisode(loom.id, episode.id).catch(() => null);
+ setReviewing(false);
+ if (result) {
+ setReview(result.review);
+ setStructural(result.structural);
+ }
+ };
+
+ const findingRow = (item, key, nodeId) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => nodeId && onSelectNode(nodeId)}
+ disabled={!nodeId}
+ className={`w-full text-left flex items-start gap-2 text-xs rounded px-2 py-1.5 border border-port-border ${
+ nodeId ? 'hover:border-port-accent cursor-pointer' : 'cursor-default'
+ }`}
+ >
+ {severityIcon(item.severity)}
+ <span>
+ {item.message || item.problem}
+ {item.suggestion ? <span className="block text-port-text-muted mt-0.5">{item.suggestion}</span> : null}
+ </span>
+ </button>
+ );
+
+ 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.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>
+
+ <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-text-muted">
+ Ask the AI story editor to critique intents, branches, and endings.
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 4ba5094e27..71681030f2 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -120,6 +120,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `kanbanColumns.js` | `bucketTickets` / `ticketInColumn` / `columnConfig` / `FALLBACK_COLUMNS` — pure column logic for the Jira Kanban board (`components/KanbanBoard.jsx`). Buckets tickets into resolved workflow columns (by status name, or statusCategory for the fallback board), assigns each column a stable unique `id` (Jira `name` is not unique — same-named columns map to different statuses), appends an orphan column for any unmatched status, and precomputes per-column Tailwind color config (Blocked→red, Review/QA→purple, else by category). |
| `localLlmTargetKey.js` | `localLlmTargetKey({ backend, modelId })` — stable string key for a local-LLM compare target. Shared by the LocalLlmTab checkbox grid and the LocalLlmPlayground compare URL so a delimiter change can't desync the round-trip. |
| `letteringDensity.js` | `analyzeComicLettering` / `panelLetteringMetrics` / `countWords` / `overflowSeverity` / `DEFAULT_LETTERING_THRESHOLDS` — comic lettering-density accounting over parsed comic pages, powering the comic-script stage's inline over-stuffed-panel warnings (#1313). Byte-for-byte mirror of `server/lib/editorial/letteringDensity.js` (the server `comic.lettering-density` check is authoritative). Pure/DOM-free. |
+| `loomLayout.js` | FableLoom canvas layout — `layoutLoomGraph(episode)` (BFS-layered default positions, persisted `pos` overrides, canvas extents), `loomGraphLayers`, `loomEdgePath(from, to)` (cubic edge + label midpoint), `LOOM_NODE_W`/`LOOM_NODE_H`. Client mirror of `server/lib/fableLoomGraph.js` layering. Pure/DOM-free. |
| `loopbackHost.js` | `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or `getUserMedia`-gated surface; matches the full `127.0.0.0/8` range, IPv6 `::1`, and the browser-bracketed `[::1]` form. |
| `manuscriptAnchors.js` | `locateFind` / `locateAnchors` / `buildHighlightSegments` — resolve editorial-comment `anchorQuote`s to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Mirrors the nearest-occurrence `locateFind` in `server/services/pipeline/manuscriptFix.js`. |
| `manuscriptFormat.js` | `formatManuscript(text, stageId)` / `REFLOW_STAGES` — normalize a manuscript section's text for the editor's "Format" button: undo PDF-paste artifacts (stylized drop-cap split onto its own line, hyphen-split words, trailing whitespace, runaway blank lines) for every stage, and additionally reflow soft-wrapped lines back into paragraphs for `prose` only (scripts keep their structural line breaks). Pure/DOM-free. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index c3e4e302b5..20c957f2cf 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -91,6 +91,7 @@ export * from './healthProvenance.js';
export * from './joinInfluenceList.js';
export * from './kanbanColumns.js';
export * from './localLlmTargetKey.js';
+export * from './loomLayout.js';
export * from './loopbackHost.js';
export * from './manuscriptAnchors.js';
export * from './manuscriptFormat.js';
diff --git a/client/src/lib/loomLayout.js b/client/src/lib/loomLayout.js
new file mode 100644
index 0000000000..099bffb677
--- /dev/null
+++ b/client/src/lib/loomLayout.js
@@ -0,0 +1,94 @@
+/**
+ * FableLoom graph layout — pure helpers that place an episode's scene nodes on
+ * the editor canvas and route its transition edges.
+ *
+ * Default positions come from BFS layering (columns = depth from the opening
+ * scene, rows = order within a layer; unreachable nodes trail in extra
+ * columns). A node the author dragged carries a persisted `pos` override that
+ * always wins. Mirrors the layering rule in `server/lib/fableLoomGraph.js`
+ * `computeGraphLayers` — keep the two BFS orders in step.
+ */
+
+export const LOOM_NODE_W = 200;
+export const LOOM_NODE_H = 112;
+const COL_GAP = 96;
+const ROW_GAP = 40;
+const MARGIN = 24;
+
+const asArray = (v) => (Array.isArray(v) ? v : []);
+
+/** BFS layers from the start node (client mirror of computeGraphLayers). */
+export function loomGraphLayers(episode) {
+ const nodes = asArray(episode?.nodes);
+ const byId = new Map(nodes.map((n) => [n.id, n]));
+ const layers = [];
+ const seen = new Set();
+ if (byId.has(episode?.startNodeId)) {
+ let frontier = [episode.startNodeId];
+ seen.add(episode.startNodeId);
+ while (frontier.length) {
+ layers.push(frontier);
+ const next = [];
+ for (const id of frontier) {
+ for (const tr of asArray(byId.get(id)?.transitions)) {
+ if (byId.has(tr?.targetNodeId) && !seen.has(tr.targetNodeId)) {
+ seen.add(tr.targetNodeId);
+ next.push(tr.targetNodeId);
+ }
+ }
+ }
+ frontier = next;
+ }
+ }
+ // Unreachable nodes trail in chunked extra columns so they stay visible.
+ const orphans = nodes.filter((n) => !seen.has(n.id)).map((n) => n.id);
+ for (let i = 0; i < orphans.length; i += 4) {
+ layers.push(orphans.slice(i, i + 4));
+ }
+ return layers;
+}
+
+/**
+ * Position every node. Returns `{ positions, width, height }` where
+ * `positions` maps nodeId → `{ x, y }` (top-left corners). Persisted
+ * `node.pos` overrides the computed slot; the canvas size covers both.
+ */
+export function layoutLoomGraph(episode) {
+ const nodes = asArray(episode?.nodes);
+ const posById = new Map(nodes.map((n) => [n.id, n.pos]));
+ const layers = loomGraphLayers(episode);
+ const positions = {};
+ layers.forEach((layer, col) => {
+ layer.forEach((id, row) => {
+ const custom = posById.get(id);
+ positions[id] = custom && Number.isFinite(custom.x) && Number.isFinite(custom.y)
+ ? { x: custom.x, y: custom.y }
+ : { x: MARGIN + col * (LOOM_NODE_W + COL_GAP), y: MARGIN + row * (LOOM_NODE_H + ROW_GAP) };
+ });
+ });
+ let width = 0;
+ let height = 0;
+ for (const { x, y } of Object.values(positions)) {
+ width = Math.max(width, x + LOOM_NODE_W + MARGIN);
+ height = Math.max(height, y + LOOM_NODE_H + MARGIN);
+ }
+ return { positions, width: Math.max(width, 400), height: Math.max(height, 240) };
+}
+
+/**
+ * Cubic path from a source node's right edge to a target node's left edge,
+ * with the label midpoint. A self-or-backward edge bows harder so it stays
+ * readable when the target sits left of (or on top of) the source.
+ */
+export function loomEdgePath(from, to) {
+ const x1 = from.x + LOOM_NODE_W;
+ const y1 = from.y + LOOM_NODE_H / 2;
+ const x2 = to.x;
+ const y2 = to.y + LOOM_NODE_H / 2;
+ const dx = Math.max(48, Math.abs(x2 - x1) / 2);
+ return {
+ d: `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2} ${y2}`,
+ labelX: (x1 + x2) / 2,
+ labelY: (y1 + y2) / 2,
+ };
+}
diff --git a/client/src/lib/loomLayout.test.js b/client/src/lib/loomLayout.test.js
new file mode 100644
index 0000000000..907b756a40
--- /dev/null
+++ b/client/src/lib/loomLayout.test.js
@@ -0,0 +1,64 @@
+import { describe, it, expect } from 'vitest';
+import {
+ layoutLoomGraph, loomEdgePath, loomGraphLayers, LOOM_NODE_W,
+} from './loomLayout.js';
+
+const tr = (id, targetNodeId) => ({ id, targetNodeId, intent: 'go' });
+
+const episode = () => ({
+ id: 'ep-1',
+ startNodeId: 'n1',
+ nodes: [
+ { id: 'n1', transitions: [tr('t1', 'n2'), tr('t2', 'n3')] },
+ { id: 'n2', transitions: [tr('t3', 'n4')] },
+ { id: 'n3', isEnding: true, transitions: [] },
+ { id: 'n4', isEnding: true, transitions: [] },
+ ],
+});
+
+describe('loomGraphLayers', () => {
+ it('layers by BFS depth and trails unreachable nodes', () => {
+ const ep = episode();
+ ep.nodes.push({ id: 'orphan', transitions: [] });
+ const layers = loomGraphLayers(ep);
+ expect(layers[0]).toEqual(['n1']);
+ expect(layers[1]).toEqual(['n2', 'n3']);
+ expect(layers[2]).toEqual(['n4']);
+ expect(layers[3]).toEqual(['orphan']);
+ });
+
+ it('returns only orphan chunks when there is no valid start', () => {
+ const layers = loomGraphLayers({ startNodeId: 'gone', nodes: [{ id: 'a' }, { id: 'b' }] });
+ expect(layers).toEqual([['a', 'b']]);
+ });
+});
+
+describe('layoutLoomGraph', () => {
+ it('assigns columns by depth and lets persisted pos win', () => {
+ const ep = episode();
+ ep.nodes[3].pos = { x: 999, y: 5 };
+ const { positions, width, height } = layoutLoomGraph(ep);
+ expect(positions.n1.x).toBeLessThan(positions.n2.x);
+ expect(positions.n2.x).toBe(positions.n3.x);
+ expect(positions.n4).toEqual({ x: 999, y: 5 });
+ expect(width).toBeGreaterThanOrEqual(999 + LOOM_NODE_W);
+ expect(height).toBeGreaterThan(0);
+ });
+
+ it('handles an empty episode without NaN extents', () => {
+ const { positions, width, height } = layoutLoomGraph({ nodes: [] });
+ expect(positions).toEqual({});
+ expect(width).toBeGreaterThan(0);
+ expect(height).toBeGreaterThan(0);
+ });
+});
+
+describe('loomEdgePath', () => {
+ it('produces a cubic path from right edge to left edge with a label midpoint', () => {
+ const { d, labelX, labelY } = loomEdgePath({ x: 0, y: 0 }, { x: 300, y: 100 });
+ expect(d.startsWith(`M ${LOOM_NODE_W} `)).toBe(true);
+ expect(d).toContain('C ');
+ expect(labelX).toBe((LOOM_NODE_W + 300) / 2);
+ expect(labelY).toBeGreaterThan(0);
+ });
+});
diff --git a/client/src/pages/FableLoom.jsx b/client/src/pages/FableLoom.jsx
new file mode 100644
index 0000000000..cfd6e1fffb
--- /dev/null
+++ b/client/src/pages/FableLoom.jsx
@@ -0,0 +1,228 @@
+/**
+ * FableLoom index — branching narratives.
+ *
+ * Lists every loom (a branching-narrative story: episodes of scene graphs a
+ * reader plays through by chatting intents) and creates new ones. The heavy
+ * visual editor lives at /fableloom/:loomId/:episodeId.
+ */
+
+import { useEffect, useState } from 'react';
+import { useNavigate } from 'react-router';
+import { Plus, Trash2, Waypoints } from 'lucide-react';
+import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
+import { useConfirmDelete } from '../hooks/useConfirmDelete';
+import { timeAgo } from '../utils/formatters';
+import {
+ createLoom, deleteLoom, listLooms, listPipelineSeries, listUniverses,
+} from '../services/api';
+
+const emptyForm = () => ({ name: '', logline: '', premise: '', universeId: '', seriesId: '' });
+
+const loomStats = (loom) => {
+ const episodes = loom.episodes || [];
+ const nodes = episodes.reduce((sum, e) => sum + (e.nodes?.length || 0), 0);
+ const endings = episodes.reduce((sum, e) => sum + (e.nodes?.filter((n) => n.isEnding).length || 0), 0);
+ return { episodes: episodes.length, nodes, endings };
+};
+
+export default function FableLoom() {
+ const navigate = useNavigate();
+ const [looms, setLooms] = useState(null);
+ const [universes, setUniverses] = useState([]);
+ const [series, setSeries] = useState([]);
+ const [showForm, setShowForm] = useState(false);
+ const [form, setForm] = useState(emptyForm());
+ const [creating, setCreating] = useState(false);
+ const del = useConfirmDelete();
+
+ useEffect(() => {
+ listLooms().then(setLooms).catch(() => setLooms([]));
+ listUniverses({ silent: true }).then(setUniverses).catch(() => {});
+ listPipelineSeries({ silent: true }).then(setSeries).catch(() => {});
+ }, []);
+
+ const universeName = (id) => universes.find((u) => u.id === id)?.name || null;
+ const seriesName = (id) => series.find((s) => s.id === id)?.name || null;
+
+ const handleCreate = async (event) => {
+ event.preventDefault();
+ if (!form.name.trim() || creating) return;
+ setCreating(true);
+ const loom = await createLoom({
+ name: form.name.trim(),
+ logline: form.logline,
+ premise: form.premise,
+ universeId: form.universeId || null,
+ seriesId: form.seriesId || null,
+ }).catch(() => null);
+ setCreating(false);
+ if (loom) navigate(`/fableloom/${loom.id}`);
+ };
+
+ const handleDelete = async (id) => {
+ const ok = await deleteLoom(id).then(() => true).catch(() => false);
+ if (ok) setLooms((prev) => prev.filter((l) => l.id !== id));
+ del.cancelDelete();
+ };
+
+ return (
+ <div className="max-w-5xl mx-auto space-y-6">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <div>
+ <h1 className="text-xl font-semibold flex items-center gap-2">
+ <Waypoints size={20} className="text-port-accent" /> FableLoom
+ </h1>
+ <p className="text-sm text-port-text-muted mt-1">
+ Branching narratives readers play through by chatting their intents — every episode is a
+ graph of scenes with multiple endings.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => setShowForm((v) => !v)}
+ className="flex items-center gap-1.5 px-3 py-2 rounded bg-port-accent text-white text-sm"
+ >
+ <Plus size={15} /> New loom
+ </button>
+ </div>
+
+ {showForm && (
+ <form onSubmit={handleCreate} className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <div className="grid gap-3 md:grid-cols-2">
+ <div>
+ <label className="block text-xs font-medium text-port-text-muted mb-1" htmlFor="loom-name">Name</label>
+ <input
+ id="loom-name"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ value={form.name}
+ onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))}
+ placeholder="e.g. The Hollow Crown"
+ required
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-medium text-port-text-muted mb-1" htmlFor="loom-logline">Logline</label>
+ <input
+ id="loom-logline"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ value={form.logline}
+ onChange={(e) => setForm((p) => ({ ...p, logline: e.target.value }))}
+ placeholder="One sentence of premise"
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-medium text-port-text-muted mb-1" htmlFor="loom-universe">Universe (canon + style for AI)</label>
+ <select
+ id="loom-universe"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ value={form.universeId}
+ onChange={(e) => setForm((p) => ({ ...p, universeId: e.target.value }))}
+ >
+ <option value="">No universe</option>
+ {universes.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
+ </select>
+ </div>
+ <div>
+ <label className="block text-xs font-medium text-port-text-muted mb-1" htmlFor="loom-series">Part of series (optional)</label>
+ <select
+ id="loom-series"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ value={form.seriesId}
+ onChange={(e) => setForm((p) => ({ ...p, seriesId: e.target.value }))}
+ >
+ <option value="">Standalone</option>
+ {series.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
+ </select>
+ </div>
+ </div>
+ <div>
+ <label className="block text-xs font-medium text-port-text-muted mb-1" htmlFor="loom-premise">Premise</label>
+ <textarea
+ id="loom-premise"
+ rows={3}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ value={form.premise}
+ onChange={(e) => setForm((p) => ({ ...p, premise: e.target.value }))}
+ placeholder="The setup, stakes, and tone the AI should weave from"
+ />
+ </div>
+ <div className="flex justify-end">
+ <button
+ type="submit"
+ disabled={creating || !form.name.trim()}
+ className="px-4 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50"
+ >
+ {creating ? 'Creating…' : 'Create loom'}
+ </button>
+ </div>
+ </form>
+ )}
+
+ {looms === null ? (
+ <p className="text-sm text-port-text-muted">Loading…</p>
+ ) : looms.length === 0 ? (
+ <div className="text-center py-16 border border-dashed border-port-border rounded-lg">
+ <Waypoints size={32} className="mx-auto text-port-text-muted mb-3" />
+ <p className="text-sm text-port-text-muted">
+ No branching narratives yet. Create a loom, link a universe, and weave your first episode.
+ </p>
+ </div>
+ ) : (
+ <div className="grid gap-3 sm:grid-cols-2">
+ {looms.map((loom) => {
+ const stats = loomStats(loom);
+ return (
+ <div
+ key={loom.id}
+ className="bg-port-card border border-port-border rounded-lg p-4 hover:border-port-accent transition-colors cursor-pointer"
+ role="link"
+ tabIndex={0}
+ onClick={() => navigate(`/fableloom/${loom.id}`)}
+ onKeyDown={(e) => { if (e.key === 'Enter') navigate(`/fableloom/${loom.id}`); }}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <h2 className="font-medium truncate">{loom.name}</h2>
+ {loom.logline && <p className="text-xs text-port-text-muted mt-0.5 line-clamp-2">{loom.logline}</p>}
+ </div>
+ <div onClick={(e) => e.stopPropagation()} onKeyDown={(e) => e.stopPropagation()} role="none">
+ {del.isConfirming(loom.id) ? (
+ <ConfirmButtonPair
+ prompt="Delete?"
+ onConfirm={() => handleDelete(loom.id)}
+ onCancel={del.cancelDelete}
+ />
+ ) : (
+ <button
+ type="button"
+ aria-label={`Delete ${loom.name}`}
+ onClick={() => del.requestDelete(loom.id)}
+ className="text-port-text-muted hover:text-port-error p-1"
+ >
+ <Trash2 size={15} />
+ </button>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center gap-3 mt-3 text-xs text-port-text-muted flex-wrap">
+ <span>{stats.episodes} episode{stats.episodes === 1 ? '' : 's'}</span>
+ <span>{stats.nodes} scene{stats.nodes === 1 ? '' : 's'}</span>
+ <span>{stats.endings} ending{stats.endings === 1 ? '' : 's'}</span>
+ {universeName(loom.universeId) && (
+ <span className="px-1.5 py-0.5 rounded bg-port-accent/10 text-port-accent">
+ {universeName(loom.universeId)}
+ </span>
+ )}
+ {seriesName(loom.seriesId) && (
+ <span className="px-1.5 py-0.5 rounded bg-port-border/40">{seriesName(loom.seriesId)}</span>
+ )}
+ <span className="ml-auto">{timeAgo(loom.updatedAt)}</span>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/FableLoom.test.jsx b/client/src/pages/FableLoom.test.jsx
new file mode 100644
index 0000000000..b7ad3e3173
--- /dev/null
+++ b/client/src/pages/FableLoom.test.jsx
@@ -0,0 +1,97 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router';
+
+vi.mock('../services/api', () => ({
+ listLooms: vi.fn(),
+ createLoom: vi.fn(),
+ deleteLoom: vi.fn(),
+ listUniverses: vi.fn(),
+ listPipelineSeries: vi.fn(),
+}));
+
+const navigate = vi.fn();
+vi.mock('react-router', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, useNavigate: () => navigate };
+});
+
+import * as api from '../services/api';
+import FableLoom from './FableLoom';
+
+const looms = [
+ {
+ id: 'loom-1',
+ name: 'The Hollow Crown',
+ logline: 'A crown that remembers.',
+ universeId: 'uni-1',
+ seriesId: null,
+ updatedAt: '2026-08-20T00:00:00Z',
+ episodes: [
+ {
+ id: 'ep-1',
+ nodes: [
+ { id: 'n1', isEnding: false },
+ { id: 'n2', isEnding: true },
+ { id: 'n3', isEnding: true },
+ ],
+ },
+ ],
+ },
+];
+
+const renderPage = () => render(<MemoryRouter><FableLoom /></MemoryRouter>);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.listLooms.mockResolvedValue(looms);
+ api.listUniverses.mockResolvedValue([{ id: 'uni-1', name: 'Aria Verse' }]);
+ api.listPipelineSeries.mockResolvedValue([]);
+});
+
+describe('FableLoom index', () => {
+ it('lists looms with episode/scene/ending stats and the universe chip', async () => {
+ renderPage();
+ await waitFor(() => expect(screen.getByText('The Hollow Crown')).toBeInTheDocument());
+ expect(screen.getByText('1 episode')).toBeInTheDocument();
+ expect(screen.getByText('3 scenes')).toBeInTheDocument();
+ expect(screen.getByText('2 endings')).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText('Aria Verse')).toBeInTheDocument());
+ });
+
+ it('shows the empty state when there are no looms', async () => {
+ api.listLooms.mockResolvedValue([]);
+ renderPage();
+ await waitFor(() => expect(screen.getByText(/No branching narratives yet/)).toBeInTheDocument());
+ });
+
+ it('creates a loom and navigates to its editor', async () => {
+ api.createLoom.mockResolvedValue({ id: 'loom-9' });
+ const user = userEvent.setup();
+ renderPage();
+ await waitFor(() => expect(screen.getByText('The Hollow Crown')).toBeInTheDocument());
+
+ await user.click(screen.getByRole('button', { name: /New loom/ }));
+ await user.type(screen.getByLabelText('Name'), 'Gate of Ash');
+ await user.click(screen.getByRole('button', { name: 'Create loom' }));
+
+ await waitFor(() => expect(api.createLoom).toHaveBeenCalledWith({
+ name: 'Gate of Ash', logline: '', premise: '', universeId: null, seriesId: null,
+ }));
+ expect(navigate).toHaveBeenCalledWith('/fableloom/loom-9');
+ });
+
+ it('deletes a loom after inline confirmation', async () => {
+ api.deleteLoom.mockResolvedValue({});
+ const user = userEvent.setup();
+ renderPage();
+ await waitFor(() => expect(screen.getByText('The Hollow Crown')).toBeInTheDocument());
+
+ await user.click(screen.getByRole('button', { name: 'Delete The Hollow Crown' }));
+ await user.click(screen.getByRole('button', { name: /^Delete$/ }));
+
+ await waitFor(() => expect(api.deleteLoom).toHaveBeenCalledWith('loom-1'));
+ await waitFor(() => expect(screen.queryByText('The Hollow Crown')).not.toBeInTheDocument());
+ });
+});
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
new file mode 100644
index 0000000000..a7e2e21eb2
--- /dev/null
+++ b/client/src/pages/FableLoomStory.jsx
@@ -0,0 +1,425 @@
+/**
+ * FableLoom editor — the full-bleed visual workspace for one loom.
+ *
+ * URL is the source of truth: /fableloom/:loomId/:episodeId/:nodeId? — the
+ * selected episode and scene are route params, the play drawer rides ?play=1.
+ * Left: the scene-graph canvas. Right rail: the selected scene's editor, or
+ * the structure/review panel when nothing is selected.
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+import { Link, Navigate, useNavigate, useParams, useSearchParams } from 'react-router';
+import { ArrowLeft, BookOpenText, Loader2, Plus, Sparkles, Trash2, Waypoints } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import Drawer from '../components/Drawer';
+import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
+import { useConfirmDelete } from '../hooks/useConfirmDelete';
+import LoomCanvas from '../components/fableloom/LoomCanvas';
+import LoomNodeEditor from '../components/fableloom/LoomNodeEditor';
+import LoomPlayPanel from '../components/fableloom/LoomPlayPanel';
+import LoomValidationPanel from '../components/fableloom/LoomValidationPanel';
+import {
+ addLoomEpisode, addLoomNode, deleteLoomEpisode, getLoom, updateLoomEpisode,
+ updateLoomNode, weaveLoomEpisode,
+} from '../services/api';
+
+export default function FableLoomStory() {
+ const { loomId, episodeId, nodeId } = useParams();
+ const navigate = useNavigate();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [loom, setLoom] = useState(null);
+ const [notFound, setNotFound] = useState(false);
+ const [setupOpen, setSetupOpen] = useState(false);
+ const playOpen = searchParams.get('play') === '1';
+
+ useEffect(() => {
+ setNotFound(false);
+ getLoom(loomId).then(setLoom).catch(() => setNotFound(true));
+ }, [loomId]);
+
+ const episode = loom?.episodes.find((e) => e.id === episodeId) || null;
+ const node = episode?.nodes.find((n) => n.id === nodeId) || null;
+
+ const basePath = `/fableloom/${loomId}`;
+ const episodePath = useCallback(
+ (epId, nId) => `${basePath}/${epId}${nId ? `/${nId}` : ''}`,
+ [basePath],
+ );
+
+ const onLoomUpdate = useCallback((next) => setLoom(next), []);
+
+ const setPlayOpen = (open) => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ if (open) next.set('play', '1');
+ else next.delete('play');
+ return next;
+ }, { replace: true });
+ };
+
+ const handleAddEpisode = async () => {
+ const updated = await addLoomEpisode(loomId, { title: `Episode ${(loom?.episodes.length || 0) + 1}` })
+ .catch(() => null);
+ if (updated) {
+ setLoom(updated);
+ const added = updated.episodes[updated.episodes.length - 1];
+ navigate(episodePath(added.id));
+ setSetupOpen(true);
+ }
+ };
+
+ const handleAddNode = async () => {
+ const updated = await addLoomNode(loomId, episode.id, { title: 'New scene' }).catch(() => null);
+ if (updated) {
+ setLoom(updated);
+ const ep = updated.episodes.find((e) => e.id === episode.id);
+ const added = ep?.nodes[ep.nodes.length - 1];
+ if (added) navigate(episodePath(episode.id, added.id));
+ }
+ };
+
+ const handleMoveNode = (movedNodeId, pos) => {
+ // Optimistic: fold the new position into local state, persist silently.
+ setLoom((prev) => ({
+ ...prev,
+ episodes: prev.episodes.map((e) => (e.id !== episode.id ? e : {
+ ...e,
+ nodes: e.nodes.map((n) => (n.id === movedNodeId ? { ...n, pos } : n)),
+ })),
+ }));
+ updateLoomNode(loomId, episode.id, movedNodeId, { pos }, { silent: true })
+ .then(onLoomUpdate)
+ .catch(() => {});
+ };
+
+ if (notFound) {
+ return (
+ <div className="p-8 text-center">
+ <p className="text-sm text-port-text-muted">This loom no longer exists.</p>
+ <Link to="/fableloom" className="text-port-accent text-sm hover:underline">Back to FableLoom</Link>
+ </div>
+ );
+ }
+ if (!loom) {
+ return <div className="p-8 text-sm text-port-text-muted">Loading…</div>;
+ }
+
+ // Route normalization: no/stale episode id → first episode (or stay bare
+ // when the loom has none yet).
+ if (!episode && loom.episodes.length) {
+ return <Navigate to={episodePath(loom.episodes[0].id)} replace />;
+ }
+ if (episodeId && !episode) {
+ return <Navigate to={basePath} replace />;
+ }
+
+ return (
+ <div className="h-full flex flex-col">
+ <header className="border-b border-port-border px-4 py-2.5 space-y-2">
+ <div className="flex items-center gap-3 flex-wrap">
+ <Link to="/fableloom" className="text-port-text-muted hover:text-port-text" aria-label="Back to FableLoom">
+ <ArrowLeft size={18} />
+ </Link>
+ <h1 className="font-semibold flex items-center gap-2 min-w-0">
+ <Waypoints size={16} className="text-port-accent shrink-0" />
+ <span className="truncate">{loom.name}</span>
+ </h1>
+ {episode && (
+ <div className="flex items-center gap-2 ml-auto">
+ <button
+ type="button"
+ onClick={handleAddNode}
+ className="flex items-center gap-1 px-2.5 py-1.5 rounded border border-port-border text-xs hover:border-port-accent"
+ >
+ <Plus size={13} /> Scene
+ </button>
+ <button
+ type="button"
+ onClick={() => setSetupOpen(true)}
+ className="flex items-center gap-1 px-2.5 py-1.5 rounded border border-port-border text-xs hover:border-port-accent"
+ >
+ <Sparkles size={13} /> Weave
+ </button>
+ <button
+ type="button"
+ onClick={() => setPlayOpen(true)}
+ className="flex items-center gap-1 px-2.5 py-1.5 rounded bg-port-accent text-white text-xs"
+ >
+ <BookOpenText size={13} /> Play
+ </button>
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-1.5 flex-wrap">
+ {loom.episodes.map((e) => (
+ <button
+ key={e.id}
+ type="button"
+ onClick={() => navigate(episodePath(e.id))}
+ className={`px-2.5 py-1 rounded-full text-xs border ${
+ e.id === episodeId
+ ? 'border-port-accent text-port-accent bg-port-accent/10'
+ : 'border-port-border text-port-text-muted hover:border-port-accent'
+ }`}
+ >
+ {e.number}. {e.title || 'Untitled'}
+ </button>
+ ))}
+ <button
+ type="button"
+ onClick={handleAddEpisode}
+ className="px-2.5 py-1 rounded-full text-xs border border-dashed border-port-border text-port-text-muted hover:border-port-accent hover:text-port-accent"
+ >
+ + Episode
+ </button>
+ </div>
+ </header>
+
+ {!episode ? (
+ <div className="flex-1 grid place-items-center p-8 text-center">
+ <div>
+ <Waypoints size={32} className="mx-auto text-port-text-muted mb-3" />
+ <p className="text-sm text-port-text-muted mb-3">
+ No episodes yet — add one, then weave its scene graph with AI or build it by hand.
+ </p>
+ <button
+ type="button"
+ onClick={handleAddEpisode}
+ className="px-3 py-2 rounded bg-port-accent text-white text-sm"
+ >
+ Add the first episode
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex-1 min-h-0 flex flex-col lg:flex-row">
+ <section className="flex-1 min-h-[45vh] lg:min-h-0 relative">
+ {episode.nodes.length ? (
+ <LoomCanvas
+ episode={episode}
+ selectedNodeId={nodeId || null}
+ onSelectNode={(id) => navigate(episodePath(episode.id, id) + (playOpen ? '?play=1' : ''))}
+ onMoveNode={handleMoveNode}
+ />
+ ) : (
+ <div className="h-full grid place-items-center p-8 text-center">
+ <div>
+ <p className="text-sm text-port-text-muted mb-3">
+ This episode has no scenes yet.
+ </p>
+ <div className="flex items-center justify-center gap-2">
+ <button
+ type="button"
+ onClick={() => setSetupOpen(true)}
+ className="flex items-center gap-1.5 px-3 py-2 rounded bg-port-accent text-white text-sm"
+ >
+ <Sparkles size={14} /> Weave with AI
+ </button>
+ <button
+ type="button"
+ onClick={handleAddNode}
+ className="px-3 py-2 rounded border border-port-border text-sm hover:border-port-accent"
+ >
+ Add a scene by hand
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </section>
+ <aside className="lg:w-[380px] lg:shrink-0 border-t lg:border-t-0 lg:border-l border-port-border overflow-y-auto">
+ {node ? (
+ <LoomNodeEditor
+ key={node.id}
+ loom={loom}
+ episode={episode}
+ node={node}
+ onLoomUpdate={onLoomUpdate}
+ onClearSelection={() => navigate(episodePath(episode.id))}
+ onMakeStart={node.id !== episode.startNodeId ? async () => {
+ const updated = await updateLoomEpisode(loomId, episode.id, { startNodeId: node.id })
+ .catch(() => null);
+ if (updated) setLoom(updated);
+ } : null}
+ />
+ ) : (
+ <LoomValidationPanel
+ loom={loom}
+ episode={episode}
+ onSelectNode={(id) => navigate(episodePath(episode.id, id))}
+ />
+ )}
+ </aside>
+ </div>
+ )}
+
+ {episode && (
+ <EpisodeSetupDrawer
+ open={setupOpen}
+ onClose={() => setSetupOpen(false)}
+ loom={loom}
+ episode={episode}
+ onLoomUpdate={onLoomUpdate}
+ onDeleted={() => {
+ setSetupOpen(false);
+ navigate(basePath);
+ }}
+ />
+ )}
+
+ {episode && (
+ <Drawer open={playOpen} onClose={() => setPlayOpen(false)} title="Play" subtitle={loom.name} size="md" bodyClassName="p-0">
+ <LoomPlayPanel loom={loom} episode={episode} />
+ </Drawer>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Episode setup drawer — title/synopsis (the weave inputs), the AI weave
+ * controls, and episode deletion.
+ */
+function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onDeleted }) {
+ const [form, setForm] = useState({ title: '', synopsis: '', guidance: '', nodeTarget: 12, endingTarget: 3 });
+ const [weaving, setWeaving] = useState(false);
+ const del = useConfirmDelete();
+ const hasScenes = episode.nodes.length > 0;
+
+ useEffect(() => {
+ setForm((prev) => ({ ...prev, title: episode.title || '', synopsis: episode.synopsis || '' }));
+ }, [episode.id, episode.title, episode.synopsis]);
+
+ const saveMeta = (patch) => {
+ updateLoomEpisode(loom.id, episode.id, patch, { silent: true })
+ .then(onLoomUpdate)
+ .catch((err) => toast.error(`Save failed: ${err.message}`));
+ };
+
+ const handleWeave = async () => {
+ setWeaving(true);
+ const result = await weaveLoomEpisode(loom.id, episode.id, {
+ guidance: form.guidance,
+ nodeTarget: Number(form.nodeTarget) || 12,
+ endingTarget: Number(form.endingTarget) || 3,
+ replace: hasScenes,
+ }).catch(() => null);
+ setWeaving(false);
+ if (result?.loom) {
+ onLoomUpdate(result.loom);
+ toast.success('Episode woven');
+ onClose();
+ }
+ };
+
+ const handleDelete = async () => {
+ const updated = await deleteLoomEpisode(loom.id, episode.id).catch(() => null);
+ if (updated) {
+ onLoomUpdate(updated);
+ onDeleted();
+ }
+ };
+
+ const field = 'w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
+ const label = 'block text-xs font-medium text-port-text-muted mb-1';
+
+ return (
+ <Drawer open={open} onClose={onClose} title="Episode setup" subtitle={`${loom.name} — episode ${episode.number}`} size="sm">
+ <div className="space-y-4">
+ <div>
+ <label className={label} htmlFor="loom-ep-title">Title</label>
+ <input
+ id="loom-ep-title"
+ className={field}
+ value={form.title}
+ onChange={(e) => setForm((p) => ({ ...p, title: e.target.value }))}
+ onBlur={() => saveMeta({ title: form.title })}
+ />
+ </div>
+ <div>
+ <label className={label} htmlFor="loom-ep-synopsis">Synopsis (feeds the weave)</label>
+ <textarea
+ id="loom-ep-synopsis"
+ rows={4}
+ className={field}
+ placeholder="What this episode is about — setup, stakes, tone"
+ value={form.synopsis}
+ onChange={(e) => setForm((p) => ({ ...p, synopsis: e.target.value }))}
+ onBlur={() => saveMeta({ synopsis: form.synopsis })}
+ />
+ </div>
+
+ <div className="border-t border-port-border pt-4 space-y-3">
+ <h4 className="text-sm font-semibold flex items-center gap-1.5">
+ <Sparkles size={14} className="text-port-accent" /> Weave the scene graph
+ </h4>
+ <div>
+ <label className={label} htmlFor="loom-ep-guidance">Guidance (optional)</label>
+ <textarea
+ id="loom-ep-guidance"
+ rows={2}
+ className={field}
+ placeholder="e.g. lean into dread; one ending must be hopeful"
+ value={form.guidance}
+ onChange={(e) => setForm((p) => ({ ...p, guidance: e.target.value }))}
+ />
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <label className={label} htmlFor="loom-ep-nodes">Scenes (approx.)</label>
+ <input
+ id="loom-ep-nodes"
+ type="number" min={3} max={60}
+ className={field}
+ value={form.nodeTarget}
+ onChange={(e) => setForm((p) => ({ ...p, nodeTarget: e.target.value }))}
+ />
+ </div>
+ <div>
+ <label className={label} htmlFor="loom-ep-endings">Endings</label>
+ <input
+ id="loom-ep-endings"
+ type="number" min={1} max={12}
+ className={field}
+ value={form.endingTarget}
+ onChange={(e) => setForm((p) => ({ ...p, endingTarget: e.target.value }))}
+ />
+ </div>
+ </div>
+ {hasScenes && (
+ <p className="text-xs text-port-warning">
+ Weaving replaces this episode's {episode.nodes.length} existing scene{episode.nodes.length === 1 ? '' : 's'}.
+ </p>
+ )}
+ <button
+ type="button"
+ onClick={handleWeave}
+ disabled={weaving}
+ className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-60"
+ >
+ {weaving ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {weaving ? 'Weaving…' : hasScenes ? 'Reweave episode' : 'Weave episode'}
+ </button>
+ </div>
+
+ <div className="border-t border-port-border pt-4">
+ {del.isConfirming(episode.id) ? (
+ <ConfirmButtonPair
+ prompt="Delete episode?"
+ onConfirm={handleDelete}
+ onCancel={del.cancelDelete}
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={() => del.requestDelete(episode.id)}
+ className="flex items-center gap-1.5 text-xs text-port-text-muted hover:text-port-error"
+ >
+ <Trash2 size={13} /> Delete this episode
+ </button>
+ )}
+ </div>
+ </div>
+ </Drawer>
+ );
+}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index dc8c50157a..bcdecffbd5 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -102,6 +102,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiMediaJobs.js` | Media generation job tracking + `refineMediaPrompt` / `promptFromMedia` (vision reverse-prompt). |
| `apiCreativeDirector.js` | Creative Director (video production). |
| `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). |
+| `apiFableLoom.js` | FableLoom branching narratives — loom/episode/scene-node CRUD, deterministic graph validation, and the AI lanes (weave, branch, review, play turns). |
| `apiGames.js` | Game studio records, managed-app binding, reusable sprite/music bindings, deterministic asset-bundle compilation/integrity preflight, and AI feedback history. |
| `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. |
| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 117288ae35..b67cfbddc2 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -73,6 +73,7 @@ export * from './apiSyncReview.js';
export * from './apiBatch.js';
export * from './apiCreativeDirector.js';
export * from './apiCreativeCommission.js';
+export * from './apiFableLoom.js';
export * from './apiGames.js';
export * from './apiMusicVideo.js';
export * from './apiSprites.js';
diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.js
new file mode 100644
index 0000000000..56193b3f83
--- /dev/null
+++ b/client/src/services/apiFableLoom.js
@@ -0,0 +1,55 @@
+import { request } from './apiCore.js';
+
+const loomPath = (id, rest = '') => `/fableloom/${encodeURIComponent(id)}${rest}`;
+const episodePath = (id, episodeId, rest = '') =>
+ loomPath(id, `/episodes/${encodeURIComponent(episodeId)}${rest}`);
+const nodePath = (id, episodeId, nodeId, rest = '') =>
+ episodePath(id, episodeId, `/nodes/${encodeURIComponent(nodeId)}${rest}`);
+
+export const listLooms = (options = {}) => request('/fableloom', options);
+export const getLoom = (id, options = {}) => request(loomPath(id), options);
+
+export const createLoom = (body, options = {}) => request('/fableloom', {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const updateLoom = (id, patch, options = {}) => request(loomPath(id), {
+ method: 'PATCH', body: JSON.stringify(patch), ...options,
+});
+export const deleteLoom = (id, options = {}) => request(loomPath(id), {
+ method: 'DELETE', ...options,
+});
+
+export const addLoomEpisode = (id, body, options = {}) => request(loomPath(id, '/episodes'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const updateLoomEpisode = (id, episodeId, patch, options = {}) => request(episodePath(id, episodeId), {
+ method: 'PATCH', body: JSON.stringify(patch), ...options,
+});
+export const deleteLoomEpisode = (id, episodeId, options = {}) => request(episodePath(id, episodeId), {
+ method: 'DELETE', ...options,
+});
+export const validateLoomEpisode = (id, episodeId, options = {}) =>
+ request(episodePath(id, episodeId, '/validate'), options);
+
+export const addLoomNode = (id, episodeId, body, options = {}) => request(episodePath(id, episodeId, '/nodes'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const updateLoomNode = (id, episodeId, nodeId, patch, options = {}) => request(nodePath(id, episodeId, nodeId), {
+ method: 'PATCH', body: JSON.stringify(patch), ...options,
+});
+export const deleteLoomNode = (id, episodeId, nodeId, options = {}) => request(nodePath(id, episodeId, nodeId), {
+ method: 'DELETE', ...options,
+});
+
+export const weaveLoomEpisode = (id, episodeId, body = {}, options = {}) => request(episodePath(id, episodeId, '/weave'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const branchLoomNode = (id, episodeId, nodeId, body = {}, options = {}) => request(nodePath(id, episodeId, nodeId, '/branch'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const reviewLoomEpisode = (id, episodeId, body = {}, options = {}) => request(episodePath(id, episodeId, '/review'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const playLoomTurn = (id, episodeId, body, options = {}) => request(episodePath(id, episodeId, '/play'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
diff --git a/client/src/services/apiFableLoom.test.js b/client/src/services/apiFableLoom.test.js
new file mode 100644
index 0000000000..7230250bf1
--- /dev/null
+++ b/client/src/services/apiFableLoom.test.js
@@ -0,0 +1,54 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('./apiCore.js', () => ({
+ request: vi.fn(),
+}));
+
+let request;
+let api;
+
+beforeEach(async () => {
+ vi.resetModules();
+ ({ request } = await import('./apiCore.js'));
+ api = await import('./apiFableLoom.js');
+ request.mockReset();
+ request.mockResolvedValue({});
+});
+
+describe('apiFableLoom', () => {
+ it('encodes ids in nested node paths', async () => {
+ await api.updateLoomNode('loom/1', 'ep/1', 'node/1', { prose: 'x' }, { silent: true });
+ expect(request).toHaveBeenCalledWith('/fableloom/loom%2F1/episodes/ep%2F1/nodes/node%2F1', {
+ method: 'PATCH',
+ body: JSON.stringify({ prose: 'x' }),
+ silent: true,
+ });
+ });
+
+ it('posts weave options to the episode weave lane', async () => {
+ await api.weaveLoomEpisode('loom-1', 'ep-1', { guidance: 'darker', replace: true });
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/weave', {
+ method: 'POST',
+ body: JSON.stringify({ guidance: 'darker', replace: true }),
+ });
+ });
+
+ it('posts play turns with the transcript', async () => {
+ const body = { nodeId: 'node-1', message: 'open the gate', transcript: [] };
+ await api.playLoomTurn('loom-1', 'ep-1', body);
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/play', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ });
+ });
+
+ it('reads validation silently for the polling panel', async () => {
+ await api.validateLoomEpisode('loom-1', 'ep-1', { silent: true });
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/validate', { silent: true });
+ });
+
+ it('deletes nodes with DELETE', async () => {
+ await api.deleteLoomNode('loom-1', 'ep-1', 'node-1');
+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/nodes/node-1', { method: 'DELETE' });
+ });
+});
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index b6ae522911..73b5b527d6 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -988,6 +988,34 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "fableloom-weave-episode": {
+ "name": "FableLoom — Weave Episode Graph",
+ "description": "Generates a complete branching-narrative episode as a directed graph of scenes: an opening, 2–4 intent-labeled paths per scene (with example reader phrasings), and multiple distinct endings. Grounded in the loom's premise plus the linked universe's canon. Returns { startKey, nodes[] } with author-stable keys the service maps onto server-minted node ids.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
+ "fableloom-branch-node": {
+ "name": "FableLoom — Branch a Scene",
+ "description": "Grows new paths out of ONE scene of a branching-narrative episode: each branch is a new scene plus the reader intent (label + example phrasings + spoiler-safe description) that leads to it, kept distinct from the scene's existing paths. Returns { branches[] }.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "fableloom-play-turn": {
+ "name": "FableLoom — Play Turn",
+ "description": "Narrates one turn of an interactive read-through: matches the reader's free-text message against the current scene's intent-labeled paths (move) or responds in-world without leaving the scene (stay). Returns { action, transitionId?, narration }.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "fableloom-review": {
+ "name": "FableLoom — Episode Review",
+ "description": "Story-editor critique of a branching episode's narrative layer — intent clarity, branch coherence, ending payoff, scene craft, canon fit — layered over the deterministic graph checks (which run separately and are passed in so the model doesn't repeat them). Returns { summary, findings[] } with node-anchored findings.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/fableloom-branch-node.md b/data.reference/prompts/stages/fableloom-branch-node.md
new file mode 100644
index 0000000000..8c7755b43f
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-branch-node.md
@@ -0,0 +1,57 @@
+# FableLoom — Branch a Scene
+
+You are a branching-narrative designer growing new paths out of ONE scene of an interactive story. Readers move through the story by expressing intents in free text, so each new path must be labeled with a clear, distinct intent.
+
+## Story
+
+{{storyContext}}
+
+## World canon (use these characters, places, and objects where they fit)
+
+{{canonDigest}}
+
+## Existing episode graph
+
+{{graphDigest}}
+
+## The scene to branch
+
+**{{sceneTitle}}**
+
+{{sceneProse}}
+
+## Author guidance
+
+{{guidance}}
+
+## Design contract
+
+- Create exactly {{branchCount}} new branches out of this scene. Each branch is a NEW scene plus the intent that leads to it.
+- Each branch's `intent` is a short imperative label (≤10 words) a reader could plausibly express; include 2–4 `triggers` (example free-text phrasings) and a one-sentence spoiler-safe `description`.
+- The new intents must be clearly distinguishable from each other AND from the scene's existing paths shown in the graph digest.
+- A new scene may be an ending (`isEnding: true` + `endingLabel`) when the branch naturally concludes the story; otherwise write it as a scene that ends at a decision point (its own paths will be authored later).
+- Each new scene's `prose` is 100–250 words of second-person present-tense narration. Each `imagePrompt` is one sentence of concrete visual description.
+- Stay consistent with the tone, continuity, and canon of the existing graph.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "branches": [
+ {
+ "intent": "string",
+ "triggers": ["string"],
+ "description": "string",
+ "node": {
+ "title": "string",
+ "prose": "string",
+ "imagePrompt": "string",
+ "isEnding": false,
+ "endingLabel": ""
+ }
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/fableloom-play-turn.md b/data.reference/prompts/stages/fableloom-play-turn.md
new file mode 100644
index 0000000000..d7c360a5a1
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-play-turn.md
@@ -0,0 +1,44 @@
+# FableLoom — Play Turn
+
+You are the narrator of an interactive branching story. The reader is at one scene and has just told you what they want to do, in their own words. Your job: decide whether their message matches one of the scene's available paths, and answer in-world.
+
+## Story
+
+{{storyContext}}
+
+## Current scene
+
+{{sceneProse}}
+
+## Available paths
+
+{{choicesDigest}}
+
+## Recent conversation
+
+{{transcriptDigest}}
+
+## The reader just said
+
+{{readerMessage}}
+
+## Rules
+
+1. **Match generously but honestly.** If the reader's message expresses the same underlying intent as one path — even phrased differently, partially, or with extra flavor — choose that path (`action: "move"` with its `id`). The example phrasings show the spirit of each intent, not an exhaustive list.
+2. **Never invent a path.** If the message doesn't match any available path (a question about the scene, an impossible action, small talk, an intent this scene doesn't offer), set `action: "stay"` and respond in-world: answer their question or narrate the attempt from within the current scene, then gently steer them back toward what's possible here. Do NOT list the paths mechanically — hint at them through the fiction.
+3. **Narration** is 1–3 short paragraphs of second-person present-tense prose. When moving, narrate the *bridge* — the reader's chosen action carrying them out of this scene — without repeating the next scene's text (it will be shown separately). Stay consistent with the scene, the conversation so far, and the story's tone.
+4. If the reader's message could match two paths, pick the one their wording fits best; do not ask them to choose from a menu.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "action": "move",
+ "transitionId": "the chosen path's id, only when action is move",
+ "narration": "string"
+}
+```
+
+`action` must be `"move"` or `"stay"`. Omit or null `transitionId` when staying.
diff --git a/data.reference/prompts/stages/fableloom-review.md b/data.reference/prompts/stages/fableloom-review.md
new file mode 100644
index 0000000000..3048cfa7f6
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-review.md
@@ -0,0 +1,45 @@
+# FableLoom — Episode Review
+
+You are a story editor reviewing ONE episode of an interactive branching narrative. The structural graph checks (reachability, dead ends, dangling paths) have already run — your job is the *narrative* layer: does each branch read as a coherent story, do the intents make sense to a reader, and do the endings pay off?
+
+## Story
+
+{{storyContext}}
+
+## Episode graph
+
+{{graphDigest}}
+
+## Structural findings already detected (do not repeat these)
+
+{{structuralDigest}}
+
+## What to look for
+
+1. **Intent clarity.** A scene whose paths a reader couldn't tell apart from the prose alone, an intent label that promises something different from where it leads, or an intent no reader would plausibly express at that moment.
+2. **Branch coherence.** A path whose destination doesn't follow from the choice (continuity break, tone whiplash, a character acting against their established behavior), or branches that converge in ways that contradict what the reader did.
+3. **Ending payoff.** Endings that are interchangeable, unearned, or abrupt; a "best" path with no narrative cost; an ending whose label misrepresents its content.
+4. **Scene craft.** A scene that doesn't end at a decision point (non-endings), prose that reveals the outcome of a choice before it's made, or a scene doing nothing but routing traffic.
+5. **Canon fit.** A scene that contradicts the world canon or the story's own earlier scenes.
+
+Flag only concrete, fixable problems — name the scene and propose the smallest edit. Do NOT pad with low-confidence "consider also…" entries.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "summary": "2-4 sentences on the episode's overall shape and strongest/weakest branches",
+ "findings": [
+ {
+ "severity": "high",
+ "nodeId": "the [id] from the graph digest, when the finding is scene-specific",
+ "problem": "string (what's wrong, with the specific evidence)",
+ "suggestion": "string (the smallest concrete edit that resolves it)"
+ }
+ ]
+}
+```
+
+`severity` must be one of `high` / `medium` / `low`. Return `{ "summary": "...", "findings": [] }` when the episode is sound.
diff --git a/data.reference/prompts/stages/fableloom-weave-episode.md b/data.reference/prompts/stages/fableloom-weave-episode.md
new file mode 100644
index 0000000000..a17aa404b3
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-weave-episode.md
@@ -0,0 +1,59 @@
+# FableLoom — Weave Episode Graph
+
+You are a branching-narrative designer. Build ONE complete episode of an interactive story as a directed graph of scenes. Readers move through the graph by expressing intents in free text ("sneak past the guard", "ask her about the letter"), so every scene's outgoing paths must be labeled with a clear, distinct intent a reader could plausibly express on their own.
+
+## Story
+
+{{storyContext}}
+
+## World canon (use these characters, places, and objects where they fit)
+
+{{canonDigest}}
+
+## Author guidance
+
+{{guidance}}
+
+## Design contract
+
+- Aim for roughly {{nodeTarget}} scenes and {{endingTarget}} distinct endings. Endings must differ meaningfully in outcome and tone — not the same conclusion reworded.
+- Exactly one scene is the opening (`startKey`). Every scene must be reachable from it.
+- Every non-ending scene needs 2–4 outgoing paths. Each path gets: an `intent` (a short imperative label, ≤10 words), 2–4 `triggers` (example free-text phrasings a reader might type), and a one-sentence `description` of where it leads (spoiler-safe).
+- Intents on the same scene must be clearly distinguishable from each other — no two paths a reader could mean with the same sentence.
+- Ending scenes have `isEnding: true`, an `endingLabel` (a short evocative name for that outcome), and NO outgoing paths.
+- Loops back to earlier scenes are allowed when they make narrative sense, but at least one ending must remain reachable from every scene.
+- Each scene's `prose` is 100–250 words of second-person present-tense narration that ends at a decision point (except endings, which resolve).
+- Each scene's `imagePrompt` is one sentence of concrete visual description for an image generator — subject, setting, mood, no character names unless they're in the canon above.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "startKey": "s1",
+ "nodes": [
+ {
+ "key": "s1",
+ "title": "string",
+ "prose": "string",
+ "imagePrompt": "string",
+ "isEnding": false,
+ "transitions": [
+ { "targetKey": "s2", "intent": "string", "triggers": ["string"], "description": "string" }
+ ]
+ },
+ {
+ "key": "s9",
+ "title": "string",
+ "prose": "string",
+ "imagePrompt": "string",
+ "isEnding": true,
+ "endingLabel": "string",
+ "transitions": []
+ }
+ ]
+}
+```
+
+Every `targetKey` must reference a `key` that exists in `nodes`. Use short stable keys (`s1`, `s2`, …).
diff --git a/docs/README.md b/docs/README.md
index e472a48f97..0a70db0823 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -40,7 +40,7 @@ Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system]
Knowledge: [brain-system](./features/brain-system.md) · [messages-security](./features/messages-security.md)
-Create: [writers-room](./features/writers-room.md) · [openworld](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md)
+Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [openworld](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md)
Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md)
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
new file mode 100644
index 0000000000..0545a1da72
--- /dev/null
+++ b/docs/features/fableloom.md
@@ -0,0 +1,72 @@
+# FableLoom — Branching Narratives
+
+FableLoom is the Create-section workspace for branching narratives: stories a
+reader plays through by *chatting their intent* rather than picking from a
+fixed menu. A loom holds one or more episodes (like a series holds episodes);
+each episode is a directed graph of scene nodes with multiple endings. Every
+transition out of a scene is labeled with a reader **intent** ("sneak past the
+guard") plus example phrasings — at read time an LLM matches the reader's
+free-text message against those intents and moves them through the graph, or
+answers in-world without leaving the scene when nothing matches.
+
+## Concepts
+
+| Term | Meaning |
+|---|---|
+| **Loom** | A branching-narrative story (`loom-*`): name/logline/premise, optional `universeId` + `seriesId` links, episodes. |
+| **Episode** | One playable graph (`ep-*`): title, synopsis (feeds generation), `startNodeId`, nodes. |
+| **Scene node** | One story beat (`node-*`): prose, image prompt + rendered image, ending flag/label, transitions. |
+| **Transition** | An intent-labeled edge (`tr-*`): `intent`, `triggers` (example phrasings), spoiler-safe `description`, `targetNodeId`. |
+
+## Surfaces
+
+- **`/fableloom`** — index: create/delete looms, link a universe (canon +
+ style for AI) and optionally a pipeline series.
+- **`/fableloom/:loomId/:episodeId/:nodeId?`** — the visual editor: an SVG
+ scene-graph canvas (BFS-layered; drag to reposition, positions persist),
+ a scene editor rail (prose, endings, intent paths, scene image), and a
+ structure/review rail when nothing is selected. `?play=1` opens the reader
+ drawer.
+- **Play drawer** — the reader chat. Sessions are client-side state
+ (restart is free; nothing persists server-side).
+
+## AI lanes (all direct user actions; stage prompts in `data/prompts/stages/`)
+
+| Stage | What it does |
+|---|---|
+| `fableloom-weave-episode` | Generates a full episode graph (scenes, intents, triggers, endings) from the loom premise + episode synopsis + linked-universe canon. |
+| `fableloom-branch-node` | Grows N new intent-labeled branches out of one scene. |
+| `fableloom-play-turn` | Resolves one reader message: `move` through a matched transition or `stay` with in-world narration. |
+| `fableloom-review` | Story-editor critique (intent clarity, branch coherence, ending payoff) layered over the deterministic checks. |
+
+Deterministic graph validation (no LLM) lives in
+`server/lib/fableLoomGraph.js` — reachability from the opening scene, dead
+ends, dangling transitions, unreachable endings, duplicate/empty intents —
+and renders in the editor's Structure panel via
+`GET /api/fableloom/:id/episodes/:episodeId/validate`.
+
+## Scene images
+
+Each node carries an `imagePrompt`; **Generate** posts to the shared
+`/api/image-gen/generate` queue with a `fableLoom: { loomId, episodeId,
+nodeId }` destination tag. The completion hook
+(`server/services/fableLoomSceneImageHook.js`) files the finished render onto
+the node durably — even if the editor unmounted mid-render — with
+newest-render-wins per node. The loom's `styleNotes` are appended to the
+prompt for a consistent look.
+
+## Storage
+
+`fableloom_stories` (db-primary; one row per loom, full record in `data`
+JSONB, `universe_id`/`series_id` mirrored as soft refs). **Machine-local — no
+federation**: no dataSync category, no sync cursor, hard deletes (same posture
+as Games / Writers Room). Service: `server/services/fableLoom/` (records /
+weave / store / db); routes: `server/routes/fableLoom.js` (`/api/fableloom`).
+
+## Relationship to the series pipeline
+
+A loom can *link* to a pipeline series (`seriesId`) but is its own record
+type — branching narratives don't run the linear issue/stage pipeline
+(manuscript formats, autopilot, federation semantics don't apply to a graph).
+Deeper integration (a branching series type surfaced inside series
+management) is deliberately deferred.
diff --git a/scripts/migrations/286-fableloom-stages.js b/scripts/migrations/286-fableloom-stages.js
new file mode 100644
index 0000000000..577c4093ad
--- /dev/null
+++ b/scripts/migrations/286-fableloom-stages.js
@@ -0,0 +1,18 @@
+/**
+ * Seed the four FableLoom stages into existing installs.
+ *
+ * Boot runs migrations (server/index.js) but NOT `setup-data.js`, so an
+ * upgrade that pulls + `pm2 restart`s would otherwise leave the new
+ * branching-narrative stages unseeded and `runStagedLLM('fableloom-…')`
+ * would throw "Stage not found" the first time a weave/branch/play/review
+ * call runs.
+ */
+
+import { makeSeedMigrations } from './_seedStageHelpers.js';
+
+export default makeSeedMigrations([
+ 'fableloom-weave-episode',
+ 'fableloom-branch-node',
+ 'fableloom-play-turn',
+ 'fableloom-review',
+]);
diff --git a/scripts/migrations/286-fableloom-stages.test.js b/scripts/migrations/286-fableloom-stages.test.js
new file mode 100644
index 0000000000..0f00a8164b
--- /dev/null
+++ b/scripts/migrations/286-fableloom-stages.test.js
@@ -0,0 +1,20 @@
+import { describe } from 'vitest';
+
+import migration from './286-fableloom-stages.js';
+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';
+
+// The four FableLoom branching-narrative stages. A template shipped without its
+// stage-config entry throws "Stage <name> not found" at the button press with
+// nothing failing first — this guards the pair stays complete on upgrades.
+describe('migration 286 — seed the FableLoom stages', () => {
+ runSeedStageMigrationTests({
+ migration,
+ stages: [
+ 'fableloom-weave-episode',
+ 'fableloom-branch-node',
+ 'fableloom-play-turn',
+ 'fableloom-review',
+ ],
+ prefix: 'migration-286-',
+ });
+});
diff --git a/scripts/migrations/287-fableloom-table.js b/scripts/migrations/287-fableloom-table.js
new file mode 100644
index 0000000000..b1733ac047
--- /dev/null
+++ b/scripts/migrations/287-fableloom-table.js
@@ -0,0 +1,13 @@
+/**
+ * Registration stub for the fableloom_stories table (FableLoom branching
+ * narratives). The table itself is created idempotently by ensureSchema at
+ * boot (server/lib/db/schema/pipeline.js) — this stub exists so the applied
+ * ledger records when the domain arrived on an install. Mirrors
+ * 212-games-table.js.
+ */
+
+export default {
+ async up() {
+ console.log('🧶 fableloom_stories: table created idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/index.js b/server/index.js
index 8b3dca07e6..f70ae7d54c 100644
--- a/server/index.js
+++ b/server/index.js
@@ -120,6 +120,7 @@ import federatedMediaRoutes from './routes/federatedMedia.js';
import creativeDirectorRoutes from './routes/creativeDirector.js';
import creativeCommissionRoutes from './routes/creativeCommissions.js';
import gamesRoutes from './routes/games.js';
+import fableLoomRoutes from './routes/fableLoom.js';
import musicVideoRoutes from './routes/musicVideo.js';
import spriteRoutes from './routes/sprites.js';
import moodBoardRoutes from './routes/moodBoard.js';
@@ -356,6 +357,7 @@ app.use('/api/federation/media/v1', federatedMediaRoutes);
app.use('/api/creative-director', creativeDirectorRoutes);
app.use('/api/creative-commission', creativeCommissionRoutes);
app.use('/api/games', gamesRoutes);
+app.use('/api/fableloom', fableLoomRoutes);
app.use('/api/music-video', musicVideoRoutes);
app.use('/api/sprites', spriteRoutes);
app.use('/api/mood-boards', moodBoardRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index c87720ba5f..a6bef332a4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -45,6 +45,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `creativeCommissionValidation.js` | Creative Commission (Autonomous Creation Engine) create/update + brief/schedule/generation schemas. Brief field caps are mirrored by the commission form in `client/src/components/creative-commission/commissionForm.js` (parity: `creativeCommissionValidation.mirror.test.js`). |
| `creativeDirectorValidation.js` | Creative Director project/treatment/scene + Create-Suite importer schemas. `CREATIVE_DIRECTOR_GOAL_MAX` is mirrored in `client/src/lib/creativeDirectorPlan.js` (parity: `creativeDirectorValidation.mirror.test.js`). |
| `digitalTwinValidation.js` | Digital twin document/category schemas. |
+| `fableLoomValidation.js` | FableLoom branching-narrative route schemas (loom/episode/node CRUD, weave/branch/review, play turns). |
| `genomeValidation.js` | Genome upload + search schemas. |
| `identityValidation.js` | Identity section + chronotype + scheduling schemas. |
| `meatspaceValidation.js` | Meatspace (location/health log) schemas. |
@@ -70,6 +71,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `editorial/` | Extensible editorial-check registry (#1284) — `EDITORIAL_CHECKS` + fail-fast guards + lookup/state helpers. See `editorial/README.md`. The runner that executes checks lives at `server/services/pipeline/editorial/checkRunner.js`. |
+| `fableLoomGraph.js` | FableLoom branching-narrative graph analysis: `analyzeEpisodeGraph` (deterministic validation — reachability, dead ends, dangling paths, intent hygiene), `computeGraphLayers` (BFS layering), `describeGraphForPrompt` (compact text rendering for LLM stages), `GRAPH_ISSUE_CODES`. |
| `storyBible.js` | Canonical Character / Place / Object shapes + `BIBLE_LIMITS`. Also the reveal-gated canon / spoiler-scoping helpers (#2178): `filterCanonForIssue` / `filterCanonListForIssue` / `isCanonEntryGatedForIssue` (hide or surface-substitute a gated entry in a drafting prompt), `canonHasRevealGated` + `revealGatedCanonRows` (for the `continuity.premature-reveal` check gate/summary). |
| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. |
| `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. |
diff --git a/server/lib/db/schema/audit.js b/server/lib/db/schema/audit.js
index aed157eb24..e645c6b4c8 100644
--- a/server/lib/db/schema/audit.js
+++ b/server/lib/db/schema/audit.js
@@ -89,7 +89,7 @@ export const auditedTables = [
'universes', 'universe_runs', 'pipeline_series', 'pipeline_issues',
'story_builder_sessions', 'writers_room_works', 'writers_room_folders',
'writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',
- 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'games', 'mood_boards',
+ 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'games', 'mood_boards', 'fableloom_stories',
'lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints',
];
diff --git a/server/lib/db/schema/pipeline.js b/server/lib/db/schema/pipeline.js
index 13acfada23..88e02cbc78 100644
--- a/server/lib/db/schema/pipeline.js
+++ b/server/lib/db/schema/pipeline.js
@@ -92,4 +92,22 @@ export const pipelineDdl = [
// mutation epoch. The only thing that stays on disk is the draft prose body
// (drafts/<draftId>.md, file-primary); its metadata is the draft_versions row.
+ // FableLoom branching narratives. One row per loom (a branching-narrative
+ // story), the full sanitized record (episodes, scene-node graphs, intent
+ // transitions) in `data` JSONB. `universe_id`/`series_id` are soft refs
+ // mirrored for relationship queries only. Machine-local like Writers Room —
+ // no dataSync category, no sync cursor, no tombstones; deletes are hard
+ // deletes (games precedent). Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS fableloom_stories (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ universe_id TEXT,
+ series_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_fableloom_universe ON fableloom_stories (universe_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_fableloom_updated ON fableloom_stories (updated_at)`,
+
];
diff --git a/server/lib/fableLoomGraph.js b/server/lib/fableLoomGraph.js
new file mode 100644
index 0000000000..6b423c9071
--- /dev/null
+++ b/server/lib/fableLoomGraph.js
@@ -0,0 +1,177 @@
+/**
+ * FableLoom — pure graph analysis for branching-narrative episodes.
+ *
+ * A FableLoom episode is a directed graph of scene nodes. Each node carries
+ * prose plus a list of intent-triggered transitions (the reader expresses an
+ * intent in free text; the play LLM matches it to a transition). Ending nodes
+ * terminate a read-through. This module holds the deterministic (no-LLM)
+ * validation, traversal, and prompt-rendering helpers shared by the service,
+ * routes, and tests.
+ *
+ * Issue severities: 'error' blocks play (the graph cannot be read through
+ * coherently); 'warning' is an authoring smell the UI surfaces but never
+ * blocks on.
+ */
+
+const asArray = (v) => (Array.isArray(v) ? v : []);
+const isStr = (v) => typeof v === 'string' && v.length > 0;
+
+export const GRAPH_ISSUE_CODES = Object.freeze({
+ MISSING_START: 'MISSING_START',
+ START_NOT_FOUND: 'START_NOT_FOUND',
+ NO_NODES: 'NO_NODES',
+ NO_ENDINGS: 'NO_ENDINGS',
+ UNREACHABLE_NODE: 'UNREACHABLE_NODE',
+ DEAD_END: 'DEAD_END',
+ DANGLING_TRANSITION: 'DANGLING_TRANSITION',
+ ENDING_WITH_TRANSITIONS: 'ENDING_WITH_TRANSITIONS',
+ EMPTY_INTENT: 'EMPTY_INTENT',
+ DUPLICATE_INTENT: 'DUPLICATE_INTENT',
+ ENDING_UNREACHABLE: 'ENDING_UNREACHABLE',
+ SELF_LOOP: 'SELF_LOOP',
+});
+
+/**
+ * Breadth-first layering from the episode's start node. Returns
+ * `{ layers, depthById }` where `layers` is an array of node-id arrays
+ * (layer 0 = start) and `depthById` maps nodeId → BFS depth. Nodes not
+ * reachable from the start are absent from both — callers that need them
+ * (layout, validation) diff against the full node list.
+ */
+export function computeGraphLayers(episode) {
+ const nodes = asArray(episode?.nodes);
+ const byId = new Map(nodes.map((n) => [n.id, n]));
+ const startId = episode?.startNodeId;
+ const layers = [];
+ const depthById = new Map();
+ if (!byId.has(startId)) return { layers, depthById };
+
+ let frontier = [startId];
+ depthById.set(startId, 0);
+ while (frontier.length) {
+ layers.push(frontier);
+ const next = [];
+ for (const id of frontier) {
+ for (const tr of asArray(byId.get(id)?.transitions)) {
+ const target = tr?.targetNodeId;
+ if (byId.has(target) && !depthById.has(target)) {
+ depthById.set(target, layers.length);
+ next.push(target);
+ }
+ }
+ }
+ frontier = next;
+ }
+ return { layers, depthById };
+}
+
+/**
+ * Deterministic structural validation of one episode graph. Returns
+ * `{ issues, stats }`; `issues` entries are
+ * `{ code, severity: 'error'|'warning', message, nodeId?, transitionId? }`.
+ */
+export function analyzeEpisodeGraph(episode) {
+ const nodes = asArray(episode?.nodes);
+ const byId = new Map(nodes.map((n) => [n.id, n]));
+ const issues = [];
+ const push = (code, severity, message, extra = {}) => issues.push({ code, severity, message, ...extra });
+
+ if (!nodes.length) {
+ push(GRAPH_ISSUE_CODES.NO_NODES, 'error', 'The episode has no scenes yet.');
+ }
+ if (!isStr(episode?.startNodeId)) {
+ if (nodes.length) push(GRAPH_ISSUE_CODES.MISSING_START, 'error', 'No opening scene is set.');
+ } else if (nodes.length && !byId.has(episode.startNodeId)) {
+ push(GRAPH_ISSUE_CODES.START_NOT_FOUND, 'error', 'The opening scene points at a scene that no longer exists.');
+ }
+
+ const { depthById } = computeGraphLayers(episode);
+ const endings = nodes.filter((n) => n?.isEnding);
+ if (nodes.length && !endings.length) {
+ push(GRAPH_ISSUE_CODES.NO_ENDINGS, 'error', 'The episode has no endings — every path loops forever.');
+ }
+
+ const reachableEndings = endings.filter((n) => depthById.has(n.id));
+ if (endings.length && depthById.size && !reachableEndings.length) {
+ push(GRAPH_ISSUE_CODES.ENDING_UNREACHABLE, 'error', 'No ending is reachable from the opening scene.');
+ }
+
+ for (const node of nodes) {
+ const transitions = asArray(node?.transitions);
+ const label = node?.title || node?.id;
+
+ if (depthById.size && !depthById.has(node.id)) {
+ push(GRAPH_ISSUE_CODES.UNREACHABLE_NODE, 'warning', `"${label}" cannot be reached from the opening scene.`, { nodeId: node.id });
+ }
+ if (!node?.isEnding && !transitions.length) {
+ push(GRAPH_ISSUE_CODES.DEAD_END, 'error', `"${label}" has no paths out and is not marked as an ending.`, { nodeId: node.id });
+ }
+ if (node?.isEnding && transitions.length) {
+ push(GRAPH_ISSUE_CODES.ENDING_WITH_TRANSITIONS, 'warning', `Ending "${label}" still has outgoing paths — they will never fire.`, { nodeId: node.id });
+ }
+
+ const seenIntents = new Set();
+ for (const tr of transitions) {
+ const intent = typeof tr?.intent === 'string' ? tr.intent.trim().toLowerCase() : '';
+ if (!intent) {
+ push(GRAPH_ISSUE_CODES.EMPTY_INTENT, 'error', `A path out of "${label}" has no intent label.`, { nodeId: node.id, transitionId: tr?.id });
+ } else if (seenIntents.has(intent)) {
+ push(GRAPH_ISSUE_CODES.DUPLICATE_INTENT, 'warning', `"${label}" has two paths with the intent "${tr.intent}".`, { nodeId: node.id, transitionId: tr?.id });
+ } else {
+ seenIntents.add(intent);
+ }
+ if (!byId.has(tr?.targetNodeId)) {
+ push(GRAPH_ISSUE_CODES.DANGLING_TRANSITION, 'error', `A path out of "${label}" points at a scene that no longer exists.`, { nodeId: node.id, transitionId: tr?.id });
+ } else if (tr.targetNodeId === node.id) {
+ push(GRAPH_ISSUE_CODES.SELF_LOOP, 'warning', `"${label}" has a path that loops straight back to itself.`, { nodeId: node.id, transitionId: tr?.id });
+ }
+ }
+ }
+
+ const transitionCounts = nodes.map((n) => asArray(n?.transitions).length);
+ const branchingNodes = transitionCounts.filter((c) => c > 0);
+ const stats = {
+ nodeCount: nodes.length,
+ endingCount: endings.length,
+ reachableCount: depthById.size,
+ reachableEndingCount: reachableEndings.length,
+ maxDepth: depthById.size ? Math.max(...depthById.values()) : 0,
+ avgBranching: branchingNodes.length
+ ? Math.round((branchingNodes.reduce((a, b) => a + b, 0) / branchingNodes.length) * 10) / 10
+ : 0,
+ errorCount: issues.filter((i) => i.severity === 'error').length,
+ warningCount: issues.filter((i) => i.severity === 'warning').length,
+ };
+ return { issues, stats };
+}
+
+/**
+ * Render an episode graph as compact text for LLM prompts (generation context,
+ * play turns, and the story review). One block per node:
+ *
+ * [n1] Title (START) (ENDING: label)
+ * prose…
+ * -> [n2] intent "search the wreck" (triggers: poke around; investigate)
+ *
+ * `proseLimit` truncates each node's prose so a large graph stays inside the
+ * stage's context window.
+ */
+export function describeGraphForPrompt(episode, { proseLimit = 400 } = {}) {
+ const nodes = asArray(episode?.nodes);
+ const lines = [];
+ for (const node of nodes) {
+ const flags = [
+ node.id === episode?.startNodeId ? 'START' : null,
+ node?.isEnding ? `ENDING${isStr(node?.endingLabel) ? `: ${node.endingLabel}` : ''}` : null,
+ ].filter(Boolean);
+ lines.push(`[${node.id}] ${node.title || 'Untitled scene'}${flags.length ? ` (${flags.join(') (')})` : ''}`);
+ const prose = typeof node.prose === 'string' ? node.prose.trim() : '';
+ if (prose) lines.push(prose.length > proseLimit ? `${prose.slice(0, proseLimit)}…` : prose);
+ for (const tr of asArray(node.transitions)) {
+ const triggers = asArray(tr?.triggers).filter(isStr);
+ lines.push(`-> [${tr?.targetNodeId}] intent "${tr?.intent || ''}"${triggers.length ? ` (triggers: ${triggers.join('; ')})` : ''}`);
+ }
+ lines.push('');
+ }
+ return lines.join('\n').trim();
+}
diff --git a/server/lib/fableLoomGraph.test.js b/server/lib/fableLoomGraph.test.js
new file mode 100644
index 0000000000..612f4eb237
--- /dev/null
+++ b/server/lib/fableLoomGraph.test.js
@@ -0,0 +1,154 @@
+import { describe, it, expect } from 'vitest';
+import {
+ GRAPH_ISSUE_CODES,
+ analyzeEpisodeGraph,
+ computeGraphLayers,
+ describeGraphForPrompt,
+} from './fableLoomGraph.js';
+
+const tr = (id, targetNodeId, intent, triggers = []) => ({ id, targetNodeId, intent, triggers });
+
+// A small sound graph: start branches into two paths, one loops back once,
+// both reach distinct endings.
+const soundEpisode = () => ({
+ id: 'ep-1',
+ startNodeId: 'n1',
+ nodes: [
+ { id: 'n1', title: 'The Gate', prose: 'You stand before the gate.', transitions: [tr('t1', 'n2', 'enter the gate'), tr('t2', 'n3', 'walk away')] },
+ { id: 'n2', title: 'Inside', prose: 'Torchlight.', transitions: [tr('t3', 'n4', 'press on'), tr('t4', 'n1', 'retreat')] },
+ { id: 'n3', title: 'The Road Home', prose: 'Dust and regret.', isEnding: true, endingLabel: 'Turned back', transitions: [] },
+ { id: 'n4', title: 'The Vault', prose: 'Gold everywhere.', isEnding: true, endingLabel: 'Treasure found', transitions: [] },
+ ],
+});
+
+const issueCodes = (episode) => analyzeEpisodeGraph(episode).issues.map((i) => i.code);
+
+describe('computeGraphLayers', () => {
+ it('layers nodes by BFS depth from the start node', () => {
+ const { layers, depthById } = computeGraphLayers(soundEpisode());
+ expect(layers[0]).toEqual(['n1']);
+ expect(layers[1]).toEqual(['n2', 'n3']);
+ expect(layers[2]).toEqual(['n4']);
+ expect(depthById.get('n4')).toBe(2);
+ });
+
+ it('returns empty layers when the start node is missing', () => {
+ const ep = soundEpisode();
+ ep.startNodeId = 'nope';
+ const { layers, depthById } = computeGraphLayers(ep);
+ expect(layers).toEqual([]);
+ expect(depthById.size).toBe(0);
+ });
+
+ it('omits unreachable nodes', () => {
+ const ep = soundEpisode();
+ ep.nodes.push({ id: 'n9', title: 'Orphan', isEnding: true, transitions: [] });
+ const { depthById } = computeGraphLayers(ep);
+ expect(depthById.has('n9')).toBe(false);
+ });
+});
+
+describe('analyzeEpisodeGraph', () => {
+ it('reports a sound graph clean with accurate stats', () => {
+ const { issues, stats } = analyzeEpisodeGraph(soundEpisode());
+ expect(issues).toEqual([]);
+ expect(stats).toMatchObject({
+ nodeCount: 4,
+ endingCount: 2,
+ reachableCount: 4,
+ reachableEndingCount: 2,
+ maxDepth: 2,
+ errorCount: 0,
+ warningCount: 0,
+ });
+ });
+
+ it('flags an empty episode', () => {
+ expect(issueCodes({ id: 'ep', nodes: [] })).toContain(GRAPH_ISSUE_CODES.NO_NODES);
+ });
+
+ it('flags a missing start pointer and a start pointing at a deleted node', () => {
+ const noStart = soundEpisode();
+ delete noStart.startNodeId;
+ expect(issueCodes(noStart)).toContain(GRAPH_ISSUE_CODES.MISSING_START);
+
+ const badStart = soundEpisode();
+ badStart.startNodeId = 'gone';
+ expect(issueCodes(badStart)).toContain(GRAPH_ISSUE_CODES.START_NOT_FOUND);
+ });
+
+ it('flags a graph with no endings as an error', () => {
+ const ep = soundEpisode();
+ for (const n of ep.nodes) n.isEnding = false;
+ ep.nodes[2].transitions = [tr('t9', 'n1', 'go back')];
+ ep.nodes[3].transitions = [tr('t10', 'n1', 'go back')];
+ expect(issueCodes(ep)).toContain(GRAPH_ISSUE_CODES.NO_ENDINGS);
+ });
+
+ it('flags a non-ending node with no way out as a dead end', () => {
+ const ep = soundEpisode();
+ ep.nodes[3].isEnding = false;
+ const { issues } = analyzeEpisodeGraph(ep);
+ const deadEnd = issues.find((i) => i.code === GRAPH_ISSUE_CODES.DEAD_END);
+ expect(deadEnd).toMatchObject({ severity: 'error', nodeId: 'n4' });
+ });
+
+ it('warns on unreachable nodes and errors when no ending is reachable', () => {
+ const ep = soundEpisode();
+ ep.nodes.push({ id: 'n9', title: 'Orphan', transitions: [tr('t9', 'n4', 'onward')] });
+ const codes = issueCodes(ep);
+ expect(codes).toContain(GRAPH_ISSUE_CODES.UNREACHABLE_NODE);
+
+ // Cut both endings off from the start: n1 only reaches n2, which only loops back.
+ const cut = soundEpisode();
+ cut.nodes[0].transitions = [tr('t1', 'n2', 'enter')];
+ cut.nodes[1].transitions = [tr('t4', 'n1', 'retreat')];
+ expect(issueCodes(cut)).toContain(GRAPH_ISSUE_CODES.ENDING_UNREACHABLE);
+ });
+
+ it('errors on transitions pointing at deleted nodes and empty intents', () => {
+ const ep = soundEpisode();
+ ep.nodes[0].transitions.push(tr('t9', 'gone', 'leap into the void'));
+ ep.nodes[1].transitions.push(tr('t10', 'n4', ' '));
+ const codes = issueCodes(ep);
+ expect(codes).toContain(GRAPH_ISSUE_CODES.DANGLING_TRANSITION);
+ expect(codes).toContain(GRAPH_ISSUE_CODES.EMPTY_INTENT);
+ });
+
+ it('warns on duplicate intents, self-loops, and endings with outgoing paths', () => {
+ const ep = soundEpisode();
+ ep.nodes[0].transitions.push(tr('t9', 'n2', 'Enter The Gate')); // dup of t1, case-insensitive
+ ep.nodes[1].transitions.push(tr('t10', 'n2', 'linger')); // self-loop
+ ep.nodes[2].transitions = [tr('t11', 'n1', 'change of heart')]; // ending with a way out
+ const codes = issueCodes(ep);
+ expect(codes).toContain(GRAPH_ISSUE_CODES.DUPLICATE_INTENT);
+ expect(codes).toContain(GRAPH_ISSUE_CODES.SELF_LOOP);
+ expect(codes).toContain(GRAPH_ISSUE_CODES.ENDING_WITH_TRANSITIONS);
+ const { stats } = analyzeEpisodeGraph(ep);
+ expect(stats.errorCount).toBe(0);
+ expect(stats.warningCount).toBe(3);
+ });
+});
+
+describe('describeGraphForPrompt', () => {
+ it('renders nodes with flags, prose, and intent lines', () => {
+ const text = describeGraphForPrompt(soundEpisode());
+ expect(text).toContain('[n1] The Gate (START)');
+ expect(text).toContain('[n4] The Vault (ENDING: Treasure found)');
+ expect(text).toContain('-> [n2] intent "enter the gate"');
+ });
+
+ it('truncates long prose at proseLimit', () => {
+ const ep = soundEpisode();
+ ep.nodes[0].prose = 'x'.repeat(500);
+ const text = describeGraphForPrompt(ep, { proseLimit: 100 });
+ expect(text).toContain(`${'x'.repeat(100)}…`);
+ expect(text).not.toContain('x'.repeat(101));
+ });
+
+ it('includes trigger examples', () => {
+ const ep = soundEpisode();
+ ep.nodes[0].transitions[0].triggers = ['go in', 'open the gate'];
+ expect(describeGraphForPrompt(ep)).toContain('(triggers: go in; open the gate)');
+ });
+});
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
new file mode 100644
index 0000000000..900747e605
--- /dev/null
+++ b/server/lib/fableLoomValidation.js
@@ -0,0 +1,104 @@
+/**
+ * Zod schemas for the FableLoom routes. Length caps mirror LOOM_LIMITS in
+ * server/services/fableLoom/records.js — the sanitizer is the enforcement
+ * layer; these reject obviously-oversized payloads at the door.
+ */
+
+import { z } from 'zod';
+
+const name = z.string().trim().min(1).max(200);
+const logline = z.string().max(500);
+const premise = z.string().max(20000);
+const styleNotes = z.string().max(4000);
+const refId = z.string().max(64).nullable();
+const title = z.string().max(300);
+const synopsis = z.string().max(4000);
+const nodeIdStr = z.string().min(1).max(80);
+
+export const loomCreateSchema = z.object({
+ name,
+ logline: logline.optional(),
+ premise: premise.optional(),
+ styleNotes: styleNotes.optional(),
+ universeId: refId.optional(),
+ seriesId: refId.optional(),
+});
+
+export const loomPatchSchema = z.object({
+ name: name.optional(),
+ logline: logline.optional(),
+ premise: premise.optional(),
+ styleNotes: styleNotes.optional(),
+ universeId: refId.optional(),
+ seriesId: refId.optional(),
+});
+
+export const episodeCreateSchema = z.object({
+ title: title.optional(),
+ synopsis: synopsis.optional(),
+});
+
+export const episodePatchSchema = z.object({
+ title: title.optional(),
+ synopsis: synopsis.optional(),
+ number: z.number().int().min(1).max(9999).optional(),
+ startNodeId: nodeIdStr.nullable().optional(),
+});
+
+const transitionSchema = z.object({
+ id: z.string().max(80).optional(),
+ targetNodeId: nodeIdStr,
+ intent: z.string().max(120),
+ triggers: z.array(z.string().max(160)).max(8).optional(),
+ description: z.string().max(500).optional(),
+});
+
+const nodeFields = {
+ title: title.optional(),
+ prose: z.string().max(20000).optional(),
+ imagePrompt: z.string().max(2000).optional(),
+ isEnding: z.boolean().optional(),
+ endingLabel: z.string().max(200).optional(),
+ pos: z.object({ x: z.number(), y: z.number() }).nullable().optional(),
+ transitions: z.array(transitionSchema).max(12).optional(),
+};
+
+export const nodeCreateSchema = z.object({
+ ...nodeFields,
+ // Optionally wire the new scene in as a branch of an existing one.
+ fromNodeId: nodeIdStr.optional(),
+ fromIntent: z.string().max(120).optional(),
+});
+
+export const nodePatchSchema = z.object(nodeFields);
+
+const llmPickFields = {
+ providerId: z.string().max(100).optional(),
+ model: z.string().max(200).optional(),
+};
+
+export const weaveSchema = z.object({
+ guidance: z.string().max(4000).optional(),
+ nodeTarget: z.number().int().min(3).max(60).optional(),
+ endingTarget: z.number().int().min(1).max(12).optional(),
+ replace: z.boolean().optional(),
+ ...llmPickFields,
+});
+
+export const branchSchema = z.object({
+ guidance: z.string().max(4000).optional(),
+ branchCount: z.number().int().min(1).max(4).optional(),
+ ...llmPickFields,
+});
+
+export const reviewSchema = z.object({ ...llmPickFields });
+
+export const playTurnSchema = z.object({
+ nodeId: nodeIdStr,
+ message: z.string().min(1).max(1000),
+ transcript: z.array(z.object({
+ role: z.enum(['reader', 'narrator']),
+ text: z.string().max(4000),
+ })).max(50).optional(),
+ ...llmPickFields,
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 47a0189c65..b911d5f6b0 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -25,6 +25,7 @@ export * as cosValidation from './cosValidation.js';
export * as creativeCommissionValidation from './creativeCommissionValidation.js';
export * as creativeDirectorValidation from './creativeDirectorValidation.js';
export * as digitalTwinValidation from './digitalTwinValidation.js';
+export * as fableLoomValidation from './fableLoomValidation.js';
export * as genomeValidation from './genomeValidation.js';
export * as identityValidation from './identityValidation.js';
export * as meatspaceValidation from './meatspaceValidation.js';
@@ -74,6 +75,7 @@ export * from './creativeDirectorPrompts.js';
// subdir with its own barrel — surface it under `editorial.*` so the root
// discovery surface reaches EDITORIAL_CHECKS + the lookup helpers.
export * as editorial from './editorial/index.js';
+export * from './fableLoomGraph.js';
export * from './sceneExtractor.js';
export * from './scenePrompt.js';
export * from './proseExportSettings.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index c7c0ce4f56..2095f5d8b9 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -75,6 +75,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
{ id: 'nav.create.creative-director', path: '/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'producer', 'orchestrator', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form', 'directive', 'production plan', 'plan board', 'orchestrator', 'studio', 'producer'] },
{ id: 'nav.create.creative-commission', path: '/creative-commission', label: 'Creative Commissions', section: 'Create', aliases: ['creative-commission', 'commissions', 'commission', 'creation-engine', 'autonomous-creation', 'standing-brief', 'recurring-brief'], keywords: ['schedule', 'recurring', 'nightly', 'brief', 'autonomous', 'creation engine', 'cron', 'feedback', 'taste', 'standing commission', 'auto-generate'] },
+ { id: 'nav.create.fableloom', path: '/fableloom', label: 'FableLoom', section: 'Create', aliases: ['fableloom', 'fable-loom', 'loom', 'branching-narrative', 'interactive-story', 'branching-story'], keywords: ['branching', 'interactive', 'narrative', 'intent', 'endings', 'reader', 'scene', 'node', 'graph', 'nonlinear', 'play', 'story graph'] },
{ id: 'nav.create.game', path: '/game', label: 'Game', section: 'Create', aliases: ['game', 'games', 'game-studio'], keywords: ['managed app', 'sprite', 'atlas', 'music', 'asset bundle', 'manifest', 'feedback'] },
{ id: 'nav.create.music-video', path: '/music-video', label: 'Music Video', section: 'Create', aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography'] },
{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
new file mode 100644
index 0000000000..28b7bb2f5b
--- /dev/null
+++ b/server/routes/fableLoom.js
@@ -0,0 +1,149 @@
+/**
+ * FableLoom REST surface — branching narratives.
+ *
+ * CRUD for looms/episodes/nodes plus the AI lanes (weave/branch/review/play)
+ * and the deterministic graph validation. Every AI endpoint is a direct
+ * user action in the same request (AI Provider Usage Policy). Scene images
+ * ride the existing `/api/image-gen/generate` queue with a `fableLoom`
+ * destination tag — there is no image endpoint here.
+ */
+
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import {
+ branchSchema,
+ episodeCreateSchema,
+ episodePatchSchema,
+ loomCreateSchema,
+ loomPatchSchema,
+ nodeCreateSchema,
+ nodePatchSchema,
+ playTurnSchema,
+ reviewSchema,
+ weaveSchema,
+} from '../lib/fableLoomValidation.js';
+import { analyzeEpisodeGraph } from '../lib/fableLoomGraph.js';
+import {
+ addEpisode,
+ addNode,
+ branchNode,
+ createLoom,
+ deleteEpisode,
+ deleteLoom,
+ deleteNode,
+ getLoom,
+ listLooms,
+ playTurn,
+ reviewEpisode,
+ updateEpisode,
+ updateLoom,
+ updateNode,
+ weaveEpisode,
+} from '../services/fableLoom/index.js';
+import { getUniverse } from '../services/universeBuilder.js';
+import { getSeries } from '../services/pipeline/series.js';
+
+const router = Router();
+
+// Soft refs are validated at write time so a typo'd id fails loudly here
+// rather than silently producing an empty canon digest at weave time.
+async function assertRefsExist({ universeId, seriesId }) {
+ if (universeId && !(await getUniverse(universeId).catch(() => null))) {
+ throw new ServerError('Linked universe not found', { status: 400, code: 'INVALID_UNIVERSE' });
+ }
+ if (seriesId && !(await getSeries(seriesId).catch(() => null))) {
+ throw new ServerError('Linked series not found', { status: 400, code: 'INVALID_SERIES' });
+ }
+}
+
+router.get('/', asyncHandler(async (req, res) => {
+ res.json(await listLooms());
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const input = validateRequest(loomCreateSchema, req.body);
+ await assertRefsExist(input);
+ res.status(201).json(await createLoom(input));
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ const loom = await getLoom(req.params.id);
+ if (!loom) throw new ServerError('Loom not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(loom);
+}));
+
+router.patch('/:id', asyncHandler(async (req, res) => {
+ const patch = validateRequest(loomPatchSchema, req.body);
+ await assertRefsExist(patch);
+ res.json(await updateLoom(req.params.id, patch));
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ await deleteLoom(req.params.id);
+ res.json({ ok: true });
+}));
+
+// --- Episodes ---------------------------------------------------------------
+
+router.post('/:id/episodes', asyncHandler(async (req, res) => {
+ const input = validateRequest(episodeCreateSchema, req.body);
+ res.status(201).json(await addEpisode(req.params.id, input));
+}));
+
+router.patch('/:id/episodes/:episodeId', asyncHandler(async (req, res) => {
+ const patch = validateRequest(episodePatchSchema, req.body);
+ res.json(await updateEpisode(req.params.id, req.params.episodeId, patch));
+}));
+
+router.delete('/:id/episodes/:episodeId', asyncHandler(async (req, res) => {
+ res.json(await deleteEpisode(req.params.id, req.params.episodeId));
+}));
+
+// Deterministic graph validation — no LLM.
+router.get('/:id/episodes/:episodeId/validate', asyncHandler(async (req, res) => {
+ const loom = await getLoom(req.params.id);
+ const episode = loom?.episodes.find((e) => e.id === req.params.episodeId);
+ if (!episode) throw new ServerError('Episode not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(analyzeEpisodeGraph(episode));
+}));
+
+// --- Nodes ------------------------------------------------------------------
+
+router.post('/:id/episodes/:episodeId/nodes', asyncHandler(async (req, res) => {
+ const input = validateRequest(nodeCreateSchema, req.body);
+ res.status(201).json(await addNode(req.params.id, req.params.episodeId, input));
+}));
+
+router.patch('/:id/episodes/:episodeId/nodes/:nodeId', asyncHandler(async (req, res) => {
+ const patch = validateRequest(nodePatchSchema, req.body);
+ res.json(await updateNode(req.params.id, req.params.episodeId, req.params.nodeId, patch));
+}));
+
+router.delete('/:id/episodes/:episodeId/nodes/:nodeId', asyncHandler(async (req, res) => {
+ res.json(await deleteNode(req.params.id, req.params.episodeId, req.params.nodeId));
+}));
+
+// --- AI lanes ---------------------------------------------------------------
+
+router.post('/:id/episodes/:episodeId/weave', asyncHandler(async (req, res) => {
+ const input = validateRequest(weaveSchema, req.body);
+ res.json(await weaveEpisode(req.params.id, req.params.episodeId, input));
+}));
+
+router.post('/:id/episodes/:episodeId/nodes/:nodeId/branch', asyncHandler(async (req, res) => {
+ const input = validateRequest(branchSchema, req.body);
+ res.json(await branchNode(req.params.id, req.params.episodeId, req.params.nodeId, input));
+}));
+
+router.post('/:id/episodes/:episodeId/review', asyncHandler(async (req, res) => {
+ const input = validateRequest(reviewSchema, req.body);
+ res.json(await reviewEpisode(req.params.id, req.params.episodeId, input));
+}));
+
+router.post('/:id/episodes/:episodeId/play', asyncHandler(async (req, res) => {
+ const input = validateRequest(playTurnSchema, req.body);
+ res.json(await playTurn(req.params.id, req.params.episodeId, input));
+}));
+
+export default router;
diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.js
new file mode 100644
index 0000000000..705a972e8b
--- /dev/null
+++ b/server/routes/fableLoom.test.js
@@ -0,0 +1,150 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { request } from '../lib/testHelper.js';
+
+vi.mock('../services/fableLoom/index.js', () => ({
+ addEpisode: vi.fn(),
+ addNode: vi.fn(),
+ branchNode: vi.fn(),
+ createLoom: vi.fn(),
+ deleteEpisode: vi.fn(),
+ deleteLoom: vi.fn(),
+ deleteNode: vi.fn(),
+ getLoom: vi.fn(),
+ listLooms: vi.fn(async () => []),
+ playTurn: vi.fn(),
+ reviewEpisode: vi.fn(),
+ updateEpisode: vi.fn(),
+ updateLoom: vi.fn(),
+ updateNode: vi.fn(),
+ weaveEpisode: vi.fn(),
+}));
+vi.mock('../services/universeBuilder.js', () => ({ getUniverse: vi.fn() }));
+vi.mock('../services/pipeline/series.js', () => ({ getSeries: vi.fn() }));
+
+import * as fableLoom from '../services/fableLoom/index.js';
+import { getUniverse } from '../services/universeBuilder.js';
+import { getSeries } from '../services/pipeline/series.js';
+import routes from './fableLoom.js';
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/fableloom', routes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+describe('FableLoom routes', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('GET / lists looms', async () => {
+ fableLoom.listLooms.mockResolvedValueOnce([{ id: 'loom-1', name: 'X' }]);
+ const response = await request(makeApp()).get('/api/fableloom');
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual([{ id: 'loom-1', name: 'X' }]);
+ });
+
+ it('POST / validates linked refs before creating', async () => {
+ getUniverse.mockResolvedValueOnce(null);
+ const missing = await request(makeApp())
+ .post('/api/fableloom')
+ .send({ name: 'X', universeId: 'uni-gone' });
+ expect(missing.status).toBe(400);
+ expect(missing.body.code).toBe('INVALID_UNIVERSE');
+ expect(fableLoom.createLoom).not.toHaveBeenCalled();
+
+ getUniverse.mockResolvedValueOnce({ id: 'uni-1' });
+ getSeries.mockResolvedValueOnce({ id: 'ser-1' });
+ fableLoom.createLoom.mockResolvedValueOnce({ id: 'loom-1', name: 'X' });
+ const created = await request(makeApp())
+ .post('/api/fableloom')
+ .send({ name: 'X', universeId: 'uni-1', seriesId: 'ser-1' });
+ expect(created.status).toBe(201);
+ expect(fableLoom.createLoom).toHaveBeenCalledWith({ name: 'X', universeId: 'uni-1', seriesId: 'ser-1' });
+ });
+
+ it('POST / rejects a missing name', async () => {
+ const response = await request(makeApp()).post('/api/fableloom').send({});
+ expect(response.status).toBe(400);
+ expect(fableLoom.createLoom).not.toHaveBeenCalled();
+ });
+
+ it('GET /:id 404s on a missing loom', async () => {
+ fableLoom.getLoom.mockResolvedValueOnce(null);
+ const response = await request(makeApp()).get('/api/fableloom/loom-gone');
+ expect(response.status).toBe(404);
+ });
+
+ it('PATCH /:id forwards only provided fields', async () => {
+ fableLoom.updateLoom.mockResolvedValueOnce({ id: 'loom-1', name: 'Y' });
+ const response = await request(makeApp())
+ .patch('/api/fableloom/loom-1')
+ .send({ name: 'Y' });
+ expect(response.status).toBe(200);
+ expect(fableLoom.updateLoom).toHaveBeenCalledWith('loom-1', { name: 'Y' });
+ // No refs in the patch → no existence lookups.
+ expect(getUniverse).not.toHaveBeenCalled();
+ expect(getSeries).not.toHaveBeenCalled();
+ });
+
+ it('episode + node CRUD dispatches with route params', async () => {
+ fableLoom.addEpisode.mockResolvedValueOnce({ id: 'loom-1' });
+ await request(makeApp()).post('/api/fableloom/loom-1/episodes').send({ title: 'Pilot' });
+ expect(fableLoom.addEpisode).toHaveBeenCalledWith('loom-1', { title: 'Pilot' });
+
+ fableLoom.updateNode.mockResolvedValueOnce({ id: 'loom-1' });
+ await request(makeApp())
+ .patch('/api/fableloom/loom-1/episodes/ep-1/nodes/node-1')
+ .send({ prose: 'New prose' });
+ expect(fableLoom.updateNode).toHaveBeenCalledWith('loom-1', 'ep-1', 'node-1', { prose: 'New prose' });
+
+ fableLoom.deleteNode.mockResolvedValueOnce({ id: 'loom-1' });
+ await request(makeApp()).delete('/api/fableloom/loom-1/episodes/ep-1/nodes/node-1');
+ expect(fableLoom.deleteNode).toHaveBeenCalledWith('loom-1', 'ep-1', 'node-1');
+ });
+
+ it('GET validate runs the deterministic analysis on the episode', async () => {
+ fableLoom.getLoom.mockResolvedValueOnce({
+ id: 'loom-1',
+ episodes: [{ id: 'ep-1', startNodeId: 'n1', nodes: [{ id: 'n1', isEnding: true, transitions: [] }] }],
+ });
+ const response = await request(makeApp()).get('/api/fableloom/loom-1/episodes/ep-1/validate');
+ expect(response.status).toBe(200);
+ expect(response.body.stats.nodeCount).toBe(1);
+ expect(response.body.issues).toEqual([]);
+ });
+
+ it('POST weave validates bounds and forwards options', async () => {
+ const invalid = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/weave')
+ .send({ nodeTarget: 999 });
+ expect(invalid.status).toBe(400);
+ expect(fableLoom.weaveEpisode).not.toHaveBeenCalled();
+
+ fableLoom.weaveEpisode.mockResolvedValueOnce({ loom: { id: 'loom-1' }, runId: 'r' });
+ const ok = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/weave')
+ .send({ guidance: 'darker', replace: true });
+ expect(ok.status).toBe(200);
+ expect(fableLoom.weaveEpisode).toHaveBeenCalledWith('loom-1', 'ep-1', { guidance: 'darker', replace: true });
+ });
+
+ it('POST play requires a nodeId and message', async () => {
+ const invalid = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/play')
+ .send({ message: 'hello' });
+ expect(invalid.status).toBe(400);
+ expect(fableLoom.playTurn).not.toHaveBeenCalled();
+
+ fableLoom.playTurn.mockResolvedValueOnce({ action: 'stay' });
+ const ok = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/play')
+ .send({ nodeId: 'node-1', message: 'open the gate', transcript: [{ role: 'reader', text: 'hi' }] });
+ expect(ok.status).toBe(200);
+ expect(fableLoom.playTurn).toHaveBeenCalledWith('loom-1', 'ep-1', {
+ nodeId: 'node-1', message: 'open the gate', transcript: [{ role: 'reader', text: 'hi' }],
+ });
+ });
+});
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 598ecd7334..0e823693f0 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -157,6 +157,17 @@ const generateSchema = z.object({
analysisId: z.string().min(1).max(200),
sceneId: z.string().min(1).max(200),
}).optional(),
+ // FableLoom scene render. When present, the mediaJobQueue completion hook
+ // (`fableLoomSceneImageHook`) files the finished render onto that loom
+ // episode's scene node — durably, even if the editor unmounted mid-render.
+ // Only the async local/Codex lanes ride the queue; the synchronous external
+ // SD-API lane returns the filename inline and the client PATCHes the node.
+ // Rides into job.params untouched via `...params`. JSON-only.
+ fableLoom: z.object({
+ loomId: z.string().min(1).max(200),
+ episodeId: z.string().min(1).max(200),
+ nodeId: z.string().min(1).max(200),
+ }).optional(),
// Music Video scene reference-frame render (#1760 Phase 1b). When present, the
// mediaJobQueue completion hook (`musicVideoSceneImageHook`) files the finished
// render onto the project scene's `referenceImageId` — durably, even if the
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index a201d4b0f0..51c42f8e77 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1156,6 +1156,25 @@ CREATE TABLE IF NOT EXISTS writers_room_exercises (
);
CREATE INDEX IF NOT EXISTS idx_wr_exercises_work ON writers_room_exercises (work_id, started_at DESC);
+-- FableLoom branching narratives. One row per loom (a branching-narrative
+-- story), the full sanitized record (episodes, scene-node graphs, intent
+-- transitions) in `data` JSONB. `universe_id`/`series_id` are soft refs
+-- mirrored for relationship queries only. Machine-local like Writers Room —
+-- no dataSync category, no sync cursor, no tombstones; deletes are hard
+-- deletes (games precedent). Mirrors the fableloom_stories block in
+-- db/schema/pipeline.js.
+CREATE TABLE IF NOT EXISTS fableloom_stories (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ universe_id TEXT,
+ series_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_fableloom_universe ON fableloom_stories (universe_id);
+CREATE INDEX IF NOT EXISTS idx_fableloom_updated ON fableloom_stories (updated_at);
+
-- LoRA training runs (character LoRA training, /api/lora-training). One row
-- per run: id/status/character_id mirrored as columns for filtering, the
-- full record in `data` JSONB. Machine-local — no sync cursor/tombstones
@@ -1649,6 +1668,8 @@ DROP TRIGGER IF EXISTS trg_sprite_records_audit ON sprite_records;
CREATE TRIGGER trg_sprite_records_audit AFTER UPDATE OR DELETE ON sprite_records FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_games_audit ON games;
CREATE TRIGGER trg_games_audit AFTER UPDATE OR DELETE ON games FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+DROP TRIGGER IF EXISTS trg_fableloom_stories_audit ON fableloom_stories;
+CREATE TRIGGER trg_fableloom_stories_audit AFTER UPDATE OR DELETE ON fableloom_stories FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_mood_boards_audit ON mood_boards;
CREATE TRIGGER trg_mood_boards_audit AFTER UPDATE OR DELETE ON mood_boards FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 9145e8c283..415ec3beb9 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -117,6 +117,7 @@ import { initMortalLoomStore } from './mortalLoomStore.js';
import { initUniverseBuilderCollectionHook } from './universeBuilderCollectionHook.js';
import { initCatalogImageAttachHook } from './catalogImageAttachHook.js';
import { initWritersRoomSceneImageHook } from './writersRoomSceneImageHook.js';
+import { initFableLoomSceneImageHook } from './fableLoomSceneImageHook.js';
import { initMusicVideoSceneImageHook } from './musicVideoSceneImageHook.js';
import { initMusicVideoSceneVideoHook } from './musicVideoSceneVideoHook.js';
import { initCreativeDirectorMusicBedHook } from './creativeDirectorMusicBedHook.js';
@@ -477,6 +478,9 @@ const initMediaJobDependentHooks = () => {
// Writers-Room scene-image hook — durably files a queued storyboard render
// onto its analysis snapshot + work collection on completion (#1363).
initWritersRoomSceneImageHook();
+ // FableLoom scene-image hook — durably files a queued scene render onto its
+ // loom episode's node on completion, even if the editor unmounted mid-render.
+ initFableLoomSceneImageHook();
// Music Video scene-image hook — durably files a queued reference-frame
// render onto its project scene's `referenceImageId` on completion, even if
// the director board unmounted mid-render (#1760 Phase 1b).
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 8c05d31e36..3fc01149bf 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -64,6 +64,7 @@ export const CATEGORIES = {
'creative-commissions': { label: 'Creative Commissions', description: 'Commission records (file mirror of the Postgres store)', archivable: true, deletable: false },
'db-dumps': { label: 'DB Dumps', description: 'PostgreSQL database backups', archivable: true, deletable: true, purgeScope: 'category' },
'digital-twin': { label: 'Digital Twin', description: 'Identity, goals, character data', archivable: true, deletable: false },
+ 'fableloom': { label: 'FableLoom', description: 'Branching-narrative records (file mirror of the Postgres store)', archivable: true, deletable: false },
'games': { label: 'Games', description: 'Game project records and assets', archivable: true, deletable: false },
'health': { label: 'Apple Health', description: 'Daily health JSON snapshots', archivable: true, deletable: false },
'image-clean-tmp': { label: 'Image Cleaner Scratch', description: 'Ephemeral working files for Image Cleaner renders — swept automatically, safe to purge when no render is in flight', archivable: false, deletable: true, purgeScope: 'category', busyCheck: imageCleanTmpBusy },
diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.md
new file mode 100644
index 0000000000..c9abf79496
--- /dev/null
+++ b/server/services/fableLoom/README.md
@@ -0,0 +1,16 @@
+# server/services/fableLoom
+
+FableLoom — branching narratives. A loom holds episodes; each episode is a
+directed graph of scene nodes with intent-triggered transitions. Readers play
+an episode through a chat conversation: the play stage matches their free-text
+intent to a transition and moves them through the graph until an ending.
+
+| Module | Purpose |
+|---|---|
+| `records.js` | Sanitizer + CRUD for looms/episodes/nodes/transitions; `attachNodeImage` for the media-job hook. |
+| `weave.js` | AI ops via `runStagedLLM`: `weaveEpisode` (full graph), `branchNode` (grow paths), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition). |
+| `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). |
+| `db.js` | PostgreSQL leaf I/O. |
+
+Pure graph analysis (validation, BFS layering, prompt rendering) lives in
+`server/lib/fableLoomGraph.js`. Machine-local — no federation.
diff --git a/server/services/fableLoom/db.js b/server/services/fableLoom/db.js
new file mode 100644
index 0000000000..a8cb5cc172
--- /dev/null
+++ b/server/services/fableLoom/db.js
@@ -0,0 +1,40 @@
+/**
+ * PostgreSQL leaf I/O for FableLoom records. The full sanitized record lives
+ * in JSONB; name/universe_id/series_id/updated_at are mirrored for the common
+ * list/filter paths.
+ */
+
+import { query } from '../../lib/db.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+
+export async function readRaw(id) {
+ const { rows } = await query('SELECT data FROM fableloom_stories WHERE id = $1', [id]);
+ return rows[0]?.data ?? null;
+}
+
+export async function listRaw() {
+ const { rows } = await query('SELECT data FROM fableloom_stories ORDER BY updated_at DESC, id ASC');
+ return rows.map((row) => row.data);
+}
+
+export async function writeRaw(id, record) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record?.createdAt, now);
+ const updatedAt = mirrorTimestamp(record?.updatedAt, createdAt);
+ await query(
+ `INSERT INTO fableloom_stories (id, name, universe_id, series_id, data, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
+ ON CONFLICT (id) DO UPDATE SET
+ name = EXCLUDED.name,
+ universe_id = EXCLUDED.universe_id,
+ series_id = EXCLUDED.series_id,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at`,
+ [id, record.name, record.universeId ?? null, record.seriesId ?? null, JSON.stringify(record), createdAt, updatedAt],
+ );
+ return record;
+}
+
+export async function deleteRaw(id) {
+ await query('DELETE FROM fableloom_stories WHERE id = $1', [id]);
+}
diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.js
new file mode 100644
index 0000000000..b3e563917e
--- /dev/null
+++ b/server/services/fableLoom/index.js
@@ -0,0 +1,31 @@
+export {
+ LOOM_LIMITS,
+ addEpisode,
+ addNode,
+ attachNodeImage,
+ createLoom,
+ deleteEpisode,
+ deleteLoom,
+ deleteNode,
+ getLoom,
+ listLooms,
+ mutateLoom,
+ sanitizeLoom,
+ updateEpisode,
+ updateLoom,
+ updateNode,
+} from './records.js';
+export {
+ branchNode,
+ buildCanonDigest,
+ mapGeneratedGraph,
+ playTurn,
+ publicNode,
+ reviewEpisode,
+ weaveEpisode,
+} from './weave.js';
+export {
+ _resetFableLoomBackend,
+ isValidLoomId,
+ verifySchemaVersion,
+} from './store.js';
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
new file mode 100644
index 0000000000..9e68205676
--- /dev/null
+++ b/server/services/fableLoom/records.js
@@ -0,0 +1,338 @@
+/**
+ * FableLoom record lifecycle — looms, episodes, scene nodes, and intent
+ * transitions.
+ *
+ * A loom is a branching-narrative story: episodes hold a directed graph of
+ * scene nodes; each node carries prose, an image prompt/render, and a list of
+ * intent-triggered transitions the play LLM matches free-text reader input
+ * against. All ids are server-minted. Every write funnels through
+ * `mutateLoom` (per-record write queue + full re-sanitize), so a malformed
+ * mutation can never persist.
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+import { isStr, trimTo } from '../../lib/storyBible.js';
+import {
+ deleteRaw,
+ isValidLoomId,
+ listRaw,
+ queueLoomWrite,
+ readRaw,
+ writeRaw,
+} from './store.js';
+
+export const LOOM_LIMITS = Object.freeze({
+ NAME_MAX: 200,
+ LOGLINE_MAX: 500,
+ PREMISE_MAX: 20000,
+ STYLE_NOTES_MAX: 4000,
+ REF_ID_MAX: 64,
+ EPISODES_MAX: 100,
+ EPISODE_TITLE_MAX: 300,
+ SYNOPSIS_MAX: 4000,
+ NODES_MAX: 200,
+ NODE_TITLE_MAX: 300,
+ PROSE_MAX: 20000,
+ IMAGE_PROMPT_MAX: 2000,
+ ENDING_LABEL_MAX: 200,
+ TRANSITIONS_MAX: 12,
+ INTENT_MAX: 120,
+ TRIGGER_MAX: 160,
+ TRIGGERS_MAX: 8,
+ TRANSITION_DESC_MAX: 500,
+});
+
+const isSafeImageFilename = (value) =>
+ typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]*\.(png|jpg|jpeg|webp)$/i.test(value);
+
+const nullableRef = (value) => (isStr(value) && value.trim() ? value.trim().slice(0, LOOM_LIMITS.REF_ID_MAX) : null);
+
+const sanitizePos = (raw) => (raw && typeof raw === 'object'
+ && Number.isFinite(raw.x) && Number.isFinite(raw.y)
+ ? { x: Math.round(raw.x), y: Math.round(raw.y) }
+ : null);
+
+function sanitizeTransition(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const intent = trimTo(raw.intent, LOOM_LIMITS.INTENT_MAX);
+ const targetNodeId = isStr(raw.targetNodeId) ? raw.targetNodeId : '';
+ if (!targetNodeId) return null;
+ return {
+ id: isStr(raw.id) && raw.id ? raw.id : `tr-${randomUUID()}`,
+ targetNodeId,
+ intent,
+ triggers: (Array.isArray(raw.triggers) ? raw.triggers : [])
+ .map((t) => trimTo(t, LOOM_LIMITS.TRIGGER_MAX))
+ .filter(Boolean)
+ .slice(0, LOOM_LIMITS.TRIGGERS_MAX),
+ description: trimTo(raw.description, LOOM_LIMITS.TRANSITION_DESC_MAX),
+ };
+}
+
+function sanitizeNode(raw) {
+ if (!raw || typeof raw !== 'object' || !isStr(raw.id) || !raw.id) return null;
+ return {
+ id: raw.id,
+ title: trimTo(raw.title, LOOM_LIMITS.NODE_TITLE_MAX),
+ prose: trimTo(raw.prose, LOOM_LIMITS.PROSE_MAX),
+ imagePrompt: trimTo(raw.imagePrompt, LOOM_LIMITS.IMAGE_PROMPT_MAX),
+ image: isSafeImageFilename(raw.image) ? raw.image : null,
+ imageJobId: isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId.slice(0, 200) : null,
+ isEnding: raw.isEnding === true,
+ endingLabel: trimTo(raw.endingLabel, LOOM_LIMITS.ENDING_LABEL_MAX),
+ transitions: (Array.isArray(raw.transitions) ? raw.transitions : [])
+ .map(sanitizeTransition)
+ .filter(Boolean)
+ .slice(0, LOOM_LIMITS.TRANSITIONS_MAX),
+ pos: sanitizePos(raw.pos),
+ };
+}
+
+function sanitizeEpisode(raw) {
+ if (!raw || typeof raw !== 'object' || !isStr(raw.id) || !raw.id) return null;
+ const nodes = (Array.isArray(raw.nodes) ? raw.nodes : [])
+ .map(sanitizeNode)
+ .filter(Boolean)
+ .slice(0, LOOM_LIMITS.NODES_MAX);
+ const nodeIds = new Set(nodes.map((n) => n.id));
+ // Transitions to nodes dropped by sanitize/caps would dangle forever with no
+ // UI to remove them — strip them here; authored dangling edges are still
+ // surfaced (not silently removed) because the target id survives sanitize.
+ const now = new Date().toISOString();
+ return {
+ id: raw.id,
+ number: Number.isFinite(raw.number) ? Math.max(1, Math.round(raw.number)) : 1,
+ title: trimTo(raw.title, LOOM_LIMITS.EPISODE_TITLE_MAX),
+ synopsis: trimTo(raw.synopsis, LOOM_LIMITS.SYNOPSIS_MAX),
+ startNodeId: isStr(raw.startNodeId) && nodeIds.has(raw.startNodeId) ? raw.startNodeId : (nodes[0]?.id ?? null),
+ nodes,
+ createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : now,
+ updatedAt: isStr(raw.updatedAt) && raw.updatedAt ? raw.updatedAt : now,
+ };
+}
+
+export function sanitizeLoom(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ if (!isStr(raw.id) || !raw.id) return null;
+ const name = trimTo(raw.name, LOOM_LIMITS.NAME_MAX);
+ if (!name) return null;
+ const now = new Date().toISOString();
+ return {
+ id: raw.id,
+ schemaVersion: 1,
+ name,
+ logline: trimTo(raw.logline, LOOM_LIMITS.LOGLINE_MAX),
+ premise: trimTo(raw.premise, LOOM_LIMITS.PREMISE_MAX),
+ styleNotes: trimTo(raw.styleNotes, LOOM_LIMITS.STYLE_NOTES_MAX),
+ universeId: nullableRef(raw.universeId),
+ seriesId: nullableRef(raw.seriesId),
+ episodes: (Array.isArray(raw.episodes) ? raw.episodes : [])
+ .map(sanitizeEpisode)
+ .filter(Boolean)
+ .slice(0, LOOM_LIMITS.EPISODES_MAX)
+ .sort((a, b) => a.number - b.number || a.createdAt.localeCompare(b.createdAt)),
+ createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : now,
+ updatedAt: isStr(raw.updatedAt) && raw.updatedAt ? raw.updatedAt : now,
+ };
+}
+
+const notFound = (what = 'Loom') => new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' });
+
+const requireLoomRaw = async (id) => {
+ if (!isValidLoomId(id)) throw notFound();
+ const loom = sanitizeLoom(await readRaw(id));
+ if (!loom) throw notFound();
+ return loom;
+};
+
+export async function listLooms() {
+ const records = (await listRaw()).map(sanitizeLoom).filter(Boolean);
+ return records.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.name.localeCompare(b.name));
+}
+
+export async function getLoom(id) {
+ if (!isValidLoomId(id)) return null;
+ return sanitizeLoom(await readRaw(id));
+}
+
+export async function createLoom({ name, logline, premise, styleNotes, universeId, seriesId } = {}) {
+ const now = new Date().toISOString();
+ const loom = sanitizeLoom({
+ id: `loom-${randomUUID()}`,
+ name,
+ logline,
+ premise,
+ styleNotes,
+ universeId,
+ seriesId,
+ episodes: [],
+ createdAt: now,
+ updatedAt: now,
+ });
+ if (!loom) throw new ServerError('Loom needs a name', { status: 400, code: 'VALIDATION_ERROR' });
+ await writeRaw(loom.id, loom);
+ return loom;
+}
+
+/**
+ * Serialized read-modify-write. `mutator(current)` returns the changed record
+ * (or a falsy value to skip the write). The result is re-sanitized before
+ * persisting so a mutation can never store a malformed record.
+ */
+export function mutateLoom(id, mutator) {
+ if (!isValidLoomId(id)) throw notFound();
+ return queueLoomWrite(id, async () => {
+ const current = await requireLoomRaw(id);
+ const changed = await mutator(current);
+ if (!changed) return current;
+ const next = sanitizeLoom({ ...changed, id, updatedAt: new Date().toISOString() });
+ if (!next) throw new ServerError('Invalid loom record', { status: 400, code: 'VALIDATION_ERROR' });
+ await writeRaw(id, next);
+ return next;
+ });
+}
+
+const PATCH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'universeId', 'seriesId'];
+
+export function updateLoom(id, patch = {}) {
+ return mutateLoom(id, (loom) => {
+ const next = { ...loom };
+ for (const key of PATCH_FIELDS) {
+ if (key in patch) next[key] = patch[key];
+ }
+ return next;
+ });
+}
+
+export async function deleteLoom(id) {
+ await requireLoomRaw(id);
+ await deleteRaw(id);
+}
+
+// --- Episodes ---------------------------------------------------------------
+
+const findEpisode = (loom, episodeId) => {
+ const episode = loom.episodes.find((e) => e.id === episodeId);
+ if (!episode) throw notFound('Episode');
+ return episode;
+};
+
+export function addEpisode(loomId, { title, synopsis } = {}) {
+ return mutateLoom(loomId, (loom) => {
+ if (loom.episodes.length >= LOOM_LIMITS.EPISODES_MAX) {
+ throw new ServerError('Episode limit reached', { status: 400, code: 'LIMIT_REACHED' });
+ }
+ const now = new Date().toISOString();
+ const number = loom.episodes.reduce((max, e) => Math.max(max, e.number), 0) + 1;
+ loom.episodes.push({
+ id: `ep-${randomUUID()}`,
+ number,
+ title,
+ synopsis,
+ startNodeId: null,
+ nodes: [],
+ createdAt: now,
+ updatedAt: now,
+ });
+ return loom;
+ });
+}
+
+export function updateEpisode(loomId, episodeId, patch = {}) {
+ return mutateLoom(loomId, (loom) => {
+ const episode = findEpisode(loom, episodeId);
+ for (const key of ['title', 'synopsis', 'number', 'startNodeId']) {
+ if (key in patch) episode[key] = patch[key];
+ }
+ episode.updatedAt = new Date().toISOString();
+ return loom;
+ });
+}
+
+export function deleteEpisode(loomId, episodeId) {
+ return mutateLoom(loomId, (loom) => {
+ findEpisode(loom, episodeId);
+ loom.episodes = loom.episodes.filter((e) => e.id !== episodeId);
+ return loom;
+ });
+}
+
+// --- Nodes & transitions ----------------------------------------------------
+
+const NODE_PATCH_FIELDS = ['title', 'prose', 'imagePrompt', 'isEnding', 'endingLabel', 'pos', 'transitions'];
+
+export function addNode(loomId, episodeId, fields = {}) {
+ return mutateLoom(loomId, (loom) => {
+ const episode = findEpisode(loom, episodeId);
+ if (episode.nodes.length >= LOOM_LIMITS.NODES_MAX) {
+ throw new ServerError('Scene limit reached', { status: 400, code: 'LIMIT_REACHED' });
+ }
+ const node = { id: `node-${randomUUID()}`, ...fields };
+ episode.nodes.push(node);
+ if (!episode.startNodeId) episode.startNodeId = node.id;
+ // Optionally wire the new node in as a branch of an existing one.
+ if (isStr(fields.fromNodeId)) {
+ const from = episode.nodes.find((n) => n.id === fields.fromNodeId);
+ if (from) {
+ from.transitions = [...(from.transitions || []), {
+ id: `tr-${randomUUID()}`,
+ targetNodeId: node.id,
+ intent: fields.fromIntent,
+ triggers: [],
+ description: '',
+ }];
+ }
+ }
+ episode.updatedAt = new Date().toISOString();
+ return loom;
+ });
+}
+
+export function updateNode(loomId, episodeId, nodeId, patch = {}) {
+ return mutateLoom(loomId, (loom) => {
+ const episode = findEpisode(loom, episodeId);
+ const node = episode.nodes.find((n) => n.id === nodeId);
+ if (!node) throw notFound('Scene');
+ for (const key of NODE_PATCH_FIELDS) {
+ if (key in patch) node[key] = patch[key];
+ }
+ episode.updatedAt = new Date().toISOString();
+ return loom;
+ });
+}
+
+export function deleteNode(loomId, episodeId, nodeId) {
+ return mutateLoom(loomId, (loom) => {
+ const episode = findEpisode(loom, episodeId);
+ if (!episode.nodes.some((n) => n.id === nodeId)) throw notFound('Scene');
+ episode.nodes = episode.nodes.filter((n) => n.id !== nodeId);
+ // Strip inbound edges so deleting a scene never leaves dangling paths.
+ for (const node of episode.nodes) {
+ node.transitions = (node.transitions || []).filter((t) => t.targetNodeId !== nodeId);
+ }
+ if (episode.startNodeId === nodeId) episode.startNodeId = episode.nodes[0]?.id ?? null;
+ episode.updatedAt = new Date().toISOString();
+ return loom;
+ });
+}
+
+/**
+ * Durable image attach for the media-job completion hook: files a finished
+ * render onto its node, even when the editor unmounted mid-render. Returns the
+ * updated node (or null when the loom/episode/node has since been deleted —
+ * the hook logs and moves on rather than erroring).
+ */
+export async function attachNodeImage(loomId, episodeId, nodeId, { filename, jobId }) {
+ if (!isValidLoomId(loomId) || !isSafeImageFilename(filename)) return null;
+ const updated = await mutateLoom(loomId, (loom) => {
+ const episode = loom.episodes.find((e) => e.id === episodeId);
+ const node = episode?.nodes.find((n) => n.id === nodeId);
+ if (!node) return null;
+ node.image = filename;
+ node.imageJobId = isStr(jobId) ? jobId : null;
+ episode.updatedAt = new Date().toISOString();
+ return loom;
+ }).catch(() => null);
+ 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
new file mode 100644
index 0000000000..1385365886
--- /dev/null
+++ b/server/services/fableLoom/records.test.js
@@ -0,0 +1,201 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+// Real per-suite tmpdir backing the fableloom/ collectionStore layout (the
+// NODE_ENV=test escape-hatch backend). Wiped per test.
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'fableloom-records-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
+ };
+});
+
+const {
+ addEpisode, addNode, attachNodeImage, createLoom, deleteEpisode, deleteLoom,
+ deleteNode, getLoom, listLooms, sanitizeLoom, updateEpisode, updateLoom, updateNode,
+} = await import('./records.js');
+const { _resetFableLoomBackend } = await import('./store.js');
+
+beforeEach(() => {
+ rmSync(join(TEST_DATA_ROOT, 'fableloom'), { recursive: true, force: true });
+ _resetFableLoomBackend();
+});
+
+afterAll(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+});
+
+const makeLoom = (fields = {}) => createLoom({ name: 'The Hollow Crown', ...fields });
+
+describe('sanitizeLoom', () => {
+ it('rejects records without an id or name', () => {
+ expect(sanitizeLoom(null)).toBeNull();
+ expect(sanitizeLoom({ id: 'loom-1' })).toBeNull();
+ expect(sanitizeLoom({ name: 'x' })).toBeNull();
+ });
+
+ it('drops malformed nodes and transitions but keeps authored dangling targets', () => {
+ const loom = sanitizeLoom({
+ id: 'loom-1',
+ name: 'X',
+ episodes: [{
+ id: 'ep-1',
+ startNodeId: 'n1',
+ nodes: [
+ { id: 'n1', title: 'A', transitions: [
+ { id: 't1', targetNodeId: 'n-gone', intent: 'leap' }, // dangling: kept (validation surfaces it)
+ { targetNodeId: '', intent: 'no target' }, // no target: dropped
+ 'garbage',
+ ] },
+ { title: 'no id — dropped' },
+ ],
+ }],
+ });
+ expect(loom.episodes[0].nodes).toHaveLength(1);
+ expect(loom.episodes[0].nodes[0].transitions).toHaveLength(1);
+ expect(loom.episodes[0].nodes[0].transitions[0].targetNodeId).toBe('n-gone');
+ });
+
+ it('repoints a missing startNodeId at the first node', () => {
+ const loom = sanitizeLoom({
+ id: 'loom-1',
+ name: 'X',
+ episodes: [{ id: 'ep-1', startNodeId: 'gone', nodes: [{ id: 'n1' }] }],
+ });
+ expect(loom.episodes[0].startNodeId).toBe('n1');
+ });
+
+ it('rejects unsafe image filenames', () => {
+ const loom = sanitizeLoom({
+ id: 'loom-1',
+ name: 'X',
+ episodes: [{ id: 'ep-1', nodes: [{ id: 'n1', image: '../../etc/passwd' }, { id: 'n2', image: 'render.png' }] }],
+ });
+ expect(loom.episodes[0].nodes[0].image).toBeNull();
+ expect(loom.episodes[0].nodes[1].image).toBe('render.png');
+ });
+});
+
+describe('loom CRUD', () => {
+ it('creates, lists, patches, and deletes a loom', async () => {
+ const loom = await makeLoom({ logline: 'A crown that remembers.', universeId: 'uni-1' });
+ expect(loom.id).toMatch(/^loom-/);
+ expect(loom.universeId).toBe('uni-1');
+
+ expect((await listLooms()).map((l) => l.id)).toEqual([loom.id]);
+
+ const patched = await updateLoom(loom.id, { logline: 'New logline', seriesId: 'ser-9' });
+ expect(patched.logline).toBe('New logline');
+ expect(patched.seriesId).toBe('ser-9');
+ // Absent keys preserve current values.
+ expect(patched.universeId).toBe('uni-1');
+
+ await deleteLoom(loom.id);
+ expect(await getLoom(loom.id)).toBeNull();
+ });
+
+ it('rejects creating a loom without a name', async () => {
+ await expect(createLoom({ name: ' ' })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
+ });
+});
+
+describe('episodes', () => {
+ it('adds episodes with sequential numbers and deletes them', async () => {
+ const loom = await makeLoom();
+ let updated = await addEpisode(loom.id, { title: 'Pilot' });
+ updated = await addEpisode(loom.id, { title: 'Second' });
+ expect(updated.episodes.map((e) => [e.number, e.title])).toEqual([[1, 'Pilot'], [2, 'Second']]);
+
+ const [first] = updated.episodes;
+ updated = await updateEpisode(loom.id, first.id, { synopsis: 'It begins.' });
+ expect(updated.episodes[0].synopsis).toBe('It begins.');
+
+ updated = await deleteEpisode(loom.id, first.id);
+ expect(updated.episodes.map((e) => e.title)).toEqual(['Second']);
+ await expect(deleteEpisode(loom.id, 'ep-missing')).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+});
+
+describe('nodes and transitions', () => {
+ const setup = async () => {
+ const loom = await makeLoom();
+ const withEp = await addEpisode(loom.id, { title: 'Pilot' });
+ return { loomId: loom.id, episodeId: withEp.episodes[0].id };
+ };
+
+ it('first node becomes the start node; fromNodeId wires a branch', async () => {
+ const { loomId, episodeId } = await setup();
+ let updated = await addNode(loomId, episodeId, { title: 'Opening', prose: 'You wake.' });
+ const ep = () => updated.episodes[0];
+ const start = ep().nodes[0];
+ expect(ep().startNodeId).toBe(start.id);
+
+ updated = await addNode(loomId, episodeId, {
+ title: 'The Door', fromNodeId: start.id, fromIntent: 'open the door',
+ });
+ const startNow = updated.episodes[0].nodes.find((n) => n.id === start.id);
+ const door = updated.episodes[0].nodes.find((n) => n.title === 'The Door');
+ expect(startNow.transitions).toHaveLength(1);
+ expect(startNow.transitions[0]).toMatchObject({ targetNodeId: door.id, intent: 'open the door' });
+ });
+
+ it('patches node fields and replaces transitions', async () => {
+ const { loomId, episodeId } = await setup();
+ let updated = await addNode(loomId, episodeId, { title: 'A' });
+ updated = await addNode(loomId, episodeId, { title: 'B' });
+ const [a, b] = updated.episodes[0].nodes;
+
+ updated = await updateNode(loomId, episodeId, a.id, {
+ prose: 'New prose',
+ isEnding: false,
+ transitions: [{ targetNodeId: b.id, intent: 'press on', triggers: ['keep going'] }],
+ });
+ const aNow = updated.episodes[0].nodes.find((n) => n.id === a.id);
+ expect(aNow.prose).toBe('New prose');
+ expect(aNow.transitions[0]).toMatchObject({ targetNodeId: b.id, intent: 'press on', triggers: ['keep going'] });
+ expect(aNow.transitions[0].id).toMatch(/^tr-/);
+ });
+
+ it('deleting a node strips inbound transitions and repoints the start', async () => {
+ const { loomId, episodeId } = await setup();
+ let updated = await addNode(loomId, episodeId, { title: 'A' });
+ const a = updated.episodes[0].nodes[0];
+ updated = await addNode(loomId, episodeId, { title: 'B', fromNodeId: a.id, fromIntent: 'go' });
+ const b = updated.episodes[0].nodes.find((n) => n.title === 'B');
+
+ updated = await deleteNode(loomId, episodeId, b.id);
+ const aNow = updated.episodes[0].nodes.find((n) => n.id === a.id);
+ expect(aNow.transitions).toEqual([]);
+
+ updated = await deleteNode(loomId, episodeId, a.id);
+ expect(updated.episodes[0].startNodeId).toBeNull();
+ });
+});
+
+describe('attachNodeImage', () => {
+ it('files a completed render onto its node', async () => {
+ const loom = await makeLoom();
+ let updated = await addEpisode(loom.id, {});
+ const episodeId = updated.episodes[0].id;
+ updated = await addNode(loom.id, episodeId, { title: 'A' });
+ const node = updated.episodes[0].nodes[0];
+
+ const attached = await attachNodeImage(loom.id, episodeId, node.id, { filename: 'job-1.png', jobId: 'job-1' });
+ expect(attached).toMatchObject({ id: node.id, image: 'job-1.png', imageJobId: 'job-1' });
+ expect((await getLoom(loom.id)).episodes[0].nodes[0].image).toBe('job-1.png');
+ });
+
+ it('returns null (no throw) when the target is gone or the filename is unsafe', async () => {
+ const loom = await makeLoom();
+ const updated = await addEpisode(loom.id, {});
+ const episodeId = updated.episodes[0].id;
+ expect(await attachNodeImage(loom.id, episodeId, 'node-gone', { filename: 'x.png' })).toBeNull();
+ expect(await attachNodeImage(loom.id, episodeId, 'node-gone', { filename: '../x.png' })).toBeNull();
+ expect(await attachNodeImage('loom-missing', episodeId, 'node-gone', { filename: 'x.png' })).toBeNull();
+ });
+});
diff --git a/server/services/fableLoom/store.js b/server/services/fableLoom/store.js
new file mode 100644
index 0000000000..8687181fc0
--- /dev/null
+++ b/server/services/fableLoom/store.js
@@ -0,0 +1,97 @@
+/**
+ * FableLoom records — PostgreSQL/file backend facade.
+ *
+ * Looms are db-primary in normal installs (`fableloom_stories`). The
+ * collectionStore backend keeps the domain runnable in tests and under the
+ * unsupported MEMORY_BACKEND=file development escape hatch — same split as
+ * games (server/services/games/store.js).
+ */
+
+import { join } from 'path';
+import { PATHS } from '../../lib/fileUtils.js';
+import { createCollectionStore } from '../../lib/collectionStore.js';
+import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';
+import { createPgFileFacade, resolvePgBackend } from '../../lib/pgFileFacade.js';
+
+const TYPE_SCHEMA_VERSION = 1;
+const ID_PATTERN = /^loom-[A-Za-z0-9-]{1,80}$/;
+export const isValidLoomId = (id) => typeof id === 'string' && ID_PATTERN.test(id);
+
+function assertId(id) {
+ if (!isValidLoomId(id)) {
+ throw new Error(`fableLoom: invalid record id "${id}"`);
+ }
+}
+
+const loomsDir = () => join(PATHS.data, 'fableloom');
+
+function makeFileBackend() {
+ const collection = createCollectionStore({
+ dir: loomsDir(),
+ type: 'fableloom',
+ schemaVersion: TYPE_SCHEMA_VERSION,
+ idPattern: ID_PATTERN,
+ });
+
+ return {
+ name: 'file',
+ readRaw: (id) => collection.loadOneRaw(id),
+ listRaw: () => collection.loadAll(),
+ writeRaw: (id, record) => collection.saveOneNow(id, record),
+ deleteRaw: (id) => collection.deleteOneNow(id),
+ verify: () => collection.verifySchemaVersion(),
+ };
+}
+
+function makePgBackend(db) {
+ return {
+ name: 'postgres',
+ readRaw: db.readRaw,
+ listRaw: db.listRaw,
+ writeRaw: db.writeRaw,
+ deleteRaw: db.deleteRaw,
+ verify: async () => ({
+ ok: true,
+ type: 'fableloom',
+ onDisk: null,
+ expected: null,
+ message: 'collection "fableloom" @ postgres',
+ }),
+ };
+}
+
+const facade = createPgFileFacade({
+ makeFile: makeFileBackend,
+ makePg: () => resolvePgBackend({
+ requirement: 'FableLoom requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',
+ loadDb: () => import('./db.js'),
+ makePg: makePgBackend,
+ }),
+});
+
+const queueRecordWrite = createRecordWriteQueue(assertId);
+
+export const readRaw = async (id) => {
+ assertId(id);
+ return (await facade.getBackend()).readRaw(id);
+};
+
+export const listRaw = async () => (await facade.getBackend()).listRaw();
+
+export const writeRaw = async (id, record) => {
+ assertId(id);
+ return (await facade.getBackend()).writeRaw(id, record);
+};
+
+export const deleteRaw = async (id) => {
+ assertId(id);
+ return (await facade.getBackend()).deleteRaw(id);
+};
+
+export const queueLoomWrite = (id, fn) => queueRecordWrite(id, fn);
+
+export const verifySchemaVersion = async () => (await facade.getBackend()).verify();
+
+export function _resetFableLoomBackend() {
+ facade.reset();
+}
diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.js
new file mode 100644
index 0000000000..c30355ea8a
--- /dev/null
+++ b/server/services/fableLoom/weave.js
@@ -0,0 +1,312 @@
+/**
+ * FableLoom AI operations — weave (generate a full episode graph), branch
+ * (grow new paths out of one scene), review (LLM story critique layered over
+ * the deterministic graph analysis), and play (resolve a reader's free-text
+ * intent into a graph transition).
+ *
+ * Every call here is triggered by a direct user action in the same request
+ * (button click / chat message), per the AI Provider Usage Policy — nothing
+ * fires at boot or in the background. LLM execution rides `runStagedLLM`, so
+ * provider/model resolution, run records, and JSON extraction follow the same
+ * rules as every other stage.
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+import { runStagedLLM } from '../../lib/stageRunner.js';
+import { isStr, trimTo } from '../../lib/storyBible.js';
+import { descriptorForCanonEntry } from '../../lib/canonPrompt.js';
+import { analyzeEpisodeGraph, describeGraphForPrompt } from '../../lib/fableLoomGraph.js';
+import { getUniverse } from '../universeBuilder.js';
+import { pickCanon } from '../pipeline/seriesCanon.js';
+import { LOOM_LIMITS, getLoom, mutateLoom } from './records.js';
+
+const CANON_ENTRIES_PER_KIND = 20;
+const TRANSCRIPT_TURNS_MAX = 12;
+
+const aiShapeError = (message) =>
+ new ServerError(message, { status: 502, code: 'AI_RESPONSE_INVALID' });
+
+const requireLoom = async (loomId) => {
+ const loom = await getLoom(loomId);
+ if (!loom) throw new ServerError('Loom not found', { status: 404, code: 'NOT_FOUND' });
+ return loom;
+};
+
+const requireEpisode = (loom, episodeId) => {
+ const episode = loom.episodes.find((e) => e.id === episodeId);
+ if (!episode) throw new ServerError('Episode not found', { status: 404, code: 'NOT_FOUND' });
+ return episode;
+};
+
+const llmOptions = ({ providerId, model } = {}, source) => ({
+ source,
+ returnsJson: true,
+ ...(providerId ? { providerOverride: providerId } : {}),
+ ...(model ? { modelOverride: model } : {}),
+});
+
+/**
+ * Render the linked universe's canon as a compact digest for prompts. Empty
+ * string when the loom has no universe (the stages treat it as optional).
+ */
+export async function buildCanonDigest(loom) {
+ if (!loom.universeId) return '';
+ const universe = await getUniverse(loom.universeId).catch(() => null);
+ if (!universe) return '';
+ const canon = pickCanon(universe);
+ const lines = [];
+ const section = (label, kind, entries) => {
+ const named = entries.filter((e) => isStr(e?.name) && e.name).slice(0, CANON_ENTRIES_PER_KIND);
+ if (!named.length) return;
+ lines.push(`${label}:`);
+ for (const entry of named) {
+ const descriptor = descriptorForCanonEntry(kind, entry);
+ lines.push(`- ${entry.name}${descriptor ? ` — ${descriptor}` : ''}`);
+ }
+ lines.push('');
+ };
+ section('Characters', 'character', canon.characters);
+ section('Places', 'place', canon.places);
+ section('Objects', 'object', canon.objects);
+ return lines.join('\n').trim();
+}
+
+const storyContext = (loom, episode) => [
+ `Story: ${loom.name}`,
+ loom.logline ? `Logline: ${loom.logline}` : '',
+ loom.premise ? `Premise: ${loom.premise}` : '',
+ episode ? `Episode ${episode.number}: ${episode.title || 'Untitled'}` : '',
+ episode?.synopsis ? `Synopsis: ${episode.synopsis}` : '',
+].filter(Boolean).join('\n');
+
+// --- Weave: generate a full episode graph -----------------------------------
+
+const sanitizeGeneratedTransitions = (rawTransitions, idByKey, selfId) =>
+ (Array.isArray(rawTransitions) ? rawTransitions : [])
+ .filter((t) => t && typeof t === 'object' && idByKey.has(t.targetKey) && idByKey.get(t.targetKey) !== selfId)
+ .slice(0, LOOM_LIMITS.TRANSITIONS_MAX)
+ .map((t) => ({
+ id: `tr-${randomUUID()}`,
+ targetNodeId: idByKey.get(t.targetKey),
+ intent: trimTo(t.intent, LOOM_LIMITS.INTENT_MAX),
+ triggers: (Array.isArray(t.triggers) ? t.triggers : [])
+ .map((s) => trimTo(s, LOOM_LIMITS.TRIGGER_MAX)).filter(Boolean)
+ .slice(0, LOOM_LIMITS.TRIGGERS_MAX),
+ description: trimTo(t.description, LOOM_LIMITS.TRANSITION_DESC_MAX),
+ }));
+
+const generatedNodeFields = (raw) => ({
+ title: trimTo(raw.title, LOOM_LIMITS.NODE_TITLE_MAX),
+ prose: trimTo(raw.prose, LOOM_LIMITS.PROSE_MAX),
+ imagePrompt: trimTo(raw.imagePrompt, LOOM_LIMITS.IMAGE_PROMPT_MAX),
+ isEnding: raw.isEnding === true,
+ endingLabel: trimTo(raw.endingLabel, LOOM_LIMITS.ENDING_LABEL_MAX),
+});
+
+/**
+ * Map an LLM graph (`{ startKey, nodes: [{ key, …, transitions: [{ targetKey,
+ * … }] }] }`) onto server-minted node ids. Throws AI_RESPONSE_INVALID when the
+ * shape is unusable (too few scenes, no ending, unknown start).
+ */
+export function mapGeneratedGraph(parsed) {
+ const rawNodes = Array.isArray(parsed?.nodes) ? parsed.nodes.filter((n) => n && typeof n === 'object' && isStr(n.key)) : [];
+ if (rawNodes.length < 2) throw aiShapeError('The model returned too few scenes to form a story graph');
+ const idByKey = new Map();
+ for (const raw of rawNodes.slice(0, LOOM_LIMITS.NODES_MAX)) {
+ if (!idByKey.has(raw.key)) idByKey.set(raw.key, `node-${randomUUID()}`);
+ }
+ const nodes = rawNodes.slice(0, LOOM_LIMITS.NODES_MAX).map((raw) => ({
+ id: idByKey.get(raw.key),
+ ...generatedNodeFields(raw),
+ transitions: sanitizeGeneratedTransitions(raw.transitions, idByKey, idByKey.get(raw.key)),
+ pos: null,
+ }));
+ if (!nodes.some((n) => n.isEnding)) throw aiShapeError('The model returned a graph with no endings');
+ const startNodeId = idByKey.get(parsed?.startKey) ?? nodes[0].id;
+ return { nodes, startNodeId };
+}
+
+export async function weaveEpisode(loomId, episodeId, {
+ guidance = '', nodeTarget = 12, endingTarget = 3, replace = false, providerId, model,
+} = {}) {
+ const loom = await requireLoom(loomId);
+ const episode = requireEpisode(loom, episodeId);
+ if (episode.nodes.length && !replace) {
+ throw new ServerError('Episode already has scenes — pass replace to regenerate', { status: 409, code: 'EPISODE_NOT_EMPTY' });
+ }
+ const canonDigest = await buildCanonDigest(loom);
+ const { content, runId } = await runStagedLLM('fableloom-weave-episode', {
+ storyContext: storyContext(loom, episode),
+ canonDigest: canonDigest || '(none — invent what the story needs)',
+ guidance: guidance || '(none)',
+ nodeTarget: String(nodeTarget),
+ endingTarget: String(endingTarget),
+ }, llmOptions({ providerId, model }, 'fableloom-weave'));
+
+ const { nodes, startNodeId } = mapGeneratedGraph(content);
+ const updated = await mutateLoom(loomId, (current) => {
+ const ep = current.episodes.find((e) => e.id === episodeId);
+ if (!ep) throw new ServerError('Episode not found', { status: 404, code: 'NOT_FOUND' });
+ ep.nodes = nodes;
+ ep.startNodeId = startNodeId;
+ ep.updatedAt = new Date().toISOString();
+ return current;
+ });
+ return { loom: updated, episodeId, runId };
+}
+
+// --- Branch: grow new paths out of one scene --------------------------------
+
+export async function branchNode(loomId, episodeId, nodeId, {
+ guidance = '', branchCount = 2, providerId, model,
+} = {}) {
+ const loom = await requireLoom(loomId);
+ const episode = requireEpisode(loom, episodeId);
+ const node = episode.nodes.find((n) => n.id === nodeId);
+ if (!node) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });
+ const count = Math.min(4, Math.max(1, Math.round(branchCount)));
+
+ const canonDigest = await buildCanonDigest(loom);
+ const { content, runId } = await runStagedLLM('fableloom-branch-node', {
+ storyContext: storyContext(loom, episode),
+ canonDigest: canonDigest || '(none — invent what the story needs)',
+ graphDigest: describeGraphForPrompt(episode, { proseLimit: 200 }),
+ sceneTitle: node.title || 'Untitled scene',
+ sceneProse: node.prose || '(no prose yet)',
+ branchCount: String(count),
+ guidance: guidance || '(none)',
+ }, llmOptions({ providerId, model }, 'fableloom-branch'));
+
+ const branches = Array.isArray(content?.branches)
+ ? content.branches.filter((b) => b && typeof b === 'object' && b.node && typeof b.node === 'object').slice(0, count)
+ : [];
+ if (!branches.length) throw aiShapeError('The model returned no usable branches');
+
+ const updated = await mutateLoom(loomId, (current) => {
+ const ep = current.episodes.find((e) => e.id === episodeId);
+ const source = ep?.nodes.find((n) => n.id === nodeId);
+ if (!source) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });
+ for (const branch of branches) {
+ if (ep.nodes.length >= LOOM_LIMITS.NODES_MAX) break;
+ const newNode = {
+ id: `node-${randomUUID()}`,
+ ...generatedNodeFields(branch.node),
+ transitions: [],
+ pos: null,
+ };
+ ep.nodes.push(newNode);
+ source.transitions = [...(source.transitions || []), {
+ id: `tr-${randomUUID()}`,
+ targetNodeId: newNode.id,
+ intent: trimTo(branch.intent, LOOM_LIMITS.INTENT_MAX),
+ triggers: (Array.isArray(branch.triggers) ? branch.triggers : [])
+ .map((s) => trimTo(s, LOOM_LIMITS.TRIGGER_MAX)).filter(Boolean)
+ .slice(0, LOOM_LIMITS.TRIGGERS_MAX),
+ description: trimTo(branch.description, LOOM_LIMITS.TRANSITION_DESC_MAX),
+ }].slice(0, LOOM_LIMITS.TRANSITIONS_MAX);
+ }
+ ep.updatedAt = new Date().toISOString();
+ return current;
+ });
+ return { loom: updated, episodeId, nodeId, runId };
+}
+
+// --- Review: LLM critique over the deterministic analysis -------------------
+
+const REVIEW_SEVERITIES = new Set(['high', 'medium', 'low']);
+
+export async function reviewEpisode(loomId, episodeId, { providerId, model } = {}) {
+ const loom = await requireLoom(loomId);
+ const episode = requireEpisode(loom, episodeId);
+ const structural = analyzeEpisodeGraph(episode);
+ const { content, runId } = await runStagedLLM('fableloom-review', {
+ storyContext: storyContext(loom, episode),
+ graphDigest: describeGraphForPrompt(episode),
+ structuralDigest: structural.issues.length
+ ? structural.issues.map((i) => `- [${i.severity}] ${i.message}`).join('\n')
+ : '(no structural issues)',
+ }, llmOptions({ providerId, model }, 'fableloom-review'));
+
+ const nodeIds = new Set(episode.nodes.map((n) => n.id));
+ const findings = (Array.isArray(content?.findings) ? content.findings : [])
+ .filter((f) => f && typeof f === 'object' && isStr(f.problem))
+ .map((f) => ({
+ severity: REVIEW_SEVERITIES.has(f.severity) ? f.severity : 'medium',
+ nodeId: nodeIds.has(f.nodeId) ? f.nodeId : null,
+ problem: trimTo(f.problem, 1000),
+ suggestion: trimTo(f.suggestion, 1000),
+ }));
+ return {
+ structural,
+ review: { summary: trimTo(content?.summary, 2000), findings },
+ runId,
+ };
+}
+
+// --- Play: resolve a reader's free-text intent ------------------------------
+
+/** Reader-facing scene shape — trigger phrases stay server-side. */
+export const publicNode = (node) => ({
+ id: node.id,
+ title: node.title,
+ prose: node.prose,
+ image: node.image,
+ isEnding: node.isEnding,
+ endingLabel: node.endingLabel,
+ choices: (node.transitions || []).map((t) => ({ id: t.id, intent: t.intent })),
+});
+
+const transcriptDigest = (transcript) =>
+ (Array.isArray(transcript) ? transcript : [])
+ .filter((t) => t && typeof t === 'object' && isStr(t.text))
+ .slice(-TRANSCRIPT_TURNS_MAX)
+ .map((t) => `${t.role === 'reader' ? 'Reader' : 'Narrator'}: ${trimTo(t.text, 500)}`)
+ .join('\n');
+
+export async function playTurn(loomId, episodeId, {
+ nodeId, message, transcript = [], providerId, model,
+} = {}) {
+ const loom = await requireLoom(loomId);
+ const episode = requireEpisode(loom, episodeId);
+ const node = episode.nodes.find((n) => n.id === nodeId);
+ if (!node) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });
+ if (node.isEnding || !(node.transitions || []).length) {
+ return { action: 'stay', narration: '', node: publicNode(node), ended: true };
+ }
+
+ const choicesDigest = node.transitions.map((t) => [
+ `- id: ${t.id}`,
+ ` intent: ${t.intent}`,
+ t.triggers.length ? ` example phrasings: ${t.triggers.join('; ')}` : null,
+ t.description ? ` leads to: ${t.description}` : null,
+ ].filter(Boolean).join('\n')).join('\n');
+
+ const { content } = await runStagedLLM('fableloom-play-turn', {
+ storyContext: storyContext(loom, episode),
+ sceneProse: node.prose || node.title || '',
+ choicesDigest,
+ transcriptDigest: transcriptDigest(transcript) || '(start of the read-through)',
+ readerMessage: trimTo(message, 1000),
+ }, llmOptions({ providerId, model }, 'fableloom-play'));
+
+ const narration = trimTo(content?.narration, 4000);
+ const chosen = content?.action === 'move'
+ ? node.transitions.find((t) => t.id === content?.transitionId)
+ : null;
+ if (!chosen) {
+ return { action: 'stay', narration, node: publicNode(node), ended: false };
+ }
+ const next = episode.nodes.find((n) => n.id === chosen.targetNodeId);
+ if (!next) {
+ // Dangling edge (authored, then target deleted) — stay rather than crash the read.
+ return { action: 'stay', narration, node: publicNode(node), ended: false };
+ }
+ return {
+ action: 'move',
+ transitionId: chosen.id,
+ narration,
+ node: publicNode(next),
+ ended: next.isEnding === true,
+ };
+}
diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.js
new file mode 100644
index 0000000000..b054a04dd7
--- /dev/null
+++ b/server/services/fableLoom/weave.test.js
@@ -0,0 +1,231 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'fableloom-weave-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
+ };
+});
+
+const runStagedLLM = vi.hoisted(() => vi.fn());
+vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM }));
+
+const getUniverseMock = vi.hoisted(() => vi.fn(async () => null));
+vi.mock('../universeBuilder.js', () => ({ getUniverse: getUniverseMock }));
+
+const { createLoom, addEpisode, addNode, updateNode, getLoom } = await import('./records.js');
+const { _resetFableLoomBackend } = await import('./store.js');
+const {
+ branchNode, buildCanonDigest, mapGeneratedGraph, playTurn, reviewEpisode, weaveEpisode,
+} = await import('./weave.js');
+
+beforeEach(() => {
+ rmSync(join(TEST_DATA_ROOT, 'fableloom'), { recursive: true, force: true });
+ _resetFableLoomBackend();
+ runStagedLLM.mockReset();
+ getUniverseMock.mockReset().mockResolvedValue(null);
+});
+
+afterAll(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+});
+
+const setup = async () => {
+ const loom = await createLoom({ name: 'The Hollow Crown', universeId: 'uni-1' });
+ const withEp = await addEpisode(loom.id, { title: 'Pilot', synopsis: 'A crown wakes.' });
+ return { loomId: loom.id, episodeId: withEp.episodes[0].id };
+};
+
+const generatedGraph = () => ({
+ startKey: 's1',
+ nodes: [
+ { key: 's1', title: 'The Gate', prose: 'You stand before it.', imagePrompt: 'a vast gate at dusk', transitions: [
+ { targetKey: 's2', intent: 'enter', triggers: ['go in'], description: 'Step through.' },
+ { targetKey: 's3', intent: 'walk away', triggers: [], description: 'Leave.' },
+ { targetKey: 'missing', intent: 'dangling — dropped' },
+ ] },
+ { key: 's2', title: 'Inside', prose: 'Torchlight.', transitions: [{ targetKey: 's3', intent: 'give up' }] },
+ { key: 's3', title: 'The Road Home', isEnding: true, endingLabel: 'Turned back', transitions: [] },
+ ],
+});
+
+describe('mapGeneratedGraph', () => {
+ it('mints server ids, remaps targets, and drops unknown-target transitions', () => {
+ const { nodes, startNodeId } = mapGeneratedGraph(generatedGraph());
+ expect(nodes).toHaveLength(3);
+ expect(nodes.every((n) => n.id.startsWith('node-'))).toBe(true);
+ expect(startNodeId).toBe(nodes[0].id);
+ expect(nodes[0].transitions).toHaveLength(2);
+ expect(nodes[0].transitions.map((t) => t.targetNodeId)).toEqual([nodes[1].id, nodes[2].id]);
+ });
+
+ it('rejects graphs with too few scenes or no endings', () => {
+ expect(() => mapGeneratedGraph({ nodes: [{ key: 's1' }] })).toThrowError(/too few scenes/);
+ expect(() => mapGeneratedGraph({
+ startKey: 's1',
+ nodes: [{ key: 's1', transitions: [] }, { key: 's2', transitions: [] }],
+ })).toThrowError(/no endings/);
+ });
+});
+
+describe('weaveEpisode', () => {
+ it('replaces the episode graph from the LLM response', async () => {
+ const { loomId, episodeId } = await setup();
+ runStagedLLM.mockResolvedValue({ content: generatedGraph(), runId: 'run-1' });
+
+ const { loom, runId } = await weaveEpisode(loomId, episodeId, { guidance: 'darker' });
+ expect(runId).toBe('run-1');
+ const ep = loom.episodes[0];
+ expect(ep.nodes).toHaveLength(3);
+ expect(ep.startNodeId).toBe(ep.nodes[0].id);
+
+ const [stage, variables] = runStagedLLM.mock.calls[0];
+ expect(stage).toBe('fableloom-weave-episode');
+ expect(variables.storyContext).toContain('The Hollow Crown');
+ expect(variables.guidance).toBe('darker');
+ });
+
+ it('refuses to clobber a non-empty episode without replace', async () => {
+ const { loomId, episodeId } = await setup();
+ await addNode(loomId, episodeId, { title: 'Handwritten' });
+ await expect(weaveEpisode(loomId, episodeId, {})).rejects.toMatchObject({ code: 'EPISODE_NOT_EMPTY' });
+ expect(runStagedLLM).not.toHaveBeenCalled();
+
+ runStagedLLM.mockResolvedValue({ content: generatedGraph(), runId: 'run-2' });
+ const { loom } = await weaveEpisode(loomId, episodeId, { replace: true });
+ expect(loom.episodes[0].nodes).toHaveLength(3);
+ });
+});
+
+describe('branchNode', () => {
+ it('adds new scenes wired as transitions from the source node', async () => {
+ const { loomId, episodeId } = await setup();
+ const withNode = await addNode(loomId, episodeId, { title: 'The Gate', prose: 'You stand before it.' });
+ const nodeId = withNode.episodes[0].nodes[0].id;
+
+ runStagedLLM.mockResolvedValue({
+ content: {
+ branches: [
+ { intent: 'scale the wall', triggers: ['climb'], description: 'Up and over.', node: { title: 'The Wall', prose: 'Cold stone.' } },
+ { intent: 'bribe the guard', node: { title: 'A Deal', prose: 'He smiles.', isEnding: true, endingLabel: 'Bought passage' } },
+ 'garbage',
+ ],
+ },
+ runId: 'run-3',
+ });
+
+ const { loom } = await branchNode(loomId, episodeId, nodeId, { branchCount: 2 });
+ const ep = loom.episodes[0];
+ expect(ep.nodes).toHaveLength(3);
+ const source = ep.nodes.find((n) => n.id === nodeId);
+ expect(source.transitions.map((t) => t.intent)).toEqual(['scale the wall', 'bribe the guard']);
+ const ending = ep.nodes.find((n) => n.title === 'A Deal');
+ expect(ending).toMatchObject({ isEnding: true, endingLabel: 'Bought passage' });
+ });
+
+ it('rejects when the model returns no usable branches', async () => {
+ const { loomId, episodeId } = await setup();
+ const withNode = await addNode(loomId, episodeId, { title: 'A' });
+ runStagedLLM.mockResolvedValue({ content: { branches: [] }, runId: 'r' });
+ await expect(branchNode(loomId, episodeId, withNode.episodes[0].nodes[0].id, {}))
+ .rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });
+ });
+});
+
+describe('reviewEpisode', () => {
+ it('combines structural analysis with sanitized LLM findings', async () => {
+ const { loomId, episodeId } = await setup();
+ const withNode = await addNode(loomId, episodeId, { title: 'Lone scene' }); // dead end → structural error
+ const nodeId = withNode.episodes[0].nodes[0].id;
+ runStagedLLM.mockResolvedValue({
+ content: {
+ summary: 'Thin.',
+ findings: [
+ { severity: 'high', nodeId, problem: 'Only one scene', suggestion: 'Branch it' },
+ { severity: 'nonsense', nodeId: 'node-unknown', problem: 'Vague', suggestion: '' },
+ { problem: null },
+ ],
+ },
+ runId: 'run-4',
+ });
+
+ const result = await reviewEpisode(loomId, episodeId, {});
+ expect(result.structural.stats.errorCount).toBeGreaterThan(0);
+ expect(result.review.summary).toBe('Thin.');
+ expect(result.review.findings).toEqual([
+ { severity: 'high', nodeId, problem: 'Only one scene', suggestion: 'Branch it' },
+ { severity: 'medium', nodeId: null, problem: 'Vague', suggestion: '' },
+ ]);
+ });
+});
+
+describe('playTurn', () => {
+ const playSetup = async () => {
+ const { loomId, episodeId } = await setup();
+ let updated = await addNode(loomId, episodeId, { title: 'The Gate', prose: 'You stand before it.' });
+ const gateId = updated.episodes[0].nodes[0].id;
+ updated = await addNode(loomId, episodeId, { title: 'Inside', prose: 'Torchlight.', fromNodeId: gateId, fromIntent: 'enter the gate' });
+ const insideId = updated.episodes[0].nodes.find((n) => n.title === 'Inside').id;
+ await updateNode(loomId, episodeId, insideId, { isEnding: true, endingLabel: 'Within' });
+ const gate = (await getLoom(loomId)).episodes[0].nodes.find((n) => n.id === gateId);
+ return { loomId, episodeId, gate, insideId };
+ };
+
+ it('moves through the matched transition and flags endings', async () => {
+ const { loomId, episodeId, gate, insideId } = await playSetup();
+ runStagedLLM.mockResolvedValue({
+ content: { action: 'move', transitionId: gate.transitions[0].id, narration: 'You step through.' },
+ });
+
+ const result = await playTurn(loomId, episodeId, { nodeId: gate.id, message: 'go inside' });
+ expect(result).toMatchObject({
+ action: 'move', narration: 'You step through.', ended: true,
+ });
+ expect(result.node).toMatchObject({ id: insideId, isEnding: true, endingLabel: 'Within' });
+ // Reader-facing shape: choices carry intents only, no trigger phrases.
+ expect(result.node.choices).toEqual([]);
+
+ const [stage, variables] = runStagedLLM.mock.calls[0];
+ expect(stage).toBe('fableloom-play-turn');
+ expect(variables.readerMessage).toBe('go inside');
+ expect(variables.choicesDigest).toContain('enter the gate');
+ });
+
+ it('stays in place when the model declines or names an invalid transition', async () => {
+ const { loomId, episodeId, gate } = await playSetup();
+ runStagedLLM.mockResolvedValue({ content: { action: 'move', transitionId: 'tr-bogus', narration: 'Hmm.' } });
+ const result = await playTurn(loomId, episodeId, { nodeId: gate.id, message: 'fly to the moon' });
+ expect(result).toMatchObject({ action: 'stay', ended: false });
+ expect(result.node.id).toBe(gate.id);
+ });
+
+ it('short-circuits on ending nodes without calling the LLM', async () => {
+ const { loomId, episodeId, insideId } = await playSetup();
+ const result = await playTurn(loomId, episodeId, { nodeId: insideId, message: 'now what' });
+ expect(result).toMatchObject({ action: 'stay', ended: true });
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+});
+
+describe('buildCanonDigest', () => {
+ it('renders linked-universe canon and returns empty for unlinked looms', async () => {
+ getUniverseMock.mockResolvedValue({
+ characters: [{ name: 'Mara', appearance: 'silver-eyed' }],
+ places: [{ name: 'The Hollow' }],
+ objects: [],
+ });
+ const digest = await buildCanonDigest({ universeId: 'uni-1' });
+ expect(digest).toContain('Characters:');
+ expect(digest).toContain('- Mara');
+ expect(digest).toContain('Places:');
+ expect(digest).not.toContain('Objects:');
+
+ expect(await buildCanonDigest({ universeId: null })).toBe('');
+ });
+});
diff --git a/server/services/fableLoomSceneImageHook.js b/server/services/fableLoomSceneImageHook.js
new file mode 100644
index 0000000000..479635472c
--- /dev/null
+++ b/server/services/fableLoomSceneImageHook.js
@@ -0,0 +1,53 @@
+/**
+ * FableLoom scene-image attach hook.
+ *
+ * Subscribes to mediaJobEvents and, for each completed image job carrying
+ * `params.fableLoom`, files the rendered filename onto that loom episode's
+ * scene node — server-side, independent of any mounted client, so a long
+ * queued local/Codex render that completes after the user navigated away
+ * still lands on the node. Same durable-attach split as the writers-room
+ * scene hook (#1363): only the async lanes ride the queue; the synchronous
+ * external SD-API lane returns its filename inline and the client PATCHes the
+ * node directly.
+ *
+ * The shared completion-hook scaffold (tag-decode, per-record serialization,
+ * newest-render-wins, best-effort error handling, idempotent init/reset)
+ * lives in `createMediaJobImageHook` — this file is just the FableLoom
+ * config. Mounted once at server boot from services/bootstrap.js (after the
+ * media job queue is running).
+ */
+
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
+import { attachNodeImage } from './fableLoom/records.js';
+
+const deriveJobId = (job, filename) =>
+ (typeof job.id === 'string' && job.id ? job.id : filename.replace(/\.png$/, ''));
+
+const hook = createMediaJobImageHook({
+ label: 'fableloom scene-image',
+ initLog: '🧶 FableLoom scene-image hook initialized',
+ tagKey: 'fableLoom',
+ identify: (tag) => (tag?.loomId && tag.episodeId && tag.nodeId
+ ? { loomId: tag.loomId, episodeId: tag.episodeId, nodeId: tag.nodeId }
+ : null),
+ // Writes already serialize per loom via the record write queue; keying the
+ // hook per loom keeps its retry/ordering bookkeeping aligned with that.
+ serializeKey: ({ loomId }) => loomId,
+ // Newest-render-wins per node so an older render completing after a newer
+ // regenerate can't overwrite the newer scene image.
+ sceneKey: ({ loomId, episodeId, nodeId }) => `${loomId}:${episodeId}:${nodeId}`,
+ describe: ({ loomId, nodeId }) => `${loomId.slice(0, 13)}/${nodeId.slice(0, 13)}`,
+ attach: ({ loomId, episodeId, nodeId, filename, job }) =>
+ attachNodeImage(loomId, episodeId, nodeId, { filename, jobId: deriveJobId(job, filename) }),
+ onAttached: ({ loomId, nodeId, filename }, result) => {
+ if (!result) return;
+ console.log(`🧶 fableloom scene image ${loomId.slice(0, 13)}/${nodeId.slice(0, 13)} ← ${filename}`);
+ },
+});
+
+export function initFableLoomSceneImageHook() {
+ hook.init();
+}
+
+// Test-only reset so suites that re-init can do so cleanly.
+export const __testing = hook.__testing;
diff --git a/server/services/fableLoomSceneImageHook.test.js b/server/services/fableLoomSceneImageHook.test.js
new file mode 100644
index 0000000000..a380d257fb
--- /dev/null
+++ b/server/services/fableLoomSceneImageHook.test.js
@@ -0,0 +1,59 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+// Mock the record layer so the hook's tag-decode + attach dispatch is
+// exercised without touching disk.
+const attachNodeImage = vi.fn(async (loomId, episodeId, nodeId, { filename, jobId }) => ({
+ id: nodeId, image: filename, imageJobId: jobId,
+}));
+vi.mock('./fableLoom/records.js', () => ({ attachNodeImage }));
+
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const hook = await import('./fableLoomSceneImageHook.js');
+
+async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+}
+
+const tag = (over = {}) => ({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1', ...over });
+const completedImageJob = ({ params = {}, filename = 'job-abc.png', id = 'job-abc' } = {}) => ({
+ kind: 'image', id, params, result: { filename },
+});
+
+describe('fableLoomSceneImageHook', () => {
+ beforeEach(() => {
+ hook.__testing.reset();
+ hook.initFableLoomSceneImageHook();
+ attachNodeImage.mockClear();
+ });
+
+ afterEach(() => {
+ hook.__testing.reset();
+ });
+
+ it('files a completed fableLoom-tagged render onto its node', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ params: { fableLoom: tag() } }));
+ await waitFor(() => attachNodeImage.mock.calls.length > 0);
+ expect(attachNodeImage).toHaveBeenCalledWith('loom-1', 'ep-1', 'node-1', {
+ filename: 'job-abc.png', jobId: 'job-abc',
+ });
+ });
+
+ it('derives jobId from the filename when the job carries no id', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ params: { fableLoom: tag() }, filename: 'noid.png', id: null }));
+ await waitFor(() => attachNodeImage.mock.calls.length > 0);
+ expect(attachNodeImage.mock.calls[0][3].jobId).toBe('noid');
+ });
+
+ it('ignores jobs without the fableLoom tag and tags missing their ids', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ params: {} }));
+ mediaJobEvents.emit('completed', completedImageJob({ params: { fableLoom: { loomId: 'loom-1' } } }));
+ // Give the async handlers a beat to (not) fire.
+ await new Promise((r) => setTimeout(r, 25));
+ expect(attachNodeImage).not.toHaveBeenCalled();
+ });
+});