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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: model FableLoom audience participation
Adam Eivy81ed597cd78e
diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsxindex 735185c55f..8009baa945 100644--- a/client/src/components/fableloom/LoomNodeEditor.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.jsx@@ -28,6 +28,7 @@ import { isTeleplayFormat } from './loomFormats';import LoomSceneMedia from './LoomSceneMedia';import { FABLELOOM_CAMERA_MOVEMENTS } from '../../../../server/lib/fableLoomCameraMovements.js';import { FABLELOOM_PLAYBACK_MODES } from '../../../../server/lib/fableLoomPlayback.js';+import { FABLELOOM_AUDIENCE_CONNECTION_STATES } from '../../../../server/lib/fableLoomParticipation.js';const toRow = (t) => ({ ...t, triggersText: (t.triggers || []).join('; ') });const rowToPatch = ({ targetNodeId, intent, triggersText, description }) => ({@@ -65,6 +66,7 @@ export default function LoomNodeEditor({videoPrompt: node.videoPrompt || '',cameraMovement: node.cameraMovement || '',playbackMode: node.playbackMode || 'decision',+ audienceConnection: node.audienceConnection || 'disconnected',isEnding: !!node.isEnding,endingLabel: node.endingLabel || '',transitions: (node.transitions || []).map(toRow),@@ -205,6 +207,8 @@ export default function LoomNodeEditor({if (!form) return null;const aiBlocked = pendingSaves > 0;+ const helperMode = loom.participationMode === 'helper';+ const audienceConnected = !helperMode || form.audienceConnection === 'connected';return (<div className="space-y-4 p-4">@@ -265,13 +269,44 @@ export default function LoomNodeEditor({}}>{FABLELOOM_PLAYBACK_MODES.map((mode) => (- <option key={mode} value={mode}>+ <option key={mode} value={mode} disabled={helperMode && !audienceConnected && mode === 'decision'}>{mode === 'cut' ? 'Automatic cut — play once, then advance' : 'Decision point — loop while awaiting input'}</option>))}</select></FormField>+ {helperMode && (+ <FormField label="Audience connection" labelClassName={labelClass}>+ <select+ className={fieldClass}+ aria-label="Audience connection"+ value={form.audienceConnection}+ onChange={(event) => {+ const audienceConnection = event.target.value;+ const nextPlaybackMode = audienceConnection === 'disconnected' ? 'cut' : form.playbackMode;+ setForm((current) => ({+ ...current,+ audienceConnection,+ playbackMode: nextPlaybackMode,+ }));+ patchNode({ audienceConnection, playbackMode: nextPlaybackMode });+ }}+ >+ {FABLELOOM_AUDIENCE_CONNECTION_STATES.map((state) => (+ <option key={state} value={state}>+ {state === 'connected' ? 'Connected — audience can help' : 'Disconnected — passive canon only'}+ </option>+ ))}+ </select>+ <p className="text-xs text-port-text-muted mt-1">+ {form.audienceConnection === 'connected'+ ? `The protagonist can hear the audience through ${loom.audienceCommunicationMedium || 'the configured medium'}.`+ : 'The audience watches but cannot choose until the communication medium is activated or restored.'}+ </p>+ </FormField>+ )}+<div className="flex items-center gap-3"><label className="flex items-center gap-2 text-sm" htmlFor="loom-node-ending"><input@@ -366,7 +401,8 @@ export default function LoomNodeEditor({<buttontype="button"onClick={runBranch}- disabled={branching || aiBlocked}+ disabled={branching || aiBlocked || !audienceConnected}+ title={!audienceConnected ? 'Connect the audience communication medium before adding decision branches' : undefined}className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50">{branching ? <Loader2 size={12} className="animate-spin" /> : <GitBranch size={12} />}diff --git a/client/src/components/fableloom/LoomNodeEditor.test.jsx b/client/src/components/fableloom/LoomNodeEditor.test.jsxindex e0767a3fec..cd5005ea01 100644--- a/client/src/components/fableloom/LoomNodeEditor.test.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.test.jsx@@ -52,6 +52,25 @@ const renderEditor = (transitions = [existingPath]) => {return { onLoomUpdate, onGenerateImage, onGenerateVideo };};+const renderHelperEditor = () => {+ const nodes = makeNodes([existingPath]);+ nodes[0].audienceConnection = 'connected';+ const helperLoom = {+ ...loom,+ participationMode: 'helper',+ audienceCommunicationMedium: 'a field radio',+ };+ render(+ <LoomNodeEditor+ loom={helperLoom}+ episode={{ id: 'ep-1', startNodeId: 'n1', nodes }}+ node={nodes[0]}+ onLoomUpdate={vi.fn()}+ onClearSelection={() => {}}+ />,+ );+};+beforeEach(() => vi.clearAllMocks());describe('LoomNodeEditor paths', () => {@@ -180,6 +199,21 @@ describe('LoomNodeEditor scene media', () => {));});+ it('turns a helper scene into an automatic cut when its audience channel disconnects', async () => {+ const user = userEvent.setup();+ updateLoomNode.mockResolvedValue({ id: 'loom-1' });+ renderHelperEditor();++ expect(screen.getByText(/hear the audience through a field radio/)).toBeInTheDocument();+ await user.selectOptions(screen.getByLabelText('Audience connection'), 'disconnected');++ await waitFor(() => expect(updateLoomNode).toHaveBeenCalledWith(+ 'loom-1', 'ep-1', 'n1',+ { audienceConnection: 'disconnected', playbackMode: 'cut' },+ { silent: true },+ ));+ });+it('reflects the decision mode applied when AI adds branches', async () => {const user = userEvent.setup();const nodes = makeNodes([existingPath]);diff --git a/client/src/components/fableloom/LoomPlayPanel.jsx b/client/src/components/fableloom/LoomPlayPanel.jsxindex 000b0a65c6..a78024397a 100644--- a/client/src/components/fableloom/LoomPlayPanel.jsx+++ b/client/src/components/fableloom/LoomPlayPanel.jsx@@ -19,6 +19,7 @@ import MediaImage from '../MediaImage';import { useAsyncAction } from '../../hooks/useAsyncAction';import { playLoomTurn } from '../../services/api';import { sceneProseClass } from './fieldStyles';+import { audienceCanParticipate } from '../../../../server/lib/fableLoomParticipation.js';const findNode = (episode, id) => episode?.nodes.find((n) => n.id === id) || null;const hasPlayableStart = (episode) => !!findNode(episode, episode?.startNodeId);@@ -33,6 +34,7 @@ const asPublic = (node) => (node ? {image: node.image,videoHistoryId: node.videoHistoryId,playbackMode: node.playbackMode || 'decision',+ audienceConnection: node.audienceConnection || 'disconnected',isEnding: !!node.isEnding,endingLabel: node.endingLabel,choices: (node.transitions || []).map((t) => ({ id: t.id, intent: t.intent })),@@ -63,7 +65,10 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode }) {// Mirrors the server's terminal rule: an ending, or a dead-end scene with// no paths out, ends the read-through.const ended = !!scene && (scene.isEnding || !scene.choices?.length);- const automaticCut = !!scene && !scene.isEnding && scene.playbackMode === 'cut' && scene.choices?.length === 1;+ const audienceConnected = audienceCanParticipate(loom, scene);+ const automaticCut = !!scene && !scene.isEnding+ && (scene.playbackMode === 'cut' || !audienceConnected)+ && scene.choices?.length === 1;const restart = () => {setScene(start);@@ -216,7 +221,7 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode }) {)}</div><div className="border-t border-port-border p-3 space-y-2">- {!ended && !automaticCut && scene?.choices?.length > 0 && (+ {!ended && audienceConnected && !automaticCut && scene?.choices?.length > 0 && (<div className="flex flex-wrap gap-1.5">{scene.choices.filter((c) => c.intent).map((c) => (<button@@ -254,10 +259,17 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode }) {</button></div>)}- {!automaticCut && <div className="flex gap-2">+ {!ended && !audienceConnected && (+ <p className="text-xs text-port-text-muted" role="status">+ Connection unavailable — the story follows its canon path until {loom.audienceCommunicationMedium || 'the audience channel'} is restored.+ </p>+ )}+ {!automaticCut && (ended || audienceConnected) && <div className="flex gap-2"><inputclassName="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?'}+ placeholder={ended+ ? 'The story has ended'+ : loom.participationMode === 'helper' ? 'What do you tell the protagonist?' : 'What do you do?'}aria-label="Your action"value={message}disabled={ended || sending}@@ -329,7 +341,9 @@ function SceneCard({)}{!node.isEnding && (<p className="mt-2 text-xs text-port-text-muted">- {automaticCut ? 'Automatic cut' : 'Decision loop — waits for viewer input'}+ {automaticCut+ ? 'Automatic cut'+ : node.audienceConnection === 'connected' ? 'Audience connected — waits for input' : 'Decision loop — waits for viewer input'}</p>)}</div>diff --git a/client/src/components/fableloom/LoomPlayPanel.test.jsx b/client/src/components/fableloom/LoomPlayPanel.test.jsxindex b100f297d4..a3fe9f32e2 100644--- a/client/src/components/fableloom/LoomPlayPanel.test.jsx+++ b/client/src/components/fableloom/LoomPlayPanel.test.jsx@@ -37,6 +37,34 @@ describe('LoomPlayPanel', () => {expect(screen.getByRole('button', { name: 'Take path: enter the gate' })).toBeInTheDocument();});+ it('keeps a helper audience passive until the configured channel connects', () => {+ const helperEpisode = {+ id: 'ep-helper', startNodeId: 'opening', nodes: [{+ id: 'opening', title: 'Opening', prose: 'The protagonist walks alone.',+ playbackMode: 'cut', audienceConnection: 'disconnected',+ transitions: [{ id: 'continue', targetNodeId: 'radio', intent: 'Continue' }],+ }, {+ id: 'radio', title: 'Radio', prose: 'The radio crackles.',+ playbackMode: 'decision', audienceConnection: 'connected',+ transitions: [{ id: 'answer', targetNodeId: 'end', intent: 'warn them' }],+ }],+ };+ render(<LoomPlayPanel+ loom={{+ ...loom,+ participationMode: 'helper',+ audienceCommunicationMedium: 'the crystal radio',+ episodes: [helperEpisode],+ }}+ episode={helperEpisode}+ />);++ expect(screen.getByText(/Connection unavailable/)).toHaveTextContent('the crystal radio');+ expect(screen.queryByLabelText('Your action')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Take path: Continue' })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Next cut' })).toBeEnabled();+ });+it('sends a tapped path as a transition id, not as free text to match', async () => {const user = userEvent.setup();playLoomTurn.mockResolvedValue({diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsxindex de34c771d0..fd5d292e34 100644--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx@@ -1,7 +1,9 @@/*** FableLoom story settings — the loom-level choices that steer every AI lane.*- * Two things live here:+ * Three things live here:+ * - **Audience participation.** Whether the audience acts as the protagonist+ * or helps an autonomous protagonist through a named in-story channel.* - **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@@ -26,6 +28,7 @@ import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providerimport { reformatLoomEpisode, updateLoom } from '../../services/api';import { fieldClass, labelClass } from './fieldStyles';import { LOOM_FORMATS, episodesNeedingReformat, loomFormatHint, loomFormatLabel } from './loomFormats';+import { FABLELOOM_PARTICIPATION_MODES } from '../../../../server/lib/fableLoomParticipation.js';/*** The one line of feedback a multi-minute rewrite gives. Built as a single@@ -48,6 +51,8 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,const [rewritingEpisode, setRewritingEpisode] = useState(null);const format = loom.format || 'prose';+ const [participationMode, setParticipationMode] = useState(loom.participationMode || 'protagonist');+ const [communicationMedium, setCommunicationMedium] = useState(loom.audienceCommunicationMedium || '');const play = loom.playSettings || {};const playProvider = providers.find((p) => p.id === play.providerId);// Only scenes not already in the target format are sent, so this is what the@@ -144,6 +149,53 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,><div className="space-y-5"><section className="space-y-2">+ <FormField label="Audience role" labelClassName={labelClass}>+ <select+ className={fieldClass}+ value={participationMode}+ disabled={saving || reformatting}+ onChange={(event) => {+ const mode = event.target.value;+ setParticipationMode(mode);+ if (mode === 'protagonist' || communicationMedium.trim()) {+ patch({+ participationMode: mode,+ ...(mode === 'helper' ? { audienceCommunicationMedium: communicationMedium.trim() } : {}),+ });+ }+ }}+ >+ {FABLELOOM_PARTICIPATION_MODES.map((mode) => (+ <option key={mode} value={mode}>+ {mode === 'helper' ? 'Audience helps the protagonist' : 'Audience acts as the protagonist'}+ </option>+ ))}+ </select>+ </FormField>+ <p className="text-xs text-port-text-muted">+ {participationMode === 'helper'+ ? 'The protagonist keeps their own agency. The audience can advise them only while an in-story connection is working.'+ : 'The audience chooses the protagonist’s actions directly, like a classic choose-your-own adventure.'}+ </p>+ {participationMode === 'helper' && (+ <FormField label="Communication medium" labelClassName={labelClass}>+ <textarea+ rows={3}+ className={fieldClass}+ value={communicationMedium}+ onChange={(event) => setCommunicationMedium(event.target.value)}+ onBlur={() => {+ if (communicationMedium.trim() !== (loom.audienceCommunicationMedium || '')) {+ patch({ participationMode: 'helper', audienceCommunicationMedium: communicationMedium.trim() });+ }+ }}+ placeholder="How the protagonist hears the audience: radio, telepathy, magic device, phone…"+ />+ </FormField>+ )}+ </section>++ <section className="border-t border-port-border pt-4 space-y-2"><FormField label="Scene format" labelClassName={labelClass}><selectclassName={fieldClass}diff --git a/client/src/components/fableloom/LoomSettingsDrawer.test.jsx b/client/src/components/fableloom/LoomSettingsDrawer.test.jsxindex bf46949351..6e76cadfc4 100644--- a/client/src/components/fableloom/LoomSettingsDrawer.test.jsx+++ b/client/src/components/fableloom/LoomSettingsDrawer.test.jsx@@ -10,7 +10,7 @@ vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [vi.mock('../ProviderModelSelector', () => ({ default: () => null }));vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));-import { reformatLoomEpisode } from '../../services/api';+import { reformatLoomEpisode, updateLoom } from '../../services/api';import toast from '../ui/Toast';import LoomSettingsDrawer from './LoomSettingsDrawer';@@ -159,3 +159,24 @@ describe('LoomSettingsDrawer rewrite', () => {expect(screen.getByText(/Every scene you have is already written as teleplay/)).toBeInTheDocument();});});++describe('LoomSettingsDrawer audience participation', () => {+ it('saves the helper role together with its required communication medium', async () => {+ updateLoom.mockResolvedValue({+ ...makeLoom([]),+ participationMode: 'helper',+ audienceCommunicationMedium: 'A silver mirror.',+ });+ const user = userEvent.setup();+ renderDrawer({ ...makeLoom([]), participationMode: 'protagonist' });++ await user.selectOptions(screen.getByLabelText('Audience role'), 'helper');+ await user.type(screen.getByLabelText('Communication medium'), 'A silver mirror.');+ await user.tab();++ await waitFor(() => expect(updateLoom).toHaveBeenCalledWith('loom-1', {+ participationMode: 'helper',+ audienceCommunicationMedium: 'A silver mirror.',+ }, { silent: true }));+ });+});diff --git a/client/src/components/pipeline/SeriesLoomsPanel.jsx b/client/src/components/pipeline/SeriesLoomsPanel.jsxindex 1ee1480f6d..24952bfd14 100644--- a/client/src/components/pipeline/SeriesLoomsPanel.jsx+++ b/client/src/components/pipeline/SeriesLoomsPanel.jsx@@ -14,9 +14,11 @@ import { useEffect, useState } from 'react';import { Link, useNavigate } from 'react-router';import { Loader2, Plus, Waypoints } from 'lucide-react';import Pill from '../ui/Pill';+import { FormField } from '../ui/FormField.jsx';import { useAsyncAction } from '../../hooks/useAsyncAction';import { timeAgo } from '../../utils/formatters';import { createLoom, listLooms } from '../../services/api';+import { fieldClass, labelClass } from '../fableloom/fieldStyles';// Mirrors LOOM_LIMITS.NAME_MAX (server/lib/fableLoomLimits.js) — the// derived name is built from the series name, which has its own longer cap, so@@ -36,6 +38,9 @@ export default function SeriesLoomsPanel({ series }) {const navigate = useNavigate();const seriesId = series?.id;const [looms, setLooms] = useState(null);+ const [showCreate, setShowCreate] = useState(false);+ const [participationMode, setParticipationMode] = useState('helper');+ const [communicationMedium, setCommunicationMedium] = useState('');useEffect(() => {if (!seriesId) return undefined;@@ -51,6 +56,8 @@ export default function SeriesLoomsPanel({ series }) {const loom = await createLoom({name: deriveLoomName(series?.name),logline: series?.logline || '',+ participationMode,+ audienceCommunicationMedium: participationMode === 'helper' ? communicationMedium.trim() : '',universeId: series?.universeId || null,seriesId,}, { silent: true });@@ -73,7 +80,7 @@ export default function SeriesLoomsPanel({ series }) {</div><buttontype="button"- onClick={runCreate}+ onClick={() => setShowCreate((shown) => !shown)}disabled={creating}className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs bg-port-accent/15 border border-port-accent/40 text-port-accent hover:bg-port-accent/25 disabled:opacity-50">@@ -84,6 +91,53 @@ export default function SeriesLoomsPanel({ series }) {</button></div>+ {showCreate && (+ <div className="rounded border border-port-border bg-port-card p-3 space-y-3">+ <div className="grid gap-3 @md:grid-cols-2">+ <FormField label="Audience role" labelClassName={labelClass}>+ <select+ className={fieldClass}+ value={participationMode}+ onChange={(event) => setParticipationMode(event.target.value)}+ disabled={creating}+ >+ <option value="helper">Audience helps the protagonist</option>+ <option value="protagonist">Audience acts as the protagonist</option>+ </select>+ </FormField>+ {participationMode === 'helper' && (+ <FormField label="Communication medium" labelClassName={labelClass}>+ <input+ className={fieldClass}+ value={communicationMedium}+ onChange={(event) => setCommunicationMedium(event.target.value)}+ placeholder="e.g. a radio activated in the opening"+ disabled={creating}+ />+ </FormField>+ )}+ </div>+ <div className="flex justify-end gap-2">+ <button+ type="button"+ onClick={() => setShowCreate(false)}+ disabled={creating}+ className="px-2.5 py-1.5 rounded border border-port-border text-xs disabled:opacity-50"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={runCreate}+ disabled={creating || (participationMode === 'helper' && !communicationMedium.trim())}+ className="px-2.5 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-50"+ >+ {creating ? 'Creating…' : 'Create narrative'}+ </button>+ </div>+ </div>+ )}+{looms === null ? (<div className="flex items-center gap-2 text-xs text-gray-500"><Loader2 size={12} className="animate-spin" aria-hidden="true" />diff --git a/client/src/components/pipeline/SeriesLoomsPanel.test.jsx b/client/src/components/pipeline/SeriesLoomsPanel.test.jsxindex 14c586bd09..6a06563b8d 100644--- a/client/src/components/pipeline/SeriesLoomsPanel.test.jsx+++ b/client/src/components/pipeline/SeriesLoomsPanel.test.jsx@@ -69,9 +69,13 @@ describe('SeriesLoomsPanel', () => {await waitFor(() => expect(screen.getByText('Example Series — branching narrative')).toBeInTheDocument());await user.click(screen.getByRole('button', { name: /New branching narrative/ }));+ await user.type(screen.getByLabelText('Communication medium'), 'A crystal radio.');+ await user.click(screen.getByRole('button', { name: 'Create narrative' }));await waitFor(() => expect(api.createLoom).toHaveBeenCalledWith({name: 'Example Series — branching narrative',logline: 'A quiet town keeps a loud secret.',+ participationMode: 'helper',+ audienceCommunicationMedium: 'A crystal radio.',universeId: 'uni-1',seriesId: 'ser-1',}, { silent: true }));@@ -86,8 +90,13 @@ describe('SeriesLoomsPanel', () => {await waitFor(() => expect(screen.getByText(/None yet/)).toBeInTheDocument());await user.click(screen.getByRole('button', { name: /New branching narrative/ }));+ await user.selectOptions(screen.getByLabelText('Audience role'), 'protagonist');+ await user.click(screen.getByRole('button', { name: 'Create narrative' }));await waitFor(() => expect(api.createLoom).toHaveBeenCalledWith(- expect.objectContaining({ universeId: null, seriesId: 'ser-2' }),+ expect.objectContaining({+ participationMode: 'protagonist', audienceCommunicationMedium: '',+ universeId: null, seriesId: 'ser-2',+ }),{ silent: true },));});diff --git a/client/src/pages/FableLoom.jsx b/client/src/pages/FableLoom.jsxindex 066b8c7ebd..82c5a52aac 100644--- a/client/src/pages/FableLoom.jsx+++ b/client/src/pages/FableLoom.jsx@@ -26,8 +26,12 @@ import { LOOM_FORMATS, isTeleplayFormat, loomFormatLabel } from '../components/fimport {createLoom, deleteLoom, generateLoomSeriesPlan, listLooms, listPipelineSeries, listUniverses,} from '../services/api';+import { FABLELOOM_PARTICIPATION_MODES } from '../../../server/lib/fableLoomParticipation.js';-const emptyForm = () => ({ name: '', logline: '', premise: '', styleNotes: '', format: 'prose', universeId: '', seriesId: '' });+const emptyForm = () => ({+ name: '', logline: '', premise: '', styleNotes: '', format: 'prose',+ participationMode: 'helper', audienceCommunicationMedium: '', universeId: '', seriesId: '',+});export default function FableLoom() {const navigate = useNavigate();@@ -65,6 +69,8 @@ export default function FableLoom() {premise: form.premise,styleNotes: form.styleNotes,format: form.format,+ participationMode: form.participationMode,+ audienceCommunicationMedium: form.participationMode === 'helper' ? form.audienceCommunicationMedium.trim() : '',universeId: form.universeId || null,seriesId: form.seriesId || null,}, { silent: true });@@ -141,6 +147,31 @@ export default function FableLoom() {{LOOM_FORMATS.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}</select></FormField>+ <FormField label="Audience role" labelClassName={labelClass}>+ <select+ className={fieldClass}+ value={form.participationMode}+ onChange={(e) => setForm((p) => ({ ...p, participationMode: e.target.value }))}+ >+ {FABLELOOM_PARTICIPATION_MODES.map((mode) => (+ <option key={mode} value={mode}>+ {mode === 'helper' ? 'Audience helps the protagonist' : 'Audience acts as the protagonist'}+ </option>+ ))}+ </select>+ </FormField>+ {form.participationMode === 'helper' && (+ <FormField label="Audience communication medium" labelClassName={labelClass}>+ <textarea+ rows={2}+ className={fieldClass}+ value={form.audienceCommunicationMedium}+ onChange={(e) => setForm((p) => ({ ...p, audienceCommunicationMedium: e.target.value }))}+ placeholder="e.g. a cracked field radio the protagonist activates in the opening"+ required+ />+ </FormField>+ )}<FormField label="Universe (canon + style for AI)" labelClassName={labelClass}><selectclassName={fieldClass}@@ -216,7 +247,7 @@ export default function FableLoom() {<buttontype="submit"value="empty"- disabled={creating || !form.name.trim()}+ disabled={creating || !form.name.trim() || (form.participationMode === 'helper' && !form.audienceCommunicationMedium.trim())}className="px-4 py-2 rounded border border-port-border text-sm hover:border-port-accent disabled:opacity-50">{creating ? 'Creating…' : 'Create loom'}@@ -224,7 +255,7 @@ export default function FableLoom() {<buttontype="submit"value="draft"- disabled={creating || providersLoading || !form.name.trim()}+ disabled={creating || providersLoading || !form.name.trim() || (form.participationMode === 'helper' && !form.audienceCommunicationMedium.trim())}className="flex items-center justify-center gap-1.5 px-4 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50"><Sparkles size={14} /> {creating ? 'Creating…' : 'Create & draft plan'}@@ -287,6 +318,7 @@ export default function FableLoom() {{seriesNames.has(loom.seriesId) && (<Pill tone="muted">{seriesNames.get(loom.seriesId)}</Pill>)}+ {loom.participationMode === 'helper' && <Pill tone="accent" bordered={false}>Audience helper</Pill>}{isTeleplayFormat(loom.format) && <Pill tone="muted">{loomFormatLabel(loom.format)}</Pill>}<span className="ml-auto">{timeAgo(loom.updatedAt)}</span></div>diff --git a/client/src/pages/FableLoom.test.jsx b/client/src/pages/FableLoom.test.jsxindex 3a751ccdc0..c8977e6698 100644--- a/client/src/pages/FableLoom.test.jsx+++ b/client/src/pages/FableLoom.test.jsx@@ -30,6 +30,7 @@ const looms = [logline: 'A crown that remembers.',universeId: 'uni-1',seriesId: null,+ participationMode: 'helper',updatedAt: '2026-08-20T00:00:00Z',episodeCount: 1,sceneCount: 3,@@ -60,6 +61,7 @@ describe('FableLoom index', () => {expect(screen.getByText('1 episode')).toBeInTheDocument();expect(screen.getByText('3 scenes')).toBeInTheDocument();expect(screen.getByText('2 endings')).toBeInTheDocument();+ expect(screen.getByText('Audience helper')).toBeInTheDocument();await waitFor(() => expect(screen.getByText('Aria Verse')).toBeInTheDocument());});@@ -77,10 +79,13 @@ describe('FableLoom index', () => {await user.click(screen.getByRole('button', { name: /New loom/ }));await user.type(screen.getByLabelText('Name'), 'Gate of Ash');+ await user.type(screen.getByLabelText('Audience communication medium'), 'A crystal radio.');await user.click(screen.getByRole('button', { name: 'Create loom' }));await waitFor(() => expect(api.createLoom).toHaveBeenCalledWith({- name: 'Gate of Ash', logline: '', premise: '', styleNotes: '', format: 'prose', universeId: null, seriesId: null,+ name: 'Gate of Ash', logline: '', premise: '', styleNotes: '', format: 'prose',+ participationMode: 'helper', audienceCommunicationMedium: 'A crystal radio.',+ universeId: null, seriesId: null,}, { silent: true }));expect(navigate).toHaveBeenCalledWith('/fableloom/loom-9/plan');expect(api.generateLoomSeriesPlan).not.toHaveBeenCalled();@@ -95,6 +100,7 @@ describe('FableLoom index', () => {await user.click(screen.getByRole('button', { name: /New loom/ }));await user.type(screen.getByLabelText('Name'), 'Gate of Ash');+ await user.type(screen.getByLabelText('Audience communication medium'), 'A crystal radio.');await user.selectOptions(await screen.findByLabelText('Plan AI provider'), 'codex');await user.selectOptions(screen.getByLabelText('Model'), 'gpt-5.6');await user.selectOptions(screen.getByLabelText('Thinking effort'), 'high');diff --git a/data.reference/prompts/stages/fableloom-branch-node.md b/data.reference/prompts/stages/fableloom-branch-node.mdindex 8334096839..69ba199e38 100644--- a/data.reference/prompts/stages/fableloom-branch-node.md+++ b/data.reference/prompts/stages/fableloom-branch-node.md@@ -24,6 +24,10 @@ You are a branching-narrative designer growing new paths out of ONE scene of an{{guidance}}+## Audience participation++{{participationContract}}+## Design contract- Create exactly {{branchCount}} new branches out of this scene. Each branch is a NEW scene plus the intent that leads to it.@@ -33,6 +37,7 @@ You are a branching-narrative designer growing new paths out of ONE scene of an- Each new scene's `imagePrompt` is one sentence of concrete visual description.- Each new scene's `videoPrompt` directs one renderable clip: visible action, one primary camera movement, pace, atmosphere, and final beat. Never put a cut or angle change inside it.- Set `playbackMode` to `decision`: a newly branched node has no outgoing path yet, so it must wait for viewer choice/feedback. Its loop must depict repeatable ongoing action, not an irreversible beat.+- Set `audienceConnection` to `connected`. Branching is only available where this story's audience can participate through its configured role or communication channel.- Choose `cameraMovement` from this vocabulary (the stable id before the parentheses):{{cameraMovementCatalog}}@@ -60,6 +65,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"videoPrompt": "string","cameraMovement": "slow-dolly-in","playbackMode": "decision",+ "audienceConnection": "connected","isEnding": false,"endingLabel": ""}diff --git a/data.reference/prompts/stages/fableloom-feedback-episode.md b/data.reference/prompts/stages/fableloom-feedback-episode.mdindex ccd5cb1ed4..b8e0b51d8d 100644--- a/data.reference/prompts/stages/fableloom-feedback-episode.md+++ b/data.reference/prompts/stages/fableloom-feedback-episode.md@@ -25,12 +25,13 @@ The bracketed values are stable scene and path ids. They are the only records yo- Interpret the feedback as an actionable revision, not as a request for critique or an explanation.- Return only the fields that need to change. An omitted field is preserved. A present empty string intentionally clears that field.- You may revise the episode `title` and `synopsis`.-- You may revise existing scenes' `title`, complete `prose`, `imagePrompt`, `videoPrompt`, `cameraMovement`, `playbackMode`, `isEnding`, and `endingLabel`.+- You may revise existing scenes' `title`, complete `prose`, `imagePrompt`, `videoPrompt`, `cameraMovement`, `playbackMode`, `audienceConnection`, `isEnding`, and `endingLabel`.- You may revise the `intent`, `triggers`, `description`, or `targetNodeId` of an existing path, using its existing path id.- Do not add or remove scenes or paths. Keep every id exactly as shown. Keep any changed `targetNodeId` pointed at an existing scene id.- A prose edit must be a complete replacement for that scene, not a summary, placeholder, or editorial note. Preserve the episode's scene format and continuity.- Each scene is one continuous camera cut and one separately rendered video clip. A revised `videoPrompt` must contain visible action, one primary move, pace, atmosphere, and final beat—never an edit or second setup.- `playbackMode: "cut"` plays once and advances through its one Continue path. `playbackMode: "decision"` loops seamlessly while awaiting viewer choice or feedback; its action must be repeatable rather than irreversible.+- In helper mode, `audienceConnection: "connected"` means the configured communication medium is working in-world and the audience may advise the protagonist. A `disconnected` scene cannot be a decision loop and must follow its one canon continuation. Preserve or explicitly dramatize activation, loss, and restoration when revising this state.- Choose `cameraMovement` from this vocabulary:{{cameraMovementCatalog}}@@ -54,6 +55,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"videoPrompt": "new single-clip video prompt, only when changed","cameraMovement": "slow-dolly-in, only when changed","playbackMode": "cut or decision, only when changed",+ "audienceConnection": "connected or disconnected, only when changed","isEnding": false,"endingLabel": "new ending label, only when changed","transitions": [diff --git a/data.reference/prompts/stages/fableloom-review.md b/data.reference/prompts/stages/fableloom-review.mdindex 3048cfa7f6..df61e1393f 100644--- a/data.reference/prompts/stages/fableloom-review.md+++ b/data.reference/prompts/stages/fableloom-review.md@@ -21,6 +21,7 @@ You are a story editor reviewing ONE episode of an interactive branching narrati3. **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.+6. **Audience contract.** In helper mode, verify that the configured communication medium is established close to the beginning, the first connection invites the audience in as themselves, decisions occur only while it works, and any loss/restoration is clear in the story. The protagonist must retain independent agency rather than becoming an audience-controlled avatar.Flag only concrete, fixable problems — name the scene and propose the smallest edit. Do NOT pad with low-confidence "consider also…" entries.diff --git a/data.reference/prompts/stages/fableloom-weave-episode.md b/data.reference/prompts/stages/fableloom-weave-episode.mdindex 5f7b42cd31..99536e9568 100644--- a/data.reference/prompts/stages/fableloom-weave-episode.md+++ b/data.reference/prompts/stages/fableloom-weave-episode.md@@ -14,6 +14,10 @@ You are a story writer and creative director. Build ONE complete episode of an i{{guidance}}+## Audience participation++{{participationContract}}+## Existing episode graph{{existingGraph}}@@ -26,6 +30,7 @@ When an existing graph is present, this is a reweave: preserve its story events,- Each node is exactly ONE continuous shot with one primary framing and one camera movement. Split every change of angle, framing, location, time, or camera movement into another node.- Set `playbackMode: "cut"` on setup/action nodes that play once and automatically feed the next camera cut. They must have exactly one `Continue` transition.- Set `playbackMode: "decision"` on choice or feedback nodes. Their video is designed to loop seamlessly while the experience waits for the viewer; give them 1–4 distinct intent paths. The loop must show an ongoing, repeatable situation rather than irreversible action (for example, a guard pacing a hallway while the viewer decides when to move).+- Set `audienceConnection` on every node. In helper mode, the opening is passive until the configured communication medium is visibly activated close to the beginning; that first connected scene must invite the audience into the story as themselves. Only `connected` scenes may use `playbackMode: "decision"`. Every `disconnected` scene uses `playbackMode: "cut"` with exactly one canon continuation, including scenes after the medium is lost, stolen, broken, or jammed. A later scene may restore it. In protagonist mode use `connected` on decision scenes and `disconnected` on automatic cuts.- Reserve multiple paths for genuine viewer decisions. Endings must differ meaningfully in outcome and tone.- Exactly one scene is the opening (`startKey`). Every scene must be reachable from it.- Every non-ending node needs either one `Continue` path for consecutive coverage or 2–4 outgoing paths at a genuine decision. Each path gets: an `intent` (a short imperative label, ≤10 words), 2–4 `triggers` (example free-text phrasings a reader might type), and a one-sentence `description` of where it leads (spoiler-safe).@@ -58,6 +63,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"videoPrompt": "string","cameraMovement": "slow-dolly-in","playbackMode": "cut",+ "audienceConnection": "disconnected","isEnding": false,"transitions": [{ "targetKey": "s2", "intent": "string", "triggers": ["string"], "description": "string" }@@ -71,6 +77,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"videoPrompt": "string","cameraMovement": "locked-off","playbackMode": "cut",+ "audienceConnection": "disconnected","isEnding": true,"endingLabel": "string","transitions": []diff --git a/docs/features/fableloom.md b/docs/features/fableloom.mdindex a978f63968..957e072eab 100644--- a/docs/features/fableloom.md+++ b/docs/features/fableloom.md@@ -5,16 +5,16 @@ A loom progresses from a text teleplay, through storyboard stills, to renderedvideo clips without changing its graph. Each node is one comic-panel-likecamera cut and one eventual video file. Automatic cuts play once and continue;decision nodes loop while the viewer chooses a path or gives free-text-feedback. A loom holds one or more ordered episodes, and the Play surface can+feedback—when that story's audience role permits it. A loom holds one or more ordered episodes, and the Play surface canrehearse the same experience at any of those three production stages.## Concepts| Term | Meaning ||---|---|-| **Loom** | A branching-narrative story (`loom-*`): name/logline/premise, scene `format`, optional `playSettings` pin, optional `universeId` + `seriesId` links, episodes. |+| **Loom** | A branching-narrative story (`loom-*`): name/logline/premise, scene `format`, audience `participationMode`, helper `audienceCommunicationMedium`, optional `playSettings` pin, optional `universeId` + `seriesId` links, episodes. || **Episode** | One playable graph (`ep-*`): title, synopsis (feeds generation), `startNodeId`, nodes. |-| **Scene node** | One camera cut (`node-*`): teleplay/prose, image prompt/render, single-clip video prompt/render, camera movement, `playbackMode`, ending state, transitions. |+| **Scene node** | One camera cut (`node-*`): teleplay/prose, image prompt/render, single-clip video prompt/render, camera movement, `playbackMode`, `audienceConnection`, ending state, transitions. || **Transition** | An intent-labeled edge (`tr-*`): `intent`, `triggers` (example phrasings), spoiler-safe `description`, `targetNodeId`. |## Playback contract@@ -36,6 +36,27 @@ The deterministic validator rejects an automatic cut without exactly one nextpath. Legacy nodes default to `decision`; an upgrade therefore never startsauto-advancing an existing choice story without an author edit or reweave.+## Audience participation++Every loom chooses one of two roles:++- **Helper (the new-story default and primary experience).** The protagonist+ has independent agency. The audience enters the fiction as themselves and+ advises the protagonist through a configured medium such as a radio,+ telepathic link, magic device, or phone.+- **Protagonist.** The audience directly chooses the protagonist's actions,+ preserving classic choose-your-own-adventure behavior. Looms created before+ this setting existed read as protagonist mode for compatibility.++Helper stories annotate every scene with `audienceConnection`. The opening is+passive canon (`disconnected`) until the story visibly activates the configured+medium close to the beginning and invites the audience to participate. Only a+`connected` scene may wait at a decision loop or accept typed input. If the+medium is lost, stolen, broken, or jammed, disconnected scenes continue through+their single automatic canon path until a later scene restores the connection.+The graph validator flags helper episodes that never connect, connect too late,+or expose a decision while disconnected.+## Surfaces- **`/fableloom`** — index: create/delete looms, link a universe (canon +@@ -58,8 +79,8 @@ auto-advancing an existing choice story without an author edit or reweave.rendered decision nodes loop. At an episode ending the player continues tothe next ordered episode, allowing a full loom/series read-through. Sessionsare 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.+- **Story settings drawer** — audience role and communication medium, scene+ format (plus the rewrite pass), and the narrator's provider/model/effort pin.- **Series detail page** (`/pipeline/series/:seriesId`) — a "Branchingnarratives" card lists the looms linked to that series (counts + a link intothe editor) and spawns a new one pre-linked to the series and its universe.@@ -123,7 +144,8 @@ path) or `transitionId` (a path the reader named outright). The second laneresolves straight off the authored graph — no provider call, no wait — andanswers `resolvedBy: 'choice'`. Tapping a chip and automatic cut advancementboth send that cheap lane, so neither costs an LLM call. Only typed free text-at a decision loop reaches `fableloom-play-turn`. Automatic nodes do not expose+at an available decision loop reaches `fableloom-play-turn`. Automatic nodes+and disconnected helper scenes do not exposethe text box: their one path is production sequencing, not a viewer decision.Which provider maps typed input is the loom's own `playSettings`@@ -136,7 +158,7 @@ in the request body beats both.| Stage | What it does ||---|---|| `fableloom-generate-series-plan` | Drafts the full series arc, ordered plot points, and side quests from the loom metadata, linked-universe canon, and episode outline. |-| `fableloom-weave-episode` | Generates or reweaves a full episode as single-camera-cut nodes. The story writer/creative director chooses node and ending counts, marks automatic cuts vs decision loops, and assigns camera/video direction. A reweave sees and preserves the existing story graph while splitting multi-cut scenes. |+| `fableloom-weave-episode` | Generates or reweaves a full episode as single-camera-cut nodes. The story writer/creative director chooses node and ending counts, establishes the configured audience role/medium near the opening, tracks connection availability, marks automatic cuts vs decision loops, and assigns camera/video direction. A reweave sees and preserves the existing story graph while splitting multi-cut scenes. || `fableloom-branch-node` | Grows N new intent-labeled single-cut branches with playback and camera direction. || `fableloom-play-turn` | Resolves one reader message: `move` through a matched transition or `stay` with in-world narration. || `fableloom-review` | Story-editor critique (intent clarity, branch coherence, ending payoff) layered over the deterministic checks. |@@ -144,8 +166,8 @@ in the request body beats both.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-the exactly-one-next-path contract for automatic cuts —+ends, dangling transitions, unreachable endings, duplicate/empty intents,+audience-connection availability, and the exactly-one-next-path contract for automatic cuts —and renders in the editor's Structure panel via`GET /api/fableloom/:id/episodes/:episodeId/validate`.diff --git a/scripts/migrations/288-fableloom-scene-format.js b/scripts/migrations/288-fableloom-scene-format.jsindex abee5833ba..51d4cd8892 100644--- a/scripts/migrations/288-fableloom-scene-format.js+++ b/scripts/migrations/288-fableloom-scene-format.js@@ -25,8 +25,8 @@ export const ACCEPTED_OLD_MD5 = {// Post-change shipped hashes (format contract rendered from the loom record).export const NEW_SHIPPED_MD5 = {- 'fableloom-weave-episode.md': '4c9454d1537c4ebb3becbfa04fae3ed8',- 'fableloom-branch-node.md': 'c14e2b9c435e43a8c3b134a62cd66d08',+ 'fableloom-weave-episode.md': '18a442e39b973e4074a0d595928a665d',+ 'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da','fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',};diff --git a/scripts/migrations/310-fableloom-camera-cuts.js b/scripts/migrations/310-fableloom-camera-cuts.jsindex ebabad322c..2e89f326a2 100644--- a/scripts/migrations/310-fableloom-camera-cuts.js+++ b/scripts/migrations/310-fableloom-camera-cuts.js@@ -12,9 +12,9 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'fableloom-weave-episode.md': '4c9454d1537c4ebb3becbfa04fae3ed8',- 'fableloom-branch-node.md': 'c14e2b9c435e43a8c3b134a62cd66d08',- 'fableloom-feedback-episode.md': 'd09bb405478d24c294b0c658ef365cd1',+ 'fableloom-weave-episode.md': '18a442e39b973e4074a0d595928a665d',+ 'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da',+ 'fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/311-fableloom-audience-participation.js b/scripts/migrations/311-fableloom-audience-participation.jsnew file mode 100644index 0000000000..0b80a91249--- /dev/null+++ b/scripts/migrations/311-fableloom-audience-participation.js@@ -0,0 +1,29 @@+/** Upgrade FableLoom prompts with audience-role and communication-channel rules. */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'fableloom-weave-episode.md': ['4c9454d1537c4ebb3becbfa04fae3ed8'],+ 'fableloom-branch-node.md': ['c14e2b9c435e43a8c3b134a62cd66d08'],+ 'fableloom-feedback-episode.md': ['d09bb405478d24c294b0c658ef365cd1'],+ 'fableloom-review.md': ['2802f269f246e00ec5a8937637d42de6'],+};++export const NEW_SHIPPED_MD5 = {+ 'fableloom-weave-episode.md': '18a442e39b973e4074a0d595928a665d',+ 'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da',+ 'fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670',+ 'fableloom-review.md': 'c26a641f6d0530caef7d1186c3b09937',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'FableLoom audience participation and communication channels',+ customizedHint: (filename) =>+ ` Merge the helper/protagonist audience contract and per-scene connection rules from\n`+ + ` data.reference/prompts/stages/${filename} into the installed template.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/311-fableloom-audience-participation.test.js b/scripts/migrations/311-fableloom-audience-participation.test.jsnew file mode 100644index 0000000000..33959f9452--- /dev/null+++ b/scripts/migrations/311-fableloom-audience-participation.test.js@@ -0,0 +1,16 @@+import { describe } from 'vitest';++import migration, {+ applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5,+} from './311-fableloom-audience-participation.js';+import { runPromptMigrationTests } from './_testHelpers.js';++describe('migration 311 — FableLoom audience participation prompts', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-311-',+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 9cbdf42664..013ca251b1 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -55,10 +55,11 @@ const EXPECTED_STAGE_OLD = {'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f'],'pipeline-observer.md': ['f3dc51ac077050a887c2161ee7438181'],'pipeline-self-improve.md': ['ed0b0df42e0690d515b8dd88911931e4'],- 'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46', '1b27f5b0073a304c21079aa6e2c71447'],- 'fableloom-branch-node.md': ['f558e4804b056a5961af1ea74fdef2ba', '6279b1c9912c300363a727245d22fe84'],+ 'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46', '1b27f5b0073a304c21079aa6e2c71447', '4c9454d1537c4ebb3becbfa04fae3ed8'],+ 'fableloom-branch-node.md': ['f558e4804b056a5961af1ea74fdef2ba', '6279b1c9912c300363a727245d22fe84', 'c14e2b9c435e43a8c3b134a62cd66d08'],'fableloom-play-turn.md': ['bb33dc9bc483668d88196ca972d5f364'],- 'fableloom-feedback-episode.md': ['43d1525fcedce99b933ae5b003516a36'],+ 'fableloom-feedback-episode.md': ['43d1525fcedce99b933ae5b003516a36', 'd09bb405478d24c294b0c658ef365cd1'],+ 'fableloom-review.md': ['2802f269f246e00ec5a8937637d42de6'],};const EXPECTED_STAGE_NEW = {'pipeline-idea-expansion.md': 'a032e4a724251ed3e3495d33c4dbab8e',@@ -92,10 +93,11 @@ const EXPECTED_STAGE_NEW = {'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410','pipeline-observer.md': '29e0212d2252b1be3278f20e2959eb8e','pipeline-self-improve.md': '95b378832ff78e5976a6a63fcf328090',- 'fableloom-weave-episode.md': '4c9454d1537c4ebb3becbfa04fae3ed8',- 'fableloom-branch-node.md': 'c14e2b9c435e43a8c3b134a62cd66d08',+ 'fableloom-weave-episode.md': '18a442e39b973e4074a0d595928a665d',+ 'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da','fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',- 'fableloom-feedback-episode.md': 'd09bb405478d24c294b0c658ef365cd1',+ 'fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670',+ 'fableloom-review.md': 'c26a641f6d0530caef7d1186c3b09937',};const EXPECTED_PARTIAL_OLD = {'bible-deference.md': ['218f0e85643609ed85a12b1ccc7b5a8d'],diff --git a/server/lib/README.md b/server/lib/README.mdindex ff3231b1cf..552d3c1930 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -34,6 +34,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. || `fableLoomCameraMovements.js` | Shared FableLoom camera-movement registry for generated cut direction and the manual scene editor selector. || `fableLoomPlayback.js` | FableLoom node playback modes (`cut` auto-advances; `decision` loops while awaiting input), with the backward-compatible default. |+| `fableLoomParticipation.js` | FableLoom audience roles (helper vs protagonist), per-scene connection availability, prompt contracts, and backward-compatible defaults. || `fableLoomFormats.js` | FableLoom scene formats (`LOOM_FORMATS`, `asLoomFormat`, `sceneFormatContract`, …) — how a loom writes scene text, read by validation, the sanitizer, and every generative stage. || `postDrillTypes.js` | MeatSpace POST drill vocabularies (`CACHEABLE_TYPES`, `COGNITIVE_DRILL_TYPES`), kept below validation so a route schema never pulls in the POST services (and, through them, the LLM drill generator). || `spriteVocabulary.js` | Sprite id pattern, record kinds, the canonical 8-direction order + derived anchor set, `TURNAROUND_ID`, and the animation provider ids — the alphabets the sprite route schemas enumerate, kept below the sprite services. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 403a6cb329..6482867cb9 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -8790,7 +8790,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 200+ "line": 203}]},@@ -8801,7 +8801,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 139+ "line": 142}]},@@ -8812,7 +8812,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 149+ "line": 152}]},@@ -8823,7 +8823,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 144+ "line": 147}]},@@ -8834,7 +8834,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 187+ "line": 190}]},@@ -8845,7 +8845,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 162+ "line": 165}]},@@ -8856,7 +8856,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 174+ "line": 177}]},@@ -8867,7 +8867,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 167+ "line": 170}]},@@ -8878,7 +8878,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 205+ "line": 208}]},@@ -8889,7 +8889,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 216+ "line": 219}]},@@ -8900,7 +8900,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 192+ "line": 195}]},@@ -8922,7 +8922,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 182+ "line": 185}]},diff --git a/server/lib/fableLoomGraph.js b/server/lib/fableLoomGraph.jsindex 89a762f6fa..ee4d5e002d 100644--- a/server/lib/fableLoomGraph.js+++ b/server/lib/fableLoomGraph.js@@ -30,6 +30,9 @@ export const GRAPH_ISSUE_CODES = Object.freeze({ENDING_UNREACHABLE: 'ENDING_UNREACHABLE',SELF_LOOP: 'SELF_LOOP',CUT_TRANSITION_COUNT: 'CUT_TRANSITION_COUNT',+ DISCONNECTED_DECISION: 'DISCONNECTED_DECISION',+ NO_AUDIENCE_CONNECTION: 'NO_AUDIENCE_CONNECTION',+ LATE_AUDIENCE_CONNECTION: 'LATE_AUDIENCE_CONNECTION',});/**@@ -71,7 +74,9 @@ export function computeGraphLayers(episode) {* `{ issues, stats }`; `issues` entries are* `{ code, severity: 'error'|'warning', message, nodeId?, transitionId? }`.*/-export function analyzeEpisodeGraph(episode) {+export function analyzeEpisodeGraph(episode, {+ participationMode = 'protagonist', requireAudienceIntroduction = false,+} = {}) {const nodes = asArray(episode?.nodes);const byId = new Map(nodes.map((n) => [n.id, n]));const issues = [];@@ -97,6 +102,27 @@ export function analyzeEpisodeGraph(episode) {push(GRAPH_ISSUE_CODES.ENDING_UNREACHABLE, 'error', 'No ending is reachable from the opening scene.');}+ if (participationMode === 'helper' && requireAudienceIntroduction && nodes.length) {+ const connected = nodes.filter((node) => node?.audienceConnection === 'connected' && depthById.has(node.id));+ if (!connected.length) {+ push(+ GRAPH_ISSUE_CODES.NO_AUDIENCE_CONNECTION,+ 'error',+ 'The audience is never invited into the story through its communication medium.',+ );+ } else {+ const firstDepth = Math.min(...connected.map((node) => depthById.get(node.id)));+ if (firstDepth > 3) {+ push(+ GRAPH_ISSUE_CODES.LATE_AUDIENCE_CONNECTION,+ 'warning',+ 'The audience communication channel is not activated until late in the opening sequence.',+ { nodeId: connected.find((node) => depthById.get(node.id) === firstDepth)?.id },+ );+ }+ }+ }+for (const node of nodes) {const transitions = asArray(node?.transitions);const label = node?.title || node?.id;@@ -118,6 +144,15 @@ export function analyzeEpisodeGraph(episode) {{ nodeId: node.id },);}+ if (participationMode === 'helper' && !node?.isEnding+ && node?.audienceConnection !== 'connected' && node?.playbackMode !== 'cut') {+ push(+ GRAPH_ISSUE_CODES.DISCONNECTED_DECISION,+ 'error',+ `"${label}" waits for viewer input while the audience communication channel is disconnected.`,+ { nodeId: node.id },+ );+ }const seenIntents = new Set();for (const tr of transitions) {@@ -170,6 +205,7 @@ export function describeGraphForPrompt(episode, { proseLimit = 400 } = {}) {node.id === episode?.startNodeId ? 'START' : null,node?.isEnding ? `ENDING${isStr(node?.endingLabel) ? `: ${node.endingLabel}` : ''}` : null,node?.isEnding ? null : (node?.playbackMode === 'cut' ? 'AUTO CUT' : 'DECISION LOOP'),+ node?.audienceConnection === 'connected' ? 'AUDIENCE CONNECTED' : 'AUDIENCE DISCONNECTED',].filter(Boolean);lines.push(`[${node.id}] ${node.title || 'Untitled scene'}${flags.length ? ` (${flags.join(') (')})` : ''}`);const prose = typeof node.prose === 'string' ? node.prose.trim() : '';diff --git a/server/lib/fableLoomGraph.test.js b/server/lib/fableLoomGraph.test.jsindex 24f5d31e71..4c51a9a0fb 100644--- a/server/lib/fableLoomGraph.test.js+++ b/server/lib/fableLoomGraph.test.js@@ -111,6 +111,30 @@ describe('analyzeEpisodeGraph', () => {expect(issueCodes(one)).not.toContain(GRAPH_ISSUE_CODES.CUT_TRANSITION_COUNT);});+ it('requires helper stories to connect near the opening and blocks disconnected decisions', () => {+ const neverConnected = soundEpisode();+ neverConnected.nodes[0].playbackMode = 'cut';+ neverConnected.nodes[0].transitions = [tr('t1', 'n2', 'Continue')];+ const disconnectedCodes = analyzeEpisodeGraph(neverConnected, {+ participationMode: 'helper', requireAudienceIntroduction: true,+ })+ .issues.map((issue) => issue.code);+ expect(disconnectedCodes).toContain(GRAPH_ISSUE_CODES.NO_AUDIENCE_CONNECTION);+ expect(disconnectedCodes).toContain(GRAPH_ISSUE_CODES.DISCONNECTED_DECISION);++ const connected = soundEpisode();+ connected.nodes[0].playbackMode = 'cut';+ connected.nodes[0].transitions = [tr('t1', 'n2', 'Continue')];+ connected.nodes[1].audienceConnection = 'connected';+ connected.nodes[1].playbackMode = 'decision';+ const connectedCodes = analyzeEpisodeGraph(connected, {+ participationMode: 'helper', requireAudienceIntroduction: true,+ })+ .issues.map((issue) => issue.code);+ expect(connectedCodes).not.toContain(GRAPH_ISSUE_CODES.NO_AUDIENCE_CONNECTION);+ expect(connectedCodes).not.toContain(GRAPH_ISSUE_CODES.DISCONNECTED_DECISION);+ });+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')] });diff --git a/server/lib/fableLoomLimits.js b/server/lib/fableLoomLimits.jsindex ca7e4dd4b9..3baa5416ec 100644--- a/server/lib/fableLoomLimits.js+++ b/server/lib/fableLoomLimits.js@@ -10,6 +10,7 @@ export const LOOM_LIMITS = Object.freeze({LOGLINE_MAX: 500,PREMISE_MAX: 20000,STYLE_NOTES_MAX: 4000,+ AUDIENCE_COMMUNICATION_MEDIUM_MAX: 1000,STORY_ARC_MAX: 12000,PLAN_ITEMS_MAX: 50,PLAN_ITEM_TITLE_MAX: 300,diff --git a/server/lib/fableLoomParticipation.js b/server/lib/fableLoomParticipation.jsnew file mode 100644index 0000000000..4fc3bfc9cf--- /dev/null+++ b/server/lib/fableLoomParticipation.js@@ -0,0 +1,49 @@+/**+ * FableLoom audience-participation semantics shared by persistence, prompts,+ * graph validation, and the client editor.+ *+ * Existing stories predate the distinction and behaved as protagonist-led+ * choose-your-own adventures, so missing loom values retain that behavior.+ * New looms created through the product UI default to the primary helper+ * experience, while API clients that omit the field retain legacy behavior.+ */++export const FABLELOOM_PARTICIPATION_MODES = Object.freeze(['helper', 'protagonist']);+export const FABLELOOM_LEGACY_PARTICIPATION_MODE = 'protagonist';+export const FABLELOOM_NEW_PARTICIPATION_MODE = 'helper';++export const FABLELOOM_AUDIENCE_CONNECTION_STATES = Object.freeze(['disconnected', 'connected']);+export const FABLELOOM_AUDIENCE_CONNECTION_DEFAULT = 'disconnected';++export const isFableLoomParticipationMode = (value) => FABLELOOM_PARTICIPATION_MODES.includes(value);+export const asFableLoomParticipationMode = (value) => (+ isFableLoomParticipationMode(value) ? value : FABLELOOM_LEGACY_PARTICIPATION_MODE+);++export const isFableLoomAudienceConnection = (value) => FABLELOOM_AUDIENCE_CONNECTION_STATES.includes(value);+export const asFableLoomAudienceConnection = (value) => (+ isFableLoomAudienceConnection(value) ? value : FABLELOOM_AUDIENCE_CONNECTION_DEFAULT+);++export const audienceCanParticipate = (loom, node) => (+ asFableLoomParticipationMode(loom?.participationMode) === 'protagonist'+ || asFableLoomAudienceConnection(node?.audienceConnection) === 'connected'+);++export const participationContractForPrompt = (loom, { requiresIntroduction = true } = {}) => {+ const mode = asFableLoomParticipationMode(loom?.participationMode);+ if (mode === 'protagonist') {+ return 'The audience acts as the protagonist. Decision scenes may address their choices from the opening scene onward.';+ }+ const medium = typeof loom?.audienceCommunicationMedium === 'string'+ ? loom.audienceCommunicationMedium.trim()+ : '';+ return [+ 'The protagonist has independent agency. The audience enters the fiction as themselves and can only advise or help the protagonist.',+ `Communication medium: ${medium || '(not configured)'}.`,+ requiresIntroduction+ ? 'Open passively, establish and visibly activate this medium close to the beginning, and make that activation an in-story invitation to participate.'+ : 'The audience has already been introduced in the series. Preserve the medium and its current in-world availability without repeating the original invitation.',+ 'Only scenes with audienceConnection "connected" may be decision loops or accept audience input. Disconnected scenes are passive canon with exactly one automatic continuation. The medium may be lost, stolen, broken, jammed, or restored later; mark every scene accordingly.',+ ].join(' ');+};diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex 70825812d4..930ea5ac61 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -9,12 +9,18 @@ import { z } from 'zod';import { LOOM_LIMITS } from './fableLoomLimits.js';import { LOOM_FORMATS } from './fableLoomFormats.js';import { FABLELOOM_PLAYBACK_MODES } from './fableLoomPlayback.js';+import {+ FABLELOOM_AUDIENCE_CONNECTION_STATES,+ FABLELOOM_PARTICIPATION_MODES,+} from './fableLoomParticipation.js';import { llmRoutePinSchema } from './llmRoutePin.js';const name = z.string().trim().min(1).max(LOOM_LIMITS.NAME_MAX);const logline = z.string().max(LOOM_LIMITS.LOGLINE_MAX);const premise = z.string().max(LOOM_LIMITS.PREMISE_MAX);const styleNotes = z.string().max(LOOM_LIMITS.STYLE_NOTES_MAX);+const participationMode = z.enum(FABLELOOM_PARTICIPATION_MODES);+const audienceCommunicationMedium = z.string().max(LOOM_LIMITS.AUDIENCE_COMMUNICATION_MEDIUM_MAX);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);@@ -60,6 +66,8 @@ export const loomCreateSchema = z.object({logline: logline.optional(),premise: premise.optional(),styleNotes: styleNotes.optional(),+ participationMode: participationMode.optional(),+ audienceCommunicationMedium: audienceCommunicationMedium.optional(),format: format.optional(),playSettings: playSettings.optional(),seriesPlan: seriesPlan.optional(),@@ -72,6 +80,8 @@ export const loomPatchSchema = z.object({logline: logline.optional(),premise: premise.optional(),styleNotes: styleNotes.optional(),+ participationMode: participationMode.optional(),+ audienceCommunicationMedium: audienceCommunicationMedium.optional(),format: format.optional(),playSettings: playSettings.optional(),seriesPlan: seriesPlan.optional(),@@ -126,6 +136,7 @@ const nodeFields = {videoPrompt: z.string().max(LOOM_LIMITS.VIDEO_PROMPT_MAX).optional(),cameraMovement: z.string().max(LOOM_LIMITS.CAMERA_MOVEMENT_MAX).optional(),playbackMode: z.enum(FABLELOOM_PLAYBACK_MODES).optional(),+ audienceConnection: z.enum(FABLELOOM_AUDIENCE_CONNECTION_STATES).optional(),isEnding: z.boolean().optional(),endingLabel: z.string().max(LOOM_LIMITS.ENDING_LABEL_MAX).optional(),pos: z.object({ x: z.number(), y: z.number() }).nullable().optional(),diff --git a/server/lib/index.js b/server/lib/index.jsindex b22d71d1c1..4a3173b84c 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -83,6 +83,7 @@ export * as editorial from './editorial/index.js';export * from './fableLoomGraph.js';export * from './fableLoomCameraMovements.js';export * from './fableLoomPlayback.js';+export * from './fableLoomParticipation.js';export * from './fableLoomLimits.js';export * from './fableLoomFormats.js';export * from './scenePrompt.js';diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.jsindex 6243f5aa9e..435cd42965 100644--- a/server/routes/fableLoom.js+++ b/server/routes/fableLoom.js@@ -131,7 +131,10 @@ 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));+ res.json(analyzeEpisodeGraph(episode, {+ participationMode: loom.participationMode,+ requireAudienceIntroduction: episode.id === loom.episodes[0]?.id,+ }));}));// --- Nodes ------------------------------------------------------------------diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.jsindex 70068449be..b621227999 100644--- a/server/services/fableLoom/records.js+++ b/server/services/fableLoom/records.js@@ -28,6 +28,11 @@ import {import { LOOM_LIMITS } from './limits.js';import { asLoomFormat, isLoomFormat } from './formats.js';import { asFableLoomPlaybackMode } from '../../lib/fableLoomPlayback.js';+import {+ FABLELOOM_LEGACY_PARTICIPATION_MODE,+ asFableLoomAudienceConnection,+ asFableLoomParticipationMode,+} from '../../lib/fableLoomParticipation.js';import { normalizeFableLoomCameraMovement } from '../../lib/fableLoomCameraMovements.js';export { LOOM_LIMITS };@@ -73,6 +78,7 @@ function sanitizeNode(raw) {videoPrompt: trimTo(raw.videoPrompt, LOOM_LIMITS.VIDEO_PROMPT_MAX),cameraMovement: trimTo(normalizeFableLoomCameraMovement(raw.cameraMovement), LOOM_LIMITS.CAMERA_MOVEMENT_MAX),playbackMode: asFableLoomPlaybackMode(raw.playbackMode),+ audienceConnection: asFableLoomAudienceConnection(raw.audienceConnection),videoHistoryId: isSafeVideoHistoryId(raw.videoHistoryId) ? raw.videoHistoryId : null,isEnding: raw.isEnding === true,// The format this scene's text is actually WRITTEN in — server-set, not@@ -172,6 +178,11 @@ export function sanitizeLoom(raw) {logline: trimTo(raw.logline, LOOM_LIMITS.LOGLINE_MAX),premise: trimTo(raw.premise, LOOM_LIMITS.PREMISE_MAX),styleNotes: trimTo(raw.styleNotes, LOOM_LIMITS.STYLE_NOTES_MAX),+ participationMode: asFableLoomParticipationMode(raw.participationMode),+ audienceCommunicationMedium: trimTo(+ raw.audienceCommunicationMedium,+ LOOM_LIMITS.AUDIENCE_COMMUNICATION_MEDIUM_MAX,+ ),format: asLoomFormat(raw.format),// The loom's route pin for the play stage — which provider/model/effort// turns a reader's free text into a path. An unset dimension stays null@@ -230,11 +241,16 @@ export async function listLooms() {export async function listLoomSummaries({ seriesId: scopeSeriesId } = {}) {const looms = await listLooms();const scoped = scopeSeriesId ? looms.filter((loom) => loom.seriesId === scopeSeriesId) : looms;- return scoped.map(({ id, name, logline, format, universeId, seriesId, createdAt, updatedAt, episodes }) => ({+ return scoped.map(({+ id, name, logline, format, participationMode, audienceCommunicationMedium,+ universeId, seriesId, createdAt, updatedAt, episodes,+ }) => ({id,name,logline,format,+ participationMode,+ audienceCommunicationMedium,universeId,seriesId,createdAt,@@ -250,8 +266,23 @@ export async function getLoom(id) {return sanitizeLoom(await readRaw(id));}-export async function createLoom({ name, logline, premise, styleNotes, format, playSettings, seriesPlan, universeId, seriesId } = {}) {+const assertParticipationConfigured = ({ participationMode, audienceCommunicationMedium }) => {+ if (asFableLoomParticipationMode(participationMode) === 'helper'+ && !trimTo(audienceCommunicationMedium, LOOM_LIMITS.AUDIENCE_COMMUNICATION_MEDIUM_MAX)) {+ throw new ServerError('Helper stories need an audience communication medium', {+ status: 400,+ code: 'AUDIENCE_MEDIUM_REQUIRED',+ });+ }+};++export async function createLoom({+ name, logline, premise, styleNotes, format, playSettings, seriesPlan,+ participationMode = FABLELOOM_LEGACY_PARTICIPATION_MODE,+ audienceCommunicationMedium, universeId, seriesId,+} = {}) {const now = new Date().toISOString();+ assertParticipationConfigured({ participationMode, audienceCommunicationMedium });await assertRefsExist({ universeId: nullableRef(universeId), seriesId: nullableRef(seriesId) });const loom = sanitizeLoom({id: `loom-${randomUUID()}`,@@ -259,6 +290,8 @@ export async function createLoom({ name, logline, premise, styleNotes, format, plogline,premise,styleNotes,+ participationMode,+ audienceCommunicationMedium,format,playSettings,seriesPlan,@@ -291,7 +324,10 @@ export function mutateLoom(id, mutator) {});}-const PATCH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan', 'universeId', 'seriesId'];+const PATCH_FIELDS = [+ 'name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan',+ 'participationMode', 'audienceCommunicationMedium', 'universeId', 'seriesId',+];export async function updateLoom(id, patch = {}) {await assertRefsExist({@@ -303,6 +339,7 @@ export async function updateLoom(id, patch = {}) {for (const key of PATCH_FIELDS) {if (key in patch) next[key] = patch[key];}+ assertParticipationConfigured(next);return next;});}@@ -374,7 +411,10 @@ export function deleteEpisode(loomId, episodeId) {// --- Nodes & transitions -----------------------------------------------------const NODE_PATCH_FIELDS = ['title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode', 'isEnding', 'endingLabel', 'pos', 'transitions'];+const NODE_PATCH_FIELDS = [+ 'title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode',+ 'audienceConnection', 'isEnding', 'endingLabel', 'pos', 'transitions',+];export function addNode(loomId, episodeId, fields = {}) {return mutateLoom(loomId, (loom) => {diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.jsindex ab03377f5f..55d3b83a09 100644--- a/server/services/fableLoom/records.test.js+++ b/server/services/fableLoom/records.test.js@@ -112,6 +112,15 @@ describe('sanitizeLoom', () => {expect(sanitizeLoom({ id: 'loom-1', name: 'X', format: 'haiku' }).format).toBe('prose');});+ it('preserves legacy protagonist behavior and defaults old scenes to a disconnected channel', () => {+ const loom = sanitizeLoom({+ id: 'loom-1', name: 'X', episodes: [{ id: 'ep-1', nodes: [{ id: 'n1' }] }],+ });+ expect(loom.participationMode).toBe('protagonist');+ expect(loom.audienceCommunicationMedium).toBe('');+ expect(loom.episodes[0].nodes[0].audienceConnection).toBe('disconnected');+ });+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 },@@ -219,6 +228,28 @@ describe('format and play settings round-trip', () => {});});+describe('audience participation round-trip', () => {+ it('requires a communication medium in helper mode and persists connection state', async () => {+ await expect(makeLoom({ participationMode: 'helper' }))+ .rejects.toMatchObject({ code: 'AUDIENCE_MEDIUM_REQUIRED' });++ let loom = await makeLoom({+ participationMode: 'helper',+ audienceCommunicationMedium: 'A hand-cranked radio carried by the protagonist.',+ });+ expect(loom).toMatchObject({+ participationMode: 'helper',+ audienceCommunicationMedium: 'A hand-cranked radio carried by the protagonist.',+ });+ loom = await addEpisode(loom.id, { title: 'Pilot' });+ loom = await addNode(loom.id, loom.episodes[0].id, { audienceConnection: 'connected' });+ expect(loom.episodes[0].nodes[0].audienceConnection).toBe('connected');++ await expect(updateLoom(loom.id, { audienceCommunicationMedium: '' }))+ .rejects.toMatchObject({ code: 'AUDIENCE_MEDIUM_REQUIRED' });+ });+});+describe('series plan round-trip', () => {it('persists ordered plot points and side quests without changing them on unrelated patches', async () => {let loom = await makeLoom();diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex b966495ad9..f5fc0017c8 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -18,18 +18,28 @@ import { runStagedLLM } from '../stageRunner.js';import { isStr, trimTo } from '../../lib/storyBible.js';import { resolveLlmRoutePin } from '../../lib/llmRoutePin.js';import { renderCanonForPrompt } from '../../lib/universePromptRenderers.js';-import { analyzeEpisodeGraph, describeGraphForPrompt } from '../../lib/fableLoomGraph.js';+import { GRAPH_ISSUE_CODES, analyzeEpisodeGraph, describeGraphForPrompt } from '../../lib/fableLoomGraph.js';import {FABLELOOM_CAMERA_MOVEMENT_VALUES,fableLoomCameraMovementCatalogForPrompt,normalizeFableLoomCameraMovement,} from '../../lib/fableLoomCameraMovements.js';import { isFableLoomPlaybackMode } from '../../lib/fableLoomPlayback.js';+import {+ asFableLoomAudienceConnection,+ audienceCanParticipate,+ participationContractForPrompt,+} from '../../lib/fableLoomParticipation.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;+const AUDIENCE_GRAPH_ERROR_CODES = new Set([+ GRAPH_ISSUE_CODES.NO_AUDIENCE_CONNECTION,+ GRAPH_ISSUE_CODES.DISCONNECTED_DECISION,+ GRAPH_ISSUE_CODES.CUT_TRANSITION_COUNT,+]);const clamp = (value, min, max, fallback) =>(Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : fallback);@@ -102,9 +112,18 @@ const seriesPlanContext = (loom, episode) => {].filter(Boolean);};+const requiresAudienceIntroduction = (loom, episode) => (+ !episode || episode.id === loom.episodes[0]?.id+);++const audienceContract = (loom, episode) => participationContractForPrompt(loom, {+ requiresIntroduction: requiresAudienceIntroduction(loom, episode),+});+const storyContext = (loom, episode) => [`Story: ${loom.name}`,`Scene format: ${loomFormatLabel(loom.format)}`,+ `Audience participation: ${audienceContract(loom, episode)}`,loom.logline ? `Logline: ${loom.logline}` : '',loom.premise ? `Premise: ${loom.premise}` : '',...seriesPlanContext(loom, episode),@@ -148,6 +167,7 @@ const generatedNodeFields = (raw) => ({videoPrompt: raw.videoPrompt,cameraMovement: raw.cameraMovement,playbackMode: raw.playbackMode,+ audienceConnection: raw.audienceConnection,isEnding: raw.isEnding === true,endingLabel: raw.endingLabel,});@@ -203,9 +223,22 @@ export async function weaveEpisode(loomId, episodeId, {: '(none — create the episode from the story context)',cameraMovementCatalog: fableLoomCameraMovementCatalogForPrompt(),sceneFormatContract: sceneFormatContract(loom.format),+ participationContract: audienceContract(loom, episode),}, llmOptions({ providerId, model, effort }, 'fableloom-weave'));const { nodes, startNodeId } = mapGeneratedGraph(content);+ if (loom.participationMode === 'helper') {+ const audienceErrors = analyzeEpisodeGraph(+ { ...episode, nodes, startNodeId },+ {+ participationMode: 'helper',+ requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),+ },+ ).issues.filter((issue) => issue.severity === 'error' && AUDIENCE_GRAPH_ERROR_CODES.has(issue.code));+ if (audienceErrors.length) {+ throw aiShapeError(`The model returned an invalid audience connection graph: ${audienceErrors[0].message}`);+ }+ }const updated = await mutateLoom(loomId, (current) => {const ep = findEpisode(current, episodeId);// Stamped with the format they were generated in, so a later reformat can@@ -226,6 +259,12 @@ export async function branchNode(loomId, episodeId, nodeId, {const loom = await requireLoom(loomId);const episode = findEpisode(loom, episodeId);const node = findNode(episode, nodeId);+ if (!audienceCanParticipate(loom, node)) {+ throw new ServerError('The audience cannot branch this scene until its communication channel is connected', {+ status: 409,+ code: 'AUDIENCE_DISCONNECTED',+ });+ }const count = clamp(branchCount, 1, 4, 2);const canonDigest = await buildCanonDigest(loom);@@ -239,6 +278,7 @@ export async function branchNode(loomId, episodeId, nodeId, {cameraMovementCatalog: fableLoomCameraMovementCatalogForPrompt(),guidance: guidance || '(none)',sceneFormatContract: sceneFormatContract(loom.format),+ participationContract: audienceContract(loom, episode),}, llmOptions({ providerId, model, effort }, 'fableloom-branch'));const branches = Array.isArray(content?.branches)@@ -258,6 +298,7 @@ export async function branchNode(loomId, episodeId, nodeId, {id: `node-${randomUUID()}`,...generatedNodeFields(branch.node),playbackMode: 'decision',+ audienceConnection: 'connected',format: asLoomFormat(loom.format),transitions: [],pos: null,@@ -283,7 +324,10 @@ const REVIEW_SEVERITIES = new Set(['high', 'medium', 'low']);export async function reviewEpisode(loomId, episodeId, { providerId, model, effort } = {}) {const loom = await requireLoom(loomId);const episode = findEpisode(loom, episodeId);- const structural = analyzeEpisodeGraph(episode);+ const structural = analyzeEpisodeGraph(episode, {+ participationMode: loom.participationMode,+ requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),+ });const { content, runId } = await runStagedLLM('fableloom-review', {storyContext: storyContext(loom, episode),graphDigest: describeGraphForPrompt(episode),@@ -310,7 +354,10 @@ export async function reviewEpisode(loomId, episodeId, { providerId, model, effo// --- Feedback: apply a conversational episode edit ---------------------------const FEEDBACK_NODE_FIELDS = ['title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode', 'isEnding', 'endingLabel'];+const FEEDBACK_NODE_FIELDS = [+ 'title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode',+ 'audienceConnection', 'isEnding', 'endingLabel',+];const FEEDBACK_TRANSITION_FIELDS = ['targetNodeId', 'intent', 'triggers', 'description'];const FEEDBACK_STRING_NODE_FIELDS = new Set(['title', 'prose', 'imagePrompt', 'videoPrompt', 'endingLabel']);@@ -345,6 +392,8 @@ const normalizeFeedbackPatch = (content, episode) => {if (!movement || FABLELOOM_CAMERA_MOVEMENT_VALUES.includes(movement)) nodePatch[key] = movement;} else if (key === 'playbackMode' && isFableLoomPlaybackMode(value)) {nodePatch[key] = value;+ } else if (key === 'audienceConnection' && ['connected', 'disconnected'].includes(value)) {+ nodePatch[key] = value;} else if (key === 'isEnding' && typeof value === 'boolean') {nodePatch[key] = value;}@@ -593,6 +642,7 @@ export const publicNode = (node) => ({image: node.image,videoHistoryId: node.videoHistoryId,playbackMode: node.playbackMode,+ audienceConnection: asFableLoomAudienceConnection(node.audienceConnection),isEnding: node.isEnding,endingLabel: node.endingLabel,choices: (node.transitions || []).map((t) => ({ id: t.id, intent: t.intent })),@@ -628,7 +678,17 @@ export async function playTurn(loomId, episodeId, {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' });+ return moveResult(episode, node, taken, {+ narration: '',+ resolvedBy: audienceCanParticipate(loom, node) ? 'choice' : 'graph',+ });+ }++ if (!audienceCanParticipate(loom, node)) {+ throw new ServerError('The audience communication channel is not connected in this scene', {+ status: 409,+ code: 'AUDIENCE_DISCONNECTED',+ });}const choicesDigest = node.transitions.map((t) => [diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.jsindex 58c322e39b..34cb158669 100644--- a/server/services/fableLoom/weave.test.js+++ b/server/services/fableLoom/weave.test.js@@ -106,6 +106,7 @@ describe('weaveEpisode', () => {expect(variables.guidance).toBe('darker');expect(variables.existingGraph).toContain('(none');expect(variables.cameraMovementCatalog).toContain('slow-dolly-in');+ expect(variables.participationContract).toContain('audience acts as the protagonist');expect(variables).not.toHaveProperty('nodeTarget');expect(variables).not.toHaveProperty('endingTarget');});@@ -120,6 +121,38 @@ describe('weaveEpisode', () => {const { loom } = await weaveEpisode(loomId, episodeId, { replace: true });expect(loom.episodes[0].nodes).toHaveLength(3);});++ it('rejects a helper weave that offers decisions before establishing its audience channel', async () => {+ const { loomId, episodeId } = await setup();+ await updateLoom(loomId, {+ participationMode: 'helper',+ audienceCommunicationMedium: 'A pocket radio.',+ });+ runStagedLLM.mockResolvedValue({ content: generatedGraph(), runId: 'run-disconnected' });++ await expect(weaveEpisode(loomId, episodeId))+ .rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });+ expect((await getLoom(loomId)).episodes[0].nodes).toEqual([]);+ });++ it('persists the first helper invitation and its connected decision scenes', async () => {+ const { loomId, episodeId } = await setup();+ await updateLoom(loomId, {+ participationMode: 'helper',+ audienceCommunicationMedium: 'A pocket radio.',+ });+ const graph = generatedGraph();+ graph.nodes[0].playbackMode = 'cut';+ graph.nodes[0].audienceConnection = 'disconnected';+ graph.nodes[0].transitions = [graph.nodes[0].transitions[0]];+ graph.nodes[1].playbackMode = 'decision';+ graph.nodes[1].audienceConnection = 'connected';+ runStagedLLM.mockResolvedValue({ content: graph, runId: 'run-connected' });++ const result = await weaveEpisode(loomId, episodeId);+ expect(result.loom.episodes[0].nodes.map((node) => node.audienceConnection))+ .toEqual(['disconnected', 'connected', 'disconnected']);+ });});describe('branchNode', () => {@@ -157,6 +190,19 @@ describe('branchNode', () => {await expect(branchNode(loomId, episodeId, withNode.episodes[0].nodes[0].id, {})).rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });});++ it('does not create audience branches while a helper story is disconnected', async () => {+ const { loomId, episodeId } = await setup();+ await updateLoom(loomId, {+ participationMode: 'helper',+ audienceCommunicationMedium: 'A pocket radio.',+ });+ const withNode = await addNode(loomId, episodeId, { title: 'Silent opening', audienceConnection: 'disconnected' });++ await expect(branchNode(loomId, episodeId, withNode.episodes[0].nodes[0].id, {}))+ .rejects.toMatchObject({ code: 'AUDIENCE_DISCONNECTED' });+ expect(runStagedLLM).not.toHaveBeenCalled();+ });});describe('reviewEpisode', () => {@@ -324,6 +370,26 @@ describe('playTurn', () => {expect(runStagedLLM).not.toHaveBeenCalled();});+ it('locks typed audience input out while a helper channel is disconnected but permits canon advance', async () => {+ const { loomId, episodeId, gate, insideId } = await playSetup();+ await updateLoom(loomId, {+ participationMode: 'helper',+ audienceCommunicationMedium: 'A pocket radio.',+ });+ await updateNode(loomId, episodeId, gate.id, {+ playbackMode: 'cut', audienceConnection: 'disconnected',+ });++ await expect(playTurn(loomId, episodeId, { nodeId: gate.id, message: 'Can you hear me?' }))+ .rejects.toMatchObject({ code: 'AUDIENCE_DISCONNECTED' });+ const advanced = await playTurn(loomId, episodeId, {+ nodeId: gate.id, transitionId: gate.transitions[0].id,+ });+ expect(advanced).toMatchObject({ action: 'move', resolvedBy: 'graph' });+ expect(advanced.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' }))