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

give a loom a scene format, a narrator pin, and a free tapped path

[._.]/ Adam Eivy4897ce779db4
diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsx
index 61e8cbb8a8..18c0da8518 100644
--- a/client/src/components/fableloom/LoomNodeEditor.jsx
+++ b/client/src/components/fableloom/LoomNodeEditor.jsx
@@ -20,7 +20,8 @@ import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import {
branchLoomNode, deleteLoomNode, generateImage, updateLoomNode,
} from '../../services/api';
-import { fieldClass, labelClass } from './fieldStyles';
+import { fieldClass, labelClass, sceneFieldClass } from './fieldStyles';
+import { isTeleplayFormat } from './loomFormats';
const toRow = (t) => ({ ...t, triggersText: (t.triggers || []).join('; ') });
const rowsToTransitions = (rows) => rows
@@ -37,6 +38,9 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl
// disabled until every pending save settles.
const [pendingSaves, setPendingSaves] = useState(0);
const del = useConfirmDelete();
+ // A teleplay carries its own line breaks, so the editor gives it a taller
+ // monospaced field — the same surface prose gets, sized for the format.
+ const teleplay = isTeleplayFormat(loom.format);
// 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
@@ -194,10 +198,10 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl
/>
</FormField>
- <FormField label="Scene prose" labelClassName={labelClass}>
+ <FormField label={teleplay ? 'Scene (teleplay)' : 'Scene prose'} labelClassName={labelClass}>
<textarea
- rows={7}
- className={fieldClass}
+ rows={teleplay ? 12 : 7}
+ className={sceneFieldClass(loom.format)}
value={form.prose}
onChange={(e) => setForm((p) => ({ ...p, prose: e.target.value }))}
onBlur={() => saveField('prose', form.prose)}
diff --git a/client/src/components/fableloom/LoomPlayPanel.jsx b/client/src/components/fableloom/LoomPlayPanel.jsx
index cb8265446f..1c378af1bc 100644
--- a/client/src/components/fableloom/LoomPlayPanel.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.jsx
@@ -6,6 +6,12 @@
* 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.
+ *
+ * TAPPING a path costs nothing: the turn carries the transition id, and the
+ * server resolves the move straight off the authored graph — same endpoint,
+ * no provider call, no wait. Only free text the reader typed reaches the play
+ * stage; which provider/model/effort maps it is the loom's own `playSettings`
+ * pin, applied server-side.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
@@ -13,11 +19,13 @@ import { Loader2, RotateCcw, Send, Flag } from 'lucide-react';
import MediaImage from '../MediaImage';
import { useAsyncAction } from '../../hooks/useAsyncAction';
import { playLoomTurn } from '../../services/api';
+import { sceneProseClass } from './fieldStyles';
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).
+// Reader-facing projection of an authored node — the OPENING scene only, which
+// the panel shows before any turn has been taken. Every later scene arrives
+// from the play endpoint already in this shape (the server's `publicNode`).
const asPublic = (node) => (node ? {
id: node.id,
title: node.title,
@@ -58,10 +66,14 @@ export default function LoomPlayPanel({ loom, episode }) {
if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}, [transcript, scene]);
- const [runTurn, sending] = useAsyncAction(async (text, history) => {
+ // One turn, either lane. `transitionId` is the tapped-path lane the server
+ // resolves off the graph with no provider call; `message` is free text the
+ // play stage matches. The panel never resolves a move itself — one owner for
+ // the rule, on the side that holds the authored graph.
+ const [runTurn, sending] = useAsyncAction(async (turn, history) => {
const result = await playLoomTurn(loom.id, episode.id, {
nodeId: scene.id,
- message: text,
+ ...turn,
// The transcript state also holds scene cards ({ role: 'scene', node })
// — the API accepts only reader/narrator text turns, so filter first or
// every turn after the first move fails validation.
@@ -79,13 +91,23 @@ export default function LoomPlayPanel({ loom, episode }) {
if (additions.length) setTranscript((prev) => [...prev, ...additions]);
}, { errorMessage: 'The narrator lost the thread — try again' });
+ // Tapping a path: the reader already named the transition, so the turn
+ // carries its id and the server moves them without an intent-matching call.
+ const takePath = (choice) => {
+ if (sending || !scene) return;
+ setMessage('');
+ const history = [...transcript, { role: 'reader', text: choice.intent }];
+ setTranscript(history);
+ runTurn({ transitionId: choice.id }, history);
+ };
+
const send = () => {
const text = message.trim();
if (!text || sending || !scene) return;
setMessage('');
const history = [...transcript, { role: 'reader', text }];
setTranscript(history);
- runTurn(text, history);
+ runTurn({ message: text }, history);
};
if (!start) {
@@ -99,9 +121,9 @@ export default function LoomPlayPanel({ loom, episode }) {
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 />
+ <SceneCard node={start} isOpening format={loom.format} />
{transcript.map((turn, i) => {
- if (turn.role === 'scene') return <SceneCard key={i} node={turn.node} />;
+ if (turn.role === 'scene') return <SceneCard key={i} node={turn.node} format={loom.format} />;
return (
<div key={i} className={turn.role === 'reader' ? 'text-right' : ''}>
<div
@@ -130,7 +152,8 @@ export default function LoomPlayPanel({ loom, episode }) {
<button
key={c.id}
type="button"
- onClick={() => setMessage(c.intent)}
+ aria-label={`Take path: ${c.intent}`}
+ onClick={() => takePath(c)}
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}
@@ -173,7 +196,7 @@ export default function LoomPlayPanel({ loom, episode }) {
);
}
-function SceneCard({ node, isOpening = false }) {
+function SceneCard({ node, isOpening = false, format }) {
if (!node) return null;
return (
<div className="border border-port-border rounded-lg overflow-hidden bg-port-card">
@@ -184,7 +207,7 @@ function SceneCard({ node, isOpening = false }) {
<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>
+ <p className={sceneProseClass(format)}>{node.prose}</p>
</div>
</div>
);
diff --git a/client/src/components/fableloom/LoomPlayPanel.test.jsx b/client/src/components/fableloom/LoomPlayPanel.test.jsx
index 22f8f57689..76a78d7107 100644
--- a/client/src/components/fableloom/LoomPlayPanel.test.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.test.jsx
@@ -34,7 +34,46 @@ describe('LoomPlayPanel', () => {
it('renders the opening scene with intent hint chips', () => {
render(<LoomPlayPanel loom={loom} episode={episode} />);
expect(screen.getByText('You stand before it.')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'enter the gate' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Take path: enter the gate' })).toBeInTheDocument();
+ });
+
+ it('sends a tapped path as a transition id, not as free text to match', async () => {
+ const user = userEvent.setup();
+ playLoomTurn.mockResolvedValue({
+ action: 'move',
+ resolvedBy: 'choice',
+ narration: '',
+ ended: false,
+ node: { id: 'n2', title: 'Inside', prose: 'Torchlight.', isEnding: false, choices: [{ id: 't2', intent: 'retreat' }] },
+ });
+ render(<LoomPlayPanel loom={loom} episode={episode} />);
+ await user.click(screen.getByRole('button', { name: 'Take path: enter the gate' }));
+
+ await waitFor(() => expect(playLoomTurn).toHaveBeenCalledTimes(1));
+ const [, , payload] = playLoomTurn.mock.calls[0];
+ // No `message`: nothing for the play stage to match, so it never runs.
+ expect(payload).toMatchObject({ nodeId: 'n1', transitionId: 't1' });
+ expect(payload.message).toBeUndefined();
+ // The reader's choice reads back in the transcript, and the scene advanced.
+ expect(screen.getByText('enter the gate')).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Take path: retreat' })).toBeInTheDocument());
+ });
+
+ it('sends typed text as a message for the play stage to match', async () => {
+ const user = userEvent.setup();
+ playLoomTurn.mockResolvedValue({ action: 'stay', narration: 'You hesitate.', ended: false });
+ render(<LoomPlayPanel loom={loom} episode={episode} />);
+
+ await sendMessage(user, 'look at the lock');
+ await waitFor(() => expect(playLoomTurn).toHaveBeenCalledTimes(1));
+ const [, , payload] = playLoomTurn.mock.calls[0];
+ expect(payload).toMatchObject({ message: 'look at the lock' });
+ expect(payload.transitionId).toBeUndefined();
+ });
+
+ it('renders teleplay scenes monospaced', () => {
+ render(<LoomPlayPanel loom={{ ...loom, format: 'teleplay' }} episode={episode} />);
+ expect(screen.getByText('You stand before it.').className).toContain('font-mono');
});
it('sends only reader/narrator turns in the transcript after a scene move', async () => {
diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsx
new file mode 100644
index 0000000000..37d752836b
--- /dev/null
+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx
@@ -0,0 +1,121 @@
+/**
+ * FableLoom story settings — the loom-level choices that steer every AI lane.
+ *
+ * Two things live here:
+ * - **Scene format.** Whether scenes are written as narrated prose or as a
+ * teleplay. The setting is a pin: weave, branch, and play all render the
+ * matching format contract into their prompts. Changing it does NOT
+ * rewrite what is already authored — the separate "Rewrite every scene"
+ * action does that, as an explicit user-triggered pass (AI Provider Usage
+ * Policy), naming the provider it will use.
+ * - **Narrator routing.** Which provider/model/effort turns a reader's free
+ * text into a path during play. Unset means the play stage's own pin (or
+ * the install's active provider) — a tapped path never calls a provider at
+ * all, so this only governs typed input.
+ */
+
+import { Loader2, Sparkles } from 'lucide-react';
+import Drawer from '../Drawer';
+import ProviderModelSelector from '../ProviderModelSelector';
+import { FormField } from '../ui/FormField.jsx';
+import toast from '../ui/Toast';
+import useProviderModels from '../../hooks/useProviderModels';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providers';
+import { reformatLoom, updateLoom } from '../../services/api';
+import { fieldClass, labelClass } from './fieldStyles';
+import { LOOM_FORMATS, loomFormatHint, loomFormatLabel } from './loomFormats';
+
+export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate }) {
+ const { providers } = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
+
+ const format = loom.format || 'prose';
+ const play = loom.playSettings || {};
+ const playProvider = providers.find((p) => p.id === play.providerId);
+ const sceneCount = loom.episodes.reduce((total, ep) => total + ep.nodes.length, 0);
+
+ // The rewrite reads the format pin SERVER-side, so it stays disabled while a
+ // pin save is in flight — otherwise picking teleplay and immediately
+ // rewriting would rewrite into the previous format.
+ const [patch, saving] = useAsyncAction(
+ async (body) => onLoomUpdate(await updateLoom(loom.id, body, { silent: true })),
+ { errorMessage: 'Save failed' },
+ );
+
+ // Clearing the provider clears the model and effort with it — neither is
+ // meaningful (or necessarily valid) without the provider that offered them.
+ const savePlay = (changes) => patch({
+ playSettings: { providerId: play.providerId ?? null, model: play.model ?? null, effort: play.effort ?? null, ...changes },
+ });
+
+ const [runReformat, reformatting] = useAsyncAction(async () => {
+ const result = await reformatLoom(loom.id, { format }, { silent: true });
+ onLoomUpdate(result.loom);
+ toast.success(`Rewrote ${result.rewritten} scene${result.rewritten === 1 ? '' : 's'} as ${loomFormatLabel(format).toLowerCase()}`);
+ }, { errorMessage: 'The rewrite failed' });
+
+ return (
+ <Drawer open={open} onClose={onClose} title="Story settings" subtitle={loom.name} size="sm">
+ <div className="space-y-5">
+ <section className="space-y-2">
+ <FormField label="Scene format" labelClassName={labelClass}>
+ <select
+ className={fieldClass}
+ value={format}
+ disabled={saving || reformatting}
+ onChange={(e) => patch({ format: e.target.value })}
+ >
+ {LOOM_FORMATS.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
+ </select>
+ </FormField>
+ <p className="text-xs text-port-text-muted">
+ {loomFormatHint(format)} New scenes are written this way — scenes
+ you already have keep their current text until you rewrite them.
+ </p>
+ {sceneCount > 0 && (
+ <button
+ type="button"
+ onClick={runReformat}
+ disabled={reformatting || saving}
+ className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded border border-port-border text-sm hover:border-port-accent disabled:opacity-60"
+ >
+ {reformatting ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {reformatting
+ ? 'Rewriting…'
+ : `Rewrite all ${sceneCount} scene${sceneCount === 1 ? '' : 's'} as ${loomFormatLabel(format).toLowerCase()}`}
+ </button>
+ )}
+ </section>
+
+ <section className="border-t border-port-border pt-4 space-y-2">
+ <h4 className="text-sm font-semibold">Narrator</h4>
+ <p className="text-xs text-port-text-muted">
+ Turns what a reader types into one of the scene's paths. Tapping a path skips the AI
+ entirely, so this only runs on typed input.
+ </p>
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={play.providerId || ''}
+ selectedModel={play.model || ''}
+ availableModels={effortAwareModelOptions(playProvider, play.model)}
+ onProviderChange={(providerId) => savePlay({ providerId: providerId || null, model: null, effort: null })}
+ onModelChange={(model) => savePlay({ model: model || null })}
+ effort={play.effort || ''}
+ onEffortChange={(effort) => savePlay({ effort: effort || null })}
+ label="Provider"
+ layout="stacked"
+ emptyProviderOption="Default (whatever the play stage uses)"
+ emptyModelOption="Default model"
+ alwaysShowModel={!!play.providerId}
+ />
+ {playProvider && (
+ <p className="text-xs text-port-text-muted">
+ Reader input is sent to {playProvider.name}
+ {effectiveModelFor(playProvider, play.model) ? ` (${effectiveModelFor(playProvider, play.model)})` : ''}.
+ </p>
+ )}
+ </section>
+ </div>
+ </Drawer>
+ );
+}
diff --git a/client/src/components/fableloom/fieldStyles.js b/client/src/components/fableloom/fieldStyles.js
index 4dc44b7087..66d23ef020 100644
--- a/client/src/components/fableloom/fieldStyles.js
+++ b/client/src/components/fableloom/fieldStyles.js
@@ -1,4 +1,21 @@
+import { isTeleplayFormat } from './loomFormats';
+
// Shared form styling for the FableLoom surfaces — one source for the input
// and label classes the index form, episode drawer, and scene editor all use.
export const fieldClass = 'w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
export const labelClass = 'block text-xs font-medium text-port-text-muted mb-1';
+
+// A teleplay carries its own line breaks (slugline / action / cue / dialogue),
+// so it reads monospaced wherever it is shown — one token, composed into both
+// the display class and the editor's field class, so tuning the look is a
+// one-line change rather than two that can drift.
+const TELEPLAY_TEXT = 'font-mono text-[13px] leading-relaxed';
+
+// How a scene's text is DISPLAYED, per the loom's format. Both keep
+// `whitespace-pre-wrap` — an authored blank line is meaningful either way.
+export const sceneProseClass = (format) => (isTeleplayFormat(format)
+ ? `${TELEPLAY_TEXT} whitespace-pre-wrap`
+ : 'text-sm whitespace-pre-wrap');
+
+/** The scene textarea in the editor, sized and typeset for the format. */
+export const sceneFieldClass = (format) => (isTeleplayFormat(format) ? `${fieldClass} ${TELEPLAY_TEXT}` : fieldClass);
diff --git a/client/src/components/fableloom/loomFormats.js b/client/src/components/fableloom/loomFormats.js
new file mode 100644
index 0000000000..ea9bfff0a4
--- /dev/null
+++ b/client/src/components/fableloom/loomFormats.js
@@ -0,0 +1,20 @@
+/**
+ * Client mirror of the loom scene formats (`server/services/fableLoom/formats.js`).
+ *
+ * The server owns the prompt contracts; the client owns only the labels and the
+ * option order, so the index form's select, the settings drawer's select, and
+ * the index card's badge all read the same list. Keep the ids in step with
+ * `LOOM_FORMATS` server-side — a format the server rejects would fail the
+ * PATCH at the door.
+ */
+
+export const LOOM_FORMATS = [
+ { id: 'prose', label: 'Narrated prose', hint: 'Second-person interactive fiction — flowing paragraphs.' },
+ { id: 'teleplay', label: 'Teleplay', hint: 'Sluglines, action lines, and character cues, in screenplay format.' },
+];
+
+export const loomFormatLabel = (id) => LOOM_FORMATS.find((f) => f.id === id)?.label || LOOM_FORMATS[0].label;
+export const loomFormatHint = (id) => LOOM_FORMATS.find((f) => f.id === id)?.hint || LOOM_FORMATS[0].hint;
+
+/** The one format predicate — display, editor typography, and badges share it. */
+export const isTeleplayFormat = (id) => id === 'teleplay';
diff --git a/client/src/pages/FableLoom.jsx b/client/src/pages/FableLoom.jsx
index 7d2ff6c4c1..dbe93df10f 100644
--- a/client/src/pages/FableLoom.jsx
+++ b/client/src/pages/FableLoom.jsx
@@ -18,11 +18,12 @@ import { useAsyncAction } from '../hooks/useAsyncAction';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
import { timeAgo } from '../utils/formatters';
import { fieldClass, labelClass } from '../components/fableloom/fieldStyles';
+import { LOOM_FORMATS, isTeleplayFormat, loomFormatLabel } from '../components/fableloom/loomFormats';
import {
createLoom, deleteLoom, listLooms, listPipelineSeries, listUniverses,
} from '../services/api';
-const emptyForm = () => ({ name: '', logline: '', premise: '', styleNotes: '', universeId: '', seriesId: '' });
+const emptyForm = () => ({ name: '', logline: '', premise: '', styleNotes: '', format: 'prose', universeId: '', seriesId: '' });
export default function FableLoom() {
const navigate = useNavigate();
@@ -48,6 +49,7 @@ export default function FableLoom() {
logline: form.logline,
premise: form.premise,
styleNotes: form.styleNotes,
+ format: form.format,
universeId: form.universeId || null,
seriesId: form.seriesId || null,
}, { silent: true });
@@ -107,6 +109,15 @@ export default function FableLoom() {
placeholder="One sentence of premise"
/>
</FormField>
+ <FormField label="Scene format" labelClassName={labelClass}>
+ <select
+ className={fieldClass}
+ value={form.format}
+ onChange={(e) => setForm((p) => ({ ...p, format: e.target.value }))}
+ >
+ {LOOM_FORMATS.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
+ </select>
+ </FormField>
<FormField label="Universe (canon + style for AI)" labelClassName={labelClass}>
<select
className={fieldClass}
@@ -212,6 +223,7 @@ export default function FableLoom() {
{seriesNames.has(loom.seriesId) && (
<Pill tone="muted">{seriesNames.get(loom.seriesId)}</Pill>
)}
+ {isTeleplayFormat(loom.format) && <Pill tone="muted">{loomFormatLabel(loom.format)}</Pill>}
<span className="ml-auto">{timeAgo(loom.updatedAt)}</span>
</div>
</div>
diff --git a/client/src/pages/FableLoom.test.jsx b/client/src/pages/FableLoom.test.jsx
index 923071e268..f543e783e7 100644
--- a/client/src/pages/FableLoom.test.jsx
+++ b/client/src/pages/FableLoom.test.jsx
@@ -71,7 +71,7 @@ describe('FableLoom index', () => {
await user.click(screen.getByRole('button', { name: 'Create loom' }));
await waitFor(() => expect(api.createLoom).toHaveBeenCalledWith({
- name: 'Gate of Ash', logline: '', premise: '', styleNotes: '', universeId: null, seriesId: null,
+ name: 'Gate of Ash', logline: '', premise: '', styleNotes: '', format: 'prose', universeId: null, seriesId: null,
}, { silent: true }));
expect(navigate).toHaveBeenCalledWith('/fableloom/loom-9');
});
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 5e75d86c9f..1bd93d5a48 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -9,7 +9,7 @@
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 { ArrowLeft, BookOpenText, Loader2, Plus, Settings, Sparkles, Trash2, Waypoints } from 'lucide-react';
import toast from '../components/ui/Toast';
import Drawer from '../components/Drawer';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
@@ -21,6 +21,7 @@ import { useConfirmDelete } from '../hooks/useConfirmDelete';
import LoomCanvas from '../components/fableloom/LoomCanvas';
import LoomNodeEditor from '../components/fableloom/LoomNodeEditor';
import LoomPlayPanel from '../components/fableloom/LoomPlayPanel';
+import LoomSettingsDrawer from '../components/fableloom/LoomSettingsDrawer';
import LoomValidationPanel from '../components/fableloom/LoomValidationPanel';
import { fieldClass, labelClass } from '../components/fableloom/fieldStyles';
import {
@@ -35,6 +36,7 @@ export default function FableLoomStory() {
const [loom, setLoom] = useState(null);
const [notFound, setNotFound] = useState(false);
const [setupOpen, setSetupOpen] = useState(false);
+ const [settingsOpen, setSettingsOpen] = useState(false);
const playOpen = searchParams.get('play') === '1';
useEffect(() => {
@@ -132,8 +134,17 @@ export default function FableLoomStory() {
<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">
+ <div className="flex items-center gap-2 ml-auto">
+ <button
+ type="button"
+ onClick={() => setSettingsOpen(true)}
+ aria-label="Story settings"
+ className="flex items-center gap-1 px-2.5 py-1.5 rounded border border-port-border text-xs hover:border-port-accent"
+ >
+ <Settings size={13} /> Settings
+ </button>
+ {episode && (
+ <>
<button
type="button"
onClick={handleAddNode}
@@ -155,8 +166,9 @@ export default function FableLoomStory() {
>
<BookOpenText size={13} /> Play
</button>
- </div>
- )}
+ </>
+ )}
+ </div>
</div>
<div className="flex items-center gap-2 flex-wrap">
{loom.episodes.length > 0 && (
@@ -272,6 +284,13 @@ export default function FableLoomStory() {
/>
)}
+ <LoomSettingsDrawer
+ open={settingsOpen}
+ onClose={() => setSettingsOpen(false)}
+ loom={loom}
+ onLoomUpdate={setLoom}
+ />
+
{episode && (
<Drawer open={playOpen} onClose={() => setPlayOpen(false)} title="Play" subtitle={loom.name} size="md" bodyClassName="p-0">
<LoomPlayPanel loom={loom} episode={episode} />
diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.js
index 56193b3f83..4fa8d0dfb4 100644
--- a/client/src/services/apiFableLoom.js
+++ b/client/src/services/apiFableLoom.js
@@ -53,3 +53,6 @@ export const reviewLoomEpisode = (id, episodeId, body = {}, options = {}) => req
export const playLoomTurn = (id, episodeId, body, options = {}) => request(episodePath(id, episodeId, '/play'), {
method: 'POST', body: JSON.stringify(body), ...options,
});
+export const reformatLoom = (id, body, options = {}) => request(loomPath(id, '/reformat'), {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 73b5b527d6..0b2e2aede6 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -1010,6 +1010,13 @@
"returnsJson": true,
"variables": []
},
+ "fableloom-reformat-scenes": {
+ "name": "FableLoom — Reformat Scenes",
+ "description": "Rewrites existing branching-narrative scenes into another scene format (narrated prose ⇄ teleplay) without changing the story: same beats, same characters, same decision points, same ids. Returns { scenes[] } keyed by node id.",
+ "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.",
diff --git a/data.reference/prompts/stages/fableloom-branch-node.md b/data.reference/prompts/stages/fableloom-branch-node.md
index 8c7755b43f..f962312fbf 100644
--- a/data.reference/prompts/stages/fableloom-branch-node.md
+++ b/data.reference/prompts/stages/fableloom-branch-node.md
@@ -30,9 +30,13 @@ You are a branching-narrative designer growing new paths out of ONE scene of an
- 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.
+- Each new scene's `imagePrompt` is one sentence of concrete visual description.
- Stay consistent with the tone, continuity, and canon of the existing graph.
+## Scene format
+
+{{sceneFormatContract}}
+
## Output contract
Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
diff --git a/data.reference/prompts/stages/fableloom-play-turn.md b/data.reference/prompts/stages/fableloom-play-turn.md
index d7c360a5a1..86503c953e 100644
--- a/data.reference/prompts/stages/fableloom-play-turn.md
+++ b/data.reference/prompts/stages/fableloom-play-turn.md
@@ -26,7 +26,7 @@ You are the narrator of an interactive branching story. The reader is at one sce
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.
+3. **Narration** is written in this story's format: {{narrationFormatContract}} 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
diff --git a/data.reference/prompts/stages/fableloom-reformat-scenes.md b/data.reference/prompts/stages/fableloom-reformat-scenes.md
new file mode 100644
index 0000000000..ba202f3c07
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-reformat-scenes.md
@@ -0,0 +1,41 @@
+# FableLoom — Reformat Scenes
+
+You are rewriting existing scenes of a branching narrative into a different format. The story, the events, the characters, and the branching structure do NOT change — only how the scene text is written.
+
+## Story
+
+{{storyContext}}
+
+## World canon (names and places to keep consistent)
+
+{{canonDigest}}
+
+## Target format: {{formatLabel}}
+
+{{sceneFormatContract}}
+
+## Rules
+
+1. **Rewrite, don't re-plot.** Every beat, reveal, character, and object in the original scene must survive the rewrite. Do not add events, cut events, or change who is present.
+2. **Keep the scene's exit intact.** Each scene ends where it ended before — at the same decision point (or the same resolution, for an ending). The reader's available paths are authored separately and must still make sense as the next thing that happens.
+3. **Keep the same point in the story.** Do not summarize, expand into a new scene, or merge scenes together.
+4. **Titles stay** unless the original title is empty — return the title you were given.
+5. Return every scene you were given, keyed by the same `id`.
+
+## Scenes to rewrite
+
+```json
+{{scenesJson}}
+```
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "scenes": [
+ { "id": "the id you were given", "title": "string", "prose": "the rewritten scene" }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/fableloom-weave-episode.md b/data.reference/prompts/stages/fableloom-weave-episode.md
index a17aa404b3..081618da24 100644
--- a/data.reference/prompts/stages/fableloom-weave-episode.md
+++ b/data.reference/prompts/stages/fableloom-weave-episode.md
@@ -22,9 +22,12 @@ You are a branching-narrative designer. Build ONE complete episode of an interac
- 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.
+## Scene format
+
+{{sceneFormatContract}}
+
## Output contract
Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 0545a1da72..c9eef079fb 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -13,7 +13,7 @@ answers in-world without leaving the scene when nothing matches.
| Term | Meaning |
|---|---|
-| **Loom** | A branching-narrative story (`loom-*`): name/logline/premise, optional `universeId` + `seriesId` links, episodes. |
+| **Loom** | A branching-narrative story (`loom-*`): name/logline/premise, scene `format`, optional `playSettings` pin, 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`. |
@@ -29,6 +29,37 @@ answers in-world without leaving the scene when nothing matches.
drawer.
- **Play drawer** — the reader chat. Sessions are client-side state
(restart is free; nothing persists server-side).
+- **Story settings drawer** — scene format (plus the rewrite pass), and the
+ narrator's provider/model/effort pin.
+
+## Scene format
+
+A loom is written either as **narrated prose** (second-person interactive
+fiction) or as a **teleplay** (sluglines, action lines, character cues). The
+choice lives on the record as `format` and is rendered into every generative
+stage's prompt by `server/services/fableLoom/formats.js` — so weave, branch,
+and play-turn narration all follow it, and the reader-facing scene cards
+render a teleplay monospaced.
+
+Changing the setting steers *new* generation only. **Story settings → Rewrite
+all N scenes** runs `fableloom-reformat-scenes` over every scene of every
+episode (in chunks, persisted as each chunk lands, so a mid-run failure keeps
+what already succeeded) and re-pins the loom. It rewrites text only: ids,
+transitions, endings, and image prompts are untouched.
+
+## Playing: what costs an LLM call
+
+`POST …/play` takes EITHER `message` (free text the play stage matches to a
+path) or `transitionId` (a path the reader named outright). The second lane
+resolves straight off the authored graph — no provider call, no wait — and
+answers `resolvedBy: 'choice'`. Tapping a chip in the play drawer sends that
+lane, so the common case of "the reader picked one of the offered paths" costs
+nothing; only typed free text reaches `fableloom-play-turn`.
+
+Which provider maps typed input is the loom's own `playSettings`
+(`{ providerId, model, effort }`, set in Story settings). It beats the stage
+pin — the author chose that narrator for that story — and a per-call override
+in the request body beats both.
## AI lanes (all direct user actions; stage prompts in `data/prompts/stages/`)
@@ -38,6 +69,7 @@ answers in-world without leaving the scene when nothing matches.
| `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. |
+| `fableloom-reformat-scenes` | Rewrites existing scenes into the loom's other format (prose ⇄ teleplay), preserving every beat and decision point. |
Deterministic graph validation (no LLM) lives in
`server/lib/fableLoomGraph.js` — reachability from the opening scene, dead
diff --git a/scripts/migrations/288-fableloom-scene-format.js b/scripts/migrations/288-fableloom-scene-format.js
new file mode 100644
index 0000000000..5894bca281
--- /dev/null
+++ b/scripts/migrations/288-fableloom-scene-format.js
@@ -0,0 +1,51 @@
+/**
+ * FableLoom scene formats — a loom is written either as narrated prose or as a
+ * teleplay, and the generative stages now render that choice into their
+ * prompts (`{{sceneFormatContract}}` / `{{narrationFormatContract}}`) instead
+ * of hard-coding "100–250 words of second-person present-tense narration".
+ *
+ * `scripts/setup-data.js` only copies *missing* prompt files, so an install
+ * that already has the v1 FableLoom templates (seeded by migration 286) would
+ * keep them — and the format variables would render as literal `{{…}}` text
+ * in every weave/branch/play prompt. This rewrites the three templates when
+ * they still hash to the shipped v1 body; a customized template is left alone
+ * and warned about.
+ *
+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+// Pre-change shipped hashes — the v1 bodies seeded by migration 286.
+export const ACCEPTED_OLD_MD5 = {
+ 'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46'],
+ 'fableloom-branch-node.md': ['f558e4804b056a5961af1ea74fdef2ba'],
+ 'fableloom-play-turn.md': ['bb33dc9bc483668d88196ca972d5f364'],
+};
+
+// Post-change shipped hashes (format contract rendered from the loom record).
+export const NEW_SHIPPED_MD5 = {
+ 'fableloom-weave-episode.md': '1b27f5b0073a304c21079aa6e2c71447',
+ 'fableloom-branch-node.md': '6279b1c9912c300363a727245d22fe84',
+ 'fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'FableLoom scene format',
+ customizedHint: (filename) =>
+ ` To take the scene-format variable manually, diff:\n`
+ + ` data.reference/prompts/stages/${filename}\n`
+ + ` against your current:\n`
+ + ` data/prompts/stages/${filename}\n`
+ + ` and move the hard-coded prose rule to {{sceneFormatContract}}\n`
+ + ` (or {{narrationFormatContract}}, in the play-turn template).`,
+ skipFooter: (count) =>
+ `⚠️ ${count} FableLoom prompt(s) could not be auto-updated because they were customized.\n`
+ + ` Those looms still generate in narrated prose regardless of the story's\n`
+ + ` format setting until you merge the variable from data.reference/.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/288-fableloom-scene-format.test.js b/scripts/migrations/288-fableloom-scene-format.test.js
new file mode 100644
index 0000000000..0ccc10c1c9
--- /dev/null
+++ b/scripts/migrations/288-fableloom-scene-format.test.js
@@ -0,0 +1,21 @@
+/**
+ * Test for migration 288 — the FableLoom stages take the scene-format
+ * variable ({{sceneFormatContract}} / {{narrationFormatContract}}).
+ *
+ * Picked up via the vitest include glob in server/vitest.config.js
+ * (`../scripts/migrations/**\/*.test.js`).
+ */
+import { describe } from 'vitest';
+
+import { runPromptMigrationTests } from './_testHelpers.js';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './288-fableloom-scene-format.js';
+
+describe('migration 288 — FableLoom scene format', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-288-',
+ });
+});
diff --git a/scripts/migrations/289-fableloom-reformat-stage.js b/scripts/migrations/289-fableloom-reformat-stage.js
new file mode 100644
index 0000000000..291d9421a5
--- /dev/null
+++ b/scripts/migrations/289-fableloom-reformat-stage.js
@@ -0,0 +1,12 @@
+/**
+ * Seed the FableLoom reformat stage into existing installs.
+ *
+ * Boot runs migrations (server/index.js) but NOT `setup-data.js`, so an
+ * upgrade that pulls + `pm2 restart`s would leave the new stage unseeded and
+ * "rewrite this story as a teleplay" would throw "Stage not found" the first
+ * time it runs.
+ */
+
+import { makeSeedMigrations } from './_seedStageHelpers.js';
+
+export default makeSeedMigrations(['fableloom-reformat-scenes']);
diff --git a/scripts/migrations/289-fableloom-reformat-stage.test.js b/scripts/migrations/289-fableloom-reformat-stage.test.js
new file mode 100644
index 0000000000..6247896f59
--- /dev/null
+++ b/scripts/migrations/289-fableloom-reformat-stage.test.js
@@ -0,0 +1,18 @@
+/**
+ * Test for migration 289 — seeding the FableLoom reformat stage.
+ *
+ * Picked up via the vitest include glob in server/vitest.config.js
+ * (`../scripts/migrations/**\/*.test.js`).
+ */
+import { describe } from 'vitest';
+
+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';
+import migration from './289-fableloom-reformat-stage.js';
+
+describe('migration 289 — FableLoom reformat stage', () => {
+ runSeedStageMigrationTests({
+ migration,
+ stages: ['fableloom-reformat-scenes'],
+ prefix: 'migration-289-',
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 00c95fec95..4f42789bdf 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -55,6 +55,9 @@ const EXPECTED_STAGE_OLD = {
'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f'],
'pipeline-observer.md': ['f3dc51ac077050a887c2161ee7438181'],
'pipeline-self-improve.md': ['ed0b0df42e0690d515b8dd88911931e4'],
+ 'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46'],
+ 'fableloom-branch-node.md': ['f558e4804b056a5961af1ea74fdef2ba'],
+ 'fableloom-play-turn.md': ['bb33dc9bc483668d88196ca972d5f364'],
};
const EXPECTED_STAGE_NEW = {
'pipeline-idea-expansion.md': 'a032e4a724251ed3e3495d33c4dbab8e',
@@ -88,6 +91,9 @@ const EXPECTED_STAGE_NEW = {
'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410',
'pipeline-observer.md': '29e0212d2252b1be3278f20e2959eb8e',
'pipeline-self-improve.md': '95b378832ff78e5976a6a63fcf328090',
+ 'fableloom-weave-episode.md': '1b27f5b0073a304c21079aa6e2c71447',
+ 'fableloom-branch-node.md': '6279b1c9912c300363a727245d22fe84',
+ 'fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',
};
const EXPECTED_PARTIAL_OLD = {
'bible-deference.md': ['218f0e85643609ed85a12b1ccc7b5a8d'],
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
index b637adf18e..9457ef6b4f 100644
--- a/server/lib/fableLoomValidation.js
+++ b/server/lib/fableLoomValidation.js
@@ -7,6 +7,8 @@
import { z } from 'zod';
import { LOOM_LIMITS } from '../services/fableLoom/limits.js';
+import { LOOM_FORMATS } from '../services/fableLoom/formats.js';
+import { EFFORT_LEVELS } from './providerModels.js';
const name = z.string().trim().min(1).max(LOOM_LIMITS.NAME_MAX);
const logline = z.string().max(LOOM_LIMITS.LOGLINE_MAX);
@@ -16,12 +18,25 @@ const refId = z.string().max(LOOM_LIMITS.REF_ID_MAX).nullable();
const title = z.string().max(LOOM_LIMITS.EPISODE_TITLE_MAX);
const synopsis = z.string().max(LOOM_LIMITS.SYNOPSIS_MAX);
const nodeIdStr = z.string().min(1).max(80);
+const format = z.enum(LOOM_FORMATS);
+// The loom's pinned play routing. Nullable per field ('' from a cleared select
+// is normalized to null by the sanitizer) and nullable as a whole, so the UI
+// can clear the pin outright. `effort` is the shared ladder enum, not a free
+// string — the runner would clamp an unknown level silently, and the door
+// check is where a typo should surface.
+const effort = z.enum(EFFORT_LEVELS);
+const playSettings = z.object({
+ providerId: z.string().max(LOOM_LIMITS.PROVIDER_ID_MAX).nullable().optional(),
+ model: z.string().max(LOOM_LIMITS.MODEL_ID_MAX).nullable().optional(),
+ effort: effort.nullable().optional(),
+}).nullable();
export const loomCreateSchema = z.object({
name,
logline: logline.optional(),
premise: premise.optional(),
styleNotes: styleNotes.optional(),
+ format: format.optional(),
universeId: refId.optional(),
seriesId: refId.optional(),
});
@@ -31,6 +46,8 @@ export const loomPatchSchema = z.object({
logline: logline.optional(),
premise: premise.optional(),
styleNotes: styleNotes.optional(),
+ format: format.optional(),
+ playSettings: playSettings.optional(),
universeId: refId.optional(),
seriesId: refId.optional(),
});
@@ -75,8 +92,9 @@ export const nodeCreateSchema = z.object({
export const nodePatchSchema = z.object(nodeFields);
const llmPickFields = {
- providerId: z.string().max(100).optional(),
- model: z.string().max(200).optional(),
+ providerId: z.string().max(LOOM_LIMITS.PROVIDER_ID_MAX).optional(),
+ model: z.string().max(LOOM_LIMITS.MODEL_ID_MAX).optional(),
+ effort: effort.optional(),
};
export const weaveSchema = z.object({
@@ -95,12 +113,24 @@ export const branchSchema = z.object({
export const reviewSchema = z.object({ ...llmPickFields });
+// A turn is EITHER a reader's free text (matched to a path by the play stage)
+// or a path the reader took outright — a tapped choice needs no intent
+// mapping, so it carries the transition id and no LLM call happens at all.
export const playTurnSchema = z.object({
nodeId: nodeIdStr,
- message: z.string().min(1).max(1000),
+ message: z.string().min(1).max(1000).optional(),
+ transitionId: z.string().min(1).max(80).optional(),
transcript: z.array(z.object({
role: z.enum(['reader', 'narrator']),
text: z.string().max(4000),
})).max(50).optional(),
...llmPickFields,
+}).refine((body) => body.message || body.transitionId, {
+ message: 'A play turn needs either a message or a transitionId',
+ path: ['message'],
+});
+
+export const reformatSchema = z.object({
+ format,
+ ...llmPickFields,
});
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
index 711f4a0bea..88bbe0c7c9 100644
--- a/server/lib/promptStageCallSites.generated.json
+++ b/server/lib/promptStageCallSites.generated.json
@@ -35,6 +35,9 @@
"fableloom-play-turn": [
"server/services/fableLoom/weave.js"
],
+ "fableloom-reformat-scenes": [
+ "server/services/fableLoom/weave.js"
+ ],
"fableloom-review": [
"server/services/fableLoom/weave.js"
],
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
index 2a4214165a..aec3cc556f 100644
--- a/server/routes/fableLoom.js
+++ b/server/routes/fableLoom.js
@@ -20,6 +20,7 @@ import {
nodeCreateSchema,
nodePatchSchema,
playTurnSchema,
+ reformatSchema,
reviewSchema,
weaveSchema,
} from '../lib/fableLoomValidation.js';
@@ -35,6 +36,7 @@ import {
getLoom,
listLoomSummaries,
playTurn,
+ reformatLoom,
reviewEpisode,
updateEpisode,
updateLoom,
@@ -135,4 +137,12 @@ router.post('/:id/episodes/:episodeId/play', asyncHandler(async (req, res) => {
res.json(await playTurn(req.params.id, req.params.episodeId, input));
}));
+// Rewrite every scene of every episode into another format (prose ⇄ teleplay)
+// and pin the loom to it. Loom-scoped rather than episode-scoped: a story
+// half in screenplay and half in prose is never what the author meant.
+router.post('/:id/reformat', asyncHandler(async (req, res) => {
+ const input = validateRequest(reformatSchema, req.body);
+ res.json(await reformatLoom(req.params.id, input));
+}));
+
export default router;
diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.js
index 5b515a1d1a..7669ba370b 100644
--- a/server/routes/fableLoom.test.js
+++ b/server/routes/fableLoom.test.js
@@ -14,6 +14,7 @@ vi.mock('../services/fableLoom/index.js', () => ({
getLoom: vi.fn(),
listLoomSummaries: vi.fn(async () => []),
playTurn: vi.fn(),
+ reformatLoom: vi.fn(),
reviewEpisode: vi.fn(),
updateEpisode: vi.fn(),
updateLoom: vi.fn(),
@@ -114,6 +115,36 @@ describe('FableLoom routes', () => {
expect(fableLoom.weaveEpisode).toHaveBeenCalledWith('loom-1', 'ep-1', { guidance: 'darker', replace: true });
});
+ it('POST play accepts a tapped path instead of a message', async () => {
+ const neither = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/play')
+ .send({ nodeId: 'node-1' });
+ expect(neither.status).toBe(400);
+ expect(fableLoom.playTurn).not.toHaveBeenCalled();
+
+ fableLoom.playTurn.mockResolvedValueOnce({ action: 'move', resolvedBy: 'choice' });
+ const tapped = await request(makeApp())
+ .post('/api/fableloom/loom-1/episodes/ep-1/play')
+ .send({ nodeId: 'node-1', transitionId: 'tr-1' });
+ expect(tapped.status).toBe(200);
+ expect(fableLoom.playTurn).toHaveBeenCalledWith('loom-1', 'ep-1', { nodeId: 'node-1', transitionId: 'tr-1' });
+ });
+
+ it('POST reformat validates the target format and forwards it', async () => {
+ const invalid = await request(makeApp())
+ .post('/api/fableloom/loom-1/reformat')
+ .send({ format: 'haiku' });
+ expect(invalid.status).toBe(400);
+ expect(fableLoom.reformatLoom).not.toHaveBeenCalled();
+
+ fableLoom.reformatLoom.mockResolvedValueOnce({ loom: { id: 'loom-1' }, rewritten: 3 });
+ const ok = await request(makeApp())
+ .post('/api/fableloom/loom-1/reformat')
+ .send({ format: 'teleplay', providerId: 'claude' });
+ expect(ok.status).toBe(200);
+ expect(fableLoom.reformatLoom).toHaveBeenCalledWith('loom-1', { format: 'teleplay', providerId: 'claude' });
+ });
+
it('POST play requires a nodeId and message', async () => {
const invalid = await request(makeApp())
.post('/api/fableloom/loom-1/episodes/ep-1/play')
diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.md
index c9abf79496..12ab9dfca9 100644
--- a/server/services/fableLoom/README.md
+++ b/server/services/fableLoom/README.md
@@ -8,7 +8,8 @@ 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). |
+| `weave.js` | AI ops via `runStagedLLM`: `weaveEpisode` (full graph), `branchNode` (grow paths), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; a tapped path resolves off the graph with NO LLM call), `reformatLoom` (rewrite every scene into another format). |
+| `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. |
| `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). |
| `db.js` | PostgreSQL leaf I/O. |
diff --git a/server/services/fableLoom/formats.js b/server/services/fableLoom/formats.js
new file mode 100644
index 0000000000..e345f69c4c
--- /dev/null
+++ b/server/services/fableLoom/formats.js
@@ -0,0 +1,48 @@
+/**
+ * FableLoom scene formats — how a loom's scene text is WRITTEN, and therefore
+ * how every generative stage is told to write it.
+ *
+ * A loom is either narrated prose (second-person interactive fiction) or a
+ * teleplay (sluglines, action lines, character cues). The choice is one field
+ * on the record, and each stage that produces scene text renders the matching
+ * contract into its prompt — so the format lives here once rather than as
+ * three near-duplicate paragraphs across the templates.
+ *
+ * A leaf module (no imports): the validation schemas, the sanitizer, and the
+ * weave service all read from it without pulling in the service graph.
+ */
+
+export const LOOM_FORMATS = Object.freeze(['prose', 'teleplay']);
+export const LOOM_FORMAT_DEFAULT = 'prose';
+
+export const isLoomFormat = (value) => LOOM_FORMATS.includes(value);
+
+/** Normalize a stored/incoming format, falling back to the default. */
+export const asLoomFormat = (value) => (isLoomFormat(value) ? value : LOOM_FORMAT_DEFAULT);
+
+// What each stage is told about the `prose` field it generates. Written as
+// prompt bullets: the templates render them under their own heading.
+const SCENE_CONTRACTS = Object.freeze({
+ prose: [
+ "Each scene's `prose` is 100–250 words of second-person present-tense narration that ends at a decision point (except endings, which resolve).",
+ 'Write flowing narrative paragraphs — no sluglines, no character cues, no screenplay formatting.',
+ ].join('\n'),
+ teleplay: [
+ "Each scene's `prose` is a teleplay fragment in standard screenplay format, 120–250 words, ending at a decision point (except endings, which resolve).",
+ 'Open with a slugline in caps (`INT. HOLDING CELL - NIGHT`). Action lines are present tense, third person, no camera directions.',
+ 'Character cues are ALL CAPS on their own line above the dialogue; parentheticals go on their own line in lowercase. Introduce a character with their name in caps the first time they appear in an action line.',
+ 'Use `\\n` line breaks between every slugline, action block, cue, and dialogue block — the text is rendered as written.',
+ ].join('\n'),
+});
+
+// How the narrator answers a reader mid-scene, in the loom's format.
+const NARRATION_CONTRACTS = Object.freeze({
+ prose: '1–3 short paragraphs of second-person present-tense prose.',
+ teleplay: 'a short teleplay fragment — action lines in present tense, plus a character cue and dialogue when someone speaks. No slugline unless the location changes.',
+});
+
+export const sceneFormatContract = (format) => SCENE_CONTRACTS[asLoomFormat(format)];
+export const narrationFormatContract = (format) => NARRATION_CONTRACTS[asLoomFormat(format)];
+
+/** Human label for the format, used in prompts and error copy. */
+export const loomFormatLabel = (format) => (asLoomFormat(format) === 'teleplay' ? 'teleplay / screenplay' : 'narrated prose');
diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.js
index a23db1a884..8d4b17537b 100644
--- a/server/services/fableLoom/index.js
+++ b/server/services/fableLoom/index.js
@@ -24,6 +24,7 @@ export {
mapGeneratedGraph,
playTurn,
publicNode,
+ reformatLoom,
reviewEpisode,
weaveEpisode,
} from './weave.js';
@@ -32,3 +33,9 @@ export {
isValidLoomId,
verifySchemaVersion,
} from './store.js';
+export {
+ LOOM_FORMATS,
+ LOOM_FORMAT_DEFAULT,
+ asLoomFormat,
+ isLoomFormat,
+} from './formats.js';
diff --git a/server/services/fableLoom/limits.js b/server/services/fableLoom/limits.js
index 35f47e9876..7e5e51b86c 100644
--- a/server/services/fableLoom/limits.js
+++ b/server/services/fableLoom/limits.js
@@ -24,4 +24,7 @@ export const LOOM_LIMITS = Object.freeze({
TRIGGER_MAX: 160,
TRIGGERS_MAX: 8,
TRANSITION_DESC_MAX: 500,
+ PROVIDER_ID_MAX: 100,
+ MODEL_ID_MAX: 200,
+ EFFORT_MAX: 20,
});
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index b35a7fb015..4a8c9b8342 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -24,6 +24,7 @@ import {
writeRaw,
} from './store.js';
import { LOOM_LIMITS } from './limits.js';
+import { asLoomFormat } from './formats.js';
export { LOOM_LIMITS };
@@ -32,6 +33,24 @@ const isSafeImageFilename = (value) =>
const nullableRef = (value) => (isStr(value) && value.trim() ? value.trim().slice(0, LOOM_LIMITS.REF_ID_MAX) : null);
+/**
+ * The loom's pinned routing for the play stage — which provider/model/effort
+ * turns a reader's free text into a path. Stored as a whole object so an
+ * unset dimension stays unset (null = "fall through to the stage pin / active
+ * provider"), rather than collapsing to an empty string that would read as a
+ * deliberate choice downstream.
+ */
+const sanitizePlaySettings = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const pick = (value, max) => trimTo(value, max) || null;
+ const settings = {
+ providerId: pick(raw.providerId, LOOM_LIMITS.PROVIDER_ID_MAX),
+ model: pick(raw.model, LOOM_LIMITS.MODEL_ID_MAX),
+ effort: pick(raw.effort, LOOM_LIMITS.EFFORT_MAX),
+ };
+ return Object.values(settings).some(Boolean) ? settings : 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) }
@@ -109,6 +128,8 @@ export function sanitizeLoom(raw) {
logline: trimTo(raw.logline, LOOM_LIMITS.LOGLINE_MAX),
premise: trimTo(raw.premise, LOOM_LIMITS.PREMISE_MAX),
styleNotes: trimTo(raw.styleNotes, LOOM_LIMITS.STYLE_NOTES_MAX),
+ format: asLoomFormat(raw.format),
+ playSettings: sanitizePlaySettings(raw.playSettings),
universeId: nullableRef(raw.universeId),
seriesId: nullableRef(raw.seriesId),
episodes: (Array.isArray(raw.episodes) ? raw.episodes : [])
@@ -159,10 +180,11 @@ export async function listLooms() {
* full records would make the index multi-MB to render three counts.
*/
export async function listLoomSummaries() {
- return (await listLooms()).map(({ id, name, logline, universeId, seriesId, createdAt, updatedAt, episodes }) => ({
+ return (await listLooms()).map(({ id, name, logline, format, universeId, seriesId, createdAt, updatedAt, episodes }) => ({
id,
name,
logline,
+ format,
universeId,
seriesId,
createdAt,
@@ -178,7 +200,7 @@ export async function getLoom(id) {
return sanitizeLoom(await readRaw(id));
}
-export async function createLoom({ name, logline, premise, styleNotes, universeId, seriesId } = {}) {
+export async function createLoom({ name, logline, premise, styleNotes, format, universeId, seriesId } = {}) {
const now = new Date().toISOString();
await assertRefsExist({ universeId: nullableRef(universeId), seriesId: nullableRef(seriesId) });
const loom = sanitizeLoom({
@@ -187,6 +209,7 @@ export async function createLoom({ name, logline, premise, styleNotes, universeI
logline,
premise,
styleNotes,
+ format,
universeId,
seriesId,
episodes: [],
@@ -216,7 +239,7 @@ export function mutateLoom(id, mutator) {
});
}
-const PATCH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'universeId', 'seriesId'];
+const PATCH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'universeId', 'seriesId'];
export async function updateLoom(id, patch = {}) {
await assertRefsExist({
diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.js
index fa4d2137c4..35c9dc9857 100644
--- a/server/services/fableLoom/records.test.js
+++ b/server/services/fableLoom/records.test.js
@@ -81,6 +81,21 @@ describe('sanitizeLoom', () => {
expect(loom.episodes[0].startNodeId).toBe('n1');
});
+ it('defaults the scene format and keeps only a known one', () => {
+ expect(sanitizeLoom({ id: 'loom-1', name: 'X' }).format).toBe('prose');
+ expect(sanitizeLoom({ id: 'loom-1', name: 'X', format: 'teleplay' }).format).toBe('teleplay');
+ expect(sanitizeLoom({ id: 'loom-1', name: 'X', format: 'haiku' }).format).toBe('prose');
+ });
+
+ it('keeps a partial play pin but collapses an all-empty one to null', () => {
+ const pinned = sanitizeLoom({
+ id: 'loom-1', name: 'X', playSettings: { providerId: ' claude ', model: '', effort: null },
+ });
+ expect(pinned.playSettings).toEqual({ providerId: 'claude', model: null, effort: null });
+ expect(sanitizeLoom({ id: 'loom-1', name: 'X', playSettings: { providerId: '' } }).playSettings).toBeNull();
+ expect(sanitizeLoom({ id: 'loom-1', name: 'X' }).playSettings).toBeNull();
+ });
+
it('rejects unsafe image filenames', () => {
const loom = sanitizeLoom({
id: 'loom-1',
diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.js
index ffa16cf30c..db81197e46 100644
--- a/server/services/fableLoom/weave.js
+++ b/server/services/fableLoom/weave.js
@@ -20,6 +20,7 @@ import { renderCanonForPrompt } from '../../lib/universePromptRenderers.js';
import { analyzeEpisodeGraph, describeGraphForPrompt } from '../../lib/fableLoomGraph.js';
import { getUniverse } from '../universeBuilder.js';
import { LOOM_LIMITS, findEpisode, findNode, getLoom, mutateLoom } from './records.js';
+import { asLoomFormat, loomFormatLabel, narrationFormatContract, sceneFormatContract } from './formats.js';
const TRANSCRIPT_TURNS_MAX = 12;
@@ -35,13 +36,37 @@ const requireLoom = async (loomId) => {
return loom;
};
-const llmOptions = ({ providerId, model } = {}, source) => ({
+const llmOptions = ({ providerId, model, effort } = {}, source) => ({
source,
returnsJson: true,
...(providerId ? { providerOverride: providerId } : {}),
...(model ? { modelOverride: model } : {}),
+ ...(effort ? { effortOverride: effort } : {}),
});
+/**
+ * Routing for a play turn: an explicit per-call pick beats the loom's saved
+ * play settings, which beat the stage pin. The loom's settings use the HARD
+ * overrides deliberately — the author chose this narrator for this story, so
+ * it outranks a global stage pin the same way a per-call pick does.
+ *
+ * A model id and an effort level are both provider-specific, so the loom's are
+ * inherited only while the EFFECTIVE provider is still the one they were
+ * picked for. A per-call override that switches providers without naming its
+ * own falls through to the new provider's defaults rather than forwarding a
+ * foreign model id that would fail — the same rule as
+ * `resolveSeriesLlmOverride` (server/lib/seriesLlmOverride.js).
+ */
+const playRouting = (loom, { providerId, model, effort } = {}) => {
+ const pinned = loom.playSettings || {};
+ const inherits = !providerId || providerId === pinned.providerId;
+ return {
+ providerId: providerId || pinned.providerId || null,
+ model: model || (inherits ? pinned.model : null) || null,
+ effort: effort || (inherits ? pinned.effort : null) || null,
+ };
+};
+
/**
* Render the linked universe's canon as a prompt digest via the shared
* renderer (field precedence, per-kind caps, and the "+ N more" truncation
@@ -56,6 +81,7 @@ export async function buildCanonDigest(loom) {
const storyContext = (loom, episode) => [
`Story: ${loom.name}`,
+ `Scene format: ${loomFormatLabel(loom.format)}`,
loom.logline ? `Logline: ${loom.logline}` : '',
loom.premise ? `Premise: ${loom.premise}` : '',
episode ? `Episode ${episode.number}: ${episode.title || 'Untitled'}` : '',
@@ -107,7 +133,7 @@ export function mapGeneratedGraph(parsed) {
}
export async function weaveEpisode(loomId, episodeId, {
- guidance = '', nodeTarget, endingTarget, replace = false, providerId, model,
+ guidance = '', nodeTarget, endingTarget, replace = false, providerId, model, effort,
} = {}) {
const loom = await requireLoom(loomId);
const episode = findEpisode(loom, episodeId);
@@ -121,7 +147,8 @@ export async function weaveEpisode(loomId, episodeId, {
guidance: guidance || '(none)',
nodeTarget: String(clamp(nodeTarget, 3, 60, 12)),
endingTarget: String(clamp(endingTarget, 1, 12, 3)),
- }, llmOptions({ providerId, model }, 'fableloom-weave'));
+ sceneFormatContract: sceneFormatContract(loom.format),
+ }, llmOptions({ providerId, model, effort }, 'fableloom-weave'));
const { nodes, startNodeId } = mapGeneratedGraph(content);
const updated = await mutateLoom(loomId, (current) => {
@@ -137,7 +164,7 @@ export async function weaveEpisode(loomId, episodeId, {
// --- Branch: grow new paths out of one scene --------------------------------
export async function branchNode(loomId, episodeId, nodeId, {
- guidance = '', branchCount, providerId, model,
+ guidance = '', branchCount, providerId, model, effort,
} = {}) {
const loom = await requireLoom(loomId);
const episode = findEpisode(loom, episodeId);
@@ -153,7 +180,8 @@ export async function branchNode(loomId, episodeId, nodeId, {
sceneProse: node.prose || '(no prose yet)',
branchCount: String(count),
guidance: guidance || '(none)',
- }, llmOptions({ providerId, model }, 'fableloom-branch'));
+ sceneFormatContract: sceneFormatContract(loom.format),
+ }, llmOptions({ providerId, model, effort }, '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)
@@ -184,7 +212,7 @@ export async function branchNode(loomId, episodeId, nodeId, {
const REVIEW_SEVERITIES = new Set(['high', 'medium', 'low']);
-export async function reviewEpisode(loomId, episodeId, { providerId, model } = {}) {
+export async function reviewEpisode(loomId, episodeId, { providerId, model, effort } = {}) {
const loom = await requireLoom(loomId);
const episode = findEpisode(loom, episodeId);
const structural = analyzeEpisodeGraph(episode);
@@ -194,7 +222,7 @@ export async function reviewEpisode(loomId, episodeId, { providerId, model } = {
structuralDigest: structural.issues.length
? structural.issues.map((i) => `- [${i.severity}] ${i.message}`).join('\n')
: '(no structural issues)',
- }, llmOptions({ providerId, model }, 'fableloom-review'));
+ }, llmOptions({ providerId, model, effort }, 'fableloom-review'));
const nodeIds = new Set(episode.nodes.map((n) => n.id));
const findings = (Array.isArray(content?.findings) ? content.findings : [])
@@ -232,14 +260,30 @@ const transcriptDigest = (transcript) =>
.map((t) => `${t.role === 'reader' ? 'Reader' : 'Narrator'}: ${trimTo(t.text, 500)}`)
.join('\n');
+/**
+ * Advance one play turn.
+ *
+ * Two lanes, and the cheap one is the default: when the reader TAPPED a path
+ * (`transitionId`), there is no intent to map, so the move resolves straight
+ * off the graph — no provider call, no latency, no spend. Free text goes
+ * through the play stage, which either matches a path or answers in-world.
+ */
export async function playTurn(loomId, episodeId, {
- nodeId, message, transcript = [], providerId, model,
+ nodeId, message, transitionId, transcript = [], providerId, model, effort,
} = {}) {
const loom = await requireLoom(loomId);
const episode = findEpisode(loom, episodeId);
const node = findNode(episode, nodeId);
if (node.isEnding || !(node.transitions || []).length) {
- return { action: 'stay', narration: '', node: publicNode(node), ended: true };
+ return { action: 'stay', narration: '', node: publicNode(node), ended: true, resolvedBy: 'graph' };
+ }
+
+ if (transitionId) {
+ const taken = node.transitions.find((t) => t.id === transitionId);
+ if (!taken) {
+ throw new ServerError('That path is not on this scene', { status: 400, code: 'INVALID_TRANSITION' });
+ }
+ return moveResult(episode, node, taken, { narration: '', resolvedBy: 'choice' });
}
const choicesDigest = node.transitions.map((t) => [
@@ -249,13 +293,14 @@ export async function playTurn(loomId, episodeId, {
t.description ? ` leads to: ${t.description}` : null,
].filter(Boolean).join('\n')).join('\n');
- const { content } = await runStagedLLM('fableloom-play-turn', {
+ const { content, runId } = 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'));
+ narrationFormatContract: narrationFormatContract(loom.format),
+ }, llmOptions(playRouting(loom, { providerId, model, effort }), 'fableloom-play'));
const narration = trimTo(content?.narration, 4000);
const chosen = content?.action === 'move'
@@ -263,15 +308,86 @@ export async function playTurn(loomId, episodeId, {
: null;
// No usable choice — including a dangling edge whose target was deleted —
// stays in place rather than crashing the read.
- const next = chosen ? episode.nodes.find((n) => n.id === chosen.targetNodeId) : null;
- if (!next) {
- return { action: 'stay', narration, node: publicNode(node), ended: false };
+ if (!chosen) {
+ return { action: 'stay', narration, node: publicNode(node), ended: false, resolvedBy: 'llm', runId };
}
- return {
- action: 'move',
- transitionId: chosen.id,
- narration,
- node: publicNode(next),
- ended: next.isEnding === true,
- };
+ return moveResult(episode, node, chosen, { narration, resolvedBy: 'llm', runId });
+}
+
+/**
+ * Resolve a chosen transition to its target scene. A dangling edge (target
+ * deleted since the graph was woven) keeps the reader where they are rather
+ * than ending the read-through on a crash.
+ */
+function moveResult(episode, node, transition, { narration = '', resolvedBy, runId } = {}) {
+ const next = episode.nodes.find((n) => n.id === transition.targetNodeId);
+ const common = { narration, resolvedBy, ...(runId ? { runId } : {}) };
+ return next
+ ? { action: 'move', transitionId: transition.id, node: publicNode(next), ended: next.isEnding === true, ...common }
+ : { action: 'stay', node: publicNode(node), ended: false, ...common };
+}
+
+// --- Reformat: rewrite existing scenes into another format ------------------
+
+// Scenes per LLM call. Small enough that one refusal or truncation costs a
+// handful of scenes rather than the episode, large enough that a 13-scene
+// episode is two calls, not thirteen.
+const REFORMAT_CHUNK = 5;
+
+/**
+ * Rewrite every scene of every episode into `format` (prose ⇄ teleplay) and
+ * pin the loom to it, so later weaves/branches/play turns keep generating in
+ * the same format.
+ *
+ * Each chunk is persisted as it lands: a provider failure halfway through
+ * leaves the already-rewritten scenes rewritten, and re-running finishes the
+ * job rather than starting over.
+ */
+export async function reformatLoom(loomId, { format, providerId, model, effort } = {}) {
+ const target = asLoomFormat(format);
+ // Pin first: the scenes are rewritten INTO this format, so a run that dies
+ // halfway leaves the loom already describing what its rewritten scenes are —
+ // and it saves a second full-record round-trip at the end.
+ const loom = await mutateLoom(loomId, (current) => ({ ...current, format: target }));
+ const canonDigest = await buildCanonDigest(loom);
+ const runIds = [];
+ const sceneCount = loom.episodes.reduce((total, ep) => total + ep.nodes.length, 0);
+ let rewritten = 0;
+
+ for (const episode of loom.episodes) {
+ for (let i = 0; i < episode.nodes.length; i += REFORMAT_CHUNK) {
+ const batch = episode.nodes.slice(i, i + REFORMAT_CHUNK);
+ const { content, runId } = await runStagedLLM('fableloom-reformat-scenes', {
+ storyContext: storyContext(loom, episode),
+ canonDigest: canonDigest || '(none)',
+ formatLabel: loomFormatLabel(target),
+ sceneFormatContract: sceneFormatContract(target),
+ scenesJson: JSON.stringify(batch.map((n) => ({ id: n.id, title: n.title, prose: n.prose })), null, 2),
+ }, llmOptions({ providerId, model, effort }, 'fableloom-reformat'));
+ if (runId) runIds.push(runId);
+
+ const byId = new Map((Array.isArray(content?.scenes) ? content.scenes : [])
+ .filter((sc) => sc && typeof sc === 'object' && isStr(sc.id) && isStr(sc.prose) && sc.prose.trim())
+ .map((sc) => [sc.id, sc]));
+ if (!byId.size) continue;
+ await mutateLoom(loomId, (current) => {
+ const ep = findEpisode(current, episode.id);
+ for (const sceneNode of ep.nodes) {
+ const rewrite = byId.get(sceneNode.id);
+ if (!rewrite) continue;
+ sceneNode.prose = rewrite.prose;
+ if (isStr(rewrite.title) && rewrite.title.trim()) sceneNode.title = rewrite.title;
+ }
+ ep.updatedAt = new Date().toISOString();
+ return current;
+ });
+ rewritten += byId.size;
+ }
+ }
+
+ // A loom with nothing authored yet is a no-op, not a failure — the pin is
+ // still the point. Only a loom that HAD scenes and got none back is a bad
+ // response worth surfacing.
+ if (sceneCount && !rewritten) throw aiShapeError('The model returned no rewritten scenes');
+ return { loom: await getLoom(loomId), format: target, rewritten, runIds };
}
diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.js
index dde3d2e231..557a91ac36 100644
--- a/server/services/fableLoom/weave.test.js
+++ b/server/services/fableLoom/weave.test.js
@@ -22,10 +22,10 @@ vi.mock('../universeBuilder.js', () => ({ getUniverse: getUniverseMock }));
const getSeriesMock = vi.hoisted(() => vi.fn(async () => null));
vi.mock('../pipeline/series.js', () => ({ getSeries: getSeriesMock }));
-const { createLoom, addEpisode, addNode, updateNode, getLoom } = await import('./records.js');
+const { createLoom, addEpisode, addNode, updateLoom, updateNode, getLoom } = await import('./records.js');
const { _resetFableLoomBackend } = await import('./store.js');
const {
- branchNode, buildCanonDigest, mapGeneratedGraph, playTurn, reviewEpisode, weaveEpisode,
+ branchNode, buildCanonDigest, mapGeneratedGraph, playTurn, reformatLoom, reviewEpisode, weaveEpisode,
} = await import('./weave.js');
beforeEach(() => {
@@ -225,6 +225,104 @@ describe('playTurn', () => {
expect(result).toMatchObject({ action: 'stay', ended: true });
expect(runStagedLLM).not.toHaveBeenCalled();
});
+
+ it('takes a named transition off the graph with no LLM call at all', async () => {
+ const { loomId, episodeId, gate, insideId } = await playSetup();
+ const result = await playTurn(loomId, episodeId, {
+ nodeId: gate.id, transitionId: gate.transitions[0].id,
+ });
+ expect(result).toMatchObject({
+ action: 'move', resolvedBy: 'choice', narration: '', ended: true,
+ });
+ expect(result.node.id).toBe(insideId);
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('rejects a transition id that is not on the current scene', async () => {
+ const { loomId, episodeId, gate } = await playSetup();
+ await expect(playTurn(loomId, episodeId, { nodeId: gate.id, transitionId: 'tr-bogus' }))
+ .rejects.toMatchObject({ status: 400, code: 'INVALID_TRANSITION' });
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it("routes typed input through the loom's saved play settings, and lets a per-call pick win", async () => {
+ const { loomId, episodeId, gate } = await playSetup();
+ await updateLoom(loomId, { playSettings: { providerId: 'claude', model: 'opus', effort: 'high' } });
+ runStagedLLM.mockResolvedValue({ content: { action: 'stay', narration: 'Hmm.' } });
+
+ await playTurn(loomId, episodeId, { nodeId: gate.id, message: 'look around' });
+ expect(runStagedLLM.mock.calls[0][2]).toMatchObject({
+ providerOverride: 'claude', modelOverride: 'opus', effortOverride: 'high',
+ });
+
+ // Switching providers per call drops the pinned model and effort with it —
+ // both belong to the provider they were picked for.
+ await playTurn(loomId, episodeId, { nodeId: gate.id, message: 'look around', providerId: 'codex' });
+ expect(runStagedLLM.mock.calls[1][2]).toMatchObject({ providerOverride: 'codex' });
+ expect(runStagedLLM.mock.calls[1][2].modelOverride).toBeUndefined();
+ expect(runStagedLLM.mock.calls[1][2].effortOverride).toBeUndefined();
+
+ // ...but naming the same provider keeps them.
+ await playTurn(loomId, episodeId, { nodeId: gate.id, message: 'look around', providerId: 'claude' });
+ expect(runStagedLLM.mock.calls[2][2]).toMatchObject({
+ providerOverride: 'claude', modelOverride: 'opus', effortOverride: 'high',
+ });
+ });
+
+ it("renders the loom's format into the narration contract", async () => {
+ const { loomId, episodeId, gate } = await playSetup();
+ await updateLoom(loomId, { format: 'teleplay' });
+ runStagedLLM.mockResolvedValue({ content: { action: 'stay', narration: 'Hmm.' } });
+ await playTurn(loomId, episodeId, { nodeId: gate.id, message: 'look around' });
+ const [, variables] = runStagedLLM.mock.calls[0];
+ expect(variables.narrationFormatContract).toContain('teleplay');
+ expect(variables.storyContext).toContain('teleplay');
+ });
+});
+
+describe('reformatLoom', () => {
+ const proseSetup = 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' });
+ const insideId = updated.episodes[0].nodes.find((n) => n.title === 'Inside').id;
+ return { loomId, episodeId, gateId, insideId };
+ };
+
+ it('rewrites every returned scene, pins the format, and leaves the graph alone', async () => {
+ const { loomId, gateId, insideId } = await proseSetup();
+ runStagedLLM.mockImplementation(async (stage, variables) => ({
+ content: {
+ scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: `INT. GATE - NIGHT\n\n${sc.prose}` })),
+ },
+ runId: 'run-1',
+ }));
+
+ const result = await reformatLoom(loomId, { format: 'teleplay' });
+ expect(result).toMatchObject({ format: 'teleplay', rewritten: 2 });
+ expect(result.loom.format).toBe('teleplay');
+ const nodes = result.loom.episodes[0].nodes;
+ expect(nodes.find((n) => n.id === gateId).prose).toContain('INT. GATE - NIGHT');
+ expect(nodes.find((n) => n.id === insideId).prose).toContain('Torchlight.');
+ // The rewrite is text-only: the authored edges survive it.
+ expect(nodes.find((n) => n.id === gateId).transitions[0].targetNodeId).toBe(insideId);
+ const [stage, variables] = runStagedLLM.mock.calls[0];
+ expect(stage).toBe('fableloom-reformat-scenes');
+ expect(variables.sceneFormatContract).toContain('slugline');
+ });
+
+ it('ignores scenes the model dropped or blanked, and fails when it returns none', async () => {
+ const { loomId, gateId, insideId } = await proseSetup();
+ runStagedLLM.mockResolvedValue({ content: { scenes: [{ id: gateId, prose: 'INT. GATE' }, { id: insideId, prose: ' ' }] } });
+ const kept = await reformatLoom(loomId, { format: 'teleplay' });
+ expect(kept.rewritten).toBe(1);
+ expect(kept.loom.episodes[0].nodes.find((n) => n.id === insideId).prose).toBe('Torchlight.');
+
+ runStagedLLM.mockResolvedValue({ content: { scenes: [] } });
+ await expect(reformatLoom(loomId, { format: 'prose' }))
+ .rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });
+ });
});
describe('buildCanonDigest', () => {