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: add FableLoom series planning workspace
[._.]/ Adam Eivy95ecbc86c5d8
diff --git a/client/src/components/fableloom/LoomSeriesPlan.jsx b/client/src/components/fableloom/LoomSeriesPlan.jsxnew file mode 100644index 0000000000..d4b81d3701--- /dev/null+++ b/client/src/components/fableloom/LoomSeriesPlan.jsx@@ -0,0 +1,382 @@+/**+ * Series-level FableLoom planning, intentionally separate from episode scene+ * graphs. One explicit save persists the whole ordered plan so moving a beat+ * and editing its copy cannot race as independent PATCH requests.+ */++import { useEffect, useState } from 'react';+import { BrainCircuit, ChevronDown, ChevronUp, Loader2, MessageSquareText, Plus, Save, Sparkles, Trash2 } from 'lucide-react';+import toast from '../ui/Toast';+import { FormField } from '../ui/FormField.jsx';+import UnsavedChangesConfirm from '../ui/UnsavedChangesConfirm.jsx';+import ProviderModelSelector from '../ProviderModelSelector';+import { useAsyncAction } from '../../hooks/useAsyncAction';+import useProviderModels from '../../hooks/useProviderModels';+import useUnsavedChangesGuard from '../../hooks/useUnsavedChangesGuard';+import { feedbackLoomSeriesPlan, reviewLoomSeriesPlan, updateLoom } from '../../services/api';+import { uuidv4 } from '../../lib/uuid.js';+import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providers';+import LoomEpisodeFeedback from './LoomEpisodeFeedback';+import { fieldClass, labelClass } from './fieldStyles';++const newItemId = (prefix) => `${prefix}-${uuidv4()}`;++const normalizePlan = (plan) => ({+ storyArc: plan?.storyArc || '',+ plotPoints: Array.isArray(plan?.plotPoints) ? plan.plotPoints : [],+ sideQuests: Array.isArray(plan?.sideQuests) ? plan.sideQuests : [],+});++export default function LoomSeriesPlan({ loom, onLoomUpdate }) {+ const [plan, setPlan] = useState(() => normalizePlan(loom.seriesPlan));+ const [dirty, setDirty] = useState(false);+ const routeGuard = useUnsavedChangesGuard(dirty);++ useEffect(() => {+ setPlan(normalizePlan(loom.seriesPlan));+ setDirty(false);+ }, [loom.id, loom.seriesPlan]);++ const changePlan = (updater) => {+ setPlan((current) => (typeof updater === 'function' ? updater(current) : updater));+ setDirty(true);+ };++ const updateItem = (collection, id, patch) => changePlan((current) => ({+ ...current,+ [collection]: current[collection].map((item) => (item.id === id ? { ...item, ...patch } : item)),+ }));++ const removeItem = (collection, id) => changePlan((current) => ({+ ...current,+ [collection]: current[collection].filter((item) => item.id !== id),+ }));++ const moveItem = (collection, index, direction) => changePlan((current) => {+ const next = [...current[collection]];+ const target = index + direction;+ if (target < 0 || target >= next.length) return current;+ [next[index], next[target]] = [next[target], next[index]];+ return { ...current, [collection]: next };+ });++ const [save, saving] = useAsyncAction(async () => {+ const updated = await updateLoom(loom.id, { seriesPlan: plan }, { silent: true });+ onLoomUpdate(updated);+ setDirty(false);+ toast.success('Series plan saved');+ }, { errorMessage: 'Could not save series plan' });++ const episodeOptions = loom.episodes.map((episode) => ({+ id: episode.id,+ label: `${episode.number}. ${episode.title || 'Untitled'}`,+ }));++ const discardAndExit = () => {+ setPlan(normalizePlan(loom.seriesPlan));+ setDirty(false);+ routeGuard.proceed();+ };++ return (+ <section className="flex-1 overflow-y-auto p-4 md:p-6" aria-label="Series plan">+ <UnsavedChangesConfirm+ guard={routeGuard}+ when={!saving}+ question="Discard your unsaved series-plan changes?"+ label={`Discard unsaved changes to ${loom.name}`}+ onDiscard={discardAndExit}+ />+ <div className="max-w-5xl mx-auto space-y-6">+ <div className="flex items-start justify-between gap-4">+ <div>+ <h2 className="text-lg font-semibold">Series plan</h2>+ <p className="text-sm text-port-text-muted mt-1">+ Shape the full narrative before working inside individual episode graphs.+ </p>+ </div>+ <button+ type="button"+ onClick={save}+ disabled={!dirty || saving}+ className="shrink-0 flex items-center gap-2 px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {saving ? 'Saving…' : 'Save plan'}+ </button>+ </div>++ <div className="rounded-lg border border-port-border bg-port-card p-4">+ <FormField+ label="Story arc"+ hint="The beginning-to-end dramatic movement, central conflict, and intended resolution."+ labelClassName={labelClass}+ >+ <textarea+ rows={7}+ className={fieldClass}+ value={plan.storyArc}+ placeholder="What changes across the series, why it matters, and where the story lands…"+ onChange={(event) => changePlan((current) => ({ ...current, storyArc: event.target.value }))}+ />+ </FormField>+ </div>++ <PlanCollection+ title="Plot points"+ description="Order the tentpole beats and connect each one to the episode where it should land."+ items={plan.plotPoints}+ episodes={episodeOptions}+ onAdd={() => changePlan((current) => ({ ...current, plotPoints: [...current.plotPoints, {+ id: newItemId('plot'), title: '', description: '', episodeId: null,+ }] }))}+ onUpdate={(id, patch) => updateItem('plotPoints', id, patch)}+ onRemove={(id) => removeItem('plotPoints', id)}+ onMove={(index, direction) => moveItem('plotPoints', index, direction)}+ />++ <PlanCollection+ title="Side quests"+ description="Track supporting threads without letting them disappear inside a single episode."+ items={plan.sideQuests}+ episodes={episodeOptions}+ sideQuests+ onAdd={() => changePlan((current) => ({ ...current, sideQuests: [...current.sideQuests, {+ id: newItemId('quest'), title: '', description: '', status: 'idea', startEpisodeId: null, endEpisodeId: null,+ }] }))}+ onUpdate={(id, patch) => updateItem('sideQuests', id, patch)}+ onRemove={(id) => removeItem('sideQuests', id)}+ onMove={(index, direction) => moveItem('sideQuests', index, direction)}+ />++ <SeriesAiEditor loom={loom} dirty={dirty} onLoomUpdate={onLoomUpdate} />++ <WholeEpisodeEditor loom={loom} dirty={dirty} onLoomUpdate={onLoomUpdate} />+ </div>+ </section>+ );+}++function SeriesAiEditor({ loom, dirty, onLoomUpdate }) {+ const [feedback, setFeedback] = useState('');+ const [analysis, setAnalysis] = useState(null);+ const [route, setRoute] = useState({ providerId: '', model: '', effort: '' });+ const { providers, loading } = useProviderModels({ allowDefault: true, silent: true, withEffort: true });+ const selectedProvider = providers.find((provider) => provider.id === route.providerId);+ const routeBody = {+ ...(route.providerId ? { providerId: route.providerId } : {}),+ ...(route.model ? { model: route.model } : {}),+ ...(route.effort ? { effort: route.effort } : {}),+ };++ const [runReview, reviewing] = useAsyncAction(async () => {+ const result = await reviewLoomSeriesPlan(loom.id, routeBody, { silent: true });+ setAnalysis(result.analysis);+ }, { errorMessage: 'Series analysis failed' });++ const [applyFeedback, applying] = useAsyncAction(async () => {+ const result = await feedbackLoomSeriesPlan(loom.id, { feedback: feedback.trim(), ...routeBody }, { silent: true });+ onLoomUpdate(result.loom);+ setFeedback('');+ setAnalysis(null);+ toast.success(result.changes?.[0] || 'Series plan updated');+ }, { errorMessage: 'Series-plan feedback failed' });++ const busy = reviewing || applying;+ return (+ <div className="rounded-lg border border-port-border bg-port-card p-4 space-y-4">+ <div>+ <h3 className="font-semibold flex items-center gap-2"><BrainCircuit size={16} className="text-port-accent" /> AI story editor</h3>+ <p className="text-xs text-port-text-muted mt-1">+ Analyze the complete arc or describe an edit to apply across the series plan.+ </p>+ </div>+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={route.providerId}+ selectedModel={route.model}+ availableModels={effortAwareModelOptions(selectedProvider, route.model)}+ onProviderChange={(providerId) => setRoute({ providerId, model: '', effort: '' })}+ onModelChange={(model) => setRoute((current) => ({ ...current, model }))}+ effort={route.effort}+ onEffortChange={(effort) => setRoute((current) => ({ ...current, effort }))}+ label="AI route"+ layout="stacked"+ disabled={busy || loading}+ modelDisabled={busy || loading}+ emptyProviderOption="Default (series-plan stage or active provider)"+ emptyModelOption="Default model"+ alwaysShowModel={!!route.providerId}+ />+ {selectedProvider ? (+ <p className="text-xs text-port-text-muted">+ These actions will use {selectedProvider.name}{effectiveModelFor(selectedProvider, route.model) ? ` (${effectiveModelFor(selectedProvider, route.model)})` : ''}.+ </p>+ ) : null}+ <div className="flex flex-wrap gap-2">+ <button+ type="button"+ onClick={runReview}+ disabled={busy || dirty}+ className="flex items-center gap-2 px-3 py-2 rounded border border-port-border text-sm hover:border-port-accent disabled:opacity-50"+ >+ {reviewing ? <Loader2 size={14} className="animate-spin" /> : <BrainCircuit size={14} />}+ {reviewing ? 'Analyzing…' : 'Analyze series'}+ </button>+ </div>+ <FormField+ label="Editing guidance"+ hint="For example: Move the betrayal earlier, make the midpoint irreversible, and resolve the courier side quest in episode 6."+ labelClassName={labelClass}+ >+ <textarea+ rows={4}+ className={fieldClass}+ value={feedback}+ placeholder="Describe the arc, plot-point, or side-quest changes you want…"+ onChange={(event) => setFeedback(event.target.value)}+ disabled={busy}+ />+ </FormField>+ <button+ type="button"+ onClick={applyFeedback}+ disabled={busy || dirty || !feedback.trim()}+ className="flex items-center justify-center gap-2 w-full px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50"+ >+ {applying ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}+ {applying ? 'Updating series plan…' : 'Apply guidance to plan'}+ </button>+ {dirty ? <p className="text-xs text-port-warning">Save the plan before running AI so it reads the edits on screen.</p> : null}+ {analysis ? <SeriesAnalysis analysis={analysis} /> : null}+ </div>+ );+}++function SeriesAnalysis({ analysis }) {+ const groups = [+ ['Strengths', analysis.strengths],+ ['Story risks', analysis.risks],+ ['Recommended edits', analysis.recommendations],+ ];+ return (+ <div className="rounded border border-port-accent/30 bg-port-bg p-3 space-y-3" aria-live="polite">+ <h4 className="text-sm font-semibold">Series analysis</h4>+ {analysis.summary ? <p className="text-sm text-port-text-muted">{analysis.summary}</p> : null}+ {groups.map(([label, items]) => items?.length ? (+ <div key={label}>+ <h5 className="text-xs font-semibold uppercase tracking-wide text-port-text-muted">{label}</h5>+ <ul className="mt-1 space-y-1 text-sm list-disc pl-5">+ {items.map((item) => <li key={item}>{item}</li>)}+ </ul>+ </div>+ ) : null)}+ </div>+ );+}++function WholeEpisodeEditor({ loom, dirty, onLoomUpdate }) {+ const [episodeId, setEpisodeId] = useState(loom.episodes[0]?.id || '');+ useEffect(() => {+ if (!loom.episodes.some((episode) => episode.id === episodeId)) setEpisodeId(loom.episodes[0]?.id || '');+ }, [episodeId, loom.episodes]);+ const episode = loom.episodes.find((candidate) => candidate.id === episodeId);+ return (+ <div className="rounded-lg border border-port-border bg-port-card p-4 space-y-3">+ <div>+ <h3 className="font-semibold flex items-center gap-2"><MessageSquareText size={16} className="text-port-accent" /> Edit a whole episode</h3>+ <p className="text-xs text-port-text-muted mt-1">+ Apply one instruction across an episode's title, synopsis, existing scenes, and path language.+ </p>+ </div>+ {episode ? (+ <>+ <PlanSelect+ label="Episode"+ value={episodeId}+ onChange={setEpisodeId}+ options={loom.episodes.map((item) => ({ id: item.id, label: `${item.number}. ${item.title || 'Untitled'}` }))}+ />+ <LoomEpisodeFeedback+ key={episode.id}+ open+ loom={loom}+ episode={episode}+ onLoomUpdate={onLoomUpdate}+ disabled={dirty}+ />+ {dirty ? <p className="text-xs text-port-warning">Save the series plan before editing an episode with AI.</p> : null}+ </>+ ) : <p className="text-sm text-port-text-muted">Add an episode to use whole-episode AI editing.</p>}+ </div>+ );+}++function PlanCollection({ title, description, items, episodes, sideQuests = false, onAdd, onUpdate, onRemove, onMove }) {+ return (+ <div className="rounded-lg border border-port-border bg-port-card p-4 space-y-4">+ <div className="flex items-start justify-between gap-3">+ <div>+ <h3 className="font-semibold">{title}</h3>+ <p className="text-xs text-port-text-muted mt-1">{description}</p>+ </div>+ <button type="button" onClick={onAdd} className="flex items-center gap-1 px-2.5 py-1.5 rounded border border-port-border text-xs hover:border-port-accent">+ <Plus size={13} /> Add+ </button>+ </div>++ {!items.length ? (+ <button type="button" onClick={onAdd} className="w-full rounded border border-dashed border-port-border p-5 text-sm text-port-text-muted hover:border-port-accent hover:text-port-accent">+ Add the first {sideQuests ? 'side quest' : 'plot point'}+ </button>+ ) : items.map((item, index) => (+ <div key={item.id} className="rounded border border-port-border p-3 space-y-3">+ <div className="flex items-center gap-2">+ <span className="text-xs font-medium text-port-text-muted w-6">{index + 1}.</span>+ <input+ aria-label={`${title} ${index + 1} title`}+ className={fieldClass}+ value={item.title}+ placeholder={sideQuests ? 'Side quest title' : 'Plot point title'}+ onChange={(event) => onUpdate(item.id, { title: event.target.value })}+ />+ <button type="button" aria-label={`Move ${title.toLowerCase()} ${index + 1} up`} disabled={index === 0} onClick={() => onMove(index, -1)} className="p-1 text-port-text-muted hover:text-port-text disabled:opacity-30"><ChevronUp size={15} /></button>+ <button type="button" aria-label={`Move ${title.toLowerCase()} ${index + 1} down`} disabled={index === items.length - 1} onClick={() => onMove(index, 1)} className="p-1 text-port-text-muted hover:text-port-text disabled:opacity-30"><ChevronDown size={15} /></button>+ <button type="button" aria-label={`Remove ${title.toLowerCase()} ${index + 1}`} onClick={() => onRemove(item.id)} className="p-1 text-port-text-muted hover:text-port-error"><Trash2 size={15} /></button>+ </div>+ <textarea+ aria-label={`${title} ${index + 1} description`}+ rows={3}+ className={fieldClass}+ value={item.description}+ placeholder="What happens, why it matters, and what it changes…"+ onChange={(event) => onUpdate(item.id, { description: event.target.value })}+ />+ {sideQuests ? (+ <div className="grid sm:grid-cols-3 gap-3">+ <PlanSelect label="Status" value={item.status} onChange={(status) => onUpdate(item.id, { status })} options={[+ { id: 'idea', label: 'Idea' }, { id: 'planned', label: 'Planned' },+ { id: 'active', label: 'Active' }, { id: 'resolved', label: 'Resolved' },+ ]} />+ <PlanSelect label="Starts" value={item.startEpisodeId || ''} onChange={(value) => onUpdate(item.id, { startEpisodeId: value || null })} options={episodes} emptyLabel="Unassigned" />+ <PlanSelect label="Ends" value={item.endEpisodeId || ''} onChange={(value) => onUpdate(item.id, { endEpisodeId: value || null })} options={episodes} emptyLabel="Unassigned" />+ </div>+ ) : (+ <PlanSelect label="Episode" value={item.episodeId || ''} onChange={(value) => onUpdate(item.id, { episodeId: value || null })} options={episodes} emptyLabel="Unassigned" />+ )}+ </div>+ ))}+ </div>+ );+}++function PlanSelect({ label, value, options, emptyLabel, onChange }) {+ return (+ <FormField label={label} labelClassName={labelClass}>+ <select className={fieldClass} value={value} onChange={(event) => onChange(event.target.value)}>+ {emptyLabel ? <option value="">{emptyLabel}</option> : null}+ {options.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}+ </select>+ </FormField>+ );+}diff --git a/client/src/components/fableloom/LoomSeriesPlan.test.jsx b/client/src/components/fableloom/LoomSeriesPlan.test.jsxnew file mode 100644index 0000000000..fc9693e46c--- /dev/null+++ b/client/src/components/fableloom/LoomSeriesPlan.test.jsx@@ -0,0 +1,70 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { createMemoryRouter, RouterProvider } from 'react-router';++vi.mock('../../services/api', () => ({+ feedbackLoomSeriesPlan: vi.fn(),+ reviewLoomSeriesPlan: vi.fn(),+ updateLoom: vi.fn(),+}));+vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [], loading: false }) }));+vi.mock('../ProviderModelSelector', () => ({ default: () => <div>AI route picker</div> }));+vi.mock('./LoomEpisodeFeedback', () => ({ default: ({ episode }) => <div>Episode feedback for {episode.title}</div> }));++import * as api from '../../services/api';+import LoomSeriesPlan from './LoomSeriesPlan';++const loom = (fields = {}) => ({+ id: 'loom-1',+ name: 'Example Loom',+ episodes: [{ id: 'ep-1', number: 1, title: 'Pilot' }],+ seriesPlan: {+ storyArc: 'An old arc.',+ plotPoints: [{ id: 'plot-1', title: 'The turn', description: 'Everything changes.', episodeId: 'ep-1' }],+ sideQuests: [],+ },+ ...fields,+});++beforeEach(() => {+ vi.clearAllMocks();+});++const renderPlan = (props) => render(<RouterProvider router={createMemoryRouter([+ { path: '/', element: <LoomSeriesPlan {...props} /> },+], { initialEntries: ['/'] })} />);++describe('LoomSeriesPlan', () => {+ it('edits and saves the series-level plan as one patch', async () => {+ const onLoomUpdate = vi.fn();+ const updated = loom({ seriesPlan: { ...loom().seriesPlan, storyArc: 'A stronger arc.' } });+ api.updateLoom.mockResolvedValue(updated);+ renderPlan({ loom: loom(), onLoomUpdate });++ fireEvent.change(screen.getByRole('textbox', { name: /story arc/i }), { target: { value: 'A stronger arc.' } });+ expect(screen.getByRole('button', { name: /analyze series/i })).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: /save plan/i }));++ await waitFor(() => expect(api.updateLoom).toHaveBeenCalledWith('loom-1', {+ seriesPlan: expect.objectContaining({ storyArc: 'A stronger arc.' }),+ }, { silent: true }));+ expect(onLoomUpdate).toHaveBeenCalledWith(updated);+ });++ it('shows AI series analysis and exposes whole-episode editing outside the episode graph', async () => {+ api.reviewLoomSeriesPlan.mockResolvedValue({+ analysis: {+ summary: 'The spine works.',+ strengths: ['Clear protagonist goal'],+ risks: ['Midpoint arrives late'],+ recommendations: ['Move the reversal into episode 3'],+ },+ });+ renderPlan({ loom: loom(), onLoomUpdate: () => {} });++ fireEvent.click(screen.getByRole('button', { name: /analyze series/i }));+ expect(await screen.findByText('The spine works.')).toBeInTheDocument();+ expect(screen.getByText('Move the reversal into episode 3')).toBeInTheDocument();+ expect(screen.getByText('Episode feedback for Pilot')).toBeInTheDocument();+ });+});diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsxindex 53fab0441b..1e17bb82b3 100644--- a/client/src/pages/FableLoomStory.jsx+++ b/client/src/pages/FableLoomStory.jsx@@ -1,8 +1,9 @@/*** FableLoom editor — the full-bleed visual workspace for one loom.*- * URL is the source of truth: /fableloom/:loomId/:episodeId/:nodeId? — the- * selected episode and scene are route params, the play drawer rides ?play=1.+ * URL is the source of truth: /fableloom/:loomId/plan is the series workspace;+ * /fableloom/:loomId/:episodeId/:nodeId? selects an episode and scene, and the+ * play drawer rides ?play=1.* Left: the scene-graph canvas (stacks top-to-bottom under the `lg` rail* breakpoint). Right rail: the selected scene's editor, or the* structure/review panel when nothing is selected. On small screens the@@ -27,6 +28,7 @@ import LoomEpisodeFeedback from '../components/fableloom/LoomEpisodeFeedback';import LoomNodeEditor from '../components/fableloom/LoomNodeEditor';import LoomPlayPanel from '../components/fableloom/LoomPlayPanel';import LoomSettingsDrawer from '../components/fableloom/LoomSettingsDrawer';+import LoomSeriesPlan from '../components/fableloom/LoomSeriesPlan';import LoomValidationPanel from '../components/fableloom/LoomValidationPanel';import { fieldClass, labelClass } from '../components/fableloom/fieldStyles';import { LOOM_ORIENTATION, LOOM_STACK_WIDTH } from '../lib/loomLayout';@@ -48,6 +50,7 @@ export default function FableLoomStory() {const [setupOpen, setSetupOpen] = useState(false);const [settingsOpen, setSettingsOpen] = useState(false);const playOpen = searchParams.get('play') === '1';+ const seriesPlanOpen = episodeId === 'plan';// Orientation keys off the PAGE, not the canvas. The canvas is the leftover// after the 380px rail on `lg+`, so measuring it would stack a laptop graph// while the rail is still beside it.@@ -74,7 +77,7 @@ export default function FableLoomStory() {return () => { canceled = true; };}, [linkedSeriesId]);- const episode = loom?.episodes.find((e) => e.id === episodeId) || null;+ const episode = seriesPlanOpen ? null : loom?.episodes.find((e) => e.id === episodeId) || null;const node = episode?.nodes.find((n) => n.id === nodeId) || null;const basePath = `/fableloom/${loomId}`;@@ -156,11 +159,11 @@ export default function FableLoomStory() {}// Route normalization: no/stale episode id → first episode (or stay bare- // when the loom has none yet).- if (!episode && loom.episodes.length) {+ // when the loom has none yet). The reserved `plan` id is the series view.+ if (!seriesPlanOpen && !episode && loom.episodes.length) {return <Navigate to={episodePath(loom.episodes[0].id)} replace />;}- if (episodeId && !episode) {+ if (!seriesPlanOpen && episodeId && !episode) {return <Navigate to={basePath} replace />;}@@ -222,17 +225,18 @@ export default function FableLoomStory() {</div></div><div className="flex items-center gap-2 flex-wrap">- {loom.episodes.length > 0 && (- <TabPills- variant="pills"- size="sm"- ariaLabel="Episodes"- mobileDropdown- tabs={loom.episodes.map((e) => ({ id: e.id, label: `${e.number}. ${e.title || 'Untitled'}` }))}- activeTab={episodeId}- onChange={(id) => navigate(episodePath(id))}- />- )}+ <TabPills+ variant="pills"+ size="sm"+ ariaLabel="Series and episodes"+ mobileDropdown+ tabs={[+ { id: 'plan', label: 'Series plan' },+ ...loom.episodes.map((e) => ({ id: e.id, label: `${e.number}. ${e.title || 'Untitled'}` })),+ ]}+ activeTab={seriesPlanOpen ? 'plan' : episodeId}+ onChange={(id) => navigate(episodePath(id))}+ /><buttontype="button"onClick={handleAddEpisode}@@ -243,7 +247,9 @@ export default function FableLoomStory() {</div></header>- {!episode ? (+ {seriesPlanOpen ? (+ <LoomSeriesPlan loom={loom} onLoomUpdate={setLoom} />+ ) : !episode ? (<div className="flex-1 grid place-items-center p-8 text-center"><div><Waypoints size={32} className="mx-auto text-port-text-muted mb-3" />diff --git a/client/src/pages/FableLoomStory.test.jsx b/client/src/pages/FableLoomStory.test.jsxindex 347536789e..e92e796559 100644--- a/client/src/pages/FableLoomStory.test.jsx+++ b/client/src/pages/FableLoomStory.test.jsx@@ -9,6 +9,7 @@ vi.mock('../services/api', () => ({getLoom: vi.fn(),getPipelineSeries: vi.fn(),updateLoomEpisode: vi.fn(),+ updateLoom: vi.fn(),updateLoomNode: vi.fn(),weaveLoomEpisode: vi.fn(),}));@@ -19,6 +20,7 @@ vi.mock('../components/fableloom/LoomCanvas', () => ({ default: () => <div /> })vi.mock('../components/fableloom/LoomNodeEditor', () => ({ default: () => <div /> }));vi.mock('../components/fableloom/LoomPlayPanel', () => ({ default: () => <div /> }));vi.mock('../components/fableloom/LoomSettingsDrawer', () => ({ default: () => <div /> }));+vi.mock('../components/fableloom/LoomSeriesPlan', () => ({ default: () => <div>Series planning workspace</div> }));vi.mock('../components/fableloom/LoomValidationPanel', () => ({ default: () => <div /> }));import * as api from '../services/api';@@ -82,4 +84,16 @@ describe('FableLoomStory series backlink', () => {await screen.findByText('Example Loom');expect(api.getPipelineSeries).not.toHaveBeenCalled();});++ it('keeps series planning outside the episode tabs at a dedicated URL', async () => {+ render(+ <MemoryRouter initialEntries={['/fableloom/loom-1/plan']}>+ <Routes>+ <Route path="/fableloom/:loomId/:episodeId" element={<FableLoomStory />} />+ </Routes>+ </MemoryRouter>,+ );+ expect(await screen.findByText('Series planning workspace')).toBeInTheDocument();+ expect(screen.getByRole('tab', { name: 'Series plan' })).toBeInTheDocument();+ });});diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.jsindex b67ca935cc..dd52abcfa8 100644--- a/client/src/services/apiFableLoom.js+++ b/client/src/services/apiFableLoom.js@@ -24,6 +24,13 @@ export const deleteLoom = (id, options = {}) => request(loomPath(id), {method: 'DELETE', ...options,});+export const reviewLoomSeriesPlan = (id, body = {}, options = {}) => request(loomPath(id, '/plan/review'), {+ method: 'POST', body: JSON.stringify(body), ...options,+});+export const feedbackLoomSeriesPlan = (id, body, options = {}) => request(loomPath(id, '/plan/feedback'), {+ method: 'POST', body: JSON.stringify(body), ...options,+});+export const addLoomEpisode = (id, body, options = {}) => request(loomPath(id, '/episodes'), {method: 'POST', body: JSON.stringify(body), ...options,});diff --git a/client/src/services/apiFableLoom.test.js b/client/src/services/apiFableLoom.test.jsindex 940ad3f90d..6716feb130 100644--- a/client/src/services/apiFableLoom.test.js+++ b/client/src/services/apiFableLoom.test.js@@ -43,6 +43,18 @@ describe('apiFableLoom', () => {});});+ it('posts series-plan analysis and feedback', async () => {+ await api.reviewLoomSeriesPlan('loom/1', { providerId: 'writer' }, { silent: true });+ expect(request).toHaveBeenCalledWith('/fableloom/loom%2F1/plan/review', {+ method: 'POST', body: JSON.stringify({ providerId: 'writer' }), silent: true,+ });++ await api.feedbackLoomSeriesPlan('loom-1', { feedback: 'Raise the stakes.' });+ expect(request).toHaveBeenCalledWith('/fableloom/loom-1/plan/feedback', {+ method: 'POST', body: JSON.stringify({ feedback: 'Raise the stakes.' }),+ });+ });+it('posts play turns with the transcript', async () => {const body = { nodeId: 'node-1', message: 'open the gate', transcript: [] };await api.playLoomTurn('loom-1', 'ep-1', body);diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 8984e03edc..8087e83209 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -1010,6 +1010,13 @@"returnsJson": true,"variables": []},+ "fableloom-feedback-series-plan": {+ "name": "FableLoom — Apply Series Plan Feedback",+ "description": "Applies one conversational author instruction to a FableLoom series arc, ordered plot points, and side quests without changing episode scene graphs. Returns a sparse top-level plan patch plus a short change list.",+ "model": "heavy",+ "returnsJson": true,+ "variables": []+ },"fableloom-play-turn": {"name": "FableLoom — Play Turn","description": "Narrates one turn of an interactive read-through: matches the reader's free-text message against the current scene's intent-labeled paths (move) or responds in-world without leaving the scene (stay). Returns { action, transitionId?, narration }.",@@ -1030,6 +1037,13 @@"model": "heavy","returnsJson": true,"variables": []+ },+ "fableloom-review-series-plan": {+ "name": "FableLoom — Review Series Plan",+ "description": "Holistic story-editor analysis of the series arc, ordered plot points, side-quest lifecycle, and episode outline. Returns a summary, strengths, risks, and actionable recommendations without modifying the loom.",+ "model": "heavy",+ "returnsJson": true,+ "variables": []}}}diff --git a/data.reference/prompts/stages/fableloom-feedback-series-plan.md b/data.reference/prompts/stages/fableloom-feedback-series-plan.mdnew file mode 100644index 0000000000..76a2009a90--- /dev/null+++ b/data.reference/prompts/stages/fableloom-feedback-series-plan.md@@ -0,0 +1,40 @@+# FableLoom — Apply Series Plan Feedback++You are the story editor for an interactive branching series. Apply the author's instruction to the series-level plan. Do not edit episode scene graphs.++## Story++{{storyContext}}++## World canon++{{canonDigest}}++## Current series plan and episode outline++{{seriesPlanJson}}++## Author feedback++{{feedback}}++## Editing contract++- Make the smallest coherent change that fully satisfies the instruction.+- A missing top-level field preserves it. A present empty string or empty array intentionally clears it.+- `plotPoints` and `sideQuests` are ordered complete arrays when present; include every item that should remain.+- Preserve existing item ids. New items omit `id`; the server will mint one.+- Episode references must use an episode id from the supplied outline or `null`.+- Side-quest status is one of `idea`, `planned`, `active`, or `resolved`.+- Do not change episode titles, synopses, scenes, paths, or ids in this pass.++Return ONLY valid JSON matching this shape, omitting unchanged top-level fields:++```json+{+ "storyArc": "complete revised arc",+ "plotPoints": [{ "id": "existing id", "title": "Beat", "description": "Purpose and consequence", "episodeId": "episode id or null" }],+ "sideQuests": [{ "id": "existing id", "title": "Thread", "description": "Progression and payoff", "status": "planned", "startEpisodeId": "episode id or null", "endEpisodeId": "episode id or null" }],+ "changes": ["short description of an applied change"]+}+```diff --git a/data.reference/prompts/stages/fableloom-review-series-plan.md b/data.reference/prompts/stages/fableloom-review-series-plan.mdnew file mode 100644index 0000000000..d0dc785b36--- /dev/null+++ b/data.reference/prompts/stages/fableloom-review-series-plan.md@@ -0,0 +1,28 @@+# FableLoom — Review Series Plan++You are a senior story editor analyzing the complete plan for an interactive branching series. Give the author specific, actionable guidance. This is a read-only analysis: do not rewrite the plan.++## Story++{{storyContext}}++## World canon++{{canonDigest}}++## Series plan and episode outline++{{seriesPlanJson}}++Evaluate the long-form dramatic arc, escalation and payoff of the ordered plot points, pacing across episodes, integration and resolution of side quests, continuity, thematic coherence, and whether the plan leaves each episode a distinct dramatic job. Account for branching storytelling: meaningful paths can vary locally, but the series-level promises and payoffs still need to remain legible.++Return ONLY valid JSON matching this shape:++```json+{+ "summary": "concise editorial assessment",+ "strengths": ["specific strength"],+ "risks": ["specific story risk"],+ "recommendations": ["concrete next edit"]+}+```diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex e6c63d4880..78796676ee 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -8625,7 +8625,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 62+ "line": 66}]},@@ -8636,7 +8636,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 69+ "line": 73}]},@@ -8647,7 +8647,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 85+ "line": 89}]},@@ -8658,7 +8658,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 74+ "line": 78}]},@@ -8669,7 +8669,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 80+ "line": 84}]},@@ -8680,7 +8680,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 92+ "line": 108}]},@@ -8691,7 +8691,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 102+ "line": 118}]},@@ -8702,7 +8702,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 97+ "line": 113}]},@@ -8713,7 +8713,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 177+ "line": 193}]},@@ -8724,7 +8724,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 116+ "line": 132}]},@@ -8735,7 +8735,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 126+ "line": 142}]},@@ -8746,7 +8746,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 121+ "line": 137}]},@@ -8757,7 +8757,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 164+ "line": 180}]},@@ -8768,7 +8768,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 139+ "line": 155}]},@@ -8779,7 +8779,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 151+ "line": 167}]},@@ -8790,7 +8790,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 144+ "line": 160}]},@@ -8801,7 +8801,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 182+ "line": 198}]},@@ -8812,7 +8812,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 193+ "line": 209}]},@@ -8823,7 +8823,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 169+ "line": 185}]},@@ -8834,7 +8834,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 107+ "line": 123}]},@@ -8845,7 +8845,29 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 159+ "line": 175+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/fableloom/:id/plan/feedback",+ "mountPath": "/api/fableloom",+ "sources": [+ {+ "source": "server/routes/fableLoom.js",+ "line": 101+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/fableloom/:id/plan/review",+ "mountPath": "/api/fableloom",+ "sources": [+ {+ "source": "server/routes/fableLoom.js",+ "line": 96}]},@@ -22938,8 +22960,8 @@],"stats": {"mounts": 145,- "operations": 2069,- "declarations": 2072,+ "operations": 2071,+ "declarations": 2074,"sourceFiles": 224}}diff --git a/server/lib/fableLoomLimits.js b/server/lib/fableLoomLimits.jsindex f543e6e6f3..6f73fe2661 100644--- a/server/lib/fableLoomLimits.js+++ b/server/lib/fableLoomLimits.js@@ -10,6 +10,10 @@ export const LOOM_LIMITS = Object.freeze({LOGLINE_MAX: 500,PREMISE_MAX: 20000,STYLE_NOTES_MAX: 4000,+ STORY_ARC_MAX: 12000,+ PLAN_ITEMS_MAX: 50,+ PLAN_ITEM_TITLE_MAX: 300,+ PLAN_ITEM_DESCRIPTION_MAX: 4000,REF_ID_MAX: 64,EPISODES_MAX: 100,EPISODE_TITLE_MAX: 300,diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex b0560d1847..a63e8acad8 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -25,6 +25,26 @@ const format = z.enum(LOOM_FORMATS);// the runner would clamp an unknown level silently, and the door check is// where a typo should surface.const playSettings = llmRoutePinSchema.nullable();+const planItemId = z.string().min(1).max(80).optional();+const planEpisodeId = z.string().min(1).max(80).nullable().optional();+const planItemFields = {+ id: planItemId,+ title: z.string().max(LOOM_LIMITS.PLAN_ITEM_TITLE_MAX),+ description: z.string().max(LOOM_LIMITS.PLAN_ITEM_DESCRIPTION_MAX),+};+const seriesPlan = z.object({+ storyArc: z.string().max(LOOM_LIMITS.STORY_ARC_MAX),+ plotPoints: z.array(z.object({+ ...planItemFields,+ episodeId: planEpisodeId,+ })).max(LOOM_LIMITS.PLAN_ITEMS_MAX),+ sideQuests: z.array(z.object({+ ...planItemFields,+ status: z.enum(['idea', 'planned', 'active', 'resolved']),+ startEpisodeId: planEpisodeId,+ endEpisodeId: planEpisodeId,+ })).max(LOOM_LIMITS.PLAN_ITEMS_MAX),+});// Index filter. `?seriesId=` scopes the list to the looms soft-linked to one// pipeline series (the series detail page's "Branching narratives" card). An@@ -41,6 +61,7 @@ export const loomCreateSchema = z.object({styleNotes: styleNotes.optional(),format: format.optional(),playSettings: playSettings.optional(),+ seriesPlan: seriesPlan.optional(),universeId: refId.optional(),seriesId: refId.optional(),});@@ -52,6 +73,7 @@ export const loomPatchSchema = z.object({styleNotes: styleNotes.optional(),format: format.optional(),playSettings: playSettings.optional(),+ seriesPlan: seriesPlan.optional(),universeId: refId.optional(),seriesId: refId.optional(),});@@ -160,3 +182,10 @@ export const feedbackSchema = z.object({feedback: z.string().trim().min(1).max(LOOM_LIMITS.FEEDBACK_MAX),...llmPickFields,});++export const seriesPlanReviewSchema = z.object({ ...llmPickFields });++export const seriesPlanFeedbackSchema = z.object({+ feedback: z.string().trim().min(1).max(LOOM_LIMITS.FEEDBACK_MAX),+ ...llmPickFields,+});diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.jsonindex 51a5ea3997..5f64210efa 100644--- a/server/lib/promptStageCallSites.generated.json+++ b/server/lib/promptStageCallSites.generated.json@@ -37,6 +37,9 @@"fableloom-feedback-episode": ["server/services/fableLoom/weave.js"],+ "fableloom-feedback-series-plan": [+ "server/services/fableLoom/weave.js"+ ],"fableloom-play-turn": ["server/services/fableLoom/weave.js"],@@ -46,6 +49,9 @@"fableloom-review": ["server/services/fableLoom/weave.js"],+ "fableloom-review-series-plan": [+ "server/services/fableLoom/weave.js"+ ],"fableloom-weave-episode": ["server/services/fableLoom/weave.js"],diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.jsindex a9656c1541..e1c79b4346 100644--- a/server/routes/fableLoom.js+++ b/server/routes/fableLoom.js@@ -24,6 +24,8 @@ import {playTurnSchema,reformatSchema,reviewSchema,+ seriesPlanFeedbackSchema,+ seriesPlanReviewSchema,transitionCreateSchema,transitionPatchSchema,weaveSchema,@@ -40,11 +42,13 @@ import {deleteNode,deleteNodeTransition,feedbackEpisode,+ feedbackSeriesPlan,getLoom,listLoomSummaries,playTurn,reformatEpisodeScenes,reviewEpisode,+ reviewSeriesPlan,updateEpisode,updateLoom,updateNode,@@ -87,6 +91,18 @@ router.delete('/:id', asyncHandler(async (req, res) => {res.json({ ok: true });}));+// --- Series plan ------------------------------------------------------------++router.post('/:id/plan/review', asyncHandler(async (req, res) => {+ const input = validateRequest(seriesPlanReviewSchema, req.body);+ res.json(await reviewSeriesPlan(req.params.id, input));+}));++router.post('/:id/plan/feedback', asyncHandler(async (req, res) => {+ const input = validateRequest(seriesPlanFeedbackSchema, req.body);+ res.json(await feedbackSeriesPlan(req.params.id, input));+}));+// --- Episodes ---------------------------------------------------------------router.post('/:id/episodes', asyncHandler(async (req, res) => {diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.jsindex 8d09250d6a..8911ff6ab3 100644--- a/server/routes/fableLoom.test.js+++ b/server/routes/fableLoom.test.js@@ -14,11 +14,13 @@ vi.mock('../services/fableLoom/index.js', () => ({deleteNode: vi.fn(),deleteNodeTransition: vi.fn(),feedbackEpisode: vi.fn(),+ feedbackSeriesPlan: vi.fn(),getLoom: vi.fn(),listLoomSummaries: vi.fn(async () => []),playTurn: vi.fn(),reformatEpisodeScenes: vi.fn(),reviewEpisode: vi.fn(),+ reviewSeriesPlan: vi.fn(),updateEpisode: vi.fn(),updateLoom: vi.fn(),updateNode: vi.fn(),@@ -95,6 +97,38 @@ describe('FableLoom routes', () => {expect(fableLoom.updateLoom).toHaveBeenCalledWith('loom-1', { name: 'Y' });});+ it('reviews and conversationally edits the series plan', async () => {+ fableLoom.reviewSeriesPlan.mockResolvedValueOnce({ analysis: { summary: 'Coherent.' } });+ const reviewed = await request(makeApp())+ .post('/api/fableloom/loom-1/plan/review')+ .send({ providerId: 'writer', model: 'large' });+ expect(reviewed.status).toBe(200);+ expect(fableLoom.reviewSeriesPlan).toHaveBeenCalledWith('loom-1', { providerId: 'writer', model: 'large' });++ fableLoom.feedbackSeriesPlan.mockResolvedValueOnce({ loom: { id: 'loom-1' }, changes: ['Moved midpoint'] });+ const edited = await request(makeApp())+ .post('/api/fableloom/loom-1/plan/feedback')+ .send({ feedback: 'Move the midpoint earlier.' });+ expect(edited.status).toBe(200);+ expect(fableLoom.feedbackSeriesPlan).toHaveBeenCalledWith('loom-1', { feedback: 'Move the midpoint earlier.' });++ const invalid = await request(makeApp()).post('/api/fableloom/loom-1/plan/feedback').send({ feedback: ' ' });+ expect(invalid.status).toBe(400);+ expect(fableLoom.feedbackSeriesPlan).toHaveBeenCalledTimes(1);+ });++ it('validates and forwards structured series-plan patches', async () => {+ const seriesPlan = {+ storyArc: 'A courier becomes a leader.',+ plotPoints: [{ id: 'plot-1', title: 'The choice', description: 'She stays.', episodeId: 'ep-1' }],+ sideQuests: [{ id: 'quest-1', title: 'Lost map', description: 'Recover it.', status: 'active', startEpisodeId: 'ep-1', endEpisodeId: null }],+ };+ fableLoom.updateLoom.mockResolvedValueOnce({ id: 'loom-1', seriesPlan });+ const response = await request(makeApp()).patch('/api/fableloom/loom-1').send({ seriesPlan });+ expect(response.status).toBe(200);+ expect(fableLoom.updateLoom).toHaveBeenCalledWith('loom-1', { seriesPlan });+ });+it('episode + node CRUD dispatches with route params', async () => {fableLoom.addEpisode.mockResolvedValueOnce({ id: 'loom-1' });await request(makeApp()).post('/api/fableloom/loom-1/episodes').send({ title: 'Pilot' });diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.jsindex 2624e0fc9c..46b3e6c1e0 100644--- a/server/services/fableLoom/index.js+++ b/server/services/fableLoom/index.js@@ -26,11 +26,13 @@ export {branchNode,buildCanonDigest,feedbackEpisode,+ feedbackSeriesPlan,mapGeneratedGraph,playTurn,publicNode,reformatEpisodeScenes,reviewEpisode,+ reviewSeriesPlan,weaveEpisode,} from './weave.js';export {diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.jsindex 982ace0954..f801e4570c 100644--- a/server/services/fableLoom/records.js+++ b/server/services/fableLoom/records.js@@ -104,12 +104,58 @@ function sanitizeEpisode(raw) {};}+const planItemId = (prefix, value, seenIds) => {+ const candidate = isStr(value) && value.trim() ? value.trim().slice(0, 80) : '';+ const id = candidate && !seenIds.has(candidate) ? candidate : `${prefix}-${randomUUID()}`;+ seenIds.add(id);+ return id;+};++const planEpisodeRef = (value, episodeIds) => (+ isStr(value) && episodeIds.has(value) ? value : null+);++function sanitizeSeriesPlan(raw, episodes) {+ const source = raw && typeof raw === 'object' ? raw : {};+ const episodeIds = new Set(episodes.map((episode) => episode.id));+ const plotIds = new Set();+ const questIds = new Set();+ return {+ storyArc: trimTo(source.storyArc, LOOM_LIMITS.STORY_ARC_MAX),+ plotPoints: (Array.isArray(source.plotPoints) ? source.plotPoints : [])+ .filter((item) => item && typeof item === 'object')+ .slice(0, LOOM_LIMITS.PLAN_ITEMS_MAX)+ .map((item) => ({+ id: planItemId('plot', item.id, plotIds),+ title: trimTo(item.title, LOOM_LIMITS.PLAN_ITEM_TITLE_MAX),+ description: trimTo(item.description, LOOM_LIMITS.PLAN_ITEM_DESCRIPTION_MAX),+ episodeId: planEpisodeRef(item.episodeId, episodeIds),+ })),+ sideQuests: (Array.isArray(source.sideQuests) ? source.sideQuests : [])+ .filter((item) => item && typeof item === 'object')+ .slice(0, LOOM_LIMITS.PLAN_ITEMS_MAX)+ .map((item) => ({+ id: planItemId('quest', item.id, questIds),+ title: trimTo(item.title, LOOM_LIMITS.PLAN_ITEM_TITLE_MAX),+ description: trimTo(item.description, LOOM_LIMITS.PLAN_ITEM_DESCRIPTION_MAX),+ status: ['idea', 'planned', 'active', 'resolved'].includes(item.status) ? item.status : 'idea',+ startEpisodeId: planEpisodeRef(item.startEpisodeId, episodeIds),+ endEpisodeId: planEpisodeRef(item.endEpisodeId, episodeIds),+ })),+ };+}+export function sanitizeLoom(raw) {if (!raw || typeof raw !== 'object') return null;if (!isStr(raw.id) || !raw.id) return null;const name = trimTo(raw.name, LOOM_LIMITS.NAME_MAX);if (!name) return null;const now = new Date().toISOString();+ const episodes = (Array.isArray(raw.episodes) ? raw.episodes : [])+ .map(sanitizeEpisode)+ .filter(Boolean)+ .slice(0, LOOM_LIMITS.EPISODES_MAX)+ .sort((a, b) => a.number - b.number || a.createdAt.localeCompare(b.createdAt));return {id: raw.id,schemaVersion: 1,@@ -124,11 +170,8 @@ export function sanitizeLoom(raw) {playSettings: sanitizeLlmRoutePin(raw.playSettings),universeId: nullableRef(raw.universeId),seriesId: nullableRef(raw.seriesId),- episodes: (Array.isArray(raw.episodes) ? raw.episodes : [])- .map(sanitizeEpisode)- .filter(Boolean)- .slice(0, LOOM_LIMITS.EPISODES_MAX)- .sort((a, b) => a.number - b.number || a.createdAt.localeCompare(b.createdAt)),+ seriesPlan: sanitizeSeriesPlan(raw.seriesPlan, episodes),+ episodes,createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : now,updatedAt: isStr(raw.updatedAt) && raw.updatedAt ? raw.updatedAt : now,};@@ -198,7 +241,7 @@ export async function getLoom(id) {return sanitizeLoom(await readRaw(id));}-export async function createLoom({ name, logline, premise, styleNotes, format, playSettings, universeId, seriesId } = {}) {+export async function createLoom({ name, logline, premise, styleNotes, format, playSettings, seriesPlan, universeId, seriesId } = {}) {const now = new Date().toISOString();await assertRefsExist({ universeId: nullableRef(universeId), seriesId: nullableRef(seriesId) });const loom = sanitizeLoom({@@ -209,6 +252,7 @@ export async function createLoom({ name, logline, premise, styleNotes, format, pstyleNotes,format,playSettings,+ seriesPlan,universeId,seriesId,episodes: [],@@ -238,7 +282,7 @@ export function mutateLoom(id, mutator) {});}-const PATCH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'universeId', 'seriesId'];+const PATCH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan', '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.jsindex bcf836fd04..5f49ee069e 100644--- a/server/services/fableLoom/records.test.js+++ b/server/services/fableLoom/records.test.js@@ -106,6 +106,38 @@ describe('sanitizeLoom', () => {expect(loom.episodes[0].nodes[0].image).toBeNull();expect(loom.episodes[0].nodes[1].image).toBe('render.png');});++ it('sanitizes the series plan and clears episode references that no longer resolve', () => {+ const loom = sanitizeLoom({+ id: 'loom-1',+ name: 'X',+ episodes: [{ id: 'ep-1', number: 1 }],+ seriesPlan: {+ storyArc: 'A long transformation.',+ plotPoints: [{ title: 'Midpoint', description: 'The truth lands.', episodeId: 'ep-1' }],+ sideQuests: [{ title: 'Map', description: 'Find it.', status: 'bogus', startEpisodeId: 'gone', endEpisodeId: 'ep-1' }],+ },+ });+ expect(loom.seriesPlan.storyArc).toBe('A long transformation.');+ expect(loom.seriesPlan.plotPoints[0]).toMatchObject({ title: 'Midpoint', episodeId: 'ep-1' });+ expect(loom.seriesPlan.plotPoints[0].id).toMatch(/^plot-/);+ expect(loom.seriesPlan.sideQuests[0]).toMatchObject({ status: 'idea', startEpisodeId: null, endEpisodeId: 'ep-1' });+ });++ it('re-mints duplicate planning ids so each editable row remains addressable', () => {+ const loom = sanitizeLoom({+ id: 'loom-1', name: 'X',+ seriesPlan: {+ storyArc: '',+ plotPoints: [+ { id: 'plot-same', title: 'One', description: '' },+ { id: 'plot-same', title: 'Two', description: '' },+ ],+ sideQuests: [],+ },+ });+ expect(new Set(loom.seriesPlan.plotPoints.map((item) => item.id)).size).toBe(2);+ });});describe('loom CRUD', () => {@@ -163,6 +195,23 @@ describe('format and play settings round-trip', () => {});});+describe('series plan round-trip', () => {+ it('persists ordered plot points and side quests without changing them on unrelated patches', async () => {+ let loom = await makeLoom();+ loom = await addEpisode(loom.id, { title: 'Pilot' });+ const episodeId = loom.episodes[0].id;+ const seriesPlan = {+ storyArc: 'The courier learns to lead.',+ plotPoints: [{ id: 'plot-1', title: 'Refusal', description: 'She turns away.', episodeId }],+ sideQuests: [{ id: 'quest-1', title: 'The map', description: 'A hidden route.', status: 'planned', startEpisodeId: episodeId, endEpisodeId: null }],+ };+ const planned = await updateLoom(loom.id, { seriesPlan });+ expect(planned.seriesPlan).toEqual(seriesPlan);+ const renamed = await updateLoom(loom.id, { name: 'Renamed' });+ expect(renamed.seriesPlan).toEqual(seriesPlan);+ });+});+describe('listLoomSummaries', () => {it('projects counts without the episode graphs', async () => {const loom = await makeLoom({ logline: 'A crown that remembers.' });diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex 5768d13e4b..33daa11697 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -69,15 +69,44 @@ export async function buildCanonDigest(loom) {return universe ? renderCanonForPrompt(universe) : '';}+const seriesPlanContext = (plan) => {+ if (!plan) return [];+ const plotPoints = (plan.plotPoints || []).slice(0, 12).map((item, index) =>+ `Plot point ${index + 1}: ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`);+ const sideQuests = (plan.sideQuests || []).slice(0, 12).map((item) =>+ `Side quest (${item.status}): ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`);+ return [+ plan.storyArc ? `Series arc: ${trimTo(plan.storyArc, 4000)}` : '',+ ...plotPoints,+ ...sideQuests,+ ].filter(Boolean);+};+const storyContext = (loom, episode) => [`Story: ${loom.name}`,`Scene format: ${loomFormatLabel(loom.format)}`,loom.logline ? `Logline: ${loom.logline}` : '',loom.premise ? `Premise: ${loom.premise}` : '',+ ...seriesPlanContext(loom.seriesPlan),episode ? `Episode ${episode.number}: ${episode.title || 'Untitled'}` : '',episode?.synopsis ? `Synopsis: ${episode.synopsis}` : '',].filter(Boolean).join('\n');+const seriesPlanDigest = (loom) => JSON.stringify({+ storyArc: trimTo(loom.seriesPlan?.storyArc, 6000),+ plotPoints: (loom.seriesPlan?.plotPoints || []).slice(0, 30).map((item) => ({+ ...item, description: trimTo(item.description, 600),+ })),+ omittedPlotPoints: Math.max(0, (loom.seriesPlan?.plotPoints?.length || 0) - 30),+ sideQuests: (loom.seriesPlan?.sideQuests || []).slice(0, 30).map((item) => ({+ ...item, description: trimTo(item.description, 600),+ })),+ omittedSideQuests: Math.max(0, (loom.seriesPlan?.sideQuests?.length || 0) - 30),+ episodes: loom.episodes.map(({ id, number, title, synopsis }) => ({+ id, number, title, synopsis: trimTo(synopsis, 500),+ })),+}, null, 2);+// --- Weave: generate a full episode graph -----------------------------------// Raw generated node fields, passed through for the sanitizer to trim/cap.@@ -352,6 +381,75 @@ export async function feedbackEpisode(loomId, episodeId, {};}+// --- Series plan: holistic guidance and conversational editing --------------++const analysisStrings = (value) => (Array.isArray(value) ? value : [])+ .filter((item) => typeof item === 'string')+ .map((item) => trimTo(item, 1000))+ .filter(Boolean)+ .slice(0, 12);++/** Read-only story-editor pass over the arc, tentpole beats, side quests, and episode outline. */+export async function reviewSeriesPlan(loomId, { providerId, model, effort } = {}) {+ const loom = await requireLoom(loomId);+ const canonDigest = await buildCanonDigest(loom);+ const { content, runId } = await runStagedLLM('fableloom-review-series-plan', {+ storyContext: storyContext(loom),+ canonDigest: canonDigest || '(none)',+ seriesPlanJson: seriesPlanDigest(loom),+ }, llmOptions({ providerId, model, effort }, 'fableloom-review-series-plan'));+ const analysis = {+ summary: trimTo(content?.summary, 2000),+ strengths: analysisStrings(content?.strengths),+ risks: analysisStrings(content?.risks),+ recommendations: analysisStrings(content?.recommendations),+ };+ if (!analysis.summary && !analysis.strengths.length && !analysis.risks.length && !analysis.recommendations.length) {+ throw aiShapeError('The model returned no usable series analysis');+ }+ return {+ analysis,+ runId,+ };+}++/** Apply one author instruction to the series-level plan without touching episode scene graphs. */+export async function feedbackSeriesPlan(loomId, {+ feedback, providerId, model, effort,+} = {}) {+ const instruction = trimTo(feedback, LOOM_LIMITS.FEEDBACK_MAX);+ if (!instruction) {+ throw new ServerError('Series-plan feedback is required', { status: 400, code: 'FEEDBACK_REQUIRED' });+ }+ const loom = await requireLoom(loomId);+ const canonDigest = await buildCanonDigest(loom);+ const { content, runId } = await runStagedLLM('fableloom-feedback-series-plan', {+ storyContext: storyContext(loom),+ canonDigest: canonDigest || '(none)',+ seriesPlanJson: seriesPlanDigest(loom),+ feedback: instruction,+ }, llmOptions({ providerId, model, effort }, 'fableloom-feedback-series-plan'));++ if (!content || typeof content !== 'object') {+ throw aiShapeError('The model returned no series-plan edits');+ }+ const patch = {};+ if (hasOwn(content, 'storyArc') && typeof content.storyArc === 'string') patch.storyArc = content.storyArc;+ if (hasOwn(content, 'plotPoints') && Array.isArray(content.plotPoints)) patch.plotPoints = content.plotPoints;+ if (hasOwn(content, 'sideQuests') && Array.isArray(content.sideQuests)) patch.sideQuests = content.sideQuests;+ if (!Object.keys(patch).length) throw aiShapeError('The model returned no usable series-plan edits');++ const updated = await mutateLoom(loomId, (current) => {+ current.seriesPlan = { ...current.seriesPlan, ...patch };+ return current;+ });+ return {+ loom: updated,+ changes: analysisStrings(content.changes),+ runId,+ };+}+// --- Play: resolve a reader's free-text intent ------------------------------/** Reader-facing scene shape — trigger phrases stay server-side. */diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.jsindex 263385e499..5245074e61 100644--- a/server/services/fableLoom/weave.test.js+++ b/server/services/fableLoom/weave.test.js@@ -25,7 +25,8 @@ vi.mock('../pipeline/series.js', () => ({ getSeries: getSeriesMock }));const { createLoom, addEpisode, addNode, mutateLoom, updateLoom, updateNode, getLoom } = await import('./records.js');const { _resetFableLoomBackend } = await import('./store.js');const {- branchNode, buildCanonDigest, feedbackEpisode, mapGeneratedGraph, playTurn, reformatEpisodeScenes, reviewEpisode, weaveEpisode,+ branchNode, buildCanonDigest, feedbackEpisode, feedbackSeriesPlan, mapGeneratedGraph, playTurn,+ reformatEpisodeScenes, reviewEpisode, reviewSeriesPlan, weaveEpisode,} = await import('./weave.js');beforeEach(() => {@@ -583,3 +584,38 @@ describe('buildCanonDigest', () => {expect(await buildCanonDigest({ universeId: null })).toBe('');});});++describe('series plan AI', () => {+ it('returns normalized holistic analysis without mutating the loom', async () => {+ const { loomId } = await setup();+ runStagedLLM.mockResolvedValueOnce({+ content: { summary: 'Strong spine.', strengths: ['Clear goal'], risks: ['Late turn'], recommendations: ['Move the turn'] },+ runId: 'run-review',+ });+ const result = await reviewSeriesPlan(loomId, { providerId: 'writer' });+ expect(result).toEqual({+ analysis: { summary: 'Strong spine.', strengths: ['Clear goal'], risks: ['Late turn'], recommendations: ['Move the turn'] },+ runId: 'run-review',+ });+ expect(runStagedLLM).toHaveBeenCalledWith('fableloom-review-series-plan', expect.objectContaining({+ seriesPlanJson: expect.stringContaining('episodes'),+ }), expect.objectContaining({ providerOverride: 'writer' }));+ });++ it('applies sparse series-plan feedback and preserves omitted collections', async () => {+ const { loomId, episodeId } = await setup();+ await updateLoom(loomId, { seriesPlan: {+ storyArc: 'Old arc',+ plotPoints: [{ id: 'plot-1', title: 'Turn', description: 'Old', episodeId }],+ sideQuests: [],+ } });+ runStagedLLM.mockResolvedValueOnce({+ content: { storyArc: 'New arc', changes: ['Raised the stakes'] },+ runId: 'run-feedback',+ });+ const result = await feedbackSeriesPlan(loomId, { feedback: 'Raise the stakes.' });+ expect(result.loom.seriesPlan.storyArc).toBe('New arc');+ expect(result.loom.seriesPlan.plotPoints).toHaveLength(1);+ expect(result.changes).toEqual(['Raised the stakes']);+ });+});